code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
/* global postboxes, deleteUserSetting, setUserSetting, getUserSetting */
jQuery(document).ready( function($) {
var newCat, noSyncChecks = false, syncChecks, catAddAfter;
$('#link_name').focus();
// postboxes
postboxes.add_postbox_toggles('link');
// category tabs
$('#category-tabs a').click(function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('.tabs-panel').hide();
$(t).show();
if ( '#categories-all' == t )
deleteUserSetting('cats');
else
setUserSetting('cats','pop');
return false;
});
if ( getUserSetting('cats') )
$('#category-tabs a[href="#categories-pop"]').click();
// Ajax Cat
newCat = $('#newcat').one( 'focus', function() { $(this).val( '' ).removeClass( 'form-input-tip' ); } );
$('#link-category-add-submit').click( function() { newCat.focus(); } );
syncChecks = function() {
if ( noSyncChecks )
return;
noSyncChecks = true;
var th = $(this), c = th.is(':checked'), id = th.val().toString();
$('#in-link-category-' + id + ', #in-popular-link_category-' + id).prop( 'checked', c );
noSyncChecks = false;
};
catAddAfter = function( r, s ) {
$(s.what + ' response_data', r).each( function() {
var t = $($(this).text());
t.find( 'label' ).each( function() {
var th = $(this), val = th.find('input').val(), id = th.find('input')[0].id, name = $.trim( th.text() ), o;
$('#' + id).change( syncChecks );
o = $( '<option value="' + parseInt( val, 10 ) + '"></option>' ).text( name );
} );
} );
};
$('#categorychecklist').wpList( {
alt: '',
what: 'link-category',
response: 'category-ajax-response',
addAfter: catAddAfter
} );
$('a[href="#categories-all"]').click(function(){deleteUserSetting('cats');});
$('a[href="#categories-pop"]').click(function(){setUserSetting('cats','pop');});
if ( 'pop' == getUserSetting('cats') )
$('a[href="#categories-pop"]').click();
$('#category-add-toggle').click( function() {
$(this).parents('div:first').toggleClass( 'wp-hidden-children' );
$('#category-tabs a[href="#categories-all"]').click();
$('#newcategory').focus();
return false;
} );
$('.categorychecklist :checkbox').change( syncChecks ).filter( ':checked' ).change();
});
| 01-wordpress-paypal | trunk/wp-admin/js/link.js | JavaScript | gpl3 | 2,247 |
/* global ajaxurl, attachMediaBoxL10n */
var findPosts;
( function( $ ){
findPosts = {
open: function( af_name, af_val ) {
var overlay = $( '.ui-find-overlay' );
if ( overlay.length === 0 ) {
$( 'body' ).append( '<div class="ui-find-overlay"></div>' );
findPosts.overlay();
}
overlay.show();
if ( af_name && af_val ) {
$( '#affected' ).attr( 'name', af_name ).val( af_val );
}
$( '#find-posts' ).show();
$('#find-posts-input').focus().keyup( function( event ){
if ( event.which == 27 ) {
findPosts.close();
} // close on Escape
});
// Pull some results up by default
findPosts.send();
return false;
},
close: function() {
$('#find-posts-response').html('');
$('#find-posts').hide();
$( '.ui-find-overlay' ).hide();
},
overlay: function() {
$( '.ui-find-overlay' ).on( 'click', function () {
findPosts.close();
});
},
send: function() {
var post = {
ps: $( '#find-posts-input' ).val(),
action: 'find_posts',
_ajax_nonce: $('#_ajax_nonce').val()
},
spinner = $( '.find-box-search .spinner' );
spinner.show();
$.ajax( ajaxurl, {
type: 'POST',
data: post,
dataType: 'json'
}).always( function() {
spinner.hide();
}).done( function( x ) {
if ( ! x.success ) {
$( '#find-posts-response' ).text( attachMediaBoxL10n.error );
}
$( '#find-posts-response' ).html( x.data );
}).fail( function() {
$( '#find-posts-response' ).text( attachMediaBoxL10n.error );
});
}
};
$( document ).ready( function() {
$( '#find-posts-submit' ).click( function( event ) {
if ( ! $( '#find-posts-response input[type="radio"]:checked' ).length )
event.preventDefault();
});
$( '#find-posts .find-box-search :input' ).keypress( function( event ) {
if ( 13 == event.which ) {
findPosts.send();
return false;
}
});
$( '#find-posts-search' ).click( findPosts.send );
$( '#find-posts-close' ).click( findPosts.close );
$( '#doaction, #doaction2' ).click( function( event ) {
$( 'select[name^="action"]' ).each( function() {
if ( $(this).val() === 'attach' ) {
event.preventDefault();
findPosts.open();
}
});
});
// Enable whole row to be clicked
$( '.find-box-inside' ).on( 'click', 'tr', function() {
$( this ).find( '.found-radio input' ).prop( 'checked', true );
});
});
})( jQuery );
| 01-wordpress-paypal | trunk/wp-admin/js/media.js | JavaScript | gpl3 | 2,419 |
/* global ajaxurl */
(function($) {
$(document).ready(function() {
var frame,
bgImage = $( '#custom-background-image' );
$('#background-color').wpColorPicker({
change: function( event, ui ) {
bgImage.css('background-color', ui.color.toString());
},
clear: function() {
bgImage.css('background-color', '');
}
});
$('input[name="background-position-x"]').change(function() {
bgImage.css('background-position', $(this).val() + ' top');
});
$('input[name="background-repeat"]').change(function() {
bgImage.css('background-repeat', $(this).val());
});
$('#choose-from-library-link').click( function( event ) {
var $el = $(this);
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create the media frame.
frame = wp.media.frames.customBackground = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Tell the modal to show only images.
library: {
type: 'image'
},
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
frame.on( 'select', function() {
// Grab the selected attachment.
var attachment = frame.state().get('selection').first();
// Run an AJAX request to set the background image.
$.post( ajaxurl, {
action: 'set-background-image',
attachment_id: attachment.id,
size: 'full'
}).done( function() {
// When the request completes, reload the window.
window.location.reload();
});
});
// Finally, open the modal.
frame.open();
});
});
})(jQuery);
| 01-wordpress-paypal | trunk/wp-admin/js/custom-background.js | JavaScript | gpl3 | 1,874 |
/* global inlineEditL10n, ajaxurl, typenow */
var inlineEditPost;
(function($) {
inlineEditPost = {
init : function(){
var t = this, qeRow = $('#inline-edit'), bulkRow = $('#bulk-edit');
t.type = $('table.widefat').hasClass('pages') ? 'page' : 'post';
t.what = '#post-';
// prepare the edit rows
qeRow.keyup(function(e){
if ( e.which === 27 ) {
return inlineEditPost.revert();
}
});
bulkRow.keyup(function(e){
if ( e.which === 27 ) {
return inlineEditPost.revert();
}
});
$('a.cancel', qeRow).click(function(){
return inlineEditPost.revert();
});
$('a.save', qeRow).click(function(){
return inlineEditPost.save(this);
});
$('td', qeRow).keydown(function(e){
if ( e.which === 13 ) {
return inlineEditPost.save(this);
}
});
$('a.cancel', bulkRow).click(function(){
return inlineEditPost.revert();
});
$('#inline-edit .inline-edit-private input[value="private"]').click( function(){
var pw = $('input.inline-edit-password-input');
if ( $(this).prop('checked') ) {
pw.val('').prop('disabled', true);
} else {
pw.prop('disabled', false);
}
});
// add events
$('#the-list').on('click', 'a.editinline', function(){
inlineEditPost.edit(this);
return false;
});
$('#bulk-title-div').parents('fieldset').after(
$('#inline-edit fieldset.inline-edit-categories').clone()
).siblings( 'fieldset:last' ).prepend(
$('#inline-edit label.inline-edit-tags').clone()
);
$('select[name="_status"] option[value="future"]', bulkRow).remove();
$('#doaction, #doaction2').click(function(e){
var n = $(this).attr('id').substr(2);
if ( 'edit' === $( 'select[name="' + n + '"]' ).val() ) {
e.preventDefault();
t.setBulk();
} else if ( $('form#posts-filter tr.inline-editor').length > 0 ) {
t.revert();
}
});
},
toggle : function(el){
var t = this;
$( t.what + t.getId( el ) ).css( 'display' ) === 'none' ? t.revert() : t.edit( el );
},
setBulk : function(){
var te = '', type = this.type, tax, c = true;
this.revert();
$('#bulk-edit td').attr('colspan', $('.widefat:first thead th:visible').length);
$('table.widefat tbody').prepend( $('#bulk-edit') );
$('#bulk-edit').addClass('inline-editor').show();
$( 'tbody th.check-column input[type="checkbox"]' ).each( function() {
if ( $(this).prop('checked') ) {
c = false;
var id = $(this).val(), theTitle;
theTitle = $('#inline_'+id+' .post_title').html() || inlineEditL10n.notitle;
te += '<div id="ttle'+id+'"><a id="_'+id+'" class="ntdelbutton" title="'+inlineEditL10n.ntdeltitle+'">X</a>'+theTitle+'</div>';
}
});
if ( c ) {
return this.revert();
}
$('#bulk-titles').html(te);
$('#bulk-titles a').click(function(){
var id = $(this).attr('id').substr(1);
$('table.widefat input[value="' + id + '"]').prop('checked', false);
$('#ttle'+id).remove();
});
// enable autocomplete for tags
if ( 'post' === type ) {
// support multi taxonomies?
tax = 'post_tag';
$('tr.inline-editor textarea[name="tax_input['+tax+']"]').suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } );
}
$('html, body').animate( { scrollTop: 0 }, 'fast' );
},
edit : function(id) {
var t = this, fields, editRow, rowData, status, pageOpt, pageLevel, nextPage, pageLoop = true, nextLevel, cur_format, f;
t.revert();
if ( typeof(id) === 'object' ) {
id = t.getId(id);
}
fields = ['post_title', 'post_name', 'post_author', '_status', 'jj', 'mm', 'aa', 'hh', 'mn', 'ss', 'post_password', 'post_format', 'menu_order'];
if ( t.type === 'page' ) {
fields.push('post_parent', 'page_template');
}
// add the new blank row
editRow = $('#inline-edit').clone(true);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $( t.what + id ).hasClass( 'alternate' ) ) {
$(editRow).addClass('alternate');
}
$(t.what+id).hide().after(editRow);
// populate the data
rowData = $('#inline_'+id);
if ( !$(':input[name="post_author"] option[value="' + $('.post_author', rowData).text() + '"]', editRow).val() ) {
// author no longer has edit caps, so we need to add them to the list of authors
$(':input[name="post_author"]', editRow).prepend('<option value="' + $('.post_author', rowData).text() + '">' + $('#' + t.type + '-' + id + ' .author').text() + '</option>');
}
if ( $( ':input[name="post_author"] option', editRow ).length === 1 ) {
$('label.inline-edit-author', editRow).hide();
}
// hide unsupported formats, but leave the current format alone
cur_format = $('.post_format', rowData).text();
$('option.unsupported', editRow).each(function() {
var $this = $(this);
if ( $this.val() !== cur_format ) {
$this.remove();
}
});
for ( f = 0; f < fields.length; f++ ) {
$(':input[name="' + fields[f] + '"]', editRow).val( $('.'+fields[f], rowData).text() );
}
if ( $( '.comment_status', rowData ).text() === 'open' ) {
$( 'input[name="comment_status"]', editRow ).prop( 'checked', true );
}
if ( $( '.ping_status', rowData ).text() === 'open' ) {
$( 'input[name="ping_status"]', editRow ).prop( 'checked', true );
}
if ( $( '.sticky', rowData ).text() === 'sticky' ) {
$( 'input[name="sticky"]', editRow ).prop( 'checked', true );
}
// hierarchical taxonomies
$('.post_category', rowData).each(function(){
var taxname,
term_ids = $(this).text();
if ( term_ids ) {
taxname = $(this).attr('id').replace('_'+id, '');
$('ul.'+taxname+'-checklist :checkbox', editRow).val(term_ids.split(','));
}
});
//flat taxonomies
$('.tags_input', rowData).each(function(){
var terms = $(this).text(),
taxname = $(this).attr('id').replace('_' + id, ''),
textarea = $('textarea.tax_input_' + taxname, editRow),
comma = inlineEditL10n.comma;
if ( terms ) {
if ( ',' !== comma ) {
terms = terms.replace(/,/g, comma);
}
textarea.val(terms);
}
textarea.suggest( ajaxurl + '?action=ajax-tag-search&tax=' + taxname, { delay: 500, minchars: 2, multiple: true, multipleSep: inlineEditL10n.comma + ' ' } );
});
// handle the post status
status = $('._status', rowData).text();
if ( 'future' !== status ) {
$('select[name="_status"] option[value="future"]', editRow).remove();
}
if ( 'private' === status ) {
$('input[name="keep_private"]', editRow).prop('checked', true);
$('input.inline-edit-password-input').val('').prop('disabled', true);
}
// remove the current page and children from the parent dropdown
pageOpt = $('select[name="post_parent"] option[value="' + id + '"]', editRow);
if ( pageOpt.length > 0 ) {
pageLevel = pageOpt[0].className.split('-')[1];
nextPage = pageOpt;
while ( pageLoop ) {
nextPage = nextPage.next('option');
if ( nextPage.length === 0 ) {
break;
}
nextLevel = nextPage[0].className.split('-')[1];
if ( nextLevel <= pageLevel ) {
pageLoop = false;
} else {
nextPage.remove();
nextPage = pageOpt;
}
}
pageOpt.remove();
}
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).focus();
return false;
},
save : function(id) {
var params, fields, page = $('.post_status_page').val() || '';
if ( typeof(id) === 'object' ) {
id = this.getId(id);
}
$('table.widefat .spinner').show();
params = {
action: 'inline-save',
post_type: typenow,
post_ID: id,
edit_date: 'true',
post_status: page
};
fields = $('#edit-'+id).find(':input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post( ajaxurl, params,
function(r) {
$('table.widefat .spinner').hide();
if (r) {
if ( -1 !== r.indexOf( '<tr' ) ) {
$(inlineEditPost.what+id).remove();
$('#edit-'+id).before(r).remove();
$(inlineEditPost.what+id).hide().fadeIn();
} else {
r = r.replace( /<.[^<>]*?>/g, '' );
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
}
} else {
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
if ( $('#post-'+id).prev().hasClass('alternate') ) {
$('#post-'+id).removeClass('alternate');
}
},
'html');
return false;
},
revert : function(){
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .spinner').hide();
if ( 'bulk-edit' === id ) {
$('table.widefat #bulk-edit').removeClass('inline-editor').hide();
$('#bulk-titles').html('');
$('#inlineedit').append( $('#bulk-edit') );
} else {
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
}
return false;
},
getId : function(o) {
var id = $(o).closest('tr').attr('id'),
parts = id.split('-');
return parts[parts.length - 1];
}
};
$( document ).ready( function(){ inlineEditPost.init(); } );
// Show/hide locks on posts
$( document ).on( 'heartbeat-tick.wp-check-locked-posts', function( e, data ) {
var locked = data['wp-check-locked-posts'] || {};
$('#the-list tr').each( function(i, el) {
var key = el.id, row = $(el), lock_data, avatar;
if ( locked.hasOwnProperty( key ) ) {
if ( ! row.hasClass('wp-locked') ) {
lock_data = locked[key];
row.find('.column-title .locked-text').text( lock_data.text );
row.find('.check-column checkbox').prop('checked', false);
if ( lock_data.avatar_src ) {
avatar = $('<img class="avatar avatar-18 photo" width="18" height="18" />').attr( 'src', lock_data.avatar_src.replace(/&/g, '&') );
row.find('.column-title .locked-avatar').empty().append( avatar );
}
row.addClass('wp-locked');
}
} else if ( row.hasClass('wp-locked') ) {
// Make room for the CSS animation
row.removeClass('wp-locked').delay(1000).find('.locked-info span').empty();
}
});
}).on( 'heartbeat-send.wp-check-locked-posts', function( e, data ) {
var check = [];
$('#the-list tr').each( function(i, el) {
if ( el.id ) {
check.push( el.id );
}
});
if ( check.length ) {
data['wp-check-locked-posts'] = check;
}
}).ready( function() {
// Set the heartbeat interval to 15 sec.
if ( typeof wp !== 'undefined' && wp.heartbeat ) {
wp.heartbeat.interval( 15 );
}
});
}(jQuery));
| 01-wordpress-paypal | trunk/wp-admin/js/inline-edit-post.js | JavaScript | gpl3 | 10,393 |
/* global unescape, getUserSetting, setUserSetting */
jQuery(document).ready(function($) {
var gallerySortable, gallerySortableInit, sortIt, clearAll, w, desc = false;
gallerySortableInit = function() {
gallerySortable = $('#media-items').sortable( {
items: 'div.media-item',
placeholder: 'sorthelper',
axis: 'y',
distance: 2,
handle: 'div.filename',
stop: function() {
// When an update has occurred, adjust the order for each item
var all = $('#media-items').sortable('toArray'), len = all.length;
$.each(all, function(i, id) {
var order = desc ? (len - i) : (1 + i);
$('#' + id + ' .menu_order input').val(order);
});
}
} );
};
sortIt = function() {
var all = $('.menu_order_input'), len = all.length;
all.each(function(i){
var order = desc ? (len - i) : (1 + i);
$(this).val(order);
});
};
clearAll = function(c) {
c = c || 0;
$('.menu_order_input').each( function() {
if ( this.value === '0' || c ) {
this.value = '';
}
});
};
$('#asc').click( function() {
desc = false;
sortIt();
return false;
});
$('#desc').click( function() {
desc = true;
sortIt();
return false;
});
$('#clear').click( function() {
clearAll(1);
return false;
});
$('#showall').click( function() {
$('#sort-buttons span a').toggle();
$('a.describe-toggle-on').hide();
$('a.describe-toggle-off, table.slidetoggle').show();
$('img.pinkynail').toggle(false);
return false;
});
$('#hideall').click( function() {
$('#sort-buttons span a').toggle();
$('a.describe-toggle-on').show();
$('a.describe-toggle-off, table.slidetoggle').hide();
$('img.pinkynail').toggle(true);
return false;
});
// initialize sortable
gallerySortableInit();
clearAll();
if ( $('#media-items>*').length > 1 ) {
w = wpgallery.getWin();
$('#save-all, #gallery-settings').show();
if ( typeof w.tinyMCE !== 'undefined' && w.tinyMCE.activeEditor && ! w.tinyMCE.activeEditor.isHidden() ) {
wpgallery.mcemode = true;
wpgallery.init();
} else {
$('#insert-gallery').show();
}
}
});
jQuery(window).unload( function () { tinymce = tinyMCE = wpgallery = null; } ); // Cleanup
/* gallery settings */
var tinymce = null, tinyMCE, wpgallery;
wpgallery = {
mcemode : false,
editor : {},
dom : {},
is_update : false,
el : {},
I : function(e) {
return document.getElementById(e);
},
init: function() {
var t = this, li, q, i, it, w = t.getWin();
if ( ! t.mcemode ) {
return;
}
li = ('' + document.location.search).replace(/^\?/, '').split('&');
q = {};
for (i=0; i<li.length; i++) {
it = li[i].split('=');
q[unescape(it[0])] = unescape(it[1]);
}
if ( q.mce_rdomain ) {
document.domain = q.mce_rdomain;
}
// Find window & API
tinymce = w.tinymce;
tinyMCE = w.tinyMCE;
t.editor = tinymce.EditorManager.activeEditor;
t.setup();
},
getWin : function() {
return window.dialogArguments || opener || parent || top;
},
setup : function() {
var t = this, a, ed = t.editor, g, columns, link, order, orderby;
if ( ! t.mcemode ) {
return;
}
t.el = ed.selection.getNode();
if ( t.el.nodeName !== 'IMG' || ! ed.dom.hasClass(t.el, 'wpGallery') ) {
if ( ( g = ed.dom.select('img.wpGallery') ) && g[0] ) {
t.el = g[0];
} else {
if ( getUserSetting('galfile') === '1' ) {
t.I('linkto-file').checked = 'checked';
}
if ( getUserSetting('galdesc') === '1' ) {
t.I('order-desc').checked = 'checked';
}
if ( getUserSetting('galcols') ) {
t.I('columns').value = getUserSetting('galcols');
}
if ( getUserSetting('galord') ) {
t.I('orderby').value = getUserSetting('galord');
}
jQuery('#insert-gallery').show();
return;
}
}
a = ed.dom.getAttrib(t.el, 'title');
a = ed.dom.decode(a);
if ( a ) {
jQuery('#update-gallery').show();
t.is_update = true;
columns = a.match(/columns=['"]([0-9]+)['"]/);
link = a.match(/link=['"]([^'"]+)['"]/i);
order = a.match(/order=['"]([^'"]+)['"]/i);
orderby = a.match(/orderby=['"]([^'"]+)['"]/i);
if ( link && link[1] ) {
t.I('linkto-file').checked = 'checked';
}
if ( order && order[1] ) {
t.I('order-desc').checked = 'checked';
}
if ( columns && columns[1] ) {
t.I('columns').value = '' + columns[1];
}
if ( orderby && orderby[1] ) {
t.I('orderby').value = orderby[1];
}
} else {
jQuery('#insert-gallery').show();
}
},
update : function() {
var t = this, ed = t.editor, all = '', s;
if ( ! t.mcemode || ! t.is_update ) {
s = '[gallery' + t.getSettings() + ']';
t.getWin().send_to_editor(s);
return;
}
if ( t.el.nodeName !== 'IMG' ) {
return;
}
all = ed.dom.decode( ed.dom.getAttrib( t.el, 'title' ) );
all = all.replace(/\s*(order|link|columns|orderby)=['"]([^'"]+)['"]/gi, '');
all += t.getSettings();
ed.dom.setAttrib(t.el, 'title', all);
t.getWin().tb_remove();
},
getSettings : function() {
var I = this.I, s = '';
if ( I('linkto-file').checked ) {
s += ' link="file"';
setUserSetting('galfile', '1');
}
if ( I('order-desc').checked ) {
s += ' order="DESC"';
setUserSetting('galdesc', '1');
}
if ( I('columns').value !== 3 ) {
s += ' columns="' + I('columns').value + '"';
setUserSetting('galcols', I('columns').value);
}
if ( I('orderby').value !== 'menu_order' ) {
s += ' orderby="' + I('orderby').value + '"';
setUserSetting('galord', I('orderby').value);
}
return s;
}
};
| 01-wordpress-paypal | trunk/wp-admin/js/gallery.js | JavaScript | gpl3 | 5,505 |
/* global _wpThemeSettings, confirm */
window.wp = window.wp || {};
( function($) {
// Set up our namespace...
var themes, l10n;
themes = wp.themes = wp.themes || {};
// Store the theme data and settings for organized and quick access
// themes.data.settings, themes.data.themes, themes.data.l10n
themes.data = _wpThemeSettings;
l10n = themes.data.l10n;
// Shortcut for isInstall check
themes.isInstall = !! themes.data.settings.isInstall;
// Setup app structure
_.extend( themes, { model: {}, view: {}, routes: {}, router: {}, template: wp.template });
themes.Model = Backbone.Model.extend({
// Adds attributes to the default data coming through the .org themes api
// Map `id` to `slug` for shared code
initialize: function() {
var description;
// If theme is already installed, set an attribute.
if ( _.indexOf( themes.data.installedThemes, this.get( 'slug' ) ) !== -1 ) {
this.set({ installed: true });
}
// Set the attributes
this.set({
// slug is for installation, id is for existing.
id: this.get( 'slug' ) || this.get( 'id' )
});
// Map `section.description` to `description`
// as the API sometimes returns it differently
if ( this.has( 'sections' ) ) {
description = this.get( 'sections' ).description;
this.set({ description: description });
}
}
});
// Main view controller for themes.php
// Unifies and renders all available views
themes.view.Appearance = wp.Backbone.View.extend({
el: '#wpbody-content .wrap .theme-browser',
window: $( window ),
// Pagination instance
page: 0,
// Sets up a throttler for binding to 'scroll'
initialize: function( options ) {
// Scroller checks how far the scroll position is
_.bindAll( this, 'scroller' );
this.SearchView = options.SearchView ? options.SearchView : themes.view.Search;
// Bind to the scroll event and throttle
// the results from this.scroller
this.window.bind( 'scroll', _.throttle( this.scroller, 300 ) );
},
// Main render control
render: function() {
// Setup the main theme view
// with the current theme collection
this.view = new themes.view.Themes({
collection: this.collection,
parent: this
});
// Render search form.
this.search();
// Render and append
this.view.render();
this.$el.empty().append( this.view.el ).addClass('rendered');
this.$el.append( '<br class="clear"/>' );
},
// Defines search element container
searchContainer: $( '#wpbody h2:first' ),
// Search input and view
// for current theme collection
search: function() {
var view,
self = this;
// Don't render the search if there is only one theme
if ( themes.data.themes.length === 1 ) {
return;
}
view = new this.SearchView({
collection: self.collection,
parent: this
});
// Render and append after screen title
view.render();
this.searchContainer
.append( $.parseHTML( '<label class="screen-reader-text" for="theme-search-input">' + l10n.search + '</label>' ) )
.append( view.el );
},
// Checks when the user gets close to the bottom
// of the mage and triggers a theme:scroll event
scroller: function() {
var self = this,
bottom, threshold;
bottom = this.window.scrollTop() + self.window.height();
threshold = self.$el.offset().top + self.$el.outerHeight( false ) - self.window.height();
threshold = Math.round( threshold * 0.9 );
if ( bottom > threshold ) {
this.trigger( 'theme:scroll' );
}
}
});
// Set up the Collection for our theme data
// @has 'id' 'name' 'screenshot' 'author' 'authorURI' 'version' 'active' ...
themes.Collection = Backbone.Collection.extend({
model: themes.Model,
// Search terms
terms: '',
// Controls searching on the current theme collection
// and triggers an update event
doSearch: function( value ) {
// Don't do anything if we've already done this search
// Useful because the Search handler fires multiple times per keystroke
if ( this.terms === value ) {
return;
}
// Updates terms with the value passed
this.terms = value;
// If we have terms, run a search...
if ( this.terms.length > 0 ) {
this.search( this.terms );
}
// If search is blank, show all themes
// Useful for resetting the views when you clean the input
if ( this.terms === '' ) {
this.reset( themes.data.themes );
}
// Trigger an 'update' event
this.trigger( 'update' );
},
// Performs a search within the collection
// @uses RegExp
search: function( term ) {
var match, results, haystack;
// Start with a full collection
this.reset( themes.data.themes, { silent: true } );
// Escape the term string for RegExp meta characters
term = term.replace( /[-\/\\^$*+?.()|[\]{}]/g, '\\$&' );
// Consider spaces as word delimiters and match the whole string
// so matching terms can be combined
term = term.replace( / /g, ')(?=.*' );
match = new RegExp( '^(?=.*' + term + ').+', 'i' );
// Find results
// _.filter and .test
results = this.filter( function( data ) {
haystack = _.union( data.get( 'name' ), data.get( 'id' ), data.get( 'description' ), data.get( 'author' ), data.get( 'tags' ) );
if ( match.test( data.get( 'author' ) ) && term.length > 2 ) {
data.set( 'displayAuthor', true );
}
return match.test( haystack );
});
this.reset( results );
},
// Paginates the collection with a helper method
// that slices the collection
paginate: function( instance ) {
var collection = this;
instance = instance || 0;
// Themes per instance are set at 20
collection = _( collection.rest( 20 * instance ) );
collection = _( collection.first( 20 ) );
return collection;
},
count: false,
// Handles requests for more themes
// and caches results
//
// When we are missing a cache object we fire an apiCall()
// which triggers events of `query:success` or `query:fail`
query: function( request ) {
/**
* @static
* @type Array
*/
var queries = this.queries,
self = this,
query, isPaginated, count;
// Store current query request args
// for later use with the event `theme:end`
this.currentQuery.request = request;
// Search the query cache for matches.
query = _.find( queries, function( query ) {
return _.isEqual( query.request, request );
});
// If the request matches the stored currentQuery.request
// it means we have a paginated request.
isPaginated = _.has( request, 'page' );
// Reset the internal api page counter for non paginated queries.
if ( ! isPaginated ) {
this.currentQuery.page = 1;
}
// Otherwise, send a new API call and add it to the cache.
if ( ! query && ! isPaginated ) {
query = this.apiCall( request ).done( function( data ) {
// Update the collection with the queried data.
if ( data.themes ) {
self.reset( data.themes );
count = data.info.results;
// Store the results and the query request
queries.push( { themes: data.themes, request: request, total: count } );
}
// Trigger a collection refresh event
// and a `query:success` event with a `count` argument.
self.trigger( 'update' );
self.trigger( 'query:success', count );
if ( data.themes && data.themes.length === 0 ) {
self.trigger( 'query:empty' );
}
}).fail( function() {
self.trigger( 'query:fail' );
});
} else {
// If it's a paginated request we need to fetch more themes...
if ( isPaginated ) {
return this.apiCall( request, isPaginated ).done( function( data ) {
// Add the new themes to the current collection
// @todo update counter
self.add( data.themes );
self.trigger( 'query:success' );
// We are done loading themes for now.
self.loadingThemes = false;
}).fail( function() {
self.trigger( 'query:fail' );
});
}
if ( query.themes.length === 0 ) {
self.trigger( 'query:empty' );
} else {
$( 'body' ).removeClass( 'no-results' );
}
// Only trigger an update event since we already have the themes
// on our cached object
if ( _.isNumber( query.total ) ) {
this.count = query.total;
}
this.reset( query.themes );
if ( ! query.total ) {
this.count = this.length;
}
this.trigger( 'update' );
this.trigger( 'query:success', this.count );
}
},
// Local cache array for API queries
queries: [],
// Keep track of current query so we can handle pagination
currentQuery: {
page: 1,
request: {}
},
// Send request to api.wordpress.org/themes
apiCall: function( request, paginated ) {
return wp.ajax.send( 'query-themes', {
data: {
// Request data
request: _.extend({
per_page: 100,
fields: {
description: true,
tested: true,
requires: true,
rating: true,
downloaded: true,
downloadLink: true,
last_updated: true,
homepage: true,
num_ratings: true
}
}, request)
},
beforeSend: function() {
if ( ! paginated ) {
// Spin it
$( 'body' ).addClass( 'loading-themes' ).removeClass( 'no-results' );
}
}
});
},
// Static status controller for when we are loading themes.
loadingThemes: false
});
// This is the view that controls each theme item
// that will be displayed on the screen
themes.view.Theme = wp.Backbone.View.extend({
// Wrap theme data on a div.theme element
className: 'theme',
// Reflects which theme view we have
// 'grid' (default) or 'detail'
state: 'grid',
// The HTML template for each element to be rendered
html: themes.template( 'theme' ),
events: {
'click': themes.isInstall ? 'preview': 'expand',
'click .preview': 'preview',
'keydown': themes.isInstall ? 'preview': 'expand',
'touchend': themes.isInstall ? 'preview': 'expand',
'keyup': 'addFocus',
'touchmove': 'preventExpand'
},
touchDrag: false,
render: function() {
var data = this.model.toJSON();
// Render themes using the html template
this.$el.html( this.html( data ) ).attr({
tabindex: 0,
'aria-describedby' : data.id + '-action ' + data.id + '-name'
});
// Renders active theme styles
this.activeTheme();
if ( this.model.get( 'displayAuthor' ) ) {
this.$el.addClass( 'display-author' );
}
if ( this.model.get( 'installed' ) ) {
this.$el.addClass( 'is-installed' );
}
},
// Adds a class to the currently active theme
// and to the overlay in detailed view mode
activeTheme: function() {
if ( this.model.get( 'active' ) ) {
this.$el.addClass( 'active' );
}
},
// Add class of focus to the theme we are focused on.
addFocus: function() {
var $themeToFocus = ( $( ':focus' ).hasClass( 'theme' ) ) ? $( ':focus' ) : $(':focus').parents('.theme');
$('.theme.focus').removeClass('focus');
$themeToFocus.addClass('focus');
},
// Single theme overlay screen
// It's shown when clicking a theme
expand: function( event ) {
var self = this;
event = event || window.event;
// 'enter' and 'space' keys expand the details view when a theme is :focused
if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
return;
}
// Bail if the user scrolled on a touch device
if ( this.touchDrag === true ) {
return this.touchDrag = false;
}
// Prevent the modal from showing when the user clicks
// one of the direct action buttons
if ( $( event.target ).is( '.theme-actions a' ) ) {
return;
}
// Set focused theme to current element
themes.focusedTheme = this.$el;
this.trigger( 'theme:expand', self.model.cid );
},
preventExpand: function() {
this.touchDrag = true;
},
preview: function( event ) {
var self = this,
current, preview;
// Bail if the user scrolled on a touch device
if ( this.touchDrag === true ) {
return this.touchDrag = false;
}
// Allow direct link path to installing a theme.
if ( $( event.target ).hasClass( 'button-primary' ) ) {
return;
}
// 'enter' and 'space' keys expand the details view when a theme is :focused
if ( event.type === 'keydown' && ( event.which !== 13 && event.which !== 32 ) ) {
return;
}
// pressing enter while focused on the buttons shouldn't open the preview
if ( event.type === 'keydown' && event.which !== 13 && $( ':focus' ).hasClass( 'button' ) ) {
return;
}
event.preventDefault();
event = event || window.event;
// Set focus to current theme.
themes.focusedTheme = this.$el;
// Construct a new Preview view.
preview = new themes.view.Preview({
model: this.model
});
// Render the view and append it.
preview.render();
this.setNavButtonsState();
// Hide previous/next navigation if there is only one theme
if ( this.model.collection.length === 1 ) {
preview.$el.addClass( 'no-navigation' );
} else {
preview.$el.removeClass( 'no-navigation' );
}
// Apend preview
$( 'div.wrap' ).append( preview.el );
// Listen to our preview object
// for `theme:next` and `theme:previous` events.
this.listenTo( preview, 'theme:next', function() {
// Keep local track of current theme model.
current = self.model;
// If we have ventured away from current model update the current model position.
if ( ! _.isUndefined( self.current ) ) {
current = self.current;
}
// Get previous theme model.
self.current = self.model.collection.at( self.model.collection.indexOf( current ) + 1 );
// If we have no more themes, bail.
if ( _.isUndefined( self.current ) ) {
self.options.parent.parent.trigger( 'theme:end' );
return self.current = current;
}
// Construct a new Preview view.
preview = new themes.view.Preview({
model: self.current
});
// Render and append.
preview.render();
this.setNavButtonsState();
$( 'div.wrap' ).append( preview.el );
$( '.next-theme' ).focus();
})
.listenTo( preview, 'theme:previous', function() {
// Keep track of current theme model.
current = self.model;
// Bail early if we are at the beginning of the collection
if ( self.model.collection.indexOf( self.current ) === 0 ) {
return;
}
// If we have ventured away from current model update the current model position.
if ( ! _.isUndefined( self.current ) ) {
current = self.current;
}
// Get previous theme model.
self.current = self.model.collection.at( self.model.collection.indexOf( current ) - 1 );
// If we have no more themes, bail.
if ( _.isUndefined( self.current ) ) {
return;
}
// Construct a new Preview view.
preview = new themes.view.Preview({
model: self.current
});
// Render and append.
preview.render();
this.setNavButtonsState();
$( 'div.wrap' ).append( preview.el );
$( '.previous-theme' ).focus();
});
this.listenTo( preview, 'preview:close', function() {
self.current = self.model;
});
},
// Handles .disabled classes for previous/next buttons in theme installer preview
setNavButtonsState: function() {
var $themeInstaller = $( '.theme-install-overlay' ),
current = _.isUndefined( this.current ) ? this.model : this.current;
// Disable previous at the zero position
if ( 0 === this.model.collection.indexOf( current ) ) {
$themeInstaller.find( '.previous-theme' ).addClass( 'disabled' );
}
// Disable next if the next model is undefined
if ( _.isUndefined( this.model.collection.at( this.model.collection.indexOf( current ) + 1 ) ) ) {
$themeInstaller.find( '.next-theme' ).addClass( 'disabled' );
}
}
});
// Theme Details view
// Set ups a modal overlay with the expanded theme data
themes.view.Details = wp.Backbone.View.extend({
// Wrap theme data on a div.theme element
className: 'theme-overlay',
events: {
'click': 'collapse',
'click .delete-theme': 'deleteTheme',
'click .left': 'previousTheme',
'click .right': 'nextTheme'
},
// The HTML template for the theme overlay
html: themes.template( 'theme-single' ),
render: function() {
var data = this.model.toJSON();
this.$el.html( this.html( data ) );
// Renders active theme styles
this.activeTheme();
// Set up navigation events
this.navigation();
// Checks screenshot size
this.screenshotCheck( this.$el );
// Contain "tabbing" inside the overlay
this.containFocus( this.$el );
},
// Adds a class to the currently active theme
// and to the overlay in detailed view mode
activeTheme: function() {
// Check the model has the active property
this.$el.toggleClass( 'active', this.model.get( 'active' ) );
},
// Keeps :focus within the theme details elements
containFocus: function( $el ) {
var $target;
// Move focus to the primary action
_.delay( function() {
$( '.theme-wrap a.button-primary:visible' ).focus();
}, 500 );
$el.on( 'keydown.wp-themes', function( event ) {
// Tab key
if ( event.which === 9 ) {
$target = $( event.target );
// Keep focus within the overlay by making the last link on theme actions
// switch focus to button.left on tabbing and vice versa
if ( $target.is( 'button.left' ) && event.shiftKey ) {
$el.find( '.theme-actions a:last-child' ).focus();
event.preventDefault();
} else if ( $target.is( '.theme-actions a:last-child' ) ) {
$el.find( 'button.left' ).focus();
event.preventDefault();
}
}
});
},
// Single theme overlay screen
// It's shown when clicking a theme
collapse: function( event ) {
var self = this,
scroll;
event = event || window.event;
// Prevent collapsing detailed view when there is only one theme available
if ( themes.data.themes.length === 1 ) {
return;
}
// Detect if the click is inside the overlay
// and don't close it unless the target was
// the div.back button
if ( $( event.target ).is( '.theme-backdrop' ) || $( event.target ).is( '.close' ) || event.keyCode === 27 ) {
// Add a temporary closing class while overlay fades out
$( 'body' ).addClass( 'closing-overlay' );
// With a quick fade out animation
this.$el.fadeOut( 130, function() {
// Clicking outside the modal box closes the overlay
$( 'body' ).removeClass( 'closing-overlay' );
// Handle event cleanup
self.closeOverlay();
// Get scroll position to avoid jumping to the top
scroll = document.body.scrollTop;
// Clean the url structure
themes.router.navigate( themes.router.baseUrl( '' ) );
// Restore scroll position
document.body.scrollTop = scroll;
// Return focus to the theme div
if ( themes.focusedTheme ) {
themes.focusedTheme.focus();
}
});
}
},
// Handles .disabled classes for next/previous buttons
navigation: function() {
// Disable Left/Right when at the start or end of the collection
if ( this.model.cid === this.model.collection.at(0).cid ) {
this.$el.find( '.left' ).addClass( 'disabled' );
}
if ( this.model.cid === this.model.collection.at( this.model.collection.length - 1 ).cid ) {
this.$el.find( '.right' ).addClass( 'disabled' );
}
},
// Performs the actions to effectively close
// the theme details overlay
closeOverlay: function() {
$( 'body' ).removeClass( 'theme-overlay-open' );
this.remove();
this.unbind();
this.trigger( 'theme:collapse' );
},
// Confirmation dialog for deleting a theme
deleteTheme: function() {
return confirm( themes.data.settings.confirmDelete );
},
nextTheme: function() {
var self = this;
self.trigger( 'theme:next', self.model.cid );
return false;
},
previousTheme: function() {
var self = this;
self.trigger( 'theme:previous', self.model.cid );
return false;
},
// Checks if the theme screenshot is the old 300px width version
// and adds a corresponding class if it's true
screenshotCheck: function( el ) {
var screenshot, image;
screenshot = el.find( '.screenshot img' );
image = new Image();
image.src = screenshot.attr( 'src' );
// Width check
if ( image.width && image.width <= 300 ) {
el.addClass( 'small-screenshot' );
}
}
});
// Theme Preview view
// Set ups a modal overlay with the expanded theme data
themes.view.Preview = themes.view.Details.extend({
className: 'wp-full-overlay expanded',
el: '.theme-install-overlay',
events: {
'click .close-full-overlay': 'close',
'click .collapse-sidebar': 'collapse',
'click .previous-theme': 'previousTheme',
'click .next-theme': 'nextTheme',
'keyup': 'keyEvent'
},
// The HTML template for the theme preview
html: themes.template( 'theme-preview' ),
render: function() {
var data = this.model.toJSON();
this.$el.html( this.html( data ) );
themes.router.navigate( themes.router.baseUrl( '?theme=' + this.model.get( 'id' ) ), { replace: true } );
this.$el.fadeIn( 200, function() {
$( 'body' ).addClass( 'theme-installer-active full-overlay-active' );
$( '.close-full-overlay' ).focus();
});
},
close: function() {
this.$el.fadeOut( 200, function() {
$( 'body' ).removeClass( 'theme-installer-active full-overlay-active' );
// Return focus to the theme div
if ( themes.focusedTheme ) {
themes.focusedTheme.focus();
}
});
themes.router.navigate( themes.router.baseUrl( '' ) );
this.trigger( 'preview:close' );
this.unbind();
return false;
},
collapse: function() {
this.$el.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
return false;
},
keyEvent: function( event ) {
// The escape key closes the preview
if ( event.keyCode === 27 ) {
this.undelegateEvents();
this.close();
}
// The right arrow key, next theme
if ( event.keyCode === 39 ) {
_.once( this.nextTheme() );
}
// The left arrow key, previous theme
if ( event.keyCode === 37 ) {
this.previousTheme();
}
}
});
// Controls the rendering of div.themes,
// a wrapper that will hold all the theme elements
themes.view.Themes = wp.Backbone.View.extend({
className: 'themes',
$overlay: $( 'div.theme-overlay' ),
// Number to keep track of scroll position
// while in theme-overlay mode
index: 0,
// The theme count element
count: $( '.theme-count' ),
initialize: function( options ) {
var self = this;
// Set up parent
this.parent = options.parent;
// Set current view to [grid]
this.setView( 'grid' );
// Move the active theme to the beginning of the collection
self.currentTheme();
// When the collection is updated by user input...
this.listenTo( self.collection, 'update', function() {
self.parent.page = 0;
self.currentTheme();
self.render( this );
});
// Update theme count to full result set when available.
this.listenTo( self.collection, 'query:success', function( count ) {
if ( _.isNumber( count ) ) {
self.count.text( count );
} else {
self.count.text( self.collection.length );
}
});
this.listenTo( self.collection, 'query:empty', function() {
$( 'body' ).addClass( 'no-results' );
});
this.listenTo( this.parent, 'theme:scroll', function() {
self.renderThemes( self.parent.page );
});
this.listenTo( this.parent, 'theme:close', function() {
if ( self.overlay ) {
self.overlay.closeOverlay();
}
} );
// Bind keyboard events.
$( 'body' ).on( 'keyup', function( event ) {
if ( ! self.overlay ) {
return;
}
// Pressing the right arrow key fires a theme:next event
if ( event.keyCode === 39 ) {
self.overlay.nextTheme();
}
// Pressing the left arrow key fires a theme:previous event
if ( event.keyCode === 37 ) {
self.overlay.previousTheme();
}
// Pressing the escape key fires a theme:collapse event
if ( event.keyCode === 27 ) {
self.overlay.collapse( event );
}
});
},
// Manages rendering of theme pages
// and keeping theme count in sync
render: function() {
// Clear the DOM, please
this.$el.html( '' );
// If the user doesn't have switch capabilities
// or there is only one theme in the collection
// render the detailed view of the active theme
if ( themes.data.themes.length === 1 ) {
// Constructs the view
this.singleTheme = new themes.view.Details({
model: this.collection.models[0]
});
// Render and apply a 'single-theme' class to our container
this.singleTheme.render();
this.$el.addClass( 'single-theme' );
this.$el.append( this.singleTheme.el );
}
// Generate the themes
// Using page instance
// While checking the collection has items
if ( this.options.collection.size() > 0 ) {
this.renderThemes( this.parent.page );
}
// Display a live theme count for the collection
this.count.text( this.collection.count ? this.collection.count : this.collection.length );
},
// Iterates through each instance of the collection
// and renders each theme module
renderThemes: function( page ) {
var self = this;
self.instance = self.collection.paginate( page );
// If we have no more themes bail
if ( self.instance.size() === 0 ) {
// Fire a no-more-themes event.
this.parent.trigger( 'theme:end' );
return;
}
// Make sure the add-new stays at the end
if ( page >= 1 ) {
$( '.add-new-theme' ).remove();
}
// Loop through the themes and setup each theme view
self.instance.each( function( theme ) {
self.theme = new themes.view.Theme({
model: theme,
parent: self
});
// Render the views...
self.theme.render();
// and append them to div.themes
self.$el.append( self.theme.el );
// Binds to theme:expand to show the modal box
// with the theme details
self.listenTo( self.theme, 'theme:expand', self.expand, self );
});
// 'Add new theme' element shown at the end of the grid
if ( themes.data.settings.canInstall ) {
this.$el.append( '<div class="theme add-new-theme"><a href="' + themes.data.settings.installURI + '"><div class="theme-screenshot"><span></span></div><h3 class="theme-name">' + l10n.addNew + '</h3></a></div>' );
}
this.parent.page++;
},
// Grabs current theme and puts it at the beginning of the collection
currentTheme: function() {
var self = this,
current;
current = self.collection.findWhere({ active: true });
// Move the active theme to the beginning of the collection
if ( current ) {
self.collection.remove( current );
self.collection.add( current, { at:0 } );
}
},
// Sets current view
setView: function( view ) {
return view;
},
// Renders the overlay with the ThemeDetails view
// Uses the current model data
expand: function( id ) {
var self = this;
// Set the current theme model
this.model = self.collection.get( id );
// Trigger a route update for the current model
themes.router.navigate( themes.router.baseUrl( '?theme=' + this.model.id ) );
// Sets this.view to 'detail'
this.setView( 'detail' );
$( 'body' ).addClass( 'theme-overlay-open' );
// Set up the theme details view
this.overlay = new themes.view.Details({
model: self.model
});
this.overlay.render();
this.$overlay.html( this.overlay.el );
// Bind to theme:next and theme:previous
// triggered by the arrow keys
//
// Keep track of the current model so we
// can infer an index position
this.listenTo( this.overlay, 'theme:next', function() {
// Renders the next theme on the overlay
self.next( [ self.model.cid ] );
})
.listenTo( this.overlay, 'theme:previous', function() {
// Renders the previous theme on the overlay
self.previous( [ self.model.cid ] );
});
},
// This method renders the next theme on the overlay modal
// based on the current position in the collection
// @params [model cid]
next: function( args ) {
var self = this,
model, nextModel;
// Get the current theme
model = self.collection.get( args[0] );
// Find the next model within the collection
nextModel = self.collection.at( self.collection.indexOf( model ) + 1 );
// Sanity check which also serves as a boundary test
if ( nextModel !== undefined ) {
// We have a new theme...
// Close the overlay
this.overlay.closeOverlay();
// Trigger a route update for the current model
self.theme.trigger( 'theme:expand', nextModel.cid );
}
},
// This method renders the previous theme on the overlay modal
// based on the current position in the collection
// @params [model cid]
previous: function( args ) {
var self = this,
model, previousModel;
// Get the current theme
model = self.collection.get( args[0] );
// Find the previous model within the collection
previousModel = self.collection.at( self.collection.indexOf( model ) - 1 );
if ( previousModel !== undefined ) {
// We have a new theme...
// Close the overlay
this.overlay.closeOverlay();
// Trigger a route update for the current model
self.theme.trigger( 'theme:expand', previousModel.cid );
}
}
});
// Search input view controller.
themes.view.Search = wp.Backbone.View.extend({
tagName: 'input',
className: 'theme-search',
id: 'theme-search-input',
searching: false,
attributes: {
placeholder: l10n.searchPlaceholder,
type: 'search'
},
events: {
'input': 'search',
'keyup': 'search',
'change': 'search',
'search': 'search',
'blur': 'pushState'
},
initialize: function( options ) {
this.parent = options.parent;
this.listenTo( this.parent, 'theme:close', function() {
this.searching = false;
} );
},
// Runs a search on the theme collection.
search: function( event ) {
var options = {};
// Clear on escape.
if ( event.type === 'keyup' && event.which === 27 ) {
event.target.value = '';
}
// Lose input focus when pressing enter
if ( event.which === 13 ) {
this.$el.trigger( 'blur' );
}
this.collection.doSearch( event.target.value );
// if search is initiated and key is not return
if ( this.searching && event.which !== 13 ) {
options.replace = true;
} else {
this.searching = true;
}
// Update the URL hash
if ( event.target.value ) {
themes.router.navigate( themes.router.baseUrl( '?search=' + event.target.value ), options );
} else {
themes.router.navigate( themes.router.baseUrl( '' ) );
}
},
pushState: function( event ) {
var url = themes.router.baseUrl( '' );
if ( event.target.value ) {
url = themes.router.baseUrl( '?search=' + event.target.value );
}
this.searching = false;
themes.router.navigate( url );
}
});
// Sets up the routes events for relevant url queries
// Listens to [theme] and [search] params
themes.Router = Backbone.Router.extend({
routes: {
'themes.php?theme=:slug': 'theme',
'themes.php?search=:query': 'search',
'themes.php?s=:query': 'search',
'themes.php': 'themes',
'': 'themes'
},
baseUrl: function( url ) {
return 'themes.php' + url;
},
search: function( query ) {
$( '.theme-search' ).val( query );
},
themes: function() {
$( '.theme-search' ).val( '' );
},
navigate: function() {
if ( Backbone.history._hasPushState ) {
Backbone.Router.prototype.navigate.apply( this, arguments );
}
}
});
// Execute and setup the application
themes.Run = {
init: function() {
// Initializes the blog's theme library view
// Create a new collection with data
this.themes = new themes.Collection( themes.data.themes );
// Set up the view
this.view = new themes.view.Appearance({
collection: this.themes
});
this.render();
},
render: function() {
// Render results
this.view.render();
this.routes();
Backbone.history.start({
root: themes.data.settings.adminUrl,
pushState: true,
hashChange: false
});
},
routes: function() {
var self = this;
// Bind to our global thx object
// so that the object is available to sub-views
themes.router = new themes.Router();
// Handles theme details route event
themes.router.on( 'route:theme', function( slug ) {
self.view.view.expand( slug );
});
themes.router.on( 'route:themes', function() {
self.themes.doSearch( '' );
self.view.trigger( 'theme:close' );
});
// Handles search route event
themes.router.on( 'route:search', function() {
$( '.theme-search' ).trigger( 'keyup' );
});
this.extraRoutes();
},
extraRoutes: function() {
return false;
}
};
// Extend the main Search view
themes.view.InstallerSearch = themes.view.Search.extend({
events: {
'keyup': 'search'
},
// Handles Ajax request for searching through themes in public repo
search: function( event ) {
// Tabbing or reverse tabbing into the search input shouldn't trigger a search
if ( event.type === 'keyup' && ( event.which === 9 || event.which === 16 ) ) {
return;
}
this.collection = this.options.parent.view.collection;
// Clear on escape.
if ( event.type === 'keyup' && event.which === 27 ) {
event.target.value = '';
}
_.debounce( _.bind( this.doSearch, this ), 300 )( event.target.value );
},
doSearch: _.debounce( function( value ) {
var request = {};
request.search = value;
// Intercept an [author] search.
//
// If input value starts with `author:` send a request
// for `author` instead of a regular `search`
if ( value.substring( 0, 7 ) === 'author:' ) {
request.search = '';
request.author = value.slice( 7 );
}
// Intercept a [tag] search.
//
// If input value starts with `tag:` send a request
// for `tag` instead of a regular `search`
if ( value.substring( 0, 4 ) === 'tag:' ) {
request.search = '';
request.tag = [ value.slice( 4 ) ];
}
$( '.theme-section.current' ).removeClass( 'current' );
$( 'body' ).removeClass( 'more-filters-opened filters-applied' );
// Get the themes by sending Ajax POST request to api.wordpress.org/themes
// or searching the local cache
this.collection.query( request );
// Set route
themes.router.navigate( themes.router.baseUrl( '?search=' + value ), { replace: true } );
}, 300 )
});
themes.view.Installer = themes.view.Appearance.extend({
el: '#wpbody-content .wrap',
// Register events for sorting and filters in theme-navigation
events: {
'click .theme-section': 'onSort',
'click .theme-filter': 'onFilter',
'click .more-filters': 'moreFilters',
'click .apply-filters': 'applyFilters',
'click [type="checkbox"]': 'addFilter',
'click .clear-filters': 'clearFilters',
'click .feature-name': 'filterSection',
'click .filtering-by a': 'backToFilters'
},
// Initial render method
render: function() {
var self = this;
this.search();
this.uploader();
this.collection = new themes.Collection();
// Bump `collection.currentQuery.page` and request more themes if we hit the end of the page.
this.listenTo( this, 'theme:end', function() {
// Make sure we are not already loading
if ( self.collection.loadingThemes ) {
return;
}
// Set loadingThemes to true and bump page instance of currentQuery.
self.collection.loadingThemes = true;
self.collection.currentQuery.page++;
// Use currentQuery.page to build the themes request.
_.extend( self.collection.currentQuery.request, { page: self.collection.currentQuery.page } );
self.collection.query( self.collection.currentQuery.request );
});
this.listenTo( this.collection, 'query:success', function() {
$( 'body' ).removeClass( 'loading-themes' );
$( '.theme-browser' ).find( 'div.error' ).remove();
});
this.listenTo( this.collection, 'query:fail', function() {
$( 'body' ).removeClass( 'loading-themes' );
$( '.theme-browser' ).find( 'div.error' ).remove();
$( '.theme-browser' ).find( 'div.themes' ).before( '<div class="error"><p>' + l10n.error + '</p></div>' );
});
if ( this.view ) {
this.view.remove();
}
// Set ups the view and passes the section argument
this.view = new themes.view.Themes({
collection: this.collection,
parent: this
});
// Reset pagination every time the install view handler is run
this.page = 0;
// Render and append
this.$el.find( '.themes' ).remove();
this.view.render();
this.$el.find( '.theme-browser' ).append( this.view.el ).addClass( 'rendered' );
},
// Handles all the rendering of the public theme directory
browse: function( section ) {
// Create a new collection with the proper theme data
// for each section
this.collection.query( { browse: section } );
},
// Sorting navigation
onSort: function( event ) {
var $el = $( event.target ),
sort = $el.data( 'sort' );
event.preventDefault();
$( 'body' ).removeClass( 'filters-applied more-filters-opened' );
// Bail if this is already active
if ( $el.hasClass( this.activeClass ) ) {
return;
}
this.sort( sort );
// Trigger a router.naviagte update
themes.router.navigate( themes.router.baseUrl( '?browse=' + sort ) );
},
sort: function( sort ) {
this.clearSearch();
$( '.theme-section, .theme-filter' ).removeClass( this.activeClass );
$( '[data-sort="' + sort + '"]' ).addClass( this.activeClass );
this.browse( sort );
},
// Filters and Tags
onFilter: function( event ) {
var request,
$el = $( event.target ),
filter = $el.data( 'filter' );
// Bail if this is already active
if ( $el.hasClass( this.activeClass ) ) {
return;
}
$( '.theme-filter, .theme-section' ).removeClass( this.activeClass );
$el.addClass( this.activeClass );
if ( ! filter ) {
return;
}
// Construct the filter request
// using the default values
filter = _.union( filter, this.filtersChecked() );
request = { tag: [ filter ] };
// Get the themes by sending Ajax POST request to api.wordpress.org/themes
// or searching the local cache
this.collection.query( request );
},
// Clicking on a checkbox to add another filter to the request
addFilter: function() {
this.filtersChecked();
},
// Applying filters triggers a tag request
applyFilters: function( event ) {
var name,
tags = this.filtersChecked(),
request = { tag: tags },
filteringBy = $( '.filtering-by .tags' );
if ( event ) {
event.preventDefault();
}
$( 'body' ).addClass( 'filters-applied' );
$( '.theme-section.current' ).removeClass( 'current' );
filteringBy.empty();
_.each( tags, function( tag ) {
name = $( 'label[for="feature-id-' + tag + '"]' ).text();
filteringBy.append( '<span class="tag">' + name + '</span>' );
});
// Get the themes by sending Ajax POST request to api.wordpress.org/themes
// or searching the local cache
this.collection.query( request );
},
// Get the checked filters
// @return {array} of tags or false
filtersChecked: function() {
var items = $( '.feature-group' ).find( ':checkbox' ),
tags = [];
_.each( items.filter( ':checked' ), function( item ) {
tags.push( $( item ).prop( 'value' ) );
});
// When no filters are checked, restore initial state and return
if ( tags.length === 0 ) {
$( '.apply-filters' ).find( 'span' ).text( '' );
$( '.clear-filters' ).hide();
$( 'body' ).removeClass( 'filters-applied' );
return false;
}
$( '.apply-filters' ).find( 'span' ).text( tags.length );
$( '.clear-filters' ).css( 'display', 'inline-block' );
return tags;
},
activeClass: 'current',
// Overwrite search container class to append search
// in new location
searchContainer: $( '.theme-navigation' ),
uploader: function() {
$( 'a.upload' ).on( 'click', function( event ) {
event.preventDefault();
$( 'body' ).addClass( 'show-upload-theme' );
themes.router.navigate( themes.router.baseUrl( '?upload' ), { replace: true } );
});
$( 'a.browse-themes' ).on( 'click', function( event ) {
event.preventDefault();
$( 'body' ).removeClass( 'show-upload-theme' );
themes.router.navigate( themes.router.baseUrl( '' ), { replace: true } );
});
},
// Toggle the full filters navigation
moreFilters: function( event ) {
event.preventDefault();
if ( $( 'body' ).hasClass( 'filters-applied' ) ) {
return this.backToFilters();
}
// If the filters section is opened and filters are checked
// run the relevant query collapsing to filtered-by state
if ( $( 'body' ).hasClass( 'more-filters-opened' ) && this.filtersChecked() ) {
return this.addFilter();
}
this.clearSearch();
themes.router.navigate( themes.router.baseUrl( '' ) );
$( 'body' ).toggleClass( 'more-filters-opened' );
},
// Expand/collapse each individual filter section
filterSection: function() {
$( event.target ).parent().toggleClass( 'open' );
},
// Clears all the checked filters
// @uses filtersChecked()
clearFilters: function( event ) {
var items = $( '.feature-group' ).find( ':checkbox' ),
self = this;
event.preventDefault();
_.each( items.filter( ':checked' ), function( item ) {
$( item ).prop( 'checked', false );
return self.filtersChecked();
});
},
backToFilters: function( event ) {
if ( event ) {
event.preventDefault();
}
$( 'body' ).removeClass( 'filters-applied' );
},
clearSearch: function() {
$( '#theme-search-input').val( '' );
}
});
themes.InstallerRouter = Backbone.Router.extend({
routes: {
'theme-install.php?theme=:slug': 'preview',
'theme-install.php?browse=:sort': 'sort',
'theme-install.php?upload': 'upload',
'theme-install.php?search=:query': 'search',
'theme-install.php': 'sort'
},
baseUrl: function( url ) {
return 'theme-install.php' + url;
},
search: function( query ) {
$( '.theme-search' ).val( query );
},
navigate: function() {
if ( Backbone.history._hasPushState ) {
Backbone.Router.prototype.navigate.apply( this, arguments );
}
}
});
themes.RunInstaller = {
init: function() {
// Set up the view
// Passes the default 'section' as an option
this.view = new themes.view.Installer({
section: 'featured',
SearchView: themes.view.InstallerSearch
});
// Render results
this.render();
},
render: function() {
// Render results
this.view.render();
this.routes();
Backbone.history.start({
root: themes.data.settings.adminUrl,
pushState: true,
hashChange: false
});
},
routes: function() {
var self = this,
request = {};
// Bind to our global `wp.themes` object
// so that the router is available to sub-views
themes.router = new themes.InstallerRouter();
// Handles `theme` route event
// Queries the API for the passed theme slug
themes.router.on( 'route:preview', function( slug ) {
request.theme = slug;
self.view.collection.query( request );
});
// Handles sorting / browsing routes
// Also handles the root URL triggering a sort request
// for `featured`, the default view
themes.router.on( 'route:sort', function( sort ) {
if ( ! sort ) {
sort = 'featured';
}
self.view.sort( sort );
self.view.trigger( 'theme:close' );
});
// Support the `upload` route by going straight to upload section
themes.router.on( 'route:upload', function() {
$( 'a.upload' ).trigger( 'click' );
});
// The `search` route event. The router populates the input field.
themes.router.on( 'route:search', function() {
$( '.theme-search' ).focus().trigger( 'keyup' );
});
this.extraRoutes();
},
extraRoutes: function() {
return false;
}
};
// Ready...
$( document ).ready(function() {
if ( themes.isInstall ) {
themes.RunInstaller.init();
} else {
themes.Run.init();
}
});
})( jQuery );
// Align theme browser thickbox
var tb_position;
jQuery(document).ready( function($) {
tb_position = function() {
var tbWindow = $('#TB_window'),
width = $(window).width(),
H = $(window).height(),
W = ( 1040 < width ) ? 1040 : width,
adminbar_height = 0;
if ( $('#wpadminbar').length ) {
adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
}
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
if ( typeof document.body.style.maxWidth !== 'undefined' ) {
tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
}
}
};
$(window).resize(function(){ tb_position(); });
});
| 01-wordpress-paypal | trunk/wp-admin/js/theme.js | JavaScript | gpl3 | 43,871 |
/* global ajaxurl, wpAjax, tagsl10n, showNotice, validateForm */
jQuery(document).ready(function($) {
$( '#the-list' ).on( 'click', '.delete-tag', function() {
var t = $(this), tr = t.parents('tr'), r = true, data;
if ( 'undefined' != showNotice )
r = showNotice.warn();
if ( r ) {
data = t.attr('href').replace(/[^?]*\?/, '').replace(/action=delete/, 'action=delete-tag');
$.post(ajaxurl, data, function(r){
if ( '1' == r ) {
$('#ajax-response').empty();
tr.fadeOut('normal', function(){ tr.remove(); });
// Remove the term from the parent box and tag cloud
$('select#parent option[value="' + data.match(/tag_ID=(\d+)/)[1] + '"]').remove();
$('a.tag-link-' + data.match(/tag_ID=(\d+)/)[1]).remove();
} else if ( '-1' == r ) {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.noPerm + '</p></div>');
tr.children().css('backgroundColor', '');
} else {
$('#ajax-response').empty().append('<div class="error"><p>' + tagsl10n.broken + '</p></div>');
tr.children().css('backgroundColor', '');
}
});
tr.children().css('backgroundColor', '#f33');
}
return false;
});
$('#submit').click(function(){
var form = $(this).parents('form');
if ( ! validateForm( form ) )
return false;
$.post(ajaxurl, $('#addtag').serialize(), function(r){
var res, parent, term, indent, i;
$('#ajax-response').empty();
res = wpAjax.parseAjaxResponse( r, 'ajax-response' );
if ( ! res || res.errors )
return;
parent = form.find( 'select#parent' ).val();
if ( parent > 0 && $('#tag-' + parent ).length > 0 ) // If the parent exists on this page, insert it below. Else insert it at the top of the list.
$( '.tags #tag-' + parent ).after( res.responses[0].supplemental.noparents ); // As the parent exists, Insert the version with - - - prefixed
else
$( '.tags' ).prepend( res.responses[0].supplemental.parents ); // As the parent is not visible, Insert the version with Parent - Child - ThisTerm
$('.tags .no-items').remove();
if ( form.find('select#parent') ) {
// Parents field exists, Add new term to the list.
term = res.responses[1].supplemental;
// Create an indent for the Parent field
indent = '';
for ( i = 0; i < res.responses[1].position; i++ )
indent += ' ';
form.find( 'select#parent option:selected' ).after( '<option value="' + term.term_id + '">' + indent + term.name + '</option>' );
}
$('input[type="text"]:visible, textarea:visible', form).val('');
});
return false;
});
});
| 01-wordpress-paypal | trunk/wp-admin/js/tags.js | JavaScript | gpl3 | 2,592 |
/* global tinymce, tinyMCEPreInit, QTags, setUserSetting */
window.switchEditors = {
switchto: function( el ) {
var aid = el.id,
l = aid.length,
id = aid.substr( 0, l - 5 ),
mode = aid.substr( l - 4 );
this.go( id, mode );
},
// mode can be 'html', 'tmce', or 'toggle'; 'html' is used for the 'Text' editor tab.
go: function( id, mode ) {
var t = this, ed, wrap_id, txtarea_el, iframe, editorHeight, toolbarHeight,
DOM = tinymce.DOM; //DOMUtils outside the editor iframe
id = id || 'content';
mode = mode || 'toggle';
ed = tinymce.get( id );
wrap_id = 'wp-' + id + '-wrap';
txtarea_el = DOM.get( id );
if ( 'toggle' === mode ) {
if ( ed && ! ed.isHidden() ) {
mode = 'html';
} else {
mode = 'tmce';
}
}
function getToolbarHeight() {
var node = DOM.select( '.mce-toolbar-grp', ed.getContainer() )[0],
height = node && node.clientHeight;
if ( height && height > 10 && height < 200 ) {
return parseInt( height, 10 );
}
return 30;
}
if ( 'tmce' === mode || 'tinymce' === mode ) {
if ( ed && ! ed.isHidden() ) {
return false;
}
if ( typeof( QTags ) !== 'undefined' ) {
QTags.closeAllTags( id );
}
editorHeight = txtarea_el ? parseInt( txtarea_el.style.height, 10 ) : 0;
if ( tinyMCEPreInit.mceInit[ id ] && tinyMCEPreInit.mceInit[ id ].wpautop ) {
txtarea_el.value = t.wpautop( txtarea_el.value );
}
if ( ed ) {
ed.show();
if ( editorHeight ) {
toolbarHeight = getToolbarHeight();
editorHeight = editorHeight - toolbarHeight + 14;
// height cannot be under 50 or over 5000
if ( editorHeight > 50 && editorHeight < 5000 ) {
ed.theme.resizeTo( null, editorHeight );
}
}
} else {
tinymce.init( tinyMCEPreInit.mceInit[id] );
}
DOM.removeClass( wrap_id, 'html-active' );
DOM.addClass( wrap_id, 'tmce-active' );
setUserSetting( 'editor', 'tinymce' );
} else if ( 'html' === mode ) {
if ( ed && ed.isHidden() ) {
return false;
}
if ( ed ) {
iframe = DOM.get( id + '_ifr' );
editorHeight = iframe ? parseInt( iframe.style.height, 10 ) : 0;
if ( editorHeight ) {
toolbarHeight = getToolbarHeight();
editorHeight = editorHeight + toolbarHeight - 14;
// height cannot be under 50 or over 5000
if ( editorHeight > 50 && editorHeight < 5000 ) {
txtarea_el.style.height = editorHeight + 'px';
}
}
ed.hide();
} else {
// The TinyMCE instance doesn't exist, run the content through 'pre_wpautop()' and show the textarea
if ( tinyMCEPreInit.mceInit[ id ] && tinyMCEPreInit.mceInit[ id ].wpautop ) {
txtarea_el.value = t.pre_wpautop( txtarea_el.value );
}
DOM.setStyles( txtarea_el, {'display': '', 'visibility': ''} );
}
DOM.removeClass( wrap_id, 'tmce-active' );
DOM.addClass( wrap_id, 'html-active' );
setUserSetting( 'editor', 'html' );
}
return false;
},
_wp_Nop: function( content ) {
var blocklist1, blocklist2,
preserve_linebreaks = false,
preserve_br = false;
// Protect pre|script tags
if ( content.indexOf( '<pre' ) !== -1 || content.indexOf( '<script' ) !== -1 ) {
preserve_linebreaks = true;
content = content.replace( /<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function( a ) {
a = a.replace( /<br ?\/?>(\r\n|\n)?/g, '<wp-line-break>' );
a = a.replace( /<\/?p( [^>]*)?>(\r\n|\n)?/g, '<wp-line-break>' );
return a.replace( /\r?\n/g, '<wp-line-break>' );
});
}
// keep <br> tags inside captions and remove line breaks
if ( content.indexOf( '[caption' ) !== -1 ) {
preserve_br = true;
content = content.replace( /\[caption[\s\S]+?\[\/caption\]/g, function( a ) {
return a.replace( /<br([^>]*)>/g, '<wp-temp-br$1>' ).replace( /[\r\n\t]+/, '' );
});
}
// Pretty it up for the source editor
blocklist1 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|div|h[1-6]|p|fieldset';
content = content.replace( new RegExp( '\\s*</(' + blocklist1 + ')>\\s*', 'g' ), '</$1>\n' );
content = content.replace( new RegExp( '\\s*<((?:' + blocklist1 + ')(?: [^>]*)?)>', 'g' ), '\n<$1>' );
// Mark </p> if it has any attributes.
content = content.replace( /(<p [^>]+>.*?)<\/p>/g, '$1</p#>' );
// Separate <div> containing <p>
content = content.replace( /<div( [^>]*)?>\s*<p>/gi, '<div$1>\n\n' );
// Remove <p> and <br />
content = content.replace( /\s*<p>/gi, '' );
content = content.replace( /\s*<\/p>\s*/gi, '\n\n' );
content = content.replace( /\n[\s\u00a0]+\n/g, '\n\n' );
content = content.replace( /\s*<br ?\/?>\s*/gi, '\n' );
// Fix some block element newline issues
content = content.replace( /\s*<div/g, '\n<div' );
content = content.replace( /<\/div>\s*/g, '</div>\n' );
content = content.replace( /\s*\[caption([^\[]+)\[\/caption\]\s*/gi, '\n\n[caption$1[/caption]\n\n' );
content = content.replace( /caption\]\n\n+\[caption/g, 'caption]\n\n[caption' );
blocklist2 = 'blockquote|ul|ol|li|table|thead|tbody|tfoot|tr|th|td|h[1-6]|pre|fieldset';
content = content.replace( new RegExp('\\s*<((?:' + blocklist2 + ')(?: [^>]*)?)\\s*>', 'g' ), '\n<$1>' );
content = content.replace( new RegExp('\\s*</(' + blocklist2 + ')>\\s*', 'g' ), '</$1>\n' );
content = content.replace( /<li([^>]*)>/g, '\t<li$1>' );
if ( content.indexOf( '<hr' ) !== -1 ) {
content = content.replace( /\s*<hr( [^>]*)?>\s*/g, '\n\n<hr$1>\n\n' );
}
if ( content.indexOf( '<object' ) !== -1 ) {
content = content.replace( /<object[\s\S]+?<\/object>/g, function( a ) {
return a.replace( /[\r\n]+/g, '' );
});
}
// Unmark special paragraph closing tags
content = content.replace( /<\/p#>/g, '</p>\n' );
content = content.replace( /\s*(<p [^>]+>[\s\S]*?<\/p>)/g, '\n$1' );
// Trim whitespace
content = content.replace( /^\s+/, '' );
content = content.replace( /[\s\u00a0]+$/, '' );
// put back the line breaks in pre|script
if ( preserve_linebreaks ) {
content = content.replace( /<wp-line-break>/g, '\n' );
}
// and the <br> tags in captions
if ( preserve_br ) {
content = content.replace( /<wp-temp-br([^>]*)>/g, '<br$1>' );
}
return content;
},
_wp_Autop: function(pee) {
var preserve_linebreaks = false,
preserve_br = false,
blocklist = 'table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre' +
'|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|legend|section' +
'|article|aside|hgroup|header|footer|nav|figure|details|menu|summary';
if ( pee.indexOf( '<object' ) !== -1 ) {
pee = pee.replace( /<object[\s\S]+?<\/object>/g, function( a ) {
return a.replace( /[\r\n]+/g, '' );
});
}
pee = pee.replace( /<[^<>]+>/g, function( a ){
return a.replace( /[\r\n]+/g, ' ' );
});
// Protect pre|script tags
if ( pee.indexOf( '<pre' ) !== -1 || pee.indexOf( '<script' ) !== -1 ) {
preserve_linebreaks = true;
pee = pee.replace( /<(pre|script)[^>]*>[\s\S]+?<\/\1>/g, function( a ) {
return a.replace( /(\r\n|\n)/g, '<wp-line-break>' );
});
}
// keep <br> tags inside captions and convert line breaks
if ( pee.indexOf( '[caption' ) !== -1 ) {
preserve_br = true;
pee = pee.replace( /\[caption[\s\S]+?\[\/caption\]/g, function( a ) {
// keep existing <br>
a = a.replace( /<br([^>]*)>/g, '<wp-temp-br$1>' );
// no line breaks inside HTML tags
a = a.replace( /<[a-zA-Z0-9]+( [^<>]+)?>/g, function( b ) {
return b.replace( /[\r\n\t]+/, ' ' );
});
// convert remaining line breaks to <br>
return a.replace( /\s*\n\s*/g, '<wp-temp-br />' );
});
}
pee = pee + '\n\n';
pee = pee.replace( /<br \/>\s*<br \/>/gi, '\n\n' );
pee = pee.replace( new RegExp( '(<(?:' + blocklist + ')(?: [^>]*)?>)', 'gi' ), '\n$1' );
pee = pee.replace( new RegExp( '(</(?:' + blocklist + ')>)', 'gi' ), '$1\n\n' );
pee = pee.replace( /<hr( [^>]*)?>/gi, '<hr$1>\n\n' ); // hr is self closing block element
pee = pee.replace( /\r\n|\r/g, '\n' );
pee = pee.replace( /\n\s*\n+/g, '\n\n' );
pee = pee.replace( /([\s\S]+?)\n\n/g, '<p>$1</p>\n' );
pee = pee.replace( /<p>\s*?<\/p>/gi, '');
pee = pee.replace( new RegExp( '<p>\\s*(</?(?:' + blocklist + ')(?: [^>]*)?>)\\s*</p>', 'gi' ), '$1' );
pee = pee.replace( /<p>(<li.+?)<\/p>/gi, '$1');
pee = pee.replace( /<p>\s*<blockquote([^>]*)>/gi, '<blockquote$1><p>');
pee = pee.replace( /<\/blockquote>\s*<\/p>/gi, '</p></blockquote>');
pee = pee.replace( new RegExp( '<p>\\s*(</?(?:' + blocklist + ')(?: [^>]*)?>)', 'gi' ), '$1' );
pee = pee.replace( new RegExp( '(</?(?:' + blocklist + ')(?: [^>]*)?>)\\s*</p>', 'gi' ), '$1' );
pee = pee.replace( /\s*\n/gi, '<br />\n');
pee = pee.replace( new RegExp( '(</?(?:' + blocklist + ')[^>]*>)\\s*<br />', 'gi' ), '$1' );
pee = pee.replace( /<br \/>(\s*<\/?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)>)/gi, '$1' );
pee = pee.replace( /(?:<p>|<br ?\/?>)*\s*\[caption([^\[]+)\[\/caption\]\s*(?:<\/p>|<br ?\/?>)*/gi, '[caption$1[/caption]' );
pee = pee.replace( /(<(?:div|th|td|form|fieldset|dd)[^>]*>)(.*?)<\/p>/g, function( a, b, c ) {
if ( c.match( /<p( [^>]*)?>/ ) ) {
return a;
}
return b + '<p>' + c + '</p>';
});
// put back the line breaks in pre|script
if ( preserve_linebreaks ) {
pee = pee.replace( /<wp-line-break>/g, '\n' );
}
if ( preserve_br ) {
pee = pee.replace( /<wp-temp-br([^>]*)>/g, '<br$1>' );
}
return pee;
},
pre_wpautop: function( content ) {
var t = this, o = { o: t, data: content, unfiltered: content },
q = typeof( jQuery ) !== 'undefined';
if ( q ) {
jQuery( 'body' ).trigger( 'beforePreWpautop', [ o ] );
}
o.data = t._wp_Nop( o.data );
if ( q ) {
jQuery('body').trigger('afterPreWpautop', [ o ] );
}
return o.data;
},
wpautop: function( pee ) {
var t = this, o = { o: t, data: pee, unfiltered: pee },
q = typeof( jQuery ) !== 'undefined';
if ( q ) {
jQuery( 'body' ).trigger('beforeWpautop', [ o ] );
}
o.data = t._wp_Autop( o.data );
if ( q ) {
jQuery( 'body' ).trigger('afterWpautop', [ o ] );
}
return o.data;
}
};
| 01-wordpress-paypal | trunk/wp-admin/js/editor.js | JavaScript | gpl3 | 10,103 |
/* global adminCommentsL10n, thousandsSeparator, list_args, QTags, ajaxurl, wpAjax */
var setCommentsList, theList, theExtraList, commentReply;
(function($) {
var getCount, updateCount, updatePending;
setCommentsList = function() {
var totalInput, perPageInput, pageInput, dimAfter, delBefore, updateTotalCount, delAfter, refillTheExtraList, diff,
lastConfidentTime = 0;
totalInput = $('input[name="_total"]', '#comments-form');
perPageInput = $('input[name="_per_page"]', '#comments-form');
pageInput = $('input[name="_page"]', '#comments-form');
dimAfter = function( r, settings ) {
var editRow, replyID, replyButton,
c = $( '#' + settings.element );
editRow = $('#replyrow');
replyID = $('#comment_ID', editRow).val();
replyButton = $('#replybtn', editRow);
if ( c.is('.unapproved') ) {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.replyApprove);
c.find('div.comment_status').html('0');
} else {
if ( settings.data.id == replyID )
replyButton.text(adminCommentsL10n.reply);
c.find('div.comment_status').html('1');
}
diff = $('#' + settings.element).is('.' + settings.dimClass) ? 1 : -1;
updatePending( diff );
};
// Send current total, page, per_page and url
delBefore = function( settings, list ) {
var note, id, el, n, h, a, author,
action = false,
wpListsData = $( settings.target ).attr( 'data-wp-lists' );
settings.data._total = totalInput.val() || 0;
settings.data._per_page = perPageInput.val() || 0;
settings.data._page = pageInput.val() || 0;
settings.data._url = document.location.href;
settings.data.comment_status = $('input[name="comment_status"]', '#comments-form').val();
if ( wpListsData.indexOf(':trash=1') != -1 )
action = 'trash';
else if ( wpListsData.indexOf(':spam=1') != -1 )
action = 'spam';
if ( action ) {
id = wpListsData.replace(/.*?comment-([0-9]+).*/, '$1');
el = $('#comment-' + id);
note = $('#' + action + '-undo-holder').html();
el.find('.check-column :checkbox').prop('checked', false); // Uncheck the row so as not to be affected by Bulk Edits.
if ( el.siblings('#replyrow').length && commentReply.cid == id )
commentReply.close();
if ( el.is('tr') ) {
n = el.children(':visible').length;
author = $('.author strong', el).text();
h = $('<tr id="undo-' + id + '" class="undo un' + action + '" style="display:none;"><td colspan="' + n + '">' + note + '</td></tr>');
} else {
author = $('.comment-author', el).text();
h = $('<div id="undo-' + id + '" style="display:none;" class="undo un' + action + '">' + note + '</div>');
}
el.before(h);
$('strong', '#undo-' + id).text(author);
a = $('.undo a', '#undo-' + id);
a.attr('href', 'comment.php?action=un' + action + 'comment&c=' + id + '&_wpnonce=' + settings.data._ajax_nonce);
a.attr('data-wp-lists', 'delete:the-comment-list:comment-' + id + '::un' + action + '=1');
a.attr('class', 'vim-z vim-destructive');
$('.avatar', el).first().clone().prependTo('#undo-' + id + ' .' + action + '-undo-inside');
a.click(function(){
list.wpList.del(this);
$('#undo-' + id).css( {backgroundColor:'#ceb'} ).fadeOut(350, function(){
$(this).remove();
$('#comment-' + id).css('backgroundColor', '').fadeIn(300, function(){ $(this).show(); });
});
return false;
});
}
return settings;
};
// Updates the current total (stored in the _total input)
updateTotalCount = function( total, time, setConfidentTime ) {
if ( time < lastConfidentTime )
return;
if ( setConfidentTime )
lastConfidentTime = time;
totalInput.val( total.toString() );
};
getCount = function(el) {
var n = parseInt( el.html().replace(/[^0-9]+/g, ''), 10 );
if ( isNaN(n) )
return 0;
return n;
};
updateCount = function(el, n) {
var n1 = '';
if ( isNaN(n) )
return;
n = n < 1 ? '0' : n.toString();
if ( n.length > 3 ) {
while ( n.length > 3 ) {
n1 = thousandsSeparator + n.substr(n.length - 3) + n1;
n = n.substr(0, n.length - 3);
}
n = n + n1;
}
el.html(n);
};
updatePending = function( diff ) {
$('span.pending-count').each(function() {
var a = $(this), n = getCount(a) + diff;
if ( n < 1 )
n = 0;
a.closest('.awaiting-mod')[ 0 === n ? 'addClass' : 'removeClass' ]('count-0');
updateCount( a, n );
});
};
// In admin-ajax.php, we send back the unix time stamp instead of 1 on success
delAfter = function( r, settings ) {
var total_items_i18n, total, spam, trash, pending,
untrash = $(settings.target).parent().is('span.untrash'),
unspam = $(settings.target).parent().is('span.unspam'),
unapproved = $('#' + settings.element).is('.unapproved');
function getUpdate(s) {
if ( $(settings.target).parent().is('span.' + s) )
return 1;
else if ( $('#' + settings.element).is('.' + s) )
return -1;
return 0;
}
if ( untrash )
trash = -1;
else
trash = getUpdate('trash');
if ( unspam )
spam = -1;
else
spam = getUpdate('spam');
if ( $(settings.target).parent().is('span.unapprove') || ( ( untrash || unspam ) && unapproved ) ) {
// a comment was 'deleted' from another list (e.g. approved, spam, trash) and moved to pending,
// or a trash/spam of a pending comment was undone
pending = 1;
} else if ( unapproved ) {
// a pending comment was trashed/spammed/approved
pending = -1;
}
if ( pending )
updatePending(pending);
$('span.spam-count').each( function() {
var a = $(this), n = getCount(a) + spam;
updateCount(a, n);
});
$('span.trash-count').each( function() {
var a = $(this), n = getCount(a) + trash;
updateCount(a, n);
});
if ( ! $('#dashboard_right_now').length ) {
total = totalInput.val() ? parseInt( totalInput.val(), 10 ) : 0;
if ( $(settings.target).parent().is('span.undo') )
total++;
else
total--;
if ( total < 0 )
total = 0;
if ( ( 'object' == typeof r ) && lastConfidentTime < settings.parsed.responses[0].supplemental.time ) {
total_items_i18n = settings.parsed.responses[0].supplemental.total_items_i18n || '';
if ( total_items_i18n ) {
$('.displaying-num').text( total_items_i18n );
$('.total-pages').text( settings.parsed.responses[0].supplemental.total_pages_i18n );
$('.tablenav-pages').find('.next-page, .last-page').toggleClass('disabled', settings.parsed.responses[0].supplemental.total_pages == $('.current-page').val());
}
updateTotalCount( total, settings.parsed.responses[0].supplemental.time, true );
} else {
updateTotalCount( total, r, false );
}
}
if ( ! theExtraList || theExtraList.size() === 0 || theExtraList.children().size() === 0 || untrash || unspam ) {
return;
}
theList.get(0).wpList.add( theExtraList.children(':eq(0)').remove().clone() );
refillTheExtraList();
};
refillTheExtraList = function(ev) {
var args = $.query.get(), total_pages = $('.total-pages').text(), per_page = $('input[name="_per_page"]', '#comments-form').val();
if (! args.paged)
args.paged = 1;
if (args.paged > total_pages) {
return;
}
if (ev) {
theExtraList.empty();
args.number = Math.min(8, per_page); // see WP_Comments_List_Table::prepare_items() @ class-wp-comments-list-table.php
} else {
args.number = 1;
args.offset = Math.min(8, per_page) - 1; // fetch only the next item on the extra list
}
args.no_placeholder = true;
args.paged ++;
// $.query.get() needs some correction to be sent into an ajax request
if ( true === args.comment_type )
args.comment_type = '';
args = $.extend(args, {
'action': 'fetch-list',
'list_args': list_args,
'_ajax_fetch_list_nonce': $('#_ajax_fetch_list_nonce').val()
});
$.ajax({
url: ajaxurl,
global: false,
dataType: 'json',
data: args,
success: function(response) {
theExtraList.get(0).wpList.add( response.rows );
}
});
};
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' } )
.bind('wpListDelEnd', function(e, s){
var wpListsData = $(s.target).attr('data-wp-lists'), id = s.element.replace(/[^0-9]+/g, '');
if ( wpListsData.indexOf(':trash=1') != -1 || wpListsData.indexOf(':spam=1') != -1 )
$('#undo-' + id).fadeIn(300, function(){ $(this).show(); });
});
};
commentReply = {
cid : '',
act : '',
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(){
if ( $('#the-comment-list #replyrow').length > 0 )
commentReply.close();
});
this.comments_listing = $('#comments-form > input[name="comment_status"]').val() || '';
/* $(listTable).bind('beforeChangePage', function(){
commentReply.close();
}); */
},
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() {
var c, replyrow = $('#replyrow');
// replyrow is not showing?
if ( replyrow.parent().is('#com-reply') )
return;
if ( this.cid && this.act == 'edit-comment' ) {
c = $('#comment-' + this.cid);
c.fadeIn(300, function(){ c.show(); }).css('backgroundColor', '');
}
// reset the Quicktags buttons
if ( typeof QTags != 'undefined' )
QTags.closeAllTags('replycontent');
$('#add-new-comment').css('display', '');
replyrow.hide();
$('#com-reply').append( replyrow );
$('#replycontent').css('height', '').val('');
$('#edithead input').val('');
$('.error', replyrow).html('').hide();
$('.spinner', replyrow).hide();
this.cid = '';
},
open : function(comment_id, post_id, action) {
var editRow, rowData, act, replyButton, editHeight,
t = this,
c = $('#comment-' + comment_id),
h = c.height();
t.close();
t.cid = comment_id;
editRow = $('#replyrow');
rowData = $('#inline-'+comment_id);
action = action || 'replyto';
act = 'edit' == action ? 'edit' : 'replyto';
act = t.act = act + '-comment';
$('#action', editRow).val(act);
$('#comment_post_ID', editRow).val(post_id);
$('#comment_ID', editRow).val(comment_id);
if ( action == '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, #addhead, #addbtn', editRow).hide();
if ( h > 120 ) {
// Limit the maximum height when editing very long comments to make it more manageable.
// The textarea is resizable in most browsers, so the user can adjust it if needed.
editHeight = h > 500 ? 500 : h;
$('#replycontent', editRow).css('height', editHeight + 'px');
}
c.after( editRow ).fadeOut('fast', function(){
$('#replyrow').fadeIn(300, function(){ $(this).show(); });
});
} else if ( action == 'add' ) {
$('#addhead, #addbtn', editRow).show();
$('#replyhead, #replybtn, #edithead, #editbtn', editRow).hide();
$('#the-comment-list').prepend(editRow);
$('#replyrow').fadeIn(300);
} else {
replyButton = $('#replybtn', editRow);
$('#edithead, #savebtn, #addhead, #addbtn', editRow).hide();
$('#replyhead, #replybtn', editRow).show();
c.after(editRow);
if ( c.hasClass('unapproved') ) {
replyButton.text(adminCommentsL10n.replyApprove);
} else {
replyButton.text(adminCommentsL10n.reply);
}
$('#replyrow').fadeIn(300, function(){ $(this).show(); });
}
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 || window.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 .error').hide();
$('#replysubmit .spinner').show();
$('#replyrow input').not(':button').each(function() {
var t = $(this);
post[ t.attr('name') ] = t.val();
});
post.content = $('#replycontent').val();
post.id = post.comment_post_ID;
post.comments_listing = this.comments_listing;
post.p = $('[name="p"]').val();
if ( $('#comment-' + $('#comment_ID').val()).hasClass('unapproved') )
post.approve_parent = 1;
$.ajax({
type : 'POST',
url : ajaxurl,
data : post,
success : function(x) { commentReply.show(x); },
error : function(r) { commentReply.error(r); }
});
return false;
},
show : function(xml) {
var t = this, r, c, id, bg, pid;
if ( typeof(xml) == 'string' ) {
t.error({'responseText': xml});
return false;
}
r = wpAjax.parseAjaxResponse(xml);
if ( r.errors ) {
t.error({'responseText': wpAjax.broken});
return false;
}
t.revert();
r = r.responses[0];
id = '#comment-' + r.id;
if ( 'edit-comment' == t.act )
$(id).remove();
if ( r.supplemental.parent_approved ) {
pid = $('#comment-' + r.supplemental.parent_approved);
updatePending( -1 );
if ( this.comments_listing == 'moderated' ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 400, function(){
pid.fadeOut();
});
return;
}
}
c = $.trim(r.data); // Trim leading whitespaces
$(c).hide();
$('#replyrow').after(c);
id = $(id);
t.addEvents(id);
bg = id.hasClass('unapproved') ? '#FFFFE0' : id.closest('.widefat, .postbox').css('backgroundColor');
id.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300, function() {
if ( pid && pid.length ) {
pid.animate( { 'backgroundColor':'#CCEEBB' }, 300 )
.animate( { 'backgroundColor': bg }, 300 )
.removeClass('unapproved').addClass('approved')
.find('div.comment_status').html('1');
}
});
},
error : function(r) {
var er = r.statusText;
$('#replysubmit .spinner').hide();
if ( r.responseText )
er = r.responseText.replace( /<.[^<>]*?>/g, '' );
if ( er )
$('#replysubmit .error').html(er).show();
},
addcomment: function(post_id) {
var t = this;
$('#add-new-comment').fadeOut(200, function(){
t.open(0, post_id, 'add');
$('table.comments-box').css('display', '');
$('#no-comments').remove();
});
}
};
$(document).ready(function(){
var make_hotkeys_redirect, edit_comment, toggle_all, make_bulk;
setCommentsList();
commentReply.init();
$(document).delegate('span.delete a.delete', 'click', function(){return false;});
if ( typeof $.table_hotkeys != 'undefined' ) {
make_hotkeys_redirect = function(which) {
return function() {
var first_last, l;
first_last = 'next' == which? 'first' : 'last';
l = $('.tablenav-pages .'+which+'-page:not(.disabled)');
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() {
$('#cb-select-all-1').data( 'wp-toggle', 1 ).trigger( 'click' ).removeData( 'wp-toggle' );
};
make_bulk = function(value) {
return function() {
var scope = $('select[name="action"]');
$('option[value="' + value + '"]', scope).prop('selected', true);
$('#doaction').click();
};
};
$.table_hotkeys(
$('table.widefat'),
[
'a', 'u', 's', 'd', 'r', 'q', 'z',
['e', edit_comment],
['shift+x', toggle_all],
['shift+a', make_bulk('approve')],
['shift+s', make_bulk('spam')],
['shift+d', make_bulk('delete')],
['shift+t', make_bulk('trash')],
['shift+z', make_bulk('untrash')],
['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'),
hotkeys_opts: {
disableInInput: true,
type: 'keypress',
noDisable: '.check-column input[type="checkbox"]'
}
}
);
}
});
})(jQuery);
| 01-wordpress-paypal | trunk/wp-admin/js/edit-comments.js | JavaScript | gpl3 | 17,526 |
/**
* Attempt to re-color SVG icons used in the admin menu or the toolbar
*
*/
window.wp = window.wp || {};
wp.svgPainter = ( function( $, window, document, undefined ) {
'use strict';
var selector, base64, painter,
colorscheme = {},
elements = [];
$(document).ready( function() {
// detection for browser SVG capability
if ( document.implementation.hasFeature( 'http://www.w3.org/TR/SVG11/feature#Image', '1.1' ) ) {
$( document.body ).removeClass( 'no-svg' ).addClass( 'svg' );
wp.svgPainter.init();
}
});
/**
* Needed only for IE9
*
* Based on jquery.base64.js 0.0.3 - https://github.com/yckart/jquery.base64.js
*
* Based on: https://gist.github.com/Yaffle/1284012
*
* Copyright (c) 2012 Yannick Albert (http://yckart.com)
* Licensed under the MIT license
* http://www.opensource.org/licenses/mit-license.php
*/
base64 = ( function() {
var c,
b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',
a256 = '',
r64 = [256],
r256 = [256],
i = 0;
function init() {
while( i < 256 ) {
c = String.fromCharCode(i);
a256 += c;
r256[i] = i;
r64[i] = b64.indexOf(c);
++i;
}
}
function code( s, discard, alpha, beta, w1, w2 ) {
var tmp, length,
buffer = 0,
i = 0,
result = '',
bitsInBuffer = 0;
s = String(s);
length = s.length;
while( i < length ) {
c = s.charCodeAt(i);
c = c < 256 ? alpha[c] : -1;
buffer = ( buffer << w1 ) + c;
bitsInBuffer += w1;
while( bitsInBuffer >= w2 ) {
bitsInBuffer -= w2;
tmp = buffer >> bitsInBuffer;
result += beta.charAt(tmp);
buffer ^= tmp << bitsInBuffer;
}
++i;
}
if ( ! discard && bitsInBuffer > 0 ) {
result += beta.charAt( buffer << ( w2 - bitsInBuffer ) );
}
return result;
}
function btoa( plain ) {
if ( ! c ) {
init();
}
plain = code( plain, false, r256, b64, 8, 6 );
return plain + '===='.slice( ( plain.length % 4 ) || 4 );
}
function atob( coded ) {
var i;
if ( ! c ) {
init();
}
coded = coded.replace( /[^A-Za-z0-9\+\/\=]/g, '' );
coded = String(coded).split('=');
i = coded.length;
do {
--i;
coded[i] = code( coded[i], true, r64, a256, 6, 8 );
} while ( i > 0 );
coded = coded.join('');
return coded;
}
return {
atob: atob,
btoa: btoa
};
})();
return {
init: function() {
painter = this;
selector = $( '#adminmenu .wp-menu-image, #wpadminbar .ab-item' );
this.setColors();
this.findElements();
this.paint();
},
setColors: function( colors ) {
if ( typeof colors === 'undefined' && typeof window._wpColorScheme !== 'undefined' ) {
colors = window._wpColorScheme;
}
if ( colors && colors.icons && colors.icons.base && colors.icons.current && colors.icons.focus ) {
colorscheme = colors.icons;
}
},
findElements: function() {
selector.each( function() {
var $this = $(this), bgImage = $this.css( 'background-image' );
if ( bgImage && bgImage.indexOf( 'data:image/svg+xml;base64' ) != -1 ) {
elements.push( $this );
}
});
},
paint: function() {
// loop through all elements
$.each( elements, function( index, $element ) {
var $menuitem = $element.parent().parent();
if ( $menuitem.hasClass( 'current' ) || $menuitem.hasClass( 'wp-has-current-submenu' ) ) {
// paint icon in 'current' color
painter.paintElement( $element, 'current' );
} else {
// paint icon in base color
painter.paintElement( $element, 'base' );
// set hover callbacks
$menuitem.hover(
function() {
painter.paintElement( $element, 'focus' );
},
function() {
// Match the delay from hoverIntent
window.setTimeout( function() {
painter.paintElement( $element, 'base' );
}, 100 );
}
);
}
});
},
paintElement: function( $element, colorType ) {
var xml, encoded, color;
if ( ! colorType || ! colorscheme.hasOwnProperty( colorType ) ) {
return;
}
color = colorscheme[ colorType ];
// only accept hex colors: #101 or #101010
if ( ! color.match( /^(#[0-9a-f]{3}|#[0-9a-f]{6})$/i ) ) {
return;
}
xml = $element.data( 'wp-ui-svg-' + color );
if ( xml === 'none' ) {
return;
}
if ( ! xml ) {
encoded = $element.css( 'background-image' ).match( /.+data:image\/svg\+xml;base64,([A-Za-z0-9\+\/\=]+)/ );
if ( ! encoded || ! encoded[1] ) {
$element.data( 'wp-ui-svg-' + color, 'none' );
return;
}
try {
if ( 'atob' in window ) {
xml = window.atob( encoded[1] );
} else {
xml = base64.atob( encoded[1] );
}
} catch ( error ) {}
if ( xml ) {
// replace `fill` attributes
xml = xml.replace( /fill="(.+?)"/g, 'fill="' + color + '"');
// replace `style` attributes
xml = xml.replace( /style="(.+?)"/g, 'style="fill:' + color + '"');
// replace `fill` properties in `<style>` tags
xml = xml.replace( /fill:.*?;/g, 'fill: ' + color + ';');
if ( 'btoa' in window ) {
xml = window.btoa( xml );
} else {
xml = base64.btoa( xml );
}
$element.data( 'wp-ui-svg-' + color, xml );
} else {
$element.data( 'wp-ui-svg-' + color, 'none' );
return;
}
}
$element.attr( 'style', 'background-image: url("data:image/svg+xml;base64,' + xml + '") !important;' );
}
};
})( jQuery, window, document );
| 01-wordpress-paypal | trunk/wp-admin/js/svg-painter.js | JavaScript | gpl3 | 5,484 |
jQuery( document ).ready(function( $ ) {
$( '#link_rel' ).prop( 'readonly', true );
$( '#linkxfndiv input' ).bind( 'click keyup', function() {
var isMe = $( '#me' ).is( ':checked' ), inputs = '';
$( 'input.valinp' ).each( function() {
if ( isMe ) {
$( this ).prop( 'disabled', true ).parent().addClass( 'disabled' );
} else {
$( this ).removeAttr( 'disabled' ).parent().removeClass( 'disabled' );
if ( $( this ).is( ':checked' ) && $( this ).val() !== '') {
inputs += $( this ).val() + ' ';
}
}
});
$( '#link_rel' ).val( ( isMe ) ? 'me' : inputs.substr( 0,inputs.length - 1 ) );
});
});
| 01-wordpress-paypal | trunk/wp-admin/js/xfn.js | JavaScript | gpl3 | 628 |
/* globals _wpCustomizeHeader, _wpMediaViewsL10n */
(function( exports, $ ){
var api = wp.customize;
/**
* @param options
* - previewer - The Previewer instance to sync with.
* - transport - The transport to use for previewing. Supports 'refresh' and 'postMessage'.
*/
api.Setting = api.Value.extend({
initialize: function( id, value, options ) {
api.Value.prototype.initialize.call( this, value, options );
this.id = id;
this.transport = this.transport || 'refresh';
this.bind( this.preview );
},
preview: function() {
switch ( this.transport ) {
case 'refresh':
return this.previewer.refresh();
case 'postMessage':
return this.previewer.send( 'setting', [ this.id, this() ] );
}
}
});
api.Control = api.Class.extend({
initialize: function( id, options ) {
var control = this,
nodes, radios, settings;
this.params = {};
$.extend( this, options || {} );
this.id = id;
this.selector = '#customize-control-' + id.replace( /\]/g, '' ).replace( /\[/g, '-' );
this.container = $( this.selector );
settings = $.map( this.params.settings, function( value ) {
return value;
});
api.apply( api, settings.concat( function() {
var key;
control.settings = {};
for ( key in control.params.settings ) {
control.settings[ key ] = api( control.params.settings[ key ] );
}
control.setting = control.settings['default'] || null;
control.ready();
}) );
control.elements = [];
nodes = this.container.find('[data-customize-setting-link]');
radios = {};
nodes.each( function() {
var node = $(this),
name;
if ( node.is(':radio') ) {
name = node.prop('name');
if ( radios[ name ] )
return;
radios[ name ] = true;
node = nodes.filter( '[name="' + name + '"]' );
}
api( node.data('customizeSettingLink'), function( setting ) {
var element = new api.Element( node );
control.elements.push( element );
element.sync( setting );
element.set( setting() );
});
});
},
ready: function() {},
dropdownInit: function() {
var control = this,
statuses = this.container.find('.dropdown-status'),
params = this.params,
toggleFreeze = false,
update = function( to ) {
if ( typeof to === 'string' && params.statuses && params.statuses[ to ] )
statuses.html( params.statuses[ to ] ).show();
else
statuses.hide();
};
// Support the .dropdown class to open/close complex elements
this.container.on( 'click keydown', '.dropdown', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
event.preventDefault();
if (!toggleFreeze)
control.container.toggleClass('open');
if ( control.container.hasClass('open') )
control.container.parent().parent().find('li.library-selected').focus();
// Don't want to fire focus and click at same time
toggleFreeze = true;
setTimeout(function () {
toggleFreeze = false;
}, 400);
});
this.setting.bind( update );
update( this.setting() );
}
});
api.ColorControl = api.Control.extend({
ready: function() {
var control = this,
picker = this.container.find('.color-picker-hex');
picker.val( control.setting() ).wpColorPicker({
change: function() {
control.setting.set( picker.wpColorPicker('color') );
},
clear: function() {
control.setting.set( false );
}
});
}
});
api.UploadControl = api.Control.extend({
ready: function() {
var control = this;
this.params.removed = this.params.removed || '';
this.success = $.proxy( this.success, this );
this.uploader = $.extend({
container: this.container,
browser: this.container.find('.upload'),
dropzone: this.container.find('.upload-dropzone'),
success: this.success,
plupload: {},
params: {}
}, this.uploader || {} );
if ( control.params.extensions ) {
control.uploader.plupload.filters = [{
title: api.l10n.allowedFiles,
extensions: control.params.extensions
}];
}
if ( control.params.context )
control.uploader.params['post_data[context]'] = this.params.context;
if ( api.settings.theme.stylesheet )
control.uploader.params['post_data[theme]'] = api.settings.theme.stylesheet;
this.uploader = new wp.Uploader( this.uploader );
this.remover = this.container.find('.remove');
this.remover.on( 'click keydown', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
control.setting.set( control.params.removed );
event.preventDefault();
});
this.removerVisibility = $.proxy( this.removerVisibility, this );
this.setting.bind( this.removerVisibility );
this.removerVisibility( this.setting.get() );
},
success: function( attachment ) {
this.setting.set( attachment.get('url') );
},
removerVisibility: function( to ) {
this.remover.toggle( to != this.params.removed );
}
});
api.ImageControl = api.UploadControl.extend({
ready: function() {
var control = this,
panels;
this.uploader = {
init: function() {
var fallback, button;
if ( this.supports.dragdrop )
return;
// Maintain references while wrapping the fallback button.
fallback = control.container.find( '.upload-fallback' );
button = fallback.children().detach();
this.browser.detach().empty().append( button );
fallback.append( this.browser ).show();
}
};
api.UploadControl.prototype.ready.call( this );
this.thumbnail = this.container.find('.preview-thumbnail img');
this.thumbnailSrc = $.proxy( this.thumbnailSrc, this );
this.setting.bind( this.thumbnailSrc );
this.library = this.container.find('.library');
// Generate tab objects
this.tabs = {};
panels = this.library.find('.library-content');
this.library.children('ul').children('li').each( function() {
var link = $(this),
id = link.data('customizeTab'),
panel = panels.filter('[data-customize-tab="' + id + '"]');
control.tabs[ id ] = {
both: link.add( panel ),
link: link,
panel: panel
};
});
// Bind tab switch events
this.library.children('ul').on( 'click keydown', 'li', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
var id = $(this).data('customizeTab'),
tab = control.tabs[ id ];
event.preventDefault();
if ( tab.link.hasClass('library-selected') )
return;
control.selected.both.removeClass('library-selected');
control.selected = tab;
control.selected.both.addClass('library-selected');
});
// Bind events to switch image urls.
this.library.on( 'click keydown', 'a', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
var value = $(this).data('customizeImageValue');
if ( value ) {
control.setting.set( value );
event.preventDefault();
}
});
if ( this.tabs.uploaded ) {
this.tabs.uploaded.target = this.library.find('.uploaded-target');
if ( ! this.tabs.uploaded.panel.find('.thumbnail').length )
this.tabs.uploaded.both.addClass('hidden');
}
// Select a tab
panels.each( function() {
var tab = control.tabs[ $(this).data('customizeTab') ];
// Select the first visible tab.
if ( ! tab.link.hasClass('hidden') ) {
control.selected = tab;
tab.both.addClass('library-selected');
return false;
}
});
this.dropdownInit();
},
success: function( attachment ) {
api.UploadControl.prototype.success.call( this, attachment );
// Add the uploaded image to the uploaded tab.
if ( this.tabs.uploaded && this.tabs.uploaded.target.length ) {
this.tabs.uploaded.both.removeClass('hidden');
// @todo: Do NOT store this on the attachment model. That is bad.
attachment.element = $( '<a href="#" class="thumbnail"></a>' )
.data( 'customizeImageValue', attachment.get('url') )
.append( '<img src="' + attachment.get('url')+ '" />' )
.appendTo( this.tabs.uploaded.target );
}
},
thumbnailSrc: function( to ) {
if ( /^(https?:)?\/\//.test( to ) )
this.thumbnail.prop( 'src', to ).show();
else
this.thumbnail.hide();
}
});
api.HeaderControl = api.Control.extend({
ready: function() {
this.btnRemove = $('.actions .remove');
this.btnNew = $('.actions .new');
_.bindAll(this, 'openMedia', 'removeImage');
this.btnNew.on( 'click', this.openMedia );
this.btnRemove.on( 'click', this.removeImage );
api.HeaderTool.currentHeader = new api.HeaderTool.ImageModel();
new api.HeaderTool.CurrentView({
model: api.HeaderTool.currentHeader,
el: '.current .container'
});
new api.HeaderTool.ChoiceListView({
collection: api.HeaderTool.UploadsList = new api.HeaderTool.ChoiceList(),
el: '.choices .uploaded .list'
});
new api.HeaderTool.ChoiceListView({
collection: api.HeaderTool.DefaultsList = new api.HeaderTool.DefaultsList(),
el: '.choices .default .list'
});
api.HeaderTool.combinedList = api.HeaderTool.CombinedList = new api.HeaderTool.CombinedList([
api.HeaderTool.UploadsList,
api.HeaderTool.DefaultsList
]);
},
/**
* Returns a set of options, computed from the attached image data and
* theme-specific data, to be fed to the imgAreaSelect plugin in
* wp.media.view.Cropper.
*
* @param {wp.media.model.Attachment} attachment
* @param {wp.media.controller.Cropper} controller
* @returns {Object} Options
*/
calculateImageSelectOptions: function(attachment, controller) {
var xInit = parseInt(_wpCustomizeHeader.data.width, 10),
yInit = parseInt(_wpCustomizeHeader.data.height, 10),
flexWidth = !! parseInt(_wpCustomizeHeader.data['flex-width'], 10),
flexHeight = !! parseInt(_wpCustomizeHeader.data['flex-height'], 10),
ratio, xImg, yImg, realHeight, realWidth,
imgSelectOptions;
realWidth = attachment.get('width');
realHeight = attachment.get('height');
this.headerImage = new api.HeaderTool.ImageModel();
this.headerImage.set({
themeWidth: xInit,
themeHeight: yInit,
themeFlexWidth: flexWidth,
themeFlexHeight: flexHeight,
imageWidth: realWidth,
imageHeight: realHeight
});
controller.set( 'canSkipCrop', ! this.headerImage.shouldBeCropped() );
ratio = xInit / yInit;
xImg = realWidth;
yImg = realHeight;
if ( xImg / yImg > ratio ) {
yInit = yImg;
xInit = yInit * ratio;
} else {
xInit = xImg;
yInit = xInit / ratio;
}
imgSelectOptions = {
handles: true,
keys: true,
instance: true,
persistent: true,
imageWidth: realWidth,
imageHeight: realHeight,
x1: 0,
y1: 0,
x2: xInit,
y2: yInit
};
if (flexHeight === false && flexWidth === false) {
imgSelectOptions.aspectRatio = xInit + ':' + yInit;
}
if (flexHeight === false ) {
imgSelectOptions.maxHeight = yInit;
}
if (flexWidth === false ) {
imgSelectOptions.maxWidth = xInit;
}
return imgSelectOptions;
},
/**
* Sets up and opens the Media Manager in order to select an image.
* Depending on both the size of the image and the properties of the
* current theme, a cropping step after selection may be required or
* skippable.
*
* @param {event} event
*/
openMedia: function(event) {
var l10n = _wpMediaViewsL10n;
event.preventDefault();
this.frame = wp.media({
button: {
text: l10n.selectAndCrop,
close: false
},
states: [
new wp.media.controller.Library({
title: l10n.chooseImage,
library: wp.media.query({ type: 'image' }),
multiple: false,
priority: 20,
suggestedWidth: _wpCustomizeHeader.data.width,
suggestedHeight: _wpCustomizeHeader.data.height
}),
new wp.media.controller.Cropper({
imgSelectOptions: this.calculateImageSelectOptions
})
]
});
this.frame.on('select', this.onSelect, this);
this.frame.on('cropped', this.onCropped, this);
this.frame.on('skippedcrop', this.onSkippedCrop, this);
this.frame.open();
},
onSelect: function() {
this.frame.setState('cropper');
},
onCropped: function(croppedImage) {
var url = croppedImage.post_content,
attachmentId = croppedImage.attachment_id,
w = croppedImage.width,
h = croppedImage.height;
this.setImageFromURL(url, attachmentId, w, h);
},
onSkippedCrop: function(selection) {
var url = selection.get('url'),
w = selection.get('width'),
h = selection.get('height');
this.setImageFromURL(url, selection.id, w, h);
},
/**
* Creates a new wp.customize.HeaderTool.ImageModel from provided
* header image data and inserts it into the user-uploaded headers
* collection.
*
* @param {String} url
* @param {Number} attachmentId
* @param {Number} width
* @param {Number} height
*/
setImageFromURL: function(url, attachmentId, width, height) {
var choice, data = {};
data.url = url;
data.thumbnail_url = url;
data.timestamp = _.now();
if (attachmentId) {
data.attachment_id = attachmentId;
}
if (width) {
data.width = width;
}
if (height) {
data.height = height;
}
choice = new api.HeaderTool.ImageModel({
header: data,
choice: url.split('/').pop()
});
api.HeaderTool.UploadsList.add(choice);
api.HeaderTool.currentHeader.set(choice.toJSON());
choice.save();
choice.importImage();
},
/**
* Triggers the necessary events to deselect an image which was set as
* the currently selected one.
*/
removeImage: function() {
api.HeaderTool.currentHeader.trigger('hide');
api.HeaderTool.CombinedList.trigger('control:removeImage');
}
});
// Change objects contained within the main customize object to Settings.
api.defaultConstructor = api.Setting;
// Create the collection of Control objects.
api.control = new api.Values({ defaultConstructor: api.Control });
api.PreviewFrame = api.Messenger.extend({
sensitivity: 2000,
initialize: function( params, options ) {
var deferred = $.Deferred();
// This is the promise object.
deferred.promise( this );
this.container = params.container;
this.signature = params.signature;
$.extend( params, { channel: api.PreviewFrame.uuid() });
api.Messenger.prototype.initialize.call( this, params, options );
this.add( 'previewUrl', params.previewUrl );
this.query = $.extend( params.query || {}, { customize_messenger_channel: this.channel() });
this.run( deferred );
},
run: function( deferred ) {
var self = this,
loaded = false,
ready = false;
if ( this._ready )
this.unbind( 'ready', this._ready );
this._ready = function() {
ready = true;
if ( loaded )
deferred.resolveWith( self );
};
this.bind( 'ready', this._ready );
this.request = $.ajax( this.previewUrl(), {
type: 'POST',
data: this.query,
xhrFields: {
withCredentials: true
}
} );
this.request.fail( function() {
deferred.rejectWith( self, [ 'request failure' ] );
});
this.request.done( function( response ) {
var location = self.request.getResponseHeader('Location'),
signature = self.signature,
index;
// Check if the location response header differs from the current URL.
// If so, the request was redirected; try loading the requested page.
if ( location && location != self.previewUrl() ) {
deferred.rejectWith( self, [ 'redirect', location ] );
return;
}
// Check if the user is not logged in.
if ( '0' === response ) {
self.login( deferred );
return;
}
// Check for cheaters.
if ( '-1' === response ) {
deferred.rejectWith( self, [ 'cheatin' ] );
return;
}
// Check for a signature in the request.
index = response.lastIndexOf( signature );
if ( -1 === index || index < response.lastIndexOf('</html>') ) {
deferred.rejectWith( self, [ 'unsigned' ] );
return;
}
// Strip the signature from the request.
response = response.slice( 0, index ) + response.slice( index + signature.length );
// Create the iframe and inject the html content.
self.iframe = $('<iframe />').appendTo( self.container );
// Bind load event after the iframe has been added to the page;
// otherwise it will fire when injected into the DOM.
self.iframe.one( 'load', function() {
loaded = true;
if ( ready ) {
deferred.resolveWith( self );
} else {
setTimeout( function() {
deferred.rejectWith( self, [ 'ready timeout' ] );
}, self.sensitivity );
}
});
self.targetWindow( self.iframe[0].contentWindow );
self.targetWindow().document.open();
self.targetWindow().document.write( response );
self.targetWindow().document.close();
});
},
login: function( deferred ) {
var self = this,
reject;
reject = function() {
deferred.rejectWith( self, [ 'logged out' ] );
};
if ( this.triedLogin )
return reject();
// Check if we have an admin cookie.
$.get( api.settings.url.ajax, {
action: 'logged-in'
}).fail( reject ).done( function( response ) {
var iframe;
if ( '1' !== response )
reject();
iframe = $('<iframe src="' + self.previewUrl() + '" />').hide();
iframe.appendTo( self.container );
iframe.load( function() {
self.triedLogin = true;
iframe.remove();
self.run( deferred );
});
});
},
destroy: function() {
api.Messenger.prototype.destroy.call( this );
this.request.abort();
if ( this.iframe )
this.iframe.remove();
delete this.request;
delete this.iframe;
delete this.targetWindow;
}
});
(function(){
var uuid = 0;
api.PreviewFrame.uuid = function() {
return 'preview-' + uuid++;
};
}());
api.Previewer = api.Messenger.extend({
refreshBuffer: 250,
/**
* Requires params:
* - container - a selector or jQuery element
* - previewUrl - the URL of preview frame
*/
initialize: function( params, options ) {
var self = this,
rscheme = /^https?/;
$.extend( this, options || {} );
/*
* Wrap this.refresh to prevent it from hammering the servers:
*
* If refresh is called once and no other refresh requests are
* loading, trigger the request immediately.
*
* If refresh is called while another refresh request is loading,
* debounce the refresh requests:
* 1. Stop the loading request (as it is instantly outdated).
* 2. Trigger the new request once refresh hasn't been called for
* self.refreshBuffer milliseconds.
*/
this.refresh = (function( self ) {
var refresh = self.refresh,
callback = function() {
timeout = null;
refresh.call( self );
},
timeout;
return function() {
if ( typeof timeout !== 'number' ) {
if ( self.loading ) {
self.abort();
} else {
return callback();
}
}
clearTimeout( timeout );
timeout = setTimeout( callback, self.refreshBuffer );
};
})( this );
this.container = api.ensure( params.container );
this.allowedUrls = params.allowedUrls;
this.signature = params.signature;
params.url = window.location.href;
api.Messenger.prototype.initialize.call( this, params );
this.add( 'scheme', this.origin() ).link( this.origin ).setter( function( to ) {
var match = to.match( rscheme );
return match ? match[0] : '';
});
// Limit the URL to internal, front-end links.
//
// If the frontend and the admin are served from the same domain, load the
// preview over ssl if the customizer is being loaded over ssl. This avoids
// insecure content warnings. This is not attempted if the admin and frontend
// are on different domains to avoid the case where the frontend doesn't have
// ssl certs.
this.add( 'previewUrl', params.previewUrl ).setter( function( to ) {
var result;
// Check for URLs that include "/wp-admin/" or end in "/wp-admin".
// Strip hashes and query strings before testing.
if ( /\/wp-admin(\/|$)/.test( to.replace( /[#?].*$/, '' ) ) )
return null;
// Attempt to match the URL to the control frame's scheme
// and check if it's allowed. If not, try the original URL.
$.each([ to.replace( rscheme, self.scheme() ), to ], function( i, url ) {
$.each( self.allowedUrls, function( i, allowed ) {
var path;
allowed = allowed.replace( /\/+$/, '' );
path = url.replace( allowed, '' );
if ( 0 === url.indexOf( allowed ) && /^([/#?]|$)/.test( path ) ) {
result = url;
return false;
}
});
if ( result )
return false;
});
// If we found a matching result, return it. If not, bail.
return result ? result : null;
});
// Refresh the preview when the URL is changed (but not yet).
this.previewUrl.bind( this.refresh );
this.scroll = 0;
this.bind( 'scroll', function( distance ) {
this.scroll = distance;
});
// Update the URL when the iframe sends a URL message.
this.bind( 'url', this.previewUrl );
},
query: function() {},
abort: function() {
if ( this.loading ) {
this.loading.destroy();
delete this.loading;
}
},
refresh: function() {
var self = this;
this.abort();
this.loading = new api.PreviewFrame({
url: this.url(),
previewUrl: this.previewUrl(),
query: this.query() || {},
container: this.container,
signature: this.signature
});
this.loading.done( function() {
// 'this' is the loading frame
this.bind( 'synced', function() {
if ( self.preview )
self.preview.destroy();
self.preview = this;
delete self.loading;
self.targetWindow( this.targetWindow() );
self.channel( this.channel() );
self.send( 'active' );
});
this.send( 'sync', {
scroll: self.scroll,
settings: api.get()
});
});
this.loading.fail( function( reason, location ) {
if ( 'redirect' === reason && location )
self.previewUrl( location );
if ( 'logged out' === reason ) {
if ( self.preview ) {
self.preview.destroy();
delete self.preview;
}
self.login().done( self.refresh );
}
if ( 'cheatin' === reason )
self.cheatin();
});
},
login: function() {
var previewer = this,
deferred, messenger, iframe;
if ( this._login )
return this._login;
deferred = $.Deferred();
this._login = deferred.promise();
messenger = new api.Messenger({
channel: 'login',
url: api.settings.url.login
});
iframe = $('<iframe src="' + api.settings.url.login + '" />').appendTo( this.container );
messenger.targetWindow( iframe[0].contentWindow );
messenger.bind( 'login', function() {
iframe.remove();
messenger.destroy();
delete previewer._login;
deferred.resolve();
});
return this._login;
},
cheatin: function() {
$( document.body ).empty().addClass('cheatin').append( '<p>' + api.l10n.cheatin + '</p>' );
}
});
/* =====================================================================
* Ready.
* ===================================================================== */
api.controlConstructor = {
color: api.ColorControl,
upload: api.UploadControl,
image: api.ImageControl,
header: api.HeaderControl
};
$( function() {
api.settings = window._wpCustomizeSettings;
api.l10n = window._wpCustomizeControlsL10n;
// Check if we can run the customizer.
if ( ! api.settings )
return;
// Redirect to the fallback preview if any incompatibilities are found.
if ( ! $.support.postMessage || ( ! $.support.cors && api.settings.isCrossDomain ) )
return window.location = api.settings.url.fallback;
var previewer, parent, topFocus,
body = $( document.body ),
overlay = body.children('.wp-full-overlay');
// Prevent the form from saving when enter is pressed on an input or select element.
$('#customize-controls').on( 'keydown', function( e ) {
var isEnter = ( 13 === e.which ),
$el = $( e.target );
if ( isEnter && ( $el.is( 'input:not([type=button])' ) || $el.is( 'select' ) ) ) {
e.preventDefault();
}
});
// Initialize Previewer
previewer = new api.Previewer({
container: '#customize-preview',
form: '#customize-controls',
previewUrl: api.settings.url.preview,
allowedUrls: api.settings.url.allowed,
signature: 'WP_CUSTOMIZER_SIGNATURE'
}, {
nonce: api.settings.nonce,
query: function() {
return {
wp_customize: 'on',
theme: api.settings.theme.stylesheet,
customized: JSON.stringify( api.get() ),
nonce: this.nonce.preview
};
},
save: function() {
var self = this,
query = $.extend( this.query(), {
action: 'customize_save',
nonce: this.nonce.save
} ),
processing = api.state( 'processing' ),
submitWhenDoneProcessing,
submit;
body.addClass( 'saving' );
submit = function () {
var request = $.post( api.settings.url.ajax, query );
api.trigger( 'save', request );
request.always( function () {
body.removeClass( 'saving' );
} );
request.done( function( response ) {
// Check if the user is logged out.
if ( '0' === response ) {
self.preview.iframe.hide();
self.login().done( function() {
self.save();
self.preview.iframe.show();
} );
return;
}
// Check for cheaters.
if ( '-1' === response ) {
self.cheatin();
return;
}
api.trigger( 'saved' );
} );
};
if ( 0 === processing() ) {
submit();
} else {
submitWhenDoneProcessing = function () {
if ( 0 === processing() ) {
api.state.unbind( 'change', submitWhenDoneProcessing );
submit();
}
};
api.state.bind( 'change', submitWhenDoneProcessing );
}
}
});
// Refresh the nonces if the preview sends updated nonces over.
previewer.bind( 'nonce', function( nonce ) {
$.extend( this.nonce, nonce );
});
$.each( api.settings.settings, function( id, data ) {
api.create( id, id, data.value, {
transport: data.transport,
previewer: previewer
} );
});
$.each( api.settings.controls, function( id, data ) {
var constructor = api.controlConstructor[ data.type ] || api.Control,
control;
control = api.control.add( id, new constructor( id, {
params: data,
previewer: previewer
} ) );
});
// Check if preview url is valid and load the preview frame.
if ( previewer.previewUrl() )
previewer.refresh();
else
previewer.previewUrl( api.settings.url.home );
// Save and activated states
(function() {
var state = new api.Values(),
saved = state.create( 'saved' ),
activated = state.create( 'activated' ),
processing = state.create( 'processing' );
state.bind( 'change', function() {
var save = $('#save'),
back = $('.back');
if ( ! activated() ) {
save.val( api.l10n.activate ).prop( 'disabled', false );
back.text( api.l10n.cancel );
} else if ( saved() ) {
save.val( api.l10n.saved ).prop( 'disabled', true );
back.text( api.l10n.close );
} else {
save.val( api.l10n.save ).prop( 'disabled', false );
back.text( api.l10n.cancel );
}
});
// Set default states.
saved( true );
activated( api.settings.theme.active );
processing( 0 );
api.bind( 'change', function() {
state('saved').set( false );
});
api.bind( 'saved', function() {
state('saved').set( true );
state('activated').set( true );
});
activated.bind( function( to ) {
if ( to )
api.trigger( 'activated' );
});
// Expose states to the API.
api.state = state;
}());
// Button bindings.
$('#save').click( function( event ) {
previewer.save();
event.preventDefault();
}).keydown( function( event ) {
if ( 9 === event.which ) // tab
return;
if ( 13 === event.which ) // enter
previewer.save();
event.preventDefault();
});
$('.back').keydown( function( event ) {
if ( 9 === event.which ) // tab
return;
if ( 13 === event.which ) // enter
this.click();
event.preventDefault();
});
$('.upload-dropzone a.upload').keydown( function( event ) {
if ( 13 === event.which ) // enter
this.click();
});
$('.collapse-sidebar').on( 'click keydown', function( event ) {
if ( event.type === 'keydown' && 13 !== event.which ) // enter
return;
overlay.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
event.preventDefault();
});
// Create a potential postMessage connection with the parent frame.
parent = new api.Messenger({
url: api.settings.url.parent,
channel: 'loader'
});
// If we receive a 'back' event, we're inside an iframe.
// Send any clicks to the 'Return' link to the parent page.
parent.bind( 'back', function() {
$('.back').on( 'click.back', function( event ) {
event.preventDefault();
parent.send( 'close' );
});
});
// Pass events through to the parent.
api.bind( 'saved', function() {
parent.send( 'saved' );
});
// When activated, let the loader handle redirecting the page.
// If no loader exists, redirect the page ourselves (if a url exists).
api.bind( 'activated', function() {
if ( parent.targetWindow() )
parent.send( 'activated', api.settings.url.activated );
else if ( api.settings.url.activated )
window.location = api.settings.url.activated;
});
// Initialize the connection with the parent frame.
parent.send( 'ready' );
// Control visibility for default controls
$.each({
'background_image': {
controls: [ 'background_repeat', 'background_position_x', 'background_attachment' ],
callback: function( to ) { return !! to; }
},
'show_on_front': {
controls: [ 'page_on_front', 'page_for_posts' ],
callback: function( to ) { return 'page' === to; }
},
'header_textcolor': {
controls: [ 'header_textcolor' ],
callback: function( to ) { return 'blank' !== to; }
}
}, function( settingId, o ) {
api( settingId, function( setting ) {
$.each( o.controls, function( i, controlId ) {
api.control( controlId, function( control ) {
var visibility = function( to ) {
control.container.toggle( o.callback( to ) );
};
visibility( setting.get() );
setting.bind( visibility );
});
});
});
});
// Juggle the two controls that use header_textcolor
api.control( 'display_header_text', function( control ) {
var last = '';
control.elements[0].unsync( api( 'header_textcolor' ) );
control.element = new api.Element( control.container.find('input') );
control.element.set( 'blank' !== control.setting() );
control.element.bind( function( to ) {
if ( ! to )
last = api( 'header_textcolor' ).get();
control.setting.set( to ? last : 'blank' );
});
control.setting.bind( function( to ) {
control.element.set( 'blank' !== to );
});
});
api.trigger( 'ready' );
// Make sure left column gets focus
topFocus = $('.back');
topFocus.focus();
setTimeout(function () {
topFocus.focus();
}, 200);
});
})( wp, jQuery );
| 01-wordpress-paypal | trunk/wp-admin/js/customize-controls.js | JavaScript | gpl3 | 31,592 |
( function( $ ){
$( document ).ready( function () {
// Expand/Collapse on click
$( '.accordion-container' ).on( 'click keydown', '.accordion-section-title', function( e ) {
if ( e.type === 'keydown' && 13 !== e.which ) // "return" key
return;
e.preventDefault(); // Keep this AFTER the key filter above
accordionSwitch( $( this ) );
});
// Re-initialize accordion when screen options are toggled
$( '.hide-postbox-tog' ).click( function () {
accordionInit();
});
});
var accordionOptions = $( '.accordion-container li.accordion-section' ),
sectionContent = $( '.accordion-section-content' );
function accordionInit () {
// Rounded corners
accordionOptions.removeClass( 'top bottom' );
accordionOptions.filter( ':visible' ).first().addClass( 'top' );
accordionOptions.filter( ':visible' ).last().addClass( 'bottom' ).find( sectionContent ).addClass( 'bottom' );
}
function accordionSwitch ( el ) {
var section = el.closest( '.accordion-section' ),
siblings = section.closest( '.accordion-container' ).find( '.open' ),
content = section.find( sectionContent );
if ( section.hasClass( 'cannot-expand' ) )
return;
if ( section.hasClass( 'open' ) ) {
section.toggleClass( 'open' );
content.toggle( true ).slideToggle( 150 );
} else {
siblings.removeClass( 'open' );
siblings.find( sectionContent ).show().slideUp( 150 );
content.toggle( false ).slideToggle( 150 );
section.toggleClass( 'open' );
}
accordionInit();
}
// Initialize the accordion (currently just corner fixes)
accordionInit();
})(jQuery);
| 01-wordpress-paypal | trunk/wp-admin/js/accordion.js | JavaScript | gpl3 | 1,601 |
/* global setPostThumbnailL10n, ajaxurl, post_id, alert */
/* exported WPSetAsThumbnail */
function WPSetAsThumbnail( id, nonce ) {
var $link = jQuery('a#wp-post-thumbnail-' + id);
$link.text( setPostThumbnailL10n.saving );
jQuery.post(ajaxurl, {
action: 'set-post-thumbnail', post_id: post_id, thumbnail_id: id, _ajax_nonce: nonce, cookie: encodeURIComponent( document.cookie )
}, function(str){
var win = window.dialogArguments || opener || parent || top;
$link.text( setPostThumbnailL10n.setThumbnail );
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
jQuery('a.wp-post-thumbnail').show();
$link.text( setPostThumbnailL10n.done );
$link.fadeOut( 2000 );
win.WPSetThumbnailID(id);
win.WPSetThumbnailHTML(str);
}
}
);
}
| 01-wordpress-paypal | trunk/wp-admin/js/set-post-thumbnail.js | JavaScript | gpl3 | 777 |
/* global wordCountL10n */
var wpWordCount;
(function($,undefined) {
wpWordCount = {
settings : {
strip : /<[a-zA-Z\/][^<>]*>/g, // strip HTML tags
clean : /[0-9.(),;:!?%#$¿'"_+=\\/-]+/g, // regexp to remove punctuation, etc.
w : /\S\s+/g, // word-counting regexp
c : /\S/g // char-counting regexp for asian languages
},
block : 0,
wc : function(tx, type) {
var t = this, w = $('.word-count'), tc = 0;
if ( type === undefined )
type = wordCountL10n.type;
if ( type !== 'w' && type !== 'c' )
type = 'w';
if ( t.block )
return;
t.block = 1;
setTimeout( function() {
if ( tx ) {
tx = tx.replace( t.settings.strip, ' ' ).replace( / | /gi, ' ' );
tx = tx.replace( t.settings.clean, '' );
tx.replace( t.settings[type], function(){tc++;} );
}
w.html(tc.toString());
setTimeout( function() { t.block = 0; }, 2000 );
}, 1 );
}
};
$(document).bind( 'wpcountwords', function(e, txt) {
wpWordCount.wc(txt);
});
}(jQuery));
| 01-wordpress-paypal | trunk/wp-admin/js/word-count.js | JavaScript | gpl3 | 1,023 |
/* global wpColorPickerL10n:true */
( function( $, undef ){
var ColorPicker,
// html stuff
_before = '<a tabindex="0" class="wp-color-result" />',
_after = '<div class="wp-picker-holder" />',
_wrap = '<div class="wp-picker-container" />',
_button = '<input type="button" class="button button-small hidden" />';
// jQuery UI Widget constructor
ColorPicker = {
options: {
defaultColor: false,
change: false,
clear: false,
hide: true,
palettes: true
},
_create: function() {
// bail early for unsupported Iris.
if ( ! $.support.iris )
return;
var self = this,
el = self.element;
$.extend( self.options, el.data() );
self.initialValue = el.val();
// Set up HTML structure, hide things
el.addClass( 'wp-color-picker' ).hide().wrap( _wrap );
self.wrap = el.parent();
self.toggler = $( _before ).insertBefore( el ).css( { backgroundColor: self.initialValue } ).attr( 'title', wpColorPickerL10n.pick ).attr( 'data-current', wpColorPickerL10n.current );
self.pickerContainer = $( _after ).insertAfter( el );
self.button = $( _button );
if ( self.options.defaultColor )
self.button.addClass( 'wp-picker-default' ).val( wpColorPickerL10n.defaultString );
else
self.button.addClass( 'wp-picker-clear' ).val( wpColorPickerL10n.clear );
el.wrap('<span class="wp-picker-input-wrap" />').after(self.button);
el.iris( {
target: self.pickerContainer,
hide: true,
width: 255,
mode: 'hsv',
palettes: self.options.palettes,
change: function( event, ui ) {
self.toggler.css( { backgroundColor: ui.color.toString() } );
// check for a custom cb
if ( $.isFunction( self.options.change ) )
self.options.change.call( this, event, ui );
}
} );
el.val( self.initialValue );
self._addListeners();
if ( ! self.options.hide )
self.toggler.click();
},
_addListeners: function() {
var self = this;
self.toggler.click( function( event ){
event.stopPropagation();
self.element.toggle().iris( 'toggle' );
self.button.toggleClass('hidden');
self.toggler.toggleClass( 'wp-picker-open' );
// close picker when you click outside it
if ( self.toggler.hasClass( 'wp-picker-open' ) )
$( 'body' ).on( 'click', { wrap: self.wrap, toggler: self.toggler }, self._bodyListener );
else
$( 'body' ).off( 'click', self._bodyListener );
});
self.element.change(function( event ) {
var me = $(this),
val = me.val();
// Empty = clear
if ( val === '' || val === '#' ) {
self.toggler.css('backgroundColor', '');
// fire clear callback if we have one
if ( $.isFunction( self.options.clear ) )
self.options.clear.call( this, event );
}
});
// open a keyboard-focused closed picker with space or enter
self.toggler.on('keyup', function( e ) {
if ( e.keyCode === 13 || e.keyCode === 32 ) {
e.preventDefault();
self.toggler.trigger('click').next().focus();
}
});
self.button.click( function( event ) {
var me = $(this);
if ( me.hasClass( 'wp-picker-clear' ) ) {
self.element.val( '' );
self.toggler.css('backgroundColor', '');
if ( $.isFunction( self.options.clear ) )
self.options.clear.call( this, event );
} else if ( me.hasClass( 'wp-picker-default' ) ) {
self.element.val( self.options.defaultColor ).change();
}
});
},
_bodyListener: function( event ) {
if ( ! event.data.wrap.find( event.target ).length )
event.data.toggler.click();
},
// $("#input").wpColorPicker('color') returns the current color
// $("#input").wpColorPicker('color', '#bada55') to set
color: function( newColor ) {
if ( newColor === undef )
return this.element.iris( 'option', 'color' );
this.element.iris( 'option', 'color', newColor );
},
//$("#input").wpColorPicker('defaultColor') returns the current default color
//$("#input").wpColorPicker('defaultColor', newDefaultColor) to set
defaultColor: function( newDefaultColor ) {
if ( newDefaultColor === undef )
return this.options.defaultColor;
this.options.defaultColor = newDefaultColor;
}
};
$.widget( 'wp.wpColorPicker', ColorPicker );
}( jQuery ) );
| 01-wordpress-paypal | trunk/wp-admin/js/color-picker.js | JavaScript | gpl3 | 4,228 |
/* global imageEditL10n, ajaxurl, confirm */
(function($) {
var imageEdit = window.imageEdit = {
iasapi : {},
hold : {},
postid : '',
_view : false,
intval : function(f) {
return f | 0;
},
setDisabled : function(el, s) {
if ( s ) {
el.removeClass('disabled');
$('input', el).removeAttr('disabled');
} else {
el.addClass('disabled');
$('input', el).prop('disabled', true);
}
},
init : function(postid) {
var t = this, old = $('#image-editor-' + t.postid),
x = t.intval( $('#imgedit-x-' + postid).val() ),
y = t.intval( $('#imgedit-y-' + postid).val() );
if ( t.postid !== postid && old.length ) {
t.close(t.postid);
}
t.hold.w = t.hold.ow = x;
t.hold.h = t.hold.oh = y;
t.hold.xy_ratio = x / y;
t.hold.sizer = parseFloat( $('#imgedit-sizer-' + postid).val() );
t.postid = postid;
$('#imgedit-response-' + postid).empty();
$('input[type="text"]', '#imgedit-panel-' + postid).keypress(function(e) {
var k = e.keyCode;
if ( 36 < k && k < 41 ) {
$(this).blur();
}
if ( 13 === k ) {
e.preventDefault();
e.stopPropagation();
return false;
}
});
},
toggleEditor : function(postid, toggle) {
var wait = $('#imgedit-wait-' + postid);
if ( toggle ) {
wait.height( $('#imgedit-panel-' + postid).height() ).fadeIn('fast');
} else {
wait.fadeOut('fast');
}
},
toggleHelp : function(el) {
$( el ).parents( '.imgedit-group-top' ).toggleClass( 'imgedit-help-toggled' ).find( '.imgedit-help' ).slideToggle( 'fast' );
return false;
},
getTarget : function(postid) {
return $('input[name="imgedit-target-' + postid + '"]:checked', '#imgedit-save-target-' + postid).val() || 'full';
},
scaleChanged : function(postid, x) {
var w = $('#imgedit-scale-width-' + postid), h = $('#imgedit-scale-height-' + postid),
warn = $('#imgedit-scale-warn-' + postid), w1 = '', h1 = '';
if ( x ) {
h1 = ( w.val() !== '' ) ? Math.round( w.val() / this.hold.xy_ratio ) : '';
h.val( h1 );
} else {
w1 = ( h.val() !== '' ) ? Math.round( h.val() * this.hold.xy_ratio ) : '';
w.val( w1 );
}
if ( ( h1 && h1 > this.hold.oh ) || ( w1 && w1 > this.hold.ow ) ) {
warn.css('visibility', 'visible');
} else {
warn.css('visibility', 'hidden');
}
},
getSelRatio : function(postid) {
var x = this.hold.w, y = this.hold.h,
X = this.intval( $('#imgedit-crop-width-' + postid).val() ),
Y = this.intval( $('#imgedit-crop-height-' + postid).val() );
if ( X && Y ) {
return X + ':' + Y;
}
if ( x && y ) {
return x + ':' + y;
}
return '1:1';
},
filterHistory : function(postid, setSize) {
// apply undo state to history
var history = $('#imgedit-history-' + postid).val(), pop, n, o, i, op = [];
if ( history !== '' ) {
history = JSON.parse(history);
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop > 0 ) {
while ( pop > 0 ) {
history.pop();
pop--;
}
}
if ( setSize ) {
if ( !history.length ) {
this.hold.w = this.hold.ow;
this.hold.h = this.hold.oh;
return '';
}
// restore
o = history[history.length - 1];
o = o.c || o.r || o.f || false;
if ( o ) {
this.hold.w = o.fw;
this.hold.h = o.fh;
}
}
// filter the values
for ( n in history ) {
i = history[n];
if ( i.hasOwnProperty('c') ) {
op[n] = { 'c': { 'x': i.c.x, 'y': i.c.y, 'w': i.c.w, 'h': i.c.h } };
} else if ( i.hasOwnProperty('r') ) {
op[n] = { 'r': i.r.r };
} else if ( i.hasOwnProperty('f') ) {
op[n] = { 'f': i.f.f };
}
}
return JSON.stringify(op);
}
return '';
},
refreshEditor : function(postid, nonce, callback) {
var t = this, data, img;
t.toggleEditor(postid, 1);
data = {
'action': 'imgedit-preview',
'_ajax_nonce': nonce,
'postid': postid,
'history': t.filterHistory(postid, 1),
'rand': t.intval(Math.random() * 1000000)
};
img = $('<img id="image-preview-' + postid + '" />')
.on('load', function() {
var max1, max2, parent = $('#imgedit-crop-' + postid), t = imageEdit;
parent.empty().append(img);
// w, h are the new full size dims
max1 = Math.max( t.hold.w, t.hold.h );
max2 = Math.max( $(img).width(), $(img).height() );
t.hold.sizer = max1 > max2 ? max2 / max1 : 1;
t.initCrop(postid, img, parent);
t.setCropSelection(postid, 0);
if ( (typeof callback !== 'undefined') && callback !== null ) {
callback();
}
if ( $('#imgedit-history-' + postid).val() && $('#imgedit-undone-' + postid).val() === '0' ) {
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).removeAttr('disabled');
} else {
$('input.imgedit-submit-btn', '#imgedit-panel-' + postid).prop('disabled', true);
}
t.toggleEditor(postid, 0);
})
.on('error', function() {
$('#imgedit-crop-' + postid).empty().append('<div class="error"><p>' + imageEditL10n.error + '</p></div>');
t.toggleEditor(postid, 0);
})
.attr('src', ajaxurl + '?' + $.param(data));
},
action : function(postid, nonce, action) {
var t = this, data, w, h, fw, fh;
if ( t.notsaved(postid) ) {
return false;
}
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid
};
if ( 'scale' === action ) {
w = $('#imgedit-scale-width-' + postid),
h = $('#imgedit-scale-height-' + postid),
fw = t.intval(w.val()),
fh = t.intval(h.val());
if ( fw < 1 ) {
w.focus();
return false;
} else if ( fh < 1 ) {
h.focus();
return false;
}
if ( fw === t.hold.ow || fh === t.hold.oh ) {
return false;
}
data['do'] = 'scale';
data.fwidth = fw;
data.fheight = fh;
} else if ( 'restore' === action ) {
data['do'] = 'restore';
} else {
return false;
}
t.toggleEditor(postid, 1);
$.post(ajaxurl, data, function(r) {
$('#image-editor-' + postid).empty().append(r);
t.toggleEditor(postid, 0);
// refresh the attachment model so that changes propagate
if ( t._view ) {
t._view.refresh();
}
});
},
save : function(postid, nonce) {
var data,
target = this.getTarget(postid),
history = this.filterHistory(postid, 0),
self = this;
if ( '' === history ) {
return false;
}
this.toggleEditor(postid, 1);
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'history': history,
'target': target,
'context': $('#image-edit-context').length ? $('#image-edit-context').val() : null,
'do': 'save'
};
$.post(ajaxurl, data, function(r) {
var ret = JSON.parse(r);
if ( ret.error ) {
$('#imgedit-response-' + postid).html('<div class="error"><p>' + ret.error + '</p><div>');
imageEdit.close(postid);
return;
}
if ( ret.fw && ret.fh ) {
$('#media-dims-' + postid).html( ret.fw + ' × ' + ret.fh );
}
if ( ret.thumbnail ) {
$('.thumbnail', '#thumbnail-head-' + postid).attr('src', ''+ret.thumbnail);
}
if ( ret.msg ) {
$('#imgedit-response-' + postid).html('<div class="updated"><p>' + ret.msg + '</p></div>');
}
if ( self._view ) {
self._view.save();
} else {
imageEdit.close(postid);
}
});
},
open : function( postid, nonce, view ) {
this._view = view;
var data, elem = $('#image-editor-' + postid), head = $('#media-head-' + postid),
btn = $('#imgedit-open-btn-' + postid), spin = btn.siblings('.spinner');
btn.prop('disabled', true);
spin.show();
data = {
'action': 'image-editor',
'_ajax_nonce': nonce,
'postid': postid,
'do': 'open'
};
elem.load(ajaxurl, data, function() {
elem.fadeIn('fast');
head.fadeOut('fast', function(){
btn.removeAttr('disabled');
spin.hide();
});
});
},
imgLoaded : function(postid) {
var img = $('#image-preview-' + postid), parent = $('#imgedit-crop-' + postid);
this.initCrop(postid, img, parent);
this.setCropSelection(postid, 0);
this.toggleEditor(postid, 0);
},
initCrop : function(postid, image, parent) {
var t = this,
selW = $('#imgedit-sel-width-' + postid),
selH = $('#imgedit-sel-height-' + postid),
$img;
t.iasapi = $(image).imgAreaSelect({
parent: parent,
instance: true,
handles: true,
keys: true,
minWidth: 3,
minHeight: 3,
onInit: function( img ) {
// Ensure that the imgareaselect wrapper elements are position:absolute
// (even if we're in a position:fixed modal)
$img = $( img );
$img.next().css( 'position', 'absolute' )
.nextAll( '.imgareaselect-outer' ).css( 'position', 'absolute' );
parent.children().mousedown(function(e){
var ratio = false, sel, defRatio;
if ( e.shiftKey ) {
sel = t.iasapi.getSelection();
defRatio = t.getSelRatio(postid);
ratio = ( sel && sel.width && sel.height ) ? sel.width + ':' + sel.height : defRatio;
}
t.iasapi.setOptions({
aspectRatio: ratio
});
});
},
onSelectStart: function() {
imageEdit.setDisabled($('#imgedit-crop-sel-' + postid), 1);
},
onSelectEnd: function(img, c) {
imageEdit.setCropSelection(postid, c);
},
onSelectChange: function(img, c) {
var sizer = imageEdit.hold.sizer;
selW.val( imageEdit.round(c.width / sizer) );
selH.val( imageEdit.round(c.height / sizer) );
}
});
},
setCropSelection : function(postid, c) {
var sel, min = $('#imgedit-minthumb-' + postid).val() || '128:128',
sizer = this.hold.sizer;
min = min.split(':');
c = c || 0;
if ( !c || ( c.width < 3 && c.height < 3 ) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
this.setDisabled($('#imgedit-crop-sel-' + postid), 0);
$('#imgedit-sel-width-' + postid).val('');
$('#imgedit-sel-height-' + postid).val('');
$('#imgedit-selection-' + postid).val('');
return false;
}
if ( c.width < (min[0] * sizer) && c.height < (min[1] * sizer) ) {
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 0);
$('#imgedit-selection-' + postid).val('');
return false;
}
sel = { 'x': c.x1, 'y': c.y1, 'w': c.width, 'h': c.height };
this.setDisabled($('.imgedit-crop', '#imgedit-panel-' + postid), 1);
$('#imgedit-selection-' + postid).val( JSON.stringify(sel) );
},
close : function(postid, warn) {
warn = warn || false;
if ( warn && this.notsaved(postid) ) {
return false;
}
this.iasapi = {};
this.hold = {};
// If we've loaded the editor in the context of a Media Modal, then switch to the previous view,
// whatever that might have been.
if ( this._view ){
this._view.back();
}
// In case we are not accessing the image editor in the context of a View, close the editor the old-skool way
else {
$('#image-editor-' + postid).fadeOut('fast', function() {
$('#media-head-' + postid).fadeIn('fast');
$(this).empty();
});
}
},
notsaved : function(postid) {
var h = $('#imgedit-history-' + postid).val(),
history = ( h !== '' ) ? JSON.parse(h) : [],
pop = this.intval( $('#imgedit-undone-' + postid).val() );
if ( pop < history.length ) {
if ( confirm( $('#imgedit-leaving-' + postid).html() ) ) {
return false;
}
return true;
}
return false;
},
addStep : function(op, postid, nonce) {
var t = this, elem = $('#imgedit-history-' + postid),
history = ( elem.val() !== '' ) ? JSON.parse( elem.val() ) : [],
undone = $('#imgedit-undone-' + postid),
pop = t.intval(undone.val());
while ( pop > 0 ) {
history.pop();
pop--;
}
undone.val(0); // reset
history.push(op);
elem.val( JSON.stringify(history) );
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled($('#image-redo-' + postid), false);
});
},
rotate : function(angle, postid, nonce, t) {
if ( $(t).hasClass('disabled') ) {
return false;
}
this.addStep({ 'r': { 'r': angle, 'fw': this.hold.h, 'fh': this.hold.w }}, postid, nonce);
},
flip : function (axis, postid, nonce, t) {
if ( $(t).hasClass('disabled') ) {
return false;
}
this.addStep({ 'f': { 'f': axis, 'fw': this.hold.w, 'fh': this.hold.h }}, postid, nonce);
},
crop : function (postid, nonce, t) {
var sel = $('#imgedit-selection-' + postid).val(),
w = this.intval( $('#imgedit-sel-width-' + postid).val() ),
h = this.intval( $('#imgedit-sel-height-' + postid).val() );
if ( $(t).hasClass('disabled') || sel === '' ) {
return false;
}
sel = JSON.parse(sel);
if ( sel.w > 0 && sel.h > 0 && w > 0 && h > 0 ) {
sel.fw = w;
sel.fh = h;
this.addStep({ 'c': sel }, postid, nonce);
}
},
undo : function (postid, nonce) {
var t = this, button = $('#image-undo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) + 1;
if ( button.hasClass('disabled') ) {
return;
}
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
var elem = $('#imgedit-history-' + postid),
history = ( elem.val() !== '' ) ? JSON.parse( elem.val() ) : [];
t.setDisabled($('#image-redo-' + postid), true);
t.setDisabled(button, pop < history.length);
});
},
redo : function(postid, nonce) {
var t = this, button = $('#image-redo-' + postid), elem = $('#imgedit-undone-' + postid),
pop = t.intval( elem.val() ) - 1;
if ( button.hasClass('disabled') ) {
return;
}
elem.val(pop);
t.refreshEditor(postid, nonce, function() {
t.setDisabled($('#image-undo-' + postid), true);
t.setDisabled(button, pop > 0);
});
},
setNumSelection : function(postid) {
var sel, elX = $('#imgedit-sel-width-' + postid), elY = $('#imgedit-sel-height-' + postid),
x = this.intval( elX.val() ), y = this.intval( elY.val() ),
img = $('#image-preview-' + postid), imgh = img.height(), imgw = img.width(),
sizer = this.hold.sizer, x1, y1, x2, y2, ias = this.iasapi;
if ( x < 1 ) {
elX.val('');
return false;
}
if ( y < 1 ) {
elY.val('');
return false;
}
if ( x && y && ( sel = ias.getSelection() ) ) {
x2 = sel.x1 + Math.round( x * sizer );
y2 = sel.y1 + Math.round( y * sizer );
x1 = sel.x1;
y1 = sel.y1;
if ( x2 > imgw ) {
x1 = 0;
x2 = imgw;
elX.val( Math.round( x2 / sizer ) );
}
if ( y2 > imgh ) {
y1 = 0;
y2 = imgh;
elY.val( Math.round( y2 / sizer ) );
}
ias.setSelection( x1, y1, x2, y2 );
ias.update();
this.setCropSelection(postid, ias.getSelection());
}
},
round : function(num) {
var s;
num = Math.round(num);
if ( this.hold.sizer > 0.6 ) {
return num;
}
s = num.toString().slice(-1);
if ( '1' === s ) {
return num - 1;
} else if ( '9' === s ) {
return num + 1;
}
return num;
},
setRatioSelection : function(postid, n, el) {
var sel, r, x = this.intval( $('#imgedit-crop-width-' + postid).val() ),
y = this.intval( $('#imgedit-crop-height-' + postid).val() ),
h = $('#image-preview-' + postid).height();
if ( !this.intval( $(el).val() ) ) {
$(el).val('');
return;
}
if ( x && y ) {
this.iasapi.setOptions({
aspectRatio: x + ':' + y
});
if ( sel = this.iasapi.getSelection(true) ) {
r = Math.ceil( sel.y1 + ( ( sel.x2 - sel.x1 ) / ( x / y ) ) );
if ( r > h ) {
r = h;
if ( n ) {
$('#imgedit-crop-height-' + postid).val('');
} else {
$('#imgedit-crop-width-' + postid).val('');
}
}
this.iasapi.setSelection( sel.x1, sel.y1, sel.x2, r );
this.iasapi.update();
}
}
}
};
})(jQuery);
| 01-wordpress-paypal | trunk/wp-admin/js/image-edit.js | JavaScript | gpl3 | 15,477 |
/* global ajaxurl */
jQuery(function($){
$( 'body' ).bind( 'click.wp-gallery', function(e){
var target = $( e.target ), id, img_size;
if ( target.hasClass( 'wp-set-header' ) ) {
( window.dialogArguments || opener || parent || top ).location.href = target.data( 'location' );
e.preventDefault();
} else if ( target.hasClass( 'wp-set-background' ) ) {
id = target.data( 'attachment-id' );
img_size = $( 'input[name="attachments[' + id + '][image-size]"]:checked').val();
jQuery.post(ajaxurl, {
action: 'set-background-image',
attachment_id: id,
size: img_size
}, function(){
var win = window.dialogArguments || opener || parent || top;
win.tb_remove();
win.location.reload();
});
e.preventDefault();
}
});
});
| 01-wordpress-paypal | trunk/wp-admin/js/media-gallery.js | JavaScript | gpl3 | 769 |
/* global ajaxurl, pwsL10n */
(function($){
function check_pass_strength() {
var pass1 = $('#pass1').val(), pass2 = $('#pass2').val(), strength;
$('#pass-strength-result').removeClass('short bad good strong');
if ( ! pass1 ) {
$('#pass-strength-result').html( pwsL10n.empty );
return;
}
strength = wp.passwordStrength.meter( pass1, wp.passwordStrength.userInputBlacklist(), pass2 );
switch ( strength ) {
case 2:
$('#pass-strength-result').addClass('bad').html( pwsL10n.bad );
break;
case 3:
$('#pass-strength-result').addClass('good').html( pwsL10n.good );
break;
case 4:
$('#pass-strength-result').addClass('strong').html( pwsL10n.strong );
break;
case 5:
$('#pass-strength-result').addClass('short').html( pwsL10n.mismatch );
break;
default:
$('#pass-strength-result').addClass('short').html( pwsL10n['short'] );
}
}
$(document).ready( function() {
var $colorpicker, $stylesheet, user_id, current_user_id,
select = $( '#display_name' );
$('#pass1').val('').keyup( check_pass_strength );
$('#pass2').val('').keyup( check_pass_strength );
$('#pass-strength-result').show();
$('.color-palette').click( function() {
$(this).siblings('input[name="admin_color"]').prop('checked', true);
});
if ( select.length ) {
$('#first_name, #last_name, #nickname').bind( 'blur.user_profile', function() {
var dub = [],
inputs = {
display_nickname : $('#nickname').val() || '',
display_username : $('#user_login').val() || '',
display_firstname : $('#first_name').val() || '',
display_lastname : $('#last_name').val() || ''
};
if ( inputs.display_firstname && inputs.display_lastname ) {
inputs.display_firstlast = inputs.display_firstname + ' ' + inputs.display_lastname;
inputs.display_lastfirst = inputs.display_lastname + ' ' + inputs.display_firstname;
}
$.each( $('option', select), function( i, el ){
dub.push( el.value );
});
$.each(inputs, function( id, value ) {
if ( ! value ) {
return;
}
var val = value.replace(/<\/?[a-z][^>]*>/gi, '');
if ( inputs[id].length && $.inArray( val, dub ) === -1 ) {
dub.push(val);
$('<option />', {
'text': val
}).appendTo( select );
}
});
});
}
$colorpicker = $( '#color-picker' );
$stylesheet = $( '#colors-css' );
user_id = $( 'input#user_id' ).val();
current_user_id = $( 'input[name="checkuser_id"]' ).val();
$colorpicker.on( 'click.colorpicker', '.color-option', function() {
var colors,
$this = $(this);
if ( $this.hasClass( 'selected' ) ) {
return;
}
$this.siblings( '.selected' ).removeClass( 'selected' );
$this.addClass( 'selected' ).find( 'input[type="radio"]' ).prop( 'checked', true );
// Set color scheme
if ( user_id === current_user_id ) {
// Load the colors stylesheet.
// The default color scheme won't have one, so we'll need to create an element.
if ( 0 === $stylesheet.length ) {
$stylesheet = $( '<link rel="stylesheet" />' ).appendTo( 'head' );
}
$stylesheet.attr( 'href', $this.children( '.css_url' ).val() );
// repaint icons
if ( typeof wp !== 'undefined' && wp.svgPainter ) {
try {
colors = $.parseJSON( $this.children( '.icon_colors' ).val() );
} catch ( error ) {}
if ( colors ) {
wp.svgPainter.setColors( colors );
wp.svgPainter.paint();
}
}
// update user option
$.post( ajaxurl, {
action: 'save-user-color-scheme',
color_scheme: $this.children( 'input[name="admin_color"]' ).val(),
nonce: $('#color-nonce').val()
});
}
});
});
})(jQuery);
| 01-wordpress-paypal | trunk/wp-admin/js/user-profile.js | JavaScript | gpl3 | 3,719 |
/* global plugininstallL10n, tb_click, confirm */
/* Plugin Browser Thickbox related JS*/
var tb_position;
jQuery( document ).ready( function( $ ) {
tb_position = function() {
var tbWindow = $( '#TB_window' ),
width = $( window ).width(),
H = $( window ).height() - ( ( 850 < width ) ? 60 : 20 ),
W = ( 850 < width ) ? 830 : width - 20;
if ( tbWindow.size() ) {
tbWindow.width( W ).height( H );
$( '#TB_iframeContent' ).width( W ).height( H );
tbWindow.css({
'margin-left': '-' + parseInt( ( W / 2 ), 10 ) + 'px'
});
if ( typeof document.body.style.maxWidth !== 'undefined' ) {
tbWindow.css({
'top': ( ( 850 < width ) ? 30 : 10 ) + 'px',
'margin-top': '0'
});
}
}
return $( 'a.thickbox' ).each( function() {
var href = $( this ).attr( 'href' );
if ( ! href ) {
return;
}
href = href.replace( /&width=[0-9]+/g, '' );
href = href.replace( /&height=[0-9]+/g, '' );
$(this).attr( 'href', href + '&width=' + W + '&height=' + ( H ) );
});
};
$( window ).resize( function() {
tb_position();
});
$('.plugins').on( 'click', 'a.thickbox', function() {
tb_click.call(this);
$('#TB_title').css({'background-color':'#222','color':'#cfcfcf'});
$('#TB_ajaxWindowTitle').html('<strong>' + plugininstallL10n.plugin_information + '</strong> ' + $(this).attr('title') );
return false;
});
/* Plugin install related JS*/
$( '#plugin-information-tabs a' ).click( function( event ) {
var tab = $( this ).attr( 'name' );
event.preventDefault();
//Flip the tab
$( '#plugin-information-tabs a.current' ).removeClass( 'current' );
$( this ).addClass( 'current' );
//Flip the content.
$( '#section-holder div.section' ).hide(); //Hide 'em all
$( '#section-' + tab ).show();
});
$( 'a.install-now' ).click( function() {
return confirm( plugininstallL10n.ays );
});
});
| 01-wordpress-paypal | trunk/wp-admin/js/plugin-install.js | JavaScript | gpl3 | 1,874 |
/* global deleteUserSetting, setUserSetting, switchEditors, tinymce, tinyMCEPreInit */
/**
* Distraction Free Writing
* (wp-fullscreen)
*
* Access the API globally using the window.wp.editor.fullscreen variable.
*/
( function( $, window ) {
var api, ps, s, toggleUI, uiTimer, PubSub,
uiScrollTop = 0,
transitionend = 'transitionend webkitTransitionEnd',
$body = $( document.body ),
$document = $( document );
/**
* PubSub
*
* A lightweight publish/subscribe implementation.
*
* @access private
*/
PubSub = function() {
this.topics = {};
this.subscribe = function( topic, callback ) {
if ( ! this.topics[ topic ] )
this.topics[ topic ] = [];
this.topics[ topic ].push( callback );
return callback;
};
this.unsubscribe = function( topic, callback ) {
var i, l,
topics = this.topics[ topic ];
if ( ! topics )
return callback || [];
// Clear matching callbacks
if ( callback ) {
for ( i = 0, l = topics.length; i < l; i++ ) {
if ( callback == topics[i] )
topics.splice( i, 1 );
}
return callback;
// Clear all callbacks
} else {
this.topics[ topic ] = [];
return topics;
}
};
this.publish = function( topic, args ) {
var i, l, broken,
topics = this.topics[ topic ];
if ( ! topics )
return;
args = args || [];
for ( i = 0, l = topics.length; i < l; i++ ) {
broken = ( topics[i].apply( null, args ) === false || broken );
}
return ! broken;
};
};
// Initialize the fullscreen/api object
api = {};
// Create the PubSub (publish/subscribe) interface.
ps = api.pubsub = new PubSub();
s = api.settings = { // Settings
visible: false,
mode: 'tinymce',
id: '',
title_id: '',
timer: 0,
toolbar_shown: false
};
function _hideUI() {
$body.removeClass('wp-dfw-show-ui');
}
/**
* toggleUI
*
* Toggle the CSS class to show/hide the toolbar, borders and statusbar.
*/
toggleUI = api.toggleUI = function( show ) {
clearTimeout( uiTimer );
if ( ! $body.hasClass('wp-dfw-show-ui') || show === 'show' ) {
$body.addClass('wp-dfw-show-ui');
} else if ( show !== 'autohide' ) {
$body.removeClass('wp-dfw-show-ui');
}
if ( show === 'autohide' ) {
uiTimer = setTimeout( _hideUI, 2000 );
}
};
function resetCssPosition( add ) {
s.$dfwWrap.parents().each( function( i, parent ) {
var cssPosition, $parent = $(parent);
if ( add ) {
if ( parent.style.position ) {
$parent.data( 'wp-dfw-css-position', parent.style.position );
}
$parent.css( 'position', 'static' );
} else {
cssPosition = $parent.data( 'wp-dfw-css-position' );
cssPosition = cssPosition || '';
$parent.css( 'position', cssPosition );
}
if ( parent.nodeName === 'BODY' ) {
return false;
}
});
}
/**
* on()
*
* Turns fullscreen on.
*
* @param string mode Optional. Switch to the given mode before opening.
*/
api.on = function() {
var id, $dfwWrap, titleId;
if ( s.visible ) {
return;
}
if ( ! s.$fullscreenFader ) {
api.ui.init();
}
// Settings can be added or changed by defining "wp_fullscreen_settings" JS object.
if ( typeof window.wp_fullscreen_settings === 'object' )
$.extend( s, window.wp_fullscreen_settings );
id = s.id || window.wpActiveEditor;
if ( ! id ) {
if ( s.hasTinymce ) {
id = tinymce.activeEditor.id;
} else {
return;
}
}
s.id = id;
$dfwWrap = s.$dfwWrap = $( '#wp-' + id + '-wrap' );
if ( ! $dfwWrap.length ) {
return;
}
s.$dfwTextarea = $( '#' + id );
s.$editorContainer = $dfwWrap.find( '.wp-editor-container' );
uiScrollTop = $document.scrollTop();
if ( s.hasTinymce ) {
s.editor = tinymce.get( id );
}
if ( s.editor && ! s.editor.isHidden() ) {
s.origHeight = $( '#' + id + '_ifr' ).height();
s.mode = 'tinymce';
} else {
s.origHeight = s.$dfwTextarea.height();
s.mode = 'html';
}
// Try to find title field
if ( typeof window.adminpage !== 'undefined' &&
( window.adminpage === 'post-php' || window.adminpage === 'post-new-php' ) ) {
titleId = 'title';
} else {
titleId = id + '-title';
}
s.$dfwTitle = $( '#' + titleId );
if ( ! s.$dfwTitle.length ) {
s.$dfwTitle = null;
}
api.ui.fade( 'show', 'showing', 'shown' );
};
/**
* off()
*
* Turns fullscreen off.
*/
api.off = function() {
if ( ! s.visible )
return;
api.ui.fade( 'hide', 'hiding', 'hidden' );
};
/**
* switchmode()
*
* @return string - The current mode.
*
* @param string to - The fullscreen mode to switch to.
* @event switchMode
* @eventparam string to - The new mode.
* @eventparam string from - The old mode.
*/
api.switchmode = function( to ) {
var from = s.mode;
if ( ! to || ! s.visible || ! s.hasTinymce || typeof switchEditors === 'undefined' ) {
return from;
}
// Don't switch if the mode is the same.
if ( from == to )
return from;
if ( to === 'tinymce' && ! s.editor ) {
s.editor = tinymce.get( s.id );
if ( ! s.editor && typeof tinyMCEPreInit !== 'undefined' &&
tinyMCEPreInit.mceInit && tinyMCEPreInit.mceInit[ s.id ] ) {
// If the TinyMCE instance hasn't been created, set the "wp_fulscreen" flag on creating it
tinyMCEPreInit.mceInit[ s.id ].wp_fullscreen = true;
}
}
s.mode = to;
switchEditors.go( s.id, to );
api.refreshButtons( true );
if ( to === 'html' ) {
setTimeout( api.resizeTextarea, 200 );
}
return to;
};
/**
* General
*/
api.save = function() {
var $hidden = $('#hiddenaction'),
oldVal = $hidden.val(),
$spinner = $('#wp-fullscreen-save .spinner'),
$saveMessage = $('#wp-fullscreen-save .wp-fullscreen-saved-message'),
$errorMessage = $('#wp-fullscreen-save .wp-fullscreen-error-message');
$spinner.show();
$errorMessage.hide();
$saveMessage.hide();
$hidden.val('wp-fullscreen-save-post');
if ( s.editor && ! s.editor.isHidden() ) {
s.editor.save();
}
$.ajax({
url: window.ajaxurl,
type: 'post',
data: $('form#post').serialize(),
dataType: 'json'
}).done( function( response ) {
$spinner.hide();
if ( response && response.success ) {
$saveMessage.show();
setTimeout( function() {
$saveMessage.fadeOut(300);
}, 3000 );
if ( response.data && response.data.last_edited ) {
$('#wp-fullscreen-save input').attr( 'title', response.data.last_edited );
}
} else {
$errorMessage.show();
}
}).fail( function() {
$spinner.hide();
$errorMessage.show();
});
$hidden.val( oldVal );
};
api.dfwWidth = function( pixels, total ) {
var width;
if ( pixels && pixels.toString().indexOf('%') !== -1 ) {
s.$editorContainer.css( 'width', pixels );
s.$statusbar.css( 'width', pixels );
if ( s.$dfwTitle ) {
s.$dfwTitle.css( 'width', pixels );
}
return;
}
if ( ! pixels ) {
// Reset to theme width
width = $('#wp-fullscreen-body').data('theme-width') || 800;
s.$editorContainer.width( width );
s.$statusbar.width( width );
if ( s.$dfwTitle ) {
s.$dfwTitle.width( width - 16 );
}
deleteUserSetting('dfw_width');
return;
}
if ( total ) {
width = pixels;
} else {
width = s.$editorContainer.width();
width += pixels;
}
if ( width < 200 || width > 1200 ) {
// sanity check
return;
}
s.$editorContainer.width( width );
s.$statusbar.width( width );
if ( s.$dfwTitle ) {
s.$dfwTitle.width( width - 16 );
}
setUserSetting( 'dfw_width', width );
};
// This event occurs before the overlay blocks the UI.
ps.subscribe( 'show', function() {
var title = $('#last-edit').text();
if ( title ) {
$('#wp-fullscreen-save input').attr( 'title', title );
}
});
// This event occurs while the overlay blocks the UI.
ps.subscribe( 'showing', function() {
$body.addClass( 'wp-fullscreen-active' );
s.$dfwWrap.addClass( 'wp-fullscreen-wrap' );
if ( s.$dfwTitle ) {
s.$dfwTitle.after( '<span id="wp-fullscreen-title-placeholder">' );
s.$dfwWrap.prepend( s.$dfwTitle.addClass('wp-fullscreen-title') );
}
api.refreshButtons();
resetCssPosition( true );
$('#wpadminbar').hide();
// Show the UI for 2 sec. when opening
toggleUI('autohide');
api.bind_resize();
if ( s.editor ) {
s.editor.execCommand( 'wpFullScreenOn' );
}
if ( 'ontouchstart' in window ) {
api.dfwWidth( '90%' );
} else {
api.dfwWidth( $( '#wp-fullscreen-body' ).data('dfw-width') || 800, true );
}
// scroll to top so the user is not disoriented
scrollTo(0, 0);
});
// This event occurs after the overlay unblocks the UI
ps.subscribe( 'shown', function() {
s.visible = true;
if ( s.editor && ! s.editor.isHidden() ) {
s.editor.execCommand( 'wpAutoResize' );
} else {
api.resizeTextarea( 'force' );
}
});
ps.subscribe( 'hide', function() { // This event occurs before the overlay blocks DFW.
$document.unbind( '.fullscreen' );
s.$dfwTextarea.unbind('.wp-dfw-resize');
});
ps.subscribe( 'hiding', function() { // This event occurs while the overlay blocks the DFW UI.
$body.removeClass( 'wp-fullscreen-active' );
if ( s.$dfwTitle ) {
$( '#wp-fullscreen-title-placeholder' ).before( s.$dfwTitle.removeClass('wp-fullscreen-title').css( 'width', '' ) ).remove();
}
s.$dfwWrap.removeClass( 'wp-fullscreen-wrap' );
s.$editorContainer.css( 'width', '' );
s.$dfwTextarea.add( '#' + s.id + '_ifr' ).height( s.origHeight );
if ( s.editor ) {
s.editor.execCommand( 'wpFullScreenOff' );
}
resetCssPosition( false );
window.scrollTo( 0, uiScrollTop );
$('#wpadminbar').show();
});
// This event occurs after DFW is removed.
ps.subscribe( 'hidden', function() {
s.visible = false;
});
api.refreshButtons = function( fade ) {
if ( s.mode === 'html' ) {
$('#wp-fullscreen-mode-bar').removeClass('wp-tmce-mode').addClass('wp-html-mode')
.find('a').removeClass( 'active' ).filter('.wp-fullscreen-mode-html').addClass( 'active' );
if ( fade ) {
$('#wp-fullscreen-button-bar').fadeOut( 150, function(){
$(this).addClass('wp-html-mode').fadeIn( 150 );
});
} else {
$('#wp-fullscreen-button-bar').addClass('wp-html-mode');
}
} else if ( s.mode === 'tinymce' ) {
$('#wp-fullscreen-mode-bar').removeClass('wp-html-mode').addClass('wp-tmce-mode')
.find('a').removeClass( 'active' ).filter('.wp-fullscreen-mode-tinymce').addClass( 'active' );
if ( fade ) {
$('#wp-fullscreen-button-bar').fadeOut( 150, function(){
$(this).removeClass('wp-html-mode').fadeIn( 150 );
});
} else {
$('#wp-fullscreen-button-bar').removeClass('wp-html-mode');
}
}
};
/**
* UI Elements
*
* Used for transitioning between states.
*/
api.ui = {
init: function() {
var toolbar;
s.toolbar = toolbar = $('#fullscreen-topbar');
s.$fullscreenFader = $('#fullscreen-fader');
s.$statusbar = $('#wp-fullscreen-status');
s.hasTinymce = typeof tinymce !== 'undefined';
if ( ! s.hasTinymce )
$('#wp-fullscreen-mode-bar').hide();
$document.keyup( function(e) {
var c = e.keyCode || e.charCode, modKey;
if ( ! s.visible ) {
return;
}
if ( navigator.platform && navigator.platform.indexOf('Mac') !== -1 ) {
modKey = e.ctrlKey; // Ctrl key for Mac
} else {
modKey = e.altKey; // Alt key for Win & Linux
}
if ( modKey && ( 61 === c || 107 === c || 187 === c ) ) { // +
api.dfwWidth( 25 );
e.preventDefault();
}
if ( modKey && ( 45 === c || 109 === c || 189 === c ) ) { // -
api.dfwWidth( -25 );
e.preventDefault();
}
if ( modKey && 48 === c ) { // 0
api.dfwWidth( 0 );
e.preventDefault();
}
});
$document.on( 'keydown.wp-fullscreen', function( event ) {
if ( 27 === event.which && s.visible ) { // Esc
api.off();
event.stopImmediatePropagation();
}
});
if ( 'ontouchstart' in window ) {
$body.addClass('wp-dfw-touch');
}
toolbar.on( 'mouseenter', function() {
toggleUI('show');
}).on( 'mouseleave', function() {
toggleUI('autohide');
});
// Bind buttons
$('#wp-fullscreen-buttons').on( 'click.wp-fullscreen', 'button', function( event ) {
var command = event.currentTarget.id ? event.currentTarget.id.substr(6) : null;
if ( s.editor && 'tinymce' === s.mode ) {
switch( command ) {
case 'bold':
s.editor.execCommand('Bold');
break;
case 'italic':
s.editor.execCommand('Italic');
break;
case 'bullist':
s.editor.execCommand('InsertUnorderedList');
break;
case 'numlist':
s.editor.execCommand('InsertOrderedList');
break;
case 'link':
s.editor.execCommand('WP_Link');
break;
case 'unlink':
s.editor.execCommand('unlink');
break;
case 'help':
s.editor.execCommand('WP_Help');
break;
case 'blockquote':
s.editor.execCommand('mceBlockQuote');
break;
}
} else if ( command === 'link' && window.wpLink ) {
window.wpLink.open();
}
if ( command === 'wp-media-library' && typeof wp !== 'undefined' && wp.media && wp.media.editor ) {
wp.media.editor.open( s.id );
}
});
},
fade: function( before, during, after ) {
if ( ! s.$fullscreenFader ) {
api.ui.init();
}
// If any callback bound to before returns false, bail.
if ( before && ! ps.publish( before ) ) {
return;
}
api.fade.In( s.$fullscreenFader, 200, function() {
if ( during ) {
ps.publish( during );
}
api.fade.Out( s.$fullscreenFader, 200, function() {
if ( after ) {
ps.publish( after );
}
});
});
}
};
api.fade = {
// Sensitivity to allow browsers to render the blank element before animating.
sensitivity: 100,
In: function( element, speed, callback, stop ) {
callback = callback || $.noop;
speed = speed || 400;
stop = stop || false;
if ( api.fade.transitions ) {
if ( element.is(':visible') ) {
element.addClass( 'fade-trigger' );
return element;
}
element.show();
element.first().one( transitionend, function() {
callback();
});
setTimeout( function() { element.addClass( 'fade-trigger' ); }, this.sensitivity );
} else {
if ( stop ) {
element.stop();
}
element.css( 'opacity', 1 );
element.first().fadeIn( speed, callback );
if ( element.length > 1 ) {
element.not(':first').fadeIn( speed );
}
}
return element;
},
Out: function( element, speed, callback, stop ) {
callback = callback || $.noop;
speed = speed || 400;
stop = stop || false;
if ( ! element.is(':visible') ) {
return element;
}
if ( api.fade.transitions ) {
element.first().one( transitionend, function() {
if ( element.hasClass('fade-trigger') ) {
return;
}
element.hide();
callback();
});
setTimeout( function() { element.removeClass( 'fade-trigger' ); }, this.sensitivity );
} else {
if ( stop ) {
element.stop();
}
element.first().fadeOut( speed, callback );
if ( element.length > 1 ) {
element.not(':first').fadeOut( speed );
}
}
return element;
},
// Check if the browser supports CSS 3.0 transitions
transitions: ( function() {
var style = document.documentElement.style;
return ( typeof style.WebkitTransition === 'string' ||
typeof style.MozTransition === 'string' ||
typeof style.OTransition === 'string' ||
typeof style.transition === 'string' );
})()
};
/**
* Resize API
*
* Automatically updates textarea height.
*/
api.bind_resize = function() {
s.$dfwTextarea.on( 'keydown.wp-dfw-resize click.wp-dfw-resize paste.wp-dfw-resize', function() {
api.resizeTextarea();
});
};
api.resizeTextarea = function() {
var node = s.$dfwTextarea[0];
if ( node.scrollHeight > node.clientHeight ) {
node.style.height = node.scrollHeight + 50 + 'px';
}
};
// Export
window.wp = window.wp || {};
window.wp.editor = window.wp.editor || {};
window.wp.editor.fullscreen = api;
})( jQuery, window );
| 01-wordpress-paypal | trunk/wp-admin/js/wp-fullscreen.js | JavaScript | gpl3 | 16,167 |
/* global tinymce, QTags */
// send html to the post editor
var wpActiveEditor, send_to_editor;
send_to_editor = function( html ) {
var editor,
hasTinymce = typeof tinymce !== 'undefined',
hasQuicktags = typeof QTags !== 'undefined';
if ( ! wpActiveEditor ) {
if ( hasTinymce && tinymce.activeEditor ) {
editor = tinymce.activeEditor;
wpActiveEditor = editor.id;
} else if ( ! hasQuicktags ) {
return false;
}
} else if ( hasTinymce ) {
editor = tinymce.get( wpActiveEditor );
}
if ( editor && ! editor.isHidden() ) {
editor.execCommand( 'mceInsertContent', false, html );
} else if ( hasQuicktags ) {
QTags.insertContent( html );
} else {
document.getElementById( wpActiveEditor ).value += html;
}
// If the old thickbox remove function exists, call it
if ( window.tb_remove ) {
try { window.tb_remove(); } catch( e ) {}
}
};
// thickbox settings
var tb_position;
(function($) {
tb_position = function() {
var tbWindow = $('#TB_window'),
width = $(window).width(),
H = $(window).height(),
W = ( 720 < width ) ? 720 : width,
adminbar_height = 0;
if ( $('#wpadminbar').length ) {
adminbar_height = parseInt( $('#wpadminbar').css('height'), 10 );
}
if ( tbWindow.size() ) {
tbWindow.width( W - 50 ).height( H - 45 - adminbar_height );
$('#TB_iframeContent').width( W - 50 ).height( H - 75 - adminbar_height );
tbWindow.css({'margin-left': '-' + parseInt( ( ( W - 50 ) / 2 ), 10 ) + 'px'});
if ( typeof document.body.style.maxWidth !== 'undefined' )
tbWindow.css({'top': 20 + adminbar_height + 'px', 'margin-top': '0'});
}
return $('a.thickbox').each( function() {
var href = $(this).attr('href');
if ( ! href ) return;
href = href.replace(/&width=[0-9]+/g, '');
href = href.replace(/&height=[0-9]+/g, '');
$(this).attr( 'href', href + '&width=' + ( W - 80 ) + '&height=' + ( H - 85 - adminbar_height ) );
});
};
$(window).resize(function(){ tb_position(); });
})(jQuery);
| 01-wordpress-paypal | trunk/wp-admin/js/media-upload.js | JavaScript | gpl3 | 1,984 |
window.wp = window.wp || {};
(function( $, wp ) {
wp.updates = {};
/**
* Decrement update counts throughout the various menus
*
* @param {string} updateType
*/
wp.updates.decrementCount = function( upgradeType ) {
var count, pluginCount, $elem;
$elem = $( '#wp-admin-bar-updates .ab-label' );
count = $elem.text();
count = parseInt( count, 10 ) - 1;
if ( count < 0 ) {
return;
}
$( '#wp-admin-bar-updates .ab-item' ).removeAttr( 'title' );
$elem.text( count );
$elem = $( 'a[href="update-core.php"] .update-plugins' );
$elem.each( function( index, elem ) {
elem.className = elem.className.replace( /count-\d+/, 'count-' + count );
} );
$elem.removeAttr( 'title' );
$elem.find( '.update-count' ).text( count );
if ( 'plugin' === upgradeType ) {
$elem = $( '#menu-plugins' );
pluginCount = $elem.find( '.plugin-count' ).eq(0).text();
pluginCount = parseInt( pluginCount, 10 ) - 1;
if ( count < 0 ) {
return;
}
$elem.find( '.plugin-count' ).text( pluginCount );
$elem.find( '.update-plugins' ).each( function( index, elem ) {
elem.className = elem.className.replace( /count-\d+/, 'count-' + pluginCount );
} );
}
};
$( window ).on( 'message', function( e ) {
var event = e.originalEvent,
message,
loc = document.location,
expectedOrigin = loc.protocol + '//' + loc.hostname;
if ( event.origin !== expectedOrigin ) {
return;
}
message = $.parseJSON( event.data );
if ( typeof message.action === 'undefined' || message.action !== 'decrementUpdateCount' ) {
return;
}
wp.updates.decrementCount( message.upgradeType );
} );
})( jQuery, window.wp );
| 01-wordpress-paypal | trunk/wp-admin/js/updates.js | JavaScript | gpl3 | 1,666 |
/* global setUserSetting, ajaxurl, commonL10n, alert, confirm, pagenow */
var showNotice, adminMenu, columns, validateForm, screenMeta;
( function( $, window, undefined ) {
// Removed in 3.3.
// (perhaps) needed for back-compat
adminMenu = {
init : function() {},
fold : function() {},
restoreMenuState : function() {},
toggle : function() {},
favorites : function() {}
};
// show/hide/save table columns
columns = {
init : function() {
var that = this;
$('.hide-column-tog', '#adv-settings').click( function() {
var $t = $(this), column = $t.val();
if ( $t.prop('checked') )
that.checked(column);
else
that.unchecked(column);
columns.saveManageColumnsState();
});
},
saveManageColumnsState : function() {
var hidden = this.hidden();
$.post(ajaxurl, {
action: 'hidden-columns',
hidden: hidden,
screenoptionnonce: $('#screenoptionnonce').val(),
page: pagenow
});
},
checked : function(column) {
$('.column-' + column).show();
this.colSpanChange(+1);
},
unchecked : function(column) {
$('.column-' + column).hide();
this.colSpanChange(-1);
},
hidden : function() {
return $('.manage-column').filter(':hidden').map(function() { return this.id; }).get().join(',');
},
useCheckboxesForHidden : function() {
this.hidden = function(){
return $('.hide-column-tog').not(':checked').map(function() {
var id = this.id;
return id.substring( id, id.length - 5 );
}).get().join(',');
};
},
colSpanChange : function(diff) {
var $t = $('table').find('.colspanchange'), n;
if ( !$t.length )
return;
n = parseInt( $t.attr('colspan'), 10 ) + diff;
$t.attr('colspan', n.toString());
}
};
$(document).ready(function(){columns.init();});
validateForm = function( form ) {
return !$( form )
.find( '.form-required' )
.filter( function() { return $( 'input:visible', this ).val() === ''; } )
.addClass( 'form-invalid' )
.find( 'input:visible' )
.change( function() { $( this ).closest( '.form-invalid' ).removeClass( 'form-invalid' ); } )
.size();
};
// stub for doing better warnings
showNotice = {
warn : function() {
var msg = commonL10n.warnDelete || '';
if ( confirm(msg) ) {
return true;
}
return false;
},
note : function(text) {
alert(text);
}
};
screenMeta = {
element: null, // #screen-meta
toggles: null, // .screen-meta-toggle
page: null, // #wpcontent
init: function() {
this.element = $('#screen-meta');
this.toggles = $('.screen-meta-toggle a');
this.page = $('#wpcontent');
this.toggles.click( this.toggleEvent );
},
toggleEvent: function( e ) {
var panel = $( this.href.replace(/.+#/, '#') );
e.preventDefault();
if ( !panel.length )
return;
if ( panel.is(':visible') )
screenMeta.close( panel, $(this) );
else
screenMeta.open( panel, $(this) );
},
open: function( panel, link ) {
$('.screen-meta-toggle').not( link.parent() ).css('visibility', 'hidden');
panel.parent().show();
panel.slideDown( 'fast', function() {
panel.focus();
link.addClass('screen-meta-active').attr('aria-expanded', true);
});
},
close: function( panel, link ) {
panel.slideUp( 'fast', function() {
link.removeClass('screen-meta-active').attr('aria-expanded', false);
$('.screen-meta-toggle').css('visibility', '');
panel.parent().hide();
});
}
};
/**
* Help tabs.
*/
$('.contextual-help-tabs').delegate('a', 'click focus', function(e) {
var link = $(this),
panel;
e.preventDefault();
// Don't do anything if the click is for the tab already showing.
if ( link.is('.active a') )
return false;
// Links
$('.contextual-help-tabs .active').removeClass('active');
link.parent('li').addClass('active');
panel = $( link.attr('href') );
// Panels
$('.help-tab-content').not( panel ).removeClass('active').hide();
panel.addClass('active').show();
});
$(document).ready( function() {
var checks, first, last, checked, sliced, mobileEvent, transitionTimeout, focusedRowActions,
lastClicked = false,
menu = $('#adminmenu'),
pageInput = $('input.current-page'),
currentPage = pageInput.val();
// when the menu is folded, make the fly-out submenu header clickable
menu.on('click.wp-submenu-head', '.wp-submenu-head', function(e){
$(e.target).parent().siblings('a').get(0).click();
});
$('#collapse-menu').on('click.collapse-menu', function() {
var body = $( document.body ), respWidth;
// reset any compensation for submenus near the bottom of the screen
$('#adminmenu div.wp-submenu').css('margin-top', '');
if ( window.innerWidth ) {
// window.innerWidth is affected by zooming on phones
respWidth = Math.max( window.innerWidth, document.documentElement.clientWidth );
} else {
// IE < 9 doesn't support @media CSS rules
respWidth = 901;
}
if ( respWidth && respWidth < 900 ) {
if ( body.hasClass('auto-fold') ) {
body.removeClass('auto-fold').removeClass('folded');
setUserSetting('unfold', 1);
setUserSetting('mfold', 'o');
} else {
body.addClass('auto-fold');
setUserSetting('unfold', 0);
}
} else {
if ( body.hasClass('folded') ) {
body.removeClass('folded');
setUserSetting('mfold', 'o');
} else {
body.addClass('folded');
setUserSetting('mfold', 'f');
}
}
});
if ( 'ontouchstart' in window || /IEMobile\/[1-9]/.test(navigator.userAgent) ) { // touch screen device
// iOS Safari works with touchstart, the rest work with click
mobileEvent = /Mobile\/.+Safari/.test(navigator.userAgent) ? 'touchstart' : 'click';
// close any open submenus when touch/click is not on the menu
$(document.body).on( mobileEvent+'.wp-mobile-hover', function(e) {
if ( menu.data('wp-responsive') ) {
return;
}
if ( ! $(e.target).closest('#adminmenu').length ) {
menu.find('li.wp-has-submenu.opensub').removeClass('opensub');
}
});
menu.find('a.wp-has-submenu').on( mobileEvent+'.wp-mobile-hover', function(e) {
var b, h, o, f, menutop, wintop, maxtop,
el = $(this),
parent = el.parent(),
m = parent.find('.wp-submenu');
if ( menu.data('wp-responsive') ) {
return;
}
// Show the sub instead of following the link if:
// - the submenu is not open
// - the submenu is not shown inline or the menu is not folded
if ( !parent.hasClass('opensub') && ( !parent.hasClass('wp-menu-open') || parent.width() < 40 ) ) {
e.preventDefault();
menutop = parent.offset().top;
wintop = $(window).scrollTop();
maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar
b = menutop + m.height() + 1; // Bottom offset of the menu
h = $('#wpwrap').height(); // Height of the entire page
o = 60 + b - h;
f = $(window).height() + wintop - 50; // The fold
if ( f < (b - o) ) {
o = b - f;
}
if ( o > maxtop ) {
o = maxtop;
}
if ( o > 1 ) {
m.css('margin-top', '-'+o+'px');
} else {
m.css('margin-top', '');
}
menu.find('li.opensub').removeClass('opensub');
parent.addClass('opensub');
}
});
}
menu.find('li.wp-has-submenu').hoverIntent({
over: function() {
var b, h, o, f, m = $(this).find('.wp-submenu'), menutop, wintop, maxtop, top = parseInt( m.css('top'), 10 );
if ( isNaN(top) || top > -5 ) { // meaning the submenu is visible
return;
}
if ( menu.data('wp-responsive') ) {
// The menu is in responsive mode, bail
return;
}
menutop = $(this).offset().top;
wintop = $(window).scrollTop();
maxtop = menutop - wintop - 30; // max = make the top of the sub almost touch admin bar
b = menutop + m.height() + 1; // Bottom offset of the menu
h = $('#wpwrap').height(); // Height of the entire page
o = 60 + b - h;
f = $(window).height() + wintop - 15; // The fold
if ( f < (b - o) ) {
o = b - f;
}
if ( o > maxtop ) {
o = maxtop;
}
if ( o > 1 ) {
m.css('margin-top', '-'+o+'px');
} else {
m.css('margin-top', '');
}
menu.find('li.menu-top').removeClass('opensub');
$(this).addClass('opensub');
},
out: function(){
if ( menu.data('wp-responsive') ) {
// The menu is in responsive mode, bail
return;
}
$(this).removeClass('opensub').find('.wp-submenu').css('margin-top', '');
},
timeout: 200,
sensitivity: 7,
interval: 90
});
menu.on('focus.adminmenu', '.wp-submenu a', function(e){
if ( menu.data('wp-responsive') ) {
// The menu is in responsive mode, bail
return;
}
$(e.target).closest('li.menu-top').addClass('opensub');
}).on('blur.adminmenu', '.wp-submenu a', function(e){
if ( menu.data('wp-responsive') ) {
// The menu is in responsive mode, bail
return;
}
$(e.target).closest('li.menu-top').removeClass('opensub');
});
// Move .updated and .error alert boxes. Don't move boxes designed to be inline.
$('div.wrap h2:first').nextAll('div.updated, div.error').addClass('below-h2');
$('div.updated, div.error').not('.below-h2, .inline').insertAfter( $('div.wrap h2:first') );
// Init screen meta
screenMeta.init();
// check all checkboxes
$('tbody').children().children('.check-column').find(':checkbox').click( function(e) {
if ( 'undefined' == e.shiftKey ) { return true; }
if ( e.shiftKey ) {
if ( !lastClicked ) { return true; }
checks = $( lastClicked ).closest( 'form' ).find( ':checkbox' );
first = checks.index( lastClicked );
last = checks.index( this );
checked = $(this).prop('checked');
if ( 0 < first && 0 < last && first != last ) {
sliced = ( last > first ) ? checks.slice( first, last ) : checks.slice( last, first );
sliced.prop( 'checked', function() {
if ( $(this).closest('tr').is(':visible') )
return checked;
return false;
});
}
}
lastClicked = this;
// toggle "check all" checkboxes
var unchecked = $(this).closest('tbody').find(':checkbox').filter(':visible').not(':checked');
$(this).closest('table').children('thead, tfoot').find(':checkbox').prop('checked', function() {
return ( 0 === unchecked.length );
});
return true;
});
$('thead, tfoot').find('.check-column :checkbox').on( 'click.wp-toggle-checkboxes', function( event ) {
var $this = $(this),
$table = $this.closest( 'table' ),
controlChecked = $this.prop('checked'),
toggle = event.shiftKey || $this.data('wp-toggle');
$table.children( 'tbody' ).filter(':visible')
.children().children('.check-column').find(':checkbox')
.prop('checked', function() {
if ( $(this).is(':hidden') ) {
return false;
}
if ( toggle ) {
return ! $(this).prop( 'checked' );
} else if ( controlChecked ) {
return true;
}
return false;
});
$table.children('thead, tfoot').filter(':visible')
.children().children('.check-column').find(':checkbox')
.prop('checked', function() {
if ( toggle ) {
return false;
} else if ( controlChecked ) {
return true;
}
return false;
});
});
// Show row actions on keyboard focus of its parent container element or any other elements contained within
$( 'td.post-title, td.title, td.comment, .bookmarks td.column-name, td.blogname, td.username, .dashboard-comment-wrap' ).focusin(function(){
clearTimeout( transitionTimeout );
focusedRowActions = $(this).find( '.row-actions' );
focusedRowActions.addClass( 'visible' );
}).focusout(function(){
// Tabbing between post title and .row-actions links needs a brief pause, otherwise
// the .row-actions div gets hidden in transit in some browsers (ahem, Firefox).
transitionTimeout = setTimeout(function(){
focusedRowActions.removeClass( 'visible' );
}, 30);
});
$('#default-password-nag-no').click( function() {
setUserSetting('default_password_nag', 'hide');
$('div.default-password-nag').hide();
return false;
});
// tab in textareas
$('#newcontent').bind('keydown.wpevent_InsertTab', function(e) {
var el = e.target, selStart, selEnd, val, scroll, sel;
if ( e.keyCode == 27 ) { // escape key
$(el).data('tab-out', true);
return;
}
if ( e.keyCode != 9 || e.ctrlKey || e.altKey || e.shiftKey ) // tab key
return;
if ( $(el).data('tab-out') ) {
$(el).data('tab-out', false);
return;
}
selStart = el.selectionStart;
selEnd = el.selectionEnd;
val = el.value;
try {
this.lastKey = 9; // not a standard DOM property, lastKey is to help stop Opera tab event. See blur handler below.
} catch(err) {}
if ( document.selection ) {
el.focus();
sel = document.selection.createRange();
sel.text = '\t';
} else if ( selStart >= 0 ) {
scroll = this.scrollTop;
el.value = val.substring(0, selStart).concat('\t', val.substring(selEnd) );
el.selectionStart = el.selectionEnd = selStart + 1;
this.scrollTop = scroll;
}
if ( e.stopPropagation )
e.stopPropagation();
if ( e.preventDefault )
e.preventDefault();
});
$('#newcontent').bind('blur.wpevent_InsertTab', function() {
if ( this.lastKey && 9 == this.lastKey )
this.focus();
});
if ( pageInput.length ) {
pageInput.closest('form').submit( function() {
// Reset paging var for new filters/searches but not for bulk actions. See #17685.
if ( $('select[name="action"]').val() == -1 && $('select[name="action2"]').val() == -1 && pageInput.val() == currentPage )
pageInput.val('1');
});
}
$('.search-box input[type="search"], .search-box input[type="submit"]').mousedown(function () {
$('select[name^="action"]').val('-1');
});
// Scroll into view when focused
$('#contextual-help-link, #show-settings-link').on( 'focus.scroll-into-view', function(e){
if ( e.target.scrollIntoView )
e.target.scrollIntoView(false);
});
// Disable upload buttons until files are selected
(function(){
var button, input, form = $('form.wp-upload-form');
if ( ! form.length )
return;
button = form.find('input[type="submit"]');
input = form.find('input[type="file"]');
function toggleUploadButton() {
button.prop('disabled', '' === input.map( function() {
return $(this).val();
}).get().join(''));
}
toggleUploadButton();
input.on('change', toggleUploadButton);
})();
});
// Fire a custom jQuery event at the end of window resize
( function() {
var timeout;
function triggerEvent() {
$(document).trigger( 'wp-window-resized' );
}
function fireOnce() {
window.clearTimeout( timeout );
timeout = window.setTimeout( triggerEvent, 200 );
}
$(window).on( 'resize.wp-fire-once', fireOnce );
}());
$(document).ready( function() {
var $document = $( document ),
$window = $( window ),
$body = $( document.body ),
$adminMenuWrap = $( '#adminmenuwrap' ),
$collapseMenu = $( '#collapse-menu' ),
$wpwrap = $( '#wpwrap' ),
$adminmenu = $( '#adminmenu' ),
$overlay = $( '#wp-responsive-overlay' ),
$toolbar = $( '#wp-toolbar' ),
$toolbarPopups = $toolbar.find( 'a[aria-haspopup="true"]' ),
$sortables = $('.meta-box-sortables'),
stickyMenuActive = false,
wpResponsiveActive = false;
window.stickyMenu = {
enable: function() {
if ( ! stickyMenuActive ) {
$document.on( 'wp-window-resized.sticky-menu', $.proxy( this.update, this ) );
$collapseMenu.on( 'click.sticky-menu', $.proxy( this.update, this ) );
this.update();
stickyMenuActive = true;
}
},
disable: function() {
if ( stickyMenuActive ) {
$window.off( 'resize.sticky-menu' );
$collapseMenu.off( 'click.sticky-menu' );
$body.removeClass( 'sticky-menu' );
stickyMenuActive = false;
}
},
update: function() {
// Make the admin menu sticky if the viewport is taller than it
if ( $window.height() > $adminMenuWrap.height() + 32 ) {
if ( ! $body.hasClass( 'sticky-menu' ) ) {
$body.addClass( 'sticky-menu' );
}
} else {
if ( $body.hasClass( 'sticky-menu' ) ) {
$body.removeClass( 'sticky-menu' );
}
}
}
};
window.wpResponsive = {
init: function() {
var self = this,
scrollStart = 0;
// Modify functionality based on custom activate/deactivate event
$document.on( 'wp-responsive-activate.wp-responsive', function() {
self.activate();
}).on( 'wp-responsive-deactivate.wp-responsive', function() {
self.deactivate();
});
$( '#wp-admin-bar-menu-toggle a' ).attr( 'aria-expanded', 'false' );
// Toggle sidebar when toggle is clicked
$( '#wp-admin-bar-menu-toggle' ).on( 'click.wp-responsive', function( event ) {
event.preventDefault();
$wpwrap.toggleClass( 'wp-responsive-open' );
if ( $wpwrap.hasClass( 'wp-responsive-open' ) ) {
$(this).find('a').attr( 'aria-expanded', 'true' );
$( '#adminmenu a:first' ).focus();
} else {
$(this).find('a').attr( 'aria-expanded', 'false' );
}
} );
// Add menu events
$adminmenu.on( 'touchstart.wp-responsive', 'li.wp-has-submenu > a', function() {
scrollStart = $window.scrollTop();
}).on( 'touchend.wp-responsive click.wp-responsive', 'li.wp-has-submenu > a', function( event ) {
if ( ! $adminmenu.data('wp-responsive') ||
( event.type === 'touchend' && $window.scrollTop() !== scrollStart ) ) {
return;
}
$( this ).parent( 'li' ).toggleClass( 'selected' );
event.preventDefault();
});
self.trigger();
$document.on( 'wp-window-resized.wp-responsive', $.proxy( this.trigger, this ) );
// This needs to run later as UI Sortable may be initialized later on $(document).ready()
$window.on( 'load.wp-responsive', function() {
var width = navigator.userAgent.indexOf('AppleWebKit/') > -1 ? $window.width() : window.innerWidth;
if ( width <= 782 ) {
self.disableSortables();
}
});
},
activate: function() {
window.stickyMenu.disable();
if ( ! $body.hasClass( 'auto-fold' ) ) {
$body.addClass( 'auto-fold' );
}
$adminmenu.data( 'wp-responsive', 1 );
this.disableSortables();
},
deactivate: function() {
window.stickyMenu.enable();
$adminmenu.removeData('wp-responsive');
this.enableSortables();
},
trigger: function() {
var width;
if ( window.innerWidth ) {
// window.innerWidth is affected by zooming on phones
width = Math.max( window.innerWidth, document.documentElement.clientWidth );
} else {
// Exclude IE < 9, it doesn't support @media CSS rules
return;
}
if ( width <= 782 ) {
if ( ! wpResponsiveActive ) {
$document.trigger( 'wp-responsive-activate' );
wpResponsiveActive = true;
}
} else {
if ( wpResponsiveActive ) {
$document.trigger( 'wp-responsive-deactivate' );
wpResponsiveActive = false;
}
}
if ( width <= 480 ) {
this.enableOverlay();
} else {
this.disableOverlay();
}
},
enableOverlay: function() {
if ( $overlay.length === 0 ) {
$overlay = $( '<div id="wp-responsive-overlay"></div>' )
.insertAfter( '#wpcontent' )
.hide()
.on( 'click.wp-responsive', function() {
$toolbar.find( '.menupop.hover' ).removeClass( 'hover' );
$( this ).hide();
});
}
$toolbarPopups.on( 'click.wp-responsive', function() {
$overlay.show();
});
},
disableOverlay: function() {
$toolbarPopups.off( 'click.wp-responsive' );
$overlay.hide();
},
disableSortables: function() {
if ( $sortables.length ) {
try {
$sortables.sortable('disable');
} catch(e) {}
}
},
enableSortables: function() {
if ( $sortables.length ) {
try {
$sortables.sortable('enable');
} catch(e) {}
}
}
};
window.stickyMenu.enable();
window.wpResponsive.init();
});
// make Windows 8 devices playing along nicely
(function(){
if ( '-ms-user-select' in document.documentElement.style && navigator.userAgent.match(/IEMobile\/10\.0/) ) {
var msViewportStyle = document.createElement( 'style' );
msViewportStyle.appendChild(
document.createTextNode( '@-ms-viewport{width:auto!important}' )
);
document.getElementsByTagName( 'head' )[0].appendChild( msViewportStyle );
}
})();
}( jQuery, window ));
| 01-wordpress-paypal | trunk/wp-admin/js/common.js | JavaScript | gpl3 | 19,972 |
/*!
* Farbtastic: jQuery color picker plug-in v1.3u
*
* Licensed under the GPL license:
* http://www.gnu.org/licenses/gpl.html
*/
(function($) {
$.fn.farbtastic = function (options) {
$.farbtastic(this, options);
return this;
};
$.farbtastic = function (container, callback) {
var container = $(container).get(0);
return container.farbtastic || (container.farbtastic = new $._farbtastic(container, callback));
};
$._farbtastic = function (container, callback) {
// Store farbtastic object
var fb = this;
// Insert markup
$(container).html('<div class="farbtastic"><div class="color"></div><div class="wheel"></div><div class="overlay"></div><div class="h-marker marker"></div><div class="sl-marker marker"></div></div>');
var e = $('.farbtastic', container);
fb.wheel = $('.wheel', container).get(0);
// Dimensions
fb.radius = 84;
fb.square = 100;
fb.width = 194;
// Fix background PNGs in IE6
if (navigator.appVersion.match(/MSIE [0-6]\./)) {
$('*', e).each(function () {
if (this.currentStyle.backgroundImage != 'none') {
var image = this.currentStyle.backgroundImage;
image = this.currentStyle.backgroundImage.substring(5, image.length - 2);
$(this).css({
'backgroundImage': 'none',
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')"
});
}
});
}
/**
* Link to the given element(s) or callback.
*/
fb.linkTo = function (callback) {
// Unbind previous nodes
if (typeof fb.callback == 'object') {
$(fb.callback).unbind('keyup', fb.updateValue);
}
// Reset color
fb.color = null;
// Bind callback or elements
if (typeof callback == 'function') {
fb.callback = callback;
}
else if (typeof callback == 'object' || typeof callback == 'string') {
fb.callback = $(callback);
fb.callback.bind('keyup', fb.updateValue);
if (fb.callback.get(0).value) {
fb.setColor(fb.callback.get(0).value);
}
}
return this;
};
fb.updateValue = function (event) {
if (this.value && this.value != fb.color) {
fb.setColor(this.value);
}
};
/**
* Change color with HTML syntax #123456
*/
fb.setColor = function (color) {
var unpack = fb.unpack(color);
if (fb.color != color && unpack) {
fb.color = color;
fb.rgb = unpack;
fb.hsl = fb.RGBToHSL(fb.rgb);
fb.updateDisplay();
}
return this;
};
/**
* Change color with HSL triplet [0..1, 0..1, 0..1]
*/
fb.setHSL = function (hsl) {
fb.hsl = hsl;
fb.rgb = fb.HSLToRGB(hsl);
fb.color = fb.pack(fb.rgb);
fb.updateDisplay();
return this;
};
/////////////////////////////////////////////////////
/**
* Retrieve the coordinates of the given event relative to the center
* of the widget.
*/
fb.widgetCoords = function (event) {
var offset = $(fb.wheel).offset();
return { x: (event.pageX - offset.left) - fb.width / 2, y: (event.pageY - offset.top) - fb.width / 2 };
};
/**
* Mousedown handler
*/
fb.mousedown = function (event) {
// Capture mouse
if (!document.dragging) {
$(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup);
document.dragging = true;
}
// Check which area is being dragged
var pos = fb.widgetCoords(event);
fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square;
// Process
fb.mousemove(event);
return false;
};
/**
* Mousemove handler
*/
fb.mousemove = function (event) {
// Get coordinates relative to color picker center
var pos = fb.widgetCoords(event);
// Set new HSL parameters
if (fb.circleDrag) {
var hue = Math.atan2(pos.x, -pos.y) / 6.28;
if (hue < 0) hue += 1;
fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]);
}
else {
var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5));
var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5));
fb.setHSL([fb.hsl[0], sat, lum]);
}
return false;
};
/**
* Mouseup handler
*/
fb.mouseup = function () {
// Uncapture mouse
$(document).unbind('mousemove', fb.mousemove);
$(document).unbind('mouseup', fb.mouseup);
document.dragging = false;
};
/**
* Update the markers and styles
*/
fb.updateDisplay = function () {
// Markers
var angle = fb.hsl[0] * 6.28;
$('.h-marker', e).css({
left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px',
top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px'
});
$('.sl-marker', e).css({
left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px',
top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px'
});
// Saturation/Luminance gradient
$('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5])));
// Linked elements or callback
if (typeof fb.callback == 'object') {
// Set background/foreground color
$(fb.callback).css({
backgroundColor: fb.color,
color: fb.hsl[2] > 0.5 ? '#000' : '#fff'
});
// Change linked value
$(fb.callback).each(function() {
if (this.value && this.value != fb.color) {
this.value = fb.color;
}
});
}
else if (typeof fb.callback == 'function') {
fb.callback.call(fb, fb.color);
}
};
/* Various color utility functions */
fb.pack = function (rgb) {
var r = Math.round(rgb[0] * 255);
var g = Math.round(rgb[1] * 255);
var b = Math.round(rgb[2] * 255);
return '#' + (r < 16 ? '0' : '') + r.toString(16) +
(g < 16 ? '0' : '') + g.toString(16) +
(b < 16 ? '0' : '') + b.toString(16);
};
fb.unpack = function (color) {
if (color.length == 7) {
return [parseInt('0x' + color.substring(1, 3)) / 255,
parseInt('0x' + color.substring(3, 5)) / 255,
parseInt('0x' + color.substring(5, 7)) / 255];
}
else if (color.length == 4) {
return [parseInt('0x' + color.substring(1, 2)) / 15,
parseInt('0x' + color.substring(2, 3)) / 15,
parseInt('0x' + color.substring(3, 4)) / 15];
}
};
fb.HSLToRGB = function (hsl) {
var m1, m2, r, g, b;
var h = hsl[0], s = hsl[1], l = hsl[2];
m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s;
m1 = l * 2 - m2;
return [this.hueToRGB(m1, m2, h+0.33333),
this.hueToRGB(m1, m2, h),
this.hueToRGB(m1, m2, h-0.33333)];
};
fb.hueToRGB = function (m1, m2, h) {
h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h);
if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;
if (h * 2 < 1) return m2;
if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6;
return m1;
};
fb.RGBToHSL = function (rgb) {
var min, max, delta, h, s, l;
var r = rgb[0], g = rgb[1], b = rgb[2];
min = Math.min(r, Math.min(g, b));
max = Math.max(r, Math.max(g, b));
delta = max - min;
l = (min + max) / 2;
s = 0;
if (l > 0 && l < 1) {
s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l));
}
h = 0;
if (delta > 0) {
if (max == r && max != g) h += (g - b) / delta;
if (max == g && max != b) h += (2 + (b - r) / delta);
if (max == b && max != r) h += (4 + (r - g) / delta);
h /= 6;
}
return [h, s, l];
};
// Install mousedown handler (the others are set on the document on-demand)
$('*', e).mousedown(fb.mousedown);
// Init color
fb.setColor('#000000');
// Set linked elements/callback
if (callback) {
fb.linkTo(callback);
}
};
})(jQuery); | 01-wordpress-paypal | trunk/wp-admin/js/farbtastic.js | JavaScript | gpl3 | 7,689 |
/* global zxcvbn */
window.wp = window.wp || {};
var passwordStrength;
(function($){
wp.passwordStrength = {
/**
* Determine the strength of a given password
*
* @param string password1 The password
* @param array blacklist An array of words that will lower the entropy of the password
* @param string password2 The confirmed password
*/
meter : function( password1, blacklist, password2 ) {
if ( ! $.isArray( blacklist ) )
blacklist = [ blacklist.toString() ];
if (password1 != password2 && password2 && password2.length > 0)
return 5;
var result = zxcvbn( password1, blacklist );
return result.score;
},
/**
* Builds an array of data that should be penalized, because it would lower the entropy of a password if it were used
*
* @return array The array of data to be blacklisted
*/
userInputBlacklist : function() {
var i, userInputFieldsLength, rawValuesLength, currentField,
rawValues = [],
blacklist = [],
userInputFields = [ 'user_login', 'first_name', 'last_name', 'nickname', 'display_name', 'email', 'url', 'description', 'weblog_title', 'admin_email' ];
// Collect all the strings we want to blacklist
rawValues.push( document.title );
rawValues.push( document.URL );
userInputFieldsLength = userInputFields.length;
for ( i = 0; i < userInputFieldsLength; i++ ) {
currentField = $( '#' + userInputFields[ i ] );
if ( 0 === currentField.length ) {
continue;
}
rawValues.push( currentField[0].defaultValue );
rawValues.push( currentField.val() );
}
// Strip out non-alphanumeric characters and convert each word to an individual entry
rawValuesLength = rawValues.length;
for ( i = 0; i < rawValuesLength; i++ ) {
if ( rawValues[ i ] ) {
blacklist = blacklist.concat( rawValues[ i ].replace( /\W/g, ' ' ).split( ' ' ) );
}
}
// Remove empty values, short words, and duplicates. Short words are likely to cause many false positives.
blacklist = $.grep( blacklist, function( value, key ) {
if ( '' === value || 4 > value.length ) {
return false;
}
return $.inArray( value, blacklist ) === key;
});
return blacklist;
}
};
// Backwards compatibility.
passwordStrength = wp.passwordStrength.meter;
})(jQuery); | 01-wordpress-paypal | trunk/wp-admin/js/password-strength-meter.js | JavaScript | gpl3 | 2,314 |
/* global pagenow, ajaxurl, postboxes, wpActiveEditor:true */
var ajaxWidgets, ajaxPopulateWidgets, quickPressLoad;
jQuery(document).ready( function($) {
var welcomePanel = $( '#welcome-panel' ),
welcomePanelHide = $('#wp_welcome_panel-hide'),
updateWelcomePanel;
updateWelcomePanel = function( visible ) {
$.post( ajaxurl, {
action: 'update-welcome-panel',
visible: visible,
welcomepanelnonce: $( '#welcomepanelnonce' ).val()
});
};
if ( welcomePanel.hasClass('hidden') && welcomePanelHide.prop('checked') ) {
welcomePanel.removeClass('hidden');
}
$('.welcome-panel-close, .welcome-panel-dismiss a', welcomePanel).click( function(e) {
e.preventDefault();
welcomePanel.addClass('hidden');
updateWelcomePanel( 0 );
$('#wp_welcome_panel-hide').prop('checked', false);
});
welcomePanelHide.click( function() {
welcomePanel.toggleClass('hidden', ! this.checked );
updateWelcomePanel( this.checked ? 1 : 0 );
});
// These widgets are sometimes populated via ajax
ajaxWidgets = ['dashboard_primary'];
ajaxPopulateWidgets = function(el) {
function show(i, id) {
var p, e = $('#' + id + ' div.inside:visible').find('.widget-loading');
if ( e.length ) {
p = e.parent();
setTimeout( function(){
p.load( ajaxurl + '?action=dashboard-widgets&widget=' + id + '&pagenow=' + pagenow, '', function() {
p.hide().slideDown('normal', function(){
$(this).css('display', '');
});
});
}, i * 500 );
}
}
if ( el ) {
el = el.toString();
if ( $.inArray(el, ajaxWidgets) !== -1 ) {
show(0, el);
}
} else {
$.each( ajaxWidgets, show );
}
};
ajaxPopulateWidgets();
postboxes.add_postbox_toggles(pagenow, { pbshow: ajaxPopulateWidgets } );
/* QuickPress */
quickPressLoad = function() {
var act = $('#quickpost-action'), t;
t = $('#quick-press').submit( function() {
$('#dashboard_quick_press #publishing-action .spinner').show();
$('#quick-press .submit input[type="submit"], #quick-press .submit input[type="reset"]').prop('disabled', true);
$.post( t.attr( 'action' ), t.serializeArray(), function( data ) {
// Replace the form, and prepend the published post.
$('#dashboard_quick_press .inside').html( data );
$('#quick-press').removeClass('initial-form');
quickPressLoad();
highlightLatestPost();
$('#title').focus();
});
function highlightLatestPost () {
var latestPost = $('.drafts ul li').first();
latestPost.css('background', '#fffbe5');
setTimeout(function () {
latestPost.css('background', 'none');
}, 1000);
}
return false;
} );
$('#publish').click( function() { act.val( 'post-quickpress-publish' ); } );
$('#title, #tags-input, #content').each( function() {
var input = $(this), prompt = $('#' + this.id + '-prompt-text');
if ( '' === this.value ) {
prompt.removeClass('screen-reader-text');
}
prompt.click( function() {
$(this).addClass('screen-reader-text');
input.focus();
});
input.blur( function() {
if ( '' === this.value ) {
prompt.removeClass('screen-reader-text');
}
});
input.focus( function() {
prompt.addClass('screen-reader-text');
});
});
$('#quick-press').on( 'click focusin', function() {
wpActiveEditor = 'content';
});
autoResizeTextarea();
};
quickPressLoad();
$( '.meta-box-sortables' ).sortable( 'option', 'containment', 'document' );
function autoResizeTextarea() {
if ( document.documentMode && document.documentMode < 9 ) {
return;
}
// Add a hidden div. We'll copy over the text from the textarea to measure its height.
$('body').append( '<div class="quick-draft-textarea-clone" style="display: none;"></div>' );
var clone = $('.quick-draft-textarea-clone'),
editor = $('#content'),
editorHeight = editor.height(),
// 100px roughly accounts for browser chrome and allows the
// save draft button to show on-screen at the same time.
editorMaxHeight = $(window).height() - 100;
// Match up textarea and clone div as much as possible.
// Padding cannot be reliably retrieved using shorthand in all browsers.
clone.css({
'font-family': editor.css('font-family'),
'font-size': editor.css('font-size'),
'line-height': editor.css('line-height'),
'padding-bottom': editor.css('paddingBottom'),
'padding-left': editor.css('paddingLeft'),
'padding-right': editor.css('paddingRight'),
'padding-top': editor.css('paddingTop'),
'white-space': 'pre-wrap',
'word-wrap': 'break-word',
'display': 'none'
});
// propertychange is for IE < 9
editor.on('focus input propertychange', function() {
var $this = $(this),
// is to ensure that the height of a final trailing newline is included.
textareaContent = $this.val() + ' ',
// 2px is for border-top & border-bottom
cloneHeight = clone.css('width', $this.css('width')).text(textareaContent).outerHeight() + 2;
// Default to having scrollbars
editor.css('overflow-y', 'auto');
// Only change the height if it has indeed changed and both heights are below the max.
if ( cloneHeight === editorHeight || ( cloneHeight >= editorMaxHeight && editorHeight >= editorMaxHeight ) ) {
return;
}
// Don't allow editor to exceed height of window.
// This is also bound in CSS to a max-height of 1300px to be extra safe.
if ( cloneHeight > editorMaxHeight ) {
editorHeight = editorMaxHeight;
} else {
editorHeight = cloneHeight;
}
// No scrollbars as we change height, not for IE < 9
editor.css('overflow', 'hidden');
$this.css('height', editorHeight + 'px');
});
}
} );
| 01-wordpress-paypal | trunk/wp-admin/js/dashboard.js | JavaScript | gpl3 | 5,660 |
/* global ajaxurl, current_site_id, isRtl */
(function( $ ) {
var id = ( typeof current_site_id !== 'undefined' ) ? '&site_id=' + current_site_id : '';
$(document).ready( function() {
var position = { offset: '0, -1' };
if ( typeof isRtl !== 'undefined' && isRtl ) {
position.my = 'right top';
position.at = 'right bottom';
}
$( '.wp-suggest-user' ).each( function(){
var $this = $( this ),
autocompleteType = ( typeof $this.data( 'autocompleteType' ) !== 'undefined' ) ? $this.data( 'autocompleteType' ) : 'add',
autocompleteField = ( typeof $this.data( 'autocompleteField' ) !== 'undefined' ) ? $this.data( 'autocompleteField' ) : 'user_login';
$this.autocomplete({
source: ajaxurl + '?action=autocomplete-user&autocomplete_type=' + autocompleteType + '&autocomplete_field=' + autocompleteField + id,
delay: 500,
minLength: 2,
position: position,
open: function() {
$( this ).addClass( 'open' );
},
close: function() {
$( this ).removeClass( 'open' );
}
});
});
});
})( jQuery );
| 01-wordpress-paypal | trunk/wp-admin/js/user-suggest.js | JavaScript | gpl3 | 1,070 |
/* global _wpRevisionsSettings, isRtl */
window.wp = window.wp || {};
(function($) {
var revisions;
revisions = wp.revisions = { model: {}, view: {}, controller: {} };
// Link settings.
revisions.settings = _.isUndefined( _wpRevisionsSettings ) ? {} : _wpRevisionsSettings;
// For debugging
revisions.debug = false;
revisions.log = function() {
if ( window.console && revisions.debug ) {
window.console.log.apply( window.console, arguments );
}
};
// Handy functions to help with positioning
$.fn.allOffsets = function() {
var offset = this.offset() || {top: 0, left: 0}, win = $(window);
return _.extend( offset, {
right: win.width() - offset.left - this.outerWidth(),
bottom: win.height() - offset.top - this.outerHeight()
});
};
$.fn.allPositions = function() {
var position = this.position() || {top: 0, left: 0}, parent = this.parent();
return _.extend( position, {
right: parent.outerWidth() - position.left - this.outerWidth(),
bottom: parent.outerHeight() - position.top - this.outerHeight()
});
};
// wp_localize_script transforms top-level numbers into strings. Undo that.
if ( revisions.settings.to ) {
revisions.settings.to = parseInt( revisions.settings.to, 10 );
}
if ( revisions.settings.from ) {
revisions.settings.from = parseInt( revisions.settings.from, 10 );
}
// wp_localize_script does not allow for top-level booleans. Fix that.
if ( revisions.settings.compareTwoMode ) {
revisions.settings.compareTwoMode = revisions.settings.compareTwoMode === '1';
}
/**
* ========================================================================
* MODELS
* ========================================================================
*/
revisions.model.Slider = Backbone.Model.extend({
defaults: {
value: null,
values: null,
min: 0,
max: 1,
step: 1,
range: false,
compareTwoMode: false
},
initialize: function( options ) {
this.frame = options.frame;
this.revisions = options.revisions;
// Listen for changes to the revisions or mode from outside
this.listenTo( this.frame, 'update:revisions', this.receiveRevisions );
this.listenTo( this.frame, 'change:compareTwoMode', this.updateMode );
// Listen for internal changes
this.listenTo( this, 'change:from', this.handleLocalChanges );
this.listenTo( this, 'change:to', this.handleLocalChanges );
this.listenTo( this, 'change:compareTwoMode', this.updateSliderSettings );
this.listenTo( this, 'update:revisions', this.updateSliderSettings );
// Listen for changes to the hovered revision
this.listenTo( this, 'change:hoveredRevision', this.hoverRevision );
this.set({
max: this.revisions.length - 1,
compareTwoMode: this.frame.get('compareTwoMode'),
from: this.frame.get('from'),
to: this.frame.get('to')
});
this.updateSliderSettings();
},
getSliderValue: function( a, b ) {
return isRtl ? this.revisions.length - this.revisions.indexOf( this.get(a) ) - 1 : this.revisions.indexOf( this.get(b) );
},
updateSliderSettings: function() {
if ( this.get('compareTwoMode') ) {
this.set({
values: [
this.getSliderValue( 'to', 'from' ),
this.getSliderValue( 'from', 'to' )
],
value: null,
range: true // ensures handles cannot cross
});
} else {
this.set({
value: this.getSliderValue( 'to', 'to' ),
values: null,
range: false
});
}
this.trigger( 'update:slider' );
},
// Called when a revision is hovered
hoverRevision: function( model, value ) {
this.trigger( 'hovered:revision', value );
},
// Called when `compareTwoMode` changes
updateMode: function( model, value ) {
this.set({ compareTwoMode: value });
},
// Called when `from` or `to` changes in the local model
handleLocalChanges: function() {
this.frame.set({
from: this.get('from'),
to: this.get('to')
});
},
// Receives revisions changes from outside the model
receiveRevisions: function( from, to ) {
// Bail if nothing changed
if ( this.get('from') === from && this.get('to') === to ) {
return;
}
this.set({ from: from, to: to }, { silent: true });
this.trigger( 'update:revisions', from, to );
}
});
revisions.model.Tooltip = Backbone.Model.extend({
defaults: {
revision: null,
offset: {},
hovering: false, // Whether the mouse is hovering
scrubbing: false // Whether the mouse is scrubbing
},
initialize: function( options ) {
this.frame = options.frame;
this.revisions = options.revisions;
this.slider = options.slider;
this.listenTo( this.slider, 'hovered:revision', this.updateRevision );
this.listenTo( this.slider, 'change:hovering', this.setHovering );
this.listenTo( this.slider, 'change:scrubbing', this.setScrubbing );
},
updateRevision: function( revision ) {
this.set({ revision: revision });
},
setHovering: function( model, value ) {
this.set({ hovering: value });
},
setScrubbing: function( model, value ) {
this.set({ scrubbing: value });
}
});
revisions.model.Revision = Backbone.Model.extend({});
revisions.model.Revisions = Backbone.Collection.extend({
model: revisions.model.Revision,
initialize: function() {
_.bindAll( this, 'next', 'prev' );
},
next: function( revision ) {
var index = this.indexOf( revision );
if ( index !== -1 && index !== this.length - 1 ) {
return this.at( index + 1 );
}
},
prev: function( revision ) {
var index = this.indexOf( revision );
if ( index !== -1 && index !== 0 ) {
return this.at( index - 1 );
}
}
});
revisions.model.Field = Backbone.Model.extend({});
revisions.model.Fields = Backbone.Collection.extend({
model: revisions.model.Field
});
revisions.model.Diff = Backbone.Model.extend({
initialize: function() {
var fields = this.get('fields');
this.unset('fields');
this.fields = new revisions.model.Fields( fields );
}
});
revisions.model.Diffs = Backbone.Collection.extend({
initialize: function( models, options ) {
_.bindAll( this, 'getClosestUnloaded' );
this.loadAll = _.once( this._loadAll );
this.revisions = options.revisions;
this.requests = {};
},
model: revisions.model.Diff,
ensure: function( id, context ) {
var diff = this.get( id ),
request = this.requests[ id ],
deferred = $.Deferred(),
ids = {},
from = id.split(':')[0],
to = id.split(':')[1];
ids[id] = true;
wp.revisions.log( 'ensure', id );
this.trigger( 'ensure', ids, from, to, deferred.promise() );
if ( diff ) {
deferred.resolveWith( context, [ diff ] );
} else {
this.trigger( 'ensure:load', ids, from, to, deferred.promise() );
_.each( ids, _.bind( function( id ) {
// Remove anything that has an ongoing request
if ( this.requests[ id ] ) {
delete ids[ id ];
}
// Remove anything we already have
if ( this.get( id ) ) {
delete ids[ id ];
}
}, this ) );
if ( ! request ) {
// Always include the ID that started this ensure
ids[ id ] = true;
request = this.load( _.keys( ids ) );
}
request.done( _.bind( function() {
deferred.resolveWith( context, [ this.get( id ) ] );
}, this ) ).fail( _.bind( function() {
deferred.reject();
}) );
}
return deferred.promise();
},
// Returns an array of proximal diffs
getClosestUnloaded: function( ids, centerId ) {
var self = this;
return _.chain([0].concat( ids )).initial().zip( ids ).sortBy( function( pair ) {
return Math.abs( centerId - pair[1] );
}).map( function( pair ) {
return pair.join(':');
}).filter( function( diffId ) {
return _.isUndefined( self.get( diffId ) ) && ! self.requests[ diffId ];
}).value();
},
_loadAll: function( allRevisionIds, centerId, num ) {
var self = this, deferred = $.Deferred(),
diffs = _.first( this.getClosestUnloaded( allRevisionIds, centerId ), num );
if ( _.size( diffs ) > 0 ) {
this.load( diffs ).done( function() {
self._loadAll( allRevisionIds, centerId, num ).done( function() {
deferred.resolve();
});
}).fail( function() {
if ( 1 === num ) { // Already tried 1. This just isn't working. Give up.
deferred.reject();
} else { // Request fewer diffs this time
self._loadAll( allRevisionIds, centerId, Math.ceil( num / 2 ) ).done( function() {
deferred.resolve();
});
}
});
} else {
deferred.resolve();
}
return deferred;
},
load: function( comparisons ) {
wp.revisions.log( 'load', comparisons );
// Our collection should only ever grow, never shrink, so remove: false
return this.fetch({ data: { compare: comparisons }, remove: false }).done( function() {
wp.revisions.log( 'load:complete', comparisons );
});
},
sync: function( method, model, options ) {
if ( 'read' === method ) {
options = options || {};
options.context = this;
options.data = _.extend( options.data || {}, {
action: 'get-revision-diffs',
post_id: revisions.settings.postId
});
var deferred = wp.ajax.send( options ),
requests = this.requests;
// Record that we're requesting each diff.
if ( options.data.compare ) {
_.each( options.data.compare, function( id ) {
requests[ id ] = deferred;
});
}
// When the request completes, clear the stored request.
deferred.always( function() {
if ( options.data.compare ) {
_.each( options.data.compare, function( id ) {
delete requests[ id ];
});
}
});
return deferred;
// Otherwise, fall back to `Backbone.sync()`.
} else {
return Backbone.Model.prototype.sync.apply( this, arguments );
}
}
});
revisions.model.FrameState = Backbone.Model.extend({
defaults: {
loading: false,
error: false,
compareTwoMode: false
},
initialize: function( attributes, options ) {
var properties = {};
_.bindAll( this, 'receiveDiff' );
this._debouncedEnsureDiff = _.debounce( this._ensureDiff, 200 );
this.revisions = options.revisions;
this.diffs = new revisions.model.Diffs( [], { revisions: this.revisions });
// Set the initial diffs collection provided through the settings
this.diffs.set( revisions.settings.diffData );
// Set up internal listeners
this.listenTo( this, 'change:from', this.changeRevisionHandler );
this.listenTo( this, 'change:to', this.changeRevisionHandler );
this.listenTo( this, 'change:compareTwoMode', this.changeMode );
this.listenTo( this, 'update:revisions', this.updatedRevisions );
this.listenTo( this.diffs, 'ensure:load', this.updateLoadingStatus );
this.listenTo( this, 'update:diff', this.updateLoadingStatus );
// Set the initial revisions, baseUrl, and mode as provided through settings
properties.to = this.revisions.get( revisions.settings.to );
properties.from = this.revisions.get( revisions.settings.from );
properties.compareTwoMode = revisions.settings.compareTwoMode;
properties.baseUrl = revisions.settings.baseUrl;
this.set( properties );
// Start the router if browser supports History API
if ( window.history && window.history.pushState ) {
this.router = new revisions.Router({ model: this });
Backbone.history.start({ pushState: true });
}
},
updateLoadingStatus: function() {
this.set( 'error', false );
this.set( 'loading', ! this.diff() );
},
changeMode: function( model, value ) {
// If we were on the first revision before switching, we have to bump them over one
if ( value && 0 === this.revisions.indexOf( this.get('to') ) ) {
this.set({
from: this.revisions.at(0),
to: this.revisions.at(1)
});
}
},
updatedRevisions: function( from, to ) {
if ( this.get( 'compareTwoMode' ) ) {
// TODO: compare-two loading strategy
} else {
this.diffs.loadAll( this.revisions.pluck('id'), to.id, 40 );
}
},
// Fetch the currently loaded diff.
diff: function() {
return this.diffs.get( this._diffId );
},
// So long as `from` and `to` are changed at the same time, the diff
// will only be updated once. This is because Backbone updates all of
// the changed attributes in `set`, and then fires the `change` events.
updateDiff: function( options ) {
var from, to, diffId, diff;
options = options || {};
from = this.get('from');
to = this.get('to');
diffId = ( from ? from.id : 0 ) + ':' + to.id;
// Check if we're actually changing the diff id.
if ( this._diffId === diffId ) {
return $.Deferred().reject().promise();
}
this._diffId = diffId;
this.trigger( 'update:revisions', from, to );
diff = this.diffs.get( diffId );
// If we already have the diff, then immediately trigger the update.
if ( diff ) {
this.receiveDiff( diff );
return $.Deferred().resolve().promise();
// Otherwise, fetch the diff.
} else {
if ( options.immediate ) {
return this._ensureDiff();
} else {
this._debouncedEnsureDiff();
return $.Deferred().reject().promise();
}
}
},
// A simple wrapper around `updateDiff` to prevent the change event's
// parameters from being passed through.
changeRevisionHandler: function() {
this.updateDiff();
},
receiveDiff: function( diff ) {
// Did we actually get a diff?
if ( _.isUndefined( diff ) || _.isUndefined( diff.id ) ) {
this.set({
loading: false,
error: true
});
} else if ( this._diffId === diff.id ) { // Make sure the current diff didn't change
this.trigger( 'update:diff', diff );
}
},
_ensureDiff: function() {
return this.diffs.ensure( this._diffId, this ).always( this.receiveDiff );
}
});
/**
* ========================================================================
* VIEWS
* ========================================================================
*/
// The frame view. This contains the entire page.
revisions.view.Frame = wp.Backbone.View.extend({
className: 'revisions',
template: wp.template('revisions-frame'),
initialize: function() {
this.listenTo( this.model, 'update:diff', this.renderDiff );
this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode );
this.listenTo( this.model, 'change:loading', this.updateLoadingStatus );
this.listenTo( this.model, 'change:error', this.updateErrorStatus );
this.views.set( '.revisions-control-frame', new revisions.view.Controls({
model: this.model
}) );
},
render: function() {
wp.Backbone.View.prototype.render.apply( this, arguments );
$('html').css( 'overflow-y', 'scroll' );
$('#wpbody-content .wrap').append( this.el );
this.updateCompareTwoMode();
this.renderDiff( this.model.diff() );
this.views.ready();
return this;
},
renderDiff: function( diff ) {
this.views.set( '.revisions-diff-frame', new revisions.view.Diff({
model: diff
}) );
},
updateLoadingStatus: function() {
this.$el.toggleClass( 'loading', this.model.get('loading') );
},
updateErrorStatus: function() {
this.$el.toggleClass( 'diff-error', this.model.get('error') );
},
updateCompareTwoMode: function() {
this.$el.toggleClass( 'comparing-two-revisions', this.model.get('compareTwoMode') );
}
});
// The control view.
// This contains the revision slider, previous/next buttons, the meta info and the compare checkbox.
revisions.view.Controls = wp.Backbone.View.extend({
className: 'revisions-controls',
initialize: function() {
_.bindAll( this, 'setWidth' );
// Add the button view
this.views.add( new revisions.view.Buttons({
model: this.model
}) );
// Add the checkbox view
this.views.add( new revisions.view.Checkbox({
model: this.model
}) );
// Prep the slider model
var slider = new revisions.model.Slider({
frame: this.model,
revisions: this.model.revisions
}),
// Prep the tooltip model
tooltip = new revisions.model.Tooltip({
frame: this.model,
revisions: this.model.revisions,
slider: slider
});
// Add the tooltip view
this.views.add( new revisions.view.Tooltip({
model: tooltip
}) );
// Add the tickmarks view
this.views.add( new revisions.view.Tickmarks({
model: tooltip
}) );
// Add the slider view
this.views.add( new revisions.view.Slider({
model: slider
}) );
// Add the Metabox view
this.views.add( new revisions.view.Metabox({
model: this.model
}) );
},
ready: function() {
this.top = this.$el.offset().top;
this.window = $(window);
this.window.on( 'scroll.wp.revisions', {controls: this}, function(e) {
var controls = e.data.controls,
container = controls.$el.parent(),
scrolled = controls.window.scrollTop(),
frame = controls.views.parent;
if ( scrolled >= controls.top ) {
if ( ! frame.$el.hasClass('pinned') ) {
controls.setWidth();
container.css('height', container.height() + 'px' );
controls.window.on('resize.wp.revisions.pinning click.wp.revisions.pinning', {controls: controls}, function(e) {
e.data.controls.setWidth();
});
}
frame.$el.addClass('pinned');
} else if ( frame.$el.hasClass('pinned') ) {
controls.window.off('.wp.revisions.pinning');
controls.$el.css('width', 'auto');
frame.$el.removeClass('pinned');
container.css('height', 'auto');
controls.top = controls.$el.offset().top;
} else {
controls.top = controls.$el.offset().top;
}
});
},
setWidth: function() {
this.$el.css('width', this.$el.parent().width() + 'px');
}
});
// The tickmarks view
revisions.view.Tickmarks = wp.Backbone.View.extend({
className: 'revisions-tickmarks',
direction: isRtl ? 'right' : 'left',
initialize: function() {
this.listenTo( this.model, 'change:revision', this.reportTickPosition );
},
reportTickPosition: function( model, revision ) {
var offset, thisOffset, parentOffset, tick, index = this.model.revisions.indexOf( revision );
thisOffset = this.$el.allOffsets();
parentOffset = this.$el.parent().allOffsets();
if ( index === this.model.revisions.length - 1 ) {
// Last one
offset = {
rightPlusWidth: thisOffset.left - parentOffset.left + 1,
leftPlusWidth: thisOffset.right - parentOffset.right + 1
};
} else {
// Normal tick
tick = this.$('div:nth-of-type(' + (index + 1) + ')');
offset = tick.allPositions();
_.extend( offset, {
left: offset.left + thisOffset.left - parentOffset.left,
right: offset.right + thisOffset.right - parentOffset.right
});
_.extend( offset, {
leftPlusWidth: offset.left + tick.outerWidth(),
rightPlusWidth: offset.right + tick.outerWidth()
});
}
this.model.set({ offset: offset });
},
ready: function() {
var tickCount, tickWidth;
tickCount = this.model.revisions.length - 1;
tickWidth = 1 / tickCount;
this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px');
_(tickCount).times( function( index ){
this.$el.append( '<div style="' + this.direction + ': ' + ( 100 * tickWidth * index ) + '%"></div>' );
}, this );
}
});
// The metabox view
revisions.view.Metabox = wp.Backbone.View.extend({
className: 'revisions-meta',
initialize: function() {
// Add the 'from' view
this.views.add( new revisions.view.MetaFrom({
model: this.model,
className: 'diff-meta diff-meta-from'
}) );
// Add the 'to' view
this.views.add( new revisions.view.MetaTo({
model: this.model
}) );
}
});
// The revision meta view (to be extended)
revisions.view.Meta = wp.Backbone.View.extend({
template: wp.template('revisions-meta'),
events: {
'click .restore-revision': 'restoreRevision'
},
initialize: function() {
this.listenTo( this.model, 'update:revisions', this.render );
},
prepare: function() {
return _.extend( this.model.toJSON()[this.type] || {}, {
type: this.type
});
},
restoreRevision: function() {
document.location = this.model.get('to').attributes.restoreUrl;
}
});
// The revision meta 'from' view
revisions.view.MetaFrom = revisions.view.Meta.extend({
className: 'diff-meta diff-meta-from',
type: 'from'
});
// The revision meta 'to' view
revisions.view.MetaTo = revisions.view.Meta.extend({
className: 'diff-meta diff-meta-to',
type: 'to'
});
// The checkbox view.
revisions.view.Checkbox = wp.Backbone.View.extend({
className: 'revisions-checkbox',
template: wp.template('revisions-checkbox'),
events: {
'click .compare-two-revisions': 'compareTwoToggle'
},
initialize: function() {
this.listenTo( this.model, 'change:compareTwoMode', this.updateCompareTwoMode );
},
ready: function() {
if ( this.model.revisions.length < 3 ) {
$('.revision-toggle-compare-mode').hide();
}
},
updateCompareTwoMode: function() {
this.$('.compare-two-revisions').prop( 'checked', this.model.get('compareTwoMode') );
},
// Toggle the compare two mode feature when the compare two checkbox is checked.
compareTwoToggle: function() {
// Activate compare two mode?
this.model.set({ compareTwoMode: $('.compare-two-revisions').prop('checked') });
}
});
// The tooltip view.
// Encapsulates the tooltip.
revisions.view.Tooltip = wp.Backbone.View.extend({
className: 'revisions-tooltip',
template: wp.template('revisions-meta'),
initialize: function() {
this.listenTo( this.model, 'change:offset', this.render );
this.listenTo( this.model, 'change:hovering', this.toggleVisibility );
this.listenTo( this.model, 'change:scrubbing', this.toggleVisibility );
},
prepare: function() {
if ( _.isNull( this.model.get('revision') ) ) {
return;
} else {
return _.extend( { type: 'tooltip' }, {
attributes: this.model.get('revision').toJSON()
});
}
},
render: function() {
var otherDirection,
direction,
directionVal,
flipped,
css = {},
position = this.model.revisions.indexOf( this.model.get('revision') ) + 1;
flipped = ( position / this.model.revisions.length ) > 0.5;
if ( isRtl ) {
direction = flipped ? 'left' : 'right';
directionVal = flipped ? 'leftPlusWidth' : direction;
} else {
direction = flipped ? 'right' : 'left';
directionVal = flipped ? 'rightPlusWidth' : direction;
}
otherDirection = 'right' === direction ? 'left': 'right';
wp.Backbone.View.prototype.render.apply( this, arguments );
css[direction] = this.model.get('offset')[directionVal] + 'px';
css[otherDirection] = '';
this.$el.toggleClass( 'flipped', flipped ).css( css );
},
visible: function() {
return this.model.get( 'scrubbing' ) || this.model.get( 'hovering' );
},
toggleVisibility: function() {
if ( this.visible() ) {
this.$el.stop().show().fadeTo( 100 - this.el.style.opacity * 100, 1 );
} else {
this.$el.stop().fadeTo( this.el.style.opacity * 300, 0, function(){ $(this).hide(); } );
}
return;
}
});
// The buttons view.
// Encapsulates all of the configuration for the previous/next buttons.
revisions.view.Buttons = wp.Backbone.View.extend({
className: 'revisions-buttons',
template: wp.template('revisions-buttons'),
events: {
'click .revisions-next .button': 'nextRevision',
'click .revisions-previous .button': 'previousRevision'
},
initialize: function() {
this.listenTo( this.model, 'update:revisions', this.disabledButtonCheck );
},
ready: function() {
this.disabledButtonCheck();
},
// Go to a specific model index
gotoModel: function( toIndex ) {
var attributes = {
to: this.model.revisions.at( toIndex )
};
// If we're at the first revision, unset 'from'.
if ( toIndex ) {
attributes.from = this.model.revisions.at( toIndex - 1 );
} else {
this.model.unset('from', { silent: true });
}
this.model.set( attributes );
},
// Go to the 'next' revision
nextRevision: function() {
var toIndex = this.model.revisions.indexOf( this.model.get('to') ) + 1;
this.gotoModel( toIndex );
},
// Go to the 'previous' revision
previousRevision: function() {
var toIndex = this.model.revisions.indexOf( this.model.get('to') ) - 1;
this.gotoModel( toIndex );
},
// Check to see if the Previous or Next buttons need to be disabled or enabled.
disabledButtonCheck: function() {
var maxVal = this.model.revisions.length - 1,
minVal = 0,
next = $('.revisions-next .button'),
previous = $('.revisions-previous .button'),
val = this.model.revisions.indexOf( this.model.get('to') );
// Disable "Next" button if you're on the last node.
next.prop( 'disabled', ( maxVal === val ) );
// Disable "Previous" button if you're on the first node.
previous.prop( 'disabled', ( minVal === val ) );
}
});
// The slider view.
revisions.view.Slider = wp.Backbone.View.extend({
className: 'wp-slider',
direction: isRtl ? 'right' : 'left',
events: {
'mousemove' : 'mouseMove'
},
initialize: function() {
_.bindAll( this, 'start', 'slide', 'stop', 'mouseMove', 'mouseEnter', 'mouseLeave' );
this.listenTo( this.model, 'update:slider', this.applySliderSettings );
},
ready: function() {
this.$el.css('width', ( this.model.revisions.length * 50 ) + 'px');
this.$el.slider( _.extend( this.model.toJSON(), {
start: this.start,
slide: this.slide,
stop: this.stop
}) );
this.$el.hoverIntent({
over: this.mouseEnter,
out: this.mouseLeave,
timeout: 800
});
this.applySliderSettings();
},
mouseMove: function( e ) {
var zoneCount = this.model.revisions.length - 1, // One fewer zone than models
sliderFrom = this.$el.allOffsets()[this.direction], // "From" edge of slider
sliderWidth = this.$el.width(), // Width of slider
tickWidth = sliderWidth / zoneCount, // Calculated width of zone
actualX = ( isRtl ? $(window).width() - e.pageX : e.pageX ) - sliderFrom, // Flipped for RTL - sliderFrom;
currentModelIndex = Math.floor( ( actualX + ( tickWidth / 2 ) ) / tickWidth ); // Calculate the model index
// Ensure sane value for currentModelIndex.
if ( currentModelIndex < 0 ) {
currentModelIndex = 0;
} else if ( currentModelIndex >= this.model.revisions.length ) {
currentModelIndex = this.model.revisions.length - 1;
}
// Update the tooltip mode
this.model.set({ hoveredRevision: this.model.revisions.at( currentModelIndex ) });
},
mouseLeave: function() {
this.model.set({ hovering: false });
},
mouseEnter: function() {
this.model.set({ hovering: true });
},
applySliderSettings: function() {
this.$el.slider( _.pick( this.model.toJSON(), 'value', 'values', 'range' ) );
var handles = this.$('a.ui-slider-handle');
if ( this.model.get('compareTwoMode') ) {
// in RTL mode the 'left handle' is the second in the slider, 'right' is first
handles.first()
.toggleClass( 'to-handle', !! isRtl )
.toggleClass( 'from-handle', ! isRtl );
handles.last()
.toggleClass( 'from-handle', !! isRtl )
.toggleClass( 'to-handle', ! isRtl );
} else {
handles.removeClass('from-handle to-handle');
}
},
start: function( event, ui ) {
this.model.set({ scrubbing: true });
// Track the mouse position to enable smooth dragging,
// overrides default jQuery UI step behavior.
$( window ).on( 'mousemove.wp.revisions', { view: this }, function( e ) {
var handles,
view = e.data.view,
leftDragBoundary = view.$el.offset().left,
sliderOffset = leftDragBoundary,
sliderRightEdge = leftDragBoundary + view.$el.width(),
rightDragBoundary = sliderRightEdge,
leftDragReset = '0',
rightDragReset = '100%',
handle = $( ui.handle );
// In two handle mode, ensure handles can't be dragged past each other.
// Adjust left/right boundaries and reset points.
if ( view.model.get('compareTwoMode') ) {
handles = handle.parent().find('.ui-slider-handle');
if ( handle.is( handles.first() ) ) { // We're the left handle
rightDragBoundary = handles.last().offset().left;
rightDragReset = rightDragBoundary - sliderOffset;
} else { // We're the right handle
leftDragBoundary = handles.first().offset().left + handles.first().width();
leftDragReset = leftDragBoundary - sliderOffset;
}
}
// Follow mouse movements, as long as handle remains inside slider.
if ( e.pageX < leftDragBoundary ) {
handle.css( 'left', leftDragReset ); // Mouse to left of slider.
} else if ( e.pageX > rightDragBoundary ) {
handle.css( 'left', rightDragReset ); // Mouse to right of slider.
} else {
handle.css( 'left', e.pageX - sliderOffset ); // Mouse in slider.
}
} );
},
getPosition: function( position ) {
return isRtl ? this.model.revisions.length - position - 1: position;
},
// Responds to slide events
slide: function( event, ui ) {
var attributes, movedRevision;
// Compare two revisions mode
if ( this.model.get('compareTwoMode') ) {
// Prevent sliders from occupying same spot
if ( ui.values[1] === ui.values[0] ) {
return false;
}
if ( isRtl ) {
ui.values.reverse();
}
attributes = {
from: this.model.revisions.at( this.getPosition( ui.values[0] ) ),
to: this.model.revisions.at( this.getPosition( ui.values[1] ) )
};
} else {
attributes = {
to: this.model.revisions.at( this.getPosition( ui.value ) )
};
// If we're at the first revision, unset 'from'.
if ( this.getPosition( ui.value ) > 0 ) {
attributes.from = this.model.revisions.at( this.getPosition( ui.value ) - 1 );
} else {
attributes.from = undefined;
}
}
movedRevision = this.model.revisions.at( this.getPosition( ui.value ) );
// If we are scrubbing, a scrub to a revision is considered a hover
if ( this.model.get('scrubbing') ) {
attributes.hoveredRevision = movedRevision;
}
this.model.set( attributes );
},
stop: function() {
$( window ).off('mousemove.wp.revisions');
this.model.updateSliderSettings(); // To snap us back to a tick mark
this.model.set({ scrubbing: false });
}
});
// The diff view.
// This is the view for the current active diff.
revisions.view.Diff = wp.Backbone.View.extend({
className: 'revisions-diff',
template: wp.template('revisions-diff'),
// Generate the options to be passed to the template.
prepare: function() {
return _.extend({ fields: this.model.fields.toJSON() }, this.options );
}
});
// The revisions router.
// Maintains the URL routes so browser URL matches state.
revisions.Router = Backbone.Router.extend({
initialize: function( options ) {
this.model = options.model;
// Maintain state and history when navigating
this.listenTo( this.model, 'update:diff', _.debounce( this.updateUrl, 250 ) );
this.listenTo( this.model, 'change:compareTwoMode', this.updateUrl );
},
baseUrl: function( url ) {
return this.model.get('baseUrl') + url;
},
updateUrl: function() {
var from = this.model.has('from') ? this.model.get('from').id : 0,
to = this.model.get('to').id;
if ( this.model.get('compareTwoMode' ) ) {
this.navigate( this.baseUrl( '?from=' + from + '&to=' + to ), { replace: true } );
} else {
this.navigate( this.baseUrl( '?revision=' + to ), { replace: true } );
}
},
handleRoute: function( a, b ) {
var compareTwo = _.isUndefined( b );
if ( ! compareTwo ) {
b = this.model.revisions.get( a );
a = this.model.revisions.prev( b );
b = b ? b.id : 0;
a = a ? a.id : 0;
}
}
});
// Initialize the revisions UI.
revisions.init = function() {
revisions.view.frame = new revisions.view.Frame({
model: new revisions.model.FrameState({}, {
revisions: new revisions.model.Revisions( revisions.settings.revisionData )
})
}).render();
};
$( revisions.init );
}(jQuery));
| 01-wordpress-paypal | trunk/wp-admin/js/revisions.js | JavaScript | gpl3 | 32,205 |
/* global postL10n, ajaxurl, wpAjax, setPostThumbnailL10n, postboxes, pagenow, tinymce, alert, deleteUserSetting */
/* global theList:true, theExtraList:true, getUserSetting, setUserSetting */
var tagBox, commentsBox, WPSetThumbnailHTML, WPSetThumbnailID, WPRemoveThumbnail, wptitlehint, makeSlugeditClickable, editPermalink;
// Back-compat: prevent fatal errors
makeSlugeditClickable = editPermalink = function(){};
window.wp = window.wp || {};
// 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($) {
var titleHasFocus = false;
tagBox = {
clean : function(tags) {
var comma = postL10n.comma;
if ( ',' !== comma )
tags = tags.replace(new RegExp(comma, 'g'), ',');
tags = tags.replace(/\s*,\s*/g, ',').replace(/,+/g, ',').replace(/[,\s]+$/, '').replace(/^[,\s]+/, '');
if ( ',' !== comma )
tags = tags.replace(/,/g, comma);
return tags;
},
parseTags : function(el) {
var id = el.id, num = id.split('-check-num-')[1], taxbox = $(el).closest('.tagsdiv'),
thetags = taxbox.find('.the-tags'), comma = postL10n.comma,
current_tags = thetags.val().split(comma), new_tags = [];
delete current_tags[num];
$.each( current_tags, function(key, val) {
val = $.trim(val);
if ( val ) {
new_tags.push(val);
}
});
thetags.val( this.clean( new_tags.join(comma) ) );
this.quickClicks(taxbox);
return false;
},
quickClicks : function(el) {
var thetags = $('.the-tags', el),
tagchecklist = $('.tagchecklist', el),
id = $(el).attr('id'),
current_tags, disabled;
if ( !thetags.length )
return;
disabled = thetags.prop('disabled');
current_tags = thetags.val().split(postL10n.comma);
tagchecklist.empty();
$.each( current_tags, function( key, val ) {
var span, xbutton;
val = $.trim( val );
if ( ! val )
return;
// Create a new span, and ensure the text is properly escaped.
span = $('<span />').text( val );
// If tags editing isn't disabled, create the X button.
if ( ! disabled ) {
xbutton = $( '<a id="' + id + '-check-num-' + key + '" class="ntdelbutton">X</a>' );
xbutton.click( function(){ tagBox.parseTags(this); });
span.prepend(' ').prepend( xbutton );
}
// Append the span to the tag list.
tagchecklist.append( span );
});
},
flushTags : function(el, a, f) {
var tagsval, newtags, text,
tags = $('.the-tags', el),
newtag = $('input.newtag', el),
comma = postL10n.comma;
a = a || false;
text = a ? $(a).text() : newtag.val();
tagsval = tags.val();
newtags = tagsval ? tagsval + comma + text : text;
newtags = this.clean( newtags );
newtags = array_unique_noempty( newtags.split(comma) ).join(comma);
tags.val(newtags);
this.quickClicks(el);
if ( !a )
newtag.val('');
if ( 'undefined' == typeof(f) )
newtag.focus();
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 = $('<p id="tagcloud-'+tax+'" class="the-tagcloud">'+r+'</p>');
$('a', r).click(function(){
tagBox.flushTags( $(this).closest('.inside').children('.tagsdiv'), this);
return false;
});
$('#'+id).after(r);
});
},
init : function() {
var t = this, ajaxtag = $('div.ajaxtag');
$('.tagsdiv').each( function() {
tagBox.quickClicks(this);
});
$('input.tagadd', ajaxtag).click(function(){
t.flushTags( $(this).closest('.tagsdiv') );
});
$('div.taghint', ajaxtag).click(function(){
$(this).css('visibility', 'hidden').parent().siblings('.newtag').focus();
});
$('input.newtag', ajaxtag).blur(function() {
if ( '' === this.value )
$(this).parent().siblings('.taghint').css('visibility', '');
}).focus(function(){
$(this).parent().siblings('.taghint').css('visibility', 'hidden');
}).keyup(function(e){
if ( 13 == e.which ) {
tagBox.flushTags( $(this).closest('.tagsdiv') );
return false;
}
}).keypress(function(e){
if ( 13 == e.which ) {
e.preventDefault();
return false;
}
}).each(function(){
var tax = $(this).closest('div.tagsdiv').attr('id');
$(this).suggest( ajaxurl + '?action=ajax-tag-search&tax=' + tax, { delay: 500, minchars: 2, multiple: true, multipleSep: postL10n.comma + ' ' } );
});
// save tags on post save/publish
$('#post').submit(function(){
$('div.tagsdiv').each( function() {
tagBox.flushTags(this, false, 1);
});
});
// tag cloud
$('a.tagcloud-link').click(function(){
tagBox.get( $(this).attr('id') );
$(this).unbind().click(function(){
$(this).siblings('.the-tagcloud').toggle();
return false;
});
return false;
});
}
};
commentsBox = {
st : 0,
get : function(total, num) {
var st = this.st, data;
if ( ! num )
num = 20;
this.st += num;
this.total = total;
$('#commentsdiv .spinner').show();
data = {
'action' : 'get-comments',
'mode' : 'single',
'_ajax_nonce' : $('#add_comment_nonce').val(),
'p' : $('#post_ID').val(),
'start' : st,
'number' : num
};
$.post(ajaxurl, data,
function(r) {
r = wpAjax.parseAjaxResponse(r);
$('#commentsdiv .widefat').show();
$('#commentsdiv .spinner').hide();
if ( 'object' == typeof r && r.responses[0] ) {
$('#the-comment-list').append( r.responses[0].data );
theList = theExtraList = null;
$( 'a[className*=\':\']' ).unbind();
if ( commentsBox.st > commentsBox.total )
$('#show-comments').hide();
else
$('#show-comments').show().children('a').html(postL10n.showcomm);
return;
} else if ( 1 == r ) {
$('#show-comments').html(postL10n.endcomm);
return;
}
$('#the-comment-list').append('<tr><td colspan="2">'+wpAjax.broken+'</td></tr>');
}
);
return false;
}
};
WPSetThumbnailHTML = function(html){
$('.inside', '#postimagediv').html(html);
};
WPSetThumbnailID = function(id){
var field = $('input[value="_thumbnail_id"]', '#list-table');
if ( field.size() > 0 ) {
$('#meta\\[' + field.attr('id').match(/[0-9]+/) + '\\]\\[value\\]').text(id);
}
};
WPRemoveThumbnail = function(nonce){
$.post(ajaxurl, {
action: 'set-post-thumbnail', post_id: $( '#post_ID' ).val(), thumbnail_id: -1, _ajax_nonce: nonce, cookie: encodeURIComponent( document.cookie )
}, function(str){
if ( str == '0' ) {
alert( setPostThumbnailL10n.error );
} else {
WPSetThumbnailHTML(str);
}
}
);
};
$(document).on( 'heartbeat-send.refresh-lock', function( e, data ) {
var lock = $('#active_post_lock').val(),
post_id = $('#post_ID').val(),
send = {};
if ( ! post_id || ! $('#post-lock-dialog').length )
return;
send.post_id = post_id;
if ( lock )
send.lock = lock;
data['wp-refresh-post-lock'] = send;
}).on( 'heartbeat-tick.refresh-lock', function( e, data ) {
// Post locks: update the lock string or show the dialog if somebody has taken over editing
var received, wrap, avatar;
if ( data['wp-refresh-post-lock'] ) {
received = data['wp-refresh-post-lock'];
if ( received.lock_error ) {
// show "editing taken over" message
wrap = $('#post-lock-dialog');
if ( wrap.length && ! wrap.is(':visible') ) {
if ( wp.autosave ) {
// Save the latest changes and disable
$(document).one( 'heartbeat-tick', function() {
wp.autosave.server.suspend();
wrap.removeClass('saving').addClass('saved');
$(window).off( 'beforeunload.edit-post' );
});
wrap.addClass('saving');
wp.autosave.server.triggerSave();
}
if ( received.lock_error.avatar_src ) {
avatar = $('<img class="avatar avatar-64 photo" width="64" height="64" />').attr( 'src', received.lock_error.avatar_src.replace(/&/g, '&') );
wrap.find('div.post-locked-avatar').empty().append( avatar );
}
wrap.show().find('.currently-editing').text( received.lock_error.text );
wrap.find('.wp-tab-first').focus();
}
} else if ( received.new_lock ) {
$('#active_post_lock').val( received.new_lock );
}
}
}).on( 'before-autosave.update-post-slug', function() {
titleHasFocus = document.activeElement && document.activeElement.id === 'title';
}).on( 'after-autosave.update-post-slug', function() {
// Create slug area only if not already there
// and the title field was not focused (user was not typing a title) when autosave ran
if ( ! $('#edit-slug-box > *').length && ! titleHasFocus ) {
$.post( ajaxurl, {
action: 'sample-permalink',
post_id: $('#post_ID').val(),
new_title: $('#title').val(),
samplepermalinknonce: $('#samplepermalinknonce').val()
},
function( data ) {
if ( data != '-1' ) {
$('#edit-slug-box').html(data);
}
}
);
}
});
}(jQuery));
(function($) {
var check, timeout;
function schedule() {
check = false;
window.clearTimeout( timeout );
timeout = window.setTimeout( function(){ check = true; }, 300000 );
}
$(document).on( 'heartbeat-send.wp-refresh-nonces', function( e, data ) {
var nonce, post_id;
if ( check ) {
if ( ( post_id = $('#post_ID').val() ) && ( nonce = $('#_wpnonce').val() ) ) {
data['wp-refresh-post-nonces'] = {
post_id: post_id,
post_nonce: nonce
};
}
}
}).on( 'heartbeat-tick.wp-refresh-nonces', function( e, data ) {
var nonces = data['wp-refresh-post-nonces'];
if ( nonces ) {
schedule();
if ( nonces.replace ) {
$.each( nonces.replace, function( selector, value ) {
$( '#' + selector ).val( value );
});
}
if ( nonces.heartbeatNonce )
window.heartbeatSettings.nonce = nonces.heartbeatNonce;
}
}).ready( function() {
schedule();
});
}(jQuery));
jQuery(document).ready( function($) {
var stamp, visibility, $submitButtons, updateVisibility, updateText,
sticky = '',
last = 0,
co = $('#content'),
$document = $(document),
$editSlugWrap = $('#edit-slug-box'),
postId = $('#post_ID').val() || 0,
$submitpost = $('#submitpost'),
releaseLock = true,
$postVisibilitySelect = $('#post-visibility-select'),
$timestampdiv = $('#timestampdiv'),
$postStatusSelect = $('#post-status-select');
postboxes.add_postbox_toggles(pagenow);
// Clear the window name. Otherwise if this is a former preview window where the user navigated to edit another post,
// and the first post is still being edited, clicking Preview there will use this window to show the preview.
window.name = '';
// Post locks: contain focus inside the dialog. If the dialog is shown, focus the first item.
$('#post-lock-dialog .notification-dialog').on( 'keydown', function(e) {
if ( e.which != 9 )
return;
var target = $(e.target);
if ( target.hasClass('wp-tab-first') && e.shiftKey ) {
$(this).find('.wp-tab-last').focus();
e.preventDefault();
} else if ( target.hasClass('wp-tab-last') && ! e.shiftKey ) {
$(this).find('.wp-tab-first').focus();
e.preventDefault();
}
}).filter(':visible').find('.wp-tab-first').focus();
// Set the heartbeat interval to 15 sec. if post lock dialogs are enabled
if ( wp.heartbeat && $('#post-lock-dialog').length ) {
wp.heartbeat.interval( 15 );
}
// The form is being submitted by the user
$submitButtons = $submitpost.find( ':button, :submit, a.submitdelete, #post-preview' ).on( 'click.edit-post', function( event ) {
var $button = $(this);
if ( $button.hasClass('disabled') ) {
event.preventDefault();
return;
}
if ( $button.hasClass('submitdelete') || $button.is( '#post-preview' ) ) {
return;
}
// The form submission can be blocked from JS or by using HTML 5.0 validation on some fields.
// Run this only on an actual 'submit'.
$('form#post').off( 'submit.edit-post' ).on( 'submit.edit-post', function( event ) {
if ( event.isDefaultPrevented() ) {
return;
}
// Stop autosave
if ( wp.autosave ) {
wp.autosave.server.suspend();
}
releaseLock = false;
$(window).off( 'beforeunload.edit-post' );
$submitButtons.addClass( 'disabled' );
if ( $button.attr('id') === 'publish' ) {
$submitpost.find('#major-publishing-actions .spinner').show();
} else {
$submitpost.find('#minor-publishing .spinner').show();
}
});
});
// Submit the form saving a draft or an autosave, and show a preview in a new tab
$('#post-preview').on( 'click.post-preview', function( event ) {
var $this = $(this),
$form = $('form#post'),
$previewField = $('input#wp-preview'),
target = $this.attr('target') || 'wp-preview',
ua = navigator.userAgent.toLowerCase();
event.preventDefault();
if ( $this.hasClass('disabled') ) {
return;
}
if ( wp.autosave ) {
wp.autosave.server.tempBlockSave();
}
$previewField.val('dopreview');
$form.attr( 'target', target ).submit().attr( 'target', '' );
// Workaround for WebKit bug preventing a form submitting twice to the same action.
// https://bugs.webkit.org/show_bug.cgi?id=28633
if ( ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1 ) {
$form.attr( 'action', function( index, value ) {
return value + '?t=' + ( new Date() ).getTime();
});
}
$previewField.val('');
});
// This code is meant to allow tabbing from Title to Post content.
$('#title').on( 'keydown.editor-focus', function( event ) {
var editor, $textarea;
if ( event.keyCode === 9 && ! event.ctrlKey && ! event.altKey && ! event.shiftKey ) {
editor = typeof tinymce != 'undefined' && tinymce.get('content');
$textarea = $('#content');
if ( editor && ! editor.isHidden() ) {
editor.focus();
} else if ( $textarea.length ) {
$textarea.focus();
} else {
return;
}
event.preventDefault();
}
});
// Autosave new posts after a title is typed
if ( $( '#auto_draft' ).val() ) {
$( '#title' ).blur( function() {
var cancel;
if ( ! this.value || $('#edit-slug-box > *').length ) {
return;
}
// Cancel the autosave when the blur was triggered by the user submitting the form
$('form#post').one( 'submit', function() {
cancel = true;
});
window.setTimeout( function() {
if ( ! cancel && wp.autosave ) {
wp.autosave.server.triggerSave();
}
}, 200 );
});
}
$document.on( 'autosave-disable-buttons.edit-post', function() {
$submitButtons.addClass( 'disabled' );
}).on( 'autosave-enable-buttons.edit-post', function() {
if ( ! wp.heartbeat || ! wp.heartbeat.hasConnectionError() ) {
$submitButtons.removeClass( 'disabled' );
}
}).on( 'before-autosave.edit-post', function() {
$( '.autosave-message' ).text( postL10n.savingText );
}).on( 'after-autosave.edit-post', function( event, data ) {
$( '.autosave-message' ).text( data.message );
});
$(window).on( 'beforeunload.edit-post', function() {
var editor = typeof tinymce !== 'undefined' && tinymce.get('content');
if ( ( editor && ! editor.isHidden() && editor.isDirty() ) ||
( wp.autosave && wp.autosave.server.postChanged() ) ) {
return postL10n.saveAlert;
}
}).on( 'unload.edit-post', function( event ) {
if ( ! releaseLock ) {
return;
}
// Unload is triggered (by hand) on removing the Thickbox iframe.
// Make sure we process only the main document unload.
if ( event.target && event.target.nodeName != '#document' ) {
return;
}
$.ajax({
type: 'POST',
url: ajaxurl,
async: false,
data: {
action: 'wp-remove-post-lock',
_wpnonce: $('#_wpnonce').val(),
post_ID: $('#post_ID').val(),
active_post_lock: $('#active_post_lock').val()
}
});
});
// multi-taxonomies
if ( $('#tagsdiv-post_tag').length ) {
tagBox.init();
} else {
$('#side-sortables, #normal-sortables, #advanced-sortables').children('div.postbox').each(function(){
if ( this.id.indexOf('tagsdiv-') === 0 ) {
tagBox.init();
return false;
}
});
}
// categories
$('.categorydiv').each( function(){
var this_id = $(this).attr('id'), catAddBefore, catAddAfter, taxonomyParts, taxonomy, settingName;
taxonomyParts = this_id.split('-');
taxonomyParts.shift();
taxonomy = taxonomyParts.join('-');
settingName = taxonomy + '_tab';
if ( taxonomy == 'category' )
settingName = 'cats';
// TODO: move to jQuery 1.3+, support for multiple hierarchical taxonomies, see wp-lists.js
$('a', '#' + taxonomy + '-tabs').click( function(){
var t = $(this).attr('href');
$(this).parent().addClass('tabs').siblings('li').removeClass('tabs');
$('#' + taxonomy + '-tabs').siblings('.tabs-panel').hide();
$(t).show();
if ( '#' + taxonomy + '-all' == t )
deleteUserSetting( settingName );
else
setUserSetting( settingName, 'pop' );
return false;
});
if ( getUserSetting( settingName ) )
$('a[href="#' + taxonomy + '-pop"]', '#' + taxonomy + '-tabs').click();
// Ajax Cat
$( '#new' + taxonomy ).one( 'focus', function() { $( this ).val( '' ).removeClass( 'form-input-tip' ); } );
$('#new' + taxonomy).keypress( function(event){
if( 13 === event.keyCode ) {
event.preventDefault();
$('#' + taxonomy + '-add-submit').click();
}
});
$('#' + taxonomy + '-add-submit').click( function(){ $('#new' + taxonomy).focus(); });
catAddBefore = function( s ) {
if ( !$('#new'+taxonomy).val() )
return false;
s.data += '&' + $( ':checked', '#'+taxonomy+'checklist' ).serialize();
$( '#' + taxonomy + '-add-submit' ).prop( 'disabled', true );
return s;
};
catAddAfter = function( r, s ) {
var sup, drop = $('#new'+taxonomy+'_parent');
$( '#' + taxonomy + '-add-submit' ).prop( 'disabled', false );
if ( 'undefined' != s.parsed.responses[0] && (sup = s.parsed.responses[0].supplemental.newcat_parent) ) {
drop.before(sup);
drop.remove();
}
};
$('#' + taxonomy + 'checklist').wpList({
alt: '',
response: taxonomy + '-ajax-response',
addBefore: catAddBefore,
addAfter: catAddAfter
});
$('#' + taxonomy + '-add-toggle').click( function() {
$('#' + taxonomy + '-adder').toggleClass( 'wp-hidden-children' );
$('a[href="#' + taxonomy + '-all"]', '#' + taxonomy + '-tabs').click();
$('#new'+taxonomy).focus();
return false;
});
$('#' + taxonomy + 'checklist, #' + taxonomy + 'checklist-pop').on( 'click', 'li.popular-category > label input[type="checkbox"]', function() {
var t = $(this), c = t.is(':checked'), id = t.val();
if ( id && t.parents('#taxonomy-'+taxonomy).length )
$('#in-' + taxonomy + '-' + id + ', #in-popular-' + taxonomy + '-' + id).prop( 'checked', c );
});
}); // end cats
// Custom Fields
if ( $('#postcustom').length ) {
$( '#the-list' ).wpList( { addAfter: function() {
$('table#list-table').show();
}, addBefore: function( s ) {
s.data += '&post_id=' + $('#post_ID').val();
return s;
}
});
}
// submitdiv
if ( $('#submitdiv').length ) {
stamp = $('#timestamp').html();
visibility = $('#post-visibility-display').html();
updateVisibility = function() {
if ( $postVisibilitySelect.find('input:radio:checked').val() != 'public' ) {
$('#sticky').prop('checked', false);
$('#sticky-span').hide();
} else {
$('#sticky-span').show();
}
if ( $postVisibilitySelect.find('input:radio:checked').val() != 'password' ) {
$('#password-span').hide();
} else {
$('#password-span').show();
}
};
updateText = function() {
if ( ! $timestampdiv.length )
return true;
var attemptedDate, originalDate, currentDate, publishOn, postStatus = $('#post_status'),
optPublish = $('option[value="publish"]', postStatus), aa = $('#aa').val(),
mm = $('#mm').val(), jj = $('#jj').val(), hh = $('#hh').val(), mn = $('#mn').val();
attemptedDate = new Date( aa, mm - 1, jj, hh, mn );
originalDate = new Date( $('#hidden_aa').val(), $('#hidden_mm').val() -1, $('#hidden_jj').val(), $('#hidden_hh').val(), $('#hidden_mn').val() );
currentDate = new Date( $('#cur_aa').val(), $('#cur_mm').val() -1, $('#cur_jj').val(), $('#cur_hh').val(), $('#cur_mn').val() );
if ( attemptedDate.getFullYear() != aa || (1 + attemptedDate.getMonth()) != mm || attemptedDate.getDate() != jj || attemptedDate.getMinutes() != mn ) {
$timestampdiv.find('.timestamp-wrap').addClass('form-invalid');
return false;
} else {
$timestampdiv.find('.timestamp-wrap').removeClass('form-invalid');
}
if ( attemptedDate > currentDate && $('#original_post_status').val() != 'future' ) {
publishOn = postL10n.publishOnFuture;
$('#publish').val( postL10n.schedule );
} else if ( attemptedDate <= currentDate && $('#original_post_status').val() != 'publish' ) {
publishOn = postL10n.publishOn;
$('#publish').val( postL10n.publish );
} else {
publishOn = postL10n.publishOnPast;
$('#publish').val( postL10n.update );
}
if ( originalDate.toUTCString() == attemptedDate.toUTCString() ) { //hack
$('#timestamp').html(stamp);
} else {
$('#timestamp').html(
publishOn + ' <b>' +
postL10n.dateFormat.replace( '%1$s', $('option[value="' + $('#mm').val() + '"]', '#mm').text() )
.replace( '%2$s', jj )
.replace( '%3$s', aa )
.replace( '%4$s', hh )
.replace( '%5$s', mn ) +
'</b> '
);
}
if ( $postVisibilitySelect.find('input:radio:checked').val() == 'private' ) {
$('#publish').val( postL10n.update );
if ( 0 === optPublish.length ) {
postStatus.append('<option value="publish">' + postL10n.privatelyPublished + '</option>');
} else {
optPublish.html( postL10n.privatelyPublished );
}
$('option[value="publish"]', postStatus).prop('selected', true);
$('#misc-publishing-actions .edit-post-status').hide();
} else {
if ( $('#original_post_status').val() == 'future' || $('#original_post_status').val() == 'draft' ) {
if ( optPublish.length ) {
optPublish.remove();
postStatus.val($('#hidden_post_status').val());
}
} else {
optPublish.html( postL10n.published );
}
if ( postStatus.is(':hidden') )
$('#misc-publishing-actions .edit-post-status').show();
}
$('#post-status-display').html($('option:selected', postStatus).text());
if ( $('option:selected', postStatus).val() == 'private' || $('option:selected', postStatus).val() == 'publish' ) {
$('#save-post').hide();
} else {
$('#save-post').show();
if ( $('option:selected', postStatus).val() == 'pending' ) {
$('#save-post').show().val( postL10n.savePending );
} else {
$('#save-post').show().val( postL10n.saveDraft );
}
}
return true;
};
$( '#visibility .edit-visibility').click( function () {
if ( $postVisibilitySelect.is(':hidden') ) {
updateVisibility();
$postVisibilitySelect.slideDown('fast').find('input[type="radio"]').first().focus();
$(this).hide();
}
return false;
});
$postVisibilitySelect.find('.cancel-post-visibility').click( function( event ) {
$postVisibilitySelect.slideUp('fast');
$('#visibility-radio-' + $('#hidden-post-visibility').val()).prop('checked', true);
$('#post_password').val($('#hidden-post-password').val());
$('#sticky').prop('checked', $('#hidden-post-sticky').prop('checked'));
$('#post-visibility-display').html(visibility);
$('#visibility .edit-visibility').show().focus();
updateText();
event.preventDefault();
});
$postVisibilitySelect.find('.save-post-visibility').click( function( event ) { // crazyhorse - multiple ok cancels
$postVisibilitySelect.slideUp('fast');
$('#visibility .edit-visibility').show();
updateText();
if ( $postVisibilitySelect.find('input:radio:checked').val() != 'public' ) {
$('#sticky').prop('checked', false);
} // WEAPON LOCKED
if ( $('#sticky').prop('checked') ) {
sticky = 'Sticky';
} else {
sticky = '';
}
$('#post-visibility-display').html( postL10n[ $postVisibilitySelect.find('input:radio:checked').val() + sticky ] );
event.preventDefault();
});
$postVisibilitySelect.find('input:radio').change( function() {
updateVisibility();
});
$timestampdiv.siblings('a.edit-timestamp').click( function( event ) {
if ( $timestampdiv.is( ':hidden' ) ) {
$timestampdiv.slideDown('fast');
$('#mm').focus();
$(this).hide();
}
event.preventDefault();
});
$timestampdiv.find('.cancel-timestamp').click( function( event ) {
$timestampdiv.slideUp('fast').siblings('a.edit-timestamp').show().focus();
$('#mm').val($('#hidden_mm').val());
$('#jj').val($('#hidden_jj').val());
$('#aa').val($('#hidden_aa').val());
$('#hh').val($('#hidden_hh').val());
$('#mn').val($('#hidden_mn').val());
updateText();
event.preventDefault();
});
$timestampdiv.find('.save-timestamp').click( function( event ) { // crazyhorse - multiple ok cancels
if ( updateText() ) {
$timestampdiv.slideUp('fast');
$timestampdiv.siblings('a.edit-timestamp').show();
}
event.preventDefault();
});
$('#post').on( 'submit', function( event ) {
if ( ! updateText() ) {
event.preventDefault();
$timestampdiv.show();
if ( wp.autosave ) {
wp.autosave.enableButtons();
}
$('#publishing-action .spinner').hide();
}
});
$postStatusSelect.siblings('a.edit-post-status').click( function( event ) {
if ( $postStatusSelect.is( ':hidden' ) ) {
$postStatusSelect.slideDown('fast').find('select').focus();
$(this).hide();
}
event.preventDefault();
});
$postStatusSelect.find('.save-post-status').click( function( event ) {
$postStatusSelect.slideUp('fast').siblings('a.edit-post-status').show();
updateText();
event.preventDefault();
});
$postStatusSelect.find('.cancel-post-status').click( function( event ) {
$('#post-status-select').slideUp('fast').siblings( 'a.edit-post-status' ).show().focus();
$('#post_status').val( $('#hidden_post_status').val() );
updateText();
event.preventDefault();
});
} // end submitdiv
// permalink
function editPermalink() {
var i, slug_value,
c = 0,
e = $('#editable-post-name'),
revert_e = e.html(),
real_slug = $('#post_name'),
revert_slug = real_slug.val(),
b = $('#edit-slug-buttons'),
revert_b = b.html(),
full = $('#editable-post-name-full').html();
$('#view-post-btn').hide();
b.html('<a href="#" class="save button button-small">'+postL10n.ok+'</a> <a class="cancel" href="#">'+postL10n.cancel+'</a>');
b.children('.save').click(function() {
var new_slug = e.children('input').val();
if ( new_slug == $('#editable-post-name-full').text() ) {
return $('#edit-slug-buttons .cancel').click();
}
$.post(ajaxurl, {
action: 'sample-permalink',
post_id: postId,
new_slug: new_slug,
new_title: $('#title').val(),
samplepermalinknonce: $('#samplepermalinknonce').val()
}, function(data) {
var box = $('#edit-slug-box');
box.html(data);
if (box.hasClass('hidden')) {
box.fadeIn('fast', function () {
box.removeClass('hidden');
});
}
b.html(revert_b);
real_slug.val(new_slug);
$('#view-post-btn').show();
});
return false;
});
$('#edit-slug-buttons .cancel').click(function() {
$('#view-post-btn').show();
e.html(revert_e);
b.html(revert_b);
real_slug.val(revert_slug);
return false;
});
for ( i = 0; i < full.length; ++i ) {
if ( '%' == full.charAt(i) )
c++;
}
slug_value = ( c > full.length / 4 ) ? '' : full;
e.html('<input type="text" id="new-post-slug" value="'+slug_value+'" />').children('input').keypress(function(e) {
var key = e.keyCode || 0;
// on enter, just save the new slug, don't save the post
if ( 13 == key ) {
b.children('.save').click();
return false;
}
if ( 27 == key ) {
b.children('.cancel').click();
return false;
}
} ).keyup( function() {
real_slug.val(this.value);
}).focus();
}
if ( $editSlugWrap.length ) {
$editSlugWrap.on( 'click', function( event ) {
var $target = $( event.target );
if ( $target.is('#editable-post-name') || $target.hasClass('edit-slug') ) {
editPermalink();
}
});
}
// word count
if ( typeof(wpWordCount) != 'undefined' ) {
$document.triggerHandler('wpcountwords', [ co.val() ]);
co.keyup( function(e) {
var k = e.keyCode || e.charCode;
if ( k == last )
return true;
if ( 13 == k || 8 == last || 46 == last )
$document.triggerHandler('wpcountwords', [ co.val() ]);
last = k;
return true;
});
}
wptitlehint = function(id) {
id = id || 'title';
var title = $('#' + id), titleprompt = $('#' + id + '-prompt-text');
if ( '' === title.val() )
titleprompt.removeClass('screen-reader-text');
titleprompt.click(function(){
$(this).addClass('screen-reader-text');
title.focus();
});
title.blur(function(){
if ( '' === this.value )
titleprompt.removeClass('screen-reader-text');
}).focus(function(){
titleprompt.addClass('screen-reader-text');
}).keydown(function(e){
titleprompt.addClass('screen-reader-text');
$(this).unbind(e);
});
};
wptitlehint();
// Resize the visual and text editors
( function() {
var editor, offset, mce,
$textarea = $('textarea#content'),
$handle = $('#post-status-info');
// No point for touch devices
if ( ! $textarea.length || 'ontouchstart' in window ) {
return;
}
function dragging( event ) {
if ( mce ) {
editor.theme.resizeTo( null, offset + event.pageY );
} else {
$textarea.height( Math.max( 50, offset + event.pageY ) );
}
event.preventDefault();
}
function endDrag() {
var height, toolbarHeight;
if ( mce ) {
editor.focus();
toolbarHeight = $( '#wp-content-editor-container .mce-toolbar-grp' ).height();
if ( toolbarHeight < 10 || toolbarHeight > 200 ) {
toolbarHeight = 30;
}
height = parseInt( $('#content_ifr').css('height'), 10 ) + toolbarHeight - 28;
} else {
$textarea.focus();
height = parseInt( $textarea.css('height'), 10 );
}
$document.off( '.wp-editor-resize' );
// sanity check
if ( height && height > 50 && height < 5000 ) {
setUserSetting( 'ed_size', height );
}
}
$textarea.css( 'resize', 'none' );
$handle.on( 'mousedown.wp-editor-resize', function( event ) {
if ( typeof tinymce !== 'undefined' ) {
editor = tinymce.get('content');
}
if ( editor && ! editor.isHidden() ) {
mce = true;
offset = $('#content_ifr').height() - event.pageY;
} else {
mce = false;
offset = $textarea.height() - event.pageY;
$textarea.blur();
}
$document.on( 'mousemove.wp-editor-resize', dragging )
.on( 'mouseup.wp-editor-resize mouseleave.wp-editor-resize', endDrag );
event.preventDefault();
}).on( 'mouseup.wp-editor-resize', endDrag );
})();
if ( typeof tinymce !== 'undefined' ) {
// When changing post formats, change the editor body class
$( '#post-formats-select input.post-format' ).on( 'change.set-editor-class', function() {
var editor, body, format = this.id;
if ( format && $( this ).prop('checked') ) {
editor = tinymce.get( 'content' );
if ( editor ) {
body = editor.getBody();
body.className = body.className.replace( /\bpost-format-[^ ]+/, '' );
editor.dom.addClass( body, format == 'post-format-0' ? 'post-format-standard' : format );
}
}
});
}
});
| 01-wordpress-paypal | trunk/wp-admin/js/post.js | JavaScript | gpl3 | 31,439 |
/**
* WordPress Administration Navigation Menu
* Interface JS functions
*
* @version 2.0.0
*
* @package WordPress
* @subpackage Administration
*/
/* global menus, postboxes, columns, isRtl, navMenuL10n, ajaxurl */
var wpNavMenu;
(function($) {
var api;
api = wpNavMenu = {
options : {
menuItemDepthPerLevel : 30, // Do not use directly. Use depthToPx and pxToDepth instead.
globalMaxDepth : 11
},
menuList : undefined, // Set in init.
targetList : undefined, // Set in init.
menusChanged : false,
isRTL: !! ( 'undefined' != typeof isRtl && isRtl ),
negateIfRTL: ( 'undefined' != typeof isRtl && isRtl ) ? -1 : 1,
// Functions that run on init.
init : function() {
api.menuList = $('#menu-to-edit');
api.targetList = api.menuList;
this.jQueryExtensions();
this.attachMenuEditListeners();
this.setupInputWithDefaultTitle();
this.attachQuickSearchListeners();
this.attachThemeLocationsListeners();
this.attachTabsPanelListeners();
this.attachUnsavedChangesListener();
if ( api.menuList.length )
this.initSortables();
if ( menus.oneThemeLocationNoMenus )
$( '#posttype-page' ).addSelectedToMenu( api.addMenuItemToBottom );
this.initManageLocations();
this.initAccessibility();
this.initToggles();
},
jQueryExtensions : function() {
// jQuery extensions
$.fn.extend({
menuItemDepth : function() {
var margin = api.isRTL ? this.eq(0).css('margin-right') : this.eq(0).css('margin-left');
return api.pxToDepth( margin && -1 != margin.indexOf('px') ? margin.slice(0, -2) : 0 );
},
updateDepthClass : function(current, prev) {
return this.each(function(){
var t = $(this);
prev = prev || t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ prev )
.addClass('menu-item-depth-'+ current );
});
},
shiftDepthClass : function(change) {
return this.each(function(){
var t = $(this),
depth = t.menuItemDepth();
$(this).removeClass('menu-item-depth-'+ depth )
.addClass('menu-item-depth-'+ (depth + change) );
});
},
childMenuItems : function() {
var result = $();
this.each(function(){
var t = $(this), depth = t.menuItemDepth(), next = t.next();
while( next.length && next.menuItemDepth() > depth ) {
result = result.add( next );
next = next.next();
}
});
return result;
},
shiftHorizontally : function( dir ) {
return this.each(function(){
var t = $(this),
depth = t.menuItemDepth(),
newDepth = depth + dir;
// Change .menu-item-depth-n class
t.moveHorizontally( newDepth, depth );
});
},
moveHorizontally : function( newDepth, depth ) {
return this.each(function(){
var t = $(this),
children = t.childMenuItems(),
diff = newDepth - depth,
subItemText = t.find('.is-submenu');
// Change .menu-item-depth-n class
t.updateDepthClass( newDepth, depth ).updateParentMenuItemDBId();
// If it has children, move those too
if ( children ) {
children.each(function() {
var t = $(this),
thisDepth = t.menuItemDepth(),
newDepth = thisDepth + diff;
t.updateDepthClass(newDepth, thisDepth).updateParentMenuItemDBId();
});
}
// Show "Sub item" helper text
if (0 === newDepth)
subItemText.hide();
else
subItemText.show();
});
},
updateParentMenuItemDBId : function() {
return this.each(function(){
var item = $(this),
input = item.find( '.menu-item-data-parent-id' ),
depth = parseInt( item.menuItemDepth(), 10 ),
parentDepth = depth - 1,
parent = item.prevAll( '.menu-item-depth-' + parentDepth ).first();
if ( 0 === depth ) { // Item is on the top level, has no parent
input.val(0);
} else { // Find the parent item, and retrieve its object id.
input.val( parent.find( '.menu-item-data-db-id' ).val() );
}
});
},
hideAdvancedMenuItemFields : function() {
return this.each(function(){
var that = $(this);
$('.hide-column-tog').not(':checked').each(function(){
that.find('.field-' + $(this).val() ).addClass('hidden-field');
});
});
},
/**
* Adds selected menu items to the menu.
*
* @param jQuery metabox The metabox jQuery object.
*/
addSelectedToMenu : function(processMethod) {
if ( 0 === $('#menu-to-edit').length ) {
return false;
}
return this.each(function() {
var t = $(this), menuItems = {},
checkboxes = ( menus.oneThemeLocationNoMenus && 0 === t.find( '.tabs-panel-active .categorychecklist li input:checked' ).length ) ? t.find( '#page-all li input[type="checkbox"]' ) : t.find( '.tabs-panel-active .categorychecklist li input:checked' ),
re = /menu-item\[([^\]]*)/;
processMethod = processMethod || api.addMenuItemToBottom;
// If no items are checked, bail.
if ( !checkboxes.length )
return false;
// Show the ajax spinner
t.find('.spinner').show();
// Retrieve menu item data
$(checkboxes).each(function(){
var t = $(this),
listItemDBIDMatch = re.exec( t.attr('name') ),
listItemDBID = 'undefined' == typeof listItemDBIDMatch[1] ? 0 : parseInt(listItemDBIDMatch[1], 10);
if ( this.className && -1 != this.className.indexOf('add-to-top') )
processMethod = api.addMenuItemToTop;
menuItems[listItemDBID] = t.closest('li').getItemData( 'add-menu-item', listItemDBID );
});
// Add the items
api.addItemToMenu(menuItems, processMethod, function(){
// Deselect the items and hide the ajax spinner
checkboxes.removeAttr('checked');
t.find('.spinner').hide();
});
});
},
getItemData : function( itemType, id ) {
itemType = itemType || 'menu-item';
var itemData = {}, i,
fields = [
'menu-item-db-id',
'menu-item-object-id',
'menu-item-object',
'menu-item-parent-id',
'menu-item-position',
'menu-item-type',
'menu-item-title',
'menu-item-url',
'menu-item-description',
'menu-item-attr-title',
'menu-item-target',
'menu-item-classes',
'menu-item-xfn'
];
if( !id && itemType == 'menu-item' ) {
id = this.find('.menu-item-data-db-id').val();
}
if( !id ) return itemData;
this.find('input').each(function() {
var field;
i = fields.length;
while ( i-- ) {
if( itemType == 'menu-item' )
field = fields[i] + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + fields[i] + ']';
if (
this.name &&
field == this.name
) {
itemData[fields[i]] = this.value;
}
}
});
return itemData;
},
setItemData : function( itemData, itemType, id ) { // Can take a type, such as 'menu-item', or an id.
itemType = itemType || 'menu-item';
if( !id && itemType == 'menu-item' ) {
id = $('.menu-item-data-db-id', this).val();
}
if( !id ) return this;
this.find('input').each(function() {
var t = $(this), field;
$.each( itemData, function( attr, val ) {
if( itemType == 'menu-item' )
field = attr + '[' + id + ']';
else if( itemType == 'add-menu-item' )
field = 'menu-item[' + id + '][' + attr + ']';
if ( field == t.attr('name') ) {
t.val( val );
}
});
});
return this;
}
});
},
countMenuItems : function( depth ) {
return $( '.menu-item-depth-' + depth ).length;
},
moveMenuItem : function( $this, dir ) {
var items, newItemPosition, newDepth,
menuItems = $( '#menu-to-edit li' ),
menuItemsCount = menuItems.length,
thisItem = $this.parents( 'li.menu-item' ),
thisItemChildren = thisItem.childMenuItems(),
thisItemData = thisItem.getItemData(),
thisItemDepth = parseInt( thisItem.menuItemDepth(), 10 ),
thisItemPosition = parseInt( thisItem.index(), 10 ),
nextItem = thisItem.next(),
nextItemChildren = nextItem.childMenuItems(),
nextItemDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1,
prevItem = thisItem.prev(),
prevItemDepth = parseInt( prevItem.menuItemDepth(), 10 ),
prevItemId = prevItem.getItemData()['menu-item-db-id'];
switch ( dir ) {
case 'up':
newItemPosition = thisItemPosition - 1;
// Already at top
if ( 0 === thisItemPosition )
break;
// If a sub item is moved to top, shift it to 0 depth
if ( 0 === newItemPosition && 0 !== thisItemDepth )
thisItem.moveHorizontally( 0, thisItemDepth );
// If prev item is sub item, shift to match depth
if ( 0 !== prevItemDepth )
thisItem.moveHorizontally( prevItemDepth, thisItemDepth );
// Does this item have sub items?
if ( thisItemChildren ) {
items = thisItem.add( thisItemChildren );
// Move the entire block
items.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
} else {
thisItem.detach().insertBefore( menuItems.eq( newItemPosition ) ).updateParentMenuItemDBId();
}
break;
case 'down':
// Does this item have sub items?
if ( thisItemChildren ) {
items = thisItem.add( thisItemChildren ),
nextItem = menuItems.eq( items.length + thisItemPosition ),
nextItemChildren = 0 !== nextItem.childMenuItems().length;
if ( nextItemChildren ) {
newDepth = parseInt( nextItem.menuItemDepth(), 10 ) + 1;
thisItem.moveHorizontally( newDepth, thisItemDepth );
}
// Have we reached the bottom?
if ( menuItemsCount === thisItemPosition + items.length )
break;
items.detach().insertAfter( menuItems.eq( thisItemPosition + items.length ) ).updateParentMenuItemDBId();
} else {
// If next item has sub items, shift depth
if ( 0 !== nextItemChildren.length )
thisItem.moveHorizontally( nextItemDepth, thisItemDepth );
// Have we reached the bottom
if ( menuItemsCount === thisItemPosition + 1 )
break;
thisItem.detach().insertAfter( menuItems.eq( thisItemPosition + 1 ) ).updateParentMenuItemDBId();
}
break;
case 'top':
// Already at top
if ( 0 === thisItemPosition )
break;
// Does this item have sub items?
if ( thisItemChildren ) {
items = thisItem.add( thisItemChildren );
// Move the entire block
items.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
} else {
thisItem.detach().insertBefore( menuItems.eq( 0 ) ).updateParentMenuItemDBId();
}
break;
case 'left':
// As far left as possible
if ( 0 === thisItemDepth )
break;
thisItem.shiftHorizontally( -1 );
break;
case 'right':
// Can't be sub item at top
if ( 0 === thisItemPosition )
break;
// Already sub item of prevItem
if ( thisItemData['menu-item-parent-id'] === prevItemId )
break;
thisItem.shiftHorizontally( 1 );
break;
}
$this.focus();
api.registerChange();
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
initAccessibility : function() {
var menu = $( '#menu-to-edit' );
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
// Events
menu.on( 'click', '.menus-move-up', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'up' );
e.preventDefault();
});
menu.on( 'click', '.menus-move-down', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'down' );
e.preventDefault();
});
menu.on( 'click', '.menus-move-top', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'top' );
e.preventDefault();
});
menu.on( 'click', '.menus-move-left', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'left' );
e.preventDefault();
});
menu.on( 'click', '.menus-move-right', function ( e ) {
api.moveMenuItem( $( this ).parents( 'li.menu-item' ).find( 'a.item-edit' ), 'right' );
e.preventDefault();
});
},
refreshAdvancedAccessibility : function() {
// Hide all links by default
$( '.menu-item-settings .field-move a' ).css( 'display', 'none' );
$( '.item-edit' ).each( function() {
var thisLink, thisLinkText, primaryItems, itemPosition, title,
parentItem, parentItemId, parentItemName, subItems,
$this = $(this),
menuItem = $this.closest( 'li.menu-item' ).first(),
depth = menuItem.menuItemDepth(),
isPrimaryMenuItem = ( 0 === depth ),
itemName = $this.closest( '.menu-item-handle' ).find( '.menu-item-title' ).text(),
position = parseInt( menuItem.index(), 10 ),
prevItemDepth = ( isPrimaryMenuItem ) ? depth : parseInt( depth - 1, 10 ),
prevItemNameLeft = menuItem.prevAll('.menu-item-depth-' + prevItemDepth).first().find( '.menu-item-title' ).text(),
prevItemNameRight = menuItem.prevAll('.menu-item-depth-' + depth).first().find( '.menu-item-title' ).text(),
totalMenuItems = $('#menu-to-edit li').length,
hasSameDepthSibling = menuItem.nextAll( '.menu-item-depth-' + depth ).length;
// Where can they move this menu item?
if ( 0 !== position ) {
thisLink = menuItem.find( '.menus-move-up' );
thisLink.prop( 'title', menus.moveUp ).css( 'display', 'inline' );
}
if ( 0 !== position && isPrimaryMenuItem ) {
thisLink = menuItem.find( '.menus-move-top' );
thisLink.prop( 'title', menus.moveToTop ).css( 'display', 'inline' );
}
if ( position + 1 !== totalMenuItems && 0 !== position ) {
thisLink = menuItem.find( '.menus-move-down' );
thisLink.prop( 'title', menus.moveDown ).css( 'display', 'inline' );
}
if ( 0 === position && 0 !== hasSameDepthSibling ) {
thisLink = menuItem.find( '.menus-move-down' );
thisLink.prop( 'title', menus.moveDown ).css( 'display', 'inline' );
}
if ( ! isPrimaryMenuItem ) {
thisLink = menuItem.find( '.menus-move-left' ),
thisLinkText = menus.outFrom.replace( '%s', prevItemNameLeft );
thisLink.prop( 'title', menus.moveOutFrom.replace( '%s', prevItemNameLeft ) ).html( thisLinkText ).css( 'display', 'inline' );
}
if ( 0 !== position ) {
if ( menuItem.find( '.menu-item-data-parent-id' ).val() !== menuItem.prev().find( '.menu-item-data-db-id' ).val() ) {
thisLink = menuItem.find( '.menus-move-right' ),
thisLinkText = menus.under.replace( '%s', prevItemNameRight );
thisLink.prop( 'title', menus.moveUnder.replace( '%s', prevItemNameRight ) ).html( thisLinkText ).css( 'display', 'inline' );
}
}
if ( isPrimaryMenuItem ) {
primaryItems = $( '.menu-item-depth-0' ),
itemPosition = primaryItems.index( menuItem ) + 1,
totalMenuItems = primaryItems.length,
// String together help text for primary menu items
title = menus.menuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$d', totalMenuItems );
} else {
parentItem = menuItem.prevAll( '.menu-item-depth-' + parseInt( depth - 1, 10 ) ).first(),
parentItemId = parentItem.find( '.menu-item-data-db-id' ).val(),
parentItemName = parentItem.find( '.menu-item-title' ).text(),
subItems = $( '.menu-item .menu-item-data-parent-id[value="' + parentItemId + '"]' ),
itemPosition = $( subItems.parents('.menu-item').get().reverse() ).index( menuItem ) + 1;
// String together help text for sub menu items
title = menus.subMenuFocus.replace( '%1$s', itemName ).replace( '%2$d', itemPosition ).replace( '%3$s', parentItemName );
}
$this.prop('title', title).html( title );
});
},
refreshKeyboardAccessibility : function() {
$( '.item-edit' ).off( 'focus' ).on( 'focus', function(){
$(this).off( 'keydown' ).on( 'keydown', function(e){
var arrows,
$this = $( this ),
thisItem = $this.parents( 'li.menu-item' ),
thisItemData = thisItem.getItemData();
// Bail if it's not an arrow key
if ( 37 != e.which && 38 != e.which && 39 != e.which && 40 != e.which )
return;
// Avoid multiple keydown events
$this.off('keydown');
// Bail if there is only one menu item
if ( 1 === $('#menu-to-edit li').length )
return;
// If RTL, swap left/right arrows
arrows = { '38': 'up', '40': 'down', '37': 'left', '39': 'right' };
if ( $('body').hasClass('rtl') )
arrows = { '38' : 'up', '40' : 'down', '39' : 'left', '37' : 'right' };
switch ( arrows[e.which] ) {
case 'up':
api.moveMenuItem( $this, 'up' );
break;
case 'down':
api.moveMenuItem( $this, 'down' );
break;
case 'left':
api.moveMenuItem( $this, 'left' );
break;
case 'right':
api.moveMenuItem( $this, 'right' );
break;
}
// Put focus back on same menu item
$( '#edit-' + thisItemData['menu-item-db-id'] ).focus();
return false;
});
});
},
initToggles : function() {
// init postboxes
postboxes.add_postbox_toggles('nav-menus');
// adjust columns functions for menus UI
columns.useCheckboxesForHidden();
columns.checked = function(field) {
$('.field-' + field).removeClass('hidden-field');
};
columns.unchecked = function(field) {
$('.field-' + field).addClass('hidden-field');
};
// hide fields
api.menuList.hideAdvancedMenuItemFields();
$('.hide-postbox-tog').click(function () {
var hidden = $( '.accordion-container li.accordion-section' ).filter(':hidden').map(function() { return this.id; }).get().join(',');
$.post(ajaxurl, {
action: 'closed-postboxes',
hidden: hidden,
closedpostboxesnonce: jQuery('#closedpostboxesnonce').val(),
page: 'nav-menus'
});
});
},
initSortables : function() {
var currentDepth = 0, originalDepth, minDepth, maxDepth,
prev, next, prevBottom, nextThreshold, helperHeight, transport,
menuEdge = api.menuList.offset().left,
body = $('body'), maxChildDepth,
menuMaxDepth = initialMenuMaxDepth();
if( 0 !== $( '#menu-to-edit li' ).length )
$( '.drag-instructions' ).show();
// Use the right edge if RTL.
menuEdge += api.isRTL ? api.menuList.width() : 0;
api.menuList.sortable({
handle: '.menu-item-handle',
placeholder: 'sortable-placeholder',
start: function(e, ui) {
var height, width, parent, children, tempHolder;
// handle placement for rtl orientation
if ( api.isRTL )
ui.item[0].style.right = 'auto';
transport = ui.item.children('.menu-item-transport');
// Set depths. currentDepth must be set before children are located.
originalDepth = ui.item.menuItemDepth();
updateCurrentDepth(ui, originalDepth);
// Attach child elements to parent
// Skip the placeholder
parent = ( ui.item.next()[0] == ui.placeholder[0] ) ? ui.item.next() : ui.item;
children = parent.childMenuItems();
transport.append( children );
// Update the height of the placeholder to match the moving item.
height = transport.outerHeight();
// If there are children, account for distance between top of children and parent
height += ( height > 0 ) ? (ui.placeholder.css('margin-top').slice(0, -2) * 1) : 0;
height += ui.helper.outerHeight();
helperHeight = height;
height -= 2; // Subtract 2 for borders
ui.placeholder.height(height);
// Update the width of the placeholder to match the moving item.
maxChildDepth = originalDepth;
children.each(function(){
var depth = $(this).menuItemDepth();
maxChildDepth = (depth > maxChildDepth) ? depth : maxChildDepth;
});
width = ui.helper.find('.menu-item-handle').outerWidth(); // Get original width
width += api.depthToPx(maxChildDepth - originalDepth); // Account for children
width -= 2; // Subtract 2 for borders
ui.placeholder.width(width);
// Update the list of menu items.
tempHolder = ui.placeholder.next();
tempHolder.css( 'margin-top', helperHeight + 'px' ); // Set the margin to absorb the placeholder
ui.placeholder.detach(); // detach or jQuery UI will think the placeholder is a menu item
$(this).sortable( 'refresh' ); // The children aren't sortable. We should let jQ UI know.
ui.item.after( ui.placeholder ); // reattach the placeholder.
tempHolder.css('margin-top', 0); // reset the margin
// Now that the element is complete, we can update...
updateSharedVars(ui);
},
stop: function(e, ui) {
var children, subMenuTitle,
depthChange = currentDepth - originalDepth;
// Return child elements to the list
children = transport.children().insertAfter(ui.item);
// Add "sub menu" description
subMenuTitle = ui.item.find( '.item-title .is-submenu' );
if ( 0 < currentDepth )
subMenuTitle.show();
else
subMenuTitle.hide();
// Update depth classes
if ( 0 !== depthChange ) {
ui.item.updateDepthClass( currentDepth );
children.shiftDepthClass( depthChange );
updateMenuMaxDepth( depthChange );
}
// Register a change
api.registerChange();
// Update the item data.
ui.item.updateParentMenuItemDBId();
// address sortable's incorrectly-calculated top in opera
ui.item[0].style.top = 0;
// handle drop placement for rtl orientation
if ( api.isRTL ) {
ui.item[0].style.left = 'auto';
ui.item[0].style.right = 0;
}
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
change: function(e, ui) {
// Make sure the placeholder is inside the menu.
// Otherwise fix it, or we're in trouble.
if( ! ui.placeholder.parent().hasClass('menu') )
(prev.length) ? prev.after( ui.placeholder ) : api.menuList.prepend( ui.placeholder );
updateSharedVars(ui);
},
sort: function(e, ui) {
var offset = ui.helper.offset(),
edge = api.isRTL ? offset.left + ui.helper.width() : offset.left,
depth = api.negateIfRTL * api.pxToDepth( edge - menuEdge );
// Check and correct if depth is not within range.
// Also, if the dragged element is dragged upwards over
// an item, shift the placeholder to a child position.
if ( depth > maxDepth || offset.top < prevBottom ) depth = maxDepth;
else if ( depth < minDepth ) depth = minDepth;
if( depth != currentDepth )
updateCurrentDepth(ui, depth);
// If we overlap the next element, manually shift downwards
if( nextThreshold && offset.top + helperHeight > nextThreshold ) {
next.after( ui.placeholder );
updateSharedVars( ui );
$( this ).sortable( 'refreshPositions' );
}
}
});
function updateSharedVars(ui) {
var depth;
prev = ui.placeholder.prev();
next = ui.placeholder.next();
// Make sure we don't select the moving item.
if( prev[0] == ui.item[0] ) prev = prev.prev();
if( next[0] == ui.item[0] ) next = next.next();
prevBottom = (prev.length) ? prev.offset().top + prev.height() : 0;
nextThreshold = (next.length) ? next.offset().top + next.height() / 3 : 0;
minDepth = (next.length) ? next.menuItemDepth() : 0;
if( prev.length )
maxDepth = ( (depth = prev.menuItemDepth() + 1) > api.options.globalMaxDepth ) ? api.options.globalMaxDepth : depth;
else
maxDepth = 0;
}
function updateCurrentDepth(ui, depth) {
ui.placeholder.updateDepthClass( depth, currentDepth );
currentDepth = depth;
}
function initialMenuMaxDepth() {
if( ! body[0].className ) return 0;
var match = body[0].className.match(/menu-max-depth-(\d+)/);
return match && match[1] ? parseInt( match[1], 10 ) : 0;
}
function updateMenuMaxDepth( depthChange ) {
var depth, newDepth = menuMaxDepth;
if ( depthChange === 0 ) {
return;
} else if ( depthChange > 0 ) {
depth = maxChildDepth + depthChange;
if( depth > menuMaxDepth )
newDepth = depth;
} else if ( depthChange < 0 && maxChildDepth == menuMaxDepth ) {
while( ! $('.menu-item-depth-' + newDepth, api.menuList).length && newDepth > 0 )
newDepth--;
}
// Update the depth class.
body.removeClass( 'menu-max-depth-' + menuMaxDepth ).addClass( 'menu-max-depth-' + newDepth );
menuMaxDepth = newDepth;
}
},
initManageLocations : function () {
$('#menu-locations-wrap form').submit(function(){
window.onbeforeunload = null;
});
$('.menu-location-menus select').on('change', function () {
var editLink = $(this).closest('tr').find('.locations-edit-menu-link');
if ($(this).find('option:selected').data('orig'))
editLink.show();
else
editLink.hide();
});
},
attachMenuEditListeners : function() {
var that = this;
$('#update-nav-menu').bind('click', function(e) {
if ( e.target && e.target.className ) {
if ( -1 != e.target.className.indexOf('item-edit') ) {
return that.eventOnClickEditLink(e.target);
} else if ( -1 != e.target.className.indexOf('menu-save') ) {
return that.eventOnClickMenuSave(e.target);
} else if ( -1 != e.target.className.indexOf('menu-delete') ) {
return that.eventOnClickMenuDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-delete') ) {
return that.eventOnClickMenuItemDelete(e.target);
} else if ( -1 != e.target.className.indexOf('item-cancel') ) {
return that.eventOnClickCancelLink(e.target);
}
}
});
$('#add-custom-links input[type="text"]').keypress(function(e){
if ( e.keyCode === 13 ) {
e.preventDefault();
$( '#submit-customlinkdiv' ).click();
}
});
},
/**
* An interface for managing default values for input elements
* that is both JS and accessibility-friendly.
*
* Input elements that add the class 'input-with-default-title'
* will have their values set to the provided HTML title when empty.
*/
setupInputWithDefaultTitle : function() {
var name = 'input-with-default-title';
$('.' + name).each( function(){
var $t = $(this), title = $t.attr('title'), val = $t.val();
$t.data( name, title );
if( '' === val ) $t.val( title );
else if ( title == val ) return;
else $t.removeClass( name );
}).focus( function(){
var $t = $(this);
if( $t.val() == $t.data(name) )
$t.val('').removeClass( name );
}).blur( function(){
var $t = $(this);
if( '' === $t.val() )
$t.addClass( name ).val( $t.data(name) );
});
$( '.blank-slate .input-with-default-title' ).focus();
},
attachThemeLocationsListeners : function() {
var loc = $('#nav-menu-theme-locations'), params = {};
params.action = 'menu-locations-save';
params['menu-settings-column-nonce'] = $('#menu-settings-column-nonce').val();
loc.find('input[type="submit"]').click(function() {
loc.find('select').each(function() {
params[this.name] = $(this).val();
});
loc.find('.spinner').show();
$.post( ajaxurl, params, function() {
loc.find('.spinner').hide();
});
return false;
});
},
attachQuickSearchListeners : function() {
var searchTimer;
$('.quick-search').keypress(function(e){
var t = $(this);
if( 13 == e.which ) {
api.updateQuickSearchResults( t );
return false;
}
if( searchTimer ) clearTimeout(searchTimer);
searchTimer = setTimeout(function(){
api.updateQuickSearchResults( t );
}, 400);
}).attr('autocomplete','off');
},
updateQuickSearchResults : function(input) {
var panel, params,
minSearchLength = 2,
q = input.val();
if( q.length < minSearchLength ) return;
panel = input.parents('.tabs-panel');
params = {
'action': 'menu-quick-search',
'response-format': 'markup',
'menu': $('#menu').val(),
'menu-settings-column-nonce': $('#menu-settings-column-nonce').val(),
'q': q,
'type': input.attr('name')
};
$('.spinner', panel).show();
$.post( ajaxurl, params, function(menuMarkup) {
api.processQuickSearchQueryResponse(menuMarkup, params, panel);
});
},
addCustomLink : function( processMethod ) {
var url = $('#custom-menu-item-url').val(),
label = $('#custom-menu-item-name').val();
processMethod = processMethod || api.addMenuItemToBottom;
if ( '' === url || 'http://' == url )
return false;
// Show the ajax spinner
$('.customlinkdiv .spinner').show();
this.addLinkToMenu( url, label, processMethod, function() {
// Remove the ajax spinner
$('.customlinkdiv .spinner').hide();
// Set custom link form back to defaults
$('#custom-menu-item-name').val('').blur();
$('#custom-menu-item-url').val('http://');
});
},
addLinkToMenu : function(url, label, processMethod, callback) {
processMethod = processMethod || api.addMenuItemToBottom;
callback = callback || function(){};
api.addItemToMenu({
'-1': {
'menu-item-type': 'custom',
'menu-item-url': url,
'menu-item-title': label
}
}, processMethod, callback);
},
addItemToMenu : function(menuItem, processMethod, callback) {
var menu = $('#menu').val(),
nonce = $('#menu-settings-column-nonce').val(),
params;
processMethod = processMethod || function(){};
callback = callback || function(){};
params = {
'action': 'add-menu-item',
'menu': menu,
'menu-settings-column-nonce': nonce,
'menu-item': menuItem
};
$.post( ajaxurl, params, function(menuMarkup) {
var ins = $('#menu-instructions');
menuMarkup = $.trim( menuMarkup ); // Trim leading whitespaces
processMethod(menuMarkup, params);
// Make it stand out a bit more visually, by adding a fadeIn
$( 'li.pending' ).hide().fadeIn('slow');
$( '.drag-instructions' ).show();
if( ! ins.hasClass( 'menu-instructions-inactive' ) && ins.siblings().length )
ins.addClass( 'menu-instructions-inactive' );
callback();
});
},
/**
* Process the add menu item request response into menu list item.
*
* @param string menuMarkup The text server response of menu item markup.
* @param object req The request arguments.
*/
addMenuItemToBottom : function( menuMarkup ) {
$(menuMarkup).hideAdvancedMenuItemFields().appendTo( api.targetList );
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
addMenuItemToTop : function( menuMarkup ) {
$(menuMarkup).hideAdvancedMenuItemFields().prependTo( api.targetList );
api.refreshKeyboardAccessibility();
api.refreshAdvancedAccessibility();
},
attachUnsavedChangesListener : function() {
$('#menu-management input, #menu-management select, #menu-management, #menu-management textarea, .menu-location-menus select').change(function(){
api.registerChange();
});
if ( 0 !== $('#menu-to-edit').length || 0 !== $('.menu-location-menus select').length ) {
window.onbeforeunload = function(){
if ( api.menusChanged )
return navMenuL10n.saveAlert;
};
} else {
// Make the post boxes read-only, as they can't be used yet
$( '#menu-settings-column' ).find( 'input,select' ).end().find( 'a' ).attr( 'href', '#' ).unbind( 'click' );
}
},
registerChange : function() {
api.menusChanged = true;
},
attachTabsPanelListeners : function() {
$('#menu-settings-column').bind('click', function(e) {
var selectAreaMatch, panelId, wrapper, items,
target = $(e.target);
if ( target.hasClass('nav-tab-link') ) {
panelId = target.data( 'type' );
wrapper = target.parents('.accordion-section-content').first();
// upon changing tabs, we want to uncheck all checkboxes
$('input', wrapper).removeAttr('checked');
$('.tabs-panel-active', wrapper).removeClass('tabs-panel-active').addClass('tabs-panel-inactive');
$('#' + panelId, wrapper).removeClass('tabs-panel-inactive').addClass('tabs-panel-active');
$('.tabs', wrapper).removeClass('tabs');
target.parent().addClass('tabs');
// select the search bar
$('.quick-search', wrapper).focus();
e.preventDefault();
} else if ( target.hasClass('select-all') ) {
selectAreaMatch = /#(.*)$/.exec(e.target.href);
if ( selectAreaMatch && selectAreaMatch[1] ) {
items = $('#' + selectAreaMatch[1] + ' .tabs-panel-active .menu-item-title input');
if( items.length === items.filter(':checked').length )
items.removeAttr('checked');
else
items.prop('checked', true);
return false;
}
} else if ( target.hasClass('submit-add-to-menu') ) {
api.registerChange();
if ( e.target.id && 'submit-customlinkdiv' == e.target.id )
api.addCustomLink( api.addMenuItemToBottom );
else if ( e.target.id && -1 != e.target.id.indexOf('submit-') )
$('#' + e.target.id.replace(/submit-/, '')).addSelectedToMenu( api.addMenuItemToBottom );
return false;
} else if ( target.hasClass('page-numbers') ) {
$.post( ajaxurl, e.target.href.replace(/.*\?/, '').replace(/action=([^&]*)/, '') + '&action=menu-get-metabox',
function( resp ) {
if ( -1 == resp.indexOf('replace-id') )
return;
var metaBoxData = $.parseJSON(resp),
toReplace = document.getElementById(metaBoxData['replace-id']),
placeholder = document.createElement('div'),
wrap = document.createElement('div');
if ( ! metaBoxData.markup || ! toReplace )
return;
wrap.innerHTML = metaBoxData.markup ? metaBoxData.markup : '';
toReplace.parentNode.insertBefore( placeholder, toReplace );
placeholder.parentNode.removeChild( toReplace );
placeholder.parentNode.insertBefore( wrap, placeholder );
placeholder.parentNode.removeChild( placeholder );
}
);
return false;
}
});
},
eventOnClickEditLink : function(clickedEl) {
var settings, item,
matchedSection = /#(.*)$/.exec(clickedEl.href);
if ( matchedSection && matchedSection[1] ) {
settings = $('#'+matchedSection[1]);
item = settings.parent();
if( 0 !== item.length ) {
if( item.hasClass('menu-item-edit-inactive') ) {
if( ! settings.data('menu-item-data') ) {
settings.data( 'menu-item-data', settings.getItemData() );
}
settings.slideDown('fast');
item.removeClass('menu-item-edit-inactive')
.addClass('menu-item-edit-active');
} else {
settings.slideUp('fast');
item.removeClass('menu-item-edit-active')
.addClass('menu-item-edit-inactive');
}
return false;
}
}
},
eventOnClickCancelLink : function(clickedEl) {
var settings = $( clickedEl ).closest( '.menu-item-settings' ),
thisMenuItem = $( clickedEl ).closest( '.menu-item' );
thisMenuItem.removeClass('menu-item-edit-active').addClass('menu-item-edit-inactive');
settings.setItemData( settings.data('menu-item-data') ).hide();
return false;
},
eventOnClickMenuSave : function() {
var locs = '',
menuName = $('#menu-name'),
menuNameVal = menuName.val();
// Cancel and warn if invalid menu name
if( !menuNameVal || menuNameVal == menuName.attr('title') || !menuNameVal.replace(/\s+/, '') ) {
menuName.parent().addClass('form-invalid');
return false;
}
// Copy menu theme locations
$('#nav-menu-theme-locations select').each(function() {
locs += '<input type="hidden" name="' + this.name + '" value="' + $(this).val() + '" />';
});
$('#update-nav-menu').append( locs );
// Update menu item position data
api.menuList.find('.menu-item-data-position').val( function(index) { return index + 1; } );
window.onbeforeunload = null;
return true;
},
eventOnClickMenuDelete : function() {
// Delete warning AYS
if ( window.confirm( navMenuL10n.warnDeleteMenu ) ) {
window.onbeforeunload = null;
return true;
}
return false;
},
eventOnClickMenuItemDelete : function(clickedEl) {
var itemID = parseInt(clickedEl.id.replace('delete-', ''), 10);
api.removeMenuItem( $('#menu-item-' + itemID) );
api.registerChange();
return false;
},
/**
* Process the quick search response into a search result
*
* @param string resp The server response to the query.
* @param object req The request arguments.
* @param jQuery panel The tabs panel we're searching in.
*/
processQuickSearchQueryResponse : function(resp, req, panel) {
var matched, newID,
takenIDs = {},
form = document.getElementById('nav-menu-meta'),
pattern = /menu-item[(\[^]\]*/,
$items = $('<div>').html(resp).find('li'),
$item;
if( ! $items.length ) {
$('.categorychecklist', panel).html( '<li><p>' + navMenuL10n.noResultsFound + '</p></li>' );
$('.spinner', panel).hide();
return;
}
$items.each(function(){
$item = $(this);
// make a unique DB ID number
matched = pattern.exec($item.html());
if ( matched && matched[1] ) {
newID = matched[1];
while( form.elements['menu-item[' + newID + '][menu-item-type]'] || takenIDs[ newID ] ) {
newID--;
}
takenIDs[newID] = true;
if ( newID != matched[1] ) {
$item.html( $item.html().replace(new RegExp(
'menu-item\\[' + matched[1] + '\\]', 'g'),
'menu-item[' + newID + ']'
) );
}
}
});
$('.categorychecklist', panel).html( $items );
$('.spinner', panel).hide();
},
removeMenuItem : function(el) {
var children = el.childMenuItems();
el.addClass('deleting').animate({
opacity : 0,
height: 0
}, 350, function() {
var ins = $('#menu-instructions');
el.remove();
children.shiftDepthClass( -1 ).updateParentMenuItemDBId();
if ( 0 === $( '#menu-to-edit li' ).length ) {
$( '.drag-instructions' ).hide();
ins.removeClass( 'menu-instructions-inactive' );
}
});
},
depthToPx : function(depth) {
return depth * api.options.menuItemDepthPerLevel;
},
pxToDepth : function(px) {
return Math.floor(px / api.options.menuItemDepthPerLevel);
}
};
$(document).ready(function(){ wpNavMenu.init(); });
})(jQuery);
| 01-wordpress-paypal | trunk/wp-admin/js/nav-menu.js | JavaScript | gpl3 | 38,480 |
/*global ajaxurl, isRtl */
var wpWidgets;
(function($) {
wpWidgets = {
init : function() {
var rem, the_id,
self = this,
chooser = $('.widgets-chooser'),
selectSidebar = chooser.find('.widgets-chooser-sidebars'),
sidebars = $('div.widgets-sortables'),
isRTL = !! ( 'undefined' !== typeof isRtl && isRtl );
$('#widgets-right .sidebar-name').click( function() {
var $this = $(this),
$wrap = $this.closest('.widgets-holder-wrap');
if ( $wrap.hasClass('closed') ) {
$wrap.removeClass('closed');
$this.parent().sortable('refresh');
} else {
$wrap.addClass('closed');
}
});
$('#widgets-left .sidebar-name').click( function() {
$(this).closest('.widgets-holder-wrap').toggleClass('closed');
});
$(document.body).bind('click.widgets-toggle', function(e) {
var target = $(e.target),
css = { 'z-index': 100 },
widget, inside, targetWidth, widgetWidth, margin;
if ( target.parents('.widget-top').length && ! target.parents('#available-widgets').length ) {
widget = target.closest('div.widget');
inside = widget.children('.widget-inside');
targetWidth = parseInt( widget.find('input.widget-width').val(), 10 ),
widgetWidth = widget.parent().width();
if ( inside.is(':hidden') ) {
if ( targetWidth > 250 && ( targetWidth + 30 > widgetWidth ) && widget.closest('div.widgets-sortables').length ) {
if ( widget.closest('div.widget-liquid-right').length ) {
margin = isRTL ? 'margin-right' : 'margin-left';
} else {
margin = isRTL ? 'margin-left' : 'margin-right';
}
css[ margin ] = widgetWidth - ( targetWidth + 30 ) + 'px';
widget.css( css );
}
inside.slideDown('fast');
} else {
inside.slideUp('fast', function() {
widget.attr( 'style', '' );
});
}
e.preventDefault();
} else if ( target.hasClass('widget-control-save') ) {
wpWidgets.save( target.closest('div.widget'), 0, 1, 0 );
e.preventDefault();
} else if ( target.hasClass('widget-control-remove') ) {
wpWidgets.save( target.closest('div.widget'), 1, 1, 0 );
e.preventDefault();
} else if ( target.hasClass('widget-control-close') ) {
wpWidgets.close( target.closest('div.widget') );
e.preventDefault();
}
});
sidebars.children('.widget').each( function() {
var $this = $(this);
wpWidgets.appendTitle( this );
if ( $this.find( 'p.widget-error' ).length ) {
$this.find( 'a.widget-action' ).trigger('click');
}
});
$('#widget-list').children('.widget').draggable({
connectToSortable: 'div.widgets-sortables',
handle: '> .widget-top > .widget-title',
distance: 2,
helper: 'clone',
zIndex: 100,
containment: 'document',
start: function( event, ui ) {
var chooser = $(this).find('.widgets-chooser');
ui.helper.find('div.widget-description').hide();
the_id = this.id;
if ( chooser.length ) {
// Hide the chooser and move it out of the widget
$( '#wpbody-content' ).append( chooser.hide() );
// Delete the cloned chooser from the drag helper
ui.helper.find('.widgets-chooser').remove();
self.clearWidgetSelection();
}
},
stop: function() {
if ( rem ) {
$(rem).hide();
}
rem = '';
}
});
sidebars.sortable({
placeholder: 'widget-placeholder',
items: '> .widget',
handle: '> .widget-top > .widget-title',
cursor: 'move',
distance: 2,
containment: 'document',
start: function( event, ui ) {
var height, $this = $(this),
$wrap = $this.parent(),
inside = ui.item.children('.widget-inside');
if ( inside.css('display') === 'block' ) {
inside.hide();
$(this).sortable('refreshPositions');
}
if ( ! $wrap.hasClass('closed') ) {
// Lock all open sidebars min-height when starting to drag.
// Prevents jumping when dragging a widget from an open sidebar to a closed sidebar below.
height = ui.item.hasClass('ui-draggable') ? $this.height() : 1 + $this.height();
$this.css( 'min-height', height + 'px' );
}
},
stop: function( event, ui ) {
var addNew, widgetNumber, $sidebar, $children, child, item,
$widget = ui.item,
id = the_id;
if ( $widget.hasClass('deleting') ) {
wpWidgets.save( $widget, 1, 0, 1 ); // delete widget
$widget.remove();
return;
}
addNew = $widget.find('input.add_new').val();
widgetNumber = $widget.find('input.multi_number').val();
$widget.attr( 'style', '' ).removeClass('ui-draggable');
the_id = '';
if ( addNew ) {
if ( 'multi' === addNew ) {
$widget.html(
$widget.html().replace( /<[^<>]+>/g, function( tag ) {
return tag.replace( /__i__|%i%/g, widgetNumber );
})
);
$widget.attr( 'id', id.replace( '__i__', widgetNumber ) );
widgetNumber++;
$( 'div#' + id ).find( 'input.multi_number' ).val( widgetNumber );
} else if ( 'single' === addNew ) {
$widget.attr( 'id', 'new-' + id );
rem = 'div#' + id;
}
wpWidgets.save( $widget, 0, 0, 1 );
$widget.find('input.add_new').val('');
$( document ).trigger( 'widget-added', [ $widget ] );
}
$sidebar = $widget.parent();
if ( $sidebar.parent().hasClass('closed') ) {
$sidebar.parent().removeClass('closed');
$children = $sidebar.children('.widget');
// Make sure the dropped widget is at the top
if ( $children.length > 1 ) {
child = $children.get(0);
item = $widget.get(0);
if ( child.id && item.id && child.id !== item.id ) {
$( child ).before( $widget );
}
}
}
if ( addNew ) {
$widget.find( 'a.widget-action' ).trigger('click');
} else {
wpWidgets.saveOrder( $sidebar.attr('id') );
}
},
activate: function() {
$(this).parent().addClass( 'widget-hover' );
},
deactivate: function() {
// Remove all min-height added on "start"
$(this).css( 'min-height', '' ).parent().removeClass( 'widget-hover' );
},
receive: function( event, ui ) {
var $sender = $( ui.sender );
// Don't add more widgets to orphaned sidebars
if ( this.id.indexOf('orphaned_widgets') > -1 ) {
$sender.sortable('cancel');
return;
}
// If the last widget was moved out of an orphaned sidebar, close and remove it.
if ( $sender.attr('id').indexOf('orphaned_widgets') > -1 && ! $sender.children('.widget').length ) {
$sender.parents('.orphan-sidebar').slideUp( 400, function(){ $(this).remove(); } );
}
}
}).sortable( 'option', 'connectWith', 'div.widgets-sortables' );
$('#available-widgets').droppable({
tolerance: 'pointer',
accept: function(o){
return $(o).parent().attr('id') !== 'widget-list';
},
drop: function(e,ui) {
ui.draggable.addClass('deleting');
$('#removing-widget').hide().children('span').html('');
},
over: function(e,ui) {
ui.draggable.addClass('deleting');
$('div.widget-placeholder').hide();
if ( ui.draggable.hasClass('ui-sortable-helper') ) {
$('#removing-widget').show().children('span')
.html( ui.draggable.find('div.widget-title').children('h4').html() );
}
},
out: function(e,ui) {
ui.draggable.removeClass('deleting');
$('div.widget-placeholder').show();
$('#removing-widget').hide().children('span').html('');
}
});
// Area Chooser
$( '#widgets-right .widgets-holder-wrap' ).each( function( index, element ) {
var $element = $( element ),
name = $element.find( '.sidebar-name h3' ).text(),
id = $element.find( '.widgets-sortables' ).attr( 'id' ),
li = $('<li tabindex="0">').text( $.trim( name ) );
if ( index === 0 ) {
li.addClass( 'widgets-chooser-selected' );
}
selectSidebar.append( li );
li.data( 'sidebarId', id );
});
$( '#available-widgets .widget .widget-title' ).on( 'click.widgets-chooser', function() {
var $widget = $(this).closest( '.widget' );
if ( $widget.hasClass( 'widget-in-question' ) || $( '#widgets-left' ).hasClass( 'chooser' ) ) {
self.closeChooser();
} else {
// Open the chooser
self.clearWidgetSelection();
$( '#widgets-left' ).addClass( 'chooser' );
$widget.addClass( 'widget-in-question' ).children( '.widget-description' ).after( chooser );
chooser.slideDown( 300, function() {
selectSidebar.find('.widgets-chooser-selected').focus();
});
selectSidebar.find( 'li' ).on( 'focusin.widgets-chooser', function() {
selectSidebar.find('.widgets-chooser-selected').removeClass( 'widgets-chooser-selected' );
$(this).addClass( 'widgets-chooser-selected' );
} );
}
});
// Add event handlers
chooser.on( 'click.widgets-chooser', function( event ) {
var $target = $( event.target );
if ( $target.hasClass('button-primary') ) {
self.addWidget( chooser );
self.closeChooser();
} else if ( $target.hasClass('button-secondary') ) {
self.closeChooser();
}
}).on( 'keyup.widgets-chooser', function( event ) {
if ( event.which === $.ui.keyCode.ENTER ) {
if ( $( event.target ).hasClass('button-secondary') ) {
// Close instead of adding when pressing Enter on the Cancel button
self.closeChooser();
} else {
self.addWidget( chooser );
self.closeChooser();
}
} else if ( event.which === $.ui.keyCode.ESCAPE ) {
self.closeChooser();
}
});
},
saveOrder : function( sidebarId ) {
var data = {
action: 'widgets-order',
savewidgets: $('#_wpnonce_widgets').val(),
sidebars: []
};
if ( sidebarId ) {
$( '#' + sidebarId ).find('.spinner:first').css('display', 'inline-block');
}
$('div.widgets-sortables').each( function() {
if ( $(this).sortable ) {
data['sidebars[' + $(this).attr('id') + ']'] = $(this).sortable('toArray').join(',');
}
});
$.post( ajaxurl, data, function() {
$('.spinner').hide();
});
},
save : function( widget, del, animate, order ) {
var sidebarId = widget.closest('div.widgets-sortables').attr('id'),
data = widget.find('form').serialize(), a;
widget = $(widget);
$('.spinner', widget).show();
a = {
action: 'save-widget',
savewidgets: $('#_wpnonce_widgets').val(),
sidebar: sidebarId
};
if ( del ) {
a.delete_widget = 1;
}
data += '&' + $.param(a);
$.post( ajaxurl, data, function(r) {
var id;
if ( del ) {
if ( ! $('input.widget_number', widget).val() ) {
id = $('input.widget-id', widget).val();
$('#available-widgets').find('input.widget-id').each(function(){
if ( $(this).val() === id ) {
$(this).closest('div.widget').show();
}
});
}
if ( animate ) {
order = 0;
widget.slideUp('fast', function(){
$(this).remove();
wpWidgets.saveOrder();
});
} else {
widget.remove();
}
} else {
$('.spinner').hide();
if ( r && r.length > 2 ) {
$( 'div.widget-content', widget ).html( r );
wpWidgets.appendTitle( widget );
$( document ).trigger( 'widget-updated', [ widget ] );
}
}
if ( order ) {
wpWidgets.saveOrder();
}
});
},
appendTitle : function(widget) {
var title = $('input[id*="-title"]', widget).val() || '';
if ( title ) {
title = ': ' + title.replace(/<[^<>]+>/g, '').replace(/</g, '<').replace(/>/g, '>');
}
$(widget).children('.widget-top').children('.widget-title').children()
.children('.in-widget-title').html(title);
},
close : function(widget) {
widget.children('.widget-inside').slideUp('fast', function() {
widget.attr( 'style', '' );
});
},
addWidget: function( chooser ) {
var widget, widgetId, add, n, viewportTop, viewportBottom, sidebarBounds,
sidebarId = chooser.find( '.widgets-chooser-selected' ).data('sidebarId'),
sidebar = $( '#' + sidebarId );
widget = $('#available-widgets').find('.widget-in-question').clone();
widgetId = widget.attr('id');
add = widget.find( 'input.add_new' ).val();
n = widget.find( 'input.multi_number' ).val();
// Remove the cloned chooser from the widget
widget.find('.widgets-chooser').remove();
if ( 'multi' === add ) {
widget.html(
widget.html().replace( /<[^<>]+>/g, function(m) {
return m.replace( /__i__|%i%/g, n );
})
);
widget.attr( 'id', widgetId.replace( '__i__', n ) );
n++;
$( '#' + widgetId ).find('input.multi_number').val(n);
} else if ( 'single' === add ) {
widget.attr( 'id', 'new-' + widgetId );
$( '#' + widgetId ).hide();
}
// Open the widgets container
sidebar.closest( '.widgets-holder-wrap' ).removeClass('closed');
sidebar.append( widget );
sidebar.sortable('refresh');
wpWidgets.save( widget, 0, 0, 1 );
// No longer "new" widget
widget.find( 'input.add_new' ).val('');
$( document ).trigger( 'widget-added', [ widget ] );
/*
* Check if any part of the sidebar is visible in the viewport. If it is, don't scroll.
* Otherwise, scroll up to so the sidebar is in view.
*
* We do this by comparing the top and bottom, of the sidebar so see if they are within
* the bounds of the viewport.
*/
viewportTop = $(window).scrollTop();
viewportBottom = viewportTop + $(window).height();
sidebarBounds = sidebar.offset();
sidebarBounds.bottom = sidebarBounds.top + sidebar.outerHeight();
if ( viewportTop > sidebarBounds.bottom || viewportBottom < sidebarBounds.top ) {
$( 'html, body' ).animate({
scrollTop: sidebarBounds.top - 130
}, 200 );
}
window.setTimeout( function() {
// Cannot use a callback in the animation above as it fires twice,
// have to queue this "by hand".
widget.find( '.widget-title' ).trigger('click');
}, 250 );
},
closeChooser: function() {
var self = this;
$( '.widgets-chooser' ).slideUp( 200, function() {
$( '#wpbody-content' ).append( this );
self.clearWidgetSelection();
});
},
clearWidgetSelection: function() {
$( '#widgets-left' ).removeClass( 'chooser' );
$( '.widget-in-question' ).removeClass( 'widget-in-question' );
}
};
$(document).ready( function(){ wpWidgets.init(); } );
})(jQuery);
| 01-wordpress-paypal | trunk/wp-admin/js/widgets.js | JavaScript | gpl3 | 14,091 |
/* global isRtl */
(function($) {
var frame;
$( function() {
// Fetch available headers and apply jQuery.masonry
// once the images have loaded.
var $headers = $('.available-headers');
$headers.imagesLoaded( function() {
$headers.masonry({
itemSelector: '.default-header',
isRTL: !! ( 'undefined' != typeof isRtl && isRtl )
});
});
// Build the choose from library frame.
$('#choose-from-library-link').click( function( event ) {
var $el = $(this);
event.preventDefault();
// If the media frame already exists, reopen it.
if ( frame ) {
frame.open();
return;
}
// Create the media frame.
frame = wp.media.frames.customHeader = wp.media({
// Set the title of the modal.
title: $el.data('choose'),
// Tell the modal to show only images.
library: {
type: 'image'
},
// Customize the submit button.
button: {
// Set the text of the button.
text: $el.data('update'),
// Tell the button not to close the modal, since we're
// going to refresh the page when the image is selected.
close: false
}
});
// When an image is selected, run a callback.
frame.on( 'select', function() {
// Grab the selected attachment.
var attachment = frame.state().get('selection').first(),
link = $el.data('updateLink');
// Tell the browser to navigate to the crop step.
window.location = link + '&file=' + attachment.id;
});
frame.open();
});
});
}(jQuery));
| 01-wordpress-paypal | trunk/wp-admin/js/custom-header.js | JavaScript | gpl3 | 1,502 |
/* global ajaxurl */
var postboxes;
(function($) {
postboxes = {
add_postbox_toggles : function(page, args) {
var self = this;
self.init(page, args);
$('.postbox h3, .postbox .handlediv').bind('click.postboxes', function() {
var p = $(this).parent('.postbox'), id = p.attr('id');
if ( 'dashboard_browser_nag' == id )
return;
p.toggleClass('closed');
if ( page != 'press-this' )
self.save_state(page);
if ( id ) {
if ( !p.hasClass('closed') && $.isFunction(postboxes.pbshow) )
self.pbshow(id);
else if ( p.hasClass('closed') && $.isFunction(postboxes.pbhide) )
self.pbhide(id);
}
});
$('.postbox h3 a').click( function(e) {
e.stopPropagation();
});
$( '.postbox a.dismiss' ).bind( 'click.postboxes', function() {
var hide_id = $(this).parents('.postbox').attr('id') + '-hide';
$( '#' + hide_id ).prop('checked', false).triggerHandler('click');
return false;
});
$('.hide-postbox-tog').bind('click.postboxes', function() {
var box = $(this).val();
if ( $(this).prop('checked') ) {
$('#' + box).show();
if ( $.isFunction( postboxes.pbshow ) )
self.pbshow( box );
} else {
$('#' + box).hide();
if ( $.isFunction( postboxes.pbhide ) )
self.pbhide( box );
}
self.save_state(page);
self._mark_area();
});
$('.columns-prefs input[type="radio"]').bind('click.postboxes', function(){
var n = parseInt($(this).val(), 10);
if ( n ) {
self._pb_edit(n);
self.save_order(page);
}
});
},
init : function(page, args) {
var isMobile = $(document.body).hasClass('mobile');
$.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',
delay: ( isMobile ? 200 : 0 ),
distance: 2,
tolerance: 'pointer',
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
stop: function() {
if ( $(this).find('#dashboard_browser_nag').is(':visible') && 'dashboard_browser_nag' != this.firstChild.id ) {
$(this).sortable('cancel');
return;
}
postboxes.save_order(page);
},
receive: function(e,ui) {
if ( 'dashboard_browser_nag' == ui.item[0].id )
$(ui.sender).sortable('cancel');
postboxes._mark_area();
}
});
if ( isMobile ) {
$(document.body).bind('orientationchange.postboxes', function(){ postboxes._pb_change(); });
this._pb_change();
}
this._mark_area();
},
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(ajaxurl, {
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( ajaxurl, postVars );
},
_mark_area : function() {
var visible = $('div.postbox:visible').length, side = $('#post-body #side-sortables');
$( '#dashboard-widgets .meta-box-sortables:visible' ).each( function() {
var t = $(this);
if ( visible == 1 || t.children('.postbox:visible').length )
t.removeClass('empty-container');
else
t.addClass('empty-container');
});
if ( side.length ) {
if ( side.children('.postbox:visible').length )
side.removeClass('empty-container');
else if ( $('#postbox-container-1').css('width') == '280px' )
side.addClass('empty-container');
}
},
_pb_edit : function(n) {
var el = $('.metabox-holder').get(0);
if ( el ) {
el.className = el.className.replace(/columns-\d+/, 'columns-' + n);
}
},
_pb_change : function() {
var check = $( 'label.columns-prefs-1 input[type="radio"]' );
switch ( window.orientation ) {
case 90:
case -90:
if ( !check.length || !check.is(':checked') )
this._pb_edit(2);
break;
case 0:
case 180:
if ( $('#poststuff').length ) {
this._pb_edit(1);
} else {
if ( !check.length || !check.is(':checked') )
this._pb_edit(2);
}
break;
}
},
/* Callbacks */
pbshow : false,
pbhide : false
};
}(jQuery));
| 01-wordpress-paypal | trunk/wp-admin/js/postbox.js | JavaScript | gpl3 | 4,834 |
/* global inlineEditL10n, ajaxurl */
var inlineEditTax;
(function($) {
inlineEditTax = {
init : function() {
var t = this, row = $('#inline-edit');
t.type = $('#the-list').attr('data-wp-lists').substr(5);
t.what = '#'+t.type+'-';
$('#the-list').on('click', 'a.editinline', function(){
inlineEditTax.edit(this);
return false;
});
// prepare the edit row
row.keyup( function( e ) {
if ( e.which === 27 ) {
return inlineEditTax.revert();
}
});
$( 'a.cancel', row ).click( function() {
return inlineEditTax.revert();
});
$( 'a.save', row ).click( function() {
return inlineEditTax.save(this);
});
$( 'input, select', row ).keydown( function( e ) {
if ( e.which === 13 ) {
return inlineEditTax.save( this );
}
});
$( '#posts-filter input[type="submit"]' ).mousedown( function() {
t.revert();
});
},
toggle : function(el) {
var t = this;
$(t.what+t.getId(el)).css('display') === 'none' ? t.revert() : t.edit(el);
},
edit : function(id) {
var editRow, rowData,
t = this;
t.revert();
if ( typeof(id) === 'object' ) {
id = t.getId(id);
}
editRow = $('#inline-edit').clone(true), rowData = $('#inline_'+id);
$('td', editRow).attr('colspan', $('.widefat:first thead th:visible').length);
if ( $( t.what + id ).hasClass( 'alternate' ) ) {
$(editRow).addClass('alternate');
}
$(t.what+id).hide().after(editRow);
$(':input[name="name"]', editRow).val( $('.name', rowData).text() );
$(':input[name="slug"]', editRow).val( $('.slug', rowData).text() );
$(editRow).attr('id', 'edit-'+id).addClass('inline-editor').show();
$('.ptitle', editRow).eq(0).focus();
return false;
},
save : function(id) {
var params, fields, tax = $('input[name="taxonomy"]').val() || '';
if( typeof(id) === 'object' ) {
id = this.getId(id);
}
$('table.widefat .spinner').show();
params = {
action: 'inline-save-tax',
tax_type: this.type,
tax_ID: id,
taxonomy: tax
};
fields = $('#edit-'+id).find(':input').serialize();
params = fields + '&' + $.param(params);
// make ajax request
$.post( ajaxurl, params,
function(r) {
var row, new_id;
$('table.widefat .spinner').hide();
if (r) {
if ( -1 !== r.indexOf( '<tr' ) ) {
$(inlineEditTax.what+id).remove();
new_id = $(r).attr('id');
$('#edit-'+id).before(r).remove();
row = new_id ? $('#'+new_id) : $(inlineEditTax.what+id);
row.hide().fadeIn();
} else {
$('#edit-'+id+' .inline-edit-save .error').html(r).show();
}
} else {
$('#edit-'+id+' .inline-edit-save .error').html(inlineEditL10n.error).show();
}
if ( $( row ).prev( 'tr' ).hasClass( 'alternate' ) ) {
$(row).removeClass('alternate');
}
}
);
return false;
},
revert : function() {
var id = $('table.widefat tr.inline-editor').attr('id');
if ( id ) {
$('table.widefat .spinner').hide();
$('#'+id).remove();
id = id.substr( id.lastIndexOf('-') + 1 );
$(this.what+id).show();
}
return false;
},
getId : function(o) {
var id = o.tagName === 'TR' ? o.id : $(o).parents('tr').attr('id'), parts = id.split('-');
return parts[parts.length - 1];
}
};
$(document).ready(function(){inlineEditTax.init();});
})(jQuery);
| 01-wordpress-paypal | trunk/wp-admin/js/inline-edit-tax.js | JavaScript | gpl3 | 3,279 |
<?php
/**
* Plugins may load this file to gain access to special helper functions for
* plugin installation. This file is not included by WordPress and it is
* recommended, to prevent fatal errors, that this file is included using
* require_once().
*
* These functions are not optimized for speed, but they should only be used
* once in a while, so speed shouldn't be a concern. If it is and you are
* needing to use these functions a lot, you might experience time outs. If you
* do, then it is advised to just write the SQL code yourself.
*
* <code>
* check_column('wp_links', 'link_description', 'mediumtext');
* if (check_column($wpdb->comments, 'comment_author', 'tinytext'))
* echo "ok\n";
*
* $error_count = 0;
* $tablename = $wpdb->links;
* // check the column
* if (!check_column($wpdb->links, 'link_description', 'varchar(255)')) {
* $ddl = "ALTER TABLE $wpdb->links MODIFY COLUMN link_description varchar(255) NOT NULL DEFAULT '' ";
* $q = $wpdb->query($ddl);
* }
*
* if (check_column($wpdb->links, 'link_description', 'varchar(255)')) {
* $res .= $tablename . ' - ok <br />';
* } else {
* $res .= 'There was a problem with ' . $tablename . '<br />';
* ++$error_count;
* }
* </code>
*
* @package WordPress
* @subpackage Plugin
*/
/** Load WordPress Bootstrap */
require_once(dirname(dirname(__FILE__)).'/wp-load.php');
if ( ! function_exists('maybe_create_table') ) :
/**
* Create database table, if it doesn't already exist.
*
* @since 1.0.0
*
* @uses $wpdb
*
* @param string $table_name Database table name.
* @param string $create_ddl Create database table SQL.
* @return bool False on error, true if already exists or success.
*/
function maybe_create_table($table_name, $create_ddl) {
global $wpdb;
foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
if ($table == $table_name) {
return true;
}
}
//didn't find it try to create it.
$wpdb->query($create_ddl);
// we cannot directly tell that whether this succeeded!
foreach ($wpdb->get_col("SHOW TABLES",0) as $table ) {
if ($table == $table_name) {
return true;
}
}
return false;
}
endif;
if ( ! function_exists('maybe_add_column') ) :
/**
* Add column to database table, if column doesn't already exist in table.
*
* @since 1.0.0
*
* @uses $wpdb
*
* @param string $table_name Database table name
* @param string $column_name Table column name
* @param string $create_ddl SQL to add column to table.
* @return bool False on failure. True, if already exists or was successful.
*/
function maybe_add_column($table_name, $column_name, $create_ddl) {
global $wpdb;
foreach ($wpdb->get_col("DESC $table_name",0) as $column ) {
if ($column == $column_name) {
return true;
}
}
//didn't find it try to create it.
$wpdb->query($create_ddl);
// we cannot directly tell that whether this succeeded!
foreach ($wpdb->get_col("DESC $table_name",0) as $column ) {
if ($column == $column_name) {
return true;
}
}
return false;
}
endif;
/**
* Drop column from database table, if it exists.
*
* @since 1.0.0
*
* @uses $wpdb
*
* @param string $table_name Table name
* @param string $column_name Column name
* @param string $drop_ddl SQL statement to drop column.
* @return bool False on failure, true on success or doesn't exist.
*/
function maybe_drop_column($table_name, $column_name, $drop_ddl) {
global $wpdb;
foreach ($wpdb->get_col("DESC $table_name",0) as $column ) {
if ($column == $column_name) {
//found it try to drop it.
$wpdb->query($drop_ddl);
// we cannot directly tell that whether this succeeded!
foreach ($wpdb->get_col("DESC $table_name",0) as $column ) {
if ($column == $column_name) {
return false;
}
}
}
}
// else didn't find it
return true;
}
/**
* Check column matches criteria.
*
* Uses the SQL DESC for retrieving the table info for the column. It will help
* understand the parameters, if you do more research on what column information
* is returned by the SQL statement. Pass in null to skip checking that
* criteria.
*
* Column names returned from DESC table are case sensitive and are listed:
* Field
* Type
* Null
* Key
* Default
* Extra
*
* @since 1.0.0
*
* @param string $table_name Table name
* @param string $col_name Column name
* @param string $col_type Column type
* @param bool $is_null Optional. Check is null.
* @param mixed $key Optional. Key info.
* @param mixed $default Optional. Default value.
* @param mixed $extra Optional. Extra value.
* @return bool True, if matches. False, if not matching.
*/
function check_column($table_name, $col_name, $col_type, $is_null = null, $key = null, $default = null, $extra = null) {
global $wpdb;
$diffs = 0;
$results = $wpdb->get_results("DESC $table_name");
foreach ($results as $row ) {
if ($row->Field == $col_name) {
// got our column, check the params
if (($col_type != null) && ($row->Type != $col_type)) {
++$diffs;
}
if (($is_null != null) && ($row->Null != $is_null)) {
++$diffs;
}
if (($key != null) && ($row->Key != $key)) {
++$diffs;
}
if (($default != null) && ($row->Default != $default)) {
++$diffs;
}
if (($extra != null) && ($row->Extra != $extra)) {
++$diffs;
}
if ($diffs > 0) {
return false;
}
return true;
} // end if found our column
}
return false;
}
| 01-wordpress-paypal | trunk/wp-admin/install-helper.php | PHP | gpl3 | 5,423 |
<?php
/**
* Accepts file uploads from swfupload or other asynchronous upload methods.
*
* @package WordPress
* @subpackage Administration
*/
if ( isset( $_REQUEST['action'] ) && 'upload-attachment' === $_REQUEST['action'] ) {
define( 'DOING_AJAX', true );
}
define('WP_ADMIN', true);
if ( defined('ABSPATH') )
require_once(ABSPATH . 'wp-load.php');
else
require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );
if ( ! ( isset( $_REQUEST['action'] ) && 'upload-attachment' == $_REQUEST['action'] ) ) {
// Flash often fails to send cookies with the POST or upload, so we need to pass it in GET or POST instead
if ( is_ssl() && empty($_COOKIE[SECURE_AUTH_COOKIE]) && !empty($_REQUEST['auth_cookie']) )
$_COOKIE[SECURE_AUTH_COOKIE] = $_REQUEST['auth_cookie'];
elseif ( empty($_COOKIE[AUTH_COOKIE]) && !empty($_REQUEST['auth_cookie']) )
$_COOKIE[AUTH_COOKIE] = $_REQUEST['auth_cookie'];
if ( empty($_COOKIE[LOGGED_IN_COOKIE]) && !empty($_REQUEST['logged_in_cookie']) )
$_COOKIE[LOGGED_IN_COOKIE] = $_REQUEST['logged_in_cookie'];
unset($current_user);
}
require_once( ABSPATH . 'wp-admin/admin.php' );
if ( !current_user_can('upload_files') )
wp_die(__('You do not have permission to upload files.'));
header('Content-Type: text/html; charset=' . get_option('blog_charset'));
if ( isset( $_REQUEST['action'] ) && 'upload-attachment' === $_REQUEST['action'] ) {
include ABSPATH . 'wp-admin/includes/ajax-actions.php';
send_nosniff_header();
nocache_headers();
wp_ajax_upload_attachment();
die( '0' );
}
// just fetch the detail form for that attachment
if ( isset($_REQUEST['attachment_id']) && ($id = intval($_REQUEST['attachment_id'])) && $_REQUEST['fetch'] ) {
$post = get_post( $id );
if ( 'attachment' != $post->post_type )
wp_die( __( 'Unknown post type.' ) );
if ( ! current_user_can( 'edit_post', $id ) )
wp_die( __( 'You are not allowed to edit this item.' ) );
switch ( $_REQUEST['fetch'] ) {
case 3 :
if ( $thumb_url = wp_get_attachment_image_src( $id, 'thumbnail', true ) )
echo '<img class="pinkynail" src="' . esc_url( $thumb_url[0] ) . '" alt="" />';
echo '<a class="edit-attachment" href="' . esc_url( get_edit_post_link( $id ) ) . '" target="_blank">' . _x( 'Edit', 'media item' ) . '</a>';
$title = $post->post_title ? $post->post_title : wp_basename( $post->guid ); // title shouldn't ever be empty, but use filename just in cas.e
echo '<div class="filename new"><span class="title">' . esc_html( wp_html_excerpt( $title, 60, '…' ) ) . '</span></div>';
break;
case 2 :
add_filter('attachment_fields_to_edit', 'media_single_attachment_fields_to_edit', 10, 2);
echo get_media_item($id, array( 'send' => false, 'delete' => true ));
break;
default:
add_filter('attachment_fields_to_edit', 'media_post_single_attachment_fields_to_edit', 10, 2);
echo get_media_item($id);
break;
}
exit;
}
check_admin_referer('media-form');
$post_id = 0;
if ( isset( $_REQUEST['post_id'] ) ) {
$post_id = absint( $_REQUEST['post_id'] );
if ( ! get_post( $post_id ) || ! current_user_can( 'edit_post', $post_id ) )
$post_id = 0;
}
$id = media_handle_upload( 'async-upload', $post_id );
if ( is_wp_error($id) ) {
echo '<div class="error-div">
<a class="dismiss" href="#" onclick="jQuery(this).parents(\'div.media-item\').slideUp(200, function(){jQuery(this).remove();});">' . __('Dismiss') . '</a>
<strong>' . sprintf(__('“%s” has failed to upload due to an error'), esc_html($_FILES['async-upload']['name']) ) . '</strong><br />' .
esc_html($id->get_error_message()) . '</div>';
exit;
}
if ( $_REQUEST['short'] ) {
// short form response - attachment ID only
echo $id;
} else {
// long form response - big chunk o html
$type = $_REQUEST['type'];
/**
* Filter the returned ID of an uploaded attachment.
*
* The dynamic portion of the hook name, $type, refers to the attachment type,
* such as 'image', 'audio', 'video', 'file', etc.
*
* @since 2.5.0
*
* @param int $id Uploaded attachment ID.
*/
echo apply_filters( "async_upload_{$type}", $id );
}
| 01-wordpress-paypal | trunk/wp-admin/async-upload.php | PHP | gpl3 | 4,091 |
<?php
/**
* WordPress Administration Template Header
*
* @package WordPress
* @subpackage Administration
*/
@header('Content-Type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
if ( ! defined( 'WP_ADMIN' ) )
require_once( dirname( __FILE__ ) . '/admin.php' );
// In case admin-header.php is included in a function.
global $title, $hook_suffix, $current_screen, $wp_locale, $pagenow, $wp_version,
$update_title, $total_update_count, $parent_file;
// Catch plugins that include admin-header.php before admin.php completes.
if ( empty( $current_screen ) )
set_current_screen();
get_admin_page_title();
$title = esc_html( strip_tags( $title ) );
if ( is_network_admin() )
$admin_title = sprintf( __( 'Network Admin: %s' ), esc_html( get_current_site()->site_name ) );
elseif ( is_user_admin() )
$admin_title = sprintf( __( 'Global Dashboard: %s' ), esc_html( get_current_site()->site_name ) );
else
$admin_title = get_bloginfo( 'name' );
if ( $admin_title == $title )
$admin_title = sprintf( __( '%1$s — WordPress' ), $title );
else
$admin_title = sprintf( __( '%1$s ‹ %2$s — WordPress' ), $title, $admin_title );
/**
* Filter the <title> content for an admin page.
*
* @since 3.1.0
*
* @param string $admin_title The page title, with extra context added.
* @param string $title The original page title.
*/
$admin_title = apply_filters( 'admin_title', $admin_title, $title );
wp_user_settings();
_wp_admin_html_begin();
?>
<title><?php echo $admin_title; ?></title>
<?php
wp_enqueue_style( 'colors' );
wp_enqueue_style( 'ie' );
wp_enqueue_script('utils');
wp_enqueue_script( 'svg-painter' );
$admin_body_class = preg_replace('/[^a-z0-9_-]+/i', '-', $hook_suffix);
?>
<script type="text/javascript">
addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}};
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>',
pagenow = '<?php echo $current_screen->id; ?>',
typenow = '<?php echo $current_screen->post_type; ?>',
adminpage = '<?php echo $admin_body_class; ?>',
thousandsSeparator = '<?php echo addslashes( $wp_locale->number_format['thousands_sep'] ); ?>',
decimalPoint = '<?php echo addslashes( $wp_locale->number_format['decimal_point'] ); ?>',
isRtl = <?php echo (int) is_rtl(); ?>;
</script>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<?php
/**
* Enqueue scripts for all admin pages.
*
* @since 2.8.0
*
* @param string $hook_suffix The current admin page.
*/
do_action( 'admin_enqueue_scripts', $hook_suffix );
/**
* Fires when styles are printed for a specific admin page based on $hook_suffix.
*
* @since 2.6.0
*/
do_action( "admin_print_styles-$hook_suffix" );
/**
* Fires when styles are printed for all admin pages.
*
* @since 2.6.0
*/
do_action( 'admin_print_styles' );
/**
* Fires when scripts are printed for a specific admin page based on $hook_suffix.
*
* @since 2.1.0
*/
do_action( "admin_print_scripts-$hook_suffix" );
/**
* Fires when scripts are printed for all admin pages.
*
* @since 2.1.0
*/
do_action( 'admin_print_scripts' );
/**
* Fires in <head> for a specific admin page based on $hook_suffix.
*
* @since 2.1.0
*/
do_action( "admin_head-$hook_suffix" );
/**
* Fires in <head> for all admin pages.
*
* @since 2.1.0
*/
do_action( 'admin_head' );
if ( get_user_setting('mfold') == 'f' )
$admin_body_class .= ' folded';
if ( !get_user_setting('unfold') )
$admin_body_class .= ' auto-fold';
if ( is_admin_bar_showing() )
$admin_body_class .= ' admin-bar';
if ( is_rtl() )
$admin_body_class .= ' rtl';
if ( $current_screen->post_type )
$admin_body_class .= ' post-type-' . $current_screen->post_type;
if ( $current_screen->taxonomy )
$admin_body_class .= ' taxonomy-' . $current_screen->taxonomy;
$admin_body_class .= ' branch-' . str_replace( array( '.', ',' ), '-', floatval( $wp_version ) );
$admin_body_class .= ' version-' . str_replace( '.', '-', preg_replace( '/^([.0-9]+).*/', '$1', $wp_version ) );
$admin_body_class .= ' admin-color-' . sanitize_html_class( get_user_option( 'admin_color' ), 'fresh' );
$admin_body_class .= ' locale-' . sanitize_html_class( strtolower( str_replace( '_', '-', get_locale() ) ) );
if ( wp_is_mobile() )
$admin_body_class .= ' mobile';
if ( is_multisite() )
$admin_body_class .= ' multisite';
if ( is_network_admin() )
$admin_body_class .= ' network-admin';
$admin_body_class .= ' no-customize-support no-svg';
?>
</head>
<?php
/**
* Filter the admin <body> CSS classes.
*
* This filter differs from the post_class or body_class filters in two important ways:
* 1. $classes is a space-separated string of class names instead of an array.
* 2. Not all core admin classes are filterable, notably: wp-admin, wp-core-ui, and no-js cannot be removed.
*
* @since 2.3.0
*
* @param string $classes Space-separated string of CSS classes.
*/
?>
<body class="wp-admin wp-core-ui no-js <?php echo apply_filters( 'admin_body_class', '' ) . " $admin_body_class"; ?>">
<script type="text/javascript">
document.body.className = document.body.className.replace('no-js','js');
</script>
<?php
// Make sure the customize body classes are correct as early as possible.
if ( current_user_can( 'edit_theme_options' ) )
wp_customize_support_script();
?>
<div id="wpwrap">
<a tabindex="1" href="#wpbody-content" class="screen-reader-shortcut"><?php _e('Skip to main content'); ?></a>
<?php require(ABSPATH . 'wp-admin/menu-header.php'); ?>
<div id="wpcontent">
<?php
/**
* Fires at the beginning of the content section in an admin page.
*
* @since 3.0.0
*/
do_action( 'in_admin_header' );
?>
<div id="wpbody">
<?php
unset($title_class, $blog_name, $total_update_count, $update_title);
$current_screen->set_parentage( $parent_file );
?>
<div id="wpbody-content" aria-label="<?php esc_attr_e('Main content'); ?>" tabindex="0">
<?php
$current_screen->render_screen_meta();
if ( is_network_admin() ) {
/**
* Print network admin screen notices.
*
* @since 3.1.0
*/
do_action( 'network_admin_notices' );
} elseif ( is_user_admin() ) {
/**
* Print user admin screen notices.
*
* @since 3.1.0
*/
do_action( 'user_admin_notices' );
} else {
/**
* Print admin screen notices.
*
* @since 3.1.0
*/
do_action( 'admin_notices' );
}
/**
* Print generic admin screen notices.
*
* @since 3.1.0
*/
do_action( 'all_admin_notices' );
if ( $parent_file == 'options-general.php' )
require(ABSPATH . 'wp-admin/options-head.php');
| 01-wordpress-paypal | trunk/wp-admin/admin-header.php | PHP | gpl3 | 6,653 |
<?php
/**
* User Profile Administration Screen.
*
* @package WordPress
* @subpackage Administration
*/
/**
* This is a profile page.
*
* @since 2.5.0
* @var bool
*/
define('IS_PROFILE_PAGE', true);
/** Load User Editing Page */
require_once( dirname( __FILE__ ) . '/user-edit.php' );
| 01-wordpress-paypal | trunk/wp-admin/profile.php | PHP | gpl3 | 296 |
<?php
/**
* Users administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! current_user_can( 'list_users' ) )
wp_die( __( 'Cheatin’ uh?' ) );
$wp_list_table = _get_list_table('WP_Users_List_Table');
$pagenum = $wp_list_table->get_pagenum();
$title = __('Users');
$parent_file = 'users.php';
add_screen_option( 'per_page', array('label' => _x( 'Users', 'users per page (screen options)' )) );
// contextual help - choose Help on the top right of admin panel to preview this.
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' => '<p>' . __('This screen lists all the existing users for your site. Each user has one of five defined roles as set by the site admin: Site Administrator, Editor, Author, Contributor, or Subscriber. Users with roles other than Administrator will see fewer options in the dashboard navigation when they are logged in, based on their role.') . '</p>' .
'<p>' . __('To add a new user for your site, click the Add New button at the top of the screen or Add New in the Users menu section.') . '</p>'
) ) ;
get_current_screen()->add_help_tab( array(
'id' => 'screen-display',
'title' => __('Screen Display'),
'content' => '<p>' . __('You can customize the display of this screen in a number of ways:') . '</p>' .
'<ul>' .
'<li>' . __('You can hide/display columns based on your needs and decide how many users to list per screen using the Screen Options tab.') . '</li>' .
'<li>' . __('You can filter the list of users by User Role using the text links in the upper left to show All, Administrator, Editor, Author, Contributor, or Subscriber. The default view is to show all users. Unused User Roles are not listed.') . '</li>' .
'<li>' . __('You can view all posts made by a user by clicking on the number under the Posts column.') . '</li>' .
'</ul>'
) );
$help = '<p>' . __('Hovering over a row in the users list will display action links that allow you to manage users. You can perform the following actions:') . '</p>' .
'<ul>' .
'<li>' . __('Edit takes you to the editable profile screen for that user. You can also reach that screen by clicking on the username.') . '</li>';
if ( is_multisite() )
$help .= '<li>' . __( 'Remove allows you to remove a user from your site. It does not delete their content. You can also remove multiple users at once by using Bulk Actions.' ) . '</li>';
else
$help .= '<li>' . __( 'Delete brings you to the Delete Users screen for confirmation, where you can permanently remove a user from your site and delete their content. You can also delete multiple users at once by using Bulk Actions.' ) . '</li>';
$help .= '</ul>';
get_current_screen()->add_help_tab( array(
'id' => 'actions',
'title' => __('Actions'),
'content' => $help,
) );
unset( $help );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Users_Screen" target="_blank">Documentation on Managing Users</a>') . '</p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Roles_and_Capabilities" target="_blank">Descriptions of Roles and Capabilities</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
if ( empty($_REQUEST) ) {
$referer = '<input type="hidden" name="wp_http_referer" value="'. esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';
} elseif ( isset($_REQUEST['wp_http_referer']) ) {
$redirect = remove_query_arg(array('wp_http_referer', 'updated', 'delete_count'), wp_unslash( $_REQUEST['wp_http_referer'] ) );
$referer = '<input type="hidden" name="wp_http_referer" value="' . esc_attr($redirect) . '" />';
} else {
$redirect = 'users.php';
$referer = '';
}
$update = '';
/**
* @since 3.5.0
* @access private
*/
function delete_users_add_js() { ?>
<script>
jQuery(document).ready( function($) {
var submit = $('#submit').prop('disabled', true);
$('input[name=delete_option]').one('change', function() {
submit.prop('disabled', false);
});
$('#reassign_user').focus( function() {
$('#delete_option1').prop('checked', true).trigger('change');
});
});
</script>
<?php
}
switch ( $wp_list_table->current_action() ) {
/* Bulk Dropdown menu Role changes */
case 'promote':
check_admin_referer('bulk-users');
if ( ! current_user_can( 'promote_users' ) )
wp_die( __( 'You can’t edit that user.' ) );
if ( empty($_REQUEST['users']) ) {
wp_redirect($redirect);
exit();
}
$editable_roles = get_editable_roles();
if ( empty( $editable_roles[$_REQUEST['new_role']] ) )
wp_die(__('You can’t give users that role.'));
$userids = $_REQUEST['users'];
$update = 'promote';
foreach ( $userids as $id ) {
$id = (int) $id;
if ( ! current_user_can('promote_user', $id) )
wp_die(__('You can’t edit that user.'));
// The new role of the current user must also have the promote_users cap or be a multisite super admin
if ( $id == $current_user->ID && ! $wp_roles->role_objects[ $_REQUEST['new_role'] ]->has_cap('promote_users')
&& ! ( is_multisite() && is_super_admin() ) ) {
$update = 'err_admin_role';
continue;
}
// If the user doesn't already belong to the blog, bail.
if ( is_multisite() && !is_user_member_of_blog( $id ) )
wp_die(__('Cheatin’ uh?'));
$user = get_userdata( $id );
$user->set_role($_REQUEST['new_role']);
}
wp_redirect(add_query_arg('update', $update, $redirect));
exit();
break;
case 'dodelete':
if ( is_multisite() )
wp_die( __('User deletion is not allowed from this screen.') );
check_admin_referer('delete-users');
if ( empty($_REQUEST['users']) ) {
wp_redirect($redirect);
exit();
}
$userids = array_map( 'intval', (array) $_REQUEST['users'] );
if ( empty( $_REQUEST['delete_option'] ) ) {
$url = self_admin_url( 'users.php?action=delete&users[]=' . implode( '&users[]=', $userids ) . '&error=true' );
$url = str_replace( '&', '&', wp_nonce_url( $url, 'bulk-users' ) );
wp_redirect( $url );
exit;
}
if ( ! current_user_can( 'delete_users' ) )
wp_die(__('You can’t delete users.'));
$update = 'del';
$delete_count = 0;
foreach ( $userids as $id ) {
if ( ! current_user_can( 'delete_user', $id ) )
wp_die(__( 'You can’t delete that user.' ) );
if ( $id == $current_user->ID ) {
$update = 'err_admin_del';
continue;
}
switch ( $_REQUEST['delete_option'] ) {
case 'delete':
wp_delete_user( $id );
break;
case 'reassign':
wp_delete_user( $id, $_REQUEST['reassign_user'] );
break;
}
++$delete_count;
}
$redirect = add_query_arg( array('delete_count' => $delete_count, 'update' => $update), $redirect);
wp_redirect($redirect);
exit();
break;
case 'delete':
if ( is_multisite() )
wp_die( __('User deletion is not allowed from this screen.') );
check_admin_referer('bulk-users');
if ( empty($_REQUEST['users']) && empty($_REQUEST['user']) ) {
wp_redirect($redirect);
exit();
}
if ( ! current_user_can( 'delete_users' ) )
$errors = new WP_Error( 'edit_users', __( 'You can’t delete users.' ) );
if ( empty($_REQUEST['users']) )
$userids = array( intval( $_REQUEST['user'] ) );
else
$userids = array_map( 'intval', (array) $_REQUEST['users'] );
add_action( 'admin_head', 'delete_users_add_js' );
include( ABSPATH . 'wp-admin/admin-header.php' );
?>
<form action="" method="post" name="updateusers" id="updateusers">
<?php wp_nonce_field('delete-users') ?>
<?php echo $referer; ?>
<div class="wrap">
<h2><?php _e('Delete Users'); ?></h2>
<?php if ( isset( $_REQUEST['error'] ) ) : ?>
<div class="error">
<p><strong><?php _e( 'ERROR:' ); ?></strong> <?php _e( 'Please select an option.' ); ?></p>
</div>
<?php endif; ?>
<p><?php echo _n( 'You have specified this user for deletion:', 'You have specified these users for deletion:', count( $userids ) ); ?></p>
<ul>
<?php
$go_delete = 0;
foreach ( $userids as $id ) {
$user = get_userdata( $id );
if ( $id == $current_user->ID ) {
echo "<li>" . sprintf(__('ID #%1$s: %2$s <strong>The current user will not be deleted.</strong>'), $id, $user->user_login) . "</li>\n";
} else {
echo "<li><input type=\"hidden\" name=\"users[]\" value=\"" . esc_attr($id) . "\" />" . sprintf(__('ID #%1$s: %2$s'), $id, $user->user_login) . "</li>\n";
$go_delete++;
}
}
?>
</ul>
<?php if ( $go_delete ) : ?>
<fieldset><p><legend><?php echo _n( 'What should be done with content owned by this user?', 'What should be done with content owned by these users?', $go_delete ); ?></legend></p>
<ul style="list-style:none;">
<li><label><input type="radio" id="delete_option0" name="delete_option" value="delete" />
<?php _e('Delete all content.'); ?></label></li>
<li><input type="radio" id="delete_option1" name="delete_option" value="reassign" />
<?php echo '<label for="delete_option1">' . __( 'Attribute all content to:' ) . '</label> ';
wp_dropdown_users( array( 'name' => 'reassign_user', 'exclude' => array_diff( $userids, array($current_user->ID) ) ) ); ?></li>
</ul></fieldset>
<input type="hidden" name="action" value="dodelete" />
<?php submit_button( __('Confirm Deletion'), 'secondary' ); ?>
<?php else : ?>
<p><?php _e('There are no valid users selected for deletion.'); ?></p>
<?php endif; ?>
</div>
</form>
<?php
break;
case 'doremove':
check_admin_referer('remove-users');
if ( ! is_multisite() )
wp_die( __( 'You can’t remove users.' ) );
if ( empty($_REQUEST['users']) ) {
wp_redirect($redirect);
exit;
}
if ( ! current_user_can( 'remove_users' ) )
wp_die( __( 'You can’t remove users.' ) );
$userids = $_REQUEST['users'];
$update = 'remove';
foreach ( $userids as $id ) {
$id = (int) $id;
if ( $id == $current_user->ID && !is_super_admin() ) {
$update = 'err_admin_remove';
continue;
}
if ( !current_user_can('remove_user', $id) ) {
$update = 'err_admin_remove';
continue;
}
remove_user_from_blog($id, $blog_id);
}
$redirect = add_query_arg( array('update' => $update), $redirect);
wp_redirect($redirect);
exit;
break;
case 'remove':
check_admin_referer('bulk-users');
if ( ! is_multisite() )
wp_die( __( 'You can’t remove users.' ) );
if ( empty($_REQUEST['users']) && empty($_REQUEST['user']) ) {
wp_redirect($redirect);
exit();
}
if ( !current_user_can('remove_users') )
$error = new WP_Error('edit_users', __('You can’t remove users.'));
if ( empty($_REQUEST['users']) )
$userids = array(intval($_REQUEST['user']));
else
$userids = $_REQUEST['users'];
include( ABSPATH . 'wp-admin/admin-header.php' );
?>
<form action="" method="post" name="updateusers" id="updateusers">
<?php wp_nonce_field('remove-users') ?>
<?php echo $referer; ?>
<div class="wrap">
<h2><?php _e('Remove Users from Site'); ?></h2>
<p><?php _e('You have specified these users for removal:'); ?></p>
<ul>
<?php
$go_remove = false;
foreach ( $userids as $id ) {
$id = (int) $id;
$user = get_userdata( $id );
if ( $id == $current_user->ID && !is_super_admin() ) {
echo "<li>" . sprintf(__('ID #%1$s: %2$s <strong>The current user will not be removed.</strong>'), $id, $user->user_login) . "</li>\n";
} elseif ( !current_user_can('remove_user', $id) ) {
echo "<li>" . sprintf(__('ID #%1$s: %2$s <strong>You don\'t have permission to remove this user.</strong>'), $id, $user->user_login) . "</li>\n";
} else {
echo "<li><input type=\"hidden\" name=\"users[]\" value=\"{$id}\" />" . sprintf(__('ID #%1$s: %2$s'), $id, $user->user_login) . "</li>\n";
$go_remove = true;
}
}
?>
<?php if ( $go_remove ) : ?>
<input type="hidden" name="action" value="doremove" />
<?php submit_button( __('Confirm Removal'), 'secondary' ); ?>
<?php else : ?>
<p><?php _e('There are no valid users selected for removal.'); ?></p>
<?php endif; ?>
</div>
</form>
<?php
break;
default:
if ( !empty($_GET['_wp_http_referer']) ) {
wp_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce'), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
exit;
}
$wp_list_table->prepare_items();
$total_pages = $wp_list_table->get_pagination_arg( 'total_pages' );
if ( $pagenum > $total_pages && $total_pages > 0 ) {
wp_redirect( add_query_arg( 'paged', $total_pages ) );
exit;
}
include( ABSPATH . 'wp-admin/admin-header.php' );
$messages = array();
if ( isset($_GET['update']) ) :
switch($_GET['update']) {
case 'del':
case 'del_many':
$delete_count = isset($_GET['delete_count']) ? (int) $_GET['delete_count'] : 0;
$messages[] = '<div id="message" class="updated"><p>' . sprintf( _n( 'User deleted.', '%s users deleted.', $delete_count ), number_format_i18n( $delete_count ) ) . '</p></div>';
break;
case 'add':
if ( isset( $_GET['id'] ) && ( $user_id = $_GET['id'] ) && current_user_can( 'edit_user', $user_id ) ) {
$messages[] = '<div id="message" class="updated"><p>' . sprintf( __( 'New user created. <a href="%s">Edit user</a>' ),
esc_url( add_query_arg( 'wp_http_referer', urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ),
self_admin_url( 'user-edit.php?user_id=' . $user_id ) ) ) ) . '</p></div>';
} else {
$messages[] = '<div id="message" class="updated"><p>' . __( 'New user created.' ) . '</p></div>';
}
break;
case 'promote':
$messages[] = '<div id="message" class="updated"><p>' . __('Changed roles.') . '</p></div>';
break;
case 'err_admin_role':
$messages[] = '<div id="message" class="error"><p>' . __('The current user’s role must have user editing capabilities.') . '</p></div>';
$messages[] = '<div id="message" class="updated"><p>' . __('Other user roles have been changed.') . '</p></div>';
break;
case 'err_admin_del':
$messages[] = '<div id="message" class="error"><p>' . __('You can’t delete the current user.') . '</p></div>';
$messages[] = '<div id="message" class="updated"><p>' . __('Other users have been deleted.') . '</p></div>';
break;
case 'remove':
$messages[] = '<div id="message" class="updated fade"><p>' . __('User removed from this site.') . '</p></div>';
break;
case 'err_admin_remove':
$messages[] = '<div id="message" class="error"><p>' . __("You can't remove the current user.") . '</p></div>';
$messages[] = '<div id="message" class="updated fade"><p>' . __('Other users have been removed.') . '</p></div>';
break;
}
endif; ?>
<?php if ( isset($errors) && is_wp_error( $errors ) ) : ?>
<div class="error">
<ul>
<?php
foreach ( $errors->get_error_messages() as $err )
echo "<li>$err</li>\n";
?>
</ul>
</div>
<?php endif;
if ( ! empty($messages) ) {
foreach ( $messages as $msg )
echo $msg;
} ?>
<div class="wrap">
<h2>
<?php
echo esc_html( $title );
if ( current_user_can( 'create_users' ) ) { ?>
<a href="user-new.php" class="add-new-h2"><?php echo esc_html_x( 'Add New', 'user' ); ?></a>
<?php } elseif ( is_multisite() && current_user_can( 'promote_users' ) ) { ?>
<a href="user-new.php" class="add-new-h2"><?php echo esc_html_x( 'Add Existing', 'user' ); ?></a>
<?php }
if ( $usersearch )
printf( '<span class="subtitle">' . __('Search results for “%s”') . '</span>', esc_html( $usersearch ) ); ?>
</h2>
<?php $wp_list_table->views(); ?>
<form action="" method="get">
<?php $wp_list_table->search_box( __( 'Search Users' ), 'user' ); ?>
<?php $wp_list_table->display(); ?>
</form>
<br class="clear" />
</div>
<?php
break;
} // end of the $doaction switch
include( ABSPATH . 'wp-admin/admin-footer.php' );
| 01-wordpress-paypal | trunk/wp-admin/users.php | PHP | gpl3 | 15,704 |
<?php
/**
* Media management action handler.
*
* @package WordPress
* @subpackage Administration
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
$parent_file = 'upload.php';
$submenu_file = 'upload.php';
wp_reset_vars(array('action'));
switch( $action ) :
case 'editattachment' :
$attachment_id = (int) $_POST['attachment_id'];
check_admin_referer('media-form');
if ( !current_user_can('edit_post', $attachment_id) )
wp_die ( __('You are not allowed to edit this attachment.') );
$errors = media_upload_form_handler();
if ( empty($errors) ) {
$location = 'media.php';
if ( $referer = wp_get_original_referer() ) {
if ( false !== strpos($referer, 'upload.php') || ( url_to_postid($referer) == $attachment_id ) )
$location = $referer;
}
if ( false !== strpos($location, 'upload.php') ) {
$location = remove_query_arg('message', $location);
$location = add_query_arg('posted', $attachment_id, $location);
} elseif ( false !== strpos($location, 'media.php') ) {
$location = add_query_arg('message', 'updated', $location);
}
wp_redirect($location);
exit;
}
// no break
case 'edit' :
$title = __('Edit Media');
if ( empty($errors) )
$errors = null;
if ( empty( $_GET['attachment_id'] ) ) {
wp_redirect( admin_url('upload.php') );
exit();
}
$att_id = (int) $_GET['attachment_id'];
if ( !current_user_can('edit_post', $att_id) )
wp_die ( __('You are not allowed to edit this attachment.') );
$att = get_post($att_id);
if ( empty($att->ID) ) wp_die( __('You attempted to edit an attachment that doesn’t exist. Perhaps it was deleted?') );
if ( 'attachment' !== $att->post_type ) wp_die( __('You attempted to edit an item that isn’t an attachment. Please go back and try again.') );
if ( $att->post_status == 'trash' ) wp_die( __('You can’t edit this attachment because it is in the Trash. Please move it out of the Trash and try again.') );
add_filter('attachment_fields_to_edit', 'media_single_attachment_fields_to_edit', 10, 2);
wp_enqueue_script( 'wp-ajax-response' );
wp_enqueue_script('image-edit');
wp_enqueue_style('imgareaselect');
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('This screen allows you to edit five fields for metadata in a file within the media library.') . '</p>' .
'<p>' . __('For images only, you can click on Edit Image under the thumbnail to expand out an inline image editor with icons for cropping, rotating, or flipping the image as well as for undoing and redoing. The boxes on the right give you more options for scaling the image, for cropping it, and for cropping the thumbnail in a different way than you crop the original image. You can click on Help in those boxes to get more information.') . '</p>' .
'<p>' . __('Note that you crop the image by clicking on it (the Crop icon is already selected) and dragging the cropping frame to select the desired part. Then click Save to retain the cropping.') . '</p>' .
'<p>' . __('Remember to click Update Media to save metadata entered or changed.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Media_Add_New_Screen#Edit_Media" target="_blank">Documentation on Edit Media</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
require( ABSPATH . 'wp-admin/admin-header.php' );
$parent_file = 'upload.php';
$message = '';
$class = '';
if ( isset($_GET['message']) ) {
switch ( $_GET['message'] ) :
case 'updated' :
$message = __('Media attachment updated.');
$class = 'updated';
break;
endswitch;
}
if ( $message )
echo "<div id='message' class='$class'><p>$message</p></div>\n";
?>
<div class="wrap">
<h2>
<?php
echo esc_html( $title );
if ( current_user_can( 'upload_files' ) ) { ?>
<a href="media-new.php" class="add-new-h2"><?php echo esc_html_x('Add New', 'file'); ?></a>
<?php } ?>
</h2>
<form method="post" action="" class="media-upload-form" id="media-single-form">
<p class="submit" style="padding-bottom: 0;">
<?php submit_button( __( 'Update Media' ), 'primary', 'save', false ); ?>
</p>
<div class="media-single">
<div id='media-item-<?php echo $att_id; ?>' class='media-item'>
<?php echo get_media_item( $att_id, array( 'toggle' => false, 'send' => false, 'delete' => false, 'show_title' => false, 'errors' => !empty($errors[$att_id]) ? $errors[$att_id] : null ) ); ?>
</div>
</div>
<?php submit_button( __( 'Update Media' ), 'primary', 'save' ); ?>
<input type="hidden" name="post_id" id="post_id" value="<?php echo isset($post_id) ? esc_attr($post_id) : ''; ?>" />
<input type="hidden" name="attachment_id" id="attachment_id" value="<?php echo esc_attr($att_id); ?>" />
<input type="hidden" name="action" value="editattachment" />
<?php wp_original_referer_field(true, 'previous'); ?>
<?php wp_nonce_field('media-form'); ?>
</form>
</div>
<?php
require( ABSPATH . 'wp-admin/admin-footer.php' );
exit;
default:
wp_redirect( admin_url('upload.php') );
exit;
endswitch;
| 01-wordpress-paypal | trunk/wp-admin/media.php | PHP | gpl3 | 5,241 |
<?php
/**
* Edit tag form for inclusion in administration panels.
*
* @package WordPress
* @subpackage Administration
*/
// don't load directly
if ( !defined('ABSPATH') )
die('-1');
if ( empty($tag_ID) ) { ?>
<div id="message" class="updated"><p><strong><?php _e( 'You did not select an item for editing.' ); ?></strong></p></div>
<?php
return;
}
// Back compat hooks
if ( 'category' == $taxonomy ) {
/**
* Fires before the Edit Category form.
*
* @since 2.1.0
* @deprecated 3.0.0 Use {$taxonomy}_pre_edit_form instead.
*
* @param object $tag Current category term object.
*/
do_action( 'edit_category_form_pre', $tag );
} elseif ( 'link_category' == $taxonomy ) {
/**
* Fires before the Edit Link Category form.
*
* @since 2.3.0
* @deprecated 3.0.0 Use {$taxonomy}_pre_edit_form instead.
*
* @param object $tag Current link category term object.
*/
do_action( 'edit_link_category_form_pre', $tag );
} else {
/**
* Fires before the Edit Tag form.
*
* @since 2.5.0
* @deprecated 3.0.0 Use {$taxonomy}_pre_edit_form instead.
*
* @param object $tag Current tag term object.
*/
do_action( 'edit_tag_form_pre', $tag );
}
/**
* Fires before the Edit Term form for all taxonomies.
*
* The dynamic portion of the hook name, $taxonomy, refers to
* the taxonomy slug.
*
* @since 3.0.0
*
* @param object $tag Current taxonomy term object.
* @param string $taxonomy Current $taxonomy slug.
*/
do_action( "{$taxonomy}_pre_edit_form", $tag, $taxonomy ); ?>
<div class="wrap">
<h2><?php echo $tax->labels->edit_item; ?></h2>
<div id="ajax-response"></div>
<?php
/**
* Fires inside the Edit Term form tag.
*
* The dynamic portion of the hook name, $taxonomy, refers to
* the taxonomy slug.
*
* @since 3.7.0
*/
?>
<form name="edittag" id="edittag" method="post" action="edit-tags.php" class="validate"<?php do_action( "{$taxonomy}_term_edit_form_tag" ); ?>>
<input type="hidden" name="action" value="editedtag" />
<input type="hidden" name="tag_ID" value="<?php echo esc_attr($tag->term_id) ?>" />
<input type="hidden" name="taxonomy" value="<?php echo esc_attr($taxonomy) ?>" />
<?php wp_original_referer_field(true, 'previous'); wp_nonce_field('update-tag_' . $tag_ID); ?>
<table class="form-table">
<tr class="form-field form-required">
<th scope="row"><label for="name"><?php _ex('Name', 'Taxonomy Name'); ?></label></th>
<td><input name="name" id="name" type="text" value="<?php if ( isset( $tag->name ) ) echo esc_attr($tag->name); ?>" size="40" aria-required="true" />
<p class="description"><?php _e('The name is how it appears on your site.'); ?></p></td>
</tr>
<?php if ( !global_terms_enabled() ) { ?>
<tr class="form-field">
<th scope="row"><label for="slug"><?php _ex('Slug', 'Taxonomy Slug'); ?></label></th>
<?php
/**
* Filter the editable term slug.
*
* @since 2.6.0
*
* @param string $slug The current term slug.
*/
?>
<td><input name="slug" id="slug" type="text" value="<?php if ( isset( $tag->slug ) ) echo esc_attr( apply_filters( 'editable_slug', $tag->slug ) ); ?>" size="40" />
<p class="description"><?php _e('The “slug” is the URL-friendly version of the name. It is usually all lowercase and contains only letters, numbers, and hyphens.'); ?></p></td>
</tr>
<?php } ?>
<?php if ( is_taxonomy_hierarchical($taxonomy) ) : ?>
<tr class="form-field">
<th scope="row"><label for="parent"><?php _ex('Parent', 'Taxonomy Parent'); ?></label></th>
<td>
<?php wp_dropdown_categories(array('hide_empty' => 0, 'hide_if_empty' => false, 'name' => 'parent', 'orderby' => 'name', 'taxonomy' => $taxonomy, 'selected' => $tag->parent, 'exclude_tree' => $tag->term_id, 'hierarchical' => true, 'show_option_none' => __('None'))); ?>
<?php if ( 'category' == $taxonomy ) : ?>
<p class="description"><?php _e('Categories, unlike tags, can have a hierarchy. You might have a Jazz category, and under that have children categories for Bebop and Big Band. Totally optional.'); ?></p>
<?php endif; ?>
</td>
</tr>
<?php endif; // is_taxonomy_hierarchical() ?>
<tr class="form-field">
<th scope="row"><label for="description"><?php _ex('Description', 'Taxonomy Description'); ?></label></th>
<td><textarea name="description" id="description" rows="5" cols="50" class="large-text"><?php echo $tag->description; // textarea_escaped ?></textarea><br />
<span class="description"><?php _e('The description is not prominent by default; however, some themes may show it.'); ?></span></td>
</tr>
<?php
// Back compat hooks
if ( 'category' == $taxonomy ) {
/**
* Fires after the Edit Category form fields are displayed.
*
* @since 2.9.0
* @deprecated 3.0.0 Use {$taxonomy}_edit_form_fields instead.
*
* @param object $tag Current category term object.
*/
do_action( 'edit_category_form_fields', $tag );
} elseif ( 'link_category' == $taxonomy ) {
/**
* Fires after the Edit Link Category form fields are displayed.
*
* @since 2.9.0
* @deprecated 3.0.0 Use {$taxonomy}_edit_form_fields instead.
*
* @param object $tag Current link category term object.
*/
do_action( 'edit_link_category_form_fields', $tag );
} else {
/**
* Fires after the Edit Tag form fields are displayed.
*
* @since 2.9.0
* @deprecated 3.0.0 Use {$taxonomy}_edit_form_fields instead.
*
* @param object $tag Current tag term object.
*/
do_action( 'edit_tag_form_fields', $tag );
}
/**
* Fires after the Edit Term form fields are displayed.
*
* The dynamic portion of the hook name, $taxonomy, refers to
* the taxonomy slug.
*
* @since 3.0.0
*
* @param object $tag Current taxonomy term object.
* @param string $taxonomy Current taxonomy slug.
*/
do_action( "{$taxonomy}_edit_form_fields", $tag, $taxonomy );
?>
</table>
<?php
// Back compat hooks
if ( 'category' == $taxonomy ) {
/** This action is documented in wp-admin/edit-tags.php */
do_action( 'edit_category_form', $tag );
} elseif ( 'link_category' == $taxonomy ) {
/** This action is documented in wp-admin/edit-tags.php */
do_action( 'edit_link_category_form', $tag );
} else {
/**
* Fires at the end of the Edit Term form.
*
* @since 2.5.0
* @deprecated 3.0.0 Use {$taxonomy}_edit_form instead.
*
* @param object $tag Current taxonomy term object.
*/
do_action( 'edit_tag_form', $tag );
}
/**
* Fires at the end of the Edit Term form for all taxonomies.
*
* The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug.
*
* @since 3.0.0
*
* @param object $tag Current taxonomy term object.
* @param string $taxonomy Current taxonomy slug.
*/
do_action( "{$taxonomy}_edit_form", $tag, $taxonomy );
submit_button( __('Update') );
?>
</form>
</div>
<script type="text/javascript">
try{document.forms.edittag.name.focus();}catch(e){}
</script>
| 01-wordpress-paypal | trunk/wp-admin/edit-tag-form.php | PHP | gpl3 | 6,948 |
<?php
/**
* Edit Tags Administration Screen.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! $taxnow )
wp_die( __( 'Invalid taxonomy' ) );
$tax = get_taxonomy( $taxnow );
if ( ! $tax )
wp_die( __( 'Invalid taxonomy' ) );
if ( ! current_user_can( $tax->cap->manage_terms ) )
wp_die( __( 'Cheatin’ uh?' ) );
$wp_list_table = _get_list_table('WP_Terms_List_Table');
$pagenum = $wp_list_table->get_pagenum();
$title = $tax->labels->name;
if ( 'post' != $post_type ) {
$parent_file = ( 'attachment' == $post_type ) ? 'upload.php' : "edit.php?post_type=$post_type";
$submenu_file = "edit-tags.php?taxonomy=$taxonomy&post_type=$post_type";
} else if ( 'link_category' == $tax->name ) {
$parent_file = 'link-manager.php';
$submenu_file = 'edit-tags.php?taxonomy=link_category';
} else {
$parent_file = 'edit.php';
$submenu_file = "edit-tags.php?taxonomy=$taxonomy";
}
add_screen_option( 'per_page', array( 'label' => $title, 'default' => 20, 'option' => 'edit_' . $tax->name . '_per_page' ) );
switch ( $wp_list_table->current_action() ) {
case 'add-tag':
check_admin_referer( 'add-tag', '_wpnonce_add-tag' );
if ( !current_user_can( $tax->cap->edit_terms ) )
wp_die( __( 'Cheatin’ uh?' ) );
$ret = wp_insert_term( $_POST['tag-name'], $taxonomy, $_POST );
$location = 'edit-tags.php?taxonomy=' . $taxonomy;
if ( 'post' != $post_type )
$location .= '&post_type=' . $post_type;
if ( $referer = wp_get_original_referer() ) {
if ( false !== strpos( $referer, 'edit-tags.php' ) )
$location = $referer;
}
if ( $ret && !is_wp_error( $ret ) )
$location = add_query_arg( 'message', 1, $location );
else
$location = add_query_arg( 'message', 4, $location );
wp_redirect( $location );
exit;
break;
case 'delete':
$location = 'edit-tags.php?taxonomy=' . $taxonomy;
if ( 'post' != $post_type )
$location .= '&post_type=' . $post_type;
if ( $referer = wp_get_referer() ) {
if ( false !== strpos( $referer, 'edit-tags.php' ) )
$location = $referer;
}
if ( !isset( $_REQUEST['tag_ID'] ) ) {
wp_redirect( $location );
exit;
}
$tag_ID = (int) $_REQUEST['tag_ID'];
check_admin_referer( 'delete-tag_' . $tag_ID );
if ( !current_user_can( $tax->cap->delete_terms ) )
wp_die( __( 'Cheatin’ uh?' ) );
wp_delete_term( $tag_ID, $taxonomy );
$location = add_query_arg( 'message', 2, $location );
wp_redirect( $location );
exit;
break;
case 'bulk-delete':
check_admin_referer( 'bulk-tags' );
if ( !current_user_can( $tax->cap->delete_terms ) )
wp_die( __( 'Cheatin’ uh?' ) );
$tags = (array) $_REQUEST['delete_tags'];
foreach ( $tags as $tag_ID ) {
wp_delete_term( $tag_ID, $taxonomy );
}
$location = 'edit-tags.php?taxonomy=' . $taxonomy;
if ( 'post' != $post_type )
$location .= '&post_type=' . $post_type;
if ( $referer = wp_get_referer() ) {
if ( false !== strpos( $referer, 'edit-tags.php' ) )
$location = $referer;
}
$location = add_query_arg( 'message', 6, $location );
wp_redirect( $location );
exit;
break;
case 'edit':
$title = $tax->labels->edit_item;
$tag_ID = (int) $_REQUEST['tag_ID'];
$tag = get_term( $tag_ID, $taxonomy, OBJECT, 'edit' );
if ( ! $tag )
wp_die( __( 'You attempted to edit an item that doesn’t exist. Perhaps it was deleted?' ) );
require_once( ABSPATH . 'wp-admin/admin-header.php' );
include( ABSPATH . 'wp-admin/edit-tag-form.php' );
break;
case 'editedtag':
$tag_ID = (int) $_POST['tag_ID'];
check_admin_referer( 'update-tag_' . $tag_ID );
if ( !current_user_can( $tax->cap->edit_terms ) )
wp_die( __( 'Cheatin’ uh?' ) );
$tag = get_term( $tag_ID, $taxonomy );
if ( ! $tag )
wp_die( __( 'You attempted to edit an item that doesn’t exist. Perhaps it was deleted?' ) );
$ret = wp_update_term( $tag_ID, $taxonomy, $_POST );
$location = 'edit-tags.php?taxonomy=' . $taxonomy;
if ( 'post' != $post_type )
$location .= '&post_type=' . $post_type;
if ( $referer = wp_get_original_referer() ) {
if ( false !== strpos( $referer, 'edit-tags.php' ) )
$location = $referer;
}
if ( $ret && !is_wp_error( $ret ) )
$location = add_query_arg( 'message', 3, $location );
else
$location = add_query_arg( 'message', 5, $location );
wp_redirect( $location );
exit;
break;
default:
if ( ! empty($_REQUEST['_wp_http_referer']) ) {
$location = remove_query_arg( array('_wp_http_referer', '_wpnonce'), wp_unslash($_SERVER['REQUEST_URI']) );
if ( ! empty( $_REQUEST['paged'] ) )
$location = add_query_arg( 'paged', (int) $_REQUEST['paged'] );
wp_redirect( $location );
exit;
}
$wp_list_table->prepare_items();
$total_pages = $wp_list_table->get_pagination_arg( 'total_pages' );
if ( $pagenum > $total_pages && $total_pages > 0 ) {
wp_redirect( add_query_arg( 'paged', $total_pages ) );
exit;
}
wp_enqueue_script('admin-tags');
if ( current_user_can($tax->cap->edit_terms) )
wp_enqueue_script('inline-edit-tax');
if ( 'category' == $taxonomy || 'link_category' == $taxonomy || 'post_tag' == $taxonomy ) {
$help ='';
if ( 'category' == $taxonomy )
$help = '<p>' . sprintf(__( 'You can use categories to define sections of your site and group related posts. The default category is “Uncategorized” until you change it in your <a href="%s">writing settings</a>.' ) , 'options-writing.php' ) . '</p>';
elseif ( 'link_category' == $taxonomy )
$help = '<p>' . __( 'You can create groups of links by using Link Categories. Link Category names must be unique and Link Categories are separate from the categories you use for posts.' ) . '</p>';
else
$help = '<p>' . __( 'You can assign keywords to your posts using <strong>tags</strong>. Unlike categories, tags have no hierarchy, meaning there’s no relationship from one tag to another.' ) . '</p>';
if ( 'link_category' == $taxonomy )
$help .= '<p>' . __( 'You can delete Link Categories in the Bulk Action pull-down, but that action does not delete the links within the category. Instead, it moves them to the default Link Category.' ) . '</p>';
else
$help .='<p>' . __( 'What’s the difference between categories and tags? Normally, tags are ad-hoc keywords that identify important information in your post (names, subjects, etc) that may or may not recur in other posts, while categories are pre-determined sections. If you think of your site like a book, the categories are like the Table of Contents and the tags are like the terms in the index.' ) . '</p>';
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' => $help,
) );
if ( 'category' == $taxonomy || 'post_tag' == $taxonomy ) {
if ( 'category' == $taxonomy )
$help = '<p>' . __( 'When adding a new category on this screen, you’ll fill in the following fields:' ) . '</p>';
else
$help = '<p>' . __( 'When adding a new tag on this screen, you’ll fill in the following fields:' ) . '</p>';
$help .= '<ul>' .
'<li>' . __( '<strong>Name</strong> - The name is how it appears on your site.' ) . '</li>';
if ( ! global_terms_enabled() )
$help .= '<li>' . __( '<strong>Slug</strong> - The “slug” is the URL-friendly version of the name. It is usually all lowercase and contains only letters, numbers, and hyphens.' ) . '</li>';
if ( 'category' == $taxonomy )
$help .= '<li>' . __( '<strong>Parent</strong> - Categories, unlike tags, can have a hierarchy. You might have a Jazz category, and under that have child categories for Bebop and Big Band. Totally optional. To create a subcategory, just choose another category from the Parent dropdown.' ) . '</li>';
$help .= '<li>' . __( '<strong>Description</strong> - The description is not prominent by default; however, some themes may display it.' ) . '</li>' .
'</ul>' .
'<p>' . __( 'You can change the display of this screen using the Screen Options tab to set how many items are displayed per screen and to display/hide columns in the table.' ) . '</p>';
get_current_screen()->add_help_tab( array(
'id' => 'adding-terms',
'title' => 'category' == $taxonomy ? __( 'Adding Categories' ) : __( 'Adding Tags' ),
'content' => $help,
) );
}
$help = '<p><strong>' . __( 'For more information:' ) . '</strong></p>';
if ( 'category' == $taxonomy )
$help .= '<p>' . __( '<a href="http://codex.wordpress.org/Posts_Categories_Screen" target="_blank">Documentation on Categories</a>' ) . '</p>';
elseif ( 'link_category' == $taxonomy )
$help .= '<p>' . __( '<a href="http://codex.wordpress.org/Links_Link_Categories_Screen" target="_blank">Documentation on Link Categories</a>' ) . '</p>';
else
$help .= '<p>' . __( '<a href="http://codex.wordpress.org/Posts_Tags_Screen" target="_blank">Documentation on Tags</a>' ) . '</p>';
$help .= '<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>';
get_current_screen()->set_help_sidebar( $help );
unset( $help );
}
require_once( ABSPATH . 'wp-admin/admin-header.php' );
if ( !current_user_can($tax->cap->edit_terms) )
wp_die( __('You are not allowed to edit this item.') );
$messages = array();
$messages['_item'] = array(
0 => '', // Unused. Messages start at index 1.
1 => __( 'Item added.' ),
2 => __( 'Item deleted.' ),
3 => __( 'Item updated.' ),
4 => __( 'Item not added.' ),
5 => __( 'Item not updated.' ),
6 => __( 'Items deleted.' )
);
$messages['category'] = array(
0 => '', // Unused. Messages start at index 1.
1 => __( 'Category added.' ),
2 => __( 'Category deleted.' ),
3 => __( 'Category updated.' ),
4 => __( 'Category not added.' ),
5 => __( 'Category not updated.' ),
6 => __( 'Categories deleted.' )
);
$messages['post_tag'] = array(
0 => '', // Unused. Messages start at index 1.
1 => __( 'Tag added.' ),
2 => __( 'Tag deleted.' ),
3 => __( 'Tag updated.' ),
4 => __( 'Tag not added.' ),
5 => __( 'Tag not updated.' ),
6 => __( 'Tags deleted.' )
);
/**
* Filter the messages displayed when a tag is updated.
*
* @since 3.7.0
*
* @param array $messages The messages to be displayed.
*/
$messages = apply_filters( 'term_updated_messages', $messages );
$message = false;
if ( isset( $_REQUEST['message'] ) && ( $msg = (int) $_REQUEST['message'] ) ) {
if ( isset( $messages[ $taxonomy ][ $msg ] ) )
$message = $messages[ $taxonomy ][ $msg ];
elseif ( ! isset( $messages[ $taxonomy ] ) && isset( $messages['_item'][ $msg ] ) )
$message = $messages['_item'][ $msg ];
}
?>
<div class="wrap nosubsub">
<h2><?php echo esc_html( $title );
if ( !empty($_REQUEST['s']) )
printf( '<span class="subtitle">' . __('Search results for “%s”') . '</span>', esc_html( wp_unslash($_REQUEST['s']) ) ); ?>
</h2>
<?php if ( $message ) : ?>
<div id="message" class="updated"><p><?php echo $message; ?></p></div>
<?php $_SERVER['REQUEST_URI'] = remove_query_arg(array('message'), $_SERVER['REQUEST_URI']);
endif; ?>
<div id="ajax-response"></div>
<form class="search-form" action="" method="get">
<input type="hidden" name="taxonomy" value="<?php echo esc_attr($taxonomy); ?>" />
<input type="hidden" name="post_type" value="<?php echo esc_attr($post_type); ?>" />
<?php $wp_list_table->search_box( $tax->labels->search_items, 'tag' ); ?>
</form>
<br class="clear" />
<div id="col-container">
<div id="col-right">
<div class="col-wrap">
<form id="posts-filter" action="" method="post">
<input type="hidden" name="taxonomy" value="<?php echo esc_attr($taxonomy); ?>" />
<input type="hidden" name="post_type" value="<?php echo esc_attr($post_type); ?>" />
<?php $wp_list_table->display(); ?>
<br class="clear" />
</form>
<?php if ( 'category' == $taxonomy ) : ?>
<div class="form-wrap">
<?php /** This filter is documented in wp-includes/category-template.php */ ?>
<p><?php printf(__('<strong>Note:</strong><br />Deleting a category does not delete the posts in that category. Instead, posts that were only assigned to the deleted category are set to the category <strong>%s</strong>.'), apply_filters('the_category', get_cat_name(get_option('default_category')))) ?></p>
<?php if ( current_user_can( 'import' ) ) : ?>
<p><?php printf(__('Categories can be selectively converted to tags using the <a href="%s">category to tag converter</a>.'), 'import.php') ?></p>
<?php endif; ?>
</div>
<?php elseif ( 'post_tag' == $taxonomy && current_user_can( 'import' ) ) : ?>
<div class="form-wrap">
<p><?php printf(__('Tags can be selectively converted to categories using the <a href="%s">tag to category converter</a>.'), 'import.php') ;?></p>
</div>
<?php endif;
/**
* Fires after the taxonomy list table.
*
* The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug.
*
* @since 3.0.0
*
* @param string $taxonomy The taxonomy name.
*/
do_action( "after-{$taxonomy}-table", $taxonomy );
?>
</div>
</div><!-- /col-right -->
<div id="col-left">
<div class="col-wrap">
<?php
if ( !is_null( $tax->labels->popular_items ) ) {
if ( current_user_can( $tax->cap->edit_terms ) )
$tag_cloud = wp_tag_cloud( array( 'taxonomy' => $taxonomy, 'post_type' => $post_type, 'echo' => false, 'link' => 'edit' ) );
else
$tag_cloud = wp_tag_cloud( array( 'taxonomy' => $taxonomy, 'echo' => false ) );
if ( $tag_cloud ) :
?>
<div class="tagcloud">
<h3><?php echo $tax->labels->popular_items; ?></h3>
<?php echo $tag_cloud; unset( $tag_cloud ); ?>
</div>
<?php
endif;
}
if ( current_user_can($tax->cap->edit_terms) ) {
if ( 'category' == $taxonomy ) {
/**
* Fires before the Add Category form.
*
* @since 2.1.0
* @deprecated 3.0.0 Use {$taxonomy}_pre_add_form instead.
*
* @param object $arg Optional arguments cast to an object.
*/
do_action( 'add_category_form_pre', (object) array( 'parent' => 0 ) );
} elseif ( 'link_category' == $taxonomy ) {
/**
* Fires before the link category form.
*
* @since 2.3.0
* @deprecated 3.0.0 Use {$taxonomy}_pre_add_form instead.
*
* @param object $arg Optional arguments cast to an object.
*/
do_action( 'add_link_category_form_pre', (object) array( 'parent' => 0 ) );
} else {
/**
* Fires before the Add Tag form.
*
* @since 2.5.0
* @deprecated 3.0.0 Use {$taxonomy}_pre_add_form instead.
*
* @param string $taxonomy The taxonomy slug.
*/
do_action( 'add_tag_form_pre', $taxonomy );
}
/**
* Fires before the Add Term form for all taxonomies.
*
* The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug.
*
* @since 3.0.0
*
* @param string $taxonomy The taxonomy slug.
*/
do_action( "{$taxonomy}_pre_add_form", $taxonomy );
?>
<div class="form-wrap">
<h3><?php echo $tax->labels->add_new_item; ?></h3>
<?php
/**
* Fires at the beginning of the Add Tag form.
*
* The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug.
*
* @since 3.7.0
*/
?>
<form id="addtag" method="post" action="edit-tags.php" class="validate"<?php do_action( "{$taxonomy}_term_new_form_tag" ); ?>>
<input type="hidden" name="action" value="add-tag" />
<input type="hidden" name="screen" value="<?php echo esc_attr($current_screen->id); ?>" />
<input type="hidden" name="taxonomy" value="<?php echo esc_attr($taxonomy); ?>" />
<input type="hidden" name="post_type" value="<?php echo esc_attr($post_type); ?>" />
<?php wp_nonce_field('add-tag', '_wpnonce_add-tag'); ?>
<div class="form-field form-required">
<label for="tag-name"><?php _ex('Name', 'Taxonomy Name'); ?></label>
<input name="tag-name" id="tag-name" type="text" value="" size="40" aria-required="true" />
<p><?php _e('The name is how it appears on your site.'); ?></p>
</div>
<?php if ( ! global_terms_enabled() ) : ?>
<div class="form-field">
<label for="tag-slug"><?php _ex('Slug', 'Taxonomy Slug'); ?></label>
<input name="slug" id="tag-slug" type="text" value="" size="40" />
<p><?php _e('The “slug” is the URL-friendly version of the name. It is usually all lowercase and contains only letters, numbers, and hyphens.'); ?></p>
</div>
<?php endif; // global_terms_enabled() ?>
<?php if ( is_taxonomy_hierarchical($taxonomy) ) : ?>
<div class="form-field">
<label for="parent"><?php _ex('Parent', 'Taxonomy Parent'); ?></label>
<?php
$dropdown_args = array(
'hide_empty' => 0,
'hide_if_empty' => false,
'taxonomy' => $taxonomy,
'name' => 'parent',
'orderby' => 'name',
'hierarchical' => true,
'show_option_none' => __( 'None' ),
);
/**
* Filter the taxonomy parent drop-down on the Edit Term page.
*
* @since 3.7.0
*
* @param array $dropdown_args {
* An array of taxonomy parent drop-down arguments.
*
* @type int|bool $hide_empty Whether to hide terms not attached to any posts. Default 0|false.
* @type bool $hide_if_empty Whether to hide the drop-down if no terms exist. Default false.
* @type string $taxonomy The taxonomy slug.
* @type string $name Value of the name attribute to use for the drop-down select element.
* Default 'parent'.
* @type string $orderby The field to order by. Default 'name'.
* @type bool $hierarchical Whether the taxonomy is hierarchical. Default true.
* @type string $show_option_none Label to display if there are no terms. Default 'None'.
* }
* @param string $taxonomy The taxonomy slug.
*/
$dropdown_args = apply_filters( 'taxonomy_parent_dropdown_args', $dropdown_args, $taxonomy );
wp_dropdown_categories( $dropdown_args );
?>
<?php if ( 'category' == $taxonomy ) : // @todo: Generic text for hierarchical taxonomies ?>
<p><?php _e('Categories, unlike tags, can have a hierarchy. You might have a Jazz category, and under that have children categories for Bebop and Big Band. Totally optional.'); ?></p>
<?php endif; ?>
</div>
<?php endif; // is_taxonomy_hierarchical() ?>
<div class="form-field">
<label for="tag-description"><?php _ex('Description', 'Taxonomy Description'); ?></label>
<textarea name="description" id="tag-description" rows="5" cols="40"></textarea>
<p><?php _e('The description is not prominent by default; however, some themes may show it.'); ?></p>
</div>
<?php
if ( ! is_taxonomy_hierarchical( $taxonomy ) ) {
/**
* Fires after the Add Tag form fields for non-hierarchical taxonomies.
*
* @since 3.0.0
*
* @param string $taxonomy The taxonomy slug.
*/
do_action( 'add_tag_form_fields', $taxonomy );
}
/**
* Fires after the Add Term form fields for hierarchical taxonomies.
*
* The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug.
*
* @since 3.0.0
*
* @param string $taxonomy The taxonomy slug.
*/
do_action( "{$taxonomy}_add_form_fields", $taxonomy );
submit_button( $tax->labels->add_new_item );
if ( 'category' == $taxonomy ) {
/**
* Fires at the end of the Edit Category form.
*
* @since 2.1.0
* @deprecated 3.0.0 Use {$taxonomy}_add_form instead.
*
* @param object $arg Optional arguments cast to an object.
*/
do_action( 'edit_category_form', (object) array( 'parent' => 0 ) );
} elseif ( 'link_category' == $taxonomy ) {
/**
* Fires at the end of the Edit Link form.
*
* @since 2.3.0
* @deprecated 3.0.0 Use {$taxonomy}_add_form instead.
*
* @param object $arg Optional arguments cast to an object.
*/
do_action( 'edit_link_category_form', (object) array( 'parent' => 0 ) );
} else {
/**
* Fires at the end of the Add Tag form.
*
* @since 2.7.0
* @deprecated 3.0.0 Use {$taxonomy}_add_form instead.
*
* @param string $taxonomy The taxonomy slug.
*/
do_action( 'add_tag_form', $taxonomy );
}
/**
* Fires at the end of the Add Term form for all taxonomies.
*
* The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug.
*
* @since 3.0.0
*
* @param string $taxonomy The taxonomy slug.
*/
do_action( "{$taxonomy}_add_form", $taxonomy );
?>
</form></div>
<?php } ?>
</div>
</div><!-- /col-left -->
</div><!-- /col-container -->
</div><!-- /wrap -->
<script type="text/javascript">
try{document.forms.addtag['tag-name'].focus();}catch(e){}
</script>
<?php $wp_list_table->inline_edit(); ?>
<?php
break;
}
include( ABSPATH . 'wp-admin/admin-footer.php' );
| 01-wordpress-paypal | trunk/wp-admin/edit-tags.php | PHP | gpl3 | 20,331 |
<?php
/**
* Build Administration Menu.
*
* @package WordPress
* @subpackage Administration
*/
/**
* Constructs the admin menu.
*
* The elements in the array are :
* 0: Menu item name
* 1: Minimum level or capability required.
* 2: The URL of the item's file
* 3: Class
* 4: ID
* 5: Icon for top level menu
*
* @global array $menu
* @name $menu
* @var array
*/
$menu[2] = array( __('Dashboard'), 'read', 'index.php', '', 'menu-top menu-top-first menu-icon-dashboard', 'menu-dashboard', 'dashicons-dashboard' );
$submenu[ 'index.php' ][0] = array( __('Home'), 'read', 'index.php' );
if ( is_multisite() ) {
$submenu[ 'index.php' ][5] = array( __('My Sites'), 'read', 'my-sites.php' );
}
if ( ! is_multisite() || is_super_admin() )
$update_data = wp_get_update_data();
if ( ! is_multisite() ) {
if ( current_user_can( 'update_core' ) )
$cap = 'update_core';
elseif ( current_user_can( 'update_plugins' ) )
$cap = 'update_plugins';
else
$cap = 'update_themes';
$submenu[ 'index.php' ][10] = array( sprintf( __('Updates %s'), "<span class='update-plugins count-{$update_data['counts']['total']}' title='{$update_data['title']}'><span class='update-count'>" . number_format_i18n($update_data['counts']['total']) . "</span></span>" ), $cap, 'update-core.php');
unset( $cap );
}
$menu[4] = array( '', 'read', 'separator1', '', 'wp-menu-separator' );
$menu[5] = array( __('Posts'), 'edit_posts', 'edit.php', '', 'open-if-no-js menu-top menu-icon-post', 'menu-posts', 'dashicons-admin-post' );
$submenu['edit.php'][5] = array( __('All Posts'), 'edit_posts', 'edit.php' );
/* translators: add new post */
$submenu['edit.php'][10] = array( _x('Add New', 'post'), get_post_type_object( 'post' )->cap->create_posts, 'post-new.php' );
$i = 15;
foreach ( get_taxonomies( array(), 'objects' ) as $tax ) {
if ( ! $tax->show_ui || ! $tax->show_in_menu || ! in_array('post', (array) $tax->object_type, true) )
continue;
$submenu['edit.php'][$i++] = array( esc_attr( $tax->labels->menu_name ), $tax->cap->manage_terms, 'edit-tags.php?taxonomy=' . $tax->name );
}
unset($tax);
$menu[10] = array( __('Media'), 'upload_files', 'upload.php', '', 'menu-top menu-icon-media', 'menu-media', 'dashicons-admin-media' );
$submenu['upload.php'][5] = array( __('Library'), 'upload_files', 'upload.php');
/* translators: add new file */
$submenu['upload.php'][10] = array( _x('Add New', 'file'), 'upload_files', 'media-new.php');
foreach ( get_taxonomies_for_attachments( 'objects' ) as $tax ) {
if ( ! $tax->show_ui || ! $tax->show_in_menu )
continue;
$submenu['upload.php'][$i++] = array( esc_attr( $tax->labels->menu_name ), $tax->cap->manage_terms, 'edit-tags.php?taxonomy=' . $tax->name . '&post_type=attachment' );
}
unset($tax);
$menu[15] = array( __('Links'), 'manage_links', 'link-manager.php', '', 'menu-top menu-icon-links', 'menu-links', 'dashicons-admin-links' );
$submenu['link-manager.php'][5] = array( _x('All Links', 'admin menu'), 'manage_links', 'link-manager.php' );
/* translators: add new links */
$submenu['link-manager.php'][10] = array( _x('Add New', 'link'), 'manage_links', 'link-add.php' );
$submenu['link-manager.php'][15] = array( __('Link Categories'), 'manage_categories', 'edit-tags.php?taxonomy=link_category' );
$menu[20] = array( __('Pages'), 'edit_pages', 'edit.php?post_type=page', '', 'menu-top menu-icon-page', 'menu-pages', 'dashicons-admin-page' );
$submenu['edit.php?post_type=page'][5] = array( __('All Pages'), 'edit_pages', 'edit.php?post_type=page' );
/* translators: add new page */
$submenu['edit.php?post_type=page'][10] = array( _x('Add New', 'page'), get_post_type_object( 'page' )->cap->create_posts, 'post-new.php?post_type=page' );
$i = 15;
foreach ( get_taxonomies( array(), 'objects' ) as $tax ) {
if ( ! $tax->show_ui || ! $tax->show_in_menu || ! in_array('page', (array) $tax->object_type, true) )
continue;
$submenu['edit.php?post_type=page'][$i++] = array( esc_attr( $tax->labels->menu_name ), $tax->cap->manage_terms, 'edit-tags.php?taxonomy=' . $tax->name . '&post_type=page' );
}
unset($tax);
$awaiting_mod = wp_count_comments();
$awaiting_mod = $awaiting_mod->moderated;
$menu[25] = array( sprintf( __('Comments %s'), "<span class='awaiting-mod count-$awaiting_mod'><span class='pending-count'>" . number_format_i18n($awaiting_mod) . "</span></span>" ), 'edit_posts', 'edit-comments.php', '', 'menu-top menu-icon-comments', 'menu-comments', 'dashicons-admin-comments' );
unset($awaiting_mod);
$submenu[ 'edit-comments.php' ][0] = array( __('All Comments'), 'edit_posts', 'edit-comments.php' );
$_wp_last_object_menu = 25; // The index of the last top-level menu in the object menu group
foreach ( (array) get_post_types( array('show_ui' => true, '_builtin' => false, 'show_in_menu' => true ) ) as $ptype ) {
$ptype_obj = get_post_type_object( $ptype );
// Check if it should be a submenu.
if ( $ptype_obj->show_in_menu !== true )
continue;
$ptype_menu_position = is_int( $ptype_obj->menu_position ) ? $ptype_obj->menu_position : ++$_wp_last_object_menu; // If we're to use $_wp_last_object_menu, increment it first.
$ptype_for_id = sanitize_html_class( $ptype );
if ( is_string( $ptype_obj->menu_icon ) ) {
// Special handling for data:image/svg+xml and Dashicons.
if ( 0 === strpos( $ptype_obj->menu_icon, 'data:image/svg+xml;base64,' ) || 0 === strpos( $ptype_obj->menu_icon, 'dashicons-' ) ) {
$menu_icon = $ptype_obj->menu_icon;
} else {
$menu_icon = esc_url( $ptype_obj->menu_icon );
}
$ptype_class = $ptype_for_id;
} else {
$menu_icon = 'dashicons-admin-post';
$ptype_class = 'post';
}
// if $ptype_menu_position is already populated or will be populated by a hard-coded value below, increment the position.
$core_menu_positions = array(59, 60, 65, 70, 75, 80, 85, 99);
while ( isset($menu[$ptype_menu_position]) || in_array($ptype_menu_position, $core_menu_positions) )
$ptype_menu_position++;
$menu[$ptype_menu_position] = array( esc_attr( $ptype_obj->labels->menu_name ), $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype", '', 'menu-top menu-icon-' . $ptype_class, 'menu-posts-' . $ptype_for_id, $menu_icon );
$submenu["edit.php?post_type=$ptype"][5] = array( $ptype_obj->labels->all_items, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype");
$submenu["edit.php?post_type=$ptype"][10] = array( $ptype_obj->labels->add_new, $ptype_obj->cap->create_posts, "post-new.php?post_type=$ptype" );
$i = 15;
foreach ( get_taxonomies( array(), 'objects' ) as $tax ) {
if ( ! $tax->show_ui || ! $tax->show_in_menu || ! in_array($ptype, (array) $tax->object_type, true) )
continue;
$submenu["edit.php?post_type=$ptype"][$i++] = array( esc_attr( $tax->labels->menu_name ), $tax->cap->manage_terms, "edit-tags.php?taxonomy=$tax->name&post_type=$ptype" );
}
}
unset($ptype, $ptype_obj, $ptype_class, $ptype_for_id, $ptype_menu_position, $menu_icon, $i, $tax);
$menu[59] = array( '', 'read', 'separator2', '', 'wp-menu-separator' );
$appearance_cap = current_user_can( 'switch_themes') ? 'switch_themes' : 'edit_theme_options';
$menu[60] = array( __('Appearance'), $appearance_cap, 'themes.php', '', 'menu-top menu-icon-appearance', 'menu-appearance', 'dashicons-admin-appearance' );
$submenu['themes.php'][5] = array( __( 'Themes' ), $appearance_cap, 'themes.php' );
$submenu['themes.php'][6] = array( __( 'Customize' ), 'edit_theme_options', 'customize.php', 'hide-if-no-customize' );
if ( current_theme_supports( 'menus' ) || current_theme_supports( 'widgets' ) )
$submenu['themes.php'][10] = array(__( 'Menus' ), 'edit_theme_options', 'nav-menus.php');
unset( $appearance_cap );
// Add 'Editor' to the bottom of the Appearance menu.
if ( ! is_multisite() )
add_action('admin_menu', '_add_themes_utility_last', 101);
function _add_themes_utility_last() {
// Must use API on the admin_menu hook, direct modification is only possible on/before the _admin_menu hook
add_submenu_page('themes.php', _x('Editor', 'theme editor'), _x('Editor', 'theme editor'), 'edit_themes', 'theme-editor.php');
}
$count = '';
if ( ! is_multisite() && current_user_can( 'update_plugins' ) ) {
if ( ! isset( $update_data ) )
$update_data = wp_get_update_data();
$count = "<span class='update-plugins count-{$update_data['counts']['plugins']}'><span class='plugin-count'>" . number_format_i18n($update_data['counts']['plugins']) . "</span></span>";
}
$menu[65] = array( sprintf( __('Plugins %s'), $count ), 'activate_plugins', 'plugins.php', '', 'menu-top menu-icon-plugins', 'menu-plugins', 'dashicons-admin-plugins' );
$submenu['plugins.php'][5] = array( __('Installed Plugins'), 'activate_plugins', 'plugins.php' );
if ( ! is_multisite() ) {
/* translators: add new plugin */
$submenu['plugins.php'][10] = array( _x('Add New', 'plugin'), 'install_plugins', 'plugin-install.php' );
$submenu['plugins.php'][15] = array( _x('Editor', 'plugin editor'), 'edit_plugins', 'plugin-editor.php' );
}
unset( $update_data );
if ( current_user_can('list_users') )
$menu[70] = array( __('Users'), 'list_users', 'users.php', '', 'menu-top menu-icon-users', 'menu-users', 'dashicons-admin-users' );
else
$menu[70] = array( __('Profile'), 'read', 'profile.php', '', 'menu-top menu-icon-users', 'menu-users', 'dashicons-admin-users' );
if ( current_user_can('list_users') ) {
$_wp_real_parent_file['profile.php'] = 'users.php'; // Back-compat for plugins adding submenus to profile.php.
$submenu['users.php'][5] = array(__('All Users'), 'list_users', 'users.php');
if ( current_user_can('create_users') )
$submenu['users.php'][10] = array(_x('Add New', 'user'), 'create_users', 'user-new.php');
else
$submenu['users.php'][10] = array(_x('Add New', 'user'), 'promote_users', 'user-new.php');
$submenu['users.php'][15] = array(__('Your Profile'), 'read', 'profile.php');
} else {
$_wp_real_parent_file['users.php'] = 'profile.php';
$submenu['profile.php'][5] = array(__('Your Profile'), 'read', 'profile.php');
if ( current_user_can('create_users') )
$submenu['profile.php'][10] = array(__('Add New User'), 'create_users', 'user-new.php');
else
$submenu['profile.php'][10] = array(__('Add New User'), 'promote_users', 'user-new.php');
}
$menu[75] = array( __('Tools'), 'edit_posts', 'tools.php', '', 'menu-top menu-icon-tools', 'menu-tools', 'dashicons-admin-tools' );
$submenu['tools.php'][5] = array( __('Available Tools'), 'edit_posts', 'tools.php' );
$submenu['tools.php'][10] = array( __('Import'), 'import', 'import.php' );
$submenu['tools.php'][15] = array( __('Export'), 'export', 'export.php' );
if ( is_multisite() && !is_main_site() )
$submenu['tools.php'][25] = array( __('Delete Site'), 'manage_options', 'ms-delete-site.php' );
if ( ! is_multisite() && defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE )
$submenu['tools.php'][50] = array(__('Network Setup'), 'manage_options', 'network.php');
$menu[80] = array( __('Settings'), 'manage_options', 'options-general.php', '', 'menu-top menu-icon-settings', 'menu-settings', 'dashicons-admin-settings' );
$submenu['options-general.php'][10] = array(_x('General', 'settings screen'), 'manage_options', 'options-general.php');
$submenu['options-general.php'][15] = array(__('Writing'), 'manage_options', 'options-writing.php');
$submenu['options-general.php'][20] = array(__('Reading'), 'manage_options', 'options-reading.php');
$submenu['options-general.php'][25] = array(__('Discussion'), 'manage_options', 'options-discussion.php');
$submenu['options-general.php'][30] = array(__('Media'), 'manage_options', 'options-media.php');
$submenu['options-general.php'][40] = array(__('Permalinks'), 'manage_options', 'options-permalink.php');
$_wp_last_utility_menu = 80; // The index of the last top-level menu in the utility menu group
$menu[99] = array( '', 'read', 'separator-last', '', 'wp-menu-separator' );
// Back-compat for old top-levels
$_wp_real_parent_file['post.php'] = 'edit.php';
$_wp_real_parent_file['post-new.php'] = 'edit.php';
$_wp_real_parent_file['edit-pages.php'] = 'edit.php?post_type=page';
$_wp_real_parent_file['page-new.php'] = 'edit.php?post_type=page';
$_wp_real_parent_file['wpmu-admin.php'] = 'tools.php';
$_wp_real_parent_file['ms-admin.php'] = 'tools.php';
// ensure we're backwards compatible
$compat = array(
'index' => 'dashboard',
'edit' => 'posts',
'post' => 'posts',
'upload' => 'media',
'link-manager' => 'links',
'edit-pages' => 'pages',
'page' => 'pages',
'edit-comments' => 'comments',
'options-general' => 'settings',
'themes' => 'appearance',
);
require_once(ABSPATH . 'wp-admin/includes/menu.php');
| 01-wordpress-paypal | trunk/wp-admin/menu.php | PHP | gpl3 | 12,682 |
<?php
/**
* Edit comment form for inclusion in another file.
*
* @package WordPress
* @subpackage Administration
*/
// don't load directly
if ( !defined('ABSPATH') )
die('-1');
?>
<form name="post" action="comment.php" method="post" id="post">
<?php wp_nonce_field('update-comment_' . $comment->comment_ID) ?>
<div class="wrap">
<h2><?php _e('Edit Comment'); ?></h2>
<div id="poststuff">
<input type="hidden" name="user_ID" value="<?php echo (int) $user_ID; ?>" />
<input type="hidden" name="action" value="editedcomment" />
<input type="hidden" name="comment_ID" value="<?php echo esc_attr( $comment->comment_ID ); ?>" />
<input type="hidden" name="comment_post_ID" value="<?php echo esc_attr( $comment->comment_post_ID ); ?>" />
<div id="post-body" class="metabox-holder columns-2">
<div id="post-body-content" class="edit-form-section">
<div id="namediv" class="stuffbox">
<h3><label for="name"><?php _e( 'Author' ) ?></label></h3>
<div class="inside">
<table class="form-table editcomment">
<tbody>
<tr>
<td class="first"><?php _e( 'Name:' ); ?></td>
<td><input type="text" name="newcomment_author" size="30" value="<?php echo esc_attr( $comment->comment_author ); ?>" id="name" /></td>
</tr>
<tr>
<td class="first">
<?php
if ( $comment->comment_author_email ) {
printf( __( 'E-mail (%s):' ), get_comment_author_email_link( __( 'send e-mail' ), '', '' ) );
} else {
_e( 'E-mail:' );
}
?></td>
<td><input type="text" name="newcomment_author_email" size="30" value="<?php echo $comment->comment_author_email; ?>" id="email" /></td>
</tr>
<tr>
<td class="first">
<?php
if ( ! empty( $comment->comment_author_url ) && 'http://' != $comment->comment_author_url ) {
$link = '<a href="' . $comment->comment_author_url . '" rel="external nofollow" target="_blank">' . __('visit site') . '</a>';
/** This filter is documented in wp-includes/comment-template.php */
printf( __( 'URL (%s):' ), apply_filters( 'get_comment_author_link', $link ) );
} else {
_e( 'URL:' );
} ?></td>
<td><input type="text" id="newcomment_author_url" name="newcomment_author_url" size="30" class="code" value="<?php echo esc_attr($comment->comment_author_url); ?>" /></td>
</tr>
</tbody>
</table>
<br />
</div>
</div>
<div id="postdiv" class="postarea">
<?php
$quicktags_settings = array( 'buttons' => 'strong,em,link,block,del,ins,img,ul,ol,li,code,close' );
wp_editor( $comment->comment_content, 'content', array( 'media_buttons' => false, 'tinymce' => false, 'quicktags' => $quicktags_settings ) );
wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false ); ?>
</div>
</div><!-- /post-body-content -->
<div id="postbox-container-1" class="postbox-container">
<div id="submitdiv" class="stuffbox" >
<h3><span class='hndle'><?php _e('Status') ?></span></h3>
<div class="inside">
<div class="submitbox" id="submitcomment">
<div id="minor-publishing">
<div id="minor-publishing-actions">
<div id="preview-action">
<a class="preview button" href="<?php echo get_comment_link(); ?>" target="_blank"><?php _e('View Comment'); ?></a>
</div>
<div class="clear"></div>
</div>
<div id="misc-publishing-actions">
<div class="misc-pub-section misc-pub-comment-status" id="comment-status-radio">
<label class="approved"><input type="radio"<?php checked( $comment->comment_approved, '1' ); ?> name="comment_status" value="1" /><?php /* translators: comment type radio button */ _ex('Approved', 'adjective') ?></label><br />
<label class="waiting"><input type="radio"<?php checked( $comment->comment_approved, '0' ); ?> name="comment_status" value="0" /><?php /* translators: comment type radio button */ _ex('Pending', 'adjective') ?></label><br />
<label class="spam"><input type="radio"<?php checked( $comment->comment_approved, 'spam' ); ?> name="comment_status" value="spam" /><?php /* translators: comment type radio button */ _ex('Spam', 'adjective'); ?></label>
</div>
<?php if ( $ip = get_comment_author_IP() ) : ?>
<div class="misc-pub-section misc-pub-comment-author-ip">
<?php _e( 'IP address:' ); ?> <strong><a href="<?php echo esc_url( sprintf( 'http://whois.arin.net/rest/ip/%s', $ip ) ); ?>"><?php echo esc_html( $ip ); ?></a></strong>
</div>
<?php endif; ?>
<div class="misc-pub-section curtime misc-pub-curtime">
<?php
/* translators: Publish box date format, see http://php.net/date */
$datef = __( 'M j, Y @ G:i' );
$stamp = __('Submitted on: <b>%1$s</b>');
$date = date_i18n( $datef, strtotime( $comment->comment_date ) );
?>
<span id="timestamp"><?php printf($stamp, $date); ?></span> <a href="#edit_timestamp" class="edit-timestamp hide-if-no-js"><?php _e('Edit') ?></a>
<div id='timestampdiv' class='hide-if-js'><?php touch_time(('editcomment' == $action), 0); ?></div>
</div>
</div> <!-- misc actions -->
<div class="clear"></div>
</div>
<div id="major-publishing-actions">
<div id="delete-action">
<?php echo "<a class='submitdelete deletion' href='" . wp_nonce_url("comment.php?action=" . ( !EMPTY_TRASH_DAYS ? 'deletecomment' : 'trashcomment' ) . "&c=$comment->comment_ID&_wp_original_http_referer=" . urlencode(wp_get_referer()), 'delete-comment_' . $comment->comment_ID) . "'>" . ( !EMPTY_TRASH_DAYS ? __('Delete Permanently') : __('Move to Trash') ) . "</a>\n"; ?>
</div>
<div id="publishing-action">
<?php submit_button( __( 'Update' ), 'primary', 'save', false ); ?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div><!-- /submitdiv -->
</div>
<div id="postbox-container-2" class="postbox-container">
<?php
/** This action is documented in wp-admin/edit-form-advanced.php */
do_action( 'add_meta_boxes', 'comment', $comment );
/**
* Fires when comment-specific meta boxes are added.
*
* @since 3.0.0
*
* @param object $comment Comment object.
*/
do_action( 'add_meta_boxes_comment', $comment );
do_meta_boxes(null, 'normal', $comment);
?>
</div>
<input type="hidden" name="c" value="<?php echo esc_attr($comment->comment_ID) ?>" />
<input type="hidden" name="p" value="<?php echo esc_attr($comment->comment_post_ID) ?>" />
<input name="referredby" type="hidden" id="referredby" value="<?php echo esc_url( wp_get_referer() ); ?>" />
<?php wp_original_referer_field(true, 'previous'); ?>
<input type="hidden" name="noredir" value="1" />
</div><!-- /post-body -->
</div>
</div>
</form>
<script type="text/javascript">
try{document.post.name.focus();}catch(e){}
</script>
| 01-wordpress-paypal | trunk/wp-admin/edit-form-comment.php | PHP | gpl3 | 6,364 |
<?php
/**
* Administration Functions
*
* This file is deprecated, use 'wp-admin/includes/admin.php' instead.
*
* @deprecated 2.5.0
* @package WordPress
* @subpackage Administration
*/
_deprecated_file( basename(__FILE__), '2.5', 'wp-admin/includes/admin.php' );
/** WordPress Administration API: Includes all Administration functions. */
require_once(ABSPATH . 'wp-admin/includes/admin.php');
| 01-wordpress-paypal | trunk/wp-admin/admin-functions.php | PHP | gpl3 | 403 |
<?php
/**
* WordPress Administration Bootstrap
*
* @package WordPress
* @subpackage Administration
*/
/**
* In WordPress Administration Screens
*
* @since 2.3.2
*/
if ( ! defined('WP_ADMIN') )
define('WP_ADMIN', true);
if ( ! defined('WP_NETWORK_ADMIN') )
define('WP_NETWORK_ADMIN', false);
if ( ! defined('WP_USER_ADMIN') )
define('WP_USER_ADMIN', false);
if ( ! WP_NETWORK_ADMIN && ! WP_USER_ADMIN ) {
define('WP_BLOG_ADMIN', true);
}
if ( isset($_GET['import']) && !defined('WP_LOAD_IMPORTERS') )
define('WP_LOAD_IMPORTERS', true);
require_once(dirname(dirname(__FILE__)) . '/wp-load.php');
nocache_headers();
if ( get_option('db_upgraded') ) {
flush_rewrite_rules();
update_option( 'db_upgraded', false );
/**
* Fires on the next page load after a successful DB upgrade.
*
* @since 2.8.0
*/
do_action( 'after_db_upgrade' );
} elseif ( get_option('db_version') != $wp_db_version && empty($_POST) ) {
if ( !is_multisite() ) {
wp_redirect( admin_url( 'upgrade.php?_wp_http_referer=' . urlencode( wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) );
exit;
/**
* Filter whether to attempt to perform the multisite DB upgrade routine.
*
* In single site, the user would be redirected to wp-admin/upgrade.php.
* In multisite, it is automatically fired, but only when this filter
* returns true.
*
* If the network is 50 sites or less, it will run every time. Otherwise,
* it will throttle itself to reduce load.
*
* @since 3.0.0
*
* @param bool true Whether to perform the Multisite upgrade routine. Default true.
*/
} elseif ( apply_filters( 'do_mu_upgrade', true ) ) {
$c = get_blog_count();
// If 50 or fewer sites, run every time. Else, run "about ten percent" of the time. Shh, don't check that math.
if ( $c <= 50 || ( $c > 50 && mt_rand( 0, (int)( $c / 50 ) ) == 1 ) ) {
require_once( ABSPATH . WPINC . '/http.php' );
$response = wp_remote_get( admin_url( 'upgrade.php?step=1' ), array( 'timeout' => 120, 'httpversion' => '1.1' ) );
/** This action is documented in wp-admin/network/upgrade.php */
do_action( 'after_mu_upgrade', $response );
unset($response);
}
unset($c);
}
}
require_once(ABSPATH . 'wp-admin/includes/admin.php');
auth_redirect();
// Schedule trash collection
if ( !wp_next_scheduled('wp_scheduled_delete') && !defined('WP_INSTALLING') )
wp_schedule_event(time(), 'daily', 'wp_scheduled_delete');
set_screen_options();
$date_format = get_option('date_format');
$time_format = get_option('time_format');
wp_enqueue_script( 'common' );
$editing = false;
if ( isset($_GET['page']) ) {
$plugin_page = wp_unslash( $_GET['page'] );
$plugin_page = plugin_basename($plugin_page);
}
if ( isset( $_REQUEST['post_type'] ) && post_type_exists( $_REQUEST['post_type'] ) )
$typenow = $_REQUEST['post_type'];
else
$typenow = '';
if ( isset( $_REQUEST['taxonomy'] ) && taxonomy_exists( $_REQUEST['taxonomy'] ) )
$taxnow = $_REQUEST['taxonomy'];
else
$taxnow = '';
if ( WP_NETWORK_ADMIN )
require(ABSPATH . 'wp-admin/network/menu.php');
elseif ( WP_USER_ADMIN )
require(ABSPATH . 'wp-admin/user/menu.php');
else
require(ABSPATH . 'wp-admin/menu.php');
if ( current_user_can( 'manage_options' ) ) {
/**
* Filter the maximum memory limit available for administration screens.
*
* This only applies to administrators, who may require more memory for tasks like updates.
* Memory limits when processing images (uploaded or edited by users of any role) are
* handled separately.
*
* The WP_MAX_MEMORY_LIMIT constant specifically defines the maximum memory limit available
* when in the administration back-end. The default is 256M, or 256 megabytes of memory.
*
* @since 3.0.0
*
* @param string 'WP_MAX_MEMORY_LIMIT' The maximum WordPress memory limit. Default 256M.
*/
@ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
}
/**
* Fires as an admin screen or script is being initialized.
*
* Note, this does not just run on user-facing admin screens.
* It runs on admin-ajax.php and admin-post.php as well.
*
* This is roughly analgous to the more general 'init' hook, which fires earlier.
*
* @since 2.5.0
*/
do_action( 'admin_init' );
if ( isset($plugin_page) ) {
if ( !empty($typenow) )
$the_parent = $pagenow . '?post_type=' . $typenow;
else
$the_parent = $pagenow;
if ( ! $page_hook = get_plugin_page_hook($plugin_page, $the_parent) ) {
$page_hook = get_plugin_page_hook($plugin_page, $plugin_page);
// backwards compatibility for plugins using add_management_page
if ( empty( $page_hook ) && 'edit.php' == $pagenow && '' != get_plugin_page_hook($plugin_page, 'tools.php') ) {
// There could be plugin specific params on the URL, so we need the whole query string
if ( !empty($_SERVER[ 'QUERY_STRING' ]) )
$query_string = $_SERVER[ 'QUERY_STRING' ];
else
$query_string = 'page=' . $plugin_page;
wp_redirect( admin_url('tools.php?' . $query_string) );
exit;
}
}
unset($the_parent);
}
$hook_suffix = '';
if ( isset($page_hook) )
$hook_suffix = $page_hook;
else if ( isset($plugin_page) )
$hook_suffix = $plugin_page;
else if ( isset($pagenow) )
$hook_suffix = $pagenow;
set_current_screen();
// Handle plugin admin pages.
if ( isset($plugin_page) ) {
if ( $page_hook ) {
/**
* Fires before a particular screen is loaded.
*
* The load-* hook fires in a number of contexts. This hook is for plugin screens
* where a callback is provided when the screen is registered.
*
* The dynamic portion of the hook name, $page_hook, refers to a mixture of plugin
* page information including:
* 1. The page type. If the plugin page is registered as a submenu page, such as for
* Settings, the page type would be 'settings'. Otherwise the type is 'toplevel'.
* 2. A separator of '_page_'.
* 3. The plugin basename minus the file extension.
*
* Together, the three parts form the $page_hook. Citing the example above,
* the hook name used would be 'load-settings_page_pluginbasename'.
*
* @see get_plugin_page_hook()
*
* @since 2.1.0
*/
do_action( 'load-' . $page_hook );
if (! isset($_GET['noheader']))
require_once(ABSPATH . 'wp-admin/admin-header.php');
/**
* Used to call the registered callback for a plugin screen.
*
* @access private
*
* @since 1.5.0
*/
do_action( $page_hook );
} else {
if ( validate_file($plugin_page) )
wp_die(__('Invalid plugin page'));
if ( !( file_exists(WP_PLUGIN_DIR . "/$plugin_page") && is_file(WP_PLUGIN_DIR . "/$plugin_page") ) && !( file_exists(WPMU_PLUGIN_DIR . "/$plugin_page") && is_file(WPMU_PLUGIN_DIR . "/$plugin_page") ) )
wp_die(sprintf(__('Cannot load %s.'), htmlentities($plugin_page)));
/**
* Fires before a particular screen is loaded.
*
* The load-* hook fires in a number of contexts. This hook is for plugin screens
* where the file to load is directly included, rather than the use of a function.
*
* The dynamic portion of the hook name, $plugin_page, refers to the plugin basename.
*
* @see plugin_basename()
*
* @since 1.5.0
*/
do_action( 'load-' . $plugin_page );
if ( !isset($_GET['noheader']))
require_once(ABSPATH . 'wp-admin/admin-header.php');
if ( file_exists(WPMU_PLUGIN_DIR . "/$plugin_page") )
include(WPMU_PLUGIN_DIR . "/$plugin_page");
else
include(WP_PLUGIN_DIR . "/$plugin_page");
}
include(ABSPATH . 'wp-admin/admin-footer.php');
exit();
} else if (isset($_GET['import'])) {
$importer = $_GET['import'];
if ( ! current_user_can('import') )
wp_die(__('You are not allowed to import.'));
if ( validate_file($importer) ) {
wp_redirect( admin_url( 'import.php?invalid=' . $importer ) );
exit;
}
if ( ! isset($wp_importers[$importer]) || ! is_callable($wp_importers[$importer][2]) ) {
wp_redirect( admin_url( 'import.php?invalid=' . $importer ) );
exit;
}
/**
* Fires before an importer screen is loaded.
*
* The dynamic portion of the hook name, $importer, refers to the importer slug.
*
* @since 3.5.0
*/
do_action( 'load-importer-' . $importer );
$parent_file = 'tools.php';
$submenu_file = 'import.php';
$title = __('Import');
if (! isset($_GET['noheader']))
require_once(ABSPATH . 'wp-admin/admin-header.php');
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
define('WP_IMPORTING', true);
/**
* Whether to filter imported data through kses on import.
*
* Multisite uses this hook to filter all data through kses by default,
* as a super administrator may be assisting an untrusted user.
*
* @since 3.1.0
*
* @param bool false Whether to force data to be filtered through kses. Default false.
*/
if ( apply_filters( 'force_filtered_html_on_import', false ) )
kses_init_filters(); // Always filter imported data with kses on multisite.
call_user_func($wp_importers[$importer][2]);
include(ABSPATH . 'wp-admin/admin-footer.php');
// Make sure rules are flushed
flush_rewrite_rules(false);
exit();
} else {
/**
* Fires before a particular screen is loaded.
*
* The load-* hook fires in a number of contexts. This hook is for core screens.
*
* The dynamic portion of the hook name, $pagenow, is a global variable
* referring to the filename of the current page, such as 'admin.php',
* 'post-new.php' etc. A complete hook for the latter would be 'load-post-new.php'.
*
* @since 2.1.0
*/
do_action( 'load-' . $pagenow );
// Backwards compatibility with old load-page-new.php, load-page.php,
// and load-categories.php actions.
if ( $typenow == 'page' ) {
if ( $pagenow == 'post-new.php' )
do_action( 'load-page-new.php' );
elseif ( $pagenow == 'post.php' )
do_action( 'load-page.php' );
} elseif ( $pagenow == 'edit-tags.php' ) {
if ( $taxnow == 'category' )
do_action( 'load-categories.php' );
elseif ( $taxnow == 'link_category' )
do_action( 'load-edit-link-categories.php' );
}
}
if ( ! empty( $_REQUEST['action'] ) ) {
/**
* Fires when an 'action' request variable is sent.
*
* The dynamic portion of the hook name, $_REQUEST['action'],
* refers to the action derived from the GET or POST request.
*
* @since 2.6.0
*/
do_action( 'admin_action_' . $_REQUEST['action'] );
}
| 01-wordpress-paypal | trunk/wp-admin/admin.php | PHP | gpl3 | 10,277 |
<?php
/**
* Reading settings administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! current_user_can( 'manage_options' ) )
wp_die( __( 'You do not have sufficient permissions to manage options for this site.' ) );
$title = __( 'Reading Settings' );
$parent_file = 'options-general.php';
/**
* Display JavaScript on the page.
*
* @since 3.5.0
*/
function options_reading_add_js() {
?>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function($){
var section = $('#front-static-pages'),
staticPage = section.find('input:radio[value="page"]'),
selects = section.find('select'),
check_disabled = function(){
selects.prop( 'disabled', ! staticPage.prop('checked') );
};
check_disabled();
section.find('input:radio').change(check_disabled);
});
//]]>
</script>
<?php
}
add_action('admin_head', 'options_reading_add_js');
/**
* Render the blog charset setting.
*
* @since 3.5.0
*/
function options_reading_blog_charset() {
echo '<input name="blog_charset" type="text" id="blog_charset" value="' . esc_attr( get_option( 'blog_charset' ) ) . '" class="regular-text" />';
echo '<p class="description">' . __( 'The <a href="http://codex.wordpress.org/Glossary#Character_set">character encoding</a> of your site (UTF-8 is recommended)' ) . '</p>';
}
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' => '<p>' . __('This screen contains the settings that affect the display of your content.') . '</p>' .
'<p>' . sprintf(__('You can choose what’s displayed on the front page of your site. It can be posts in reverse chronological order (classic blog), or a fixed/static page. To set a static home page, you first need to create two <a href="%s">Pages</a>. One will become the front page, and the other will be where your posts are displayed.'), 'post-new.php?post_type=page') . '</p>' .
'<p>' . __('You can also control the display of your content in RSS feeds, including the maximum numbers of posts to display and whether to show full text or a summary.') . '</p>' .
'<p>' . __('You must click the Save Changes button at the bottom of the screen for new settings to take effect.') . '</p>',
) );
get_current_screen()->add_help_tab( array(
'id' => 'site-visibility',
'title' => has_action( 'blog_privacy_selector' ) ? __( 'Site Visibility' ) : __( 'Search Engine Visibility' ),
'content' => '<p>' . __( 'You can choose whether or not your site will be crawled by robots, ping services, and spiders. If you want those services to ignore your site, click the checkbox next to “Discourage search engines from indexing this site” and click the Save Changes button at the bottom of the screen. Note that your privacy is not complete; your site is still visible on the web.' ) . '</p>' .
'<p>' . __( 'When this setting is in effect, a reminder is shown in the At a Glance box of the Dashboard that says, “Search Engines Discouraged,” to remind you that your site is not being crawled.' ) . '</p>',
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Settings_Reading_Screen" target="_blank">Documentation on Reading Settings</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
include( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2><?php echo esc_html( $title ); ?></h2>
<form method="post" action="options.php">
<?php
settings_fields( 'reading' );
if ( ! in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) ) )
add_settings_field( 'blog_charset', __( 'Encoding for pages and feeds' ), 'options_reading_blog_charset', 'reading', 'default', array( 'label_for' => 'blog_charset' ) );
?>
<?php if ( ! get_pages() ) : ?>
<input name="show_on_front" type="hidden" value="posts" />
<table class="form-table">
<?php
if ( 'posts' != get_option( 'show_on_front' ) ) :
update_option( 'show_on_front', 'posts' );
endif;
else :
if ( 'page' == get_option( 'show_on_front' ) && ! get_option( 'page_on_front' ) && ! get_option( 'page_for_posts' ) )
update_option( 'show_on_front', 'posts' );
?>
<table class="form-table">
<tr>
<th scope="row"><?php _e( 'Front page displays' ); ?></th>
<td id="front-static-pages"><fieldset><legend class="screen-reader-text"><span><?php _e( 'Front page displays' ); ?></span></legend>
<p><label>
<input name="show_on_front" type="radio" value="posts" class="tog" <?php checked( 'posts', get_option( 'show_on_front' ) ); ?> />
<?php _e( 'Your latest posts' ); ?>
</label>
</p>
<p><label>
<input name="show_on_front" type="radio" value="page" class="tog" <?php checked( 'page', get_option( 'show_on_front' ) ); ?> />
<?php printf( __( 'A <a href="%s">static page</a> (select below)' ), 'edit.php?post_type=page' ); ?>
</label>
</p>
<ul>
<li><label for="page_on_front"><?php printf( __( 'Front page: %s' ), wp_dropdown_pages( array( 'name' => 'page_on_front', 'echo' => 0, 'show_option_none' => __( '— Select —' ), 'option_none_value' => '0', 'selected' => get_option( 'page_on_front' ) ) ) ); ?></label></li>
<li><label for="page_for_posts"><?php printf( __( 'Posts page: %s' ), wp_dropdown_pages( array( 'name' => 'page_for_posts', 'echo' => 0, 'show_option_none' => __( '— Select —' ), 'option_none_value' => '0', 'selected' => get_option( 'page_for_posts' ) ) ) ); ?></label></li>
</ul>
<?php if ( 'page' == get_option( 'show_on_front' ) && get_option( 'page_for_posts' ) == get_option( 'page_on_front' ) ) : ?>
<div id="front-page-warning" class="error inline"><p><?php _e( '<strong>Warning:</strong> these pages should not be the same!' ); ?></p></div>
<?php endif; ?>
</fieldset></td>
</tr>
<?php endif; ?>
<tr>
<th scope="row"><label for="posts_per_page"><?php _e( 'Blog pages show at most' ); ?></label></th>
<td>
<input name="posts_per_page" type="number" step="1" min="1" id="posts_per_page" value="<?php form_option( 'posts_per_page' ); ?>" class="small-text" /> <?php _e( 'posts' ); ?>
</td>
</tr>
<tr>
<th scope="row"><label for="posts_per_rss"><?php _e( 'Syndication feeds show the most recent' ); ?></label></th>
<td><input name="posts_per_rss" type="number" step="1" min="1" id="posts_per_rss" value="<?php form_option( 'posts_per_rss' ); ?>" class="small-text" /> <?php _e( 'items' ); ?></td>
</tr>
<tr>
<th scope="row"><?php _e( 'For each article in a feed, show' ); ?> </th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e( 'For each article in a feed, show' ); ?> </span></legend>
<p><label><input name="rss_use_excerpt" type="radio" value="0" <?php checked( 0, get_option( 'rss_use_excerpt' ) ); ?> /> <?php _e( 'Full text' ); ?></label><br />
<label><input name="rss_use_excerpt" type="radio" value="1" <?php checked( 1, get_option( 'rss_use_excerpt' ) ); ?> /> <?php _e( 'Summary' ); ?></label></p>
</fieldset></td>
</tr>
<tr class="option-site-visibility">
<th scope="row"><?php has_action( 'blog_privacy_selector' ) ? _e( 'Site Visibility' ) : _e( 'Search Engine Visibility' ); ?> </th>
<td><fieldset><legend class="screen-reader-text"><span><?php has_action( 'blog_privacy_selector' ) ? _e( 'Site Visibility' ) : _e( 'Search Engine Visibility' ); ?> </span></legend>
<?php if ( has_action( 'blog_privacy_selector' ) ) : ?>
<input id="blog-public" type="radio" name="blog_public" value="1" <?php checked('1', get_option('blog_public')); ?> />
<label for="blog-public"><?php _e( 'Allow search engines to index this site' );?></label><br/>
<input id="blog-norobots" type="radio" name="blog_public" value="0" <?php checked('0', get_option('blog_public')); ?> />
<label for="blog-norobots"><?php _e( 'Discourage search engines from indexing this site' ); ?></label>
<p class="description"><?php _e( 'Note: Neither of these options blocks access to your site — it is up to search engines to honor your request.' ); ?></p>
<?php
/**
* Enable the legacy 'Site Visibility' privacy options.
*
* By default the privacy options form displays a single checkbox to 'discourage' search
* engines from indexing the site. Hooking to this action serves a dual purpose:
* 1. Disable the single checkbox in favor of a multiple-choice list of radio buttons.
* 2. Open the door to adding additional radio button choices to the list.
*
* Hooking to this action also converts the 'Search Engine Visibility' heading to the more
* open-ended 'Site Visibility' heading.
*
* @since 2.1.0
*/
do_action( 'blog_privacy_selector' );
?>
<?php else : ?>
<label for="blog_public"><input name="blog_public" type="checkbox" id="blog_public" value="0" <?php checked( '0', get_option( 'blog_public' ) ); ?> />
<?php _e( 'Discourage search engines from indexing this site' ); ?></label>
<p class="description"><?php _e( 'It is up to search engines to honor this request.' ); ?></p>
<?php endif; ?>
</fieldset></td>
</tr>
<?php do_settings_fields( 'reading', 'default' ); ?>
</table>
<?php do_settings_sections( 'reading' ); ?>
<?php submit_button(); ?>
</form>
</div>
<?php include( ABSPATH . 'wp-admin/admin-footer.php' ); ?>
| 01-wordpress-paypal | trunk/wp-admin/options-reading.php | PHP | gpl3 | 9,352 |
<?php
/**
* Credits administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
$title = __( 'Credits' );
/**
* Retrieve the contributor credits.
*
* @global string $wp_version The current WordPress version.
*
* @since 3.2.0
*
* @return array|bool A list of all of the contributors, or false on error.
*/
function wp_credits() {
global $wp_version;
$locale = get_locale();
$results = get_site_transient( 'wordpress_credits_' . $locale );
if ( ! is_array( $results )
|| false !== strpos( $wp_version, '-' )
|| ( isset( $results['data']['version'] ) && strpos( $wp_version, $results['data']['version'] ) !== 0 )
) {
$response = wp_remote_get( "http://api.wordpress.org/core/credits/1.1/?version=$wp_version&locale=$locale" );
if ( is_wp_error( $response ) || 200 != wp_remote_retrieve_response_code( $response ) )
return false;
$results = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $results ) )
return false;
set_site_transient( 'wordpress_credits_' . $locale, $results, DAY_IN_SECONDS );
}
return $results;
}
/**
* Retrieve the link to a contributor's WordPress.org profile page.
*
* @access private
* @since 3.2.0
*
* @param string &$display_name The contributor's display name, passed by reference.
* @param string $username The contributor's username.
* @param string $profiles URL to the contributor's WordPress.org profile page.
* @return string A contributor's display name, hyperlinked to a WordPress.org profile page.
*/
function _wp_credits_add_profile_link( &$display_name, $username, $profiles ) {
$display_name = '<a href="' . esc_url( sprintf( $profiles, $username ) ) . '">' . esc_html( $display_name ) . '</a>';
}
/**
* Retrieve the link to an external library used in WordPress.
*
* @access private
* @since 3.2.0
*
* @param string &$data External library data, passed by reference.
* @return string Link to the external library.
*/
function _wp_credits_build_object_link( &$data ) {
$data = '<a href="' . esc_url( $data[1] ) . '">' . $data[0] . '</a>';
}
list( $display_version ) = explode( '-', $wp_version );
include( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap about-wrap">
<h1><?php printf( __( 'Welcome to WordPress %s' ), $display_version ); ?></h1>
<div class="about-text"><?php printf( __( 'Thank you for updating to WordPress %s, the most beautiful WordPress yet.' ), $display_version ); ?></div>
<div class="wp-badge"><?php printf( __( 'Version %s' ), $display_version ); ?></div>
<h2 class="nav-tab-wrapper">
<a href="about.php" class="nav-tab">
<?php _e( 'What’s New' ); ?>
</a><a href="credits.php" class="nav-tab nav-tab-active">
<?php _e( 'Credits' ); ?>
</a><a href="freedoms.php" class="nav-tab">
<?php _e( 'Freedoms' ); ?>
</a>
</h2>
<?php
$credits = wp_credits();
if ( ! $credits ) {
echo '<p class="about-description">' . sprintf( __( 'WordPress is created by a <a href="%1$s">worldwide team</a> of passionate individuals. <a href="%2$s">Get involved in WordPress</a>.' ),
'https://wordpress.org/about/',
/* translators: Url to the codex documentation on contributing to WordPress used on the credits page */
__( 'http://codex.wordpress.org/Contributing_to_WordPress' ) ) . '</p>';
include( ABSPATH . 'wp-admin/admin-footer.php' );
exit;
}
echo '<p class="about-description">' . __( 'WordPress is created by a worldwide team of passionate individuals.' ) . "</p>\n";
$gravatar = is_ssl() ? 'https://secure.gravatar.com/avatar/' : 'http://0.gravatar.com/avatar/';
foreach ( $credits['groups'] as $group_slug => $group_data ) {
if ( $group_data['name'] ) {
if ( 'Translators' == $group_data['name'] ) {
// Considered a special slug in the API response. (Also, will never be returned for en_US.)
$title = _x( 'Translators', 'Translate this to be the equivalent of English Translators in your language for the credits page Translators section' );
} elseif ( isset( $group_data['placeholders'] ) ) {
$title = vsprintf( translate( $group_data['name'] ), $group_data['placeholders'] );
} else {
$title = translate( $group_data['name'] );
}
echo '<h4 class="wp-people-group">' . $title . "</h4>\n";
}
if ( ! empty( $group_data['shuffle'] ) )
shuffle( $group_data['data'] ); // We were going to sort by ability to pronounce "hierarchical," but that wouldn't be fair to Matt.
switch ( $group_data['type'] ) {
case 'list' :
array_walk( $group_data['data'], '_wp_credits_add_profile_link', $credits['data']['profiles'] );
echo '<p class="wp-credits-list">' . wp_sprintf( '%l.', $group_data['data'] ) . "</p>\n\n";
break;
case 'libraries' :
array_walk( $group_data['data'], '_wp_credits_build_object_link' );
echo '<p class="wp-credits-list">' . wp_sprintf( '%l.', $group_data['data'] ) . "</p>\n\n";
break;
default:
$compact = 'compact' == $group_data['type'];
$classes = 'wp-people-group ' . ( $compact ? 'compact' : '' );
echo '<ul class="' . $classes . '" id="wp-people-group-' . $group_slug . '">' . "\n";
foreach ( $group_data['data'] as $person_data ) {
echo '<li class="wp-person" id="wp-person-' . $person_data[2] . '">' . "\n\t";
echo '<a href="' . sprintf( $credits['data']['profiles'], $person_data[2] ) . '">';
$size = 'compact' == $group_data['type'] ? '30' : '60';
echo '<img src="' . $gravatar . $person_data[1] . '?s=' . $size . '" class="gravatar" alt="' . esc_attr( $person_data[0] ) . '" /></a>' . "\n\t";
echo '<a class="web" href="' . sprintf( $credits['data']['profiles'], $person_data[2] ) . '">' . $person_data[0] . "</a>\n\t";
if ( ! $compact )
echo '<span class="title">' . translate( $person_data[3] ) . "</span>\n";
echo "</li>\n";
}
echo "</ul>\n";
break;
}
}
?>
<p class="clear"><?php printf( __( 'Want to see your name in lights on this page? <a href="%s">Get involved in WordPress</a>.' ),
/* translators: URL to the Make WordPress 'Get Involved' landing page used on the credits page */
__( 'https://make.wordpress.org/' ) ); ?></p>
</div>
<?php
include( ABSPATH . 'wp-admin/admin-footer.php' );
return;
// These are strings returned by the API that we want to be translatable
__( 'Project Leaders' );
__( 'Extended Core Team' );
__( 'Core Developers' );
__( 'Recent Rockstars' );
__( 'Core Contributors to WordPress %s' );
__( 'Contributing Developers' );
__( 'Cofounder, Project Lead' );
__( 'Lead Developer' );
__( 'User Experience Lead' );
__( 'Core Developer' );
__( 'Core Committer' );
__( 'Guest Committer' );
__( 'Developer' );
__( 'Designer' );
__( 'XML-RPC' );
__( 'Internationalization' );
__( 'External Libraries' );
__( 'Icon Design' );
| 01-wordpress-paypal | trunk/wp-admin/credits.php | PHP | gpl3 | 6,807 |
<?php
/**
* Media settings administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! current_user_can( 'manage_options' ) )
wp_die( __( 'You do not have sufficient permissions to manage options for this site.' ) );
$title = __('Media Settings');
$parent_file = 'options-general.php';
$media_options_help = '<p>' . __('You can set maximum sizes for images inserted into your written content; you can also insert an image as Full Size.') . '</p>';
if ( ! is_multisite() && ( get_option('upload_url_path') || ( get_option('upload_path') != 'wp-content/uploads' && get_option('upload_path') ) ) ) {
$media_options_help .= '<p>' . __('Uploading Files allows you to choose the folder and path for storing your uploaded files.') . '</p>';
}
$media_options_help .= '<p>' . __('You must click the Save Changes button at the bottom of the screen for new settings to take effect.') . '</p>';
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' => $media_options_help,
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Settings_Media_Screen" target="_blank">Documentation on Media Settings</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
include( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2><?php echo esc_html( $title ); ?></h2>
<form action="options.php" method="post">
<?php settings_fields('media'); ?>
<h3 class="title"><?php _e('Image sizes') ?></h3>
<p><?php _e( 'The sizes listed below determine the maximum dimensions in pixels to use when adding an image to the Media Library.' ); ?></p>
<table class="form-table">
<tr>
<th scope="row"><?php _e('Thumbnail size') ?></th>
<td>
<label for="thumbnail_size_w"><?php _e('Width'); ?></label>
<input name="thumbnail_size_w" type="number" step="1" min="0" id="thumbnail_size_w" value="<?php form_option('thumbnail_size_w'); ?>" class="small-text" />
<label for="thumbnail_size_h"><?php _e('Height'); ?></label>
<input name="thumbnail_size_h" type="number" step="1" min="0" id="thumbnail_size_h" value="<?php form_option('thumbnail_size_h'); ?>" class="small-text" /><br />
<input name="thumbnail_crop" type="checkbox" id="thumbnail_crop" value="1" <?php checked('1', get_option('thumbnail_crop')); ?>/>
<label for="thumbnail_crop"><?php _e('Crop thumbnail to exact dimensions (normally thumbnails are proportional)'); ?></label>
</td>
</tr>
<tr>
<th scope="row"><?php _e('Medium size') ?></th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e('Medium size'); ?></span></legend>
<label for="medium_size_w"><?php _e('Max Width'); ?></label>
<input name="medium_size_w" type="number" step="1" min="0" id="medium_size_w" value="<?php form_option('medium_size_w'); ?>" class="small-text" />
<label for="medium_size_h"><?php _e('Max Height'); ?></label>
<input name="medium_size_h" type="number" step="1" min="0" id="medium_size_h" value="<?php form_option('medium_size_h'); ?>" class="small-text" />
</fieldset></td>
</tr>
<tr>
<th scope="row"><?php _e('Large size') ?></th>
<td><fieldset><legend class="screen-reader-text"><span><?php _e('Large size'); ?></span></legend>
<label for="large_size_w"><?php _e('Max Width'); ?></label>
<input name="large_size_w" type="number" step="1" min="0" id="large_size_w" value="<?php form_option('large_size_w'); ?>" class="small-text" />
<label for="large_size_h"><?php _e('Max Height'); ?></label>
<input name="large_size_h" type="number" step="1" min="0" id="large_size_h" value="<?php form_option('large_size_h'); ?>" class="small-text" />
</fieldset></td>
</tr>
<?php do_settings_fields('media', 'default'); ?>
</table>
<?php if ( isset( $GLOBALS['wp_settings']['media']['embeds'] ) ) : ?>
<h3 class="title"><?php _e('Embeds') ?></h3>
<table class="form-table">
<?php do_settings_fields( 'media', 'embeds' ); ?>
</table>
<?php endif; ?>
<?php if ( !is_multisite() ) : ?>
<h3 class="title"><?php _e('Uploading Files'); ?></h3>
<table class="form-table">
<?php
// If upload_url_path is not the default (empty), and upload_path is not the default ('wp-content/uploads' or empty)
if ( get_option('upload_url_path') || ( get_option('upload_path') != 'wp-content/uploads' && get_option('upload_path') ) ) :
?>
<tr>
<th scope="row"><label for="upload_path"><?php _e('Store uploads in this folder'); ?></label></th>
<td><input name="upload_path" type="text" id="upload_path" value="<?php echo esc_attr(get_option('upload_path')); ?>" class="regular-text code" />
<p class="description"><?php _e('Default is <code>wp-content/uploads</code>'); ?></p>
</td>
</tr>
<tr>
<th scope="row"><label for="upload_url_path"><?php _e('Full URL path to files'); ?></label></th>
<td><input name="upload_url_path" type="text" id="upload_url_path" value="<?php echo esc_attr( get_option('upload_url_path')); ?>" class="regular-text code" />
<p class="description"><?php _e('Configuring this is optional. By default, it should be blank.'); ?></p>
</td>
</tr>
<?php endif; ?>
<tr>
<th scope="row" colspan="2" class="th-full">
<label for="uploads_use_yearmonth_folders">
<input name="uploads_use_yearmonth_folders" type="checkbox" id="uploads_use_yearmonth_folders" value="1"<?php checked('1', get_option('uploads_use_yearmonth_folders')); ?> />
<?php _e('Organize my uploads into month- and year-based folders'); ?>
</label>
</th>
</tr>
<?php do_settings_fields('media', 'uploads'); ?>
</table>
<?php endif; ?>
<?php do_settings_sections('media'); ?>
<?php submit_button(); ?>
</form>
</div>
<?php include( ABSPATH . 'wp-admin/admin-footer.php' ); ?>
| 01-wordpress-paypal | trunk/wp-admin/options-media.php | PHP | gpl3 | 5,831 |
<?php
/**
* Options Management Administration Screen.
*
* If accessed directly in a browser this page shows a list of all saved options
* along with editable fields for their values. Serialized data is not supported
* and there is no way to remove options via this page. It is not linked to from
* anywhere else in the admin.
*
* This file is also the target of the forms in core and custom options pages
* that use the Settings API. In this case it saves the new option values
* and returns the user to their page of origin.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
$title = __('Settings');
$this_file = 'options.php';
$parent_file = 'options-general.php';
wp_reset_vars(array('action', 'option_page'));
$capability = 'manage_options';
if ( empty($option_page) ) // This is for back compat and will eventually be removed.
$option_page = 'options';
else
/**
* Filter the capability required when using the Settings API.
*
* By default, the options groups for all registered settings require the manage_options capability.
* This filter is required to change the capability required for a certain options page.
*
* @since 3.2.0
*
* @param string $capability The capability used for the page, which is manage_options by default.
*/
$capability = apply_filters( "option_page_capability_{$option_page}", $capability );
if ( !current_user_can( $capability ) )
wp_die(__('Cheatin’ uh?'));
// Handle admin email change requests
if ( is_multisite() ) {
if ( ! empty($_GET[ 'adminhash' ] ) ) {
$new_admin_details = get_option( 'adminhash' );
$redirect = 'options-general.php?updated=false';
if ( is_array( $new_admin_details ) && $new_admin_details[ 'hash' ] == $_GET[ 'adminhash' ] && !empty($new_admin_details[ 'newemail' ]) ) {
update_option( 'admin_email', $new_admin_details[ 'newemail' ] );
delete_option( 'adminhash' );
delete_option( 'new_admin_email' );
$redirect = 'options-general.php?updated=true';
}
wp_redirect( admin_url( $redirect ) );
exit;
} elseif ( ! empty( $_GET['dismiss'] ) && 'new_admin_email' == $_GET['dismiss'] ) {
delete_option( 'adminhash' );
delete_option( 'new_admin_email' );
wp_redirect( admin_url( 'options-general.php?updated=true' ) );
exit;
}
}
if ( is_multisite() && !is_super_admin() && 'update' != $action )
wp_die(__('Cheatin’ uh?'));
$whitelist_options = array(
'general' => array( 'blogname', 'blogdescription', 'gmt_offset', 'date_format', 'time_format', 'start_of_week', 'timezone_string' ),
'discussion' => array( 'default_pingback_flag', 'default_ping_status', 'default_comment_status', 'comments_notify', 'moderation_notify', 'comment_moderation', 'require_name_email', 'comment_whitelist', 'comment_max_links', 'moderation_keys', 'blacklist_keys', 'show_avatars', 'avatar_rating', 'avatar_default', 'close_comments_for_old_posts', 'close_comments_days_old', 'thread_comments', 'thread_comments_depth', 'page_comments', 'comments_per_page', 'default_comments_page', 'comment_order', 'comment_registration' ),
'media' => array( 'thumbnail_size_w', 'thumbnail_size_h', 'thumbnail_crop', 'medium_size_w', 'medium_size_h', 'large_size_w', 'large_size_h', 'image_default_size', 'image_default_align', 'image_default_link_type' ),
'reading' => array( 'posts_per_page', 'posts_per_rss', 'rss_use_excerpt', 'show_on_front', 'page_on_front', 'page_for_posts', 'blog_public' ),
'writing' => array( 'use_smilies', 'default_category', 'default_email_category', 'use_balanceTags', 'default_link_category', 'default_post_format' )
);
$whitelist_options['misc'] = $whitelist_options['options'] = $whitelist_options['privacy'] = array();
$mail_options = array('mailserver_url', 'mailserver_port', 'mailserver_login', 'mailserver_pass');
if ( ! in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) ) )
$whitelist_options['reading'][] = 'blog_charset';
if ( !is_multisite() ) {
if ( !defined( 'WP_SITEURL' ) )
$whitelist_options['general'][] = 'siteurl';
if ( !defined( 'WP_HOME' ) )
$whitelist_options['general'][] = 'home';
$whitelist_options['general'][] = 'admin_email';
$whitelist_options['general'][] = 'users_can_register';
$whitelist_options['general'][] = 'default_role';
$whitelist_options['writing'] = array_merge($whitelist_options['writing'], $mail_options);
$whitelist_options['writing'][] = 'ping_sites';
$whitelist_options['media'][] = 'uploads_use_yearmonth_folders';
// If upload_url_path and upload_path are both default values, they're locked.
if ( get_option( 'upload_url_path' ) || ( get_option('upload_path') != 'wp-content/uploads' && get_option('upload_path') ) ) {
$whitelist_options['media'][] = 'upload_path';
$whitelist_options['media'][] = 'upload_url_path';
}
} else {
$whitelist_options['general'][] = 'new_admin_email';
$whitelist_options['general'][] = 'WPLANG';
/**
* Filter whether the post-by-email functionality is enabled.
*
* @since 3.0.0
*
* @param bool $enabled Whether post-by-email configuration is enabled. Default true.
*/
if ( apply_filters( 'enable_post_by_email_configuration', true ) )
$whitelist_options['writing'] = array_merge($whitelist_options['writing'], $mail_options);
}
/**
* Filter the options white list.
*
* @since 2.7.0
*
* @param array White list options.
*/
$whitelist_options = apply_filters( 'whitelist_options', $whitelist_options );
/*
* If $_GET['action'] == 'update' we are saving settings sent from a settings page
*/
if ( 'update' == $action ) {
if ( 'options' == $option_page && !isset( $_POST['option_page'] ) ) { // This is for back compat and will eventually be removed.
$unregistered = true;
check_admin_referer( 'update-options' );
} else {
$unregistered = false;
check_admin_referer( $option_page . '-options' );
}
if ( !isset( $whitelist_options[ $option_page ] ) )
wp_die( __( '<strong>ERROR</strong>: options page not found.' ) );
if ( 'options' == $option_page ) {
if ( is_multisite() && ! is_super_admin() )
wp_die( __( 'You do not have sufficient permissions to modify unregistered settings for this site.' ) );
$options = explode( ',', wp_unslash( $_POST[ 'page_options' ] ) );
} else {
$options = $whitelist_options[ $option_page ];
}
// Handle custom date/time formats
if ( 'general' == $option_page ) {
if ( !empty($_POST['date_format']) && isset($_POST['date_format_custom']) && '\c\u\s\t\o\m' == wp_unslash( $_POST['date_format'] ) )
$_POST['date_format'] = $_POST['date_format_custom'];
if ( !empty($_POST['time_format']) && isset($_POST['time_format_custom']) && '\c\u\s\t\o\m' == wp_unslash( $_POST['time_format'] ) )
$_POST['time_format'] = $_POST['time_format_custom'];
// Map UTC+- timezones to gmt_offsets and set timezone_string to empty.
if ( !empty($_POST['timezone_string']) && preg_match('/^UTC[+-]/', $_POST['timezone_string']) ) {
$_POST['gmt_offset'] = $_POST['timezone_string'];
$_POST['gmt_offset'] = preg_replace('/UTC\+?/', '', $_POST['gmt_offset']);
$_POST['timezone_string'] = '';
}
}
if ( $options ) {
foreach ( $options as $option ) {
if ( $unregistered )
_deprecated_argument( 'options.php', '2.7', sprintf( __( 'The <code>%1$s</code> setting is unregistered. Unregistered settings are deprecated. See http://codex.wordpress.org/Settings_API' ), $option, $option_page ) );
$option = trim( $option );
$value = null;
if ( isset( $_POST[ $option ] ) ) {
$value = $_POST[ $option ];
if ( ! is_array( $value ) )
$value = trim( $value );
$value = wp_unslash( $value );
}
update_option( $option, $value );
}
}
/**
* Handle settings errors and return to options page
*/
// If no settings errors were registered add a general 'updated' message.
if ( !count( get_settings_errors() ) )
add_settings_error('general', 'settings_updated', __('Settings saved.'), 'updated');
set_transient('settings_errors', get_settings_errors(), 30);
/**
* Redirect back to the settings page that was submitted
*/
$goback = add_query_arg( 'settings-updated', 'true', wp_get_referer() );
wp_redirect( $goback );
exit;
}
include( ABSPATH . 'wp-admin/admin-header.php' ); ?>
<div class="wrap">
<h2><?php esc_html_e('All Settings'); ?></h2>
<form name="form" action="options.php" method="post" id="all-options">
<?php wp_nonce_field('options-options') ?>
<input type="hidden" name="action" value="update" />
<input type='hidden' name='option_page' value='options' />
<table class="form-table">
<?php
$options = $wpdb->get_results( "SELECT * FROM $wpdb->options ORDER BY option_name" );
foreach ( (array) $options as $option ) :
$disabled = false;
if ( $option->option_name == '' )
continue;
if ( is_serialized( $option->option_value ) ) {
if ( is_serialized_string( $option->option_value ) ) {
// this is a serialized string, so we should display it
$value = maybe_unserialize( $option->option_value );
$options_to_update[] = $option->option_name;
$class = 'all-options';
} else {
$value = 'SERIALIZED DATA';
$disabled = true;
$class = 'all-options disabled';
}
} else {
$value = $option->option_value;
$options_to_update[] = $option->option_name;
$class = 'all-options';
}
$name = esc_attr( $option->option_name );
echo "
<tr>
<th scope='row'><label for='$name'>" . esc_html( $option->option_name ) . "</label></th>
<td>";
if ( strpos( $value, "\n" ) !== false )
echo "<textarea class='$class' name='$name' id='$name' cols='30' rows='5'>" . esc_textarea( $value ) . "</textarea>";
else
echo "<input class='regular-text $class' type='text' name='$name' id='$name' value='" . esc_attr( $value ) . "'" . disabled( $disabled, true, false ) . " />";
echo "</td>
</tr>";
endforeach;
?>
</table>
<input type="hidden" name="page_options" value="<?php echo esc_attr( implode( ',', $options_to_update ) ); ?>" />
<?php submit_button( __( 'Save Changes' ), 'primary', 'Update' ); ?>
</form>
</div>
<?php
include( ABSPATH . 'wp-admin/admin-footer.php' );
| 01-wordpress-paypal | trunk/wp-admin/options.php | PHP | gpl3 | 10,137 |
<?php
/**
* Edit links form for inclusion in administration panels.
*
* @package WordPress
* @subpackage Administration
*/
// don't load directly
if ( !defined('ABSPATH') )
die('-1');
if ( ! empty($link_id) ) {
$heading = sprintf( __( '<a href="%s">Links</a> / Edit Link' ), 'link-manager.php' );
$submit_text = __('Update Link');
$form = '<form name="editlink" id="editlink" method="post" action="link.php">';
$nonce_action = 'update-bookmark_' . $link_id;
} else {
$heading = sprintf( __( '<a href="%s">Links</a> / Add New Link' ), 'link-manager.php' );
$submit_text = __('Add Link');
$form = '<form name="addlink" id="addlink" method="post" action="link.php">';
$nonce_action = 'add-bookmark';
}
require_once( ABSPATH . 'wp-admin/includes/meta-boxes.php' );
add_meta_box('linksubmitdiv', __('Save'), 'link_submit_meta_box', null, 'side', 'core');
add_meta_box('linkcategorydiv', __('Categories'), 'link_categories_meta_box', null, 'normal', 'core');
add_meta_box('linktargetdiv', __('Target'), 'link_target_meta_box', null, 'normal', 'core');
add_meta_box('linkxfndiv', __('Link Relationship (XFN)'), 'link_xfn_meta_box', null, 'normal', 'core');
add_meta_box('linkadvanceddiv', __('Advanced'), 'link_advanced_meta_box', null, 'normal', 'core');
/** This action is documented in wp-admin/edit-form-advanced.php */
do_action( 'add_meta_boxes', 'link', $link );
/**
* Fires when link-specific meta boxes are added.
*
* @since 3.0.0
*
* @param object $link Link object.
*/
do_action( 'add_meta_boxes_link', $link );
/** This action is documented in wp-admin/edit-form-advanced.php */
do_action( 'do_meta_boxes', 'link', 'normal', $link );
/** This action is documented in wp-admin/edit-form-advanced.php */
do_action( 'do_meta_boxes', 'link', 'advanced', $link );
/** This action is documented in wp-admin/edit-form-advanced.php */
do_action( 'do_meta_boxes', 'link', 'side', $link );
add_screen_option('layout_columns', array('max' => 2, 'default' => 2) );
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __( 'You can add or edit links on this screen by entering information in each of the boxes. Only the link’s web address and name (the text you want to display on your site as the link) are required fields.' ) . '</p>' .
'<p>' . __( 'The boxes for link name, web address, and description have fixed positions, while the others may be repositioned using drag and drop. You can also hide boxes you don’t use in the Screen Options tab, or minimize boxes by clicking on the title bar of the box.' ) . '</p>' .
'<p>' . __( 'XFN stands for <a href="http://gmpg.org/xfn/" target="_blank">XHTML Friends Network</a>, which is optional. WordPress allows the generation of XFN attributes to show how you are related to the authors/owners of the site to which you are linking.' ) . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __( 'For more information:' ) . '</strong></p>' .
'<p>' . __( '<a href="http://codex.wordpress.org/Links_Add_New_Screen" target="_blank">Documentation on Creating Links</a>' ) . '</p>' .
'<p>' . __( '<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>' ) . '</p>'
);
require_once( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2><?php echo esc_html( $title ); ?> <a href="link-add.php" class="add-new-h2"><?php echo esc_html_x('Add New', 'link'); ?></a></h2>
<?php if ( isset( $_GET['added'] ) ) : ?>
<div id="message" class="updated"><p><?php _e('Link added.'); ?></p></div>
<?php endif; ?>
<?php
if ( !empty($form) )
echo $form;
if ( !empty($link_added) )
echo $link_added;
wp_nonce_field( $nonce_action );
wp_nonce_field( 'closedpostboxes', 'closedpostboxesnonce', false );
wp_nonce_field( 'meta-box-order', 'meta-box-order-nonce', false ); ?>
<div id="poststuff">
<div id="post-body" class="metabox-holder columns-<?php echo 1 == get_current_screen()->get_columns() ? '1' : '2'; ?>">
<div id="post-body-content">
<div id="namediv" class="stuffbox">
<h3><label for="link_name"><?php _ex('Name', 'link name') ?></label></h3>
<div class="inside">
<input type="text" name="link_name" size="30" maxlength="255" value="<?php echo esc_attr($link->link_name); ?>" id="link_name" />
<p><?php _e('Example: Nifty blogging software'); ?></p>
</div>
</div>
<div id="addressdiv" class="stuffbox">
<h3><label for="link_url"><?php _e('Web Address') ?></label></h3>
<div class="inside">
<input type="text" name="link_url" size="30" maxlength="255" class="code" value="<?php echo esc_attr($link->link_url); ?>" id="link_url" />
<p><?php _e('Example: <code>http://wordpress.org/</code> — don’t forget the <code>http://</code>'); ?></p>
</div>
</div>
<div id="descriptiondiv" class="stuffbox">
<h3><label for="link_description"><?php _e('Description') ?></label></h3>
<div class="inside">
<input type="text" name="link_description" size="30" maxlength="255" value="<?php echo isset($link->link_description) ? esc_attr($link->link_description) : ''; ?>" id="link_description" />
<p><?php _e('This will be shown when someone hovers over the link in the blogroll, or optionally below the link.'); ?></p>
</div>
</div>
</div><!-- /post-body-content -->
<div id="postbox-container-1" class="postbox-container">
<?php
/**
* Fires before the Save meta box in the sidebar.
*
* @since 2.5.0
*/
do_action( 'submitlink_box' );
$side_meta_boxes = do_meta_boxes( 'link', 'side', $link );
?>
</div>
<div id="postbox-container-2" class="postbox-container">
<?php
do_meta_boxes(null, 'normal', $link);
do_meta_boxes(null, 'advanced', $link);
?>
</div>
<?php
if ( $link_id ) : ?>
<input type="hidden" name="action" value="save" />
<input type="hidden" name="link_id" value="<?php echo (int) $link_id; ?>" />
<input type="hidden" name="cat_id" value="<?php echo (int) $cat_id ?>" />
<?php else: ?>
<input type="hidden" name="action" value="add" />
<?php endif; ?>
</div>
</div>
</form>
</div>
| 01-wordpress-paypal | trunk/wp-admin/edit-link-form.php | PHP | gpl3 | 6,009 |
<?php
/**
* Link Management Administration Screen.
*
* @package WordPress
* @subpackage Administration
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! current_user_can( 'manage_links' ) )
wp_die( __( 'You do not have sufficient permissions to edit the links for this site.' ) );
$wp_list_table = _get_list_table('WP_Links_List_Table');
// Handle bulk deletes
$doaction = $wp_list_table->current_action();
if ( $doaction && isset( $_REQUEST['linkcheck'] ) ) {
check_admin_referer( 'bulk-bookmarks' );
if ( 'delete' == $doaction ) {
$bulklinks = (array) $_REQUEST['linkcheck'];
foreach ( $bulklinks as $link_id ) {
$link_id = (int) $link_id;
wp_delete_link( $link_id );
}
wp_redirect( add_query_arg('deleted', count( $bulklinks ), admin_url( 'link-manager.php' ) ) );
exit;
}
} elseif ( ! empty( $_GET['_wp_http_referer'] ) ) {
wp_redirect( remove_query_arg( array( '_wp_http_referer', '_wpnonce' ), wp_unslash( $_SERVER['REQUEST_URI'] ) ) );
exit;
}
$wp_list_table->prepare_items();
$title = __('Links');
$this_file = $parent_file = 'link-manager.php';
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . sprintf(__('You can add links here to be displayed on your site, usually using <a href="%s">Widgets</a>. By default, links to several sites in the WordPress community are included as examples.'), 'widgets.php') . '</p>' .
'<p>' . __('Links may be separated into Link Categories; these are different than the categories used on your posts.') . '</p>' .
'<p>' . __('You can customize the display of this screen using the Screen Options tab and/or the dropdown filters above the links table.') . '</p>'
) );
get_current_screen()->add_help_tab( array(
'id' => 'deleting-links',
'title' => __('Deleting Links'),
'content' =>
'<p>' . __('If you delete a link, it will be removed permanently, as Links do not have a Trash function yet.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Links_Screen" target="_blank">Documentation on Managing Links</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
include_once( ABSPATH . 'wp-admin/admin-header.php' );
if ( ! current_user_can('manage_links') )
wp_die(__("You do not have sufficient permissions to edit the links for this site."));
?>
<div class="wrap nosubsub">
<h2><?php echo esc_html( $title ); ?> <a href="link-add.php" class="add-new-h2"><?php echo esc_html_x('Add New', 'link'); ?></a> <?php
if ( !empty($_REQUEST['s']) )
printf( '<span class="subtitle">' . __('Search results for “%s”') . '</span>', esc_html( wp_unslash($_REQUEST['s']) ) ); ?>
</h2>
<?php
if ( isset($_REQUEST['deleted']) ) {
echo '<div id="message" class="updated"><p>';
$deleted = (int) $_REQUEST['deleted'];
printf(_n('%s link deleted.', '%s links deleted', $deleted), $deleted);
echo '</p></div>';
$_SERVER['REQUEST_URI'] = remove_query_arg(array('deleted'), $_SERVER['REQUEST_URI']);
}
?>
<form id="posts-filter" action="" method="get">
<?php $wp_list_table->search_box( __( 'Search Links' ), 'link' ); ?>
<?php $wp_list_table->display(); ?>
<div id="ajax-response"></div>
</form>
</div>
<?php
include( ABSPATH . 'wp-admin/admin-footer.php' );
| 01-wordpress-paypal | trunk/wp-admin/link-manager.php | PHP | gpl3 | 3,468 |
<?php
/**
* Theme editor administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( is_multisite() && ! is_network_admin() ) {
wp_redirect( network_admin_url( 'theme-editor.php' ) );
exit();
}
if ( !current_user_can('edit_themes') )
wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this site.').'</p>');
$title = __("Edit Themes");
$parent_file = 'themes.php';
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('You can use the Theme Editor to edit the individual CSS and PHP files which make up your theme.') . '</p>
<p>' . __('Begin by choosing a theme to edit from the dropdown menu and clicking Select. A list then appears of all the template files. Clicking once on any file name causes the file to appear in the large Editor box.') . '</p>
<p>' . __('For PHP files, you can use the Documentation dropdown to select from functions recognized in that file. Look Up takes you to a web page with reference material about that particular function.') . '</p>
<p id="newcontent-description">' . __('In the editing area the Tab key enters a tab character. To move below this area by pressing Tab, press the Esc key followed by the Tab key.') . '</p>
<p>' . __('After typing in your edits, click Update File.') . '</p>
<p>' . __('<strong>Advice:</strong> think very carefully about your site crashing if you are live-editing the theme currently in use.') . '</p>
<p>' . sprintf( __('Upgrading to a newer version of the same theme will override changes made here. To avoid this, consider creating a <a href="%s" target="_blank">child theme</a> instead.'), __('http://codex.wordpress.org/Child_Themes') ) . '</p>' .
( is_network_admin() ? '<p>' . __('Any edits to files from this screen will be reflected on all sites in the network.') . '</p>' : '' )
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Theme_Development" target="_blank">Documentation on Theme Development</a>') . '</p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Using_Themes" target="_blank">Documentation on Using Themes</a>') . '</p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Editing_Files" target="_blank">Documentation on Editing Files</a>') . '</p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Template_Tags" target="_blank">Documentation on Template Tags</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
wp_reset_vars( array( 'action', 'error', 'file', 'theme' ) );
if ( $theme )
$stylesheet = $theme;
else
$stylesheet = get_stylesheet();
$theme = wp_get_theme( $stylesheet );
if ( ! $theme->exists() )
wp_die( __( 'The requested theme does not exist.' ) );
if ( $theme->errors() && 'theme_no_stylesheet' == $theme->errors()->get_error_code() )
wp_die( __( 'The requested theme does not exist.' ) . ' ' . $theme->errors()->get_error_message() );
$allowed_files = $theme->get_files( 'php', 1 );
$has_templates = ! empty( $allowed_files );
$style_files = $theme->get_files( 'css' );
$allowed_files['style.css'] = $style_files['style.css'];
$allowed_files += $style_files;
if ( empty( $file ) ) {
$relative_file = 'style.css';
$file = $allowed_files['style.css'];
} else {
$relative_file = $file;
$file = $theme->get_stylesheet_directory() . '/' . $relative_file;
}
validate_file_to_edit( $file, $allowed_files );
$scrollto = isset( $_REQUEST['scrollto'] ) ? (int) $_REQUEST['scrollto'] : 0;
switch( $action ) {
case 'update':
check_admin_referer( 'edit-theme_' . $file . $stylesheet );
$newcontent = wp_unslash( $_POST['newcontent'] );
$location = 'theme-editor.php?file=' . urlencode( $relative_file ) . '&theme=' . urlencode( $stylesheet ) . '&scrollto=' . $scrollto;
if ( is_writeable( $file ) ) {
//is_writable() not always reliable, check return value. see comments @ http://uk.php.net/is_writable
$f = fopen( $file, 'w+' );
if ( $f !== false ) {
fwrite( $f, $newcontent );
fclose( $f );
$location .= '&updated=true';
$theme->cache_delete();
}
}
wp_redirect( $location );
exit;
break;
default:
require_once( ABSPATH . 'wp-admin/admin-header.php' );
update_recently_edited( $file );
if ( ! is_file( $file ) )
$error = true;
$content = '';
if ( ! $error && filesize( $file ) > 0 ) {
$f = fopen($file, 'r');
$content = fread($f, filesize($file));
if ( '.php' == substr( $file, strrpos( $file, '.' ) ) ) {
$functions = wp_doc_link_parse( $content );
$docs_select = '<select name="docs-list" id="docs-list">';
$docs_select .= '<option value="">' . esc_attr__( 'Function Name…' ) . '</option>';
foreach ( $functions as $function ) {
$docs_select .= '<option value="' . esc_attr( urlencode( $function ) ) . '">' . htmlspecialchars( $function ) . '()</option>';
}
$docs_select .= '</select>';
}
$content = esc_textarea( $content );
}
?>
<?php if ( isset( $_GET['updated'] ) ) : ?>
<div id="message" class="updated"><p><?php _e( 'File edited successfully.' ) ?></p></div>
<?php endif;
$description = get_file_description( $file );
$file_show = array_search( $file, array_filter( $allowed_files ) );
if ( $description != $file_show )
$description .= ' <span>(' . $file_show . ')</span>';
?>
<div class="wrap">
<h2><?php echo esc_html( $title ); ?></h2>
<div class="fileedit-sub">
<div class="alignleft">
<h3><?php echo $theme->display('Name'); if ( $description ) echo ': ' . $description; ?></h3>
</div>
<div class="alignright">
<form action="theme-editor.php" method="post">
<strong><label for="theme"><?php _e('Select theme to edit:'); ?> </label></strong>
<select name="theme" id="theme">
<?php
foreach ( wp_get_themes( array( 'errors' => null ) ) as $a_stylesheet => $a_theme ) {
if ( $a_theme->errors() && 'theme_no_stylesheet' == $a_theme->errors()->get_error_code() )
continue;
$selected = $a_stylesheet == $stylesheet ? ' selected="selected"' : '';
echo "\n\t" . '<option value="' . esc_attr( $a_stylesheet ) . '"' . $selected . '>' . $a_theme->display('Name') . '</option>';
}
?>
</select>
<?php submit_button( __( 'Select' ), 'button', 'Submit', false ); ?>
</form>
</div>
<br class="clear" />
</div>
<?php
if ( $theme->errors() )
echo '<div class="error"><p><strong>' . __( 'This theme is broken.' ) . '</strong> ' . $theme->errors()->get_error_message() . '</p></div>';
?>
<div id="templateside">
<?php
if ( $allowed_files ) :
if ( $has_templates || $theme->parent() ) :
?>
<h3><?php _e('Templates'); ?></h3>
<?php if ( $theme->parent() ) : ?>
<p class="howto"><?php printf( __( 'This child theme inherits templates from a parent theme, %s.' ), '<a href="' . self_admin_url('theme-editor.php?theme=' . urlencode( $theme->get_template() ) ) . '">' . $theme->parent()->display('Name') . '</a>' ); ?></p>
<?php endif; ?>
<ul>
<?php
endif;
foreach ( $allowed_files as $filename => $absolute_filename ) :
if ( 'style.css' == $filename )
echo "\t</ul>\n\t<h3>" . _x( 'Styles', 'Theme stylesheets in theme editor' ) . "</h3>\n\t<ul>\n";
$file_description = get_file_description( $absolute_filename );
if ( $file_description != basename( $filename ) )
$file_description .= '<br /><span class="nonessential">(' . $filename . ')</span>';
if ( $absolute_filename == $file )
$file_description = '<span class="highlight">' . $file_description . '</span>';
?>
<li><a href="theme-editor.php?file=<?php echo urlencode( $filename ) ?>&theme=<?php echo urlencode( $stylesheet ) ?>"><?php echo $file_description; ?></a></li>
<?php
endforeach;
?>
</ul>
<?php endif; ?>
</div>
<?php if ( $error ) :
echo '<div class="error"><p>' . __('Oops, no such file exists! Double check the name and try again, merci.') . '</p></div>';
else : ?>
<form name="template" id="template" action="theme-editor.php" method="post">
<?php wp_nonce_field( 'edit-theme_' . $file . $stylesheet ); ?>
<div><textarea cols="70" rows="30" name="newcontent" id="newcontent" aria-describedby="newcontent-description"><?php echo $content; ?></textarea>
<input type="hidden" name="action" value="update" />
<input type="hidden" name="file" value="<?php echo esc_attr( $relative_file ); ?>" />
<input type="hidden" name="theme" value="<?php echo esc_attr( $theme->get_stylesheet() ); ?>" />
<input type="hidden" name="scrollto" id="scrollto" value="<?php echo $scrollto; ?>" />
</div>
<?php if ( ! empty( $functions ) ) : ?>
<div id="documentation" class="hide-if-no-js">
<label for="docs-list"><?php _e('Documentation:') ?></label>
<?php echo $docs_select; ?>
<input type="button" class="button" value=" <?php esc_attr_e( 'Look Up' ); ?> " onclick="if ( '' != jQuery('#docs-list').val() ) { window.open( 'http://api.wordpress.org/core/handbook/1.0/?function=' + escape( jQuery( '#docs-list' ).val() ) + '&locale=<?php echo urlencode( get_locale() ) ?>&version=<?php echo urlencode( $wp_version ) ?>&redirect=true'); }" />
</div>
<?php endif; ?>
<div>
<?php if ( is_child_theme() && $theme->get_stylesheet() == get_template() ) : ?>
<p><?php if ( is_writeable( $file ) ) { ?><strong><?php _e( 'Caution:' ); ?></strong><?php } ?>
<?php _e( 'This is a file in your current parent theme.' ); ?></p>
<?php endif; ?>
<?php
if ( is_writeable( $file ) ) :
submit_button( __( 'Update File' ), 'primary', 'submit', true );
else : ?>
<p><em><?php _e('You need to make this file writable before you can save your changes. See <a href="http://codex.wordpress.org/Changing_File_Permissions">the Codex</a> for more information.'); ?></em></p>
<?php endif; ?>
</div>
</form>
<?php
endif; // $error
?>
<br class="clear" />
</div>
<script type="text/javascript">
/* <![CDATA[ */
jQuery(document).ready(function($){
$('#template').submit(function(){ $('#scrollto').val( $('#newcontent').scrollTop() ); });
$('#newcontent').scrollTop( $('#scrollto').val() );
});
/* ]]> */
</script>
<?php
break;
}
include(ABSPATH . 'wp-admin/admin-footer.php' );
| 01-wordpress-paypal | trunk/wp-admin/theme-editor.php | PHP | gpl3 | 10,207 |
<?php
/**
* Action handler for Multisite administration panels.
*
* @package WordPress
* @subpackage Multisite
* @since 3.0.0
*/
require_once( dirname( __FILE__ ) . '/admin.php' );
wp_redirect( network_admin_url() );
exit;
| 01-wordpress-paypal | trunk/wp-admin/ms-edit.php | PHP | gpl3 | 231 |
<?php
/**
* Update Core administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
wp_enqueue_style( 'plugin-install' );
wp_enqueue_script( 'plugin-install' );
wp_enqueue_script( 'updates' );
add_thickbox();
if ( is_multisite() && ! is_network_admin() ) {
wp_redirect( network_admin_url( 'update-core.php' ) );
exit();
}
if ( ! current_user_can( 'update_core' ) && ! current_user_can( 'update_themes' ) && ! current_user_can( 'update_plugins' ) )
wp_die( __( 'You do not have sufficient permissions to update this site.' ) );
function list_core_update( $update ) {
global $wp_local_package, $wpdb, $wp_version;
static $first_pass = true;
if ( 'en_US' == $update->locale && 'en_US' == get_locale() )
$version_string = $update->current;
// If the only available update is a partial builds, it doesn't need a language-specific version string.
elseif ( 'en_US' == $update->locale && $update->packages->partial && $wp_version == $update->partial_version && ( $updates = get_core_updates() ) && 1 == count( $updates ) )
$version_string = $update->current;
else
$version_string = sprintf( "%s–<strong>%s</strong>", $update->current, $update->locale );
$current = false;
if ( !isset($update->response) || 'latest' == $update->response )
$current = true;
$submit = __('Update Now');
$form_action = 'update-core.php?action=do-core-upgrade';
$php_version = phpversion();
$mysql_version = $wpdb->db_version();
$show_buttons = true;
if ( 'development' == $update->response ) {
$message = __('You are using a development version of WordPress. You can update to the latest nightly build automatically or download the nightly build and install it manually:');
$download = __('Download nightly build');
} else {
if ( $current ) {
$message = sprintf( __( 'If you need to re-install version %s, you can do so here or download the package and re-install manually:' ), $version_string );
$submit = __('Re-install Now');
$form_action = 'update-core.php?action=do-core-reinstall';
} else {
$php_compat = version_compare( $php_version, $update->php_version, '>=' );
if ( file_exists( WP_CONTENT_DIR . '/db.php' ) && empty( $wpdb->is_mysql ) )
$mysql_compat = true;
else
$mysql_compat = version_compare( $mysql_version, $update->mysql_version, '>=' );
if ( !$mysql_compat && !$php_compat )
$message = sprintf( __('You cannot update because <a href="http://codex.wordpress.org/Version_%1$s">WordPress %1$s</a> requires PHP version %2$s or higher and MySQL version %3$s or higher. You are running PHP version %4$s and MySQL version %5$s.'), $update->current, $update->php_version, $update->mysql_version, $php_version, $mysql_version );
elseif ( !$php_compat )
$message = sprintf( __('You cannot update because <a href="http://codex.wordpress.org/Version_%1$s">WordPress %1$s</a> requires PHP version %2$s or higher. You are running version %3$s.'), $update->current, $update->php_version, $php_version );
elseif ( !$mysql_compat )
$message = sprintf( __('You cannot update because <a href="http://codex.wordpress.org/Version_%1$s">WordPress %1$s</a> requires MySQL version %2$s or higher. You are running version %3$s.'), $update->current, $update->mysql_version, $mysql_version );
else
$message = sprintf(__('You can update to <a href="http://codex.wordpress.org/Version_%1$s">WordPress %2$s</a> automatically or download the package and install it manually:'), $update->current, $version_string);
if ( !$mysql_compat || !$php_compat )
$show_buttons = false;
}
$download = sprintf(__('Download %s'), $version_string);
}
echo '<p>';
echo $message;
echo '</p>';
echo '<form method="post" action="' . $form_action . '" name="upgrade" class="upgrade">';
wp_nonce_field('upgrade-core');
echo '<p>';
echo '<input name="version" value="'. esc_attr($update->current) .'" type="hidden"/>';
echo '<input name="locale" value="'. esc_attr($update->locale) .'" type="hidden"/>';
if ( $show_buttons ) {
if ( $first_pass ) {
submit_button( $submit, $current ? 'button' : 'primary regular', 'upgrade', false );
$first_pass = false;
} else {
submit_button( $submit, 'button', 'upgrade', false );
}
echo ' <a href="' . esc_url( $update->download ) . '" class="button">' . $download . '</a> ';
}
if ( 'en_US' != $update->locale )
if ( !isset( $update->dismissed ) || !$update->dismissed )
submit_button( __('Hide this update'), 'button', 'dismiss', false );
else
submit_button( __('Bring back this update'), 'button', 'undismiss', false );
echo '</p>';
if ( 'en_US' != $update->locale && ( !isset($wp_local_package) || $wp_local_package != $update->locale ) )
echo '<p class="hint">'.__('This localized version contains both the translation and various other localization fixes. You can skip upgrading if you want to keep your current translation.').'</p>';
// Partial builds don't need language-specific warnings.
elseif ( 'en_US' == $update->locale && get_locale() != 'en_US' && ( ! $update->packages->partial && $wp_version == $update->partial_version ) ) {
echo '<p class="hint">'.sprintf( __('You are about to install WordPress %s <strong>in English (US).</strong> There is a chance this update will break your translation. You may prefer to wait for the localized version to be released.'), $update->response != 'development' ? $update->current : '' ).'</p>';
}
echo '</form>';
}
function dismissed_updates() {
$dismissed = get_core_updates( array( 'dismissed' => true, 'available' => false ) );
if ( $dismissed ) {
$show_text = esc_js(__('Show hidden updates'));
$hide_text = esc_js(__('Hide hidden updates'));
?>
<script type="text/javascript">
jQuery(function($) {
$('dismissed-updates').show();
$('#show-dismissed').toggle(function(){$(this).text('<?php echo $hide_text; ?>');}, function() {$(this).text('<?php echo $show_text; ?>')});
$('#show-dismissed').click(function() { $('#dismissed-updates').toggle('slow');});
});
</script>
<?php
echo '<p class="hide-if-no-js"><a id="show-dismissed" href="#">'.__('Show hidden updates').'</a></p>';
echo '<ul id="dismissed-updates" class="core-updates dismissed">';
foreach( (array) $dismissed as $update) {
echo '<li>';
list_core_update( $update );
echo '</li>';
}
echo '</ul>';
}
}
/**
* Display upgrade WordPress for downloading latest or upgrading automatically form.
*
* @since 2.7.0
*
* @return null
*/
function core_upgrade_preamble() {
global $wp_version, $required_php_version, $required_mysql_version;
$updates = get_core_updates();
if ( !isset($updates[0]->response) || 'latest' == $updates[0]->response ) {
echo '<h3>';
_e('You have the latest version of WordPress.');
if ( wp_http_supports( array( 'ssl' ) ) ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
$upgrader = new WP_Automatic_Updater;
$future_minor_update = (object) array(
'current' => $wp_version . '.1.next.minor',
'version' => $wp_version . '.1.next.minor',
'php_version' => $required_php_version,
'mysql_version' => $required_mysql_version,
);
$should_auto_update = $upgrader->should_update( 'core', $future_minor_update, ABSPATH );
if ( $should_auto_update )
echo ' ' . __( 'Future security updates will be applied automatically.' );
}
echo '</h3>';
} else {
echo '<div class="updated inline"><p>';
_e('<strong>Important:</strong> before updating, please <a href="http://codex.wordpress.org/WordPress_Backups">back up your database and files</a>. For help with updates, visit the <a href="http://codex.wordpress.org/Updating_WordPress">Updating WordPress</a> Codex page.');
echo '</p></div>';
echo '<h3 class="response">';
_e( 'An updated version of WordPress is available.' );
echo '</h3>';
}
if ( isset( $updates[0] ) && $updates[0]->response == 'development' ) {
require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
$upgrader = new WP_Automatic_Updater;
if ( wp_http_supports( 'ssl' ) && $upgrader->should_update( 'core', $updates[0], ABSPATH ) )
echo '<div class="updated inline"><p><strong>BETA TESTERS:</strong> This site is set up to install updates of future beta versions automatically.</p></div>';
}
echo '<ul class="core-updates">';
$alternate = true;
foreach( (array) $updates as $update ) {
echo '<li>';
list_core_update( $update );
echo '</li>';
}
echo '</ul>';
// Don't show the maintenance mode notice when we are only showing a single re-install option.
if ( $updates && ( count( $updates ) > 1 || $updates[0]->response != 'latest' ) ) {
echo '<p>' . __( 'While your site is being updated, it will be in maintenance mode. As soon as your updates are complete, your site will return to normal.' ) . '</p>';
} elseif ( ! $updates ) {
list( $normalized_version ) = explode( '-', $wp_version );
echo '<p>' . sprintf( __( '<a href="%s">Learn more about WordPress %s</a>.' ), esc_url( self_admin_url( 'about.php' ) ), $normalized_version ) . '</p>';
}
dismissed_updates();
}
function list_plugin_updates() {
global $wp_version;
$cur_wp_version = preg_replace('/-.*$/', '', $wp_version);
require_once(ABSPATH . 'wp-admin/includes/plugin-install.php');
$plugins = get_plugin_updates();
if ( empty( $plugins ) ) {
echo '<h3>' . __( 'Plugins' ) . '</h3>';
echo '<p>' . __( 'Your plugins are all up to date.' ) . '</p>';
return;
}
$form_action = 'update-core.php?action=do-plugin-upgrade';
$core_updates = get_core_updates();
if ( !isset($core_updates[0]->response) || 'latest' == $core_updates[0]->response || 'development' == $core_updates[0]->response || version_compare( $core_updates[0]->current, $cur_wp_version, '=') )
$core_update_version = false;
else
$core_update_version = $core_updates[0]->current;
?>
<h3><?php _e( 'Plugins' ); ?></h3>
<p><?php _e( 'The following plugins have new versions available. Check the ones you want to update and then click “Update Plugins”.' ); ?></p>
<form method="post" action="<?php echo esc_url( $form_action ); ?>" name="upgrade-plugins" class="upgrade">
<?php wp_nonce_field('upgrade-core'); ?>
<p><input id="upgrade-plugins" class="button" type="submit" value="<?php esc_attr_e('Update Plugins'); ?>" name="upgrade" /></p>
<table class="widefat" id="update-plugins-table">
<thead>
<tr>
<th scope="col" class="manage-column check-column"><input type="checkbox" id="plugins-select-all" /></th>
<th scope="col" class="manage-column"><label for="plugins-select-all"><?php _e('Select All'); ?></label></th>
</tr>
</thead>
<tfoot>
<tr>
<th scope="col" class="manage-column check-column"><input type="checkbox" id="plugins-select-all-2" /></th>
<th scope="col" class="manage-column"><label for="plugins-select-all-2"><?php _e('Select All'); ?></label></th>
</tr>
</tfoot>
<tbody class="plugins">
<?php
foreach ( (array) $plugins as $plugin_file => $plugin_data) {
$info = plugins_api('plugin_information', array('slug' => $plugin_data->update->slug ));
// Get plugin compat for running version of WordPress.
if ( isset($info->tested) && version_compare($info->tested, $cur_wp_version, '>=') ) {
$compat = '<br />' . sprintf(__('Compatibility with WordPress %1$s: 100%% (according to its author)'), $cur_wp_version);
} elseif ( isset($info->compatibility[$cur_wp_version][$plugin_data->update->new_version]) ) {
$compat = $info->compatibility[$cur_wp_version][$plugin_data->update->new_version];
$compat = '<br />' . sprintf(__('Compatibility with WordPress %1$s: %2$d%% (%3$d "works" votes out of %4$d total)'), $cur_wp_version, $compat[0], $compat[2], $compat[1]);
} else {
$compat = '<br />' . sprintf(__('Compatibility with WordPress %1$s: Unknown'), $cur_wp_version);
}
// Get plugin compat for updated version of WordPress.
if ( $core_update_version ) {
if ( isset($info->compatibility[$core_update_version][$plugin_data->update->new_version]) ) {
$update_compat = $info->compatibility[$core_update_version][$plugin_data->update->new_version];
$compat .= '<br />' . sprintf(__('Compatibility with WordPress %1$s: %2$d%% (%3$d "works" votes out of %4$d total)'), $core_update_version, $update_compat[0], $update_compat[2], $update_compat[1]);
} else {
$compat .= '<br />' . sprintf(__('Compatibility with WordPress %1$s: Unknown'), $core_update_version);
}
}
// Get the upgrade notice for the new plugin version.
if ( isset($plugin_data->update->upgrade_notice) ) {
$upgrade_notice = '<br />' . strip_tags($plugin_data->update->upgrade_notice);
} else {
$upgrade_notice = '';
}
$details_url = self_admin_url('plugin-install.php?tab=plugin-information&plugin=' . $plugin_data->update->slug . '§ion=changelog&TB_iframe=true&width=640&height=662');
$details_text = sprintf(__('View version %1$s details'), $plugin_data->update->new_version);
$details = sprintf('<a href="%1$s" class="thickbox" title="%2$s">%3$s</a>.', esc_url($details_url), esc_attr($plugin_data->Name), $details_text);
echo "
<tr>
<th scope='row' class='check-column'><input type='checkbox' name='checked[]' value='" . esc_attr($plugin_file) . "' /></th>
<td><p><strong>{$plugin_data->Name}</strong><br />" . sprintf(__('You have version %1$s installed. Update to %2$s.'), $plugin_data->Version, $plugin_data->update->new_version) . ' ' . $details . $compat . $upgrade_notice . "</p></td>
</tr>";
}
?>
</tbody>
</table>
<p><input id="upgrade-plugins-2" class="button" type="submit" value="<?php esc_attr_e('Update Plugins'); ?>" name="upgrade" /></p>
</form>
<?php
}
function list_theme_updates() {
$themes = get_theme_updates();
if ( empty( $themes ) ) {
echo '<h3>' . __( 'Themes' ) . '</h3>';
echo '<p>' . __( 'Your themes are all up to date.' ) . '</p>';
return;
}
$form_action = 'update-core.php?action=do-theme-upgrade';
?>
<h3><?php _e( 'Themes' ); ?></h3>
<p><?php _e( 'The following themes have new versions available. Check the ones you want to update and then click “Update Themes”.' ); ?></p>
<p><?php printf( __( '<strong>Please Note:</strong> Any customizations you have made to theme files will be lost. Please consider using <a href="%s">child themes</a> for modifications.' ), __( 'http://codex.wordpress.org/Child_Themes' ) ); ?></p>
<form method="post" action="<?php echo esc_url( $form_action ); ?>" name="upgrade-themes" class="upgrade">
<?php wp_nonce_field('upgrade-core'); ?>
<p><input id="upgrade-themes" class="button" type="submit" value="<?php esc_attr_e('Update Themes'); ?>" name="upgrade" /></p>
<table class="widefat" id="update-themes-table">
<thead>
<tr>
<th scope="col" class="manage-column check-column"><input type="checkbox" id="themes-select-all" /></th>
<th scope="col" class="manage-column"><label for="themes-select-all"><?php _e('Select All'); ?></label></th>
</tr>
</thead>
<tfoot>
<tr>
<th scope="col" class="manage-column check-column"><input type="checkbox" id="themes-select-all-2" /></th>
<th scope="col" class="manage-column"><label for="themes-select-all-2"><?php _e('Select All'); ?></label></th>
</tr>
</tfoot>
<tbody class="plugins">
<?php
foreach ( $themes as $stylesheet => $theme ) {
echo "
<tr>
<th scope='row' class='check-column'><input type='checkbox' name='checked[]' value='" . esc_attr( $stylesheet ) . "' /></th>
<td class='plugin-title'><img src='" . esc_url( $theme->get_screenshot() ) . "' width='85' height='64' style='float:left; padding: 0 5px 5px' /><strong>" . $theme->display('Name') . '</strong> ' . sprintf( __( 'You have version %1$s installed. Update to %2$s.' ), $theme->display('Version'), $theme->update['new_version'] ) . "</td>
</tr>";
}
?>
</tbody>
</table>
<p><input id="upgrade-themes-2" class="button" type="submit" value="<?php esc_attr_e('Update Themes'); ?>" name="upgrade" /></p>
</form>
<?php
}
function list_translation_updates() {
$updates = wp_get_translation_updates();
if ( ! $updates ) {
if ( 'en_US' != get_locale() ) {
echo '<h3>' . __( 'Translations' ) . '</h3>';
echo '<p>' . __( 'Your translations are all up to date.' ) . '</p>';
}
return;
}
$form_action = 'update-core.php?action=do-translation-upgrade';
?>
<h3><?php _e( 'Translations' ); ?></h3>
<form method="post" action="<?php echo esc_url( $form_action ); ?>" name="upgrade-themes" class="upgrade">
<p><?php _e( 'Some of your translations are out of date.' ); ?></p>
<?php wp_nonce_field('upgrade-translations'); ?>
<p><input class="button" type="submit" value="<?php esc_attr_e( 'Update Translations' ); ?>" name="upgrade" /></p>
</form>
<?php
}
/**
* Upgrade WordPress core display.
*
* @since 2.7.0
*
* @return null
*/
function do_core_upgrade( $reinstall = false ) {
global $wp_filesystem;
include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
if ( $reinstall )
$url = 'update-core.php?action=do-core-reinstall';
else
$url = 'update-core.php?action=do-core-upgrade';
$url = wp_nonce_url($url, 'upgrade-core');
$version = isset( $_POST['version'] )? $_POST['version'] : false;
$locale = isset( $_POST['locale'] )? $_POST['locale'] : 'en_US';
$update = find_core_update( $version, $locale );
if ( !$update )
return;
?>
<div class="wrap">
<h2><?php _e('Update WordPress'); ?></h2>
<?php
if ( false === ( $credentials = request_filesystem_credentials( $url, '', false, ABSPATH ) ) ) {
echo '</div>';
return;
}
if ( ! WP_Filesystem( $credentials, ABSPATH ) ) {
// Failed to connect, Error and request again
request_filesystem_credentials( $url, '', true, ABSPATH );
echo '</div>';
return;
}
if ( $wp_filesystem->errors->get_error_code() ) {
foreach ( $wp_filesystem->errors->get_error_messages() as $message )
show_message($message);
echo '</div>';
return;
}
if ( $reinstall )
$update->response = 'reinstall';
add_filter( 'update_feedback', 'show_message' );
$upgrader = new Core_Upgrader();
$result = $upgrader->upgrade( $update );
if ( is_wp_error($result) ) {
show_message($result);
if ('up_to_date' != $result->get_error_code() )
show_message( __('Installation Failed') );
echo '</div>';
return;
}
show_message( __('WordPress updated successfully') );
show_message( '<span class="hide-if-no-js">' . sprintf( __( 'Welcome to WordPress %1$s. You will be redirected to the About WordPress screen. If not, click <a href="%2$s">here</a>.' ), $result, esc_url( self_admin_url( 'about.php?updated' ) ) ) . '</span>' );
show_message( '<span class="hide-if-js">' . sprintf( __( 'Welcome to WordPress %1$s. <a href="%2$s">Learn more</a>.' ), $result, esc_url( self_admin_url( 'about.php?updated' ) ) ) . '</span>' );
?>
</div>
<script type="text/javascript">
window.location = '<?php echo self_admin_url( 'about.php?updated' ); ?>';
</script>
<?php
}
function do_dismiss_core_update() {
$version = isset( $_POST['version'] )? $_POST['version'] : false;
$locale = isset( $_POST['locale'] )? $_POST['locale'] : 'en_US';
$update = find_core_update( $version, $locale );
if ( !$update )
return;
dismiss_core_update( $update );
wp_redirect( wp_nonce_url('update-core.php?action=upgrade-core', 'upgrade-core') );
exit;
}
function do_undismiss_core_update() {
$version = isset( $_POST['version'] )? $_POST['version'] : false;
$locale = isset( $_POST['locale'] )? $_POST['locale'] : 'en_US';
$update = find_core_update( $version, $locale );
if ( !$update )
return;
undismiss_core_update( $version, $locale );
wp_redirect( wp_nonce_url('update-core.php?action=upgrade-core', 'upgrade-core') );
exit;
}
$action = isset($_GET['action']) ? $_GET['action'] : 'upgrade-core';
$upgrade_error = false;
if ( ( 'do-theme-upgrade' == $action || ( 'do-plugin-upgrade' == $action && ! isset( $_GET['plugins'] ) ) )
&& ! isset( $_POST['checked'] ) ) {
$upgrade_error = $action == 'do-theme-upgrade' ? 'themes' : 'plugins';
$action = 'upgrade-core';
}
$title = __('WordPress Updates');
$parent_file = 'index.php';
$updates_overview = '<p>' . __( 'On this screen, you can update to the latest version of WordPress, as well as update your themes and plugins from the WordPress.org repositories.' ) . '</p>';
$updates_overview .= '<p>' . __( 'If an update is available, you᾿ll see a notification appear in the Toolbar and navigation menu.' ) . ' ' . __( 'Keeping your site updated is important for security. It also makes the internet a safer place for you and your readers.' ) . '</p>';
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __( 'Overview' ),
'content' => $updates_overview
) );
$updates_howto = '<p>' . __( '<strong>WordPress</strong> — Updating your WordPress installation is a simple one-click procedure: just <strong>click on the “Update Now” button</strong> when you are notified that a new version is available.' ) . ' ' . __( 'In most cases, WordPress will automatically apply maintenance and security updates in the background for you.' ) . '</p>';
$updates_howto .= '<p>' . __( '<strong>Themes and Plugins</strong> — To update individual themes or plugins from this screen, use the checkboxes to make your selection, then <strong>click on the appropriate “Update” button</strong>. To update all of your themes or plugins at once, you can check the box at the top of the section to select all before clicking the update button.' ) . '</p>';
if ( 'en_US' != get_locale() ) {
$updates_howto .= '<p>' . __( '<strong>Translations</strong> — The files translating WordPress into your language are updated for you whenever any other updates occur. But if these files are out of date, you can <strong>click the “Update Translations”</strong> button.' ) . '</p>';
}
get_current_screen()->add_help_tab( array(
'id' => 'how-to-update',
'title' => __( 'How to Update' ),
'content' => $updates_howto
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __( '<a href="http://codex.wordpress.org/Dashboard_Updates_Screen" target="_blank">Documentation on Updating WordPress</a>' ) . '</p>' .
'<p>' . __( '<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>' ) . '</p>'
);
if ( 'upgrade-core' == $action ) {
// Force a update check when requested
$force_check = ! empty( $_GET['force-check'] );
wp_version_check( array(), $force_check );
require_once(ABSPATH . 'wp-admin/admin-header.php');
?>
<div class="wrap">
<h2><?php _e('WordPress Updates'); ?></h2>
<?php
if ( $upgrade_error ) {
echo '<div class="error"><p>';
if ( $upgrade_error == 'themes' )
_e('Please select one or more themes to update.');
else
_e('Please select one or more plugins to update.');
echo '</p></div>';
}
echo '<p>';
/* translators: %1 date, %2 time. */
printf( __('Last checked on %1$s at %2$s.'), date_i18n( get_option( 'date_format' ) ), date_i18n( get_option( 'time_format' ) ) );
echo ' <a class="button" href="' . esc_url( self_admin_url('update-core.php?force-check=1') ) . '">' . __( 'Check Again' ) . '</a>';
echo '</p>';
if ( $core = current_user_can( 'update_core' ) )
core_upgrade_preamble();
if ( $plugins = current_user_can( 'update_plugins' ) )
list_plugin_updates();
if ( $themes = current_user_can( 'update_themes' ) )
list_theme_updates();
if ( $core || $plugins || $themes )
list_translation_updates();
unset( $core, $plugins, $themes );
/**
* Fires after the core, plugin, and theme update tables.
*
* @since 2.9.0
*/
do_action( 'core_upgrade_preamble' );
echo '</div>';
include(ABSPATH . 'wp-admin/admin-footer.php');
} elseif ( 'do-core-upgrade' == $action || 'do-core-reinstall' == $action ) {
if ( ! current_user_can( 'update_core' ) )
wp_die( __( 'You do not have sufficient permissions to update this site.' ) );
check_admin_referer('upgrade-core');
// do the (un)dismiss actions before headers,
// so that they can redirect
if ( isset( $_POST['dismiss'] ) )
do_dismiss_core_update();
elseif ( isset( $_POST['undismiss'] ) )
do_undismiss_core_update();
require_once(ABSPATH . 'wp-admin/admin-header.php');
if ( 'do-core-reinstall' == $action )
$reinstall = true;
else
$reinstall = false;
if ( isset( $_POST['upgrade'] ) )
do_core_upgrade($reinstall);
include(ABSPATH . 'wp-admin/admin-footer.php');
} elseif ( 'do-plugin-upgrade' == $action ) {
if ( ! current_user_can( 'update_plugins' ) )
wp_die( __( 'You do not have sufficient permissions to update this site.' ) );
check_admin_referer('upgrade-core');
if ( isset( $_GET['plugins'] ) ) {
$plugins = explode( ',', $_GET['plugins'] );
} elseif ( isset( $_POST['checked'] ) ) {
$plugins = (array) $_POST['checked'];
} else {
wp_redirect( admin_url('update-core.php') );
exit;
}
$url = 'update.php?action=update-selected&plugins=' . urlencode(implode(',', $plugins));
$url = wp_nonce_url($url, 'bulk-update-plugins');
$title = __('Update Plugins');
require_once(ABSPATH . 'wp-admin/admin-header.php');
echo '<div class="wrap">';
echo '<h2>' . esc_html__('Update Plugins') . '</h2>';
echo "<iframe src='$url' style='width: 100%; height: 100%; min-height: 750px;' frameborder='0'></iframe>";
echo '</div>';
include(ABSPATH . 'wp-admin/admin-footer.php');
} elseif ( 'do-theme-upgrade' == $action ) {
if ( ! current_user_can( 'update_themes' ) )
wp_die( __( 'You do not have sufficient permissions to update this site.' ) );
check_admin_referer('upgrade-core');
if ( isset( $_GET['themes'] ) ) {
$themes = explode( ',', $_GET['themes'] );
} elseif ( isset( $_POST['checked'] ) ) {
$themes = (array) $_POST['checked'];
} else {
wp_redirect( admin_url('update-core.php') );
exit;
}
$url = 'update.php?action=update-selected-themes&themes=' . urlencode(implode(',', $themes));
$url = wp_nonce_url($url, 'bulk-update-themes');
$title = __('Update Themes');
require_once(ABSPATH . 'wp-admin/admin-header.php');
echo '<div class="wrap">';
echo '<h2>' . esc_html__('Update Themes') . '</h2>';
echo "<iframe src='$url' style='width: 100%; height: 100%; min-height: 750px;' frameborder='0'></iframe>";
echo '</div>';
include(ABSPATH . 'wp-admin/admin-footer.php');
} elseif ( 'do-translation-upgrade' == $action ) {
if ( ! current_user_can( 'update_core' ) && ! current_user_can( 'update_plugins' ) && ! current_user_can( 'update_themes' ) )
wp_die( __( 'You do not have sufficient permissions to update this site.' ) );
check_admin_referer( 'upgrade-translations' );
require_once( ABSPATH . 'wp-admin/admin-header.php' );
include_once( ABSPATH . 'wp-admin/includes/class-wp-upgrader.php' );
$url = 'update-core.php?action=do-translation-upgrade';
$nonce = 'upgrade-translations';
$title = __( 'Update Translations' );
$context = WP_LANG_DIR;
$upgrader = new Language_Pack_Upgrader( new Language_Pack_Upgrader_Skin( compact( 'url', 'nonce', 'title', 'context' ) ) );
$result = $upgrader->bulk_upgrade();
require_once( ABSPATH . 'wp-admin/admin-footer.php' );
} else {
/**
* Fires for each custom update action on the WordPress Updates screen.
*
* The dynamic portion of the hook name, $action, refers to the
* passed update action. The hook fires in lieu of all available
* default update actions.
*
* @since 3.2.0
*/
do_action( "update-core-custom_{$action}" );
}
| 01-wordpress-paypal | trunk/wp-admin/update-core.php | PHP | gpl3 | 27,520 |
<?php
/**
* Press This Display and Handler.
*
* @package WordPress
* @subpackage Press_This
*/
define('IFRAME_REQUEST' , true);
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
header('Content-Type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
if ( ! current_user_can( 'edit_posts' ) || ! current_user_can( get_post_type_object( 'post' )->cap->create_posts ) )
wp_die( __( 'Cheatin’ uh?' ) );
/**
* Press It form handler.
*
* @since 2.6.0
*
* @return int Post ID
*/
function press_it() {
$post = get_default_post_to_edit();
$post = get_object_vars($post);
$post_ID = $post['ID'] = (int) $_POST['post_id'];
if ( !current_user_can('edit_post', $post_ID) )
wp_die(__('You are not allowed to edit this post.'));
$post['post_category'] = isset($_POST['post_category']) ? $_POST['post_category'] : '';
$post['tax_input'] = isset($_POST['tax_input']) ? $_POST['tax_input'] : '';
$post['post_title'] = isset($_POST['title']) ? $_POST['title'] : '';
$content = isset($_POST['content']) ? $_POST['content'] : '';
$upload = false;
if ( !empty($_POST['photo_src']) && current_user_can('upload_files') ) {
foreach( (array) $_POST['photo_src'] as $key => $image) {
// see if files exist in content - we don't want to upload non-used selected files.
if ( strpos($_POST['content'], htmlspecialchars($image)) !== false ) {
$desc = isset($_POST['photo_description'][$key]) ? $_POST['photo_description'][$key] : '';
$upload = media_sideload_image($image, $post_ID, $desc);
// Replace the POSTED content <img> with correct uploaded ones. Regex contains fix for Magic Quotes
if ( !is_wp_error($upload) )
$content = preg_replace('/<img ([^>]*)src=\\\?(\"|\')'.preg_quote(htmlspecialchars($image), '/').'\\\?(\2)([^>\/]*)\/*>/is', $upload, $content);
}
}
}
// set the post_content and status
$post['post_content'] = $content;
if ( isset( $_POST['publish'] ) && current_user_can( 'publish_posts' ) )
$post['post_status'] = 'publish';
elseif ( isset( $_POST['review'] ) )
$post['post_status'] = 'pending';
else
$post['post_status'] = 'draft';
// error handling for media_sideload
if ( is_wp_error($upload) ) {
wp_delete_post($post_ID);
wp_die($upload);
} else {
// Post formats
if ( isset( $_POST['post_format'] ) ) {
if ( current_theme_supports( 'post-formats', $_POST['post_format'] ) )
set_post_format( $post_ID, $_POST['post_format'] );
elseif ( '0' == $_POST['post_format'] )
set_post_format( $post_ID, false );
}
$post_ID = wp_update_post($post);
}
return $post_ID;
}
// For submitted posts.
if ( isset($_REQUEST['action']) && 'post' == $_REQUEST['action'] ) {
check_admin_referer('press-this');
$posted = $post_ID = press_it();
} else {
$post = get_default_post_to_edit('post', true);
$post_ID = $post->ID;
}
// Set Variables
$title = isset( $_GET['t'] ) ? trim( strip_tags( html_entity_decode( wp_unslash( $_GET['t'] ) , ENT_QUOTES) ) ) : '';
$selection = '';
if ( !empty($_GET['s']) ) {
$selection = str_replace(''', "'", wp_unslash($_GET['s']));
$selection = trim( htmlspecialchars( html_entity_decode($selection, ENT_QUOTES) ) );
}
if ( ! empty($selection) ) {
$selection = preg_replace('/(\r?\n|\r)/', '</p><p>', $selection);
$selection = '<p>' . str_replace('<p></p>', '', $selection) . '</p>';
}
$url = isset($_GET['u']) ? esc_url($_GET['u']) : '';
$image = isset($_GET['i']) ? $_GET['i'] : '';
if ( !empty($_REQUEST['ajax']) ) {
switch ($_REQUEST['ajax']) {
case 'video': ?>
<script type="text/javascript">
/* <![CDATA[ */
jQuery('.select').click(function() {
append_editor(jQuery('#embed-code').val());
jQuery('#extra-fields').hide();
jQuery('#extra-fields').html('');
});
jQuery('.close').click(function() {
jQuery('#extra-fields').hide();
jQuery('#extra-fields').html('');
});
/* ]]> */
</script>
<div class="postbox">
<h2><label for="embed-code"><?php _e('Embed Code') ?></label></h2>
<div class="inside">
<textarea name="embed-code" id="embed-code" rows="8" cols="40"><?php echo esc_textarea( $selection ); ?></textarea>
<p id="options"><a href="#" class="select button"><?php _e('Insert Video'); ?></a> <a href="#" class="close button"><?php _e('Cancel'); ?></a></p>
</div>
</div>
<?php break;
case 'photo_thickbox': ?>
<script type="text/javascript">
/* <![CDATA[ */
jQuery('.cancel').click(function() {
tb_remove();
});
jQuery('.select').click(function() {
image_selector(this);
});
/* ]]> */
</script>
<h3 class="tb"><label for="tb_this_photo_description"><?php _e('Description') ?></label></h3>
<div class="titlediv">
<div class="titlewrap">
<input id="tb_this_photo_description" name="photo_description" class="tb_this_photo_description tbtitle text" type="text" onkeypress="if(event.keyCode==13) image_selector(this);" value="<?php echo esc_attr($title);?>"/>
</div>
</div>
<p class="centered">
<input type="hidden" name="this_photo" value="<?php echo esc_attr($image); ?>" id="tb_this_photo" class="tb_this_photo" />
<a href="#" class="select">
<img src="<?php echo esc_url($image); ?>" alt="<?php echo esc_attr(__('Click to insert.')); ?>" title="<?php echo esc_attr(__('Click to insert.')); ?>" />
</a>
</p>
<p id="options"><a href="#" class="select button"><?php _e('Insert Image'); ?></a> <a href="#" class="cancel button"><?php _e('Cancel'); ?></a></p>
<?php break;
case 'photo_images':
/**
* Retrieve all image URLs from given URI.
*
* @since 2.6.0
*
* @param string $uri
* @return string
*/
function get_images_from_uri($uri) {
$uri = preg_replace('/\/#.+?$/','', $uri);
if ( preg_match( '/\.(jpe?g|jpe|gif|png)\b/i', $uri ) && !strpos( $uri, 'blogger.com' ) )
return "'" . esc_attr( html_entity_decode($uri) ) . "'";
$content = wp_remote_fopen($uri);
if ( false === $content )
return '';
$host = parse_url($uri);
$pattern = '/<img ([^>]*)src=(\"|\')([^<>\'\"]+)(\2)([^>]*)\/*>/i';
$content = str_replace(array("\n","\t","\r"), '', $content);
preg_match_all($pattern, $content, $matches);
if ( empty($matches[0]) )
return '';
$sources = array();
foreach ($matches[3] as $src) {
// if no http in url
if (strpos($src, 'http') === false)
// if it doesn't have a relative uri
if ( strpos($src, '../') === false && strpos($src, './') === false && strpos($src, '/') === 0)
$src = 'http://'.str_replace('//','/', $host['host'].'/'.$src);
else
$src = 'http://'.str_replace('//','/', $host['host'].'/'.dirname($host['path']).'/'.$src);
$sources[] = esc_url($src);
}
return "'" . implode("','", $sources) . "'";
}
$url = wp_kses(urldecode($url), null);
echo 'new Array('.get_images_from_uri($url).')';
break;
case 'photo_js': ?>
// gather images and load some default JS
var last = null
var img, img_tag, aspect, w, h, skip, i, strtoappend = "";
if(photostorage == false) {
var my_src = eval(
jQuery.ajax({
type: "GET",
url: "<?php echo esc_url($_SERVER['PHP_SELF']); ?>",
cache : false,
async : false,
data: "ajax=photo_images&u=<?php echo urlencode($url); ?>",
dataType : "script"
}).responseText
);
if(my_src.length == 0) {
var my_src = eval(
jQuery.ajax({
type: "GET",
url: "<?php echo esc_url($_SERVER['PHP_SELF']); ?>",
cache : false,
async : false,
data: "ajax=photo_images&u=<?php echo urlencode($url); ?>",
dataType : "script"
}).responseText
);
if(my_src.length == 0) {
strtoappend = '<?php _e('Unable to retrieve images or no images on page.'); ?>';
}
}
}
for (i = 0; i < my_src.length; i++) {
img = new Image();
img.src = my_src[i];
img_attr = 'id="img' + i + '"';
skip = false;
maybeappend = '<a href="?ajax=photo_thickbox&i=' + encodeURIComponent(img.src) + '&u=<?php echo urlencode($url); ?>&height=400&width=500" title="" class="thickbox"><img src="' + img.src + '" ' + img_attr + '/></a>';
if (img.width && img.height) {
if (img.width >= 30 && img.height >= 30) {
aspect = img.width / img.height;
scale = (aspect > 1) ? (71 / img.width) : (71 / img.height);
w = img.width;
h = img.height;
if (scale < 1) {
w = parseInt(img.width * scale);
h = parseInt(img.height * scale);
}
img_attr += ' style="width: ' + w + 'px; height: ' + h + 'px;"';
strtoappend += maybeappend;
}
} else {
strtoappend += maybeappend;
}
}
function pick(img, desc) {
if (img) {
if('object' == typeof jQuery('.photolist input') && jQuery('.photolist input').length != 0) length = jQuery('.photolist input').length;
if(length == 0) length = 1;
jQuery('.photolist').append('<input name="photo_src[' + length + ']" value="' + img +'" type="hidden"/>');
jQuery('.photolist').append('<input name="photo_description[' + length + ']" value="' + desc +'" type="hidden"/>');
insert_editor( "\n\n" + encodeURI('<p style="text-align: center;"><a href="<?php echo $url; ?>"><img src="' + img +'" alt="' + desc + '" /></a></p>'));
}
return false;
}
function image_selector(el) {
var desc, src, parent = jQuery(el).closest('#photo-add-url-div');
if ( parent.length ) {
desc = parent.find('input.tb_this_photo_description').val() || '';
src = parent.find('input.tb_this_photo').val() || ''
} else {
desc = jQuery('#tb_this_photo_description').val() || '';
src = jQuery('#tb_this_photo').val() || ''
}
tb_remove();
pick(src, desc);
jQuery('#extra-fields').hide();
jQuery('#extra-fields').html('');
return false;
}
jQuery('#extra-fields').html('<div class="postbox"><h2><?php _e( 'Add Photos' ); ?> <small id="photo_directions">(<?php _e("click images to select") ?>)</small></h2><ul class="actions"><li><a href="#" id="photo-add-url" class="button button-small"><?php _e("Add from URL") ?> +</a></li></ul><div class="inside"><div class="titlewrap"><div id="img_container"></div></div><p id="options"><a href="#" class="close button"><?php _e('Cancel'); ?></a><a href="#" class="refresh button"><?php _e('Refresh'); ?></a></p></div>');
jQuery('#img_container').html(strtoappend);
<?php break;
}
die;
}
wp_enqueue_style( 'colors' );
wp_enqueue_script( 'post' );
add_thickbox();
_wp_admin_html_begin();
?>
<title><?php _e('Press This') ?></title>
<script type="text/javascript">
//<![CDATA[
addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}};
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php', 'relative' ); ?>', pagenow = 'press-this', isRtl = <?php echo (int) is_rtl(); ?>;
var photostorage = false;
//]]>
</script>
<?php
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_enqueue_scripts', 'press-this.php' );
/**
* Fires when styles are printed for the Press This admin page.
*
* @since 3.7.0
*/
do_action( 'admin_print_styles-press-this.php' );
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_print_styles' );
/**
* Fires when scripts are printed for the Press This admin page.
*
* @since 3.7.0
*/
do_action( 'admin_print_scripts-press-this.php' );
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_print_scripts' );
/**
* Fires in the head tag on the Press This admin page.
*
* @since 3.7.0
*/
do_action( 'admin_head-press-this.php' );
/** This action is documented in wp-admin/admin-header.php */
do_action( 'admin_head' );
?>
<script type="text/javascript">
var wpActiveEditor = 'content';
function insert_plain_editor(text) {
if ( typeof(QTags) != 'undefined' )
QTags.insertContent(text);
}
function set_editor(text) {
if ( '' == text || '<p></p>' == text )
text = '<p><br /></p>';
if ( tinyMCE.activeEditor )
tinyMCE.execCommand('mceSetContent', false, text);
}
function insert_editor(text) {
if ( '' != text && tinyMCE.activeEditor && ! tinyMCE.activeEditor.isHidden()) {
tinyMCE.execCommand('mceInsertContent', false, '<p>' + decodeURI(tinymce.DOM.decode(text)) + '</p>', {format : 'raw'});
} else {
insert_plain_editor(decodeURI(text));
}
}
function append_editor(text) {
if ( '' != text && tinyMCE.activeEditor && ! tinyMCE.activeEditor.isHidden()) {
tinyMCE.execCommand('mceSetContent', false, tinyMCE.activeEditor.getContent({format : 'raw'}) + '<p>' + text + '</p>');
} else {
insert_plain_editor(text);
}
}
function show(tab_name) {
jQuery('#extra-fields').html('');
switch(tab_name) {
case 'video' :
jQuery('#extra-fields').load('<?php echo esc_url($_SERVER['PHP_SELF']); ?>', { ajax: 'video', s: '<?php echo esc_attr($selection); ?>'}, function() {
<?php
$content = '';
if ( preg_match("/youtube\.com\/watch/i", $url) ) {
list($domain, $video_id) = explode("v=", $url);
$video_id = esc_attr($video_id);
$content = '<object width="425" height="350"><param name="movie" value="http://www.youtube.com/v/' . $video_id . '"></param><param name="wmode" value="transparent"></param><embed src="http://www.youtube.com/v/' . $video_id . '" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed></object>';
} elseif ( preg_match("/vimeo\.com\/[0-9]+/i", $url) ) {
list($domain, $video_id) = explode(".com/", $url);
$video_id = esc_attr($video_id);
$content = '<object width="400" height="225"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://www.vimeo.com/moogaloop.swf?clip_id=' . $video_id . '&server=www.vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1" /> <embed src="http://www.vimeo.com/moogaloop.swf?clip_id=' . $video_id . '&server=www.vimeo.com&show_title=1&show_byline=1&show_portrait=0&color=&fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="225"></embed></object>';
if ( trim($selection) == '' )
$selection = '<p><a href="http://www.vimeo.com/' . $video_id . '?pg=embed&sec=' . $video_id . '">' . $title . '</a> on <a href="http://vimeo.com?pg=embed&sec=' . $video_id . '">Vimeo</a></p>';
} elseif ( strpos( $selection, '<object' ) !== false ) {
$content = $selection;
}
?>
jQuery('#embed-code').prepend('<?php echo htmlentities($content); ?>');
});
jQuery('#extra-fields').show();
return false;
break;
case 'photo' :
function setup_photo_actions() {
jQuery('.close').click(function() {
jQuery('#extra-fields').hide();
jQuery('#extra-fields').html('');
});
jQuery('.refresh').click(function() {
photostorage = false;
show('photo');
});
jQuery('#photo-add-url').click(function(){
var form = jQuery('#photo-add-url-div').clone();
jQuery('#img_container').empty().append( form.show() );
});
jQuery('#waiting').hide();
jQuery('#extra-fields').show();
}
jQuery('#waiting').show();
if(photostorage == false) {
jQuery.ajax({
type: "GET",
cache : false,
url: "<?php echo esc_url($_SERVER['PHP_SELF']); ?>",
data: "ajax=photo_js&u=<?php echo urlencode($url)?>",
dataType : "script",
success : function(data) {
eval(data);
photostorage = jQuery('#extra-fields').html();
setup_photo_actions();
}
});
} else {
jQuery('#extra-fields').html(photostorage);
setup_photo_actions();
}
return false;
break;
}
}
jQuery(document).ready(function($) {
//resize screen
window.resizeTo(760,580);
// set button actions
jQuery('#photo_button').click(function() { show('photo'); return false; });
jQuery('#video_button').click(function() { show('video'); return false; });
// auto select
<?php if ( preg_match("/youtube\.com\/watch/i", $url) ) { ?>
show('video');
<?php } elseif ( preg_match("/vimeo\.com\/[0-9]+/i", $url) ) { ?>
show('video');
<?php } elseif ( preg_match("/flickr\.com/i", $url) ) { ?>
show('photo');
<?php } ?>
jQuery('#title').unbind();
jQuery('#publish, #save').click(function() { jQuery('.press-this #publishing-actions .spinner').css('display', 'inline-block'); });
$('#tagsdiv-post_tag, #categorydiv').children('h3, .handlediv').click(function(){
$(this).siblings('.inside').toggle();
});
});
</script>
</head>
<?php
$admin_body_class = ( is_rtl() ) ? 'rtl' : '';
$admin_body_class .= ' locale-' . sanitize_html_class( strtolower( str_replace( '_', '-', get_locale() ) ) );
?>
<body class="press-this wp-admin wp-core-ui <?php echo $admin_body_class; ?>">
<form action="press-this.php?action=post" method="post">
<div id="poststuff" class="metabox-holder">
<div id="side-sortables" class="press-this-sidebar">
<div class="sleeve">
<?php wp_nonce_field('press-this') ?>
<input type="hidden" name="post_type" id="post_type" value="text"/>
<input type="hidden" name="autosave" id="autosave" />
<input type="hidden" id="original_post_status" name="original_post_status" value="draft" />
<input type="hidden" id="prev_status" name="prev_status" value="draft" />
<input type="hidden" id="post_id" name="post_id" value="<?php echo (int) $post_ID; ?>" />
<!-- This div holds the photo metadata -->
<div class="photolist"></div>
<div id="submitdiv" class="postbox">
<div class="handlediv" title="<?php esc_attr_e( 'Click to toggle' ); ?>"><br /></div>
<h3 class="hndle"><?php _e('Press This') ?></h3>
<div class="inside">
<p id="publishing-actions">
<?php
submit_button( __( 'Save Draft' ), 'button', 'draft', false, array( 'id' => 'save' ) );
if ( current_user_can('publish_posts') ) {
submit_button( __( 'Publish' ), 'primary', 'publish', false );
} else {
echo '<br /><br />';
submit_button( __( 'Submit for Review' ), 'primary', 'review', false );
} ?>
<span class="spinner" style="display: none;"></span>
</p>
<?php if ( current_theme_supports( 'post-formats' ) && post_type_supports( 'post', 'post-formats' ) ) :
$post_formats = get_theme_support( 'post-formats' );
if ( is_array( $post_formats[0] ) ) :
$default_format = get_option( 'default_post_format', '0' );
?>
<p>
<label for="post_format"><?php _e( 'Post Format:' ); ?>
<select name="post_format" id="post_format">
<option value="0"><?php echo get_post_format_string( 'standard' ); ?></option>
<?php foreach ( $post_formats[0] as $format ): ?>
<option<?php selected( $default_format, $format ); ?> value="<?php echo esc_attr( $format ); ?>"> <?php echo esc_html( get_post_format_string( $format ) ); ?></option>
<?php endforeach; ?>
</select></label>
</p>
<?php endif; endif; ?>
</div>
</div>
<?php $tax = get_taxonomy( 'category' ); ?>
<div id="categorydiv" class="postbox">
<div class="handlediv" title="<?php esc_attr_e( 'Click to toggle' ); ?>"><br /></div>
<h3 class="hndle"><?php _e('Categories') ?></h3>
<div class="inside">
<div id="taxonomy-category" class="categorydiv">
<ul id="category-tabs" class="category-tabs">
<li class="tabs"><a href="#category-all"><?php echo $tax->labels->all_items; ?></a></li>
<li class="hide-if-no-js"><a href="#category-pop"><?php _e( 'Most Used' ); ?></a></li>
</ul>
<div id="category-pop" class="tabs-panel" style="display: none;">
<ul id="categorychecklist-pop" class="categorychecklist form-no-clear" >
<?php $popular_ids = wp_popular_terms_checklist( 'category' ); ?>
</ul>
</div>
<div id="category-all" class="tabs-panel">
<ul id="categorychecklist" data-wp-lists="list:category" class="categorychecklist form-no-clear">
<?php wp_terms_checklist($post_ID, array( 'taxonomy' => 'category', 'popular_cats' => $popular_ids ) ) ?>
</ul>
</div>
<?php if ( !current_user_can($tax->cap->assign_terms) ) : ?>
<p><em><?php _e('You cannot modify this Taxonomy.'); ?></em></p>
<?php endif; ?>
<?php if ( current_user_can($tax->cap->edit_terms) ) : ?>
<div id="category-adder" class="wp-hidden-children">
<h4>
<a id="category-add-toggle" href="#category-add" class="hide-if-no-js">
<?php printf( __( '+ %s' ), $tax->labels->add_new_item ); ?>
</a>
</h4>
<p id="category-add" class="category-add wp-hidden-child">
<label class="screen-reader-text" for="newcategory"><?php echo $tax->labels->add_new_item; ?></label>
<input type="text" name="newcategory" id="newcategory" class="form-required form-input-tip" value="<?php echo esc_attr( $tax->labels->new_item_name ); ?>" aria-required="true"/>
<label class="screen-reader-text" for="newcategory_parent">
<?php echo $tax->labels->parent_item_colon; ?>
</label>
<?php wp_dropdown_categories( array( 'taxonomy' => 'category', 'hide_empty' => 0, 'name' => 'newcategory_parent', 'orderby' => 'name', 'hierarchical' => 1, 'show_option_none' => '— ' . $tax->labels->parent_item . ' —' ) ); ?>
<input type="button" id="category-add-submit" data-wp-lists="add:categorychecklist:category-add" class="button category-add-submit" value="<?php echo esc_attr( $tax->labels->add_new_item ); ?>" />
<?php wp_nonce_field( 'add-category', '_ajax_nonce-add-category', false ); ?>
<span id="category-ajax-response"></span>
</p>
</div>
<?php endif; ?>
</div>
</div>
</div>
<div id="tagsdiv-post_tag" class="postbox">
<div class="handlediv" title="<?php esc_attr_e( 'Click to toggle' ); ?>"><br /></div>
<h3><span><?php _e('Tags'); ?></span></h3>
<div class="inside">
<div class="tagsdiv" id="post_tag">
<div class="jaxtag">
<label class="screen-reader-text" for="newtag"><?php _e('Tags'); ?></label>
<input type="hidden" name="tax_input[post_tag]" class="the-tags" id="tax-input[post_tag]" value="" />
<div class="ajaxtag">
<input type="text" name="newtag[post_tag]" class="newtag form-input-tip" size="16" autocomplete="off" value="" />
<input type="button" class="button tagadd" value="<?php esc_attr_e('Add'); ?>" />
</div>
</div>
<div class="tagchecklist"></div>
</div>
<p class="tagcloud-link"><a href="#titlediv" class="tagcloud-link" id="link-post_tag"><?php _e('Choose from the most used tags'); ?></a></p>
</div>
</div>
</div>
</div>
<div class="posting">
<div id="wphead">
<h1 id="site-heading">
<a href="<?php echo get_option('home'); ?>/" target="_blank">
<span id="site-title"><?php bloginfo('name'); ?></span>
</a>
</h1>
</div>
<?php
if ( isset($posted) && intval($posted) ) {
$post_ID = intval($posted); ?>
<div id="message" class="updated">
<p><strong><?php _e('Your post has been saved.'); ?></strong>
<a onclick="window.opener.location.replace(this.href); window.close();" href="<?php echo get_permalink($post_ID); ?>"><?php _e('View post'); ?></a>
| <a href="<?php echo get_edit_post_link( $post_ID ); ?>" onclick="window.opener.location.replace(this.href); window.close();"><?php _e('Edit Post'); ?></a>
| <a href="#" onclick="window.close();"><?php _e('Close Window'); ?></a></p>
</div>
<?php } ?>
<div id="titlediv">
<div class="titlewrap">
<input name="title" id="title" class="text" type="text" value="<?php echo esc_attr($title);?>"/>
</div>
</div>
<div id="waiting" style="display: none"><span class="spinner"></span> <span><?php esc_html_e( 'Loading…' ); ?></span></div>
<div id="extra-fields" style="display: none"></div>
<div class="postdivrich">
<?php
$editor_settings = array(
'teeny' => true,
'textarea_rows' => '15'
);
$content = '';
if ( $selection )
$content .= $selection;
if ( $url ) {
$content .= '<p>';
if ( $selection )
$content .= __('via ');
$content .= sprintf( "<a href='%s'>%s</a>.</p>", esc_url( $url ), esc_html( $title ) );
}
remove_action( 'media_buttons', 'media_buttons' );
add_action( 'media_buttons', 'press_this_media_buttons' );
function press_this_media_buttons() {
_e( 'Add:' );
if ( current_user_can('upload_files') ) {
?>
<a id="photo_button" title="<?php esc_attr_e('Insert an Image'); ?>" href="#">
<img alt="<?php esc_attr_e('Insert an Image'); ?>" src="<?php echo esc_url( admin_url( 'images/media-button-image.gif?ver=20100531' ) ); ?>"/></a>
<?php
}
?>
<a id="video_button" title="<?php esc_attr_e('Embed a Video'); ?>" href="#"><img alt="<?php esc_attr_e('Embed a Video'); ?>" src="<?php echo esc_url( admin_url( 'images/media-button-video.gif?ver=20100531' ) ); ?>"/></a>
<?php
}
wp_editor( $content, 'content', $editor_settings );
?>
</div>
</div>
</div>
</form>
<div id="photo-add-url-div" style="display:none;">
<table><tr>
<td><label for="this_photo"><?php _e('URL') ?></label></td>
<td><input type="text" id="this_photo" name="this_photo" class="tb_this_photo text" onkeypress="if(event.keyCode==13) image_selector(this);" /></td>
</tr><tr>
<td><label for="this_photo_description"><?php _e('Description') ?></label></td>
<td><input type="text" id="this_photo_description" name="photo_description" class="tb_this_photo_description text" onkeypress="if(event.keyCode==13) image_selector(this);" value="<?php echo esc_attr($title);?>"/></td>
</tr><tr>
<td><input type="button" class="button" onclick="image_selector(this)" value="<?php esc_attr_e('Insert Image'); ?>" /></td>
</tr></table>
</div>
<?php
/** This action is documented in wp-admin/admin-footer.php */
do_action( 'admin_footer' );
/** This action is documented in wp-admin/admin-footer.php */
do_action( 'admin_print_footer_scripts' );
?>
<script type="text/javascript">if(typeof wpOnload=='function')wpOnload();</script>
</body>
</html>
| 01-wordpress-paypal | trunk/wp-admin/press-this.php | PHP | gpl3 | 26,376 |
<?php
/**
* User Dashboard Administration Screen
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
require_once( dirname( __FILE__ ) . '/admin.php' );
require( ABSPATH . 'wp-admin/index.php' );
| 01-wordpress-paypal | trunk/wp-admin/user/index.php | PHP | gpl3 | 222 |
<?php
/**
* Edit user administration panel.
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
require_once( dirname( __FILE__ ) . '/admin.php' );
require( ABSPATH . 'wp-admin/user-edit.php' );
| 01-wordpress-paypal | trunk/wp-admin/user/user-edit.php | PHP | gpl3 | 221 |
<?php
/**
* User Dashboard About administration panel.
*
* @package WordPress
* @subpackage Administration
* @since 3.4.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
require( ABSPATH . 'wp-admin/about.php' );
| 01-wordpress-paypal | trunk/wp-admin/user/about.php | PHP | gpl3 | 275 |
<?php
/**
* User Profile Administration Screen.
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
require_once( dirname( __FILE__ ) . '/admin.php' );
require( ABSPATH . 'wp-admin/profile.php' );
| 01-wordpress-paypal | trunk/wp-admin/user/profile.php | PHP | gpl3 | 223 |
<?php
/**
* Build User Administration Menu.
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
$menu[2] = array(__('Dashboard'), 'exist', 'index.php', '', 'menu-top menu-top-first menu-icon-dashboard', 'menu-dashboard', 'div');
$menu[4] = array( '', 'exist', 'separator1', '', 'wp-menu-separator' );
$menu[70] = array( __('Profile'), 'exist', 'profile.php', '', 'menu-top menu-icon-users', 'menu-users', 'div' );
$menu[99] = array( '', 'exist', 'separator-last', '', 'wp-menu-separator' );
$_wp_real_parent_file['users.php'] = 'profile.php';
$compat = array();
$submenu = array();
require_once(ABSPATH . 'wp-admin/includes/menu.php');
| 01-wordpress-paypal | trunk/wp-admin/user/menu.php | PHP | gpl3 | 666 |
<?php
/**
* WordPress User Administration Bootstrap
*
* @package WordPress
* @subpackage Administration
* @since 3.1.0
*/
define('WP_USER_ADMIN', true);
require_once( dirname(dirname(__FILE__)) . '/admin.php');
if ( ! is_multisite() ) {
wp_redirect( admin_url() );
exit;
}
$redirect_user_admin_request = ( ( $current_blog->domain != $current_site->domain ) || ( $current_blog->path != $current_site->path ) );
/**
* Filter whether to redirect the request to the User Admin in Multisite.
*
* @since 3.2.0
*
* @param bool $redirect_user_admin_request Whether the request should be redirected.
*/
$redirect_user_admin_request = apply_filters( 'redirect_user_admin_request', $redirect_user_admin_request );
if ( $redirect_user_admin_request ) {
wp_redirect( user_admin_url() );
exit;
}
unset( $redirect_user_admin_request );
| 01-wordpress-paypal | trunk/wp-admin/user/admin.php | PHP | gpl3 | 841 |
<?php
/**
* User Dashboard Credits administration panel.
*
* @package WordPress
* @subpackage Administration
* @since 3.4.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
require( ABSPATH . 'wp-admin/credits.php' );
| 01-wordpress-paypal | trunk/wp-admin/user/credits.php | PHP | gpl3 | 279 |
<?php
/**
* User Dashboard Freedoms administration panel.
*
* @package WordPress
* @subpackage Administration
* @since 3.4.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
require( ABSPATH . 'wp-admin/freedoms.php' );
| 01-wordpress-paypal | trunk/wp-admin/user/freedoms.php | PHP | gpl3 | 281 |
<?php
/**
* New Post Administration Screen.
*
* @package WordPress
* @subpackage Administration
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( !isset($_GET['post_type']) )
$post_type = 'post';
elseif ( in_array( $_GET['post_type'], get_post_types( array('show_ui' => true ) ) ) )
$post_type = $_GET['post_type'];
else
wp_die( __('Invalid post type') );
$post_type_object = get_post_type_object( $post_type );
if ( 'post' == $post_type ) {
$parent_file = 'edit.php';
$submenu_file = 'post-new.php';
} elseif ( 'attachment' == $post_type ) {
if ( wp_redirect( admin_url( 'media-new.php' ) ) )
exit;
} else {
$submenu_file = "post-new.php?post_type=$post_type";
if ( isset( $post_type_object ) && $post_type_object->show_in_menu && $post_type_object->show_in_menu !== true ) {
$parent_file = $post_type_object->show_in_menu;
if ( ! isset( $_registered_pages[ get_plugin_page_hookname( "post-new.php?post_type=$post_type", $post_type_object->show_in_menu ) ] ) )
$submenu_file = $parent_file;
} else {
$parent_file = "edit.php?post_type=$post_type";
}
}
$title = $post_type_object->labels->add_new_item;
$editing = true;
if ( ! current_user_can( $post_type_object->cap->edit_posts ) || ! current_user_can( $post_type_object->cap->create_posts ) )
wp_die( __( 'Cheatin’ uh?' ) );
// Schedule auto-draft cleanup
if ( ! wp_next_scheduled( 'wp_scheduled_auto_draft_delete' ) )
wp_schedule_event( time(), 'daily', 'wp_scheduled_auto_draft_delete' );
wp_enqueue_script( 'autosave' );
if ( is_multisite() ) {
add_action( 'admin_footer', '_admin_notice_post_locked' );
} else {
$check_users = get_users( array( 'fields' => 'ID', 'number' => 2 ) );
if ( count( $check_users ) > 1 )
add_action( 'admin_footer', '_admin_notice_post_locked' );
unset( $check_users );
}
// Show post form.
$post = get_default_post_to_edit( $post_type, true );
$post_ID = $post->ID;
include( ABSPATH . 'wp-admin/edit-form-advanced.php' );
include( ABSPATH . 'wp-admin/admin-footer.php' );
| 01-wordpress-paypal | trunk/wp-admin/post-new.php | PHP | gpl3 | 2,067 |
<?php
/**
* Edit plugin editor administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( is_multisite() && ! is_network_admin() ) {
wp_redirect( network_admin_url( 'plugin-editor.php' ) );
exit();
}
if ( !current_user_can('edit_plugins') )
wp_die( __('You do not have sufficient permissions to edit plugins for this site.') );
$title = __("Edit Plugins");
$parent_file = 'plugins.php';
wp_reset_vars( array( 'action', 'error', 'file', 'plugin' ) );
$plugins = get_plugins();
if ( empty( $plugins ) ) {
include( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2><?php echo esc_html( $title ); ?></h2>
<div id="message" class="error"><p><?php _e( 'You do not appear to have any plugins available at this time.' ); ?></p></div>
</div>
<?php
include( ABSPATH . 'wp-admin/admin-footer.php' );
exit;
}
if ( $file ) {
$plugin = $file;
} elseif ( empty( $plugin ) ) {
$plugin = array_keys($plugins);
$plugin = $plugin[0];
}
$plugin_files = get_plugin_files($plugin);
if ( empty($file) )
$file = $plugin_files[0];
$file = validate_file_to_edit($file, $plugin_files);
$real_file = WP_PLUGIN_DIR . '/' . $file;
$scrollto = isset($_REQUEST['scrollto']) ? (int) $_REQUEST['scrollto'] : 0;
switch ( $action ) {
case 'update':
check_admin_referer('edit-plugin_' . $file);
$newcontent = wp_unslash( $_POST['newcontent'] );
if ( is_writeable($real_file) ) {
$f = fopen($real_file, 'w+');
fwrite($f, $newcontent);
fclose($f);
$network_wide = is_plugin_active_for_network( $file );
// Deactivate so we can test it.
if ( is_plugin_active($file) || isset($_POST['phperror']) ) {
if ( is_plugin_active($file) )
deactivate_plugins($file, true);
if ( ! is_network_admin() )
update_option( 'recently_activated', array( $file => time() ) + (array) get_option( 'recently_activated' ) );
wp_redirect(add_query_arg('_wpnonce', wp_create_nonce('edit-plugin-test_' . $file), "plugin-editor.php?file=$file&liveupdate=1&scrollto=$scrollto&networkwide=" . $network_wide));
exit;
}
wp_redirect( self_admin_url("plugin-editor.php?file=$file&a=te&scrollto=$scrollto") );
} else {
wp_redirect( self_admin_url("plugin-editor.php?file=$file&scrollto=$scrollto") );
}
exit;
break;
default:
if ( isset($_GET['liveupdate']) ) {
check_admin_referer('edit-plugin-test_' . $file);
$error = validate_plugin($file);
if ( is_wp_error($error) )
wp_die( $error );
if ( ( ! empty( $_GET['networkwide'] ) && ! is_plugin_active_for_network($file) ) || ! is_plugin_active($file) )
activate_plugin($file, "plugin-editor.php?file=$file&phperror=1", ! empty( $_GET['networkwide'] ) ); // we'll override this later if the plugin can be included without fatal error
wp_redirect( self_admin_url("plugin-editor.php?file=$file&a=te&scrollto=$scrollto") );
exit;
}
// List of allowable extensions
$editable_extensions = array('php', 'txt', 'text', 'js', 'css', 'html', 'htm', 'xml', 'inc', 'include');
/**
* Filter file type extensions editable in the plugin editor.
*
* @since 2.8.0
*
* @param array $editable_extensions An array of editable plugin file extensions.
*/
$editable_extensions = (array) apply_filters( 'editable_extensions', $editable_extensions );
if ( ! is_file($real_file) ) {
wp_die(sprintf('<p>%s</p>', __('No such file exists! Double check the name and try again.')));
} else {
// Get the extension of the file
if ( preg_match('/\.([^.]+)$/', $real_file, $matches) ) {
$ext = strtolower($matches[1]);
// If extension is not in the acceptable list, skip it
if ( !in_array( $ext, $editable_extensions) )
wp_die(sprintf('<p>%s</p>', __('Files of this type are not editable.')));
}
}
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('You can use the editor to make changes to any of your plugins’ individual PHP files. Be aware that if you make changes, plugins updates will overwrite your customizations.') . '</p>' .
'<p>' . __('Choose a plugin to edit from the menu in the upper right and click the Select button. Click once on any file name to load it in the editor, and make your changes. Don’t forget to save your changes (Update File) when you’re finished.') . '</p>' .
'<p>' . __('The Documentation menu below the editor lists the PHP functions recognized in the plugin file. Clicking Look Up takes you to a web page about that particular function.') . '</p>' .
'<p id="newcontent-description">' . __('In the editing area the Tab key enters a tab character. To move below this area by pressing Tab, press the Esc key followed by the Tab key.') . '</p>' .
'<p>' . __('If you want to make changes but don’t want them to be overwritten when the plugin is updated, you may be ready to think about writing your own plugin. For information on how to edit plugins, write your own from scratch, or just better understand their anatomy, check out the links below.') . '</p>' .
( is_network_admin() ? '<p>' . __('Any edits to files from this screen will be reflected on all sites in the network.') . '</p>' : '' )
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Plugins_Editor_Screen" target="_blank">Documentation on Editing Plugins</a>') . '</p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Writing_a_Plugin" target="_blank">Documentation on Writing Plugins</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
require_once(ABSPATH . 'wp-admin/admin-header.php');
update_recently_edited(WP_PLUGIN_DIR . '/' . $file);
$content = file_get_contents( $real_file );
if ( '.php' == substr( $real_file, strrpos( $real_file, '.' ) ) ) {
$functions = wp_doc_link_parse( $content );
if ( !empty($functions) ) {
$docs_select = '<select name="docs-list" id="docs-list">';
$docs_select .= '<option value="">' . __( 'Function Name…' ) . '</option>';
foreach ( $functions as $function) {
$docs_select .= '<option value="' . esc_attr( $function ) . '">' . esc_html( $function ) . '()</option>';
}
$docs_select .= '</select>';
}
}
$content = esc_textarea( $content );
?>
<?php if (isset($_GET['a'])) : ?>
<div id="message" class="updated"><p><?php _e('File edited successfully.') ?></p></div>
<?php elseif (isset($_GET['phperror'])) : ?>
<div id="message" class="updated"><p><?php _e('This plugin has been deactivated because your changes resulted in a <strong>fatal error</strong>.') ?></p>
<?php
if ( wp_verify_nonce($_GET['_error_nonce'], 'plugin-activation-error_' . $file) ) { ?>
<iframe style="border:0" width="100%" height="70px" src="<?php bloginfo('wpurl'); ?>/wp-admin/plugins.php?action=error_scrape&plugin=<?php echo esc_attr($file); ?>&_wpnonce=<?php echo esc_attr($_GET['_error_nonce']); ?>"></iframe>
<?php } ?>
</div>
<?php endif; ?>
<div class="wrap">
<h2><?php echo esc_html( $title ); ?></h2>
<div class="fileedit-sub">
<div class="alignleft">
<big><?php
if ( is_plugin_active($plugin) ) {
if ( is_writeable($real_file) )
echo sprintf(__('Editing <strong>%s</strong> (active)'), $file);
else
echo sprintf(__('Browsing <strong>%s</strong> (active)'), $file);
} else {
if ( is_writeable($real_file) )
echo sprintf(__('Editing <strong>%s</strong> (inactive)'), $file);
else
echo sprintf(__('Browsing <strong>%s</strong> (inactive)'), $file);
}
?></big>
</div>
<div class="alignright">
<form action="plugin-editor.php" method="post">
<strong><label for="plugin"><?php _e('Select plugin to edit:'); ?> </label></strong>
<select name="plugin" id="plugin">
<?php
foreach ( $plugins as $plugin_key => $a_plugin ) {
$plugin_name = $a_plugin['Name'];
if ( $plugin_key == $plugin )
$selected = " selected='selected'";
else
$selected = '';
$plugin_name = esc_attr($plugin_name);
$plugin_key = esc_attr($plugin_key);
echo "\n\t<option value=\"$plugin_key\" $selected>$plugin_name</option>";
}
?>
</select>
<?php submit_button( __( 'Select' ), 'button', 'Submit', false ); ?>
</form>
</div>
<br class="clear" />
</div>
<div id="templateside">
<h3><?php _e('Plugin Files'); ?></h3>
<ul>
<?php
foreach ( $plugin_files as $plugin_file ) :
// Get the extension of the file
if ( preg_match('/\.([^.]+)$/', $plugin_file, $matches) ) {
$ext = strtolower($matches[1]);
// If extension is not in the acceptable list, skip it
if ( !in_array( $ext, $editable_extensions ) )
continue;
} else {
// No extension found
continue;
}
?>
<li<?php echo $file == $plugin_file ? ' class="highlight"' : ''; ?>><a href="plugin-editor.php?file=<?php echo urlencode( $plugin_file ) ?>&plugin=<?php echo urlencode( $plugin ) ?>"><?php echo $plugin_file ?></a></li>
<?php endforeach; ?>
</ul>
</div>
<form name="template" id="template" action="plugin-editor.php" method="post">
<?php wp_nonce_field('edit-plugin_' . $file) ?>
<div><textarea cols="70" rows="25" name="newcontent" id="newcontent" aria-describedby="newcontent-description"><?php echo $content; ?></textarea>
<input type="hidden" name="action" value="update" />
<input type="hidden" name="file" value="<?php echo esc_attr($file) ?>" />
<input type="hidden" name="plugin" value="<?php echo esc_attr($plugin) ?>" />
<input type="hidden" name="scrollto" id="scrollto" value="<?php echo $scrollto; ?>" />
</div>
<?php if ( !empty( $docs_select ) ) : ?>
<div id="documentation" class="hide-if-no-js"><label for="docs-list"><?php _e('Documentation:') ?></label> <?php echo $docs_select ?> <input type="button" class="button" value="<?php esc_attr_e( 'Look Up' ) ?> " onclick="if ( '' != jQuery('#docs-list').val() ) { window.open( 'http://api.wordpress.org/core/handbook/1.0/?function=' + escape( jQuery( '#docs-list' ).val() ) + '&locale=<?php echo urlencode( get_locale() ) ?>&version=<?php echo urlencode( $wp_version ) ?>&redirect=true'); }" /></div>
<?php endif; ?>
<?php if ( is_writeable($real_file) ) : ?>
<?php if ( in_array( $file, (array) get_option( 'active_plugins', array() ) ) ) { ?>
<p><?php _e('<strong>Warning:</strong> Making changes to active plugins is not recommended. If your changes cause a fatal error, the plugin will be automatically deactivated.'); ?></p>
<?php } ?>
<p class="submit">
<?php
if ( isset($_GET['phperror']) ) {
echo "<input type='hidden' name='phperror' value='1' />";
submit_button( __( 'Update File and Attempt to Reactivate' ), 'primary', 'submit', false );
} else {
submit_button( __( 'Update File' ), 'primary', 'submit', false );
}
?>
</p>
<?php else : ?>
<p><em><?php _e('You need to make this file writable before you can save your changes. See <a href="http://codex.wordpress.org/Changing_File_Permissions">the Codex</a> for more information.'); ?></em></p>
<?php endif; ?>
</form>
<br class="clear" />
</div>
<script type="text/javascript">
jQuery(document).ready(function($){
$('#template').submit(function(){ $('#scrollto').val( $('#newcontent').scrollTop() ); });
$('#newcontent').scrollTop( $('#scrollto').val() );
});
</script>
<?php
break;
}
include(ABSPATH . "wp-admin/admin-footer.php");
| 01-wordpress-paypal | trunk/wp-admin/plugin-editor.php | PHP | gpl3 | 11,410 |
<?php
/**
* WordPress Generic Request (POST/GET) Handler
*
* Intended for form submission handling in themes and plugins.
*
* @package WordPress
* @subpackage Administration
*/
/** We are located in WordPress Administration Screens */
define('WP_ADMIN', true);
if ( defined('ABSPATH') )
require_once(ABSPATH . 'wp-load.php');
else
require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );
/** Allow for cross-domain requests (from the frontend). */
send_origin_headers();
require_once(ABSPATH . 'wp-admin/includes/admin.php');
nocache_headers();
/** This action is documented in wp-admin/admin.php */
do_action( 'admin_init' );
$action = 'admin_post';
if ( !wp_validate_auth_cookie() )
$action .= '_nopriv';
if ( !empty($_REQUEST['action']) )
$action .= '_' . $_REQUEST['action'];
/**
* Fires the requested handler action.
*
* admin_post_nopriv_{$_REQUEST['action']} is called for not-logged-in users.
* admin_post_{$_REQUEST['action']} is called for logged-in users.
*
* @since 2.6.0
*/
do_action( $action );
| 01-wordpress-paypal | trunk/wp-admin/admin-post.php | PHP | gpl3 | 1,045 |
<?php
/**
* Database Repair and Optimization Script.
*
* @package WordPress
* @subpackage Database
*/
define('WP_REPAIRING', true);
require_once( dirname( dirname( dirname( __FILE__ ) ) ) . '/wp-load.php' );
header( 'Content-Type: text/html; charset=utf-8' );
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>
<head>
<meta name="viewport" content="width=device-width" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title><?php _e( 'WordPress › Database Repair' ); ?></title>
<?php
wp_admin_css( 'install', true );
?>
</head>
<body class="wp-core-ui">
<h1 id="logo"><a href="<?php echo esc_url( __( 'https://wordpress.org/' ) ); ?>"><?php _e( 'WordPress' ); ?></a></h1>
<?php
if ( ! defined( 'WP_ALLOW_REPAIR' ) ) {
echo '<p>' . __( 'To allow use of this page to automatically repair database problems, please add the following line to your <code>wp-config.php</code> file. Once this line is added to your config, reload this page.' ) . "</p><p><code>define('WP_ALLOW_REPAIR', true);</code></p>";
} elseif ( isset( $_GET['repair'] ) ) {
$optimize = 2 == $_GET['repair'];
$okay = true;
$problems = array();
$tables = $wpdb->tables();
// Sitecategories may not exist if global terms are disabled.
if ( is_multisite() && ! $wpdb->get_var( "SHOW TABLES LIKE '$wpdb->sitecategories'" ) )
unset( $tables['sitecategories'] );
/**
* Filter additional database tables to repair.
*
* @since 3.0.0
*
* @param array $tables Array of prefixed table names to be repaired.
*/
$tables = array_merge( $tables, (array) apply_filters( 'tables_to_repair', array() ) );
// Loop over the tables, checking and repairing as needed.
foreach ( $tables as $table ) {
$check = $wpdb->get_row( "CHECK TABLE $table" );
echo '<p>';
if ( 'OK' == $check->Msg_text ) {
/* translators: %s: table name */
printf( __( 'The %s table is okay.' ), "<code>$table</code>" );
} else {
/* translators: 1: table name, 2: error message, */
printf( __( 'The %1$s table is not okay. It is reporting the following error: %2$s. WordPress will attempt to repair this table…' ) , "<code>$table</code>", "<code>$check->Msg_text</code>" );
$repair = $wpdb->get_row( "REPAIR TABLE $table" );
echo '<br /> ';
if ( 'OK' == $check->Msg_text ) {
/* translators: %s: table name */
printf( __( 'Successfully repaired the %s table.' ), "<code>$table</code>" );
} else {
/* translators: 1: table name, 2: error message, */
echo sprintf( __( 'Failed to repair the %1$s table. Error: %2$s' ), "<code>$table</code>", "<code>$check->Msg_text</code>" ) . '<br />';
$problems[$table] = $check->Msg_text;
$okay = false;
}
}
if ( $okay && $optimize ) {
$check = $wpdb->get_row( "ANALYZE TABLE $table" );
echo '<br /> ';
if ( 'Table is already up to date' == $check->Msg_text ) {
/* translators: %s: table name */
printf( __( 'The %s table is already optimized.' ), "<code>$table</code>" );
} else {
$check = $wpdb->get_row( "OPTIMIZE TABLE $table" );
echo '<br /> ';
if ( 'OK' == $check->Msg_text || 'Table is already up to date' == $check->Msg_text ) {
/* translators: %s: table name */
printf( __( 'Successfully optimized the %s table.' ), "<code>$table</code>" );
} else {
/* translators: 1: table name, 2: error message, */
printf( __( 'Failed to optimize the %1$s table. Error: %2$s' ), "<code>$table</code>", "<code>$check->Msg_text</code>" );
}
}
}
echo '</p>';
}
if ( $problems ) {
printf( '<p>' . __('Some database problems could not be repaired. Please copy-and-paste the following list of errors to the <a href="%s">WordPress support forums</a> to get additional assistance.') . '</p>', __( 'https://wordpress.org/support/forum/how-to-and-troubleshooting' ) );
$problem_output = '';
foreach ( $problems as $table => $problem )
$problem_output .= "$table: $problem\n";
echo '<p><textarea name="errors" id="errors" rows="20" cols="60">' . esc_textarea( $problem_output ) . '</textarea></p>';
} else {
echo '<p>' . __( 'Repairs complete. Please remove the following line from wp-config.php to prevent this page from being used by unauthorized users.' ) . "</p><p><code>define('WP_ALLOW_REPAIR', true);</code></p>";
}
} else {
if ( isset( $_GET['referrer'] ) && 'is_blog_installed' == $_GET['referrer'] )
echo '<p>' . __( 'One or more database tables are unavailable. To allow WordPress to attempt to repair these tables, press the “Repair Database” button. Repairing can take a while, so please be patient.' ) . '</p>';
else
echo '<p>' . __( 'WordPress can automatically look for some common database problems and repair them. Repairing can take a while, so please be patient.' ) . '</p>';
?>
<p class="step"><a class="button button-large" href="repair.php?repair=1"><?php _e( 'Repair Database' ); ?></a></p>
<p><?php _e( 'WordPress can also attempt to optimize the database. This improves performance in some situations. Repairing and optimizing the database can take a long time and the database will be locked while optimizing.' ); ?></p>
<p class="step"><a class="button button-large" href="repair.php?repair=2"><?php _e( 'Repair and Optimize Database' ); ?></a></p>
<?php
}
?>
</body>
</html>
| 01-wordpress-paypal | trunk/wp-admin/maint/repair.php | PHP | gpl3 | 5,409 |
<?php
/**
* Your Rights administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
$title = __( 'Freedoms' );
list( $display_version ) = explode( '-', $wp_version );
include( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap about-wrap">
<h1><?php printf( __( 'Welcome to WordPress %s' ), $display_version ); ?></h1>
<div class="about-text"><?php printf( __( 'Thank you for updating to WordPress %s, the most beautiful WordPress yet.' ), $display_version ); ?></div>
<div class="wp-badge"><?php printf( __( 'Version %s' ), $display_version ); ?></div>
<h2 class="nav-tab-wrapper">
<a href="about.php" class="nav-tab">
<?php _e( 'What’s New' ); ?>
</a><a href="credits.php" class="nav-tab">
<?php _e( 'Credits' ); ?>
</a><a href="freedoms.php" class="nav-tab nav-tab-active">
<?php _e( 'Freedoms' ); ?>
</a>
</h2>
<p class="about-description"><?php printf( __( 'WordPress is Free and open source software, built by a distributed community of mostly volunteer developers from around the world. WordPress comes with some awesome, worldview-changing rights courtesy of its <a href="%s">license</a>, the GPL.' ), 'https://wordpress.org/about/license/' ); ?></p>
<ol start="0">
<li><p><?php _e( 'You have the freedom to run the program, for any purpose.' ); ?></p></li>
<li><p><?php _e( 'You have access to the source code, the freedom to study how the program works, and the freedom to change it to make it do what you wish.' ); ?></p></li>
<li><p><?php _e( 'You have the freedom to redistribute copies of the original program so you can help your neighbor.' ); ?></p></li>
<li><p><?php _e( 'You have the freedom to distribute copies of your modified versions to others. By doing this you can give the whole community a chance to benefit from your changes.' ); ?></p></li>
</ol>
<p><?php printf( __( 'WordPress grows when people like you tell their friends about it, and the thousands of businesses and services that are built on and around WordPress share that fact with their users. We’re flattered every time someone spreads the good word, just make sure to <a href="%s">check out our trademark guidelines</a> first.' ), 'http://wordpressfoundation.org/trademark-policy/' ); ?></p>
<p><?php
$plugins_url = current_user_can( 'activate_plugins' ) ? admin_url( 'plugins.php' ) : 'https://wordpress.org/plugins/';
$themes_url = current_user_can( 'switch_themes' ) ? admin_url( 'themes.php' ) : 'https://wordpress.org/themes/';
printf( __( 'Every plugin and theme in WordPress.org’s directory is 100%% GPL or a similarly free and compatible license, so you can feel safe finding <a href="%1$s">plugins</a> and <a href="%2$s">themes</a> there. If you get a plugin or theme from another source, make sure to <a href="%3$s">ask them if it’s GPL</a> first. If they don’t respect the WordPress license, we don’t recommend them.' ), $plugins_url, $themes_url, 'https://wordpress.org/about/license/' ); ?></p>
<p><?php _e( 'Don’t you wish all software came with these freedoms? So do we! For more information, check out the <a href="http://www.fsf.org/">Free Software Foundation</a>.' ); ?></p>
</div>
<?php include( ABSPATH . 'wp-admin/admin-footer.php' ); ?>
| 01-wordpress-paypal | trunk/wp-admin/freedoms.php | PHP | gpl3 | 3,352 |
<?php
/**
* Plugins administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! current_user_can('activate_plugins') )
wp_die( __( 'You do not have sufficient permissions to manage plugins for this site.' ) );
$wp_list_table = _get_list_table('WP_Plugins_List_Table');
$pagenum = $wp_list_table->get_pagenum();
$action = $wp_list_table->current_action();
$plugin = isset($_REQUEST['plugin']) ? $_REQUEST['plugin'] : '';
$s = isset($_REQUEST['s']) ? urlencode($_REQUEST['s']) : '';
// Clean up request URI from temporary args for screen options/paging uri's to work as expected.
$_SERVER['REQUEST_URI'] = remove_query_arg(array('error', 'deleted', 'activate', 'activate-multi', 'deactivate', 'deactivate-multi', '_error_nonce'), $_SERVER['REQUEST_URI']);
if ( $action ) {
switch ( $action ) {
case 'activate':
if ( ! current_user_can('activate_plugins') )
wp_die(__('You do not have sufficient permissions to activate plugins for this site.'));
if ( is_multisite() && ! is_network_admin() && is_network_only_plugin( $plugin ) ) {
wp_redirect( self_admin_url("plugins.php?plugin_status=$status&paged=$page&s=$s") );
exit;
}
check_admin_referer('activate-plugin_' . $plugin);
$result = activate_plugin($plugin, self_admin_url('plugins.php?error=true&plugin=' . $plugin), is_network_admin() );
if ( is_wp_error( $result ) ) {
if ( 'unexpected_output' == $result->get_error_code() ) {
$redirect = self_admin_url('plugins.php?error=true&charsout=' . strlen($result->get_error_data()) . '&plugin=' . $plugin . "&plugin_status=$status&paged=$page&s=$s");
wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect));
exit;
} else {
wp_die($result);
}
}
if ( ! is_network_admin() ) {
$recent = (array) get_option( 'recently_activated' );
unset( $recent[ $plugin ] );
update_option( 'recently_activated', $recent );
}
if ( isset($_GET['from']) && 'import' == $_GET['from'] ) {
wp_redirect( self_admin_url("import.php?import=" . str_replace('-importer', '', dirname($plugin))) ); // overrides the ?error=true one above and redirects to the Imports page, stripping the -importer suffix
} else {
wp_redirect( self_admin_url("plugins.php?activate=true&plugin_status=$status&paged=$page&s=$s") ); // overrides the ?error=true one above
}
exit;
break;
case 'activate-selected':
if ( ! current_user_can('activate_plugins') )
wp_die(__('You do not have sufficient permissions to activate plugins for this site.'));
check_admin_referer('bulk-plugins');
$plugins = isset( $_POST['checked'] ) ? (array) $_POST['checked'] : array();
if ( is_network_admin() ) {
foreach ( $plugins as $i => $plugin ) {
// Only activate plugins which are not already network activated.
if ( is_plugin_active_for_network( $plugin ) ) {
unset( $plugins[ $i ] );
}
}
} else {
foreach ( $plugins as $i => $plugin ) {
// Only activate plugins which are not already active and are not network-only when on Multisite.
if ( is_plugin_active( $plugin ) || ( is_multisite() && is_network_only_plugin( $plugin ) ) ) {
unset( $plugins[ $i ] );
}
}
}
if ( empty($plugins) ) {
wp_redirect( self_admin_url("plugins.php?plugin_status=$status&paged=$page&s=$s") );
exit;
}
activate_plugins($plugins, self_admin_url('plugins.php?error=true'), is_network_admin() );
if ( ! is_network_admin() ) {
$recent = (array) get_option('recently_activated' );
foreach ( $plugins as $plugin )
unset( $recent[ $plugin ] );
update_option( 'recently_activated', $recent );
}
wp_redirect( self_admin_url("plugins.php?activate-multi=true&plugin_status=$status&paged=$page&s=$s") );
exit;
break;
case 'update-selected' :
check_admin_referer( 'bulk-plugins' );
if ( isset( $_GET['plugins'] ) )
$plugins = explode( ',', $_GET['plugins'] );
elseif ( isset( $_POST['checked'] ) )
$plugins = (array) $_POST['checked'];
else
$plugins = array();
$title = __( 'Update Plugins' );
$parent_file = 'plugins.php';
wp_enqueue_script( 'updates' );
require_once(ABSPATH . 'wp-admin/admin-header.php');
echo '<div class="wrap">';
echo '<h2>' . esc_html( $title ) . '</h2>';
$url = self_admin_url('update.php?action=update-selected&plugins=' . urlencode( join(',', $plugins) ));
$url = wp_nonce_url($url, 'bulk-update-plugins');
echo "<iframe src='$url' style='width: 100%; height:100%; min-height:850px;'></iframe>";
echo '</div>';
require_once(ABSPATH . 'wp-admin/admin-footer.php');
exit;
break;
case 'error_scrape':
if ( ! current_user_can('activate_plugins') )
wp_die(__('You do not have sufficient permissions to activate plugins for this site.'));
check_admin_referer('plugin-activation-error_' . $plugin);
$valid = validate_plugin($plugin);
if ( is_wp_error($valid) )
wp_die($valid);
if ( ! WP_DEBUG ) {
error_reporting( E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR );
}
@ini_set('display_errors', true); //Ensure that Fatal errors are displayed.
// Go back to "sandbox" scope so we get the same errors as before
function plugin_sandbox_scrape( $plugin ) {
wp_register_plugin_realpath( WP_PLUGIN_DIR . '/' . $plugin );
include( WP_PLUGIN_DIR . '/' . $plugin );
}
plugin_sandbox_scrape( $plugin );
/** This action is documented in wp-admin/includes/plugins.php */
do_action( "activate_{$plugin}" );
exit;
break;
case 'deactivate':
if ( ! current_user_can('activate_plugins') )
wp_die(__('You do not have sufficient permissions to deactivate plugins for this site.'));
check_admin_referer('deactivate-plugin_' . $plugin);
if ( ! is_network_admin() && is_plugin_active_for_network( $plugin ) ) {
wp_redirect( self_admin_url("plugins.php?plugin_status=$status&paged=$page&s=$s") );
exit;
}
deactivate_plugins( $plugin, false, is_network_admin() );
if ( ! is_network_admin() )
update_option( 'recently_activated', array( $plugin => time() ) + (array) get_option( 'recently_activated' ) );
if ( headers_sent() )
echo "<meta http-equiv='refresh' content='" . esc_attr( "0;url=plugins.php?deactivate=true&plugin_status=$status&paged=$page&s=$s" ) . "' />";
else
wp_redirect( self_admin_url("plugins.php?deactivate=true&plugin_status=$status&paged=$page&s=$s") );
exit;
break;
case 'deactivate-selected':
if ( ! current_user_can('activate_plugins') )
wp_die(__('You do not have sufficient permissions to deactivate plugins for this site.'));
check_admin_referer('bulk-plugins');
$plugins = isset( $_POST['checked'] ) ? (array) $_POST['checked'] : array();
// Do not deactivate plugins which are already deactivated.
if ( is_network_admin() ) {
$plugins = array_filter( $plugins, 'is_plugin_active_for_network' );
} else {
$plugins = array_filter( $plugins, 'is_plugin_active' );
$plugins = array_diff( $plugins, array_filter( $plugins, 'is_plugin_active_for_network' ) );
}
if ( empty($plugins) ) {
wp_redirect( self_admin_url("plugins.php?plugin_status=$status&paged=$page&s=$s") );
exit;
}
deactivate_plugins( $plugins, false, is_network_admin() );
if ( ! is_network_admin() ) {
$deactivated = array();
foreach ( $plugins as $plugin )
$deactivated[ $plugin ] = time();
update_option( 'recently_activated', $deactivated + (array) get_option( 'recently_activated' ) );
}
wp_redirect( self_admin_url("plugins.php?deactivate-multi=true&plugin_status=$status&paged=$page&s=$s") );
exit;
break;
case 'delete-selected':
if ( ! current_user_can('delete_plugins') )
wp_die(__('You do not have sufficient permissions to delete plugins for this site.'));
check_admin_referer('bulk-plugins');
//$_POST = from the plugin form; $_GET = from the FTP details screen.
$plugins = isset( $_REQUEST['checked'] ) ? (array) $_REQUEST['checked'] : array();
if ( empty( $plugins ) ) {
wp_redirect( self_admin_url("plugins.php?plugin_status=$status&paged=$page&s=$s") );
exit;
}
$plugins = array_filter($plugins, 'is_plugin_inactive'); // Do not allow to delete Activated plugins.
if ( empty( $plugins ) ) {
wp_redirect( self_admin_url( "plugins.php?error=true&main=true&plugin_status=$status&paged=$page&s=$s" ) );
exit;
}
include(ABSPATH . 'wp-admin/update.php');
$parent_file = 'plugins.php';
if ( ! isset($_REQUEST['verify-delete']) ) {
wp_enqueue_script('jquery');
require_once(ABSPATH . 'wp-admin/admin-header.php');
?>
<div class="wrap">
<?php
$files_to_delete = $plugin_info = array();
$have_non_network_plugins = false;
foreach ( (array) $plugins as $plugin ) {
if ( '.' == dirname($plugin) ) {
$files_to_delete[] = WP_PLUGIN_DIR . '/' . $plugin;
if( $data = get_plugin_data(WP_PLUGIN_DIR . '/' . $plugin) ) {
$plugin_info[ $plugin ] = $data;
$plugin_info[ $plugin ]['is_uninstallable'] = is_uninstallable_plugin( $plugin );
if ( ! $plugin_info[ $plugin ]['Network'] )
$have_non_network_plugins = true;
}
} else {
// Locate all the files in that folder
$files = list_files( WP_PLUGIN_DIR . '/' . dirname($plugin) );
if ( $files ) {
$files_to_delete = array_merge($files_to_delete, $files);
}
// Get plugins list from that folder
if ( $folder_plugins = get_plugins( '/' . dirname($plugin)) ) {
foreach( $folder_plugins as $plugin_file => $data ) {
$plugin_info[ $plugin_file ] = _get_plugin_data_markup_translate( $plugin_file, $data );
$plugin_info[ $plugin_file ]['is_uninstallable'] = is_uninstallable_plugin( $plugin );
if ( ! $plugin_info[ $plugin_file ]['Network'] )
$have_non_network_plugins = true;
}
}
}
}
$plugins_to_delete = count( $plugin_info );
echo '<h2>' . _n( 'Delete Plugin', 'Delete Plugins', $plugins_to_delete ) . '</h2>';
?>
<?php if ( $have_non_network_plugins && is_network_admin() ) : ?>
<div class="error"><p><strong><?php _e( 'Caution:' ); ?></strong> <?php echo _n( 'This plugin may be active on other sites in the network.', 'These plugins may be active on other sites in the network.', $plugins_to_delete ); ?></p></div>
<?php endif; ?>
<p><?php echo _n( 'You are about to remove the following plugin:', 'You are about to remove the following plugins:', $plugins_to_delete ); ?></p>
<ul class="ul-disc">
<?php
$data_to_delete = false;
foreach ( $plugin_info as $plugin ) {
if ( $plugin['is_uninstallable'] ) {
/* translators: 1: plugin name, 2: plugin author */
echo '<li>', sprintf( __( '<strong>%1$s</strong> by <em>%2$s</em> (will also <strong>delete its data</strong>)' ), esc_html($plugin['Name']), esc_html($plugin['AuthorName']) ), '</li>';
$data_to_delete = true;
} else {
/* translators: 1: plugin name, 2: plugin author */
echo '<li>', sprintf( __('<strong>%1$s</strong> by <em>%2$s</em>' ), esc_html($plugin['Name']), esc_html($plugin['AuthorName']) ), '</li>';
}
}
?>
</ul>
<p><?php
if ( $data_to_delete )
_e('Are you sure you wish to delete these files and data?');
else
_e('Are you sure you wish to delete these files?');
?></p>
<form method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" style="display:inline;">
<input type="hidden" name="verify-delete" value="1" />
<input type="hidden" name="action" value="delete-selected" />
<?php
foreach ( (array) $plugins as $plugin )
echo '<input type="hidden" name="checked[]" value="' . esc_attr($plugin) . '" />';
?>
<?php wp_nonce_field('bulk-plugins') ?>
<?php submit_button( $data_to_delete ? __( 'Yes, Delete these files and data' ) : __( 'Yes, Delete these files' ), 'button', 'submit', false ); ?>
</form>
<form method="post" action="<?php echo esc_url(wp_get_referer()); ?>" style="display:inline;">
<?php submit_button( __( 'No, Return me to the plugin list' ), 'button', 'submit', false ); ?>
</form>
<p><a href="#" onclick="jQuery('#files-list').toggle(); return false;"><?php _e('Click to view entire list of files which will be deleted'); ?></a></p>
<div id="files-list" style="display:none;">
<ul class="code">
<?php
foreach ( (array)$files_to_delete as $file )
echo '<li>' . esc_html(str_replace(WP_PLUGIN_DIR, '', $file)) . '</li>';
?>
</ul>
</div>
</div>
<?php
require_once(ABSPATH . 'wp-admin/admin-footer.php');
exit;
} //Endif verify-delete
$delete_result = delete_plugins($plugins);
set_transient('plugins_delete_result_' . $user_ID, $delete_result); //Store the result in a cache rather than a URL param due to object type & length
wp_redirect( self_admin_url("plugins.php?deleted=true&plugin_status=$status&paged=$page&s=$s") );
exit;
break;
case 'clear-recent-list':
if ( ! is_network_admin() )
update_option( 'recently_activated', array() );
break;
}
}
$wp_list_table->prepare_items();
wp_enqueue_script('plugin-install');
add_thickbox();
add_screen_option( 'per_page', array('label' => _x( 'Plugins', 'plugins per page (screen options)' ), 'default' => 999 ) );
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('Plugins extend and expand the functionality of WordPress. Once a plugin is installed, you may activate it or deactivate it here.') . '</p>' .
'<p>' . sprintf(__('You can find additional plugins for your site by using the <a href="%1$s">Plugin Browser/Installer</a> functionality or by browsing the <a href="%2$s" target="_blank">WordPress Plugin Directory</a> directly and installing new plugins manually. To manually install a plugin you generally just need to upload the plugin file into your <code>/wp-content/plugins</code> directory. Once a plugin has been installed, you can activate it here.'), 'plugin-install.php', 'https://wordpress.org/plugins/') . '</p>'
) );
get_current_screen()->add_help_tab( array(
'id' => 'compatibility-problems',
'title' => __('Troubleshooting'),
'content' =>
'<p>' . __('Most of the time, plugins play nicely with the core of WordPress and with other plugins. Sometimes, though, a plugin’s code will get in the way of another plugin, causing compatibility issues. If your site starts doing strange things, this may be the problem. Try deactivating all your plugins and re-activating them in various combinations until you isolate which one(s) caused the issue.') . '</p>' .
'<p>' . sprintf( __('If something goes wrong with a plugin and you can’t use WordPress, delete or rename that file in the <code>%s</code> directory and it will be automatically deactivated.'), WP_PLUGIN_DIR) . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Managing_Plugins#Plugin_Management" target="_blank">Documentation on Managing Plugins</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
$title = __('Plugins');
$parent_file = 'plugins.php';
require_once(ABSPATH . 'wp-admin/admin-header.php');
$invalid = validate_active_plugins();
if ( !empty($invalid) )
foreach ( $invalid as $plugin_file => $error )
echo '<div id="message" class="error"><p>' . sprintf(__('The plugin <code>%s</code> has been <strong>deactivated</strong> due to an error: %s'), esc_html($plugin_file), $error->get_error_message()) . '</p></div>';
?>
<?php if ( isset($_GET['error']) ) :
if ( isset( $_GET['main'] ) )
$errmsg = __( 'You cannot delete a plugin while it is active on the main site.' );
elseif ( isset($_GET['charsout']) )
$errmsg = sprintf(__('The plugin generated %d characters of <strong>unexpected output</strong> during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.'), $_GET['charsout']);
else
$errmsg = __('Plugin could not be activated because it triggered a <strong>fatal error</strong>.');
?>
<div id="message" class="updated"><p><?php echo $errmsg; ?></p>
<?php
if ( !isset( $_GET['main'] ) && !isset($_GET['charsout']) && wp_verify_nonce($_GET['_error_nonce'], 'plugin-activation-error_' . $plugin) ) { ?>
<iframe style="border:0" width="100%" height="70px" src="<?php echo 'plugins.php?action=error_scrape&plugin=' . esc_attr($plugin) . '&_wpnonce=' . esc_attr($_GET['_error_nonce']); ?>"></iframe>
<?php
}
?>
</div>
<?php elseif ( isset($_GET['deleted']) ) :
$delete_result = get_transient( 'plugins_delete_result_' . $user_ID );
// Delete it once we're done.
delete_transient( 'plugins_delete_result_' . $user_ID );
if ( is_wp_error($delete_result) ) : ?>
<div id="message" class="updated"><p><?php printf( __('Plugin could not be deleted due to an error: %s'), $delete_result->get_error_message() ); ?></p></div>
<?php else : ?>
<div id="message" class="updated"><p><?php _e('The selected plugins have been <strong>deleted</strong>.'); ?></p></div>
<?php endif; ?>
<?php elseif ( isset($_GET['activate']) ) : ?>
<div id="message" class="updated"><p><?php _e('Plugin <strong>activated</strong>.') ?></p></div>
<?php elseif (isset($_GET['activate-multi'])) : ?>
<div id="message" class="updated"><p><?php _e('Selected plugins <strong>activated</strong>.'); ?></p></div>
<?php elseif ( isset($_GET['deactivate']) ) : ?>
<div id="message" class="updated"><p><?php _e('Plugin <strong>deactivated</strong>.') ?></p></div>
<?php elseif (isset($_GET['deactivate-multi'])) : ?>
<div id="message" class="updated"><p><?php _e('Selected plugins <strong>deactivated</strong>.'); ?></p></div>
<?php elseif ( 'update-selected' == $action ) : ?>
<div id="message" class="updated"><p><?php _e('No out of date plugins were selected.'); ?></p></div>
<?php endif; ?>
<div class="wrap">
<h2><?php echo esc_html( $title );
if ( ( ! is_multisite() || is_network_admin() ) && current_user_can('install_plugins') ) { ?>
<a href="<?php echo self_admin_url( 'plugin-install.php' ); ?>" class="add-new-h2"><?php echo esc_html_x('Add New', 'plugin'); ?></a>
<?php }
if ( $s )
printf( '<span class="subtitle">' . __('Search results for “%s”') . '</span>', esc_html( $s ) ); ?>
</h2>
<?php
/**
* Fires before the plugins list table is rendered.
*
* This hook also fires before the plugins list table is rendered in the Network Admin.
*
* Please note: The 'active' portion of the hook name does not refer to whether the current
* view is for active plugins, but rather all plugins actively-installed.
*
* @since 3.0.0
*
* @param array $plugins_all An array containing all installed plugins.
*/
do_action( 'pre_current_active_plugins', $plugins['all'] );
?>
<?php $wp_list_table->views(); ?>
<form method="get" action="">
<?php $wp_list_table->search_box( __( 'Search Installed Plugins' ), 'plugin' ); ?>
</form>
<form method="post" action="">
<input type="hidden" name="plugin_status" value="<?php echo esc_attr($status) ?>" />
<input type="hidden" name="paged" value="<?php echo esc_attr($page) ?>" />
<?php $wp_list_table->display(); ?>
</form>
</div>
<?php
include(ABSPATH . 'wp-admin/admin-footer.php');
| 01-wordpress-paypal | trunk/wp-admin/plugins.php | PHP | gpl3 | 19,830 |
<?php
/**
* Edit post administration panel.
*
* Manage Post actions: post, edit, delete, etc.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
$parent_file = 'edit.php';
$submenu_file = 'edit.php';
wp_reset_vars( array( 'action' ) );
if ( isset( $_GET['post'] ) )
$post_id = $post_ID = (int) $_GET['post'];
elseif ( isset( $_POST['post_ID'] ) )
$post_id = $post_ID = (int) $_POST['post_ID'];
else
$post_id = $post_ID = 0;
$post = $post_type = $post_type_object = null;
if ( $post_id )
$post = get_post( $post_id );
if ( $post ) {
$post_type = $post->post_type;
$post_type_object = get_post_type_object( $post_type );
}
/**
* Redirect to previous page.
*
* @param int $post_id Optional. Post ID.
*/
function redirect_post($post_id = '') {
if ( isset($_POST['save']) || isset($_POST['publish']) ) {
$status = get_post_status( $post_id );
if ( isset( $_POST['publish'] ) ) {
switch ( $status ) {
case 'pending':
$message = 8;
break;
case 'future':
$message = 9;
break;
default:
$message = 6;
}
} else {
$message = 'draft' == $status ? 10 : 1;
}
$location = add_query_arg( 'message', $message, get_edit_post_link( $post_id, 'url' ) );
} elseif ( isset($_POST['addmeta']) && $_POST['addmeta'] ) {
$location = add_query_arg( 'message', 2, wp_get_referer() );
$location = explode('#', $location);
$location = $location[0] . '#postcustom';
} elseif ( isset($_POST['deletemeta']) && $_POST['deletemeta'] ) {
$location = add_query_arg( 'message', 3, wp_get_referer() );
$location = explode('#', $location);
$location = $location[0] . '#postcustom';
} else {
$location = add_query_arg( 'message', 4, get_edit_post_link( $post_id, 'url' ) );
}
/**
* Filter the post redirect destination URL.
*
* @since 2.9.0
*
* @param string $location The destination URL.
* @param int $post_id The post ID.
*/
wp_redirect( apply_filters( 'redirect_post_location', $location, $post_id ) );
exit;
}
if ( isset( $_POST['deletepost'] ) )
$action = 'delete';
elseif ( isset($_POST['wp-preview']) && 'dopreview' == $_POST['wp-preview'] )
$action = 'preview';
$sendback = wp_get_referer();
if ( ! $sendback ||
strpos( $sendback, 'post.php' ) !== false ||
strpos( $sendback, 'post-new.php' ) !== false ) {
if ( 'attachment' == $post_type ) {
$sendback = admin_url( 'upload.php' );
} else {
$sendback = admin_url( 'edit.php' );
$sendback .= ( ! empty( $post_type ) ) ? '?post_type=' . $post_type : '';
}
} else {
$sendback = remove_query_arg( array('trashed', 'untrashed', 'deleted', 'ids'), $sendback );
}
switch($action) {
case 'post-quickdraft-save':
// Check nonce and capabilities
$nonce = $_REQUEST['_wpnonce'];
$error_msg = false;
// For output of the quickdraft dashboard widget
require_once ABSPATH . 'wp-admin/includes/dashboard.php';
if ( ! wp_verify_nonce( $nonce, 'add-post' ) )
$error_msg = __( 'Unable to submit this form, please refresh and try again.' );
if ( ! current_user_can( 'edit_posts' ) )
$error_msg = __( 'Oops, you don’t have access to add new drafts.' );
if ( $error_msg )
return wp_dashboard_quick_press( $error_msg );
$post = get_post( $_REQUEST['post_ID'] );
check_admin_referer( 'add-' . $post->post_type );
$_POST['comment_status'] = get_option( 'default_comment_status' );
$_POST['ping_status'] = get_option( 'default_ping_status' );
edit_post();
wp_dashboard_quick_press();
exit;
break;
case 'postajaxpost':
case 'post':
check_admin_referer( 'add-' . $post_type );
$post_id = 'postajaxpost' == $action ? edit_post() : write_post();
redirect_post( $post_id );
exit();
break;
case 'edit':
$editing = true;
if ( empty( $post_id ) ) {
wp_redirect( admin_url('post.php') );
exit();
}
if ( ! $post )
wp_die( __( 'You attempted to edit an item that doesn’t exist. Perhaps it was deleted?' ) );
if ( ! $post_type_object )
wp_die( __( 'Unknown post type.' ) );
if ( ! current_user_can( 'edit_post', $post_id ) )
wp_die( __( 'You are not allowed to edit this item.' ) );
if ( 'trash' == $post->post_status )
wp_die( __( 'You can’t edit this item because it is in the Trash. Please restore it and try again.' ) );
if ( ! empty( $_GET['get-post-lock'] ) ) {
wp_set_post_lock( $post_id );
wp_redirect( get_edit_post_link( $post_id, 'url' ) );
exit();
}
$post_type = $post->post_type;
if ( 'post' == $post_type ) {
$parent_file = "edit.php";
$submenu_file = "edit.php";
$post_new_file = "post-new.php";
} elseif ( 'attachment' == $post_type ) {
$parent_file = 'upload.php';
$submenu_file = 'upload.php';
$post_new_file = 'media-new.php';
} else {
if ( isset( $post_type_object ) && $post_type_object->show_in_menu && $post_type_object->show_in_menu !== true )
$parent_file = $post_type_object->show_in_menu;
else
$parent_file = "edit.php?post_type=$post_type";
$submenu_file = "edit.php?post_type=$post_type";
$post_new_file = "post-new.php?post_type=$post_type";
}
if ( ! wp_check_post_lock( $post->ID ) ) {
$active_post_lock = wp_set_post_lock( $post->ID );
if ( 'attachment' !== $post_type )
wp_enqueue_script('autosave');
}
if ( is_multisite() ) {
add_action( 'admin_footer', '_admin_notice_post_locked' );
} else {
$check_users = get_users( array( 'fields' => 'ID', 'number' => 2 ) );
if ( count( $check_users ) > 1 )
add_action( 'admin_footer', '_admin_notice_post_locked' );
unset( $check_users );
}
$title = $post_type_object->labels->edit_item;
$post = get_post($post_id, OBJECT, 'edit');
if ( post_type_supports($post_type, 'comments') ) {
wp_enqueue_script('admin-comments');
enqueue_comment_hotkeys_js();
}
include( ABSPATH . 'wp-admin/edit-form-advanced.php' );
break;
case 'editattachment':
check_admin_referer('update-post_' . $post_id);
// Don't let these be changed
unset($_POST['guid']);
$_POST['post_type'] = 'attachment';
// Update the thumbnail filename
$newmeta = wp_get_attachment_metadata( $post_id, true );
$newmeta['thumb'] = $_POST['thumb'];
wp_update_attachment_metadata( $post_id, $newmeta );
case 'editpost':
check_admin_referer('update-post_' . $post_id);
$post_id = edit_post();
// Session cookie flag that the post was saved
if ( isset( $_COOKIE['wp-saving-post-' . $post_id] ) )
setcookie( 'wp-saving-post-' . $post_id, 'saved' );
redirect_post($post_id); // Send user on their way while we keep working
exit();
break;
case 'trash':
check_admin_referer('trash-post_' . $post_id);
if ( ! $post )
wp_die( __( 'The item you are trying to move to the Trash no longer exists.' ) );
if ( ! $post_type_object )
wp_die( __( 'Unknown post type.' ) );
if ( ! current_user_can( 'delete_post', $post_id ) )
wp_die( __( 'You are not allowed to move this item to the Trash.' ) );
if ( $user_id = wp_check_post_lock( $post_id ) ) {
$user = get_userdata( $user_id );
wp_die( sprintf( __( 'You cannot move this item to the Trash. %s is currently editing.' ), $user->display_name ) );
}
if ( ! wp_trash_post( $post_id ) )
wp_die( __( 'Error in moving to Trash.' ) );
wp_redirect( add_query_arg( array('trashed' => 1, 'ids' => $post_id), $sendback ) );
exit();
break;
case 'untrash':
check_admin_referer('untrash-post_' . $post_id);
if ( ! $post )
wp_die( __( 'The item you are trying to restore from the Trash no longer exists.' ) );
if ( ! $post_type_object )
wp_die( __( 'Unknown post type.' ) );
if ( ! current_user_can( 'delete_post', $post_id ) )
wp_die( __( 'You are not allowed to move this item out of the Trash.' ) );
if ( ! wp_untrash_post( $post_id ) )
wp_die( __( 'Error in restoring from Trash.' ) );
wp_redirect( add_query_arg('untrashed', 1, $sendback) );
exit();
break;
case 'delete':
check_admin_referer('delete-post_' . $post_id);
if ( ! $post )
wp_die( __( 'This item has already been deleted.' ) );
if ( ! $post_type_object )
wp_die( __( 'Unknown post type.' ) );
if ( ! current_user_can( 'delete_post', $post_id ) )
wp_die( __( 'You are not allowed to delete this item.' ) );
$force = ! EMPTY_TRASH_DAYS;
if ( $post->post_type == 'attachment' ) {
$force = ( $force || ! MEDIA_TRASH );
if ( ! wp_delete_attachment( $post_id, $force ) )
wp_die( __( 'Error in deleting.' ) );
} else {
if ( ! wp_delete_post( $post_id, $force ) )
wp_die( __( 'Error in deleting.' ) );
}
wp_redirect( add_query_arg('deleted', 1, $sendback) );
exit();
break;
case 'preview':
check_admin_referer( 'update-post_' . $post_id );
$url = post_preview();
wp_redirect($url);
exit();
break;
default:
wp_redirect( admin_url('edit.php') );
exit();
break;
} // end switch
include( ABSPATH . 'wp-admin/admin-footer.php' );
| 01-wordpress-paypal | trunk/wp-admin/post.php | PHP | gpl3 | 8,848 |
<?php
/**
* WordPress Options Header.
*
* Displays updated message, if updated variable is part of the URL query.
*
* @package WordPress
* @subpackage Administration
*/
wp_reset_vars( array( 'action' ) );
if ( isset( $_GET['updated'] ) && isset( $_GET['page'] ) ) {
// For backwards compat with plugins that don't use the Settings API and just set updated=1 in the redirect
add_settings_error('general', 'settings_updated', __('Settings saved.'), 'updated');
}
settings_errors();
| 01-wordpress-paypal | trunk/wp-admin/options-head.php | PHP | gpl3 | 492 |
<?php
/**
* Network installation administration panel.
*
* A multi-step process allowing the user to enable a network of WordPress sites.
*
* @since 3.0.0
*
* @package WordPress
* @subpackage Administration
*/
define( 'WP_INSTALLING_NETWORK', true );
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_super_admin() )
wp_die( __( 'You do not have sufficient permissions to manage options for this site.' ) );
if ( is_multisite() ) {
if ( ! is_network_admin() ) {
wp_redirect( network_admin_url( 'setup.php' ) );
exit;
}
if ( ! defined( 'MULTISITE' ) )
wp_die( __( 'The Network creation panel is not for WordPress MU networks.' ) );
}
// We need to create references to ms global tables to enable Network.
foreach ( $wpdb->tables( 'ms_global' ) as $table => $prefixed_table )
$wpdb->$table = $prefixed_table;
/**
* Check for an existing network.
*
* @since 3.0.0
* @return Whether a network exists.
*/
function network_domain_check() {
global $wpdb;
if ( $wpdb->get_var( "SHOW TABLES LIKE '$wpdb->site'" ) )
return $wpdb->get_var( "SELECT domain FROM $wpdb->site ORDER BY id ASC LIMIT 1" );
return false;
}
/**
* Allow subdomain install
*
* @since 3.0.0
* @return bool Whether subdomain install is allowed
*/
function allow_subdomain_install() {
$domain = preg_replace( '|https?://([^/]+)|', '$1', get_option( 'home' ) );
if( parse_url( get_option( 'home' ), PHP_URL_PATH ) || 'localhost' == $domain || preg_match( '|^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$|', $domain ) )
return false;
return true;
}
/**
* Allow subdirectory install.
*
* @since 3.0.0
* @return bool Whether subdirectory install is allowed
*/
function allow_subdirectory_install() {
global $wpdb;
/**
* Filter whether to enable the subdirectory install feature in Multisite.
*
* @since 3.0.0
*
* @param bool true Whether to enable the subdirectory install feature in Multisite. Default is false.
*/
if ( apply_filters( 'allow_subdirectory_install', false ) )
return true;
if ( defined( 'ALLOW_SUBDIRECTORY_INSTALL' ) && ALLOW_SUBDIRECTORY_INSTALL )
return true;
$post = $wpdb->get_row( "SELECT ID FROM $wpdb->posts WHERE post_date < DATE_SUB(NOW(), INTERVAL 1 MONTH) AND post_status = 'publish'" );
if ( empty( $post ) )
return true;
return false;
}
/**
* Get base domain of network.
*
* @since 3.0.0
* @return string Base domain.
*/
function get_clean_basedomain() {
if ( $existing_domain = network_domain_check() )
return $existing_domain;
$domain = preg_replace( '|https?://|', '', get_option( 'siteurl' ) );
if ( $slash = strpos( $domain, '/' ) )
$domain = substr( $domain, 0, $slash );
return $domain;
}
if ( ! network_domain_check() && ( ! defined( 'WP_ALLOW_MULTISITE' ) || ! WP_ALLOW_MULTISITE ) )
wp_die( __( 'You must define the <code>WP_ALLOW_MULTISITE</code> constant as true in your wp-config.php file to allow creation of a Network.' ) );
if ( is_network_admin() ) {
$title = __( 'Network Setup' );
$parent_file = 'settings.php';
} else {
$title = __( 'Create a Network of WordPress Sites' );
$parent_file = 'tools.php';
}
$network_help = '<p>' . __('This screen allows you to configure a network as having subdomains (<code>site1.example.com</code>) or subdirectories (<code>example.com/site1</code>). Subdomains require wildcard subdomains to be enabled in Apache and DNS records, if your host allows it.') . '</p>' .
'<p>' . __('Choose subdomains or subdirectories; this can only be switched afterwards by reconfiguring your install. Fill out the network details, and click install. If this does not work, you may have to add a wildcard DNS record (for subdomains) or change to another setting in Permalinks (for subdirectories).') . '</p>' .
'<p>' . __('The next screen for Network Setup will give you individually-generated lines of code to add to your wp-config.php and .htaccess files. Make sure the settings of your FTP client make files starting with a dot visible, so that you can find .htaccess; you may have to create this file if it really is not there. Make backup copies of those two files.') . '</p>' .
'<p>' . __('Add the designated lines of code to wp-config.php (just before <code>/*...stop editing...*/</code>) and <code>.htaccess</code> (replacing the existing WordPress rules).') . '</p>' .
'<p>' . __('Once you add this code and refresh your browser, multisite should be enabled. This screen, now in the Network Admin navigation menu, will keep an archive of the added code. You can toggle between Network Admin and Site Admin by clicking on the Network Admin or an individual site name under the My Sites dropdown in the Toolbar.') . '</p>' .
'<p>' . __('The choice of subdirectory sites is disabled if this setup is more than a month old because of permalink problems with “/blog/” from the main site. This disabling will be addressed in a future version.') . '</p>' .
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Create_A_Network" target="_blank">Documentation on Creating a Network</a>') . '</p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Tools_Network_Screen" target="_blank">Documentation on the Network Screen</a>') . '</p>';
get_current_screen()->add_help_tab( array(
'id' => 'network',
'title' => __('Network'),
'content' => $network_help,
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Create_A_Network" target="_blank">Documentation on Creating a Network</a>') . '</p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Tools_Network_Screen" target="_blank">Documentation on the Network Screen</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
include( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2><?php echo esc_html( $title ); ?></h2>
<?php
/**
* Prints step 1 for Network installation process.
*
* @todo Realistically, step 1 should be a welcome screen explaining what a Network is and such. Navigating to Tools > Network
* should not be a sudden "Welcome to a new install process! Fill this out and click here." See also contextual help todo.
*
* @since 3.0.0
*/
function network_step1( $errors = false ) {
global $is_apache;
if ( defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) {
echo '<div class="error"><p><strong>' . __('ERROR:') . '</strong> ' . __( 'The constant DO_NOT_UPGRADE_GLOBAL_TABLES cannot be defined when creating a network.' ) . '</p></div>';
echo '</div>';
include ( ABSPATH . 'wp-admin/admin-footer.php' );
die();
}
$active_plugins = get_option( 'active_plugins' );
if ( ! empty( $active_plugins ) ) {
echo '<div class="updated"><p><strong>' . __('Warning:') . '</strong> ' . sprintf( __( 'Please <a href="%s">deactivate your plugins</a> before enabling the Network feature.' ), admin_url( 'plugins.php?plugin_status=active' ) ) . '</p></div><p>' . __( 'Once the network is created, you may reactivate your plugins.' ) . '</p>';
echo '</div>';
include( ABSPATH . 'wp-admin/admin-footer.php' );
die();
}
$hostname = get_clean_basedomain();
$has_ports = strstr( $hostname, ':' );
if ( ( false !== $has_ports && ! in_array( $has_ports, array( ':80', ':443' ) ) ) ) {
echo '<div class="error"><p><strong>' . __( 'ERROR:') . '</strong> ' . __( 'You cannot install a network of sites with your server address.' ) . '</p></div>';
echo '<p>' . sprintf( __( 'You cannot use port numbers such as <code>%s</code>.' ), $has_ports ) . '</p>';
echo '<a href="' . esc_url( admin_url() ) . '">' . __( 'Return to Dashboard' ) . '</a>';
echo '</div>';
include( ABSPATH . 'wp-admin/admin-footer.php' );
die();
}
echo '<form method="post" action="">';
wp_nonce_field( 'install-network-1' );
$error_codes = array();
if ( is_wp_error( $errors ) ) {
echo '<div class="error"><p><strong>' . __( 'ERROR: The network could not be created.' ) . '</strong></p>';
foreach ( $errors->get_error_messages() as $error )
echo "<p>$error</p>";
echo '</div>';
$error_codes = $errors->get_error_codes();
}
$site_name = ( ! empty( $_POST['sitename'] ) && ! in_array( 'empty_sitename', $error_codes ) ) ? $_POST['sitename'] : sprintf( _x('%s Sites', 'Default network name' ), get_option( 'blogname' ) );
$admin_email = ( ! empty( $_POST['email'] ) && ! in_array( 'invalid_email', $error_codes ) ) ? $_POST['email'] : get_option( 'admin_email' );
?>
<p><?php _e( 'Welcome to the Network installation process!' ); ?></p>
<p><?php _e( 'Fill in the information below and you’ll be on your way to creating a network of WordPress sites. We will create configuration files in the next step.' ); ?></p>
<?php
if ( isset( $_POST['subdomain_install'] ) ) {
$subdomain_install = (bool) $_POST['subdomain_install'];
} elseif ( apache_mod_loaded('mod_rewrite') ) { // assume nothing
$subdomain_install = true;
} elseif ( !allow_subdirectory_install() ) {
$subdomain_install = true;
} else {
$subdomain_install = false;
if ( $got_mod_rewrite = got_mod_rewrite() ) // dangerous assumptions
echo '<div class="updated inline"><p><strong>' . __( 'Note:' ) . '</strong> ' . __( 'Please make sure the Apache <code>mod_rewrite</code> module is installed as it will be used at the end of this installation.' ) . '</p>';
elseif ( $is_apache )
echo '<div class="error inline"><p><strong>' . __( 'Warning!' ) . '</strong> ' . __( 'It looks like the Apache <code>mod_rewrite</code> module is not installed.' ) . '</p>';
if ( $got_mod_rewrite || $is_apache ) // Protect against mod_rewrite mimicry (but ! Apache)
echo '<p>' . __( 'If <code>mod_rewrite</code> is disabled, ask your administrator to enable that module, or look at the <a href="http://httpd.apache.org/docs/mod/mod_rewrite.html">Apache documentation</a> or <a href="http://www.google.com/search?q=apache+mod_rewrite">elsewhere</a> for help setting it up.' ) . '</p></div>';
}
if ( allow_subdomain_install() && allow_subdirectory_install() ) : ?>
<h3><?php esc_html_e( 'Addresses of Sites in your Network' ); ?></h3>
<p><?php _e( 'Please choose whether you would like sites in your WordPress network to use sub-domains or sub-directories. <strong>You cannot change this later.</strong>' ); ?></p>
<p><?php _e( 'You will need a wildcard DNS record if you are going to use the virtual host (sub-domain) functionality.' ); ?></p>
<?php // @todo: Link to an MS readme? ?>
<table class="form-table">
<tr>
<th><label><input type='radio' name='subdomain_install' value='1'<?php checked( $subdomain_install ); ?> /> <?php _e( 'Sub-domains' ); ?></label></th>
<td><?php printf( _x( 'like <code>site1.%1$s</code> and <code>site2.%1$s</code>', 'subdomain examples' ), $hostname ); ?></td>
</tr>
<tr>
<th><label><input type='radio' name='subdomain_install' value='0'<?php checked( ! $subdomain_install ); ?> /> <?php _e( 'Sub-directories' ); ?></label></th>
<td><?php printf( _x( 'like <code>%1$s/site1</code> and <code>%1$s/site2</code>', 'subdirectory examples' ), $hostname ); ?></td>
</tr>
</table>
<?php
endif;
if ( WP_CONTENT_DIR != ABSPATH . 'wp-content' && ( allow_subdirectory_install() || ! allow_subdomain_install() ) )
echo '<div class="error inline"><p><strong>' . __('Warning!') . '</strong> ' . __( 'Subdirectory networks may not be fully compatible with custom wp-content directories.' ) . '</p></div>';
$is_www = ( 0 === strpos( $hostname, 'www.' ) );
if ( $is_www ) :
?>
<h3><?php esc_html_e( 'Server Address' ); ?></h3>
<p><?php printf( __( 'We recommend you change your siteurl to <code>%1$s</code> before enabling the network feature. It will still be possible to visit your site using the <code>www</code> prefix with an address like <code>%2$s</code> but any links will not have the <code>www</code> prefix.' ), substr( $hostname, 4 ), $hostname ); ?></p>
<table class="form-table">
<tr>
<th scope='row'><?php esc_html_e( 'Server Address' ); ?></th>
<td>
<?php printf( __( 'The internet address of your network will be <code>%s</code>.' ), $hostname ); ?>
</td>
</tr>
</table>
<?php endif; ?>
<h3><?php esc_html_e( 'Network Details' ); ?></h3>
<table class="form-table">
<?php if ( 'localhost' == $hostname ) : ?>
<tr>
<th scope="row"><?php esc_html_e( 'Sub-directory Install' ); ?></th>
<td><?php
_e( 'Because you are using <code>localhost</code>, the sites in your WordPress network must use sub-directories. Consider using <code>localhost.localdomain</code> if you wish to use sub-domains.' );
// Uh oh:
if ( !allow_subdirectory_install() )
echo ' <strong>' . __( 'Warning!' ) . ' ' . __( 'The main site in a sub-directory install will need to use a modified permalink structure, potentially breaking existing links.' ) . '</strong>';
?></td>
</tr>
<?php elseif ( !allow_subdomain_install() ) : ?>
<tr>
<th scope="row"><?php esc_html_e( 'Sub-directory Install' ); ?></th>
<td><?php
_e( 'Because your install is in a directory, the sites in your WordPress network must use sub-directories.' );
// Uh oh:
if ( !allow_subdirectory_install() )
echo ' <strong>' . __( 'Warning!' ) . ' ' . __( 'The main site in a sub-directory install will need to use a modified permalink structure, potentially breaking existing links.' ) . '</strong>';
?></td>
</tr>
<?php elseif ( !allow_subdirectory_install() ) : ?>
<tr>
<th scope="row"><?php esc_html_e( 'Sub-domain Install' ); ?></th>
<td><?php _e( 'Because your install is not new, the sites in your WordPress network must use sub-domains.' );
echo ' <strong>' . __( 'The main site in a sub-directory install will need to use a modified permalink structure, potentially breaking existing links.' ) . '</strong>';
?></td>
</tr>
<?php endif; ?>
<?php if ( ! $is_www ) : ?>
<tr>
<th scope='row'><?php esc_html_e( 'Server Address' ); ?></th>
<td>
<?php printf( __( 'The internet address of your network will be <code>%s</code>.' ), $hostname ); ?>
</td>
</tr>
<?php endif; ?>
<tr>
<th scope='row'><?php esc_html_e( 'Network Title' ); ?></th>
<td>
<input name='sitename' type='text' size='45' value='<?php echo esc_attr( $site_name ); ?>' />
<p class="description">
<?php _e( 'What would you like to call your network?' ); ?>
</p>
</td>
</tr>
<tr>
<th scope='row'><?php esc_html_e( 'Network Admin Email' ); ?></th>
<td>
<input name='email' type='text' size='45' value='<?php echo esc_attr( $admin_email ); ?>' />
<p class="description">
<?php _e( 'Your email address.' ); ?>
</p>
</td>
</tr>
</table>
<?php submit_button( __( 'Install' ), 'primary', 'submit' ); ?>
</form>
<?php
}
/**
* Prints step 2 for Network installation process.
*
* @since 3.0.0
*/
function network_step2( $errors = false ) {
global $wpdb;
$hostname = get_clean_basedomain();
$slashed_home = trailingslashit( get_option( 'home' ) );
$base = parse_url( $slashed_home, PHP_URL_PATH );
$document_root_fix = str_replace( '\\', '/', realpath( $_SERVER['DOCUMENT_ROOT'] ) );
$abspath_fix = str_replace( '\\', '/', ABSPATH );
$home_path = 0 === strpos( $abspath_fix, $document_root_fix ) ? $document_root_fix . $base : get_home_path();
$wp_siteurl_subdir = preg_replace( '#^' . preg_quote( $home_path, '#' ) . '#', '', $abspath_fix );
$rewrite_base = ! empty( $wp_siteurl_subdir ) ? ltrim( trailingslashit( $wp_siteurl_subdir ), '/' ) : '';
$location_of_wp_config = $abspath_fix;
if ( ! file_exists( ABSPATH . 'wp-config.php' ) && file_exists( dirname( ABSPATH ) . '/wp-config.php' ) ) {
$location_of_wp_config = dirname( $abspath_fix );
}
$location_of_wp_config = trailingslashit( $location_of_wp_config );
// Wildcard DNS message.
if ( is_wp_error( $errors ) )
echo '<div class="error">' . $errors->get_error_message() . '</div>';
if ( $_POST ) {
if ( allow_subdomain_install() )
$subdomain_install = allow_subdirectory_install() ? ! empty( $_POST['subdomain_install'] ) : true;
else
$subdomain_install = false;
} else {
if ( is_multisite() ) {
$subdomain_install = is_subdomain_install();
?>
<p><?php _e( 'The original configuration steps are shown here for reference.' ); ?></p>
<?php
} else {
$subdomain_install = (bool) $wpdb->get_var( "SELECT meta_value FROM $wpdb->sitemeta WHERE site_id = 1 AND meta_key = 'subdomain_install'" );
?>
<div class="error"><p><strong><?php _e('Warning:'); ?></strong> <?php _e( 'An existing WordPress network was detected.' ); ?></p></div>
<p><?php _e( 'Please complete the configuration steps. To create a new network, you will need to empty or remove the network database tables.' ); ?></p>
<?php
}
}
$subdir_match = $subdomain_install ? '' : '([_0-9a-zA-Z-]+/)?';
$subdir_replacement_01 = $subdomain_install ? '' : '$1';
$subdir_replacement_12 = $subdomain_install ? '$1' : '$2';
if ( $_POST || ! is_multisite() ) {
?>
<h3><?php esc_html_e( 'Enabling the Network' ); ?></h3>
<p><?php _e( 'Complete the following steps to enable the features for creating a network of sites.' ); ?></p>
<div class="updated inline"><p><?php
if ( file_exists( $home_path . '.htaccess' ) )
printf( __( '<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> and <code>%s</code> files.' ), '.htaccess' );
elseif ( file_exists( $home_path . 'web.config' ) )
printf( __( '<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> and <code>%s</code> files.' ), 'web.config' );
else
_e( '<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> file.' );
?></p></div>
<?php
}
?>
<ol>
<li><p><?php printf( __( 'Add the following to your <code>wp-config.php</code> file in <code>%s</code> <strong>above</strong> the line reading <code>/* That’s all, stop editing! Happy blogging. */</code>:' ), $location_of_wp_config ); ?></p>
<textarea class="code" readonly="readonly" cols="100" rows="6">
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', <?php echo $subdomain_install ? 'true' : 'false'; ?>);
define('DOMAIN_CURRENT_SITE', '<?php echo $hostname; ?>');
define('PATH_CURRENT_SITE', '<?php echo $base; ?>');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);</textarea>
<?php
$keys_salts = array( 'AUTH_KEY' => '', 'SECURE_AUTH_KEY' => '', 'LOGGED_IN_KEY' => '', 'NONCE_KEY' => '', 'AUTH_SALT' => '', 'SECURE_AUTH_SALT' => '', 'LOGGED_IN_SALT' => '', 'NONCE_SALT' => '' );
foreach ( $keys_salts as $c => $v ) {
if ( defined( $c ) )
unset( $keys_salts[ $c ] );
}
if ( ! empty( $keys_salts ) ) {
$keys_salts_str = '';
$from_api = wp_remote_get( 'https://api.wordpress.org/secret-key/1.1/salt/' );
if ( is_wp_error( $from_api ) ) {
foreach ( $keys_salts as $c => $v ) {
$keys_salts_str .= "\ndefine( '$c', '" . wp_generate_password( 64, true, true ) . "' );";
}
} else {
$from_api = explode( "\n", wp_remote_retrieve_body( $from_api ) );
foreach ( $keys_salts as $c => $v ) {
$keys_salts_str .= "\ndefine( '$c', '" . substr( array_shift( $from_api ), 28, 64 ) . "' );";
}
}
$num_keys_salts = count( $keys_salts );
?>
<p><?php
echo _n( 'This unique authentication key is also missing from your <code>wp-config.php</code> file.', 'These unique authentication keys are also missing from your <code>wp-config.php</code> file.', $num_keys_salts ); ?> <?php _e( 'To make your installation more secure, you should also add:' ) ?></p>
<textarea class="code" readonly="readonly" cols="100" rows="<?php echo $num_keys_salts; ?>"><?php echo esc_textarea( $keys_salts_str ); ?></textarea>
<?php
}
?>
</li>
<?php
if ( iis7_supports_permalinks() ) :
// IIS doesn't support RewriteBase, all your RewriteBase are belong to us
$iis_subdir_match = ltrim( $base, '/' ) . $subdir_match;
$iis_rewrite_base = ltrim( $base, '/' ) . $rewrite_base;
$iis_subdir_replacement = $subdomain_install ? '' : '{R:1}';
$web_config_file = '<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="WordPress Rule 1" stopProcessing="true">
<match url="^index\.php$" ignoreCase="false" />
<action type="None" />
</rule>';
if ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) {
$web_config_file .= '
<rule name="WordPress Rule for Files" stopProcessing="true">
<match url="^' . $iis_subdir_match . 'files/(.+)" ignoreCase="false" />
<action type="Rewrite" url="' . $iis_rewrite_base . 'wp-includes/ms-files.php?file={R:1}" appendQueryString="false" />
</rule>';
}
$web_config_file .= '
<rule name="WordPress Rule 2" stopProcessing="true">
<match url="^' . $iis_subdir_match . 'wp-admin$" ignoreCase="false" />
<action type="Redirect" url="' . $iis_subdir_replacement . 'wp-admin/" redirectType="Permanent" />
</rule>
<rule name="WordPress Rule 3" stopProcessing="true">
<match url="^" ignoreCase="false" />
<conditions logicalGrouping="MatchAny">
<add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" />
</conditions>
<action type="None" />
</rule>
<rule name="WordPress Rule 4" stopProcessing="true">
<match url="^' . $iis_subdir_match . '(wp-(content|admin|includes).*)" ignoreCase="false" />
<action type="Rewrite" url="' . $iis_rewrite_base . '{R:1}" />
</rule>
<rule name="WordPress Rule 5" stopProcessing="true">
<match url="^' . $iis_subdir_match . '([_0-9a-zA-Z-]+/)?(.*\.php)$" ignoreCase="false" />
<action type="Rewrite" url="' . $iis_rewrite_base . '{R:2}" />
</rule>
<rule name="WordPress Rule 6" stopProcessing="true">
<match url="." ignoreCase="false" />
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>';
echo '<li><p>';
/* translators: 1: a filename like .htaccess. 2: a file path. */
printf( __( 'Add the following to your %1$s file in %2$s, <strong>replacing</strong> other WordPress rules:' ),
'<code>web.config</code>', '<code>' . $home_path . '</code>' );
echo '</p>';
if ( ! $subdomain_install && WP_CONTENT_DIR != ABSPATH . 'wp-content' )
echo '<p><strong>' . __('Warning:') . ' ' . __( 'Subdirectory networks may not be fully compatible with custom wp-content directories.' ) . '</strong></p>';
?>
<textarea class="code" readonly="readonly" cols="100" rows="20"><?php echo esc_textarea( $web_config_file ); ?>
</textarea></li>
</ol>
<?php else : // end iis7_supports_permalinks(). construct an htaccess file instead:
$ms_files_rewriting = '';
if ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) {
$ms_files_rewriting = "\n# uploaded files\nRewriteRule ^";
$ms_files_rewriting .= $subdir_match . "files/(.+) {$rewrite_base}wp-includes/ms-files.php?file={$subdir_replacement_12} [L]" . "\n";
}
$htaccess_file = <<<EOF
RewriteEngine On
RewriteBase {$base}
RewriteRule ^index\.php$ - [L]
{$ms_files_rewriting}
# add a trailing slash to /wp-admin
RewriteRule ^{$subdir_match}wp-admin$ {$subdir_replacement_01}wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^{$subdir_match}(wp-(content|admin|includes).*) {$rewrite_base}{$subdir_replacement_12} [L]
RewriteRule ^{$subdir_match}(.*\.php)$ {$rewrite_base}$subdir_replacement_12 [L]
RewriteRule . index.php [L]
EOF;
echo '<li><p>';
/* translators: 1: a filename like .htaccess. 2: a file path. */
printf( __( 'Add the following to your %1$s file in %2$s, <strong>replacing</strong> other WordPress rules:' ),
'<code>.htaccess</code>', '<code>' . $home_path . '</code>' );
echo '</p>';
if ( ! $subdomain_install && WP_CONTENT_DIR != ABSPATH . 'wp-content' )
echo '<p><strong>' . __('Warning:') . ' ' . __( 'Subdirectory networks may not be fully compatible with custom wp-content directories.' ) . '</strong></p>';
?>
<textarea class="code" readonly="readonly" cols="100" rows="<?php echo substr_count( $htaccess_file, "\n" ) + 1; ?>">
<?php echo esc_textarea( $htaccess_file ); ?></textarea></li>
</ol>
<?php endif; // end IIS/Apache code branches.
if ( !is_multisite() ) { ?>
<p><?php printf( __( 'Once you complete these steps, your network is enabled and configured. You will have to log in again.') ); ?> <a href="<?php echo esc_url( site_url( 'wp-login.php' ) ); ?>"><?php _e( 'Log In' ); ?></a></p>
<?php
}
}
if ( $_POST ) {
check_admin_referer( 'install-network-1' );
require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
// create network tables
install_network();
$base = parse_url( trailingslashit( get_option( 'home' ) ), PHP_URL_PATH );
$subdomain_install = allow_subdomain_install() ? !empty( $_POST['subdomain_install'] ) : false;
if ( ! network_domain_check() ) {
$result = populate_network( 1, get_clean_basedomain(), sanitize_email( $_POST['email'] ), wp_unslash( $_POST['sitename'] ), $base, $subdomain_install );
if ( is_wp_error( $result ) ) {
if ( 1 == count( $result->get_error_codes() ) && 'no_wildcard_dns' == $result->get_error_code() )
network_step2( $result );
else
network_step1( $result );
} else {
network_step2();
}
} else {
network_step2();
}
} elseif ( is_multisite() || network_domain_check() ) {
network_step2();
} else {
network_step1();
}
?>
</div>
<?php include( ABSPATH . 'wp-admin/admin-footer.php' ); ?>
| 01-wordpress-paypal | trunk/wp-admin/network.php | PHP | gpl3 | 26,434 |
<?php
/**
* Revisions administration panel
*
* Requires wp-admin/includes/revision.php.
*
* @package WordPress
* @subpackage Administration
* @since 2.6.0
*
* @param int revision Optional. The revision ID.
* @param string action The action to take.
* Accepts 'restore', 'view' or 'edit'.
* @param int from The revision to compare from.
* @param int to Optional, required if revision missing. The revision to compare to.
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
require ABSPATH . 'wp-admin/includes/revision.php';
wp_reset_vars( array( 'revision', 'action', 'from', 'to' ) );
$revision_id = absint( $revision );
$from = is_numeric( $from ) ? absint( $from ) : null;
if ( ! $revision_id )
$revision_id = absint( $to );
$redirect = 'edit.php';
switch ( $action ) :
case 'restore' :
if ( ! $revision = wp_get_post_revision( $revision_id ) )
break;
if ( ! current_user_can( 'edit_post', $revision->post_parent ) )
break;
if ( ! $post = get_post( $revision->post_parent ) )
break;
// Revisions disabled (previously checked autosaves && ! wp_is_post_autosave( $revision ))
if ( ! wp_revisions_enabled( $post ) ) {
$redirect = 'edit.php?post_type=' . $post->post_type;
break;
}
// Don't allow revision restore when post is locked
if ( wp_check_post_lock( $post->ID ) )
break;
check_admin_referer( "restore-post_{$revision->ID}" );
wp_restore_post_revision( $revision->ID );
$redirect = add_query_arg( array( 'message' => 5, 'revision' => $revision->ID ), get_edit_post_link( $post->ID, 'url' ) );
break;
case 'view' :
case 'edit' :
default :
if ( ! $revision = wp_get_post_revision( $revision_id ) )
break;
if ( ! $post = get_post( $revision->post_parent ) )
break;
if ( ! current_user_can( 'read_post', $revision->ID ) || ! current_user_can( 'read_post', $post->ID ) )
break;
// Revisions disabled and we're not looking at an autosave
if ( ! wp_revisions_enabled( $post ) && ! wp_is_post_autosave( $revision ) ) {
$redirect = 'edit.php?post_type=' . $post->post_type;
break;
}
$post_edit_link = get_edit_post_link();
$post_title = '<a href="' . $post_edit_link . '">' . _draft_or_post_title() . '</a>';
$h2 = sprintf( __( 'Compare Revisions of “%1$s”' ), $post_title );
$return_to_post = '<a href="' . $post_edit_link . '">' . __( '← Return to post editor' ) . '</a>';
$title = __( 'Revisions' );
$redirect = false;
break;
endswitch;
// Empty post_type means either malformed object found, or no valid parent was found.
if ( ! $redirect && empty( $post->post_type ) )
$redirect = 'edit.php';
if ( ! empty( $redirect ) ) {
wp_redirect( $redirect );
exit;
}
// This is so that the correct "Edit" menu item is selected.
if ( ! empty( $post->post_type ) && 'post' != $post->post_type )
$parent_file = $submenu_file = 'edit.php?post_type=' . $post->post_type;
else
$parent_file = $submenu_file = 'edit.php';
wp_enqueue_script( 'revisions' );
wp_localize_script( 'revisions', '_wpRevisionsSettings', wp_prepare_revisions_for_js( $post, $revision_id, $from ) );
/* Revisions Help Tab */
$revisions_overview = '<p>' . __( 'This screen is used for managing your content revisions.' ) . '</p>';
$revisions_overview .= '<p>' . __( 'Revisions are saved copies of your post or page, which are periodically created as you update your content. The red text on the left shows the content that was removed. The green text on the right shows the content that was added.' ) . '</p>';
$revisions_overview .= '<p>' . __( 'From this screen you can review, compare, and restore revisions:' ) . '</p>';
$revisions_overview .= '<ul><li>' . __( 'To navigate between revisions, <strong>drag the slider handle left or right</strong> or <strong>use the Previous or Next buttons</strong>.' ) . '</li>';
$revisions_overview .= '<li>' . __( 'Compare two different revisions by <strong>selecting the “Compare any two revisions” box</strong> to the side.' ) . '</li>';
$revisions_overview .= '<li>' . __( 'To restore a revision, <strong>click Restore This Revision</strong>.' ) . '</li></ul>';
get_current_screen()->add_help_tab( array(
'id' => 'revisions-overview',
'title' => __( 'Overview' ),
'content' => $revisions_overview
) );
$revisions_sidebar = '<p><strong>' . __( 'For more information:' ) . '</strong></p>';
$revisions_sidebar .= '<p>' . __( '<a href="http://codex.wordpress.org/Revision_Management" target="_blank">Revisions Management</a>' ) . '</p>';
$revisions_sidebar .= '<p>' . __( '<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>' ) . '</p>';
get_current_screen()->set_help_sidebar( $revisions_sidebar );
require_once( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2 class="long-header"><?php echo $h2; ?></h2>
<?php echo $return_to_post; ?>
</div>
<script id="tmpl-revisions-frame" type="text/html">
<div class="revisions-control-frame"></div>
<div class="revisions-diff-frame"></div>
</script>
<script id="tmpl-revisions-buttons" type="text/html">
<div class="revisions-previous">
<input class="button" type="button" value="<?php echo esc_attr_x( 'Previous', 'Button label for a previous revision' ); ?>" />
</div>
<div class="revisions-next">
<input class="button" type="button" value="<?php echo esc_attr_x( 'Next', 'Button label for a next revision' ); ?>" />
</div>
</script>
<script id="tmpl-revisions-checkbox" type="text/html">
<div class="revision-toggle-compare-mode">
<label>
<input type="checkbox" class="compare-two-revisions"
<#
if ( 'undefined' !== typeof data && data.model.attributes.compareTwoMode ) {
#> checked="checked"<#
}
#>
/>
<?php esc_attr_e( 'Compare any two revisions' ); ?>
</label>
</div>
</script>
<script id="tmpl-revisions-meta" type="text/html">
<# if ( ! _.isUndefined( data.attributes ) ) { #>
<div class="diff-title">
<# if ( 'from' === data.type ) { #>
<strong><?php _ex( 'From:', 'Followed by post revision info' ); ?></strong>
<# } else if ( 'to' === data.type ) { #>
<strong><?php _ex( 'To:', 'Followed by post revision info' ); ?></strong>
<# } #>
<div class="author-card<# if ( data.attributes.autosave ) { #> autosave<# } #>">
{{{ data.attributes.author.avatar }}}
<div class="author-info">
<# if ( data.attributes.autosave ) { #>
<span class="byline"><?php printf( __( 'Autosave by %s' ),
'<span class="author-name">{{ data.attributes.author.name }}</span>' ); ?></span>
<# } else if ( data.attributes.current ) { #>
<span class="byline"><?php printf( __( 'Current Revision by %s' ),
'<span class="author-name">{{ data.attributes.author.name }}</span>' ); ?></span>
<# } else { #>
<span class="byline"><?php printf( __( 'Revision by %s' ),
'<span class="author-name">{{ data.attributes.author.name }}</span>' ); ?></span>
<# } #>
<span class="time-ago">{{ data.attributes.timeAgo }}</span>
<span class="date">({{ data.attributes.dateShort }})</span>
</div>
<# if ( 'to' === data.type && data.attributes.restoreUrl ) { #>
<input <?php if ( wp_check_post_lock( $post->ID ) ) { ?>
disabled="disabled"
<?php } else { ?>
<# if ( data.attributes.current ) { #>
disabled="disabled"
<# } #>
<?php } ?>
<# if ( data.attributes.autosave ) { #>
type="button" class="restore-revision button button-primary" value="<?php esc_attr_e( 'Restore This Autosave' ); ?>" />
<# } else { #>
type="button" class="restore-revision button button-primary" value="<?php esc_attr_e( 'Restore This Revision' ); ?>" />
<# } #>
<# } #>
</div>
<# if ( 'tooltip' === data.type ) { #>
<div class="revisions-tooltip-arrow"><span></span></div>
<# } #>
<# } #>
</script>
<script id="tmpl-revisions-diff" type="text/html">
<div class="loading-indicator"><span class="spinner"></span></div>
<div class="diff-error"><?php _e( 'Sorry, something went wrong. The requested comparison could not be loaded.' ); ?></div>
<div class="diff">
<# _.each( data.fields, function( field ) { #>
<h3>{{ field.name }}</h3>
{{{ field.diff }}}
<# }); #>
</div>
</script>
<?php
require_once( ABSPATH . 'wp-admin/admin-footer.php' );
| 01-wordpress-paypal | trunk/wp-admin/revision.php | PHP | gpl3 | 8,330 |
<?php
/**
* General settings administration panel.
*
* @package WordPress
* @subpackage Administration
*/
/** WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! current_user_can( 'manage_options' ) )
wp_die( __( 'You do not have sufficient permissions to manage options for this site.' ) );
$title = __('General Settings');
$parent_file = 'options-general.php';
/* translators: date and time format for exact current time, mainly about timezones, see http://php.net/date */
$timezone_format = _x('Y-m-d G:i:s', 'timezone date format');
/**
* Display JavaScript on the page.
*
* @since 3.5.0
*/
function options_general_add_js() {
?>
<script type="text/javascript">
//<![CDATA[
jQuery(document).ready(function($){
$("input[name='date_format']").click(function(){
if ( "date_format_custom_radio" != $(this).attr("id") )
$("input[name='date_format_custom']").val( $(this).val() ).siblings('.example').text( $(this).siblings('span').text() );
});
$("input[name='date_format_custom']").focus(function(){
$( '#date_format_custom_radio' ).prop( 'checked', true );
});
$("input[name='time_format']").click(function(){
if ( "time_format_custom_radio" != $(this).attr("id") )
$("input[name='time_format_custom']").val( $(this).val() ).siblings('.example').text( $(this).siblings('span').text() );
});
$("input[name='time_format_custom']").focus(function(){
$( '#time_format_custom_radio' ).prop( 'checked', true );
});
$("input[name='date_format_custom'], input[name='time_format_custom']").change( function() {
var format = $(this);
format.siblings('.spinner').css('display', 'inline-block'); // show(); can't be used here
$.post(ajaxurl, {
action: 'date_format_custom' == format.attr('name') ? 'date_format' : 'time_format',
date : format.val()
}, function(d) { format.siblings('.spinner').hide(); format.siblings('.example').text(d); } );
});
});
//]]>
</script>
<?php
}
add_action('admin_head', 'options_general_add_js');
$options_help = '<p>' . __('The fields on this screen determine some of the basics of your site setup.') . '</p>' .
'<p>' . __('Most themes display the site title at the top of every page, in the title bar of the browser, and as the identifying name for syndicated feeds. The tagline is also displayed by many themes.') . '</p>';
if ( ! is_multisite() ) {
$options_help .= '<p>' . __('The WordPress URL and the Site URL can be the same (example.com) or different; for example, having the WordPress core files (example.com/wordpress) in a subdirectory instead of the root directory.') . '</p>' .
'<p>' . __('If you want site visitors to be able to register themselves, as opposed to by the site administrator, check the membership box. A default user role can be set for all new users, whether self-registered or registered by the site admin.') . '</p>';
}
$options_help .= '<p>' . __('UTC means Coordinated Universal Time.') . '</p>' .
'<p>' . __( 'You must click the Save Changes button at the bottom of the screen for new settings to take effect.' ) . '</p>';
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' => $options_help,
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Settings_General_Screen" target="_blank">Documentation on General Settings</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
include( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2><?php echo esc_html( $title ); ?></h2>
<form method="post" action="options.php">
<?php settings_fields('general'); ?>
<table class="form-table">
<tr>
<th scope="row"><label for="blogname"><?php _e('Site Title') ?></label></th>
<td><input name="blogname" type="text" id="blogname" value="<?php form_option('blogname'); ?>" class="regular-text" /></td>
</tr>
<tr>
<th scope="row"><label for="blogdescription"><?php _e('Tagline') ?></label></th>
<td><input name="blogdescription" type="text" id="blogdescription" value="<?php form_option('blogdescription'); ?>" class="regular-text" />
<p class="description"><?php _e('In a few words, explain what this site is about.') ?></p></td>
</tr>
<?php if ( !is_multisite() ) { ?>
<tr>
<th scope="row"><label for="siteurl"><?php _e('WordPress Address (URL)') ?></label></th>
<td><input name="siteurl" type="text" id="siteurl" value="<?php form_option('siteurl'); ?>"<?php disabled( defined( 'WP_SITEURL' ) ); ?> class="regular-text code<?php if ( defined( 'WP_SITEURL' ) ) echo ' disabled' ?>" /></td>
</tr>
<tr>
<th scope="row"><label for="home"><?php _e('Site Address (URL)') ?></label></th>
<td><input name="home" type="text" id="home" value="<?php form_option('home'); ?>"<?php disabled( defined( 'WP_HOME' ) ); ?> class="regular-text code<?php if ( defined( 'WP_HOME' ) ) echo ' disabled' ?>" />
<p class="description"><?php _e('Enter the address here if you want your site homepage <a href="http://codex.wordpress.org/Giving_WordPress_Its_Own_Directory">to be different from the directory</a> you installed WordPress.'); ?></p></td>
</tr>
<tr>
<th scope="row"><label for="admin_email"><?php _e('E-mail Address') ?> </label></th>
<td><input name="admin_email" type="text" id="admin_email" value="<?php form_option('admin_email'); ?>" class="regular-text ltr" />
<p class="description"><?php _e('This address is used for admin purposes, like new user notification.') ?></p></td>
</tr>
<tr>
<th scope="row"><?php _e('Membership') ?></th>
<td> <fieldset><legend class="screen-reader-text"><span><?php _e('Membership') ?></span></legend><label for="users_can_register">
<input name="users_can_register" type="checkbox" id="users_can_register" value="1" <?php checked('1', get_option('users_can_register')); ?> />
<?php _e('Anyone can register') ?></label>
</fieldset></td>
</tr>
<tr>
<th scope="row"><label for="default_role"><?php _e('New User Default Role') ?></label></th>
<td>
<select name="default_role" id="default_role"><?php wp_dropdown_roles( get_option('default_role') ); ?></select>
</td>
</tr>
<?php } else { ?>
<tr>
<th scope="row"><label for="new_admin_email"><?php _e('E-mail Address') ?> </label></th>
<td><input name="new_admin_email" type="text" id="new_admin_email" value="<?php form_option('admin_email'); ?>" class="regular-text ltr" />
<p class="description"><?php _e('This address is used for admin purposes. If you change this we will send you an e-mail at your new address to confirm it. <strong>The new address will not become active until confirmed.</strong>') ?></p>
<?php
$new_admin_email = get_option( 'new_admin_email' );
if ( $new_admin_email && $new_admin_email != get_option('admin_email') ) : ?>
<div class="updated inline">
<p><?php printf( __('There is a pending change of the admin e-mail to <code>%1$s</code>. <a href="%2$s">Cancel</a>'), esc_html( $new_admin_email ), esc_url( admin_url( 'options.php?dismiss=new_admin_email' ) ) ); ?></p>
</div>
<?php endif; ?>
</td>
</tr>
<?php } ?>
<tr>
<?php
$current_offset = get_option('gmt_offset');
$tzstring = get_option('timezone_string');
$check_zone_info = true;
// Remove old Etc mappings. Fallback to gmt_offset.
if ( false !== strpos($tzstring,'Etc/GMT') )
$tzstring = '';
if ( empty($tzstring) ) { // Create a UTC+- zone if no timezone string exists
$check_zone_info = false;
if ( 0 == $current_offset )
$tzstring = 'UTC+0';
elseif ($current_offset < 0)
$tzstring = 'UTC' . $current_offset;
else
$tzstring = 'UTC+' . $current_offset;
}
?>
<th scope="row"><label for="timezone_string"><?php _e('Timezone') ?></label></th>
<td>
<select id="timezone_string" name="timezone_string">
<?php echo wp_timezone_choice($tzstring); ?>
</select>
<span id="utc-time"><?php printf(__('<abbr title="Coordinated Universal Time">UTC</abbr> time is <code>%s</code>'), date_i18n($timezone_format, false, 'gmt')); ?></span>
<?php if ( get_option('timezone_string') || !empty($current_offset) ) : ?>
<span id="local-time"><?php printf(__('Local time is <code>%1$s</code>'), date_i18n($timezone_format)); ?></span>
<?php endif; ?>
<p class="description"><?php _e('Choose a city in the same timezone as you.'); ?></p>
<?php if ($check_zone_info && $tzstring) : ?>
<br />
<span>
<?php
// Set TZ so localtime works.
date_default_timezone_set($tzstring);
$now = localtime(time(), true);
if ( $now['tm_isdst'] )
_e('This timezone is currently in daylight saving time.');
else
_e('This timezone is currently in standard time.');
?>
<br />
<?php
$allowed_zones = timezone_identifiers_list();
if ( in_array( $tzstring, $allowed_zones) ) {
$found = false;
$date_time_zone_selected = new DateTimeZone($tzstring);
$tz_offset = timezone_offset_get($date_time_zone_selected, date_create());
$right_now = time();
foreach ( timezone_transitions_get($date_time_zone_selected) as $tr) {
if ( $tr['ts'] > $right_now ) {
$found = true;
break;
}
}
if ( $found ) {
echo ' ';
$message = $tr['isdst'] ?
__('Daylight saving time begins on: <code>%s</code>.') :
__('Standard time begins on: <code>%s</code>.');
// Add the difference between the current offset and the new offset to ts to get the correct transition time from date_i18n().
printf( $message, date_i18n(get_option('date_format') . ' ' . get_option('time_format'), $tr['ts'] + ($tz_offset - $tr['offset']) ) );
} else {
_e('This timezone does not observe daylight saving time.');
}
}
// Set back to UTC.
date_default_timezone_set('UTC');
?>
</span>
<?php endif; ?>
</td>
</tr>
<tr>
<th scope="row"><?php _e('Date Format') ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e('Date Format') ?></span></legend>
<?php
/**
* Filter the default date formats.
*
* @since 2.7.0
*
* @param array $default_date_formats Array of default date formats.
*/
$date_formats = array_unique( apply_filters( 'date_formats', array( __( 'F j, Y' ), 'Y/m/d', 'm/d/Y', 'd/m/Y' ) ) );
$custom = true;
foreach ( $date_formats as $format ) {
echo "\t<label title='" . esc_attr($format) . "'><input type='radio' name='date_format' value='" . esc_attr($format) . "'";
if ( get_option('date_format') === $format ) { // checked() uses "==" rather than "==="
echo " checked='checked'";
$custom = false;
}
echo ' /> <span>' . date_i18n( $format ) . "</span></label><br />\n";
}
echo ' <label><input type="radio" name="date_format" id="date_format_custom_radio" value="\c\u\s\t\o\m"';
checked( $custom );
echo '/> ' . __('Custom:') . ' </label><input type="text" name="date_format_custom" value="' . esc_attr( get_option('date_format') ) . '" class="small-text" /> <span class="example"> ' . date_i18n( get_option('date_format') ) . "</span> <span class='spinner'></span>\n";
echo "\t<p>" . __('<a href="http://codex.wordpress.org/Formatting_Date_and_Time">Documentation on date and time formatting</a>.') . "</p>\n";
?>
</fieldset>
</td>
</tr>
<tr>
<th scope="row"><?php _e('Time Format') ?></th>
<td>
<fieldset><legend class="screen-reader-text"><span><?php _e('Time Format') ?></span></legend>
<?php
/**
* Filter the default time formats.
*
* @since 2.7.0
*
* @param array $default_time_formats Array of default time formats.
*/
$time_formats = array_unique( apply_filters( 'time_formats', array( __( 'g:i a' ), 'g:i A', 'H:i' ) ) );
$custom = true;
foreach ( $time_formats as $format ) {
echo "\t<label title='" . esc_attr($format) . "'><input type='radio' name='time_format' value='" . esc_attr($format) . "'";
if ( get_option('time_format') === $format ) { // checked() uses "==" rather than "==="
echo " checked='checked'";
$custom = false;
}
echo ' /> <span>' . date_i18n( $format ) . "</span></label><br />\n";
}
echo ' <label><input type="radio" name="time_format" id="time_format_custom_radio" value="\c\u\s\t\o\m"';
checked( $custom );
echo '/> ' . __('Custom:') . ' </label><input type="text" name="time_format_custom" value="' . esc_attr( get_option('time_format') ) . '" class="small-text" /> <span class="example"> ' . date_i18n( get_option('time_format') ) . "</span> <span class='spinner'></span>\n";
;
?>
</fieldset>
</td>
</tr>
<tr>
<th scope="row"><label for="start_of_week"><?php _e('Week Starts On') ?></label></th>
<td><select name="start_of_week" id="start_of_week">
<?php
for ($day_index = 0; $day_index <= 6; $day_index++) :
$selected = (get_option('start_of_week') == $day_index) ? 'selected="selected"' : '';
echo "\n\t<option value='" . esc_attr($day_index) . "' $selected>" . $wp_locale->get_weekday($day_index) . '</option>';
endfor;
?>
</select></td>
</tr>
<?php do_settings_fields('general', 'default'); ?>
<?php
$languages = get_available_languages();
if ( is_multisite() && !empty( $languages ) ):
?>
<tr>
<th width="33%" scope="row"><?php _e('Site Language') ?></th>
<td>
<select name="WPLANG" id="WPLANG">
<?php mu_dropdown_languages( $languages, get_option('WPLANG') ); ?>
</select>
</td>
</tr>
<?php
endif;
?>
</table>
<?php do_settings_sections('general'); ?>
<?php submit_button(); ?>
</form>
</div>
<?php include( ABSPATH . 'wp-admin/admin-footer.php' ); ?>
| 01-wordpress-paypal | trunk/wp-admin/options-general.php | PHP | gpl3 | 13,304 |
<?php
/**
* Multisite administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.0.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
/** Load WordPress dashboard API */
require_once( ABSPATH . 'wp-admin/includes/dashboard.php' );
if ( !is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( ! current_user_can( 'manage_network' ) )
wp_die( __( 'You do not have permission to access this page.' ) );
$title = __( 'Dashboard' );
$parent_file = 'index.php';
$overview = '<p>' . __( 'Welcome to your Network Admin. This area of the Administration Screens is used for managing all aspects of your Multisite Network.' ) . '</p>';
$overview .= '<p>' . __( 'From here you can:' ) . '</p>';
$overview .= '<ul><li>' . __( 'Add and manage sites or users' ) . '</li>';
$overview .= '<li>' . __( 'Install and activate themes or plugins' ) . '</li>';
$overview .= '<li>' . __( 'Update your network' ) . '</li>';
$overview .= '<li>' . __( 'Modify global network settings' ) . '</li></ul>';
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __( 'Overview' ),
'content' => $overview
) );
$quick_tasks = '<p>' . __( 'The Right Now widget on this screen provides current user and site counts on your network.' ) . '</p>';
$quick_tasks .= '<ul><li>' . __( 'To add a new user, <strong>click Create a New User</strong>.' ) . '</li>';
$quick_tasks .= '<li>' . __( 'To add a new site, <strong>click Create a New Site</strong>.' ) . '</li></ul>';
$quick_tasks .= '<p>' . __( 'To search for a user or site, use the search boxes.' ) . '</p>';
$quick_tasks .= '<ul><li>' . __( 'To search for a user, <strong>enter an email address or username</strong>. Use a wildcard to search for a partial username, such as user*.' ) . '</li>';
$quick_tasks .= '<li>' . __( 'To search for a site, <strong>enter the path or domain</strong>.' ) . '</li></ul>';
get_current_screen()->add_help_tab( array(
'id' => 'quick-tasks',
'title' => __( 'Quick Tasks' ),
'content' => $quick_tasks
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Network_Admin" target="_blank">Documentation on the Network Admin</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/forum/multisite/" target="_blank">Support Forums</a>') . '</p>'
);
wp_dashboard_setup();
wp_enqueue_script( 'dashboard' );
wp_enqueue_script( 'plugin-install' );
add_thickbox();
require_once( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2><?php echo esc_html( $title ); ?></h2>
<div id="dashboard-widgets-wrap">
<?php wp_dashboard(); ?>
<div class="clear"></div>
</div><!-- dashboard-widgets-wrap -->
</div><!-- wrap -->
<?php include( ABSPATH . 'wp-admin/admin-footer.php' ); ?>
| 01-wordpress-paypal | trunk/wp-admin/network/index.php | PHP | gpl3 | 2,906 |
<?php
/**
* Edit user network administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/user-edit.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/user-edit.php | PHP | gpl3 | 350 |
<?php
/**
* Multisite network settings administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.0.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( ! current_user_can( 'manage_network_options' ) )
wp_die( __( 'You do not have permission to access this page.' ) );
$title = __( 'Network Settings' );
$parent_file = 'settings.php';
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('This screen sets and changes options for the network as a whole. The first site is the main site in the network and network options are pulled from that original site’s options.') . '</p>' .
'<p>' . __('Operational settings has fields for the network’s name and admin email.') . '</p>' .
'<p>' . __('Registration settings can disable/enable public signups. If you let others sign up for a site, install spam plugins. Spaces, not commas, should separate names banned as sites for this network.') . '</p>' .
'<p>' . __('New site settings are defaults applied when a new site is created in the network. These include welcome email for when a new site or user account is registered, and what᾿s put in the first post, page, comment, comment author, and comment URL.') . '</p>' .
'<p>' . __('Upload settings control the size of the uploaded files and the amount of available upload space for each site. You can change the default value for specific sites when you edit a particular site. Allowed file types are also listed (space separated only).') . '</p>' .
'<p>' . __('Menu setting enables/disables the plugin menus from appearing for non super admins, so that only super admins, not site admins, have access to activate plugins.') . '</p>' .
'<p>' . __('Super admins can no longer be added on the Options screen. You must now go to the list of existing users on Network Admin > Users and click on Username or the Edit action link below that name. This goes to an Edit User page where you can check a box to grant super admin privileges.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Network_Admin_Settings_Screen" target="_blank">Documentation on Network Settings</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
if ( $_POST ) {
/** This action is documented in wp-admin/network/edit.php */
do_action( 'wpmuadminedit' );
check_admin_referer( 'siteoptions' );
$checked_options = array( 'menu_items' => array(), 'registrationnotification' => 'no', 'upload_space_check_disabled' => 1, 'add_new_users' => 0 );
foreach ( $checked_options as $option_name => $option_unchecked_value ) {
if ( ! isset( $_POST[$option_name] ) )
$_POST[$option_name] = $option_unchecked_value;
}
$options = array(
'registrationnotification', 'registration', 'add_new_users', 'menu_items',
'upload_space_check_disabled', 'blog_upload_space', 'upload_filetypes', 'site_name',
'first_post', 'first_page', 'first_comment', 'first_comment_url', 'first_comment_author',
'welcome_email', 'welcome_user_email', 'fileupload_maxk', 'global_terms_enabled',
'illegal_names', 'limited_email_domains', 'banned_email_domains', 'WPLANG', 'admin_email',
);
foreach ( $options as $option_name ) {
if ( ! isset($_POST[$option_name]) )
continue;
$value = wp_unslash( $_POST[$option_name] );
update_site_option( $option_name, $value );
}
/**
* Fires after the network options are updated.
*
* @since MU
*/
do_action( 'update_wpmu_options' );
wp_redirect( add_query_arg( 'updated', 'true', network_admin_url( 'settings.php' ) ) );
exit();
}
include( ABSPATH . 'wp-admin/admin-header.php' );
if ( isset( $_GET['updated'] ) ) {
?><div id="message" class="updated"><p><?php _e( 'Options saved.' ) ?></p></div><?php
}
?>
<div class="wrap">
<h2><?php echo esc_html( $title ); ?></h2>
<form method="post" action="settings.php">
<?php wp_nonce_field( 'siteoptions' ); ?>
<h3><?php _e( 'Operational Settings' ); ?></h3>
<table class="form-table">
<tr>
<th scope="row"><label for="site_name"><?php _e( 'Network Title' ) ?></label></th>
<td>
<input name="site_name" type="text" id="site_name" class="regular-text" value="<?php echo esc_attr( $current_site->site_name ) ?>" />
</td>
</tr>
<tr>
<th scope="row"><label for="admin_email"><?php _e( 'Network Admin Email' ) ?></label></th>
<td>
<input name="admin_email" type="text" id="admin_email" class="regular-text" value="<?php echo esc_attr( get_site_option('admin_email') ) ?>" />
<p class="description">
<?php _e( 'This email address will receive notifications. Registration and support emails will also come from this address.' ); ?>
</p>
</td>
</tr>
</table>
<h3><?php _e( 'Registration Settings' ); ?></h3>
<table class="form-table">
<tr>
<th scope="row"><?php _e( 'Allow new registrations' ) ?></th>
<?php
if ( !get_site_option( 'registration' ) )
update_site_option( 'registration', 'none' );
$reg = get_site_option( 'registration' );
?>
<td>
<label><input name="registration" type="radio" id="registration1" value="none"<?php checked( $reg, 'none') ?> /> <?php _e( 'Registration is disabled.' ); ?></label><br />
<label><input name="registration" type="radio" id="registration2" value="user"<?php checked( $reg, 'user') ?> /> <?php _e( 'User accounts may be registered.' ); ?></label><br />
<label><input name="registration" type="radio" id="registration3" value="blog"<?php checked( $reg, 'blog') ?> /> <?php _e( 'Logged in users may register new sites.' ); ?></label><br />
<label><input name="registration" type="radio" id="registration4" value="all"<?php checked( $reg, 'all') ?> /> <?php _e( 'Both sites and user accounts can be registered.' ); ?></label>
<p class="description">
<?php if ( is_subdomain_install() )
_e( 'If registration is disabled, please set <code>NOBLOGREDIRECT</code> in <code>wp-config.php</code> to a URL you will redirect visitors to if they visit a non-existent site.' );
?>
</p>
</td>
</tr>
<tr>
<th scope="row"><?php _e( 'Registration notification' ) ?></th>
<?php
if ( !get_site_option( 'registrationnotification' ) )
update_site_option( 'registrationnotification', 'yes' );
?>
<td>
<label><input name="registrationnotification" type="checkbox" id="registrationnotification" value="yes"<?php checked( get_site_option( 'registrationnotification' ), 'yes' ) ?> /> <?php _e( 'Send the network admin an email notification every time someone registers a site or user account.' ) ?></label>
</td>
</tr>
<tr id="addnewusers">
<th scope="row"><?php _e( 'Add New Users' ) ?></th>
<td>
<label><input name="add_new_users" type="checkbox" id="add_new_users" value="1"<?php checked( get_site_option( 'add_new_users' ) ) ?> /> <?php _e( 'Allow site administrators to add new users to their site via the "Users → Add New" page.' ); ?></label>
</td>
</tr>
<tr>
<th scope="row"><label for="illegal_names"><?php _e( 'Banned Names' ) ?></label></th>
<td>
<input name="illegal_names" type="text" id="illegal_names" class="large-text" value="<?php echo esc_attr( implode( " ", (array) get_site_option( 'illegal_names' ) ) ); ?>" size="45" />
<p class="description">
<?php _e( 'Users are not allowed to register these sites. Separate names by spaces.' ) ?>
</p>
</td>
</tr>
<tr>
<th scope="row"><label for="limited_email_domains"><?php _e( 'Limited Email Registrations' ) ?></label></th>
<td>
<?php $limited_email_domains = get_site_option( 'limited_email_domains' );
$limited_email_domains = str_replace( ' ', "\n", $limited_email_domains ); ?>
<textarea name="limited_email_domains" id="limited_email_domains" cols="45" rows="5">
<?php echo esc_textarea( $limited_email_domains == '' ? '' : implode( "\n", (array) $limited_email_domains ) ); ?></textarea>
<p class="description">
<?php _e( 'If you want to limit site registrations to certain domains. One domain per line.' ) ?>
</p>
</td>
</tr>
<tr>
<th scope="row"><label for="banned_email_domains"><?php _e('Banned Email Domains') ?></label></th>
<td>
<textarea name="banned_email_domains" id="banned_email_domains" cols="45" rows="5">
<?php echo esc_textarea( get_site_option( 'banned_email_domains' ) == '' ? '' : implode( "\n", (array) get_site_option( 'banned_email_domains' ) ) ); ?></textarea>
<p class="description">
<?php _e( 'If you want to ban domains from site registrations. One domain per line.' ) ?>
</p>
</td>
</tr>
</table>
<h3><?php _e('New Site Settings'); ?></h3>
<table class="form-table">
<tr>
<th scope="row"><label for="welcome_email"><?php _e( 'Welcome Email' ) ?></label></th>
<td>
<textarea name="welcome_email" id="welcome_email" rows="5" cols="45" class="large-text">
<?php echo esc_textarea( get_site_option( 'welcome_email' ) ) ?></textarea>
<p class="description">
<?php _e( 'The welcome email sent to new site owners.' ) ?>
</p>
</td>
</tr>
<tr>
<th scope="row"><label for="welcome_user_email"><?php _e( 'Welcome User Email' ) ?></label></th>
<td>
<textarea name="welcome_user_email" id="welcome_user_email" rows="5" cols="45" class="large-text">
<?php echo esc_textarea( get_site_option( 'welcome_user_email' ) ) ?></textarea>
<p class="description">
<?php _e( 'The welcome email sent to new users.' ) ?>
</p>
</td>
</tr>
<tr>
<th scope="row"><label for="first_post"><?php _e( 'First Post' ) ?></label></th>
<td>
<textarea name="first_post" id="first_post" rows="5" cols="45" class="large-text">
<?php echo esc_textarea( get_site_option( 'first_post' ) ) ?></textarea>
<p class="description">
<?php _e( 'The first post on a new site.' ) ?>
</p>
</td>
</tr>
<tr>
<th scope="row"><label for="first_page"><?php _e( 'First Page' ) ?></label></th>
<td>
<textarea name="first_page" id="first_page" rows="5" cols="45" class="large-text">
<?php echo esc_textarea( get_site_option( 'first_page' ) ) ?></textarea>
<p class="description">
<?php _e( 'The first page on a new site.' ) ?>
</p>
</td>
</tr>
<tr>
<th scope="row"><label for="first_comment"><?php _e( 'First Comment' ) ?></label></th>
<td>
<textarea name="first_comment" id="first_comment" rows="5" cols="45" class="large-text">
<?php echo esc_textarea( get_site_option( 'first_comment' ) ) ?></textarea>
<p class="description">
<?php _e( 'The first comment on a new site.' ) ?>
</p>
</td>
</tr>
<tr>
<th scope="row"><label for="first_comment_author"><?php _e( 'First Comment Author' ) ?></label></th>
<td>
<input type="text" size="40" name="first_comment_author" id="first_comment_author" value="<?php echo get_site_option('first_comment_author') ?>" />
<p class="description">
<?php _e( 'The author of the first comment on a new site.' ) ?>
</p>
</td>
</tr>
<tr>
<th scope="row"><label for="first_comment_url"><?php _e( 'First Comment URL' ) ?></label></th>
<td>
<input type="text" size="40" name="first_comment_url" id="first_comment_url" value="<?php echo esc_attr( get_site_option( 'first_comment_url' ) ) ?>" />
<p class="description">
<?php _e( 'The URL for the first comment on a new site.' ) ?>
</p>
</td>
</tr>
</table>
<h3><?php _e( 'Upload Settings' ); ?></h3>
<table class="form-table">
<tr>
<th scope="row"><?php _e( 'Site upload space' ) ?></th>
<td>
<label><input type="checkbox" id="upload_space_check_disabled" name="upload_space_check_disabled" value="0"<?php checked( get_site_option( 'upload_space_check_disabled' ), 0 ) ?>/> <?php printf( __( 'Limit total size of files uploaded to %s MB' ), '</label><label><input name="blog_upload_space" type="number" min="0" style="width: 100px" id="blog_upload_space" value="' . esc_attr( get_site_option('blog_upload_space', 100) ) . '" />' ); ?></label><br />
</td>
</tr>
<tr>
<th scope="row"><label for="upload_filetypes"><?php _e( 'Upload file types' ) ?></label></th>
<td><input name="upload_filetypes" type="text" id="upload_filetypes" class="large-text" value="<?php echo esc_attr( get_site_option('upload_filetypes', 'jpg jpeg png gif') ) ?>" size="45" /></td>
</tr>
<tr>
<th scope="row"><label for="fileupload_maxk"><?php _e( 'Max upload file size' ) ?></label></th>
<td><?php printf( _x( '%s KB', 'File size in kilobytes' ), '<input name="fileupload_maxk" type="number" min="0" style="width: 100px" id="fileupload_maxk" value="' . esc_attr( get_site_option( 'fileupload_maxk', 300 ) ) . '" />' ); ?></td>
</tr>
</table>
<?php
$languages = get_available_languages();
if ( ! empty( $languages ) ) {
$lang = get_site_option( 'WPLANG' );
?>
<h3><?php _e( 'Language Settings' ); ?></h3>
<table class="form-table">
<tr>
<th><label for="WPLANG"><?php _e( 'Default Language' ); ?></label></th>
<td>
<select name="WPLANG" id="WPLANG">
<?php mu_dropdown_languages( $languages, get_site_option( 'WPLANG' ) ); ?>
</select>
</td>
</tr>
</table>
<?php
} // languages
?>
<h3><?php _e( 'Menu Settings' ); ?></h3>
<table id="menu" class="form-table">
<tr>
<th scope="row"><?php _e( 'Enable administration menus' ); ?></th>
<td>
<?php
$menu_perms = get_site_option( 'menu_items' );
/**
* Filter available network-wide administration menu options.
*
* Options returned to this filter are output as individual checkboxes that, when selected,
* enable site administrator access to the specified administration menu in certain contexts.
*
* Adding options for specific menus here hinges on the appropriate checks and capabilities
* being in place in the site dashboard on the other side. For instance, when the single
* default option, 'plugins' is enabled, site administrators are granted access to the Plugins
* screen in their individual sites' dashboards.
*
* @since MU
*
* @param array $admin_menus The menu items available.
*/
$menu_items = apply_filters( 'mu_menu_items', array( 'plugins' => __( 'Plugins' ) ) );
foreach ( (array) $menu_items as $key => $val ) {
echo "<label><input type='checkbox' name='menu_items[" . $key . "]' value='1'" . ( isset( $menu_perms[$key] ) ? checked( $menu_perms[$key], '1', false ) : '' ) . " /> " . esc_html( $val ) . "</label><br/>";
}
?>
</td>
</tr>
</table>
<?php
/**
* Fires at the end of the Network Settings form, before the submit button.
*
* @since MU
*/
do_action( 'wpmu_options' ); ?>
<?php submit_button(); ?>
</form>
</div>
<?php include( ABSPATH . 'wp-admin/admin-footer.php' ); ?>
| 01-wordpress-paypal | trunk/wp-admin/network/settings.php | PHP | gpl3 | 15,247 |
<?php
/**
* Multisite themes administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( !current_user_can('manage_network_themes') )
wp_die( __( 'You do not have sufficient permissions to manage network themes.' ) );
$wp_list_table = _get_list_table('WP_MS_Themes_List_Table');
$pagenum = $wp_list_table->get_pagenum();
$action = $wp_list_table->current_action();
$s = isset($_REQUEST['s']) ? $_REQUEST['s'] : '';
// Clean up request URI from temporary args for screen options/paging uri's to work as expected.
$temp_args = array( 'enabled', 'disabled', 'deleted', 'error' );
$_SERVER['REQUEST_URI'] = remove_query_arg( $temp_args, $_SERVER['REQUEST_URI'] );
$referer = remove_query_arg( $temp_args, wp_get_referer() );
if ( $action ) {
$allowed_themes = get_site_option( 'allowedthemes' );
switch ( $action ) {
case 'enable':
check_admin_referer('enable-theme_' . $_GET['theme']);
$allowed_themes[ $_GET['theme'] ] = true;
update_site_option( 'allowedthemes', $allowed_themes );
if ( false === strpos( $referer, '/network/themes.php' ) )
wp_redirect( network_admin_url( 'themes.php?enabled=1' ) );
else
wp_safe_redirect( add_query_arg( 'enabled', 1, $referer ) );
exit;
break;
case 'disable':
check_admin_referer('disable-theme_' . $_GET['theme']);
unset( $allowed_themes[ $_GET['theme'] ] );
update_site_option( 'allowedthemes', $allowed_themes );
wp_safe_redirect( add_query_arg( 'disabled', '1', $referer ) );
exit;
break;
case 'enable-selected':
check_admin_referer('bulk-themes');
$themes = isset( $_POST['checked'] ) ? (array) $_POST['checked'] : array();
if ( empty($themes) ) {
wp_safe_redirect( add_query_arg( 'error', 'none', $referer ) );
exit;
}
foreach( (array) $themes as $theme )
$allowed_themes[ $theme ] = true;
update_site_option( 'allowedthemes', $allowed_themes );
wp_safe_redirect( add_query_arg( 'enabled', count( $themes ), $referer ) );
exit;
break;
case 'disable-selected':
check_admin_referer('bulk-themes');
$themes = isset( $_POST['checked'] ) ? (array) $_POST['checked'] : array();
if ( empty($themes) ) {
wp_safe_redirect( add_query_arg( 'error', 'none', $referer ) );
exit;
}
foreach( (array) $themes as $theme )
unset( $allowed_themes[ $theme ] );
update_site_option( 'allowedthemes', $allowed_themes );
wp_safe_redirect( add_query_arg( 'disabled', count( $themes ), $referer ) );
exit;
break;
case 'update-selected' :
check_admin_referer( 'bulk-themes' );
if ( isset( $_GET['themes'] ) )
$themes = explode( ',', $_GET['themes'] );
elseif ( isset( $_POST['checked'] ) )
$themes = (array) $_POST['checked'];
else
$themes = array();
$title = __( 'Update Themes' );
$parent_file = 'themes.php';
require_once(ABSPATH . 'wp-admin/admin-header.php');
echo '<div class="wrap">';
echo '<h2>' . esc_html( $title ) . '</h2>';
$url = self_admin_url('update.php?action=update-selected-themes&themes=' . urlencode( join(',', $themes) ));
$url = wp_nonce_url($url, 'bulk-update-themes');
echo "<iframe src='$url' style='width: 100%; height:100%; min-height:850px;'></iframe>";
echo '</div>';
require_once(ABSPATH . 'wp-admin/admin-footer.php');
exit;
break;
case 'delete-selected':
if ( ! current_user_can( 'delete_themes' ) )
wp_die( __('You do not have sufficient permissions to delete themes for this site.') );
check_admin_referer( 'bulk-themes' );
$themes = isset( $_REQUEST['checked'] ) ? (array) $_REQUEST['checked'] : array();
unset( $themes[ get_option( 'stylesheet' ) ], $themes[ get_option( 'template' ) ] );
if ( empty( $themes ) ) {
wp_safe_redirect( add_query_arg( 'error', 'none', $referer ) );
exit;
}
$files_to_delete = $theme_info = array();
foreach ( $themes as $key => $theme ) {
$theme_info[ $theme ] = wp_get_theme( $theme );
$files_to_delete = array_merge( $files_to_delete, list_files( $theme_info[ $theme ]->get_stylesheet_directory() ) );
}
if ( empty( $themes ) ) {
wp_safe_redirect( add_query_arg( 'error', 'main', $referer ) );
exit;
}
include(ABSPATH . 'wp-admin/update.php');
$parent_file = 'themes.php';
if ( ! isset( $_REQUEST['verify-delete'] ) ) {
wp_enqueue_script( 'jquery' );
require_once( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<?php
$themes_to_delete = count( $themes );
echo '<h2>' . _n( 'Delete Theme', 'Delete Themes', $themes_to_delete ) . '</h2>';
?>
<div class="error"><p><strong><?php _e( 'Caution:' ); ?></strong> <?php echo _n( 'This theme may be active on other sites in the network.', 'These themes may be active on other sites in the network.', $themes_to_delete ); ?></p></div>
<p><?php echo _n( 'You are about to remove the following theme:', 'You are about to remove the following themes:', $themes_to_delete ); ?></p>
<ul class="ul-disc">
<?php foreach ( $theme_info as $theme )
echo '<li>', sprintf( __('<strong>%1$s</strong> by <em>%2$s</em>' ), $theme->display('Name'), $theme->display('Author') ), '</li>'; /* translators: 1: theme name, 2: theme author */ ?>
</ul>
<p><?php _e('Are you sure you wish to delete these themes?'); ?></p>
<form method="post" action="<?php echo esc_url($_SERVER['REQUEST_URI']); ?>" style="display:inline;">
<input type="hidden" name="verify-delete" value="1" />
<input type="hidden" name="action" value="delete-selected" />
<?php
foreach ( (array) $themes as $theme )
echo '<input type="hidden" name="checked[]" value="' . esc_attr($theme) . '" />';
?>
<?php wp_nonce_field('bulk-themes') ?>
<?php submit_button( _n( 'Yes, Delete this theme', 'Yes, Delete these themes', $themes_to_delete ), 'button', 'submit', false ); ?>
</form>
<form method="post" action="<?php echo esc_url(wp_get_referer()); ?>" style="display:inline;">
<?php submit_button( __( 'No, Return me to the theme list' ), 'button', 'submit', false ); ?>
</form>
<p><a href="#" onclick="jQuery('#files-list').toggle(); return false;"><?php _e('Click to view entire list of files which will be deleted'); ?></a></p>
<div id="files-list" style="display:none;">
<ul class="code">
<?php
foreach ( (array) $files_to_delete as $file )
echo '<li>' . esc_html( str_replace( WP_CONTENT_DIR . "/themes", '', $file) ) . '</li>';
?>
</ul>
</div>
</div>
<?php
require_once(ABSPATH . 'wp-admin/admin-footer.php');
exit;
} // Endif verify-delete
foreach ( $themes as $theme ) {
$delete_result = delete_theme( $theme, esc_url( add_query_arg( array(
'verify-delete' => 1,
'action' => 'delete-selected',
'checked' => $_REQUEST['checked'],
'_wpnonce' => $_REQUEST['_wpnonce']
), network_admin_url( 'themes.php' ) ) ) );
}
$paged = ( $_REQUEST['paged'] ) ? $_REQUEST['paged'] : 1;
wp_redirect( add_query_arg( array(
'deleted' => count( $themes ),
'paged' => $paged,
's' => $s
), network_admin_url( 'themes.php' ) ) );
exit;
break;
}
}
$wp_list_table->prepare_items();
add_thickbox();
add_screen_option( 'per_page', array('label' => _x( 'Themes', 'themes per page (screen options)' )) );
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('This screen enables and disables the inclusion of themes available to choose in the Appearance menu for each site. It does not activate or deactivate which theme a site is currently using.') . '</p>' .
'<p>' . __('If the network admin disables a theme that is in use, it can still remain selected on that site. If another theme is chosen, the disabled theme will not appear in the site’s Appearance > Themes screen.') . '</p>' .
'<p>' . __('Themes can be enabled on a site by site basis by the network admin on the Edit Site screen (which has a Themes tab); get there via the Edit action link on the All Sites screen. Only network admins are able to install or edit themes.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Network_Admin_Themes_Screen" target="_blank">Documentation on Network Themes</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>'
);
$title = __('Themes');
$parent_file = 'themes.php';
wp_enqueue_script( 'theme-preview' );
require_once(ABSPATH . 'wp-admin/admin-header.php');
?>
<div class="wrap">
<h2><?php echo esc_html( $title ); if ( current_user_can('install_themes') ) { ?> <a href="theme-install.php" class="add-new-h2"><?php echo esc_html_x('Add New', 'theme'); ?></a><?php }
if ( $s )
printf( '<span class="subtitle">' . __('Search results for “%s”') . '</span>', esc_html( $s ) ); ?>
</h2>
<?php
if ( isset( $_GET['enabled'] ) ) {
$_GET['enabled'] = absint( $_GET['enabled'] );
echo '<div id="message" class="updated"><p>' . sprintf( _n( 'Theme enabled.', '%s themes enabled.', $_GET['enabled'] ), number_format_i18n( $_GET['enabled'] ) ) . '</p></div>';
} elseif ( isset( $_GET['disabled'] ) ) {
$_GET['disabled'] = absint( $_GET['disabled'] );
echo '<div id="message" class="updated"><p>' . sprintf( _n( 'Theme disabled.', '%s themes disabled.', $_GET['disabled'] ), number_format_i18n( $_GET['disabled'] ) ) . '</p></div>';
} elseif ( isset( $_GET['deleted'] ) ) {
$_GET['deleted'] = absint( $_GET['deleted'] );
echo '<div id="message" class="updated"><p>' . sprintf( _nx( 'Theme deleted.', '%s themes deleted.', $_GET['deleted'], 'network' ), number_format_i18n( $_GET['deleted'] ) ) . '</p></div>';
} elseif ( isset( $_GET['error'] ) && 'none' == $_GET['error'] ) {
echo '<div id="message" class="error"><p>' . __( 'No theme selected.' ) . '</p></div>';
} elseif ( isset( $_GET['error'] ) && 'main' == $_GET['error'] ) {
echo '<div class="error"><p>' . __( 'You cannot delete a theme while it is active on the main site.' ) . '</p></div>';
}
?>
<form method="get" action="">
<?php $wp_list_table->search_box( __( 'Search Installed Themes' ), 'theme' ); ?>
</form>
<?php
$wp_list_table->views();
if ( 'broken' == $status )
echo '<p class="clear">' . __('The following themes are installed but incomplete. Themes must have a stylesheet and a template.') . '</p>';
?>
<form method="post" action="">
<input type="hidden" name="theme_status" value="<?php echo esc_attr($status) ?>" />
<input type="hidden" name="paged" value="<?php echo esc_attr($page) ?>" />
<?php $wp_list_table->display(); ?>
</form>
</div>
<?php
include(ABSPATH . 'wp-admin/admin-footer.php');
| 01-wordpress-paypal | trunk/wp-admin/network/themes.php | PHP | gpl3 | 11,002 |
<?php
/**
* Install plugin network administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
if ( isset( $_GET['tab'] ) && ( 'plugin-information' == $_GET['tab'] ) )
define( 'IFRAME_REQUEST', true );
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/plugin-install.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/plugin-install.php | PHP | gpl3 | 469 |
<?php
/**
* Network About administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.4.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/about.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/about.php | PHP | gpl3 | 342 |
<?php
/**
* Install theme network administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
if ( isset( $_GET['tab'] ) && ( 'theme-information' == $_GET['tab'] ) )
define( 'IFRAME_REQUEST', true );
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/theme-install.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/theme-install.php | PHP | gpl3 | 466 |
<?php
/**
* Add New User network administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( ! current_user_can('create_users') )
wp_die(__('You do not have sufficient permissions to add users to this network.'));
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('Add User will set up a new user account on the network and send that person an email with username and password.') . '</p>' .
'<p>' . __('Users who are signed up to the network without a site are added as subscribers to the main or primary dashboard site, giving them profile pages to manage their accounts. These users will only see Dashboard and My Sites in the main navigation until a site is created for them.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Network_Admin_Users_Screen" target="_blank">Documentation on Network Users</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/forum/multisite/" target="_blank">Support Forums</a>') . '</p>'
);
if ( isset($_REQUEST['action']) && 'add-user' == $_REQUEST['action'] ) {
check_admin_referer( 'add-user', '_wpnonce_add-user' );
if ( ! current_user_can( 'manage_network_users' ) )
wp_die( __( 'You do not have permission to access this page.' ) );
if ( ! is_array( $_POST['user'] ) )
wp_die( __( 'Cannot create an empty user.' ) );
$user = $_POST['user'];
$user_details = wpmu_validate_user_signup( $user['username'], $user['email'] );
if ( is_wp_error( $user_details[ 'errors' ] ) && ! empty( $user_details[ 'errors' ]->errors ) ) {
$add_user_errors = $user_details[ 'errors' ];
} else {
$password = wp_generate_password( 12, false);
$user_id = wpmu_create_user( esc_html( strtolower( $user['username'] ) ), $password, esc_html( $user['email'] ) );
if ( ! $user_id ) {
$add_user_errors = new WP_Error( 'add_user_fail', __( 'Cannot add user.' ) );
} else {
wp_new_user_notification( $user_id, $password );
wp_redirect( add_query_arg( array('update' => 'added'), 'user-new.php' ) );
exit;
}
}
}
if ( isset($_GET['update']) ) {
$messages = array();
if ( 'added' == $_GET['update'] )
$messages[] = __('User added.');
}
$title = __('Add New User');
$parent_file = 'users.php';
require( ABSPATH . 'wp-admin/admin-header.php' ); ?>
<div class="wrap">
<h2 id="add-new-user"><?php _e('Add New User') ?></h2>
<?php
if ( ! empty( $messages ) ) {
foreach ( $messages as $msg )
echo '<div id="message" class="updated"><p>' . $msg . '</p></div>';
}
if ( isset( $add_user_errors ) && is_wp_error( $add_user_errors ) ) { ?>
<div class="error">
<?php
foreach ( $add_user_errors->get_error_messages() as $message )
echo "<p>$message</p>";
?>
</div>
<?php } ?>
<form action="<?php echo network_admin_url('user-new.php?action=add-user'); ?>" id="adduser" method="post">
<table class="form-table">
<tr class="form-field form-required">
<th scope="row"><?php _e( 'Username' ) ?></th>
<td><input type="text" class="regular-text" name="user[username]" /></td>
</tr>
<tr class="form-field form-required">
<th scope="row"><?php _e( 'Email' ) ?></th>
<td><input type="text" class="regular-text" name="user[email]" /></td>
</tr>
<tr class="form-field">
<td colspan="2"><?php _e( 'Username and password will be mailed to the above email address.' ) ?></td>
</tr>
</table>
<?php wp_nonce_field( 'add-user', '_wpnonce_add-user' ); ?>
<?php submit_button( __('Add User'), 'primary', 'add-user' ); ?>
</form>
</div>
<?php
require( ABSPATH . 'wp-admin/admin-footer.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/user-new.php | PHP | gpl3 | 3,899 |
<?php
/**
* User profile network administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/profile.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/profile.php | PHP | gpl3 | 351 |
<?php
/**
* Multisite users administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.0.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( ! current_user_can( 'manage_network_users' ) )
wp_die( __( 'You do not have permission to access this page.' ) );
function confirm_delete_users( $users ) {
$current_user = wp_get_current_user();
if ( !is_array( $users ) )
return false;
?>
<h2><?php esc_html_e( 'Users' ); ?></h2>
<p><?php _e( 'Transfer or delete content before deleting users.' ); ?></p>
<form action="users.php?action=dodelete" method="post">
<input type="hidden" name="dodelete" />
<?php
wp_nonce_field( 'ms-users-delete' );
$site_admins = get_super_admins();
$admin_out = "<option value='$current_user->ID'>$current_user->user_login</option>";
foreach ( ( $allusers = (array) $_POST['allusers'] ) as $key => $val ) {
if ( $val != '' && $val != '0' ) {
$delete_user = get_userdata( $val );
if ( ! current_user_can( 'delete_user', $delete_user->ID ) )
wp_die( sprintf( __( 'Warning! User %s cannot be deleted.' ), $delete_user->user_login ) );
if ( in_array( $delete_user->user_login, $site_admins ) )
wp_die( sprintf( __( 'Warning! User cannot be deleted. The user %s is a network administrator.' ), $delete_user->user_login ) );
echo "<input type='hidden' name='user[]' value='{$val}'/>\n";
$blogs = get_blogs_of_user( $val, true );
if ( !empty( $blogs ) ) {
?>
<br /><fieldset><p><legend><?php printf( __( "What should be done with content owned by %s?" ), '<em>' . $delete_user->user_login . '</em>' ); ?></legend></p>
<?php
foreach ( (array) $blogs as $key => $details ) {
$blog_users = get_users( array( 'blog_id' => $details->userblog_id, 'fields' => array( 'ID', 'user_login' ) ) );
if ( is_array( $blog_users ) && !empty( $blog_users ) ) {
$user_site = "<a href='" . esc_url( get_home_url( $details->userblog_id ) ) . "'>{$details->blogname}</a>";
$user_dropdown = "<select name='blog[$val][{$key}]'>";
$user_list = '';
foreach ( $blog_users as $user ) {
if ( ! in_array( $user->ID, $allusers ) )
$user_list .= "<option value='{$user->ID}'>{$user->user_login}</option>";
}
if ( '' == $user_list )
$user_list = $admin_out;
$user_dropdown .= $user_list;
$user_dropdown .= "</select>\n";
?>
<ul style="list-style:none;">
<li><?php printf( __( 'Site: %s' ), $user_site ); ?></li>
<li><label><input type="radio" id="delete_option0" name="delete[<?php echo $details->userblog_id . '][' . $delete_user->ID ?>]" value="delete" checked="checked" />
<?php _e( 'Delete all content.' ); ?></label></li>
<li><label><input type="radio" id="delete_option1" name="delete[<?php echo $details->userblog_id . '][' . $delete_user->ID ?>]" value="reassign" />
<?php echo __( 'Attribute all content to:' ) . '</label>' . $user_dropdown; ?></li>
</ul>
<?php
}
}
echo "</fieldset>";
}
}
}
submit_button( __('Confirm Deletion'), 'delete' );
?>
</form>
<?php
return true;
}
if ( isset( $_GET['action'] ) ) {
/** This action is documented in wp-admin/network/edit.php */
do_action( 'wpmuadminedit' );
switch ( $_GET['action'] ) {
case 'deleteuser':
if ( ! current_user_can( 'manage_network_users' ) )
wp_die( __( 'You do not have permission to access this page.' ) );
check_admin_referer( 'deleteuser' );
$id = intval( $_GET['id'] );
if ( $id != '0' && $id != '1' ) {
$_POST['allusers'] = array( $id ); // confirm_delete_users() can only handle with arrays
$title = __( 'Users' );
$parent_file = 'users.php';
require_once( ABSPATH . 'wp-admin/admin-header.php' );
echo '<div class="wrap">';
confirm_delete_users( $_POST['allusers'] );
echo '</div>';
require_once( ABSPATH . 'wp-admin/admin-footer.php' );
} else {
wp_redirect( network_admin_url( 'users.php' ) );
}
exit();
break;
case 'allusers':
if ( !current_user_can( 'manage_network_users' ) )
wp_die( __( 'You do not have permission to access this page.' ) );
if ( ( isset( $_POST['action']) || isset($_POST['action2'] ) ) && isset( $_POST['allusers'] ) ) {
check_admin_referer( 'bulk-users-network' );
$doaction = $_POST['action'] != -1 ? $_POST['action'] : $_POST['action2'];
$userfunction = '';
foreach ( (array) $_POST['allusers'] as $key => $val ) {
if ( !empty( $val ) ) {
switch ( $doaction ) {
case 'delete':
if ( ! current_user_can( 'delete_users' ) )
wp_die( __( 'You do not have permission to access this page.' ) );
$title = __( 'Users' );
$parent_file = 'users.php';
require_once( ABSPATH . 'wp-admin/admin-header.php' );
echo '<div class="wrap">';
confirm_delete_users( $_POST['allusers'] );
echo '</div>';
require_once( ABSPATH . 'wp-admin/admin-footer.php' );
exit();
break;
case 'spam':
$user = get_userdata( $val );
if ( is_super_admin( $user->ID ) )
wp_die( sprintf( __( 'Warning! User cannot be modified. The user %s is a network administrator.' ), esc_html( $user->user_login ) ) );
$userfunction = 'all_spam';
$blogs = get_blogs_of_user( $val, true );
foreach ( (array) $blogs as $key => $details ) {
if ( $details->userblog_id != $current_site->blog_id ) // main blog not a spam !
update_blog_status( $details->userblog_id, 'spam', '1' );
}
update_user_status( $val, 'spam', '1' );
break;
case 'notspam':
$userfunction = 'all_notspam';
$blogs = get_blogs_of_user( $val, true );
foreach ( (array) $blogs as $key => $details )
update_blog_status( $details->userblog_id, 'spam', '0' );
update_user_status( $val, 'spam', '0' );
break;
}
}
}
wp_safe_redirect( add_query_arg( array( 'updated' => 'true', 'action' => $userfunction ), wp_get_referer() ) );
} else {
$location = network_admin_url( 'users.php' );
if ( ! empty( $_REQUEST['paged'] ) )
$location = add_query_arg( 'paged', (int) $_REQUEST['paged'], $location );
wp_redirect( $location );
}
exit();
break;
case 'dodelete':
check_admin_referer( 'ms-users-delete' );
if ( ! ( current_user_can( 'manage_network_users' ) && current_user_can( 'delete_users' ) ) )
wp_die( __( 'You do not have permission to access this page.' ) );
if ( ! empty( $_POST['blog'] ) && is_array( $_POST['blog'] ) ) {
foreach ( $_POST['blog'] as $id => $users ) {
foreach ( $users as $blogid => $user_id ) {
if ( ! current_user_can( 'delete_user', $id ) )
continue;
if ( ! empty( $_POST['delete'] ) && 'reassign' == $_POST['delete'][$blogid][$id] )
remove_user_from_blog( $id, $blogid, $user_id );
else
remove_user_from_blog( $id, $blogid );
}
}
}
$i = 0;
if ( is_array( $_POST['user'] ) && ! empty( $_POST['user'] ) )
foreach( $_POST['user'] as $id ) {
if ( ! current_user_can( 'delete_user', $id ) )
continue;
wpmu_delete_user( $id );
$i++;
}
if ( $i == 1 )
$deletefunction = 'delete';
else
$deletefunction = 'all_delete';
wp_redirect( add_query_arg( array( 'updated' => 'true', 'action' => $deletefunction ), network_admin_url( 'users.php' ) ) );
exit();
break;
}
}
$wp_list_table = _get_list_table('WP_MS_Users_List_Table');
$pagenum = $wp_list_table->get_pagenum();
$wp_list_table->prepare_items();
$total_pages = $wp_list_table->get_pagination_arg( 'total_pages' );
if ( $pagenum > $total_pages && $total_pages > 0 ) {
wp_redirect( add_query_arg( 'paged', $total_pages ) );
exit;
}
$title = __( 'Users' );
$parent_file = 'users.php';
add_screen_option( 'per_page', array('label' => _x( 'Users', 'users per page (screen options)' )) );
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('This table shows all users across the network and the sites to which they are assigned.') . '</p>' .
'<p>' . __('Hover over any user on the list to make the edit links appear. The Edit link on the left will take you to their Edit User profile page; the Edit link on the right by any site name goes to an Edit Site screen for that site.') . '</p>' .
'<p>' . __('You can also go to the user’s profile page by clicking on the individual username.') . '</p>' .
'<p>' . __('You can sort the table by clicking on any of the bold headings and switch between list and excerpt views by using the icons in the upper right.') . '</p>' .
'<p>' . __('The bulk action will permanently delete selected users, or mark/unmark those selected as spam. Spam users will have posts removed and will be unable to sign up again with the same email addresses.') . '</p>' .
'<p>' . __('You can make an existing user an additional super admin by going to the Edit User profile page and checking the box to grant that privilege.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Network_Admin_Users_Screen" target="_blank">Documentation on Network Users</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/forum/multisite/" target="_blank">Support Forums</a>') . '</p>'
);
require_once( ABSPATH . 'wp-admin/admin-header.php' );
if ( isset( $_REQUEST['updated'] ) && $_REQUEST['updated'] == 'true' && ! empty( $_REQUEST['action'] ) ) {
?>
<div id="message" class="updated"><p>
<?php
switch ( $_REQUEST['action'] ) {
case 'delete':
_e( 'User deleted.' );
break;
case 'all_spam':
_e( 'Users marked as spam.' );
break;
case 'all_notspam':
_e( 'Users removed from spam.' );
break;
case 'all_delete':
_e( 'Users deleted.' );
break;
case 'add':
_e( 'User added.' );
break;
}
?>
</p></div>
<?php
}
?>
<div class="wrap">
<h2><?php esc_html_e( 'Users' );
if ( current_user_can( 'create_users') ) : ?>
<a href="<?php echo network_admin_url('user-new.php'); ?>" class="add-new-h2"><?php echo esc_html_x( 'Add New', 'user' ); ?></a><?php
endif;
if ( !empty( $usersearch ) )
printf( '<span class="subtitle">' . __( 'Search results for “%s”' ) . '</span>', esc_html( $usersearch ) );
?>
</h2>
<?php $wp_list_table->views(); ?>
<form action="" method="get" class="search-form">
<?php $wp_list_table->search_box( __( 'Search Users' ), 'all-user' ); ?>
</form>
<form id="form-user-list" action='users.php?action=allusers' method='post'>
<?php $wp_list_table->display(); ?>
</form>
</div>
<?php require_once( ABSPATH . 'wp-admin/admin-footer.php' ); ?>
| 01-wordpress-paypal | trunk/wp-admin/network/users.php | PHP | gpl3 | 10,991 |
<?php
/**
* Build Network Administration Menu.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/* translators: Network menu item */
$menu[2] = array(__('Dashboard'), 'manage_network', 'index.php', '', 'menu-top menu-top-first menu-icon-dashboard', 'menu-dashboard', 'dashicons-dashboard');
$menu[4] = array( '', 'read', 'separator1', '', 'wp-menu-separator' );
/* translators: Sites menu item */
$menu[5] = array(__('Sites'), 'manage_sites', 'sites.php', '', 'menu-top menu-icon-site', 'menu-site', 'dashicons-admin-network');
$submenu['sites.php'][5] = array( __('All Sites'), 'manage_sites', 'sites.php' );
$submenu['sites.php'][10] = array( _x('Add New', 'site'), 'create_sites', 'site-new.php' );
$menu[10] = array(__('Users'), 'manage_network_users', 'users.php', '', 'menu-top menu-icon-users', 'menu-users', 'dashicons-admin-users');
$submenu['users.php'][5] = array( __('All Users'), 'manage_network_users', 'users.php' );
$submenu['users.php'][10] = array( _x('Add New', 'user'), 'create_users', 'user-new.php' );
$update_data = wp_get_update_data();
if ( $update_data['counts']['themes'] ) {
$menu[15] = array(sprintf( __( 'Themes %s' ), "<span class='update-plugins count-{$update_data['counts']['themes']}'><span class='theme-count'>" . number_format_i18n( $update_data['counts']['themes'] ) . "</span></span>" ), 'manage_network_themes', 'themes.php', '', 'menu-top menu-icon-appearance', 'menu-appearance', 'dashicons-admin-appearance' );
} else {
$menu[15] = array( __( 'Themes' ), 'manage_network_themes', 'themes.php', '', 'menu-top menu-icon-appearance', 'menu-appearance', 'dashicons-admin-appearance' );
}
$submenu['themes.php'][5] = array( __('Installed Themes'), 'manage_network_themes', 'themes.php' );
$submenu['themes.php'][10] = array( _x('Add New', 'theme'), 'install_themes', 'theme-install.php' );
$submenu['themes.php'][15] = array( _x('Editor', 'theme editor'), 'edit_themes', 'theme-editor.php' );
if ( current_user_can( 'update_plugins' ) ) {
$menu[20] = array( sprintf( __( 'Plugins %s' ), "<span class='update-plugins count-{$update_data['counts']['plugins']}'><span class='plugin-count'>" . number_format_i18n( $update_data['counts']['plugins'] ) . "</span></span>" ), 'manage_network_plugins', 'plugins.php', '', 'menu-top menu-icon-plugins', 'menu-plugins', 'dashicons-admin-plugins');
} else {
$menu[20] = array( __('Plugins'), 'manage_network_plugins', 'plugins.php', '', 'menu-top menu-icon-plugins', 'menu-plugins', 'dashicons-admin-plugins' );
}
$submenu['plugins.php'][5] = array( __('Installed Plugins'), 'manage_network_plugins', 'plugins.php' );
$submenu['plugins.php'][10] = array( _x('Add New', 'plugin'), 'install_plugins', 'plugin-install.php' );
$submenu['plugins.php'][15] = array( _x('Editor', 'plugin editor'), 'edit_plugins', 'plugin-editor.php' );
$menu[25] = array(__('Settings'), 'manage_network_options', 'settings.php', '', 'menu-top menu-icon-settings', 'menu-settings', 'dashicons-admin-settings');
if ( defined( 'MULTISITE' ) && defined( 'WP_ALLOW_MULTISITE' ) && WP_ALLOW_MULTISITE ) {
$submenu['settings.php'][5] = array( __('Network Settings'), 'manage_network_options', 'settings.php' );
$submenu['settings.php'][10] = array( __('Network Setup'), 'manage_network_options', 'setup.php' );
}
if ( $update_data['counts']['total'] ) {
$menu[30] = array( sprintf( __( 'Updates %s' ), "<span class='update-plugins count-{$update_data['counts']['total']}' title='{$update_data['title']}'><span class='update-count'>" . number_format_i18n($update_data['counts']['total']) . "</span></span>" ), 'manage_network', 'upgrade.php', '', 'menu-top menu-icon-tools', 'menu-update', 'dashicons-admin-tools' );
} else {
$menu[30] = array( __( 'Updates' ), 'manage_network', 'upgrade.php', '', 'menu-top menu-icon-tools', 'menu-update', 'dashicons-admin-tools' );
}
unset($update_data);
$submenu[ 'upgrade.php' ][10] = array( __( 'Available Updates' ), 'update_core', 'update-core.php' );
$submenu[ 'upgrade.php' ][15] = array( __( 'Upgrade Network' ), 'manage_network', 'upgrade.php' );
$menu[99] = array( '', 'exist', 'separator-last', '', 'wp-menu-separator' );
require_once(ABSPATH . 'wp-admin/includes/menu.php');
| 01-wordpress-paypal | trunk/wp-admin/network/menu.php | PHP | gpl3 | 4,219 |
<?php
/**
* WordPress Network Administration Bootstrap
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
define( 'WP_NETWORK_ADMIN', true );
/** Load WordPress Administration Bootstrap */
require_once( dirname( dirname( __FILE__ ) ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
$redirect_network_admin_request = 0 !== strcasecmp( $current_blog->domain, $current_site->domain ) || 0 !== strcasecmp( $current_blog->path, $current_site->path );
/**
* Filter whether to redirect the request to the Network Admin.
*
* @since 3.2.0
*
* @param bool $redirect_network_admin_request Whether the request should be redirected.
*/
$redirect_network_admin_request = apply_filters( 'redirect_network_admin_request', $redirect_network_admin_request );
if ( $redirect_network_admin_request ) {
wp_redirect( network_admin_url() );
exit;
}
unset( $redirect_network_admin_request );
| 01-wordpress-paypal | trunk/wp-admin/network/admin.php | PHP | gpl3 | 949 |
<?php
/**
* Network Credits administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.4.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/credits.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/credits.php | PHP | gpl3 | 346 |
<?php
/**
* Theme editor network administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/theme-editor.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/theme-editor.php | PHP | gpl3 | 356 |
<?php
/**
* Updates network administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/update-core.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/update-core.php | PHP | gpl3 | 350 |
<?php
/**
* Plugin editor network administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/plugin-editor.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/plugin-editor.php | PHP | gpl3 | 358 |
<?php
/**
* Network Freedoms administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.4.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/freedoms.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/freedoms.php | PHP | gpl3 | 348 |
<?php
/**
* Network Plugins administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/plugins.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/plugins.php | PHP | gpl3 | 346 |
<?php
/**
* Multisite sites administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.0.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( ! current_user_can( 'manage_sites' ) )
wp_die( __( 'You do not have permission to access this page.' ) );
$wp_list_table = _get_list_table( 'WP_MS_Sites_List_Table' );
$pagenum = $wp_list_table->get_pagenum();
$title = __( 'Sites' );
$parent_file = 'sites.php';
add_screen_option( 'per_page', array( 'label' => _x( 'Sites', 'sites per page (screen options)' ) ) );
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('Add New takes you to the Add New Site screen. You can search for a site by Name, ID number, or IP address. Screen Options allows you to choose how many sites to display on one page.') . '</p>' .
'<p>' . __('This is the main table of all sites on this network. Switch between list and excerpt views by using the icons above the right side of the table.') . '</p>' .
'<p>' . __('Hovering over each site reveals seven options (three for the primary site):') . '</p>' .
'<ul><li>' . __('An Edit link to a separate Edit Site screen.') . '</li>' .
'<li>' . __('Dashboard leads to the Dashboard for that site.') . '</li>' .
'<li>' . __('Deactivate, Archive, and Spam which lead to confirmation screens. These actions can be reversed later.') . '</li>' .
'<li>' . __('Delete which is a permanent action after the confirmation screens.') . '</li>' .
'<li>' . __('Visit to go to the frontend site live.') . '</li></ul>' .
'<p>' . __('The site ID is used internally, and is not shown on the front end of the site or to users/viewers.') . '</p>' .
'<p>' . __('Clicking on bold headings can re-sort this table.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Network_Admin_Sites_Screen" target="_blank">Documentation on Site Management</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/forum/multisite/" target="_blank">Support Forums</a>') . '</p>'
);
$id = isset( $_REQUEST['id'] ) ? intval( $_REQUEST['id'] ) : 0;
if ( isset( $_GET['action'] ) ) {
/** This action is documented in wp-admin/network/edit.php */
do_action( 'wpmuadminedit' );
if ( 'confirm' === $_GET['action'] ) {
check_admin_referer( 'confirm' );
if ( ! headers_sent() ) {
nocache_headers();
header( 'Content-Type: text/html; charset=utf-8' );
}
if ( $current_site->blog_id == $id ) {
wp_die( __( 'You are not allowed to change the current site.' ) );
}
require_once( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2><?php _e( 'Confirm your action' ); ?></h2>
<form action="sites.php?action=<?php echo esc_attr( $_GET['action2'] ) ?>" method="post">
<input type="hidden" name="action" value="<?php echo esc_attr( $_GET['action2'] ) ?>" />
<input type="hidden" name="id" value="<?php echo esc_attr( $id ); ?>" />
<input type="hidden" name="_wp_http_referer" value="<?php echo esc_attr( wp_get_referer() ); ?>" />
<?php wp_nonce_field( $_GET['action2'], '_wpnonce', false ); ?>
<p><?php echo esc_html( wp_unslash( $_GET['msg'] ) ); ?></p>
<?php submit_button( __( 'Confirm' ), 'button' ); ?>
</form>
</div>
<?php
require_once( ABSPATH . 'wp-admin/admin-footer.php' );
exit();
}
$updated_action = '';
$manage_actions = array( 'deleteblog', 'allblogs', 'archiveblog', 'unarchiveblog', 'activateblog', 'deactivateblog', 'unspamblog', 'spamblog', 'unmatureblog', 'matureblog' );
if ( in_array( $_GET['action'], $manage_actions ) ) {
$action = $_GET['action'];
if ( 'allblogs' === $action )
$action = 'bulk-sites';
check_admin_referer( $action );
}
switch ( $_GET['action'] ) {
case 'deleteblog':
if ( ! current_user_can( 'delete_sites' ) )
wp_die( __( 'You do not have permission to access this page.' ) );
$updated_action = 'not_deleted';
if ( $id != '0' && $id != $current_site->blog_id && current_user_can( 'delete_site', $id ) ) {
wpmu_delete_blog( $id, true );
$updated_action = 'delete';
}
break;
case 'allblogs':
if ( ( isset( $_POST['action'] ) || isset( $_POST['action2'] ) ) && isset( $_POST['allblogs'] ) ) {
$doaction = $_POST['action'] != -1 ? $_POST['action'] : $_POST['action2'];
foreach ( (array) $_POST['allblogs'] as $key => $val ) {
if ( $val != '0' && $val != $current_site->blog_id ) {
switch ( $doaction ) {
case 'delete':
if ( ! current_user_can( 'delete_site', $val ) )
wp_die( __( 'You are not allowed to delete the site.' ) );
$updated_action = 'all_delete';
wpmu_delete_blog( $val, true );
break;
case 'spam':
case 'notspam':
$updated_action = ( 'spam' === $doaction ) ? 'all_spam' : 'all_notspam';
update_blog_status( $val, 'spam', ( 'spam' === $doaction ) ? '1' : '0' );
break;
}
} else {
wp_die( __( 'You are not allowed to change the current site.' ) );
}
}
} else {
wp_redirect( network_admin_url( 'sites.php' ) );
exit();
}
break;
case 'archiveblog':
case 'unarchiveblog':
update_blog_status( $id, 'archived', ( 'archiveblog' === $_GET['action'] ) ? '1' : '0' );
break;
case 'activateblog':
update_blog_status( $id, 'deleted', '0' );
/**
* Fires after a network site is activated.
*
* @since MU
*
* @param string $id The ID of the activated site.
*/
do_action( 'activate_blog', $id );
break;
case 'deactivateblog':
/**
* Fires before a network site is deactivated.
*
* @since MU
*
* @param string $id The ID of the site being deactivated.
*/
do_action( 'deactivate_blog', $id );
update_blog_status( $id, 'deleted', '1' );
break;
case 'unspamblog':
case 'spamblog':
update_blog_status( $id, 'spam', ( 'spamblog' === $_GET['action'] ) ? '1' : '0' );
break;
case 'unmatureblog':
case 'matureblog':
update_blog_status( $id, 'mature', ( 'matureblog' === $_GET['action'] ) ? '1' : '0' );
break;
}
if ( empty( $updated_action ) && in_array( $_GET['action'], $manage_actions ) )
$updated_action = $_GET['action'];
if ( ! empty( $updated_action ) ) {
wp_safe_redirect( add_query_arg( array( 'updated' => $updated_action ), wp_get_referer() ) );
exit();
}
}
$msg = '';
if ( isset( $_GET['updated'] ) ) {
switch ( $_GET['updated'] ) {
case 'all_notspam':
$msg = __( 'Sites removed from spam.' );
break;
case 'all_spam':
$msg = __( 'Sites marked as spam.' );
break;
case 'all_delete':
$msg = __( 'Sites deleted.' );
break;
case 'delete':
$msg = __( 'Site deleted.' );
break;
case 'not_deleted':
$msg = __( 'You do not have permission to delete that site.' );
break;
case 'archiveblog':
$msg = __( 'Site archived.' );
break;
case 'unarchiveblog':
$msg = __( 'Site unarchived.' );
break;
case 'activateblog':
$msg = __( 'Site activated.' );
break;
case 'deactivateblog':
$msg = __( 'Site deactivated.' );
break;
case 'unspamblog':
$msg = __( 'Site removed from spam.' );
break;
case 'spamblog':
$msg = __( 'Site marked as spam.' );
break;
default:
/**
* Filter a specific, non-default site-updated message in the Network admin.
*
* The dynamic portion of the hook name, $_GET['updated'], refers to the non-default
* site update action.
*
* @since 3.1.0
*
* @param string $msg The update message. Default 'Settings saved'.
*/
$msg = apply_filters( 'network_sites_updated_message_' . $_GET['updated'], __( 'Settings saved.' ) );
break;
}
if ( ! empty( $msg ) )
$msg = '<div class="updated" id="message"><p>' . $msg . '</p></div>';
}
$wp_list_table->prepare_items();
require_once( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2><?php _e( 'Sites' ) ?>
<?php if ( current_user_can( 'create_sites') ) : ?>
<a href="<?php echo network_admin_url('site-new.php'); ?>" class="add-new-h2"><?php echo esc_html_x( 'Add New', 'site' ); ?></a>
<?php endif; ?>
<?php if ( isset( $_REQUEST['s'] ) && $_REQUEST['s'] ) {
printf( '<span class="subtitle">' . __( 'Search results for “%s”' ) . '</span>', esc_html( $s ) );
} ?>
</h2>
<?php echo $msg; ?>
<form action="" method="get" id="ms-search">
<?php $wp_list_table->search_box( __( 'Search Sites' ), 'site' ); ?>
<input type="hidden" name="action" value="blogs" />
</form>
<form id="form-site-list" action="sites.php?action=allblogs" method="post">
<?php $wp_list_table->display(); ?>
</form>
</div>
<?php
require_once( ABSPATH . 'wp-admin/admin-footer.php' ); ?>
| 01-wordpress-paypal | trunk/wp-admin/network/sites.php | PHP | gpl3 | 8,929 |
<?php
/**
* Edit Site Info Administration Screen
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( ! current_user_can( 'manage_sites' ) )
wp_die( __( 'You do not have sufficient permissions to edit this site.' ) );
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('The menu is for editing information specific to individual sites, particularly if the admin area of a site is unavailable.') . '</p>' .
'<p>' . __('<strong>Info</strong> - The domain and path are rarely edited as this can cause the site to not work properly. The Registered date and Last Updated date are displayed. Network admins can mark a site as archived, spam, deleted and mature, to remove from public listings or disable.') . '</p>' .
'<p>' . __('<strong>Users</strong> - This displays the users associated with this site. You can also change their role, reset their password, or remove them from the site. Removing the user from the site does not remove the user from the network.') . '</p>' .
'<p>' . sprintf( __('<strong>Themes</strong> - This area shows themes that are not already enabled across the network. Enabling a theme in this menu makes it accessible to this site. It does not activate the theme, but allows it to show in the site’s Appearance menu. To enable a theme for the entire network, see the <a href="%s">Network Themes</a> screen.' ), network_admin_url( 'themes.php' ) ) . '</p>' .
'<p>' . __('<strong>Settings</strong> - This page shows a list of all settings associated with this site. Some are created by WordPress and others are created by plugins you activate. Note that some fields are grayed out and say Serialized Data. You cannot modify these values due to the way the setting is stored in the database.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Network_Admin_Sites_Screen" target="_blank">Documentation on Site Management</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/forum/multisite/" target="_blank">Support Forums</a>') . '</p>'
);
$id = isset( $_REQUEST['id'] ) ? intval( $_REQUEST['id'] ) : 0;
if ( ! $id )
wp_die( __('Invalid site ID.') );
$details = get_blog_details( $id );
if ( !can_edit_network( $details->site_id ) )
wp_die( __( 'You do not have permission to access this page.' ) );
$is_main_site = is_main_site( $id );
if ( isset($_REQUEST['action']) && 'update-site' == $_REQUEST['action'] ) {
check_admin_referer( 'edit-site' );
switch_to_blog( $id );
if ( isset( $_POST['update_home_url'] ) && $_POST['update_home_url'] == 'update' ) {
$blog_address = esc_url_raw( $_POST['blog']['domain'] . $_POST['blog']['path'] );
if ( get_option( 'siteurl' ) != $blog_address )
update_option( 'siteurl', $blog_address );
if ( get_option( 'home' ) != $blog_address )
update_option( 'home', $blog_address );
}
// rewrite rules can't be flushed during switch to blog
delete_option( 'rewrite_rules' );
// update blogs table
$blog_data = wp_unslash( $_POST['blog'] );
$existing_details = get_blog_details( $id, false );
$blog_data_checkboxes = array( 'public', 'archived', 'spam', 'mature', 'deleted' );
foreach ( $blog_data_checkboxes as $c ) {
if ( ! in_array( $existing_details->$c, array( 0, 1 ) ) )
$blog_data[ $c ] = $existing_details->$c;
else
$blog_data[ $c ] = isset( $_POST['blog'][ $c ] ) ? 1 : 0;
}
update_blog_details( $id, $blog_data );
restore_current_blog();
wp_redirect( add_query_arg( array( 'update' => 'updated', 'id' => $id ), 'site-info.php') );
exit;
}
if ( isset($_GET['update']) ) {
$messages = array();
if ( 'updated' == $_GET['update'] )
$messages[] = __('Site info updated.');
}
$site_url_no_http = preg_replace( '#^http(s)?://#', '', get_blogaddress_by_id( $id ) );
$title_site_url_linked = sprintf( __('Edit Site: <a href="%1$s">%2$s</a>'), get_blogaddress_by_id( $id ), $site_url_no_http );
$title = sprintf( __('Edit Site: %s'), $site_url_no_http );
$parent_file = 'sites.php';
$submenu_file = 'sites.php';
require( ABSPATH . 'wp-admin/admin-header.php' );
?>
<div class="wrap">
<h2 id="edit-site"><?php echo $title_site_url_linked ?></h2>
<h3 class="nav-tab-wrapper">
<?php
$tabs = array(
'site-info' => array( 'label' => __( 'Info' ), 'url' => 'site-info.php' ),
'site-users' => array( 'label' => __( 'Users' ), 'url' => 'site-users.php' ),
'site-themes' => array( 'label' => __( 'Themes' ), 'url' => 'site-themes.php' ),
'site-settings' => array( 'label' => __( 'Settings' ), 'url' => 'site-settings.php' ),
);
foreach ( $tabs as $tab_id => $tab ) {
$class = ( $tab['url'] == $pagenow ) ? ' nav-tab-active' : '';
echo '<a href="' . $tab['url'] . '?id=' . $id .'" class="nav-tab' . $class . '">' . esc_html( $tab['label'] ) . '</a>';
}
?>
</h3>
<?php
if ( ! empty( $messages ) ) {
foreach ( $messages as $msg )
echo '<div id="message" class="updated"><p>' . $msg . '</p></div>';
} ?>
<form method="post" action="site-info.php?action=update-site">
<?php wp_nonce_field( 'edit-site' ); ?>
<input type="hidden" name="id" value="<?php echo esc_attr( $id ) ?>" />
<table class="form-table">
<tr class="form-field form-required">
<th scope="row"><?php _e( 'Domain' ) ?></th>
<?php
$protocol = is_ssl() ? 'https://' : 'http://';
if ( $is_main_site ) { ?>
<td><code><?php echo $protocol; echo esc_attr( $details->domain ) ?></code></td>
<?php } else { ?>
<td><?php echo $protocol; ?><input name="blog[domain]" type="text" id="domain" value="<?php echo esc_attr( $details->domain ) ?>" size="33" /></td>
<?php } ?>
</tr>
<tr class="form-field form-required">
<th scope="row"><?php _e( 'Path' ) ?></th>
<?php if ( $is_main_site ) { ?>
<td><code><?php echo esc_attr( $details->path ) ?></code></td>
<?php
} else {
switch_to_blog( $id );
?>
<td><input name="blog[path]" type="text" id="path" value="<?php echo esc_attr( $details->path ) ?>" size="40" style='margin-bottom:5px;' />
<br /><input type="checkbox" style="width:20px;" name="update_home_url" value="update" <?php if ( get_option( 'siteurl' ) == untrailingslashit( get_blogaddress_by_id ($id ) ) || get_option( 'home' ) == untrailingslashit( get_blogaddress_by_id( $id ) ) ) echo 'checked="checked"'; ?> /> <?php _e( 'Update <code>siteurl</code> and <code>home</code> as well.' ); ?></td>
<?php
restore_current_blog();
} ?>
</tr>
<tr class="form-field">
<th scope="row"><?php _ex( 'Registered', 'site' ) ?></th>
<td><input name="blog[registered]" type="text" id="blog_registered" value="<?php echo esc_attr( $details->registered ) ?>" size="40" /></td>
</tr>
<tr class="form-field">
<th scope="row"><?php _e( 'Last Updated' ); ?></th>
<td><input name="blog[last_updated]" type="text" id="blog_last_updated" value="<?php echo esc_attr( $details->last_updated ) ?>" size="40" /></td>
</tr>
<?php
$attribute_fields = array( 'public' => __( 'Public' ) );
if ( ! $is_main_site ) {
$attribute_fields['archived'] = __( 'Archived' );
$attribute_fields['spam'] = _x( 'Spam', 'site' );
$attribute_fields['deleted'] = __( 'Deleted' );
}
$attribute_fields['mature'] = __( 'Mature' );
?>
<tr>
<th scope="row"><?php _e( 'Attributes' ); ?></th>
<td>
<?php foreach ( $attribute_fields as $field_key => $field_label ) : ?>
<label><input type="checkbox" name="blog[<?php echo $field_key; ?>]" value="1" <?php checked( (bool) $details->$field_key, true ); disabled( ! in_array( $details->$field_key, array( 0, 1 ) ) ); ?> />
<?php echo $field_label; ?></label><br/>
<?php endforeach; ?>
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
require( ABSPATH . 'wp-admin/admin-footer.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/site-info.php | PHP | gpl3 | 8,077 |
<?php
/**
* Update/Install Plugin/Theme network administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
if ( isset( $_GET['action'] ) && in_array( $_GET['action'], array( 'update-selected', 'activate-plugin', 'update-selected-themes' ) ) )
define( 'IFRAME_REQUEST', true );
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/update.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/update.php | PHP | gpl3 | 537 |
<?php
/**
* Edit Site Themes Administration Screen
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( ! current_user_can( 'manage_sites' ) )
wp_die( __( 'You do not have sufficient permissions to manage themes for this site.' ) );
get_current_screen()->add_help_tab( array(
'id' => 'overview',
'title' => __('Overview'),
'content' =>
'<p>' . __('The menu is for editing information specific to individual sites, particularly if the admin area of a site is unavailable.') . '</p>' .
'<p>' . __('<strong>Info</strong> - The domain and path are rarely edited as this can cause the site to not work properly. The Registered date and Last Updated date are displayed. Network admins can mark a site as archived, spam, deleted and mature, to remove from public listings or disable.') . '</p>' .
'<p>' . __('<strong>Users</strong> - This displays the users associated with this site. You can also change their role, reset their password, or remove them from the site. Removing the user from the site does not remove the user from the network.') . '</p>' .
'<p>' . sprintf( __('<strong>Themes</strong> - This area shows themes that are not already enabled across the network. Enabling a theme in this menu makes it accessible to this site. It does not activate the theme, but allows it to show in the site’s Appearance menu. To enable a theme for the entire network, see the <a href="%s">Network Themes</a> screen.' ), network_admin_url( 'themes.php' ) ) . '</p>' .
'<p>' . __('<strong>Settings</strong> - This page shows a list of all settings associated with this site. Some are created by WordPress and others are created by plugins you activate. Note that some fields are grayed out and say Serialized Data. You cannot modify these values due to the way the setting is stored in the database.') . '</p>'
) );
get_current_screen()->set_help_sidebar(
'<p><strong>' . __('For more information:') . '</strong></p>' .
'<p>' . __('<a href="http://codex.wordpress.org/Network_Admin_Sites_Screen" target="_blank">Documentation on Site Management</a>') . '</p>' .
'<p>' . __('<a href="https://wordpress.org/support/forum/multisite/" target="_blank">Support Forums</a>') . '</p>'
);
$wp_list_table = _get_list_table('WP_MS_Themes_List_Table');
$action = $wp_list_table->current_action();
$s = isset($_REQUEST['s']) ? $_REQUEST['s'] : '';
// Clean up request URI from temporary args for screen options/paging uri's to work as expected.
$temp_args = array( 'enabled', 'disabled', 'error' );
$_SERVER['REQUEST_URI'] = remove_query_arg( $temp_args, $_SERVER['REQUEST_URI'] );
$referer = remove_query_arg( $temp_args, wp_get_referer() );
if ( ! empty( $_REQUEST['paged'] ) ) {
$referer = add_query_arg( 'paged', (int) $_REQUEST['paged'], $referer );
}
$id = isset( $_REQUEST['id'] ) ? intval( $_REQUEST['id'] ) : 0;
if ( ! $id )
wp_die( __('Invalid site ID.') );
$wp_list_table->prepare_items();
$details = get_blog_details( $id );
if ( !can_edit_network( $details->site_id ) )
wp_die( __( 'You do not have permission to access this page.' ) );
$is_main_site = is_main_site( $id );
if ( $action ) {
switch_to_blog( $id );
$allowed_themes = get_option( 'allowedthemes' );
switch ( $action ) {
case 'enable':
check_admin_referer( 'enable-theme_' . $_GET['theme'] );
$theme = $_GET['theme'];
$action = 'enabled';
$n = 1;
if ( !$allowed_themes )
$allowed_themes = array( $theme => true );
else
$allowed_themes[$theme] = true;
break;
case 'disable':
check_admin_referer( 'disable-theme_' . $_GET['theme'] );
$theme = $_GET['theme'];
$action = 'disabled';
$n = 1;
if ( !$allowed_themes )
$allowed_themes = array();
else
unset( $allowed_themes[$theme] );
break;
case 'enable-selected':
check_admin_referer( 'bulk-themes' );
if ( isset( $_POST['checked'] ) ) {
$themes = (array) $_POST['checked'];
$action = 'enabled';
$n = count( $themes );
foreach( (array) $themes as $theme )
$allowed_themes[ $theme ] = true;
} else {
$action = 'error';
$n = 'none';
}
break;
case 'disable-selected':
check_admin_referer( 'bulk-themes' );
if ( isset( $_POST['checked'] ) ) {
$themes = (array) $_POST['checked'];
$action = 'disabled';
$n = count( $themes );
foreach( (array) $themes as $theme )
unset( $allowed_themes[ $theme ] );
} else {
$action = 'error';
$n = 'none';
}
break;
}
update_option( 'allowedthemes', $allowed_themes );
restore_current_blog();
wp_safe_redirect( add_query_arg( array( 'id' => $id, $action => $n ), $referer ) );
exit;
}
if ( isset( $_GET['action'] ) && 'update-site' == $_GET['action'] ) {
wp_safe_redirect( $referer );
exit();
}
add_thickbox();
add_screen_option( 'per_page', array( 'label' => _x( 'Themes', 'themes per page (screen options)' ) ) );
$site_url_no_http = preg_replace( '#^http(s)?://#', '', get_blogaddress_by_id( $id ) );
$title_site_url_linked = sprintf( __('Edit Site: <a href="%1$s">%2$s</a>'), get_blogaddress_by_id( $id ), $site_url_no_http );
$title = sprintf( __('Edit Site: %s'), $site_url_no_http );
$parent_file = 'sites.php';
$submenu_file = 'sites.php';
require( ABSPATH . 'wp-admin/admin-header.php' ); ?>
<div class="wrap">
<h2 id="edit-site"><?php echo $title_site_url_linked ?></h2>
<h3 class="nav-tab-wrapper">
<?php
$tabs = array(
'site-info' => array( 'label' => __( 'Info' ), 'url' => 'site-info.php' ),
'site-users' => array( 'label' => __( 'Users' ), 'url' => 'site-users.php' ),
'site-themes' => array( 'label' => __( 'Themes' ), 'url' => 'site-themes.php' ),
'site-settings' => array( 'label' => __( 'Settings' ), 'url' => 'site-settings.php' ),
);
foreach ( $tabs as $tab_id => $tab ) {
$class = ( $tab['url'] == $pagenow ) ? ' nav-tab-active' : '';
echo '<a href="' . $tab['url'] . '?id=' . $id .'" class="nav-tab' . $class . '">' . esc_html( $tab['label'] ) . '</a>';
}
?>
</h3><?php
if ( isset( $_GET['enabled'] ) ) {
$_GET['enabled'] = absint( $_GET['enabled'] );
echo '<div id="message" class="updated"><p>' . sprintf( _n( 'Theme enabled.', '%s themes enabled.', $_GET['enabled'] ), number_format_i18n( $_GET['enabled'] ) ) . '</p></div>';
} elseif ( isset( $_GET['disabled'] ) ) {
$_GET['disabled'] = absint( $_GET['disabled'] );
echo '<div id="message" class="updated"><p>' . sprintf( _n( 'Theme disabled.', '%s themes disabled.', $_GET['disabled'] ), number_format_i18n( $_GET['disabled'] ) ) . '</p></div>';
} elseif ( isset( $_GET['error'] ) && 'none' == $_GET['error'] ) {
echo '<div id="message" class="error"><p>' . __( 'No theme selected.' ) . '</p></div>';
} ?>
<p><?php _e( 'Network enabled themes are not shown on this screen.' ) ?></p>
<form method="get" action="">
<?php $wp_list_table->search_box( __( 'Search Installed Themes' ), 'theme' ); ?>
<input type="hidden" name="id" value="<?php echo esc_attr( $id ) ?>" />
</form>
<?php $wp_list_table->views(); ?>
<form method="post" action="site-themes.php?action=update-site">
<input type="hidden" name="id" value="<?php echo esc_attr( $id ) ?>" />
<?php $wp_list_table->display(); ?>
</form>
</div>
<?php include(ABSPATH . 'wp-admin/admin-footer.php'); ?>
| 01-wordpress-paypal | trunk/wp-admin/network/site-themes.php | PHP | gpl3 | 7,425 |
<?php
/**
* Action handler for Multisite administration panels.
*
* @package WordPress
* @subpackage Multisite
* @since 3.0.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
if ( empty( $_GET['action'] ) ) {
wp_redirect( network_admin_url() );
exit;
}
/**
* Fires just before the action handler in several Network Admin screens.
*
* This hook fires on multiple screens in the Multisite Network Admin,
* including Users, Network Settings, and Site Settings.
*
* @since 3.0.0
*/
do_action( 'wpmuadminedit' );
/**
* Fires the requested handler action.
*
* The dynamic portion of the hook name, $_GET['action'], refers to the name
* of the requested action.
*
* @since 3.1.0
*/
do_action( 'network_admin_edit_' . $_GET['action'] );
wp_redirect( network_admin_url() );
exit();
| 01-wordpress-paypal | trunk/wp-admin/network/edit.php | PHP | gpl3 | 932 |
<?php
/**
* Network Setup administration panel.
*
* @package WordPress
* @subpackage Multisite
* @since 3.1.0
*/
/** Load WordPress Administration Bootstrap */
require_once( dirname( __FILE__ ) . '/admin.php' );
if ( ! is_multisite() )
wp_die( __( 'Multisite support is not enabled.' ) );
require( ABSPATH . 'wp-admin/network.php' );
| 01-wordpress-paypal | trunk/wp-admin/network/setup.php | PHP | gpl3 | 344 |