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
/* Distraction Free Writing mode TinyMCE Styles */ html, body { background: transparent; width: auto !important; max-width: none !important; margin: 0 !important; padding: 0 !important; min-height: 0 !important; }
zyblog
trunk/zyblog/wp-includes/js/tinymce/plugins/wpfullscreen/css/wp-fullscreen.css
CSS
asf20
221
(function() { tinymce.create('tinymce.plugins.wpLink', { /** * Initializes the plugin, this will be executed after the plugin has been created. * This call is done before the editor instance has finished it's initialization so use the onInit event * of the editor instance to intercept that event. * * @param {tinymce.Editor} ed Editor instance that the plugin is initialized in. * @param {string} url Absolute URL to where the plugin is located. */ init : function(ed, url) { var disabled = true; // Register the command so that it can be invoked by using tinyMCE.activeEditor.execCommand('mceExample'); ed.addCommand('WP_Link', function() { if ( disabled ) return; ed.windowManager.open({ id : 'wp-link', width : 480, height : "auto", wpDialog : true, title : ed.getLang('advlink.link_desc') }, { plugin_url : url // Plugin absolute URL }); }); // Register example button ed.addButton('link', { title : 'advanced.link_desc', cmd : 'WP_Link' }); ed.onNodeChange.add(function(ed, cm, n, co) { disabled = co && n.nodeName != 'A'; }); }, /** * Returns information about the plugin as a name/value array. * The current keys are longname, author, authorurl, infourl and version. * * @return {Object} Name/value array containing information about the plugin. */ getInfo : function() { return { longname : 'WordPress Link Dialog', author : 'WordPress', authorurl : 'http://wordpress.org', infourl : '', version : "1.0" }; } }); // Register plugin tinymce.PluginManager.add('wplink', tinymce.plugins.wpLink); })();
zyblog
trunk/zyblog/wp-includes/js/tinymce/plugins/wplink/editor_plugin_src.js
JavaScript
asf20
1,681
/** * WordPress plugin. */ (function() { var DOM = tinymce.DOM; tinymce.create('tinymce.plugins.WordPress', { init : function(ed, url) { var t = this, tbId = ed.getParam('wordpress_adv_toolbar', 'toolbar2'), last = 0, moreHTML, nextpageHTML, closeOnClick, mod_key; moreHTML = '<img src="' + url + '/img/trans.gif" class="mceWPmore mceItemNoResize" title="'+ed.getLang('wordpress.wp_more_alt')+'" />'; nextpageHTML = '<img src="' + url + '/img/trans.gif" class="mceWPnextpage mceItemNoResize" title="'+ed.getLang('wordpress.wp_page_alt')+'" />'; if ( getUserSetting('hidetb', '0') == '1' ) ed.settings.wordpress_adv_hidden = 0; // Hides the specified toolbar and resizes the iframe ed.onPostRender.add(function() { var adv_toolbar = ed.controlManager.get(tbId); if ( ed.getParam('wordpress_adv_hidden', 1) && adv_toolbar ) { DOM.hide(adv_toolbar.id); t._resizeIframe(ed, tbId, 28); } }); // Register commands ed.addCommand('WP_More', function() { ed.execCommand('mceInsertContent', 0, moreHTML); }); ed.addCommand('WP_Page', function() { ed.execCommand('mceInsertContent', 0, nextpageHTML); }); ed.addCommand('WP_Help', function() { ed.windowManager.open({ url : tinymce.baseURL + '/wp-mce-help.php', width : 450, height : 420, inline : 1 }); }); ed.addCommand('WP_Adv', function() { var cm = ed.controlManager, id = cm.get(tbId).id; if ( 'undefined' == id ) return; if ( DOM.isHidden(id) ) { cm.setActive('wp_adv', 1); DOM.show(id); t._resizeIframe(ed, tbId, -28); ed.settings.wordpress_adv_hidden = 0; setUserSetting('hidetb', '1'); } else { cm.setActive('wp_adv', 0); DOM.hide(id); t._resizeIframe(ed, tbId, 28); ed.settings.wordpress_adv_hidden = 1; setUserSetting('hidetb', '0'); } }); ed.addCommand('WP_Medialib', function() { if ( typeof wp !== 'undefined' && wp.media && wp.media.editor ) wp.media.editor.open( ed.id ); }); // Register buttons ed.addButton('wp_more', { title : 'wordpress.wp_more_desc', cmd : 'WP_More' }); ed.addButton('wp_page', { title : 'wordpress.wp_page_desc', image : url + '/img/page.gif', cmd : 'WP_Page' }); ed.addButton('wp_help', { title : 'wordpress.wp_help_desc', cmd : 'WP_Help' }); ed.addButton('wp_adv', { title : 'wordpress.wp_adv_desc', cmd : 'WP_Adv' }); // Add Media button ed.addButton('add_media', { title : 'wordpress.add_media', image : url + '/img/image.gif', cmd : 'WP_Medialib' }); // Add Media buttons to fullscreen and handle align buttons for image captions ed.onBeforeExecCommand.add(function(ed, cmd, ui, val, o) { var DOM = tinymce.DOM, n, DL, DIV, cls, a, align; if ( 'mceFullScreen' == cmd ) { if ( 'mce_fullscreen' != ed.id && DOM.select('a.thickbox').length ) ed.settings.theme_advanced_buttons1 += ',|,add_media'; } if ( 'JustifyLeft' == cmd || 'JustifyRight' == cmd || 'JustifyCenter' == cmd ) { n = ed.selection.getNode(); if ( n.nodeName == 'IMG' ) { align = cmd.substr(7).toLowerCase(); a = 'align' + align; DL = ed.dom.getParent(n, 'dl.wp-caption'); DIV = ed.dom.getParent(n, 'div.mceTemp'); if ( DL && DIV ) { cls = ed.dom.hasClass(DL, a) ? 'alignnone' : a; DL.className = DL.className.replace(/align[^ '"]+\s?/g, ''); ed.dom.addClass(DL, cls); if (cls == 'aligncenter') ed.dom.addClass(DIV, 'mceIEcenter'); else ed.dom.removeClass(DIV, 'mceIEcenter'); o.terminate = true; ed.execCommand('mceRepaint'); } else { if ( ed.dom.hasClass(n, a) ) ed.dom.addClass(n, 'alignnone'); else ed.dom.removeClass(n, 'alignnone'); } } } }); ed.onInit.add(function(ed) { var bodyClass = ed.getParam('body_class', ''), body = ed.getBody(); // add body classes if ( bodyClass ) bodyClass = bodyClass.split(' '); else bodyClass = []; if ( ed.getParam('directionality', '') == 'rtl' ) bodyClass.push('rtl'); if ( tinymce.isIE9 ) bodyClass.push('ie9'); else if ( tinymce.isIE8 ) bodyClass.push('ie8'); else if ( tinymce.isIE7 ) bodyClass.push('ie7'); if ( ed.id != 'wp_mce_fullscreen' && ed.id != 'mce_fullscreen' ) bodyClass.push('wp-editor'); else if ( ed.id == 'mce_fullscreen' ) bodyClass.push('mce-fullscreen'); tinymce.each( bodyClass, function(cls){ if ( cls ) ed.dom.addClass(body, cls); }); // make sure these run last ed.onNodeChange.add( function(ed, cm, e) { var DL; if ( e.nodeName == 'IMG' ) { DL = ed.dom.getParent(e, 'dl.wp-caption'); } else if ( e.nodeName == 'DIV' && ed.dom.hasClass(e, 'mceTemp') ) { DL = e.firstChild; if ( ! ed.dom.hasClass(DL, 'wp-caption') ) DL = false; } if ( DL ) { if ( ed.dom.hasClass(DL, 'alignleft') ) cm.setActive('justifyleft', 1); else if ( ed.dom.hasClass(DL, 'alignright') ) cm.setActive('justifyright', 1); else if ( ed.dom.hasClass(DL, 'aligncenter') ) cm.setActive('justifycenter', 1); } }); // remove invalid parent paragraphs when pasting HTML and/or switching to the HTML editor and back ed.onBeforeSetContent.add(function(ed, o) { if ( o.content ) { o.content = o.content.replace(/<p>\s*<(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)( [^>]*)?>/gi, '<$1$2>'); o.content = o.content.replace(/<\/(p|div|ul|ol|dl|table|blockquote|h[1-6]|fieldset|pre|address)>\s*<\/p>/gi, '</$1>'); } }); }); // Word count if ( 'undefined' != typeof(jQuery) ) { ed.onKeyUp.add(function(ed, e) { var k = e.keyCode || e.charCode; if ( k == last ) return; if ( 13 == k || 8 == last || 46 == last ) jQuery(document).triggerHandler('wpcountwords', [ ed.getContent({format : 'raw'}) ]); last = k; }); }; // keep empty paragraphs :( ed.onSaveContent.addToTop(function(ed, o) { o.content = o.content.replace(/<p>(<br ?\/?>|\u00a0|\uFEFF)?<\/p>/g, '<p>&nbsp;</p>'); }); ed.onSaveContent.add(function(ed, o) { if ( ed.getParam('wpautop', true) && typeof(switchEditors) == 'object' ) { if ( ed.isHidden() ) o.content = o.element.value; else o.content = switchEditors.pre_wpautop(o.content); } }); /* disable for now ed.onBeforeSetContent.add(function(ed, o) { o.content = t._setEmbed(o.content); }); ed.onPostProcess.add(function(ed, o) { if ( o.get ) o.content = t._getEmbed(o.content); }); */ // Add listeners to handle more break t._handleMoreBreak(ed, url); // Add custom shortcuts mod_key = 'alt+shift'; // if ( tinymce.isGecko ) // disable for mow, too many shortcuts conflicts // mod_key = 'ctrl+alt'; ed.addShortcut(mod_key + '+c', 'justifycenter_desc', 'JustifyCenter'); ed.addShortcut(mod_key + '+r', 'justifyright_desc', 'JustifyRight'); ed.addShortcut(mod_key + '+l', 'justifyleft_desc', 'JustifyLeft'); ed.addShortcut(mod_key + '+j', 'justifyfull_desc', 'JustifyFull'); ed.addShortcut(mod_key + '+q', 'blockquote_desc', 'mceBlockQuote'); ed.addShortcut(mod_key + '+u', 'bullist_desc', 'InsertUnorderedList'); ed.addShortcut(mod_key + '+o', 'numlist_desc', 'InsertOrderedList'); ed.addShortcut(mod_key + '+n', 'spellchecker.desc', 'mceSpellCheck'); ed.addShortcut(mod_key + '+a', 'link_desc', 'WP_Link'); ed.addShortcut(mod_key + '+s', 'unlink_desc', 'unlink'); ed.addShortcut(mod_key + '+m', 'image_desc', 'WP_Medialib'); ed.addShortcut(mod_key + '+z', 'wordpress.wp_adv_desc', 'WP_Adv'); ed.addShortcut(mod_key + '+t', 'wordpress.wp_more_desc', 'WP_More'); ed.addShortcut(mod_key + '+d', 'striketrough_desc', 'Strikethrough'); ed.addShortcut(mod_key + '+h', 'help_desc', 'WP_Help'); ed.addShortcut(mod_key + '+p', 'wordpress.wp_page_desc', 'WP_Page'); ed.addShortcut('ctrl+s', 'save_desc', function(){if('function'==typeof autosave)autosave();}); if ( /\bwpfullscreen\b/.test(ed.settings.plugins) ) ed.addShortcut(mod_key + '+w', 'wordpress.wp_fullscreen_desc', 'wpFullScreen'); else if ( /\bfullscreen\b/.test(ed.settings.plugins) ) ed.addShortcut(mod_key + '+g', 'fullscreen.desc', 'mceFullScreen'); // popup buttons for images and the gallery ed.onInit.add(function(ed) { tinymce.dom.Event.add(ed.getWin(), 'scroll', function(e) { ed.plugins.wordpress._hideButtons(); }); tinymce.dom.Event.add(ed.getBody(), 'dragstart', function(e) { ed.plugins.wordpress._hideButtons(); }); }); ed.onBeforeExecCommand.add(function(ed, cmd, ui, val) { ed.plugins.wordpress._hideButtons(); }); ed.onSaveContent.add(function(ed, o) { ed.plugins.wordpress._hideButtons(); }); ed.onMouseDown.add(function(ed, e) { if ( e.target.nodeName != 'IMG' ) ed.plugins.wordpress._hideButtons(); }); ed.onKeyDown.add(function(ed, e){ if ( e.which == tinymce.VK.DELETE || e.which == tinymce.VK.BACKSPACE ) ed.plugins.wordpress._hideButtons(); }); closeOnClick = function(e){ var id; if ( e.target.id == 'mceModalBlocker' || e.target.className == 'ui-widget-overlay' ) { for ( id in ed.windowManager.windows ) { ed.windowManager.close(null, id); } } } // close popups when clicking on the background tinymce.dom.Event.remove(document.body, 'click', closeOnClick); tinymce.dom.Event.add(document.body, 'click', closeOnClick); }, getInfo : function() { return { longname : 'WordPress Plugin', author : 'WordPress', // add Moxiecode? authorurl : 'http://wordpress.org', infourl : 'http://wordpress.org', version : '3.0' }; }, // Internal functions _setEmbed : function(c) { return c.replace(/\[embed\]([\s\S]+?)\[\/embed\][\s\u00a0]*/g, function(a,b){ return '<img width="300" height="200" src="' + tinymce.baseURL + '/plugins/wordpress/img/trans.gif" class="wp-oembed mceItemNoResize" alt="'+b+'" title="'+b+'" />'; }); }, _getEmbed : function(c) { return c.replace(/<img[^>]+>/g, function(a) { if ( a.indexOf('class="wp-oembed') != -1 ) { var u = a.match(/alt="([^\"]+)"/); if ( u[1] ) a = '[embed]' + u[1] + '[/embed]'; } return a; }); }, _showButtons : function(n, id) { var ed = tinyMCE.activeEditor, p1, p2, vp, DOM = tinymce.DOM, X, Y; vp = ed.dom.getViewPort(ed.getWin()); p1 = DOM.getPos(ed.getContentAreaContainer()); p2 = ed.dom.getPos(n); X = Math.max(p2.x - vp.x, 0) + p1.x; Y = Math.max(p2.y - vp.y, 0) + p1.y; DOM.setStyles(id, { 'top' : Y+5+'px', 'left' : X+5+'px', 'display' : 'block' }); }, _hideButtons : function() { var DOM = tinymce.DOM; DOM.hide( DOM.select('#wp_editbtns, #wp_gallerybtns') ); }, // Resizes the iframe by a relative height value _resizeIframe : function(ed, tb_id, dy) { var ifr = ed.getContentAreaContainer().firstChild; DOM.setStyle(ifr, 'height', ifr.clientHeight + dy); // Resize iframe ed.theme.deltaHeight += dy; // For resize cookie }, _handleMoreBreak : function(ed, url) { var moreHTML, nextpageHTML; moreHTML = '<img src="' + url + '/img/trans.gif" alt="$1" class="mceWPmore mceItemNoResize" title="'+ed.getLang('wordpress.wp_more_alt')+'" />'; nextpageHTML = '<img src="' + url + '/img/trans.gif" class="mceWPnextpage mceItemNoResize" title="'+ed.getLang('wordpress.wp_page_alt')+'" />'; // Display morebreak instead if img in element path ed.onPostRender.add(function() { if (ed.theme.onResolveName) { ed.theme.onResolveName.add(function(th, o) { if (o.node.nodeName == 'IMG') { if ( ed.dom.hasClass(o.node, 'mceWPmore') ) o.name = 'wpmore'; if ( ed.dom.hasClass(o.node, 'mceWPnextpage') ) o.name = 'wppage'; } }); } }); // Replace morebreak with images ed.onBeforeSetContent.add(function(ed, o) { if ( o.content ) { o.content = o.content.replace(/<!--more(.*?)-->/g, moreHTML); o.content = o.content.replace(/<!--nextpage-->/g, nextpageHTML); } }); // Replace images with morebreak ed.onPostProcess.add(function(ed, o) { if (o.get) o.content = o.content.replace(/<img[^>]+>/g, function(im) { if (im.indexOf('class="mceWPmore') !== -1) { var m, moretext = (m = im.match(/alt="(.*?)"/)) ? m[1] : ''; im = '<!--more'+moretext+'-->'; } if (im.indexOf('class="mceWPnextpage') !== -1) im = '<!--nextpage-->'; return im; }); }); // Set active buttons if user selected pagebreak or more break ed.onNodeChange.add(function(ed, cm, n) { cm.setActive('wp_page', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mceWPnextpage')); cm.setActive('wp_more', n.nodeName === 'IMG' && ed.dom.hasClass(n, 'mceWPmore')); }); } }); // Register plugin tinymce.PluginManager.add('wordpress', tinymce.plugins.WordPress); })();
zyblog
trunk/zyblog/wp-includes/js/tinymce/plugins/wordpress/editor_plugin_src.js
JavaScript
asf20
13,207
/** * TinyMCE Schema.js * * Duck-punched by WordPress core to support a sane schema superset. * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ (function(tinymce) { var mapCache = {}, makeMap = tinymce.makeMap, each = tinymce.each; function split(str, delim) { return str.split(delim || ','); }; /** * Unpacks the specified lookup and string data it will also parse it into an object * map with sub object for it's children. This will later also include the attributes. */ function unpack(lookup, data) { var key, elements = {}; function replace(value) { return value.replace(/[A-Z]+/g, function(key) { return replace(lookup[key]); }); }; // Unpack lookup for (key in lookup) { if (lookup.hasOwnProperty(key)) lookup[key] = replace(lookup[key]); } // Unpack and parse data into object map replace(data).replace(/#/g, '#text').replace(/(\w+)\[([^\]]+)\]\[([^\]]*)\]/g, function(str, name, attributes, children) { attributes = split(attributes, '|'); elements[name] = { attributes : makeMap(attributes), attributesOrder : attributes, children : makeMap(children, '|', {'#comment' : {}}) } }); return elements; }; /** * Returns the HTML5 schema and caches it in the mapCache. */ function getHTML5() { var html5 = mapCache.html5; if (!html5) { html5 = mapCache.html5 = unpack({ A : 'accesskey|class|contextmenu|dir|draggable|dropzone|hidden|id|inert|itemid|itemprop|itemref|itemscope|itemtype|lang|spellcheck|style|tabindex|title|translate|item|role|subject|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup', B : '#|a|abbr|area|audio|b|bdi|bdo|br|button|canvas|cite|code|command|data|datalist|del|dfn|em|embed|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|math|meta|meter|noscript|object|output|progress|q|ruby|s|samp|script|select|small|span|strong|sub|sup|svg|textarea|time|u|var|video|wbr', C : '#|a|abbr|area|address|article|aside|audio|b|bdi|bdo|blockquote|br|button|canvas|cite|code|command|data|datalist|del|details|dfn|dialog|div|dl|em|embed|fieldset|figure|footer|form|h1|h2|h3|h4|h5|h6|header|hgroup|hr|i|iframe|img|input|ins|kbd|keygen|label|link|map|mark|math|menu|meta|meter|nav|noscript|ol|object|output|p|pre|progress|q|ruby|s|samp|script|section|select|small|span|strong|style|sub|sup|svg|table|textarea|time|u|ul|var|video|wbr' }, 'html[A|manifest][body|head]' + 'head[A][base|command|link|meta|noscript|script|style|title]' + 'title[A][#]' + 'base[A|href|target][]' + 'link[A|href|rel|media|type|sizes|crossorigin|hreflang][]' + 'meta[A|http-equiv|name|content|charset][]' + 'style[A|type|media|scoped][#]' + 'script[A|charset|type|src|defer|async|crossorigin][#]' + 'noscript[A][C]' + 'body[A|onafterprint|onbeforeprint|onbeforeunload|onblur|onerror|onfocus|onfullscreenchange|onfullscreenerror|onhashchange|onload|onmessage|onoffline|ononline|onpagehide|onpageshow|onpopstate|onresize|onscroll|onstorage|onunload][C]' + 'section[A][C]' + 'nav[A][C]' + 'article[A][C]' + 'aside[A][C]' + 'h1[A][B]' + 'h2[A][B]' + 'h3[A][B]' + 'h4[A][B]' + 'h5[A][B]' + 'h6[A][B]' + 'hgroup[A][h1|h2|h3|h4|h5|h6]' + 'header[A][C]' + 'footer[A][C]' + 'address[A][C]' + 'p[A][B]' + 'br[A][]' + 'pre[A][B]' + 'dialog[A|open][C|dd|dt]' + 'blockquote[A|cite][C]' + 'ol[A|start|reversed][li]' + 'ul[A][li]' + 'li[A|value][C]' + 'dl[A][dd|dt]' + 'dt[A][C|B]' + 'dd[A][C]' + 'a[A|href|target|download|ping|rel|media|type][C|B]' + 'em[A][B]' + 'strong[A][B]' + 'small[A][B]' + 's[A][B]' + 'cite[A][B]' + 'q[A|cite][B]' + 'dfn[A][B]' + 'abbr[A][B]' + 'code[A][B]' + 'var[A][B]' + 'samp[A][B]' + 'kbd[A][B]' + 'sub[A][B]' + 'sup[A][B]' + 'i[A][B]' + 'b[A][B]' + 'u[A][B]' + 'mark[A][B]' + 'progress[A|value|max][B]' + 'meter[A|value|min|max|low|high|optimum][B]' + 'time[A|datetime][B]' + 'ruby[A][B|rt|rp]' + 'rt[A][B]' + 'rp[A][B]' + 'bdi[A][B]' + 'bdo[A][B]' + 'span[A][B]' + 'ins[A|cite|datetime][C|B]' + 'del[A|cite|datetime][C|B]' + 'figure[A][C|legend|figcaption]' + 'figcaption[A][C]' + 'img[A|alt|src|srcset|crossorigin|usemap|ismap|width|height][]' + 'iframe[A|name|src|srcdoc|height|width|sandbox|seamless|allowfullscreen][C|B]' + 'embed[A|src|height|width|type][]' + 'object[A|data|type|typemustmatch|name|usemap|form|width|height][C|B|param]' + 'param[A|name|value][]' + 'summary[A][B]' + 'details[A|open][C|legend|summary]' + 'command[A|type|label|icon|disabled|checked|radiogroup|command][]' + 'menu[A|type|label][C|li]' + 'legend[A][C|B]' + 'div[A][C]' + 'source[A|src|type|media][]' + 'track[A|kind|src|srclang|label|default][]' + 'audio[A|src|autobuffer|autoplay|loop|controls|crossorigin|preload|mediagroup|muted][C|source|track]' + 'video[A|src|autobuffer|autoplay|loop|controls|width|height|poster|crossorigin|preload|mediagroup|muted][C|source|track]' + 'hr[A][]' + 'form[A|accept-charset|action|autocomplete|enctype|method|name|novalidate|target][C]' + 'fieldset[A|disabled|form|name][C|legend]' + 'label[A|form|for][B]' + 'input[A|type|accept|alt|autocomplete|autofocus|checked|dirname|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|height|inputmode|list|max|maxlength|min|multiple|name|pattern|placeholder|readonly|required|size|src|step|value|width|files][]' + 'button[A|autofocus|disabled|form|formaction|formenctype|formmethod|formnovalidate|formtarget|name|type|value][B]' + 'select[A|autofocus|disabled|form|multiple|name|required|size][option|optgroup]' + 'data[A|value][B]' + 'datalist[A][B|option]' + 'optgroup[A|disabled|label][option]' + 'option[A|disabled|selected|label|value][#]' + 'textarea[A|autocomplete|autofocus|cols|dirname|disabled|form|inputmode|maxlength|name|placeholder|readonly|required|rows|wrap][#]' + 'keygen[A|autofocus|challenge|disabled|form|keytype|name][]' + 'output[A|for|form|name][B]' + 'canvas[A|width|height][a|button|input]' + 'map[A|name][C|B]' + 'area[A|alt|coords|shape|href|target|download|ping|rel|media|hreflang|type][]' + 'math[A][]' + 'svg[A][]' + 'table[A][caption|colgroup|thead|tfoot|tbody|tr]' + 'caption[A][C]' + 'colgroup[A|span][col]' + 'col[A|span][]' + 'thead[A][tr]' + 'tfoot[A][tr]' + 'tbody[A][tr]' + 'tr[A][th|td]' + 'th[A|headers|rowspan|colspan|scope][C]' + 'td[A|headers|rowspan|colspan][C]' + 'wbr[A][]' ); } return html5; }; /** * Returns the HTML4 schema and caches it in the mapCache. */ function getHTML4() { var html4 = mapCache.html4; if (!html4) { // This is the XHTML 1.0 transitional elements with it's attributes and children packed to reduce it's size html4 = mapCache.html4 = unpack({ Z : 'H|K|N|O|P', Y : 'X|form|R|Q', ZG : 'E|span|width|align|char|charoff|valign', X : 'p|T|div|U|W|isindex|fieldset|table', ZF : 'E|align|char|charoff|valign', W : 'pre|hr|blockquote|address|center|noframes', ZE : 'abbr|axis|headers|scope|rowspan|colspan|align|char|charoff|valign|nowrap|bgcolor|width|height', ZD : '[E][S]', U : 'ul|ol|dl|menu|dir', ZC : 'p|Y|div|U|W|table|br|span|bdo|object|applet|img|map|K|N|Q', T : 'h1|h2|h3|h4|h5|h6', ZB : 'X|S|Q', S : 'R|P', ZA : 'a|G|J|M|O|P', R : 'a|H|K|N|O', Q : 'noscript|P', P : 'ins|del|script', O : 'input|select|textarea|label|button', N : 'M|L', M : 'em|strong|dfn|code|q|samp|kbd|var|cite|abbr|acronym', L : 'sub|sup', K : 'J|I', J : 'tt|i|b|u|s|strike', I : 'big|small|font|basefont', H : 'G|F', G : 'br|span|bdo', F : 'object|applet|img|map|iframe', E : 'A|B|C', D : 'accesskey|tabindex|onfocus|onblur', C : 'onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup', B : 'lang|xml:lang|dir', A : 'id|class|style|title' }, 'script[id|charset|type|language|src|defer|xml:space][]' + 'style[B|id|type|media|title|xml:space][]' + 'object[E|declare|classid|codebase|data|type|codetype|archive|standby|width|height|usemap|name|tabindex|align|border|hspace|vspace][#|param|Y]' + 'param[id|name|value|valuetype|type][]' + 'p[E|align][#|S]' + 'a[E|D|charset|type|name|href|hreflang|rel|rev|shape|coords|target][#|Z]' + 'br[A|clear][]' + 'span[E][#|S]' + 'bdo[A|C|B][#|S]' + 'applet[A|codebase|archive|code|object|alt|name|width|height|align|hspace|vspace][#|param|Y]' + 'h1[E|align][#|S]' + 'img[E|src|alt|name|longdesc|width|height|usemap|ismap|align|border|hspace|vspace][]' + 'map[B|C|A|name][X|form|Q|area]' + 'h2[E|align][#|S]' + 'iframe[A|longdesc|name|src|frameborder|marginwidth|marginheight|scrolling|align|width|height][#|Y]' + 'h3[E|align][#|S]' + 'tt[E][#|S]' + 'i[E][#|S]' + 'b[E][#|S]' + 'u[E][#|S]' + 's[E][#|S]' + 'strike[E][#|S]' + 'big[E][#|S]' + 'small[E][#|S]' + 'font[A|B|size|color|face][#|S]' + 'basefont[id|size|color|face][]' + 'em[E][#|S]' + 'strong[E][#|S]' + 'dfn[E][#|S]' + 'code[E][#|S]' + 'q[E|cite][#|S]' + 'samp[E][#|S]' + 'kbd[E][#|S]' + 'var[E][#|S]' + 'cite[E][#|S]' + 'abbr[E][#|S]' + 'acronym[E][#|S]' + 'sub[E][#|S]' + 'sup[E][#|S]' + 'input[E|D|type|name|value|checked|disabled|readonly|size|maxlength|src|alt|usemap|onselect|onchange|accept|align][]' + 'select[E|name|size|multiple|disabled|tabindex|onfocus|onblur|onchange][optgroup|option]' + 'optgroup[E|disabled|label][option]' + 'option[E|selected|disabled|label|value][]' + 'textarea[E|D|name|rows|cols|disabled|readonly|onselect|onchange][]' + 'label[E|for|accesskey|onfocus|onblur][#|S]' + 'button[E|D|name|value|type|disabled][#|p|T|div|U|W|table|G|object|applet|img|map|K|N|Q]' + 'h4[E|align][#|S]' + 'ins[E|cite|datetime][#|Y]' + 'h5[E|align][#|S]' + 'del[E|cite|datetime][#|Y]' + 'h6[E|align][#|S]' + 'div[E|align][#|Y]' + 'ul[E|type|compact][li]' + 'li[E|type|value][#|Y]' + 'ol[E|type|compact|start][li]' + 'dl[E|compact][dt|dd]' + 'dt[E][#|S]' + 'dd[E][#|Y]' + 'menu[E|compact][li]' + 'dir[E|compact][li]' + 'pre[E|width|xml:space][#|ZA]' + 'hr[E|align|noshade|size|width][]' + 'blockquote[E|cite][#|Y]' + 'address[E][#|S|p]' + 'center[E][#|Y]' + 'noframes[E][#|Y]' + 'isindex[A|B|prompt][]' + 'fieldset[E][#|legend|Y]' + 'legend[E|accesskey|align][#|S]' + 'table[E|summary|width|border|frame|rules|cellspacing|cellpadding|align|bgcolor][caption|col|colgroup|thead|tfoot|tbody|tr]' + 'caption[E|align][#|S]' + 'col[ZG][]' + 'colgroup[ZG][col]' + 'thead[ZF][tr]' + 'tr[ZF|bgcolor][th|td]' + 'th[E|ZE][#|Y]' + 'form[E|action|method|name|enctype|onsubmit|onreset|accept|accept-charset|target][#|X|R|Q]' + 'noscript[E][#|Y]' + 'td[E|ZE][#|Y]' + 'tfoot[ZF][tr]' + 'tbody[ZF][tr]' + 'area[E|D|shape|coords|href|nohref|alt|target][]' + 'base[id|href|target][]' + 'body[E|onload|onunload|background|bgcolor|text|link|vlink|alink][#|Y]' ); } return html4; }; /** * WordPress Core * * Returns a schema that is the result of a deep merge between the HTML5 * and HTML4 schemas. */ function getSaneSchema() { var cachedMapCache = mapCache, html5, html4; if ( mapCache.sane ) return mapCache.sane; // Bust the mapCache so we're not dealing with the other schema objects. mapCache = {}; html5 = getHTML5(); html4 = getHTML4(); mapCache = cachedMapCache; each( html4, function( html4settings, tag ) { var html5settings = html5[ tag ], difference = []; // Merge tags missing in HTML5 mode. if ( ! html5settings ) { html5[ tag ] = html4settings; return; } // Merge attributes missing from this HTML5 tag. each( html4settings.attributes, function( attribute, key ) { if ( ! html5settings.attributes[ key ] ) html5settings.attributes[ key ] = attribute; }); // Merge any missing attributes into the attributes order. each( html4settings.attributesOrder, function( key ) { if ( -1 === tinymce.inArray( html5settings.attributesOrder, key ) ) difference.push( key ); }); html5settings.attributesOrder = html5settings.attributesOrder.concat( difference ); // Merge children missing from this HTML5 tag. each( html4settings.children, function( child, key ) { if ( ! html5settings.children[ key ] ) html5settings.children[ key ] = child; }); }); return mapCache.sane = html5; } /** * Schema validator class. * * @class tinymce.html.Schema * @example * if (tinymce.activeEditor.schema.isValidChild('p', 'span')) * alert('span is valid child of p.'); * * if (tinymce.activeEditor.schema.getElementRule('p')) * alert('P is a valid element.'); * * @class tinymce.html.Schema * @version 3.4 */ /** * Constructs a new Schema instance. * * @constructor * @method Schema * @param {Object} settings Name/value settings object. */ tinymce.html.Schema = function(settings) { var self = this, elements = {}, children = {}, patternElements = [], validStyles, schemaItems; var whiteSpaceElementsMap, selfClosingElementsMap, shortEndedElementsMap, boolAttrMap, blockElementsMap, nonEmptyElementsMap, customElementsMap = {}; // Creates an lookup table map object for the specified option or the default value function createLookupTable(option, default_value, extend) { var value = settings[option]; if (!value) { // Get cached default map or make it if needed value = mapCache[option]; if (!value) { value = makeMap(default_value, ' ', makeMap(default_value.toUpperCase(), ' ')); value = tinymce.extend(value, extend); mapCache[option] = value; } } else { // Create custom map value = makeMap(value, ',', makeMap(value.toUpperCase(), ' ')); } return value; }; settings = settings || {}; /** * WordPress core uses a sane schema in place of the default "HTML5" schema. */ schemaItems = settings.schema == "html5" ? getSaneSchema() : getHTML4(); // Allow all elements and attributes if verify_html is set to false if (settings.verify_html === false) settings.valid_elements = '*[*]'; // Build styles list if (settings.valid_styles) { validStyles = {}; // Convert styles into a rule list each(settings.valid_styles, function(value, key) { validStyles[key] = tinymce.explode(value); }); } // Setup map objects whiteSpaceElementsMap = createLookupTable('whitespace_elements', 'pre script noscript style textarea'); selfClosingElementsMap = createLookupTable('self_closing_elements', 'colgroup dd dt li option p td tfoot th thead tr'); shortEndedElementsMap = createLookupTable('short_ended_elements', 'area base basefont br col frame hr img input isindex link meta param embed source wbr'); boolAttrMap = createLookupTable('boolean_attributes', 'checked compact declare defer disabled ismap multiple nohref noresize noshade nowrap readonly selected autoplay loop controls'); nonEmptyElementsMap = createLookupTable('non_empty_elements', 'td th iframe video audio object', shortEndedElementsMap); textBlockElementsMap = createLookupTable('text_block_elements', 'h1 h2 h3 h4 h5 h6 p div address pre form ' + 'blockquote center dir fieldset header footer article section hgroup aside nav figure'); blockElementsMap = createLookupTable('block_elements', 'hr table tbody thead tfoot ' + 'th tr td li ol ul caption dl dt dd noscript menu isindex samp option datalist select optgroup', textBlockElementsMap); // Converts a wildcard expression string to a regexp for example *a will become /.*a/. function patternToRegExp(str) { return new RegExp('^' + str.replace(/([?+*])/g, '.$1') + '$'); }; // Parses the specified valid_elements string and adds to the current rules // This function is a bit hard to read since it's heavily optimized for speed function addValidElements(valid_elements) { var ei, el, ai, al, yl, matches, element, attr, attrData, elementName, attrName, attrType, attributes, attributesOrder, prefix, outputName, globalAttributes, globalAttributesOrder, transElement, key, childKey, value, elementRuleRegExp = /^([#+\-])?([^\[\/]+)(?:\/([^\[]+))?(?:\[([^\]]+)\])?$/, attrRuleRegExp = /^([!\-])?(\w+::\w+|[^=:<]+)?(?:([=:<])(.*))?$/, hasPatternsRegExp = /[*?+]/; if (valid_elements) { // Split valid elements into an array with rules valid_elements = split(valid_elements); if (elements['@']) { globalAttributes = elements['@'].attributes; globalAttributesOrder = elements['@'].attributesOrder; } // Loop all rules for (ei = 0, el = valid_elements.length; ei < el; ei++) { // Parse element rule matches = elementRuleRegExp.exec(valid_elements[ei]); if (matches) { // Setup local names for matches prefix = matches[1]; elementName = matches[2]; outputName = matches[3]; attrData = matches[4]; // Create new attributes and attributesOrder attributes = {}; attributesOrder = []; // Create the new element element = { attributes : attributes, attributesOrder : attributesOrder }; // Padd empty elements prefix if (prefix === '#') element.paddEmpty = true; // Remove empty elements prefix if (prefix === '-') element.removeEmpty = true; // Copy attributes from global rule into current rule if (globalAttributes) { for (key in globalAttributes) attributes[key] = globalAttributes[key]; attributesOrder.push.apply(attributesOrder, globalAttributesOrder); } // Attributes defined if (attrData) { attrData = split(attrData, '|'); for (ai = 0, al = attrData.length; ai < al; ai++) { matches = attrRuleRegExp.exec(attrData[ai]); if (matches) { attr = {}; attrType = matches[1]; attrName = matches[2].replace(/::/g, ':'); prefix = matches[3]; value = matches[4]; // Required if (attrType === '!') { element.attributesRequired = element.attributesRequired || []; element.attributesRequired.push(attrName); attr.required = true; } // Denied from global if (attrType === '-') { delete attributes[attrName]; attributesOrder.splice(tinymce.inArray(attributesOrder, attrName), 1); continue; } // Default value if (prefix) { // Default value if (prefix === '=') { element.attributesDefault = element.attributesDefault || []; element.attributesDefault.push({name: attrName, value: value}); attr.defaultValue = value; } // Forced value if (prefix === ':') { element.attributesForced = element.attributesForced || []; element.attributesForced.push({name: attrName, value: value}); attr.forcedValue = value; } // Required values if (prefix === '<') attr.validValues = makeMap(value, '?'); } // Check for attribute patterns if (hasPatternsRegExp.test(attrName)) { element.attributePatterns = element.attributePatterns || []; attr.pattern = patternToRegExp(attrName); element.attributePatterns.push(attr); } else { // Add attribute to order list if it doesn't already exist if (!attributes[attrName]) attributesOrder.push(attrName); attributes[attrName] = attr; } } } } // Global rule, store away these for later usage if (!globalAttributes && elementName == '@') { globalAttributes = attributes; globalAttributesOrder = attributesOrder; } // Handle substitute elements such as b/strong if (outputName) { element.outputName = elementName; elements[outputName] = element; } // Add pattern or exact element if (hasPatternsRegExp.test(elementName)) { element.pattern = patternToRegExp(elementName); patternElements.push(element); } else elements[elementName] = element; } } } }; function setValidElements(valid_elements) { elements = {}; patternElements = []; addValidElements(valid_elements); each(schemaItems, function(element, name) { children[name] = element.children; }); }; // Adds custom non HTML elements to the schema function addCustomElements(custom_elements) { var customElementRegExp = /^(~)?(.+)$/; if (custom_elements) { each(split(custom_elements), function(rule) { var matches = customElementRegExp.exec(rule), inline = matches[1] === '~', cloneName = inline ? 'span' : 'div', name = matches[2]; children[name] = children[cloneName]; customElementsMap[name] = cloneName; // If it's not marked as inline then add it to valid block elements if (!inline) { blockElementsMap[name.toUpperCase()] = {}; blockElementsMap[name] = {}; } // Add elements clone if needed if (!elements[name]) { elements[name] = elements[cloneName]; } // Add custom elements at span/div positions each(children, function(element, child) { if (element[cloneName]) element[name] = element[cloneName]; }); }); } }; // Adds valid children to the schema object function addValidChildren(valid_children) { var childRuleRegExp = /^([+\-]?)(\w+)\[([^\]]+)\]$/; if (valid_children) { each(split(valid_children), function(rule) { var matches = childRuleRegExp.exec(rule), parent, prefix; if (matches) { prefix = matches[1]; // Add/remove items from default if (prefix) parent = children[matches[2]]; else parent = children[matches[2]] = {'#comment' : {}}; parent = children[matches[2]]; each(split(matches[3], '|'), function(child) { if (prefix === '-') delete parent[child]; else parent[child] = {}; }); } }); } }; function getElementRule(name) { var element = elements[name], i; // Exact match found if (element) return element; // No exact match then try the patterns i = patternElements.length; while (i--) { element = patternElements[i]; if (element.pattern.test(name)) return element; } }; if (!settings.valid_elements) { // No valid elements defined then clone the elements from the schema spec each(schemaItems, function(element, name) { elements[name] = { attributes : element.attributes, attributesOrder : element.attributesOrder }; children[name] = element.children; }); // Switch these on HTML4 if (settings.schema != "html5") { each(split('strong/b,em/i'), function(item) { item = split(item, '/'); elements[item[1]].outputName = item[0]; }); } // Add default alt attribute for images elements.img.attributesDefault = [{name: 'alt', value: ''}]; // Remove these if they are empty by default each(split('ol,ul,sub,sup,blockquote,span,font,a,table,tbody,tr,strong,em,b,i'), function(name) { if (elements[name]) { elements[name].removeEmpty = true; } }); // Padd these by default each(split('p,h1,h2,h3,h4,h5,h6,th,td,pre,div,address,caption'), function(name) { elements[name].paddEmpty = true; }); } else setValidElements(settings.valid_elements); addCustomElements(settings.custom_elements); addValidChildren(settings.valid_children); addValidElements(settings.extended_valid_elements); // Todo: Remove this when we fix list handling to be valid addValidChildren('+ol[ul|ol],+ul[ul|ol]'); // Delete invalid elements if (settings.invalid_elements) { tinymce.each(tinymce.explode(settings.invalid_elements), function(item) { if (elements[item]) delete elements[item]; }); } // If the user didn't allow span only allow internal spans if (!getElementRule('span')) addValidElements('span[!data-mce-type|*]'); /** * Name/value map object with valid parents and children to those parents. * * @example * children = { * div:{p:{}, h1:{}} * }; * @field children * @type {Object} */ self.children = children; /** * Name/value map object with valid styles for each element. * * @field styles * @type {Object} */ self.styles = validStyles; /** * Returns a map with boolean attributes. * * @method getBoolAttrs * @return {Object} Name/value lookup map for boolean attributes. */ self.getBoolAttrs = function() { return boolAttrMap; }; /** * Returns a map with block elements. * * @method getBlockElements * @return {Object} Name/value lookup map for block elements. */ self.getBlockElements = function() { return blockElementsMap; }; /** * Returns a map with text block elements. Such as: p,h1-h6,div,address * * @method getTextBlockElements * @return {Object} Name/value lookup map for block elements. */ self.getTextBlockElements = function() { return textBlockElementsMap; }; /** * Returns a map with short ended elements such as BR or IMG. * * @method getShortEndedElements * @return {Object} Name/value lookup map for short ended elements. */ self.getShortEndedElements = function() { return shortEndedElementsMap; }; /** * Returns a map with self closing tags such as <li>. * * @method getSelfClosingElements * @return {Object} Name/value lookup map for self closing tags elements. */ self.getSelfClosingElements = function() { return selfClosingElementsMap; }; /** * Returns a map with elements that should be treated as contents regardless if it has text * content in them or not such as TD, VIDEO or IMG. * * @method getNonEmptyElements * @return {Object} Name/value lookup map for non empty elements. */ self.getNonEmptyElements = function() { return nonEmptyElementsMap; }; /** * Returns a map with elements where white space is to be preserved like PRE or SCRIPT. * * @method getWhiteSpaceElements * @return {Object} Name/value lookup map for white space elements. */ self.getWhiteSpaceElements = function() { return whiteSpaceElementsMap; }; /** * Returns true/false if the specified element and it's child is valid or not * according to the schema. * * @method isValidChild * @param {String} name Element name to check for. * @param {String} child Element child to verify. * @return {Boolean} True/false if the element is a valid child of the specified parent. */ self.isValidChild = function(name, child) { var parent = children[name]; return !!(parent && parent[child]); }; /** * Returns true/false if the specified element name and optional attribute is * valid according to the schema. * * @method isValid * @param {String} name Name of element to check. * @param {String} attr Optional attribute name to check for. * @return {Boolean} True/false if the element and attribute is valid. */ self.isValid = function(name, attr) { var attrPatterns, i, rule = getElementRule(name); // Check if it's a valid element if (rule) { if (attr) { // Check if attribute name exists if (rule.attributes[attr]) { return true; } // Check if attribute matches a regexp pattern attrPatterns = rule.attributePatterns; if (attrPatterns) { i = attrPatterns.length; while (i--) { if (attrPatterns[i].pattern.test(name)) { return true; } } } } else { return true; } } // No match return false; }; /** * Returns true/false if the specified element is valid or not * according to the schema. * * @method getElementRule * @param {String} name Element name to check for. * @return {Object} Element object or undefined if the element isn't valid. */ self.getElementRule = getElementRule; /** * Returns an map object of all custom elements. * * @method getCustomElements * @return {Object} Name/value map object of all custom elements. */ self.getCustomElements = function() { return customElementsMap; }; /** * Parses a valid elements string and adds it to the schema. The valid elements format is for example "element[attr=default|otherattr]". * Existing rules will be replaced with the ones specified, so this extends the schema. * * @method addValidElements * @param {String} valid_elements String in the valid elements format to be parsed. */ self.addValidElements = addValidElements; /** * Parses a valid elements string and sets it to the schema. The valid elements format is for example "element[attr=default|otherattr]". * Existing rules will be replaced with the ones specified, so this extends the schema. * * @method setValidElements * @param {String} valid_elements String in the valid elements format to be parsed. */ self.setValidElements = setValidElements; /** * Adds custom non HTML elements to the schema. * * @method addCustomElements * @param {String} custom_elements Comma separated list of custom elements to add. */ self.addCustomElements = addCustomElements; /** * Parses a valid children string and adds them to the schema structure. The valid children format is for example: "element[child1|child2]". * * @method addValidChildren * @param {String} valid_children Valid children elements string to parse */ self.addValidChildren = addValidChildren; self.elements = elements; }; })(tinymce);
zyblog
trunk/zyblog/wp-includes/js/tinymce/wp-tinymce-schema.js
JavaScript
asf20
30,552
(function(){ if ( typeof tinyMCEPreInit === 'undefined' ) return; var t = tinyMCEPreInit, baseurl = t.base, markDone = tinymce.ScriptLoader.markDone, lang = t.ref.language, theme = t.ref.theme, plugins = t.ref.plugins, suffix = t.suffix; markDone( baseurl+'/langs/'+lang+'.js' ); markDone( baseurl+'/themes/'+theme+'/editor_template'+suffix+'.js' ); markDone( baseurl+'/themes/'+theme+'/langs/'+lang+'.js' ); markDone( baseurl+'/themes/'+theme+'/langs/'+lang+'_dlg.js' ); tinymce.each( plugins.split(','), function(plugin){ if ( plugin && plugin.charAt(0) != '-' ) { markDone( baseurl+'/plugins/'+plugin+'/editor_plugin'+suffix+'.js' ); markDone( baseurl+'/plugins/'+plugin+'/langs/'+lang+'.js' ); markDone( baseurl+'/plugins/'+plugin+'/langs/'+lang+'_dlg.js' ) } }); })();
zyblog
trunk/zyblog/wp-includes/js/tinymce/mark_loaded_src.js
JavaScript
asf20
802
tinyMCE.addI18n({en:{ common:{ edit_confirm:"Do you want to use the WYSIWYG mode for this textarea?", apply:"Apply", insert:"Insert", update:"Update", cancel:"Cancel", close:"Close", browse:"Browse", class_name:"Class", not_set:"-- Not set --", clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.", clipboard_no_support:"Currently not supported by your browser, use keyboard shortcuts instead.", popup_blocked:"Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.", invalid_data:"ERROR: Invalid values entered, these are marked in red.", invalid_data_number:"{#field} must be a number", invalid_data_min:"{#field} must be a number greater than {#min}", invalid_data_size:"{#field} must be a number or percentage", more_colors:"More colors" }, colors:{ "000000":"Black", "993300":"Burnt orange", "333300":"Dark olive", "003300":"Dark green", "003366":"Dark azure", "000080":"Navy Blue", "333399":"Indigo", "333333":"Very dark gray", "800000":"Maroon", "FF6600":"Orange", "808000":"Olive", "008000":"Green", "008080":"Teal", "0000FF":"Blue", "666699":"Grayish blue", "808080":"Gray", "FF0000":"Red", "FF9900":"Amber", "99CC00":"Yellow green", "339966":"Sea green", "33CCCC":"Turquoise", "3366FF":"Royal blue", "800080":"Purple", "999999":"Medium gray", "FF00FF":"Magenta", "FFCC00":"Gold", "FFFF00":"Yellow", "00FF00":"Lime", "00FFFF":"Aqua", "00CCFF":"Sky blue", "993366":"Brown", "C0C0C0":"Silver", "FF99CC":"Pink", "FFCC99":"Peach", "FFFF99":"Light yellow", "CCFFCC":"Pale green", "CCFFFF":"Pale cyan", "99CCFF":"Light sky blue", "CC99FF":"Plum", "FFFFFF":"White" }, contextmenu:{ align:"Alignment", left:"Left", center:"Center", right:"Right", full:"Full" }, insertdatetime:{ date_fmt:"%Y-%m-%d", time_fmt:"%H:%M:%S", insertdate_desc:"Insert date", inserttime_desc:"Insert time", months_long:"January,February,March,April,May,June,July,August,September,October,November,December", months_short:"Jan_January_abbreviation,Feb_February_abbreviation,Mar_March_abbreviation,Apr_April_abbreviation,May_May_abbreviation,Jun_June_abbreviation,Jul_July_abbreviation,Aug_August_abbreviation,Sep_September_abbreviation,Oct_October_abbreviation,Nov_November_abbreviation,Dec_December_abbreviation", day_long:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday", day_short:"Sun,Mon,Tue,Wed,Thu,Fri,Sat" }, print:{ print_desc:"Print" }, preview:{ preview_desc:"Preview" }, directionality:{ ltr_desc:"Direction left to right", rtl_desc:"Direction right to left" }, layer:{ insertlayer_desc:"Insert new layer", forward_desc:"Move forward", backward_desc:"Move backward", absolute_desc:"Toggle absolute positioning", content:"New layer..." }, save:{ save_desc:"Save", cancel_desc:"Cancel all changes" }, nonbreaking:{ nonbreaking_desc:"Insert non-breaking space character" }, iespell:{ iespell_desc:"Run spell checking", download:"ieSpell not detected. Do you want to install it now?" }, advhr:{ advhr_desc:"Horizontal rule" }, emotions:{ emotions_desc:"Emotions" }, searchreplace:{ search_desc:"Find", replace_desc:"Find/Replace" }, advimage:{ image_desc:"Insert/edit image" }, advlink:{ link_desc:"Insert/edit link" }, xhtmlxtras:{ cite_desc:"Citation", abbr_desc:"Abbreviation", acronym_desc:"Acronym", del_desc:"Deletion", ins_desc:"Insertion", attribs_desc:"Insert/Edit Attributes" }, style:{ desc:"Edit CSS Style" }, paste:{ paste_text_desc:"Paste as Plain Text", paste_word_desc:"Paste from Word", selectall_desc:"Select All", plaintext_mode_sticky:"Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.", plaintext_mode:"Paste is now in plain text mode. Click again to toggle back to regular paste mode." }, paste_dlg:{ text_title:"Use CTRL + V on your keyboard to paste the text into the window.", text_linebreaks:"Keep linebreaks", word_title:"Use CTRL + V on your keyboard to paste the text into the window." }, table:{ desc:"Inserts a new table", row_before_desc:"Insert row before", row_after_desc:"Insert row after", delete_row_desc:"Delete row", col_before_desc:"Insert column before", col_after_desc:"Insert column after", delete_col_desc:"Remove column", split_cells_desc:"Split merged table cells", merge_cells_desc:"Merge table cells", row_desc:"Table row properties", cell_desc:"Table cell properties", props_desc:"Table properties", paste_row_before_desc:"Paste table row before", paste_row_after_desc:"Paste table row after", cut_row_desc:"Cut table row", copy_row_desc:"Copy table row", del:"Delete table", row:"Row", col:"Column", cell:"Cell" }, autosave:{ unload_msg:"The changes you made will be lost if you navigate away from this page." }, fullscreen:{ desc:"Toggle fullscreen mode (Alt + Shift + G)" }, media:{ desc:"Insert / edit embedded media", edit:"Edit embedded media" }, fullpage:{ desc:"Document properties" }, template:{ desc:"Insert predefined template content" }, visualchars:{ desc:"Visual control characters on/off." }, spellchecker:{ desc:"Toggle spellchecker (Alt + Shift + N)", menu:"Spellchecker settings", ignore_word:"Ignore word", ignore_words:"Ignore all", langs:"Languages", wait:"Please wait...", sug:"Suggestions", no_sug:"No suggestions", no_mpell:"No misspellings found.", learn_word:"Learn word" }, pagebreak:{ desc:"Insert Page Break" }, advlist:{ types:"Types", def:"Default", lower_alpha:"Lower alpha", lower_greek:"Lower greek", lower_roman:"Lower roman", upper_alpha:"Upper alpha", upper_roman:"Upper roman", circle:"Circle", disc:"Disc", square:"Square" }, aria:{ rich_text_area:"Rich Text Area" }, wordcount:{ words:"Words: " } }}); tinyMCE.addI18n("en.advanced",{ style_select:"Styles", font_size:"Font size", fontdefault:"Font family", block:"Format", paragraph:"Paragraph", div:"Div", address:"Address", pre:"Preformatted", h1:"Heading 1", h2:"Heading 2", h3:"Heading 3", h4:"Heading 4", h5:"Heading 5", h6:"Heading 6", blockquote:"Blockquote", code:"Code", samp:"Code sample", dt:"Definition term ", dd:"Definition description", bold_desc:"Bold (Ctrl + B)", italic_desc:"Italic (Ctrl + I)", underline_desc:"Underline", striketrough_desc:"Strikethrough (Alt + Shift + D)", justifyleft_desc:"Align Left (Alt + Shift + L)", justifycenter_desc:"Align Center (Alt + Shift + C)", justifyright_desc:"Align Right (Alt + Shift + R)", justifyfull_desc:"Align Full (Alt + Shift + J)", bullist_desc:"Unordered list (Alt + Shift + U)", numlist_desc:"Ordered list (Alt + Shift + O)", outdent_desc:"Outdent", indent_desc:"Indent", undo_desc:"Undo (Ctrl + Z)", redo_desc:"Redo (Ctrl + Y)", link_desc:"Insert/edit link (Alt + Shift + A)", unlink_desc:"Unlink (Alt + Shift + S)", image_desc:"Insert/edit image (Alt + Shift + M)", cleanup_desc:"Cleanup messy code", code_desc:"Edit HTML Source", sub_desc:"Subscript", sup_desc:"Superscript", hr_desc:"Insert horizontal ruler", removeformat_desc:"Remove formatting", forecolor_desc:"Select text color", backcolor_desc:"Select background color", charmap_desc:"Insert custom character", visualaid_desc:"Toggle guidelines/invisible elements", anchor_desc:"Insert/edit anchor", cut_desc:"Cut", copy_desc:"Copy", paste_desc:"Paste", image_props_desc:"Image properties", newdocument_desc:"New document", help_desc:"Help", blockquote_desc:"Blockquote (Alt + Shift + Q)", clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.", path:"Path", newdocument:"Are you sure you want to clear all contents?", toolbar_focus:"Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X", more_colors:"More colors", shortcuts_desc:"Accessibility Help", help_shortcut:" Press ALT F10 for toolbar. Press ALT 0 for help.", rich_text_area:"Rich Text Area", toolbar:"Toolbar" }); tinyMCE.addI18n("en.advanced_dlg",{ about_title:"About TinyMCE", about_general:"About", about_help:"Help", about_license:"License", about_plugins:"Plugins", about_plugin:"Plugin", about_author:"Author", about_version:"Version", about_loaded:"Loaded plugins", anchor_title:"Insert/edit anchor", anchor_name:"Anchor name", code_title:"HTML Source Editor", code_wordwrap:"Word wrap", colorpicker_title:"Select a color", colorpicker_picker_tab:"Picker", colorpicker_picker_title:"Color picker", colorpicker_palette_tab:"Palette", colorpicker_palette_title:"Palette colors", colorpicker_named_tab:"Named", colorpicker_named_title:"Named colors", colorpicker_color:"Color:", colorpicker_name:"Name:", charmap_title:"Select custom character", charmap_usage:"Use left and right arrows to navigate.", image_title:"Insert/edit image", image_src:"Image URL", image_alt:"Image description", image_list:"Image list", image_border:"Border", image_dimensions:"Dimensions", image_vspace:"Vertical space", image_hspace:"Horizontal space", image_align:"Alignment", image_align_baseline:"Baseline", image_align_top:"Top", image_align_middle:"Middle", image_align_bottom:"Bottom", image_align_texttop:"Text top", image_align_textbottom:"Text bottom", image_align_left:"Left", image_align_right:"Right", link_title:"Insert/edit link", link_url:"Link URL", link_target:"Target", link_target_same:"Open link in the same window", link_target_blank:"Open link in a new window", link_titlefield:"Title", link_is_email:"The URL you entered seems to be an email address, do you want to add the required mailto: prefix?", link_is_external:"The URL you entered seems to external link, do you want to add the required http:// prefix?", link_list:"Link list", accessibility_help:"Accessibility Help", accessibility_usage_title:"General Usage" }); tinyMCE.addI18n("en.media_dlg",{ title:"Insert / edit embedded media", general:"General", advanced:"Advanced", file:"File/URL", list:"List", size:"Dimensions", preview:"Preview", constrain_proportions:"Constrain proportions", type:"Type", id:"Id", name:"Name", class_name:"Class", vspace:"V-Space", hspace:"H-Space", play:"Auto play", loop:"Loop", menu:"Show menu", quality:"Quality", scale:"Scale", align:"Align", salign:"SAlign", wmode:"WMode", bgcolor:"Background", base:"Base", flashvars:"Flashvars", liveconnect:"SWLiveConnect", autohref:"AutoHREF", cache:"Cache", hidden:"Hidden", controller:"Controller", kioskmode:"Kiosk mode", playeveryframe:"Play every frame", targetcache:"Target cache", correction:"No correction", enablejavascript:"Enable JavaScript", starttime:"Start time", endtime:"End time", href:"href", qtsrcchokespeed:"Choke speed", target:"Target", volume:"Volume", autostart:"Auto start", enabled:"Enabled", fullscreen:"Fullscreen", invokeurls:"Invoke URLs", mute:"Mute", stretchtofit:"Stretch to fit", windowlessvideo:"Windowless video", balance:"Balance", baseurl:"Base URL", captioningid:"Captioning id", currentmarker:"Current marker", currentposition:"Current position", defaultframe:"Default frame", playcount:"Play count", rate:"Rate", uimode:"UI Mode", flash_options:"Flash options", qt_options:"QuickTime options", wmp_options:"Windows media player options", rmp_options:"Real media player options", shockwave_options:"Shockwave options", autogotourl:"Auto goto URL", center:"Center", imagestatus:"Image status", maintainaspect:"Maintain aspect", nojava:"No java", prefetch:"Prefetch", shuffle:"Shuffle", console:"Console", numloop:"Num loops", controls:"Controls", scriptcallbacks:"Script callbacks", swstretchstyle:"Stretch style", swstretchhalign:"Stretch H-Align", swstretchvalign:"Stretch V-Align", sound:"Sound", progress:"Progress", qtsrc:"QT Src", qt_stream_warn:"Streamed rtsp resources should be added to the QT Src field under the advanced tab.", align_top:"Top", align_right:"Right", align_bottom:"Bottom", align_left:"Left", align_center:"Center", align_top_left:"Top left", align_top_right:"Top right", align_bottom_left:"Bottom left", align_bottom_right:"Bottom right", flv_options:"Flash video options", flv_scalemode:"Scale mode", flv_buffer:"Buffer", flv_startimage:"Start image", flv_starttime:"Start time", flv_defaultvolume:"Default volume", flv_hiddengui:"Hidden GUI", flv_autostart:"Auto start", flv_loop:"Loop", flv_showscalemodes:"Show scale modes", flv_smoothvideo:"Smooth video", flv_jscallback:"JS Callback", html5_video_options:"HTML5 Video Options", altsource1:"Alternative source 1", altsource2:"Alternative source 2", preload:"Preload", poster:"Poster", source:"Source" }); tinyMCE.addI18n("en.wordpress",{ wp_adv_desc:"Show/Hide Kitchen Sink (Alt + Shift + Z)", wp_more_desc:"Insert More Tag (Alt + Shift + T)", wp_page_desc:"Insert Page break (Alt + Shift + P)", wp_help_desc:"Help (Alt + Shift + H)", wp_more_alt:"More...", wp_page_alt:"Next page...", add_media:"Add Media", add_image:"Add an Image", add_video:"Add Video", add_audio:"Add Audio", editgallery:"Edit Gallery", delgallery:"Delete Gallery", wp_fullscreen_desc:"Distraction Free Writing mode (Alt + Shift + W)" }); tinyMCE.addI18n("en.wpeditimage",{ edit_img:"Edit Image", del_img:"Delete Image", adv_settings:"Advanced Settings", none:"None", size:"Size", thumbnail:"Thumbnail", medium:"Medium", full_size:"Full Size", current_link:"Current Link", link_to_img:"Link to Image", link_help:"Enter a link URL or click above for presets.", adv_img_settings:"Advanced Image Settings", source:"Source", width:"Width", height:"Height", orig_size:"Original Size", css:"CSS Class", adv_link_settings:"Advanced Link Settings", link_rel:"Link Rel", height:"Height", orig_size:"Original Size", css:"CSS Class", s60:"60%", s70:"70%", s80:"80%", s90:"90%", s100:"100%", s110:"110%", s120:"120%", s130:"130%", img_title:"Title", caption:"Caption", alt:"Alternative Text" });
zyblog
trunk/zyblog/wp-includes/js/tinymce/langs/wp-langs-en.js
JavaScript
asf20
13,662
<?php if ( ! defined( 'ABSPATH' ) ) exit; if ( ! class_exists( '_WP_Editors' ) ) require( ABSPATH . WPINC . '/class-wp-editor.php' ); // deprecated, not used function mce_escape($text) { return esc_js($text); } function wp_mce_translation() { $default = array( 'common' => array( 'edit_confirm' => __('Do you want to use the WYSIWYG mode for this textarea?'), 'apply' => __('Apply'), 'insert' => __('Insert'), 'update' => __('Update'), 'cancel' => __('Cancel'), 'close' => __('Close'), 'browse' => __('Browse'), 'class_name' => __('Class'), 'not_set' => __('-- Not set --'), 'clipboard_msg' => __('Copy/Cut/Paste is not available in Mozilla and Firefox.'), 'clipboard_no_support' => __('Currently not supported by your browser, use keyboard shortcuts instead.'), 'popup_blocked' => __('Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.'), 'invalid_data' => __('ERROR: Invalid values entered, these are marked in red.'), 'invalid_data_number' => __('{#field} must be a number'), 'invalid_data_min' => __('{#field} must be a number greater than {#min}'), 'invalid_data_size' => __('{#field} must be a number or percentage'), 'more_colors' => __('More colors') ), 'colors' => array( '000000' => __('Black'), '993300' => __('Burnt orange'), '333300' => __('Dark olive'), '003300' => __('Dark green'), '003366' => __('Dark azure'), '000080' => __('Navy Blue'), '333399' => __('Indigo'), '333333' => __('Very dark gray'), '800000' => __('Maroon'), 'FF6600' => __('Orange'), '808000' => __('Olive'), '008000' => __('Green'), '008080' => __('Teal'), '0000FF' => __('Blue'), '666699' => __('Grayish blue'), '808080' => __('Gray'), 'FF0000' => __('Red'), 'FF9900' => __('Amber'), '99CC00' => __('Yellow green'), '339966' => __('Sea green'), '33CCCC' => __('Turquoise'), '3366FF' => __('Royal blue'), '800080' => __('Purple'), '999999' => __('Medium gray'), 'FF00FF' => __('Magenta'), 'FFCC00' => __('Gold'), 'FFFF00' => __('Yellow'), '00FF00' => __('Lime'), '00FFFF' => __('Aqua'), '00CCFF' => __('Sky blue'), '993366' => __('Brown'), 'C0C0C0' => __('Silver'), 'FF99CC' => __('Pink'), 'FFCC99' => __('Peach'), 'FFFF99' => __('Light yellow'), 'CCFFCC' => __('Pale green'), 'CCFFFF' => __('Pale cyan'), '99CCFF' => __('Light sky blue'), 'CC99FF' => __('Plum'), 'FFFFFF' => __('White') ), 'contextmenu' => array( 'align' => __('Alignment'), /* translators: alignment */ 'left' => __('Left'), /* translators: alignment */ 'center' => __('Center'), /* translators: alignment */ 'right' => __('Right'), /* translators: alignment */ 'full' => __('Full') /* translators: alignment */ ), 'insertdatetime' => array( 'date_fmt' => __('%Y-%m-%d'), /* translators: year, month, date */ 'time_fmt' => __('%H:%M:%S'), /* translators: hours, minutes, seconds */ 'insertdate_desc' => __('Insert date'), 'inserttime_desc' => __('Insert time'), 'months_long' => __('January').','.__('February').','.__('March').','.__('April').','.__('May').','.__('June').','.__('July').','.__('August').','.__('September').','.__('October').','.__('November').','.__('December'), 'months_short' => __('Jan_January_abbreviation').','.__('Feb_February_abbreviation').','.__('Mar_March_abbreviation').','.__('Apr_April_abbreviation').','.__('May_May_abbreviation').','.__('Jun_June_abbreviation').','.__('Jul_July_abbreviation').','.__('Aug_August_abbreviation').','.__('Sep_September_abbreviation').','.__('Oct_October_abbreviation').','.__('Nov_November_abbreviation').','.__('Dec_December_abbreviation'), 'day_long' => __('Sunday').','.__('Monday').','.__('Tuesday').','.__('Wednesday').','.__('Thursday').','.__('Friday').','.__('Saturday'), 'day_short' => __('Sun').','.__('Mon').','.__('Tue').','.__('Wed').','.__('Thu').','.__('Fri').','.__('Sat') ), 'print' => array( 'print_desc' => __('Print') ), 'preview' => array( 'preview_desc' => __('Preview') ), 'directionality' => array( 'ltr_desc' => __('Direction left to right'), 'rtl_desc' => __('Direction right to left') ), 'layer' => array( 'insertlayer_desc' => __('Insert new layer'), 'forward_desc' => __('Move forward'), 'backward_desc' => __('Move backward'), 'absolute_desc' => __('Toggle absolute positioning'), 'content' => __('New layer...') ), 'save' => array( 'save_desc' => __('Save'), 'cancel_desc' => __('Cancel all changes') ), 'nonbreaking' => array( 'nonbreaking_desc' => __('Insert non-breaking space character') ), 'iespell' => array( 'iespell_desc' => __('Run spell checking'), 'download' => __('ieSpell not detected. Do you want to install it now?') ), 'advhr' => array( 'advhr_desc' => __('Horizontal rule') ), 'emotions' => array( 'emotions_desc' => __('Emotions') ), 'searchreplace' => array( 'search_desc' => __('Find'), 'replace_desc' => __('Find/Replace') ), 'advimage' => array( 'image_desc' => __('Insert/edit image') ), 'advlink' => array( 'link_desc' => __('Insert/edit link') ), 'xhtmlxtras' => array( 'cite_desc' => __('Citation'), 'abbr_desc' => __('Abbreviation'), 'acronym_desc' => __('Acronym'), 'del_desc' => __('Deletion'), 'ins_desc' => __('Insertion'), 'attribs_desc' => __('Insert/Edit Attributes') ), 'style' => array( 'desc' => __('Edit CSS Style') ), 'paste' => array( 'paste_text_desc' => __('Paste as Plain Text'), 'paste_word_desc' => __('Paste from Word'), 'selectall_desc' => __('Select All'), 'plaintext_mode_sticky' => __('Paste is now in plain text mode. Click again to toggle back to regular paste mode. After you paste something you will be returned to regular paste mode.'), 'plaintext_mode' => __('Paste is now in plain text mode. Click again to toggle back to regular paste mode.') ), 'paste_dlg' => array( 'text_title' => __('Use CTRL+V on your keyboard to paste the text into the window.'), 'text_linebreaks' => __('Keep linebreaks'), 'word_title' => __('Use CTRL+V on your keyboard to paste the text into the window.') ), 'table' => array( 'desc' => __('Inserts a new table'), 'row_before_desc' => __('Insert row before'), 'row_after_desc' => __('Insert row after'), 'delete_row_desc' => __('Delete row'), 'col_before_desc' => __('Insert column before'), 'col_after_desc' => __('Insert column after'), 'delete_col_desc' => __('Remove column'), 'split_cells_desc' => __('Split merged table cells'), 'merge_cells_desc' => __('Merge table cells'), 'row_desc' => __('Table row properties'), 'cell_desc' => __('Table cell properties'), 'props_desc' => __('Table properties'), 'paste_row_before_desc' => __('Paste table row before'), 'paste_row_after_desc' => __('Paste table row after'), 'cut_row_desc' => __('Cut table row'), 'copy_row_desc' => __('Copy table row'), 'del' => __('Delete table'), 'row' => __('Row'), 'col' => __('Column'), 'cell' => __('Cell') ), 'autosave' => array( 'unload_msg' => __('The changes you made will be lost if you navigate away from this page.') ), 'fullscreen' => array( 'desc' => __('Toggle fullscreen mode (Alt + Shift + G)') ), 'media' => array( 'desc' => __('Insert / edit embedded media'), 'edit' => __('Edit embedded media') ), 'fullpage' => array( 'desc' => __('Document properties') ), 'template' => array( 'desc' => __('Insert predefined template content') ), 'visualchars' => array( 'desc' => __('Visual control characters on/off.') ), 'spellchecker' => array( 'desc' => __('Toggle spellchecker (Alt + Shift + N)'), 'menu' => __('Spellchecker settings'), 'ignore_word' => __('Ignore word'), 'ignore_words' => __('Ignore all'), 'langs' => __('Languages'), 'wait' => __('Please wait...'), 'sug' => __('Suggestions'), 'no_sug' => __('No suggestions'), 'no_mpell' => __('No misspellings found.'), 'learn_word' => __('Learn word') ), 'pagebreak' => array( 'desc' => __('Insert Page Break') ), 'advlist' => array( 'types' => __('Types'), 'def' => __('Default'), 'lower_alpha' => __('Lower alpha'), 'lower_greek' => __('Lower greek'), 'lower_roman' => __('Lower roman'), 'upper_alpha' => __('Upper alpha'), 'upper_roman' => __('Upper roman'), 'circle' => __('Circle'), 'disc' => __('Disc'), 'square' => __('Square') ), 'aria' => array( 'rich_text_area' => __('Rich Text Area') ), 'wordcount' => array( 'words' => __('Words:') ) ); $advanced = array( 'style_select' => __('Styles'), /* translators: TinyMCE inline styles */ 'font_size' => __('Font size'), 'fontdefault' => __('Font family'), 'block' => __('Format'), 'paragraph' => __('Paragraph'), 'div' => __('Div'), 'address' => __('Address'), 'pre' => __('Preformatted'), 'h1' => __('Heading 1'), 'h2' => __('Heading 2'), 'h3' => __('Heading 3'), 'h4' => __('Heading 4'), 'h5' => __('Heading 5'), 'h6' => __('Heading 6'), 'blockquote' => __('Blockquote'), 'code' => __('Code'), 'samp' => __('Code sample'), 'dt' => __('Definition term '), 'dd' => __('Definition description'), 'bold_desc' => __('Bold (Ctrl + B)'), 'italic_desc' => __('Italic (Ctrl + I)'), 'underline_desc' => __('Underline'), 'striketrough_desc' => __('Strikethrough (Alt + Shift + D)'), 'justifyleft_desc' => __('Align Left (Alt + Shift + L)'), 'justifycenter_desc' => __('Align Center (Alt + Shift + C)'), 'justifyright_desc' => __('Align Right (Alt + Shift + R)'), 'justifyfull_desc' => __('Align Full (Alt + Shift + J)'), 'bullist_desc' => __('Unordered list (Alt + Shift + U)'), 'numlist_desc' => __('Ordered list (Alt + Shift + O)'), 'outdent_desc' => __('Outdent'), 'indent_desc' => __('Indent'), 'undo_desc' => __('Undo (Ctrl + Z)'), 'redo_desc' => __('Redo (Ctrl + Y)'), 'link_desc' => __('Insert/edit link (Alt + Shift + A)'), 'unlink_desc' => __('Unlink (Alt + Shift + S)'), 'image_desc' => __('Insert/edit image (Alt + Shift + M)'), 'cleanup_desc' => __('Cleanup messy code'), 'code_desc' => __('Edit HTML Source'), 'sub_desc' => __('Subscript'), 'sup_desc' => __('Superscript'), 'hr_desc' => __('Insert horizontal ruler'), 'removeformat_desc' => __('Remove formatting'), 'forecolor_desc' => __('Select text color'), 'backcolor_desc' => __('Select background color'), 'charmap_desc' => __('Insert custom character'), 'visualaid_desc' => __('Toggle guidelines/invisible elements'), 'anchor_desc' => __('Insert/edit anchor'), 'cut_desc' => __('Cut'), 'copy_desc' => __('Copy'), 'paste_desc' => __('Paste'), 'image_props_desc' => __('Image properties'), 'newdocument_desc' => __('New document'), 'help_desc' => __('Help'), 'blockquote_desc' => __('Blockquote (Alt + Shift + Q)'), 'clipboard_msg' => __('Copy/Cut/Paste is not available in Mozilla and Firefox.'), 'path' => __('Path'), 'newdocument' => __('Are you sure you want to clear all contents?'), 'toolbar_focus' => __('Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X'), 'more_colors' => __('More colors'), 'shortcuts_desc' => __('Accessibility Help'), 'help_shortcut' => __('Press ALT F10 for toolbar. Press ALT 0 for help.'), 'rich_text_area' => __('Rich Text Area'), 'toolbar' => __('Toolbar') ); $advanced_dlg = array( 'about_title' => __('About TinyMCE'), 'about_general' => __('About'), 'about_help' => __('Help'), 'about_license' => __('License'), 'about_plugins' => __('Plugins'), 'about_plugin' => __('Plugin'), 'about_author' => __('Author'), 'about_version' => __('Version'), 'about_loaded' => __('Loaded plugins'), 'anchor_title' => __('Insert/edit anchor'), 'anchor_name' => __('Anchor name'), 'code_title' => __('HTML Source Editor'), 'code_wordwrap' => __('Word wrap'), 'colorpicker_title' => __('Select a color'), 'colorpicker_picker_tab' => __('Picker'), 'colorpicker_picker_title' => __('Color picker'), 'colorpicker_palette_tab' => __('Palette'), 'colorpicker_palette_title' => __('Palette colors'), 'colorpicker_named_tab' => __('Named'), 'colorpicker_named_title' => __('Named colors'), 'colorpicker_color' => __('Color:'), 'colorpicker_name' => _x('Name:', 'html attribute'), 'charmap_title' => __('Select custom character'), 'charmap_usage' => __('Use left and right arrows to navigate.'), 'image_title' => __('Insert/edit image'), 'image_src' => __('Image URL'), 'image_alt' => __('Image description'), 'image_list' => __('Image list'), 'image_border' => __('Border'), 'image_dimensions' => __('Dimensions'), 'image_vspace' => __('Vertical space'), 'image_hspace' => __('Horizontal space'), 'image_align' => __('Alignment'), 'image_align_baseline' => __('Baseline'), 'image_align_top' => __('Top'), 'image_align_middle' => __('Middle'), 'image_align_bottom' => __('Bottom'), 'image_align_texttop' => __('Text top'), 'image_align_textbottom' => __('Text bottom'), 'image_align_left' => __('Left'), 'image_align_right' => __('Right'), 'link_title' => __('Insert/edit link'), 'link_url' => __('Link URL'), 'link_target' => __('Target'), 'link_target_same' => __('Open link in the same window'), 'link_target_blank' => __('Open link in a new window'), 'link_titlefield' => __('Title'), 'link_is_email' => __('The URL you entered seems to be an email address, do you want to add the required mailto: prefix?'), 'link_is_external' => __('The URL you entered seems to external link, do you want to add the required http:// prefix?'), 'link_list' => __('Link list'), 'accessibility_help' => __('Accessibility Help'), 'accessibility_usage_title' => __('General Usage') ); $media_dlg = array( 'title' => __('Insert / edit embedded media'), 'general' => __('General'), 'advanced' => __('Advanced'), 'file' => __('File/URL'), 'list' => __('List'), 'size' => __('Dimensions'), 'preview' => __('Preview'), 'constrain_proportions' => __('Constrain proportions'), 'type' => __('Type'), 'id' => __('Id'), 'name' => _x('Name', 'html attribute'), 'class_name' => __('Class'), 'vspace' => __('V-Space'), 'hspace' => __('H-Space'), 'play' => __('Auto play'), 'loop' => __('Loop'), 'menu' => __('Show menu'), 'quality' => __('Quality'), 'scale' => __('Scale'), 'align' => __('Align'), 'salign' => __('SAlign'), 'wmode' => __('WMode'), 'bgcolor' => __('Background'), 'base' => __('Base'), 'flashvars' => __('Flashvars'), 'liveconnect' => __('SWLiveConnect'), 'autohref' => __('AutoHREF'), 'cache' => __('Cache'), 'hidden' => __('Hidden'), 'controller' => __('Controller'), 'kioskmode' => __('Kiosk mode'), 'playeveryframe' => __('Play every frame'), 'targetcache' => __('Target cache'), 'correction' => __('No correction'), 'enablejavascript' => __('Enable JavaScript'), 'starttime' => __('Start time'), 'endtime' => __('End time'), 'href' => __('href'), 'qtsrcchokespeed' => __('Choke speed'), 'target' => __('Target'), 'volume' => __('Volume'), 'autostart' => __('Auto start'), 'enabled' => __('Enabled'), 'fullscreen' => __('Fullscreen'), 'invokeurls' => __('Invoke URLs'), 'mute' => __('Mute'), 'stretchtofit' => __('Stretch to fit'), 'windowlessvideo' => __('Windowless video'), 'balance' => __('Balance'), 'baseurl' => __('Base URL'), 'captioningid' => __('Captioning id'), 'currentmarker' => __('Current marker'), 'currentposition' => __('Current position'), 'defaultframe' => __('Default frame'), 'playcount' => __('Play count'), 'rate' => __('Rate'), 'uimode' => __('UI Mode'), 'flash_options' => __('Flash options'), 'qt_options' => __('QuickTime options'), 'wmp_options' => __('Windows media player options'), 'rmp_options' => __('Real media player options'), 'shockwave_options' => __('Shockwave options'), 'autogotourl' => __('Auto goto URL'), 'center' => __('Center'), 'imagestatus' => __('Image status'), 'maintainaspect' => __('Maintain aspect'), 'nojava' => __('No java'), 'prefetch' => __('Prefetch'), 'shuffle' => __('Shuffle'), 'console' => __('Console'), 'numloop' => __('Num loops'), 'controls' => __('Controls'), 'scriptcallbacks' => __('Script callbacks'), 'swstretchstyle' => __('Stretch style'), 'swstretchhalign' => __('Stretch H-Align'), 'swstretchvalign' => __('Stretch V-Align'), 'sound' => __('Sound'), 'progress' => __('Progress'), 'qtsrc' => __('QT Src'), 'qt_stream_warn' => __('Streamed rtsp resources should be added to the QT Src field under the advanced tab.'), 'align_top' => __('Top'), 'align_right' => __('Right'), 'align_bottom' => __('Bottom'), 'align_left' => __('Left'), 'align_center' => __('Center'), 'align_top_left' => __('Top left'), 'align_top_right' => __('Top right'), 'align_bottom_left' => __('Bottom left'), 'align_bottom_right' => __('Bottom right'), 'flv_options' => __('Flash video options'), 'flv_scalemode' => __('Scale mode'), 'flv_buffer' => __('Buffer'), 'flv_startimage' => __('Start image'), 'flv_starttime' => __('Start time'), 'flv_defaultvolume' => __('Default volume'), 'flv_hiddengui' => __('Hidden GUI'), 'flv_autostart' => __('Auto start'), 'flv_loop' => __('Loop'), 'flv_showscalemodes' => __('Show scale modes'), 'flv_smoothvideo' => __('Smooth video'), 'flv_jscallback' => __('JS Callback'), 'html5_video_options' => __('HTML5 Video Options'), 'altsource1' => __('Alternative source 1'), 'altsource2' => __('Alternative source 2'), 'preload' => __('Preload'), 'poster' => __('Poster'), 'source' => __('Source') ); $wordpress = array( 'wp_adv_desc' => __('Show/Hide Kitchen Sink (Alt + Shift + Z)'), 'wp_more_desc' => __('Insert More Tag (Alt + Shift + T)'), 'wp_page_desc' => __('Insert Page break (Alt + Shift + P)'), 'wp_help_desc' => __('Help (Alt + Shift + H)'), 'wp_more_alt' => __('More...'), 'wp_page_alt' => __('Next page...'), 'add_media' => __('Add Media'), 'add_image' => __('Add an Image'), 'add_video' => __('Add Video'), 'add_audio' => __('Add Audio'), 'editgallery' => __('Edit Gallery'), 'delgallery' => __('Delete Gallery'), 'wp_fullscreen_desc' => __('Distraction Free Writing mode (Alt + Shift + W)') ); $wpeditimage = array( 'edit_img' => __('Edit Image'), 'del_img' => __('Delete Image'), 'adv_settings' => __('Advanced Settings'), 'none' => __('None'), 'size' => __('Size'), 'thumbnail' => __('Thumbnail'), 'medium' => __('Medium'), 'full_size' => __('Full Size'), 'current_link' => __('Current Link'), 'link_to_img' => __('Link to Image'), 'link_help' => __('Enter a link URL or click above for presets.'), 'adv_img_settings' => __('Advanced Image Settings'), 'source' => __('Source'), 'width' => __('Width'), 'height' => __('Height'), 'orig_size' => __('Original Size'), 'css' => __('CSS Class'), 'adv_link_settings' => __('Advanced Link Settings'), 'link_rel' => __('Link Rel'), 'height' => __('Height'), 'orig_size' => __('Original Size'), 'css' => __('CSS Class'), 's60' => __('60%'), 's70' => __('70%'), 's80' => __('80%'), 's90' => __('90%'), 's100' => __('100%'), 's110' => __('110%'), 's120' => __('120%'), 's130' => __('130%'), 'img_title' => __('Title'), 'caption' => __('Caption'), 'alt' => __('Alternative Text') ); $locale = _WP_Editors::$mce_locale; $translated = 'tinyMCE.addI18n({' . $locale . ':' . json_encode( $default ) . "});\n"; $translated .= 'tinyMCE.addI18n("' . $locale . '.advanced", ' . json_encode( $advanced ) . ");\n"; $translated .= 'tinyMCE.addI18n("' . $locale . '.advanced_dlg", ' . json_encode( $advanced_dlg ) . ");\n"; $translated .= 'tinyMCE.addI18n("' . $locale . '.media_dlg", ' . json_encode( $media_dlg ) . ");\n"; $translated .= 'tinyMCE.addI18n("' . $locale . '.wordpress", ' . json_encode( $wordpress ) . ");\n"; $translated .= 'tinyMCE.addI18n("' . $locale . '.wpeditimage", ' . json_encode( $wpeditimage ) . ');'; return $translated; } $lang = wp_mce_translation();
zyblog
trunk/zyblog/wp-includes/js/tinymce/langs/wp-langs.php
PHP
asf20
20,390
<?php /** * Disable error reporting * * Set this to error_reporting( E_ALL ) or error_reporting( E_ALL | E_STRICT ) for debugging */ error_reporting(0); $basepath = dirname(__FILE__); function get_file($path) { if ( function_exists('realpath') ) $path = realpath($path); if ( ! $path || ! @is_file($path) ) return false; return @file_get_contents($path); } $expires_offset = 31536000; // 1 year header('Content-Type: application/x-javascript; charset=UTF-8'); header('Vary: Accept-Encoding'); // Handle proxies header('Expires: ' . gmdate( "D, d M Y H:i:s", time() + $expires_offset ) . ' GMT'); header("Cache-Control: public, max-age=$expires_offset"); if ( isset($_GET['c']) && 1 == $_GET['c'] && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') && ( $file = get_file($basepath . '/wp-tinymce.js.gz') ) ) { header('Content-Encoding: gzip'); echo $file; } else { echo get_file($basepath . '/tiny_mce.js'); echo get_file($basepath . '/wp-tinymce-schema.js'); } exit;
zyblog
trunk/zyblog/wp-includes/js/tinymce/wp-tinymce.php
PHP
asf20
1,046
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{#advanced_dlg.about_title}</title> <script type="text/javascript" src="../../tiny_mce_popup.js?ver=358-20121205"></script> <script type="text/javascript" src="../../utils/mctabs.js?ver=358-20121205"></script> <script type="text/javascript" src="js/about.js?ver=358-20121205"></script> </head> <body id="about" style="display: none"> <div class="tabs"> <ul> <li id="general_tab" class="current" aria-controls="general_panel"><span><a href="javascript:mcTabs.displayTab('general_tab','general_panel');" onmousedown="return false;">{#advanced_dlg.about_general}</a></span></li> <li id="help_tab" style="display:none" aria-hidden="true" aria-controls="help_panel"><span><a href="javascript:mcTabs.displayTab('help_tab','help_panel');" onmousedown="return false;">{#advanced_dlg.about_help}</a></span></li> <li id="plugins_tab" aria-controls="plugins_panel"><span><a href="javascript:mcTabs.displayTab('plugins_tab','plugins_panel');" onmousedown="return false;">{#advanced_dlg.about_plugins}</a></span></li> </ul> </div> <div class="panel_wrapper"> <div id="general_panel" class="panel current"> <h3>{#advanced_dlg.about_title}</h3> <p>Version: <span id="version"></span> (<span id="date"></span>)</p> <p>TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor control released as Open Source under <a href="../../license.txt" target="_blank">LGPL</a> by Moxiecode Systems AB. It has the ability to convert HTML TEXTAREA fields or other HTML elements to editor instances.</p> <p>Copyright &copy; 2003-2008, <a href="http://www.moxiecode.com" target="_blank">Moxiecode Systems AB</a>, All rights reserved.</p> <p>For more information about this software visit the <a href="http://tinymce.moxiecode.com" target="_blank">TinyMCE website</a>.</p> <div id="buttoncontainer"> <a href="http://www.moxiecode.com" target="_blank"><img src="http://tinymce.moxiecode.com/images/gotmoxie.png" alt="Got Moxie?" border="0" /></a> </div> </div> <div id="plugins_panel" class="panel"> <div id="pluginscontainer"> <h3>{#advanced_dlg.about_loaded}</h3> <div id="plugintablecontainer"> </div> <p>&nbsp;</p> </div> </div> <div id="help_panel" class="panel noscroll" style="overflow: visible;"> <div id="iframecontainer"></div> </div> </div> <div class="mceActionPanel"> <input type="button" id="cancel" name="cancel" value="{#close}" onclick="tinyMCEPopup.close();" /> </div> </body> </html>
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/about.htm
HTML
asf20
2,700
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{#advanced_dlg.link_title}</title> <script type="text/javascript" src="../../tiny_mce_popup.js?ver=358-20121205"></script> <script type="text/javascript" src="../../utils/mctabs.js?ver=358-20121205"></script> <script type="text/javascript" src="../../utils/form_utils.js?ver=358-20121205"></script> <script type="text/javascript" src="../../utils/validate.js?ver=358-20121205"></script> <script type="text/javascript" src="js/link.js?ver=358-20121205"></script> </head> <body id="link" style="display: none"> <form onsubmit="LinkDialog.update();return false;" action="#"> <div class="tabs"> <ul> <li id="general_tab" class="current"><span><a href="javascript:mcTabs.displayTab('general_tab','general_panel');" onmousedown="return false;">{#advanced_dlg.link_title}</a></span></li> </ul> </div> <div class="panel_wrapper"> <div id="general_panel" class="panel current"> <table border="0" cellpadding="4" cellspacing="0"> <tr> <td class="nowrap"><label for="href">{#advanced_dlg.link_url}</label></td> <td><table border="0" cellspacing="0" cellpadding="0"> <tr> <td><input id="href" name="href" type="text" class="mceFocus" value="" style="width: 200px" onchange="LinkDialog.checkPrefix(this);" /></td> <td id="hrefbrowsercontainer">&nbsp;</td> </tr> </table></td> </tr> <tr> <td><label for="link_list">{#advanced_dlg.link_list}</label></td> <td><select id="link_list" name="link_list" onchange="document.getElementById('href').value=this.options[this.selectedIndex].value;"></select></td> </tr> <tr> <td><label id="targetlistlabel" for="targetlist">{#advanced_dlg.link_target}</label></td> <td><select id="target_list" name="target_list"></select></td> </tr> <tr> <td class="nowrap"><label for="linktitle">{#advanced_dlg.link_titlefield}</label></td> <td><input id="linktitle" name="linktitle" type="text" value="" style="width: 200px" /></td> </tr> <tr> <td><label for="class_list">{#class_name}</label></td> <td><select id="class_list" name="class_list"></select></td> </tr> </table> </div> </div> <div class="mceActionPanel"> <input type="submit" id="insert" name="insert" value="{#insert}" /> <input type="button" id="cancel" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" /> </div> </form> </body> </html>
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/link.htm
HTML
asf20
2,555
/* Reset */ .highcontrastSkin table, .highcontrastSkin tbody, .highcontrastSkin a, .highcontrastSkin img, .highcontrastSkin tr, .highcontrastSkin div, .highcontrastSkin td, .highcontrastSkin iframe, .highcontrastSkin span, .highcontrastSkin *, .highcontrastSkin .mceText {border:0; margin:0; padding:0; vertical-align:baseline; border-collapse:separate;} .highcontrastSkin a:hover, .highcontrastSkin a:link, .highcontrastSkin a:visited, .highcontrastSkin a:active {text-decoration:none; font-weight:normal; cursor:default;} .highcontrastSkin table td {vertical-align:middle} .highcontrastSkin .mceIconOnly {display: block !important;} /* External */ .highcontrastSkin .mceExternalToolbar {position:absolute; border:1px solid; border-bottom:0; display:none; background-color: white;} .highcontrastSkin .mceExternalToolbar td.mceToolbar {padding-right:13px;} .highcontrastSkin .mceExternalClose {position:absolute; top:3px; right:3px; width:7px; height:7px;} /* Layout */ .highcontrastSkin table.mceLayout {border: 1px solid;} .highcontrastSkin .mceIframeContainer {border-top:1px solid; border-bottom:1px solid} .highcontrastSkin .mceStatusbar a:hover {text-decoration:underline} .highcontrastSkin .mceStatusbar {display:block; line-height:1.5em; overflow:visible;} .highcontrastSkin .mceStatusbar div {float:left} .highcontrastSkin .mceStatusbar a.mceResize {display:block; float:right; width:20px; height:20px; cursor:se-resize; outline:0} .highcontrastSkin .mceToolbar td { display: inline-block; float: left;} .highcontrastSkin .mceToolbar tr { display: block;} .highcontrastSkin .mceToolbar table { display: block; } /* Button */ .highcontrastSkin .mceButton { display:block; margin: 2px; padding: 5px 10px;border: 1px solid; border-radius: 3px; -moz-border-radius: 3px; -webkit-border-radius: 3px; -ms-border-radius: 3px; height: 2em;} .highcontrastSkin .mceButton .mceVoiceLabel { height: 100%; vertical-align: center; line-height: 2em} .highcontrastSkin .mceButtonDisabled .mceVoiceLabel { opacity:0.6; -ms-filter:'alpha(opacity=60)'; filter:alpha(opacity=60);} .highcontrastSkin .mceButtonActive, .highcontrastSkin .mceButton:focus, .highcontrastSkin .mceButton:active { border: 5px solid; padding: 1px 6px;-webkit-focus-ring-color:none;outline:none;} /* Separator */ .highcontrastSkin .mceSeparator {display:block; width:16px; height:26px;} /* ListBox */ .highcontrastSkin .mceListBox { display: block; margin:2px;-webkit-focus-ring-color:none;outline:none;} .highcontrastSkin .mceListBox .mceText {padding: 5px 6px; line-height: 2em; width: 15ex; overflow: hidden;} .highcontrastSkin .mceListBoxDisabled .mceText { opacity:0.6; -ms-filter:'alpha(opacity=60)'; filter:alpha(opacity=60);} .highcontrastSkin .mceListBox a.mceText { padding: 5px 10px; display: block; height: 2em; line-height: 2em; border: 1px solid; border-right: 0; border-radius: 3px 0px 0px 3px; -moz-border-radius: 3px 0px 0px 3px; -webkit-border-radius: 3px 0px 0px 3px; -ms-border-radius: 3px 0px 0px 3px;} .highcontrastSkin .mceListBox a.mceOpen { padding: 5px 4px; display: block; height: 2em; line-height: 2em; border: 1px solid; border-left: 0; border-radius: 0px 3px 3px 0px; -moz-border-radius: 0px 3px 3px 0px; -webkit-border-radius: 0px 3px 3px 0px; -ms-border-radius: 0px 3px 3px 0px;} .highcontrastSkin .mceListBox:focus a.mceText, .highcontrastSkin .mceListBox:active a.mceText { border-width: 5px; padding: 1px 10px 1px 6px;} .highcontrastSkin .mceListBox:focus a.mceOpen, .highcontrastSkin .mceListBox:active a.mceOpen { border-width: 5px; padding: 1px 0px 1px 4px;} .highcontrastSkin .mceListBoxMenu {overflow-y:auto} /* SplitButton */ .highcontrastSkin .mceSplitButtonDisabled .mceAction {opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} .highcontrastSkin .mceSplitButton { border-collapse: collapse; margin: 2px; height: 2em; line-height: 2em;-webkit-focus-ring-color:none;outline:none;} .highcontrastSkin .mceSplitButton td { display: table-cell; float: none; margin: 0; padding: 0; height: 2em;} .highcontrastSkin .mceSplitButton tr { display: table-row; } .highcontrastSkin table.mceSplitButton { display: table; } .highcontrastSkin .mceSplitButton a.mceAction { padding: 5px 10px; display: block; height: 2em; line-height: 2em; overflow: hidden; border: 1px solid; border-right: 0; border-radius: 3px 0px 0px 3px; -moz-border-radius: 3px 0px 0px 3px; -webkit-border-radius: 3px 0px 0px 3px; -ms-border-radius: 3px 0px 0px 3px;} .highcontrastSkin .mceSplitButton a.mceOpen { padding: 5px 4px; display: block; height: 2em; line-height: 2em; border: 1px solid; border-radius: 0px 3px 3px 0px; -moz-border-radius: 0px 3px 3px 0px; -webkit-border-radius: 0px 3px 3px 0px; -ms-border-radius: 0px 3px 3px 0px;} .highcontrastSkin .mceSplitButton .mceVoiceLabel { height: 2em; vertical-align: center; line-height: 2em; } .highcontrastSkin .mceSplitButton:focus a.mceAction, .highcontrastSkin .mceSplitButton:active a.mceAction { border-width: 5px; border-right-width: 1px; padding: 1px 10px 1px 6px;-webkit-focus-ring-color:none;outline:none;} .highcontrastSkin .mceSplitButton:focus a.mceOpen, .highcontrastSkin .mceSplitButton:active a.mceOpen { border-width: 5px; border-left-width: 1px; padding: 1px 0px 1px 4px;-webkit-focus-ring-color:none;outline:none;} /* Menu */ .highcontrastSkin .mceNoIcons span.mceIcon {width:0;} .highcontrastSkin .mceMenu {position:absolute; left:0; top:0; z-index:1000; border:1px solid; direction:ltr} .highcontrastSkin .mceMenu table {background:white; color: black} .highcontrastSkin .mceNoIcons a .mceText {padding-left:10px} .highcontrastSkin .mceMenu a, .highcontrastSkin .mceMenu span, .highcontrastSkin .mceMenu {display:block;background:white; color: black} .highcontrastSkin .mceMenu td {height:2em} .highcontrastSkin .mceMenu a {position:relative;padding:3px 0 4px 0; display: block;} .highcontrastSkin .mceMenu .mceText {position:relative; display:block; cursor:default; margin:0; padding:0 25px 0 25px;} .highcontrastSkin .mceMenu pre.mceText {font-family:Monospace} .highcontrastSkin .mceMenu .mceIcon {position:absolute; top:0; left:0; width:26px;} .highcontrastSkin td.mceMenuItemSeparator {border-top:1px solid; height:1px} .highcontrastSkin .mceMenuItemTitle a {border:0; border-bottom:1px solid} .highcontrastSkin .mceMenuItemTitle span.mceText {font-weight:bold; padding-left:4px} .highcontrastSkin .mceNoIcons .mceMenuItemSelected span.mceText:before {content: "\2713\A0";} .highcontrastSkin .mceMenu span.mceMenuLine {display:none} .highcontrastSkin .mceMenuItemSub a .mceText:after {content: "\A0\25B8"} .highcontrastSkin .mceMenuItem td, .highcontrastSkin .mceMenuItem th {line-height: normal} /* ColorSplitButton */ .highcontrastSkin div.mceColorSplitMenu table {background:#FFF; border:1px solid; color: #000} .highcontrastSkin .mceColorSplitMenu td {padding:2px} .highcontrastSkin .mceColorSplitMenu a {display:block; width:16px; height:16px; overflow:hidden; color:#000; margin: 0; padding: 0;} .highcontrastSkin .mceColorSplitMenu td.mceMoreColors {padding:1px 3px 1px 1px} .highcontrastSkin .mceColorSplitMenu a.mceMoreColors {width:100%; height:auto; text-align:center; font-family:Tahoma,Verdana,Arial,Helvetica; font-size:11px; line-height:20px; border:1px solid #FFF} .highcontrastSkin .mceColorSplitMenu a.mceMoreColors:hover {border:1px solid; background-color:#B6BDD2} .highcontrastSkin a.mceMoreColors:hover {border:1px solid #0A246A; color: #000;} .highcontrastSkin .mceColorPreview {display:none;} .highcontrastSkin .mce_forecolor span.mceAction, .highcontrastSkin .mce_backcolor span.mceAction {height:17px;overflow:hidden} /* Progress,Resize */ .highcontrastSkin .mceBlocker {position:absolute; left:0; top:0; z-index:1000; opacity:0.5; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=50); background:#FFF} .highcontrastSkin .mceProgress {position:absolute; left:0; top:0; z-index:1001; background:url(../default/img/progress.gif) no-repeat; width:32px; height:32px; margin:-16px 0 0 -16px} /* Rtl */ .mceRtl .mceListBox .mceText {text-align: right; padding: 0 4px 0 0} .mceRtl .mceMenuItem .mceText {text-align: right} /* Formats */ .highcontrastSkin .mce_p span.mceText {} .highcontrastSkin .mce_address span.mceText {font-style:italic} .highcontrastSkin .mce_pre span.mceText {font-family:monospace} .highcontrastSkin .mce_h1 span.mceText {font-weight:bolder; font-size: 2em} .highcontrastSkin .mce_h2 span.mceText {font-weight:bolder; font-size: 1.5em} .highcontrastSkin .mce_h3 span.mceText {font-weight:bolder; font-size: 1.17em} .highcontrastSkin .mce_h4 span.mceText {font-weight:bolder; font-size: 1em} .highcontrastSkin .mce_h5 span.mceText {font-weight:bolder; font-size: .83em} .highcontrastSkin .mce_h6 span.mceText {font-weight:bolder; font-size: .75em}
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/highcontrast/ui.css
CSS
asf20
8,780
/* Generic */ body { font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; background:#F0F0EE; color: black; padding:0; margin:8px 8px 0 8px; } html {background:#F0F0EE; color:#000;} td {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} textarea {resize:none;outline:none;} a:link, a:visited {color:black;background-color:transparent;} a:hover {color:#2B6FB6;background-color:transparent;} .nowrap {white-space: nowrap} /* Forms */ fieldset {margin:0; padding:4px; border:1px solid #919B9C; font-family:Verdana, Arial; font-size:10px;} legend {color:#2B6FB6; font-weight:bold;} label.msg {display:none;} label.invalid {color:#EE0000; display:inline;background-color:transparent;} input.invalid {border:1px solid #EE0000;background-color:transparent;} input {background:#FFF; border:1px solid #CCC;color:black;} input, select, textarea {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} input, select, textarea {border:1px solid #808080;} input.radio {border:1px none #000000; background:transparent; vertical-align:middle;} input.checkbox {border:1px none #000000; background:transparent; vertical-align:middle;} .input_noborder {border:0;} /* Buttons */ #insert, #cancel, input.button, .updateButton { font-weight:bold; width:94px; height:23px; cursor:pointer; padding-bottom:2px; float:left; } #cancel {float:right} /* Browse */ a.pickcolor, a.browse {text-decoration:none} a.browse span {display:block; width:20px; height:18px; background:url(../../img/icons.gif) -860px 0; border:1px solid #FFF; margin-left:1px;} .mceOldBoxModel a.browse span {width:22px; height:20px;} a.browse:hover span {border:1px solid #0A246A; background-color:#B2BBD0;} a.browse span.disabled {border:1px solid white; opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} a.browse:hover span.disabled {border:1px solid white; background-color:transparent;} a.pickcolor span {display:block; width:20px; height:16px; background:url(../../img/icons.gif) -840px 0; margin-left:2px;} .mceOldBoxModel a.pickcolor span {width:21px; height:17px;} a.pickcolor:hover span {background-color:#B2BBD0;} a.pickcolor:hover span.disabled {} /* Charmap */ table.charmap {border:1px solid #AAA; text-align:center} td.charmap, #charmap a {width:18px; height:18px; color:#000; border:1px solid #AAA; text-align:center; font-size:12px; vertical-align:middle; line-height: 18px;} #charmap a {display:block; color:#000; text-decoration:none; border:0} #charmap a:hover {background:#CCC;color:#2B6FB6} #charmap #codeN {font-size:10px; font-family:Arial,Helvetica,sans-serif; text-align:center} #charmap #codeV {font-size:40px; height:80px; border:1px solid #AAA; text-align:center} /* Source */ .wordWrapCode {vertical-align:middle; border:1px none #000000; background:transparent;} .mceActionPanel {margin-top:5px;} /* Tabs classes */ .tabs {width:100%; height:18px; line-height:normal;} .tabs ul {margin:0; padding:0; list-style:none;} .tabs li {float:left; border: 1px solid black; border-bottom:0; margin:0 2px 0 0; padding:0 0 0 10px; line-height:17px; height:18px; display:block; cursor:pointer;} .tabs li.current {font-weight: bold; margin-right:2px;} .tabs span {float:left; display:block; padding:0px 10px 0 0;} .tabs a {text-decoration:none; font-family:Verdana, Arial; font-size:10px;} .tabs a:link, .tabs a:visited, .tabs a:hover {color:black;} /* Panels */ .panel_wrapper div.panel {display:none;} .panel_wrapper div.current {display:block; width:100%; height:300px; overflow:visible;} .panel_wrapper {border:1px solid #919B9C; padding:10px; padding-top:5px; clear:both; background:white;} /* Columns */ .column {float:left;} .properties {width:100%;} .properties .column1 {} .properties .column2 {text-align:left;} /* Titles */ h1, h2, h3, h4 {color:#2B6FB6; margin:0; padding:0; padding-top:5px;} h3 {font-size:14px;} .title {font-size:12px; font-weight:bold; color:#2B6FB6;} /* Dialog specific */ #link .panel_wrapper, #link div.current {height:125px;} #image .panel_wrapper, #image div.current {height:200px;} #plugintable thead {font-weight:bold; background:#DDD;} #plugintable, #about #plugintable td {border:1px solid #919B9C;} #plugintable {width:96%; margin-top:10px;} #pluginscontainer {height:290px; overflow:auto;} #colorpicker #preview {display:inline-block; padding-left:40px; height:14px; border:1px solid black; margin-left:5px; margin-right: 5px} #colorpicker #previewblock {position: relative; top: -3px; padding-left:5px; padding-top: 0px; display:inline} #colorpicker #preview_wrapper { text-align:center; padding-top:4px; white-space: nowrap} #colorpicker #colors {float:left; border:1px solid gray; cursor:crosshair;} #colorpicker #light {border:1px solid gray; margin-left:5px; float:left;width:15px; height:150px; cursor:crosshair;} #colorpicker #light div {overflow:hidden;} #colorpicker .panel_wrapper div.current {height:175px;} #colorpicker #namedcolors {width:150px;} #colorpicker #namedcolors a {display:block; float:left; width:10px; height:10px; margin:1px 1px 0 0; overflow:hidden;} #colorpicker #colornamecontainer {margin-top:5px;}
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/highcontrast/dialog.css
CSS
asf20
5,113
body, td, pre { margin:8px;} body.mceForceColors {background:#FFF; color:#000;} h1 {font-size: 2em} h2 {font-size: 1.5em} h3 {font-size: 1.17em} h4 {font-size: 1em} h5 {font-size: .83em} h6 {font-size: .75em} .mceItemTable, .mceItemTable td, .mceItemTable th, .mceItemTable caption, .mceItemVisualAid {border: 1px dashed #BBB;} a.mceItemAnchor {display:inline-block; width:11px !important; height:11px !important; background:url(../default/img/items.gif) no-repeat 0 0;} span.mceItemNbsp {background: #DDD} td.mceSelected, th.mceSelected {background-color:#3399ff !important} img {border:0;} table, img, hr, .mceItemAnchor {cursor:default} table td, table th {cursor:text} ins {border-bottom:1px solid green; text-decoration: none; color:green} del {color:red; text-decoration:line-through} cite {border-bottom:1px dashed blue} acronym {border-bottom:1px dotted #CCC; cursor:help} abbr {border-bottom:1px dashed #CCC; cursor:help} img:-moz-broken {-moz-force-broken-image-icon:1; width:24px; height:24px} font[face=mceinline] {font-family:inherit !important} *[contentEditable]:focus {outline:0}
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/highcontrast/content.css
CSS
asf20
1,098
/* Generic */ body { font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; background:#f1f1f1; padding:0; margin:8px 8px 0 8px; } html {background:#f1f1f1;} td {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} textarea {resize:none;outline:none;} a:link, a:visited {color:black;} a:hover {color:#2B6FB6;} .nowrap {white-space: nowrap} /* Forms */ form {margin: 0;} fieldset {margin:0; padding:4px; border:1px solid #dfdfdf; font-family:Verdana, Arial; font-size:10px;} legend {color:#2B6FB6; font-weight:bold;} label.msg {display:none;} label.invalid {color:#EE0000; display:inline;} input.invalid {border:1px solid #EE0000;} input {background:#FFF; border:1px solid #dfdfdf;} input, select, textarea {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} input, select, textarea {border:1px solid #dfdfdf;} input.radio {border:1px none #000000; background:transparent; vertical-align:middle;} input.checkbox {border:1px none #000000; background:transparent; vertical-align:middle;} .input_noborder {border:0;} /* Buttons */ #insert, #cancel, #apply, .mceActionPanel .button, input.mceButton, .updateButton { border: 1px solid #bbb; margin:0; padding:0 0 1px; font-weight:bold; font-size: 11px; width:94px; height:24px; color:#000; cursor:pointer; -webkit-border-radius: 3px; border-radius: 3px; background-color: #eee; background-image: -webkit-gradient(linear, left bottom, left top, from(#ddd), to(#fff)); background-image: -webkit-linear-gradient(bottom, #ddd, #fff); background-image: -moz-linear-gradient(bottom, #ddd, #fff); background-image: -o-linear-gradient(bottom, #ddd, #fff); background-image: linear-gradient(to top, #ddd, #fff); } #insert:hover, #cancel:hover, input.mceButton:hover, .updateButton:hover, #insert:focus, #cancel:focus, input.mceButton:focus, .updateButton:focus { border: 1px solid #555; } .mceActionPanel #insert { float: right; } /* Browse */ a.browse span {display:block; width:20px; height:18px; background:url(../../img/icons.gif) -860px 0; border:1px solid #FFF; margin-left:1px;} .mceOldBoxModel a.browse span {width:22px; height:20px;} a.browse:hover span {border:1px solid #0A246A; background-color:#B2BBD0;} a.browse span.disabled {border:1px solid white; -moz-opacity:0.3; opacity:0.3; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30);} a.browse:hover span.disabled {border:1px solid white; background-color:transparent;} a.pickcolor span {display:block; width:20px; height:16px; background:url(../../img/icons.gif) -840px 0; margin-left:2px;} .mceOldBoxModel a.pickcolor span {width:21px; height:17px;} a.pickcolor:hover span {background-color:#B2BBD0;} a.pickcolor, a.browse {text-decoration:none} div.iframecontainer {background: #fff;} /* Charmap */ table.charmap {border:1px solid #AAA; text-align:center} td.charmap, #charmap a {width:18px; height:18px; color:#000; border:1px solid #AAA; text-align:center; font-size:12px; vertical-align:middle; line-height: 18px;} #charmap a {display:block; color:#000; text-decoration:none; border:0} #charmap a:hover {background:#CCC;color:#2B6FB6} #charmap #codeN {font-size:10px; font-family:Arial,Helvetica,sans-serif; text-align:center} #charmap #codeV {font-size:40px; height:80px; border:1px solid #AAA; text-align:center} #charmap #charmapView {background-color:#fff;} /* Source */ .wordWrapCode {vertical-align:middle; border:1px none #000000; background:transparent;} .mceActionPanel {margin-top:5px;} /* Tabs classes */ .tabs {width:100%; height:18px; line-height:normal; background:url(img/tabs.gif) repeat-x 0 -72px;} .tabs ul {margin:0; padding:0; list-style:none;} .tabs li {float:left; background:url(img/tabs.gif) no-repeat 0 0; margin:0 2px 0 0; padding:0 0 0 10px; line-height:17px; height:18px; display:block;} .tabs li.current {background:url(img/tabs.gif) no-repeat 0 -18px; margin-right:2px;} .tabs span {float:left; display:block; background:url(img/tabs.gif) no-repeat right -36px; padding:0px 10px 0 0;} .tabs .current span {background:url(img/tabs.gif) no-repeat right -54px;} .tabs a {text-decoration:none; font-family:Verdana, Arial; font-size:10px;} .tabs a:link, .tabs a:visited, .tabs a:hover {color:black;} /* Panels */ .panel_wrapper div.panel {display:none;} .panel_wrapper div.current {display:block; width:100%; height:300px; overflow:visible;} .panel_wrapper {border:1px solid #919B9C; border-top:0px; padding:10px; padding-top:5px; clear:both; background:white;} /* Columns */ .column {float:left;} .properties {width:100%;} .properties .column1 {} .properties .column2 {text-align:left;} /* Titles */ h1, h2, h3, h4 {color:#2B6FB6; margin:0; padding:0; padding-top:5px;} h3 {font-size:14px;} .title {font-size:12px; font-weight:bold; color:#2B6FB6;} /* Dialog specific */ #link .panel_wrapper, #link div.current {height:125px;} #image .panel_wrapper, #image div.current {height:200px;} #plugintable thead {font-weight:bold; background:#DDD;} #plugintable, #about #plugintable td {border:1px solid #919B9C;} #plugintable {width:96%; margin-top:10px;} #pluginscontainer {height:290px; overflow:auto;} #colorpicker #preview {display:inline-block; padding-left:40px; height:14px; border:1px solid black; margin-left:5px; margin-right: 5px} #colorpicker #previewblock {position: relative; top: -3px; padding-left:5px; padding-top: 0px; display:inline} #colorpicker #preview_wrapper {text-align:center; padding-top:4px; white-space: nowrap; float: right;} #colorpicker #insert, #colorpicker #cancel {width: 90px} #colorpicker #colors {float:left; border:1px solid gray; cursor:crosshair;} #colorpicker #light {border:1px solid gray; margin-left:5px; float:left;width:15px; height:150px; cursor:crosshair;} #colorpicker #light div {overflow:hidden;} #colorpicker .panel_wrapper div.current {height:175px;} #colorpicker #namedcolors {width:150px;} #colorpicker #namedcolors a {display:block; float:left; width:10px; height:10px; margin:1px 1px 0 0; overflow:hidden;} #colorpicker #colornamecontainer {margin-top:5px;} #colorpicker #picker_panel fieldset {margin:auto;width:325px;}
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/dialog.css
CSS
asf20
6,090
body.mceForceColors {background:#FFF; color:#000;} body.mceBrowserDefaults {background:transparent; color:inherit; font-size:inherit; font-family:inherit;} td {color:#000; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; margin:8px;} h1 {font-size: 2em} h2 {font-size: 1.5em} h3 {font-size: 1.17em} h4 {font-size: 1em} h5 {font-size: .83em} h6 {font-size: .75em} .mceItemTable, .mceItemTable td, .mceItemTable th, .mceItemTable caption, .mceItemVisualAid {border: 1px dashed #BBB;} a.mceItemAnchor {display:inline-block; -webkit-user-select:all; -webkit-user-modify:read-only; -moz-user-select:all; -moz-user-modify:read-only; width:11px !important; height:11px !important; background:url(../default/img/items.gif) no-repeat center center} span.mceItemNbsp {background: #DDD} td.mceSelected, th.mceSelected {background-color:#3399ff !important} img {border:0;} table, img, hr, .mceItemAnchor {cursor:default} table td, table th {cursor:text} ins {border-bottom:1px solid green; text-decoration: none; color:green} del {color:red; text-decoration:line-through} cite {border-bottom:1px dashed blue} acronym {border-bottom:1px dotted #CCC; cursor:help} abbr {border-bottom:1px dashed #CCC; cursor:help} img:-moz-broken {-moz-force-broken-image-icon:1; width:24px; height:24px} font[face=mceinline] {font-family:inherit !important} *[contentEditable]:focus {outline:0} .mceItemMedia {border:1px dotted #cc0000; background-position:center; background-repeat:no-repeat; background-color:#ffffcc} .mceItemShockWave {background-image:url(../../img/shockwave.gif)} .mceItemFlash {background-image:url(../../img/flash.gif)} .mceItemQuickTime {background-image:url(../../img/quicktime.gif)} .mceItemWindowsMedia {background-image:url(../../img/windowsmedia.gif)} .mceItemRealMedia {background-image:url(../../img/realmedia.gif)} .mceItemVideo {background-image:url(../../img/video.gif)} .mceItemAudio {background-image:url(../../img/video.gif)} .mceItemIframe {background-image:url(../../img/iframe.gif)} .mcePageBreak {display:block;border:0;width:100%;height:12px;border-top:1px dotted #ccc;margin-top:15px;background:#fff url(../../img/pagebreak.gif) no-repeat center top;} /* WordPress styles */ body { font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif; font-size: 13px; line-height: 19px; color: #333; margin: 10px; } br[data-mce-bogus] { line-height: 1em; margin-top: -1em; } br[data-mce-bogus]:only-child { line-height: inherit; margin-top: inherit; } .aligncenter, dl.aligncenter { display: block; margin-left: auto; margin-right: auto; } .alignleft { float: left; } .alignright { float: right; } .wp-caption { border: 1px solid #ddd; text-align: center; background-color: #f3f3f3; padding-top: 4px; margin: 10px 0; -webkit-border-radius: 3px; border-radius: 3px; } .mceIEcenter { text-align: center; } .wp-caption img { margin: 0; padding: 0; border: 0 none; -webkit-user-drag: none; } .wp-caption-dd { font-size: 11px; line-height: 17px; padding: 0 4px 5px; margin: 0; } pre { font: 12px/18px Consolas, Monaco, monospace; } td { color: #000; font-size: 11px; margin: 8px; } /* Styles for the WordPress plugins */ img.mceWPnextpage, img.mceWPmore { border: 0; border-top: 1px dotted #cccccc; display: block; width: 95%; height: 12px; margin: 15px auto 0; } img.mceWPmore { background: transparent url("img/more_bug.gif") no-repeat right top; } img.mceWPnextpage { background: transparent url("img/page_bug.gif") no-repeat right top; } img.wpGallery { border: 1px dashed #888; background: #f2f8ff url("img/gallery.png") no-repeat scroll center center; width: 99%; height: 250px; } img.wp-oembed { border: 1px dashed #888; background: #f7f5f2 url("img/embedded.png") no-repeat scroll center center; width: 300px; height: 250px; }
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/wp_theme/content.css
CSS
asf20
3,842
/* Reset */ .defaultSkin table, .defaultSkin tbody, .defaultSkin a, .defaultSkin img, .defaultSkin tr, .defaultSkin div, .defaultSkin td, .defaultSkin iframe, .defaultSkin span, .defaultSkin *, .defaultSkin .mceText {border:0; margin:0; padding:0; background:transparent; white-space:nowrap; text-decoration:none; font-weight:normal; cursor:default; color:#000; vertical-align:baseline; width:auto; border-collapse:separate; text-align:left} .defaultSkin a:hover, .defaultSkin a:link, .defaultSkin a:visited, .defaultSkin a:active {text-decoration:none; font-weight:normal; cursor:default; color:#000} .defaultSkin table td {vertical-align:middle} /* Containers */ .defaultSkin table {direction:ltr;background:transparent} .defaultSkin iframe {display:block;} .defaultSkin .mceToolbar {height:26px} .defaultSkin .mceLeft {text-align:left} .defaultSkin .mceRight {text-align:right} /* External */ .defaultSkin .mceExternalToolbar {position:absolute; border:1px solid #CCC; border-bottom:0; display:none;} .defaultSkin .mceExternalToolbar td.mceToolbar {padding-right:13px;} .defaultSkin .mceExternalClose {position:absolute; top:3px; right:3px; width:7px; height:7px; background:url(../../img/icons.gif) -820px 0} /* Layout */ .defaultSkin table.mceLayout {border:0; border-left:1px solid #CCC; border-right:1px solid #CCC} .defaultSkin table.mceLayout tr.mceFirst td {border-top:1px solid #CCC} .defaultSkin table.mceLayout tr.mceLast td {border-bottom:1px solid #CCC} .defaultSkin table.mceToolbar, .defaultSkin tr.mceFirst .mceToolbar tr td, .defaultSkin tr.mceLast .mceToolbar tr td {border:0; margin:0; padding:0;} .defaultSkin td.mceToolbar {background:#F0F0EE; padding-top:1px; vertical-align:top} .defaultSkin .mceIframeContainer {border-top:1px solid #CCC; border-bottom:1px solid #CCC} .defaultSkin .mceStatusbar {background:#F0F0EE; font-family:'MS Sans Serif',sans-serif,Verdana,Arial; font-size:9pt; line-height:16px; overflow:visible; color:#000; display:block; height:20px} .defaultSkin .mceStatusbar div {float:left; margin:2px} .defaultSkin .mceStatusbar a.mceResize {display:block; float:right; background:url(../../img/icons.gif) -800px 0; width:20px; height:20px; cursor:se-resize; outline:0} .defaultSkin .mceStatusbar a:hover {text-decoration:underline} .defaultSkin table.mceToolbar {margin-left:3px} .defaultSkin span.mceIcon, .defaultSkin img.mceIcon {display:block; width:20px; height:20px} .defaultSkin .mceIcon {background:url(../../img/icons.gif) no-repeat 20px 20px} .defaultSkin td.mceCenter {text-align:center;} .defaultSkin td.mceCenter table {margin:0 auto; text-align:left;} .defaultSkin td.mceRight table {margin:0 0 0 auto;} /* Button */ .defaultSkin .mceButton {display:block; border:1px solid #F0F0EE; width:20px; height:20px; margin-right:1px} .defaultSkin a.mceButtonEnabled:hover {border:1px solid #0A246A; background-color:#B2BBD0} .defaultSkin a.mceButtonActive, .defaultSkin a.mceButtonSelected {border:1px solid #0A246A; background-color:#C2CBE0} .defaultSkin .mceButtonDisabled .mceIcon {opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} .defaultSkin .mceButtonLabeled {width:auto} .defaultSkin .mceButtonLabeled span.mceIcon {float:left} .defaultSkin span.mceButtonLabel {display:block; font-size:10px; padding:4px 6px 0 22px; font-family:Tahoma,Verdana,Arial,Helvetica} .defaultSkin .mceButtonDisabled .mceButtonLabel {color:#888} /* Separator */ .defaultSkin .mceSeparator {display:block; background:url(../../img/icons.gif) -180px 0; width:2px; height:20px; margin:2px 2px 0 4px} /* ListBox */ .defaultSkin .mceListBox, .defaultSkin .mceListBox a {display:block} .defaultSkin .mceListBox .mceText {padding-left:4px; width:70px; text-align:left; border:1px solid #CCC; border-right:0; background:#FFF; font-family:Tahoma,Verdana,Arial,Helvetica; font-size:11px; height:20px; line-height:20px; overflow:hidden} .defaultSkin .mceListBox .mceOpen {width:9px; height:20px; background:url(../../img/icons.gif) -741px 0; margin-right:2px; border:1px solid #CCC;} .defaultSkin table.mceListBoxEnabled:hover .mceText, .defaultSkin .mceListBoxHover .mceText, .defaultSkin .mceListBoxSelected .mceText {border:1px solid #A2ABC0; border-right:0; background:#FFF} .defaultSkin table.mceListBoxEnabled:hover .mceOpen, .defaultSkin .mceListBoxHover .mceOpen, .defaultSkin .mceListBoxSelected .mceOpen {background-color:#FFF; border:1px solid #A2ABC0} .defaultSkin .mceListBoxDisabled a.mceText {color:gray; background-color:transparent;} .defaultSkin .mceListBoxMenu {overflow:auto; overflow-x:hidden} .defaultSkin .mceOldBoxModel .mceListBox .mceText {height:22px} .defaultSkin .mceOldBoxModel .mceListBox .mceOpen {width:11px; height:22px;} .defaultSkin select.mceNativeListBox {font-family:'MS Sans Serif',sans-serif,Verdana,Arial; font-size:7pt; background:#F0F0EE; border:1px solid gray; margin-right:2px;} /* SplitButton */ .defaultSkin .mceSplitButton {width:32px; height:20px; direction:ltr} .defaultSkin .mceSplitButton a, .defaultSkin .mceSplitButton span {height:20px; display:block} .defaultSkin .mceSplitButton a.mceAction {width:20px; border:1px solid #F0F0EE; border-right:0;} .defaultSkin .mceSplitButton span.mceAction {width:20px; background-image:url(../../img/icons.gif);} .defaultSkin .mceSplitButton a.mceOpen {width:9px; background:url(../../img/icons.gif) -741px 0; border:1px solid #F0F0EE;} .defaultSkin .mceSplitButton span.mceOpen {display:none} .defaultSkin table.mceSplitButtonEnabled:hover a.mceAction, .defaultSkin .mceSplitButtonHover a.mceAction, .defaultSkin .mceSplitButtonSelected a.mceAction {border:1px solid #0A246A; border-right:0; background-color:#B2BBD0} .defaultSkin table.mceSplitButtonEnabled:hover a.mceOpen, .defaultSkin .mceSplitButtonHover a.mceOpen, .defaultSkin .mceSplitButtonSelected a.mceOpen {background-color:#B2BBD0; border:1px solid #0A246A;} .defaultSkin .mceSplitButtonDisabled .mceAction, .defaultSkin .mceSplitButtonDisabled a.mceOpen {opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} .defaultSkin .mceSplitButtonActive a.mceAction {border:1px solid #0A246A; background-color:#C2CBE0} .defaultSkin .mceSplitButtonActive a.mceOpen {border-left:0;} /* ColorSplitButton */ .defaultSkin div.mceColorSplitMenu table {background:#FFF; border:1px solid gray} .defaultSkin .mceColorSplitMenu td {padding:2px} .defaultSkin .mceColorSplitMenu a {display:block; width:9px; height:9px; overflow:hidden; border:1px solid #808080} .defaultSkin .mceColorSplitMenu td.mceMoreColors {padding:1px 3px 1px 1px} .defaultSkin .mceColorSplitMenu a.mceMoreColors {width:100%; height:auto; text-align:center; font-family:Tahoma,Verdana,Arial,Helvetica; font-size:11px; line-height:20px; border:1px solid #FFF} .defaultSkin .mceColorSplitMenu a.mceMoreColors:hover {border:1px solid #0A246A; background-color:#B6BDD2} .defaultSkin a.mceMoreColors:hover {border:1px solid #0A246A} .defaultSkin .mceColorPreview {margin-left:2px; width:16px; height:4px; overflow:hidden; background:#9a9b9a} .defaultSkin .mce_forecolor span.mceAction, .defaultSkin .mce_backcolor span.mceAction {overflow:hidden; height:16px} /* Menu */ .defaultSkin .mceMenu {position:absolute; left:0; top:0; z-index:1000; border:1px solid #D4D0C8; direction:ltr} .defaultSkin .mceNoIcons span.mceIcon {width:0;} .defaultSkin .mceNoIcons a .mceText {padding-left:10px} .defaultSkin .mceMenu table {background:#FFF} .defaultSkin .mceMenu a, .defaultSkin .mceMenu span, .defaultSkin .mceMenu {display:block} .defaultSkin .mceMenu td {height:20px} .defaultSkin .mceMenu a {position:relative;padding:3px 0 4px 0} .defaultSkin .mceMenu .mceText {position:relative; display:block; font-family:Tahoma,Verdana,Arial,Helvetica; color:#000; cursor:default; margin:0; padding:0 25px 0 25px; display:block} .defaultSkin .mceMenu span.mceText, .defaultSkin .mceMenu .mcePreview {font-size:11px} .defaultSkin .mceMenu pre.mceText {font-family:Monospace} .defaultSkin .mceMenu .mceIcon {position:absolute; top:0; left:0; width:22px;} .defaultSkin .mceMenu .mceMenuItemEnabled a:hover, .defaultSkin .mceMenu .mceMenuItemActive {background-color:#dbecf3} .defaultSkin td.mceMenuItemSeparator {background:#DDD; height:1px} .defaultSkin .mceMenuItemTitle a {border:0; background:#EEE; border-bottom:1px solid #DDD} .defaultSkin .mceMenuItemTitle span.mceText {color:#000; font-weight:bold; padding-left:4px} .defaultSkin .mceMenuItemDisabled .mceText {color:#888} .defaultSkin .mceMenuItemSelected .mceIcon {background:url(img/menu_check.gif)} .defaultSkin .mceNoIcons .mceMenuItemSelected a {background:url(img/menu_arrow.gif) no-repeat -6px center} .defaultSkin .mceMenu span.mceMenuLine {display:none} .defaultSkin .mceMenuItemSub a {background:url(img/menu_arrow.gif) no-repeat top right;} .defaultSkin .mceMenuItem td, .defaultSkin .mceMenuItem th {line-height: normal} /* Progress,Resize */ .defaultSkin .mceBlocker {position:absolute; left:0; top:0; z-index:1000; opacity:0.5; -ms-filter:'alpha(opacity=50)'; filter:alpha(opacity=50); background:#FFF} .defaultSkin .mceProgress {position:absolute; left:0; top:0; z-index:1001; background:url(img/progress.gif) no-repeat; width:32px; height:32px; margin:-16px 0 0 -16px} /* Rtl */ .mceRtl .mceListBox .mceText {text-align: right; padding: 0 4px 0 0} .mceRtl .mceMenuItem .mceText {text-align: right} /* Formats */ .defaultSkin .mce_formatPreview a {font-size:10px} .defaultSkin .mce_p span.mceText {} .defaultSkin .mce_address span.mceText {font-style:italic} .defaultSkin .mce_pre span.mceText {font-family:monospace} .defaultSkin .mce_h1 span.mceText {font-weight:bolder; font-size: 2em} .defaultSkin .mce_h2 span.mceText {font-weight:bolder; font-size: 1.5em} .defaultSkin .mce_h3 span.mceText {font-weight:bolder; font-size: 1.17em} .defaultSkin .mce_h4 span.mceText {font-weight:bolder; font-size: 1em} .defaultSkin .mce_h5 span.mceText {font-weight:bolder; font-size: .83em} .defaultSkin .mce_h6 span.mceText {font-weight:bolder; font-size: .75em} /* Theme */ .defaultSkin span.mce_bold {background-position:0 0} .defaultSkin span.mce_italic {background-position:-60px 0} .defaultSkin span.mce_underline {background-position:-140px 0} .defaultSkin span.mce_strikethrough {background-position:-120px 0} .defaultSkin span.mce_undo {background-position:-160px 0} .defaultSkin span.mce_redo {background-position:-100px 0} .defaultSkin span.mce_cleanup {background-position:-40px 0} .defaultSkin span.mce_bullist {background-position:-20px 0} .defaultSkin span.mce_numlist {background-position:-80px 0} .defaultSkin span.mce_justifyleft {background-position:-460px 0} .defaultSkin span.mce_justifyright {background-position:-480px 0} .defaultSkin span.mce_justifycenter {background-position:-420px 0} .defaultSkin span.mce_justifyfull {background-position:-440px 0} .defaultSkin span.mce_anchor {background-position:-200px 0} .defaultSkin span.mce_indent {background-position:-400px 0} .defaultSkin span.mce_outdent {background-position:-540px 0} .defaultSkin span.mce_link {background-position:-500px 0} .defaultSkin span.mce_unlink {background-position:-640px 0} .defaultSkin span.mce_sub {background-position:-600px 0} .defaultSkin span.mce_sup {background-position:-620px 0} .defaultSkin span.mce_removeformat {background-position:-580px 0} .defaultSkin span.mce_newdocument {background-position:-520px 0} .defaultSkin span.mce_image {background-position:-380px 0} .defaultSkin span.mce_help {background-position:-340px 0} .defaultSkin span.mce_code {background-position:-260px 0} .defaultSkin span.mce_hr {background-position:-360px 0} .defaultSkin span.mce_visualaid {background-position:-660px 0} .defaultSkin span.mce_charmap {background-position:-240px 0} .defaultSkin span.mce_paste {background-position:-560px 0} .defaultSkin span.mce_copy {background-position:-700px 0} .defaultSkin span.mce_cut {background-position:-680px 0} .defaultSkin span.mce_blockquote {background-position:-220px 0} .defaultSkin .mce_forecolor span.mceAction {background-position:-720px 0} .defaultSkin .mce_backcolor span.mceAction {background-position:-760px 0} .defaultSkin span.mce_forecolorpicker {background-position:-720px 0} .defaultSkin span.mce_backcolorpicker {background-position:-760px 0} /* Plugins */ .defaultSkin span.mce_advhr {background-position:-0px -20px} .defaultSkin span.mce_ltr {background-position:-20px -20px} .defaultSkin span.mce_rtl {background-position:-40px -20px} .defaultSkin span.mce_emotions {background-position:-60px -20px} .defaultSkin span.mce_fullpage {background-position:-80px -20px} .defaultSkin span.mce_fullscreen {background-position:-100px -20px} .defaultSkin span.mce_iespell {background-position:-120px -20px} .defaultSkin span.mce_insertdate {background-position:-140px -20px} .defaultSkin span.mce_inserttime {background-position:-160px -20px} .defaultSkin span.mce_absolute {background-position:-180px -20px} .defaultSkin span.mce_backward {background-position:-200px -20px} .defaultSkin span.mce_forward {background-position:-220px -20px} .defaultSkin span.mce_insert_layer {background-position:-240px -20px} .defaultSkin span.mce_insertlayer {background-position:-260px -20px} .defaultSkin span.mce_movebackward {background-position:-280px -20px} .defaultSkin span.mce_moveforward {background-position:-300px -20px} .defaultSkin span.mce_media {background-position:-320px -20px} .defaultSkin span.mce_nonbreaking {background-position:-340px -20px} .defaultSkin span.mce_pastetext {background-position:-360px -20px} .defaultSkin span.mce_pasteword {background-position:-380px -20px} .defaultSkin span.mce_selectall {background-position:-400px -20px} .defaultSkin span.mce_preview {background-position:-420px -20px} .defaultSkin span.mce_print {background-position:-440px -20px} .defaultSkin span.mce_cancel {background-position:-460px -20px} .defaultSkin span.mce_save {background-position:-480px -20px} .defaultSkin span.mce_replace {background-position:-500px -20px} .defaultSkin span.mce_search {background-position:-520px -20px} .defaultSkin span.mce_styleprops {background-position:-560px -20px} .defaultSkin span.mce_table {background-position:-580px -20px} .defaultSkin span.mce_cell_props {background-position:-600px -20px} .defaultSkin span.mce_delete_table {background-position:-620px -20px} .defaultSkin span.mce_delete_col {background-position:-640px -20px} .defaultSkin span.mce_delete_row {background-position:-660px -20px} .defaultSkin span.mce_col_after {background-position:-680px -20px} .defaultSkin span.mce_col_before {background-position:-700px -20px} .defaultSkin span.mce_row_after {background-position:-720px -20px} .defaultSkin span.mce_row_before {background-position:-740px -20px} .defaultSkin span.mce_merge_cells {background-position:-760px -20px} .defaultSkin span.mce_table_props {background-position:-980px -20px} .defaultSkin span.mce_row_props {background-position:-780px -20px} .defaultSkin span.mce_split_cells {background-position:-800px -20px} .defaultSkin span.mce_template {background-position:-820px -20px} .defaultSkin span.mce_visualchars {background-position:-840px -20px} .defaultSkin span.mce_abbr {background-position:-860px -20px} .defaultSkin span.mce_acronym {background-position:-880px -20px} .defaultSkin span.mce_attribs {background-position:-900px -20px} .defaultSkin span.mce_cite {background-position:-920px -20px} .defaultSkin span.mce_del {background-position:-940px -20px} .defaultSkin span.mce_ins {background-position:-960px -20px} .defaultSkin span.mce_pagebreak {background-position:0 -40px} .defaultSkin span.mce_restoredraft {background-position:-20px -40px} .defaultSkin span.mce_spellchecker {background-position:-540px -20px} .defaultSkin span.mce_visualblocks {background-position: -40px -40px}
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/default/ui.css
CSS
asf20
15,740
/* Generic */ body { font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; scrollbar-3dlight-color:#F0F0EE; scrollbar-arrow-color:#676662; scrollbar-base-color:#F0F0EE; scrollbar-darkshadow-color:#DDDDDD; scrollbar-face-color:#E0E0DD; scrollbar-highlight-color:#F0F0EE; scrollbar-shadow-color:#F0F0EE; scrollbar-track-color:#F5F5F5; background:#F0F0EE; padding:0; margin:8px 8px 0 8px; } html {background:#F0F0EE;} td {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} textarea {resize:none;outline:none;} a:link, a:visited {color:black;} a:hover {color:#2B6FB6;} .nowrap {white-space: nowrap} /* Forms */ fieldset {margin:0; padding:4px; border:1px solid #919B9C; font-family:Verdana, Arial; font-size:10px;} legend {color:#2B6FB6; font-weight:bold;} label.msg {display:none;} label.invalid {color:#EE0000; display:inline;} input.invalid {border:1px solid #EE0000;} input {background:#FFF; border:1px solid #CCC;} input, select, textarea {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} input, select, textarea {border:1px solid #808080;} input.radio {border:1px none #000000; background:transparent; vertical-align:middle;} input.checkbox {border:1px none #000000; background:transparent; vertical-align:middle;} .input_noborder {border:0;} /* Buttons */ #insert, #cancel, input.button, .updateButton { border:0; margin:0; padding:0; font-weight:bold; width:94px; height:26px; background:url(img/buttons.png) 0 -26px; cursor:pointer; padding-bottom:2px; float:left; } #insert {background:url(img/buttons.png) 0 -52px} #cancel {background:url(img/buttons.png) 0 0; float:right} /* Browse */ a.pickcolor, a.browse {text-decoration:none} a.browse span {display:block; width:20px; height:18px; background:url(../../img/icons.gif) -860px 0; border:1px solid #FFF; margin-left:1px;} .mceOldBoxModel a.browse span {width:22px; height:20px;} a.browse:hover span {border:1px solid #0A246A; background-color:#B2BBD0;} a.browse span.disabled {border:1px solid white; opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} a.browse:hover span.disabled {border:1px solid white; background-color:transparent;} a.pickcolor span {display:block; width:20px; height:16px; background:url(../../img/icons.gif) -840px 0; margin-left:2px;} .mceOldBoxModel a.pickcolor span {width:21px; height:17px;} a.pickcolor:hover span {background-color:#B2BBD0;} a.pickcolor:hover span.disabled {} /* Charmap */ table.charmap {border:1px solid #AAA; text-align:center} td.charmap, #charmap a {width:18px; height:18px; color:#000; border:1px solid #AAA; text-align:center; font-size:12px; vertical-align:middle; line-height: 18px;} #charmap a {display:block; color:#000; text-decoration:none; border:0} #charmap a:hover {background:#CCC;color:#2B6FB6} #charmap #codeN {font-size:10px; font-family:Arial,Helvetica,sans-serif; text-align:center} #charmap #codeV {font-size:40px; height:80px; border:1px solid #AAA; text-align:center} /* Source */ .wordWrapCode {vertical-align:middle; border:1px none #000000; background:transparent;} .mceActionPanel {margin-top:5px;} /* Tabs classes */ .tabs {width:100%; height:18px; line-height:normal; background:url(img/tabs.gif) repeat-x 0 -72px;} .tabs ul {margin:0; padding:0; list-style:none;} .tabs li {float:left; background:url(img/tabs.gif) no-repeat 0 0; margin:0 2px 0 0; padding:0 0 0 10px; line-height:17px; height:18px; display:block;} .tabs li.current {background:url(img/tabs.gif) no-repeat 0 -18px; margin-right:2px;} .tabs span {float:left; display:block; background:url(img/tabs.gif) no-repeat right -36px; padding:0px 10px 0 0;} .tabs .current span {background:url(img/tabs.gif) no-repeat right -54px;} .tabs a {text-decoration:none; font-family:Verdana, Arial; font-size:10px;} .tabs a:link, .tabs a:visited, .tabs a:hover {color:black;} /* Panels */ .panel_wrapper div.panel {display:none;} .panel_wrapper div.current {display:block; width:100%; height:300px; overflow:visible;} .panel_wrapper {border:1px solid #919B9C; border-top:0px; padding:10px; padding-top:5px; clear:both; background:white;} /* Columns */ .column {float:left;} .properties {width:100%;} .properties .column1 {} .properties .column2 {text-align:left;} /* Titles */ h1, h2, h3, h4 {color:#2B6FB6; margin:0; padding:0; padding-top:5px;} h3 {font-size:14px;} .title {font-size:12px; font-weight:bold; color:#2B6FB6;} /* Dialog specific */ #link .panel_wrapper, #link div.current {height:125px;} #image .panel_wrapper, #image div.current {height:200px;} #plugintable thead {font-weight:bold; background:#DDD;} #plugintable, #about #plugintable td {border:1px solid #919B9C;} #plugintable {width:96%; margin-top:10px;} #pluginscontainer {height:290px; overflow:auto;} #colorpicker #preview {display:inline-block; padding-left:40px; height:14px; border:1px solid black; margin-left:5px; margin-right: 5px} #colorpicker #previewblock {position: relative; top: -3px; padding-left:5px; padding-top: 0px; display:inline} #colorpicker #preview_wrapper { text-align:center; padding-top:4px; white-space: nowrap} #colorpicker #colors {float:left; border:1px solid gray; cursor:crosshair;} #colorpicker #light {border:1px solid gray; margin-left:5px; float:left;width:15px; height:150px; cursor:crosshair;} #colorpicker #light div {overflow:hidden;} #colorpicker .panel_wrapper div.current {height:175px;} #colorpicker #namedcolors {width:150px;} #colorpicker #namedcolors a {display:block; float:left; width:10px; height:10px; margin:1px 1px 0 0; overflow:hidden;} #colorpicker #colornamecontainer {margin-top:5px;} #colorpicker #picker_panel fieldset {margin:auto;width:325px;}
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/default/dialog.css
CSS
asf20
5,643
body, td, pre {color:#000; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; margin:8px;} body {background:#FFF;} body.mceForceColors {background:#FFF; color:#000;} body.mceBrowserDefaults {background:transparent; color:inherit; font-size:inherit; font-family:inherit;} h1 {font-size: 2em} h2 {font-size: 1.5em} h3 {font-size: 1.17em} h4 {font-size: 1em} h5 {font-size: .83em} h6 {font-size: .75em} .mceItemTable, .mceItemTable td, .mceItemTable th, .mceItemTable caption, .mceItemVisualAid {border: 1px dashed #BBB;} a.mceItemAnchor {display:inline-block; -webkit-user-select:all; -webkit-user-modify:read-only; -moz-user-select:all; -moz-user-modify:read-only; width:11px !important; height:11px !important; background:url(img/items.gif) no-repeat center center} span.mceItemNbsp {background: #DDD} td.mceSelected, th.mceSelected {background-color:#3399ff !important} img {border:0;} table, img, hr, .mceItemAnchor {cursor:default} table td, table th {cursor:text} ins {border-bottom:1px solid green; text-decoration: none; color:green} del {color:red; text-decoration:line-through} cite {border-bottom:1px dashed blue} acronym {border-bottom:1px dotted #CCC; cursor:help} abbr {border-bottom:1px dashed #CCC; cursor:help} /* IE */ * html body { scrollbar-3dlight-color:#F0F0EE; scrollbar-arrow-color:#676662; scrollbar-base-color:#F0F0EE; scrollbar-darkshadow-color:#DDD; scrollbar-face-color:#E0E0DD; scrollbar-highlight-color:#F0F0EE; scrollbar-shadow-color:#F0F0EE; scrollbar-track-color:#F5F5F5; } img:-moz-broken {-moz-force-broken-image-icon:1; width:24px; height:24px} font[face=mceinline] {font-family:inherit !important} *[contentEditable]:focus {outline:0} .mceItemMedia {border:1px dotted #cc0000; background-position:center; background-repeat:no-repeat; background-color:#ffffcc} .mceItemShockWave {background-image:url(../../img/shockwave.gif)} .mceItemFlash {background-image:url(../../img/flash.gif)} .mceItemQuickTime {background-image:url(../../img/quicktime.gif)} .mceItemWindowsMedia {background-image:url(../../img/windowsmedia.gif)} .mceItemRealMedia {background-image:url(../../img/realmedia.gif)} .mceItemVideo {background-image:url(../../img/video.gif)} .mceItemAudio {background-image:url(../../img/video.gif)} .mceItemEmbeddedAudio {background-image:url(../../img/video.gif)} .mceItemIframe {background-image:url(../../img/iframe.gif)} .mcePageBreak {display:block;border:0;width:100%;height:12px;border-top:1px dotted #ccc;margin-top:15px;background:#fff url(../../img/pagebreak.gif) no-repeat center top;}
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/default/content.css
CSS
asf20
2,557
/* Reset */ .o2k7Skin table, .o2k7Skin tbody, .o2k7Skin a, .o2k7Skin img, .o2k7Skin tr, .o2k7Skin div, .o2k7Skin td, .o2k7Skin iframe, .o2k7Skin span, .o2k7Skin *, .o2k7Skin .mceText {border:0; margin:0; padding:0; background:transparent; white-space:nowrap; text-decoration:none; font-weight:normal; cursor:default; color:#000; vertical-align:baseline; width:auto; border-collapse:separate; text-align:left} .o2k7Skin a:hover, .o2k7Skin a:link, .o2k7Skin a:visited, .o2k7Skin a:active {text-decoration:none; font-weight:normal; cursor:default; color:#000} .o2k7Skin table td {vertical-align:middle} /* Containers */ .o2k7Skin table {background:transparent} .o2k7Skin iframe {display:block;} .o2k7Skin .mceToolbar {height:26px} /* External */ .o2k7Skin .mceExternalToolbar {position:absolute; border:1px solid #ABC6DD; border-bottom:0; display:none} .o2k7Skin .mceExternalToolbar td.mceToolbar {padding-right:13px;} .o2k7Skin .mceExternalClose {position:absolute; top:3px; right:3px; width:7px; height:7px; background:url(../../img/icons.gif) -820px 0} /* Layout */ .o2k7Skin table.mceLayout {border:0; border-left:1px solid #ABC6DD; border-right:1px solid #ABC6DD} .o2k7Skin table.mceLayout tr.mceFirst td {border-top:1px solid #ABC6DD} .o2k7Skin table.mceLayout tr.mceLast td {border-bottom:1px solid #ABC6DD} .o2k7Skin table.mceToolbar, .o2k7Skin tr.mceFirst .mceToolbar tr td, .o2k7Skin tr.mceLast .mceToolbar tr td {border:0; margin:0; padding:0} .o2k7Skin .mceIframeContainer {border-top:1px solid #ABC6DD; border-bottom:1px solid #ABC6DD} .o2k7Skin td.mceToolbar{background:#E5EFFD} .o2k7Skin .mceStatusbar {background:#E5EFFD; display:block; font-family:'MS Sans Serif',sans-serif,Verdana,Arial; font-size:9pt; line-height:16px; overflow:visible; color:#000; height:20px} .o2k7Skin .mceStatusbar div {float:left; padding:2px} .o2k7Skin .mceStatusbar a.mceResize {display:block; float:right; background:url(../../img/icons.gif) -800px 0; width:20px; height:20px; cursor:se-resize; outline:0} .o2k7Skin .mceStatusbar a:hover {text-decoration:underline} .o2k7Skin table.mceToolbar {margin-left:3px} .o2k7Skin .mceToolbar .mceToolbarStart span {display:block; background:url(img/button_bg.png) -22px 0; width:1px; height:22px; margin-left:3px;} .o2k7Skin .mceToolbar td.mceFirst span {margin:0} .o2k7Skin .mceToolbar .mceToolbarEnd span {display:block; background:url(img/button_bg.png) -22px 0; width:1px; height:22px} .o2k7Skin .mceToolbar .mceToolbarEndListBox span, .o2k7Skin .mceToolbar .mceToolbarStartListBox span {display:none} .o2k7Skin span.mceIcon, .o2k7Skin img.mceIcon {display:block; width:20px; height:20px} .o2k7Skin .mceIcon {background:url(../../img/icons.gif) no-repeat 20px 20px} .o2k7Skin td.mceCenter {text-align:center;} .o2k7Skin td.mceCenter table {margin:0 auto; text-align:left;} .o2k7Skin td.mceRight table {margin:0 0 0 auto;} /* Button */ .o2k7Skin .mceButton {display:block; background:url(img/button_bg.png); width:22px; height:22px} .o2k7Skin a.mceButton span, .o2k7Skin a.mceButton img {margin-left:1px} .o2k7Skin .mceOldBoxModel a.mceButton span, .o2k7Skin .mceOldBoxModel a.mceButton img {margin:0 0 0 1px} .o2k7Skin a.mceButtonEnabled:hover {background-color:#B2BBD0; background-position:0 -22px} .o2k7Skin a.mceButtonActive, .o2k7Skin a.mceButtonSelected {background-position:0 -44px} .o2k7Skin .mceButtonDisabled .mceIcon {opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} .o2k7Skin .mceButtonLabeled {width:auto} .o2k7Skin .mceButtonLabeled span.mceIcon {float:left} .o2k7Skin span.mceButtonLabel {display:block; font-size:10px; padding:4px 6px 0 22px; font-family:Tahoma,Verdana,Arial,Helvetica} .o2k7Skin .mceButtonDisabled .mceButtonLabel {color:#888} /* Separator */ .o2k7Skin .mceSeparator {display:block; background:url(img/button_bg.png) -22px 0; width:5px; height:22px} /* ListBox */ .o2k7Skin .mceListBox {padding-left: 3px} .o2k7Skin .mceListBox, .o2k7Skin .mceListBox a {display:block} .o2k7Skin .mceListBox .mceText {padding-left:4px; text-align:left; width:70px; border:1px solid #b3c7e1; border-right:0; background:#eaf2fb; font-family:Tahoma,Verdana,Arial,Helvetica; font-size:11px; height:20px; line-height:20px; overflow:hidden} .o2k7Skin .mceListBox .mceOpen {width:14px; height:22px; background:url(img/button_bg.png) -66px 0} .o2k7Skin table.mceListBoxEnabled:hover .mceText, .o2k7Skin .mceListBoxHover .mceText, .o2k7Skin .mceListBoxSelected .mceText {background:#FFF} .o2k7Skin table.mceListBoxEnabled:hover .mceOpen, .o2k7Skin .mceListBoxHover .mceOpen, .o2k7Skin .mceListBoxSelected .mceOpen {background-position:-66px -22px} .o2k7Skin .mceListBoxDisabled .mceText {color:gray} .o2k7Skin .mceListBoxMenu {overflow:auto; overflow-x:hidden; margin-left:3px} .o2k7Skin .mceOldBoxModel .mceListBox .mceText {height:22px} .o2k7Skin select.mceListBox {font-family:Tahoma,Verdana,Arial,Helvetica; font-size:12px; border:1px solid #b3c7e1; background:#FFF;} /* SplitButton */ .o2k7Skin .mceSplitButton, .o2k7Skin .mceSplitButton a, .o2k7Skin .mceSplitButton span {display:block; height:22px; direction:ltr} .o2k7Skin .mceSplitButton {background:url(img/button_bg.png)} .o2k7Skin .mceSplitButton a.mceAction {width:22px} .o2k7Skin .mceSplitButton span.mceAction {width:22px; background-image:url(../../img/icons.gif)} .o2k7Skin .mceSplitButton a.mceOpen {width:10px; background:url(img/button_bg.png) -44px 0} .o2k7Skin .mceSplitButton span.mceOpen {display:none} .o2k7Skin table.mceSplitButtonEnabled:hover a.mceAction, .o2k7Skin .mceSplitButtonHover a.mceAction, .o2k7Skin .mceSplitButtonSelected {background:url(img/button_bg.png) 0 -22px} .o2k7Skin table.mceSplitButtonEnabled:hover a.mceOpen, .o2k7Skin .mceSplitButtonHover a.mceOpen, .o2k7Skin .mceSplitButtonSelected a.mceOpen {background-position:-44px -44px} .o2k7Skin .mceSplitButtonDisabled .mceAction {opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} .o2k7Skin .mceSplitButtonActive {background-position:0 -44px} /* ColorSplitButton */ .o2k7Skin div.mceColorSplitMenu table {background:#FFF; border:1px solid gray} .o2k7Skin .mceColorSplitMenu td {padding:2px} .o2k7Skin .mceColorSplitMenu a {display:block; width:9px; height:9px; overflow:hidden; border:1px solid #808080} .o2k7Skin .mceColorSplitMenu td.mceMoreColors {padding:1px 3px 1px 1px} .o2k7Skin .mceColorSplitMenu a.mceMoreColors {width:100%; height:auto; text-align:center; font-family:Tahoma,Verdana,Arial,Helvetica; font-size:11px; line-height:20px; border:1px solid #FFF} .o2k7Skin .mceColorSplitMenu a.mceMoreColors:hover {border:1px solid #0A246A; background-color:#B6BDD2} .o2k7Skin a.mceMoreColors:hover {border:1px solid #0A246A} .o2k7Skin .mceColorPreview {margin-left:2px; width:16px; height:4px; overflow:hidden; background:#9a9b9a;overflow:hidden} .o2k7Skin .mce_forecolor span.mceAction, .o2k7Skin .mce_backcolor span.mceAction {height:15px;overflow:hidden} /* Menu */ .o2k7Skin .mceMenu {position:absolute; left:0; top:0; z-index:1000; border:1px solid #ABC6DD; direction:ltr} .o2k7Skin .mceNoIcons span.mceIcon {width:0;} .o2k7Skin .mceNoIcons a .mceText {padding-left:10px} .o2k7Skin .mceMenu table {background:#FFF} .o2k7Skin .mceMenu a, .o2k7Skin .mceMenu span, .o2k7Skin .mceMenu {display:block} .o2k7Skin .mceMenu td {height:20px} .o2k7Skin .mceMenu a {position:relative;padding:3px 0 4px 0} .o2k7Skin .mceMenu .mceText {position:relative; display:block; font-family:Tahoma,Verdana,Arial,Helvetica; color:#000; cursor:default; margin:0; padding:0 25px 0 25px; display:block} .o2k7Skin .mceMenu span.mceText, .o2k7Skin .mceMenu .mcePreview {font-size:11px} .o2k7Skin .mceMenu pre.mceText {font-family:Monospace} .o2k7Skin .mceMenu .mceIcon {position:absolute; top:0; left:0; width:22px;} .o2k7Skin .mceMenu .mceMenuItemEnabled a:hover, .o2k7Skin .mceMenu .mceMenuItemActive {background-color:#dbecf3} .o2k7Skin td.mceMenuItemSeparator {background:#DDD; height:1px} .o2k7Skin .mceMenuItemTitle a {border:0; background:#E5EFFD; border-bottom:1px solid #ABC6DD} .o2k7Skin .mceMenuItemTitle span.mceText {color:#000; font-weight:bold; padding-left:4px} .o2k7Skin .mceMenuItemDisabled .mceText {color:#888} .o2k7Skin .mceMenuItemSelected .mceIcon {background:url(../default/img/menu_check.gif)} .o2k7Skin .mceNoIcons .mceMenuItemSelected a {background:url(../default/img/menu_arrow.gif) no-repeat -6px center} .o2k7Skin .mceMenu span.mceMenuLine {display:none} .o2k7Skin .mceMenuItemSub a {background:url(../default/img/menu_arrow.gif) no-repeat top right;} .o2k7Skin .mceMenuItem td, .o2k7Skin .mceMenuItem th {line-height: normal} /* Progress,Resize */ .o2k7Skin .mceBlocker {position:absolute; left:0; top:0; z-index:1000; opacity:0.5; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=50); background:#FFF} .o2k7Skin .mceProgress {position:absolute; left:0; top:0; z-index:1001; background:url(../default/img/progress.gif) no-repeat; width:32px; height:32px; margin:-16px 0 0 -16px} /* Rtl */ .mceRtl .mceListBox .mceText {text-align: right; padding: 0 4px 0 0} .mceRtl .mceMenuItem .mceText {text-align: right} /* Formats */ .o2k7Skin .mce_formatPreview a {font-size:10px} .o2k7Skin .mce_p span.mceText {} .o2k7Skin .mce_address span.mceText {font-style:italic} .o2k7Skin .mce_pre span.mceText {font-family:monospace} .o2k7Skin .mce_h1 span.mceText {font-weight:bolder; font-size: 2em} .o2k7Skin .mce_h2 span.mceText {font-weight:bolder; font-size: 1.5em} .o2k7Skin .mce_h3 span.mceText {font-weight:bolder; font-size: 1.17em} .o2k7Skin .mce_h4 span.mceText {font-weight:bolder; font-size: 1em} .o2k7Skin .mce_h5 span.mceText {font-weight:bolder; font-size: .83em} .o2k7Skin .mce_h6 span.mceText {font-weight:bolder; font-size: .75em} /* Theme */ .o2k7Skin span.mce_bold {background-position:0 0} .o2k7Skin span.mce_italic {background-position:-60px 0} .o2k7Skin span.mce_underline {background-position:-140px 0} .o2k7Skin span.mce_strikethrough {background-position:-120px 0} .o2k7Skin span.mce_undo {background-position:-160px 0} .o2k7Skin span.mce_redo {background-position:-100px 0} .o2k7Skin span.mce_cleanup {background-position:-40px 0} .o2k7Skin span.mce_bullist {background-position:-20px 0} .o2k7Skin span.mce_numlist {background-position:-80px 0} .o2k7Skin span.mce_justifyleft {background-position:-460px 0} .o2k7Skin span.mce_justifyright {background-position:-480px 0} .o2k7Skin span.mce_justifycenter {background-position:-420px 0} .o2k7Skin span.mce_justifyfull {background-position:-440px 0} .o2k7Skin span.mce_anchor {background-position:-200px 0} .o2k7Skin span.mce_indent {background-position:-400px 0} .o2k7Skin span.mce_outdent {background-position:-540px 0} .o2k7Skin span.mce_link {background-position:-500px 0} .o2k7Skin span.mce_unlink {background-position:-640px 0} .o2k7Skin span.mce_sub {background-position:-600px 0} .o2k7Skin span.mce_sup {background-position:-620px 0} .o2k7Skin span.mce_removeformat {background-position:-580px 0} .o2k7Skin span.mce_newdocument {background-position:-520px 0} .o2k7Skin span.mce_image {background-position:-380px 0} .o2k7Skin span.mce_help {background-position:-340px 0} .o2k7Skin span.mce_code {background-position:-260px 0} .o2k7Skin span.mce_hr {background-position:-360px 0} .o2k7Skin span.mce_visualaid {background-position:-660px 0} .o2k7Skin span.mce_charmap {background-position:-240px 0} .o2k7Skin span.mce_paste {background-position:-560px 0} .o2k7Skin span.mce_copy {background-position:-700px 0} .o2k7Skin span.mce_cut {background-position:-680px 0} .o2k7Skin span.mce_blockquote {background-position:-220px 0} .o2k7Skin .mce_forecolor span.mceAction {background-position:-720px 0} .o2k7Skin .mce_backcolor span.mceAction {background-position:-760px 0} .o2k7Skin span.mce_forecolorpicker {background-position:-720px 0} .o2k7Skin span.mce_backcolorpicker {background-position:-760px 0} /* Plugins */ .o2k7Skin span.mce_advhr {background-position:-0px -20px} .o2k7Skin span.mce_ltr {background-position:-20px -20px} .o2k7Skin span.mce_rtl {background-position:-40px -20px} .o2k7Skin span.mce_emotions {background-position:-60px -20px} .o2k7Skin span.mce_fullpage {background-position:-80px -20px} .o2k7Skin span.mce_fullscreen {background-position:-100px -20px} .o2k7Skin span.mce_iespell {background-position:-120px -20px} .o2k7Skin span.mce_insertdate {background-position:-140px -20px} .o2k7Skin span.mce_inserttime {background-position:-160px -20px} .o2k7Skin span.mce_absolute {background-position:-180px -20px} .o2k7Skin span.mce_backward {background-position:-200px -20px} .o2k7Skin span.mce_forward {background-position:-220px -20px} .o2k7Skin span.mce_insert_layer {background-position:-240px -20px} .o2k7Skin span.mce_insertlayer {background-position:-260px -20px} .o2k7Skin span.mce_movebackward {background-position:-280px -20px} .o2k7Skin span.mce_moveforward {background-position:-300px -20px} .o2k7Skin span.mce_media {background-position:-320px -20px} .o2k7Skin span.mce_nonbreaking {background-position:-340px -20px} .o2k7Skin span.mce_pastetext {background-position:-360px -20px} .o2k7Skin span.mce_pasteword {background-position:-380px -20px} .o2k7Skin span.mce_selectall {background-position:-400px -20px} .o2k7Skin span.mce_preview {background-position:-420px -20px} .o2k7Skin span.mce_print {background-position:-440px -20px} .o2k7Skin span.mce_cancel {background-position:-460px -20px} .o2k7Skin span.mce_save {background-position:-480px -20px} .o2k7Skin span.mce_replace {background-position:-500px -20px} .o2k7Skin span.mce_search {background-position:-520px -20px} .o2k7Skin span.mce_styleprops {background-position:-560px -20px} .o2k7Skin span.mce_table {background-position:-580px -20px} .o2k7Skin span.mce_cell_props {background-position:-600px -20px} .o2k7Skin span.mce_delete_table {background-position:-620px -20px} .o2k7Skin span.mce_delete_col {background-position:-640px -20px} .o2k7Skin span.mce_delete_row {background-position:-660px -20px} .o2k7Skin span.mce_col_after {background-position:-680px -20px} .o2k7Skin span.mce_col_before {background-position:-700px -20px} .o2k7Skin span.mce_row_after {background-position:-720px -20px} .o2k7Skin span.mce_row_before {background-position:-740px -20px} .o2k7Skin span.mce_merge_cells {background-position:-760px -20px} .o2k7Skin span.mce_table_props {background-position:-980px -20px} .o2k7Skin span.mce_row_props {background-position:-780px -20px} .o2k7Skin span.mce_split_cells {background-position:-800px -20px} .o2k7Skin span.mce_template {background-position:-820px -20px} .o2k7Skin span.mce_visualchars {background-position:-840px -20px} .o2k7Skin span.mce_abbr {background-position:-860px -20px} .o2k7Skin span.mce_acronym {background-position:-880px -20px} .o2k7Skin span.mce_attribs {background-position:-900px -20px} .o2k7Skin span.mce_cite {background-position:-920px -20px} .o2k7Skin span.mce_del {background-position:-940px -20px} .o2k7Skin span.mce_ins {background-position:-960px -20px} .o2k7Skin span.mce_pagebreak {background-position:0 -40px} .o2k7Skin span.mce_restoredraft {background-position:-20px -40px} .o2k7Skin span.mce_spellchecker {background-position:-540px -20px} .o2k7Skin span.mce_visualblocks {background-position: -40px -40px}
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/o2k7/ui.css
CSS
asf20
15,183
/* Generic */ body { font-family:Verdana, Arial, Helvetica, sans-serif; font-size:11px; scrollbar-3dlight-color:#F0F0EE; scrollbar-arrow-color:#676662; scrollbar-base-color:#F0F0EE; scrollbar-darkshadow-color:#DDDDDD; scrollbar-face-color:#E0E0DD; scrollbar-highlight-color:#F0F0EE; scrollbar-shadow-color:#F0F0EE; scrollbar-track-color:#F5F5F5; background:#F0F0EE; padding:0; margin:8px 8px 0 8px; } html {background:#F0F0EE;} td {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} textarea {resize:none;outline:none;} a:link, a:visited {color:black;} a:hover {color:#2B6FB6;} .nowrap {white-space: nowrap} /* Forms */ fieldset {margin:0; padding:4px; border:1px solid #919B9C; font-family:Verdana, Arial; font-size:10px;} legend {color:#2B6FB6; font-weight:bold;} label.msg {display:none;} label.invalid {color:#EE0000; display:inline;} input.invalid {border:1px solid #EE0000;} input {background:#FFF; border:1px solid #CCC;} input, select, textarea {font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px;} input, select, textarea {border:1px solid #808080;} input.radio {border:1px none #000000; background:transparent; vertical-align:middle;} input.checkbox {border:1px none #000000; background:transparent; vertical-align:middle;} .input_noborder {border:0;} /* Buttons */ #insert, #cancel, input.button, .updateButton { border:0; margin:0; padding:0; font-weight:bold; width:94px; height:26px; background:url(../default/img/buttons.png) 0 -26px; cursor:pointer; padding-bottom:2px; float:left; } #insert {background:url(../default/img/buttons.png) 0 -52px} #cancel {background:url(../default/img/buttons.png) 0 0; float:right} /* Browse */ a.pickcolor, a.browse {text-decoration:none} a.browse span {display:block; width:20px; height:18px; background:url(../../img/icons.gif) -860px 0; border:1px solid #FFF; margin-left:1px;} .mceOldBoxModel a.browse span {width:22px; height:20px;} a.browse:hover span {border:1px solid #0A246A; background-color:#B2BBD0;} a.browse span.disabled {border:1px solid white; opacity:0.3; -ms-filter:'alpha(opacity=30)'; filter:alpha(opacity=30)} a.browse:hover span.disabled {border:1px solid white; background-color:transparent;} a.pickcolor span {display:block; width:20px; height:16px; background:url(../../img/icons.gif) -840px 0; margin-left:2px;} .mceOldBoxModel a.pickcolor span {width:21px; height:17px;} a.pickcolor:hover span {background-color:#B2BBD0;} a.pickcolor:hover span.disabled {} /* Charmap */ table.charmap {border:1px solid #AAA; text-align:center} td.charmap, #charmap a {width:18px; height:18px; color:#000; border:1px solid #AAA; text-align:center; font-size:12px; vertical-align:middle; line-height: 18px;} #charmap a {display:block; color:#000; text-decoration:none; border:0} #charmap a:hover {background:#CCC;color:#2B6FB6} #charmap #codeN {font-size:10px; font-family:Arial,Helvetica,sans-serif; text-align:center} #charmap #codeV {font-size:40px; height:80px; border:1px solid #AAA; text-align:center} /* Source */ .wordWrapCode {vertical-align:middle; border:1px none #000000; background:transparent;} .mceActionPanel {margin-top:5px;} /* Tabs classes */ .tabs {width:100%; height:18px; line-height:normal; background:url(../default/img/tabs.gif) repeat-x 0 -72px;} .tabs ul {margin:0; padding:0; list-style:none;} .tabs li {float:left; background:url(../default/img/tabs.gif) no-repeat 0 0; margin:0 2px 0 0; padding:0 0 0 10px; line-height:17px; height:18px; display:block;} .tabs li.current {background:url(../default/img/tabs.gif) no-repeat 0 -18px; margin-right:2px;} .tabs span {float:left; display:block; background:url(../default/img/tabs.gif) no-repeat right -36px; padding:0px 10px 0 0;} .tabs .current span {background:url(../default/img/tabs.gif) no-repeat right -54px;} .tabs a {text-decoration:none; font-family:Verdana, Arial; font-size:10px;} .tabs a:link, .tabs a:visited, .tabs a:hover {color:black;} /* Panels */ .panel_wrapper div.panel {display:none;} .panel_wrapper div.current {display:block; width:100%; height:300px; overflow:visible;} .panel_wrapper {border:1px solid #919B9C; border-top:0px; padding:10px; padding-top:5px; clear:both; background:white;} /* Columns */ .column {float:left;} .properties {width:100%;} .properties .column1 {} .properties .column2 {text-align:left;} /* Titles */ h1, h2, h3, h4 {color:#2B6FB6; margin:0; padding:0; padding-top:5px;} h3 {font-size:14px;} .title {font-size:12px; font-weight:bold; color:#2B6FB6;} /* Dialog specific */ #link .panel_wrapper, #link div.current {height:125px;} #image .panel_wrapper, #image div.current {height:200px;} #plugintable thead {font-weight:bold; background:#DDD;} #plugintable, #about #plugintable td {border:1px solid #919B9C;} #plugintable {width:96%; margin-top:10px;} #pluginscontainer {height:290px; overflow:auto;} #colorpicker #preview {display:inline-block; padding-left:40px; height:14px; border:1px solid black; margin-left:5px; margin-right: 5px} #colorpicker #previewblock {position: relative; top: -3px; padding-left:5px; padding-top: 0px; display:inline} #colorpicker #preview_wrapper { text-align:center; padding-top:4px; white-space: nowrap} #colorpicker #colors {float:left; border:1px solid gray; cursor:crosshair;} #colorpicker #light {border:1px solid gray; margin-left:5px; float:left;width:15px; height:150px; cursor:crosshair;} #colorpicker #light div {overflow:hidden;} #colorpicker .panel_wrapper div.current {height:175px;} #colorpicker #namedcolors {width:150px;} #colorpicker #namedcolors a {display:block; float:left; width:10px; height:10px; margin:1px 1px 0 0; overflow:hidden;} #colorpicker #colornamecontainer {margin-top:5px;} #colorpicker #picker_panel fieldset {margin:auto;width:325px;}
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/o2k7/dialog.css
CSS
asf20
5,731
body, td, pre {color:#000; font-family:Verdana, Arial, Helvetica, sans-serif; font-size:10px; margin:8px;} body {background:#FFF;} body.mceForceColors {background:#FFF; color:#000;} h1 {font-size: 2em} h2 {font-size: 1.5em} h3 {font-size: 1.17em} h4 {font-size: 1em} h5 {font-size: .83em} h6 {font-size: .75em} .mceItemTable, .mceItemTable td, .mceItemTable th, .mceItemTable caption, .mceItemVisualAid {border: 1px dashed #BBB;} a.mceItemAnchor {display:inline-block; width:11px !important; height:11px !important; background:url(../default/img/items.gif) no-repeat 0 0;} span.mceItemNbsp {background: #DDD} td.mceSelected, th.mceSelected {background-color:#3399ff !important} img {border:0;} table, img, hr, .mceItemAnchor {cursor:default} table td, table th {cursor:text} ins {border-bottom:1px solid green; text-decoration: none; color:green} del {color:red; text-decoration:line-through} cite {border-bottom:1px dashed blue} acronym {border-bottom:1px dotted #CCC; cursor:help} abbr {border-bottom:1px dashed #CCC; cursor:help} /* IE */ * html body { scrollbar-3dlight-color:#F0F0EE; scrollbar-arrow-color:#676662; scrollbar-base-color:#F0F0EE; scrollbar-darkshadow-color:#DDD; scrollbar-face-color:#E0E0DD; scrollbar-highlight-color:#F0F0EE; scrollbar-shadow-color:#F0F0EE; scrollbar-track-color:#F5F5F5; } img:-moz-broken {-moz-force-broken-image-icon:1; width:24px; height:24px} font[face=mceinline] {font-family:inherit !important} *[contentEditable]:focus {outline:0} .mceItemMedia {border:1px dotted #cc0000; background-position:center; background-repeat:no-repeat; background-color:#ffffcc} .mceItemShockWave {background-image:url(../../img/shockwave.gif)} .mceItemFlash {background-image:url(../../img/flash.gif)} .mceItemQuickTime {background-image:url(../../img/quicktime.gif)} .mceItemWindowsMedia {background-image:url(../../img/windowsmedia.gif)} .mceItemRealMedia {background-image:url(../../img/realmedia.gif)} .mceItemVideo {background-image:url(../../img/video.gif)} .mceItemAudio {background-image:url(../../img/video.gif)} .mceItemIframe {background-image:url(../../img/iframe.gif)} .mcePageBreak {display:block;border:0;width:100%;height:12px;border-top:1px dotted #ccc;margin-top:15px;background:#fff url(../../img/pagebreak.gif) no-repeat center top;}
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/skins/o2k7/content.css
CSS
asf20
2,283
tinyMCEPopup.requireLangPack(); tinyMCEPopup.onInit.add(onLoadInit); function saveContent() { tinyMCEPopup.editor.setContent(document.getElementById('htmlSource').value, {source_view : true}); tinyMCEPopup.close(); } function onLoadInit() { tinyMCEPopup.resizeToInnerSize(); // Remove Gecko spellchecking if (tinymce.isGecko) document.body.spellcheck = tinyMCEPopup.editor.getParam("gecko_spellcheck"); document.getElementById('htmlSource').value = tinyMCEPopup.editor.getContent({source_view : true}); if (tinyMCEPopup.editor.getParam("theme_advanced_source_editor_wrap", true)) { turnWrapOn(); document.getElementById('wraped').checked = true; } resizeInputs(); } function setWrap(val) { var v, n, s = document.getElementById('htmlSource'); s.wrap = val; if (!tinymce.isIE) { v = s.value; n = s.cloneNode(false); n.setAttribute("wrap", val); s.parentNode.replaceChild(n, s); n.value = v; } } function setWhiteSpaceCss(value) { var el = document.getElementById('htmlSource'); tinymce.DOM.setStyle(el, 'white-space', value); } function turnWrapOff() { if (tinymce.isWebKit) { setWhiteSpaceCss('pre'); } else { setWrap('off'); } } function turnWrapOn() { if (tinymce.isWebKit) { setWhiteSpaceCss('pre-wrap'); } else { setWrap('soft'); } } function toggleWordWrap(elm) { if (elm.checked) { turnWrapOn(); } else { turnWrapOff(); } } function resizeInputs() { var vp = tinyMCEPopup.dom.getViewPort(window), el; el = document.getElementById('htmlSource'); if (el) { el.style.width = (vp.w - 20) + 'px'; el.style.height = (vp.h - 65) + 'px'; } }
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/js/source_editor.js
JavaScript
asf20
1,616
/** * charmap.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ tinyMCEPopup.requireLangPack(); var charmap = [ ['&nbsp;', '&#160;', true, 'no-break space'], ['&amp;', '&#38;', true, 'ampersand'], ['&quot;', '&#34;', true, 'quotation mark'], // finance ['&cent;', '&#162;', true, 'cent sign'], ['&euro;', '&#8364;', true, 'euro sign'], ['&pound;', '&#163;', true, 'pound sign'], ['&yen;', '&#165;', true, 'yen sign'], // signs ['&copy;', '&#169;', true, 'copyright sign'], ['&reg;', '&#174;', true, 'registered sign'], ['&trade;', '&#8482;', true, 'trade mark sign'], ['&permil;', '&#8240;', true, 'per mille sign'], ['&micro;', '&#181;', true, 'micro sign'], ['&middot;', '&#183;', true, 'middle dot'], ['&bull;', '&#8226;', true, 'bullet'], ['&hellip;', '&#8230;', true, 'three dot leader'], ['&prime;', '&#8242;', true, 'minutes / feet'], ['&Prime;', '&#8243;', true, 'seconds / inches'], ['&sect;', '&#167;', true, 'section sign'], ['&para;', '&#182;', true, 'paragraph sign'], ['&szlig;', '&#223;', true, 'sharp s / ess-zed'], // quotations ['&lsaquo;', '&#8249;', true, 'single left-pointing angle quotation mark'], ['&rsaquo;', '&#8250;', true, 'single right-pointing angle quotation mark'], ['&laquo;', '&#171;', true, 'left pointing guillemet'], ['&raquo;', '&#187;', true, 'right pointing guillemet'], ['&lsquo;', '&#8216;', true, 'left single quotation mark'], ['&rsquo;', '&#8217;', true, 'right single quotation mark'], ['&ldquo;', '&#8220;', true, 'left double quotation mark'], ['&rdquo;', '&#8221;', true, 'right double quotation mark'], ['&sbquo;', '&#8218;', true, 'single low-9 quotation mark'], ['&bdquo;', '&#8222;', true, 'double low-9 quotation mark'], ['&lt;', '&#60;', true, 'less-than sign'], ['&gt;', '&#62;', true, 'greater-than sign'], ['&le;', '&#8804;', true, 'less-than or equal to'], ['&ge;', '&#8805;', true, 'greater-than or equal to'], ['&ndash;', '&#8211;', true, 'en dash'], ['&mdash;', '&#8212;', true, 'em dash'], ['&macr;', '&#175;', true, 'macron'], ['&oline;', '&#8254;', true, 'overline'], ['&curren;', '&#164;', true, 'currency sign'], ['&brvbar;', '&#166;', true, 'broken bar'], ['&uml;', '&#168;', true, 'diaeresis'], ['&iexcl;', '&#161;', true, 'inverted exclamation mark'], ['&iquest;', '&#191;', true, 'turned question mark'], ['&circ;', '&#710;', true, 'circumflex accent'], ['&tilde;', '&#732;', true, 'small tilde'], ['&deg;', '&#176;', true, 'degree sign'], ['&minus;', '&#8722;', true, 'minus sign'], ['&plusmn;', '&#177;', true, 'plus-minus sign'], ['&divide;', '&#247;', true, 'division sign'], ['&frasl;', '&#8260;', true, 'fraction slash'], ['&times;', '&#215;', true, 'multiplication sign'], ['&sup1;', '&#185;', true, 'superscript one'], ['&sup2;', '&#178;', true, 'superscript two'], ['&sup3;', '&#179;', true, 'superscript three'], ['&frac14;', '&#188;', true, 'fraction one quarter'], ['&frac12;', '&#189;', true, 'fraction one half'], ['&frac34;', '&#190;', true, 'fraction three quarters'], // math / logical ['&fnof;', '&#402;', true, 'function / florin'], ['&int;', '&#8747;', true, 'integral'], ['&sum;', '&#8721;', true, 'n-ary sumation'], ['&infin;', '&#8734;', true, 'infinity'], ['&radic;', '&#8730;', true, 'square root'], ['&sim;', '&#8764;', false,'similar to'], ['&cong;', '&#8773;', false,'approximately equal to'], ['&asymp;', '&#8776;', true, 'almost equal to'], ['&ne;', '&#8800;', true, 'not equal to'], ['&equiv;', '&#8801;', true, 'identical to'], ['&isin;', '&#8712;', false,'element of'], ['&notin;', '&#8713;', false,'not an element of'], ['&ni;', '&#8715;', false,'contains as member'], ['&prod;', '&#8719;', true, 'n-ary product'], ['&and;', '&#8743;', false,'logical and'], ['&or;', '&#8744;', false,'logical or'], ['&not;', '&#172;', true, 'not sign'], ['&cap;', '&#8745;', true, 'intersection'], ['&cup;', '&#8746;', false,'union'], ['&part;', '&#8706;', true, 'partial differential'], ['&forall;', '&#8704;', false,'for all'], ['&exist;', '&#8707;', false,'there exists'], ['&empty;', '&#8709;', false,'diameter'], ['&nabla;', '&#8711;', false,'backward difference'], ['&lowast;', '&#8727;', false,'asterisk operator'], ['&prop;', '&#8733;', false,'proportional to'], ['&ang;', '&#8736;', false,'angle'], // undefined ['&acute;', '&#180;', true, 'acute accent'], ['&cedil;', '&#184;', true, 'cedilla'], ['&ordf;', '&#170;', true, 'feminine ordinal indicator'], ['&ordm;', '&#186;', true, 'masculine ordinal indicator'], ['&dagger;', '&#8224;', true, 'dagger'], ['&Dagger;', '&#8225;', true, 'double dagger'], // alphabetical special chars ['&Agrave;', '&#192;', true, 'A - grave'], ['&Aacute;', '&#193;', true, 'A - acute'], ['&Acirc;', '&#194;', true, 'A - circumflex'], ['&Atilde;', '&#195;', true, 'A - tilde'], ['&Auml;', '&#196;', true, 'A - diaeresis'], ['&Aring;', '&#197;', true, 'A - ring above'], ['&AElig;', '&#198;', true, 'ligature AE'], ['&Ccedil;', '&#199;', true, 'C - cedilla'], ['&Egrave;', '&#200;', true, 'E - grave'], ['&Eacute;', '&#201;', true, 'E - acute'], ['&Ecirc;', '&#202;', true, 'E - circumflex'], ['&Euml;', '&#203;', true, 'E - diaeresis'], ['&Igrave;', '&#204;', true, 'I - grave'], ['&Iacute;', '&#205;', true, 'I - acute'], ['&Icirc;', '&#206;', true, 'I - circumflex'], ['&Iuml;', '&#207;', true, 'I - diaeresis'], ['&ETH;', '&#208;', true, 'ETH'], ['&Ntilde;', '&#209;', true, 'N - tilde'], ['&Ograve;', '&#210;', true, 'O - grave'], ['&Oacute;', '&#211;', true, 'O - acute'], ['&Ocirc;', '&#212;', true, 'O - circumflex'], ['&Otilde;', '&#213;', true, 'O - tilde'], ['&Ouml;', '&#214;', true, 'O - diaeresis'], ['&Oslash;', '&#216;', true, 'O - slash'], ['&OElig;', '&#338;', true, 'ligature OE'], ['&Scaron;', '&#352;', true, 'S - caron'], ['&Ugrave;', '&#217;', true, 'U - grave'], ['&Uacute;', '&#218;', true, 'U - acute'], ['&Ucirc;', '&#219;', true, 'U - circumflex'], ['&Uuml;', '&#220;', true, 'U - diaeresis'], ['&Yacute;', '&#221;', true, 'Y - acute'], ['&Yuml;', '&#376;', true, 'Y - diaeresis'], ['&THORN;', '&#222;', true, 'THORN'], ['&agrave;', '&#224;', true, 'a - grave'], ['&aacute;', '&#225;', true, 'a - acute'], ['&acirc;', '&#226;', true, 'a - circumflex'], ['&atilde;', '&#227;', true, 'a - tilde'], ['&auml;', '&#228;', true, 'a - diaeresis'], ['&aring;', '&#229;', true, 'a - ring above'], ['&aelig;', '&#230;', true, 'ligature ae'], ['&ccedil;', '&#231;', true, 'c - cedilla'], ['&egrave;', '&#232;', true, 'e - grave'], ['&eacute;', '&#233;', true, 'e - acute'], ['&ecirc;', '&#234;', true, 'e - circumflex'], ['&euml;', '&#235;', true, 'e - diaeresis'], ['&igrave;', '&#236;', true, 'i - grave'], ['&iacute;', '&#237;', true, 'i - acute'], ['&icirc;', '&#238;', true, 'i - circumflex'], ['&iuml;', '&#239;', true, 'i - diaeresis'], ['&eth;', '&#240;', true, 'eth'], ['&ntilde;', '&#241;', true, 'n - tilde'], ['&ograve;', '&#242;', true, 'o - grave'], ['&oacute;', '&#243;', true, 'o - acute'], ['&ocirc;', '&#244;', true, 'o - circumflex'], ['&otilde;', '&#245;', true, 'o - tilde'], ['&ouml;', '&#246;', true, 'o - diaeresis'], ['&oslash;', '&#248;', true, 'o slash'], ['&oelig;', '&#339;', true, 'ligature oe'], ['&scaron;', '&#353;', true, 's - caron'], ['&ugrave;', '&#249;', true, 'u - grave'], ['&uacute;', '&#250;', true, 'u - acute'], ['&ucirc;', '&#251;', true, 'u - circumflex'], ['&uuml;', '&#252;', true, 'u - diaeresis'], ['&yacute;', '&#253;', true, 'y - acute'], ['&thorn;', '&#254;', true, 'thorn'], ['&yuml;', '&#255;', true, 'y - diaeresis'], ['&Alpha;', '&#913;', true, 'Alpha'], ['&Beta;', '&#914;', true, 'Beta'], ['&Gamma;', '&#915;', true, 'Gamma'], ['&Delta;', '&#916;', true, 'Delta'], ['&Epsilon;', '&#917;', true, 'Epsilon'], ['&Zeta;', '&#918;', true, 'Zeta'], ['&Eta;', '&#919;', true, 'Eta'], ['&Theta;', '&#920;', true, 'Theta'], ['&Iota;', '&#921;', true, 'Iota'], ['&Kappa;', '&#922;', true, 'Kappa'], ['&Lambda;', '&#923;', true, 'Lambda'], ['&Mu;', '&#924;', true, 'Mu'], ['&Nu;', '&#925;', true, 'Nu'], ['&Xi;', '&#926;', true, 'Xi'], ['&Omicron;', '&#927;', true, 'Omicron'], ['&Pi;', '&#928;', true, 'Pi'], ['&Rho;', '&#929;', true, 'Rho'], ['&Sigma;', '&#931;', true, 'Sigma'], ['&Tau;', '&#932;', true, 'Tau'], ['&Upsilon;', '&#933;', true, 'Upsilon'], ['&Phi;', '&#934;', true, 'Phi'], ['&Chi;', '&#935;', true, 'Chi'], ['&Psi;', '&#936;', true, 'Psi'], ['&Omega;', '&#937;', true, 'Omega'], ['&alpha;', '&#945;', true, 'alpha'], ['&beta;', '&#946;', true, 'beta'], ['&gamma;', '&#947;', true, 'gamma'], ['&delta;', '&#948;', true, 'delta'], ['&epsilon;', '&#949;', true, 'epsilon'], ['&zeta;', '&#950;', true, 'zeta'], ['&eta;', '&#951;', true, 'eta'], ['&theta;', '&#952;', true, 'theta'], ['&iota;', '&#953;', true, 'iota'], ['&kappa;', '&#954;', true, 'kappa'], ['&lambda;', '&#955;', true, 'lambda'], ['&mu;', '&#956;', true, 'mu'], ['&nu;', '&#957;', true, 'nu'], ['&xi;', '&#958;', true, 'xi'], ['&omicron;', '&#959;', true, 'omicron'], ['&pi;', '&#960;', true, 'pi'], ['&rho;', '&#961;', true, 'rho'], ['&sigmaf;', '&#962;', true, 'final sigma'], ['&sigma;', '&#963;', true, 'sigma'], ['&tau;', '&#964;', true, 'tau'], ['&upsilon;', '&#965;', true, 'upsilon'], ['&phi;', '&#966;', true, 'phi'], ['&chi;', '&#967;', true, 'chi'], ['&psi;', '&#968;', true, 'psi'], ['&omega;', '&#969;', true, 'omega'], // symbols ['&alefsym;', '&#8501;', false,'alef symbol'], ['&piv;', '&#982;', false,'pi symbol'], ['&real;', '&#8476;', false,'real part symbol'], ['&thetasym;','&#977;', false,'theta symbol'], ['&upsih;', '&#978;', false,'upsilon - hook symbol'], ['&weierp;', '&#8472;', false,'Weierstrass p'], ['&image;', '&#8465;', false,'imaginary part'], // arrows ['&larr;', '&#8592;', true, 'leftwards arrow'], ['&uarr;', '&#8593;', true, 'upwards arrow'], ['&rarr;', '&#8594;', true, 'rightwards arrow'], ['&darr;', '&#8595;', true, 'downwards arrow'], ['&harr;', '&#8596;', true, 'left right arrow'], ['&crarr;', '&#8629;', false,'carriage return'], ['&lArr;', '&#8656;', false,'leftwards double arrow'], ['&uArr;', '&#8657;', false,'upwards double arrow'], ['&rArr;', '&#8658;', false,'rightwards double arrow'], ['&dArr;', '&#8659;', false,'downwards double arrow'], ['&hArr;', '&#8660;', false,'left right double arrow'], ['&there4;', '&#8756;', false,'therefore'], ['&sub;', '&#8834;', false,'subset of'], ['&sup;', '&#8835;', false,'superset of'], ['&nsub;', '&#8836;', false,'not a subset of'], ['&sube;', '&#8838;', false,'subset of or equal to'], ['&supe;', '&#8839;', false,'superset of or equal to'], ['&oplus;', '&#8853;', false,'circled plus'], ['&otimes;', '&#8855;', false,'circled times'], ['&perp;', '&#8869;', false,'perpendicular'], ['&sdot;', '&#8901;', false,'dot operator'], ['&lceil;', '&#8968;', false,'left ceiling'], ['&rceil;', '&#8969;', false,'right ceiling'], ['&lfloor;', '&#8970;', false,'left floor'], ['&rfloor;', '&#8971;', false,'right floor'], ['&lang;', '&#9001;', false,'left-pointing angle bracket'], ['&rang;', '&#9002;', false,'right-pointing angle bracket'], ['&loz;', '&#9674;', true, 'lozenge'], ['&spades;', '&#9824;', true, 'black spade suit'], ['&clubs;', '&#9827;', true, 'black club suit'], ['&hearts;', '&#9829;', true, 'black heart suit'], ['&diams;', '&#9830;', true, 'black diamond suit'], ['&ensp;', '&#8194;', false,'en space'], ['&emsp;', '&#8195;', false,'em space'], ['&thinsp;', '&#8201;', false,'thin space'], ['&zwnj;', '&#8204;', false,'zero width non-joiner'], ['&zwj;', '&#8205;', false,'zero width joiner'], ['&lrm;', '&#8206;', false,'left-to-right mark'], ['&rlm;', '&#8207;', false,'right-to-left mark'], ['&shy;', '&#173;', false,'soft hyphen'] ]; tinyMCEPopup.onInit.add(function() { tinyMCEPopup.dom.setHTML('charmapView', renderCharMapHTML()); addKeyboardNavigation(); }); function addKeyboardNavigation(){ var tableElm, cells, settings; cells = tinyMCEPopup.dom.select("a.charmaplink", "charmapgroup"); settings ={ root: "charmapgroup", items: cells }; cells[0].tabindex=0; tinyMCEPopup.dom.addClass(cells[0], "mceFocus"); if (tinymce.isGecko) { cells[0].focus(); } else { setTimeout(function(){ cells[0].focus(); }, 100); } tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', settings, tinyMCEPopup.dom); } function renderCharMapHTML() { var charsPerRow = 20, tdWidth=20, tdHeight=20, i; var html = '<div id="charmapgroup" aria-labelledby="charmap_label" tabindex="0" role="listbox">'+ '<table role="presentation" border="0" cellspacing="1" cellpadding="0" width="' + (tdWidth*charsPerRow) + '"><tr height="' + tdHeight + '">'; var cols=-1; for (i=0; i<charmap.length; i++) { var previewCharFn; if (charmap[i][2]==true) { cols++; previewCharFn = 'previewChar(\'' + charmap[i][1].substring(1,charmap[i][1].length) + '\',\'' + charmap[i][0].substring(1,charmap[i][0].length) + '\',\'' + charmap[i][3] + '\');'; html += '' + '<td class="charmap">' + '<a class="charmaplink" role="button" onmouseover="'+previewCharFn+'" onfocus="'+previewCharFn+'" href="javascript:void(0)" onclick="insertChar(\'' + charmap[i][1].substring(2,charmap[i][1].length-1) + '\');" onclick="return false;" onmousedown="return false;" title="' + charmap[i][3] + ' '+ tinyMCEPopup.editor.translate("advanced_dlg.charmap_usage")+'">' + charmap[i][1] + '</a></td>'; if ((cols+1) % charsPerRow == 0) html += '</tr><tr height="' + tdHeight + '">'; } } if (cols % charsPerRow > 0) { var padd = charsPerRow - (cols % charsPerRow); for (var i=0; i<padd-1; i++) html += '<td width="' + tdWidth + '" height="' + tdHeight + '" class="charmap">&nbsp;</td>'; } html += '</tr></table></div>'; html = html.replace(/<tr height="20"><\/tr>/g, ''); return html; } function insertChar(chr) { tinyMCEPopup.execCommand('mceInsertContent', false, '&#' + chr + ';'); // Refocus in window if (tinyMCEPopup.isWindow) window.focus(); tinyMCEPopup.editor.focus(); tinyMCEPopup.close(); } function previewChar(codeA, codeB, codeN) { var elmA = document.getElementById('codeA'); var elmB = document.getElementById('codeB'); var elmV = document.getElementById('codeV'); var elmN = document.getElementById('codeN'); if (codeA=='#160;') { elmV.innerHTML = '__'; } else { elmV.innerHTML = '&' + codeA; } elmB.innerHTML = '&amp;' + codeA; elmA.innerHTML = '&amp;' + codeB; elmN.innerHTML = codeN; }
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/js/charmap.js
JavaScript
asf20
15,430
tinyMCEPopup.requireLangPack(); var AnchorDialog = { init : function(ed) { var action, elm, f = document.forms[0]; this.editor = ed; elm = ed.dom.getParent(ed.selection.getNode(), 'A'); v = ed.dom.getAttrib(elm, 'name') || ed.dom.getAttrib(elm, 'id'); if (v) { this.action = 'update'; f.anchorName.value = v; } f.insert.value = ed.getLang(elm ? 'update' : 'insert'); }, update : function() { var ed = this.editor, elm, name = document.forms[0].anchorName.value, attribName; if (!name || !/^[a-z][a-z0-9\-\_:\.]*$/i.test(name)) { tinyMCEPopup.alert('advanced_dlg.anchor_invalid'); return; } tinyMCEPopup.restoreSelection(); if (this.action != 'update') ed.selection.collapse(1); var aRule = ed.schema.getElementRule('a'); if (!aRule || aRule.attributes.name) { attribName = 'name'; } else { attribName = 'id'; } elm = ed.dom.getParent(ed.selection.getNode(), 'A'); if (elm) { elm.setAttribute(attribName, name); elm[attribName] = name; ed.undoManager.add(); } else { // create with zero-sized nbsp so that in Webkit where anchor is on last line by itself caret cannot be placed after it var attrs = {'class' : 'mceItemAnchor'}; attrs[attribName] = name; ed.execCommand('mceInsertContent', 0, ed.dom.createHTML('a', attrs, '\uFEFF')); ed.nodeChanged(); } tinyMCEPopup.close(); } }; tinyMCEPopup.onInit.add(AnchorDialog.init, AnchorDialog);
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/js/anchor.js
JavaScript
asf20
1,442
var ImageDialog = { preInit : function() { var url; tinyMCEPopup.requireLangPack(); if (url = tinyMCEPopup.getParam("external_image_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function() { var f = document.forms[0], ed = tinyMCEPopup.editor; // Setup browse button document.getElementById('srcbrowsercontainer').innerHTML = getBrowserHTML('srcbrowser','src','image','theme_advanced_image'); if (isVisible('srcbrowser')) document.getElementById('src').style.width = '180px'; e = ed.selection.getNode(); this.fillFileList('image_list', tinyMCEPopup.getParam('external_image_list', 'tinyMCEImageList')); if (e.nodeName == 'IMG') { f.src.value = ed.dom.getAttrib(e, 'src'); f.alt.value = ed.dom.getAttrib(e, 'alt'); f.border.value = this.getAttrib(e, 'border'); f.vspace.value = this.getAttrib(e, 'vspace'); f.hspace.value = this.getAttrib(e, 'hspace'); f.width.value = ed.dom.getAttrib(e, 'width'); f.height.value = ed.dom.getAttrib(e, 'height'); f.insert.value = ed.getLang('update'); this.styleVal = ed.dom.getAttrib(e, 'style'); selectByValue(f, 'image_list', f.src.value); selectByValue(f, 'align', this.getAttrib(e, 'align')); this.updateStyle(); } }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = typeof(l) === 'function' ? l() : window[l]; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, update : function() { var f = document.forms[0], nl = f.elements, ed = tinyMCEPopup.editor, args = {}, el; tinyMCEPopup.restoreSelection(); if (f.src.value === '') { if (ed.selection.getNode().nodeName == 'IMG') { ed.dom.remove(ed.selection.getNode()); ed.execCommand('mceRepaint'); } tinyMCEPopup.close(); return; } if (!ed.settings.inline_styles) { args = tinymce.extend(args, { vspace : nl.vspace.value, hspace : nl.hspace.value, border : nl.border.value, align : getSelectValue(f, 'align') }); } else args.style = this.styleVal; tinymce.extend(args, { src : f.src.value.replace(/ /g, '%20'), alt : f.alt.value, width : f.width.value, height : f.height.value }); el = ed.selection.getNode(); if (el && el.nodeName == 'IMG') { ed.dom.setAttribs(el, args); tinyMCEPopup.editor.execCommand('mceRepaint'); tinyMCEPopup.editor.focus(); } else { tinymce.each(args, function(value, name) { if (value === "") { delete args[name]; } }); ed.execCommand('mceInsertContent', false, tinyMCEPopup.editor.dom.createHTML('img', args), {skip_undo : 1}); ed.undoManager.add(); } tinyMCEPopup.close(); }, updateStyle : function() { var dom = tinyMCEPopup.dom, st = {}, v, f = document.forms[0]; if (tinyMCEPopup.editor.settings.inline_styles) { tinymce.each(tinyMCEPopup.dom.parseStyle(this.styleVal), function(value, key) { st[key] = value; }); // Handle align v = getSelectValue(f, 'align'); if (v) { if (v == 'left' || v == 'right') { st['float'] = v; delete st['vertical-align']; } else { st['vertical-align'] = v; delete st['float']; } } else { delete st['float']; delete st['vertical-align']; } // Handle border v = f.border.value; if (v || v == '0') { if (v == '0') st['border'] = '0'; else st['border'] = v + 'px solid black'; } else delete st['border']; // Handle hspace v = f.hspace.value; if (v) { delete st['margin']; st['margin-left'] = v + 'px'; st['margin-right'] = v + 'px'; } else { delete st['margin-left']; delete st['margin-right']; } // Handle vspace v = f.vspace.value; if (v) { delete st['margin']; st['margin-top'] = v + 'px'; st['margin-bottom'] = v + 'px'; } else { delete st['margin-top']; delete st['margin-bottom']; } // Merge st = tinyMCEPopup.dom.parseStyle(dom.serializeStyle(st), 'img'); this.styleVal = dom.serializeStyle(st, 'img'); } }, getAttrib : function(e, at) { var ed = tinyMCEPopup.editor, dom = ed.dom, v, v2; if (ed.settings.inline_styles) { switch (at) { case 'align': if (v = dom.getStyle(e, 'float')) return v; if (v = dom.getStyle(e, 'vertical-align')) return v; break; case 'hspace': v = dom.getStyle(e, 'margin-left') v2 = dom.getStyle(e, 'margin-right'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'vspace': v = dom.getStyle(e, 'margin-top') v2 = dom.getStyle(e, 'margin-bottom'); if (v && v == v2) return parseInt(v.replace(/[^0-9]/g, '')); break; case 'border': v = 0; tinymce.each(['top', 'right', 'bottom', 'left'], function(sv) { sv = dom.getStyle(e, 'border-' + sv + '-width'); // False or not the same as prev if (!sv || (sv != v && v !== 0)) { v = 0; return false; } if (sv) v = sv; }); if (v) return parseInt(v.replace(/[^0-9]/g, '')); break; } } if (v = dom.getAttrib(e, at)) return v; return ''; }, resetImageData : function() { var f = document.forms[0]; f.width.value = f.height.value = ""; }, updateImageData : function() { var f = document.forms[0], t = ImageDialog; if (f.width.value == "") f.width.value = t.preloadImg.width; if (f.height.value == "") f.height.value = t.preloadImg.height; }, getImageData : function() { var f = document.forms[0]; this.preloadImg = new Image(); this.preloadImg.onload = this.updateImageData; this.preloadImg.onerror = this.resetImageData; this.preloadImg.src = tinyMCEPopup.editor.documentBaseURI.toAbsolute(f.src.value); } }; ImageDialog.preInit(); tinyMCEPopup.onInit.add(ImageDialog.init, ImageDialog);
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/js/image.js
JavaScript
asf20
6,138
tinyMCEPopup.requireLangPack(); var LinkDialog = { preInit : function() { var url; if (url = tinyMCEPopup.getParam("external_link_list_url")) document.write('<script language="javascript" type="text/javascript" src="' + tinyMCEPopup.editor.documentBaseURI.toAbsolute(url) + '"></script>'); }, init : function() { var f = document.forms[0], ed = tinyMCEPopup.editor; // Setup browse button document.getElementById('hrefbrowsercontainer').innerHTML = getBrowserHTML('hrefbrowser', 'href', 'file', 'theme_advanced_link'); if (isVisible('hrefbrowser')) document.getElementById('href').style.width = '180px'; this.fillClassList('class_list'); this.fillFileList('link_list', 'tinyMCELinkList'); this.fillTargetList('target_list'); if (e = ed.dom.getParent(ed.selection.getNode(), 'A')) { f.href.value = ed.dom.getAttrib(e, 'href'); f.linktitle.value = ed.dom.getAttrib(e, 'title'); f.insert.value = ed.getLang('update'); selectByValue(f, 'link_list', f.href.value); selectByValue(f, 'target_list', ed.dom.getAttrib(e, 'target')); selectByValue(f, 'class_list', ed.dom.getAttrib(e, 'class')); } }, update : function() { var f = document.forms[0], ed = tinyMCEPopup.editor, e, b, href = f.href.value.replace(/ /g, '%20'); tinyMCEPopup.restoreSelection(); e = ed.dom.getParent(ed.selection.getNode(), 'A'); // Remove element if there is no href if (!f.href.value) { if (e) { b = ed.selection.getBookmark(); ed.dom.remove(e, 1); ed.selection.moveToBookmark(b); tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); return; } } // Create new anchor elements if (e == null) { ed.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1}); tinymce.each(ed.dom.select("a"), function(n) { if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') { e = n; ed.dom.setAttribs(e, { href : href, title : f.linktitle.value, target : f.target_list ? getSelectValue(f, "target_list") : null, 'class' : f.class_list ? getSelectValue(f, "class_list") : null }); } }); } else { ed.dom.setAttribs(e, { href : href, title : f.linktitle.value }); if (f.target_list) { ed.dom.setAttrib(e, 'target', getSelectValue(f, "target_list")); } if (f.class_list) { ed.dom.setAttrib(e, 'class', getSelectValue(f, "class_list")); } } // Don't move caret if selection was image if (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') { ed.focus(); ed.selection.select(e); ed.selection.collapse(0); tinyMCEPopup.storeSelection(); } tinyMCEPopup.execCommand("mceEndUndoLevel"); tinyMCEPopup.close(); }, checkPrefix : function(n) { if (n.value && Validator.isEmail(n) && !/^\s*mailto:/i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_email'))) n.value = 'mailto:' + n.value; if (/^\s*www\./i.test(n.value) && confirm(tinyMCEPopup.getLang('advanced_dlg.link_is_external'))) n.value = 'http://' + n.value; }, fillFileList : function(id, l) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; l = window[l]; if (l && l.length > 0) { lst.options[lst.options.length] = new Option('', ''); tinymce.each(l, function(o) { lst.options[lst.options.length] = new Option(o[0], o[1]); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillClassList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v, cl; if (v = tinyMCEPopup.getParam('theme_advanced_styles')) { cl = []; tinymce.each(v.split(';'), function(v) { var p = v.split('='); cl.push({'title' : p[0], 'class' : p[1]}); }); } else cl = tinyMCEPopup.editor.dom.getClasses(); if (cl.length > 0) { lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); tinymce.each(cl, function(o) { lst.options[lst.options.length] = new Option(o.title || o['class'], o['class']); }); } else dom.remove(dom.getParent(id, 'tr')); }, fillTargetList : function(id) { var dom = tinyMCEPopup.dom, lst = dom.get(id), v; lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('not_set'), ''); lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_same'), '_self'); lst.options[lst.options.length] = new Option(tinyMCEPopup.getLang('advanced_dlg.link_target_blank'), '_blank'); if (v = tinyMCEPopup.getParam('theme_advanced_link_targets')) { tinymce.each(v.split(','), function(v) { v = v.split('='); lst.options[lst.options.length] = new Option(v[0], v[1]); }); } } }; LinkDialog.preInit(); tinyMCEPopup.onInit.add(LinkDialog.init, LinkDialog);
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/js/link.js
JavaScript
asf20
4,788
tinyMCEPopup.requireLangPack(); function init() { var ed, tcont; tinyMCEPopup.resizeToInnerSize(); ed = tinyMCEPopup.editor; // Give FF some time window.setTimeout(insertHelpIFrame, 10); tcont = document.getElementById('plugintablecontainer'); document.getElementById('plugins_tab').style.display = 'none'; var html = ""; html += '<table id="plugintable">'; html += '<thead>'; html += '<tr>'; html += '<td>' + ed.getLang('advanced_dlg.about_plugin') + '</td>'; html += '<td>' + ed.getLang('advanced_dlg.about_author') + '</td>'; html += '<td>' + ed.getLang('advanced_dlg.about_version') + '</td>'; html += '</tr>'; html += '</thead>'; html += '<tbody>'; tinymce.each(ed.plugins, function(p, n) { var info; if (!p.getInfo) return; html += '<tr>'; info = p.getInfo(); if (info.infourl != null && info.infourl != '') html += '<td width="50%" title="' + n + '"><a href="' + info.infourl + '" target="_blank">' + info.longname + '</a></td>'; else html += '<td width="50%" title="' + n + '">' + info.longname + '</td>'; if (info.authorurl != null && info.authorurl != '') html += '<td width="35%"><a href="' + info.authorurl + '" target="_blank">' + info.author + '</a></td>'; else html += '<td width="35%">' + info.author + '</td>'; html += '<td width="15%">' + info.version + '</td>'; html += '</tr>'; document.getElementById('plugins_tab').style.display = ''; }); html += '</tbody>'; html += '</table>'; tcont.innerHTML = html; tinyMCEPopup.dom.get('version').innerHTML = tinymce.majorVersion + "." + tinymce.minorVersion; tinyMCEPopup.dom.get('date').innerHTML = tinymce.releaseDate; } function insertHelpIFrame() { var html; if (tinyMCEPopup.getParam('docs_url')) { html = '<iframe width="100%" height="300" src="' + tinyMCEPopup.editor.baseURI.toAbsolute(tinyMCEPopup.getParam('docs_url')) + '"></iframe>'; document.getElementById('iframecontainer').innerHTML = html; document.getElementById('help_tab').style.display = 'block'; document.getElementById('help_tab').setAttribute("aria-hidden", "false"); } } tinyMCEPopup.onInit.add(init);
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/js/about.js
JavaScript
asf20
2,130
tinyMCEPopup.requireLangPack(); var detail = 50, strhex = "0123456789abcdef", i, isMouseDown = false, isMouseOver = false; var colors = [ "#000000","#000033","#000066","#000099","#0000cc","#0000ff","#330000","#330033", "#330066","#330099","#3300cc","#3300ff","#660000","#660033","#660066","#660099", "#6600cc","#6600ff","#990000","#990033","#990066","#990099","#9900cc","#9900ff", "#cc0000","#cc0033","#cc0066","#cc0099","#cc00cc","#cc00ff","#ff0000","#ff0033", "#ff0066","#ff0099","#ff00cc","#ff00ff","#003300","#003333","#003366","#003399", "#0033cc","#0033ff","#333300","#333333","#333366","#333399","#3333cc","#3333ff", "#663300","#663333","#663366","#663399","#6633cc","#6633ff","#993300","#993333", "#993366","#993399","#9933cc","#9933ff","#cc3300","#cc3333","#cc3366","#cc3399", "#cc33cc","#cc33ff","#ff3300","#ff3333","#ff3366","#ff3399","#ff33cc","#ff33ff", "#006600","#006633","#006666","#006699","#0066cc","#0066ff","#336600","#336633", "#336666","#336699","#3366cc","#3366ff","#666600","#666633","#666666","#666699", "#6666cc","#6666ff","#996600","#996633","#996666","#996699","#9966cc","#9966ff", "#cc6600","#cc6633","#cc6666","#cc6699","#cc66cc","#cc66ff","#ff6600","#ff6633", "#ff6666","#ff6699","#ff66cc","#ff66ff","#009900","#009933","#009966","#009999", "#0099cc","#0099ff","#339900","#339933","#339966","#339999","#3399cc","#3399ff", "#669900","#669933","#669966","#669999","#6699cc","#6699ff","#999900","#999933", "#999966","#999999","#9999cc","#9999ff","#cc9900","#cc9933","#cc9966","#cc9999", "#cc99cc","#cc99ff","#ff9900","#ff9933","#ff9966","#ff9999","#ff99cc","#ff99ff", "#00cc00","#00cc33","#00cc66","#00cc99","#00cccc","#00ccff","#33cc00","#33cc33", "#33cc66","#33cc99","#33cccc","#33ccff","#66cc00","#66cc33","#66cc66","#66cc99", "#66cccc","#66ccff","#99cc00","#99cc33","#99cc66","#99cc99","#99cccc","#99ccff", "#cccc00","#cccc33","#cccc66","#cccc99","#cccccc","#ccccff","#ffcc00","#ffcc33", "#ffcc66","#ffcc99","#ffcccc","#ffccff","#00ff00","#00ff33","#00ff66","#00ff99", "#00ffcc","#00ffff","#33ff00","#33ff33","#33ff66","#33ff99","#33ffcc","#33ffff", "#66ff00","#66ff33","#66ff66","#66ff99","#66ffcc","#66ffff","#99ff00","#99ff33", "#99ff66","#99ff99","#99ffcc","#99ffff","#ccff00","#ccff33","#ccff66","#ccff99", "#ccffcc","#ccffff","#ffff00","#ffff33","#ffff66","#ffff99","#ffffcc","#ffffff" ]; var named = { '#F0F8FF':'Alice Blue','#FAEBD7':'Antique White','#00FFFF':'Aqua','#7FFFD4':'Aquamarine','#F0FFFF':'Azure','#F5F5DC':'Beige', '#FFE4C4':'Bisque','#000000':'Black','#FFEBCD':'Blanched Almond','#0000FF':'Blue','#8A2BE2':'Blue Violet','#A52A2A':'Brown', '#DEB887':'Burly Wood','#5F9EA0':'Cadet Blue','#7FFF00':'Chartreuse','#D2691E':'Chocolate','#FF7F50':'Coral','#6495ED':'Cornflower Blue', '#FFF8DC':'Cornsilk','#DC143C':'Crimson','#00FFFF':'Cyan','#00008B':'Dark Blue','#008B8B':'Dark Cyan','#B8860B':'Dark Golden Rod', '#A9A9A9':'Dark Gray','#A9A9A9':'Dark Grey','#006400':'Dark Green','#BDB76B':'Dark Khaki','#8B008B':'Dark Magenta','#556B2F':'Dark Olive Green', '#FF8C00':'Darkorange','#9932CC':'Dark Orchid','#8B0000':'Dark Red','#E9967A':'Dark Salmon','#8FBC8F':'Dark Sea Green','#483D8B':'Dark Slate Blue', '#2F4F4F':'Dark Slate Gray','#2F4F4F':'Dark Slate Grey','#00CED1':'Dark Turquoise','#9400D3':'Dark Violet','#FF1493':'Deep Pink','#00BFFF':'Deep Sky Blue', '#696969':'Dim Gray','#696969':'Dim Grey','#1E90FF':'Dodger Blue','#B22222':'Fire Brick','#FFFAF0':'Floral White','#228B22':'Forest Green', '#FF00FF':'Fuchsia','#DCDCDC':'Gainsboro','#F8F8FF':'Ghost White','#FFD700':'Gold','#DAA520':'Golden Rod','#808080':'Gray','#808080':'Grey', '#008000':'Green','#ADFF2F':'Green Yellow','#F0FFF0':'Honey Dew','#FF69B4':'Hot Pink','#CD5C5C':'Indian Red','#4B0082':'Indigo','#FFFFF0':'Ivory', '#F0E68C':'Khaki','#E6E6FA':'Lavender','#FFF0F5':'Lavender Blush','#7CFC00':'Lawn Green','#FFFACD':'Lemon Chiffon','#ADD8E6':'Light Blue', '#F08080':'Light Coral','#E0FFFF':'Light Cyan','#FAFAD2':'Light Golden Rod Yellow','#D3D3D3':'Light Gray','#D3D3D3':'Light Grey','#90EE90':'Light Green', '#FFB6C1':'Light Pink','#FFA07A':'Light Salmon','#20B2AA':'Light Sea Green','#87CEFA':'Light Sky Blue','#778899':'Light Slate Gray','#778899':'Light Slate Grey', '#B0C4DE':'Light Steel Blue','#FFFFE0':'Light Yellow','#00FF00':'Lime','#32CD32':'Lime Green','#FAF0E6':'Linen','#FF00FF':'Magenta','#800000':'Maroon', '#66CDAA':'Medium Aqua Marine','#0000CD':'Medium Blue','#BA55D3':'Medium Orchid','#9370D8':'Medium Purple','#3CB371':'Medium Sea Green','#7B68EE':'Medium Slate Blue', '#00FA9A':'Medium Spring Green','#48D1CC':'Medium Turquoise','#C71585':'Medium Violet Red','#191970':'Midnight Blue','#F5FFFA':'Mint Cream','#FFE4E1':'Misty Rose','#FFE4B5':'Moccasin', '#FFDEAD':'Navajo White','#000080':'Navy','#FDF5E6':'Old Lace','#808000':'Olive','#6B8E23':'Olive Drab','#FFA500':'Orange','#FF4500':'Orange Red','#DA70D6':'Orchid', '#EEE8AA':'Pale Golden Rod','#98FB98':'Pale Green','#AFEEEE':'Pale Turquoise','#D87093':'Pale Violet Red','#FFEFD5':'Papaya Whip','#FFDAB9':'Peach Puff', '#CD853F':'Peru','#FFC0CB':'Pink','#DDA0DD':'Plum','#B0E0E6':'Powder Blue','#800080':'Purple','#FF0000':'Red','#BC8F8F':'Rosy Brown','#4169E1':'Royal Blue', '#8B4513':'Saddle Brown','#FA8072':'Salmon','#F4A460':'Sandy Brown','#2E8B57':'Sea Green','#FFF5EE':'Sea Shell','#A0522D':'Sienna','#C0C0C0':'Silver', '#87CEEB':'Sky Blue','#6A5ACD':'Slate Blue','#708090':'Slate Gray','#708090':'Slate Grey','#FFFAFA':'Snow','#00FF7F':'Spring Green', '#4682B4':'Steel Blue','#D2B48C':'Tan','#008080':'Teal','#D8BFD8':'Thistle','#FF6347':'Tomato','#40E0D0':'Turquoise','#EE82EE':'Violet', '#F5DEB3':'Wheat','#FFFFFF':'White','#F5F5F5':'White Smoke','#FFFF00':'Yellow','#9ACD32':'Yellow Green' }; var namedLookup = {}; function init() { var inputColor = convertRGBToHex(tinyMCEPopup.getWindowArg('input_color')), key, value; tinyMCEPopup.resizeToInnerSize(); generatePicker(); generateWebColors(); generateNamedColors(); if (inputColor) { changeFinalColor(inputColor); col = convertHexToRGB(inputColor); if (col) updateLight(col.r, col.g, col.b); } for (key in named) { value = named[key]; namedLookup[value.replace(/\s+/, '').toLowerCase()] = key.replace(/#/, '').toLowerCase(); } } function toHexColor(color) { var matches, red, green, blue, toInt = parseInt; function hex(value) { value = parseInt(value).toString(16); return value.length > 1 ? value : '0' + value; // Padd with leading zero }; color = tinymce.trim(color); color = color.replace(/^[#]/, '').toLowerCase(); // remove leading '#' color = namedLookup[color] || color; matches = /^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/.exec(color); if (matches) { red = toInt(matches[1]); green = toInt(matches[2]); blue = toInt(matches[3]); } else { matches = /^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/.exec(color); if (matches) { red = toInt(matches[1], 16); green = toInt(matches[2], 16); blue = toInt(matches[3], 16); } else { matches = /^([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(color); if (matches) { red = toInt(matches[1] + matches[1], 16); green = toInt(matches[2] + matches[2], 16); blue = toInt(matches[3] + matches[3], 16); } else { return ''; } } } return '#' + hex(red) + hex(green) + hex(blue); } function insertAction() { var color = document.getElementById("color").value, f = tinyMCEPopup.getWindowArg('func'); var hexColor = toHexColor(color); if (hexColor === '') { var text = tinyMCEPopup.editor.getLang('advanced_dlg.invalid_color_value'); tinyMCEPopup.alert(text + ': ' + color); } else { tinyMCEPopup.restoreSelection(); if (f) f(hexColor); tinyMCEPopup.close(); } } function showColor(color, name) { if (name) document.getElementById("colorname").innerHTML = name; document.getElementById("preview").style.backgroundColor = color; document.getElementById("color").value = color.toUpperCase(); } function convertRGBToHex(col) { var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); if (!col) return col; var rgb = col.replace(re, "$1,$2,$3").split(','); if (rgb.length == 3) { r = parseInt(rgb[0]).toString(16); g = parseInt(rgb[1]).toString(16); b = parseInt(rgb[2]).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; return "#" + r + g + b; } return col; } function convertHexToRGB(col) { if (col.indexOf('#') != -1) { col = col.replace(new RegExp('[^0-9A-F]', 'gi'), ''); r = parseInt(col.substring(0, 2), 16); g = parseInt(col.substring(2, 4), 16); b = parseInt(col.substring(4, 6), 16); return {r : r, g : g, b : b}; } return null; } function generatePicker() { var el = document.getElementById('light'), h = '', i; for (i = 0; i < detail; i++){ h += '<div id="gs'+i+'" style="background-color:#000000; width:15px; height:3px; border-style:none; border-width:0px;"' + ' onclick="changeFinalColor(this.style.backgroundColor)"' + ' onmousedown="isMouseDown = true; return false;"' + ' onmouseup="isMouseDown = false;"' + ' onmousemove="if (isMouseDown && isMouseOver) changeFinalColor(this.style.backgroundColor); return false;"' + ' onmouseover="isMouseOver = true;"' + ' onmouseout="isMouseOver = false;"' + '></div>'; } el.innerHTML = h; } function generateWebColors() { var el = document.getElementById('webcolors'), h = '', i; if (el.className == 'generated') return; // TODO: VoiceOver doesn't seem to support legend as a label referenced by labelledby. h += '<div role="listbox" aria-labelledby="webcolors_title" tabindex="0"><table role="presentation" border="0" cellspacing="1" cellpadding="0">' + '<tr>'; for (i=0; i<colors.length; i++) { h += '<td bgcolor="' + colors[i] + '" width="10" height="10">' + '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="web_colors_' + i + '" onfocus="showColor(\'' + colors[i] + '\');" onmouseover="showColor(\'' + colors[i] + '\');" style="display:block;width:10px;height:10px;overflow:hidden;">'; if (tinyMCEPopup.editor.forcedHighContrastMode) { h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>'; } h += '<span class="mceVoiceLabel" style="display:none;" id="web_colors_' + i + '">' + colors[i].toUpperCase() + '</span>'; h += '</a></td>'; if ((i+1) % 18 == 0) h += '</tr><tr>'; } h += '</table></div>'; el.innerHTML = h; el.className = 'generated'; paintCanvas(el); enableKeyboardNavigation(el.firstChild); } function paintCanvas(el) { tinyMCEPopup.getWin().tinymce.each(tinyMCEPopup.dom.select('canvas.mceColorSwatch', el), function(canvas) { var context; if (canvas.getContext && (context = canvas.getContext("2d"))) { context.fillStyle = canvas.getAttribute('data-color'); context.fillRect(0, 0, 10, 10); } }); } function generateNamedColors() { var el = document.getElementById('namedcolors'), h = '', n, v, i = 0; if (el.className == 'generated') return; for (n in named) { v = named[n]; h += '<a href="javascript:insertAction();" role="option" tabindex="-1" aria-labelledby="named_colors_' + i + '" onfocus="showColor(\'' + n + '\',\'' + v + '\');" onmouseover="showColor(\'' + n + '\',\'' + v + '\');" style="background-color: ' + n + '">'; if (tinyMCEPopup.editor.forcedHighContrastMode) { h += '<canvas class="mceColorSwatch" height="10" width="10" data-color="' + colors[i] + '"></canvas>'; } h += '<span class="mceVoiceLabel" style="display:none;" id="named_colors_' + i + '">' + v + '</span>'; h += '</a>'; i++; } el.innerHTML = h; el.className = 'generated'; paintCanvas(el); enableKeyboardNavigation(el); } function enableKeyboardNavigation(el) { tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', { root: el, items: tinyMCEPopup.dom.select('a', el) }, tinyMCEPopup.dom); } function dechex(n) { return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16); } function computeColor(e) { var x, y, partWidth, partDetail, imHeight, r, g, b, coef, i, finalCoef, finalR, finalG, finalB, pos = tinyMCEPopup.dom.getPos(e.target); x = e.offsetX ? e.offsetX : (e.target ? e.clientX - pos.x : 0); y = e.offsetY ? e.offsetY : (e.target ? e.clientY - pos.y : 0); partWidth = document.getElementById('colors').width / 6; partDetail = detail / 2; imHeight = document.getElementById('colors').height; r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255; g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255 + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth); b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth); coef = (imHeight - y) / imHeight; r = 128 + (r - 128) * coef; g = 128 + (g - 128) * coef; b = 128 + (b - 128) * coef; changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b)); updateLight(r, g, b); } function updateLight(r, g, b) { var i, partDetail = detail / 2, finalCoef, finalR, finalG, finalB, color; for (i=0; i<detail; i++) { if ((i>=0) && (i<partDetail)) { finalCoef = i / partDetail; finalR = dechex(255 - (255 - r) * finalCoef); finalG = dechex(255 - (255 - g) * finalCoef); finalB = dechex(255 - (255 - b) * finalCoef); } else { finalCoef = 2 - i / partDetail; finalR = dechex(r * finalCoef); finalG = dechex(g * finalCoef); finalB = dechex(b * finalCoef); } color = finalR + finalG + finalB; setCol('gs' + i, '#'+color); } } function changeFinalColor(color) { if (color.indexOf('#') == -1) color = convertRGBToHex(color); setCol('preview', color); document.getElementById('color').value = color; } function setCol(e, c) { try { document.getElementById(e).style.backgroundColor = c; } catch (ex) { // Ignore IE warning } } tinyMCEPopup.onInit.add(init);
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/js/color_picker.js
JavaScript
asf20
14,214
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{#advanced_dlg.accessibility_help}</title> <script type="text/javascript" src="../../tiny_mce_popup.js?ver=358-20121205"></script> <script type="text/javascript">tinyMCEPopup.requireLangPack();</script> </head> <body id="content"> <h1>{#advanced_dlg.accessibility_usage_title}</h1> <h2>Toolbars</h2> <p>Press ALT-F10 to move focus to the toolbars. Navigate through the buttons using the arrow keys. Press enter to activate a button and return focus to the editor. Press escape to return focus to the editor without performing any actions.</p> <h2>Status Bar</h2> <p>To access the editor status bar, press ALT-F11. Use the left and right arrow keys to navigate between elements in the path. Press enter or space to select an element. Press escape to return focus to the editor without changing the selection.</p> <h2>Context Menu</h2> <p>Press shift-F10 to activate the context menu. Use the up and down arrow keys to move between menu items. To open sub-menus press the right arrow key. To close submenus press the left arrow key. Press escape to close the context menu.</p> <h1>Keyboard Shortcuts</h1> <table> <thead> <tr> <th>Keystroke</th> <th>Function</th> </tr> </thead> <tbody> <tr> <td>Control-B</td><td>Bold</td> </tr> <tr> <td>Control-I</td><td>Italic</td> </tr> <tr> <td>Control-Z</td><td>Undo</td> </tr> <tr> <td>Control-Y</td><td>Redo</td> </tr> </tbody> </table> </body> </html>
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/shortcuts.htm
HTML
asf20
1,702
/** * editor_template_src.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ (function(tinymce) { var DOM = tinymce.DOM, Event = tinymce.dom.Event, extend = tinymce.extend, each = tinymce.each, Cookie = tinymce.util.Cookie, lastExtID, explode = tinymce.explode; // Generates a preview for a format function getPreviewCss(ed, fmt) { var name, previewElm, dom = ed.dom, previewCss = '', parentFontSize, previewStylesName; previewStyles = ed.settings.preview_styles; // No preview forced if (previewStyles === false) return ''; // Default preview if (!previewStyles) previewStyles = 'font-family font-size font-weight text-decoration text-transform color background-color'; // Removes any variables since these can't be previewed function removeVars(val) { return val.replace(/%(\w+)/g, ''); }; // Create block/inline element to use for preview name = fmt.block || fmt.inline || 'span'; previewElm = dom.create(name); // Add format styles to preview element each(fmt.styles, function(value, name) { value = removeVars(value); if (value) dom.setStyle(previewElm, name, value); }); // Add attributes to preview element each(fmt.attributes, function(value, name) { value = removeVars(value); if (value) dom.setAttrib(previewElm, name, value); }); // Add classes to preview element each(fmt.classes, function(value) { value = removeVars(value); if (!dom.hasClass(previewElm, value)) dom.addClass(previewElm, value); }); // Add the previewElm outside the visual area dom.setStyles(previewElm, {position: 'absolute', left: -0xFFFF}); ed.getBody().appendChild(previewElm); // Get parent container font size so we can compute px values out of em/% for older IE:s parentFontSize = dom.getStyle(ed.getBody(), 'fontSize', true); parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0; each(previewStyles.split(' '), function(name) { var value = dom.getStyle(previewElm, name, true); // If background is transparent then check if the body has a background color we can use if (name == 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) { value = dom.getStyle(ed.getBody(), name, true); // Ignore white since it's the default color, not the nicest fix if (dom.toHex(value).toLowerCase() == '#ffffff') { return; } } // Old IE won't calculate the font size so we need to do that manually if (name == 'font-size') { if (/em|%$/.test(value)) { if (parentFontSize === 0) { return; } // Convert font size from em/% to px value = parseFloat(value, 10) / (/%$/.test(value) ? 100 : 1); value = (value * parentFontSize) + 'px'; } } previewCss += name + ':' + value + ';'; }); dom.remove(previewElm); return previewCss; }; // Tell it to load theme specific language pack(s) tinymce.ThemeManager.requireLangPack('advanced'); tinymce.create('tinymce.themes.AdvancedTheme', { sizes : [8, 10, 12, 14, 18, 24, 36], // Control name lookup, format: title, command controls : { bold : ['bold_desc', 'Bold'], italic : ['italic_desc', 'Italic'], underline : ['underline_desc', 'Underline'], strikethrough : ['striketrough_desc', 'Strikethrough'], justifyleft : ['justifyleft_desc', 'JustifyLeft'], justifycenter : ['justifycenter_desc', 'JustifyCenter'], justifyright : ['justifyright_desc', 'JustifyRight'], justifyfull : ['justifyfull_desc', 'JustifyFull'], bullist : ['bullist_desc', 'InsertUnorderedList'], numlist : ['numlist_desc', 'InsertOrderedList'], outdent : ['outdent_desc', 'Outdent'], indent : ['indent_desc', 'Indent'], cut : ['cut_desc', 'Cut'], copy : ['copy_desc', 'Copy'], paste : ['paste_desc', 'Paste'], undo : ['undo_desc', 'Undo'], redo : ['redo_desc', 'Redo'], link : ['link_desc', 'mceLink'], unlink : ['unlink_desc', 'unlink'], image : ['image_desc', 'mceImage'], cleanup : ['cleanup_desc', 'mceCleanup'], help : ['help_desc', 'mceHelp'], code : ['code_desc', 'mceCodeEditor'], hr : ['hr_desc', 'InsertHorizontalRule'], removeformat : ['removeformat_desc', 'RemoveFormat'], sub : ['sub_desc', 'subscript'], sup : ['sup_desc', 'superscript'], forecolor : ['forecolor_desc', 'ForeColor'], forecolorpicker : ['forecolor_desc', 'mceForeColor'], backcolor : ['backcolor_desc', 'HiliteColor'], backcolorpicker : ['backcolor_desc', 'mceBackColor'], charmap : ['charmap_desc', 'mceCharMap'], visualaid : ['visualaid_desc', 'mceToggleVisualAid'], anchor : ['anchor_desc', 'mceInsertAnchor'], newdocument : ['newdocument_desc', 'mceNewDocument'], blockquote : ['blockquote_desc', 'mceBlockQuote'] }, stateControls : ['bold', 'italic', 'underline', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'sub', 'sup', 'blockquote'], init : function(ed, url) { var t = this, s, v, o; t.editor = ed; t.url = url; t.onResolveName = new tinymce.util.Dispatcher(this); s = ed.settings; ed.forcedHighContrastMode = ed.settings.detect_highcontrast && t._isHighContrast(); ed.settings.skin = ed.forcedHighContrastMode ? 'highcontrast' : ed.settings.skin; // Setup default buttons if (!s.theme_advanced_buttons1) { s = extend({ theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect", theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code", theme_advanced_buttons3 : "hr,removeformat,visualaid,|,sub,sup,|,charmap" }, s); } // Default settings t.settings = s = extend({ theme_advanced_path : true, theme_advanced_toolbar_location : 'top', theme_advanced_blockformats : "p,address,pre,h1,h2,h3,h4,h5,h6", theme_advanced_toolbar_align : "left", theme_advanced_statusbar_location : "bottom", theme_advanced_fonts : "Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats", theme_advanced_more_colors : 1, theme_advanced_row_height : 23, theme_advanced_resize_horizontal : 1, theme_advanced_resizing_use_cookie : 1, theme_advanced_font_sizes : "1,2,3,4,5,6,7", theme_advanced_font_selector : "span", theme_advanced_show_current_color: 0, readonly : ed.settings.readonly }, s); // Setup default font_size_style_values if (!s.font_size_style_values) s.font_size_style_values = "8pt,10pt,12pt,14pt,18pt,24pt,36pt"; if (tinymce.is(s.theme_advanced_font_sizes, 'string')) { s.font_size_style_values = tinymce.explode(s.font_size_style_values); s.font_size_classes = tinymce.explode(s.font_size_classes || ''); // Parse string value o = {}; ed.settings.theme_advanced_font_sizes = s.theme_advanced_font_sizes; each(ed.getParam('theme_advanced_font_sizes', '', 'hash'), function(v, k) { var cl; if (k == v && v >= 1 && v <= 7) { k = v + ' (' + t.sizes[v - 1] + 'pt)'; cl = s.font_size_classes[v - 1]; v = s.font_size_style_values[v - 1] || (t.sizes[v - 1] + 'pt'); } if (/^\s*\./.test(v)) cl = v.replace(/\./g, ''); o[k] = cl ? {'class' : cl} : {fontSize : v}; }); s.theme_advanced_font_sizes = o; } if ((v = s.theme_advanced_path_location) && v != 'none') s.theme_advanced_statusbar_location = s.theme_advanced_path_location; if (s.theme_advanced_statusbar_location == 'none') s.theme_advanced_statusbar_location = 0; if (ed.settings.content_css !== false) ed.contentCSS.push(ed.baseURI.toAbsolute(url + "/skins/" + ed.settings.skin + "/content.css")); // Init editor ed.onInit.add(function() { if (!ed.settings.readonly) { ed.onNodeChange.add(t._nodeChanged, t); ed.onKeyUp.add(t._updateUndoStatus, t); ed.onMouseUp.add(t._updateUndoStatus, t); ed.dom.bind(ed.dom.getRoot(), 'dragend', function() { t._updateUndoStatus(ed); }); } }); ed.onSetProgressState.add(function(ed, b, ti) { var co, id = ed.id, tb; if (b) { t.progressTimer = setTimeout(function() { co = ed.getContainer(); co = co.insertBefore(DOM.create('DIV', {style : 'position:relative'}), co.firstChild); tb = DOM.get(ed.id + '_tbl'); DOM.add(co, 'div', {id : id + '_blocker', 'class' : 'mceBlocker', style : {width : tb.clientWidth + 2, height : tb.clientHeight + 2}}); DOM.add(co, 'div', {id : id + '_progress', 'class' : 'mceProgress', style : {left : tb.clientWidth / 2, top : tb.clientHeight / 2}}); }, ti || 0); } else { DOM.remove(id + '_blocker'); DOM.remove(id + '_progress'); clearTimeout(t.progressTimer); } }); DOM.loadCSS(s.editor_css ? ed.documentBaseURI.toAbsolute(s.editor_css) : url + "/skins/" + ed.settings.skin + "/ui.css"); if (s.skin_variant) DOM.loadCSS(url + "/skins/" + ed.settings.skin + "/ui_" + s.skin_variant + ".css"); }, _isHighContrast : function() { var actualColor, div = DOM.add(DOM.getRoot(), 'div', {'style': 'background-color: rgb(171,239,86);'}); actualColor = (DOM.getStyle(div, 'background-color', true) + '').toLowerCase().replace(/ /g, ''); DOM.remove(div); return actualColor != 'rgb(171,239,86)' && actualColor != '#abef56'; }, createControl : function(n, cf) { var cd, c; if (c = cf.createControl(n)) return c; switch (n) { case "styleselect": return this._createStyleSelect(); case "formatselect": return this._createBlockFormats(); case "fontselect": return this._createFontSelect(); case "fontsizeselect": return this._createFontSizeSelect(); case "forecolor": return this._createForeColorMenu(); case "backcolor": return this._createBackColorMenu(); } if ((cd = this.controls[n])) return cf.createButton(n, {title : "advanced." + cd[0], cmd : cd[1], ui : cd[2], value : cd[3]}); }, execCommand : function(cmd, ui, val) { var f = this['_' + cmd]; if (f) { f.call(this, ui, val); return true; } return false; }, _importClasses : function(e) { var ed = this.editor, ctrl = ed.controlManager.get('styleselect'); if (ctrl.getLength() == 0) { each(ed.dom.getClasses(), function(o, idx) { var name = 'style_' + idx, fmt; fmt = { inline : 'span', attributes : {'class' : o['class']}, selector : '*' }; ed.formatter.register(name, fmt); ctrl.add(o['class'], name, { style: function() { return getPreviewCss(ed, fmt); } }); }); } }, _createStyleSelect : function(n) { var t = this, ed = t.editor, ctrlMan = ed.controlManager, ctrl; // Setup style select box ctrl = ctrlMan.createListBox('styleselect', { title : 'advanced.style_select', onselect : function(name) { var matches, formatNames = [], removedFormat; each(ctrl.items, function(item) { formatNames.push(item.value); }); ed.focus(); ed.undoManager.add(); // Toggle off the current format(s) matches = ed.formatter.matchAll(formatNames); tinymce.each(matches, function(match) { if (!name || match == name) { if (match) ed.formatter.remove(match); removedFormat = true; } }); if (!removedFormat) ed.formatter.apply(name); ed.undoManager.add(); ed.nodeChanged(); return false; // No auto select } }); // Handle specified format ed.onPreInit.add(function() { var counter = 0, formats = ed.getParam('style_formats'); if (formats) { each(formats, function(fmt) { var name, keys = 0; each(fmt, function() {keys++;}); if (keys > 1) { name = fmt.name = fmt.name || 'style_' + (counter++); ed.formatter.register(name, fmt); ctrl.add(fmt.title, name, { style: function() { return getPreviewCss(ed, fmt); } }); } else ctrl.add(fmt.title); }); } else { each(ed.getParam('theme_advanced_styles', '', 'hash'), function(val, key) { var name, fmt; if (val) { name = 'style_' + (counter++); fmt = { inline : 'span', classes : val, selector : '*' }; ed.formatter.register(name, fmt); ctrl.add(t.editor.translate(key), name, { style: function() { return getPreviewCss(ed, fmt); } }); } }); } }); // Auto import classes if the ctrl box is empty if (ctrl.getLength() == 0) { ctrl.onPostRender.add(function(ed, n) { if (!ctrl.NativeListBox) { Event.add(n.id + '_text', 'focus', t._importClasses, t); Event.add(n.id + '_text', 'mousedown', t._importClasses, t); Event.add(n.id + '_open', 'focus', t._importClasses, t); Event.add(n.id + '_open', 'mousedown', t._importClasses, t); } else Event.add(n.id, 'focus', t._importClasses, t); }); } return ctrl; }, _createFontSelect : function() { var c, t = this, ed = t.editor; c = ed.controlManager.createListBox('fontselect', { title : 'advanced.fontdefault', onselect : function(v) { var cur = c.items[c.selectedIndex]; if (!v && cur) { ed.execCommand('FontName', false, cur.value); return; } ed.execCommand('FontName', false, v); // Fake selection, execCommand will fire a nodeChange and update the selection c.select(function(sv) { return v == sv; }); if (cur && cur.value == v) { c.select(null); } return false; // No auto select } }); if (c) { each(ed.getParam('theme_advanced_fonts', t.settings.theme_advanced_fonts, 'hash'), function(v, k) { c.add(ed.translate(k), v, {style : v.indexOf('dings') == -1 ? 'font-family:' + v : ''}); }); } return c; }, _createFontSizeSelect : function() { var t = this, ed = t.editor, c, i = 0, cl = []; c = ed.controlManager.createListBox('fontsizeselect', {title : 'advanced.font_size', onselect : function(v) { var cur = c.items[c.selectedIndex]; if (!v && cur) { cur = cur.value; if (cur['class']) { ed.formatter.toggle('fontsize_class', {value : cur['class']}); ed.undoManager.add(); ed.nodeChanged(); } else { ed.execCommand('FontSize', false, cur.fontSize); } return; } if (v['class']) { ed.focus(); ed.undoManager.add(); ed.formatter.toggle('fontsize_class', {value : v['class']}); ed.undoManager.add(); ed.nodeChanged(); } else ed.execCommand('FontSize', false, v.fontSize); // Fake selection, execCommand will fire a nodeChange and update the selection c.select(function(sv) { return v == sv; }); if (cur && (cur.value.fontSize == v.fontSize || cur.value['class'] && cur.value['class'] == v['class'])) { c.select(null); } return false; // No auto select }}); if (c) { each(t.settings.theme_advanced_font_sizes, function(v, k) { var fz = v.fontSize; if (fz >= 1 && fz <= 7) fz = t.sizes[parseInt(fz) - 1] + 'pt'; c.add(k, v, {'style' : 'font-size:' + fz, 'class' : 'mceFontSize' + (i++) + (' ' + (v['class'] || ''))}); }); } return c; }, _createBlockFormats : function() { var c, fmts = { p : 'advanced.paragraph', address : 'advanced.address', pre : 'advanced.pre', h1 : 'advanced.h1', h2 : 'advanced.h2', h3 : 'advanced.h3', h4 : 'advanced.h4', h5 : 'advanced.h5', h6 : 'advanced.h6', div : 'advanced.div', blockquote : 'advanced.blockquote', code : 'advanced.code', dt : 'advanced.dt', dd : 'advanced.dd', samp : 'advanced.samp' }, t = this; c = t.editor.controlManager.createListBox('formatselect', {title : 'advanced.block', onselect : function(v) { t.editor.execCommand('FormatBlock', false, v); return false; }}); if (c) { each(t.editor.getParam('theme_advanced_blockformats', t.settings.theme_advanced_blockformats, 'hash'), function(v, k) { c.add(t.editor.translate(k != v ? k : fmts[v]), v, {'class' : 'mce_formatPreview mce_' + v, style: function() { return getPreviewCss(t.editor, {block: v}); }}); }); } return c; }, _createForeColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_text_colors) o.colors = v; if (s.theme_advanced_default_foreground_color) o.default_color = s.theme_advanced_default_foreground_color; o.title = 'advanced.forecolor_desc'; o.cmd = 'ForeColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('forecolor', o); return c; }, _createBackColorMenu : function() { var c, t = this, s = t.settings, o = {}, v; if (s.theme_advanced_more_colors) { o.more_colors_func = function() { t._mceColorPicker(0, { color : c.value, func : function(co) { c.setColor(co); } }); }; } if (v = s.theme_advanced_background_colors) o.colors = v; if (s.theme_advanced_default_background_color) o.default_color = s.theme_advanced_default_background_color; o.title = 'advanced.backcolor_desc'; o.cmd = 'HiliteColor'; o.scope = this; c = t.editor.controlManager.createColorSplitButton('backcolor', o); return c; }, renderUI : function(o) { var n, ic, tb, t = this, ed = t.editor, s = t.settings, sc, p, nl; if (ed.settings) { ed.settings.aria_label = s.aria_label + ed.getLang('advanced.help_shortcut'); } // TODO: ACC Should have an aria-describedby attribute which is user-configurable to describe what this field is actually for. // Maybe actually inherit it from the original textara? n = p = DOM.create('span', {role : 'application', 'aria-labelledby' : ed.id + '_voice', id : ed.id + '_parent', 'class' : 'mceEditor ' + ed.settings.skin + 'Skin' + (s.skin_variant ? ' ' + ed.settings.skin + 'Skin' + t._ufirst(s.skin_variant) : '') + (ed.settings.directionality == "rtl" ? ' mceRtl' : '')}); DOM.add(n, 'span', {'class': 'mceVoiceLabel', 'style': 'display:none;', id: ed.id + '_voice'}, s.aria_label); if (!DOM.boxModel) n = DOM.add(n, 'div', {'class' : 'mceOldBoxModel'}); n = sc = DOM.add(n, 'table', {role : "presentation", id : ed.id + '_tbl', 'class' : 'mceLayout', cellSpacing : 0, cellPadding : 0}); n = tb = DOM.add(n, 'tbody'); switch ((s.theme_advanced_layout_manager || '').toLowerCase()) { case "rowlayout": ic = t._rowLayout(s, tb, o); break; case "customlayout": ic = ed.execCallback("theme_advanced_custom_layout", s, tb, o, p); break; default: ic = t._simpleLayout(s, tb, o, p); } n = o.targetNode; // Add classes to first and last TRs nl = sc.rows; DOM.addClass(nl[0], 'mceFirst'); DOM.addClass(nl[nl.length - 1], 'mceLast'); // Add classes to first and last TDs each(DOM.select('tr', tb), function(n) { DOM.addClass(n.firstChild, 'mceFirst'); DOM.addClass(n.childNodes[n.childNodes.length - 1], 'mceLast'); }); if (DOM.get(s.theme_advanced_toolbar_container)) DOM.get(s.theme_advanced_toolbar_container).appendChild(p); else DOM.insertAfter(p, n); Event.add(ed.id + '_path_row', 'click', function(e) { e = e.target; if (e.nodeName == 'A') { t._sel(e.className.replace(/^.*mcePath_([0-9]+).*$/, '$1')); return false; } }); /* if (DOM.get(ed.id + '_path_row')) { Event.add(ed.id + '_tbl', 'mouseover', function(e) { var re; e = e.target; if (e.nodeName == 'SPAN' && DOM.hasClass(e.parentNode, 'mceButton')) { re = DOM.get(ed.id + '_path_row'); t.lastPath = re.innerHTML; DOM.setHTML(re, e.parentNode.title); } }); Event.add(ed.id + '_tbl', 'mouseout', function(e) { if (t.lastPath) { DOM.setHTML(ed.id + '_path_row', t.lastPath); t.lastPath = 0; } }); } */ if (!ed.getParam('accessibility_focus')) Event.add(DOM.add(p, 'a', {href : '#'}, '<!-- IE -->'), 'focus', function() {tinyMCE.get(ed.id).focus();}); if (s.theme_advanced_toolbar_location == 'external') o.deltaHeight = 0; t.deltaHeight = o.deltaHeight; o.targetNode = null; ed.onKeyDown.add(function(ed, evt) { var DOM_VK_F10 = 121, DOM_VK_F11 = 122; if (evt.altKey) { if (evt.keyCode === DOM_VK_F10) { // Make sure focus is given to toolbar in Safari. // We can't do this in IE as it prevents giving focus to toolbar when editor is in a frame if (tinymce.isWebKit) { window.focus(); } t.toolbarGroup.focus(); return Event.cancel(evt); } else if (evt.keyCode === DOM_VK_F11) { DOM.get(ed.id + '_path_row').focus(); return Event.cancel(evt); } } }); // alt+0 is the UK recommended shortcut for accessing the list of access controls. ed.addShortcut('alt+0', '', 'mceShortcuts', t); return { iframeContainer : ic, editorContainer : ed.id + '_parent', sizeContainer : sc, deltaHeight : o.deltaHeight }; }, getInfo : function() { return { longname : 'Advanced theme', author : 'Moxiecode Systems AB', authorurl : 'http://tinymce.moxiecode.com', version : tinymce.majorVersion + "." + tinymce.minorVersion } }, resizeBy : function(dw, dh) { var e = DOM.get(this.editor.id + '_ifr'); this.resizeTo(e.clientWidth + dw, e.clientHeight + dh); }, resizeTo : function(w, h, store) { var ed = this.editor, s = this.settings, e = DOM.get(ed.id + '_tbl'), ifr = DOM.get(ed.id + '_ifr'); // Boundery fix box w = Math.max(s.theme_advanced_resizing_min_width || 100, w); h = Math.max(s.theme_advanced_resizing_min_height || 100, h); w = Math.min(s.theme_advanced_resizing_max_width || 0xFFFF, w); h = Math.min(s.theme_advanced_resizing_max_height || 0xFFFF, h); // Resize iframe and container DOM.setStyle(e, 'height', ''); DOM.setStyle(ifr, 'height', h); if (s.theme_advanced_resize_horizontal) { DOM.setStyle(e, 'width', ''); DOM.setStyle(ifr, 'width', w); // Make sure that the size is never smaller than the over all ui if (w < e.clientWidth) { w = e.clientWidth; DOM.setStyle(ifr, 'width', e.clientWidth); } } // Store away the size if (store && s.theme_advanced_resizing_use_cookie) { Cookie.setHash("TinyMCE_" + ed.id + "_size", { cw : w, ch : h }); } }, destroy : function() { var id = this.editor.id; Event.clear(id + '_resize'); Event.clear(id + '_path_row'); Event.clear(id + '_external_close'); }, // Internal functions _simpleLayout : function(s, tb, o, p) { var t = this, ed = t.editor, lo = s.theme_advanced_toolbar_location, sl = s.theme_advanced_statusbar_location, n, ic, etb, c; if (s.readonly) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); return ic; } // Create toolbar container at top if (lo == 'top') t._addToolbars(tb, o); // Create external toolbar if (lo == 'external') { n = c = DOM.create('div', {style : 'position:relative'}); n = DOM.add(n, 'div', {id : ed.id + '_external', 'class' : 'mceExternalToolbar'}); DOM.add(n, 'a', {id : ed.id + '_external_close', href : 'javascript:;', 'class' : 'mceExternalClose'}); n = DOM.add(n, 'table', {id : ed.id + '_tblext', cellSpacing : 0, cellPadding : 0}); etb = DOM.add(n, 'tbody'); if (p.firstChild.className == 'mceOldBoxModel') p.firstChild.appendChild(c); else p.insertBefore(c, p.firstChild); t._addToolbars(etb, o); ed.onMouseUp.add(function() { var e = DOM.get(ed.id + '_external'); DOM.show(e); DOM.hide(lastExtID); var f = Event.add(ed.id + '_external_close', 'click', function() { DOM.hide(ed.id + '_external'); Event.remove(ed.id + '_external_close', 'click', f); return false; }); DOM.show(e); DOM.setStyle(e, 'top', 0 - DOM.getRect(ed.id + '_tblext').h - 1); // Fixes IE rendering bug DOM.hide(e); DOM.show(e); e.style.filter = ''; lastExtID = ed.id + '_external'; e = null; }); } if (sl == 'top') t._addStatusBar(tb, o); // Create iframe container if (!s.theme_advanced_toolbar_container) { n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); } // Create toolbar container at bottom if (lo == 'bottom') t._addToolbars(tb, o); if (sl == 'bottom') t._addStatusBar(tb, o); return ic; }, _rowLayout : function(s, tb, o) { var t = this, ed = t.editor, dc, da, cf = ed.controlManager, n, ic, to, a; dc = s.theme_advanced_containers_default_class || ''; da = s.theme_advanced_containers_default_align || 'center'; each(explode(s.theme_advanced_containers || ''), function(c, i) { var v = s['theme_advanced_container_' + c] || ''; switch (c.toLowerCase()) { case 'mceeditor': n = DOM.add(tb, 'tr'); n = ic = DOM.add(n, 'td', {'class' : 'mceIframeContainer'}); break; case 'mceelementpath': t._addStatusBar(tb, o); break; default: a = (s['theme_advanced_container_' + c + '_align'] || da).toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(tb, 'tr'), 'td', { 'class' : 'mceToolbar ' + (s['theme_advanced_container_' + c + '_class'] || dc) + ' ' + a || da }); to = cf.createToolbar("toolbar" + i); t._addControls(v, to); DOM.setHTML(n, to.renderHTML()); o.deltaHeight -= s.theme_advanced_row_height; } }); return ic; }, _addControls : function(v, tb) { var t = this, s = t.settings, di, cf = t.editor.controlManager; if (s.theme_advanced_disable && !t._disabled) { di = {}; each(explode(s.theme_advanced_disable), function(v) { di[v] = 1; }); t._disabled = di; } else di = t._disabled; each(explode(v), function(n) { var c; if (di && di[n]) return; // Compatiblity with 2.x if (n == 'tablecontrols') { each(["table","|","row_props","cell_props","|","row_before","row_after","delete_row","|","col_before","col_after","delete_col","|","split_cells","merge_cells"], function(n) { n = t.createControl(n, cf); if (n) tb.add(n); }); return; } c = t.createControl(n, cf); if (c) tb.add(c); }); }, _addToolbars : function(c, o) { var t = this, i, tb, ed = t.editor, s = t.settings, v, cf = ed.controlManager, di, n, h = [], a, toolbarGroup, toolbarsExist = false; toolbarGroup = cf.createToolbarGroup('toolbargroup', { 'name': ed.getLang('advanced.toolbar'), 'tab_focus_toolbar':ed.getParam('theme_advanced_tab_focus_toolbar') }); t.toolbarGroup = toolbarGroup; a = s.theme_advanced_toolbar_align.toLowerCase(); a = 'mce' + t._ufirst(a); n = DOM.add(DOM.add(c, 'tr', {role: 'presentation'}), 'td', {'class' : 'mceToolbar ' + a, "role":"toolbar"}); // Create toolbar and add the controls for (i=1; (v = s['theme_advanced_buttons' + i]); i++) { toolbarsExist = true; tb = cf.createToolbar("toolbar" + i, {'class' : 'mceToolbarRow' + i}); if (s['theme_advanced_buttons' + i + '_add']) v += ',' + s['theme_advanced_buttons' + i + '_add']; if (s['theme_advanced_buttons' + i + '_add_before']) v = s['theme_advanced_buttons' + i + '_add_before'] + ',' + v; t._addControls(v, tb); toolbarGroup.add(tb); o.deltaHeight -= s.theme_advanced_row_height; } // Handle case when there are no toolbar buttons and ensure editor height is adjusted accordingly if (!toolbarsExist) o.deltaHeight -= s.theme_advanced_row_height; h.push(toolbarGroup.renderHTML()); h.push(DOM.createHTML('a', {href : '#', accesskey : 'z', title : ed.getLang("advanced.toolbar_focus"), onfocus : 'tinyMCE.getInstanceById(\'' + ed.id + '\').focus();'}, '<!-- IE -->')); DOM.setHTML(n, h.join('')); }, _addStatusBar : function(tb, o) { var n, t = this, ed = t.editor, s = t.settings, r, mf, me, td; n = DOM.add(tb, 'tr'); n = td = DOM.add(n, 'td', {'class' : 'mceStatusbar'}); n = DOM.add(n, 'div', {id : ed.id + '_path_row', 'role': 'group', 'aria-labelledby': ed.id + '_path_voice'}); if (s.theme_advanced_path) { DOM.add(n, 'span', {id: ed.id + '_path_voice'}, ed.translate('advanced.path')); DOM.add(n, 'span', {}, ': '); } else { DOM.add(n, 'span', {}, '&#160;'); } if (s.theme_advanced_resizing) { DOM.add(td, 'a', {id : ed.id + '_resize', href : 'javascript:;', onclick : "return false;", 'class' : 'mceResize', tabIndex:"-1"}); if (s.theme_advanced_resizing_use_cookie) { ed.onPostRender.add(function() { var o = Cookie.getHash("TinyMCE_" + ed.id + "_size"), c = DOM.get(ed.id + '_tbl'); if (!o) return; t.resizeTo(o.cw, o.ch); }); } ed.onPostRender.add(function() { Event.add(ed.id + '_resize', 'click', function(e) { e.preventDefault(); }); Event.add(ed.id + '_resize', 'mousedown', function(e) { var mouseMoveHandler1, mouseMoveHandler2, mouseUpHandler1, mouseUpHandler2, startX, startY, startWidth, startHeight, width, height, ifrElm; function resizeOnMove(e) { e.preventDefault(); width = startWidth + (e.screenX - startX); height = startHeight + (e.screenY - startY); t.resizeTo(width, height); }; function endResize(e) { // Stop listening Event.remove(DOM.doc, 'mousemove', mouseMoveHandler1); Event.remove(ed.getDoc(), 'mousemove', mouseMoveHandler2); Event.remove(DOM.doc, 'mouseup', mouseUpHandler1); Event.remove(ed.getDoc(), 'mouseup', mouseUpHandler2); width = startWidth + (e.screenX - startX); height = startHeight + (e.screenY - startY); t.resizeTo(width, height, true); ed.nodeChanged(); }; e.preventDefault(); // Get the current rect size startX = e.screenX; startY = e.screenY; ifrElm = DOM.get(t.editor.id + '_ifr'); startWidth = width = ifrElm.clientWidth; startHeight = height = ifrElm.clientHeight; // Register envent handlers mouseMoveHandler1 = Event.add(DOM.doc, 'mousemove', resizeOnMove); mouseMoveHandler2 = Event.add(ed.getDoc(), 'mousemove', resizeOnMove); mouseUpHandler1 = Event.add(DOM.doc, 'mouseup', endResize); mouseUpHandler2 = Event.add(ed.getDoc(), 'mouseup', endResize); }); }); } o.deltaHeight -= 21; n = tb = null; }, _updateUndoStatus : function(ed) { var cm = ed.controlManager, um = ed.undoManager; cm.setDisabled('undo', !um.hasUndo() && !um.typing); cm.setDisabled('redo', !um.hasRedo()); }, _nodeChanged : function(ed, cm, n, co, ob) { var t = this, p, de = 0, v, c, s = t.settings, cl, fz, fn, fc, bc, formatNames, matches; tinymce.each(t.stateControls, function(c) { cm.setActive(c, ed.queryCommandState(t.controls[c][1])); }); function getParent(name) { var i, parents = ob.parents, func = name; if (typeof(name) == 'string') { func = function(node) { return node.nodeName == name; }; } for (i = 0; i < parents.length; i++) { if (func(parents[i])) return parents[i]; } }; cm.setActive('visualaid', ed.hasVisual); t._updateUndoStatus(ed); cm.setDisabled('outdent', !ed.queryCommandState('Outdent')); p = getParent('A'); if (c = cm.get('link')) { c.setDisabled((!p && co) || (p && !p.href)); c.setActive(!!p && (!p.name && !p.id)); } if (c = cm.get('unlink')) { c.setDisabled(!p && co); c.setActive(!!p && !p.name && !p.id); } if (c = cm.get('anchor')) { c.setActive(!co && !!p && (p.name || (p.id && !p.href))); } p = getParent('IMG'); if (c = cm.get('image')) c.setActive(!co && !!p && n.className.indexOf('mceItem') == -1); if (c = cm.get('styleselect')) { t._importClasses(); formatNames = []; each(c.items, function(item) { formatNames.push(item.value); }); matches = ed.formatter.matchAll(formatNames); c.select(matches[0]); tinymce.each(matches, function(match, index) { if (index > 0) { c.mark(match); } }); } if (c = cm.get('formatselect')) { p = getParent(ed.dom.isBlock); if (p) c.select(p.nodeName.toLowerCase()); } // Find out current fontSize, fontFamily and fontClass getParent(function(n) { if (n.nodeName === 'SPAN') { if (!cl && n.className) cl = n.className; } if (ed.dom.is(n, s.theme_advanced_font_selector)) { if (!fz && n.style.fontSize) fz = n.style.fontSize; if (!fn && n.style.fontFamily) fn = n.style.fontFamily.replace(/[\"\']+/g, '').replace(/^([^,]+).*/, '$1').toLowerCase(); if (!fc && n.style.color) fc = n.style.color; if (!bc && n.style.backgroundColor) bc = n.style.backgroundColor; } return false; }); if (c = cm.get('fontselect')) { c.select(function(v) { return v.replace(/^([^,]+).*/, '$1').toLowerCase() == fn; }); } // Select font size if (c = cm.get('fontsizeselect')) { // Use computed style if (s.theme_advanced_runtime_fontsize && !fz && !cl) fz = ed.dom.getStyle(n, 'fontSize', true); c.select(function(v) { if (v.fontSize && v.fontSize === fz) return true; if (v['class'] && v['class'] === cl) return true; }); } if (s.theme_advanced_show_current_color) { function updateColor(controlId, color) { if (c = cm.get(controlId)) { if (!color) color = c.settings.default_color; if (color !== c.value) { c.displayColor(color); } } } updateColor('forecolor', fc); updateColor('backcolor', bc); } if (s.theme_advanced_show_current_color) { function updateColor(controlId, color) { if (c = cm.get(controlId)) { if (!color) color = c.settings.default_color; if (color !== c.value) { c.displayColor(color); } } }; updateColor('forecolor', fc); updateColor('backcolor', bc); } if (s.theme_advanced_path && s.theme_advanced_statusbar_location) { p = DOM.get(ed.id + '_path') || DOM.add(ed.id + '_path_row', 'span', {id : ed.id + '_path'}); if (t.statusKeyboardNavigation) { t.statusKeyboardNavigation.destroy(); t.statusKeyboardNavigation = null; } DOM.setHTML(p, ''); getParent(function(n) { var na = n.nodeName.toLowerCase(), u, pi, ti = ''; // Ignore non element and bogus/hidden elements if (n.nodeType != 1 || na === 'br' || n.getAttribute('data-mce-bogus') || DOM.hasClass(n, 'mceItemHidden') || DOM.hasClass(n, 'mceItemRemoved')) return; // Handle prefix if (tinymce.isIE && n.scopeName !== 'HTML' && n.scopeName) na = n.scopeName + ':' + na; // Remove internal prefix na = na.replace(/mce\:/g, ''); // Handle node name switch (na) { case 'b': na = 'strong'; break; case 'i': na = 'em'; break; case 'img': if (v = DOM.getAttrib(n, 'src')) ti += 'src: ' + v + ' '; break; case 'a': if (v = DOM.getAttrib(n, 'name')) { ti += 'name: ' + v + ' '; na += '#' + v; } if (v = DOM.getAttrib(n, 'href')) ti += 'href: ' + v + ' '; break; case 'font': if (v = DOM.getAttrib(n, 'face')) ti += 'font: ' + v + ' '; if (v = DOM.getAttrib(n, 'size')) ti += 'size: ' + v + ' '; if (v = DOM.getAttrib(n, 'color')) ti += 'color: ' + v + ' '; break; case 'span': if (v = DOM.getAttrib(n, 'style')) ti += 'style: ' + v + ' '; break; } if (v = DOM.getAttrib(n, 'id')) ti += 'id: ' + v + ' '; if (v = n.className) { v = v.replace(/\b\s*(webkit|mce|Apple-)\w+\s*\b/g, ''); if (v) { ti += 'class: ' + v + ' '; if (ed.dom.isBlock(n) || na == 'img' || na == 'span') na += '.' + v; } } na = na.replace(/(html:)/g, ''); na = {name : na, node : n, title : ti}; t.onResolveName.dispatch(t, na); ti = na.title; na = na.name; //u = "javascript:tinymce.EditorManager.get('" + ed.id + "').theme._sel('" + (de++) + "');"; pi = DOM.create('a', {'href' : "javascript:;", role: 'button', onmousedown : "return false;", title : ti, 'class' : 'mcePath_' + (de++)}, na); if (p.hasChildNodes()) { p.insertBefore(DOM.create('span', {'aria-hidden': 'true'}, '\u00a0\u00bb '), p.firstChild); p.insertBefore(pi, p.firstChild); } else p.appendChild(pi); }, ed.getBody()); if (DOM.select('a', p).length > 0) { t.statusKeyboardNavigation = new tinymce.ui.KeyboardNavigation({ root: ed.id + "_path_row", items: DOM.select('a', p), excludeFromTabOrder: true, onCancel: function() { ed.focus(); } }, DOM); } } }, // Commands gets called by execCommand _sel : function(v) { this.editor.execCommand('mceSelectNodeDepth', false, v); }, _mceInsertAnchor : function(ui, v) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/anchor.htm', width : 320 + parseInt(ed.getLang('advanced.anchor_delta_width', 0)), height : 90 + parseInt(ed.getLang('advanced.anchor_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceCharMap : function() { var ed = this.editor; ed.windowManager.open({ url : this.url + '/charmap.htm', width : 550 + parseInt(ed.getLang('advanced.charmap_delta_width', 0)), height : 265 + parseInt(ed.getLang('advanced.charmap_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceHelp : function() { var ed = this.editor; ed.windowManager.open({ url : this.url + '/about.htm', width : 480, height : 380, inline : true }, { theme_url : this.url }); }, _mceShortcuts : function() { var ed = this.editor; ed.windowManager.open({ url: this.url + '/shortcuts.htm', width: 480, height: 380, inline: true }, { theme_url: this.url }); }, _mceColorPicker : function(u, v) { var ed = this.editor; v = v || {}; ed.windowManager.open({ url : this.url + '/color_picker.htm', width : 375 + parseInt(ed.getLang('advanced.colorpicker_delta_width', 0)), height : 250 + parseInt(ed.getLang('advanced.colorpicker_delta_height', 0)), close_previous : false, inline : true }, { input_color : v.color, func : v.func, theme_url : this.url }); }, _mceCodeEditor : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/source_editor.htm', width : parseInt(ed.getParam("theme_advanced_source_editor_width", 720)), height : parseInt(ed.getParam("theme_advanced_source_editor_height", 580)), inline : true, resizable : true, maximizable : true }, { theme_url : this.url }); }, _mceImage : function(ui, val) { var ed = this.editor; // Internal image object like a flash placeholder if (ed.dom.getAttrib(ed.selection.getNode(), 'class', '').indexOf('mceItem') != -1) return; ed.windowManager.open({ url : this.url + '/image.htm', width : 355 + parseInt(ed.getLang('advanced.image_delta_width', 0)), height : 275 + parseInt(ed.getLang('advanced.image_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceLink : function(ui, val) { var ed = this.editor; ed.windowManager.open({ url : this.url + '/link.htm', width : 310 + parseInt(ed.getLang('advanced.link_delta_width', 0)), height : 200 + parseInt(ed.getLang('advanced.link_delta_height', 0)), inline : true }, { theme_url : this.url }); }, _mceNewDocument : function() { var ed = this.editor; ed.windowManager.confirm('advanced.newdocument', function(s) { if (s) ed.execCommand('mceSetContent', false, ''); }); }, _mceForeColor : function() { var t = this; this._mceColorPicker(0, { color: t.fgColor, func : function(co) { t.fgColor = co; t.editor.execCommand('ForeColor', false, co); } }); }, _mceBackColor : function() { var t = this; this._mceColorPicker(0, { color: t.bgColor, func : function(co) { t.bgColor = co; t.editor.execCommand('HiliteColor', false, co); } }); }, _ufirst : function(s) { return s.substring(0, 1).toUpperCase() + s.substring(1); } }); tinymce.ThemeManager.add('advanced', tinymce.themes.AdvancedTheme); }(tinymce));
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/editor_template_src.js
JavaScript
asf20
41,929
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{#advanced_dlg.code_title}</title> <script type="text/javascript" src="../../tiny_mce_popup.js?ver=358-20121205"></script> <script type="text/javascript" src="js/source_editor.js?ver=358-20121205"></script> </head> <body onresize="resizeInputs();" style="display:none; overflow:hidden;" spellcheck="false"> <form name="source" onsubmit="saveContent();return false;" action="#"> <div style="float: left" class="title"><label for="htmlSource">{#advanced_dlg.code_title}</label></div> <div id="wrapline" style="float: right"> <input type="checkbox" name="wraped" id="wraped" onclick="toggleWordWrap(this);" class="wordWrapCode" /><label for="wraped">{#advanced_dlg.code_wordwrap}</label> </div> <br style="clear: both" /> <textarea name="htmlSource" id="htmlSource" rows="15" cols="100" style="width: 100%; height: 100%; font-family: 'Courier New',Courier,monospace; font-size: 12px;" dir="ltr" wrap="off" class="mceFocus"></textarea> <div class="mceActionPanel"> <input type="submit" role="button" name="insert" value="{#update}" id="insert" /> <input type="button" role="button" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" id="cancel" /> </div> </form> </body> </html>
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/source_editor.htm
HTML
asf20
1,278
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{#advanced_dlg.charmap_title}</title> <script type="text/javascript" src="../../tiny_mce_popup.js?ver=358-20121205"></script> <script type="text/javascript" src="js/charmap.js?ver=358-20121205"></script> </head> <body id="charmap" style="display:none" role="application"> <table align="center" border="0" cellspacing="0" cellpadding="2" role="presentation"> <tr> <td colspan="2" class="title" ><label for="charmapView" id="charmap_label">{#advanced_dlg.charmap_title}</label></td> </tr> <tr> <td id="charmapView" rowspan="2" align="left" valign="top"> <!-- Chars will be rendered here --> </td> <td width="100" align="center" valign="top"> <table border="0" cellpadding="0" cellspacing="0" width="100" style="height:100px" role="presentation"> <tr> <td id="codeV">&nbsp;</td> </tr> <tr> <td id="codeN">&nbsp;</td> </tr> </table> </td> </tr> <tr> <td valign="bottom" style="padding-bottom: 3px;"> <table width="100" align="center" border="0" cellpadding="2" cellspacing="0" role="presentation"> <tr> <td align="center" style="border-left: 1px solid #666699; border-top: 1px solid #666699; border-right: 1px solid #666699;"><label for="codeA">HTML-Code</label></td> </tr> <tr> <td style="font-size: 16px; font-weight: bold; border-left: 1px solid #666699; border-bottom: 1px solid #666699; border-right: 1px solid #666699;" id="codeA" align="center">&nbsp;</td> </tr> <tr> <td style="font-size: 1px;">&nbsp;</td> </tr> <tr> <td align="center" style="border-left: 1px solid #666699; border-top: 1px solid #666699; border-right: 1px solid #666699;"><label for="codeB">NUM-Code</label></td> </tr> <tr> <td style="font-size: 16px; font-weight: bold; border-left: 1px solid #666699; border-bottom: 1px solid #666699; border-right: 1px solid #666699;" id="codeB" align="center">&nbsp;</td> </tr> </table> </td> </tr> <tr> <td colspan="2" id="charmap_usage">{#advanced_dlg.charmap_usage}</td> </tr> </table> </body> </html>
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/charmap.htm
HTML
asf20
2,230
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{#advanced_dlg.image_title}</title> <script type="text/javascript" src="../../tiny_mce_popup.js?ver=358-20121205"></script> <script type="text/javascript" src="../../utils/mctabs.js?ver=358-20121205"></script> <script type="text/javascript" src="../../utils/form_utils.js?ver=358-20121205"></script> <script type="text/javascript" src="js/image.js?ver=358-20121205"></script> </head> <body id="image" style="display: none"> <form onsubmit="ImageDialog.update();return false;" action="#"> <div class="tabs"> <ul> <li id="general_tab" class="current"><span><a href="javascript:mcTabs.displayTab('general_tab','general_panel');" onmousedown="return false;">{#advanced_dlg.image_title}</a></span></li> </ul> </div> <div class="panel_wrapper"> <div id="general_panel" class="panel current"> <table border="0" cellpadding="4" cellspacing="0"> <tr> <td class="nowrap"><label for="src">{#advanced_dlg.image_src}</label></td> <td><table border="0" cellspacing="0" cellpadding="0"> <tr> <td><input id="src" name="src" type="text" class="mceFocus" value="" style="width: 200px" onchange="ImageDialog.getImageData();" /></td> <td id="srcbrowsercontainer">&nbsp;</td> </tr> </table></td> </tr> <tr> <td><label for="image_list">{#advanced_dlg.image_list}</label></td> <td><select id="image_list" name="image_list" onchange="document.getElementById('src').value=this.options[this.selectedIndex].value;document.getElementById('alt').value=this.options[this.selectedIndex].text;"></select></td> </tr> <tr> <td class="nowrap"><label for="alt">{#advanced_dlg.image_alt}</label></td> <td><input id="alt" name="alt" type="text" value="" style="width: 200px" /></td> </tr> <tr> <td class="nowrap"><label for="align">{#advanced_dlg.image_align}</label></td> <td><select id="align" name="align" onchange="ImageDialog.updateStyle();"> <option value="">{#not_set}</option> <option value="baseline">{#advanced_dlg.image_align_baseline}</option> <option value="top">{#advanced_dlg.image_align_top}</option> <option value="middle">{#advanced_dlg.image_align_middle}</option> <option value="bottom">{#advanced_dlg.image_align_bottom}</option> <option value="text-top">{#advanced_dlg.image_align_texttop}</option> <option value="text-bottom">{#advanced_dlg.image_align_textbottom}</option> <option value="left">{#advanced_dlg.image_align_left}</option> <option value="right">{#advanced_dlg.image_align_right}</option> </select></td> </tr> <tr> <td class="nowrap"><label for="width">{#advanced_dlg.image_dimensions}</label></td> <td><input id="width" name="width" type="text" value="" size="3" maxlength="5" /> x <input id="height" name="height" type="text" value="" size="3" maxlength="5" /></td> </tr> <tr> <td class="nowrap"><label for="border">{#advanced_dlg.image_border}</label></td> <td><input id="border" name="border" type="text" value="" size="3" maxlength="3" onchange="ImageDialog.updateStyle();" /></td> </tr> <tr> <td class="nowrap"><label for="vspace">{#advanced_dlg.image_vspace}</label></td> <td><input id="vspace" name="vspace" type="text" value="" size="3" maxlength="3" onchange="ImageDialog.updateStyle();" /></td> </tr> <tr> <td class="nowrap"><label for="hspace">{#advanced_dlg.image_hspace}</label></td> <td><input id="hspace" name="hspace" type="text" value="" size="3" maxlength="3" onchange="ImageDialog.updateStyle();" /></td> </tr> </table> </div> </div> <div class="mceActionPanel"> <input type="submit" id="insert" name="insert" value="{#insert}" /> <input type="button" id="cancel" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" /> </div> </form> </body> </html>
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/image.htm
HTML
asf20
4,026
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{#advanced_dlg.colorpicker_title}</title> <script type="text/javascript" src="../../tiny_mce_popup.js?ver=358-20121205"></script> <script type="text/javascript" src="../../utils/mctabs.js?ver=358-20121205"></script> <script type="text/javascript" src="js/color_picker.js?ver=358-20121205"></script> </head> <body id="colorpicker" style="display: none" role="application" aria-labelledby="app_label"> <span class="mceVoiceLabel" id="app_label" style="display:none;">{#advanced_dlg.colorpicker_title}</span> <form onsubmit="insertAction();return false" action="#"> <div class="tabs"> <ul> <li id="picker_tab" aria-controls="picker_panel" class="current"><span><a href="javascript:mcTabs.displayTab('picker_tab','picker_panel');" onmousedown="return false;">{#advanced_dlg.colorpicker_picker_tab}</a></span></li> <li id="rgb_tab" aria-controls="rgb_panel"><span><a href="javascript:;" onclick="mcTabs.displayTab('rgb_tab','rgb_panel');" onmousedown="return false;">{#advanced_dlg.colorpicker_palette_tab}</a></span></li> <li id="named_tab" aria-controls="named_panel"><span><a href="javascript:;" onclick="javascript:mcTabs.displayTab('named_tab','named_panel');" onmousedown="return false;">{#advanced_dlg.colorpicker_named_tab}</a></span></li> </ul> </div> <div class="panel_wrapper"> <div id="picker_panel" class="panel current"> <fieldset> <legend>{#advanced_dlg.colorpicker_picker_title}</legend> <div id="picker"> <img id="colors" src="img/colorpicker.jpg" onclick="computeColor(event)" onmousedown="isMouseDown = true;return false;" onmouseup="isMouseDown = false;" onmousemove="if (isMouseDown && isMouseOver) computeColor(event); return false;" onmouseover="isMouseOver=true;" onmouseout="isMouseOver=false;" alt="" /> <div id="light"> <!-- Will be filled with divs --> </div> <br style="clear: both" /> </div> </fieldset> </div> <div id="rgb_panel" class="panel"> <fieldset> <legend id="webcolors_title">{#advanced_dlg.colorpicker_palette_title}</legend> <div id="webcolors"> <!-- Gets filled with web safe colors--> </div> <br style="clear: both" /> </fieldset> </div> <div id="named_panel" class="panel"> <fieldset id="named_picker_label"> <legend id="named_title">{#advanced_dlg.colorpicker_named_title}</legend> <div id="namedcolors" role="listbox" tabindex="0" aria-labelledby="named_picker_label"> <!-- Gets filled with named colors--> </div> <br style="clear: both" /> <div id="colornamecontainer"> {#advanced_dlg.colorpicker_name} <span id="colorname"></span> </div> </fieldset> </div> </div> <div class="mceActionPanel"> <input type="submit" id="insert" name="insert" value="{#apply}" /> <input type="button" id="cancel" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();"/> <div id="preview_wrapper"><div id="previewblock"><label for="color">{#advanced_dlg.colorpicker_color}</label> <input id="color" type="text" size="8" class="text mceFocus" aria-required="true" /></div><span id="preview"></span></div> </div> </form> </body> </html>
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/color_picker.htm
HTML
asf20
3,298
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{#advanced_dlg.anchor_title}</title> <script type="text/javascript" src="../../tiny_mce_popup.js?ver=358-20121205"></script> <script type="text/javascript" src="js/anchor.js?ver=358-20121205"></script> </head> <body style="display: none" role="application" aria-labelledby="app_title"> <form onsubmit="AnchorDialog.update();return false;" action="#"> <table border="0" cellpadding="4" cellspacing="0" role="presentation"> <tr> <td colspan="2" class="title" id="app_title">{#advanced_dlg.anchor_title}</td> </tr> <tr> <td class="nowrap"><label for="anchorName">{#advanced_dlg.anchor_name}:</label></td> <td><input name="anchorName" type="text" class="mceFocus" id="anchorName" value="" style="width: 200px" aria-required="true" /></td> </tr> </table> <div class="mceActionPanel"> <input type="submit" id="insert" name="insert" value="{#update}" /> <input type="button" id="cancel" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" /> </div> </form> </body> </html>
zyblog
trunk/zyblog/wp-includes/js/tinymce/themes/advanced/anchor.htm
HTML
asf20
1,175
<?php /** * @package TinyMCE * @author Moxiecode * @copyright Copyright © 2005-2006, Moxiecode Systems AB, All rights reserved. */ /** @ignore */ require_once('../../../wp-load.php'); header('Content-Type: text/html; charset=' . get_bloginfo('charset')); ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>> <head> <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php echo get_option('blog_charset'); ?>" /> <title><?php _e('Rich Editor Help'); ?></title> <script type="text/javascript" src="tiny_mce_popup.js?ver=358-20121205"></script> <?php wp_admin_css( 'wp-admin', true ); ?> <style type="text/css"> body { min-width: 0; } #wphead { font-size: 80%; border-top: 0; color: #555; background-color: #f1f1f1; } #wphead h1 { font-size: 24px; color: #555; margin: 0; padding: 10px; } #tabs { padding: 15px 15px 3px; background-color: #f1f1f1; border-bottom: 1px solid #dfdfdf; margin: 0; } #tabs li { display: inline; } #tabs a.current { background-color: #fff; border-color: #dfdfdf; border-bottom-color: #fff; color: #d54e21; } #tabs a { color: #2583AD; padding: 6px; border-width: 1px 1px 0; border-style: solid solid none; border-color: #f1f1f1; text-decoration: none; } #tabs a:hover { color: #d54e21; } .wrap h2 { border-bottom-color: #dfdfdf; color: #555; margin: 5px 0; padding: 0; font-size: 18px; } #user_info { right: 5%; top: 5px; } h3 { font-size: 1.1em; margin-top: 10px; margin-bottom: 0px; } #flipper { margin: 0; padding: 5px 20px 10px; background-color: #fff; border-left: 1px solid #dfdfdf; border-bottom: 1px solid #dfdfdf; } * html { overflow-x: hidden; overflow-y: scroll; } #flipper div p { margin-top: 0.4em; margin-bottom: 0.8em; text-align: justify; } th { text-align: center; } .top th { text-decoration: underline; } .top .key { text-align: center; width: 5em; } .top .action { text-align: left; } .align { border-left: 3px double #333; border-right: 3px double #333; } .keys { margin-bottom: 15px; width: 100%; border: 0 none; } .keys p { display: inline-block; margin: 0px; padding: 0px; } .keys .left { text-align: left; } .keys .center { text-align: center; } .keys .right { text-align: right; } td b { font-family: "Times New Roman" Times serif; } #buttoncontainer { text-align: center; margin-bottom: 20px; } #buttoncontainer a, #buttoncontainer a:hover { border-bottom: 0px; } .macos .win, .windows .mac { display: none; } </style> <?php if ( is_rtl() ) : ?> <style type="text/css"> #wphead, #tabs { padding-left: auto; padding-right: 15px; } #flipper { margin: 5px 0 3px 10px; } .keys .left, .top, .action { text-align: right; } .keys .right { text-align: left; } td b { font-family: Tahoma, "Times New Roman", Times, serif } </style> <?php endif; ?> </head> <body class="windows wp-core-ui"> <script type="text/javascript"> if ( tinymce.isMac ) document.body.className = document.body.className.replace(/windows/, 'macos'); </script> <ul id="tabs"> <li><a id="tab1" href="javascript:flipTab(1)" title="<?php esc_attr_e('Basics of Rich Editing'); ?>" accesskey="1" class="current"><?php _e('Basics'); ?></a></li> <li><a id="tab2" href="javascript:flipTab(2)" title="<?php esc_attr_e('Advanced use of the Rich Editor'); ?>" accesskey="2"><?php _e('Advanced'); ?></a></li> <li><a id="tab3" href="javascript:flipTab(3)" title="<?php esc_attr_e('Hotkeys'); ?>" accesskey="3"><?php _e('Hotkeys'); ?></a></li> <li><a id="tab4" href="javascript:flipTab(4)" title="<?php esc_attr_e('About the software'); ?>" accesskey="4"><?php _e('About'); ?></a></li> </ul> <div id="flipper" class="wrap"> <div id="content1"> <h2><?php _e('Rich Editing Basics'); ?></h2> <p><?php _e('<em>Rich editing</em>, also called WYSIWYG for What You See Is What You Get, means your text is formatted as you type. The rich editor creates HTML code behind the scenes while you concentrate on writing. Font styles, links and images all appear approximately as they will on the internet.'); ?></p> <p><?php _e('WordPress includes a rich HTML editor that works well in all major web browsers used today. However editing HTML is not the same as typing text. Each web page has two major components: the structure, which is the actual HTML code and is produced by the editor as you type, and the display, that is applied to it by the currently selected WordPress theme and is defined in style.css. WordPress is producing valid XHTML 1.0 which means that inserting multiple line breaks (BR tags) after a paragraph would not produce white space on the web page. The BR tags will be removed as invalid by the internal HTML correcting functions.'); ?></p> <p><?php _e('While using the editor, most basic keyboard shortcuts work like in any other text editor. For example: Shift+Enter inserts line break, Ctrl+C = copy, Ctrl+X = cut, Ctrl+Z = undo, Ctrl+Y = redo, Ctrl+A = select all, etc. (on Mac use the Command key instead of Ctrl). See the Hotkeys tab for all available keyboard shortcuts.'); ?></p> <p><?php _e('If you do not like the way the rich editor works, you may turn it off from Your Profile submenu, under Users in the admin menu.'); ?></p> </div> <div id="content2" class="hidden"> <h2><?php _e('Advanced Rich Editing'); ?></h2> <h3><?php _e('Images and Attachments'); ?></h3> <p><?php _e('There is a button in the editor toolbar for inserting images that are already hosted somewhere on the internet. If you have a URL for an image, click this button and enter the URL in the box which appears.'); ?></p> <p><?php _e('If you need to upload an image or another media file from your computer, you can use the Media Library button above the editor. The media library will attempt to create a thumbnail-sized copy from each uploaded image. To insert your image into the post, first click on the thumbnail to reveal a menu of options. When you have selected the options you like, click "Insert into Post" and your image or file will appear in the post you are editing.'); ?></p> <h3><?php _e('HTML in the Rich Editor'); ?></h3> <p><?php _e('Any HTML entered directly into the rich editor will show up as text when the post is viewed. What you see is what you get. When you want to include HTML elements that cannot be generated with the toolbar buttons, you must enter it by hand in the Text editor. Examples are tables and &lt;code&gt;. To do this, click the Text tab and edit the code, then switch back to Visual mode. If the code is valid and understood by the editor, you should see it rendered immediately.'); ?></p> <h3><?php _e('Pasting in the Rich Editor'); ?></h3> <p><?php _e('When pasting content from another web page the results can be inconsistent and depend on your browser and on the web page you are pasting from. The editor tries to correct any invalid HTML code that was pasted, but for best results try using the Text tab or one of the paste buttons that are on the second row. Alternatively try pasting paragraph by paragraph. In most browsers to select one paragraph at a time, triple-click on it.'); ?></p> <p><?php _e('Pasting content from another application, like Word or Excel, is best done with the Paste from Word button on the second row, or in Text mode.'); ?></p> </div> <div id="content3" class="hidden"> <h2><?php _e('Writing at Full Speed'); ?></h2> <p><?php _e('Rather than reaching for your mouse to click on the toolbar, use these access keys. Windows and Linux use Ctrl + letter. Macintosh uses Command + letter.'); ?></p> <table class="keys"> <tr class="top"><th class="key center"><?php _e('Letter'); ?></th><th class="left"><?php _e('Action'); ?></th><th class="key center"><?php _e('Letter'); ?></th><th class="left"><?php _e('Action'); ?></th></tr> <tr><th>c</th><td><?php _e('Copy'); ?></td><th>v</th><td><?php _e('Paste'); ?></td></tr> <tr><th>a</th><td><?php _e('Select all'); ?></td><th>x</th><td><?php _e('Cut'); ?></td></tr> <tr><th>z</th><td><?php _e('Undo'); ?></td><th>y</th><td><?php _e('Redo'); ?></td></tr> <tr><th>b</th><td><?php _e('Bold'); ?></td><th>i</th><td><?php _e('Italic'); ?></td></tr> <tr><th>u</th><td><?php _e('Underline'); ?></td><th>1</th><td><?php _e('Heading 1'); ?></td></tr> <tr><th>2</th><td><?php _e('Heading 2'); ?></td><th>3</th><td><?php _e('Heading 3'); ?></td></tr> <tr><th>4</th><td><?php _e('Heading 4'); ?></td><th>5</th><td><?php _e('Heading 5'); ?></td></tr> <tr><th>6</th><td><?php _e('Heading 6'); ?></td><th>9</th><td><?php _e('Address'); ?></td></tr> </table> <p><?php _e('The following shortcuts use different access keys: Alt + Shift + letter.'); ?></p> <table class="keys"> <tr class="top"><th class="key center"><?php _e('Letter'); ?></th><th class="left"><?php _e('Action'); ?></th><th class="key center"><?php _e('Letter'); ?></th><th class="left"><?php _e('Action'); ?></th></tr> <tr><th>n</th><td><?php _e('Check Spelling'); ?></td><th>l</th><td><?php _e('Align Left'); ?></td></tr> <tr><th>j</th><td><?php _e('Justify Text'); ?></td><th>c</th><td><?php _e('Align Center'); ?></td></tr> <tr><th>d</th><td><span style="text-decoration: line-through;"><?php _e('Strikethrough'); ?></span></td><th>r</th><td><?php _e('Align Right'); ?></td></tr> <tr><th>u</th><td><strong>&bull;</strong> <?php _e('List'); ?></td><th>a</th><td><?php _e('Insert link'); ?></td></tr> <tr><th>o</th><td>1. <?php _e('List'); ?></td><th>s</th><td><?php _e('Remove link'); ?></td></tr> <tr><th>q</th><td><?php _e('Quote'); ?></td><th>m</th><td><?php _e('Insert Image'); ?></td></tr> <tr><th>w</th><td><?php _e('Distraction Free Writing mode'); ?></td><th>t</th><td><?php _e('Insert More Tag'); ?></td></tr> <tr><th>p</th><td><?php _e('Insert Page Break tag'); ?></td><th>h</th><td><?php _e('Help'); ?></td></tr> </table> <p style="padding: 15px 10px 10px;"><?php _e('Editor width in Distraction Free Writing mode:'); ?></p> <table class="keys"> <tr><th><span class="win">Alt +</span><span class="mac">Ctrl +</span></th><td><?php _e('Wider'); ?></td> <th><span class="win">Alt -</span><span class="mac">Ctrl -</span></th><td><?php _e('Narrower'); ?></td></tr> <tr><th><span class="win">Alt 0</span><span class="mac">Ctrl 0</span></th><td><?php _e('Default width'); ?></td><th></th><td></td></tr> </table> </div> <div id="content4" class="hidden"> <h2><?php _e('About TinyMCE'); ?></h2> <p><?php _e('Version:'); ?> <span id="version"></span> (<span id="date"></span>)</p> <p><?php printf(__('TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor released as Open Source under %sLGPL</a> by Moxiecode Systems AB. It has the ability to convert HTML TEXTAREA fields or other HTML elements to editor instances.'), '<a href="'.home_url('/wp-includes/js/tinymce/license.txt').'" target="_blank" title="'.esc_attr__('GNU Library General Public License').'">'); ?></p> <p><?php _e('Copyright &copy; 2003-2011, <a href="http://www.moxiecode.com" target="_blank">Moxiecode Systems AB</a>, All rights reserved.'); ?></p> <p><?php _e('For more information about this software visit the <a href="http://tinymce.com" target="_blank">TinyMCE website</a>.'); ?></p> <div id="buttoncontainer"> <a href="http://www.moxiecode.com" target="_blank"><img src="themes/advanced/img/gotmoxie.png" alt="<?php esc_attr_e('Got Moxie?'); ?>" style="border: 0" /></a> </div> </div> </div> <div class="mceActionPanel"> <div style="margin: 8px auto; text-align: center;padding-bottom: 10px;"> <input type="button" id="cancel" name="cancel" value="<?php esc_attr_e('Close'); ?>" title="<?php esc_attr_e('Close'); ?>" onclick="tinyMCEPopup.close();" /> </div> </div> <script type="text/javascript"> function d(id) { return document.getElementById(id); } function flipTab(n) { var i, c, t; for ( i = 1; i <= 4; i++ ) { c = d('content'+i.toString()); t = d('tab'+i.toString()); if ( n == i ) { c.className = ''; t.className = 'current'; } else { c.className = 'hidden'; t.className = ''; } } } tinyMCEPopup.onInit.add(function() { var win = tinyMCEPopup.getWin(); d('version').innerHTML = tinymce.majorVersion + "." + tinymce.minorVersion; d('date').innerHTML = tinymce.releaseDate; if ( win.fullscreen && win.fullscreen.settings.visible ) { d('content1').className = 'hidden'; d('tabs').className = 'hidden'; d('content3').className = 'dfw'; } }); </script> </body> </html>
zyblog
trunk/zyblog/wp-includes/js/tinymce/wp-mce-help.php
PHP
asf20
12,615
/** * validate.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ /** // String validation: if (!Validator.isEmail('myemail')) alert('Invalid email.'); // Form validation: var f = document.forms['myform']; if (!Validator.isEmail(f.myemail)) alert('Invalid email.'); */ var Validator = { isEmail : function(s) { return this.test(s, '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+@[-!#$%&\'*+\\/0-9=?A-Z^_`a-z{|}~]+\.[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$'); }, isAbsUrl : function(s) { return this.test(s, '^(news|telnet|nttp|file|http|ftp|https)://[-A-Za-z0-9\\.]+\\/?.*$'); }, isSize : function(s) { return this.test(s, '^[0-9.]+(%|in|cm|mm|em|ex|pt|pc|px)?$'); }, isId : function(s) { return this.test(s, '^[A-Za-z_]([A-Za-z0-9_])*$'); }, isEmpty : function(s) { var nl, i; if (s.nodeName == 'SELECT' && s.selectedIndex < 1) return true; if (s.type == 'checkbox' && !s.checked) return true; if (s.type == 'radio') { for (i=0, nl = s.form.elements; i<nl.length; i++) { if (nl[i].type == "radio" && nl[i].name == s.name && nl[i].checked) return false; } return true; } return new RegExp('^\\s*$').test(s.nodeType == 1 ? s.value : s); }, isNumber : function(s, d) { return !isNaN(s.nodeType == 1 ? s.value : s) && (!d || !this.test(s, '^-?[0-9]*\\.[0-9]*$')); }, test : function(s, p) { s = s.nodeType == 1 ? s.value : s; return s == '' || new RegExp(p).test(s); } }; var AutoValidator = { settings : { id_cls : 'id', int_cls : 'int', url_cls : 'url', number_cls : 'number', email_cls : 'email', size_cls : 'size', required_cls : 'required', invalid_cls : 'invalid', min_cls : 'min', max_cls : 'max' }, init : function(s) { var n; for (n in s) this.settings[n] = s[n]; }, validate : function(f) { var i, nl, s = this.settings, c = 0; nl = this.tags(f, 'label'); for (i=0; i<nl.length; i++) { this.removeClass(nl[i], s.invalid_cls); nl[i].setAttribute('aria-invalid', false); } c += this.validateElms(f, 'input'); c += this.validateElms(f, 'select'); c += this.validateElms(f, 'textarea'); return c == 3; }, invalidate : function(n) { this.mark(n.form, n); }, getErrorMessages : function(f) { var nl, i, s = this.settings, field, msg, values, messages = [], ed = tinyMCEPopup.editor; nl = this.tags(f, "label"); for (i=0; i<nl.length; i++) { if (this.hasClass(nl[i], s.invalid_cls)) { field = document.getElementById(nl[i].getAttribute("for")); values = { field: nl[i].textContent }; if (this.hasClass(field, s.min_cls, true)) { message = ed.getLang('invalid_data_min'); values.min = this.getNum(field, s.min_cls); } else if (this.hasClass(field, s.number_cls)) { message = ed.getLang('invalid_data_number'); } else if (this.hasClass(field, s.size_cls)) { message = ed.getLang('invalid_data_size'); } else { message = ed.getLang('invalid_data'); } message = message.replace(/{\#([^}]+)\}/g, function(a, b) { return values[b] || '{#' + b + '}'; }); messages.push(message); } } return messages; }, reset : function(e) { var t = ['label', 'input', 'select', 'textarea']; var i, j, nl, s = this.settings; if (e == null) return; for (i=0; i<t.length; i++) { nl = this.tags(e.form ? e.form : e, t[i]); for (j=0; j<nl.length; j++) { this.removeClass(nl[j], s.invalid_cls); nl[j].setAttribute('aria-invalid', false); } } }, validateElms : function(f, e) { var nl, i, n, s = this.settings, st = true, va = Validator, v; nl = this.tags(f, e); for (i=0; i<nl.length; i++) { n = nl[i]; this.removeClass(n, s.invalid_cls); if (this.hasClass(n, s.required_cls) && va.isEmpty(n)) st = this.mark(f, n); if (this.hasClass(n, s.number_cls) && !va.isNumber(n)) st = this.mark(f, n); if (this.hasClass(n, s.int_cls) && !va.isNumber(n, true)) st = this.mark(f, n); if (this.hasClass(n, s.url_cls) && !va.isAbsUrl(n)) st = this.mark(f, n); if (this.hasClass(n, s.email_cls) && !va.isEmail(n)) st = this.mark(f, n); if (this.hasClass(n, s.size_cls) && !va.isSize(n)) st = this.mark(f, n); if (this.hasClass(n, s.id_cls) && !va.isId(n)) st = this.mark(f, n); if (this.hasClass(n, s.min_cls, true)) { v = this.getNum(n, s.min_cls); if (isNaN(v) || parseInt(n.value) < parseInt(v)) st = this.mark(f, n); } if (this.hasClass(n, s.max_cls, true)) { v = this.getNum(n, s.max_cls); if (isNaN(v) || parseInt(n.value) > parseInt(v)) st = this.mark(f, n); } } return st; }, hasClass : function(n, c, d) { return new RegExp('\\b' + c + (d ? '[0-9]+' : '') + '\\b', 'g').test(n.className); }, getNum : function(n, c) { c = n.className.match(new RegExp('\\b' + c + '([0-9]+)\\b', 'g'))[0]; c = c.replace(/[^0-9]/g, ''); return c; }, addClass : function(n, c, b) { var o = this.removeClass(n, c); n.className = b ? c + (o != '' ? (' ' + o) : '') : (o != '' ? (o + ' ') : '') + c; }, removeClass : function(n, c) { c = n.className.replace(new RegExp("(^|\\s+)" + c + "(\\s+|$)"), ' '); return n.className = c != ' ' ? c : ''; }, tags : function(f, s) { return f.getElementsByTagName(s); }, mark : function(f, n) { var s = this.settings; this.addClass(n, s.invalid_cls); n.setAttribute('aria-invalid', 'true'); this.markLabels(f, n, s.invalid_cls); return false; }, markLabels : function(f, n, ic) { var nl, i; nl = this.tags(f, "label"); for (i=0; i<nl.length; i++) { if (nl[i].getAttribute("for") == n.id || nl[i].htmlFor == n.id) this.addClass(nl[i], ic); } return null; } };
zyblog
trunk/zyblog/wp-includes/js/tinymce/utils/validate.js
JavaScript
asf20
5,848
/** * mctabs.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ function MCTabs() { this.settings = []; this.onChange = tinyMCEPopup.editor.windowManager.createInstance('tinymce.util.Dispatcher'); }; MCTabs.prototype.init = function(settings) { this.settings = settings; }; MCTabs.prototype.getParam = function(name, default_value) { var value = null; value = (typeof(this.settings[name]) == "undefined") ? default_value : this.settings[name]; // Fix bool values if (value == "true" || value == "false") return (value == "true"); return value; }; MCTabs.prototype.showTab =function(tab){ tab.className = 'current'; tab.setAttribute("aria-selected", true); tab.setAttribute("aria-expanded", true); tab.tabIndex = 0; }; MCTabs.prototype.hideTab =function(tab){ var t=this; tab.className = ''; tab.setAttribute("aria-selected", false); tab.setAttribute("aria-expanded", false); tab.tabIndex = -1; }; MCTabs.prototype.showPanel = function(panel) { panel.className = 'current'; panel.setAttribute("aria-hidden", false); }; MCTabs.prototype.hidePanel = function(panel) { panel.className = 'panel'; panel.setAttribute("aria-hidden", true); }; MCTabs.prototype.getPanelForTab = function(tabElm) { return tinyMCEPopup.dom.getAttrib(tabElm, "aria-controls"); }; MCTabs.prototype.displayTab = function(tab_id, panel_id, avoid_focus) { var panelElm, panelContainerElm, tabElm, tabContainerElm, selectionClass, nodes, i, t = this; tabElm = document.getElementById(tab_id); if (panel_id === undefined) { panel_id = t.getPanelForTab(tabElm); } panelElm= document.getElementById(panel_id); panelContainerElm = panelElm ? panelElm.parentNode : null; tabContainerElm = tabElm ? tabElm.parentNode : null; selectionClass = t.getParam('selection_class', 'current'); if (tabElm && tabContainerElm) { nodes = tabContainerElm.childNodes; // Hide all other tabs for (i = 0; i < nodes.length; i++) { if (nodes[i].nodeName == "LI") { t.hideTab(nodes[i]); } } // Show selected tab t.showTab(tabElm); } if (panelElm && panelContainerElm) { nodes = panelContainerElm.childNodes; // Hide all other panels for (i = 0; i < nodes.length; i++) { if (nodes[i].nodeName == "DIV") t.hidePanel(nodes[i]); } if (!avoid_focus) { tabElm.focus(); } // Show selected panel t.showPanel(panelElm); } }; MCTabs.prototype.getAnchor = function() { var pos, url = document.location.href; if ((pos = url.lastIndexOf('#')) != -1) return url.substring(pos + 1); return ""; }; //Global instance var mcTabs = new MCTabs(); tinyMCEPopup.onInit.add(function() { var tinymce = tinyMCEPopup.getWin().tinymce, dom = tinyMCEPopup.dom, each = tinymce.each; each(dom.select('div.tabs'), function(tabContainerElm) { var keyNav; dom.setAttrib(tabContainerElm, "role", "tablist"); var items = tinyMCEPopup.dom.select('li', tabContainerElm); var action = function(id) { mcTabs.displayTab(id, mcTabs.getPanelForTab(id)); mcTabs.onChange.dispatch(id); }; each(items, function(item) { dom.setAttrib(item, 'role', 'tab'); dom.bind(item, 'click', function(evt) { action(item.id); }); }); dom.bind(dom.getRoot(), 'keydown', function(evt) { if (evt.keyCode === 9 && evt.ctrlKey && !evt.altKey) { // Tab keyNav.moveFocus(evt.shiftKey ? -1 : 1); tinymce.dom.Event.cancel(evt); } }); each(dom.select('a', tabContainerElm), function(a) { dom.setAttrib(a, 'tabindex', '-1'); }); keyNav = tinyMCEPopup.editor.windowManager.createInstance('tinymce.ui.KeyboardNavigation', { root: tabContainerElm, items: items, onAction: action, actOnFocus: true, enableLeftRight: true, enableUpDown: true }, tinyMCEPopup.dom); }); });
zyblog
trunk/zyblog/wp-includes/js/tinymce/utils/mctabs.js
JavaScript
asf20
3,894
/** * editable_selects.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ var TinyMCE_EditableSelects = { editSelectElm : null, init : function() { var nl = document.getElementsByTagName("select"), i, d = document, o; for (i=0; i<nl.length; i++) { if (nl[i].className.indexOf('mceEditableSelect') != -1) { o = new Option(tinyMCEPopup.editor.translate('value'), '__mce_add_custom__'); o.className = 'mceAddSelectValue'; nl[i].options[nl[i].options.length] = o; nl[i].onchange = TinyMCE_EditableSelects.onChangeEditableSelect; } } }, onChangeEditableSelect : function(e) { var d = document, ne, se = window.event ? window.event.srcElement : e.target; if (se.options[se.selectedIndex].value == '__mce_add_custom__') { ne = d.createElement("input"); ne.id = se.id + "_custom"; ne.name = se.name + "_custom"; ne.type = "text"; ne.style.width = se.offsetWidth + 'px'; se.parentNode.insertBefore(ne, se); se.style.display = 'none'; ne.focus(); ne.onblur = TinyMCE_EditableSelects.onBlurEditableSelectInput; ne.onkeydown = TinyMCE_EditableSelects.onKeyDown; TinyMCE_EditableSelects.editSelectElm = se; } }, onBlurEditableSelectInput : function() { var se = TinyMCE_EditableSelects.editSelectElm; if (se) { if (se.previousSibling.value != '') { addSelectValue(document.forms[0], se.id, se.previousSibling.value, se.previousSibling.value); selectByValue(document.forms[0], se.id, se.previousSibling.value); } else selectByValue(document.forms[0], se.id, ''); se.style.display = 'inline'; se.parentNode.removeChild(se.previousSibling); TinyMCE_EditableSelects.editSelectElm = null; } }, onKeyDown : function(e) { e = e || window.event; if (e.keyCode == 13) TinyMCE_EditableSelects.onBlurEditableSelectInput(); } };
zyblog
trunk/zyblog/wp-includes/js/tinymce/utils/editable_selects.js
JavaScript
asf20
1,976
/** * form_utils.js * * Copyright 2009, Moxiecode Systems AB * Released under LGPL License. * * License: http://tinymce.moxiecode.com/license * Contributing: http://tinymce.moxiecode.com/contributing */ var themeBaseURL = tinyMCEPopup.editor.baseURI.toAbsolute('themes/' + tinyMCEPopup.getParam("theme")); function getColorPickerHTML(id, target_form_element) { var h = "", dom = tinyMCEPopup.dom; if (label = dom.select('label[for=' + target_form_element + ']')[0]) { label.id = label.id || dom.uniqueId(); } h += '<a role="button" aria-labelledby="' + id + '_label" id="' + id + '_link" href="javascript:;" onclick="tinyMCEPopup.pickColor(event,\'' + target_form_element +'\');" onmousedown="return false;" class="pickcolor">'; h += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '">&nbsp;<span id="' + id + '_label" class="mceVoiceLabel mceIconOnly" style="display:none;">' + tinyMCEPopup.getLang('browse') + '</span></span></a>'; return h; } function updateColor(img_id, form_element_id) { document.getElementById(img_id).style.backgroundColor = document.forms[0].elements[form_element_id].value; } function setBrowserDisabled(id, state) { var img = document.getElementById(id); var lnk = document.getElementById(id + "_link"); if (lnk) { if (state) { lnk.setAttribute("realhref", lnk.getAttribute("href")); lnk.removeAttribute("href"); tinyMCEPopup.dom.addClass(img, 'disabled'); } else { if (lnk.getAttribute("realhref")) lnk.setAttribute("href", lnk.getAttribute("realhref")); tinyMCEPopup.dom.removeClass(img, 'disabled'); } } } function getBrowserHTML(id, target_form_element, type, prefix) { var option = prefix + "_" + type + "_browser_callback", cb, html; cb = tinyMCEPopup.getParam(option, tinyMCEPopup.getParam("file_browser_callback")); if (!cb) return ""; html = ""; html += '<a id="' + id + '_link" href="javascript:openBrowser(\'' + id + '\',\'' + target_form_element + '\', \'' + type + '\',\'' + option + '\');" onmousedown="return false;" class="browse">'; html += '<span id="' + id + '" title="' + tinyMCEPopup.getLang('browse') + '">&nbsp;</span></a>'; return html; } function openBrowser(img_id, target_form_element, type, option) { var img = document.getElementById(img_id); if (img.className != "mceButtonDisabled") tinyMCEPopup.openBrowser(target_form_element, type, option); } function selectByValue(form_obj, field_name, value, add_custom, ignore_case) { if (!form_obj || !form_obj.elements[field_name]) return; if (!value) value = ""; var sel = form_obj.elements[field_name]; var found = false; for (var i=0; i<sel.options.length; i++) { var option = sel.options[i]; if (option.value == value || (ignore_case && option.value.toLowerCase() == value.toLowerCase())) { option.selected = true; found = true; } else option.selected = false; } if (!found && add_custom && value != '') { var option = new Option(value, value); option.selected = true; sel.options[sel.options.length] = option; sel.selectedIndex = sel.options.length - 1; } return found; } function getSelectValue(form_obj, field_name) { var elm = form_obj.elements[field_name]; if (elm == null || elm.options == null || elm.selectedIndex === -1) return ""; return elm.options[elm.selectedIndex].value; } function addSelectValue(form_obj, field_name, name, value) { var s = form_obj.elements[field_name]; var o = new Option(name, value); s.options[s.options.length] = o; } function addClassesToList(list_id, specific_option) { // Setup class droplist var styleSelectElm = document.getElementById(list_id); var styles = tinyMCEPopup.getParam('theme_advanced_styles', false); styles = tinyMCEPopup.getParam(specific_option, styles); if (styles) { var stylesAr = styles.split(';'); for (var i=0; i<stylesAr.length; i++) { if (stylesAr != "") { var key, value; key = stylesAr[i].split('=')[0]; value = stylesAr[i].split('=')[1]; styleSelectElm.options[styleSelectElm.length] = new Option(key, value); } } } else { tinymce.each(tinyMCEPopup.editor.dom.getClasses(), function(o) { styleSelectElm.options[styleSelectElm.length] = new Option(o.title || o['class'], o['class']); }); } } function isVisible(element_id) { var elm = document.getElementById(element_id); return elm && elm.style.display != "none"; } function convertRGBToHex(col) { var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi"); var rgb = col.replace(re, "$1,$2,$3").split(','); if (rgb.length == 3) { r = parseInt(rgb[0]).toString(16); g = parseInt(rgb[1]).toString(16); b = parseInt(rgb[2]).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; return "#" + r + g + b; } return col; } function convertHexToRGB(col) { if (col.indexOf('#') != -1) { col = col.replace(new RegExp('[^0-9A-F]', 'gi'), ''); r = parseInt(col.substring(0, 2), 16); g = parseInt(col.substring(2, 4), 16); b = parseInt(col.substring(4, 6), 16); return "rgb(" + r + "," + g + "," + b + ")"; } return col; } function trimSize(size) { return size.replace(/([0-9\.]+)(px|%|in|cm|mm|em|ex|pt|pc)/i, '$1$2'); } function getCSSSize(size) { size = trimSize(size); if (size == "") return ""; // Add px if (/^[0-9]+$/.test(size)) size += 'px'; // Sanity check, IE doesn't like broken values else if (!(/^[0-9\.]+(px|%|in|cm|mm|em|ex|pt|pc)$/i.test(size))) return ""; return size; } function getStyle(elm, attrib, style) { var val = tinyMCEPopup.dom.getAttrib(elm, attrib); if (val != '') return '' + val; if (typeof(style) == 'undefined') style = attrib; return tinyMCEPopup.dom.getStyle(elm, style); }
zyblog
trunk/zyblog/wp-includes/js/tinymce/utils/form_utils.js
JavaScript
asf20
5,781
window.wp = window.wp || {}; (function( exports, $ ){ var api = wp.customize, Loader; $.extend( $.support, { history: !! ( window.history && history.pushState ), hashchange: ('onhashchange' in window) && (document.documentMode === undefined || document.documentMode > 7) }); Loader = $.extend( {}, api.Events, { initialize: function() { this.body = $( document.body ); // Ensure the loader is supported. // Check for settings, postMessage support, and whether we require CORS support. if ( ! Loader.settings || ! $.support.postMessage || ( ! $.support.cors && Loader.settings.isCrossDomain ) ) { return; } this.window = $( window ); this.element = $( '<div id="customize-container" />' ).appendTo( this.body ); this.bind( 'open', this.overlay.show ); this.bind( 'close', this.overlay.hide ); $('#wpbody').on( 'click', '.load-customize', function( event ) { event.preventDefault(); // Store a reference to the link that opened the customizer. Loader.link = $(this); // Load the theme. Loader.open( Loader.link.attr('href') ); }); // Add navigation listeners. if ( $.support.history ) this.window.on( 'popstate', Loader.popstate ); if ( $.support.hashchange ) { this.window.on( 'hashchange', Loader.hashchange ); this.window.triggerHandler( 'hashchange' ); } }, popstate: function( e ) { var state = e.originalEvent.state; if ( state && state.customize ) Loader.open( state.customize ); else if ( Loader.active ) Loader.close(); }, hashchange: function( e ) { var hash = window.location.toString().split('#')[1]; if ( hash && 0 === hash.indexOf( 'wp_customize=on' ) ) Loader.open( Loader.settings.url + '?' + hash ); if ( ! hash && ! $.support.history ) Loader.close(); }, open: function( src ) { var hash; if ( this.active ) return; // Load the full page on mobile devices. if ( Loader.settings.browser.mobile ) return window.location = src; this.active = true; this.body.addClass('customize-loading'); this.iframe = $( '<iframe />', { src: src }).appendTo( this.element ); this.iframe.one( 'load', this.loaded ); // Create a postMessage connection with the iframe. this.messenger = new api.Messenger({ url: src, channel: 'loader', targetWindow: this.iframe[0].contentWindow }); // Wait for the connection from the iframe before sending any postMessage events. this.messenger.bind( 'ready', function() { Loader.messenger.send( 'back' ); }); this.messenger.bind( 'close', function() { if ( $.support.history ) history.back(); else if ( $.support.hashchange ) window.location.hash = ''; else Loader.close(); }); this.messenger.bind( 'activated', function( location ) { if ( location ) window.location = location; }); hash = src.split('?')[1]; // Ensure we don't call pushState if the user hit the forward button. if ( $.support.history && window.location.href !== src ) history.pushState( { customize: src }, '', src ); else if ( ! $.support.history && $.support.hashchange && hash ) window.location.hash = 'wp_customize=on&' + hash; this.trigger( 'open' ); }, opened: function() { Loader.body.addClass( 'customize-active full-overlay-active' ); }, close: function() { if ( ! this.active ) return; this.active = false; this.trigger( 'close' ); // Return focus to link that was originally clicked. if ( this.link ) this.link.focus(); }, closed: function() { Loader.iframe.remove(); Loader.messenger.destroy(); Loader.iframe = null; Loader.messenger = null; Loader.body.removeClass( 'customize-active full-overlay-active' ).removeClass( 'customize-loading' ); }, loaded: function() { Loader.body.removeClass('customize-loading'); }, overlay: { show: function() { this.element.fadeIn( 200, Loader.opened ); }, hide: function() { this.element.fadeOut( 200, Loader.closed ); } } }); $( function() { Loader.settings = _wpCustomizeLoaderSettings; Loader.initialize(); }); // Expose the API to the world. api.Loader = Loader; })( wp, jQuery );
zyblog
trunk/zyblog/wp-includes/js/customize-loader.js
JavaScript
asf20
4,244
/* http://www.JSON.org/json2.js 2011-02-23 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, strict: false, regexp: false */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. var JSON; if (!JSON) { JSON = {}; } (function () { "use strict"; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function (key) { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function (key) { return this.valueOf(); }; } var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, gap, indent, meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }());
zyblog
trunk/zyblog/wp-includes/js/json2.js
JavaScript
asf20
17,413
addComment = { moveForm : function(commId, parentId, respondId, postId) { var t = this, div, comm = t.I(commId), respond = t.I(respondId), cancel = t.I('cancel-comment-reply-link'), parent = t.I('comment_parent'), post = t.I('comment_post_ID'); if ( ! comm || ! respond || ! cancel || ! parent ) return; t.respondId = respondId; postId = postId || false; if ( ! t.I('wp-temp-form-div') ) { div = document.createElement('div'); div.id = 'wp-temp-form-div'; div.style.display = 'none'; respond.parentNode.insertBefore(div, respond); } comm.parentNode.insertBefore(respond, comm.nextSibling); if ( post && postId ) post.value = postId; parent.value = parentId; cancel.style.display = ''; cancel.onclick = function() { var t = addComment, temp = t.I('wp-temp-form-div'), respond = t.I(t.respondId); if ( ! temp || ! respond ) return; t.I('comment_parent').value = '0'; temp.parentNode.insertBefore(respond, temp); temp.parentNode.removeChild(temp); this.style.display = 'none'; this.onclick = null; return false; } try { t.I('comment').focus(); } catch(e) {} return false; }, I : function(e) { return document.getElementById(e); } }
zyblog
trunk/zyblog/wp-includes/js/comment-reply.js
JavaScript
asf20
1,222
(function($){ var media = wp.media, Attachment = media.model.Attachment, Attachments = media.model.Attachments, Query = media.model.Query, l10n; // Link any localized strings. l10n = media.view.l10n = typeof _wpMediaViewsL10n === 'undefined' ? {} : _wpMediaViewsL10n; // Link any settings. media.view.settings = l10n.settings || {}; delete l10n.settings; // Copy the `post` setting over to the model settings. media.model.settings.post = media.view.settings.post; // Check if the browser supports CSS 3.0 transitions $.support.transition = (function(){ var style = document.documentElement.style, transitions = { WebkitTransition: 'webkitTransitionEnd', MozTransition: 'transitionend', OTransition: 'oTransitionEnd otransitionend', transition: 'transitionend' }, transition; transition = _.find( _.keys( transitions ), function( transition ) { return ! _.isUndefined( style[ transition ] ); }); return transition && { end: transitions[ transition ] }; }()); // Makes it easier to bind events using transitions. media.transition = function( selector, sensitivity ) { var deferred = $.Deferred(); sensitivity = sensitivity || 2000; if ( $.support.transition ) { if ( ! (selector instanceof $) ) selector = $( selector ); // Resolve the deferred when the first element finishes animating. selector.first().one( $.support.transition.end, deferred.resolve ); // Just in case the event doesn't trigger, fire a callback. _.delay( deferred.resolve, sensitivity ); // Otherwise, execute on the spot. } else { deferred.resolve(); } return deferred.promise(); }; /** * ======================================================================== * CONTROLLERS * ======================================================================== */ /** * wp.media.controller.Region */ media.controller.Region = function( options ) { _.extend( this, _.pick( options || {}, 'id', 'view', 'selector' ) ); }; // Use Backbone's self-propagating `extend` inheritance method. media.controller.Region.extend = Backbone.Model.extend; _.extend( media.controller.Region.prototype, { mode: function( mode ) { if ( ! mode ) return this._mode; // Bail if we're trying to change to the current mode. if ( mode === this._mode ) return this; this.trigger('deactivate'); this._mode = mode; this.render( mode ); this.trigger('activate'); return this; }, render: function( mode ) { // If no mode is provided, just re-render the current mode. // If the provided mode isn't active, perform a full switch. if ( mode && mode !== this._mode ) return this.mode( mode ); var set = { view: null }, view; this.trigger( 'create', set ); view = set.view; this.trigger( 'render', view ); if ( view ) this.set( view ); return this; }, get: function() { return this.view.views.first( this.selector ); }, set: function( views, options ) { if ( options ) options.add = false; return this.view.views.set( this.selector, views, options ); }, trigger: function( event ) { var base; if ( ! this._mode ) return; var args = _.toArray( arguments ); base = this.id + ':' + event; // Trigger `region:action:mode` event. args[0] = base + ':' + this._mode; this.view.trigger.apply( this.view, args ); // Trigger `region:action` event. args[0] = base; this.view.trigger.apply( this.view, args ); return this; } }); /** * wp.media.controller.StateMachine */ media.controller.StateMachine = function( states ) { this.states = new Backbone.Collection( states ); }; // Use Backbone's self-propagating `extend` inheritance method. media.controller.StateMachine.extend = Backbone.Model.extend; // Add events to the `StateMachine`. _.extend( media.controller.StateMachine.prototype, Backbone.Events, { // Fetch a state. // // If no `id` is provided, returns the active state. // // Implicitly creates states. state: function( id ) { // Ensure that the `states` collection exists so the `StateMachine` // can be used as a mixin. this.states = this.states || new Backbone.Collection(); // Default to the active state. id = id || this._state; if ( id && ! this.states.get( id ) ) this.states.add({ id: id }); return this.states.get( id ); }, // Sets the active state. setState: function( id ) { var previous = this.state(); // Bail if we're trying to select the current state, if we haven't // created the `states` collection, or are trying to select a state // that does not exist. if ( ( previous && id === previous.id ) || ! this.states || ! this.states.get( id ) ) return this; if ( previous ) { previous.trigger('deactivate'); this._lastState = previous.id; } this._state = id; this.state().trigger('activate'); return this; }, // Returns the previous active state. // // Call the `state()` method with no parameters to retrieve the current // active state. lastState: function() { if ( this._lastState ) return this.state( this._lastState ); } }); // Map methods from the `states` collection to the `StateMachine` itself. _.each([ 'on', 'off', 'trigger' ], function( method ) { media.controller.StateMachine.prototype[ method ] = function() { // Ensure that the `states` collection exists so the `StateMachine` // can be used as a mixin. this.states = this.states || new Backbone.Collection(); // Forward the method to the `states` collection. this.states[ method ].apply( this.states, arguments ); return this; }; }); // wp.media.controller.State // --------------------------- media.controller.State = Backbone.Model.extend({ constructor: function() { this.on( 'activate', this._preActivate, this ); this.on( 'activate', this.activate, this ); this.on( 'activate', this._postActivate, this ); this.on( 'deactivate', this._deactivate, this ); this.on( 'deactivate', this.deactivate, this ); this.on( 'reset', this.reset, this ); this.on( 'ready', this._ready, this ); this.on( 'ready', this.ready, this ); this.on( 'change:menu', this._updateMenu, this ); Backbone.Model.apply( this, arguments ); }, ready: function() {}, activate: function() {}, deactivate: function() {}, reset: function() {}, _ready: function() { this._updateMenu(); }, _preActivate: function() { this.active = true; }, _postActivate: function() { this.on( 'change:menu', this._menu, this ); this.on( 'change:titleMode', this._title, this ); this.on( 'change:content', this._content, this ); this.on( 'change:toolbar', this._toolbar, this ); this.frame.on( 'title:render:default', this._renderTitle, this ); this._title(); this._menu(); this._toolbar(); this._content(); this._router(); }, _deactivate: function() { this.active = false; this.frame.off( 'title:render:default', this._renderTitle, this ); this.off( 'change:menu', this._menu, this ); this.off( 'change:titleMode', this._title, this ); this.off( 'change:content', this._content, this ); this.off( 'change:toolbar', this._toolbar, this ); }, _title: function() { this.frame.title.render( this.get('titleMode') || 'default' ); }, _renderTitle: function( view ) { view.$el.text( this.get('title') || '' ); }, _router: function() { var router = this.frame.router, mode = this.get('router'), view; this.frame.$el.toggleClass( 'hide-router', ! mode ); if ( ! mode ) return; this.frame.router.render( mode ); view = router.get(); if ( view && view.select ) view.select( this.frame.content.mode() ); }, _menu: function() { var menu = this.frame.menu, mode = this.get('menu'), view; if ( ! mode ) return; menu.mode( mode ); view = menu.get(); if ( view && view.select ) view.select( this.id ); }, _updateMenu: function() { var previous = this.previous('menu'), menu = this.get('menu'); if ( previous ) this.frame.off( 'menu:render:' + previous, this._renderMenu, this ); if ( menu ) this.frame.on( 'menu:render:' + menu, this._renderMenu, this ); }, _renderMenu: function( view ) { var menuItem = this.get('menuItem'), title = this.get('title'), priority = this.get('priority'); if ( ! menuItem && title ) { menuItem = { text: title }; if ( priority ) menuItem.priority = priority; } if ( ! menuItem ) return; view.set( this.id, menuItem ); } }); _.each(['toolbar','content'], function( region ) { media.controller.State.prototype[ '_' + region ] = function() { var mode = this.get( region ); if ( mode ) this.frame[ region ].render( mode ); }; }); // wp.media.controller.Library // --------------------------- media.controller.Library = media.controller.State.extend({ defaults: { id: 'library', multiple: false, // false, 'add', 'reset' describe: false, toolbar: 'select', sidebar: 'settings', content: 'upload', router: 'browse', menu: 'default', searchable: true, filterable: false, sortable: true, title: l10n.mediaLibraryTitle, // Uses a user setting to override the content mode. contentUserSetting: true, // Sync the selection from the last state when 'multiple' matches. syncSelection: true }, initialize: function() { var selection = this.get('selection'), props; // If a library isn't provided, query all media items. if ( ! this.get('library') ) this.set( 'library', media.query() ); // If a selection instance isn't provided, create one. if ( ! (selection instanceof media.model.Selection) ) { props = selection; if ( ! props ) { props = this.get('library').props.toJSON(); props = _.omit( props, 'orderby', 'query' ); } // If the `selection` attribute is set to an object, // it will use those values as the selection instance's // `props` model. Otherwise, it will copy the library's // `props` model. this.set( 'selection', new media.model.Selection( null, { multiple: this.get('multiple'), props: props }) ); } if ( ! this.get('edge') ) this.set( 'edge', 120 ); if ( ! this.get('gutter') ) this.set( 'gutter', 8 ); this.resetDisplays(); }, activate: function() { this.syncSelection(); wp.Uploader.queue.on( 'add', this.uploading, this ); this.get('selection').on( 'add remove reset', this.refreshContent, this ); this.on( 'insert', this._insertDisplaySettings, this ); if ( this.get('contentUserSetting') ) { this.frame.on( 'content:activate', this.saveContentMode, this ); this.set( 'content', getUserSetting( 'libraryContent', this.get('content') ) ); } }, deactivate: function() { this.recordSelection(); this.frame.off( 'content:activate', this.saveContentMode, this ); // Unbind all event handlers that use this state as the context // from the selection. this.get('selection').off( null, null, this ); wp.Uploader.queue.off( null, null, this ); }, reset: function() { this.get('selection').reset(); this.resetDisplays(); this.refreshContent(); }, resetDisplays: function() { this._displays = []; this._defaultDisplaySettings = { align: getUserSetting( 'align', 'none' ), size: getUserSetting( 'imgsize', 'medium' ), link: getUserSetting( 'urlbutton', 'post' ) }; }, display: function( attachment ) { var displays = this._displays; if ( ! displays[ attachment.cid ] ) displays[ attachment.cid ] = new Backbone.Model( this._defaultDisplaySettings ); return displays[ attachment.cid ]; }, _insertDisplaySettings: function() { var selection = this.get('selection'), display; // If inserting one image, set those display properties as the // default user setting. if ( selection.length !== 1 ) return; display = this.display( selection.first() ).toJSON(); setUserSetting( 'align', display.align ); setUserSetting( 'imgsize', display.size ); setUserSetting( 'urlbutton', display.link ); }, syncSelection: function() { var selection = this.get('selection'), manager = this.frame._selection; if ( ! this.get('syncSelection') || ! manager || ! selection ) return; // If the selection supports multiple items, validate the stored // attachments based on the new selection's conditions. Record // the attachments that are not included; we'll maintain a // reference to those. Other attachments are considered in flux. if ( selection.multiple ) { selection.reset( [], { silent: true }); selection.validateAll( manager.attachments ); manager.difference = _.difference( manager.attachments.models, selection.models ); } // Sync the selection's single item with the master. selection.single( manager.single ); }, recordSelection: function() { var selection = this.get('selection'), manager = this.frame._selection, filtered; if ( ! this.get('syncSelection') || ! manager || ! selection ) return; // Record the currently active attachments, which is a combination // of the selection's attachments and the set of selected // attachments that this specific selection considered invalid. // Reset the difference and record the single attachment. if ( selection.multiple ) { manager.attachments.reset( selection.toArray().concat( manager.difference ) ); manager.difference = []; } else { manager.attachments.add( selection.toArray() ); } manager.single = selection._single; }, refreshContent: function() { var selection = this.get('selection'), frame = this.frame, router = frame.router.get(), mode = frame.content.mode(); if ( this.active && ! selection.length && ! router.get( mode ) ) this.frame.content.render( this.get('content') ); }, uploading: function( attachment ) { var content = this.frame.content; // If the uploader was selected, navigate to the browser. if ( 'upload' === content.mode() ) this.frame.content.mode('browse'); // If we're in a workflow that supports multiple attachments, // automatically select any uploading attachments. if ( this.get('multiple') ) this.get('selection').add( attachment ); }, saveContentMode: function() { // Only track the browse router on library states. if ( 'browse' !== this.get('router') ) return; var mode = this.frame.content.mode(), view = this.frame.router.get(); if ( view && view.get( mode ) ) setUserSetting( 'libraryContent', mode ); } }); // wp.media.controller.GalleryEdit // ------------------------------- media.controller.GalleryEdit = media.controller.Library.extend({ defaults: { id: 'gallery-edit', multiple: false, describe: true, edge: 199, editing: false, sortable: true, searchable: false, toolbar: 'gallery-edit', content: 'browse', title: l10n.editGalleryTitle, priority: 60, dragInfo: true, // Don't sync the selection, as the Edit Gallery library // *is* the selection. syncSelection: false }, initialize: function() { // If we haven't been provided a `library`, create a `Selection`. if ( ! this.get('library') ) this.set( 'library', new media.model.Selection() ); // The single `Attachment` view to be used in the `Attachments` view. if ( ! this.get('AttachmentView') ) this.set( 'AttachmentView', media.view.Attachment.EditLibrary ); media.controller.Library.prototype.initialize.apply( this, arguments ); }, activate: function() { var library = this.get('library'); // Limit the library to images only. library.props.set( 'type', 'image' ); // Watch for uploaded attachments. this.get('library').observe( wp.Uploader.queue ); this.frame.on( 'content:render:browse', this.gallerySettings, this ); media.controller.Library.prototype.activate.apply( this, arguments ); }, deactivate: function() { // Stop watching for uploaded attachments. this.get('library').unobserve( wp.Uploader.queue ); this.frame.off( 'content:render:browse', this.gallerySettings, this ); media.controller.Library.prototype.deactivate.apply( this, arguments ); }, gallerySettings: function( browser ) { var library = this.get('library'); if ( ! library || ! browser ) return; library.gallery = library.gallery || new Backbone.Model(); browser.sidebar.set({ gallery: new media.view.Settings.Gallery({ controller: this, model: library.gallery, priority: 40 }) }); browser.toolbar.set( 'reverse', { text: l10n.reverseOrder, priority: 80, click: function() { library.reset( library.toArray().reverse() ); } }); } }); // wp.media.controller.GalleryAdd // --------------------------------- media.controller.GalleryAdd = media.controller.Library.extend({ defaults: _.defaults({ id: 'gallery-library', filterable: 'uploaded', multiple: 'add', menu: 'gallery', toolbar: 'gallery-add', title: l10n.addToGalleryTitle, priority: 100, // Don't sync the selection, as the Edit Gallery library // *is* the selection. syncSelection: false }, media.controller.Library.prototype.defaults ), initialize: function() { // If we haven't been provided a `library`, create a `Selection`. if ( ! this.get('library') ) this.set( 'library', media.query({ type: 'image' }) ); media.controller.Library.prototype.initialize.apply( this, arguments ); }, activate: function() { var library = this.get('library'), edit = this.frame.state('gallery-edit').get('library'); if ( this.editLibrary && this.editLibrary !== edit ) library.unobserve( this.editLibrary ); // Accepts attachments that exist in the original library and // that do not exist in gallery's library. library.validator = function( attachment ) { return !! this.mirroring.getByCid( attachment.cid ) && ! edit.getByCid( attachment.cid ) && media.model.Selection.prototype.validator.apply( this, arguments ); }; library.observe( edit ); this.editLibrary = edit; media.controller.Library.prototype.activate.apply( this, arguments ); } }); // wp.media.controller.FeaturedImage // --------------------------------- media.controller.FeaturedImage = media.controller.Library.extend({ defaults: _.defaults({ id: 'featured-image', filterable: 'uploaded', multiple: false, toolbar: 'featured-image', title: l10n.setFeaturedImageTitle, priority: 60, syncSelection: false }, media.controller.Library.prototype.defaults ), initialize: function() { var library, comparator; // If we haven't been provided a `library`, create a `Selection`. if ( ! this.get('library') ) this.set( 'library', media.query({ type: 'image' }) ); media.controller.Library.prototype.initialize.apply( this, arguments ); library = this.get('library'); comparator = library.comparator; // Overload the library's comparator to push items that are not in // the mirrored query to the front of the aggregate collection. library.comparator = function( a, b ) { var aInQuery = !! this.mirroring.getByCid( a.cid ), bInQuery = !! this.mirroring.getByCid( b.cid ); if ( ! aInQuery && bInQuery ) return -1; else if ( aInQuery && ! bInQuery ) return 1; else return comparator.apply( this, arguments ); }; // Add all items in the selection to the library, so any featured // images that are not initially loaded still appear. library.observe( this.get('selection') ); }, activate: function() { this.updateSelection(); this.frame.on( 'open', this.updateSelection, this ); media.controller.Library.prototype.activate.apply( this, arguments ); }, deactivate: function() { this.frame.off( 'open', this.updateSelection, this ); media.controller.Library.prototype.deactivate.apply( this, arguments ); }, updateSelection: function() { var selection = this.get('selection'), id = media.view.settings.post.featuredImageId, attachment; if ( '' !== id && -1 !== id ) { attachment = Attachment.get( id ); attachment.fetch(); } selection.reset( attachment ? [ attachment ] : [] ); } }); // wp.media.controller.Embed // ------------------------- media.controller.Embed = media.controller.State.extend({ defaults: { id: 'embed', url: '', menu: 'default', content: 'embed', toolbar: 'main-embed', type: 'link', title: l10n.insertFromUrlTitle, priority: 120 }, // The amount of time used when debouncing the scan. sensitivity: 200, initialize: function() { this.debouncedScan = _.debounce( _.bind( this.scan, this ), this.sensitivity ); this.props = new Backbone.Model({ url: '' }); this.props.on( 'change:url', this.debouncedScan, this ); this.props.on( 'change:url', this.refresh, this ); this.on( 'scan', this.scanImage, this ); }, scan: function() { var scanners, embed = this, attributes = { type: 'link', scanners: [] }; // Scan is triggered with the list of `attributes` to set on the // state, useful for the 'type' attribute and 'scanners' attribute, // an array of promise objects for asynchronous scan operations. if ( this.props.get('url') ) this.trigger( 'scan', attributes ); if ( attributes.scanners.length ) { scanners = attributes.scanners = $.when.apply( $, attributes.scanners ); scanners.always( function() { if ( embed.get('scanners') === scanners ) embed.set( 'loading', false ); }); } else { attributes.scanners = null; } attributes.loading = !! attributes.scanners; this.set( attributes ); }, scanImage: function( attributes ) { var frame = this.frame, state = this, url = this.props.get('url'), image = new Image(), deferred = $.Deferred(); attributes.scanners.push( deferred.promise() ); // Try to load the image and find its width/height. image.onload = function() { deferred.resolve(); if ( state !== frame.state() || url !== state.props.get('url') ) return; state.set({ type: 'image' }); state.props.set({ width: image.width, height: image.height }); }; image.onerror = deferred.reject; image.src = url; }, refresh: function() { this.frame.toolbar.get().refresh(); }, reset: function() { this.props.clear().set({ url: '' }); if ( this.active ) this.refresh(); } }); /** * ======================================================================== * VIEWS * ======================================================================== */ // wp.media.Views // ------------- // // A subview manager. media.Views = function( view, views ) { this.view = view; this._views = _.isArray( views ) ? { '': views } : views || {}; }; media.Views.extend = Backbone.Model.extend; _.extend( media.Views.prototype, { // ### Fetch all of the subviews // // Returns an array of all subviews. all: function() { return _.flatten( this._views ); }, // ### Get a selector's subviews // // Fetches all subviews that match a given `selector`. // // If no `selector` is provided, it will grab all subviews attached // to the view's root. get: function( selector ) { selector = selector || ''; return this._views[ selector ]; }, // ### Get a selector's first subview // // Fetches the first subview that matches a given `selector`. // // If no `selector` is provided, it will grab the first subview // attached to the view's root. // // Useful when a selector only has one subview at a time. first: function( selector ) { var views = this.get( selector ); return views && views.length ? views[0] : null; }, // ### Register subview(s) // // Registers any number of `views` to a `selector`. // // When no `selector` is provided, the root selector (the empty string) // is used. `views` accepts a `Backbone.View` instance or an array of // `Backbone.View` instances. // // --- // // Accepts an `options` object, which has a significant effect on the // resulting behavior. // // `options.silent` &ndash; *boolean, `false`* // > If `options.silent` is true, no DOM modifications will be made. // // `options.add` &ndash; *boolean, `false`* // > Use `Views.add()` as a shortcut for setting `options.add` to true. // // > By default, the provided `views` will replace // any existing views associated with the selector. If `options.add` // is true, the provided `views` will be added to the existing views. // // `options.at` &ndash; *integer, `undefined`* // > When adding, to insert `views` at a specific index, use // `options.at`. By default, `views` are added to the end of the array. set: function( selector, views, options ) { var existing, next; if ( ! _.isString( selector ) ) { options = views; views = selector; selector = ''; } options = options || {}; views = _.isArray( views ) ? views : [ views ]; existing = this.get( selector ); next = views; if ( existing ) { if ( options.add ) { if ( _.isUndefined( options.at ) ) { next = existing.concat( views ); } else { next = existing; next.splice.apply( next, [ options.at, 0 ].concat( views ) ); } } else { _.each( next, function( view ) { view.__detach = true; }); _.each( existing, function( view ) { if ( view.__detach ) view.$el.detach(); else view.dispose(); }); _.each( next, function( view ) { delete view.__detach; }); } } this._views[ selector ] = next; _.each( views, function( subview ) { var constructor = subview.Views || media.Views, subviews = subview.views = subview.views || new constructor( subview ); subviews.parent = this.view; subviews.selector = selector; }, this ); if ( ! options.silent ) this._attach( selector, views, _.extend({ ready: this._isReady() }, options ) ); return this; }, // ### Add subview(s) to existing subviews // // An alias to `Views.set()`, which defaults `options.add` to true. // // Adds any number of `views` to a `selector`. // // When no `selector` is provided, the root selector (the empty string) // is used. `views` accepts a `Backbone.View` instance or an array of // `Backbone.View` instances. // // Use `Views.set()` when setting `options.add` to `false`. // // Accepts an `options` object. By default, provided `views` will be // inserted at the end of the array of existing views. To insert // `views` at a specific index, use `options.at`. If `options.silent` // is true, no DOM modifications will be made. // // For more information on the `options` object, see `Views.set()`. add: function( selector, views, options ) { if ( ! _.isString( selector ) ) { options = views; views = selector; selector = ''; } return this.set( selector, views, _.extend({ add: true }, options ) ); }, // ### Stop tracking subviews // // Stops tracking `views` registered to a `selector`. If no `views` are // set, then all of the `selector`'s subviews will be unregistered and // disposed. // // Accepts an `options` object. If `options.silent` is set, `dispose` // will *not* be triggered on the unregistered views. unset: function( selector, views, options ) { var existing; if ( ! _.isString( selector ) ) { options = views; views = selector; selector = ''; } views = views || []; if ( existing = this.get( selector ) ) { views = _.isArray( views ) ? views : [ views ]; this._views[ selector ] = views.length ? _.difference( existing, views ) : []; } if ( ! options || ! options.silent ) _.invoke( views, 'dispose' ); return this; }, // ### Detach all subviews // // Detaches all subviews from the DOM. // // Helps to preserve all subview events when re-rendering the master // view. Used in conjunction with `Views.render()`. detach: function() { $( _.pluck( this.all(), 'el' ) ).detach(); return this; }, // ### Render all subviews // // Renders all subviews. Used in conjunction with `Views.detach()`. render: function() { var options = { ready: this._isReady() }; _.each( this._views, function( views, selector ) { this._attach( selector, views, options ); }, this ); this.rendered = true; return this; }, // ### Dispose all subviews // // Triggers the `dispose()` method on all subviews. Detaches the master // view from its parent. Resets the internals of the views manager. // // Accepts an `options` object. If `options.silent` is set, `unset` // will *not* be triggered on the master view's parent. dispose: function( options ) { if ( ! options || ! options.silent ) { if ( this.parent && this.parent.views ) this.parent.views.unset( this.selector, this.view, { silent: true }); delete this.parent; delete this.selector; } _.invoke( this.all(), 'dispose' ); this._views = []; return this; }, // ### Replace a selector's subviews // // By default, sets the `$target` selector's html to the subview `els`. // // Can be overridden in subclasses. replace: function( $target, els ) { $target.html( els ); return this; }, // ### Insert subviews into a selector // // By default, appends the subview `els` to the end of the `$target` // selector. If `options.at` is set, inserts the subview `els` at the // provided index. // // Can be overridden in subclasses. insert: function( $target, els, options ) { var at = options && options.at, $children; if ( _.isNumber( at ) && ($children = $target.children()).length > at ) $children.eq( at ).before( els ); else $target.append( els ); return this; }, // ### Trigger the ready event // // **Only use this method if you know what you're doing.** // For performance reasons, this method does not check if the view is // actually attached to the DOM. It's taking your word for it. // // Fires the ready event on the current view and all attached subviews. ready: function() { this.view.trigger('ready'); // Find all attached subviews, and call ready on them. _.chain( this.all() ).map( function( view ) { return view.views; }).flatten().where({ attached: true }).invoke('ready'); }, // #### Internal. Attaches a series of views to a selector. // // Checks to see if a matching selector exists, renders the views, // performs the proper DOM operation, and then checks if the view is // attached to the document. _attach: function( selector, views, options ) { var $selector = selector ? this.view.$( selector ) : this.view.$el, managers; // Check if we found a location to attach the views. if ( ! $selector.length ) return this; managers = _.chain( views ).pluck('views').flatten().value(); // Render the views if necessary. _.each( managers, function( manager ) { if ( manager.rendered ) return; manager.view.render(); manager.rendered = true; }, this ); // Insert or replace the views. this[ options.add ? 'insert' : 'replace' ]( $selector, _.pluck( views, 'el' ), options ); // Set attached and trigger ready if the current view is already // attached to the DOM. _.each( managers, function( manager ) { manager.attached = true; if ( options.ready ) manager.ready(); }, this ); return this; }, // #### Internal. Checks if the current view is in the DOM. _isReady: function() { var node = this.view.el; while ( node ) { if ( node === document.body ) return true; node = node.parentNode; } return false; } }); // wp.media.View // ------------- // // The base view class. media.View = Backbone.View.extend({ // The constructor for the `Views` manager. Views: media.Views, constructor: function( options ) { this.views = new this.Views( this, this.views ); this.on( 'ready', this.ready, this ); if ( options && options.controller ) this.controller = options.controller; Backbone.View.apply( this, arguments ); }, dispose: function() { // Undelegating events, removing events from the model, and // removing events from the controller mirror the code for // `Backbone.View.dispose` in Backbone master. this.undelegateEvents(); if ( this.model && this.model.off ) this.model.off( null, null, this ); if ( this.collection && this.collection.off ) this.collection.off( null, null, this ); // Unbind controller events. if ( this.controller && this.controller.off ) this.controller.off( null, null, this ); // Recursively dispose child views. if ( this.views ) this.views.dispose(); return this; }, remove: function() { this.dispose(); return Backbone.View.prototype.remove.apply( this, arguments ); }, render: function() { var options; if ( this.prepare ) options = this.prepare(); this.views.detach(); if ( this.template ) { options = options || {}; this.trigger( 'prepare', options ); this.$el.html( this.template( options ) ); } this.views.render(); return this; }, prepare: function() { return this.options; }, ready: function() {} }); /** * wp.media.view.Frame */ media.view.Frame = media.View.extend({ initialize: function() { this._createRegions(); this._createStates(); }, _createRegions: function() { // Clone the regions array. this.regions = this.regions ? this.regions.slice() : []; // Initialize regions. _.each( this.regions, function( region ) { this[ region ] = new media.controller.Region({ view: this, id: region, selector: '.media-frame-' + region }); }, this ); }, _createStates: function() { // Create the default `states` collection. this.states = new Backbone.Collection( null, { model: media.controller.State }); // Ensure states have a reference to the frame. this.states.on( 'add', function( model ) { model.frame = this; model.trigger('ready'); }, this ); if ( this.options.states ) this.states.add( this.options.states ); }, reset: function() { this.states.invoke( 'trigger', 'reset' ); return this; } }); // Make the `Frame` a `StateMachine`. _.extend( media.view.Frame.prototype, media.controller.StateMachine.prototype ); /** * wp.media.view.MediaFrame */ media.view.MediaFrame = media.view.Frame.extend({ className: 'media-frame', template: media.template('media-frame'), regions: ['menu','title','content','toolbar','router'], initialize: function() { media.view.Frame.prototype.initialize.apply( this, arguments ); _.defaults( this.options, { title: '', modal: true, uploader: true }); // Ensure core UI is enabled. this.$el.addClass('wp-core-ui'); // Initialize modal container view. if ( this.options.modal ) { this.modal = new media.view.Modal({ controller: this, title: this.options.title }); this.modal.content( this ); } // Force the uploader off if the upload limit has been exceeded or // if the browser isn't supported. if ( wp.Uploader.limitExceeded || ! wp.Uploader.browser.supported ) this.options.uploader = false; // Initialize window-wide uploader. if ( this.options.uploader ) { this.uploader = new media.view.UploaderWindow({ controller: this, uploader: { dropzone: this.modal ? this.modal.$el : this.$el, container: this.$el } }); this.views.set( '.media-frame-uploader', this.uploader ); } this.on( 'attach', _.bind( this.views.ready, this.views ), this ); // Bind default title creation. this.on( 'title:create:default', this.createTitle, this ); this.title.mode('default'); // Bind default menu. this.on( 'menu:create:default', this.createMenu, this ); }, render: function() { // Activate the default state if no active state exists. if ( ! this.state() && this.options.state ) this.setState( this.options.state ); return media.view.Frame.prototype.render.apply( this, arguments ); }, createTitle: function( title ) { title.view = new media.View({ controller: this, tagName: 'h1' }); }, createMenu: function( menu ) { menu.view = new media.view.Menu({ controller: this }); }, createToolbar: function( toolbar ) { toolbar.view = new media.view.Toolbar({ controller: this }); }, createRouter: function( router ) { router.view = new media.view.Router({ controller: this }); }, createIframeStates: function( options ) { var settings = media.view.settings, tabs = settings.tabs, tabUrl = settings.tabUrl, $postId; if ( ! tabs || ! tabUrl ) return; // Add the post ID to the tab URL if it exists. $postId = $('#post_ID'); if ( $postId.length ) tabUrl += '&post_id=' + $postId.val(); // Generate the tab states. _.each( tabs, function( title, id ) { var frame = this.state( 'iframe:' + id ).set( _.defaults({ tab: id, src: tabUrl + '&tab=' + id, title: title, content: 'iframe', menu: 'default' }, options ) ); }, this ); this.on( 'content:create:iframe', this.iframeContent, this ); this.on( 'menu:render:default', this.iframeMenu, this ); this.on( 'open', this.hijackThickbox, this ); this.on( 'close', this.restoreThickbox, this ); }, iframeContent: function( content ) { this.$el.addClass('hide-toolbar'); content.view = new media.view.Iframe({ controller: this }); }, iframeMenu: function( view ) { var views = {}; if ( ! view ) return; _.each( media.view.settings.tabs, function( title, id ) { views[ 'iframe:' + id ] = { text: this.state( 'iframe:' + id ).get('title'), priority: 200 }; }, this ); view.set( views ); }, hijackThickbox: function() { var frame = this; if ( ! window.tb_remove || this._tb_remove ) return; this._tb_remove = window.tb_remove; window.tb_remove = function() { frame.close(); frame.reset(); frame.setState( frame.options.state ); frame._tb_remove.call( window ); }; }, restoreThickbox: function() { if ( ! this._tb_remove ) return; window.tb_remove = this._tb_remove; delete this._tb_remove; } }); // Map some of the modal's methods to the frame. _.each(['open','close','attach','detach','escape'], function( method ) { media.view.MediaFrame.prototype[ method ] = function( view ) { if ( this.modal ) this.modal[ method ].apply( this.modal, arguments ); return this; }; }); /** * wp.media.view.MediaFrame.Select */ media.view.MediaFrame.Select = media.view.MediaFrame.extend({ initialize: function() { media.view.MediaFrame.prototype.initialize.apply( this, arguments ); _.defaults( this.options, { selection: [], library: {}, multiple: false, state: 'library' }); this.createSelection(); this.createStates(); this.bindHandlers(); }, createSelection: function() { var controller = this, selection = this.options.selection; if ( ! (selection instanceof media.model.Selection) ) { this.options.selection = new media.model.Selection( selection, { multiple: this.options.multiple }); } this._selection = { attachments: new Attachments(), difference: [] }; }, createStates: function() { var options = this.options; if ( this.options.states ) return; // Add the default states. this.states.add([ // Main states. new media.controller.Library({ library: media.query( options.library ), multiple: options.multiple, title: options.title, priority: 20 }) ]); }, bindHandlers: function() { this.on( 'router:create:browse', this.createRouter, this ); this.on( 'router:render:browse', this.browseRouter, this ); this.on( 'content:create:browse', this.browseContent, this ); this.on( 'content:render:upload', this.uploadContent, this ); this.on( 'toolbar:create:select', this.createSelectToolbar, this ); }, // Routers browseRouter: function( view ) { view.set({ upload: { text: l10n.uploadFilesTitle, priority: 20 }, browse: { text: l10n.mediaLibraryTitle, priority: 40 } }); }, // Content browseContent: function( content ) { var state = this.state(); this.$el.removeClass('hide-toolbar'); // Browse our library of attachments. content.view = new media.view.AttachmentsBrowser({ controller: this, collection: state.get('library'), selection: state.get('selection'), model: state, sortable: state.get('sortable'), search: state.get('searchable'), filters: state.get('filterable'), display: state.get('displaySettings'), dragInfo: state.get('dragInfo'), AttachmentView: state.get('AttachmentView') }); }, uploadContent: function() { this.$el.removeClass('hide-toolbar'); this.content.set( new media.view.UploaderInline({ controller: this }) ); }, // Toolbars createSelectToolbar: function( toolbar, options ) { options = options || this.options.button || {}; options.controller = this; toolbar.view = new media.view.Toolbar.Select( options ); } }); /** * wp.media.view.MediaFrame.Post */ media.view.MediaFrame.Post = media.view.MediaFrame.Select.extend({ initialize: function() { _.defaults( this.options, { multiple: true, editing: false, state: 'insert' }); media.view.MediaFrame.Select.prototype.initialize.apply( this, arguments ); this.createIframeStates(); }, createStates: function() { var options = this.options; // Add the default states. this.states.add([ // Main states. new media.controller.Library({ id: 'insert', title: l10n.insertMediaTitle, priority: 20, toolbar: 'main-insert', filterable: 'all', library: media.query( options.library ), multiple: options.multiple ? 'reset' : false, editable: true, // If the user isn't allowed to edit fields, // can they still edit it locally? allowLocalEdits: true, // Show the attachment display settings. displaySettings: true, // Update user settings when users adjust the // attachment display settings. displayUserSettings: true }), new media.controller.Library({ id: 'gallery', title: l10n.createGalleryTitle, priority: 40, toolbar: 'main-gallery', filterable: 'uploaded', multiple: 'add', editable: false, library: media.query( _.defaults({ type: 'image' }, options.library ) ) }), // Embed states. new media.controller.Embed(), // Gallery states. new media.controller.GalleryEdit({ library: options.selection, editing: options.editing, menu: 'gallery' }), new media.controller.GalleryAdd() ]); if ( media.view.settings.post.featuredImageId ) { this.states.add( new media.controller.FeaturedImage() ); } }, bindHandlers: function() { media.view.MediaFrame.Select.prototype.bindHandlers.apply( this, arguments ); this.on( 'menu:create:gallery', this.createMenu, this ); this.on( 'toolbar:create:main-insert', this.createToolbar, this ); this.on( 'toolbar:create:main-gallery', this.createToolbar, this ); this.on( 'toolbar:create:featured-image', this.featuredImageToolbar, this ); this.on( 'toolbar:create:main-embed', this.mainEmbedToolbar, this ); var handlers = { menu: { 'default': 'mainMenu', 'gallery': 'galleryMenu' }, content: { 'embed': 'embedContent', 'edit-selection': 'editSelectionContent' }, toolbar: { 'main-insert': 'mainInsertToolbar', 'main-gallery': 'mainGalleryToolbar', 'gallery-edit': 'galleryEditToolbar', 'gallery-add': 'galleryAddToolbar' } }; _.each( handlers, function( regionHandlers, region ) { _.each( regionHandlers, function( callback, handler ) { this.on( region + ':render:' + handler, this[ callback ], this ); }, this ); }, this ); }, // Menus mainMenu: function( view ) { view.set({ 'library-separator': new media.View({ className: 'separator', priority: 100 }) }); }, galleryMenu: function( view ) { var lastState = this.lastState(), previous = lastState && lastState.id, frame = this; view.set({ cancel: { text: l10n.cancelGalleryTitle, priority: 20, click: function() { if ( previous ) frame.setState( previous ); else frame.close(); } }, separateCancel: new media.View({ className: 'separator', priority: 40 }) }); }, // Content embedContent: function() { var view = new media.view.Embed({ controller: this, model: this.state() }).render(); this.content.set( view ); view.url.focus(); }, editSelectionContent: function() { var state = this.state(), selection = state.get('selection'), view; view = new media.view.AttachmentsBrowser({ controller: this, collection: selection, selection: selection, model: state, sortable: true, search: false, dragInfo: true, AttachmentView: media.view.Attachment.EditSelection }).render(); view.toolbar.set( 'backToLibrary', { text: l10n.returnToLibrary, priority: -100, click: function() { this.controller.content.mode('browse'); } }); // Browse our library of attachments. this.content.set( view ); }, // Toolbars selectionStatusToolbar: function( view ) { var editable = this.state().get('editable'); view.set( 'selection', new media.view.Selection({ controller: this, collection: this.state().get('selection'), priority: -40, // If the selection is editable, pass the callback to // switch the content mode. editable: editable && function() { this.controller.content.mode('edit-selection'); } }).render() ); }, mainInsertToolbar: function( view ) { var controller = this; this.selectionStatusToolbar( view ); view.set( 'insert', { style: 'primary', priority: 80, text: l10n.insertIntoPost, requires: { selection: true }, click: function() { var state = controller.state(), selection = state.get('selection'); controller.close(); state.trigger( 'insert', selection ).reset(); } }); }, mainGalleryToolbar: function( view ) { var controller = this; this.selectionStatusToolbar( view ); view.set( 'gallery', { style: 'primary', text: l10n.createNewGallery, priority: 60, requires: { selection: true }, click: function() { var selection = controller.state().get('selection'), edit = controller.state('gallery-edit'), models = selection.where({ type: 'image' }); edit.set( 'library', new media.model.Selection( models, { props: selection.props.toJSON(), multiple: true }) ); this.controller.setState('gallery-edit'); } }); }, featuredImageToolbar: function( toolbar ) { this.createSelectToolbar( toolbar, { text: l10n.setFeaturedImage, state: this.options.state || 'upload' }); }, mainEmbedToolbar: function( toolbar ) { toolbar.view = new media.view.Toolbar.Embed({ controller: this }); }, galleryEditToolbar: function() { var editing = this.state().get('editing'); this.toolbar.set( new media.view.Toolbar({ controller: this, items: { insert: { style: 'primary', text: editing ? l10n.updateGallery : l10n.insertGallery, priority: 80, requires: { library: true }, click: function() { var controller = this.controller, state = controller.state(); controller.close(); state.trigger( 'update', state.get('library') ); controller.reset(); // @todo: Make the state activated dynamic (instead of hardcoded). controller.setState('upload'); } } } }) ); }, galleryAddToolbar: function() { this.toolbar.set( new media.view.Toolbar({ controller: this, items: { insert: { style: 'primary', text: l10n.addToGallery, priority: 80, requires: { selection: true }, click: function() { var controller = this.controller, state = controller.state(), edit = controller.state('gallery-edit'); edit.get('library').add( state.get('selection').models ); state.trigger('reset'); controller.setState('gallery-edit'); } } } }) ); } }); /** * wp.media.view.Modal */ media.view.Modal = media.View.extend({ tagName: 'div', template: media.template('media-modal'), attributes: { tabindex: 0 }, events: { 'click .media-modal-backdrop, .media-modal-close': 'escapeHandler', 'keydown': 'keydown' }, initialize: function() { _.defaults( this.options, { container: document.body, title: '', propagate: true, freeze: true }); }, prepare: function() { return { title: this.options.title }; }, attach: function() { if ( this.views.attached ) return this; if ( ! this.views.rendered ) this.render(); this.$el.appendTo( this.options.container ); // Manually mark the view as attached and trigger ready. this.views.attached = true; this.views.ready(); return this.propagate('attach'); }, detach: function() { if ( this.$el.is(':visible') ) this.close(); this.$el.detach(); this.views.attached = false; return this.propagate('detach'); }, open: function() { var $el = this.$el, options = this.options; if ( $el.is(':visible') ) return this; if ( ! this.views.attached ) this.attach(); // If the `freeze` option is set, record the window's scroll position. if ( options.freeze ) { this._freeze = { scrollTop: $( window ).scrollTop() }; } $el.show().focus(); return this.propagate('open'); }, close: function( options ) { var freeze = this._freeze; if ( ! this.views.attached || ! this.$el.is(':visible') ) return this; this.$el.hide(); this.propagate('close'); // If the `freeze` option is set, restore the container's scroll position. if ( freeze ) { $( window ).scrollTop( freeze.scrollTop ); } if ( options && options.escape ) this.propagate('escape'); return this; }, escape: function() { return this.close({ escape: true }); }, escapeHandler: function( event ) { event.preventDefault(); this.escape(); }, content: function( content ) { this.views.set( '.media-modal-content', content ); return this; }, // Triggers a modal event and if the `propagate` option is set, // forwards events to the modal's controller. propagate: function( id ) { this.trigger( id ); if ( this.options.propagate ) this.controller.trigger( id ); return this; }, keydown: function( event ) { // Close the modal when escape is pressed. if ( 27 === event.which ) { event.preventDefault(); this.escape(); return; } } }); // wp.media.view.FocusManager // ---------------------------- media.view.FocusManager = media.View.extend({ events: { keydown: 'recordTab', focusin: 'updateIndex' }, focus: function() { if ( _.isUndefined( this.index ) ) return; // Update our collection of `$tabbables`. this.$tabbables = this.$(':tabbable'); // If tab is saved, focus it. this.$tabbables.eq( this.index ).focus(); }, recordTab: function( event ) { // Look for the tab key. if ( 9 !== event.keyCode ) return; // First try to update the index. if ( _.isUndefined( this.index ) ) this.updateIndex( event ); // If we still don't have an index, bail. if ( _.isUndefined( this.index ) ) return; var index = this.index + ( event.shiftKey ? -1 : 1 ); if ( index >= 0 && index < this.$tabbables.length ) this.index = index; else delete this.index; }, updateIndex: function( event ) { this.$tabbables = this.$(':tabbable'); var index = this.$tabbables.index( event.target ); if ( -1 === index ) delete this.index; else this.index = index; } }); // wp.media.view.UploaderWindow // ---------------------------- media.view.UploaderWindow = media.View.extend({ tagName: 'div', className: 'uploader-window', template: media.template('uploader-window'), initialize: function() { var uploader; this.$browser = $('<a href="#" class="browser" />').hide().appendTo('body'); uploader = this.options.uploader = _.defaults( this.options.uploader || {}, { dropzone: this.$el, browser: this.$browser, params: {} }); // Ensure the dropzone is a jQuery collection. if ( uploader.dropzone && ! (uploader.dropzone instanceof $) ) uploader.dropzone = $( uploader.dropzone ); this.controller.on( 'activate', this.refresh, this ); }, refresh: function() { if ( this.uploader ) this.uploader.refresh(); }, ready: function() { var postId = media.view.settings.post.id, dropzone; // If the uploader already exists, bail. if ( this.uploader ) return; if ( postId ) this.options.uploader.params.post_id = postId; this.uploader = new wp.Uploader( this.options.uploader ); dropzone = this.uploader.dropzone; dropzone.on( 'dropzone:enter', _.bind( this.show, this ) ); dropzone.on( 'dropzone:leave', _.bind( this.hide, this ) ); }, show: function() { var $el = this.$el.show(); // Ensure that the animation is triggered by waiting until // the transparent element is painted into the DOM. _.defer( function() { $el.css({ opacity: 1 }); }); }, hide: function() { var $el = this.$el.css({ opacity: 0 }); media.transition( $el ).done( function() { // Transition end events are subject to race conditions. // Make sure that the value is set as intended. if ( '0' === $el.css('opacity') ) $el.hide(); }); } }); media.view.UploaderInline = media.View.extend({ tagName: 'div', className: 'uploader-inline', template: media.template('uploader-inline'), initialize: function() { _.defaults( this.options, { message: '', status: true }); if ( ! this.options.$browser && this.controller.uploader ) this.options.$browser = this.controller.uploader.$browser; if ( _.isUndefined( this.options.postId ) ) this.options.postId = media.view.settings.post.id; if ( this.options.status ) { this.views.set( '.upload-inline-status', new media.view.UploaderStatus({ controller: this.controller }) ); } }, dispose: function() { if ( this.disposing ) return media.View.prototype.dispose.apply( this, arguments ); // Run remove on `dispose`, so we can be sure to refresh the // uploader with a view-less DOM. Track whether we're disposing // so we don't trigger an infinite loop. this.disposing = true; return this.remove(); }, remove: function() { var result = media.View.prototype.remove.apply( this, arguments ); _.defer( _.bind( this.refresh, this ) ); return result; }, refresh: function() { var uploader = this.controller.uploader; if ( uploader ) uploader.refresh(); }, ready: function() { var $browser = this.options.$browser, $placeholder; if ( this.controller.uploader ) { $placeholder = this.$('.browser'); // Check if we've already replaced the placeholder. if ( $placeholder[0] === $browser[0] ) return; $browser.detach().text( $placeholder.text() ); $browser[0].className = $placeholder[0].className; $placeholder.replaceWith( $browser.show() ); } this.refresh(); return this; } }); /** * wp.media.view.UploaderStatus */ media.view.UploaderStatus = media.View.extend({ className: 'media-uploader-status', template: media.template('uploader-status'), events: { 'click .upload-dismiss-errors': 'dismiss' }, initialize: function() { this.queue = wp.Uploader.queue; this.queue.on( 'add remove reset', this.visibility, this ); this.queue.on( 'add remove reset change:percent', this.progress, this ); this.queue.on( 'add remove reset change:uploading', this.info, this ); this.errors = wp.Uploader.errors; this.errors.reset(); this.errors.on( 'add remove reset', this.visibility, this ); this.errors.on( 'add', this.error, this ); }, dispose: function() { wp.Uploader.queue.off( null, null, this ); media.View.prototype.dispose.apply( this, arguments ); return this; }, visibility: function() { this.$el.toggleClass( 'uploading', !! this.queue.length ); this.$el.toggleClass( 'errors', !! this.errors.length ); this.$el.toggle( !! this.queue.length || !! this.errors.length ); }, ready: function() { _.each({ '$bar': '.media-progress-bar div', '$index': '.upload-index', '$total': '.upload-total', '$filename': '.upload-filename' }, function( selector, key ) { this[ key ] = this.$( selector ); }, this ); this.visibility(); this.progress(); this.info(); }, progress: function() { var queue = this.queue, $bar = this.$bar, memo = 0; if ( ! $bar || ! queue.length ) return; $bar.width( ( queue.reduce( function( memo, attachment ) { if ( ! attachment.get('uploading') ) return memo + 100; var percent = attachment.get('percent'); return memo + ( _.isNumber( percent ) ? percent : 100 ); }, 0 ) / queue.length ) + '%' ); }, info: function() { var queue = this.queue, index = 0, active; if ( ! queue.length ) return; active = this.queue.find( function( attachment, i ) { index = i; return attachment.get('uploading'); }); this.$index.text( index + 1 ); this.$total.text( queue.length ); this.$filename.html( active ? this.filename( active.get('filename') ) : '' ); }, filename: function( filename ) { return media.truncate( _.escape( filename ), 24 ); }, error: function( error ) { this.views.add( '.upload-errors', new media.view.UploaderStatusError({ filename: this.filename( error.get('file').name ), message: error.get('message') }), { at: 0 }); }, dismiss: function( event ) { var errors = this.views.get('.upload-errors'); event.preventDefault(); if ( errors ) _.invoke( errors, 'remove' ); wp.Uploader.errors.reset(); } }); media.view.UploaderStatusError = media.View.extend({ className: 'upload-error', template: media.template('uploader-status-error') }); /** * wp.media.view.Toolbar */ media.view.Toolbar = media.View.extend({ tagName: 'div', className: 'media-toolbar', initialize: function() { var state = this.controller.state(), selection = this.selection = state.get('selection'), library = this.library = state.get('library'); this._views = {}; // The toolbar is composed of two `PriorityList` views. this.primary = new media.view.PriorityList(); this.secondary = new media.view.PriorityList(); this.primary.$el.addClass('media-toolbar-primary'); this.secondary.$el.addClass('media-toolbar-secondary'); this.views.set([ this.secondary, this.primary ]); if ( this.options.items ) this.set( this.options.items, { silent: true }); if ( ! this.options.silent ) this.render(); if ( selection ) selection.on( 'add remove reset', this.refresh, this ); if ( library ) library.on( 'add remove reset', this.refresh, this ); }, dispose: function() { if ( this.selection ) this.selection.off( null, null, this ); if ( this.library ) this.library.off( null, null, this ); return media.View.prototype.dispose.apply( this, arguments ); }, ready: function() { this.refresh(); }, set: function( id, view, options ) { var list; options = options || {}; // Accept an object with an `id` : `view` mapping. if ( _.isObject( id ) ) { _.each( id, function( view, id ) { this.set( id, view, { silent: true }); }, this ); } else { if ( ! ( view instanceof Backbone.View ) ) { view.classes = [ 'media-button-' + id ].concat( view.classes || [] ); view = new media.view.Button( view ).render(); } view.controller = view.controller || this.controller; this._views[ id ] = view; list = view.options.priority < 0 ? 'secondary' : 'primary'; this[ list ].set( id, view, options ); } if ( ! options.silent ) this.refresh(); return this; }, get: function( id ) { return this._views[ id ]; }, unset: function( id, options ) { delete this._views[ id ]; this.primary.unset( id, options ); this.secondary.unset( id, options ); if ( ! options || ! options.silent ) this.refresh(); return this; }, refresh: function() { var state = this.controller.state(), library = state.get('library'), selection = state.get('selection'); _.each( this._views, function( button ) { if ( ! button.model || ! button.options || ! button.options.requires ) return; var requires = button.options.requires, disabled = false; if ( requires.selection && selection && ! selection.length ) disabled = true; else if ( requires.library && library && ! library.length ) disabled = true; button.model.set( 'disabled', disabled ); }); } }); // wp.media.view.Toolbar.Select // ---------------------------- media.view.Toolbar.Select = media.view.Toolbar.extend({ initialize: function() { var options = this.options, controller = options.controller, selection = controller.state().get('selection'); _.bindAll( this, 'clickSelect' ); _.defaults( options, { event: 'select', state: false, reset: true, close: true, text: l10n.select, // Does the button rely on the selection? requires: { selection: true } }); options.items = _.defaults( options.items || {}, { select: { style: 'primary', text: options.text, priority: 80, click: this.clickSelect, requires: options.requires } }); media.view.Toolbar.prototype.initialize.apply( this, arguments ); }, clickSelect: function() { var options = this.options, controller = this.controller; if ( options.close ) controller.close(); if ( options.event ) controller.state().trigger( options.event ); if ( options.reset ) controller.reset(); if ( options.state ) controller.setState( options.state ); } }); // wp.media.view.Toolbar.Embed // --------------------------- media.view.Toolbar.Embed = media.view.Toolbar.Select.extend({ initialize: function() { _.defaults( this.options, { text: l10n.insertIntoPost, requires: false }); media.view.Toolbar.Select.prototype.initialize.apply( this, arguments ); }, refresh: function() { var url = this.controller.state().props.get('url'); this.get('select').model.set( 'disabled', ! url || url === 'http://' ); media.view.Toolbar.Select.prototype.refresh.apply( this, arguments ); } }); /** * wp.media.view.Button */ media.view.Button = media.View.extend({ tagName: 'a', className: 'media-button', attributes: { href: '#' }, events: { 'click': 'click' }, defaults: { text: '', style: '', size: 'large', disabled: false }, initialize: function() { // Create a model with the provided `defaults`. this.model = new Backbone.Model( this.defaults ); // If any of the `options` have a key from `defaults`, apply its // value to the `model` and remove it from the `options object. _.each( this.defaults, function( def, key ) { var value = this.options[ key ]; if ( _.isUndefined( value ) ) return; this.model.set( key, value ); delete this.options[ key ]; }, this ); this.model.on( 'change', this.render, this ); }, render: function() { var classes = [ 'button', this.className ], model = this.model.toJSON(); if ( model.style ) classes.push( 'button-' + model.style ); if ( model.size ) classes.push( 'button-' + model.size ); classes = _.uniq( classes.concat( this.options.classes ) ); this.el.className = classes.join(' '); this.$el.attr( 'disabled', model.disabled ); this.$el.text( this.model.get('text') ); return this; }, click: function( event ) { if ( '#' === this.attributes.href ) event.preventDefault(); if ( this.options.click && ! this.model.get('disabled') ) this.options.click.apply( this, arguments ); } }); /** * wp.media.view.ButtonGroup */ media.view.ButtonGroup = media.View.extend({ tagName: 'div', className: 'button-group button-large media-button-group', initialize: function() { this.buttons = _.map( this.options.buttons || [], function( button ) { if ( button instanceof Backbone.View ) return button; else return new media.view.Button( button ).render(); }); delete this.options.buttons; if ( this.options.classes ) this.$el.addClass( this.options.classes ); }, render: function() { this.$el.html( $( _.pluck( this.buttons, 'el' ) ).detach() ); return this; } }); /** * wp.media.view.PriorityList */ media.view.PriorityList = media.View.extend({ tagName: 'div', initialize: function() { this._views = {}; this.set( _.extend( {}, this._views, this.options.views ), { silent: true }); delete this.options.views; if ( ! this.options.silent ) this.render(); }, set: function( id, view, options ) { var priority, views, index; options = options || {}; // Accept an object with an `id` : `view` mapping. if ( _.isObject( id ) ) { _.each( id, function( view, id ) { this.set( id, view ); }, this ); return this; } if ( ! (view instanceof Backbone.View) ) view = this.toView( view, id, options ); view.controller = view.controller || this.controller; this.unset( id ); priority = view.options.priority || 10; views = this.views.get() || []; _.find( views, function( existing, i ) { if ( existing.options.priority > priority ) { index = i; return true; } }); this._views[ id ] = view; this.views.add( view, { at: _.isNumber( index ) ? index : views.length || 0 }); return this; }, get: function( id ) { return this._views[ id ]; }, unset: function( id ) { var view = this.get( id ); if ( view ) view.remove(); delete this._views[ id ]; return this; }, toView: function( options ) { return new media.View( options ); } }); /** * wp.media.view.MenuItem */ media.view.MenuItem = media.View.extend({ tagName: 'a', className: 'media-menu-item', attributes: { href: '#' }, events: { 'click': '_click' }, _click: function( event ) { var clickOverride = this.options.click; if ( event ) event.preventDefault(); if ( clickOverride ) clickOverride.call( this ); else this.click(); }, click: function() { var state = this.options.state; if ( state ) this.controller.setState( state ); }, render: function() { var options = this.options; if ( options.text ) this.$el.text( options.text ); else if ( options.html ) this.$el.html( options.html ); return this; } }); /** * wp.media.view.Menu */ media.view.Menu = media.view.PriorityList.extend({ tagName: 'div', className: 'media-menu', property: 'state', ItemView: media.view.MenuItem, region: 'menu', toView: function( options, id ) { options = options || {}; options[ this.property ] = options[ this.property ] || id; return new this.ItemView( options ).render(); }, ready: function() { media.view.PriorityList.prototype.ready.apply( this, arguments ); this.visibility(); }, set: function() { media.view.PriorityList.prototype.set.apply( this, arguments ); this.visibility(); }, unset: function() { media.view.PriorityList.prototype.unset.apply( this, arguments ); this.visibility(); }, visibility: function() { var region = this.region, view = this.controller[ region ].get(), views = this.views.get(), hide = ! views || views.length < 2; if ( this === view ) this.controller.$el.toggleClass( 'hide-' + region, hide ); }, select: function( id ) { var view = this.get( id ); if ( ! view ) return; this.deselect(); view.$el.addClass('active'); }, deselect: function() { this.$el.children().removeClass('active'); } }); /** * wp.media.view.RouterItem */ media.view.RouterItem = media.view.MenuItem.extend({ click: function() { var contentMode = this.options.contentMode; if ( contentMode ) this.controller.content.mode( contentMode ); } }); /** * wp.media.view.Router */ media.view.Router = media.view.Menu.extend({ tagName: 'div', className: 'media-router', property: 'contentMode', ItemView: media.view.RouterItem, region: 'router', initialize: function() { this.controller.on( 'content:render', this.update, this ); media.view.Menu.prototype.initialize.apply( this, arguments ); }, update: function() { var mode = this.controller.content.mode(); if ( mode ) this.select( mode ); } }); /** * wp.media.view.Sidebar */ media.view.Sidebar = media.view.PriorityList.extend({ className: 'media-sidebar' }); /** * wp.media.view.Attachment */ media.view.Attachment = media.View.extend({ tagName: 'li', className: 'attachment', template: media.template('attachment'), events: { 'click .attachment-preview': 'toggleSelectionHandler', 'change [data-setting]': 'updateSetting', 'change [data-setting] input': 'updateSetting', 'change [data-setting] select': 'updateSetting', 'change [data-setting] textarea': 'updateSetting', 'click .close': 'removeFromLibrary', 'click .check': 'removeFromSelection', 'click a': 'preventDefault' }, buttons: {}, initialize: function() { var selection = this.options.selection; this.model.on( 'change:sizes change:uploading change:caption change:title', this.render, this ); this.model.on( 'change:percent', this.progress, this ); // Update the selection. this.model.on( 'add', this.select, this ); this.model.on( 'remove', this.deselect, this ); if ( selection ) selection.on( 'reset', this.updateSelect, this ); // Update the model's details view. this.model.on( 'selection:single selection:unsingle', this.details, this ); this.details( this.model, this.controller.state().get('selection') ); }, dispose: function() { var selection = this.options.selection; // Make sure all settings are saved before removing the view. this.updateAll(); if ( selection ) selection.off( null, null, this ); media.View.prototype.dispose.apply( this, arguments ); return this; }, render: function() { var options = _.defaults( this.model.toJSON(), { orientation: 'landscape', uploading: false, type: '', subtype: '', icon: '', filename: '', caption: '', title: '', dateFormatted: '', width: '', height: '', compat: false, alt: '', description: '' }); options.buttons = this.buttons; options.describe = this.controller.state().get('describe'); if ( 'image' === options.type ) options.size = this.imageSize(); options.can = {}; if ( options.nonces ) { options.can.remove = !! options.nonces['delete']; options.can.save = !! options.nonces.update; } if ( this.controller.state().get('allowLocalEdits') ) options.allowLocalEdits = true; this.views.detach(); this.$el.html( this.template( options ) ); this.$el.toggleClass( 'uploading', options.uploading ); if ( options.uploading ) this.$bar = this.$('.media-progress-bar div'); else delete this.$bar; // Check if the model is selected. this.updateSelect(); // Update the save status. this.updateSave(); this.views.render(); return this; }, progress: function() { if ( this.$bar && this.$bar.length ) this.$bar.width( this.model.get('percent') + '%' ); }, toggleSelectionHandler: function( event ) { var method; if ( event.shiftKey ) method = 'between'; else if ( event.ctrlKey || event.metaKey ) method = 'toggle'; this.toggleSelection({ method: method }); }, toggleSelection: function( options ) { var collection = this.collection, selection = this.options.selection, model = this.model, method = options && options.method, single, between, models, singleIndex, modelIndex; if ( ! selection ) return; single = selection.single(); method = _.isUndefined( method ) ? selection.multiple : method; // If the `method` is set to `between`, select all models that // exist between the current and the selected model. if ( 'between' === method && single && selection.multiple ) { // If the models are the same, short-circuit. if ( single === model ) return; singleIndex = collection.indexOf( single ); modelIndex = collection.indexOf( this.model ); if ( singleIndex < modelIndex ) models = collection.models.slice( singleIndex, modelIndex + 1 ); else models = collection.models.slice( modelIndex, singleIndex + 1 ); selection.add( models ).single( model ); return; // If the `method` is set to `toggle`, just flip the selection // status, regardless of whether the model is the single model. } else if ( 'toggle' === method ) { selection[ this.selected() ? 'remove' : 'add' ]( model ).single( model ); return; } if ( method !== 'add' ) method = 'reset'; if ( this.selected() ) { // If the model is the single model, remove it. // If it is not the same as the single model, // it now becomes the single model. selection[ single === model ? 'remove' : 'single' ]( model ); } else { // If the model is not selected, run the `method` on the // selection. By default, we `reset` the selection, but the // `method` can be set to `add` the model to the selection. selection[ method ]( model ).single( model ); } }, updateSelect: function() { this[ this.selected() ? 'select' : 'deselect' ](); }, selected: function() { var selection = this.options.selection; if ( selection ) return !! selection.getByCid( this.model.cid ); }, select: function( model, collection ) { var selection = this.options.selection; // Check if a selection exists and if it's the collection provided. // If they're not the same collection, bail; we're in another // selection's event loop. if ( ! selection || ( collection && collection !== selection ) ) return; this.$el.addClass('selected'); }, deselect: function( model, collection ) { var selection = this.options.selection; // Check if a selection exists and if it's the collection provided. // If they're not the same collection, bail; we're in another // selection's event loop. if ( ! selection || ( collection && collection !== selection ) ) return; this.$el.removeClass('selected'); }, details: function( model, collection ) { var selection = this.options.selection, details; if ( selection !== collection ) return; details = selection.single(); this.$el.toggleClass( 'details', details === this.model ); }, preventDefault: function( event ) { event.preventDefault(); }, imageSize: function( size ) { var sizes = this.model.get('sizes'); size = size || 'medium'; // Use the provided image size if possible. if ( sizes && sizes[ size ] ) { return _.clone( sizes[ size ] ); } else { return { url: this.model.get('url'), width: this.model.get('width'), height: this.model.get('height'), orientation: this.model.get('orientation') }; } }, updateSetting: function( event ) { var $setting = $( event.target ).closest('[data-setting]'), setting, value; if ( ! $setting.length ) return; setting = $setting.data('setting'); value = event.target.value; if ( this.model.get( setting ) !== value ) this.save( setting, value ); }, // Pass all the arguments to the model's save method. // // Records the aggregate status of all save requests and updates the // view's classes accordingly. save: function() { var view = this, save = this._save = this._save || { status: 'ready' }, request = this.model.save.apply( this.model, arguments ), requests = save.requests ? $.when( request, save.requests ) : request; // If we're waiting to remove 'Saved.', stop. if ( save.savedTimer ) clearTimeout( save.savedTimer ); this.updateSave('waiting'); save.requests = requests; requests.always( function() { // If we've performed another request since this one, bail. if ( save.requests !== requests ) return; view.updateSave( requests.state() === 'resolved' ? 'complete' : 'error' ); save.savedTimer = setTimeout( function() { view.updateSave('ready'); delete save.savedTimer; }, 2000 ); }); }, updateSave: function( status ) { var save = this._save = this._save || { status: 'ready' }; if ( status && status !== save.status ) { this.$el.removeClass( 'save-' + save.status ); save.status = status; } this.$el.addClass( 'save-' + save.status ); return this; }, updateAll: function() { var $settings = this.$('[data-setting]'), model = this.model, changed; changed = _.chain( $settings ).map( function( el ) { var $input = $('input, textarea, select, [value]', el ), setting, value; if ( ! $input.length ) return; setting = $(el).data('setting'); value = $input.val(); // Record the value if it changed. if ( model.get( setting ) !== value ) return [ setting, value ]; }).compact().object().value(); if ( ! _.isEmpty( changed ) ) model.save( changed ); }, removeFromLibrary: function( event ) { // Stop propagation so the model isn't selected. event.stopPropagation(); this.collection.remove( this.model ); }, removeFromSelection: function( event ) { var selection = this.options.selection; if ( ! selection ) return; // Stop propagation so the model isn't selected. event.stopPropagation(); selection.remove( this.model ); } }); /** * wp.media.view.Attachment.Library */ media.view.Attachment.Library = media.view.Attachment.extend({ buttons: { check: true } }); /** * wp.media.view.Attachment.EditLibrary */ media.view.Attachment.EditLibrary = media.view.Attachment.extend({ buttons: { close: true } }); /** * wp.media.view.Attachments */ media.view.Attachments = media.View.extend({ tagName: 'ul', className: 'attachments', cssTemplate: media.template('attachments-css'), events: { 'scroll': 'scroll' }, initialize: function() { this.el.id = _.uniqueId('__attachments-view-'); _.defaults( this.options, { refreshSensitivity: 200, refreshThreshold: 3, AttachmentView: media.view.Attachment, sortable: false, resize: true }); this._viewsByCid = {}; this.collection.on( 'add', function( attachment, attachments, options ) { this.views.add( this.createAttachmentView( attachment ), { at: options.index }); }, this ); this.collection.on( 'remove', function( attachment, attachments, options ) { var view = this._viewsByCid[ attachment.cid ]; delete this._viewsByCid[ attachment.cid ]; if ( view ) view.remove(); }, this ); this.collection.on( 'reset', this.render, this ); // Throttle the scroll handler. this.scroll = _.chain( this.scroll ).bind( this ).throttle( this.options.refreshSensitivity ).value(); this.initSortable(); _.bindAll( this, 'css' ); this.model.on( 'change:edge change:gutter', this.css, this ); this._resizeCss = _.debounce( _.bind( this.css, this ), this.refreshSensitivity ); if ( this.options.resize ) $(window).on( 'resize.attachments', this._resizeCss ); this.css(); }, dispose: function() { this.collection.props.off( null, null, this ); $(window).off( 'resize.attachments', this._resizeCss ); media.View.prototype.dispose.apply( this, arguments ); }, css: function() { var $css = $( '#' + this.el.id + '-css' ); if ( $css.length ) $css.remove(); media.view.Attachments.$head().append( this.cssTemplate({ id: this.el.id, edge: this.edge(), gutter: this.model.get('gutter') }) ); }, edge: function() { var edge = this.model.get('edge'), gutter, width, columns; if ( ! this.$el.is(':visible') ) return edge; gutter = this.model.get('gutter') * 2; width = this.$el.width() - gutter; columns = Math.ceil( width / ( edge + gutter ) ); edge = Math.floor( ( width - ( columns * gutter ) ) / columns ); return edge; }, initSortable: function() { var collection = this.collection; if ( ! this.options.sortable || ! $.fn.sortable ) return; this.$el.sortable( _.extend({ // If the `collection` has a `comparator`, disable sorting. disabled: !! collection.comparator, // Prevent attachments from being dragged outside the bounding // box of the list. containment: this.$el, // Change the position of the attachment as soon as the // mouse pointer overlaps a thumbnail. tolerance: 'pointer', // Record the initial `index` of the dragged model. start: function( event, ui ) { ui.item.data('sortableIndexStart', ui.item.index()); }, // Update the model's index in the collection. // Do so silently, as the view is already accurate. update: function( event, ui ) { var model = collection.at( ui.item.data('sortableIndexStart') ), comparator = collection.comparator; // Temporarily disable the comparator to prevent `add` // from re-sorting. delete collection.comparator; // Silently shift the model to its new index. collection.remove( model, { silent: true }).add( model, { silent: true, at: ui.item.index() }); // Restore the comparator. collection.comparator = comparator; // Fire the `reset` event to ensure other collections sync. collection.trigger( 'reset', collection ); // If the collection is sorted by menu order, // update the menu order. collection.saveMenuOrder(); } }, this.options.sortable ) ); // If the `orderby` property is changed on the `collection`, // check to see if we have a `comparator`. If so, disable sorting. collection.props.on( 'change:orderby', function() { this.$el.sortable( 'option', 'disabled', !! collection.comparator ); }, this ); this.collection.props.on( 'change:orderby', this.refreshSortable, this ); this.refreshSortable(); }, refreshSortable: function() { if ( ! this.options.sortable || ! $.fn.sortable ) return; // If the `collection` has a `comparator`, disable sorting. var collection = this.collection, orderby = collection.props.get('orderby'), enabled = 'menuOrder' === orderby || ! collection.comparator; this.$el.sortable( 'option', 'disabled', ! enabled ); }, createAttachmentView: function( attachment ) { var view = new this.options.AttachmentView({ controller: this.controller, model: attachment, collection: this.collection, selection: this.options.selection }); return this._viewsByCid[ attachment.cid ] = view; }, prepare: function() { // Create all of the Attachment views, and replace // the list in a single DOM operation. if ( this.collection.length ) { this.views.set( this.collection.map( this.createAttachmentView, this ) ); // If there are no elements, clear the views and load some. } else { this.views.unset(); this.collection.more().done( this.scroll ); } }, ready: function() { // Trigger the scroll event to check if we're within the // threshold to query for additional attachments. this.scroll(); }, scroll: function( event ) { // @todo: is this still necessary? if ( ! this.$el.is(':visible') ) return; if ( this.collection.hasMore() && this.el.scrollHeight < this.el.scrollTop + ( this.el.clientHeight * this.options.refreshThreshold ) ) { this.collection.more().done( this.scroll ); } } }, { $head: (function() { var $head; return function() { return $head = $head || $('head'); }; }()) }); /** * wp.media.view.Search */ media.view.Search = media.View.extend({ tagName: 'input', className: 'search', attributes: { type: 'search', placeholder: l10n.search }, events: { 'input': 'search', 'keyup': 'search', 'change': 'search', 'search': 'search' }, render: function() { this.el.value = this.model.escape('search'); return this; }, search: function( event ) { if ( event.target.value ) this.model.set( 'search', event.target.value ); else this.model.unset('search'); } }); /** * wp.media.view.AttachmentFilters */ media.view.AttachmentFilters = media.View.extend({ tagName: 'select', className: 'attachment-filters', events: { change: 'change' }, keys: [], initialize: function() { this.createFilters(); _.extend( this.filters, this.options.filters ); // Build `<option>` elements. this.$el.html( _.chain( this.filters ).map( function( filter, value ) { return { el: this.make( 'option', { value: value }, filter.text ), priority: filter.priority || 50 }; }, this ).sortBy('priority').pluck('el').value() ); this.model.on( 'change', this.select, this ); this.select(); }, createFilters: function() { this.filters = {}; }, change: function( event ) { var filter = this.filters[ this.el.value ]; if ( filter ) this.model.set( filter.props ); }, select: function() { var model = this.model, value = 'all', props = model.toJSON(); _.find( this.filters, function( filter, id ) { var equal = _.all( filter.props, function( prop, key ) { return prop === ( _.isUndefined( props[ key ] ) ? null : props[ key ] ); }); if ( equal ) return value = id; }); this.$el.val( value ); } }); media.view.AttachmentFilters.Uploaded = media.view.AttachmentFilters.extend({ createFilters: function() { var type = this.model.get('type'), types = media.view.settings.mimeTypes, text; if ( types && type ) text = types[ type ]; this.filters = { all: { text: text || l10n.allMediaItems, props: { uploadedTo: null, orderby: 'date', order: 'DESC' }, priority: 10 }, uploaded: { text: l10n.uploadedToThisPost, props: { uploadedTo: media.view.settings.post.id, orderby: 'menuOrder', order: 'ASC' }, priority: 20 } }; } }); media.view.AttachmentFilters.All = media.view.AttachmentFilters.extend({ createFilters: function() { var filters = {}; _.each( media.view.settings.mimeTypes || {}, function( text, key ) { filters[ key ] = { text: text, props: { type: key, uploadedTo: null, orderby: 'date', order: 'DESC' } }; }); filters.all = { text: l10n.allMediaItems, props: { type: null, uploadedTo: null, orderby: 'date', order: 'DESC' }, priority: 10 }; filters.uploaded = { text: l10n.uploadedToThisPost, props: { type: null, uploadedTo: media.view.settings.post.id, orderby: 'menuOrder', order: 'ASC' }, priority: 20 }; this.filters = filters; } }); /** * wp.media.view.AttachmentsBrowser */ media.view.AttachmentsBrowser = media.View.extend({ tagName: 'div', className: 'attachments-browser', initialize: function() { _.defaults( this.options, { filters: false, search: true, display: false, AttachmentView: media.view.Attachment.Library }); this.createToolbar(); this.updateContent(); this.createSidebar(); this.collection.on( 'add remove reset', this.updateContent, this ); }, dispose: function() { this.options.selection.off( null, null, this ); media.View.prototype.dispose.apply( this, arguments ); return this; }, createToolbar: function() { var filters, FiltersConstructor; this.toolbar = new media.view.Toolbar({ controller: this.controller }); this.views.add( this.toolbar ); filters = this.options.filters; if ( 'uploaded' === filters ) FiltersConstructor = media.view.AttachmentFilters.Uploaded; else if ( 'all' === filters ) FiltersConstructor = media.view.AttachmentFilters.All; if ( FiltersConstructor ) { this.toolbar.set( 'filters', new FiltersConstructor({ controller: this.controller, model: this.collection.props, priority: -80 }).render() ); } if ( this.options.search ) { this.toolbar.set( 'search', new media.view.Search({ controller: this.controller, model: this.collection.props, priority: 60 }).render() ); } if ( this.options.dragInfo ) { this.toolbar.set( 'dragInfo', new media.View({ el: $( '<div class="instructions">' + l10n.dragInfo + '</div>' )[0], priority: -40 }) ); } }, updateContent: function() { var view = this; if( ! this.attachments ) this.createAttachments(); if ( ! this.collection.length ) { this.collection.more().done( function() { if ( ! view.collection.length ) view.createUploader(); }); } }, removeContent: function() { _.each(['attachments','uploader'], function( key ) { if ( this[ key ] ) { this[ key ].remove(); delete this[ key ]; } }, this ); }, createUploader: function() { this.removeContent(); this.uploader = new media.view.UploaderInline({ controller: this.controller, status: false, message: l10n.noItemsFound }); this.views.add( this.uploader ); }, createAttachments: function() { this.removeContent(); this.attachments = new media.view.Attachments({ controller: this.controller, collection: this.collection, selection: this.options.selection, model: this.model, sortable: this.options.sortable, // The single `Attachment` view to be used in the `Attachments` view. AttachmentView: this.options.AttachmentView }); this.views.add( this.attachments ); }, createSidebar: function() { var options = this.options, selection = options.selection, sidebar = this.sidebar = new media.view.Sidebar({ controller: this.controller }); this.views.add( sidebar ); if ( this.controller.uploader ) { sidebar.set( 'uploads', new media.view.UploaderStatus({ controller: this.controller, priority: 40 }) ); } selection.on( 'selection:single', this.createSingle, this ); selection.on( 'selection:unsingle', this.disposeSingle, this ); if ( selection.single() ) this.createSingle(); }, createSingle: function() { var sidebar = this.sidebar, single = this.options.selection.single(), views = {}; sidebar.set( 'details', new media.view.Attachment.Details({ controller: this.controller, model: single, priority: 80 }) ); sidebar.set( 'compat', new media.view.AttachmentCompat({ controller: this.controller, model: single, priority: 120 }) ); if ( this.options.display ) { sidebar.set( 'display', new media.view.Settings.AttachmentDisplay({ controller: this.controller, model: this.model.display( single ), attachment: single, priority: 160, userSettings: this.model.get('displayUserSettings') }) ); } }, disposeSingle: function() { var sidebar = this.sidebar; sidebar.unset('details'); sidebar.unset('compat'); sidebar.unset('display'); } }); /** * wp.media.view.Selection */ media.view.Selection = media.View.extend({ tagName: 'div', className: 'media-selection', template: media.template('media-selection'), events: { 'click .edit-selection': 'edit', 'click .clear-selection': 'clear' }, initialize: function() { _.defaults( this.options, { editable: false, clearable: true }); this.attachments = new media.view.Attachments.Selection({ controller: this.controller, collection: this.collection, selection: this.collection, model: new Backbone.Model({ edge: 40, gutter: 5 }) }); this.views.set( '.selection-view', this.attachments ); this.collection.on( 'add remove reset', this.refresh, this ); this.controller.on( 'content:activate', this.refresh, this ); }, ready: function() { this.refresh(); }, refresh: function() { // If the selection hasn't been rendered, bail. if ( ! this.$el.children().length ) return; var collection = this.collection, editing = 'edit-selection' === this.controller.content.mode(); // If nothing is selected, display nothing. this.$el.toggleClass( 'empty', ! collection.length ); this.$el.toggleClass( 'one', 1 === collection.length ); this.$el.toggleClass( 'editing', editing ); this.$('.count').text( l10n.selected.replace('%d', collection.length) ); }, edit: function( event ) { event.preventDefault(); if ( this.options.editable ) this.options.editable.call( this, this.collection ); }, clear: function( event ) { event.preventDefault(); this.collection.reset(); } }); /** * wp.media.view.Attachment.Selection */ media.view.Attachment.Selection = media.view.Attachment.extend({ className: 'attachment selection', // On click, just select the model, instead of removing the model from // the selection. toggleSelection: function() { this.options.selection.single( this.model ); } }); /** * wp.media.view.Attachments.Selection */ media.view.Attachments.Selection = media.view.Attachments.extend({ events: {}, initialize: function() { _.defaults( this.options, { sortable: true, resize: false, // The single `Attachment` view to be used in the `Attachments` view. AttachmentView: media.view.Attachment.Selection }); return media.view.Attachments.prototype.initialize.apply( this, arguments ); } }); /** * wp.media.view.Attachments.EditSelection */ media.view.Attachment.EditSelection = media.view.Attachment.Selection.extend({ buttons: { close: true } }); /** * wp.media.view.Settings */ media.view.Settings = media.View.extend({ events: { 'click button': 'updateHandler', 'change input': 'updateHandler', 'change select': 'updateHandler', 'change textarea': 'updateHandler' }, initialize: function() { this.model = this.model || new Backbone.Model(); this.model.on( 'change', this.updateChanges, this ); }, prepare: function() { return _.defaults({ model: this.model.toJSON() }, this.options ); }, render: function() { media.View.prototype.render.apply( this, arguments ); // Select the correct values. _( this.model.attributes ).chain().keys().each( this.update, this ); return this; }, update: function( key ) { var value = this.model.get( key ), $setting = this.$('[data-setting="' + key + '"]'), $buttons, $value; // Bail if we didn't find a matching setting. if ( ! $setting.length ) return; // Attempt to determine how the setting is rendered and update // the selected value. // Handle dropdowns. if ( $setting.is('select') ) { $value = $setting.find('[value="' + value + '"]'); if ( $value.length ) { $setting.find('option').prop( 'selected', false ); $value.prop( 'selected', true ); } else { // If we can't find the desired value, record what *is* selected. this.model.set( key, $setting.find(':selected').val() ); } // Handle button groups. } else if ( $setting.hasClass('button-group') ) { $buttons = $setting.find('button').removeClass('active'); $buttons.filter( '[value="' + value + '"]' ).addClass('active'); // Handle text inputs and textareas. } else if ( $setting.is('input[type="text"], textarea') ) { if ( ! $setting.is(':focus') ) $setting.val( value ); // Handle checkboxes. } else if ( $setting.is('input[type="checkbox"]') ) { $setting.attr( 'checked', !! value ); } }, updateHandler: function( event ) { var $setting = $( event.target ).closest('[data-setting]'), value = event.target.value, userSetting; event.preventDefault(); if ( ! $setting.length ) return; // Use the correct value for checkboxes. if ( $setting.is('input[type="checkbox"]') ) value = $setting[0].checked; // Update the corresponding setting. this.model.set( $setting.data('setting'), value ); // If the setting has a corresponding user setting, // update that as well. if ( userSetting = $setting.data('userSetting') ) setUserSetting( userSetting, value ); }, updateChanges: function( model, options ) { if ( options.changes ) _( options.changes ).chain().keys().each( this.update, this ); } }); /** * wp.media.view.Settings.AttachmentDisplay */ media.view.Settings.AttachmentDisplay = media.view.Settings.extend({ className: 'attachment-display-settings', template: media.template('attachment-display-settings'), initialize: function() { var attachment = this.options.attachment; _.defaults( this.options, { userSettings: false }); media.view.Settings.prototype.initialize.apply( this, arguments ); this.model.on( 'change:link', this.updateLinkTo, this ); if ( attachment ) attachment.on( 'change:uploading', this.render, this ); }, dispose: function() { var attachment = this.options.attachment; if ( attachment ) attachment.off( null, null, this ); media.view.Settings.prototype.dispose.apply( this, arguments ); }, render: function() { var attachment = this.options.attachment; if ( attachment ) { _.extend( this.options, { sizes: attachment.get('sizes'), type: attachment.get('type') }); } media.view.Settings.prototype.render.call( this ); this.updateLinkTo(); return this; }, updateLinkTo: function() { var linkTo = this.model.get('link'), $input = this.$('.link-to-custom'), attachment = this.options.attachment; if ( 'none' === linkTo || ( ! attachment && 'custom' !== linkTo ) ) { $input.hide(); return; } if ( attachment ) { if ( 'post' === linkTo ) { $input.val( attachment.get('link') ); } else if ( 'file' === linkTo ) { $input.val( attachment.get('url') ); } else if ( ! this.model.get('linkUrl') ) { $input.val('http://'); } $input.prop( 'readonly', 'custom' !== linkTo ); } $input.show(); // If the input is visible, focus and select its contents. if ( $input.is(':visible') ) $input.focus()[0].select(); } }); /** * wp.media.view.Settings.Gallery */ media.view.Settings.Gallery = media.view.Settings.extend({ className: 'gallery-settings', template: media.template('gallery-settings') }); /** * wp.media.view.Attachment.Details */ media.view.Attachment.Details = media.view.Attachment.extend({ tagName: 'div', className: 'attachment-details', template: media.template('attachment-details'), events: { 'change [data-setting]': 'updateSetting', 'change [data-setting] input': 'updateSetting', 'change [data-setting] select': 'updateSetting', 'change [data-setting] textarea': 'updateSetting', 'click .delete-attachment': 'deleteAttachment', 'click .edit-attachment': 'editAttachment', 'click .refresh-attachment': 'refreshAttachment' }, initialize: function() { this.focusManager = new media.view.FocusManager({ el: this.el }); media.view.Attachment.prototype.initialize.apply( this, arguments ); }, render: function() { media.view.Attachment.prototype.render.apply( this, arguments ); this.focusManager.focus(); return this; }, deleteAttachment: function( event ) { event.preventDefault(); if ( confirm( l10n.warnDelete ) ) this.model.destroy(); }, editAttachment: function( event ) { this.$el.addClass('needs-refresh'); }, refreshAttachment: function( event ) { this.$el.removeClass('needs-refresh'); event.preventDefault(); this.model.fetch(); } }); /** * wp.media.view.AttachmentCompat */ media.view.AttachmentCompat = media.View.extend({ tagName: 'form', className: 'compat-item', events: { 'submit': 'preventDefault', 'change input': 'save', 'change select': 'save', 'change textarea': 'save' }, initialize: function() { this.focusManager = new media.view.FocusManager({ el: this.el }); this.model.on( 'change:compat', this.render, this ); }, dispose: function() { if ( this.$(':focus').length ) this.save(); return media.View.prototype.dispose.apply( this, arguments ); }, render: function() { var compat = this.model.get('compat'); if ( ! compat || ! compat.item ) return; this.views.detach(); this.$el.html( compat.item ); this.views.render(); this.focusManager.focus(); return this; }, preventDefault: function( event ) { event.preventDefault(); }, save: function( event ) { var data = {}; if ( event ) event.preventDefault(); _.each( this.$el.serializeArray(), function( pair ) { data[ pair.name ] = pair.value; }); this.model.saveCompat( data ); } }); /** * wp.media.view.Iframe */ media.view.Iframe = media.View.extend({ className: 'media-iframe', render: function() { this.views.detach(); this.$el.html( '<iframe src="' + this.controller.state().get('src') + '" />' ); this.views.render(); return this; } }); /** * wp.media.view.Embed */ media.view.Embed = media.View.extend({ className: 'media-embed', initialize: function() { this.url = new media.view.EmbedUrl({ controller: this.controller, model: this.model.props }).render(); this.views.set([ this.url ]); this.refresh(); this.model.on( 'change:type', this.refresh, this ); this.model.on( 'change:loading', this.loading, this ); }, settings: function( view ) { if ( this._settings ) this._settings.remove(); this._settings = view; this.views.add( view ); }, refresh: function() { var type = this.model.get('type'), constructor; if ( 'image' === type ) constructor = media.view.EmbedImage; else if ( 'link' === type ) constructor = media.view.EmbedLink; else return; this.settings( new constructor({ controller: this.controller, model: this.model.props, priority: 40 }) ); }, loading: function() { this.$el.toggleClass( 'embed-loading', this.model.get('loading') ); } }); /** * wp.media.view.EmbedUrl */ media.view.EmbedUrl = media.View.extend({ tagName: 'label', className: 'embed-url', events: { 'input': 'url', 'keyup': 'url', 'change': 'url' }, initialize: function() { this.input = this.make( 'input', { type: 'text', value: this.model.get('url') || '' }); this.spinner = this.make( 'span', { 'class': 'spinner' }); this.$input = $( this.input ); this.$el.append([ this.input, this.spinner ]); this.model.on( 'change:url', this.render, this ); }, render: function() { var $input = this.$input; if ( $input.is(':focus') ) return; this.input.value = this.model.get('url') || 'http://'; media.View.prototype.render.apply( this, arguments ); return this; }, ready: function() { this.focus(); }, url: function( event ) { this.model.set( 'url', event.target.value ); }, focus: function() { var $input = this.$input; // If the input is visible, focus and select its contents. if ( $input.is(':visible') ) $input.focus()[0].select(); } }); /** * wp.media.view.EmbedLink */ media.view.EmbedLink = media.view.Settings.extend({ className: 'embed-link-settings', template: media.template('embed-link-settings') }); /** * wp.media.view.EmbedImage */ media.view.EmbedImage = media.view.Settings.AttachmentDisplay.extend({ className: 'embed-image-settings', template: media.template('embed-image-settings'), initialize: function() { media.view.Settings.AttachmentDisplay.prototype.initialize.apply( this, arguments ); this.model.on( 'change:url', this.updateImage, this ); }, updateImage: function() { this.$('img').attr( 'src', this.model.get('url') ); } }); }(jQuery));
zyblog
trunk/zyblog/wp-includes/js/media-views.js
JavaScript
asf20
106,789
var wpLink; (function($){ var inputs = {}, rivers = {}, ed, River, Query; wpLink = { timeToTriggerRiver: 150, minRiverAJAXDuration: 200, riverBottomThreshold: 5, keySensitivity: 100, lastSearch: '', textarea: '', init : function() { inputs.dialog = $('#wp-link'); inputs.submit = $('#wp-link-submit'); // URL inputs.url = $('#url-field'); inputs.nonce = $('#_ajax_linking_nonce'); // Secondary options inputs.title = $('#link-title-field'); // Advanced Options inputs.openInNewTab = $('#link-target-checkbox'); inputs.search = $('#search-field'); // Build Rivers rivers.search = new River( $('#search-results') ); rivers.recent = new River( $('#most-recent-results') ); rivers.elements = $('.query-results', inputs.dialog); // Bind event handlers inputs.dialog.keydown( wpLink.keydown ); inputs.dialog.keyup( wpLink.keyup ); inputs.submit.click( function(e){ e.preventDefault(); wpLink.update(); }); $('#wp-link-cancel').click( function(e){ e.preventDefault(); wpLink.close(); }); $('#internal-toggle').click( wpLink.toggleInternalLinking ); rivers.elements.bind('river-select', wpLink.updateFields ); inputs.search.keyup( wpLink.searchInternalLinks ); inputs.dialog.bind('wpdialogrefresh', wpLink.refresh); inputs.dialog.bind('wpdialogbeforeopen', wpLink.beforeOpen); inputs.dialog.bind('wpdialogclose', wpLink.onClose); }, beforeOpen : function() { wpLink.range = null; if ( ! wpLink.isMCE() && document.selection ) { wpLink.textarea.focus(); wpLink.range = document.selection.createRange(); } }, open : function() { if ( !wpActiveEditor ) return; this.textarea = $('#'+wpActiveEditor).get(0); // Initialize the dialog if necessary (html mode). if ( ! inputs.dialog.data('wpdialog') ) { inputs.dialog.wpdialog({ title: wpLinkL10n.title, width: 480, height: 'auto', modal: true, dialogClass: 'wp-dialog', zIndex: 300000 }); } inputs.dialog.wpdialog('open'); }, isMCE : function() { return tinyMCEPopup && ( ed = tinyMCEPopup.editor ) && ! ed.isHidden(); }, refresh : function() { // Refresh rivers (clear links, check visibility) rivers.search.refresh(); rivers.recent.refresh(); if ( wpLink.isMCE() ) wpLink.mceRefresh(); else wpLink.setDefaultValues(); // Focus the URL field and highlight its contents. // If this is moved above the selection changes, // IE will show a flashing cursor over the dialog. inputs.url.focus()[0].select(); // Load the most recent results if this is the first time opening the panel. if ( ! rivers.recent.ul.children().length ) rivers.recent.ajax(); }, mceRefresh : function() { var e; ed = tinyMCEPopup.editor; tinyMCEPopup.restoreSelection(); // If link exists, select proper values. if ( e = ed.dom.getParent(ed.selection.getNode(), 'A') ) { // Set URL and description. inputs.url.val( ed.dom.getAttrib(e, 'href') ); inputs.title.val( ed.dom.getAttrib(e, 'title') ); // Set open in new tab. if ( "_blank" == ed.dom.getAttrib(e, 'target') ) inputs.openInNewTab.prop('checked', true); // Update save prompt. inputs.submit.val( wpLinkL10n.update ); // If there's no link, set the default values. } else { wpLink.setDefaultValues(); } tinyMCEPopup.storeSelection(); }, close : function() { if ( wpLink.isMCE() ) tinyMCEPopup.close(); else inputs.dialog.wpdialog('close'); }, onClose: function() { if ( ! wpLink.isMCE() ) { wpLink.textarea.focus(); if ( wpLink.range ) { wpLink.range.moveToBookmark( wpLink.range.getBookmark() ); wpLink.range.select(); } } }, getAttrs : function() { return { href : inputs.url.val(), title : inputs.title.val(), target : inputs.openInNewTab.prop('checked') ? '_blank' : '' }; }, update : function() { if ( wpLink.isMCE() ) wpLink.mceUpdate(); else wpLink.htmlUpdate(); }, htmlUpdate : function() { var attrs, html, begin, end, cursor, textarea = wpLink.textarea; if ( ! textarea ) return; attrs = wpLink.getAttrs(); // If there's no href, return. if ( ! attrs.href || attrs.href == 'http://' ) return; // Build HTML html = '<a href="' + attrs.href + '"'; if ( attrs.title ) html += ' title="' + attrs.title + '"'; if ( attrs.target ) html += ' target="' + attrs.target + '"'; html += '>'; // Insert HTML if ( document.selection && wpLink.range ) { // IE // Note: If no text is selected, IE will not place the cursor // inside the closing tag. textarea.focus(); wpLink.range.text = html + wpLink.range.text + '</a>'; wpLink.range.moveToBookmark( wpLink.range.getBookmark() ); wpLink.range.select(); wpLink.range = null; } else if ( typeof textarea.selectionStart !== 'undefined' ) { // W3C begin = textarea.selectionStart; end = textarea.selectionEnd; selection = textarea.value.substring( begin, end ); html = html + selection + '</a>'; cursor = begin + html.length; // If no next is selected, place the cursor inside the closing tag. if ( begin == end ) cursor -= '</a>'.length; textarea.value = textarea.value.substring( 0, begin ) + html + textarea.value.substring( end, textarea.value.length ); // Update cursor position textarea.selectionStart = textarea.selectionEnd = cursor; } wpLink.close(); textarea.focus(); }, mceUpdate : function() { var ed = tinyMCEPopup.editor, attrs = wpLink.getAttrs(), e, b; tinyMCEPopup.restoreSelection(); e = ed.dom.getParent(ed.selection.getNode(), 'A'); // If the values are empty, unlink and return if ( ! attrs.href || attrs.href == 'http://' ) { if ( e ) { tinyMCEPopup.execCommand("mceBeginUndoLevel"); b = ed.selection.getBookmark(); ed.dom.remove(e, 1); ed.selection.moveToBookmark(b); tinyMCEPopup.execCommand("mceEndUndoLevel"); wpLink.close(); } return; } tinyMCEPopup.execCommand("mceBeginUndoLevel"); if (e == null) { ed.getDoc().execCommand("unlink", false, null); tinyMCEPopup.execCommand("mceInsertLink", false, "#mce_temp_url#", {skip_undo : 1}); tinymce.each(ed.dom.select("a"), function(n) { if (ed.dom.getAttrib(n, 'href') == '#mce_temp_url#') { e = n; ed.dom.setAttribs(e, attrs); } }); // Sometimes WebKit lets a user create a link where // they shouldn't be able to. In this case, CreateLink // injects "#mce_temp_url#" into their content. Fix it. if ( $(e).text() == '#mce_temp_url#' ) { ed.dom.remove(e); e = null; } } else { ed.dom.setAttribs(e, attrs); } // Don't move caret if selection was image if ( e && (e.childNodes.length != 1 || e.firstChild.nodeName != 'IMG') ) { ed.focus(); ed.selection.select(e); ed.selection.collapse(0); tinyMCEPopup.storeSelection(); } tinyMCEPopup.execCommand("mceEndUndoLevel"); wpLink.close(); }, updateFields : function( e, li, originalEvent ) { inputs.url.val( li.children('.item-permalink').val() ); inputs.title.val( li.hasClass('no-title') ? '' : li.children('.item-title').text() ); if ( originalEvent && originalEvent.type == "click" ) inputs.url.focus(); }, setDefaultValues : function() { // Set URL and description to defaults. // Leave the new tab setting as-is. inputs.url.val('http://'); inputs.title.val(''); // Update save prompt. inputs.submit.val( wpLinkL10n.save ); }, searchInternalLinks : function() { var t = $(this), waiting, search = t.val(); if ( search.length > 2 ) { rivers.recent.hide(); rivers.search.show(); // Don't search if the keypress didn't change the title. if ( wpLink.lastSearch == search ) return; wpLink.lastSearch = search; waiting = t.parent().find('.spinner').show(); rivers.search.change( search ); rivers.search.ajax( function(){ waiting.hide(); }); } else { rivers.search.hide(); rivers.recent.show(); } }, next : function() { rivers.search.next(); rivers.recent.next(); }, prev : function() { rivers.search.prev(); rivers.recent.prev(); }, keydown : function( event ) { var fn, key = $.ui.keyCode; switch( event.which ) { case key.UP: fn = 'prev'; case key.DOWN: fn = fn || 'next'; clearInterval( wpLink.keyInterval ); wpLink[ fn ](); wpLink.keyInterval = setInterval( wpLink[ fn ], wpLink.keySensitivity ); break; default: return; } event.preventDefault(); }, keyup: function( event ) { var key = $.ui.keyCode; switch( event.which ) { case key.ESCAPE: event.stopImmediatePropagation(); if ( ! $(document).triggerHandler( 'wp_CloseOnEscape', [{ event: event, what: 'wplink', cb: wpLink.close }] ) ) wpLink.close(); return false; break; case key.UP: case key.DOWN: clearInterval( wpLink.keyInterval ); break; default: return; } event.preventDefault(); }, delayedCallback : function( func, delay ) { var timeoutTriggered, funcTriggered, funcArgs, funcContext; if ( ! delay ) return func; setTimeout( function() { if ( funcTriggered ) return func.apply( funcContext, funcArgs ); // Otherwise, wait. timeoutTriggered = true; }, delay); return function() { if ( timeoutTriggered ) return func.apply( this, arguments ); // Otherwise, wait. funcArgs = arguments; funcContext = this; funcTriggered = true; }; }, toggleInternalLinking : function( event ) { var panel = $('#search-panel'), widget = inputs.dialog.wpdialog('widget'), // We're about to toggle visibility; it's currently the opposite visible = !panel.is(':visible'), win = $(window); $(this).toggleClass('toggle-arrow-active', visible); inputs.dialog.height('auto'); panel.slideToggle( 300, function() { setUserSetting('wplink', visible ? '1' : '0'); inputs[ visible ? 'search' : 'url' ].focus(); // Move the box if the box is now expanded, was opened in a collapsed state, // and if it needs to be moved. (Judged by bottom not being positive or // bottom being smaller than top.) var scroll = win.scrollTop(), top = widget.offset().top, bottom = top + widget.outerHeight(), diff = bottom - win.height(); if ( diff > scroll ) { widget.animate({'top': diff < top ? top - diff : scroll }, 200); } }); event.preventDefault(); } } River = function( element, search ) { var self = this; this.element = element; this.ul = element.children('ul'); this.waiting = element.find('.river-waiting'); this.change( search ); this.refresh(); element.scroll( function(){ self.maybeLoad(); }); element.delegate('li', 'click', function(e){ self.select( $(this), e ); }); }; $.extend( River.prototype, { refresh: function() { this.deselect(); this.visible = this.element.is(':visible'); }, show: function() { if ( ! this.visible ) { this.deselect(); this.element.show(); this.visible = true; } }, hide: function() { this.element.hide(); this.visible = false; }, // Selects a list item and triggers the river-select event. select: function( li, event ) { var liHeight, elHeight, liTop, elTop; if ( li.hasClass('unselectable') || li == this.selected ) return; this.deselect(); this.selected = li.addClass('selected'); // Make sure the element is visible liHeight = li.outerHeight(); elHeight = this.element.height(); liTop = li.position().top; elTop = this.element.scrollTop(); if ( liTop < 0 ) // Make first visible element this.element.scrollTop( elTop + liTop ); else if ( liTop + liHeight > elHeight ) // Make last visible element this.element.scrollTop( elTop + liTop - elHeight + liHeight ); // Trigger the river-select event this.element.trigger('river-select', [ li, event, this ]); }, deselect: function() { if ( this.selected ) this.selected.removeClass('selected'); this.selected = false; }, prev: function() { if ( ! this.visible ) return; var to; if ( this.selected ) { to = this.selected.prev('li'); if ( to.length ) this.select( to ); } }, next: function() { if ( ! this.visible ) return; var to = this.selected ? this.selected.next('li') : $('li:not(.unselectable):first', this.element); if ( to.length ) this.select( to ); }, ajax: function( callback ) { var self = this, delay = this.query.page == 1 ? 0 : wpLink.minRiverAJAXDuration, response = wpLink.delayedCallback( function( results, params ) { self.process( results, params ); if ( callback ) callback( results, params ); }, delay ); this.query.ajax( response ); }, change: function( search ) { if ( this.query && this._search == search ) return; this._search = search; this.query = new Query( search ); this.element.scrollTop(0); }, process: function( results, params ) { var list = '', alt = true, classes = '', firstPage = params.page == 1; if ( !results ) { if ( firstPage ) { list += '<li class="unselectable"><span class="item-title"><em>' + wpLinkL10n.noMatchesFound + '</em></span></li>'; } } else { $.each( results, function() { classes = alt ? 'alternate' : ''; classes += this['title'] ? '' : ' no-title'; list += classes ? '<li class="' + classes + '">' : '<li>'; list += '<input type="hidden" class="item-permalink" value="' + this['permalink'] + '" />'; list += '<span class="item-title">'; list += this['title'] ? this['title'] : wpLinkL10n.noTitle; list += '</span><span class="item-info">' + this['info'] + '</span></li>'; alt = ! alt; }); } this.ul[ firstPage ? 'html' : 'append' ]( list ); }, maybeLoad: function() { var self = this, el = this.element, bottom = el.scrollTop() + el.height(); if ( ! this.query.ready() || bottom < this.ul.height() - wpLink.riverBottomThreshold ) return; setTimeout(function() { var newTop = el.scrollTop(), newBottom = newTop + el.height(); if ( ! self.query.ready() || newBottom < self.ul.height() - wpLink.riverBottomThreshold ) return; self.waiting.show(); el.scrollTop( newTop + self.waiting.outerHeight() ); self.ajax( function() { self.waiting.hide(); }); }, wpLink.timeToTriggerRiver ); } }); Query = function( search ) { this.page = 1; this.allLoaded = false; this.querying = false; this.search = search; }; $.extend( Query.prototype, { ready: function() { return !( this.querying || this.allLoaded ); }, ajax: function( callback ) { var self = this, query = { action : 'wp-link-ajax', page : this.page, '_ajax_linking_nonce' : inputs.nonce.val() }; if ( this.search ) query.search = this.search; this.querying = true; $.post( ajaxurl, query, function(r) { self.page++; self.querying = false; self.allLoaded = !r; callback( r, query ); }, "json" ); } }); $(document).ready( wpLink.init ); })(jQuery);
zyblog
trunk/zyblog/wp-includes/js/wplink.js
JavaScript
asf20
15,505
/* ----------------------------------------------------------------------------------------------------------------*/ /* ---------->>> thickbox specific link and font settings <<<------------------------------------------------------*/ /* ----------------------------------------------------------------------------------------------------------------*/ #TB_window { font: 12px sans-serif; color: #333333; } #TB_secondLine { font: 10px sans-serif; color:#666666; } #TB_window a:link {color: #666666;} #TB_window a:visited {color: #666666;} #TB_window a:hover {color: #000;} #TB_window a:active {color: #666666;} #TB_window a:focus{color: #666666;} /* ----------------------------------------------------------------------------------------------------------------*/ /* ---------->>> thickbox settings <<<-----------------------------------------------------------------------------*/ /* ----------------------------------------------------------------------------------------------------------------*/ #TB_overlay { position: fixed; z-index:100; top: 0px; left: 0px; height:100%; width:100%; } .TB_overlayMacFFBGHack {background: url(macFFBgHack.png) repeat;} .TB_overlayBG { background-color:#000; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=75)"; filter:alpha(opacity=75); -moz-opacity: 0.75; opacity: 0.75; } * html #TB_overlay { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_window { position: fixed; background: #ffffff; z-index: 102; color:#000000; visibility: hidden; text-align:left; top:50%; left:50%; border: 1px solid #555; -moz-box-shadow: rgba(0,0,0,1) 0 4px 30px; -webkit-box-shadow: rgba(0,0,0,1) 0 4px 30px; -khtml-box-shadow: rgba(0,0,0,1) 0 4px 30px; box-shadow: rgba(0,0,0,1) 0 4px 30px; } * html #TB_window { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_window img#TB_Image { display:block; margin: 15px 0 0 15px; border-right: 1px solid #ccc; border-bottom: 1px solid #ccc; border-top: 1px solid #666; border-left: 1px solid #666; } #TB_caption{ height:25px; padding:7px 30px 10px 25px; float:left; } #TB_closeWindow{ height:25px; padding:11px 25px 10px 0; float:right; } #TB_closeAjaxWindow{ padding:6px 10px 0; text-align:right; float:right; } #TB_ajaxWindowTitle{ float:left; padding:6px 10px 0; } #TB_title{ background-color:#e8e8e8; height:27px; } #TB_ajaxContent{ clear:both; padding:2px 15px 15px 15px; overflow:auto; text-align:left; line-height:1.4em; } #TB_ajaxContent.TB_modal{ padding:15px; } #TB_ajaxContent p{ padding:5px 0px 5px 0px; } #TB_load{ position: fixed; display:none; z-index:103; top: 50%; left: 50%; background-color: #E8E8E8; border: 1px solid #555; margin: -45px 0pt 0pt -125px; padding: 40px 15px 15px; } * html #TB_load { /* ie6 hack */ position: absolute; margin-top: expression(0 - parseInt(this.offsetHeight / 2) + (TBWindowMargin = document.documentElement && document.documentElement.scrollTop || document.body.scrollTop) + 'px'); } #TB_HideSelect{ z-index:99; position:fixed; top: 0; left: 0; background-color:#fff; border:none; filter:alpha(opacity=0); -moz-opacity: 0; opacity: 0; height:100%; width:100%; } * html #TB_HideSelect { /* ie6 hack */ position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'); } #TB_iframeContent{ clear:both; border:none; margin-bottom:-1px; _margin-bottom:1px; } .tb-close-icon { background: url('tb-close.png') no-repeat; height: 15px; width: 15px; } @media print, (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .tb-close-icon { background: url('tb-close-2x.png') no-repeat; background-size: 15px; } }
zyblog
trunk/zyblog/wp-includes/js/thickbox/thickbox.css
CSS
asf20
4,114
/* * Thickbox 3.1 - One Box To Rule Them All. * By Cody Lindley (http://www.codylindley.com) * Copyright (c) 2007 cody lindley * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php */ if ( typeof tb_pathToImage != 'string' ) { var tb_pathToImage = thickboxL10n.loadingAnimation; } /*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/ //on page load call tb_init jQuery(document).ready(function(){ tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox imgLoader = new Image();// preload image imgLoader.src = tb_pathToImage; }); //add thickbox to href & area elements that have a class of .thickbox function tb_init(domChunk){ jQuery(domChunk).live('click', tb_click); } function tb_click(){ var t = this.title || this.name || null; var a = this.href || this.alt; var g = this.rel || false; tb_show(t,a,g); this.blur(); return false; } function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link try { if (typeof document.body.style.maxHeight === "undefined") {//if IE 6 jQuery("body","html").css({height: "100%", width: "100%"}); jQuery("html").css("overflow","hidden"); if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6 jQuery("body").append("<iframe id='TB_HideSelect'>"+thickboxL10n.noiframes+"</iframe><div id='TB_overlay'></div><div id='TB_window'></div>"); jQuery("#TB_overlay").click(tb_remove); } }else{//all others if(document.getElementById("TB_overlay") === null){ jQuery("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>"); jQuery("#TB_overlay").click(tb_remove); } } if(tb_detectMacXFF()){ jQuery("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash }else{ jQuery("#TB_overlay").addClass("TB_overlayBG");//use background and opacity } if(caption===null){caption="";} jQuery("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' width='208' /></div>");//add loader to the page jQuery('#TB_load').show();//show loader var baseURL; if(url.indexOf("?")!==-1){ //ff there is a query string involved baseURL = url.substr(0, url.indexOf("?")); }else{ baseURL = url; } var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; var urlType = baseURL.toLowerCase().match(urlString); if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images TB_PrevCaption = ""; TB_PrevURL = ""; TB_PrevHTML = ""; TB_NextCaption = ""; TB_NextURL = ""; TB_NextHTML = ""; TB_imageCount = ""; TB_FoundURL = false; if(imageGroup){ TB_TempArray = jQuery("a[rel="+imageGroup+"]").get(); for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) { var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString); if (!(TB_TempArray[TB_Counter].href == url)) { if (TB_FoundURL) { TB_NextCaption = TB_TempArray[TB_Counter].title; TB_NextURL = TB_TempArray[TB_Counter].href; TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>"+thickboxL10n.next+"</a></span>"; } else { TB_PrevCaption = TB_TempArray[TB_Counter].title; TB_PrevURL = TB_TempArray[TB_Counter].href; TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>"+thickboxL10n.prev+"</a></span>"; } } else { TB_FoundURL = true; TB_imageCount = thickboxL10n.image + ' ' + (TB_Counter + 1) + ' ' + thickboxL10n.of + ' ' + (TB_TempArray.length); } } } imgPreloader = new Image(); imgPreloader.onload = function(){ imgPreloader.onload = null; // Resizing large images - orginal by Christian Montoya edited by me. var pagesize = tb_getPageSize(); var x = pagesize[0] - 150; var y = pagesize[1] - 150; var imageWidth = imgPreloader.width; var imageHeight = imgPreloader.height; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; } } else if (imageHeight > y) { imageWidth = imageWidth * (y / imageHeight); imageHeight = y; if (imageWidth > x) { imageHeight = imageHeight * (x / imageWidth); imageWidth = x; } } // End Resizing TB_WIDTH = imageWidth + 30; TB_HEIGHT = imageHeight + 60; jQuery("#TB_window").append("<a href='' id='TB_ImageOff' title='"+thickboxL10n.close+"'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><div class='tb-close-icon'></div></a></div>"); jQuery("#TB_closeWindowButton").click(tb_remove); if (!(TB_PrevHTML === "")) { function goPrev(){ if(jQuery(document).unbind("click",goPrev)){jQuery(document).unbind("click",goPrev);} jQuery("#TB_window").remove(); jQuery("body").append("<div id='TB_window'></div>"); tb_show(TB_PrevCaption, TB_PrevURL, imageGroup); return false; } jQuery("#TB_prev").click(goPrev); } if (!(TB_NextHTML === "")) { function goNext(){ jQuery("#TB_window").remove(); jQuery("body").append("<div id='TB_window'></div>"); tb_show(TB_NextCaption, TB_NextURL, imageGroup); return false; } jQuery("#TB_next").click(goNext); } jQuery(document).bind('keydown.thickbox', function(e){ e.stopImmediatePropagation(); if ( e.which == 27 ){ // close if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) ) tb_remove(); } else if ( e.which == 190 ){ // display previous image if(!(TB_NextHTML == "")){ jQuery(document).unbind('thickbox'); goNext(); } } else if ( e.which == 188 ){ // display next image if(!(TB_PrevHTML == "")){ jQuery(document).unbind('thickbox'); goPrev(); } } return false; }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_ImageOff").click(tb_remove); jQuery("#TB_window").css({'visibility':'visible'}); //for safari using css instead of show }; imgPreloader.src = url; }else{//code to show html var queryString = url.replace(/^[^\?]+\??/,''); var params = tb_parseQuery( queryString ); TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL ajaxContentW = TB_WIDTH - 30; ajaxContentH = TB_HEIGHT - 45; if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window urlNoQuery = url.split('TB_'); jQuery("#TB_iframeContent").remove(); if(params['modal'] != "true"){//iframe no modal jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='"+thickboxL10n.close+"'><div class='tb-close-icon'></div></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' >"+thickboxL10n.noiframes+"</iframe>"); }else{//iframe modal jQuery("#TB_overlay").unbind(); jQuery("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'>"+thickboxL10n.noiframes+"</iframe>"); } }else{// not an iframe, ajax if(jQuery("#TB_window").css("visibility") != "visible"){ if(params['modal'] != "true"){//ajax no modal jQuery("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'><div class='tb-close-icon'></div></a></div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>"); }else{//ajax modal jQuery("#TB_overlay").unbind(); jQuery("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); } }else{//this means the window is already up, we are just loading new content via ajax jQuery("#TB_ajaxContent")[0].style.width = ajaxContentW +"px"; jQuery("#TB_ajaxContent")[0].style.height = ajaxContentH +"px"; jQuery("#TB_ajaxContent")[0].scrollTop = 0; jQuery("#TB_ajaxWindowTitle").html(caption); } } jQuery("#TB_closeWindowButton").click(tb_remove); if(url.indexOf('TB_inline') != -1){ jQuery("#TB_ajaxContent").append(jQuery('#' + params['inlineId']).children()); jQuery("#TB_window").bind('tb_unload', function () { jQuery('#' + params['inlineId']).append( jQuery("#TB_ajaxContent").children() ); // move elements back when you're finished }); tb_position(); jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); }else if(url.indexOf('TB_iframe') != -1){ tb_position(); if(jQuery.browser.safari){//safari needs help because it will not fire iframe onload jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); } }else{ jQuery("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method tb_position(); jQuery("#TB_load").remove(); tb_init("#TB_ajaxContent a.thickbox"); jQuery("#TB_window").css({'visibility':'visible'}); }); } } if(!params['modal']){ jQuery(document).bind('keyup.thickbox', function(e){ if ( e.which == 27 ){ // close e.stopImmediatePropagation(); if ( ! jQuery(document).triggerHandler( 'wp_CloseOnEscape', [{ event: e, what: 'thickbox', cb: tb_remove }] ) ) tb_remove(); return false; } }); } } catch(e) { //nothing here } } //helper functions below function tb_showIframe(){ jQuery("#TB_load").remove(); jQuery("#TB_window").css({'visibility':'visible'}); } function tb_remove() { jQuery("#TB_imageOff").unbind("click"); jQuery("#TB_closeWindowButton").unbind("click"); jQuery("#TB_window").fadeOut("fast",function(){jQuery('#TB_window,#TB_overlay,#TB_HideSelect').trigger("tb_unload").unbind().remove();}); jQuery("#TB_load").remove(); if (typeof document.body.style.maxHeight == "undefined") {//if IE 6 jQuery("body","html").css({height: "auto", width: "auto"}); jQuery("html").css("overflow",""); } jQuery(document).unbind('.thickbox'); return false; } function tb_position() { var isIE6 = typeof document.body.style.maxHeight === "undefined"; jQuery("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'}); if ( ! isIE6 ) { // take away IE6 jQuery("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'}); } } function tb_parseQuery ( query ) { var Params = {}; if ( ! query ) {return Params;}// return empty object var Pairs = query.split(/[;&]/); for ( var i = 0; i < Pairs.length; i++ ) { var KeyVal = Pairs[i].split('='); if ( ! KeyVal || KeyVal.length != 2 ) {continue;} var key = unescape( KeyVal[0] ); var val = unescape( KeyVal[1] ); val = val.replace(/\+/g, ' '); Params[key] = val; } return Params; } function tb_getPageSize(){ var de = document.documentElement; var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth; var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight; arrayPageSize = [w,h]; return arrayPageSize; } function tb_detectMacXFF() { var userAgent = navigator.userAgent.toLowerCase(); if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) { return true; } }
zyblog
trunk/zyblog/wp-includes/js/thickbox/thickbox.js
JavaScript
asf20
12,417
<?php /** * WordPress API for media display. * * @package WordPress * @subpackage Media */ /** * Scale down the default size of an image. * * This is so that the image is a better fit for the editor and theme. * * The $size parameter accepts either an array or a string. The supported string * values are 'thumb' or 'thumbnail' for the given thumbnail size or defaults at * 128 width and 96 height in pixels. Also supported for the string value is * 'medium' and 'full'. The 'full' isn't actually supported, but any value other * than the supported will result in the content_width size or 500 if that is * not set. * * Finally, there is a filter named 'editor_max_image_size', that will be called * on the calculated array for width and height, respectively. The second * parameter will be the value that was in the $size parameter. The returned * type for the hook is an array with the width as the first element and the * height as the second element. * * @since 2.5.0 * @uses wp_constrain_dimensions() This function passes the widths and the heights. * * @param int $width Width of the image * @param int $height Height of the image * @param string|array $size Size of what the result image should be. * @param context Could be 'display' (like in a theme) or 'edit' (like inserting into an editor) * @return array Width and height of what the result image should resize to. */ function image_constrain_size_for_editor($width, $height, $size = 'medium', $context = null ) { global $content_width, $_wp_additional_image_sizes; if ( ! $context ) $context = is_admin() ? 'edit' : 'display'; if ( is_array($size) ) { $max_width = $size[0]; $max_height = $size[1]; } elseif ( $size == 'thumb' || $size == 'thumbnail' ) { $max_width = intval(get_option('thumbnail_size_w')); $max_height = intval(get_option('thumbnail_size_h')); // last chance thumbnail size defaults if ( !$max_width && !$max_height ) { $max_width = 128; $max_height = 96; } } elseif ( $size == 'medium' ) { $max_width = intval(get_option('medium_size_w')); $max_height = intval(get_option('medium_size_h')); // if no width is set, default to the theme content width if available } elseif ( $size == 'large' ) { // We're inserting a large size image into the editor. If it's a really // big image we'll scale it down to fit reasonably within the editor // itself, and within the theme's content width if it's known. The user // can resize it in the editor if they wish. $max_width = intval(get_option('large_size_w')); $max_height = intval(get_option('large_size_h')); if ( intval($content_width) > 0 ) $max_width = min( intval($content_width), $max_width ); } elseif ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) && in_array( $size, array_keys( $_wp_additional_image_sizes ) ) ) { $max_width = intval( $_wp_additional_image_sizes[$size]['width'] ); $max_height = intval( $_wp_additional_image_sizes[$size]['height'] ); if ( intval($content_width) > 0 && 'edit' == $context ) // Only in admin. Assume that theme authors know what they're doing. $max_width = min( intval($content_width), $max_width ); } // $size == 'full' has no constraint else { $max_width = $width; $max_height = $height; } list( $max_width, $max_height ) = apply_filters( 'editor_max_image_size', array( $max_width, $max_height ), $size, $context ); return wp_constrain_dimensions( $width, $height, $max_width, $max_height ); } /** * Retrieve width and height attributes using given width and height values. * * Both attributes are required in the sense that both parameters must have a * value, but are optional in that if you set them to false or null, then they * will not be added to the returned string. * * You can set the value using a string, but it will only take numeric values. * If you wish to put 'px' after the numbers, then it will be stripped out of * the return. * * @since 2.5.0 * * @param int|string $width Optional. Width attribute value. * @param int|string $height Optional. Height attribute value. * @return string HTML attributes for width and, or height. */ function image_hwstring($width, $height) { $out = ''; if ($width) $out .= 'width="'.intval($width).'" '; if ($height) $out .= 'height="'.intval($height).'" '; return $out; } /** * Scale an image to fit a particular size (such as 'thumb' or 'medium'). * * Array with image url, width, height, and whether is intermediate size, in * that order is returned on success is returned. $is_intermediate is true if * $url is a resized image, false if it is the original. * * The URL might be the original image, or it might be a resized version. This * function won't create a new resized copy, it will just return an already * resized one if it exists. * * A plugin may use the 'image_downsize' filter to hook into and offer image * resizing services for images. The hook must return an array with the same * elements that are returned in the function. The first element being the URL * to the new image that was resized. * * @since 2.5.0 * @uses apply_filters() Calls 'image_downsize' on $id and $size to provide * resize services. * * @param int $id Attachment ID for image. * @param array|string $size Optional, default is 'medium'. Size of image, either array or string. * @return bool|array False on failure, array on success. */ function image_downsize($id, $size = 'medium') { if ( !wp_attachment_is_image($id) ) return false; $img_url = wp_get_attachment_url($id); $meta = wp_get_attachment_metadata($id); $width = $height = 0; $is_intermediate = false; $img_url_basename = wp_basename($img_url); // plugins can use this to provide resize services if ( $out = apply_filters('image_downsize', false, $id, $size) ) return $out; // try for a new style intermediate size if ( $intermediate = image_get_intermediate_size($id, $size) ) { $img_url = str_replace($img_url_basename, $intermediate['file'], $img_url); $width = $intermediate['width']; $height = $intermediate['height']; $is_intermediate = true; } elseif ( $size == 'thumbnail' ) { // fall back to the old thumbnail if ( ($thumb_file = wp_get_attachment_thumb_file($id)) && $info = getimagesize($thumb_file) ) { $img_url = str_replace($img_url_basename, wp_basename($thumb_file), $img_url); $width = $info[0]; $height = $info[1]; $is_intermediate = true; } } if ( !$width && !$height && isset($meta['width'], $meta['height']) ) { // any other type: use the real image $width = $meta['width']; $height = $meta['height']; } if ( $img_url) { // we have the actual image size, but might need to further constrain it if content_width is narrower list( $width, $height ) = image_constrain_size_for_editor( $width, $height, $size ); return array( $img_url, $width, $height, $is_intermediate ); } return false; } /** * Registers a new image size * * @since 2.9.0 */ function add_image_size( $name, $width = 0, $height = 0, $crop = false ) { global $_wp_additional_image_sizes; $_wp_additional_image_sizes[$name] = array( 'width' => absint( $width ), 'height' => absint( $height ), 'crop' => (bool) $crop ); } /** * Registers an image size for the post thumbnail * * @since 2.9.0 */ function set_post_thumbnail_size( $width = 0, $height = 0, $crop = false ) { add_image_size( 'post-thumbnail', $width, $height, $crop ); } /** * An <img src /> tag for an image attachment, scaling it down if requested. * * The filter 'get_image_tag_class' allows for changing the class name for the * image without having to use regular expressions on the HTML content. The * parameters are: what WordPress will use for the class, the Attachment ID, * image align value, and the size the image should be. * * The second filter 'get_image_tag' has the HTML content, which can then be * further manipulated by a plugin to change all attribute values and even HTML * content. * * @since 2.5.0 * * @uses apply_filters() The 'get_image_tag_class' filter is the IMG element * class attribute. * @uses apply_filters() The 'get_image_tag' filter is the full IMG element with * all attributes. * * @param int $id Attachment ID. * @param string $alt Image Description for the alt attribute. * @param string $title Image Description for the title attribute. * @param string $align Part of the class name for aligning the image. * @param string $size Optional. Default is 'medium'. * @return string HTML IMG element for given image attachment */ function get_image_tag($id, $alt, $title, $align, $size='medium') { list( $img_src, $width, $height ) = image_downsize($id, $size); $hwstring = image_hwstring($width, $height); $title = $title ? 'title="' . esc_attr( $title ) . '" ' : ''; $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id; $class = apply_filters('get_image_tag_class', $class, $id, $align, $size); $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" ' . $title . $hwstring . 'class="' . $class . '" />'; $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size ); return $html; } /** * Calculates the new dimensions for a downsampled image. * * If either width or height are empty, no constraint is applied on * that dimension. * * @since 2.5.0 * * @param int $current_width Current width of the image. * @param int $current_height Current height of the image. * @param int $max_width Optional. Maximum wanted width. * @param int $max_height Optional. Maximum wanted height. * @return array First item is the width, the second item is the height. */ function wp_constrain_dimensions( $current_width, $current_height, $max_width=0, $max_height=0 ) { if ( !$max_width and !$max_height ) return array( $current_width, $current_height ); $width_ratio = $height_ratio = 1.0; $did_width = $did_height = false; if ( $max_width > 0 && $current_width > 0 && $current_width > $max_width ) { $width_ratio = $max_width / $current_width; $did_width = true; } if ( $max_height > 0 && $current_height > 0 && $current_height > $max_height ) { $height_ratio = $max_height / $current_height; $did_height = true; } // Calculate the larger/smaller ratios $smaller_ratio = min( $width_ratio, $height_ratio ); $larger_ratio = max( $width_ratio, $height_ratio ); if ( intval( $current_width * $larger_ratio ) > $max_width || intval( $current_height * $larger_ratio ) > $max_height ) // The larger ratio is too big. It would result in an overflow. $ratio = $smaller_ratio; else // The larger ratio fits, and is likely to be a more "snug" fit. $ratio = $larger_ratio; $w = intval( $current_width * $ratio ); $h = intval( $current_height * $ratio ); // Sometimes, due to rounding, we'll end up with a result like this: 465x700 in a 177x177 box is 117x176... a pixel short // We also have issues with recursive calls resulting in an ever-changing result. Constraining to the result of a constraint should yield the original result. // Thus we look for dimensions that are one pixel shy of the max value and bump them up if ( $did_width && $w == $max_width - 1 ) $w = $max_width; // Round it up if ( $did_height && $h == $max_height - 1 ) $h = $max_height; // Round it up return array( $w, $h ); } /** * Retrieve calculated resized dimensions for use in WP_Image_Editor. * * Calculate dimensions and coordinates for a resized image that fits within a * specified width and height. If $crop is true, the largest matching central * portion of the image will be cropped out and resized to the required size. * * @since 2.5.0 * @uses apply_filters() Calls 'image_resize_dimensions' on $orig_w, $orig_h, $dest_w, $dest_h and * $crop to provide custom resize dimensions. * * @param int $orig_w Original width. * @param int $orig_h Original height. * @param int $dest_w New width. * @param int $dest_h New height. * @param bool $crop Optional, default is false. Whether to crop image or resize. * @return bool|array False on failure. Returned array matches parameters for imagecopyresampled() PHP function. */ function image_resize_dimensions($orig_w, $orig_h, $dest_w, $dest_h, $crop = false) { if ($orig_w <= 0 || $orig_h <= 0) return false; // at least one of dest_w or dest_h must be specific if ($dest_w <= 0 && $dest_h <= 0) return false; // plugins can use this to provide custom resize dimensions $output = apply_filters( 'image_resize_dimensions', null, $orig_w, $orig_h, $dest_w, $dest_h, $crop ); if ( null !== $output ) return $output; if ( $crop ) { // crop the largest possible portion of the original image that we can size to $dest_w x $dest_h $aspect_ratio = $orig_w / $orig_h; $new_w = min($dest_w, $orig_w); $new_h = min($dest_h, $orig_h); if ( !$new_w ) { $new_w = intval($new_h * $aspect_ratio); } if ( !$new_h ) { $new_h = intval($new_w / $aspect_ratio); } $size_ratio = max($new_w / $orig_w, $new_h / $orig_h); $crop_w = round($new_w / $size_ratio); $crop_h = round($new_h / $size_ratio); $s_x = floor( ($orig_w - $crop_w) / 2 ); $s_y = floor( ($orig_h - $crop_h) / 2 ); } else { // don't crop, just resize using $dest_w x $dest_h as a maximum bounding box $crop_w = $orig_w; $crop_h = $orig_h; $s_x = 0; $s_y = 0; list( $new_w, $new_h ) = wp_constrain_dimensions( $orig_w, $orig_h, $dest_w, $dest_h ); } // if the resulting image would be the same size or larger we don't want to resize it if ( $new_w >= $orig_w && $new_h >= $orig_h ) return false; // the return array matches the parameters to imagecopyresampled() // int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h ); } /** * Resize an image to make a thumbnail or intermediate size. * * The returned array has the file size, the image width, and image height. The * filter 'image_make_intermediate_size' can be used to hook in and change the * values of the returned array. The only parameter is the resized file path. * * @since 2.5.0 * * @param string $file File path. * @param int $width Image width. * @param int $height Image height. * @param bool $crop Optional, default is false. Whether to crop image to specified height and width or resize. * @return bool|array False, if no image was created. Metadata array on success. */ function image_make_intermediate_size( $file, $width, $height, $crop = false ) { if ( $width || $height ) { $editor = wp_get_image_editor( $file ); if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) ) return false; $resized_file = $editor->save(); if ( ! is_wp_error( $resized_file ) && $resized_file ) { unset( $resized_file['path'] ); return $resized_file; } } return false; } /** * Retrieve the image's intermediate size (resized) path, width, and height. * * The $size parameter can be an array with the width and height respectively. * If the size matches the 'sizes' metadata array for width and height, then it * will be used. If there is no direct match, then the nearest image size larger * than the specified size will be used. If nothing is found, then the function * will break out and return false. * * The metadata 'sizes' is used for compatible sizes that can be used for the * parameter $size value. * * The url path will be given, when the $size parameter is a string. * * If you are passing an array for the $size, you should consider using * add_image_size() so that a cropped version is generated. It's much more * efficient than having to find the closest-sized image and then having the * browser scale down the image. * * @since 2.5.0 * @see add_image_size() * * @param int $post_id Attachment ID for image. * @param array|string $size Optional, default is 'thumbnail'. Size of image, either array or string. * @return bool|array False on failure or array of file path, width, and height on success. */ function image_get_intermediate_size($post_id, $size='thumbnail') { if ( !is_array( $imagedata = wp_get_attachment_metadata( $post_id ) ) ) return false; // get the best one for a specified set of dimensions if ( is_array($size) && !empty($imagedata['sizes']) ) { foreach ( $imagedata['sizes'] as $_size => $data ) { // already cropped to width or height; so use this size if ( ( $data['width'] == $size[0] && $data['height'] <= $size[1] ) || ( $data['height'] == $size[1] && $data['width'] <= $size[0] ) ) { $file = $data['file']; list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size ); return compact( 'file', 'width', 'height' ); } // add to lookup table: area => size $areas[$data['width'] * $data['height']] = $_size; } if ( !$size || !empty($areas) ) { // find for the smallest image not smaller than the desired size ksort($areas); foreach ( $areas as $_size ) { $data = $imagedata['sizes'][$_size]; if ( $data['width'] >= $size[0] || $data['height'] >= $size[1] ) { // Skip images with unexpectedly divergent aspect ratios (crops) // First, we calculate what size the original image would be if constrained to a box the size of the current image in the loop $maybe_cropped = image_resize_dimensions($imagedata['width'], $imagedata['height'], $data['width'], $data['height'], false ); // If the size doesn't match within one pixel, then it is of a different aspect ratio, so we skip it, unless it's the thumbnail size if ( 'thumbnail' != $_size && ( !$maybe_cropped || ( $maybe_cropped[4] != $data['width'] && $maybe_cropped[4] + 1 != $data['width'] ) || ( $maybe_cropped[5] != $data['height'] && $maybe_cropped[5] + 1 != $data['height'] ) ) ) continue; // If we're still here, then we're going to use this size $file = $data['file']; list($width, $height) = image_constrain_size_for_editor( $data['width'], $data['height'], $size ); return compact( 'file', 'width', 'height' ); } } } } if ( is_array($size) || empty($size) || empty($imagedata['sizes'][$size]) ) return false; $data = $imagedata['sizes'][$size]; // include the full filesystem path of the intermediate file if ( empty($data['path']) && !empty($data['file']) ) { $file_url = wp_get_attachment_url($post_id); $data['path'] = path_join( dirname($imagedata['file']), $data['file'] ); $data['url'] = path_join( dirname($file_url), $data['file'] ); } return $data; } /** * Get the available image sizes * @since 3.0.0 * @return array Returns a filtered array of image size strings */ function get_intermediate_image_sizes() { global $_wp_additional_image_sizes; $image_sizes = array('thumbnail', 'medium', 'large'); // Standard sizes if ( isset( $_wp_additional_image_sizes ) && count( $_wp_additional_image_sizes ) ) $image_sizes = array_merge( $image_sizes, array_keys( $_wp_additional_image_sizes ) ); return apply_filters( 'intermediate_image_sizes', $image_sizes ); } /** * Retrieve an image to represent an attachment. * * A mime icon for files, thumbnail or intermediate size for images. * * @since 2.5.0 * * @param int $attachment_id Image attachment ID. * @param string $size Optional, default is 'thumbnail'. * @param bool $icon Optional, default is false. Whether it is an icon. * @return bool|array Returns an array (url, width, height), or false, if no image is available. */ function wp_get_attachment_image_src($attachment_id, $size='thumbnail', $icon = false) { // get a thumbnail or intermediate image if there is one if ( $image = image_downsize($attachment_id, $size) ) return $image; $src = false; if ( $icon && $src = wp_mime_type_icon($attachment_id) ) { $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' ); $src_file = $icon_dir . '/' . wp_basename($src); @list($width, $height) = getimagesize($src_file); } if ( $src && $width && $height ) return array( $src, $width, $height ); return false; } /** * Get an HTML img element representing an image attachment * * While $size will accept an array, it is better to register a size with * add_image_size() so that a cropped version is generated. It's much more * efficient than having to find the closest-sized image and then having the * browser scale down the image. * * @see add_image_size() * @uses apply_filters() Calls 'wp_get_attachment_image_attributes' hook on attributes array * @uses wp_get_attachment_image_src() Gets attachment file URL and dimensions * @since 2.5.0 * * @param int $attachment_id Image attachment ID. * @param string $size Optional, default is 'thumbnail'. * @param bool $icon Optional, default is false. Whether it is an icon. * @return string HTML img element or empty string on failure. */ function wp_get_attachment_image($attachment_id, $size = 'thumbnail', $icon = false, $attr = '') { $html = ''; $image = wp_get_attachment_image_src($attachment_id, $size, $icon); if ( $image ) { list($src, $width, $height) = $image; $hwstring = image_hwstring($width, $height); if ( is_array($size) ) $size = join('x', $size); $attachment = get_post($attachment_id); $default_attr = array( 'src' => $src, 'class' => "attachment-$size", 'alt' => trim(strip_tags( get_post_meta($attachment_id, '_wp_attachment_image_alt', true) )), // Use Alt field first ); if ( empty($default_attr['alt']) ) $default_attr['alt'] = trim(strip_tags( $attachment->post_excerpt )); // If not, Use the Caption if ( empty($default_attr['alt']) ) $default_attr['alt'] = trim(strip_tags( $attachment->post_title )); // Finally, use the title $attr = wp_parse_args($attr, $default_attr); $attr = apply_filters( 'wp_get_attachment_image_attributes', $attr, $attachment ); $attr = array_map( 'esc_attr', $attr ); $html = rtrim("<img $hwstring"); foreach ( $attr as $name => $value ) { $html .= " $name=" . '"' . $value . '"'; } $html .= ' />'; } return $html; } /** * Adds a 'wp-post-image' class to post thumbnails * Uses the begin_fetch_post_thumbnail_html and end_fetch_post_thumbnail_html action hooks to * dynamically add/remove itself so as to only filter post thumbnails * * @since 2.9.0 * @param array $attr Attributes including src, class, alt, title * @return array */ function _wp_post_thumbnail_class_filter( $attr ) { $attr['class'] .= ' wp-post-image'; return $attr; } /** * Adds _wp_post_thumbnail_class_filter to the wp_get_attachment_image_attributes filter * * @since 2.9.0 */ function _wp_post_thumbnail_class_filter_add( $attr ) { add_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' ); } /** * Removes _wp_post_thumbnail_class_filter from the wp_get_attachment_image_attributes filter * * @since 2.9.0 */ function _wp_post_thumbnail_class_filter_remove( $attr ) { remove_filter( 'wp_get_attachment_image_attributes', '_wp_post_thumbnail_class_filter' ); } add_shortcode('wp_caption', 'img_caption_shortcode'); add_shortcode('caption', 'img_caption_shortcode'); /** * The Caption shortcode. * * Allows a plugin to replace the content that would otherwise be returned. The * filter is 'img_caption_shortcode' and passes an empty string, the attr * parameter and the content parameter values. * * The supported attributes for the shortcode are 'id', 'align', 'width', and * 'caption'. * * @since 2.6.0 * * @param array $attr Attributes attributed to the shortcode. * @param string $content Optional. Shortcode content. * @return string */ function img_caption_shortcode($attr, $content = null) { // New-style shortcode with the caption inside the shortcode with the link and image tags. if ( ! isset( $attr['caption'] ) ) { if ( preg_match( '#((?:<a [^>]+>\s*)?<img [^>]+>(?:\s*</a>)?)(.*)#is', $content, $matches ) ) { $content = $matches[1]; $attr['caption'] = trim( $matches[2] ); } } // Allow plugins/themes to override the default caption template. $output = apply_filters('img_caption_shortcode', '', $attr, $content); if ( $output != '' ) return $output; extract(shortcode_atts(array( 'id' => '', 'align' => 'alignnone', 'width' => '', 'caption' => '' ), $attr)); if ( 1 > (int) $width || empty($caption) ) return $content; if ( $id ) $id = 'id="' . esc_attr($id) . '" '; return '<div ' . $id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px">' . do_shortcode( $content ) . '<p class="wp-caption-text">' . $caption . '</p></div>'; } add_shortcode('gallery', 'gallery_shortcode'); /** * The Gallery shortcode. * * This implements the functionality of the Gallery Shortcode for displaying * WordPress images on a post. * * @since 2.5.0 * * @param array $attr Attributes of the shortcode. * @return string HTML content to display gallery. */ function gallery_shortcode($attr) { $post = get_post(); static $instance = 0; $instance++; if ( ! empty( $attr['ids'] ) ) { // 'ids' is explicitly ordered, unless you specify otherwise. if ( empty( $attr['orderby'] ) ) $attr['orderby'] = 'post__in'; $attr['include'] = $attr['ids']; } // Allow plugins/themes to override the default gallery template. $output = apply_filters('post_gallery', '', $attr); if ( $output != '' ) return $output; // We're trusting author input, so let's at least make sure it looks like a valid orderby statement if ( isset( $attr['orderby'] ) ) { $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] ); if ( !$attr['orderby'] ) unset( $attr['orderby'] ); } extract(shortcode_atts(array( 'order' => 'ASC', 'orderby' => 'menu_order ID', 'id' => $post->ID, 'itemtag' => 'dl', 'icontag' => 'dt', 'captiontag' => 'dd', 'columns' => 3, 'size' => 'thumbnail', 'include' => '', 'exclude' => '' ), $attr)); $id = intval($id); if ( 'RAND' == $order ) $orderby = 'none'; if ( !empty($include) ) { $_attachments = get_posts( array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); $attachments = array(); foreach ( $_attachments as $key => $val ) { $attachments[$val->ID] = $_attachments[$key]; } } elseif ( !empty($exclude) ) { $attachments = get_children( array('post_parent' => $id, 'exclude' => $exclude, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); } else { $attachments = get_children( array('post_parent' => $id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby) ); } if ( empty($attachments) ) return ''; if ( is_feed() ) { $output = "\n"; foreach ( $attachments as $att_id => $attachment ) $output .= wp_get_attachment_link($att_id, $size, true) . "\n"; return $output; } $itemtag = tag_escape($itemtag); $captiontag = tag_escape($captiontag); $columns = intval($columns); $itemwidth = $columns > 0 ? floor(100/$columns) : 100; $float = is_rtl() ? 'right' : 'left'; $selector = "gallery-{$instance}"; $gallery_style = $gallery_div = ''; if ( apply_filters( 'use_default_gallery_style', true ) ) $gallery_style = " <style type='text/css'> #{$selector} { margin: auto; } #{$selector} .gallery-item { float: {$float}; margin-top: 10px; text-align: center; width: {$itemwidth}%; } #{$selector} img { border: 2px solid #cfcfcf; } #{$selector} .gallery-caption { margin-left: 0; } </style> <!-- see gallery_shortcode() in wp-includes/media.php -->"; $size_class = sanitize_html_class( $size ); $gallery_div = "<div id='$selector' class='gallery galleryid-{$id} gallery-columns-{$columns} gallery-size-{$size_class}'>"; $output = apply_filters( 'gallery_style', $gallery_style . "\n\t\t" . $gallery_div ); $i = 0; foreach ( $attachments as $id => $attachment ) { $link = isset($attr['link']) && 'file' == $attr['link'] ? wp_get_attachment_link($id, $size, false, false) : wp_get_attachment_link($id, $size, true, false); $output .= "<{$itemtag} class='gallery-item'>"; $output .= " <{$icontag} class='gallery-icon'> $link </{$icontag}>"; if ( $captiontag && trim($attachment->post_excerpt) ) { $output .= " <{$captiontag} class='wp-caption-text gallery-caption'> " . wptexturize($attachment->post_excerpt) . " </{$captiontag}>"; } $output .= "</{$itemtag}>"; if ( $columns > 0 && ++$i % $columns == 0 ) $output .= '<br style="clear: both" />'; } $output .= " <br style='clear: both;' /> </div>\n"; return $output; } /** * Display previous image link that has the same post parent. * * @since 2.5.0 * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text; * @param string $text Optional, default is false. If included, link will reflect $text variable. * @return string HTML content. */ function previous_image_link($size = 'thumbnail', $text = false) { adjacent_image_link(true, $size, $text); } /** * Display next image link that has the same post parent. * * @since 2.5.0 * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. 0 or 'none' will default to post_title or $text; * @param string $text Optional, default is false. If included, link will reflect $text variable. * @return string HTML content. */ function next_image_link($size = 'thumbnail', $text = false) { adjacent_image_link(false, $size, $text); } /** * Display next or previous image link that has the same post parent. * * Retrieves the current attachment object from the $post global. * * @since 2.5.0 * * @param bool $prev Optional. Default is true to display previous link, false for next. */ function adjacent_image_link($prev = true, $size = 'thumbnail', $text = false) { $post = get_post(); $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) ); foreach ( $attachments as $k => $attachment ) if ( $attachment->ID == $post->ID ) break; $k = $prev ? $k - 1 : $k + 1; $output = $attachment_id = null; if ( isset( $attachments[ $k ] ) ) { $attachment_id = $attachments[ $k ]->ID; $output = wp_get_attachment_link( $attachment_id, $size, true, false, $text ); } $adjacent = $prev ? 'previous' : 'next'; echo apply_filters( "{$adjacent}_image_link", $output, $attachment_id, $size, $text ); } /** * Retrieve taxonomies attached to the attachment. * * @since 2.5.0 * * @param int|array|object $attachment Attachment ID, Attachment data array, or Attachment data object. * @return array Empty array on failure. List of taxonomies on success. */ function get_attachment_taxonomies($attachment) { if ( is_int( $attachment ) ) $attachment = get_post($attachment); else if ( is_array($attachment) ) $attachment = (object) $attachment; if ( ! is_object($attachment) ) return array(); $filename = basename($attachment->guid); $objects = array('attachment'); if ( false !== strpos($filename, '.') ) $objects[] = 'attachment:' . substr($filename, strrpos($filename, '.') + 1); if ( !empty($attachment->post_mime_type) ) { $objects[] = 'attachment:' . $attachment->post_mime_type; if ( false !== strpos($attachment->post_mime_type, '/') ) foreach ( explode('/', $attachment->post_mime_type) as $token ) if ( !empty($token) ) $objects[] = "attachment:$token"; } $taxonomies = array(); foreach ( $objects as $object ) if ( $taxes = get_object_taxonomies($object) ) $taxonomies = array_merge($taxonomies, $taxes); return array_unique($taxonomies); } /** * Return all of the taxonomy names that are registered for attachments. * * Handles mime-type-specific taxonomies such as attachment:image and attachment:video. * * @since 3.5.0 * @see get_attachment_taxonomies() * @uses get_taxonomies() * * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default. * @return array The names of all taxonomy of $object_type. */ function get_taxonomies_for_attachments( $output = 'names' ) { $taxonomies = array(); foreach ( get_taxonomies( array(), 'objects' ) as $taxonomy ) { foreach ( $taxonomy->object_type as $object_type ) { if ( 'attachment' == $object_type || 0 === strpos( $object_type, 'attachment:' ) ) { if ( 'names' == $output ) $taxonomies[] = $taxonomy->name; else $taxonomies[ $taxonomy->name ] = $taxonomy; break; } } } return $taxonomies; } /** * Create new GD image resource with transparency support * @TODO: Deprecate if possible. * * @since 2.9.0 * * @param int $width Image width * @param int $height Image height * @return image resource */ function wp_imagecreatetruecolor($width, $height) { $img = imagecreatetruecolor($width, $height); if ( is_resource($img) && function_exists('imagealphablending') && function_exists('imagesavealpha') ) { imagealphablending($img, false); imagesavealpha($img, true); } return $img; } /** * Register an embed handler. This function should probably only be used for sites that do not support oEmbed. * * @since 2.9.0 * @see WP_Embed::register_handler() */ function wp_embed_register_handler( $id, $regex, $callback, $priority = 10 ) { global $wp_embed; $wp_embed->register_handler( $id, $regex, $callback, $priority ); } /** * Unregister a previously registered embed handler. * * @since 2.9.0 * @see WP_Embed::unregister_handler() */ function wp_embed_unregister_handler( $id, $priority = 10 ) { global $wp_embed; $wp_embed->unregister_handler( $id, $priority ); } /** * Create default array of embed parameters. * * The width defaults to the content width as specified by the theme. If the * theme does not specify a content width, then 500px is used. * * The default height is 1.5 times the width, or 1000px, whichever is smaller. * * The 'embed_defaults' filter can be used to adjust either of these values. * * @since 2.9.0 * * @return array Default embed parameters. */ function wp_embed_defaults() { if ( ! empty( $GLOBALS['content_width'] ) ) $width = (int) $GLOBALS['content_width']; if ( empty( $width ) ) $width = 500; $height = min( ceil( $width * 1.5 ), 1000 ); return apply_filters( 'embed_defaults', compact( 'width', 'height' ) ); } /** * Based on a supplied width/height example, return the biggest possible dimensions based on the max width/height. * * @since 2.9.0 * @uses wp_constrain_dimensions() This function passes the widths and the heights. * * @param int $example_width The width of an example embed. * @param int $example_height The height of an example embed. * @param int $max_width The maximum allowed width. * @param int $max_height The maximum allowed height. * @return array The maximum possible width and height based on the example ratio. */ function wp_expand_dimensions( $example_width, $example_height, $max_width, $max_height ) { $example_width = (int) $example_width; $example_height = (int) $example_height; $max_width = (int) $max_width; $max_height = (int) $max_height; return wp_constrain_dimensions( $example_width * 1000000, $example_height * 1000000, $max_width, $max_height ); } /** * Attempts to fetch the embed HTML for a provided URL using oEmbed. * * @since 2.9.0 * @see WP_oEmbed * * @uses _wp_oembed_get_object() * @uses WP_oEmbed::get_html() * * @param string $url The URL that should be embedded. * @param array $args Additional arguments and parameters. * @return bool|string False on failure or the embed HTML on success. */ function wp_oembed_get( $url, $args = '' ) { require_once( ABSPATH . WPINC . '/class-oembed.php' ); $oembed = _wp_oembed_get_object(); return $oembed->get_html( $url, $args ); } /** * Adds a URL format and oEmbed provider URL pair. * * @since 2.9.0 * @see WP_oEmbed * * @uses _wp_oembed_get_object() * * @param string $format The format of URL that this provider can handle. You can use asterisks as wildcards. * @param string $provider The URL to the oEmbed provider. * @param boolean $regex Whether the $format parameter is in a regex format. */ function wp_oembed_add_provider( $format, $provider, $regex = false ) { require_once( ABSPATH . WPINC . '/class-oembed.php' ); $oembed = _wp_oembed_get_object(); $oembed->providers[$format] = array( $provider, $regex ); } /** * Removes an oEmbed provider. * * @since 3.5 * @see WP_oEmbed * * @uses _wp_oembed_get_object() * * @param string $format The URL format for the oEmbed provider to remove. */ function wp_oembed_remove_provider( $format ) { require_once( ABSPATH . WPINC . '/class-oembed.php' ); $oembed = _wp_oembed_get_object(); if ( isset( $oembed->providers[ $format ] ) ) { unset( $oembed->providers[ $format ] ); return true; } return false; } /** * Determines if default embed handlers should be loaded. * * Checks to make sure that the embeds library hasn't already been loaded. If * it hasn't, then it will load the embeds library. * * @since 2.9.0 */ function wp_maybe_load_embeds() { if ( ! apply_filters( 'load_default_embeds', true ) ) return; wp_embed_register_handler( 'googlevideo', '#http://video\.google\.([A-Za-z.]{2,5})/videoplay\?docid=([\d-]+)(.*?)#i', 'wp_embed_handler_googlevideo' ); } /** * The Google Video embed handler callback. Google Video does not support oEmbed. * * @see WP_Embed::register_handler() * @see WP_Embed::shortcode() * * @param array $matches The regex matches from the provided regex when calling {@link wp_embed_register_handler()}. * @param array $attr Embed attributes. * @param string $url The original URL that was matched by the regex. * @param array $rawattr The original unmodified attributes. * @return string The embed HTML. */ function wp_embed_handler_googlevideo( $matches, $attr, $url, $rawattr ) { // If the user supplied a fixed width AND height, use it if ( !empty($rawattr['width']) && !empty($rawattr['height']) ) { $width = (int) $rawattr['width']; $height = (int) $rawattr['height']; } else { list( $width, $height ) = wp_expand_dimensions( 425, 344, $attr['width'], $attr['height'] ); } return apply_filters( 'embed_googlevideo', '<embed type="application/x-shockwave-flash" src="http://video.google.com/googleplayer.swf?docid=' . esc_attr($matches[2]) . '&amp;hl=en&amp;fs=true" style="width:' . esc_attr($width) . 'px;height:' . esc_attr($height) . 'px" allowFullScreen="true" allowScriptAccess="always" />', $matches, $attr, $url, $rawattr ); } /** * {@internal Missing Short Description}} * * @since 2.3.0 * * @param unknown_type $size * @return unknown */ function wp_convert_hr_to_bytes( $size ) { $size = strtolower( $size ); $bytes = (int) $size; if ( strpos( $size, 'k' ) !== false ) $bytes = intval( $size ) * 1024; elseif ( strpos( $size, 'm' ) !== false ) $bytes = intval($size) * 1024 * 1024; elseif ( strpos( $size, 'g' ) !== false ) $bytes = intval( $size ) * 1024 * 1024 * 1024; return $bytes; } /** * {@internal Missing Short Description}} * * @since 2.3.0 * * @param unknown_type $bytes * @return unknown */ function wp_convert_bytes_to_hr( $bytes ) { $units = array( 0 => 'B', 1 => 'kB', 2 => 'MB', 3 => 'GB' ); $log = log( $bytes, 1024 ); $power = (int) $log; $size = pow( 1024, $log - $power ); return $size . $units[$power]; } /** * {@internal Missing Short Description}} * * @since 2.5.0 * * @return unknown */ function wp_max_upload_size() { $u_bytes = wp_convert_hr_to_bytes( ini_get( 'upload_max_filesize' ) ); $p_bytes = wp_convert_hr_to_bytes( ini_get( 'post_max_size' ) ); $bytes = apply_filters( 'upload_size_limit', min( $u_bytes, $p_bytes ), $u_bytes, $p_bytes ); return $bytes; } /** * Returns a WP_Image_Editor instance and loads file into it. * * @since 3.5.0 * @access public * * @param string $path Path to file to load * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} } * @return WP_Image_Editor|WP_Error */ function wp_get_image_editor( $path, $args = array() ) { $args['path'] = $path; if ( ! isset( $args['mime_type'] ) ) { $file_info = wp_check_filetype( $args['path'] ); // If $file_info['type'] is false, then we let the editor attempt to // figure out the file type, rather than forcing a failure based on extension. if ( isset( $file_info ) && $file_info['type'] ) $args['mime_type'] = $file_info['type']; } $implementation = _wp_image_editor_choose( $args ); if ( $implementation ) { $editor = new $implementation( $path ); $loaded = $editor->load(); if ( is_wp_error( $loaded ) ) return $loaded; return $editor; } return new WP_Error( 'image_no_editor', __('No editor could be selected.') ); } /** * Tests whether there is an editor that supports a given mime type or methods. * * @since 3.5.0 * @access public * * @param string|array $args Array of requirements. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} } * @return boolean true if an eligible editor is found; false otherwise */ function wp_image_editor_supports( $args = array() ) { return (bool) _wp_image_editor_choose( $args ); } /** * Tests which editors are capable of supporting the request. * * @since 3.5.0 * @access private * * @param array $args Additional data. Accepts { 'mime_type'=>string, 'methods'=>{string, string, ...} } * @return string|bool Class name for the first editor that claims to support the request. False if no editor claims to support the request. */ function _wp_image_editor_choose( $args = array() ) { require_once ABSPATH . WPINC . '/class-wp-image-editor.php'; require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php'; require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php'; $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) ); foreach ( $implementations as $implementation ) { if ( ! call_user_func( array( $implementation, 'test' ), $args ) ) continue; if ( isset( $args['mime_type'] ) && ! call_user_func( array( $implementation, 'supports_mime_type' ), $args['mime_type'] ) ) { continue; } if ( isset( $args['methods'] ) && array_diff( $args['methods'], get_class_methods( $implementation ) ) ) { continue; } return $implementation; } return false; } /** * Prints default plupload arguments. * * @since 3.4.0 */ function wp_plupload_default_settings() { global $wp_scripts; $data = $wp_scripts->get_data( 'wp-plupload', 'data' ); if ( $data && false !== strpos( $data, '_wpPluploadSettings' ) ) return; $max_upload_size = wp_max_upload_size(); $defaults = array( 'runtimes' => 'html5,silverlight,flash,html4', 'file_data_name' => 'async-upload', // key passed to $_FILE. 'multiple_queues' => true, 'max_file_size' => $max_upload_size . 'b', 'url' => admin_url( 'async-upload.php', 'relative' ), 'flash_swf_url' => includes_url( 'js/plupload/plupload.flash.swf' ), 'silverlight_xap_url' => includes_url( 'js/plupload/plupload.silverlight.xap' ), 'filters' => array( array( 'title' => __( 'Allowed Files' ), 'extensions' => '*') ), 'multipart' => true, 'urlstream_upload' => true, ); // Multi-file uploading doesn't currently work in iOS Safari, // single-file allows the built-in camera to be used as source for images if ( wp_is_mobile() ) $defaults['multi_selection'] = false; $defaults = apply_filters( 'plupload_default_settings', $defaults ); $params = array( 'action' => 'upload-attachment', ); $params = apply_filters( 'plupload_default_params', $params ); $params['_wpnonce'] = wp_create_nonce( 'media-form' ); $defaults['multipart_params'] = $params; $settings = array( 'defaults' => $defaults, 'browser' => array( 'mobile' => wp_is_mobile(), 'supported' => _device_can_upload(), ), 'limitExceeded' => is_multisite() && ! is_upload_space_available() ); $script = 'var _wpPluploadSettings = ' . json_encode( $settings ) . ';'; if ( $data ) $script = "$data\n$script"; $wp_scripts->add_data( 'wp-plupload', 'data', $script ); } add_action( 'customize_controls_enqueue_scripts', 'wp_plupload_default_settings' ); /** * Prepares an attachment post object for JS, where it is expected * to be JSON-encoded and fit into an Attachment model. * * @since 3.5.0 * * @param mixed $attachment Attachment ID or object. * @return array Array of attachment details. */ function wp_prepare_attachment_for_js( $attachment ) { if ( ! $attachment = get_post( $attachment ) ) return; if ( 'attachment' != $attachment->post_type ) return; $meta = wp_get_attachment_metadata( $attachment->ID ); if ( false !== strpos( $attachment->post_mime_type, '/' ) ) list( $type, $subtype ) = explode( '/', $attachment->post_mime_type ); else list( $type, $subtype ) = array( $attachment->post_mime_type, '' ); $attachment_url = wp_get_attachment_url( $attachment->ID ); $response = array( 'id' => $attachment->ID, 'title' => $attachment->post_title, 'filename' => basename( $attachment->guid ), 'url' => $attachment_url, 'link' => get_attachment_link( $attachment->ID ), 'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ), 'author' => $attachment->post_author, 'description' => $attachment->post_content, 'caption' => $attachment->post_excerpt, 'name' => $attachment->post_name, 'status' => $attachment->post_status, 'uploadedTo' => $attachment->post_parent, 'date' => strtotime( $attachment->post_date_gmt ) * 1000, 'modified' => strtotime( $attachment->post_modified_gmt ) * 1000, 'menuOrder' => $attachment->menu_order, 'mime' => $attachment->post_mime_type, 'type' => $type, 'subtype' => $subtype, 'icon' => wp_mime_type_icon( $attachment->ID ), 'dateFormatted' => mysql2date( get_option('date_format'), $attachment->post_date ), 'nonces' => array( 'update' => false, 'delete' => false, ), 'editLink' => false, ); if ( current_user_can( 'edit_post', $attachment->ID ) ) { $response['nonces']['update'] = wp_create_nonce( 'update-post_' . $attachment->ID ); $response['editLink'] = get_edit_post_link( $attachment->ID, 'raw' ); } if ( current_user_can( 'delete_post', $attachment->ID ) ) $response['nonces']['delete'] = wp_create_nonce( 'delete-post_' . $attachment->ID ); if ( $meta && 'image' === $type ) { $sizes = array(); $possible_sizes = apply_filters( 'image_size_names_choose', array( 'thumbnail' => __('Thumbnail'), 'medium' => __('Medium'), 'large' => __('Large'), 'full' => __('Full Size'), ) ); unset( $possible_sizes['full'] ); // Loop through all potential sizes that may be chosen. Try to do this with some efficiency. // First: run the image_downsize filter. If it returns something, we can use its data. // If the filter does not return something, then image_downsize() is just an expensive // way to check the image metadata, which we do second. foreach ( $possible_sizes as $size => $label ) { if ( $downsize = apply_filters( 'image_downsize', false, $attachment->ID, $size ) ) { if ( ! $downsize[3] ) continue; $sizes[ $size ] = array( 'height' => $downsize[2], 'width' => $downsize[1], 'url' => $downsize[0], 'orientation' => $downsize[2] > $downsize[1] ? 'portrait' : 'landscape', ); } elseif ( isset( $meta['sizes'][ $size ] ) ) { if ( ! isset( $base_url ) ) $base_url = str_replace( wp_basename( $attachment_url ), '', $attachment_url ); // Nothing from the filter, so consult image metadata if we have it. $size_meta = $meta['sizes'][ $size ]; // We have the actual image size, but might need to further constrain it if content_width is narrower. // This is not necessary for thumbnails and medium size. if ( 'thumbnail' == $size || 'medium' == $size ) { $width = $size_meta['width']; $height = $size_meta['height']; } else { list( $width, $height ) = image_constrain_size_for_editor( $size_meta['width'], $size_meta['height'], $size, 'edit' ); } $sizes[ $size ] = array( 'height' => $height, 'width' => $width, 'url' => $base_url . $size_meta['file'], 'orientation' => $height > $width ? 'portrait' : 'landscape', ); } } $sizes['full'] = array( 'height' => $meta['height'], 'width' => $meta['width'], 'url' => $attachment_url, 'orientation' => $meta['height'] > $meta['width'] ? 'portrait' : 'landscape', ); $response = array_merge( $response, array( 'sizes' => $sizes ), $sizes['full'] ); } if ( function_exists('get_compat_media_markup') ) $response['compat'] = get_compat_media_markup( $attachment->ID, array( 'in_modal' => true ) ); return apply_filters( 'wp_prepare_attachment_for_js', $response, $attachment, $meta ); } /** * Enqueues all scripts, styles, settings, and templates necessary to use * all media JS APIs. * * @since 3.5.0 */ function wp_enqueue_media( $args = array() ) { $defaults = array( 'post' => null, ); $args = wp_parse_args( $args, $defaults ); // We're going to pass the old thickbox media tabs to `media_upload_tabs` // to ensure plugins will work. We will then unset those tabs. $tabs = array( // handler action suffix => tab label 'type' => '', 'type_url' => '', 'gallery' => '', 'library' => '', ); $tabs = apply_filters( 'media_upload_tabs', $tabs ); unset( $tabs['type'], $tabs['type_url'], $tabs['gallery'], $tabs['library'] ); $settings = array( 'tabs' => $tabs, 'tabUrl' => add_query_arg( array( 'chromeless' => true ), admin_url('media-upload.php') ), 'mimeTypes' => wp_list_pluck( get_post_mime_types(), 0 ), 'captions' => ! apply_filters( 'disable_captions', '' ), 'nonce' => array( 'sendToEditor' => wp_create_nonce( 'media-send-to-editor' ), ), 'post' => array( 'id' => 0, ), ); $post = null; if ( isset( $args['post'] ) ) { $post = get_post( $args['post'] ); $settings['post'] = array( 'id' => $post->ID, 'nonce' => wp_create_nonce( 'update-post_' . $post->ID ), ); if ( current_theme_supports( 'post-thumbnails', $post->post_type ) && post_type_supports( $post->post_type, 'thumbnail' ) ) { $featured_image_id = get_post_meta( $post->ID, '_thumbnail_id', true ); $settings['post']['featuredImageId'] = $featured_image_id ? $featured_image_id : -1; } } $hier = $post && is_post_type_hierarchical( $post->post_type ); $strings = array( // Generic 'url' => __( 'URL' ), 'addMedia' => __( 'Add Media' ), 'search' => __( 'Search' ), 'select' => __( 'Select' ), 'cancel' => __( 'Cancel' ), /* translators: This is a would-be plural string used in the media manager. If there is not a word you can use in your language to avoid issues with the lack of plural support here, turn it into "selected: %d" then translate it. */ 'selected' => __( '%d selected' ), 'dragInfo' => __( 'Drag and drop to reorder images.' ), // Upload 'uploadFilesTitle' => __( 'Upload Files' ), 'uploadImagesTitle' => __( 'Upload Images' ), // Library 'mediaLibraryTitle' => __( 'Media Library' ), 'insertMediaTitle' => __( 'Insert Media' ), 'createNewGallery' => __( 'Create a new gallery' ), 'returnToLibrary' => __( '&#8592; Return to library' ), 'allMediaItems' => __( 'All media items' ), 'noItemsFound' => __( 'No items found.' ), 'insertIntoPost' => $hier ? __( 'Insert into page' ) : __( 'Insert into post' ), 'uploadedToThisPost' => $hier ? __( 'Uploaded to this page' ) : __( 'Uploaded to this post' ), 'warnDelete' => __( "You are about to permanently delete this item.\n 'Cancel' to stop, 'OK' to delete." ), // From URL 'insertFromUrlTitle' => __( 'Insert from URL' ), // Featured Images 'setFeaturedImageTitle' => __( 'Set Featured Image' ), 'setFeaturedImage' => __( 'Set featured image' ), // Gallery 'createGalleryTitle' => __( 'Create Gallery' ), 'editGalleryTitle' => __( 'Edit Gallery' ), 'cancelGalleryTitle' => __( '&#8592; Cancel Gallery' ), 'insertGallery' => __( 'Insert gallery' ), 'updateGallery' => __( 'Update gallery' ), 'addToGallery' => __( 'Add to gallery' ), 'addToGalleryTitle' => __( 'Add to Gallery' ), 'reverseOrder' => __( 'Reverse order' ), ); $settings = apply_filters( 'media_view_settings', $settings, $post ); $strings = apply_filters( 'media_view_strings', $strings, $post ); $strings['settings'] = $settings; wp_localize_script( 'media-views', '_wpMediaViewsL10n', $strings ); wp_enqueue_script( 'media-editor' ); wp_enqueue_style( 'media-views' ); wp_plupload_default_settings(); require_once ABSPATH . WPINC . '/media-template.php'; add_action( 'admin_footer', 'wp_print_media_templates' ); add_action( 'wp_footer', 'wp_print_media_templates' ); do_action( 'wp_enqueue_media' ); }
zyblog
trunk/zyblog/wp-includes/media.php
PHP
asf20
53,747
<?php /** * Defines constants and global variables that can be overridden, generally in wp-config.php. * * @package WordPress */ /** * Defines initial WordPress constants * * @see wp_debug_mode() * * @since 3.0.0 */ function wp_initial_constants( ) { global $blog_id; // set memory limits if ( !defined('WP_MEMORY_LIMIT') ) { if( is_multisite() ) { define('WP_MEMORY_LIMIT', '64M'); } else { define('WP_MEMORY_LIMIT', '40M'); } } if ( ! defined( 'WP_MAX_MEMORY_LIMIT' ) ) { define( 'WP_MAX_MEMORY_LIMIT', '256M' ); } /** * The $blog_id global, which you can change in the config allows you to create a simple * multiple blog installation using just one WordPress and changing $blog_id around. * * @global int $blog_id * @since 2.0.0 */ if ( ! isset($blog_id) ) $blog_id = 1; // set memory limits. if ( function_exists( 'memory_get_usage' ) ) { $current_limit = @ini_get( 'memory_limit' ); if ( -1 != $current_limit && ( -1 == WP_MEMORY_LIMIT || ( intval( $current_limit ) < abs( intval( WP_MEMORY_LIMIT ) ) ) ) ) @ini_set( 'memory_limit', WP_MEMORY_LIMIT ); } if ( !defined('WP_CONTENT_DIR') ) define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' ); // no trailing slash, full paths only - WP_CONTENT_URL is defined further down // Add define('WP_DEBUG', true); to wp-config.php to enable display of notices during development. if ( !defined('WP_DEBUG') ) define( 'WP_DEBUG', false ); // Add define('WP_DEBUG_DISPLAY', null); to wp-config.php use the globally configured setting for // display_errors and not force errors to be displayed. Use false to force display_errors off. if ( !defined('WP_DEBUG_DISPLAY') ) define( 'WP_DEBUG_DISPLAY', true ); // Add define('WP_DEBUG_LOG', true); to enable error logging to wp-content/debug.log. if ( !defined('WP_DEBUG_LOG') ) define('WP_DEBUG_LOG', false); if ( !defined('WP_CACHE') ) define('WP_CACHE', false); /** * Private */ if ( !defined('MEDIA_TRASH') ) define('MEDIA_TRASH', false); if ( !defined('SHORTINIT') ) define('SHORTINIT', false); // Constants for expressing human-readable intervals // in their respective number of seconds. define( 'MINUTE_IN_SECONDS', 60 ); define( 'HOUR_IN_SECONDS', 60 * MINUTE_IN_SECONDS ); define( 'DAY_IN_SECONDS', 24 * HOUR_IN_SECONDS ); define( 'WEEK_IN_SECONDS', 7 * DAY_IN_SECONDS ); define( 'YEAR_IN_SECONDS', 365 * DAY_IN_SECONDS ); } /** * Defines plugin directory WordPress constants * * Defines must-use plugin directory constants, which may be overridden in the sunrise.php drop-in * * @since 3.0.0 */ function wp_plugin_directory_constants( ) { if ( !defined('WP_CONTENT_URL') ) define( 'WP_CONTENT_URL', get_option('siteurl') . '/wp-content'); // full url - WP_CONTENT_DIR is defined further up /** * Allows for the plugins directory to be moved from the default location. * * @since 2.6.0 */ if ( !defined('WP_PLUGIN_DIR') ) define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' ); // full path, no trailing slash /** * Allows for the plugins directory to be moved from the default location. * * @since 2.6.0 */ if ( !defined('WP_PLUGIN_URL') ) define( 'WP_PLUGIN_URL', WP_CONTENT_URL . '/plugins' ); // full url, no trailing slash /** * Allows for the plugins directory to be moved from the default location. * * @since 2.1.0 * @deprecated */ if ( !defined('PLUGINDIR') ) define( 'PLUGINDIR', 'wp-content/plugins' ); // Relative to ABSPATH. For back compat. /** * Allows for the mu-plugins directory to be moved from the default location. * * @since 2.8.0 */ if ( !defined('WPMU_PLUGIN_DIR') ) define( 'WPMU_PLUGIN_DIR', WP_CONTENT_DIR . '/mu-plugins' ); // full path, no trailing slash /** * Allows for the mu-plugins directory to be moved from the default location. * * @since 2.8.0 */ if ( !defined('WPMU_PLUGIN_URL') ) define( 'WPMU_PLUGIN_URL', WP_CONTENT_URL . '/mu-plugins' ); // full url, no trailing slash /** * Allows for the mu-plugins directory to be moved from the default location. * * @since 2.8.0 * @deprecated */ if ( !defined( 'MUPLUGINDIR' ) ) define( 'MUPLUGINDIR', 'wp-content/mu-plugins' ); // Relative to ABSPATH. For back compat. } /** * Defines cookie related WordPress constants * * Defines constants after multisite is loaded. Cookie-related constants may be overridden in ms_network_cookies(). * @since 3.0.0 */ function wp_cookie_constants( ) { /** * Used to guarantee unique hash cookies * @since 1.5 */ if ( !defined( 'COOKIEHASH' ) ) { $siteurl = get_site_option( 'siteurl' ); if ( $siteurl ) define( 'COOKIEHASH', md5( $siteurl ) ); else define( 'COOKIEHASH', '' ); } /** * @since 2.0.0 */ if ( !defined('USER_COOKIE') ) define('USER_COOKIE', 'wordpressuser_' . COOKIEHASH); /** * @since 2.0.0 */ if ( !defined('PASS_COOKIE') ) define('PASS_COOKIE', 'wordpresspass_' . COOKIEHASH); /** * @since 2.5.0 */ if ( !defined('AUTH_COOKIE') ) define('AUTH_COOKIE', 'wordpress_' . COOKIEHASH); /** * @since 2.6.0 */ if ( !defined('SECURE_AUTH_COOKIE') ) define('SECURE_AUTH_COOKIE', 'wordpress_sec_' . COOKIEHASH); /** * @since 2.6.0 */ if ( !defined('LOGGED_IN_COOKIE') ) define('LOGGED_IN_COOKIE', 'wordpress_logged_in_' . COOKIEHASH); /** * @since 2.3.0 */ if ( !defined('TEST_COOKIE') ) define('TEST_COOKIE', 'wordpress_test_cookie'); /** * @since 1.2.0 */ if ( !defined('COOKIEPATH') ) define('COOKIEPATH', preg_replace('|https?://[^/]+|i', '', get_option('home') . '/' ) ); /** * @since 1.5.0 */ if ( !defined('SITECOOKIEPATH') ) define('SITECOOKIEPATH', preg_replace('|https?://[^/]+|i', '', get_option('siteurl') . '/' ) ); /** * @since 2.6.0 */ if ( !defined('ADMIN_COOKIE_PATH') ) define( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin' ); /** * @since 2.6.0 */ if ( !defined('PLUGINS_COOKIE_PATH') ) define( 'PLUGINS_COOKIE_PATH', preg_replace('|https?://[^/]+|i', '', WP_PLUGIN_URL) ); /** * @since 2.0.0 */ if ( !defined('COOKIE_DOMAIN') ) define('COOKIE_DOMAIN', false); } /** * Defines cookie related WordPress constants * * @since 3.0.0 */ function wp_ssl_constants( ) { /** * @since 2.6.0 */ if ( !defined('FORCE_SSL_ADMIN') ) define('FORCE_SSL_ADMIN', false); force_ssl_admin(FORCE_SSL_ADMIN); /** * @since 2.6.0 */ if ( !defined('FORCE_SSL_LOGIN') ) define('FORCE_SSL_LOGIN', false); force_ssl_login(FORCE_SSL_LOGIN); } /** * Defines functionality related WordPress constants * * @since 3.0.0 */ function wp_functionality_constants( ) { /** * @since 2.5.0 */ if ( !defined( 'AUTOSAVE_INTERVAL' ) ) define( 'AUTOSAVE_INTERVAL', 60 ); /** * @since 2.9.0 */ if ( !defined( 'EMPTY_TRASH_DAYS' ) ) define( 'EMPTY_TRASH_DAYS', 30 ); if ( !defined('WP_POST_REVISIONS') ) define('WP_POST_REVISIONS', true); /** * @since 3.3.0 */ if ( !defined( 'WP_CRON_LOCK_TIMEOUT' ) ) define('WP_CRON_LOCK_TIMEOUT', 60); // In seconds } /** * Defines templating related WordPress constants * * @since 3.0.0 */ function wp_templating_constants( ) { /** * Filesystem path to the current active template directory * @since 1.5.0 */ define('TEMPLATEPATH', get_template_directory()); /** * Filesystem path to the current active template stylesheet directory * @since 2.1.0 */ define('STYLESHEETPATH', get_stylesheet_directory()); /** * Slug of the default theme for this install. * Used as the default theme when installing new sites. * Will be used as the fallback if the current theme doesn't exist. * @since 3.0.0 */ if ( !defined('WP_DEFAULT_THEME') ) define( 'WP_DEFAULT_THEME', 'twentytwelve' ); }
zyblog
trunk/zyblog/wp-includes/default-constants.php
PHP
asf20
7,757
<?php /** * BackPress Styles enqueue. * * These classes were refactored from the WordPress WP_Scripts and WordPress * script enqueue API. * * @package BackPress * @since r74 */ /** * BackPress Styles enqueue class. * * @package BackPress * @uses WP_Dependencies * @since r74 */ class WP_Styles extends WP_Dependencies { var $base_url; var $content_url; var $default_version; var $text_direction = 'ltr'; var $concat = ''; var $concat_version = ''; var $do_concat = false; var $print_html = ''; var $print_code = ''; var $default_dirs; function __construct() { do_action_ref_array( 'wp_default_styles', array(&$this) ); } function do_item( $handle ) { if ( !parent::do_item($handle) ) return false; $obj = $this->registered[$handle]; if ( null === $obj->ver ) $ver = ''; else $ver = $obj->ver ? $obj->ver : $this->default_version; if ( isset($this->args[$handle]) ) $ver = $ver ? $ver . '&amp;' . $this->args[$handle] : $this->args[$handle]; if ( $this->do_concat ) { if ( $this->in_default_dir($obj->src) && !isset($obj->extra['conditional']) && !isset($obj->extra['alt']) ) { $this->concat .= "$handle,"; $this->concat_version .= "$handle$ver"; $this->print_code .= $this->get_data( $handle, 'after' ); return true; } } if ( isset($obj->args) ) $media = esc_attr( $obj->args ); else $media = 'all'; $href = $this->_css_href( $obj->src, $ver, $handle ); $rel = isset($obj->extra['alt']) && $obj->extra['alt'] ? 'alternate stylesheet' : 'stylesheet'; $title = isset($obj->extra['title']) ? "title='" . esc_attr( $obj->extra['title'] ) . "'" : ''; $end_cond = $tag = ''; if ( isset($obj->extra['conditional']) && $obj->extra['conditional'] ) { $tag .= "<!--[if {$obj->extra['conditional']}]>\n"; $end_cond = "<![endif]-->\n"; } $tag .= apply_filters( 'style_loader_tag', "<link rel='$rel' id='$handle-css' $title href='$href' type='text/css' media='$media' />\n", $handle ); if ( 'rtl' === $this->text_direction && isset($obj->extra['rtl']) && $obj->extra['rtl'] ) { if ( is_bool( $obj->extra['rtl'] ) ) { $suffix = isset( $obj->extra['suffix'] ) ? $obj->extra['suffix'] : ''; $rtl_href = str_replace( "{$suffix}.css", "-rtl{$suffix}.css", $this->_css_href( $obj->src , $ver, "$handle-rtl" )); } else { $rtl_href = $this->_css_href( $obj->extra['rtl'], $ver, "$handle-rtl" ); } $tag .= apply_filters( 'style_loader_tag', "<link rel='$rel' id='$handle-rtl-css' $title href='$rtl_href' type='text/css' media='$media' />\n", $handle ); } $tag .= $end_cond; if ( $this->do_concat ) { $this->print_html .= $tag; $this->print_html .= $this->print_inline_style( $handle, false ); } else { echo $tag; $this->print_inline_style( $handle ); } return true; } function add_inline_style( $handle, $code ) { if ( !$code ) return false; $after = $this->get_data( $handle, 'after' ); if ( !$after ) $after = array(); $after[] = $code; return $this->add_data( $handle, 'after', $after ); } function print_inline_style( $handle, $echo = true ) { $output = $this->get_data( $handle, 'after' ); if ( empty( $output ) ) return false; $output = implode( "\n", $output ); if ( !$echo ) return $output; echo "<style type='text/css'>\n"; echo "$output\n"; echo "</style>\n"; return true; } function all_deps( $handles, $recursion = false, $group = false ) { $r = parent::all_deps( $handles, $recursion ); if ( !$recursion ) $this->to_do = apply_filters( 'print_styles_array', $this->to_do ); return $r; } function _css_href( $src, $ver, $handle ) { if ( !is_bool($src) && !preg_match('|^(https?:)?//|', $src) && ! ( $this->content_url && 0 === strpos($src, $this->content_url) ) ) { $src = $this->base_url . $src; } if ( !empty($ver) ) $src = add_query_arg('ver', $ver, $src); $src = apply_filters( 'style_loader_src', $src, $handle ); return esc_url( $src ); } function in_default_dir($src) { if ( ! $this->default_dirs ) return true; foreach ( (array) $this->default_dirs as $test ) { if ( 0 === strpos($src, $test) ) return true; } return false; } function do_footer_items() { // HTML 5 allows styles in the body, grab late enqueued items and output them in the footer. $this->do_items(false, 1); return $this->done; } function reset() { $this->do_concat = false; $this->concat = ''; $this->concat_version = ''; $this->print_html = ''; } }
zyblog
trunk/zyblog/wp-includes/class.wp-styles.php
PHP
asf20
4,514
<?php /** * Simple and uniform HTTP request API. * * Standardizes the HTTP requests for WordPress. Handles cookies, gzip encoding and decoding, chunk * decoding, if HTTP 1.1 and various other difficult HTTP protocol implementations. * * @link http://trac.wordpress.org/ticket/4779 HTTP API Proposal * * @package WordPress * @subpackage HTTP * @since 2.7.0 */ /** * WordPress HTTP Class for managing HTTP Transports and making HTTP requests. * * This class is called for the functionality of making HTTP requests and replaces Snoopy * functionality. There is no available functionality to add HTTP transport implementations, since * most of the HTTP transports are added and available for use. * * There are no properties, because none are needed and for performance reasons. Some of the * functions are static and while they do have some overhead over functions in PHP4, the purpose is * maintainability. When PHP5 is finally the requirement, it will be easy to add the static keyword * to the code. It is not as easy to convert a function to a method after enough code uses the old * way. * * Debugging includes several actions, which pass different variables for debugging the HTTP API. * * @package WordPress * @subpackage HTTP * @since 2.7.0 */ class WP_Http { /** * Send a HTTP request to a URI. * * The body and headers are part of the arguments. The 'body' argument is for the body and will * accept either a string or an array. The 'headers' argument should be an array, but a string * is acceptable. If the 'body' argument is an array, then it will automatically be escaped * using http_build_query(). * * The only URI that are supported in the HTTP Transport implementation are the HTTP and HTTPS * protocols. HTTP and HTTPS are assumed so the server might not know how to handle the send * headers. Other protocols are unsupported and most likely will fail. * * The defaults are 'method', 'timeout', 'redirection', 'httpversion', 'blocking' and * 'user-agent'. * * Accepted 'method' values are 'GET', 'POST', and 'HEAD', some transports technically allow * others, but should not be assumed. The 'timeout' is used to sent how long the connection * should stay open before failing when no response. 'redirection' is used to track how many * redirects were taken and used to sent the amount for other transports, but not all transports * accept setting that value. * * The 'httpversion' option is used to sent the HTTP version and accepted values are '1.0', and * '1.1' and should be a string. Version 1.1 is not supported, because of chunk response. The * 'user-agent' option is the user-agent and is used to replace the default user-agent, which is * 'WordPress/WP_Version', where WP_Version is the value from $wp_version. * * 'blocking' is the default, which is used to tell the transport, whether it should halt PHP * while it performs the request or continue regardless. Actually, that isn't entirely correct. * Blocking mode really just means whether the fread should just pull what it can whenever it * gets bytes or if it should wait until it has enough in the buffer to read or finishes reading * the entire content. It doesn't actually always mean that PHP will continue going after making * the request. * * @access public * @since 2.7.0 * @todo Refactor this code. The code in this method extends the scope of its original purpose * and should be refactored to allow for cleaner abstraction and reduce duplication of the * code. One suggestion is to create a class specifically for the arguments, however * preliminary refactoring to this affect has affect more than just the scope of the * arguments. Something to ponder at least. * * @param string $url URI resource. * @param str|array $args Optional. Override the defaults. * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error */ function request( $url, $args = array() ) { global $wp_version; $defaults = array( 'method' => 'GET', 'timeout' => apply_filters( 'http_request_timeout', 5), 'redirection' => apply_filters( 'http_request_redirection_count', 5), 'httpversion' => apply_filters( 'http_request_version', '1.0'), 'user-agent' => apply_filters( 'http_headers_useragent', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ), 'blocking' => true, 'headers' => array(), 'cookies' => array(), 'body' => null, 'compress' => false, 'decompress' => true, 'sslverify' => true, 'stream' => false, 'filename' => null ); // Pre-parse for the HEAD checks. $args = wp_parse_args( $args ); // By default, Head requests do not cause redirections. if ( isset($args['method']) && 'HEAD' == $args['method'] ) $defaults['redirection'] = 0; $r = wp_parse_args( $args, $defaults ); $r = apply_filters( 'http_request_args', $r, $url ); // Certain classes decrement this, store a copy of the original value for loop purposes. $r['_redirection'] = $r['redirection']; // Allow plugins to short-circuit the request $pre = apply_filters( 'pre_http_request', false, $r, $url ); if ( false !== $pre ) return $pre; $arrURL = parse_url( $url ); if ( empty( $url ) || empty( $arrURL['scheme'] ) ) return new WP_Error('http_request_failed', __('A valid URL was not provided.')); if ( $this->block_request( $url ) ) return new WP_Error( 'http_request_failed', __( 'User has blocked requests through HTTP.' ) ); // Determine if this is a https call and pass that on to the transport functions // so that we can blacklist the transports that do not support ssl verification $r['ssl'] = $arrURL['scheme'] == 'https' || $arrURL['scheme'] == 'ssl'; // Determine if this request is to OUR install of WordPress $homeURL = parse_url( get_bloginfo( 'url' ) ); $r['local'] = $homeURL['host'] == $arrURL['host'] || 'localhost' == $arrURL['host']; unset( $homeURL ); // If we are streaming to a file but no filename was given drop it in the WP temp dir // and pick it's name using the basename of the $url if ( $r['stream'] && empty( $r['filename'] ) ) $r['filename'] = get_temp_dir() . basename( $url ); // Force some settings if we are streaming to a file and check for existence and perms of destination directory if ( $r['stream'] ) { $r['blocking'] = true; if ( ! is_writable( dirname( $r['filename'] ) ) ) return new WP_Error( 'http_request_failed', __( 'Destination directory for file streaming does not exist or is not writable.' ) ); } if ( is_null( $r['headers'] ) ) $r['headers'] = array(); if ( ! is_array( $r['headers'] ) ) { $processedHeaders = WP_Http::processHeaders( $r['headers'] ); $r['headers'] = $processedHeaders['headers']; } if ( isset( $r['headers']['User-Agent'] ) ) { $r['user-agent'] = $r['headers']['User-Agent']; unset( $r['headers']['User-Agent'] ); } if ( isset( $r['headers']['user-agent'] ) ) { $r['user-agent'] = $r['headers']['user-agent']; unset( $r['headers']['user-agent'] ); } // Construct Cookie: header if any cookies are set WP_Http::buildCookieHeader( $r ); if ( WP_Http_Encoding::is_available() ) $r['headers']['Accept-Encoding'] = WP_Http_Encoding::accept_encoding(); if ( ( ! is_null( $r['body'] ) && '' != $r['body'] ) || 'POST' == $r['method'] || 'PUT' == $r['method'] ) { if ( is_array( $r['body'] ) || is_object( $r['body'] ) ) { $r['body'] = http_build_query( $r['body'], null, '&' ); if ( ! isset( $r['headers']['Content-Type'] ) ) $r['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=' . get_option( 'blog_charset' ); } if ( '' === $r['body'] ) $r['body'] = null; if ( ! isset( $r['headers']['Content-Length'] ) && ! isset( $r['headers']['content-length'] ) ) $r['headers']['Content-Length'] = strlen( $r['body'] ); } return $this->_dispatch_request($url, $r); } /** * Tests which transports are capable of supporting the request. * * @since 3.2.0 * @access private * * @param array $args Request arguments * @param string $url URL to Request * * @return string|bool Class name for the first transport that claims to support the request. False if no transport claims to support the request. */ public function _get_first_available_transport( $args, $url = null ) { $request_order = array( 'curl', 'streams', 'fsockopen' ); // Loop over each transport on each HTTP request looking for one which will serve this request's needs foreach ( $request_order as $transport ) { $class = 'WP_HTTP_' . $transport; // Check to see if this transport is a possibility, calls the transport statically if ( !call_user_func( array( $class, 'test' ), $args, $url ) ) continue; return $class; } return false; } /** * Dispatches a HTTP request to a supporting transport. * * Tests each transport in order to find a transport which matches the request arguments. * Also caches the transport instance to be used later. * * The order for blocking requests is cURL, Streams, and finally Fsockopen. * The order for non-blocking requests is cURL, Streams and Fsockopen(). * * There are currently issues with "localhost" not resolving correctly with DNS. This may cause * an error "failed to open stream: A connection attempt failed because the connected party did * not properly respond after a period of time, or established connection failed because [the] * connected host has failed to respond." * * @since 3.2.0 * @access private * * @param string $url URL to Request * @param array $args Request arguments * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error */ private function _dispatch_request( $url, $args ) { static $transports = array(); $class = $this->_get_first_available_transport( $args, $url ); if ( !$class ) return new WP_Error( 'http_failure', __( 'There are no HTTP transports available which can complete the requested request.' ) ); // Transport claims to support request, instantiate it and give it a whirl. if ( empty( $transports[$class] ) ) $transports[$class] = new $class; $response = $transports[$class]->request( $url, $args ); do_action( 'http_api_debug', $response, 'response', $class, $args, $url ); if ( is_wp_error( $response ) ) return $response; return apply_filters( 'http_response', $response, $args, $url ); } /** * Uses the POST HTTP method. * * Used for sending data that is expected to be in the body. * * @access public * @since 2.7.0 * * @param string $url URI resource. * @param str|array $args Optional. Override the defaults. * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error */ function post($url, $args = array()) { $defaults = array('method' => 'POST'); $r = wp_parse_args( $args, $defaults ); return $this->request($url, $r); } /** * Uses the GET HTTP method. * * Used for sending data that is expected to be in the body. * * @access public * @since 2.7.0 * * @param string $url URI resource. * @param str|array $args Optional. Override the defaults. * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error */ function get($url, $args = array()) { $defaults = array('method' => 'GET'); $r = wp_parse_args( $args, $defaults ); return $this->request($url, $r); } /** * Uses the HEAD HTTP method. * * Used for sending data that is expected to be in the body. * * @access public * @since 2.7.0 * * @param string $url URI resource. * @param str|array $args Optional. Override the defaults. * @return array|object Array containing 'headers', 'body', 'response', 'cookies', 'filename'. A WP_Error instance upon error */ function head($url, $args = array()) { $defaults = array('method' => 'HEAD'); $r = wp_parse_args( $args, $defaults ); return $this->request($url, $r); } /** * Parses the responses and splits the parts into headers and body. * * @access public * @static * @since 2.7.0 * * @param string $strResponse The full response string * @return array Array with 'headers' and 'body' keys. */ function processResponse($strResponse) { $res = explode("\r\n\r\n", $strResponse, 2); return array('headers' => $res[0], 'body' => isset($res[1]) ? $res[1] : ''); } /** * Transform header string into an array. * * If an array is given then it is assumed to be raw header data with numeric keys with the * headers as the values. No headers must be passed that were already processed. * * @access public * @static * @since 2.7.0 * * @param string|array $headers * @return array Processed string headers. If duplicate headers are encountered, * Then a numbered array is returned as the value of that header-key. */ public static function processHeaders($headers) { // split headers, one per array element if ( is_string($headers) ) { // tolerate line terminator: CRLF = LF (RFC 2616 19.3) $headers = str_replace("\r\n", "\n", $headers); // unfold folded header fields. LWS = [CRLF] 1*( SP | HT ) <US-ASCII SP, space (32)>, <US-ASCII HT, horizontal-tab (9)> (RFC 2616 2.2) $headers = preg_replace('/\n[ \t]/', ' ', $headers); // create the headers array $headers = explode("\n", $headers); } $response = array('code' => 0, 'message' => ''); // If a redirection has taken place, The headers for each page request may have been passed. // In this case, determine the final HTTP header and parse from there. for ( $i = count($headers)-1; $i >= 0; $i-- ) { if ( !empty($headers[$i]) && false === strpos($headers[$i], ':') ) { $headers = array_splice($headers, $i); break; } } $cookies = array(); $newheaders = array(); foreach ( (array) $headers as $tempheader ) { if ( empty($tempheader) ) continue; if ( false === strpos($tempheader, ':') ) { $stack = explode(' ', $tempheader, 3); $stack[] = ''; list( , $response['code'], $response['message']) = $stack; continue; } list($key, $value) = explode(':', $tempheader, 2); $key = strtolower( $key ); $value = trim( $value ); if ( isset( $newheaders[ $key ] ) ) { if ( ! is_array( $newheaders[ $key ] ) ) $newheaders[$key] = array( $newheaders[ $key ] ); $newheaders[ $key ][] = $value; } else { $newheaders[ $key ] = $value; } if ( 'set-cookie' == $key ) $cookies[] = new WP_Http_Cookie( $value ); } return array('response' => $response, 'headers' => $newheaders, 'cookies' => $cookies); } /** * Takes the arguments for a ::request() and checks for the cookie array. * * If it's found, then it's assumed to contain WP_Http_Cookie objects, which are each parsed * into strings and added to the Cookie: header (within the arguments array). Edits the array by * reference. * * @access public * @version 2.8.0 * @static * * @param array $r Full array of args passed into ::request() */ public static function buildCookieHeader( &$r ) { if ( ! empty($r['cookies']) ) { $cookies_header = ''; foreach ( (array) $r['cookies'] as $cookie ) { $cookies_header .= $cookie->getHeaderValue() . '; '; } $cookies_header = substr( $cookies_header, 0, -2 ); $r['headers']['cookie'] = $cookies_header; } } /** * Decodes chunk transfer-encoding, based off the HTTP 1.1 specification. * * Based off the HTTP http_encoding_dechunk function. Does not support UTF-8. Does not support * returning footer headers. Shouldn't be too difficult to support it though. * * @link http://tools.ietf.org/html/rfc2616#section-19.4.6 Process for chunked decoding. * * @todo Add support for footer chunked headers. * @access public * @since 2.7.0 * @static * * @param string $body Body content * @return string Chunked decoded body on success or raw body on failure. */ function chunkTransferDecode($body) { $body = str_replace(array("\r\n", "\r"), "\n", $body); // The body is not chunked encoding or is malformed. if ( ! preg_match( '/^[0-9a-f]+(\s|\n)+/mi', trim($body) ) ) return $body; $parsedBody = ''; //$parsedHeaders = array(); Unsupported while ( true ) { $hasChunk = (bool) preg_match( '/^([0-9a-f]+)(\s|\n)+/mi', $body, $match ); if ( $hasChunk ) { if ( empty( $match[1] ) ) return $body; $length = hexdec( $match[1] ); $chunkLength = strlen( $match[0] ); $strBody = substr($body, $chunkLength, $length); $parsedBody .= $strBody; $body = ltrim(str_replace(array($match[0], $strBody), '', $body), "\n"); if ( "0" == trim($body) ) return $parsedBody; // Ignore footer headers. } else { return $body; } } } /** * Block requests through the proxy. * * Those who are behind a proxy and want to prevent access to certain hosts may do so. This will * prevent plugins from working and core functionality, if you don't include api.wordpress.org. * * You block external URL requests by defining WP_HTTP_BLOCK_EXTERNAL as true in your wp-config.php * file and this will only allow localhost and your blog to make requests. The constant * WP_ACCESSIBLE_HOSTS will allow additional hosts to go through for requests. The format of the * WP_ACCESSIBLE_HOSTS constant is a comma separated list of hostnames to allow, wildcard domains * are supported, eg *.wordpress.org will allow for all subdomains of wordpress.org to be contacted. * * @since 2.8.0 * @link http://core.trac.wordpress.org/ticket/8927 Allow preventing external requests. * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_ACCESSIBLE_HOSTS * * @param string $uri URI of url. * @return bool True to block, false to allow. */ function block_request($uri) { // We don't need to block requests, because nothing is blocked. if ( ! defined( 'WP_HTTP_BLOCK_EXTERNAL' ) || ! WP_HTTP_BLOCK_EXTERNAL ) return false; // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure. // This will be displayed on blogs, which is not reasonable. $check = @parse_url($uri); /* Malformed URL, can not process, but this could mean ssl, so let through anyway. * * This isn't very security sound. There are instances where a hacker might attempt * to bypass the proxy and this check. However, the reason for this behavior is that * WordPress does not do any checking currently for non-proxy requests, so it is keeps with * the default unsecure nature of the HTTP request. */ if ( $check === false ) return false; $home = parse_url( get_option('siteurl') ); // Don't block requests back to ourselves by default if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] ) return apply_filters('block_local_requests', false); if ( !defined('WP_ACCESSIBLE_HOSTS') ) return true; static $accessible_hosts; static $wildcard_regex = false; if ( null == $accessible_hosts ) { $accessible_hosts = preg_split('|,\s*|', WP_ACCESSIBLE_HOSTS); if ( false !== strpos(WP_ACCESSIBLE_HOSTS, '*') ) { $wildcard_regex = array(); foreach ( $accessible_hosts as $host ) $wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/')); $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i'; } } if ( !empty($wildcard_regex) ) return !preg_match($wildcard_regex, $check['host']); else return !in_array( $check['host'], $accessible_hosts ); //Inverse logic, If its in the array, then we can't access it. } static function make_absolute_url( $maybe_relative_path, $url ) { if ( empty( $url ) ) return $maybe_relative_path; // Check for a scheme if ( false !== strpos( $maybe_relative_path, '://' ) ) return $maybe_relative_path; if ( ! $url_parts = @parse_url( $url ) ) return $maybe_relative_path; if ( ! $relative_url_parts = @parse_url( $maybe_relative_path ) ) return $maybe_relative_path; $absolute_path = $url_parts['scheme'] . '://' . $url_parts['host']; if ( isset( $url_parts['port'] ) ) $absolute_path .= ':' . $url_parts['port']; // Start off with the Absolute URL path $path = ! empty( $url_parts['path'] ) ? $url_parts['path'] : '/'; // If the it's a root-relative path, then great if ( ! empty( $relative_url_parts['path'] ) && '/' == $relative_url_parts['path'][0] ) { $path = $relative_url_parts['path']; // Else it's a relative path } elseif ( ! empty( $relative_url_parts['path'] ) ) { // Strip off any file components from the absolute path $path = substr( $path, 0, strrpos( $path, '/' ) + 1 ); // Build the new path $path .= $relative_url_parts['path']; // Strip all /path/../ out of the path while ( strpos( $path, '../' ) > 1 ) { $path = preg_replace( '![^/]+/\.\./!', '', $path ); } // Strip any final leading ../ from the path $path = preg_replace( '!^/(\.\./)+!', '', $path ); } // Add the Query string if ( ! empty( $relative_url_parts['query'] ) ) $path .= '?' . $relative_url_parts['query']; return $absolute_path . '/' . ltrim( $path, '/' ); } } /** * HTTP request method uses fsockopen function to retrieve the url. * * This would be the preferred method, but the fsockopen implementation has the most overhead of all * the HTTP transport implementations. * * @package WordPress * @subpackage HTTP * @since 2.7.0 */ class WP_Http_Fsockopen { /** * Send a HTTP request to a URI using fsockopen(). * * Does not support non-blocking mode. * * @see WP_Http::request For default options descriptions. * * @since 2.7 * @access public * @param string $url URI resource. * @param str|array $args Optional. Override the defaults. * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys. */ function request($url, $args = array()) { $defaults = array( 'method' => 'GET', 'timeout' => 5, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => null, 'cookies' => array() ); $r = wp_parse_args( $args, $defaults ); if ( isset($r['headers']['User-Agent']) ) { $r['user-agent'] = $r['headers']['User-Agent']; unset($r['headers']['User-Agent']); } else if ( isset($r['headers']['user-agent']) ) { $r['user-agent'] = $r['headers']['user-agent']; unset($r['headers']['user-agent']); } // Construct Cookie: header if any cookies are set WP_Http::buildCookieHeader( $r ); $iError = null; // Store error number $strError = null; // Store error string $arrURL = parse_url($url); $fsockopen_host = $arrURL['host']; $secure_transport = false; if ( ! isset( $arrURL['port'] ) ) { if ( ( $arrURL['scheme'] == 'ssl' || $arrURL['scheme'] == 'https' ) && extension_loaded('openssl') ) { $fsockopen_host = "ssl://$fsockopen_host"; $arrURL['port'] = 443; $secure_transport = true; } else { $arrURL['port'] = 80; } } //fsockopen has issues with 'localhost' with IPv6 with certain versions of PHP, It attempts to connect to ::1, // which fails when the server is not set up for it. For compatibility, always connect to the IPv4 address. if ( 'localhost' == strtolower($fsockopen_host) ) $fsockopen_host = '127.0.0.1'; // There are issues with the HTTPS and SSL protocols that cause errors that can be safely // ignored and should be ignored. if ( true === $secure_transport ) $error_reporting = error_reporting(0); $startDelay = time(); $proxy = new WP_HTTP_Proxy(); if ( !WP_DEBUG ) { if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) $handle = @fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] ); else $handle = @fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] ); } else { if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) $handle = fsockopen( $proxy->host(), $proxy->port(), $iError, $strError, $r['timeout'] ); else $handle = fsockopen( $fsockopen_host, $arrURL['port'], $iError, $strError, $r['timeout'] ); } $endDelay = time(); // If the delay is greater than the timeout then fsockopen shouldn't be used, because it will // cause a long delay. $elapseDelay = ($endDelay-$startDelay) > $r['timeout']; if ( true === $elapseDelay ) add_option( 'disable_fsockopen', $endDelay, null, true ); if ( false === $handle ) return new WP_Error('http_request_failed', $iError . ': ' . $strError); $timeout = (int) floor( $r['timeout'] ); $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000; stream_set_timeout( $handle, $timeout, $utimeout ); if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) //Some proxies require full URL in this field. $requestPath = $url; else $requestPath = $arrURL['path'] . ( isset($arrURL['query']) ? '?' . $arrURL['query'] : '' ); if ( empty($requestPath) ) $requestPath .= '/'; $strHeaders = strtoupper($r['method']) . ' ' . $requestPath . ' HTTP/' . $r['httpversion'] . "\r\n"; if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) $strHeaders .= 'Host: ' . $arrURL['host'] . ':' . $arrURL['port'] . "\r\n"; else $strHeaders .= 'Host: ' . $arrURL['host'] . "\r\n"; if ( isset($r['user-agent']) ) $strHeaders .= 'User-agent: ' . $r['user-agent'] . "\r\n"; if ( is_array($r['headers']) ) { foreach ( (array) $r['headers'] as $header => $headerValue ) $strHeaders .= $header . ': ' . $headerValue . "\r\n"; } else { $strHeaders .= $r['headers']; } if ( $proxy->use_authentication() ) $strHeaders .= $proxy->authentication_header() . "\r\n"; $strHeaders .= "\r\n"; if ( ! is_null($r['body']) ) $strHeaders .= $r['body']; fwrite($handle, $strHeaders); if ( ! $r['blocking'] ) { fclose($handle); return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); } $strResponse = ''; $bodyStarted = false; // If streaming to a file setup the file handle if ( $r['stream'] ) { if ( ! WP_DEBUG ) $stream_handle = @fopen( $r['filename'], 'w+' ); else $stream_handle = fopen( $r['filename'], 'w+' ); if ( ! $stream_handle ) return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) ); while ( ! feof($handle) ) { $block = fread( $handle, 4096 ); if ( $bodyStarted ) { fwrite( $stream_handle, $block ); } else { $strResponse .= $block; if ( strpos( $strResponse, "\r\n\r\n" ) ) { $process = WP_Http::processResponse( $strResponse ); $bodyStarted = true; fwrite( $stream_handle, $process['body'] ); unset( $strResponse ); $process['body'] = ''; } } } fclose( $stream_handle ); } else { while ( ! feof($handle) ) $strResponse .= fread( $handle, 4096 ); $process = WP_Http::processResponse( $strResponse ); unset( $strResponse ); } fclose( $handle ); if ( true === $secure_transport ) error_reporting($error_reporting); $arrHeaders = WP_Http::processHeaders( $process['headers'] ); // If location is found, then assume redirect and redirect to location. if ( isset($arrHeaders['headers']['location']) && 0 !== $r['_redirection'] ) { if ( $r['redirection']-- > 0 ) { return $this->request( WP_HTTP::make_absolute_url( $arrHeaders['headers']['location'], $url ), $r); } else { return new WP_Error('http_request_failed', __('Too many redirects.')); } } // If the body was chunk encoded, then decode it. if ( ! empty( $process['body'] ) && isset( $arrHeaders['headers']['transfer-encoding'] ) && 'chunked' == $arrHeaders['headers']['transfer-encoding'] ) $process['body'] = WP_Http::chunkTransferDecode($process['body']); if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($arrHeaders['headers']) ) $process['body'] = WP_Http_Encoding::decompress( $process['body'] ); return array( 'headers' => $arrHeaders['headers'], 'body' => $process['body'], 'response' => $arrHeaders['response'], 'cookies' => $arrHeaders['cookies'], 'filename' => $r['filename'] ); } /** * Whether this class can be used for retrieving an URL. * * @since 2.7.0 * @static * @return boolean False means this class can not be used, true means it can. */ public static function test( $args = array() ) { if ( ! function_exists( 'fsockopen' ) ) return false; if ( false !== ( $option = get_option( 'disable_fsockopen' ) ) && time() - $option < 12 * HOUR_IN_SECONDS ) return false; $is_ssl = isset( $args['ssl'] ) && $args['ssl']; if ( $is_ssl && ! extension_loaded( 'openssl' ) ) return false; return apply_filters( 'use_fsockopen_transport', true, $args ); } } /** * HTTP request method uses Streams to retrieve the url. * * Requires PHP 5.0+ and uses fopen with stream context. Requires that 'allow_url_fopen' PHP setting * to be enabled. * * Second preferred method for getting the URL, for PHP 5. * * @package WordPress * @subpackage HTTP * @since 2.7.0 */ class WP_Http_Streams { /** * Send a HTTP request to a URI using streams with fopen(). * * @access public * @since 2.7.0 * * @param string $url * @param str|array $args Optional. Override the defaults. * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys. */ function request($url, $args = array()) { $defaults = array( 'method' => 'GET', 'timeout' => 5, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => null, 'cookies' => array() ); $r = wp_parse_args( $args, $defaults ); if ( isset($r['headers']['User-Agent']) ) { $r['user-agent'] = $r['headers']['User-Agent']; unset($r['headers']['User-Agent']); } else if ( isset($r['headers']['user-agent']) ) { $r['user-agent'] = $r['headers']['user-agent']; unset($r['headers']['user-agent']); } // Construct Cookie: header if any cookies are set WP_Http::buildCookieHeader( $r ); $arrURL = parse_url($url); if ( false === $arrURL ) return new WP_Error('http_request_failed', sprintf(__('Malformed URL: %s'), $url)); if ( 'http' != $arrURL['scheme'] && 'https' != $arrURL['scheme'] ) $url = preg_replace('|^' . preg_quote($arrURL['scheme'], '|') . '|', 'http', $url); // Convert Header array to string. $strHeaders = ''; if ( is_array( $r['headers'] ) ) foreach ( $r['headers'] as $name => $value ) $strHeaders .= "{$name}: $value\r\n"; else if ( is_string( $r['headers'] ) ) $strHeaders = $r['headers']; $is_local = isset($args['local']) && $args['local']; $ssl_verify = isset($args['sslverify']) && $args['sslverify']; if ( $is_local ) $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify); elseif ( ! $is_local ) $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify); $arrContext = array('http' => array( 'method' => strtoupper($r['method']), 'user_agent' => $r['user-agent'], 'max_redirects' => $r['redirection'] + 1, // See #11557 'protocol_version' => (float) $r['httpversion'], 'header' => $strHeaders, 'ignore_errors' => true, // Return non-200 requests. 'timeout' => $r['timeout'], 'ssl' => array( 'verify_peer' => $ssl_verify, 'verify_host' => $ssl_verify ) ) ); $proxy = new WP_HTTP_Proxy(); if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { $arrContext['http']['proxy'] = 'tcp://' . $proxy->host() . ':' . $proxy->port(); $arrContext['http']['request_fulluri'] = true; // We only support Basic authentication so this will only work if that is what your proxy supports. if ( $proxy->use_authentication() ) $arrContext['http']['header'] .= $proxy->authentication_header() . "\r\n"; } if ( ! is_null( $r['body'] ) ) $arrContext['http']['content'] = $r['body']; $context = stream_context_create($arrContext); if ( !WP_DEBUG ) $handle = @fopen($url, 'r', false, $context); else $handle = fopen($url, 'r', false, $context); if ( ! $handle ) return new WP_Error('http_request_failed', sprintf(__('Could not open handle for fopen() to %s'), $url)); $timeout = (int) floor( $r['timeout'] ); $utimeout = $timeout == $r['timeout'] ? 0 : 1000000 * $r['timeout'] % 1000000; stream_set_timeout( $handle, $timeout, $utimeout ); if ( ! $r['blocking'] ) { stream_set_blocking($handle, 0); fclose($handle); return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); } if ( $r['stream'] ) { if ( ! WP_DEBUG ) $stream_handle = @fopen( $r['filename'], 'w+' ); else $stream_handle = fopen( $r['filename'], 'w+' ); if ( ! $stream_handle ) return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) ); stream_copy_to_stream( $handle, $stream_handle ); fclose( $stream_handle ); $strResponse = ''; } else { $strResponse = stream_get_contents( $handle ); } $meta = stream_get_meta_data( $handle ); fclose( $handle ); $processedHeaders = array(); if ( isset( $meta['wrapper_data']['headers'] ) ) $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']['headers']); else $processedHeaders = WP_Http::processHeaders($meta['wrapper_data']); // Streams does not provide an error code which we can use to see why the request stream stopped. // We can however test to see if a location header is present and return based on that. if ( isset($processedHeaders['headers']['location']) && 0 !== $args['_redirection'] ) return new WP_Error('http_request_failed', __('Too many redirects.')); if ( ! empty( $strResponse ) && isset( $processedHeaders['headers']['transfer-encoding'] ) && 'chunked' == $processedHeaders['headers']['transfer-encoding'] ) $strResponse = WP_Http::chunkTransferDecode($strResponse); if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($processedHeaders['headers']) ) $strResponse = WP_Http_Encoding::decompress( $strResponse ); return array( 'headers' => $processedHeaders['headers'], 'body' => $strResponse, 'response' => $processedHeaders['response'], 'cookies' => $processedHeaders['cookies'], 'filename' => $r['filename'] ); } /** * Whether this class can be used for retrieving an URL. * * @static * @access public * @since 2.7.0 * * @return boolean False means this class can not be used, true means it can. */ public static function test( $args = array() ) { if ( ! function_exists( 'fopen' ) ) return false; if ( ! function_exists( 'ini_get' ) || true != ini_get( 'allow_url_fopen' ) ) return false; $is_ssl = isset( $args['ssl'] ) && $args['ssl']; if ( $is_ssl && ! extension_loaded( 'openssl' ) ) return false; return apply_filters( 'use_streams_transport', true, $args ); } } /** * HTTP request method uses Curl extension to retrieve the url. * * Requires the Curl extension to be installed. * * @package WordPress * @subpackage HTTP * @since 2.7 */ class WP_Http_Curl { /** * Temporary header storage for use with streaming to a file. * * @since 3.2.0 * @access private * @var string */ private $headers = ''; /** * Send a HTTP request to a URI using cURL extension. * * @access public * @since 2.7.0 * * @param string $url * @param str|array $args Optional. Override the defaults. * @return array 'headers', 'body', 'response', 'cookies' and 'filename' keys. */ function request($url, $args = array()) { $defaults = array( 'method' => 'GET', 'timeout' => 5, 'redirection' => 5, 'httpversion' => '1.0', 'blocking' => true, 'headers' => array(), 'body' => null, 'cookies' => array() ); $r = wp_parse_args( $args, $defaults ); if ( isset($r['headers']['User-Agent']) ) { $r['user-agent'] = $r['headers']['User-Agent']; unset($r['headers']['User-Agent']); } else if ( isset($r['headers']['user-agent']) ) { $r['user-agent'] = $r['headers']['user-agent']; unset($r['headers']['user-agent']); } // Construct Cookie: header if any cookies are set. WP_Http::buildCookieHeader( $r ); $handle = curl_init(); // cURL offers really easy proxy support. $proxy = new WP_HTTP_Proxy(); if ( $proxy->is_enabled() && $proxy->send_through_proxy( $url ) ) { curl_setopt( $handle, CURLOPT_PROXYTYPE, CURLPROXY_HTTP ); curl_setopt( $handle, CURLOPT_PROXY, $proxy->host() ); curl_setopt( $handle, CURLOPT_PROXYPORT, $proxy->port() ); if ( $proxy->use_authentication() ) { curl_setopt( $handle, CURLOPT_PROXYAUTH, CURLAUTH_ANY ); curl_setopt( $handle, CURLOPT_PROXYUSERPWD, $proxy->authentication() ); } } $is_local = isset($r['local']) && $r['local']; $ssl_verify = isset($r['sslverify']) && $r['sslverify']; if ( $is_local ) $ssl_verify = apply_filters('https_local_ssl_verify', $ssl_verify); elseif ( ! $is_local ) $ssl_verify = apply_filters('https_ssl_verify', $ssl_verify); // CURLOPT_TIMEOUT and CURLOPT_CONNECTTIMEOUT expect integers. Have to use ceil since // a value of 0 will allow an unlimited timeout. $timeout = (int) ceil( $r['timeout'] ); curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt( $handle, CURLOPT_TIMEOUT, $timeout ); curl_setopt( $handle, CURLOPT_URL, $url); curl_setopt( $handle, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $handle, CURLOPT_SSL_VERIFYHOST, ( $ssl_verify === true ) ? 2 : false ); curl_setopt( $handle, CURLOPT_SSL_VERIFYPEER, $ssl_verify ); curl_setopt( $handle, CURLOPT_USERAGENT, $r['user-agent'] ); // The option doesn't work with safe mode or when open_basedir is set, and there's a // bug #17490 with redirected POST requests, so handle redirections outside Curl. curl_setopt( $handle, CURLOPT_FOLLOWLOCATION, false ); switch ( $r['method'] ) { case 'HEAD': curl_setopt( $handle, CURLOPT_NOBODY, true ); break; case 'POST': curl_setopt( $handle, CURLOPT_POST, true ); curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] ); break; case 'PUT': curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, 'PUT' ); curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] ); break; default: curl_setopt( $handle, CURLOPT_CUSTOMREQUEST, $r['method'] ); if ( ! is_null( $r['body'] ) ) curl_setopt( $handle, CURLOPT_POSTFIELDS, $r['body'] ); break; } if ( true === $r['blocking'] ) curl_setopt( $handle, CURLOPT_HEADERFUNCTION, array( $this, 'stream_headers' ) ); curl_setopt( $handle, CURLOPT_HEADER, false ); // If streaming to a file open a file handle, and setup our curl streaming handler if ( $r['stream'] ) { if ( ! WP_DEBUG ) $stream_handle = @fopen( $r['filename'], 'w+' ); else $stream_handle = fopen( $r['filename'], 'w+' ); if ( ! $stream_handle ) return new WP_Error( 'http_request_failed', sprintf( __( 'Could not open handle for fopen() to %s' ), $r['filename'] ) ); curl_setopt( $handle, CURLOPT_FILE, $stream_handle ); } if ( !empty( $r['headers'] ) ) { // cURL expects full header strings in each element $headers = array(); foreach ( $r['headers'] as $name => $value ) { $headers[] = "{$name}: $value"; } curl_setopt( $handle, CURLOPT_HTTPHEADER, $headers ); } if ( $r['httpversion'] == '1.0' ) curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0 ); else curl_setopt( $handle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1 ); // Cookies are not handled by the HTTP API currently. Allow for plugin authors to handle it // themselves... Although, it is somewhat pointless without some reference. do_action_ref_array( 'http_api_curl', array(&$handle) ); // We don't need to return the body, so don't. Just execute request and return. if ( ! $r['blocking'] ) { curl_exec( $handle ); curl_close( $handle ); return array( 'headers' => array(), 'body' => '', 'response' => array('code' => false, 'message' => false), 'cookies' => array() ); } $theResponse = curl_exec( $handle ); $theBody = ''; $theHeaders = WP_Http::processHeaders( $this->headers ); if ( strlen($theResponse) > 0 && ! is_bool( $theResponse ) ) // is_bool: when using $args['stream'], curl_exec will return (bool)true $theBody = $theResponse; // If no response if ( 0 == strlen( $theResponse ) && empty( $theHeaders['headers'] ) ) { if ( $curl_error = curl_error( $handle ) ) return new WP_Error( 'http_request_failed', $curl_error ); if ( in_array( curl_getinfo( $handle, CURLINFO_HTTP_CODE ), array( 301, 302 ) ) ) return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) ); } $this->headers = ''; $response = array(); $response['code'] = curl_getinfo( $handle, CURLINFO_HTTP_CODE ); $response['message'] = get_status_header_desc($response['code']); curl_close( $handle ); if ( $r['stream'] ) fclose( $stream_handle ); // See #11305 - When running under safe mode, redirection is disabled above. Handle it manually. if ( ! empty( $theHeaders['headers']['location'] ) && 0 !== $r['_redirection'] ) { // _redirection: The requested number of redirections if ( $r['redirection']-- > 0 ) { return $this->request( WP_HTTP::make_absolute_url( $theHeaders['headers']['location'], $url ), $r ); } else { return new WP_Error( 'http_request_failed', __( 'Too many redirects.' ) ); } } if ( true === $r['decompress'] && true === WP_Http_Encoding::should_decode($theHeaders['headers']) ) $theBody = WP_Http_Encoding::decompress( $theBody ); return array( 'headers' => $theHeaders['headers'], 'body' => $theBody, 'response' => $response, 'cookies' => $theHeaders['cookies'], 'filename' => $r['filename'] ); } /** * Grab the headers of the cURL request * * Each header is sent individually to this callback, so we append to the $header property for temporary storage * * @since 3.2.0 * @access private * @return int */ private function stream_headers( $handle, $headers ) { $this->headers .= $headers; return strlen( $headers ); } /** * Whether this class can be used for retrieving an URL. * * @static * @since 2.7.0 * * @return boolean False means this class can not be used, true means it can. */ public static function test( $args = array() ) { if ( ! function_exists( 'curl_init' ) || ! function_exists( 'curl_exec' ) ) return false; $is_ssl = isset( $args['ssl'] ) && $args['ssl']; if ( $is_ssl ) { $curl_version = curl_version(); if ( ! (CURL_VERSION_SSL & $curl_version['features']) ) // Does this cURL version support SSL requests? return false; } return apply_filters( 'use_curl_transport', true, $args ); } } /** * Adds Proxy support to the WordPress HTTP API. * * There are caveats to proxy support. It requires that defines be made in the wp-config.php file to * enable proxy support. There are also a few filters that plugins can hook into for some of the * constants. * * Please note that only BASIC authentication is supported by most transports. * cURL MAY support more methods (such as NTLM authentication) depending on your environment. * * The constants are as follows: * <ol> * <li>WP_PROXY_HOST - Enable proxy support and host for connecting.</li> * <li>WP_PROXY_PORT - Proxy port for connection. No default, must be defined.</li> * <li>WP_PROXY_USERNAME - Proxy username, if it requires authentication.</li> * <li>WP_PROXY_PASSWORD - Proxy password, if it requires authentication.</li> * <li>WP_PROXY_BYPASS_HOSTS - Will prevent the hosts in this list from going through the proxy. * You do not need to have localhost and the blog host in this list, because they will not be passed * through the proxy. The list should be presented in a comma separated list, wildcards using * are supported, eg. *.wordpress.org</li> * </ol> * * An example can be as seen below. * <code> * define('WP_PROXY_HOST', '192.168.84.101'); * define('WP_PROXY_PORT', '8080'); * define('WP_PROXY_BYPASS_HOSTS', 'localhost, www.example.com, *.wordpress.org'); * </code> * * @link http://core.trac.wordpress.org/ticket/4011 Proxy support ticket in WordPress. * @link http://core.trac.wordpress.org/ticket/14636 Allow wildcard domains in WP_PROXY_BYPASS_HOSTS * @since 2.8 */ class WP_HTTP_Proxy { /** * Whether proxy connection should be used. * * @since 2.8 * @use WP_PROXY_HOST * @use WP_PROXY_PORT * * @return bool */ function is_enabled() { return defined('WP_PROXY_HOST') && defined('WP_PROXY_PORT'); } /** * Whether authentication should be used. * * @since 2.8 * @use WP_PROXY_USERNAME * @use WP_PROXY_PASSWORD * * @return bool */ function use_authentication() { return defined('WP_PROXY_USERNAME') && defined('WP_PROXY_PASSWORD'); } /** * Retrieve the host for the proxy server. * * @since 2.8 * * @return string */ function host() { if ( defined('WP_PROXY_HOST') ) return WP_PROXY_HOST; return ''; } /** * Retrieve the port for the proxy server. * * @since 2.8 * * @return string */ function port() { if ( defined('WP_PROXY_PORT') ) return WP_PROXY_PORT; return ''; } /** * Retrieve the username for proxy authentication. * * @since 2.8 * * @return string */ function username() { if ( defined('WP_PROXY_USERNAME') ) return WP_PROXY_USERNAME; return ''; } /** * Retrieve the password for proxy authentication. * * @since 2.8 * * @return string */ function password() { if ( defined('WP_PROXY_PASSWORD') ) return WP_PROXY_PASSWORD; return ''; } /** * Retrieve authentication string for proxy authentication. * * @since 2.8 * * @return string */ function authentication() { return $this->username() . ':' . $this->password(); } /** * Retrieve header string for proxy authentication. * * @since 2.8 * * @return string */ function authentication_header() { return 'Proxy-Authorization: Basic ' . base64_encode( $this->authentication() ); } /** * Whether URL should be sent through the proxy server. * * We want to keep localhost and the blog URL from being sent through the proxy server, because * some proxies can not handle this. We also have the constant available for defining other * hosts that won't be sent through the proxy. * * @uses WP_PROXY_BYPASS_HOSTS * @since 2.8.0 * * @param string $uri URI to check. * @return bool True, to send through the proxy and false if, the proxy should not be used. */ function send_through_proxy( $uri ) { // parse_url() only handles http, https type URLs, and will emit E_WARNING on failure. // This will be displayed on blogs, which is not reasonable. $check = @parse_url($uri); // Malformed URL, can not process, but this could mean ssl, so let through anyway. if ( $check === false ) return true; $home = parse_url( get_option('siteurl') ); $result = apply_filters( 'pre_http_send_through_proxy', null, $uri, $check, $home ); if ( ! is_null( $result ) ) return $result; if ( $check['host'] == 'localhost' || $check['host'] == $home['host'] ) return false; if ( !defined('WP_PROXY_BYPASS_HOSTS') ) return true; static $bypass_hosts; static $wildcard_regex = false; if ( null == $bypass_hosts ) { $bypass_hosts = preg_split('|,\s*|', WP_PROXY_BYPASS_HOSTS); if ( false !== strpos(WP_PROXY_BYPASS_HOSTS, '*') ) { $wildcard_regex = array(); foreach ( $bypass_hosts as $host ) $wildcard_regex[] = str_replace('\*', '[\w.]+?', preg_quote($host, '/')); $wildcard_regex = '/^(' . implode('|', $wildcard_regex) . ')$/i'; } } if ( !empty($wildcard_regex) ) return !preg_match($wildcard_regex, $check['host']); else return !in_array( $check['host'], $bypass_hosts ); } } /** * Internal representation of a single cookie. * * Returned cookies are represented using this class, and when cookies are set, if they are not * already a WP_Http_Cookie() object, then they are turned into one. * * @todo The WordPress convention is to use underscores instead of camelCase for function and method * names. Need to switch to use underscores instead for the methods. * * @package WordPress * @subpackage HTTP * @since 2.8.0 */ class WP_Http_Cookie { /** * Cookie name. * * @since 2.8.0 * @var string */ var $name; /** * Cookie value. * * @since 2.8.0 * @var string */ var $value; /** * When the cookie expires. * * @since 2.8.0 * @var string */ var $expires; /** * Cookie URL path. * * @since 2.8.0 * @var string */ var $path; /** * Cookie Domain. * * @since 2.8.0 * @var string */ var $domain; /** * Sets up this cookie object. * * The parameter $data should be either an associative array containing the indices names below * or a header string detailing it. * * If it's an array, it should include the following elements: * <ol> * <li>Name</li> * <li>Value - should NOT be urlencoded already.</li> * <li>Expires - (optional) String or int (UNIX timestamp).</li> * <li>Path (optional)</li> * <li>Domain (optional)</li> * </ol> * * @access public * @since 2.8.0 * * @param string|array $data Raw cookie data. */ function __construct( $data ) { if ( is_string( $data ) ) { // Assume it's a header string direct from a previous request $pairs = explode( ';', $data ); // Special handling for first pair; name=value. Also be careful of "=" in value $name = trim( substr( $pairs[0], 0, strpos( $pairs[0], '=' ) ) ); $value = substr( $pairs[0], strpos( $pairs[0], '=' ) + 1 ); $this->name = $name; $this->value = urldecode( $value ); array_shift( $pairs ); //Removes name=value from items. // Set everything else as a property foreach ( $pairs as $pair ) { $pair = rtrim($pair); if ( empty($pair) ) //Handles the cookie ending in ; which results in a empty final pair continue; list( $key, $val ) = strpos( $pair, '=' ) ? explode( '=', $pair ) : array( $pair, '' ); $key = strtolower( trim( $key ) ); if ( 'expires' == $key ) $val = strtotime( $val ); $this->$key = $val; } } else { if ( !isset( $data['name'] ) ) return false; // Set properties based directly on parameters $this->name = $data['name']; $this->value = isset( $data['value'] ) ? $data['value'] : ''; $this->path = isset( $data['path'] ) ? $data['path'] : ''; $this->domain = isset( $data['domain'] ) ? $data['domain'] : ''; if ( isset( $data['expires'] ) ) $this->expires = is_int( $data['expires'] ) ? $data['expires'] : strtotime( $data['expires'] ); else $this->expires = null; } } /** * Confirms that it's OK to send this cookie to the URL checked against. * * Decision is based on RFC 2109/2965, so look there for details on validity. * * @access public * @since 2.8.0 * * @param string $url URL you intend to send this cookie to * @return boolean true if allowed, false otherwise. */ function test( $url ) { // Expires - if expired then nothing else matters if ( isset( $this->expires ) && time() > $this->expires ) return false; // Get details on the URL we're thinking about sending to $url = parse_url( $url ); $url['port'] = isset( $url['port'] ) ? $url['port'] : 80; $url['path'] = isset( $url['path'] ) ? $url['path'] : '/'; // Values to use for comparison against the URL $path = isset( $this->path ) ? $this->path : '/'; $port = isset( $this->port ) ? $this->port : 80; $domain = isset( $this->domain ) ? strtolower( $this->domain ) : strtolower( $url['host'] ); if ( false === stripos( $domain, '.' ) ) $domain .= '.local'; // Host - very basic check that the request URL ends with the domain restriction (minus leading dot) $domain = substr( $domain, 0, 1 ) == '.' ? substr( $domain, 1 ) : $domain; if ( substr( $url['host'], -strlen( $domain ) ) != $domain ) return false; // Port - supports "port-lists" in the format: "80,8000,8080" if ( !in_array( $url['port'], explode( ',', $port) ) ) return false; // Path - request path must start with path restriction if ( substr( $url['path'], 0, strlen( $path ) ) != $path ) return false; return true; } /** * Convert cookie name and value back to header string. * * @access public * @since 2.8.0 * * @return string Header encoded cookie name and value. */ function getHeaderValue() { if ( ! isset( $this->name ) || ! isset( $this->value ) ) return ''; return $this->name . '=' . apply_filters( 'wp_http_cookie_value', $this->value, $this->name ); } /** * Retrieve cookie header for usage in the rest of the WordPress HTTP API. * * @access public * @since 2.8.0 * * @return string */ function getFullHeader() { return 'Cookie: ' . $this->getHeaderValue(); } } /** * Implementation for deflate and gzip transfer encodings. * * Includes RFC 1950, RFC 1951, and RFC 1952. * * @since 2.8 * @package WordPress * @subpackage HTTP */ class WP_Http_Encoding { /** * Compress raw string using the deflate format. * * Supports the RFC 1951 standard. * * @since 2.8 * * @param string $raw String to compress. * @param int $level Optional, default is 9. Compression level, 9 is highest. * @param string $supports Optional, not used. When implemented it will choose the right compression based on what the server supports. * @return string|bool False on failure. */ public static function compress( $raw, $level = 9, $supports = null ) { return gzdeflate( $raw, $level ); } /** * Decompression of deflated string. * * Will attempt to decompress using the RFC 1950 standard, and if that fails * then the RFC 1951 standard deflate will be attempted. Finally, the RFC * 1952 standard gzip decode will be attempted. If all fail, then the * original compressed string will be returned. * * @since 2.8 * * @param string $compressed String to decompress. * @param int $length The optional length of the compressed data. * @return string|bool False on failure. */ public static function decompress( $compressed, $length = null ) { if ( empty($compressed) ) return $compressed; if ( false !== ( $decompressed = @gzinflate( $compressed ) ) ) return $decompressed; if ( false !== ( $decompressed = WP_Http_Encoding::compatible_gzinflate( $compressed ) ) ) return $decompressed; if ( false !== ( $decompressed = @gzuncompress( $compressed ) ) ) return $decompressed; if ( function_exists('gzdecode') ) { $decompressed = @gzdecode( $compressed ); if ( false !== $decompressed ) return $decompressed; } return $compressed; } /** * Decompression of deflated string while staying compatible with the majority of servers. * * Certain Servers will return deflated data with headers which PHP's gzinflate() * function cannot handle out of the box. The following function has been created from * various snippets on the gzinflate() PHP documentation. * * Warning: Magic numbers within. Due to the potential different formats that the compressed * data may be returned in, some "magic offsets" are needed to ensure proper decompression * takes place. For a simple progmatic way to determine the magic offset in use, see: * http://core.trac.wordpress.org/ticket/18273 * * @since 2.8.1 * @link http://core.trac.wordpress.org/ticket/18273 * @link http://au2.php.net/manual/en/function.gzinflate.php#70875 * @link http://au2.php.net/manual/en/function.gzinflate.php#77336 * * @param string $gzData String to decompress. * @return string|bool False on failure. */ public static function compatible_gzinflate($gzData) { // Compressed data might contain a full header, if so strip it for gzinflate() if ( substr($gzData, 0, 3) == "\x1f\x8b\x08" ) { $i = 10; $flg = ord( substr($gzData, 3, 1) ); if ( $flg > 0 ) { if ( $flg & 4 ) { list($xlen) = unpack('v', substr($gzData, $i, 2) ); $i = $i + 2 + $xlen; } if ( $flg & 8 ) $i = strpos($gzData, "\0", $i) + 1; if ( $flg & 16 ) $i = strpos($gzData, "\0", $i) + 1; if ( $flg & 2 ) $i = $i + 2; } $decompressed = @gzinflate( substr($gzData, $i, -8) ); if ( false !== $decompressed ) return $decompressed; } // Compressed data from java.util.zip.Deflater amongst others. $decompressed = @gzinflate( substr($gzData, 2) ); if ( false !== $decompressed ) return $decompressed; return false; } /** * What encoding types to accept and their priority values. * * @since 2.8 * * @return string Types of encoding to accept. */ public static function accept_encoding() { $type = array(); if ( function_exists( 'gzinflate' ) ) $type[] = 'deflate;q=1.0'; if ( function_exists( 'gzuncompress' ) ) $type[] = 'compress;q=0.5'; if ( function_exists( 'gzdecode' ) ) $type[] = 'gzip;q=0.5'; return implode(', ', $type); } /** * What encoding the content used when it was compressed to send in the headers. * * @since 2.8 * * @return string Content-Encoding string to send in the header. */ public static function content_encoding() { return 'deflate'; } /** * Whether the content be decoded based on the headers. * * @since 2.8 * * @param array|string $headers All of the available headers. * @return bool */ public static function should_decode($headers) { if ( is_array( $headers ) ) { if ( array_key_exists('content-encoding', $headers) && ! empty( $headers['content-encoding'] ) ) return true; } else if ( is_string( $headers ) ) { return ( stripos($headers, 'content-encoding:') !== false ); } return false; } /** * Whether decompression and compression are supported by the PHP version. * * Each function is tested instead of checking for the zlib extension, to * ensure that the functions all exist in the PHP version and aren't * disabled. * * @since 2.8 * * @return bool */ public static function is_available() { return ( function_exists('gzuncompress') || function_exists('gzdeflate') || function_exists('gzinflate') ); } }
zyblog
trunk/zyblog/wp-includes/class-http.php
PHP
asf20
58,685
<?php /** * Send XML response back to AJAX request. * * @package WordPress * @since 2.1.0 */ class WP_Ajax_Response { /** * Store XML responses to send. * * @since 2.1.0 * @var array * @access private */ var $responses = array(); /** * Constructor - Passes args to {@link WP_Ajax_Response::add()}. * * @since 2.1.0 * @see WP_Ajax_Response::add() * * @param string|array $args Optional. Will be passed to add() method. * @return WP_Ajax_Response */ function __construct( $args = '' ) { if ( !empty($args) ) $this->add($args); } /** * Append to XML response based on given arguments. * * The arguments that can be passed in the $args parameter are below. It is * also possible to pass a WP_Error object in either the 'id' or 'data' * argument. The parameter isn't actually optional, content should be given * in order to send the correct response. * * 'what' argument is a string that is the XMLRPC response type. * 'action' argument is a boolean or string that acts like a nonce. * 'id' argument can be WP_Error or an integer. * 'old_id' argument is false by default or an integer of the previous ID. * 'position' argument is an integer or a string with -1 = top, 1 = bottom, * html ID = after, -html ID = before. * 'data' argument is a string with the content or message. * 'supplemental' argument is an array of strings that will be children of * the supplemental element. * * @since 2.1.0 * * @param string|array $args Override defaults. * @return string XML response. */ function add( $args = '' ) { $defaults = array( 'what' => 'object', 'action' => false, 'id' => '0', 'old_id' => false, 'position' => 1, 'data' => '', 'supplemental' => array() ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $position = preg_replace( '/[^a-z0-9:_-]/i', '', $position ); if ( is_wp_error($id) ) { $data = $id; $id = 0; } $response = ''; if ( is_wp_error($data) ) { foreach ( (array) $data->get_error_codes() as $code ) { $response .= "<wp_error code='$code'><![CDATA[" . $data->get_error_message($code) . "]]></wp_error>"; if ( !$error_data = $data->get_error_data($code) ) continue; $class = ''; if ( is_object($error_data) ) { $class = ' class="' . get_class($error_data) . '"'; $error_data = get_object_vars($error_data); } $response .= "<wp_error_data code='$code'$class>"; if ( is_scalar($error_data) ) { $response .= "<![CDATA[$error_data]]>"; } elseif ( is_array($error_data) ) { foreach ( $error_data as $k => $v ) $response .= "<$k><![CDATA[$v]]></$k>"; } $response .= "</wp_error_data>"; } } else { $response = "<response_data><![CDATA[$data]]></response_data>"; } $s = ''; if ( is_array($supplemental) ) { foreach ( $supplemental as $k => $v ) $s .= "<$k><![CDATA[$v]]></$k>"; $s = "<supplemental>$s</supplemental>"; } if ( false === $action ) $action = $_POST['action']; $x = ''; $x .= "<response action='{$action}_$id'>"; // The action attribute in the xml output is formatted like a nonce action $x .= "<$what id='$id' " . ( false === $old_id ? '' : "old_id='$old_id' " ) . "position='$position'>"; $x .= $response; $x .= $s; $x .= "</$what>"; $x .= "</response>"; $this->responses[] = $x; return $x; } /** * Display XML formatted responses. * * Sets the content type header to text/xml. * * @since 2.1.0 */ function send() { header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ) ); echo "<?xml version='1.0' encoding='" . get_option( 'blog_charset' ) . "' standalone='yes'?><wp_ajax>"; foreach ( (array) $this->responses as $response ) echo $response; echo '</wp_ajax>'; if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) wp_die(); else die(); } }
zyblog
trunk/zyblog/wp-includes/class-wp-ajax-response.php
PHP
asf20
3,887
<?php /** * Multisite WordPress API * * @package WordPress * @subpackage Multisite * @since 3.0.0 */ /** * Gets the network's site and user counts. * * @since MU 1.0 * @uses get_blog_count() * @uses get_user_count() * * @return array Site and user count for the network. */ function get_sitestats() { global $wpdb; $stats = array( 'blogs' => get_blog_count(), 'users' => get_user_count(), ); return $stats; } /** * Get the admin for a domain/path combination. * * @since MU 1.0 * * @param string $sitedomain Optional. Site domain. * @param string $path Optional. Site path. * @return array The network admins */ function get_admin_users_for_domain( $sitedomain = '', $path = '' ) { global $wpdb; if ( ! $sitedomain ) $site_id = $wpdb->siteid; else $site_id = $wpdb->get_var( $wpdb->prepare( "SELECT id FROM $wpdb->site WHERE domain = %s AND path = %s", $sitedomain, $path ) ); if ( $site_id ) return $wpdb->get_results( $wpdb->prepare( "SELECT u.ID, u.user_login, u.user_pass FROM $wpdb->users AS u, $wpdb->sitemeta AS sm WHERE sm.meta_key = 'admin_user_id' AND u.ID = sm.meta_value AND sm.site_id = %d", $site_id ), ARRAY_A ); return false; } /** * Get one of a user's active blogs * * Returns the user's primary blog, if she has one and * it is active. If it's inactive, function returns another * active blog of the user. If none are found, the user * is added as a Subscriber to the Dashboard Blog and that blog * is returned. * * @since MU 1.0 * @uses get_blogs_of_user() * @uses add_user_to_blog() * @uses get_blog_details() * * @param int $user_id The unique ID of the user * @return object The blog object */ function get_active_blog_for_user( $user_id ) { global $wpdb; $blogs = get_blogs_of_user( $user_id ); if ( empty( $blogs ) ) return null; if ( !is_multisite() ) return $blogs[$wpdb->blogid]; $primary_blog = get_user_meta( $user_id, 'primary_blog', true ); $first_blog = current($blogs); if ( false !== $primary_blog ) { if ( ! isset( $blogs[ $primary_blog ] ) ) { update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id ); $primary = get_blog_details( $first_blog->userblog_id ); } else { $primary = get_blog_details( $primary_blog ); } } else { //TODO Review this call to add_user_to_blog too - to get here the user must have a role on this blog? add_user_to_blog( $first_blog->userblog_id, $user_id, 'subscriber' ); update_user_meta( $user_id, 'primary_blog', $first_blog->userblog_id ); $primary = $first_blog; } if ( ( ! is_object( $primary ) ) || ( $primary->archived == 1 || $primary->spam == 1 || $primary->deleted == 1 ) ) { $blogs = get_blogs_of_user( $user_id, true ); // if a user's primary blog is shut down, check their other blogs. $ret = false; if ( is_array( $blogs ) && count( $blogs ) > 0 ) { foreach ( (array) $blogs as $blog_id => $blog ) { if ( $blog->site_id != $wpdb->siteid ) continue; $details = get_blog_details( $blog_id ); if ( is_object( $details ) && $details->archived == 0 && $details->spam == 0 && $details->deleted == 0 ) { $ret = $blog; if ( get_user_meta( $user_id , 'primary_blog', true ) != $blog_id ) update_user_meta( $user_id, 'primary_blog', $blog_id ); if ( !get_user_meta($user_id , 'source_domain', true) ) update_user_meta( $user_id, 'source_domain', $blog->domain ); break; } } } else { return null; } return $ret; } else { return $primary; } } /** * The number of active users in your installation. * * The count is cached and updated twice daily. This is not a live count. * * @since MU 2.7 * * @return int */ function get_user_count() { return get_site_option( 'user_count' ); } /** * The number of active sites on your installation. * * The count is cached and updated twice daily. This is not a live count. * * @since MU 1.0 * * @param int $id Optional. A site_id. * @return int */ function get_blog_count( $id = 0 ) { return get_site_option( 'blog_count' ); } /** * Get a blog post from any site on the network. * * @since MU 1.0 * * @param int $blog_id ID of the blog. * @param int $post_id ID of the post you're looking for. * @return WP_Post|null WP_Post on success or null on failure */ function get_blog_post( $blog_id, $post_id ) { switch_to_blog( $blog_id ); $post = get_post( $post_id ); restore_current_blog(); return $post; } /** * Add a user to a blog. * * Use the 'add_user_to_blog' action to fire an event when * users are added to a blog. * * @since MU 1.0 * * @param int $blog_id ID of the blog you're adding the user to. * @param int $user_id ID of the user you're adding. * @param string $role The role you want the user to have * @return bool */ function add_user_to_blog( $blog_id, $user_id, $role ) { switch_to_blog($blog_id); $user = get_userdata( $user_id ); if ( ! $user ) { restore_current_blog(); return new WP_Error( 'user_does_not_exist', __( 'The requested user does not exist.' ) ); } if ( !get_user_meta($user_id, 'primary_blog', true) ) { update_user_meta($user_id, 'primary_blog', $blog_id); $details = get_blog_details($blog_id); update_user_meta($user_id, 'source_domain', $details->domain); } $user->set_role($role); do_action('add_user_to_blog', $user_id, $role, $blog_id); wp_cache_delete( $user_id, 'users' ); restore_current_blog(); return true; } /** * Remove a user from a blog. * * Use the 'remove_user_from_blog' action to fire an event when * users are removed from a blog. * * Accepts an optional $reassign parameter, if you want to * reassign the user's blog posts to another user upon removal. * * @since MU 1.0 * * @param int $user_id ID of the user you're removing. * @param int $blog_id ID of the blog you're removing the user from. * @param string $reassign Optional. A user to whom to reassign posts. * @return bool */ function remove_user_from_blog($user_id, $blog_id = '', $reassign = '') { global $wpdb; switch_to_blog($blog_id); $user_id = (int) $user_id; do_action('remove_user_from_blog', $user_id, $blog_id); // If being removed from the primary blog, set a new primary if the user is assigned // to multiple blogs. $primary_blog = get_user_meta($user_id, 'primary_blog', true); if ( $primary_blog == $blog_id ) { $new_id = ''; $new_domain = ''; $blogs = get_blogs_of_user($user_id); foreach ( (array) $blogs as $blog ) { if ( $blog->userblog_id == $blog_id ) continue; $new_id = $blog->userblog_id; $new_domain = $blog->domain; break; } update_user_meta($user_id, 'primary_blog', $new_id); update_user_meta($user_id, 'source_domain', $new_domain); } // wp_revoke_user($user_id); $user = get_userdata( $user_id ); if ( ! $user ) { restore_current_blog(); return new WP_Error('user_does_not_exist', __('That user does not exist.')); } $user->remove_all_caps(); $blogs = get_blogs_of_user($user_id); if ( count($blogs) == 0 ) { update_user_meta($user_id, 'primary_blog', ''); update_user_meta($user_id, 'source_domain', ''); } if ( $reassign != '' ) { $reassign = (int) $reassign; $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET post_author = %d WHERE post_author = %d", $reassign, $user_id) ); $wpdb->query( $wpdb->prepare("UPDATE $wpdb->links SET link_owner = %d WHERE link_owner = %d", $reassign, $user_id) ); } restore_current_blog(); return true; } /** * Create an empty blog. * * @since MU 1.0 * @uses install_blog() * * @param string $domain The new blog's domain. * @param string $path The new blog's path. * @param string $weblog_title The new blog's title. * @param int $site_id Optional. Defaults to 1. * @return int The ID of the newly created blog */ function create_empty_blog( $domain, $path, $weblog_title, $site_id = 1 ) { $domain = addslashes( $domain ); $weblog_title = addslashes( $weblog_title ); if ( empty($path) ) $path = '/'; // Check if the domain has been used already. We should return an error message. if ( domain_exists($domain, $path, $site_id) ) return __( '<strong>ERROR</strong>: Site URL already taken.' ); // Need to back up wpdb table names, and create a new wp_blogs entry for new blog. // Need to get blog_id from wp_blogs, and create new table names. // Must restore table names at the end of function. if ( ! $blog_id = insert_blog($domain, $path, $site_id) ) return __( '<strong>ERROR</strong>: problem creating site entry.' ); switch_to_blog($blog_id); install_blog($blog_id); restore_current_blog(); return $blog_id; } /** * Get the permalink for a post on another blog. * * @since MU 1.0 * * @param int $blog_id ID of the source blog. * @param int $post_id ID of the desired post. * @return string The post's permalink */ function get_blog_permalink( $blog_id, $post_id ) { switch_to_blog( $blog_id ); $link = get_permalink( $post_id ); restore_current_blog(); return $link; } /** * Get a blog's numeric ID from its URL. * * On a subdirectory installation like example.com/blog1/, * $domain will be the root 'example.com' and $path the * subdirectory '/blog1/'. With subdomains like blog1.example.com, * $domain is 'blog1.example.com' and $path is '/'. * * @since MU 2.6.5 * * @param string $domain * @param string $path Optional. Not required for subdomain installations. * @return int 0 if no blog found, otherwise the ID of the matching blog */ function get_blog_id_from_url( $domain, $path = '/' ) { global $wpdb; $domain = strtolower( $domain ); $path = strtolower( $path ); $id = wp_cache_get( md5( $domain . $path ), 'blog-id-cache' ); if ( $id == -1 ) // blog does not exist return 0; elseif ( $id ) return (int) $id; $id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s and path = %s /* get_blog_id_from_url */", $domain, $path ) ); if ( ! $id ) { wp_cache_set( md5( $domain . $path ), -1, 'blog-id-cache' ); return 0; } wp_cache_set( md5( $domain . $path ), $id, 'blog-id-cache' ); return $id; } // Admin functions /** * Checks an email address against a list of banned domains. * * This function checks against the Banned Email Domains list * at wp-admin/network/settings.php. The check is only run on * self-registrations; user creation at wp-admin/network/users.php * bypasses this check. * * @since MU * * @param string $user_email The email provided by the user at registration. * @return bool Returns true when the email address is banned. */ function is_email_address_unsafe( $user_email ) { $banned_names = get_site_option( 'banned_email_domains' ); if ( $banned_names && ! is_array( $banned_names ) ) $banned_names = explode( "\n", $banned_names ); $is_email_address_unsafe = false; if ( $banned_names && is_array( $banned_names ) ) { list( $email_local_part, $email_domain ) = explode( '@', $user_email ); foreach ( $banned_names as $banned_domain ) { if ( ! $banned_domain ) continue; if ( $email_domain == $banned_domain ) { $is_email_address_unsafe = true; break; } $dotted_domain = ".$banned_domain"; if ( $dotted_domain === substr( $user_email, -strlen( $dotted_domain ) ) ) { $is_email_address_unsafe = true; break; } } } return apply_filters( 'is_email_address_unsafe', $is_email_address_unsafe, $user_email ); } /** * Processes new user registrations. * * Checks the data provided by the user during signup. Verifies * the validity and uniqueness of user names and user email addresses, * and checks email addresses against admin-provided domain * whitelists and blacklists. * * The hook 'wpmu_validate_user_signup' provides an easy way * to modify the signup process. The value $result, which is passed * to the hook, contains both the user-provided info and the error * messages created by the function. 'wpmu_validate_user_signup' allows * you to process the data in any way you'd like, and unset the * relevant errors if necessary. * * @since MU * @uses is_email_address_unsafe() * @uses username_exists() * @uses email_exists() * * @param string $user_name The login name provided by the user. * @param string $user_email The email provided by the user. * @return array Contains username, email, and error messages. */ function wpmu_validate_user_signup($user_name, $user_email) { global $wpdb; $errors = new WP_Error(); $orig_username = $user_name; $user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) ); if ( $user_name != $orig_username || preg_match( '/[^a-z0-9]/', $user_name ) ) { $errors->add( 'user_name', __( 'Only lowercase letters (a-z) and numbers are allowed.' ) ); $user_name = $orig_username; } $user_email = sanitize_email( $user_email ); if ( empty( $user_name ) ) $errors->add('user_name', __( 'Please enter a username.' ) ); $illegal_names = get_site_option( 'illegal_names' ); if ( is_array( $illegal_names ) == false ) { $illegal_names = array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' ); add_site_option( 'illegal_names', $illegal_names ); } if ( in_array( $user_name, $illegal_names ) == true ) $errors->add('user_name', __( 'That username is not allowed.' ) ); if ( is_email_address_unsafe( $user_email ) ) $errors->add('user_email', __('You cannot use that email address to signup. We are having problems with them blocking some of our email. Please use another email provider.')); if ( strlen( $user_name ) < 4 ) $errors->add('user_name', __( 'Username must be at least 4 characters.' ) ); if ( strpos( ' ' . $user_name, '_' ) != false ) $errors->add( 'user_name', __( 'Sorry, usernames may not contain the character &#8220;_&#8221;!' ) ); // all numeric? $match = array(); preg_match( '/[0-9]*/', $user_name, $match ); if ( $match[0] == $user_name ) $errors->add('user_name', __('Sorry, usernames must have letters too!')); if ( !is_email( $user_email ) ) $errors->add('user_email', __( 'Please enter a valid email address.' ) ); $limited_email_domains = get_site_option( 'limited_email_domains' ); if ( is_array( $limited_email_domains ) && empty( $limited_email_domains ) == false ) { $emaildomain = substr( $user_email, 1 + strpos( $user_email, '@' ) ); if ( in_array( $emaildomain, $limited_email_domains ) == false ) $errors->add('user_email', __('Sorry, that email address is not allowed!')); } // Check if the username has been used already. if ( username_exists($user_name) ) $errors->add( 'user_name', __( 'Sorry, that username already exists!' ) ); // Check if the email address has been used already. if ( email_exists($user_email) ) $errors->add( 'user_email', __( 'Sorry, that email address is already used!' ) ); // Has someone already signed up for this username? $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_login = %s", $user_name) ); if ( $signup != null ) { $registered_at = mysql2date('U', $signup->registered); $now = current_time( 'timestamp', true ); $diff = $now - $registered_at; // If registered more than two days ago, cancel registration and let this signup go through. if ( $diff > 2 * DAY_IN_SECONDS ) $wpdb->delete( $wpdb->signups, array( 'user_login' => $user_name ) ); else $errors->add('user_name', __('That username is currently reserved but may be available in a couple of days.')); if ( $signup->active == 0 && $signup->user_email == $user_email ) $errors->add('user_email_used', __('username and email used')); } $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE user_email = %s", $user_email) ); if ( $signup != null ) { $diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered); // If registered more than two days ago, cancel registration and let this signup go through. if ( $diff > 2 * DAY_IN_SECONDS ) $wpdb->delete( $wpdb->signups, array( 'user_email' => $user_email ) ); else $errors->add('user_email', __('That email address has already been used. Please check your inbox for an activation email. It will become available in a couple of days if you do nothing.')); } $result = array('user_name' => $user_name, 'orig_username' => $orig_username, 'user_email' => $user_email, 'errors' => $errors); return apply_filters('wpmu_validate_user_signup', $result); } /** * Processes new site registrations. * * Checks the data provided by the user during blog signup. Verifies * the validity and uniqueness of blog paths and domains. * * This function prevents the current user from registering a new site * with a blogname equivalent to another user's login name. Passing the * $user parameter to the function, where $user is the other user, is * effectively an override of this limitation. * * Filter 'wpmu_validate_blog_signup' if you want to modify * the way that WordPress validates new site signups. * * @since MU * @uses domain_exists() * @uses username_exists() * * @param string $blogname The blog name provided by the user. Must be unique. * @param string $blog_title The blog title provided by the user. * @return array Contains the new site data and error messages. */ function wpmu_validate_blog_signup($blogname, $blog_title, $user = '') { global $wpdb, $domain, $current_site; $base = $current_site->path; $blog_title = strip_tags( $blog_title ); $blog_title = substr( $blog_title, 0, 50 ); $errors = new WP_Error(); $illegal_names = get_site_option( 'illegal_names' ); if ( $illegal_names == false ) { $illegal_names = array( 'www', 'web', 'root', 'admin', 'main', 'invite', 'administrator' ); add_site_option( 'illegal_names', $illegal_names ); } // On sub dir installs, Some names are so illegal, only a filter can spring them from jail if (! is_subdomain_install() ) $illegal_names = array_merge($illegal_names, apply_filters( 'subdirectory_reserved_names', array( 'page', 'comments', 'blog', 'files', 'feed' ) ) ); if ( empty( $blogname ) ) $errors->add('blogname', __( 'Please enter a site name.' ) ); if ( preg_match( '/[^a-z0-9]+/', $blogname ) ) $errors->add('blogname', __( 'Only lowercase letters (a-z) and numbers are allowed.' ) ); if ( in_array( $blogname, $illegal_names ) == true ) $errors->add('blogname', __( 'That name is not allowed.' ) ); if ( strlen( $blogname ) < 4 && !is_super_admin() ) $errors->add('blogname', __( 'Site name must be at least 4 characters.' ) ); if ( strpos( ' ' . $blogname, '_' ) != false ) $errors->add( 'blogname', __( 'Sorry, site names may not contain the character &#8220;_&#8221;!' ) ); // do not allow users to create a blog that conflicts with a page on the main blog. if ( !is_subdomain_install() && $wpdb->get_var( $wpdb->prepare( "SELECT post_name FROM " . $wpdb->get_blog_prefix( $current_site->blog_id ) . "posts WHERE post_type = 'page' AND post_name = %s", $blogname ) ) ) $errors->add( 'blogname', __( 'Sorry, you may not use that site name.' ) ); // all numeric? $match = array(); preg_match( '/[0-9]*/', $blogname, $match ); if ( $match[0] == $blogname ) $errors->add('blogname', __('Sorry, site names must have letters too!')); $blogname = apply_filters( 'newblogname', $blogname ); $blog_title = stripslashes( $blog_title ); if ( empty( $blog_title ) ) $errors->add('blog_title', __( 'Please enter a site title.' ) ); // Check if the domain/path has been used already. if ( is_subdomain_install() ) { $mydomain = $blogname . '.' . preg_replace( '|^www\.|', '', $domain ); $path = $base; } else { $mydomain = "$domain"; $path = $base.$blogname.'/'; } if ( domain_exists($mydomain, $path, $current_site->id) ) $errors->add( 'blogname', __( 'Sorry, that site already exists!' ) ); if ( username_exists( $blogname ) ) { if ( is_object( $user ) == false || ( is_object($user) && ( $user->user_login != $blogname ) ) ) $errors->add( 'blogname', __( 'Sorry, that site is reserved!' ) ); } // Has someone already signed up for this domain? $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE domain = %s AND path = %s", $mydomain, $path) ); // TODO: Check email too? if ( ! empty($signup) ) { $diff = current_time( 'timestamp', true ) - mysql2date('U', $signup->registered); // If registered more than two days ago, cancel registration and let this signup go through. if ( $diff > 2 * DAY_IN_SECONDS ) $wpdb->delete( $wpdb->signups, array( 'domain' => $mydomain , 'path' => $path ) ); else $errors->add('blogname', __('That site is currently reserved but may be available in a couple days.')); } $result = array('domain' => $mydomain, 'path' => $path, 'blogname' => $blogname, 'blog_title' => $blog_title, 'user' => $user, 'errors' => $errors); return apply_filters('wpmu_validate_blog_signup', $result); } /** * Record site signup information for future activation. * * @since MU * @uses wpmu_signup_blog_notification() * * @param string $domain The requested domain. * @param string $path The requested path. * @param string $title The requested site title. * @param string $user The user's requested login name. * @param string $user_email The user's email address. * @param array $meta By default, contains the requested privacy setting and lang_id. */ function wpmu_signup_blog($domain, $path, $title, $user, $user_email, $meta = '') { global $wpdb; $key = substr( md5( time() . rand() . $domain ), 0, 16 ); $meta = serialize($meta); $domain = $wpdb->escape($domain); $path = $wpdb->escape($path); $title = $wpdb->escape($title); $wpdb->insert( $wpdb->signups, array( 'domain' => $domain, 'path' => $path, 'title' => $title, 'user_login' => $user, 'user_email' => $user_email, 'registered' => current_time('mysql', true), 'activation_key' => $key, 'meta' => $meta ) ); wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta); } /** * Record user signup information for future activation. * * This function is used when user registration is open but * new site registration is not. * * @since MU * @uses wpmu_signup_user_notification() * * @param string $user The user's requested login name. * @param string $user_email The user's email address. * @param array $meta By default, this is an empty array. */ function wpmu_signup_user($user, $user_email, $meta = '') { global $wpdb; // Format data $user = preg_replace( '/\s+/', '', sanitize_user( $user, true ) ); $user_email = sanitize_email( $user_email ); $key = substr( md5( time() . rand() . $user_email ), 0, 16 ); $meta = serialize($meta); $wpdb->insert( $wpdb->signups, array( 'domain' => '', 'path' => '', 'title' => '', 'user_login' => $user, 'user_email' => $user_email, 'registered' => current_time('mysql', true), 'activation_key' => $key, 'meta' => $meta ) ); wpmu_signup_user_notification($user, $user_email, $key, $meta); } /** * Notify user of signup success. * * This is the notification function used when site registration * is enabled. * * Filter 'wpmu_signup_blog_notification' to bypass this function or * replace it with your own notification behavior. * * Filter 'wpmu_signup_blog_notification_email' and * 'wpmu_signup_blog_notification_subject' to change the content * and subject line of the email sent to newly registered users. * * @since MU * * @param string $domain The new blog domain. * @param string $path The new blog path. * @param string $title The site title. * @param string $user The user's login name. * @param string $user_email The user's email address. * @param array $meta By default, contains the requested privacy setting and lang_id. * @param string $key The activation key created in wpmu_signup_blog() * @return bool */ function wpmu_signup_blog_notification($domain, $path, $title, $user, $user_email, $key, $meta = '') { global $current_site; if ( !apply_filters('wpmu_signup_blog_notification', $domain, $path, $title, $user, $user_email, $key, $meta) ) return false; // Send email with activation link. if ( !is_subdomain_install() || $current_site->id != 1 ) $activate_url = network_site_url("wp-activate.php?key=$key"); else $activate_url = "http://{$domain}{$path}wp-activate.php?key=$key"; // @todo use *_url() API $activate_url = esc_url($activate_url); $admin_email = get_site_option( 'admin_email' ); if ( $admin_email == '' ) $admin_email = 'support@' . $_SERVER['SERVER_NAME']; $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) ); $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n"; $message = sprintf( apply_filters( 'wpmu_signup_blog_notification_email', __( "To activate your blog, please click the following link:\n\n%s\n\nAfter you activate, you will receive *another email* with your login.\n\nAfter you activate, you can visit your site here:\n\n%s" ), $domain, $path, $title, $user, $user_email, $key, $meta ), $activate_url, esc_url( "http://{$domain}{$path}" ), $key ); // TODO: Don't hard code activation link. $subject = sprintf( apply_filters( 'wpmu_signup_blog_notification_subject', __( '[%1$s] Activate %2$s' ), $domain, $path, $title, $user, $user_email, $key, $meta ), $from_name, esc_url( 'http://' . $domain . $path ) ); wp_mail($user_email, $subject, $message, $message_headers); return true; } /** * Notify user of signup success. * * This is the notification function used when no new site has * been requested. * * Filter 'wpmu_signup_user_notification' to bypass this function or * replace it with your own notification behavior. * * Filter 'wpmu_signup_user_notification_email' and * 'wpmu_signup_user_notification_subject' to change the content * and subject line of the email sent to newly registered users. * * @since MU * * @param string $user The user's login name. * @param string $user_email The user's email address. * @param array $meta By default, an empty array. * @param string $key The activation key created in wpmu_signup_user() * @return bool */ function wpmu_signup_user_notification($user, $user_email, $key, $meta = '') { if ( !apply_filters('wpmu_signup_user_notification', $user, $user_email, $key, $meta) ) return false; // Send email with activation link. $admin_email = get_site_option( 'admin_email' ); if ( $admin_email == '' ) $admin_email = 'support@' . $_SERVER['SERVER_NAME']; $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) ); $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n"; $message = sprintf( apply_filters( 'wpmu_signup_user_notification_email', __( "To activate your user, please click the following link:\n\n%s\n\nAfter you activate, you will receive *another email* with your login." ), $user, $user_email, $key, $meta ), site_url( "wp-activate.php?key=$key" ) ); // TODO: Don't hard code activation link. $subject = sprintf( apply_filters( 'wpmu_signup_user_notification_subject', __( '[%1$s] Activate %2$s' ), $user, $user_email, $key, $meta ), $from_name, $user ); wp_mail($user_email, $subject, $message, $message_headers); return true; } /** * Activate a signup. * * Hook to 'wpmu_activate_user' or 'wpmu_activate_blog' for events * that should happen only when users or sites are self-created (since * those actions are not called when users and sites are created * by a Super Admin). * * @since MU * @uses wp_generate_password() * @uses wpmu_welcome_user_notification() * @uses add_user_to_blog() * @uses add_new_user_to_blog() * @uses wpmu_create_user() * @uses wpmu_create_blog() * @uses wpmu_welcome_notification() * * @param string $key The activation key provided to the user. * @return array An array containing information about the activated user and/or blog */ function wpmu_activate_signup($key) { global $wpdb, $current_site; $signup = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key) ); if ( empty( $signup ) ) return new WP_Error( 'invalid_key', __( 'Invalid activation key.' ) ); if ( $signup->active ) { if ( empty( $signup->domain ) ) return new WP_Error( 'already_active', __( 'The user is already active.' ), $signup ); else return new WP_Error( 'already_active', __( 'The site is already active.' ), $signup ); } $meta = maybe_unserialize($signup->meta); $user_login = $wpdb->escape($signup->user_login); $user_email = $wpdb->escape($signup->user_email); $password = wp_generate_password( 12, false ); $user_id = username_exists($user_login); if ( ! $user_id ) $user_id = wpmu_create_user($user_login, $password, $user_email); else $user_already_exists = true; if ( ! $user_id ) return new WP_Error('create_user', __('Could not create user'), $signup); $now = current_time('mysql', true); if ( empty($signup->domain) ) { $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) ); if ( isset( $user_already_exists ) ) return new WP_Error( 'user_already_exists', __( 'That username is already activated.' ), $signup); wpmu_welcome_user_notification($user_id, $password, $meta); add_new_user_to_blog( $user_id, $user_email, $meta ); do_action('wpmu_activate_user', $user_id, $password, $meta); return array('user_id' => $user_id, 'password' => $password, 'meta' => $meta); } $blog_id = wpmu_create_blog( $signup->domain, $signup->path, $signup->title, $user_id, $meta, $wpdb->siteid ); // TODO: What to do if we create a user but cannot create a blog? if ( is_wp_error($blog_id) ) { // If blog is taken, that means a previous attempt to activate this blog failed in between creating the blog and // setting the activation flag. Let's just set the active flag and instruct the user to reset their password. if ( 'blog_taken' == $blog_id->get_error_code() ) { $blog_id->add_data( $signup ); $wpdb->update( $wpdb->signups, array( 'active' => 1, 'activated' => $now ), array( 'activation_key' => $key ) ); } return $blog_id; } $wpdb->update( $wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key) ); wpmu_welcome_notification($blog_id, $user_id, $password, $signup->title, $meta); do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $signup->title, $meta); return array('blog_id' => $blog_id, 'user_id' => $user_id, 'password' => $password, 'title' => $signup->title, 'meta' => $meta); } /** * Create a user. * * This function runs when a user self-registers as well as when * a Super Admin creates a new user. Hook to 'wpmu_new_user' for events * that should affect all new users, but only on Multisite (otherwise * use 'user_register'). * * @since MU * @uses wp_create_user() * * @param string $user_name The new user's login name. * @param string $password The new user's password. * @param string $email The new user's email address. * @return mixed Returns false on failure, or int $user_id on success */ function wpmu_create_user( $user_name, $password, $email) { $user_name = preg_replace( '/\s+/', '', sanitize_user( $user_name, true ) ); $user_id = wp_create_user( $user_name, $password, $email ); if ( is_wp_error($user_id) ) return false; // Newly created users have no roles or caps until they are added to a blog. delete_user_option( $user_id, 'capabilities' ); delete_user_option( $user_id, 'user_level' ); do_action( 'wpmu_new_user', $user_id ); return $user_id; } /** * Create a site. * * This function runs when a user self-registers a new site as well * as when a Super Admin creates a new site. Hook to 'wpmu_new_blog' * for events that should affect all new sites. * * On subdirectory installs, $domain is the same as the main site's * domain, and the path is the subdirectory name (eg 'example.com' * and '/blog1/'). On subdomain installs, $domain is the new subdomain + * root domain (eg 'blog1.example.com'), and $path is '/'. * * @since MU * @uses domain_exists() * @uses insert_blog() * @uses wp_install_defaults() * @uses add_user_to_blog() * * @param string $domain The new site's domain. * @param string $path The new site's path. * @param string $title The new site's title. * @param int $user_id The user ID of the new site's admin. * @param array $meta Optional. Used to set initial site options. * @param int $site_id Optional. Only relevant on multi-network installs. * @return mixed Returns WP_Error object on failure, int $blog_id on success */ function wpmu_create_blog($domain, $path, $title, $user_id, $meta = '', $site_id = 1) { $domain = preg_replace( '/\s+/', '', sanitize_user( $domain, true ) ); if ( is_subdomain_install() ) $domain = str_replace( '@', '', $domain ); $title = strip_tags( $title ); $user_id = (int) $user_id; if ( empty($path) ) $path = '/'; // Check if the domain has been used already. We should return an error message. if ( domain_exists($domain, $path, $site_id) ) return new WP_Error( 'blog_taken', __( 'Sorry, that site already exists!' ) ); if ( !defined('WP_INSTALLING') ) define( 'WP_INSTALLING', true ); if ( ! $blog_id = insert_blog($domain, $path, $site_id) ) return new WP_Error('insert_blog', __('Could not create site.')); switch_to_blog($blog_id); install_blog($blog_id, $title); wp_install_defaults($user_id); add_user_to_blog($blog_id, $user_id, 'administrator'); if ( is_array($meta) ) foreach ($meta as $key => $value) { if ( $key == 'public' || $key == 'archived' || $key == 'mature' || $key == 'spam' || $key == 'deleted' || $key == 'lang_id' ) update_blog_status( $blog_id, $key, $value ); else update_option( $key, $value ); } add_option( 'WPLANG', get_site_option( 'WPLANG' ) ); update_option( 'blog_public', (int)$meta['public'] ); if ( ! is_super_admin( $user_id ) && ! get_user_meta( $user_id, 'primary_blog', true ) ) update_user_meta( $user_id, 'primary_blog', $blog_id ); restore_current_blog(); do_action( 'wpmu_new_blog', $blog_id, $user_id, $domain, $path, $site_id, $meta ); return $blog_id; } /** * Notifies the network admin that a new site has been activated. * * Filter 'newblog_notify_siteadmin' to change the content of * the notification email. * * @since MU * * @param int $blog_id The new site's ID. * @return bool */ function newblog_notify_siteadmin( $blog_id, $deprecated = '' ) { if ( get_site_option( 'registrationnotification' ) != 'yes' ) return false; $email = get_site_option( 'admin_email' ); if ( is_email($email) == false ) return false; $options_site_url = esc_url(network_admin_url('settings.php')); switch_to_blog( $blog_id ); $blogname = get_option( 'blogname' ); $siteurl = site_url(); restore_current_blog(); $msg = sprintf( __( 'New Site: %1$s URL: %2$s Remote IP: %3$s Disable these notifications: %4$s' ), $blogname, $siteurl, $_SERVER['REMOTE_ADDR'], $options_site_url); $msg = apply_filters( 'newblog_notify_siteadmin', $msg ); wp_mail( $email, sprintf( __( 'New Site Registration: %s' ), $siteurl ), $msg ); return true; } /** * Notifies the network admin that a new user has been activated. * * Filter 'newuser_notify_siteadmin' to change the content of * the notification email. * * @since MU * @uses apply_filters() Filter newuser_notify_siteadmin to change the content of the email message * * @param int $user_id The new user's ID. * @return bool */ function newuser_notify_siteadmin( $user_id ) { if ( get_site_option( 'registrationnotification' ) != 'yes' ) return false; $email = get_site_option( 'admin_email' ); if ( is_email($email) == false ) return false; $user = get_userdata( $user_id ); $options_site_url = esc_url(network_admin_url('settings.php')); $msg = sprintf(__('New User: %1$s Remote IP: %2$s Disable these notifications: %3$s'), $user->user_login, $_SERVER['REMOTE_ADDR'], $options_site_url); $msg = apply_filters( 'newuser_notify_siteadmin', $msg, $user ); wp_mail( $email, sprintf(__('New User Registration: %s'), $user->user_login), $msg ); return true; } /** * Check whether a blogname is already taken. * * Used during the new site registration process to ensure * that each blogname is unique. * * @since MU * * @param string $domain The domain to be checked. * @param string $path The path to be checked. * @param int $site_id Optional. Relevant only on multi-network installs. * @return int */ function domain_exists($domain, $path, $site_id = 1) { global $wpdb; $result = $wpdb->get_var( $wpdb->prepare("SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s AND site_id = %d", $domain, $path, $site_id) ); return apply_filters( 'domain_exists', $result, $domain, $path, $site_id ); } /** * Store basic site info in the blogs table. * * This function creates a row in the wp_blogs table and returns * the new blog's ID. It is the first step in creating a new blog. * * @since MU * * @param string $domain The domain of the new site. * @param string $path The path of the new site. * @param int $site_id Unless you're running a multi-network install, be sure to set this value to 1. * @return int The ID of the new row */ function insert_blog($domain, $path, $site_id) { global $wpdb; $path = trailingslashit($path); $site_id = (int) $site_id; $result = $wpdb->insert( $wpdb->blogs, array('site_id' => $site_id, 'domain' => $domain, 'path' => $path, 'registered' => current_time('mysql')) ); if ( ! $result ) return false; refresh_blog_details($wpdb->insert_id); return $wpdb->insert_id; } /** * Install an empty blog. * * Creates the new blog tables and options. If calling this function * directly, be sure to use switch_to_blog() first, so that $wpdb * points to the new blog. * * @since MU * @uses make_db_current_silent() * @uses populate_roles() * * @param int $blog_id The value returned by insert_blog(). * @param string $blog_title The title of the new site. */ function install_blog($blog_id, $blog_title = '') { global $wpdb, $wp_roles, $current_site; // Cast for security $blog_id = (int) $blog_id; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); $wpdb->suppress_errors(); if ( $wpdb->get_results( "DESCRIBE {$wpdb->posts}" ) ) die( '<h1>' . __( 'Already Installed' ) . '</h1><p>' . __( 'You appear to have already installed WordPress. To reinstall please clear your old database tables first.' ) . '</p></body></html>' ); $wpdb->suppress_errors( false ); $url = get_blogaddress_by_id( $blog_id ); // Set everything up make_db_current_silent( 'blog' ); populate_options(); populate_roles(); $wp_roles->_init(); $url = untrailingslashit( $url ); update_option( 'siteurl', $url ); update_option( 'home', $url ); if ( get_site_option( 'ms_files_rewriting' ) ) update_option( 'upload_path', UPLOADBLOGSDIR . "/$blog_id/files" ); else update_option( 'upload_path', get_blog_option( $current_site->blog_id, 'upload_path' ) ); update_option( 'blogname', stripslashes( $blog_title ) ); update_option( 'admin_email', '' ); // remove all perms $table_prefix = $wpdb->get_blog_prefix(); delete_metadata( 'user', 0, $table_prefix . 'user_level', null, true ); // delete all delete_metadata( 'user', 0, $table_prefix . 'capabilities', null, true ); // delete all } /** * Set blog defaults. * * This function creates a row in the wp_blogs table. * * @since MU * @deprecated MU * @deprecated Use wp_install_defaults() * @uses wp_install_defaults() * * @param int $blog_id Ignored in this function. * @param int $user_id */ function install_blog_defaults($blog_id, $user_id) { global $wpdb; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); $wpdb->suppress_errors(); wp_install_defaults($user_id); $wpdb->suppress_errors( false ); } /** * Notify a user that her blog activation has been successful. * * Filter 'wpmu_welcome_notification' to disable or bypass. * * Filter 'update_welcome_email' and 'update_welcome_subject' to * modify the content and subject line of the notification email. * * @since MU * * @param int $blog_id * @param int $user_id * @param string $password * @param string $title The new blog's title * @param array $meta Optional. Not used in the default function, but is passed along to hooks for customization. * @return bool */ function wpmu_welcome_notification($blog_id, $user_id, $password, $title, $meta = '') { global $current_site; if ( !apply_filters('wpmu_welcome_notification', $blog_id, $user_id, $password, $title, $meta) ) return false; $welcome_email = stripslashes( get_site_option( 'welcome_email' ) ); if ( $welcome_email == false ) $welcome_email = stripslashes( __( 'Dear User, Your new SITE_NAME site has been successfully set up at: BLOG_URL You can log in to the administrator account with the following information: Username: USERNAME Password: PASSWORD Log in here: BLOG_URLwp-login.php We hope you enjoy your new site. Thanks! --The Team @ SITE_NAME' ) ); $url = get_blogaddress_by_id($blog_id); $user = get_userdata( $user_id ); $welcome_email = str_replace( 'SITE_NAME', $current_site->site_name, $welcome_email ); $welcome_email = str_replace( 'BLOG_TITLE', $title, $welcome_email ); $welcome_email = str_replace( 'BLOG_URL', $url, $welcome_email ); $welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email ); $welcome_email = str_replace( 'PASSWORD', $password, $welcome_email ); $welcome_email = apply_filters( 'update_welcome_email', $welcome_email, $blog_id, $user_id, $password, $title, $meta); $admin_email = get_site_option( 'admin_email' ); if ( $admin_email == '' ) $admin_email = 'support@' . $_SERVER['SERVER_NAME']; $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) ); $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n"; $message = $welcome_email; if ( empty( $current_site->site_name ) ) $current_site->site_name = 'WordPress'; $subject = apply_filters( 'update_welcome_subject', sprintf(__('New %1$s Site: %2$s'), $current_site->site_name, stripslashes( $title ) ) ); wp_mail($user->user_email, $subject, $message, $message_headers); return true; } /** * Notify a user that her account activation has been successful. * * Filter 'wpmu_welcome_user_notification' to disable or bypass. * * Filter 'update_welcome_user_email' and 'update_welcome_user_subject' to * modify the content and subject line of the notification email. * * @since MU * * @param int $user_id * @param string $password * @param array $meta Optional. Not used in the default function, but is passed along to hooks for customization. * @return bool */ function wpmu_welcome_user_notification($user_id, $password, $meta = '') { global $current_site; if ( !apply_filters('wpmu_welcome_user_notification', $user_id, $password, $meta) ) return false; $welcome_email = get_site_option( 'welcome_user_email' ); $user = get_userdata( $user_id ); $welcome_email = apply_filters( 'update_welcome_user_email', $welcome_email, $user_id, $password, $meta); $welcome_email = str_replace( 'SITE_NAME', $current_site->site_name, $welcome_email ); $welcome_email = str_replace( 'USERNAME', $user->user_login, $welcome_email ); $welcome_email = str_replace( 'PASSWORD', $password, $welcome_email ); $welcome_email = str_replace( 'LOGINLINK', wp_login_url(), $welcome_email ); $admin_email = get_site_option( 'admin_email' ); if ( $admin_email == '' ) $admin_email = 'support@' . $_SERVER['SERVER_NAME']; $from_name = get_site_option( 'site_name' ) == '' ? 'WordPress' : esc_html( get_site_option( 'site_name' ) ); $message_headers = "From: \"{$from_name}\" <{$admin_email}>\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n"; $message = $welcome_email; if ( empty( $current_site->site_name ) ) $current_site->site_name = 'WordPress'; $subject = apply_filters( 'update_welcome_user_subject', sprintf(__('New %1$s User: %2$s'), $current_site->site_name, $user->user_login) ); wp_mail($user->user_email, $subject, $message, $message_headers); return true; } /** * Get the current site info. * * Returns an object containing the ID, domain, path, and site_name * of the site being viewed. * * @since MU * * @return object */ function get_current_site() { global $current_site; return $current_site; } /** * Get a numeric user ID from either an email address or a login. * * @since MU * @uses is_email() * * @param string $string * @return int */ function get_user_id_from_string( $string ) { $user_id = 0; if ( is_email( $string ) ) { $user = get_user_by('email', $string); if ( $user ) $user_id = $user->ID; } elseif ( is_numeric( $string ) ) { $user_id = $string; } else { $user = get_user_by('login', $string); if ( $user ) $user_id = $user->ID; } return $user_id; } /** * Get a user's most recent post. * * Walks through each of a user's blogs to find the post with * the most recent post_date_gmt. * * @since MU * @uses get_blogs_of_user() * * @param int $user_id * @return array Contains the blog_id, post_id, post_date_gmt, and post_gmt_ts */ function get_most_recent_post_of_user( $user_id ) { global $wpdb; $user_blogs = get_blogs_of_user( (int) $user_id ); $most_recent_post = array(); // Walk through each blog and get the most recent post // published by $user_id foreach ( (array) $user_blogs as $blog ) { $prefix = $wpdb->get_blog_prefix( $blog->userblog_id ); $recent_post = $wpdb->get_row( $wpdb->prepare("SELECT ID, post_date_gmt FROM {$prefix}posts WHERE post_author = %d AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date_gmt DESC LIMIT 1", $user_id ), ARRAY_A); // Make sure we found a post if ( isset($recent_post['ID']) ) { $post_gmt_ts = strtotime($recent_post['post_date_gmt']); // If this is the first post checked or if this post is // newer than the current recent post, make it the new // most recent post. if ( !isset($most_recent_post['post_gmt_ts']) || ( $post_gmt_ts > $most_recent_post['post_gmt_ts'] ) ) { $most_recent_post = array( 'blog_id' => $blog->userblog_id, 'post_id' => $recent_post['ID'], 'post_date_gmt' => $recent_post['post_date_gmt'], 'post_gmt_ts' => $post_gmt_ts ); } } } return $most_recent_post; } // Misc functions /** * Get the size of a directory. * * A helper function that is used primarily to check whether * a blog has exceeded its allowed upload space. * * @since MU * @uses recurse_dirsize() * * @param string $directory * @return int */ function get_dirsize( $directory ) { $dirsize = get_transient( 'dirsize_cache' ); if ( is_array( $dirsize ) && isset( $dirsize[ $directory ][ 'size' ] ) ) return $dirsize[ $directory ][ 'size' ]; if ( false == is_array( $dirsize ) ) $dirsize = array(); $dirsize[ $directory ][ 'size' ] = recurse_dirsize( $directory ); set_transient( 'dirsize_cache', $dirsize, HOUR_IN_SECONDS ); return $dirsize[ $directory ][ 'size' ]; } /** * Get the size of a directory recursively. * * Used by get_dirsize() to get a directory's size when it contains * other directories. * * @since MU * * @param string $directory * @return int */ function recurse_dirsize( $directory ) { $size = 0; $directory = untrailingslashit( $directory ); if ( !file_exists($directory) || !is_dir( $directory ) || !is_readable( $directory ) ) return false; if ($handle = opendir($directory)) { while(($file = readdir($handle)) !== false) { $path = $directory.'/'.$file; if ($file != '.' && $file != '..') { if (is_file($path)) { $size += filesize($path); } elseif (is_dir($path)) { $handlesize = recurse_dirsize($path); if ($handlesize > 0) $size += $handlesize; } } } closedir($handle); } return $size; } /** * Check an array of MIME types against a whitelist. * * WordPress ships with a set of allowed upload filetypes, * which is defined in wp-includes/functions.php in * get_allowed_mime_types(). This function is used to filter * that list against the filetype whitelist provided by Multisite * Super Admins at wp-admin/network/settings.php. * * @since MU * * @param array $mimes * @return array */ function check_upload_mimes( $mimes ) { $site_exts = explode( ' ', get_site_option( 'upload_filetypes' ) ); foreach ( $site_exts as $ext ) { foreach ( $mimes as $ext_pattern => $mime ) { if ( $ext != '' && strpos( $ext_pattern, $ext ) !== false ) $site_mimes[$ext_pattern] = $mime; } } return $site_mimes; } /** * Update a blog's post count. * * WordPress MS stores a blog's post count as an option so as * to avoid extraneous COUNTs when a blog's details are fetched * with get_blog_details(). This function is called when posts * are published to make sure the count stays current. * * @since MU */ function update_posts_count( $deprecated = '' ) { global $wpdb; update_option( 'post_count', (int) $wpdb->get_var( "SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_status = 'publish' and post_type = 'post'" ) ); } /** * Logs user registrations. * * @since MU * * @param int $blog_id * @param int $user_id */ function wpmu_log_new_registrations( $blog_id, $user_id ) { global $wpdb; $user = get_userdata( (int) $user_id ); $wpdb->insert( $wpdb->registration_log, array('email' => $user->user_email, 'IP' => preg_replace( '/[^0-9., ]/', '',$_SERVER['REMOTE_ADDR'] ), 'blog_id' => $blog_id, 'date_registered' => current_time('mysql')) ); } /** * Maintains a canonical list of terms by syncing terms created for each blog with the global terms table. * * @since 3.0.0 * * @see term_id_filter * * @param int $term_id An ID for a term on the current blog. * @return int An ID from the global terms table mapped from $term_id. */ function global_terms( $term_id, $deprecated = '' ) { global $wpdb; static $global_terms_recurse = null; if ( !global_terms_enabled() ) return $term_id; // prevent a race condition $recurse_start = false; if ( $global_terms_recurse === null ) { $recurse_start = true; $global_terms_recurse = 1; } elseif ( 10 < $global_terms_recurse++ ) { return $term_id; } $term_id = intval( $term_id ); $c = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->terms WHERE term_id = %d", $term_id ) ); $global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE category_nicename = %s", $c->slug ) ); if ( $global_id == null ) { $used_global_id = $wpdb->get_var( $wpdb->prepare( "SELECT cat_ID FROM $wpdb->sitecategories WHERE cat_ID = %d", $c->term_id ) ); if ( null == $used_global_id ) { $wpdb->insert( $wpdb->sitecategories, array( 'cat_ID' => $term_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug ) ); $global_id = $wpdb->insert_id; if ( empty( $global_id ) ) return $term_id; } else { $max_global_id = $wpdb->get_var( "SELECT MAX(cat_ID) FROM $wpdb->sitecategories" ); $max_local_id = $wpdb->get_var( "SELECT MAX(term_id) FROM $wpdb->terms" ); $new_global_id = max( $max_global_id, $max_local_id ) + mt_rand( 100, 400 ); $wpdb->insert( $wpdb->sitecategories, array( 'cat_ID' => $new_global_id, 'cat_name' => $c->name, 'category_nicename' => $c->slug ) ); $global_id = $wpdb->insert_id; } } elseif ( $global_id != $term_id ) { $local_id = $wpdb->get_row( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE term_id = %d", $global_id ) ); if ( null != $local_id ) $local_id = global_terms( $local_id ); if ( 10 < $global_terms_recurse ) $global_id = $term_id; } if ( $global_id != $term_id ) { if ( get_option( 'default_category' ) == $term_id ) update_option( 'default_category', $global_id ); $wpdb->update( $wpdb->terms, array('term_id' => $global_id), array('term_id' => $term_id) ); $wpdb->update( $wpdb->term_taxonomy, array('term_id' => $global_id), array('term_id' => $term_id) ); $wpdb->update( $wpdb->term_taxonomy, array('parent' => $global_id), array('parent' => $term_id) ); clean_term_cache($term_id); } if( $recurse_start ) $global_terms_recurse = null; return $global_id; } /** * Ensure that the current site's domain is listed in the allowed redirect host list. * * @see wp_validate_redirect() * @since MU * * @return array The current site's domain */ function redirect_this_site( $deprecated = '' ) { global $current_site; return array( $current_site->domain ); } /** * Check whether an upload is too big. * * @since MU * * @param array $upload * @return mixed If the upload is under the size limit, $upload is returned. Otherwise returns an error message. */ function upload_is_file_too_big( $upload ) { if ( is_array( $upload ) == false || defined( 'WP_IMPORTING' ) || get_site_option( 'upload_space_check_disabled' ) ) return $upload; if ( strlen( $upload['bits'] ) > ( 1024 * get_site_option( 'fileupload_maxk', 1500 ) ) ) return sprintf( __( 'This file is too big. Files must be less than %d KB in size.' ) . '<br />', get_site_option( 'fileupload_maxk', 1500 )); return $upload; } /** * Add a nonce field to the signup page. * * @since MU * @uses wp_nonce_field() */ function signup_nonce_fields() { $id = mt_rand(); echo "<input type='hidden' name='signup_form_id' value='{$id}' />"; wp_nonce_field('signup_form_' . $id, '_signup_form', false); } /** * Process the signup nonce created in signup_nonce_fields(). * * @since MU * @uses wp_create_nonce() * * @param array $result * @return array */ function signup_nonce_check( $result ) { if ( !strpos( $_SERVER[ 'PHP_SELF' ], 'wp-signup.php' ) ) return $result; if ( wp_create_nonce('signup_form_' . $_POST[ 'signup_form_id' ]) != $_POST['_signup_form'] ) wp_die( __( 'Please try again.' ) ); return $result; } /** * Correct 404 redirects when NOBLOGREDIRECT is defined. * * @since MU */ function maybe_redirect_404() { global $current_site; if ( is_main_site() && is_404() && defined( 'NOBLOGREDIRECT' ) && ( $destination = apply_filters( 'blog_redirect_404', NOBLOGREDIRECT ) ) ) { if ( $destination == '%siteurl%' ) $destination = network_home_url(); wp_redirect( $destination ); exit(); } } /** * Add a new user to a blog by visiting /newbloguser/username/. * * This will only work when the user's details are saved as an option * keyed as 'new_user_x', where 'x' is the username of the user to be * added, as when a user is invited through the regular WP Add User interface. * * @since MU * @uses add_existing_user_to_blog() */ function maybe_add_existing_user_to_blog() { if ( false === strpos( $_SERVER[ 'REQUEST_URI' ], '/newbloguser/' ) ) return false; $parts = explode( '/', $_SERVER[ 'REQUEST_URI' ] ); $key = array_pop( $parts ); if ( $key == '' ) $key = array_pop( $parts ); $details = get_option( 'new_user_' . $key ); if ( !empty( $details ) ) delete_option( 'new_user_' . $key ); if ( empty( $details ) || is_wp_error( add_existing_user_to_blog( $details ) ) ) wp_die( sprintf(__('An error occurred adding you to this site. Back to the <a href="%s">homepage</a>.'), home_url() ) ); wp_die( sprintf( __( 'You have been added to this site. Please visit the <a href="%s">homepage</a> or <a href="%s">log in</a> using your username and password.' ), home_url(), admin_url() ), __( 'WordPress &rsaquo; Success' ) ); } /** * Add a user to a blog based on details from maybe_add_existing_user_to_blog(). * * @since MU * @uses add_user_to_blog() * * @param array $details */ function add_existing_user_to_blog( $details = false ) { global $blog_id; if ( is_array( $details ) ) { $result = add_user_to_blog( $blog_id, $details[ 'user_id' ], $details[ 'role' ] ); do_action( 'added_existing_user', $details[ 'user_id' ], $result ); } return $result; } /** * Add a newly created user to the appropriate blog * * @since MU * * @param int $user_id * @param string $email * @param array $meta */ function add_new_user_to_blog( $user_id, $email, $meta ) { global $current_site; if ( !empty( $meta[ 'add_to_blog' ] ) ) { $blog_id = $meta[ 'add_to_blog' ]; $role = $meta[ 'new_role' ]; remove_user_from_blog($user_id, $current_site->blog_id); // remove user from main blog. add_user_to_blog( $blog_id, $user_id, $role ); update_user_meta( $user_id, 'primary_blog', $blog_id ); } } /** * Correct From host on outgoing mail to match the site domain * * @since MU */ function fix_phpmailer_messageid( $phpmailer ) { global $current_site; $phpmailer->Hostname = $current_site->domain; } /** * Check to see whether a user is marked as a spammer, based on username * * @since MU * @uses get_current_user_id() * @uses get_user_id_from_string() * * @param string $username * @return bool */ function is_user_spammy( $username = 0 ) { if ( $username == 0 ) { $user_id = get_current_user_id(); } else { $user_id = get_user_id_from_string( $username ); } $u = get_userdata( $user_id ); return ( isset( $u->spam ) && $u->spam == 1 ); } /** * Update this blog's 'public' setting in the global blogs table. * * Public blogs have a setting of 1, private blogs are 0. * * @since MU * @uses update_blog_status() * * @param int $old_value * @param int $value The new public value * @return bool */ function update_blog_public( $old_value, $value ) { global $wpdb; do_action('update_blog_public'); update_blog_status( $wpdb->blogid, 'public', (int) $value ); } add_action('update_option_blog_public', 'update_blog_public', 10, 2); /** * Get the "dashboard blog", the blog where users without a blog edit their profile data. * * @since MU * @uses get_blog_details() * * @return int */ function get_dashboard_blog() { if ( $blog = get_site_option( 'dashboard_blog' ) ) return get_blog_details( $blog ); return get_blog_details( $GLOBALS['current_site']->blog_id ); } /** * Check whether a usermeta key has to do with the current blog. * * @since MU * @uses wp_get_current_user() * * @param string $key * @param int $user_id Optional. Defaults to current user. * @param int $blog_id Optional. Defaults to current blog. * @return bool */ function is_user_option_local( $key, $user_id = 0, $blog_id = 0 ) { global $wpdb; $current_user = wp_get_current_user(); if ( $user_id == 0 ) $user_id = $current_user->ID; if ( $blog_id == 0 ) $blog_id = $wpdb->blogid; $local_key = $wpdb->get_blog_prefix( $blog_id ) . $key; if ( isset( $current_user->$local_key ) ) return true; return false; } /** * Check whether users can self-register, based on Network settings. * * @since MU * * @return bool */ function users_can_register_signup_filter() { $registration = get_site_option('registration'); if ( $registration == 'all' || $registration == 'user' ) return true; return false; } add_filter('option_users_can_register', 'users_can_register_signup_filter'); /** * Ensure that the welcome message is not empty. Currently unused. * * @since MU * * @param string $text * @return string */ function welcome_user_msg_filter( $text ) { if ( !$text ) { remove_filter( 'site_option_welcome_user_email', 'welcome_user_msg_filter' ); $text = __( 'Dear User, Your new account is set up. You can log in with the following information: Username: USERNAME Password: PASSWORD LOGINLINK Thanks! --The Team @ SITE_NAME' ); update_site_option( 'welcome_user_email', $text ); } return $text; } add_filter( 'site_option_welcome_user_email', 'welcome_user_msg_filter' ); /** * Whether to force SSL on content. * * @since 2.8.5 * * @param string|bool $force * @return bool True if forced, false if not forced. */ function force_ssl_content( $force = '' ) { static $forced_content; if ( '' != $force ) { $old_forced = $forced_content; $forced_content = $force; return $old_forced; } return $forced_content; } /** * Formats a URL to use https. * * Useful as a filter. * * @since 2.8.5 * * @param string URL * @return string URL with https as the scheme */ function filter_SSL( $url ) { if ( ! is_string( $url ) ) return get_bloginfo( 'url' ); // Return home blog url with proper scheme if ( force_ssl_content() && is_ssl() ) $url = set_url_scheme( $url, 'https' ); return $url; } /** * Schedule update of the network-wide counts for the current network. * * @since 3.1.0 */ function wp_schedule_update_network_counts() { if ( !is_main_site() ) return; if ( !wp_next_scheduled('update_network_counts') && !defined('WP_INSTALLING') ) wp_schedule_event(time(), 'twicedaily', 'update_network_counts'); } /** * Update the network-wide counts for the current network. * * @since 3.1.0 */ function wp_update_network_counts() { global $wpdb; $count = $wpdb->get_var( $wpdb->prepare("SELECT COUNT(blog_id) as c FROM $wpdb->blogs WHERE site_id = %d AND spam = '0' AND deleted = '0' and archived = '0'", $wpdb->siteid) ); update_site_option( 'blog_count', $count ); $count = $wpdb->get_var( "SELECT COUNT(ID) as c FROM $wpdb->users WHERE spam = '0' AND deleted = '0'" ); update_site_option( 'user_count', $count ); } /** * Returns the space used by the current blog. * * @since 3.5.0 * * @return int Used space in megabytes */ function get_space_used() { // Allow for an alternative way of tracking storage space used $space_used = apply_filters( 'pre_get_space_used', false ); if ( false === $space_used ) { $upload_dir = wp_upload_dir(); $space_used = get_dirsize( $upload_dir['basedir'] ) / 1024 / 1024; } return $space_used; } /** * Returns the upload quota for the current blog. * * @since MU * * @return int Quota in megabytes */ function get_space_allowed() { $space_allowed = get_option( 'blog_upload_space' ); if ( ! is_numeric( $space_allowed ) ) $space_allowed = get_site_option( 'blog_upload_space' ); if ( empty( $space_allowed ) || ! is_numeric( $space_allowed ) ) $space_allowed = 50; return $space_allowed; } /** * Determines if there is any upload space left in the current blog's quota. * * @since 3.0.0 * * @return int of upload space available in bytes */ function get_upload_space_available() { $space_allowed = get_space_allowed() * 1024 * 1024; if ( get_site_option( 'upload_space_check_disabled' ) ) return $space_allowed; $space_used = get_space_used() * 1024 * 1024; if ( ( $space_allowed - $space_used ) <= 0 ) return 0; return $space_allowed - $space_used; } /** * Determines if there is any upload space left in the current blog's quota. * * @since 3.0.0 * @return bool True if space is available, false otherwise. */ function is_upload_space_available() { if ( get_site_option( 'upload_space_check_disabled' ) ) return true; return (bool) get_upload_space_available(); } /** * @since 3.0.0 * * @return int of upload size limit in bytes */ function upload_size_limit_filter( $size ) { $fileupload_maxk = 1024 * get_site_option( 'fileupload_maxk', 1500 ); if ( get_site_option( 'upload_space_check_disabled' ) ) return min( $size, $fileupload_maxk ); return min( $size, $fileupload_maxk, get_upload_space_available() ); }
zyblog
trunk/zyblog/wp-includes/ms-functions.php
PHP
asf20
63,555
<?php /** * WordPress Translation API * * @package WordPress * @subpackage i18n */ /** * Gets the current locale. * * If the locale is set, then it will filter the locale in the 'locale' filter * hook and return the value. * * If the locale is not set already, then the WPLANG constant is used if it is * defined. Then it is filtered through the 'locale' filter hook and the value * for the locale global set and the locale is returned. * * The process to get the locale should only be done once, but the locale will * always be filtered using the 'locale' hook. * * @since 1.5.0 * @uses apply_filters() Calls 'locale' hook on locale value. * @uses $locale Gets the locale stored in the global. * * @return string The locale of the blog or from the 'locale' hook. */ function get_locale() { global $locale; if ( isset( $locale ) ) return apply_filters( 'locale', $locale ); // WPLANG is defined in wp-config. if ( defined( 'WPLANG' ) ) $locale = WPLANG; // If multisite, check options. if ( is_multisite() ) { // Don't check blog option when installing. if ( defined( 'WP_INSTALLING' ) || ( false === $ms_locale = get_option( 'WPLANG' ) ) ) $ms_locale = get_site_option('WPLANG'); if ( $ms_locale !== false ) $locale = $ms_locale; } if ( empty( $locale ) ) $locale = 'en_US'; return apply_filters( 'locale', $locale ); } /** * Retrieves the translation of $text. If there is no translation, or * the domain isn't loaded, the original text is returned. * * @see __() Don't use translate() directly, use __() * @since 2.2.0 * @uses apply_filters() Calls 'gettext' on domain translated text * with the untranslated text as second parameter. * * @param string $text Text to translate. * @param string $domain Domain to retrieve the translated text. * @return string Translated text */ function translate( $text, $domain = 'default' ) { $translations = get_translations_for_domain( $domain ); return apply_filters( 'gettext', $translations->translate( $text ), $text, $domain ); } function before_last_bar( $string ) { $last_bar = strrpos( $string, '|' ); if ( false == $last_bar ) return $string; else return substr( $string, 0, $last_bar ); } function translate_with_gettext_context( $text, $context, $domain = 'default' ) { $translations = get_translations_for_domain( $domain ); return apply_filters( 'gettext_with_context', $translations->translate( $text, $context ), $text, $context, $domain ); } /** * Retrieves the translation of $text. If there is no translation, or * the domain isn't loaded, the original text is returned. * * @see translate() An alias of translate() * @since 2.1.0 * * @param string $text Text to translate * @param string $domain Optional. Domain to retrieve the translated text * @return string Translated text */ function __( $text, $domain = 'default' ) { return translate( $text, $domain ); } /** * Retrieves the translation of $text and escapes it for safe use in an attribute. * If there is no translation, or the domain isn't loaded, the original text is returned. * * @see translate() An alias of translate() * @see esc_attr() * @since 2.8.0 * * @param string $text Text to translate * @param string $domain Optional. Domain to retrieve the translated text * @return string Translated text */ function esc_attr__( $text, $domain = 'default' ) { return esc_attr( translate( $text, $domain ) ); } /** * Retrieves the translation of $text and escapes it for safe use in HTML output. * If there is no translation, or the domain isn't loaded, the original text is returned. * * @see translate() An alias of translate() * @see esc_html() * @since 2.8.0 * * @param string $text Text to translate * @param string $domain Optional. Domain to retrieve the translated text * @return string Translated text */ function esc_html__( $text, $domain = 'default' ) { return esc_html( translate( $text, $domain ) ); } /** * Displays the returned translated text from translate(). * * @see translate() Echoes returned translate() string * @since 1.2.0 * * @param string $text Text to translate * @param string $domain Optional. Domain to retrieve the translated text */ function _e( $text, $domain = 'default' ) { echo translate( $text, $domain ); } /** * Displays translated text that has been escaped for safe use in an attribute. * * @see translate() Echoes returned translate() string * @see esc_attr() * @since 2.8.0 * * @param string $text Text to translate * @param string $domain Optional. Domain to retrieve the translated text */ function esc_attr_e( $text, $domain = 'default' ) { echo esc_attr( translate( $text, $domain ) ); } /** * Displays translated text that has been escaped for safe use in HTML output. * * @see translate() Echoes returned translate() string * @see esc_html() * @since 2.8.0 * * @param string $text Text to translate * @param string $domain Optional. Domain to retrieve the translated text */ function esc_html_e( $text, $domain = 'default' ) { echo esc_html( translate( $text, $domain ) ); } /** * Retrieve translated string with gettext context * * Quite a few times, there will be collisions with similar translatable text * found in more than two places but with different translated context. * * By including the context in the pot file translators can translate the two * strings differently. * * @since 2.8.0 * * @param string $text Text to translate * @param string $context Context information for the translators * @param string $domain Optional. Domain to retrieve the translated text * @return string Translated context string without pipe */ function _x( $text, $context, $domain = 'default' ) { return translate_with_gettext_context( $text, $context, $domain ); } /** * Displays translated string with gettext context * * @see _x * @since 3.0.0 * * @param string $text Text to translate * @param string $context Context information for the translators * @param string $domain Optional. Domain to retrieve the translated text * @return string Translated context string without pipe */ function _ex( $text, $context, $domain = 'default' ) { echo _x( $text, $context, $domain ); } function esc_attr_x( $single, $context, $domain = 'default' ) { return esc_attr( translate_with_gettext_context( $single, $context, $domain ) ); } function esc_html_x( $single, $context, $domain = 'default' ) { return esc_html( translate_with_gettext_context( $single, $context, $domain ) ); } /** * Retrieve the plural or single form based on the amount. * * If the domain is not set in the $l10n list, then a comparison will be made * and either $plural or $single parameters returned. * * If the domain does exist, then the parameters $single, $plural, and $number * will first be passed to the domain's ngettext method. Then it will be passed * to the 'ngettext' filter hook along with the same parameters. The expected * type will be a string. * * @since 2.8.0 * @uses $l10n Gets list of domain translated string (gettext_reader) objects * @uses apply_filters() Calls 'ngettext' hook on domains text returned, * along with $single, $plural, and $number parameters. Expected to return string. * * @param string $single The text that will be used if $number is 1 * @param string $plural The text that will be used if $number is not 1 * @param int $number The number to compare against to use either $single or $plural * @param string $domain Optional. The domain identifier the text should be retrieved in * @return string Either $single or $plural translated text */ function _n( $single, $plural, $number, $domain = 'default' ) { $translations = get_translations_for_domain( $domain ); $translation = $translations->translate_plural( $single, $plural, $number ); return apply_filters( 'ngettext', $translation, $single, $plural, $number, $domain ); } /** * A hybrid of _n() and _x(). It supports contexts and plurals. * * @see _n() * @see _x() * */ function _nx($single, $plural, $number, $context, $domain = 'default') { $translations = get_translations_for_domain( $domain ); $translation = $translations->translate_plural( $single, $plural, $number, $context ); return apply_filters( 'ngettext_with_context', $translation, $single, $plural, $number, $context, $domain ); } /** * Register plural strings in POT file, but don't translate them. * * Used when you want to keep structures with translatable plural strings and * use them later. * * Example: * $messages = array( * 'post' => _n_noop('%s post', '%s posts'), * 'page' => _n_noop('%s pages', '%s pages') * ); * ... * $message = $messages[$type]; * $usable_text = sprintf( translate_nooped_plural( $message, $count ), $count ); * * @since 2.5 * @param string $singular Single form to be i18ned * @param string $plural Plural form to be i18ned * @param string $domain Optional. The domain identifier the text will be retrieved in * @return array array($singular, $plural) */ function _n_noop( $singular, $plural, $domain = null ) { return array( 0 => $singular, 1 => $plural, 'singular' => $singular, 'plural' => $plural, 'context' => null, 'domain' => $domain ); } /** * Register plural strings with context in POT file, but don't translate them. * * @see _n_noop() */ function _nx_noop( $singular, $plural, $context, $domain = null ) { return array( 0 => $singular, 1 => $plural, 2 => $context, 'singular' => $singular, 'plural' => $plural, 'context' => $context, 'domain' => $domain ); } /** * Translate the result of _n_noop() or _nx_noop() * * @since 3.1 * @param array $nooped_plural Array with singular, plural and context keys, usually the result of _n_noop() or _nx_noop() * @param int $count Number of objects * @param string $domain Optional. The domain identifier the text should be retrieved in. If $nooped_plural contains * a domain passed to _n_noop() or _nx_noop(), it will override this value. */ function translate_nooped_plural( $nooped_plural, $count, $domain = 'default' ) { if ( $nooped_plural['domain'] ) $domain = $nooped_plural['domain']; if ( $nooped_plural['context'] ) return _nx( $nooped_plural['singular'], $nooped_plural['plural'], $count, $nooped_plural['context'], $domain ); else return _n( $nooped_plural['singular'], $nooped_plural['plural'], $count, $domain ); } /** * Loads a MO file into the domain $domain. * * If the domain already exists, the translations will be merged. If both * sets have the same string, the translation from the original value will be taken. * * On success, the .mo file will be placed in the $l10n global by $domain * and will be a MO object. * * @since 1.5.0 * @uses $l10n Gets list of domain translated string objects * * @param string $domain Unique identifier for retrieving translated strings * @param string $mofile Path to the .mo file * @return bool True on success, false on failure */ function load_textdomain( $domain, $mofile ) { global $l10n; $plugin_override = apply_filters( 'override_load_textdomain', false, $domain, $mofile ); if ( true == $plugin_override ) { return true; } do_action( 'load_textdomain', $domain, $mofile ); $mofile = apply_filters( 'load_textdomain_mofile', $mofile, $domain ); if ( !is_readable( $mofile ) ) return false; $mo = new MO(); if ( !$mo->import_from_file( $mofile ) ) return false; if ( isset( $l10n[$domain] ) ) $mo->merge_with( $l10n[$domain] ); $l10n[$domain] = &$mo; return true; } /** * Unloads translations for a domain * * @since 3.0.0 * @param string $domain Textdomain to be unloaded * @return bool Whether textdomain was unloaded */ function unload_textdomain( $domain ) { global $l10n; $plugin_override = apply_filters( 'override_unload_textdomain', false, $domain ); if ( $plugin_override ) return true; do_action( 'unload_textdomain', $domain ); if ( isset( $l10n[$domain] ) ) { unset( $l10n[$domain] ); return true; } return false; } /** * Loads default translated strings based on locale. * * Loads the .mo file in WP_LANG_DIR constant path from WordPress root. The * translated (.mo) file is named based on the locale. * * @since 1.5.0 */ function load_default_textdomain() { $locale = get_locale(); load_textdomain( 'default', WP_LANG_DIR . "/$locale.mo" ); if ( ( is_multisite() || ( defined( 'WP_INSTALLING_NETWORK' ) && WP_INSTALLING_NETWORK ) ) && ! file_exists( WP_LANG_DIR . "/admin-$locale.mo" ) ) { load_textdomain( 'default', WP_LANG_DIR . "/ms-$locale.mo" ); return; } if ( is_admin() || ( defined( 'WP_REPAIRING' ) && WP_REPAIRING ) ) load_textdomain( 'default', WP_LANG_DIR . "/admin-$locale.mo" ); if ( is_network_admin() || ( defined( 'WP_INSTALLING_NETWORK' ) && WP_INSTALLING_NETWORK ) ) load_textdomain( 'default', WP_LANG_DIR . "/admin-network-$locale.mo" ); } /** * Loads the plugin's translated strings. * * If the path is not given then it will be the root of the plugin directory. * The .mo file should be named based on the domain with a dash, and then the locale exactly. * * @since 1.5.0 * * @param string $domain Unique identifier for retrieving translated strings * @param string $abs_rel_path Optional. Relative path to ABSPATH of a folder, * where the .mo file resides. Deprecated, but still functional until 2.7 * @param string $plugin_rel_path Optional. Relative path to WP_PLUGIN_DIR. This is the preferred argument to use. It takes precedence over $abs_rel_path */ function load_plugin_textdomain( $domain, $abs_rel_path = false, $plugin_rel_path = false ) { $locale = apply_filters( 'plugin_locale', get_locale(), $domain ); if ( false !== $plugin_rel_path ) { $path = WP_PLUGIN_DIR . '/' . trim( $plugin_rel_path, '/' ); } else if ( false !== $abs_rel_path ) { _deprecated_argument( __FUNCTION__, '2.7' ); $path = ABSPATH . trim( $abs_rel_path, '/' ); } else { $path = WP_PLUGIN_DIR; } $mofile = $path . '/'. $domain . '-' . $locale . '.mo'; return load_textdomain( $domain, $mofile ); } /** * Load the translated strings for a plugin residing in the mu-plugins dir. * * @since 3.0.0 * * @param string $domain Unique identifier for retrieving translated strings * @param string $mu_plugin_rel_path Relative to WPMU_PLUGIN_DIR directory in which * the MO file resides. Defaults to empty string. */ function load_muplugin_textdomain( $domain, $mu_plugin_rel_path = '' ) { $locale = apply_filters( 'plugin_locale', get_locale(), $domain ); $path = WPMU_PLUGIN_DIR . '/' . ltrim( $mu_plugin_rel_path, '/' ); load_textdomain( $domain, trailingslashit( $path ) . "$domain-$locale.mo" ); } /** * Loads the theme's translated strings. * * If the current locale exists as a .mo file in the theme's root directory, it * will be included in the translated strings by the $domain. * * The .mo files must be named based on the locale exactly. * * @since 1.5.0 * * @param string $domain Unique identifier for retrieving translated strings */ function load_theme_textdomain( $domain, $path = false ) { $locale = apply_filters( 'theme_locale', get_locale(), $domain ); if ( ! $path ) $path = get_template_directory(); // Load the textdomain from the Theme provided location, or theme directory first $mofile = "{$path}/{$locale}.mo"; if ( $loaded = load_textdomain($domain, $mofile) ) return $loaded; // Else, load textdomain from the Language directory $mofile = WP_LANG_DIR . "/themes/{$domain}-{$locale}.mo"; return load_textdomain($domain, $mofile); } /** * Loads the child themes translated strings. * * If the current locale exists as a .mo file in the child themes root directory, it * will be included in the translated strings by the $domain. * * The .mo files must be named based on the locale exactly. * * @since 2.9.0 * * @param string $domain Unique identifier for retrieving translated strings */ function load_child_theme_textdomain( $domain, $path = false ) { if ( ! $path ) $path = get_stylesheet_directory(); return load_theme_textdomain( $domain, $path ); } /** * Returns the Translations instance for a domain. If there isn't one, * returns empty Translations instance. * * @param string $domain * @return object A Translation instance */ function get_translations_for_domain( $domain ) { global $l10n; if ( !isset( $l10n[$domain] ) ) { $l10n[$domain] = new NOOP_Translations; } return $l10n[$domain]; } /** * Whether there are translations for the domain * * @since 3.0.0 * @param string $domain * @return bool Whether there are translations */ function is_textdomain_loaded( $domain ) { global $l10n; return isset( $l10n[$domain] ); } /** * Translates role name. Since the role names are in the database and * not in the source there are dummy gettext calls to get them into the POT * file and this function properly translates them back. * * The before_last_bar() call is needed, because older installs keep the roles * using the old context format: 'Role name|User role' and just skipping the * content after the last bar is easier than fixing them in the DB. New installs * won't suffer from that problem. */ function translate_user_role( $name ) { return translate_with_gettext_context( before_last_bar($name), 'User role' ); } /** * Get all available languages based on the presence of *.mo files in a given directory. The default directory is WP_LANG_DIR. * * @since 3.0.0 * * @param string $dir A directory in which to search for language files. The default directory is WP_LANG_DIR. * @return array Array of language codes or an empty array if no languages are present. Language codes are formed by stripping the .mo extension from the language file names. */ function get_available_languages( $dir = null ) { $languages = array(); foreach( (array)glob( ( is_null( $dir) ? WP_LANG_DIR : $dir ) . '/*.mo' ) as $lang_file ) { $lang_file = basename($lang_file, '.mo'); if ( 0 !== strpos( $lang_file, 'continents-cities' ) && 0 !== strpos( $lang_file, 'ms-' ) && 0 !== strpos( $lang_file, 'admin-' )) $languages[] = $lang_file; } return $languages; }
zyblog
trunk/zyblog/wp-includes/l10n.php
PHP
asf20
18,149
<?php /** * BackPress styles procedural API. * * @package BackPress * @since r79 */ /** * Display styles that are in the queue or part of $handles. * * @since r79 * @uses do_action() Calls 'wp_print_styles' hook. * @global object $wp_styles The WP_Styles object for printing styles. * * @param array|bool $handles Styles to be printed. An empty array prints the queue, * an array with one string prints that style, and an array of strings prints those styles. * @return bool True on success, false on failure. */ function wp_print_styles( $handles = false ) { if ( '' === $handles ) // for wp_head $handles = false; if ( ! $handles ) do_action( 'wp_print_styles' ); global $wp_styles; if ( ! is_a( $wp_styles, 'WP_Styles' ) ) { if ( ! did_action( 'init' ) ) _doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ), '<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>init</code>' ), '3.3' ); if ( !$handles ) return array(); // No need to instantiate if nothing is there. else $wp_styles = new WP_Styles(); } return $wp_styles->do_items( $handles ); } /** * Adds extra CSS. * * Works only if the stylesheet has already been added. * Accepts a string $data containing the CSS. If two or more CSS code blocks are * added to the same stylesheet $handle, they will be printed in the order * they were added, i.e. the latter added styles can redeclare the previous. * * @since 3.3.0 * @see WP_Scripts::add_inline_style() */ function wp_add_inline_style( $handle, $data ) { global $wp_styles; if ( ! is_a( $wp_styles, 'WP_Styles' ) ) { if ( ! did_action( 'init' ) ) _doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ), '<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>init</code>' ), '3.3' ); $wp_styles = new WP_Styles(); } return $wp_styles->add_inline_style( $handle, $data ); } /** * Register CSS style file. * * @since r79 * @see WP_Styles::add() For additional information. * @global object $wp_styles The WP_Styles object for printing styles. * @link http://www.w3.org/TR/CSS2/media.html#media-types List of CSS media types. * * @param string $handle Name of the stylesheet. * @param string|bool $src Path to the stylesheet from the root directory of WordPress. Example: '/css/mystyle.css'. * @param array $deps Array of handles of any stylesheet that this stylesheet depends on. * (Stylesheets that must be loaded before this stylesheet.) Pass an empty array if there are no dependencies. * @param string|bool $ver String specifying the stylesheet version number. Set to null to disable. * Used to ensure that the correct version is sent to the client regardless of caching. * @param string $media The media for which this stylesheet has been defined. */ function wp_register_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' ) { global $wp_styles; if ( ! is_a( $wp_styles, 'WP_Styles' ) ) { if ( ! did_action( 'init' ) ) _doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ), '<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>init</code>' ), '3.3' ); $wp_styles = new WP_Styles(); } $wp_styles->add( $handle, $src, $deps, $ver, $media ); } /** * Remove a registered CSS file. * * @since r79 * @see WP_Styles::remove() For additional information. * @global object $wp_styles The WP_Styles object for printing styles. * * @param string $handle Name of the stylesheet. */ function wp_deregister_style( $handle ) { global $wp_styles; if ( ! is_a( $wp_styles, 'WP_Styles' ) ) { if ( ! did_action( 'init' ) ) _doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ), '<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>init</code>' ), '3.3' ); $wp_styles = new WP_Styles(); } $wp_styles->remove( $handle ); } /** * Enqueue a CSS style file. * * Registers the style if src provided (does NOT overwrite) and enqueues. * * @since r79 * @see WP_Styles::add(), WP_Styles::enqueue() * @global object $wp_styles The WP_Styles object for printing styles. * @link http://www.w3.org/TR/CSS2/media.html#media-types List of CSS media types. * * @param string $handle Name of the stylesheet. * @param string|bool $src Path to the stylesheet from the root directory of WordPress. Example: '/css/mystyle.css'. * @param array $deps Array of handles (names) of any stylesheet that this stylesheet depends on. * (Stylesheets that must be loaded before this stylesheet.) Pass an empty array if there are no dependencies. * @param string|bool $ver String specifying the stylesheet version number, if it has one. This parameter * is used to ensure that the correct version is sent to the client regardless of caching, and so should be included * if a version number is available and makes sense for the stylesheet. * @param string $media The media for which this stylesheet has been defined. */ function wp_enqueue_style( $handle, $src = false, $deps = array(), $ver = false, $media = 'all' ) { global $wp_styles; if ( ! is_a( $wp_styles, 'WP_Styles' ) ) { if ( ! did_action( 'init' ) ) _doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ), '<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>init</code>' ), '3.3' ); $wp_styles = new WP_Styles(); } if ( $src ) { $_handle = explode('?', $handle); $wp_styles->add( $_handle[0], $src, $deps, $ver, $media ); } $wp_styles->enqueue( $handle ); } /** * Remove an enqueued style. * * @since WP 3.1 * @see WP_Styles::dequeue() For parameter information. */ function wp_dequeue_style( $handle ) { global $wp_styles; if ( ! is_a( $wp_styles, 'WP_Styles' ) ) { if ( ! did_action( 'init' ) ) _doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ), '<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>init</code>' ), '3.3' ); $wp_styles = new WP_Styles(); } $wp_styles->dequeue( $handle ); } /** * Check whether style has been added to WordPress Styles. * * By default, checks if the style has been enqueued. You can also * pass 'registered' to $list, to see if the style is registered, * and you can check processing statuses with 'to_do' and 'done'. * * @since WP unknown; BP unknown * @global object $wp_styles The WP_Styles object for printing styles. * * @param string $handle Name of the stylesheet. * @param string $list Optional. Defaults to 'enqueued'. Values are * 'registered', 'enqueued' (or 'queue'), 'to_do', and 'done'. * @return bool Whether style is in the list. */ function wp_style_is( $handle, $list = 'enqueued' ) { global $wp_styles; if ( ! is_a( $wp_styles, 'WP_Styles' ) ) { if ( ! did_action( 'init' ) ) _doing_it_wrong( __FUNCTION__, sprintf( __( 'Scripts and styles should not be registered or enqueued until the %1$s, %2$s, or %3$s hooks.' ), '<code>wp_enqueue_scripts</code>', '<code>admin_enqueue_scripts</code>', '<code>init</code>' ), '3.3' ); $wp_styles = new WP_Styles(); } return (bool) $wp_styles->query( $handle, $list ); }
zyblog
trunk/zyblog/wp-includes/functions.wp-styles.php
PHP
asf20
7,620
<?php /** * BackPress Scripts enqueue. * * These classes were refactored from the WordPress WP_Scripts and WordPress * script enqueue API. * * @package BackPress * @since r16 */ /** * BackPress Scripts enqueue class. * * @package BackPress * @uses WP_Dependencies * @since r16 */ class WP_Scripts extends WP_Dependencies { var $base_url; // Full URL with trailing slash var $content_url; var $default_version; var $in_footer = array(); var $concat = ''; var $concat_version = ''; var $do_concat = false; var $print_html = ''; var $print_code = ''; var $ext_handles = ''; var $ext_version = ''; var $default_dirs; function __construct() { $this->init(); add_action( 'init', array( $this, 'init' ), 0 ); } function init() { do_action_ref_array( 'wp_default_scripts', array(&$this) ); } /** * Prints scripts * * Prints the scripts passed to it or the print queue. Also prints all necessary dependencies. * * @param mixed $handles (optional) Scripts to be printed. (void) prints queue, (string) prints that script, (array of strings) prints those scripts. * @param int $group (optional) If scripts were queued in groups prints this group number. * @return array Scripts that have been printed */ function print_scripts( $handles = false, $group = false ) { return $this->do_items( $handles, $group ); } // Deprecated since 3.3, see print_extra_script() function print_scripts_l10n( $handle, $echo = true ) { _deprecated_function( __FUNCTION__, '3.3', 'print_extra_script()' ); return $this->print_extra_script( $handle, $echo ); } function print_extra_script( $handle, $echo = true ) { if ( !$output = $this->get_data( $handle, 'data' ) ) return; if ( !$echo ) return $output; echo "<script type='text/javascript'>\n"; // CDATA and type='text/javascript' is not needed for HTML 5 echo "/* <![CDATA[ */\n"; echo "$output\n"; echo "/* ]]> */\n"; echo "</script>\n"; return true; } function do_item( $handle, $group = false ) { if ( !parent::do_item($handle) ) return false; if ( 0 === $group && $this->groups[$handle] > 0 ) { $this->in_footer[] = $handle; return false; } if ( false === $group && in_array($handle, $this->in_footer, true) ) $this->in_footer = array_diff( $this->in_footer, (array) $handle ); if ( null === $this->registered[$handle]->ver ) $ver = ''; else $ver = $this->registered[$handle]->ver ? $this->registered[$handle]->ver : $this->default_version; if ( isset($this->args[$handle]) ) $ver = $ver ? $ver . '&amp;' . $this->args[$handle] : $this->args[$handle]; $src = $this->registered[$handle]->src; if ( $this->do_concat ) { $srce = apply_filters( 'script_loader_src', $src, $handle ); if ( $this->in_default_dir($srce) ) { $this->print_code .= $this->print_extra_script( $handle, false ); $this->concat .= "$handle,"; $this->concat_version .= "$handle$ver"; return true; } else { $this->ext_handles .= "$handle,"; $this->ext_version .= "$handle$ver"; } } $this->print_extra_script( $handle ); if ( !preg_match('|^(https?:)?//|', $src) && ! ( $this->content_url && 0 === strpos($src, $this->content_url) ) ) { $src = $this->base_url . $src; } if ( !empty($ver) ) $src = add_query_arg('ver', $ver, $src); $src = esc_url( apply_filters( 'script_loader_src', $src, $handle ) ); if ( $this->do_concat ) $this->print_html .= "<script type='text/javascript' src='$src'></script>\n"; else echo "<script type='text/javascript' src='$src'></script>\n"; return true; } /** * Localizes a script * * Localizes only if the script has already been added */ function localize( $handle, $object_name, $l10n ) { if ( is_array($l10n) && isset($l10n['l10n_print_after']) ) { // back compat, preserve the code in 'l10n_print_after' if present $after = $l10n['l10n_print_after']; unset($l10n['l10n_print_after']); } foreach ( (array) $l10n as $key => $value ) { if ( !is_scalar($value) ) continue; $l10n[$key] = html_entity_decode( (string) $value, ENT_QUOTES, 'UTF-8'); } $script = "var $object_name = " . json_encode($l10n) . ';'; if ( !empty($after) ) $script .= "\n$after;"; $data = $this->get_data( $handle, 'data' ); if ( !empty( $data ) ) $script = "$data\n$script"; return $this->add_data( $handle, 'data', $script ); } function set_group( $handle, $recursion, $group = false ) { if ( $this->registered[$handle]->args === 1 ) $grp = 1; else $grp = (int) $this->get_data( $handle, 'group' ); if ( false !== $group && $grp > $group ) $grp = $group; return parent::set_group( $handle, $recursion, $grp ); } function all_deps( $handles, $recursion = false, $group = false ) { $r = parent::all_deps( $handles, $recursion ); if ( !$recursion ) $this->to_do = apply_filters( 'print_scripts_array', $this->to_do ); return $r; } function do_head_items() { $this->do_items(false, 0); return $this->done; } function do_footer_items() { $this->do_items(false, 1); return $this->done; } function in_default_dir($src) { if ( ! $this->default_dirs ) return true; if ( 0 === strpos( $src, '/wp-includes/js/l10n' ) ) return false; foreach ( (array) $this->default_dirs as $test ) { if ( 0 === strpos($src, $test) ) return true; } return false; } function reset() { $this->do_concat = false; $this->print_code = ''; $this->concat = ''; $this->concat_version = ''; $this->print_html = ''; $this->ext_version = ''; $this->ext_handles = ''; } }
zyblog
trunk/zyblog/wp-includes/class.wp-scripts.php
PHP
asf20
5,598
<?php /** * Sets up the default filters and actions for most * of the WordPress hooks. * * If you need to remove a default hook, this file will * give you the priority for which to use to remove the * hook. * * Not all of the default hooks are found in default-filters.php * * @package WordPress */ // Strip, trim, kses, special chars for string saves foreach ( array( 'pre_term_name', 'pre_comment_author_name', 'pre_link_name', 'pre_link_target', 'pre_link_rel', 'pre_user_display_name', 'pre_user_first_name', 'pre_user_last_name', 'pre_user_nickname' ) as $filter ) { add_filter( $filter, 'sanitize_text_field' ); add_filter( $filter, 'wp_filter_kses' ); add_filter( $filter, '_wp_specialchars', 30 ); } // Strip, kses, special chars for string display foreach ( array( 'term_name', 'comment_author_name', 'link_name', 'link_target', 'link_rel', 'user_display_name', 'user_first_name', 'user_last_name', 'user_nickname' ) as $filter ) { if ( is_admin() ) { // These are expensive. Run only on admin pages for defense in depth. add_filter( $filter, 'sanitize_text_field' ); add_filter( $filter, 'wp_kses_data' ); } add_filter( $filter, '_wp_specialchars', 30 ); } // Kses only for textarea saves foreach ( array( 'pre_term_description', 'pre_link_description', 'pre_link_notes', 'pre_user_description' ) as $filter ) { add_filter( $filter, 'wp_filter_kses' ); } // Kses only for textarea admin displays if ( is_admin() ) { foreach ( array( 'term_description', 'link_description', 'link_notes', 'user_description' ) as $filter ) { add_filter( $filter, 'wp_kses_data' ); } add_filter( 'comment_text', 'wp_kses_post' ); } // Email saves foreach ( array( 'pre_comment_author_email', 'pre_user_email' ) as $filter ) { add_filter( $filter, 'trim' ); add_filter( $filter, 'sanitize_email' ); add_filter( $filter, 'wp_filter_kses' ); } // Email admin display foreach ( array( 'comment_author_email', 'user_email' ) as $filter ) { add_filter( $filter, 'sanitize_email' ); if ( is_admin() ) add_filter( $filter, 'wp_kses_data' ); } // Save URL foreach ( array( 'pre_comment_author_url', 'pre_user_url', 'pre_link_url', 'pre_link_image', 'pre_link_rss', 'pre_post_guid' ) as $filter ) { add_filter( $filter, 'wp_strip_all_tags' ); add_filter( $filter, 'esc_url_raw' ); add_filter( $filter, 'wp_filter_kses' ); } // Display URL foreach ( array( 'user_url', 'link_url', 'link_image', 'link_rss', 'comment_url', 'post_guid' ) as $filter ) { if ( is_admin() ) add_filter( $filter, 'wp_strip_all_tags' ); add_filter( $filter, 'esc_url' ); if ( is_admin() ) add_filter( $filter, 'wp_kses_data' ); } // Slugs foreach ( array( 'pre_term_slug' ) as $filter ) { add_filter( $filter, 'sanitize_title' ); } // Keys foreach ( array( 'pre_post_type', 'pre_post_status', 'pre_post_comment_status', 'pre_post_ping_status' ) as $filter ) { add_filter( $filter, 'sanitize_key' ); } // Mime types add_filter( 'pre_post_mime_type', 'sanitize_mime_type' ); add_filter( 'post_mime_type', 'sanitize_mime_type' ); // Places to balance tags on input foreach ( array( 'content_save_pre', 'excerpt_save_pre', 'comment_save_pre', 'pre_comment_content' ) as $filter ) { add_filter( $filter, 'balanceTags', 50 ); } // Format strings for display. foreach ( array( 'comment_author', 'term_name', 'link_name', 'link_description', 'link_notes', 'bloginfo', 'wp_title', 'widget_title' ) as $filter ) { add_filter( $filter, 'wptexturize' ); add_filter( $filter, 'convert_chars' ); add_filter( $filter, 'esc_html' ); } // Format WordPress foreach ( array( 'the_content', 'the_title' ) as $filter ) add_filter( $filter, 'capital_P_dangit', 11 ); add_filter( 'comment_text', 'capital_P_dangit', 31 ); // Format titles foreach ( array( 'single_post_title', 'single_cat_title', 'single_tag_title', 'single_month_title', 'nav_menu_attr_title', 'nav_menu_description' ) as $filter ) { add_filter( $filter, 'wptexturize' ); add_filter( $filter, 'strip_tags' ); } // Format text area for display. foreach ( array( 'term_description' ) as $filter ) { add_filter( $filter, 'wptexturize' ); add_filter( $filter, 'convert_chars' ); add_filter( $filter, 'wpautop' ); add_filter( $filter, 'shortcode_unautop'); } // Format for RSS foreach ( array( 'term_name_rss' ) as $filter ) { add_filter( $filter, 'convert_chars' ); } // Pre save hierarchy add_filter( 'wp_insert_post_parent', 'wp_check_post_hierarchy_for_loops', 10, 2 ); add_filter( 'wp_update_term_parent', 'wp_check_term_hierarchy_for_loops', 10, 3 ); // Display filters add_filter( 'the_title', 'wptexturize' ); add_filter( 'the_title', 'convert_chars' ); add_filter( 'the_title', 'trim' ); add_filter( 'the_content', 'wptexturize' ); add_filter( 'the_content', 'convert_smilies' ); add_filter( 'the_content', 'convert_chars' ); add_filter( 'the_content', 'wpautop' ); add_filter( 'the_content', 'shortcode_unautop' ); add_filter( 'the_content', 'prepend_attachment' ); add_filter( 'the_excerpt', 'wptexturize' ); add_filter( 'the_excerpt', 'convert_smilies' ); add_filter( 'the_excerpt', 'convert_chars' ); add_filter( 'the_excerpt', 'wpautop' ); add_filter( 'the_excerpt', 'shortcode_unautop'); add_filter( 'get_the_excerpt', 'wp_trim_excerpt' ); add_filter( 'comment_text', 'wptexturize' ); add_filter( 'comment_text', 'convert_chars' ); add_filter( 'comment_text', 'make_clickable', 9 ); add_filter( 'comment_text', 'force_balance_tags', 25 ); add_filter( 'comment_text', 'convert_smilies', 20 ); add_filter( 'comment_text', 'wpautop', 30 ); add_filter( 'comment_excerpt', 'convert_chars' ); add_filter( 'list_cats', 'wptexturize' ); add_filter( 'wp_sprintf', 'wp_sprintf_l', 10, 2 ); // RSS filters add_filter( 'the_title_rss', 'strip_tags' ); add_filter( 'the_title_rss', 'ent2ncr', 8 ); add_filter( 'the_title_rss', 'esc_html' ); add_filter( 'the_content_rss', 'ent2ncr', 8 ); add_filter( 'the_excerpt_rss', 'convert_chars' ); add_filter( 'the_excerpt_rss', 'ent2ncr', 8 ); add_filter( 'comment_author_rss', 'ent2ncr', 8 ); add_filter( 'comment_text_rss', 'ent2ncr', 8 ); add_filter( 'comment_text_rss', 'esc_html' ); add_filter( 'bloginfo_rss', 'ent2ncr', 8 ); add_filter( 'the_author', 'ent2ncr', 8 ); // Misc filters add_filter( 'option_ping_sites', 'privacy_ping_filter' ); add_filter( 'option_blog_charset', '_wp_specialchars' ); // IMPORTANT: This must not be wp_specialchars() or esc_html() or it'll cause an infinite loop add_filter( 'option_home', '_config_wp_home' ); add_filter( 'option_siteurl', '_config_wp_siteurl' ); add_filter( 'tiny_mce_before_init', '_mce_set_direction' ); add_filter( 'pre_kses', 'wp_pre_kses_less_than' ); add_filter( 'sanitize_title', 'sanitize_title_with_dashes', 10, 3 ); add_action( 'check_comment_flood', 'check_comment_flood_db', 10, 3 ); add_filter( 'comment_flood_filter', 'wp_throttle_comment_flood', 10, 3 ); add_filter( 'pre_comment_content', 'wp_rel_nofollow', 15 ); add_filter( 'comment_email', 'antispambot' ); add_filter( 'option_tag_base', '_wp_filter_taxonomy_base' ); add_filter( 'option_category_base', '_wp_filter_taxonomy_base' ); add_filter( 'the_posts', '_close_comments_for_old_posts', 10, 2); add_filter( 'comments_open', '_close_comments_for_old_post', 10, 2 ); add_filter( 'pings_open', '_close_comments_for_old_post', 10, 2 ); add_filter( 'editable_slug', 'urldecode' ); add_filter( 'editable_slug', 'esc_textarea' ); add_filter( 'nav_menu_meta_box_object', '_wp_nav_menu_meta_box_object' ); // Actions add_action( 'wp_head', 'wp_enqueue_scripts', 1 ); add_action( 'wp_head', 'feed_links', 2 ); add_action( 'wp_head', 'feed_links_extra', 3 ); add_action( 'wp_head', 'rsd_link' ); add_action( 'wp_head', 'wlwmanifest_link' ); add_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0 ); add_action( 'wp_head', 'locale_stylesheet' ); add_action( 'publish_future_post', 'check_and_publish_future_post', 10, 1 ); add_action( 'wp_head', 'noindex', 1 ); add_action( 'wp_head', 'wp_print_styles', 8 ); add_action( 'wp_head', 'wp_print_head_scripts', 9 ); add_action( 'wp_head', 'wp_generator' ); add_action( 'wp_head', 'rel_canonical' ); add_action( 'wp_footer', 'wp_print_footer_scripts', 20 ); add_action( 'wp_head', 'wp_shortlink_wp_head', 10, 0 ); add_action( 'template_redirect', 'wp_shortlink_header', 11, 0 ); add_action( 'wp_print_footer_scripts', '_wp_footer_scripts' ); add_action( 'init', 'check_theme_switched', 99 ); add_action( 'after_switch_theme', '_wp_sidebars_changed' ); if ( isset( $_GET['replytocom'] ) ) add_action( 'wp_head', 'wp_no_robots' ); // Login actions add_action( 'login_head', 'wp_print_head_scripts', 9 ); add_action( 'login_footer', 'wp_print_footer_scripts', 20 ); add_action( 'login_init', 'send_frame_options_header', 10, 0 ); // Feed Generator Tags foreach ( array( 'rss2_head', 'commentsrss2_head', 'rss_head', 'rdf_header', 'atom_head', 'comments_atom_head', 'opml_head', 'app_head' ) as $action ) { add_action( $action, 'the_generator' ); } // WP Cron if ( !defined( 'DOING_CRON' ) ) add_action( 'init', 'wp_cron' ); // 2 Actions 2 Furious add_action( 'do_feed_rdf', 'do_feed_rdf', 10, 1 ); add_action( 'do_feed_rss', 'do_feed_rss', 10, 1 ); add_action( 'do_feed_rss2', 'do_feed_rss2', 10, 1 ); add_action( 'do_feed_atom', 'do_feed_atom', 10, 1 ); add_action( 'do_pings', 'do_all_pings', 10, 1 ); add_action( 'do_robots', 'do_robots' ); add_action( 'set_comment_cookies', 'wp_set_comment_cookies', 10, 2 ); add_action( 'sanitize_comment_cookies', 'sanitize_comment_cookies' ); add_action( 'admin_print_scripts', 'print_head_scripts', 20 ); add_action( 'admin_print_footer_scripts', '_wp_footer_scripts' ); add_action( 'admin_print_styles', 'print_admin_styles', 20 ); add_action( 'init', 'smilies_init', 5 ); add_action( 'plugins_loaded', 'wp_maybe_load_widgets', 0 ); add_action( 'plugins_loaded', 'wp_maybe_load_embeds', 0 ); add_action( 'shutdown', 'wp_ob_end_flush_all', 1 ); add_action( 'pre_post_update', 'wp_save_post_revision' ); add_action( 'publish_post', '_publish_post_hook', 5, 1 ); add_action( 'transition_post_status', '_transition_post_status', 5, 3 ); add_action( 'transition_post_status', '_update_term_count_on_transition_post_status', 10, 3 ); add_action( 'comment_form', 'wp_comment_form_unfiltered_html_nonce' ); add_action( 'wp_scheduled_delete', 'wp_scheduled_delete' ); add_action( 'wp_scheduled_auto_draft_delete', 'wp_delete_auto_drafts' ); add_action( 'admin_init', 'send_frame_options_header', 10, 0 ); add_action( 'importer_scheduled_cleanup', 'wp_delete_attachment' ); add_action( 'upgrader_scheduled_cleanup', 'wp_delete_attachment' ); add_action( 'welcome_panel', 'wp_welcome_panel' ); // Navigation menu actions add_action( 'delete_post', '_wp_delete_post_menu_item' ); add_action( 'delete_term', '_wp_delete_tax_menu_item' ); add_action( 'transition_post_status', '_wp_auto_add_pages_to_menu', 10, 3 ); // Post Thumbnail CSS class filtering add_action( 'begin_fetch_post_thumbnail_html', '_wp_post_thumbnail_class_filter_add' ); add_action( 'end_fetch_post_thumbnail_html', '_wp_post_thumbnail_class_filter_remove' ); // Redirect Old Slugs add_action( 'template_redirect', 'wp_old_slug_redirect' ); add_action( 'post_updated', 'wp_check_for_changed_slugs', 12, 3 ); // Nonce check for Post Previews add_action( 'init', '_show_post_preview' ); // Timezone add_filter( 'pre_option_gmt_offset','wp_timezone_override_offset' ); // Admin Color Schemes add_action( 'admin_init', 'register_admin_color_schemes', 1); add_action( 'admin_color_scheme_picker', 'admin_color_scheme_picker' ); // If the upgrade hasn't run yet, assume link manager is used. add_filter( 'default_option_link_manager_enabled', '__return_true' ); // This option no longer exists; tell plugins we always support auto-embedding. add_filter( 'default_option_embed_autourls', '__return_true' ); unset($filter, $action);
zyblog
trunk/zyblog/wp-includes/default-filters.php
PHP
asf20
14,040
<?php /** * RSS 1 RDF Feed Template for displaying RSS 1 Posts feed. * * @package WordPress */ header('Content-Type: ' . feed_content_type('rdf') . '; charset=' . get_option('blog_charset'), true); $more = 1; echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?> <rdf:RDF xmlns="http://purl.org/rss/1.0/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:content="http://purl.org/rss/1.0/modules/content/" <?php do_action('rdf_ns'); ?> > <channel rdf:about="<?php bloginfo_rss("url") ?>"> <title><?php bloginfo_rss('name'); wp_title_rss(); ?></title> <link><?php bloginfo_rss('url') ?></link> <description><?php bloginfo_rss('description') ?></description> <dc:date><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT'), false); ?></dc:date> <sy:updatePeriod><?php echo apply_filters( 'rss_update_period', 'hourly' ); ?></sy:updatePeriod> <sy:updateFrequency><?php echo apply_filters( 'rss_update_frequency', '1' ); ?></sy:updateFrequency> <sy:updateBase>2000-01-01T12:00+00:00</sy:updateBase> <?php do_action('rdf_header'); ?> <items> <rdf:Seq> <?php while (have_posts()): the_post(); ?> <rdf:li rdf:resource="<?php the_permalink_rss() ?>"/> <?php endwhile; ?> </rdf:Seq> </items> </channel> <?php rewind_posts(); while (have_posts()): the_post(); ?> <item rdf:about="<?php the_permalink_rss() ?>"> <title><?php the_title_rss() ?></title> <link><?php the_permalink_rss() ?></link> <dc:date><?php echo mysql2date('Y-m-d\TH:i:s\Z', $post->post_date_gmt, false); ?></dc:date> <dc:creator><?php the_author() ?></dc:creator> <?php the_category_rss('rdf') ?> <?php if (get_option('rss_use_excerpt')) : ?> <description><?php the_excerpt_rss() ?></description> <?php else : ?> <description><?php the_excerpt_rss() ?></description> <content:encoded><![CDATA[<?php the_content_feed('rdf') ?>]]></content:encoded> <?php endif; ?> <?php do_action('rdf_item'); ?> </item> <?php endwhile; ?> </rdf:RDF>
zyblog
trunk/zyblog/wp-includes/feed-rdf.php
PHP
asf20
2,122
<?php /** * A class for displaying various tree-like structures. * * Extend the Walker class to use it, see examples at the below. Child classes * do not need to implement all of the abstract methods in the class. The child * only needs to implement the methods that are needed. Also, the methods are * not strictly abstract in that the parameter definition needs to be followed. * The child classes can have additional parameters. * * @package WordPress * @since 2.1.0 * @abstract */ class Walker { /** * What the class handles. * * @since 2.1.0 * @var string * @access public */ var $tree_type; /** * DB fields to use. * * @since 2.1.0 * @var array * @access protected */ var $db_fields; /** * Max number of pages walked by the paged walker * * @since 2.7.0 * @var int * @access protected */ var $max_pages = 1; /** * Starts the list before the elements are added. * * Additional parameters are used in child classes. The args parameter holds * additional values that may be used with the child class methods. This * method is called at the start of the output list. * * @since 2.1.0 * @abstract * * @param string $output Passed by reference. Used to append additional content. */ function start_lvl( &$output, $depth = 0, $args = array() ) {} /** * Ends the list of after the elements are added. * * Additional parameters are used in child classes. The args parameter holds * additional values that may be used with the child class methods. This * method finishes the list at the end of output of the elements. * * @since 2.1.0 * @abstract * * @param string $output Passed by reference. Used to append additional content. */ function end_lvl( &$output, $depth = 0, $args = array() ) {} /** * Start the element output. * * Additional parameters are used in child classes. The args parameter holds * additional values that may be used with the child class methods. Includes * the element output also. * * @since 2.1.0 * @abstract * * @param string $output Passed by reference. Used to append additional content. */ function start_el( &$output, $object, $depth, $args, $current_object_id = 0 ) {} /** * Ends the element output, if needed. * * Additional parameters are used in child classes. The args parameter holds * additional values that may be used with the child class methods. * * @since 2.1.0 * @abstract * * @param string $output Passed by reference. Used to append additional content. */ function end_el( &$output, $object, $depth = 0, $args = array() ) {} /** * Traverse elements to create list from elements. * * Display one element if the element doesn't have any children otherwise, * display the element and its children. Will only traverse up to the max * depth and no ignore elements under that depth. It is possible to set the * max depth to include all depths, see walk() method. * * This method shouldn't be called directly, use the walk() method instead. * * @since 2.5.0 * * @param object $element Data object * @param array $children_elements List of elements to continue traversing. * @param int $max_depth Max depth to traverse. * @param int $depth Depth of current element. * @param array $args * @param string $output Passed by reference. Used to append additional content. * @return null Null on failure with no changes to parameters. */ function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) { if ( !$element ) return; $id_field = $this->db_fields['id']; //display this element if ( is_array( $args[0] ) ) $args[0]['has_children'] = ! empty( $children_elements[$element->$id_field] ); $cb_args = array_merge( array(&$output, $element, $depth), $args); call_user_func_array(array($this, 'start_el'), $cb_args); $id = $element->$id_field; // descend only when the depth is right and there are childrens for this element if ( ($max_depth == 0 || $max_depth > $depth+1 ) && isset( $children_elements[$id]) ) { foreach( $children_elements[ $id ] as $child ){ if ( !isset($newlevel) ) { $newlevel = true; //start the child delimiter $cb_args = array_merge( array(&$output, $depth), $args); call_user_func_array(array($this, 'start_lvl'), $cb_args); } $this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output ); } unset( $children_elements[ $id ] ); } if ( isset($newlevel) && $newlevel ){ //end the child delimiter $cb_args = array_merge( array(&$output, $depth), $args); call_user_func_array(array($this, 'end_lvl'), $cb_args); } //end this element $cb_args = array_merge( array(&$output, $element, $depth), $args); call_user_func_array(array($this, 'end_el'), $cb_args); } /** * Display array of elements hierarchically. * * It is a generic function which does not assume any existing order of * elements. max_depth = -1 means flatly display every element. max_depth = * 0 means display all levels. max_depth > 0 specifies the number of * display levels. * * @since 2.1.0 * * @param array $elements * @param int $max_depth * @return string */ function walk( $elements, $max_depth) { $args = array_slice(func_get_args(), 2); $output = ''; if ($max_depth < -1) //invalid parameter return $output; if (empty($elements)) //nothing to walk return $output; $id_field = $this->db_fields['id']; $parent_field = $this->db_fields['parent']; // flat display if ( -1 == $max_depth ) { $empty_array = array(); foreach ( $elements as $e ) $this->display_element( $e, $empty_array, 1, 0, $args, $output ); return $output; } /* * need to display in hierarchical order * separate elements into two buckets: top level and children elements * children_elements is two dimensional array, eg. * children_elements[10][] contains all sub-elements whose parent is 10. */ $top_level_elements = array(); $children_elements = array(); foreach ( $elements as $e) { if ( 0 == $e->$parent_field ) $top_level_elements[] = $e; else $children_elements[ $e->$parent_field ][] = $e; } /* * when none of the elements is top level * assume the first one must be root of the sub elements */ if ( empty($top_level_elements) ) { $first = array_slice( $elements, 0, 1 ); $root = $first[0]; $top_level_elements = array(); $children_elements = array(); foreach ( $elements as $e) { if ( $root->$parent_field == $e->$parent_field ) $top_level_elements[] = $e; else $children_elements[ $e->$parent_field ][] = $e; } } foreach ( $top_level_elements as $e ) $this->display_element( $e, $children_elements, $max_depth, 0, $args, $output ); /* * if we are displaying all levels, and remaining children_elements is not empty, * then we got orphans, which should be displayed regardless */ if ( ( $max_depth == 0 ) && count( $children_elements ) > 0 ) { $empty_array = array(); foreach ( $children_elements as $orphans ) foreach( $orphans as $op ) $this->display_element( $op, $empty_array, 1, 0, $args, $output ); } return $output; } /** * paged_walk() - produce a page of nested elements * * Given an array of hierarchical elements, the maximum depth, a specific page number, * and number of elements per page, this function first determines all top level root elements * belonging to that page, then lists them and all of their children in hierarchical order. * * @package WordPress * @since 2.7 * @param int $max_depth = 0 means display all levels; $max_depth > 0 specifies the number of display levels. * @param int $page_num the specific page number, beginning with 1. * @return XHTML of the specified page of elements */ function paged_walk( $elements, $max_depth, $page_num, $per_page ) { /* sanity check */ if ( empty($elements) || $max_depth < -1 ) return ''; $args = array_slice( func_get_args(), 4 ); $output = ''; $id_field = $this->db_fields['id']; $parent_field = $this->db_fields['parent']; $count = -1; if ( -1 == $max_depth ) $total_top = count( $elements ); if ( $page_num < 1 || $per_page < 0 ) { // No paging $paging = false; $start = 0; if ( -1 == $max_depth ) $end = $total_top; $this->max_pages = 1; } else { $paging = true; $start = ( (int)$page_num - 1 ) * (int)$per_page; $end = $start + $per_page; if ( -1 == $max_depth ) $this->max_pages = ceil($total_top / $per_page); } // flat display if ( -1 == $max_depth ) { if ( !empty($args[0]['reverse_top_level']) ) { $elements = array_reverse( $elements ); $oldstart = $start; $start = $total_top - $end; $end = $total_top - $oldstart; } $empty_array = array(); foreach ( $elements as $e ) { $count++; if ( $count < $start ) continue; if ( $count >= $end ) break; $this->display_element( $e, $empty_array, 1, 0, $args, $output ); } return $output; } /* * separate elements into two buckets: top level and children elements * children_elements is two dimensional array, eg. * children_elements[10][] contains all sub-elements whose parent is 10. */ $top_level_elements = array(); $children_elements = array(); foreach ( $elements as $e) { if ( 0 == $e->$parent_field ) $top_level_elements[] = $e; else $children_elements[ $e->$parent_field ][] = $e; } $total_top = count( $top_level_elements ); if ( $paging ) $this->max_pages = ceil($total_top / $per_page); else $end = $total_top; if ( !empty($args[0]['reverse_top_level']) ) { $top_level_elements = array_reverse( $top_level_elements ); $oldstart = $start; $start = $total_top - $end; $end = $total_top - $oldstart; } if ( !empty($args[0]['reverse_children']) ) { foreach ( $children_elements as $parent => $children ) $children_elements[$parent] = array_reverse( $children ); } foreach ( $top_level_elements as $e ) { $count++; //for the last page, need to unset earlier children in order to keep track of orphans if ( $end >= $total_top && $count < $start ) $this->unset_children( $e, $children_elements ); if ( $count < $start ) continue; if ( $count >= $end ) break; $this->display_element( $e, $children_elements, $max_depth, 0, $args, $output ); } if ( $end >= $total_top && count( $children_elements ) > 0 ) { $empty_array = array(); foreach ( $children_elements as $orphans ) foreach( $orphans as $op ) $this->display_element( $op, $empty_array, 1, 0, $args, $output ); } return $output; } function get_number_of_root_elements( $elements ){ $num = 0; $parent_field = $this->db_fields['parent']; foreach ( $elements as $e) { if ( 0 == $e->$parent_field ) $num++; } return $num; } // unset all the children for a given top level element function unset_children( $e, &$children_elements ){ if ( !$e || !$children_elements ) return; $id_field = $this->db_fields['id']; $id = $e->$id_field; if ( !empty($children_elements[$id]) && is_array($children_elements[$id]) ) foreach ( (array) $children_elements[$id] as $child ) $this->unset_children( $child, $children_elements ); if ( isset($children_elements[$id]) ) unset( $children_elements[$id] ); } }
zyblog
trunk/zyblog/wp-includes/class-wp-walker.php
PHP
asf20
11,510
<?php /** * These functions can be replaced via plugins. If plugins do not redefine these * functions, then these will be used instead. * * @package WordPress */ if ( !function_exists('wp_set_current_user') ) : /** * Changes the current user by ID or name. * * Set $id to null and specify a name if you do not know a user's ID. * * Some WordPress functionality is based on the current user and not based on * the signed in user. Therefore, it opens the ability to edit and perform * actions on users who aren't signed in. * * @since 2.0.3 * @global object $current_user The current user object which holds the user data. * @uses do_action() Calls 'set_current_user' hook after setting the current user. * * @param int $id User ID * @param string $name User's username * @return WP_User Current user User object */ function wp_set_current_user($id, $name = '') { global $current_user; if ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->ID ) ) return $current_user; $current_user = new WP_User( $id, $name ); setup_userdata( $current_user->ID ); do_action('set_current_user'); return $current_user; } endif; if ( !function_exists('wp_get_current_user') ) : /** * Retrieve the current user object. * * @since 2.0.3 * * @return WP_User Current user WP_User object */ function wp_get_current_user() { global $current_user; get_currentuserinfo(); return $current_user; } endif; if ( !function_exists('get_currentuserinfo') ) : /** * Populate global variables with information about the currently logged in user. * * Will set the current user, if the current user is not set. The current user * will be set to the logged in person. If no user is logged in, then it will * set the current user to 0, which is invalid and won't have any permissions. * * @since 0.71 * @uses $current_user Checks if the current user is set * @uses wp_validate_auth_cookie() Retrieves current logged in user. * * @return bool|null False on XMLRPC Request and invalid auth cookie. Null when current user set */ function get_currentuserinfo() { global $current_user; if ( ! empty( $current_user ) ) { if ( $current_user instanceof WP_User ) return; // Upgrade stdClass to WP_User if ( is_object( $current_user ) && isset( $current_user->ID ) ) { $cur_id = $current_user->ID; $current_user = null; wp_set_current_user( $cur_id ); return; } // $current_user has a junk value. Force to WP_User with ID 0. $current_user = null; wp_set_current_user( 0 ); return false; } if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) { wp_set_current_user( 0 ); return false; } if ( ! $user = wp_validate_auth_cookie() ) { if ( is_blog_admin() || is_network_admin() || empty( $_COOKIE[LOGGED_IN_COOKIE] ) || !$user = wp_validate_auth_cookie( $_COOKIE[LOGGED_IN_COOKIE], 'logged_in' ) ) { wp_set_current_user( 0 ); return false; } } wp_set_current_user( $user ); } endif; if ( !function_exists('get_userdata') ) : /** * Retrieve user info by user ID. * * @since 0.71 * * @param int $user_id User ID * @return bool|object False on failure, WP_User object on success */ function get_userdata( $user_id ) { return get_user_by( 'id', $user_id ); } endif; if ( !function_exists('get_user_by') ) : /** * Retrieve user info by a given field * * @since 2.8.0 * * @param string $field The field to retrieve the user with. id | slug | email | login * @param int|string $value A value for $field. A user ID, slug, email address, or login name. * @return bool|object False on failure, WP_User object on success */ function get_user_by( $field, $value ) { $userdata = WP_User::get_data_by( $field, $value ); if ( !$userdata ) return false; $user = new WP_User; $user->init( $userdata ); return $user; } endif; if ( !function_exists('cache_users') ) : /** * Retrieve info for user lists to prevent multiple queries by get_userdata() * * @since 3.0.0 * * @param array $user_ids User ID numbers list */ function cache_users( $user_ids ) { global $wpdb; $clean = _get_non_cached_ids( $user_ids, 'users' ); if ( empty( $clean ) ) return; $list = implode( ',', $clean ); $users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" ); $ids = array(); foreach ( $users as $user ) { update_user_caches( $user ); $ids[] = $user->ID; } update_meta_cache( 'user', $ids ); } endif; if ( !function_exists( 'wp_mail' ) ) : /** * Send mail, similar to PHP's mail * * A true return value does not automatically mean that the user received the * email successfully. It just only means that the method used was able to * process the request without any errors. * * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from * creating a from address like 'Name <email@address.com>' when both are set. If * just 'wp_mail_from' is set, then just the email address will be used with no * name. * * The default content type is 'text/plain' which does not allow using HTML. * However, you can set the content type of the email by using the * 'wp_mail_content_type' filter. * * The default charset is based on the charset used on the blog. The charset can * be set using the 'wp_mail_charset' filter. * * @since 1.2.1 * @uses apply_filters() Calls 'wp_mail' hook on an array of all of the parameters. * @uses apply_filters() Calls 'wp_mail_from' hook to get the from email address. * @uses apply_filters() Calls 'wp_mail_from_name' hook to get the from address name. * @uses apply_filters() Calls 'wp_mail_content_type' hook to get the email content type. * @uses apply_filters() Calls 'wp_mail_charset' hook to get the email charset * @uses do_action_ref_array() Calls 'phpmailer_init' hook on the reference to * phpmailer object. * @uses PHPMailer * * @param string|array $to Array or comma-separated list of email addresses to send message. * @param string $subject Email subject * @param string $message Message contents * @param string|array $headers Optional. Additional headers. * @param string|array $attachments Optional. Files to attach. * @return bool Whether the email contents were sent successfully. */ function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) { // Compact the input, apply the filters, and extract them back out extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ) ); if ( !is_array($attachments) ) $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) ); global $phpmailer; // (Re)create it, if it's gone missing if ( !is_object( $phpmailer ) || !is_a( $phpmailer, 'PHPMailer' ) ) { require_once ABSPATH . WPINC . '/class-phpmailer.php'; require_once ABSPATH . WPINC . '/class-smtp.php'; $phpmailer = new PHPMailer( true ); } // Headers if ( empty( $headers ) ) { $headers = array(); } else { if ( !is_array( $headers ) ) { // Explode the headers out, so this function can take both // string headers and an array of headers. $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) ); } else { $tempheaders = $headers; } $headers = array(); $cc = array(); $bcc = array(); // If it's actually got contents if ( !empty( $tempheaders ) ) { // Iterate through the raw headers foreach ( (array) $tempheaders as $header ) { if ( strpos($header, ':') === false ) { if ( false !== stripos( $header, 'boundary=' ) ) { $parts = preg_split('/boundary=/i', trim( $header ) ); $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) ); } continue; } // Explode them out list( $name, $content ) = explode( ':', trim( $header ), 2 ); // Cleanup crew $name = trim( $name ); $content = trim( $content ); switch ( strtolower( $name ) ) { // Mainly for legacy -- process a From: header if it's there case 'from': if ( strpos($content, '<' ) !== false ) { // So... making my life hard again? $from_name = substr( $content, 0, strpos( $content, '<' ) - 1 ); $from_name = str_replace( '"', '', $from_name ); $from_name = trim( $from_name ); $from_email = substr( $content, strpos( $content, '<' ) + 1 ); $from_email = str_replace( '>', '', $from_email ); $from_email = trim( $from_email ); } else { $from_email = trim( $content ); } break; case 'content-type': if ( strpos( $content, ';' ) !== false ) { list( $type, $charset ) = explode( ';', $content ); $content_type = trim( $type ); if ( false !== stripos( $charset, 'charset=' ) ) { $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset ) ); } elseif ( false !== stripos( $charset, 'boundary=' ) ) { $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset ) ); $charset = ''; } } else { $content_type = trim( $content ); } break; case 'cc': $cc = array_merge( (array) $cc, explode( ',', $content ) ); break; case 'bcc': $bcc = array_merge( (array) $bcc, explode( ',', $content ) ); break; default: // Add it to our grand headers array $headers[trim( $name )] = trim( $content ); break; } } } } // Empty out the values that may be set $phpmailer->ClearAddresses(); $phpmailer->ClearAllRecipients(); $phpmailer->ClearAttachments(); $phpmailer->ClearBCCs(); $phpmailer->ClearCCs(); $phpmailer->ClearCustomHeaders(); $phpmailer->ClearReplyTos(); // From email and name // If we don't have a name from the input headers if ( !isset( $from_name ) ) $from_name = 'WordPress'; /* If we don't have an email from the input headers default to wordpress@$sitename * Some hosts will block outgoing mail from this address if it doesn't exist but * there's no easy alternative. Defaulting to admin_email might appear to be another * option but some hosts may refuse to relay mail from an unknown domain. See * http://trac.wordpress.org/ticket/5007. */ if ( !isset( $from_email ) ) { // Get the site domain and get rid of www. $sitename = strtolower( $_SERVER['SERVER_NAME'] ); if ( substr( $sitename, 0, 4 ) == 'www.' ) { $sitename = substr( $sitename, 4 ); } $from_email = 'wordpress@' . $sitename; } // Plugin authors can override the potentially troublesome default $phpmailer->From = apply_filters( 'wp_mail_from' , $from_email ); $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name ); // Set destination addresses if ( !is_array( $to ) ) $to = explode( ',', $to ); foreach ( (array) $to as $recipient ) { try { // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>" $recipient_name = ''; if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) { if ( count( $matches ) == 3 ) { $recipient_name = $matches[1]; $recipient = $matches[2]; } } $phpmailer->AddAddress( $recipient, $recipient_name); } catch ( phpmailerException $e ) { continue; } } // Set mail's subject and body $phpmailer->Subject = $subject; $phpmailer->Body = $message; // Add any CC and BCC recipients if ( !empty( $cc ) ) { foreach ( (array) $cc as $recipient ) { try { // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>" $recipient_name = ''; if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) { if ( count( $matches ) == 3 ) { $recipient_name = $matches[1]; $recipient = $matches[2]; } } $phpmailer->AddCc( $recipient, $recipient_name ); } catch ( phpmailerException $e ) { continue; } } } if ( !empty( $bcc ) ) { foreach ( (array) $bcc as $recipient) { try { // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>" $recipient_name = ''; if( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) { if ( count( $matches ) == 3 ) { $recipient_name = $matches[1]; $recipient = $matches[2]; } } $phpmailer->AddBcc( $recipient, $recipient_name ); } catch ( phpmailerException $e ) { continue; } } } // Set to use PHP's mail() $phpmailer->IsMail(); // Set Content-Type and charset // If we don't have a content-type from the input headers if ( !isset( $content_type ) ) $content_type = 'text/plain'; $content_type = apply_filters( 'wp_mail_content_type', $content_type ); $phpmailer->ContentType = $content_type; // Set whether it's plaintext, depending on $content_type if ( 'text/html' == $content_type ) $phpmailer->IsHTML( true ); // If we don't have a charset from the input headers if ( !isset( $charset ) ) $charset = get_bloginfo( 'charset' ); // Set the content-type and charset $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset ); // Set custom headers if ( !empty( $headers ) ) { foreach( (array) $headers as $name => $content ) { $phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) ); } if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) ) $phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) ); } if ( !empty( $attachments ) ) { foreach ( $attachments as $attachment ) { try { $phpmailer->AddAttachment($attachment); } catch ( phpmailerException $e ) { continue; } } } do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) ); // Send! try { $phpmailer->Send(); } catch ( phpmailerException $e ) { return false; } return true; } endif; if ( !function_exists('wp_authenticate') ) : /** * Checks a user's login information and logs them in if it checks out. * * @since 2.5.0 * * @param string $username User's username * @param string $password User's password * @return WP_Error|WP_User WP_User object if login successful, otherwise WP_Error object. */ function wp_authenticate($username, $password) { $username = sanitize_user($username); $password = trim($password); $user = apply_filters('authenticate', null, $username, $password); if ( $user == null ) { // TODO what should the error message be? (Or would these even happen?) // Only needed if all authentication handlers fail to return anything. $user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.')); } $ignore_codes = array('empty_username', 'empty_password'); if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) { do_action('wp_login_failed', $username); } return $user; } endif; if ( !function_exists('wp_logout') ) : /** * Log the current user out. * * @since 2.5.0 */ function wp_logout() { wp_clear_auth_cookie(); do_action('wp_logout'); } endif; if ( !function_exists('wp_validate_auth_cookie') ) : /** * Validates authentication cookie. * * The checks include making sure that the authentication cookie is set and * pulling in the contents (if $cookie is not used). * * Makes sure the cookie is not expired. Verifies the hash in cookie is what is * should be and compares the two. * * @since 2.5 * * @param string $cookie Optional. If used, will validate contents instead of cookie's * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in * @return bool|int False if invalid cookie, User ID if valid. */ function wp_validate_auth_cookie($cookie = '', $scheme = '') { if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) { do_action('auth_cookie_malformed', $cookie, $scheme); return false; } extract($cookie_elements, EXTR_OVERWRITE); $expired = $expiration; // Allow a grace period for POST and AJAX requests if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] ) $expired += HOUR_IN_SECONDS; // Quick check to see if an honest cookie has expired if ( $expired < time() ) { do_action('auth_cookie_expired', $cookie_elements); return false; } $user = get_user_by('login', $username); if ( ! $user ) { do_action('auth_cookie_bad_username', $cookie_elements); return false; } $pass_frag = substr($user->user_pass, 8, 4); $key = wp_hash($username . $pass_frag . '|' . $expiration, $scheme); $hash = hash_hmac('md5', $username . '|' . $expiration, $key); if ( $hmac != $hash ) { do_action('auth_cookie_bad_hash', $cookie_elements); return false; } if ( $expiration < time() ) // AJAX/POST grace period set above $GLOBALS['login_grace_period'] = 1; do_action('auth_cookie_valid', $cookie_elements, $user); return $user->ID; } endif; if ( !function_exists('wp_generate_auth_cookie') ) : /** * Generate authentication cookie contents. * * @since 2.5 * @uses apply_filters() Calls 'auth_cookie' hook on $cookie contents, User ID * and expiration of cookie. * * @param int $user_id User ID * @param int $expiration Cookie expiration in seconds * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in * @return string Authentication cookie contents */ function wp_generate_auth_cookie($user_id, $expiration, $scheme = 'auth') { $user = get_userdata($user_id); $pass_frag = substr($user->user_pass, 8, 4); $key = wp_hash($user->user_login . $pass_frag . '|' . $expiration, $scheme); $hash = hash_hmac('md5', $user->user_login . '|' . $expiration, $key); $cookie = $user->user_login . '|' . $expiration . '|' . $hash; return apply_filters('auth_cookie', $cookie, $user_id, $expiration, $scheme); } endif; if ( !function_exists('wp_parse_auth_cookie') ) : /** * Parse a cookie into its components * * @since 2.7 * * @param string $cookie * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in * @return array Authentication cookie components */ function wp_parse_auth_cookie($cookie = '', $scheme = '') { if ( empty($cookie) ) { switch ($scheme){ case 'auth': $cookie_name = AUTH_COOKIE; break; case 'secure_auth': $cookie_name = SECURE_AUTH_COOKIE; break; case "logged_in": $cookie_name = LOGGED_IN_COOKIE; break; default: if ( is_ssl() ) { $cookie_name = SECURE_AUTH_COOKIE; $scheme = 'secure_auth'; } else { $cookie_name = AUTH_COOKIE; $scheme = 'auth'; } } if ( empty($_COOKIE[$cookie_name]) ) return false; $cookie = $_COOKIE[$cookie_name]; } $cookie_elements = explode('|', $cookie); if ( count($cookie_elements) != 3 ) return false; list($username, $expiration, $hmac) = $cookie_elements; return compact('username', 'expiration', 'hmac', 'scheme'); } endif; if ( !function_exists('wp_set_auth_cookie') ) : /** * Sets the authentication cookies based User ID. * * The $remember parameter increases the time that the cookie will be kept. The * default the cookie is kept without remembering is two days. When $remember is * set, the cookies will be kept for 14 days or two weeks. * * @since 2.5 * * @param int $user_id User ID * @param bool $remember Whether to remember the user */ function wp_set_auth_cookie($user_id, $remember = false, $secure = '') { if ( $remember ) { $expiration = $expire = time() + apply_filters('auth_cookie_expiration', 1209600, $user_id, $remember); } else { $expiration = time() + apply_filters('auth_cookie_expiration', 172800, $user_id, $remember); $expire = 0; } if ( '' === $secure ) $secure = is_ssl(); $secure = apply_filters('secure_auth_cookie', $secure, $user_id); $secure_logged_in_cookie = apply_filters('secure_logged_in_cookie', false, $user_id, $secure); if ( $secure ) { $auth_cookie_name = SECURE_AUTH_COOKIE; $scheme = 'secure_auth'; } else { $auth_cookie_name = AUTH_COOKIE; $scheme = 'auth'; } $auth_cookie = wp_generate_auth_cookie($user_id, $expiration, $scheme); $logged_in_cookie = wp_generate_auth_cookie($user_id, $expiration, 'logged_in'); do_action('set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme); do_action('set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in'); setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true); setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true); setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true); if ( COOKIEPATH != SITECOOKIEPATH ) setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true); } endif; if ( !function_exists('wp_clear_auth_cookie') ) : /** * Removes all of the cookies associated with authentication. * * @since 2.5 */ function wp_clear_auth_cookie() { do_action('clear_auth_cookie'); setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN ); setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN ); setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN ); setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN ); setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN ); // Old cookies setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN ); setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN ); // Even older cookies setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN ); setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN ); setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN ); } endif; if ( !function_exists('is_user_logged_in') ) : /** * Checks if the current visitor is a logged in user. * * @since 2.0.0 * * @return bool True if user is logged in, false if not logged in. */ function is_user_logged_in() { $user = wp_get_current_user(); if ( ! $user->exists() ) return false; return true; } endif; if ( !function_exists('auth_redirect') ) : /** * Checks if a user is logged in, if not it redirects them to the login page. * * @since 1.5 */ function auth_redirect() { // Checks if a user is logged in, if not redirects them to the login page $secure = ( is_ssl() || force_ssl_admin() ); $secure = apply_filters('secure_auth_redirect', $secure); // If https is required and request is http, redirect if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) { if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) { wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) ); exit(); } else { wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); exit(); } } if ( is_user_admin() ) $scheme = 'logged_in'; else $scheme = apply_filters( 'auth_redirect_scheme', '' ); if ( $user_id = wp_validate_auth_cookie( '', $scheme) ) { do_action('auth_redirect', $user_id); // If the user wants ssl but the session is not ssl, redirect. if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) { if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) { wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) ); exit(); } else { wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); exit(); } } return; // The cookie is good so we're done } // The cookie is no good so force login nocache_headers(); $redirect = ( strpos( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_get_referer() ) ? wp_get_referer() : set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); $login_url = wp_login_url($redirect, true); wp_redirect($login_url); exit(); } endif; if ( !function_exists('check_admin_referer') ) : /** * Makes sure that a user was referred from another admin page. * * To avoid security exploits. * * @since 1.2.0 * @uses do_action() Calls 'check_admin_referer' on $action. * * @param string $action Action nonce * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5) */ function check_admin_referer($action = -1, $query_arg = '_wpnonce') { if ( -1 == $action ) _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' ); $adminurl = strtolower(admin_url()); $referer = strtolower(wp_get_referer()); $result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false; if ( !$result && !(-1 == $action && strpos($referer, $adminurl) === 0) ) { wp_nonce_ays($action); die(); } do_action('check_admin_referer', $action, $result); return $result; }endif; if ( !function_exists('check_ajax_referer') ) : /** * Verifies the AJAX request to prevent processing requests external of the blog. * * @since 2.0.3 * * @param string $action Action nonce * @param string $query_arg where to look for nonce in $_REQUEST (since 2.5) */ function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) { if ( $query_arg ) $nonce = $_REQUEST[$query_arg]; else $nonce = isset($_REQUEST['_ajax_nonce']) ? $_REQUEST['_ajax_nonce'] : $_REQUEST['_wpnonce']; $result = wp_verify_nonce( $nonce, $action ); if ( $die && false == $result ) { if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) wp_die( -1 ); else die( '-1' ); } do_action('check_ajax_referer', $action, $result); return $result; } endif; if ( !function_exists('wp_redirect') ) : /** * Redirects to another page. * * @since 1.5.1 * @uses apply_filters() Calls 'wp_redirect' hook on $location and $status. * * @param string $location The path to redirect to * @param int $status Status code to use * @return bool False if $location is not set */ function wp_redirect($location, $status = 302) { global $is_IIS; $location = apply_filters('wp_redirect', $location, $status); $status = apply_filters('wp_redirect_status', $status, $location); if ( !$location ) // allows the wp_redirect filter to cancel a redirect return false; $location = wp_sanitize_redirect($location); if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' ) status_header($status); // This causes problems on IIS and some FastCGI setups header("Location: $location", true, $status); } endif; if ( !function_exists('wp_sanitize_redirect') ) : /** * Sanitizes a URL for use in a redirect. * * @since 2.3 * * @return string redirect-sanitized URL **/ function wp_sanitize_redirect($location) { $location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!]|i', '', $location); $location = wp_kses_no_null($location); // remove %0d and %0a from location $strip = array('%0d', '%0a', '%0D', '%0A'); $location = _deep_replace($strip, $location); return $location; } endif; if ( !function_exists('wp_safe_redirect') ) : /** * Performs a safe (local) redirect, using wp_redirect(). * * Checks whether the $location is using an allowed host, if it has an absolute * path. A plugin can therefore set or remove allowed host(s) to or from the * list. * * If the host is not allowed, then the redirect is to wp-admin on the siteurl * instead. This prevents malicious redirects which redirect to another host, * but only used in a few places. * * @since 2.3 * @uses wp_validate_redirect() To validate the redirect is to an allowed host. * * @return void Does not return anything **/ function wp_safe_redirect($location, $status = 302) { // Need to look at the URL the way it will end up in wp_redirect() $location = wp_sanitize_redirect($location); $location = wp_validate_redirect($location, admin_url()); wp_redirect($location, $status); } endif; if ( !function_exists('wp_validate_redirect') ) : /** * Validates a URL for use in a redirect. * * Checks whether the $location is using an allowed host, if it has an absolute * path. A plugin can therefore set or remove allowed host(s) to or from the * list. * * If the host is not allowed, then the redirect is to $default supplied * * @since 2.8.1 * @uses apply_filters() Calls 'allowed_redirect_hosts' on an array containing * WordPress host string and $location host string. * * @param string $location The redirect to validate * @param string $default The value to return if $location is not allowed * @return string redirect-sanitized URL **/ function wp_validate_redirect($location, $default = '') { // browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//' if ( substr($location, 0, 2) == '//' ) $location = 'http:' . $location; // In php 5 parse_url may fail if the URL query part contains http://, bug #38143 $test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location; $lp = parse_url($test); // Give up if malformed URL if ( false === $lp ) return $default; // Allow only http and https schemes. No data:, etc. if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) ) return $default; // Reject if scheme is set but host is not. This catches urls like https:host.com for which parse_url does not set the host field. if ( isset($lp['scheme']) && !isset($lp['host']) ) return $default; $wpp = parse_url(home_url()); $allowed_hosts = (array) apply_filters('allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : ''); if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) ) $location = $default; return $location; } endif; if ( ! function_exists('wp_notify_postauthor') ) : /** * Notify an author of a comment/trackback/pingback to one of their posts. * * @since 1.0.0 * * @param int $comment_id Comment ID * @param string $comment_type Optional. The comment type either 'comment' (default), 'trackback', or 'pingback' * @return bool False if user email does not exist. True on completion. */ function wp_notify_postauthor( $comment_id, $comment_type = '' ) { $comment = get_comment( $comment_id ); $post = get_post( $comment->comment_post_ID ); $author = get_userdata( $post->post_author ); // The comment was left by the author if ( $comment->user_id == $post->post_author ) return false; // The author moderated a comment on his own post if ( $post->post_author == get_current_user_id() ) return false; // If there's no email to send the comment to if ( '' == $author->user_email ) return false; $comment_author_domain = @gethostbyaddr($comment->comment_author_IP); // The blogname option is escaped with esc_html on the way into the database in sanitize_option // we want to reverse this for the plain text arena of emails. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); if ( empty( $comment_type ) ) $comment_type = 'comment'; if ('comment' == $comment_type) { $notify_message = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n"; /* translators: 1: comment author, 2: author IP, 3: author domain */ $notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= sprintf( __('Whois : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n"; $notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n"; $notify_message .= __('You can see all comments on this post here: ') . "\r\n"; /* translators: 1: blog name, 2: post title */ $subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title ); } elseif ('trackback' == $comment_type) { $notify_message = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n"; /* translators: 1: website name, 2: author IP, 3: author domain */ $notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= __('Excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n"; $notify_message .= __('You can see all trackbacks on this post here: ') . "\r\n"; /* translators: 1: blog name, 2: post title */ $subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title ); } elseif ('pingback' == $comment_type) { $notify_message = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n"; /* translators: 1: comment author, 2: author IP, 3: author domain */ $notify_message .= sprintf( __('Website: %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= __('Excerpt: ') . "\r\n" . sprintf('[...] %s [...]', $comment->comment_content ) . "\r\n\r\n"; $notify_message .= __('You can see all pingbacks on this post here: ') . "\r\n"; /* translators: 1: blog name, 2: post title */ $subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title ); } $notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n"; $notify_message .= sprintf( __('Permalink: %s'), get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment_id ) . "\r\n"; if ( EMPTY_TRASH_DAYS ) $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n"; else $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n"; $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n"; $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); if ( '' == $comment->comment_author ) { $from = "From: \"$blogname\" <$wp_email>"; if ( '' != $comment->comment_author_email ) $reply_to = "Reply-To: $comment->comment_author_email"; } else { $from = "From: \"$comment->comment_author\" <$wp_email>"; if ( '' != $comment->comment_author_email ) $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>"; } $message_headers = "$from\n" . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n"; if ( isset($reply_to) ) $message_headers .= $reply_to . "\n"; $notify_message = apply_filters('comment_notification_text', $notify_message, $comment_id); $subject = apply_filters('comment_notification_subject', $subject, $comment_id); $message_headers = apply_filters('comment_notification_headers', $message_headers, $comment_id); @wp_mail( $author->user_email, $subject, $notify_message, $message_headers ); return true; } endif; if ( !function_exists('wp_notify_moderator') ) : /** * Notifies the moderator of the blog about a new comment that is awaiting approval. * * @since 1.0 * @uses $wpdb * * @param int $comment_id Comment ID * @return bool Always returns true */ function wp_notify_moderator($comment_id) { global $wpdb; if ( 0 == get_option( 'moderation_notify' ) ) return true; $comment = get_comment($comment_id); $post = get_post($comment->comment_post_ID); $user = get_userdata( $post->post_author ); // Send to the administration and to the post author if the author can modify the comment. $email_to = array( get_option('admin_email') ); if ( user_can($user->ID, 'edit_comment', $comment_id) && !empty($user->user_email) && ( get_option('admin_email') != $user->user_email) ) $email_to[] = $user->user_email; $comment_author_domain = @gethostbyaddr($comment->comment_author_IP); $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'"); // The blogname option is escaped with esc_html on the way into the database in sanitize_option // we want to reverse this for the plain text arena of emails. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); switch ($comment->comment_type) { case 'trackback': $notify_message = sprintf( __('A new trackback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n"; $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n"; $notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n"; break; case 'pingback': $notify_message = sprintf( __('A new pingback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n"; $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n"; $notify_message .= sprintf( __('Website : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n"; break; default: //Comments $notify_message = sprintf( __('A new comment on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n"; $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n"; $notify_message .= sprintf( __('Author : %1$s (IP: %2$s , %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n"; $notify_message .= sprintf( __('E-mail : %s'), $comment->comment_author_email ) . "\r\n"; $notify_message .= sprintf( __('URL : %s'), $comment->comment_author_url ) . "\r\n"; $notify_message .= sprintf( __('Whois : http://whois.arin.net/rest/ip/%s'), $comment->comment_author_IP ) . "\r\n"; $notify_message .= __('Comment: ') . "\r\n" . $comment->comment_content . "\r\n\r\n"; break; } $notify_message .= sprintf( __('Approve it: %s'), admin_url("comment.php?action=approve&c=$comment_id") ) . "\r\n"; if ( EMPTY_TRASH_DAYS ) $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n"; else $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n"; $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n"; $notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:', 'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n"; $notify_message .= admin_url("edit-comments.php?comment_status=moderated") . "\r\n"; $subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), $blogname, $post->post_title ); $message_headers = ''; $notify_message = apply_filters('comment_moderation_text', $notify_message, $comment_id); $subject = apply_filters('comment_moderation_subject', $subject, $comment_id); $message_headers = apply_filters('comment_moderation_headers', $message_headers); foreach ( $email_to as $email ) @wp_mail($email, $subject, $notify_message, $message_headers); return true; } endif; if ( !function_exists('wp_password_change_notification') ) : /** * Notify the blog admin of a user changing password, normally via email. * * @since 2.7 * * @param object $user User Object */ function wp_password_change_notification(&$user) { // send a copy of password change notification to the admin // but check to see if it's the admin whose password we're changing, and skip this if ( $user->user_email != get_option('admin_email') ) { $message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n"; // The blogname option is escaped with esc_html on the way into the database in sanitize_option // we want to reverse this for the plain text arena of emails. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), $blogname), $message); } } endif; if ( !function_exists('wp_new_user_notification') ) : /** * Notify the blog admin of a new user, normally via email. * * @since 2.0 * * @param int $user_id User ID * @param string $plaintext_pass Optional. The user's plaintext password */ function wp_new_user_notification($user_id, $plaintext_pass = '') { $user = get_userdata( $user_id ); $user_login = stripslashes($user->user_login); $user_email = stripslashes($user->user_email); // The blogname option is escaped with esc_html on the way into the database in sanitize_option // we want to reverse this for the plain text arena of emails. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES); $message = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n"; $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n"; $message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n"; @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message); if ( empty($plaintext_pass) ) return; $message = sprintf(__('Username: %s'), $user_login) . "\r\n"; $message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n"; $message .= wp_login_url() . "\r\n"; wp_mail($user_email, sprintf(__('[%s] Your username and password'), $blogname), $message); } endif; if ( !function_exists('wp_nonce_tick') ) : /** * Get the time-dependent variable for nonce creation. * * A nonce has a lifespan of two ticks. Nonces in their second tick may be * updated, e.g. by autosave. * * @since 2.5 * * @return int */ function wp_nonce_tick() { $nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS ); return ceil(time() / ( $nonce_life / 2 )); } endif; if ( !function_exists('wp_verify_nonce') ) : /** * Verify that correct nonce was used with time limit. * * The user is given an amount of time to use the token, so therefore, since the * UID and $action remain the same, the independent variable is the time. * * @since 2.0.3 * * @param string $nonce Nonce that was used in the form to verify * @param string|int $action Should give context to what is taking place and be the same when nonce was created. * @return bool Whether the nonce check passed or failed. */ function wp_verify_nonce($nonce, $action = -1) { $user = wp_get_current_user(); $uid = (int) $user->ID; if ( ! $uid ) $uid = apply_filters( 'nonce_user_logged_out', $uid, $action ); $i = wp_nonce_tick(); // Nonce generated 0-12 hours ago if ( substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10) == $nonce ) return 1; // Nonce generated 12-24 hours ago if ( substr(wp_hash(($i - 1) . $action . $uid, 'nonce'), -12, 10) == $nonce ) return 2; // Invalid nonce return false; } endif; if ( !function_exists('wp_create_nonce') ) : /** * Creates a random, one time use token. * * @since 2.0.3 * * @param string|int $action Scalar value to add context to the nonce. * @return string The one use form token */ function wp_create_nonce($action = -1) { $user = wp_get_current_user(); $uid = (int) $user->ID; if ( ! $uid ) $uid = apply_filters( 'nonce_user_logged_out', $uid, $action ); $i = wp_nonce_tick(); return substr(wp_hash($i . $action . $uid, 'nonce'), -12, 10); } endif; if ( !function_exists('wp_salt') ) : /** * Get salt to add to hashes. * * Salts are created using secret keys. Secret keys are located in two places: * in the database and in the wp-config.php file. The secret key in the database * is randomly generated and will be appended to the secret keys in wp-config.php. * * The secret keys in wp-config.php should be updated to strong, random keys to maximize * security. Below is an example of how the secret key constants are defined. * Do not paste this example directly into wp-config.php. Instead, have a * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just * for you. * * <code> * define('AUTH_KEY', ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON'); * define('SECURE_AUTH_KEY', 'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~'); * define('LOGGED_IN_KEY', '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM'); * define('NONCE_KEY', '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|'); * define('AUTH_SALT', 'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW'); * define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n'); * define('LOGGED_IN_SALT', '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm'); * define('NONCE_SALT', 'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT'); * </code> * * Salting passwords helps against tools which has stored hashed values of * common dictionary strings. The added values makes it harder to crack. * * @since 2.5 * * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php * * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce) * @return string Salt value */ function wp_salt( $scheme = 'auth' ) { static $cached_salts = array(); if ( isset( $cached_salts[ $scheme ] ) ) return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme ); static $duplicated_keys; if ( null === $duplicated_keys ) { $duplicated_keys = array( 'put your unique phrase here' => true ); foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) { foreach ( array( 'KEY', 'SALT' ) as $second ) { if ( ! defined( "{$first}_{$second}" ) ) continue; $value = constant( "{$first}_{$second}" ); $duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] ); } } } $key = $salt = ''; if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) ) $key = SECRET_KEY; if ( 'auth' == $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) ) $salt = SECRET_SALT; if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ) ) ) { foreach ( array( 'key', 'salt' ) as $type ) { $const = strtoupper( "{$scheme}_{$type}" ); if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) { $$type = constant( $const ); } elseif ( ! $$type ) { $$type = get_site_option( "{$scheme}_{$type}" ); if ( ! $$type ) { $$type = wp_generate_password( 64, true, true ); update_site_option( "{$scheme}_{$type}", $$type ); } } } } else { if ( ! $key ) { $key = get_site_option( 'secret_key' ); if ( ! $key ) { $key = wp_generate_password( 64, true, true ); update_site_option( 'secret_key', $key ); } } $salt = hash_hmac( 'md5', $scheme, $key ); } $cached_salts[ $scheme ] = $key . $salt; return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme ); } endif; if ( !function_exists('wp_hash') ) : /** * Get hash of given string. * * @since 2.0.3 * @uses wp_salt() Get WordPress salt * * @param string $data Plain text to hash * @return string Hash of $data */ function wp_hash($data, $scheme = 'auth') { $salt = wp_salt($scheme); return hash_hmac('md5', $data, $salt); } endif; if ( !function_exists('wp_hash_password') ) : /** * Create a hash (encrypt) of a plain text password. * * For integration with other applications, this function can be overwritten to * instead use the other package password checking algorithm. * * @since 2.5 * @global object $wp_hasher PHPass object * @uses PasswordHash::HashPassword * * @param string $password Plain text user password to hash * @return string The hash string of the password */ function wp_hash_password($password) { global $wp_hasher; if ( empty($wp_hasher) ) { require_once( ABSPATH . 'wp-includes/class-phpass.php'); // By default, use the portable hash from phpass $wp_hasher = new PasswordHash(8, true); } return $wp_hasher->HashPassword($password); } endif; if ( !function_exists('wp_check_password') ) : /** * Checks the plaintext password against the encrypted Password. * * Maintains compatibility between old version and the new cookie authentication * protocol using PHPass library. The $hash parameter is the encrypted password * and the function compares the plain text password when encrypted similarly * against the already encrypted password to see if they match. * * For integration with other applications, this function can be overwritten to * instead use the other package password checking algorithm. * * @since 2.5 * @global object $wp_hasher PHPass object used for checking the password * against the $hash + $password * @uses PasswordHash::CheckPassword * * @param string $password Plaintext user's password * @param string $hash Hash of the user's password to check against. * @return bool False, if the $password does not match the hashed password */ function wp_check_password($password, $hash, $user_id = '') { global $wp_hasher; // If the hash is still md5... if ( strlen($hash) <= 32 ) { $check = ( $hash == md5($password) ); if ( $check && $user_id ) { // Rehash using new hash. wp_set_password($password, $user_id); $hash = wp_hash_password($password); } return apply_filters('check_password', $check, $password, $hash, $user_id); } // If the stored hash is longer than an MD5, presume the // new style phpass portable hash. if ( empty($wp_hasher) ) { require_once( ABSPATH . 'wp-includes/class-phpass.php'); // By default, use the portable hash from phpass $wp_hasher = new PasswordHash(8, true); } $check = $wp_hasher->CheckPassword($password, $hash); return apply_filters('check_password', $check, $password, $hash, $user_id); } endif; if ( !function_exists('wp_generate_password') ) : /** * Generates a random password drawn from the defined set of characters. * * @since 2.5 * * @param int $length The length of password to generate * @param bool $special_chars Whether to include standard special characters. Default true. * @param bool $extra_special_chars Whether to include other special characters. Used when * generating secret keys and salts. Default false. * @return string The random password **/ function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) { $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; if ( $special_chars ) $chars .= '!@#$%^&*()'; if ( $extra_special_chars ) $chars .= '-_ []{}<>~`+=,.;:/?|'; $password = ''; for ( $i = 0; $i < $length; $i++ ) { $password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1); } // random_password filter was previously in random_password function which was deprecated return apply_filters('random_password', $password); } endif; if ( !function_exists('wp_rand') ) : /** * Generates a random number * * @since 2.6.2 * * @param int $min Lower limit for the generated number * @param int $max Upper limit for the generated number * @return int A random number between min and max */ function wp_rand( $min = 0, $max = 0 ) { global $rnd_value; // Reset $rnd_value after 14 uses // 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value if ( strlen($rnd_value) < 8 ) { if ( defined( 'WP_SETUP_CONFIG' ) ) static $seed = ''; else $seed = get_transient('random_seed'); $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed ); $rnd_value .= sha1($rnd_value); $rnd_value .= sha1($rnd_value . $seed); $seed = md5($seed . $rnd_value); if ( ! defined( 'WP_SETUP_CONFIG' ) ) set_transient('random_seed', $seed); } // Take the first 8 digits for our value $value = substr($rnd_value, 0, 8); // Strip the first eight, leaving the remainder for the next call to wp_rand(). $rnd_value = substr($rnd_value, 8); $value = abs(hexdec($value)); // Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats. $max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff // Reduce the value to be within the min - max range if ( $max != 0 ) $value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 ); return abs(intval($value)); } endif; if ( !function_exists('wp_set_password') ) : /** * Updates the user's password with a new encrypted one. * * For integration with other applications, this function can be overwritten to * instead use the other package password checking algorithm. * * @since 2.5 * @uses $wpdb WordPress database object for queries * @uses wp_hash_password() Used to encrypt the user's password before passing to the database * * @param string $password The plaintext new user password * @param int $user_id User ID */ function wp_set_password( $password, $user_id ) { global $wpdb; $hash = wp_hash_password($password); $wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) ); wp_cache_delete($user_id, 'users'); } endif; if ( !function_exists( 'get_avatar' ) ) : /** * Retrieve the avatar for a user who provided a user ID or email address. * * @since 2.5 * @param int|string|object $id_or_email A user ID, email address, or comment object * @param int $size Size of the avatar image * @param string $default URL to a default image to use if no avatar is available * @param string $alt Alternative text to use in image tag. Defaults to blank * @return string <img> tag for the user's avatar */ function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) { if ( ! get_option('show_avatars') ) return false; if ( false === $alt) $safe_alt = ''; else $safe_alt = esc_attr( $alt ); if ( !is_numeric($size) ) $size = '96'; $email = ''; if ( is_numeric($id_or_email) ) { $id = (int) $id_or_email; $user = get_userdata($id); if ( $user ) $email = $user->user_email; } elseif ( is_object($id_or_email) ) { // No avatar for pingbacks or trackbacks $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) ); if ( ! empty( $id_or_email->comment_type ) && ! in_array( $id_or_email->comment_type, (array) $allowed_comment_types ) ) return false; if ( !empty($id_or_email->user_id) ) { $id = (int) $id_or_email->user_id; $user = get_userdata($id); if ( $user) $email = $user->user_email; } elseif ( !empty($id_or_email->comment_author_email) ) { $email = $id_or_email->comment_author_email; } } else { $email = $id_or_email; } if ( empty($default) ) { $avatar_default = get_option('avatar_default'); if ( empty($avatar_default) ) $default = 'mystery'; else $default = $avatar_default; } if ( !empty($email) ) $email_hash = md5( strtolower( trim( $email ) ) ); if ( is_ssl() ) { $host = 'https://secure.gravatar.com'; } else { if ( !empty($email) ) $host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash[0] ) % 2 ) ); else $host = 'http://0.gravatar.com'; } if ( 'mystery' == $default ) $default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com') elseif ( 'blank' == $default ) $default = $email ? 'blank' : includes_url( 'images/blank.gif' ); elseif ( !empty($email) && 'gravatar_default' == $default ) $default = ''; elseif ( 'gravatar_default' == $default ) $default = "$host/avatar/?s={$size}"; elseif ( empty($email) ) $default = "$host/avatar/?d=$default&amp;s={$size}"; elseif ( strpos($default, 'http://') === 0 ) $default = add_query_arg( 's', $size, $default ); if ( !empty($email) ) { $out = "$host/avatar/"; $out .= $email_hash; $out .= '?s='.$size; $out .= '&amp;d=' . urlencode( $default ); $rating = get_option('avatar_rating'); if ( !empty( $rating ) ) $out .= "&amp;r={$rating}"; $avatar = "<img alt='{$safe_alt}' src='{$out}' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />"; } else { $avatar = "<img alt='{$safe_alt}' src='{$default}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />"; } return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt); } endif; if ( !function_exists( 'wp_text_diff' ) ) : /** * Displays a human readable HTML representation of the difference between two strings. * * The Diff is available for getting the changes between versions. The output is * HTML, so the primary use is for displaying the changes. If the two strings * are equivalent, then an empty string will be returned. * * The arguments supported and can be changed are listed below. * * 'title' : Default is an empty string. Titles the diff in a manner compatible * with the output. * 'title_left' : Default is an empty string. Change the HTML to the left of the * title. * 'title_right' : Default is an empty string. Change the HTML to the right of * the title. * * @since 2.6 * @see wp_parse_args() Used to change defaults to user defined settings. * @uses Text_Diff * @uses WP_Text_Diff_Renderer_Table * * @param string $left_string "old" (left) version of string * @param string $right_string "new" (right) version of string * @param string|array $args Optional. Change 'title', 'title_left', and 'title_right' defaults. * @return string Empty string if strings are equivalent or HTML with differences. */ function wp_text_diff( $left_string, $right_string, $args = null ) { $defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' ); $args = wp_parse_args( $args, $defaults ); if ( !class_exists( 'WP_Text_Diff_Renderer_Table' ) ) require( ABSPATH . WPINC . '/wp-diff.php' ); $left_string = normalize_whitespace($left_string); $right_string = normalize_whitespace($right_string); $left_lines = explode("\n", $left_string); $right_lines = explode("\n", $right_string); $text_diff = new Text_Diff($left_lines, $right_lines); $renderer = new WP_Text_Diff_Renderer_Table(); $diff = $renderer->render($text_diff); if ( !$diff ) return ''; $r = "<table class='diff'>\n"; $r .= "<col class='ltype' /><col class='content' /><col class='ltype' /><col class='content' />"; if ( $args['title'] || $args['title_left'] || $args['title_right'] ) $r .= "<thead>"; if ( $args['title'] ) $r .= "<tr class='diff-title'><th colspan='4'>$args[title]</th></tr>\n"; if ( $args['title_left'] || $args['title_right'] ) { $r .= "<tr class='diff-sub-title'>\n"; $r .= "\t<td></td><th>$args[title_left]</th>\n"; $r .= "\t<td></td><th>$args[title_right]</th>\n"; $r .= "</tr>\n"; } if ( $args['title'] || $args['title_left'] || $args['title_right'] ) $r .= "</thead>\n"; $r .= "<tbody>\n$diff\n</tbody>\n"; $r .= "</table>"; return $r; } endif;
zyblog
trunk/zyblog/wp-includes/pluggable.php
PHP
asf20
60,123
<?php /** * Creates common globals for the rest of WordPress * * Sets $pagenow global which is the current page. Checks * for the browser to set which one is currently being used. * * Detects which user environment WordPress is being used on. * Only attempts to check for Apache and IIS. Two web servers * with known permalink capability. * * @package WordPress */ global $pagenow, $is_lynx, $is_gecko, $is_winIE, $is_macIE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone, $is_IE, $is_apache, $is_IIS, $is_iis7; // On which page are we ? if ( is_admin() ) { // wp-admin pages are checked more carefully if ( is_network_admin() ) preg_match('#/wp-admin/network/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches); elseif ( is_user_admin() ) preg_match('#/wp-admin/user/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches); else preg_match('#/wp-admin/?(.*?)$#i', $_SERVER['PHP_SELF'], $self_matches); $pagenow = $self_matches[1]; $pagenow = trim($pagenow, '/'); $pagenow = preg_replace('#\?.*?$#', '', $pagenow); if ( '' === $pagenow || 'index' === $pagenow || 'index.php' === $pagenow ) { $pagenow = 'index.php'; } else { preg_match('#(.*?)(/|$)#', $pagenow, $self_matches); $pagenow = strtolower($self_matches[1]); if ( '.php' !== substr($pagenow, -4, 4) ) $pagenow .= '.php'; // for Options +Multiviews: /wp-admin/themes/index.php (themes.php is queried) } } else { if ( preg_match('#([^/]+\.php)([?/].*?)?$#i', $_SERVER['PHP_SELF'], $self_matches) ) $pagenow = strtolower($self_matches[1]); else $pagenow = 'index.php'; } unset($self_matches); // Simple browser detection $is_lynx = $is_gecko = $is_winIE = $is_macIE = $is_opera = $is_NS4 = $is_safari = $is_chrome = $is_iphone = false; if ( isset($_SERVER['HTTP_USER_AGENT']) ) { if ( strpos($_SERVER['HTTP_USER_AGENT'], 'Lynx') !== false ) { $is_lynx = true; } elseif ( stripos($_SERVER['HTTP_USER_AGENT'], 'chrome') !== false ) { if ( stripos( $_SERVER['HTTP_USER_AGENT'], 'chromeframe' ) !== false ) { if ( $is_chrome = apply_filters( 'use_google_chrome_frame', is_admin() ) ) header( 'X-UA-Compatible: chrome=1' ); $is_winIE = ! $is_chrome; } else { $is_chrome = true; } } elseif ( stripos($_SERVER['HTTP_USER_AGENT'], 'safari') !== false ) { $is_safari = true; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false ) { $is_gecko = true; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Win') !== false ) { $is_winIE = true; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') !== false ) { $is_macIE = true; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false ) { $is_opera = true; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Nav') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Mozilla/4.') !== false ) { $is_NS4 = true; } } if ( $is_safari && stripos($_SERVER['HTTP_USER_AGENT'], 'mobile') !== false ) $is_iphone = true; $is_IE = ( $is_macIE || $is_winIE ); // Server detection /** * Whether the server software is Apache or something else * @global bool $is_apache */ $is_apache = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false || strpos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false); /** * Whether the server software is IIS or something else * @global bool $is_IIS */ $is_IIS = !$is_apache && (strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false || strpos($_SERVER['SERVER_SOFTWARE'], 'ExpressionDevServer') !== false); /** * Whether the server software is IIS 7.X * @global bool $is_iis7 */ $is_iis7 = $is_IIS && (strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7.') !== false); /** * Test if the current browser runs on a mobile device (smart phone, tablet, etc.) * * @return bool true|false */ function wp_is_mobile() { static $is_mobile; if ( isset($is_mobile) ) return $is_mobile; if ( empty($_SERVER['HTTP_USER_AGENT']) ) { $is_mobile = false; } elseif ( strpos($_SERVER['HTTP_USER_AGENT'], 'Mobile') !== false // many mobile devices (all iPhone, iPad, etc.) || strpos($_SERVER['HTTP_USER_AGENT'], 'Android') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Silk/') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Kindle') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'BlackBerry') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mini') !== false || strpos($_SERVER['HTTP_USER_AGENT'], 'Opera Mobi') !== false ) { $is_mobile = true; } else { $is_mobile = false; } return $is_mobile; }
zyblog
trunk/zyblog/wp-includes/vars.php
PHP
asf20
4,594
<?php /** * A simple set of functions to check our version 1.0 update service. * * @package WordPress * @since 2.3.0 */ /** * Check WordPress version against the newest version. * * The WordPress version, PHP version, and Locale is sent. Checks against the * WordPress server at api.wordpress.org server. Will only check if WordPress * isn't installing. * * @package WordPress * @since 2.3.0 * @uses $wp_version Used to check against the newest WordPress version. * * @return mixed Returns null if update is unsupported. Returns false if check is too soon. */ function wp_version_check() { if ( defined('WP_INSTALLING') ) return; global $wpdb, $wp_local_package; include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version $php_version = phpversion(); $current = get_site_transient( 'update_core' ); if ( ! is_object($current) ) { $current = new stdClass; $current->updates = array(); $current->version_checked = $wp_version; } // Wait 60 seconds between multiple version check requests $timeout = 60; $time_not_changed = isset( $current->last_checked ) && $timeout > ( time() - $current->last_checked ); if ( $time_not_changed ) return false; $locale = apply_filters( 'core_version_check_locale', get_locale() ); // Update last_checked for current to prevent multiple blocking requests if request hangs $current->last_checked = time(); set_site_transient( 'update_core', $current ); if ( method_exists( $wpdb, 'db_version' ) ) $mysql_version = preg_replace('/[^0-9.].*/', '', $wpdb->db_version()); else $mysql_version = 'N/A'; if ( is_multisite( ) ) { $user_count = get_user_count( ); $num_blogs = get_blog_count( ); $wp_install = network_site_url( ); $multisite_enabled = 1; } else { $user_count = count_users( ); $user_count = $user_count['total_users']; $multisite_enabled = 0; $num_blogs = 1; $wp_install = home_url( '/' ); } $query = array( 'version' => $wp_version, 'php' => $php_version, 'locale' => $locale, 'mysql' => $mysql_version, 'local_package' => isset( $wp_local_package ) ? $wp_local_package : '', 'blogs' => $num_blogs, 'users' => $user_count, 'multisite_enabled' => $multisite_enabled ); $url = 'http://api.wordpress.org/core/version-check/1.6/?' . http_build_query( $query, null, '&' ); $options = array( 'timeout' => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 3 ), 'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url( '/' ), 'headers' => array( 'wp_install' => $wp_install, 'wp_blog' => home_url( '/' ) ) ); $response = wp_remote_get($url, $options); if ( is_wp_error( $response ) || 200 != wp_remote_retrieve_response_code( $response ) ) return false; $body = trim( wp_remote_retrieve_body( $response ) ); $body = maybe_unserialize( $body ); if ( ! is_array( $body ) || ! isset( $body['offers'] ) ) return false; $offers = $body['offers']; foreach ( $offers as &$offer ) { foreach ( $offer as $offer_key => $value ) { if ( 'packages' == $offer_key ) $offer['packages'] = (object) array_intersect_key( array_map( 'esc_url', $offer['packages'] ), array_fill_keys( array( 'full', 'no_content', 'new_bundled', 'partial' ), '' ) ); elseif ( 'download' == $offer_key ) $offer['download'] = esc_url( $value ); else $offer[ $offer_key ] = esc_html( $value ); } $offer = (object) array_intersect_key( $offer, array_fill_keys( array( 'response', 'download', 'locale', 'packages', 'current', 'php_version', 'mysql_version', 'new_bundled', 'partial_version' ), '' ) ); } $updates = new stdClass(); $updates->updates = $offers; $updates->last_checked = time(); $updates->version_checked = $wp_version; set_site_transient( 'update_core', $updates); } /** * Check plugin versions against the latest versions hosted on WordPress.org. * * The WordPress version, PHP version, and Locale is sent along with a list of * all plugins installed. Checks against the WordPress server at * api.wordpress.org. Will only check if WordPress isn't installing. * * @package WordPress * @since 2.3.0 * @uses $wp_version Used to notify the WordPress version. * * @return mixed Returns null if update is unsupported. Returns false if check is too soon. */ function wp_update_plugins() { include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version if ( defined('WP_INSTALLING') ) return false; // If running blog-side, bail unless we've not checked in the last 12 hours if ( !function_exists( 'get_plugins' ) ) require_once( ABSPATH . 'wp-admin/includes/plugin.php' ); $plugins = get_plugins(); $active = get_option( 'active_plugins', array() ); $current = get_site_transient( 'update_plugins' ); if ( ! is_object($current) ) $current = new stdClass; $new_option = new stdClass; $new_option->last_checked = time(); // Check for update on a different schedule, depending on the page. switch ( current_filter() ) { case 'load-update-core.php' : $timeout = MINUTE_IN_SECONDS; break; case 'load-plugins.php' : case 'load-update.php' : $timeout = HOUR_IN_SECONDS; break; default : $timeout = 12 * HOUR_IN_SECONDS; } $time_not_changed = isset( $current->last_checked ) && $timeout > ( time() - $current->last_checked ); if ( $time_not_changed ) { $plugin_changed = false; foreach ( $plugins as $file => $p ) { $new_option->checked[ $file ] = $p['Version']; if ( !isset( $current->checked[ $file ] ) || strval($current->checked[ $file ]) !== strval($p['Version']) ) $plugin_changed = true; } if ( isset ( $current->response ) && is_array( $current->response ) ) { foreach ( $current->response as $plugin_file => $update_details ) { if ( ! isset($plugins[ $plugin_file ]) ) { $plugin_changed = true; break; } } } // Bail if we've checked recently and if nothing has changed if ( ! $plugin_changed ) return false; } // Update last_checked for current to prevent multiple blocking requests if request hangs $current->last_checked = time(); set_site_transient( 'update_plugins', $current ); $to_send = (object) compact('plugins', 'active'); $options = array( 'timeout' => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 3), 'body' => array( 'plugins' => serialize( $to_send ) ), 'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ); $raw_response = wp_remote_post('http://api.wordpress.org/plugins/update-check/1.0/', $options); if ( is_wp_error( $raw_response ) || 200 != wp_remote_retrieve_response_code( $raw_response ) ) return false; $response = maybe_unserialize( wp_remote_retrieve_body( $raw_response ) ); if ( is_array( $response ) ) $new_option->response = $response; else $new_option->response = array(); set_site_transient( 'update_plugins', $new_option ); } /** * Check theme versions against the latest versions hosted on WordPress.org. * * A list of all themes installed in sent to WP. Checks against the * WordPress server at api.wordpress.org. Will only check if WordPress isn't * installing. * * @package WordPress * @since 2.7.0 * @uses $wp_version Used to notify the WordPress version. * * @return mixed Returns null if update is unsupported. Returns false if check is too soon. */ function wp_update_themes() { include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version if ( defined( 'WP_INSTALLING' ) ) return false; $installed_themes = wp_get_themes(); $last_update = get_site_transient( 'update_themes' ); if ( ! is_object($last_update) ) $last_update = new stdClass; $themes = array(); $checked = array(); // Put slug of current theme into request. $themes['current_theme'] = get_option( 'stylesheet' ); foreach ( $installed_themes as $theme ) { $checked[ $theme->get_stylesheet() ] = $theme->get('Version'); $themes[ $theme->get_stylesheet() ] = array( 'Name' => $theme->get('Name'), 'Title' => $theme->get('Name'), 'Version' => $theme->get('Version'), 'Author' => $theme->get('Author'), 'Author URI' => $theme->get('AuthorURI'), 'Template' => $theme->get_template(), 'Stylesheet' => $theme->get_stylesheet(), ); } // Check for update on a different schedule, depending on the page. switch ( current_filter() ) { case 'load-update-core.php' : $timeout = MINUTE_IN_SECONDS; break; case 'load-themes.php' : case 'load-update.php' : $timeout = HOUR_IN_SECONDS; break; default : $timeout = 12 * HOUR_IN_SECONDS; } $time_not_changed = isset( $last_update->last_checked ) && $timeout > ( time( ) - $last_update->last_checked ); if ( $time_not_changed ) { $theme_changed = false; foreach ( $checked as $slug => $v ) { if ( !isset( $last_update->checked[ $slug ] ) || strval($last_update->checked[ $slug ]) !== strval($v) ) $theme_changed = true; } if ( isset ( $last_update->response ) && is_array( $last_update->response ) ) { foreach ( $last_update->response as $slug => $update_details ) { if ( ! isset($checked[ $slug ]) ) { $theme_changed = true; break; } } } // Bail if we've checked recently and if nothing has changed if ( ! $theme_changed ) return false; } // Update last_checked for current to prevent multiple blocking requests if request hangs $last_update->last_checked = time(); set_site_transient( 'update_themes', $last_update ); $options = array( 'timeout' => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 3), 'body' => array( 'themes' => serialize( $themes ) ), 'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ); $raw_response = wp_remote_post( 'http://api.wordpress.org/themes/update-check/1.0/', $options ); if ( is_wp_error( $raw_response ) || 200 != wp_remote_retrieve_response_code( $raw_response ) ) return false; $new_update = new stdClass; $new_update->last_checked = time( ); $new_update->checked = $checked; $response = maybe_unserialize( wp_remote_retrieve_body( $raw_response ) ); if ( is_array( $response ) ) $new_update->response = $response; set_site_transient( 'update_themes', $new_update ); } /* * Collect counts and UI strings for available updates * * @since 3.3.0 * * @return array */ function wp_get_update_data() { $counts = array( 'plugins' => 0, 'themes' => 0, 'wordpress' => 0 ); if ( current_user_can( 'update_plugins' ) ) { $update_plugins = get_site_transient( 'update_plugins' ); if ( ! empty( $update_plugins->response ) ) $counts['plugins'] = count( $update_plugins->response ); } if ( current_user_can( 'update_themes' ) ) { $update_themes = get_site_transient( 'update_themes' ); if ( ! empty( $update_themes->response ) ) $counts['themes'] = count( $update_themes->response ); } if ( function_exists( 'get_core_updates' ) && current_user_can( 'update_core' ) ) { $update_wordpress = get_core_updates( array('dismissed' => false) ); if ( ! empty( $update_wordpress ) && ! in_array( $update_wordpress[0]->response, array('development', 'latest') ) && current_user_can('update_core') ) $counts['wordpress'] = 1; } $counts['total'] = $counts['plugins'] + $counts['themes'] + $counts['wordpress']; $titles = array(); if ( $counts['wordpress'] ) $titles['wordpress'] = sprintf( __( '%d WordPress Update'), $counts['wordpress'] ); if ( $counts['plugins'] ) $titles['plugins'] = sprintf( _n( '%d Plugin Update', '%d Plugin Updates', $counts['plugins'] ), $counts['plugins'] ); if ( $counts['themes'] ) $titles['themes'] = sprintf( _n( '%d Theme Update', '%d Theme Updates', $counts['themes'] ), $counts['themes'] ); $update_title = $titles ? esc_attr( implode( ', ', $titles ) ) : ''; return apply_filters( 'wp_get_update_data', array( 'counts' => $counts, 'title' => $update_title ), $titles ); } function _maybe_update_core() { include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version $current = get_site_transient( 'update_core' ); if ( isset( $current->last_checked ) && 12 * HOUR_IN_SECONDS > ( time() - $current->last_checked ) && isset( $current->version_checked ) && $current->version_checked == $wp_version ) return; wp_version_check(); } /** * Check the last time plugins were run before checking plugin versions. * * This might have been backported to WordPress 2.6.1 for performance reasons. * This is used for the wp-admin to check only so often instead of every page * load. * * @since 2.7.0 * @access private */ function _maybe_update_plugins() { $current = get_site_transient( 'update_plugins' ); if ( isset( $current->last_checked ) && 12 * HOUR_IN_SECONDS > ( time() - $current->last_checked ) ) return; wp_update_plugins(); } /** * Check themes versions only after a duration of time. * * This is for performance reasons to make sure that on the theme version * checker is not run on every page load. * * @since 2.7.0 * @access private */ function _maybe_update_themes( ) { $current = get_site_transient( 'update_themes' ); if ( isset( $current->last_checked ) && 12 * HOUR_IN_SECONDS > ( time( ) - $current->last_checked ) ) return; wp_update_themes(); } /** * Schedule core, theme, and plugin update checks. * * @since 3.1.0 */ function wp_schedule_update_checks() { if ( !wp_next_scheduled('wp_version_check') && !defined('WP_INSTALLING') ) wp_schedule_event(time(), 'twicedaily', 'wp_version_check'); if ( !wp_next_scheduled('wp_update_plugins') && !defined('WP_INSTALLING') ) wp_schedule_event(time(), 'twicedaily', 'wp_update_plugins'); if ( !wp_next_scheduled('wp_update_themes') && !defined('WP_INSTALLING') ) wp_schedule_event(time(), 'twicedaily', 'wp_update_themes'); } if ( ( ! is_main_site() && ! is_network_admin() ) || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) return; add_action( 'admin_init', '_maybe_update_core' ); add_action( 'wp_version_check', 'wp_version_check' ); add_action( 'load-plugins.php', 'wp_update_plugins' ); add_action( 'load-update.php', 'wp_update_plugins' ); add_action( 'load-update-core.php', 'wp_update_plugins' ); add_action( 'admin_init', '_maybe_update_plugins' ); add_action( 'wp_update_plugins', 'wp_update_plugins' ); add_action( 'load-themes.php', 'wp_update_themes' ); add_action( 'load-update.php', 'wp_update_themes' ); add_action( 'load-update-core.php', 'wp_update_themes' ); add_action( 'admin_init', '_maybe_update_themes' ); add_action( 'wp_update_themes', 'wp_update_themes' ); add_action('init', 'wp_schedule_update_checks');
zyblog
trunk/zyblog/wp-includes/update.php
PHP
asf20
14,612
<?php /** * WordPress environment setup class. * * @package WordPress * @since 2.0.0 */ class WP { /** * Public query variables. * * Long list of public query variables. * * @since 2.0.0 * @access public * @var array */ var $public_query_vars = array('m', 'p', 'posts', 'w', 'cat', 'withcomments', 'withoutcomments', 's', 'search', 'exact', 'sentence', 'calendar', 'page', 'paged', 'more', 'tb', 'pb', 'author', 'order', 'orderby', 'year', 'monthnum', 'day', 'hour', 'minute', 'second', 'name', 'category_name', 'tag', 'feed', 'author_name', 'static', 'pagename', 'page_id', 'error', 'comments_popup', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview', 'robots', 'taxonomy', 'term', 'cpage', 'post_type'); /** * Private query variables. * * Long list of private query variables. * * @since 2.0.0 * @var array */ var $private_query_vars = array('offset', 'posts_per_page', 'posts_per_archive_page', 'showposts', 'nopaging', 'post_type', 'post_status', 'category__in', 'category__not_in', 'category__and', 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'tag_id', 'post_mime_type', 'perm', 'comments_per_page', 'post__in', 'post__not_in'); /** * Extra query variables set by the user. * * @since 2.1.0 * @var array */ var $extra_query_vars = array(); /** * Query variables for setting up the WordPress Query Loop. * * @since 2.0.0 * @var array */ var $query_vars; /** * String parsed to set the query variables. * * @since 2.0.0 * @var string */ var $query_string; /** * Permalink or requested URI. * * @since 2.0.0 * @var string */ var $request; /** * Rewrite rule the request matched. * * @since 2.0.0 * @var string */ var $matched_rule; /** * Rewrite query the request matched. * * @since 2.0.0 * @var string */ var $matched_query; /** * Whether already did the permalink. * * @since 2.0.0 * @var bool */ var $did_permalink = false; /** * Add name to list of public query variables. * * @since 2.1.0 * * @param string $qv Query variable name. */ function add_query_var($qv) { if ( !in_array($qv, $this->public_query_vars) ) $this->public_query_vars[] = $qv; } /** * Set the value of a query variable. * * @since 2.3.0 * * @param string $key Query variable name. * @param mixed $value Query variable value. */ function set_query_var($key, $value) { $this->query_vars[$key] = $value; } /** * Parse request to find correct WordPress query. * * Sets up the query variables based on the request. There are also many * filters and actions that can be used to further manipulate the result. * * @since 2.0.0 * * @param array|string $extra_query_vars Set the extra query variables. */ function parse_request($extra_query_vars = '') { global $wp_rewrite; if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) ) return; $this->query_vars = array(); $post_type_query_vars = array(); if ( is_array($extra_query_vars) ) $this->extra_query_vars = & $extra_query_vars; else if (! empty($extra_query_vars)) parse_str($extra_query_vars, $this->extra_query_vars); // Process PATH_INFO, REQUEST_URI, and 404 for permalinks. // Fetch the rewrite rules. $rewrite = $wp_rewrite->wp_rewrite_rules(); if ( ! empty($rewrite) ) { // If we match a rewrite rule, this will be cleared. $error = '404'; $this->did_permalink = true; if ( isset($_SERVER['PATH_INFO']) ) $pathinfo = $_SERVER['PATH_INFO']; else $pathinfo = ''; $pathinfo_array = explode('?', $pathinfo); $pathinfo = str_replace("%", "%25", $pathinfo_array[0]); $req_uri = $_SERVER['REQUEST_URI']; $req_uri_array = explode('?', $req_uri); $req_uri = $req_uri_array[0]; $self = $_SERVER['PHP_SELF']; $home_path = parse_url(home_url()); if ( isset($home_path['path']) ) $home_path = $home_path['path']; else $home_path = ''; $home_path = trim($home_path, '/'); // Trim path info from the end and the leading home path from the // front. For path info requests, this leaves us with the requesting // filename, if any. For 404 requests, this leaves us with the // requested permalink. $req_uri = str_replace($pathinfo, '', $req_uri); $req_uri = trim($req_uri, '/'); $req_uri = preg_replace("|^$home_path|i", '', $req_uri); $req_uri = trim($req_uri, '/'); $pathinfo = trim($pathinfo, '/'); $pathinfo = preg_replace("|^$home_path|i", '', $pathinfo); $pathinfo = trim($pathinfo, '/'); $self = trim($self, '/'); $self = preg_replace("|^$home_path|i", '', $self); $self = trim($self, '/'); // The requested permalink is in $pathinfo for path info requests and // $req_uri for other requests. if ( ! empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo) ) { $request = $pathinfo; } else { // If the request uri is the index, blank it out so that we don't try to match it against a rule. if ( $req_uri == $wp_rewrite->index ) $req_uri = ''; $request = $req_uri; } $this->request = $request; // Look for matches. $request_match = $request; if ( empty( $request_match ) ) { // An empty request could only match against ^$ regex if ( isset( $rewrite['$'] ) ) { $this->matched_rule = '$'; $query = $rewrite['$']; $matches = array(''); } } else { foreach ( (array) $rewrite as $match => $query ) { // If the requesting file is the anchor of the match, prepend it to the path info. if ( ! empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request ) $request_match = $req_uri . '/' . $request; if ( preg_match("#^$match#", $request_match, $matches) || preg_match("#^$match#", urldecode($request_match), $matches) ) { if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) { // this is a verbose page match, lets check to be sure about it if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) ) continue; } // Got a match. $this->matched_rule = $match; break; } } } if ( isset( $this->matched_rule ) ) { // Trim the query of everything up to the '?'. $query = preg_replace("!^.+\?!", '', $query); // Substitute the substring matches into the query. $query = addslashes(WP_MatchesMapRegex::apply($query, $matches)); $this->matched_query = $query; // Parse the query. parse_str($query, $perma_query_vars); // If we're processing a 404 request, clear the error var since we found something. if ( '404' == $error ) unset( $error, $_GET['error'] ); } // If req_uri is empty or if it is a request for ourself, unset error. if ( empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) { unset( $error, $_GET['error'] ); if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) unset( $perma_query_vars ); $this->did_permalink = false; } } $this->public_query_vars = apply_filters('query_vars', $this->public_query_vars); foreach ( $GLOBALS['wp_post_types'] as $post_type => $t ) if ( $t->query_var ) $post_type_query_vars[$t->query_var] = $post_type; foreach ( $this->public_query_vars as $wpvar ) { if ( isset( $this->extra_query_vars[$wpvar] ) ) $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar]; elseif ( isset( $_POST[$wpvar] ) ) $this->query_vars[$wpvar] = $_POST[$wpvar]; elseif ( isset( $_GET[$wpvar] ) ) $this->query_vars[$wpvar] = $_GET[$wpvar]; elseif ( isset( $perma_query_vars[$wpvar] ) ) $this->query_vars[$wpvar] = $perma_query_vars[$wpvar]; if ( !empty( $this->query_vars[$wpvar] ) ) { if ( ! is_array( $this->query_vars[$wpvar] ) ) { $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar]; } else { foreach ( $this->query_vars[$wpvar] as $vkey => $v ) { if ( !is_object( $v ) ) { $this->query_vars[$wpvar][$vkey] = (string) $v; } } } if ( isset($post_type_query_vars[$wpvar] ) ) { $this->query_vars['post_type'] = $post_type_query_vars[$wpvar]; $this->query_vars['name'] = $this->query_vars[$wpvar]; } } } // Convert urldecoded spaces back into + foreach ( $GLOBALS['wp_taxonomies'] as $taxonomy => $t ) if ( $t->query_var && isset( $this->query_vars[$t->query_var] ) ) $this->query_vars[$t->query_var] = str_replace( ' ', '+', $this->query_vars[$t->query_var] ); // Limit publicly queried post_types to those that are publicly_queryable if ( isset( $this->query_vars['post_type']) ) { $queryable_post_types = get_post_types( array('publicly_queryable' => true) ); if ( ! is_array( $this->query_vars['post_type'] ) ) { if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) ) unset( $this->query_vars['post_type'] ); } else { $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types ); } } foreach ( (array) $this->private_query_vars as $var) { if ( isset($this->extra_query_vars[$var]) ) $this->query_vars[$var] = $this->extra_query_vars[$var]; } if ( isset($error) ) $this->query_vars['error'] = $error; $this->query_vars = apply_filters('request', $this->query_vars); do_action_ref_array('parse_request', array(&$this)); } /** * Send additional HTTP headers for caching, content type, etc. * * Sets the X-Pingback header, 404 status (if 404), Content-type. If showing * a feed, it will also send last-modified, etag, and 304 status if needed. * * @since 2.0.0 */ function send_headers() { $headers = array('X-Pingback' => get_bloginfo('pingback_url')); $status = null; $exit_required = false; if ( is_user_logged_in() ) $headers = array_merge($headers, wp_get_nocache_headers()); if ( ! empty( $this->query_vars['error'] ) ) { $status = (int) $this->query_vars['error']; if ( 404 === $status ) { if ( ! is_user_logged_in() ) $headers = array_merge($headers, wp_get_nocache_headers()); $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset'); } elseif ( in_array( $status, array( 403, 500, 502, 503 ) ) ) { $exit_required = true; } } else if ( empty($this->query_vars['feed']) ) { $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset'); } else { // We're showing a feed, so WP is indeed the only thing that last changed if ( !empty($this->query_vars['withcomments']) || ( empty($this->query_vars['withoutcomments']) && ( !empty($this->query_vars['p']) || !empty($this->query_vars['name']) || !empty($this->query_vars['page_id']) || !empty($this->query_vars['pagename']) || !empty($this->query_vars['attachment']) || !empty($this->query_vars['attachment_id']) ) ) ) $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT'; else $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT'; $wp_etag = '"' . md5($wp_last_modified) . '"'; $headers['Last-Modified'] = $wp_last_modified; $headers['ETag'] = $wp_etag; // Support for Conditional GET if (isset($_SERVER['HTTP_IF_NONE_MATCH'])) $client_etag = stripslashes(stripslashes($_SERVER['HTTP_IF_NONE_MATCH'])); else $client_etag = false; $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']); // If string is empty, return 0. If not, attempt to parse into a timestamp $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0; // Make a timestamp for our most recent modification... $wp_modified_timestamp = strtotime($wp_last_modified); if ( ($client_last_modified && $client_etag) ? (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) : (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) { $status = 304; $exit_required = true; } } $headers = apply_filters('wp_headers', $headers, $this); if ( ! empty( $status ) ) status_header( $status ); foreach( (array) $headers as $name => $field_value ) @header("{$name}: {$field_value}"); if ( isset( $headers['Last-Modified'] ) && empty( $headers['Last-Modified'] ) && function_exists( 'header_remove' ) ) @header_remove( 'Last-Modified' ); if ( $exit_required ) exit(); do_action_ref_array('send_headers', array(&$this)); } /** * Sets the query string property based off of the query variable property. * * The 'query_string' filter is deprecated, but still works. Plugins should * use the 'request' filter instead. * * @since 2.0.0 */ function build_query_string() { $this->query_string = ''; foreach ( (array) array_keys($this->query_vars) as $wpvar) { if ( '' != $this->query_vars[$wpvar] ) { $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&'; if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars. continue; $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]); } } // query_string filter deprecated. Use request filter instead. if ( has_filter('query_string') ) { // Don't bother filtering and parsing if no plugins are hooked in. $this->query_string = apply_filters('query_string', $this->query_string); parse_str($this->query_string, $this->query_vars); } } /** * Set up the WordPress Globals. * * The query_vars property will be extracted to the GLOBALS. So care should * be taken when naming global variables that might interfere with the * WordPress environment. * * @global string $query_string Query string for the loop. * @global int $more Only set, if single page or post. * @global int $single If single page or post. Only set, if single page or post. * * @since 2.0.0 */ function register_globals() { global $wp_query; // Extract updated query vars back into global namespace. foreach ( (array) $wp_query->query_vars as $key => $value) { $GLOBALS[$key] = $value; } $GLOBALS['query_string'] = $this->query_string; $GLOBALS['posts'] = & $wp_query->posts; $GLOBALS['post'] = (isset($wp_query->post)) ? $wp_query->post : null; $GLOBALS['request'] = $wp_query->request; if ( is_single() || is_page() ) { $GLOBALS['more'] = 1; $GLOBALS['single'] = 1; } } /** * Set up the current user. * * @since 2.0.0 */ function init() { wp_get_current_user(); } /** * Set up the Loop based on the query variables. * * @uses WP::$query_vars * @since 2.0.0 */ function query_posts() { global $wp_the_query; $this->build_query_string(); $wp_the_query->query($this->query_vars); } /** * Set the Headers for 404, if nothing is found for requested URL. * * Issue a 404 if a request doesn't match any posts and doesn't match * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already * issued, and if the request was not a search or the homepage. * * Otherwise, issue a 200. * * @since 2.0.0 */ function handle_404() { global $wp_query; // If we've already issued a 404, bail. if ( is_404() ) return; // Never 404 for the admin, robots, or if we found posts. if ( is_admin() || is_robots() || $wp_query->posts ) { status_header( 200 ); return; } // We will 404 for paged queries, as no posts were found. if ( ! is_paged() ) { // Don't 404 for these queries if they matched an object. if ( ( is_tag() || is_category() || is_tax() || is_author() || is_post_type_archive() ) && $wp_query->get_queried_object() ) { status_header( 200 ); return; } // Don't 404 for these queries either. if ( is_home() || is_search() ) { status_header( 200 ); return; } } // Guess it's time to 404. $wp_query->set_404(); status_header( 404 ); nocache_headers(); } /** * Sets up all of the variables required by the WordPress environment. * * The action 'wp' has one parameter that references the WP object. It * allows for accessing the properties and methods to further manipulate the * object. * * @since 2.0.0 * * @param string|array $query_args Passed to {@link parse_request()} */ function main($query_args = '') { $this->init(); $this->parse_request($query_args); $this->send_headers(); $this->query_posts(); $this->handle_404(); $this->register_globals(); do_action_ref_array('wp', array(&$this)); } } /** * Helper class to remove the need to use eval to replace $matches[] in query strings. * * @since 2.9.0 */ class WP_MatchesMapRegex { /** * store for matches * * @access private * @var array */ var $_matches; /** * store for mapping result * * @access public * @var string */ var $output; /** * subject to perform mapping on (query string containing $matches[] references * * @access private * @var string */ var $_subject; /** * regexp pattern to match $matches[] references * * @var string */ var $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number /** * constructor * * @param string $subject subject if regex * @param array $matches data to use in map * @return self */ function WP_MatchesMapRegex($subject, $matches) { $this->_subject = $subject; $this->_matches = $matches; $this->output = $this->_map(); } /** * Substitute substring matches in subject. * * static helper function to ease use * * @access public * @param string $subject subject * @param array $matches data used for substitution * @return string */ public static function apply($subject, $matches) { $oSelf = new WP_MatchesMapRegex($subject, $matches); return $oSelf->output; } /** * do the actual mapping * * @access private * @return string */ function _map() { $callback = array($this, 'callback'); return preg_replace_callback($this->_pattern, $callback, $this->_subject); } /** * preg_replace_callback hook * * @access public * @param array $matches preg_replace regexp matches * @return string */ function callback($matches) { $index = intval(substr($matches[0], 9, -1)); return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' ); } }
zyblog
trunk/zyblog/wp-includes/class-wp.php
PHP
asf20
18,610
<?php /** * WordPress Imagick Image Editor * * @package WordPress * @subpackage Image_Editor */ /** * WordPress Image Editor Class for Image Manipulation through Imagick PHP Module * * @since 3.5.0 * @package WordPress * @subpackage Image_Editor * @uses WP_Image_Editor Extends class */ class WP_Image_Editor_Imagick extends WP_Image_Editor { protected $image = null; // Imagick Object function __destruct() { if ( $this->image ) { // we don't need the original in memory anymore $this->image->clear(); $this->image->destroy(); } } /** * Checks to see if current environment supports Imagick. * * We require Imagick 2.2.0 or greater, based on whether the queryFormats() * method can be called statically. * * @since 3.5.0 * @access public * * @return boolean */ public static function test( $args = array() ) { // First, test Imagick's extension and classes. if ( ! extension_loaded( 'imagick' ) || ! class_exists( 'Imagick' ) || ! class_exists( 'ImagickPixel' ) ) return false; if ( version_compare( phpversion( 'imagick' ), '2.2.0', '<' ) ) return false; $required_methods = array( 'clear', 'destroy', 'valid', 'getimage', 'writeimage', 'getimageblob', 'getimagegeometry', 'getimageformat', 'setimageformat', 'setimagecompression', 'setimagecompressionquality', 'setimagepage', 'scaleimage', 'cropimage', 'rotateimage', 'flipimage', 'flopimage', ); // Now, test for deep requirements within Imagick. if ( ! defined( 'imagick::COMPRESSION_JPEG' ) ) return false; if ( array_diff( $required_methods, get_class_methods( 'Imagick' ) ) ) return false; return true; } /** * Checks to see if editor supports the mime-type specified. * * @since 3.5.0 * @access public * * @param string $mime_type * @return boolean */ public static function supports_mime_type( $mime_type ) { $imagick_extension = strtoupper( self::get_extension( $mime_type ) ); if ( ! $imagick_extension ) return false; // setIteratorIndex is optional unless mime is an animated format. // Here, we just say no if you are missing it and aren't loading a jpeg. if ( ! method_exists( 'Imagick', 'setIteratorIndex' ) && $mime_type != 'image/jpeg' ) return false; try { return ( (bool) Imagick::queryFormats( $imagick_extension ) ); } catch ( Exception $e ) { return false; } } /** * Loads image from $this->file into new Imagick Object. * * @since 3.5.0 * @access protected * * @return boolean|WP_Error True if loaded; WP_Error on failure. */ public function load() { if ( $this->image ) return true; if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) ) return new WP_Error( 'error_loading_image', __('File doesn&#8217;t exist?'), $this->file ); // Even though Imagick uses less PHP memory than GD, set higher limit for users that have low PHP.ini limits @ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) ); try { $this->image = new Imagick( $this->file ); if( ! $this->image->valid() ) return new WP_Error( 'invalid_image', __('File is not an image.'), $this->file); // Select the first frame to handle animated images properly if ( is_callable( array( $this->image, 'setIteratorIndex' ) ) ) $this->image->setIteratorIndex(0); $this->mime_type = $this->get_mime_type( $this->image->getImageFormat() ); } catch ( Exception $e ) { return new WP_Error( 'invalid_image', $e->getMessage(), $this->file ); } $updated_size = $this->update_size(); if ( is_wp_error( $updated_size ) ) return $updated_size; return $this->set_quality(); } /** * Sets Image Compression quality on a 1-100% scale. * * @since 3.5.0 * @access public * * @param int $quality Compression Quality. Range: [1,100] * @return boolean|WP_Error */ public function set_quality( $quality = null ) { if ( !$quality ) $quality = $this->quality; try { if( 'image/jpeg' == $this->mime_type ) { $this->image->setImageCompressionQuality( apply_filters( 'jpeg_quality', $quality, 'image_resize' ) ); $this->image->setImageCompression( imagick::COMPRESSION_JPEG ); } else { $this->image->setImageCompressionQuality( $quality ); } } catch ( Exception $e ) { return new WP_Error( 'image_quality_error', $e->getMessage() ); } return parent::set_quality( $quality ); } /** * Sets or updates current image size. * * @since 3.5.0 * @access protected * * @param int $width * @param int $height */ protected function update_size( $width = null, $height = null ) { $size = null; if ( !$width || !$height ) { try { $size = $this->image->getImageGeometry(); } catch ( Exception $e ) { return new WP_Error( 'invalid_image', __('Could not read image size'), $this->file ); } } if ( ! $width ) $width = $size['width']; if ( ! $height ) $height = $size['height']; return parent::update_size( $width, $height ); } /** * Resizes current image. * * @since 3.5.0 * @access public * * @param int $max_w * @param int $max_h * @param boolean $crop * @return boolean|WP_Error */ public function resize( $max_w, $max_h, $crop = false ) { if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) ) return true; $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop ); if ( ! $dims ) return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') ); list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims; if ( $crop ) { return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h ); } try { /** * @TODO: Thumbnail is more efficient, given a newer version of Imagemagick. * $this->image->thumbnailImage( $dst_w, $dst_h ); */ $this->image->scaleImage( $dst_w, $dst_h ); } catch ( Exception $e ) { return new WP_Error( 'image_resize_error', $e->getMessage() ); } return $this->update_size( $dst_w, $dst_h ); } /** * Processes current image and saves to disk * multiple sizes from single source. * * @since 3.5.0 * @access public * * @param array $sizes { {'width'=>int, 'height'=>int, 'crop'=>bool}, ... } * @return array */ public function multi_resize( $sizes ) { $metadata = array(); $orig_size = $this->size; $orig_image = $this->image->getImage(); foreach ( $sizes as $size => $size_data ) { if ( ! $this->image ) $this->image = $orig_image->getImage(); $resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] ); if( ! is_wp_error( $resize_result ) ) { $resized = $this->_save( $this->image ); $this->image->clear(); $this->image->destroy(); $this->image = null; if ( ! is_wp_error( $resized ) && $resized ) { unset( $resized['path'] ); $metadata[$size] = $resized; } } $this->size = $orig_size; } $this->image = $orig_image; return $metadata; } /** * Crops Image. * * @since 3.5.0 * @access public * * @param string|int $src The source file or Attachment ID. * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w Optional. The destination width. * @param int $dst_h Optional. The destination height. * @param boolean $src_abs Optional. If the source crop points are absolute. * @return boolean|WP_Error */ public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) { if ( $src_abs ) { $src_w -= $src_x; $src_h -= $src_y; } try { $this->image->cropImage( $src_w, $src_h, $src_x, $src_y ); $this->image->setImagePage( $src_w, $src_h, 0, 0); if ( $dst_w || $dst_h ) { // If destination width/height isn't specified, use same as // width/height from source. if ( ! $dst_w ) $dst_w = $src_w; if ( ! $dst_h ) $dst_h = $src_h; $this->image->scaleImage( $dst_w, $dst_h ); return $this->update_size(); } } catch ( Exception $e ) { return new WP_Error( 'image_crop_error', $e->getMessage() ); } return $this->update_size(); } /** * Rotates current image counter-clockwise by $angle. * * @since 3.5.0 * @access public * * @param float $angle * @return boolean|WP_Error */ public function rotate( $angle ) { /** * $angle is 360-$angle because Imagick rotates clockwise * (GD rotates counter-clockwise) */ try { $this->image->rotateImage( new ImagickPixel('none'), 360-$angle ); } catch ( Exception $e ) { return new WP_Error( 'image_rotate_error', $e->getMessage() ); } return $this->update_size(); } /** * Flips current image. * * @since 3.5.0 * @access public * * @param boolean $horz Horizontal Flip * @param boolean $vert Vertical Flip * @returns boolean|WP_Error */ public function flip( $horz, $vert ) { try { if ( $horz ) $this->image->flipImage(); if ( $vert ) $this->image->flopImage(); } catch ( Exception $e ) { return new WP_Error( 'image_flip_error', $e->getMessage() ); } return true; } /** * Saves current image to file. * * @since 3.5.0 * @access public * * @param string $destfilename * @param string $mime_type * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string} */ public function save( $destfilename = null, $mime_type = null ) { $saved = $this->_save( $this->image, $destfilename, $mime_type ); if ( ! is_wp_error( $saved ) ) { $this->file = $saved['path']; $this->mime_type = $saved['mime-type']; try { $this->image->setImageFormat( strtoupper( $this->get_extension( $this->mime_type ) ) ); } catch ( Exception $e ) { return new WP_Error( 'image_save_error', $e->getMessage(), $this->file ); } } return $saved; } protected function _save( $image, $filename = null, $mime_type = null ) { list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type ); if ( ! $filename ) $filename = $this->generate_filename( null, null, $extension ); try { // Store initial Format $orig_format = $this->image->getImageFormat(); $this->image->setImageFormat( strtoupper( $this->get_extension( $mime_type ) ) ); $this->make_image( $filename, array( $image, 'writeImage' ), array( $filename ) ); // Reset original Format $this->image->setImageFormat( $orig_format ); } catch ( Exception $e ) { return new WP_Error( 'image_save_error', $e->getMessage(), $filename ); } // Set correct file permissions $stat = stat( dirname( $filename ) ); $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits @ chmod( $filename, $perms ); return array( 'path' => $filename, 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ), 'width' => $this->size['width'], 'height' => $this->size['height'], 'mime-type' => $mime_type, ); } /** * Streams current image to browser. * * @since 3.5.0 * @access public * * @param string $mime_type * @return boolean|WP_Error */ public function stream( $mime_type = null ) { list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type ); try { // Temporarily change format for stream $this->image->setImageFormat( strtoupper( $extension ) ); // Output stream of image content header( "Content-Type: $mime_type" ); print $this->image->getImageBlob(); // Reset Image to original Format $this->image->setImageFormat( $this->get_extension( $this->mime_type ) ); } catch ( Exception $e ) { return new WP_Error( 'image_stream_error', $e->getMessage() ); } return true; } }
zyblog
trunk/zyblog/wp-includes/class-wp-image-editor-imagick.php
PHP
asf20
12,063
<?php /** * General API for generating and formatting diffs - the differences between * two sequences of strings. * * The original PHP version of this code was written by Geoffrey T. Dairiki * <dairiki@dairiki.org>, and is used/adapted with his permission. * * Copyright 2004 Geoffrey T. Dairiki <dairiki@dairiki.org> * Copyright 2004-2010 The Horde Project (http://www.horde.org/) * * See the enclosed file COPYING for license information (LGPL). If you did * not receive this file, see http://opensource.org/licenses/lgpl-license.php. * * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> */ class Text_Diff { /** * Array of changes. * * @var array */ var $_edits; /** * Computes diffs between sequences of strings. * * @param string $engine Name of the diffing engine to use. 'auto' * will automatically select the best. * @param array $params Parameters to pass to the diffing engine. * Normally an array of two arrays, each * containing the lines from a file. */ function Text_Diff($engine, $params) { // Backward compatibility workaround. if (!is_string($engine)) { $params = array($engine, $params); $engine = 'auto'; } if ($engine == 'auto') { $engine = extension_loaded('xdiff') ? 'xdiff' : 'native'; } else { $engine = basename($engine); } // WP #7391 require_once dirname(__FILE__).'/Diff/Engine/' . $engine . '.php'; $class = 'Text_Diff_Engine_' . $engine; $diff_engine = new $class(); $this->_edits = call_user_func_array(array($diff_engine, 'diff'), $params); } /** * Returns the array of differences. */ function getDiff() { return $this->_edits; } /** * returns the number of new (added) lines in a given diff. * * @since Text_Diff 1.1.0 * * @return integer The number of new lines */ function countAddedLines() { $count = 0; foreach ($this->_edits as $edit) { if (is_a($edit, 'Text_Diff_Op_add') || is_a($edit, 'Text_Diff_Op_change')) { $count += $edit->nfinal(); } } return $count; } /** * Returns the number of deleted (removed) lines in a given diff. * * @since Text_Diff 1.1.0 * * @return integer The number of deleted lines */ function countDeletedLines() { $count = 0; foreach ($this->_edits as $edit) { if (is_a($edit, 'Text_Diff_Op_delete') || is_a($edit, 'Text_Diff_Op_change')) { $count += $edit->norig(); } } return $count; } /** * Computes a reversed diff. * * Example: * <code> * $diff = new Text_Diff($lines1, $lines2); * $rev = $diff->reverse(); * </code> * * @return Text_Diff A Diff object representing the inverse of the * original diff. Note that we purposely don't return a * reference here, since this essentially is a clone() * method. */ function reverse() { if (version_compare(zend_version(), '2', '>')) { $rev = clone($this); } else { $rev = $this; } $rev->_edits = array(); foreach ($this->_edits as $edit) { $rev->_edits[] = $edit->reverse(); } return $rev; } /** * Checks for an empty diff. * * @return boolean True if two sequences were identical. */ function isEmpty() { foreach ($this->_edits as $edit) { if (!is_a($edit, 'Text_Diff_Op_copy')) { return false; } } return true; } /** * Computes the length of the Longest Common Subsequence (LCS). * * This is mostly for diagnostic purposes. * * @return integer The length of the LCS. */ function lcs() { $lcs = 0; foreach ($this->_edits as $edit) { if (is_a($edit, 'Text_Diff_Op_copy')) { $lcs += count($edit->orig); } } return $lcs; } /** * Gets the original set of lines. * * This reconstructs the $from_lines parameter passed to the constructor. * * @return array The original sequence of strings. */ function getOriginal() { $lines = array(); foreach ($this->_edits as $edit) { if ($edit->orig) { array_splice($lines, count($lines), 0, $edit->orig); } } return $lines; } /** * Gets the final set of lines. * * This reconstructs the $to_lines parameter passed to the constructor. * * @return array The sequence of strings. */ function getFinal() { $lines = array(); foreach ($this->_edits as $edit) { if ($edit->final) { array_splice($lines, count($lines), 0, $edit->final); } } return $lines; } /** * Removes trailing newlines from a line of text. This is meant to be used * with array_walk(). * * @param string $line The line to trim. * @param integer $key The index of the line in the array. Not used. */ function trimNewlines(&$line, $key) { $line = str_replace(array("\n", "\r"), '', $line); } /** * Determines the location of the system temporary directory. * * @static * * @access protected * * @return string A directory name which can be used for temp files. * Returns false if one could not be found. */ function _getTempDir() { $tmp_locations = array('/tmp', '/var/tmp', 'c:\WUTemp', 'c:\temp', 'c:\windows\temp', 'c:\winnt\temp'); /* Try PHP's upload_tmp_dir directive. */ $tmp = ini_get('upload_tmp_dir'); /* Otherwise, try to determine the TMPDIR environment variable. */ if (!strlen($tmp)) { $tmp = getenv('TMPDIR'); } /* If we still cannot determine a value, then cycle through a list of * preset possibilities. */ while (!strlen($tmp) && count($tmp_locations)) { $tmp_check = array_shift($tmp_locations); if (@is_dir($tmp_check)) { $tmp = $tmp_check; } } /* If it is still empty, we have failed, so return false; otherwise * return the directory determined. */ return strlen($tmp) ? $tmp : false; } /** * Checks a diff for validity. * * This is here only for debugging purposes. */ function _check($from_lines, $to_lines) { if (serialize($from_lines) != serialize($this->getOriginal())) { trigger_error("Reconstructed original doesn't match", E_USER_ERROR); } if (serialize($to_lines) != serialize($this->getFinal())) { trigger_error("Reconstructed final doesn't match", E_USER_ERROR); } $rev = $this->reverse(); if (serialize($to_lines) != serialize($rev->getOriginal())) { trigger_error("Reversed original doesn't match", E_USER_ERROR); } if (serialize($from_lines) != serialize($rev->getFinal())) { trigger_error("Reversed final doesn't match", E_USER_ERROR); } $prevtype = null; foreach ($this->_edits as $edit) { if ($prevtype == get_class($edit)) { trigger_error("Edit sequence is non-optimal", E_USER_ERROR); } $prevtype = get_class($edit); } return true; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> */ class Text_MappedDiff extends Text_Diff { /** * Computes a diff between sequences of strings. * * This can be used to compute things like case-insensitve diffs, or diffs * which ignore changes in white-space. * * @param array $from_lines An array of strings. * @param array $to_lines An array of strings. * @param array $mapped_from_lines This array should have the same size * number of elements as $from_lines. The * elements in $mapped_from_lines and * $mapped_to_lines are what is actually * compared when computing the diff. * @param array $mapped_to_lines This array should have the same number * of elements as $to_lines. */ function Text_MappedDiff($from_lines, $to_lines, $mapped_from_lines, $mapped_to_lines) { assert(count($from_lines) == count($mapped_from_lines)); assert(count($to_lines) == count($mapped_to_lines)); parent::Text_Diff($mapped_from_lines, $mapped_to_lines); $xi = $yi = 0; for ($i = 0; $i < count($this->_edits); $i++) { $orig = &$this->_edits[$i]->orig; if (is_array($orig)) { $orig = array_slice($from_lines, $xi, count($orig)); $xi += count($orig); } $final = &$this->_edits[$i]->final; if (is_array($final)) { $final = array_slice($to_lines, $yi, count($final)); $yi += count($final); } } } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op { var $orig; var $final; function &reverse() { trigger_error('Abstract method', E_USER_ERROR); } function norig() { return $this->orig ? count($this->orig) : 0; } function nfinal() { return $this->final ? count($this->final) : 0; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_copy extends Text_Diff_Op { function Text_Diff_Op_copy($orig, $final = false) { if (!is_array($final)) { $final = $orig; } $this->orig = $orig; $this->final = $final; } function &reverse() { $reverse = &new Text_Diff_Op_copy($this->final, $this->orig); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_delete extends Text_Diff_Op { function Text_Diff_Op_delete($lines) { $this->orig = $lines; $this->final = false; } function &reverse() { $reverse = &new Text_Diff_Op_add($this->orig); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_add extends Text_Diff_Op { function Text_Diff_Op_add($lines) { $this->final = $lines; $this->orig = false; } function &reverse() { $reverse = &new Text_Diff_Op_delete($this->final); return $reverse; } } /** * @package Text_Diff * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * * @access private */ class Text_Diff_Op_change extends Text_Diff_Op { function Text_Diff_Op_change($orig, $final) { $this->orig = $orig; $this->final = $final; } function &reverse() { $reverse = &new Text_Diff_Op_change($this->final, $this->orig); return $reverse; } }
zyblog
trunk/zyblog/wp-includes/Text/Diff.php
PHP
asf20
11,942
<?php /** * "Inline" diff renderer. * * Copyright 2004-2010 The Horde Project (http://www.horde.org/) * * See the enclosed file COPYING for license information (LGPL). If you did * not receive this file, see http://opensource.org/licenses/lgpl-license.php. * * @author Ciprian Popovici * @package Text_Diff */ /** Text_Diff_Renderer */ // WP #7391 require_once dirname(dirname(__FILE__)) . '/Renderer.php'; /** * "Inline" diff renderer. * * This class renders diffs in the Wiki-style "inline" format. * * @author Ciprian Popovici * @package Text_Diff */ class Text_Diff_Renderer_inline extends Text_Diff_Renderer { /** * Number of leading context "lines" to preserve. * * @var integer */ var $_leading_context_lines = 10000; /** * Number of trailing context "lines" to preserve. * * @var integer */ var $_trailing_context_lines = 10000; /** * Prefix for inserted text. * * @var string */ var $_ins_prefix = '<ins>'; /** * Suffix for inserted text. * * @var string */ var $_ins_suffix = '</ins>'; /** * Prefix for deleted text. * * @var string */ var $_del_prefix = '<del>'; /** * Suffix for deleted text. * * @var string */ var $_del_suffix = '</del>'; /** * Header for each change block. * * @var string */ var $_block_header = ''; /** * Whether to split down to character-level. * * @var boolean */ var $_split_characters = false; /** * What are we currently splitting on? Used to recurse to show word-level * or character-level changes. * * @var string */ var $_split_level = 'lines'; function _blockHeader($xbeg, $xlen, $ybeg, $ylen) { return $this->_block_header; } function _startBlock($header) { return $header; } function _lines($lines, $prefix = ' ', $encode = true) { if ($encode) { array_walk($lines, array(&$this, '_encode')); } if ($this->_split_level == 'lines') { return implode("\n", $lines) . "\n"; } else { return implode('', $lines); } } function _added($lines) { array_walk($lines, array(&$this, '_encode')); $lines[0] = $this->_ins_prefix . $lines[0]; $lines[count($lines) - 1] .= $this->_ins_suffix; return $this->_lines($lines, ' ', false); } function _deleted($lines, $words = false) { array_walk($lines, array(&$this, '_encode')); $lines[0] = $this->_del_prefix . $lines[0]; $lines[count($lines) - 1] .= $this->_del_suffix; return $this->_lines($lines, ' ', false); } function _changed($orig, $final) { /* If we've already split on characters, just display. */ if ($this->_split_level == 'characters') { return $this->_deleted($orig) . $this->_added($final); } /* If we've already split on words, just display. */ if ($this->_split_level == 'words') { $prefix = ''; while ($orig[0] !== false && $final[0] !== false && substr($orig[0], 0, 1) == ' ' && substr($final[0], 0, 1) == ' ') { $prefix .= substr($orig[0], 0, 1); $orig[0] = substr($orig[0], 1); $final[0] = substr($final[0], 1); } return $prefix . $this->_deleted($orig) . $this->_added($final); } $text1 = implode("\n", $orig); $text2 = implode("\n", $final); /* Non-printing newline marker. */ $nl = "\0"; if ($this->_split_characters) { $diff = new Text_Diff('native', array(preg_split('//', $text1), preg_split('//', $text2))); } else { /* We want to split on word boundaries, but we need to preserve * whitespace as well. Therefore we split on words, but include * all blocks of whitespace in the wordlist. */ $diff = new Text_Diff('native', array($this->_splitOnWords($text1, $nl), $this->_splitOnWords($text2, $nl))); } /* Get the diff in inline format. */ $renderer = new Text_Diff_Renderer_inline (array_merge($this->getParams(), array('split_level' => $this->_split_characters ? 'characters' : 'words'))); /* Run the diff and get the output. */ return str_replace($nl, "\n", $renderer->render($diff)) . "\n"; } function _splitOnWords($string, $newlineEscape = "\n") { // Ignore \0; otherwise the while loop will never finish. $string = str_replace("\0", '', $string); $words = array(); $length = strlen($string); $pos = 0; while ($pos < $length) { // Eat a word with any preceding whitespace. $spaces = strspn(substr($string, $pos), " \n"); $nextpos = strcspn(substr($string, $pos + $spaces), " \n"); $words[] = str_replace("\n", $newlineEscape, substr($string, $pos, $spaces + $nextpos)); $pos += $spaces + $nextpos; } return $words; } function _encode(&$string) { $string = htmlspecialchars($string); } }
zyblog
trunk/zyblog/wp-includes/Text/Diff/Renderer/inline.php
PHP
asf20
5,535
<?php /** * Class used internally by Text_Diff to actually compute the diffs. * * This class is implemented using native PHP code. * * The algorithm used here is mostly lifted from the perl module * Algorithm::Diff (version 1.06) by Ned Konz, which is available at: * http://www.perl.com/CPAN/authors/id/N/NE/NEDKONZ/Algorithm-Diff-1.06.zip * * More ideas are taken from: http://www.ics.uci.edu/~eppstein/161/960229.html * * Some ideas (and a bit of code) are taken from analyze.c, of GNU * diffutils-2.7, which can be found at: * ftp://gnudist.gnu.org/pub/gnu/diffutils/diffutils-2.7.tar.gz * * Some ideas (subdivision by NCHUNKS > 2, and some optimizations) are from * Geoffrey T. Dairiki <dairiki@dairiki.org>. The original PHP version of this * code was written by him, and is used/adapted with his permission. * * Copyright 2004-2010 The Horde Project (http://www.horde.org/) * * See the enclosed file COPYING for license information (LGPL). If you did * not receive this file, see http://opensource.org/licenses/lgpl-license.php. * * @author Geoffrey T. Dairiki <dairiki@dairiki.org> * @package Text_Diff */ class Text_Diff_Engine_native { function diff($from_lines, $to_lines) { array_walk($from_lines, array('Text_Diff', 'trimNewlines')); array_walk($to_lines, array('Text_Diff', 'trimNewlines')); $n_from = count($from_lines); $n_to = count($to_lines); $this->xchanged = $this->ychanged = array(); $this->xv = $this->yv = array(); $this->xind = $this->yind = array(); unset($this->seq); unset($this->in_seq); unset($this->lcs); // Skip leading common lines. for ($skip = 0; $skip < $n_from && $skip < $n_to; $skip++) { if ($from_lines[$skip] !== $to_lines[$skip]) { break; } $this->xchanged[$skip] = $this->ychanged[$skip] = false; } // Skip trailing common lines. $xi = $n_from; $yi = $n_to; for ($endskip = 0; --$xi > $skip && --$yi > $skip; $endskip++) { if ($from_lines[$xi] !== $to_lines[$yi]) { break; } $this->xchanged[$xi] = $this->ychanged[$yi] = false; } // Ignore lines which do not exist in both files. for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { $xhash[$from_lines[$xi]] = 1; } for ($yi = $skip; $yi < $n_to - $endskip; $yi++) { $line = $to_lines[$yi]; if (($this->ychanged[$yi] = empty($xhash[$line]))) { continue; } $yhash[$line] = 1; $this->yv[] = $line; $this->yind[] = $yi; } for ($xi = $skip; $xi < $n_from - $endskip; $xi++) { $line = $from_lines[$xi]; if (($this->xchanged[$xi] = empty($yhash[$line]))) { continue; } $this->xv[] = $line; $this->xind[] = $xi; } // Find the LCS. $this->_compareseq(0, count($this->xv), 0, count($this->yv)); // Merge edits when possible. $this->_shiftBoundaries($from_lines, $this->xchanged, $this->ychanged); $this->_shiftBoundaries($to_lines, $this->ychanged, $this->xchanged); // Compute the edit operations. $edits = array(); $xi = $yi = 0; while ($xi < $n_from || $yi < $n_to) { assert($yi < $n_to || $this->xchanged[$xi]); assert($xi < $n_from || $this->ychanged[$yi]); // Skip matching "snake". $copy = array(); while ($xi < $n_from && $yi < $n_to && !$this->xchanged[$xi] && !$this->ychanged[$yi]) { $copy[] = $from_lines[$xi++]; ++$yi; } if ($copy) { $edits[] = &new Text_Diff_Op_copy($copy); } // Find deletes & adds. $delete = array(); while ($xi < $n_from && $this->xchanged[$xi]) { $delete[] = $from_lines[$xi++]; } $add = array(); while ($yi < $n_to && $this->ychanged[$yi]) { $add[] = $to_lines[$yi++]; } if ($delete && $add) { $edits[] = &new Text_Diff_Op_change($delete, $add); } elseif ($delete) { $edits[] = &new Text_Diff_Op_delete($delete); } elseif ($add) { $edits[] = &new Text_Diff_Op_add($add); } } return $edits; } /** * Divides the Largest Common Subsequence (LCS) of the sequences (XOFF, * XLIM) and (YOFF, YLIM) into NCHUNKS approximately equally sized * segments. * * Returns (LCS, PTS). LCS is the length of the LCS. PTS is an array of * NCHUNKS+1 (X, Y) indexes giving the diving points between sub * sequences. The first sub-sequence is contained in (X0, X1), (Y0, Y1), * the second in (X1, X2), (Y1, Y2) and so on. Note that (X0, Y0) == * (XOFF, YOFF) and (X[NCHUNKS], Y[NCHUNKS]) == (XLIM, YLIM). * * This function assumes that the first lines of the specified portions of * the two files do not match, and likewise that the last lines do not * match. The caller must trim matching lines from the beginning and end * of the portions it is going to specify. */ function _diag ($xoff, $xlim, $yoff, $ylim, $nchunks) { $flip = false; if ($xlim - $xoff > $ylim - $yoff) { /* Things seems faster (I'm not sure I understand why) when the * shortest sequence is in X. */ $flip = true; list ($xoff, $xlim, $yoff, $ylim) = array($yoff, $ylim, $xoff, $xlim); } if ($flip) { for ($i = $ylim - 1; $i >= $yoff; $i--) { $ymatches[$this->xv[$i]][] = $i; } } else { for ($i = $ylim - 1; $i >= $yoff; $i--) { $ymatches[$this->yv[$i]][] = $i; } } $this->lcs = 0; $this->seq[0]= $yoff - 1; $this->in_seq = array(); $ymids[0] = array(); $numer = $xlim - $xoff + $nchunks - 1; $x = $xoff; for ($chunk = 0; $chunk < $nchunks; $chunk++) { if ($chunk > 0) { for ($i = 0; $i <= $this->lcs; $i++) { $ymids[$i][$chunk - 1] = $this->seq[$i]; } } $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $chunk) / $nchunks); for (; $x < $x1; $x++) { $line = $flip ? $this->yv[$x] : $this->xv[$x]; if (empty($ymatches[$line])) { continue; } $matches = $ymatches[$line]; reset($matches); while (list(, $y) = each($matches)) { if (empty($this->in_seq[$y])) { $k = $this->_lcsPos($y); assert($k > 0); $ymids[$k] = $ymids[$k - 1]; break; } } while (list(, $y) = each($matches)) { if ($y > $this->seq[$k - 1]) { assert($y <= $this->seq[$k]); /* Optimization: this is a common case: next match is * just replacing previous match. */ $this->in_seq[$this->seq[$k]] = false; $this->seq[$k] = $y; $this->in_seq[$y] = 1; } elseif (empty($this->in_seq[$y])) { $k = $this->_lcsPos($y); assert($k > 0); $ymids[$k] = $ymids[$k - 1]; } } } } $seps[] = $flip ? array($yoff, $xoff) : array($xoff, $yoff); $ymid = $ymids[$this->lcs]; for ($n = 0; $n < $nchunks - 1; $n++) { $x1 = $xoff + (int)(($numer + ($xlim - $xoff) * $n) / $nchunks); $y1 = $ymid[$n] + 1; $seps[] = $flip ? array($y1, $x1) : array($x1, $y1); } $seps[] = $flip ? array($ylim, $xlim) : array($xlim, $ylim); return array($this->lcs, $seps); } function _lcsPos($ypos) { $end = $this->lcs; if ($end == 0 || $ypos > $this->seq[$end]) { $this->seq[++$this->lcs] = $ypos; $this->in_seq[$ypos] = 1; return $this->lcs; } $beg = 1; while ($beg < $end) { $mid = (int)(($beg + $end) / 2); if ($ypos > $this->seq[$mid]) { $beg = $mid + 1; } else { $end = $mid; } } assert($ypos != $this->seq[$end]); $this->in_seq[$this->seq[$end]] = false; $this->seq[$end] = $ypos; $this->in_seq[$ypos] = 1; return $end; } /** * Finds LCS of two sequences. * * The results are recorded in the vectors $this->{x,y}changed[], by * storing a 1 in the element for each line that is an insertion or * deletion (ie. is not in the LCS). * * The subsequence of file 0 is (XOFF, XLIM) and likewise for file 1. * * Note that XLIM, YLIM are exclusive bounds. All line numbers are * origin-0 and discarded lines are not counted. */ function _compareseq ($xoff, $xlim, $yoff, $ylim) { /* Slide down the bottom initial diagonal. */ while ($xoff < $xlim && $yoff < $ylim && $this->xv[$xoff] == $this->yv[$yoff]) { ++$xoff; ++$yoff; } /* Slide up the top initial diagonal. */ while ($xlim > $xoff && $ylim > $yoff && $this->xv[$xlim - 1] == $this->yv[$ylim - 1]) { --$xlim; --$ylim; } if ($xoff == $xlim || $yoff == $ylim) { $lcs = 0; } else { /* This is ad hoc but seems to work well. $nchunks = * sqrt(min($xlim - $xoff, $ylim - $yoff) / 2.5); $nchunks = * max(2,min(8,(int)$nchunks)); */ $nchunks = min(7, $xlim - $xoff, $ylim - $yoff) + 1; list($lcs, $seps) = $this->_diag($xoff, $xlim, $yoff, $ylim, $nchunks); } if ($lcs == 0) { /* X and Y sequences have no common subsequence: mark all * changed. */ while ($yoff < $ylim) { $this->ychanged[$this->yind[$yoff++]] = 1; } while ($xoff < $xlim) { $this->xchanged[$this->xind[$xoff++]] = 1; } } else { /* Use the partitions to split this problem into subproblems. */ reset($seps); $pt1 = $seps[0]; while ($pt2 = next($seps)) { $this->_compareseq ($pt1[0], $pt2[0], $pt1[1], $pt2[1]); $pt1 = $pt2; } } } /** * Adjusts inserts/deletes of identical lines to join changes as much as * possible. * * We do something when a run of changed lines include a line at one end * and has an excluded, identical line at the other. We are free to * choose which identical line is included. `compareseq' usually chooses * the one at the beginning, but usually it is cleaner to consider the * following identical line to be the "change". * * This is extracted verbatim from analyze.c (GNU diffutils-2.7). */ function _shiftBoundaries($lines, &$changed, $other_changed) { $i = 0; $j = 0; assert('count($lines) == count($changed)'); $len = count($lines); $other_len = count($other_changed); while (1) { /* Scan forward to find the beginning of another run of * changes. Also keep track of the corresponding point in the * other file. * * Throughout this code, $i and $j are adjusted together so that * the first $i elements of $changed and the first $j elements of * $other_changed both contain the same number of zeros (unchanged * lines). * * Furthermore, $j is always kept so that $j == $other_len or * $other_changed[$j] == false. */ while ($j < $other_len && $other_changed[$j]) { $j++; } while ($i < $len && ! $changed[$i]) { assert('$j < $other_len && ! $other_changed[$j]'); $i++; $j++; while ($j < $other_len && $other_changed[$j]) { $j++; } } if ($i == $len) { break; } $start = $i; /* Find the end of this run of changes. */ while (++$i < $len && $changed[$i]) { continue; } do { /* Record the length of this run of changes, so that we can * later determine whether the run has grown. */ $runlength = $i - $start; /* Move the changed region back, so long as the previous * unchanged line matches the last changed one. This merges * with previous changed regions. */ while ($start > 0 && $lines[$start - 1] == $lines[$i - 1]) { $changed[--$start] = 1; $changed[--$i] = false; while ($start > 0 && $changed[$start - 1]) { $start--; } assert('$j > 0'); while ($other_changed[--$j]) { continue; } assert('$j >= 0 && !$other_changed[$j]'); } /* Set CORRESPONDING to the end of the changed run, at the * last point where it corresponds to a changed run in the * other file. CORRESPONDING == LEN means no such point has * been found. */ $corresponding = $j < $other_len ? $i : $len; /* Move the changed region forward, so long as the first * changed line matches the following unchanged one. This * merges with following changed regions. Do this second, so * that if there are no merges, the changed region is moved * forward as far as possible. */ while ($i < $len && $lines[$start] == $lines[$i]) { $changed[$start++] = false; $changed[$i++] = 1; while ($i < $len && $changed[$i]) { $i++; } assert('$j < $other_len && ! $other_changed[$j]'); $j++; if ($j < $other_len && $other_changed[$j]) { $corresponding = $i; while ($j < $other_len && $other_changed[$j]) { $j++; } } } } while ($runlength != $i - $start); /* If possible, move the fully-merged run of changes back to a * corresponding run in the other file. */ while ($corresponding < $i) { $changed[--$start] = 1; $changed[--$i] = 0; assert('$j > 0'); while ($other_changed[--$j]) { continue; } assert('$j >= 0 && !$other_changed[$j]'); } } } }
zyblog
trunk/zyblog/wp-includes/Text/Diff/Engine/native.php
PHP
asf20
15,844
<?php /** * Class used internally by Diff to actually compute the diffs. * * This class uses the xdiff PECL package (http://pecl.php.net/package/xdiff) * to compute the differences between the two input arrays. * * Copyright 2004-2010 The Horde Project (http://www.horde.org/) * * See the enclosed file COPYING for license information (LGPL). If you did * not receive this file, see http://opensource.org/licenses/lgpl-license.php. * * @author Jon Parise <jon@horde.org> * @package Text_Diff */ class Text_Diff_Engine_xdiff { /** */ function diff($from_lines, $to_lines) { array_walk($from_lines, array('Text_Diff', 'trimNewlines')); array_walk($to_lines, array('Text_Diff', 'trimNewlines')); /* Convert the two input arrays into strings for xdiff processing. */ $from_string = implode("\n", $from_lines); $to_string = implode("\n", $to_lines); /* Diff the two strings and convert the result to an array. */ $diff = xdiff_string_diff($from_string, $to_string, count($to_lines)); $diff = explode("\n", $diff); /* Walk through the diff one line at a time. We build the $edits * array of diff operations by reading the first character of the * xdiff output (which is in the "unified diff" format). * * Note that we don't have enough information to detect "changed" * lines using this approach, so we can't add Text_Diff_Op_changed * instances to the $edits array. The result is still perfectly * valid, albeit a little less descriptive and efficient. */ $edits = array(); foreach ($diff as $line) { if (!strlen($line)) { continue; } switch ($line[0]) { case ' ': $edits[] = &new Text_Diff_Op_copy(array(substr($line, 1))); break; case '+': $edits[] = &new Text_Diff_Op_add(array(substr($line, 1))); break; case '-': $edits[] = &new Text_Diff_Op_delete(array(substr($line, 1))); break; } } return $edits; } }
zyblog
trunk/zyblog/wp-includes/Text/Diff/Engine/xdiff.php
PHP
asf20
2,213
<?php /** * Class used internally by Diff to actually compute the diffs. * * This class uses the Unix `diff` program via shell_exec to compute the * differences between the two input arrays. * * Copyright 2007-2010 The Horde Project (http://www.horde.org/) * * See the enclosed file COPYING for license information (LGPL). If you did * not receive this file, see http://opensource.org/licenses/lgpl-license.php. * * @author Milian Wolff <mail@milianw.de> * @package Text_Diff * @since 0.3.0 */ class Text_Diff_Engine_shell { /** * Path to the diff executable * * @var string */ var $_diffCommand = 'diff'; /** * Returns the array of differences. * * @param array $from_lines lines of text from old file * @param array $to_lines lines of text from new file * * @return array all changes made (array with Text_Diff_Op_* objects) */ function diff($from_lines, $to_lines) { array_walk($from_lines, array('Text_Diff', 'trimNewlines')); array_walk($to_lines, array('Text_Diff', 'trimNewlines')); $temp_dir = Text_Diff::_getTempDir(); // Execute gnu diff or similar to get a standard diff file. $from_file = tempnam($temp_dir, 'Text_Diff'); $to_file = tempnam($temp_dir, 'Text_Diff'); $fp = fopen($from_file, 'w'); fwrite($fp, implode("\n", $from_lines)); fclose($fp); $fp = fopen($to_file, 'w'); fwrite($fp, implode("\n", $to_lines)); fclose($fp); $diff = shell_exec($this->_diffCommand . ' ' . $from_file . ' ' . $to_file); unlink($from_file); unlink($to_file); if (is_null($diff)) { // No changes were made return array(new Text_Diff_Op_copy($from_lines)); } $from_line_no = 1; $to_line_no = 1; $edits = array(); // Get changed lines by parsing something like: // 0a1,2 // 1,2c4,6 // 1,5d6 preg_match_all('#^(\d+)(?:,(\d+))?([adc])(\d+)(?:,(\d+))?$#m', $diff, $matches, PREG_SET_ORDER); foreach ($matches as $match) { if (!isset($match[5])) { // This paren is not set every time (see regex). $match[5] = false; } if ($match[3] == 'a') { $from_line_no--; } if ($match[3] == 'd') { $to_line_no--; } if ($from_line_no < $match[1] || $to_line_no < $match[4]) { // copied lines assert('$match[1] - $from_line_no == $match[4] - $to_line_no'); array_push($edits, new Text_Diff_Op_copy( $this->_getLines($from_lines, $from_line_no, $match[1] - 1), $this->_getLines($to_lines, $to_line_no, $match[4] - 1))); } switch ($match[3]) { case 'd': // deleted lines array_push($edits, new Text_Diff_Op_delete( $this->_getLines($from_lines, $from_line_no, $match[2]))); $to_line_no++; break; case 'c': // changed lines array_push($edits, new Text_Diff_Op_change( $this->_getLines($from_lines, $from_line_no, $match[2]), $this->_getLines($to_lines, $to_line_no, $match[5]))); break; case 'a': // added lines array_push($edits, new Text_Diff_Op_add( $this->_getLines($to_lines, $to_line_no, $match[5]))); $from_line_no++; break; } } if (!empty($from_lines)) { // Some lines might still be pending. Add them as copied array_push($edits, new Text_Diff_Op_copy( $this->_getLines($from_lines, $from_line_no, $from_line_no + count($from_lines) - 1), $this->_getLines($to_lines, $to_line_no, $to_line_no + count($to_lines) - 1))); } return $edits; } /** * Get lines from either the old or new text * * @access private * * @param array &$text_lines Either $from_lines or $to_lines * @param int &$line_no Current line number * @param int $end Optional end line, when we want to chop more * than one line. * * @return array The chopped lines */ function _getLines(&$text_lines, &$line_no, $end = false) { if (!empty($end)) { $lines = array(); // We can shift even more while ($line_no <= $end) { array_push($lines, array_shift($text_lines)); $line_no++; } } else { $lines = array(array_shift($text_lines)); $line_no++; } return $lines; } }
zyblog
trunk/zyblog/wp-includes/Text/Diff/Engine/shell.php
PHP
asf20
5,170
<?php /** * A class to render Diffs in different formats. * * This class renders the diff in classic diff format. It is intended that * this class be customized via inheritance, to obtain fancier outputs. * * Copyright 2004-2010 The Horde Project (http://www.horde.org/) * * See the enclosed file COPYING for license information (LGPL). If you did * not receive this file, see http://opensource.org/licenses/lgpl-license.php. * * @package Text_Diff */ class Text_Diff_Renderer { /** * Number of leading context "lines" to preserve. * * This should be left at zero for this class, but subclasses may want to * set this to other values. */ var $_leading_context_lines = 0; /** * Number of trailing context "lines" to preserve. * * This should be left at zero for this class, but subclasses may want to * set this to other values. */ var $_trailing_context_lines = 0; /** * Constructor. */ function Text_Diff_Renderer($params = array()) { foreach ($params as $param => $value) { $v = '_' . $param; if (isset($this->$v)) { $this->$v = $value; } } } /** * Get any renderer parameters. * * @return array All parameters of this renderer object. */ function getParams() { $params = array(); foreach (get_object_vars($this) as $k => $v) { if ($k[0] == '_') { $params[substr($k, 1)] = $v; } } return $params; } /** * Renders a diff. * * @param Text_Diff $diff A Text_Diff object. * * @return string The formatted output. */ function render($diff) { $xi = $yi = 1; $block = false; $context = array(); $nlead = $this->_leading_context_lines; $ntrail = $this->_trailing_context_lines; $output = $this->_startDiff(); $diffs = $diff->getDiff(); foreach ($diffs as $i => $edit) { /* If these are unchanged (copied) lines, and we want to keep * leading or trailing context lines, extract them from the copy * block. */ if (is_a($edit, 'Text_Diff_Op_copy')) { /* Do we have any diff blocks yet? */ if (is_array($block)) { /* How many lines to keep as context from the copy * block. */ $keep = $i == count($diffs) - 1 ? $ntrail : $nlead + $ntrail; if (count($edit->orig) <= $keep) { /* We have less lines in the block than we want for * context => keep the whole block. */ $block[] = $edit; } else { if ($ntrail) { /* Create a new block with as many lines as we need * for the trailing context. */ $context = array_slice($edit->orig, 0, $ntrail); $block[] = &new Text_Diff_Op_copy($context); } /* @todo */ $output .= $this->_block($x0, $ntrail + $xi - $x0, $y0, $ntrail + $yi - $y0, $block); $block = false; } } /* Keep the copy block as the context for the next block. */ $context = $edit->orig; } else { /* Don't we have any diff blocks yet? */ if (!is_array($block)) { /* Extract context lines from the preceding copy block. */ $context = array_slice($context, count($context) - $nlead); $x0 = $xi - count($context); $y0 = $yi - count($context); $block = array(); if ($context) { $block[] = &new Text_Diff_Op_copy($context); } } $block[] = $edit; } if ($edit->orig) { $xi += count($edit->orig); } if ($edit->final) { $yi += count($edit->final); } } if (is_array($block)) { $output .= $this->_block($x0, $xi - $x0, $y0, $yi - $y0, $block); } return $output . $this->_endDiff(); } function _block($xbeg, $xlen, $ybeg, $ylen, &$edits) { $output = $this->_startBlock($this->_blockHeader($xbeg, $xlen, $ybeg, $ylen)); foreach ($edits as $edit) { switch (strtolower(get_class($edit))) { case 'text_diff_op_copy': $output .= $this->_context($edit->orig); break; case 'text_diff_op_add': $output .= $this->_added($edit->final); break; case 'text_diff_op_delete': $output .= $this->_deleted($edit->orig); break; case 'text_diff_op_change': $output .= $this->_changed($edit->orig, $edit->final); break; } } return $output . $this->_endBlock(); } function _startDiff() { return ''; } function _endDiff() { return ''; } function _blockHeader($xbeg, $xlen, $ybeg, $ylen) { if ($xlen > 1) { $xbeg .= ',' . ($xbeg + $xlen - 1); } if ($ylen > 1) { $ybeg .= ',' . ($ybeg + $ylen - 1); } // this matches the GNU Diff behaviour if ($xlen && !$ylen) { $ybeg--; } elseif (!$xlen) { $xbeg--; } return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg; } function _startBlock($header) { return $header . "\n"; } function _endBlock() { return ''; } function _lines($lines, $prefix = ' ') { return $prefix . implode("\n$prefix", $lines) . "\n"; } function _context($lines) { return $this->_lines($lines, ' '); } function _added($lines) { return $this->_lines($lines, '> '); } function _deleted($lines) { return $this->_lines($lines, '< '); } function _changed($orig, $final) { return $this->_deleted($orig) . "---\n" . $this->_added($final); } }
zyblog
trunk/zyblog/wp-includes/Text/Diff/Renderer.php
PHP
asf20
6,693
<?php /** * RSS 0.92 Feed Template for displaying RSS 0.92 Posts feed. * * @package WordPress */ header('Content-Type: ' . feed_content_type('rss-http') . '; charset=' . get_option('blog_charset'), true); $more = 1; echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?> <rss version="0.92"> <channel> <title><?php bloginfo_rss('name'); wp_title_rss(); ?></title> <link><?php bloginfo_rss('url') ?></link> <description><?php bloginfo_rss('description') ?></description> <lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></lastBuildDate> <docs>http://backend.userland.com/rss092</docs> <language><?php bloginfo_rss( 'language' ); ?></language> <?php do_action('rss_head'); ?> <?php while (have_posts()) : the_post(); ?> <item> <title><?php the_title_rss() ?></title> <description><![CDATA[<?php the_excerpt_rss() ?>]]></description> <link><?php the_permalink_rss() ?></link> <?php do_action('rss_item'); ?> </item> <?php endwhile; ?> </channel> </rss>
zyblog
trunk/zyblog/wp-includes/feed-rss.php
PHP
asf20
1,048
<?php /** * Base WordPress Image Editor * * @package WordPress * @subpackage Image_Editor */ /** * Base image editor class from which implementations extend * * @since 3.5.0 */ abstract class WP_Image_Editor { protected $file = null; protected $size = null; protected $mime_type = null; protected $default_mime_type = 'image/jpeg'; protected $quality = 90; /** * Each instance handles a single file. */ public function __construct( $file ) { $this->file = $file; } /** * Checks to see if current environment supports the editor chosen. * Must be overridden in a sub-class. * * @since 3.5.0 * @access public * @abstract * * @param array $args * @return boolean */ public static function test( $args = array() ) { return false; } /** * Checks to see if editor supports the mime-type specified. * Must be overridden in a sub-class. * * @since 3.5.0 * @access public * @abstract * * @param string $mime_type * @return boolean */ public static function supports_mime_type( $mime_type ) { return false; } /** * Loads image from $this->file into editor. * * @since 3.5.0 * @access protected * @abstract * * @return boolean|WP_Error True if loaded; WP_Error on failure. */ abstract public function load(); /** * Saves current image to file. * * @since 3.5.0 * @access public * @abstract * * @param string $destfilename * @param string $mime_type * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string} */ abstract public function save( $destfilename = null, $mime_type = null ); /** * Resizes current image. * * @since 3.5.0 * @access public * @abstract * * @param int $max_w * @param int $max_h * @param boolean $crop * @return boolean|WP_Error */ abstract public function resize( $max_w, $max_h, $crop = false ); /** * Processes current image and saves to disk * multiple sizes from single source. * * @since 3.5.0 * @access public * @abstract * * @param array $sizes { {'width'=>int, 'height'=>int, 'crop'=>bool}, ... } * @return array */ abstract public function multi_resize( $sizes ); /** * Crops Image. * * @since 3.5.0 * @access public * @abstract * * @param string|int $src The source file or Attachment ID. * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w Optional. The destination width. * @param int $dst_h Optional. The destination height. * @param boolean $src_abs Optional. If the source crop points are absolute. * @return boolean|WP_Error */ abstract public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ); /** * Rotates current image counter-clockwise by $angle. * * @since 3.5.0 * @access public * @abstract * * @param float $angle * @return boolean|WP_Error */ abstract public function rotate( $angle ); /** * Flips current image. * * @since 3.5.0 * @access public * @abstract * * @param boolean $horz Horizontal Flip * @param boolean $vert Vertical Flip * @return boolean|WP_Error */ abstract public function flip( $horz, $vert ); /** * Streams current image to browser. * * @since 3.5.0 * @access public * @abstract * * @param string $mime_type * @return boolean|WP_Error */ abstract public function stream( $mime_type = null ); /** * Gets dimensions of image. * * @since 3.5.0 * @access public * * @return array {'width'=>int, 'height'=>int} */ public function get_size() { return $this->size; } /** * Sets current image size. * * @since 3.5.0 * @access protected * * @param int $width * @param int $height */ protected function update_size( $width = null, $height = null ) { $this->size = array( 'width' => (int) $width, 'height' => (int) $height ); return true; } /** * Sets Image Compression quality on a 1-100% scale. * * @since 3.5.0 * @access public * * @param int $quality Compression Quality. Range: [1,100] * @return boolean */ public function set_quality( $quality ) { $this->quality = apply_filters( 'wp_editor_set_quality', $quality ); return ( (bool) $this->quality ); } /** * Returns preferred mime-type and extension based on provided * file's extension and mime, or current file's extension and mime. * * Will default to $this->default_mime_type if requested is not supported. * * Provides corrected filename only if filename is provided. * * @since 3.5.0 * @access protected * * @param string $filename * @param string $mime_type * @return array { filename|null, extension, mime-type } */ protected function get_output_format( $filename = null, $mime_type = null ) { $new_ext = $file_ext = null; $file_mime = null; // By default, assume specified type takes priority if ( $mime_type ) { $new_ext = $this->get_extension( $mime_type ); } if ( $filename ) { $file_ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ); $file_mime = $this->get_mime_type( $file_ext ); } else { // If no file specified, grab editor's current extension and mime-type. $file_ext = strtolower( pathinfo( $this->file, PATHINFO_EXTENSION ) ); $file_mime = $this->mime_type; } // Check to see if specified mime-type is the same as type implied by // file extension. If so, prefer extension from file. if ( ! $mime_type || ( $file_mime == $mime_type ) ) { $mime_type = $file_mime; $new_ext = $file_ext; } // Double-check that the mime-type selected is supported by the editor. // If not, choose a default instead. if ( ! $this->supports_mime_type( $mime_type ) ) { $mime_type = apply_filters( 'image_editor_default_mime_type', $this->default_mime_type ); $new_ext = $this->get_extension( $mime_type ); } if ( $filename ) { $ext = ''; $info = pathinfo( $filename ); $dir = $info['dirname']; if( isset( $info['extension'] ) ) $ext = $info['extension']; $filename = trailingslashit( $dir ) . wp_basename( $filename, ".$ext" ) . ".{$new_ext}"; } return array( $filename, $new_ext, $mime_type ); } /** * Builds an output filename based on current file, and adding proper suffix * * @since 3.5.0 * @access public * * @param string $suffix * @param string $dest_path * @param string $extension * @return string filename */ public function generate_filename( $suffix = null, $dest_path = null, $extension = null ) { // $suffix will be appended to the destination filename, just before the extension if ( ! $suffix ) $suffix = $this->get_suffix(); $info = pathinfo( $this->file ); $dir = $info['dirname']; $ext = $info['extension']; $name = wp_basename( $this->file, ".$ext" ); $new_ext = strtolower( $extension ? $extension : $ext ); if ( ! is_null( $dest_path ) && $_dest_path = realpath( $dest_path ) ) $dir = $_dest_path; return trailingslashit( $dir ) . "{$name}-{$suffix}.{$new_ext}"; } /** * Builds and returns proper suffix for file based on height and width. * * @since 3.5.0 * @access public * * @return string suffix */ public function get_suffix() { if ( ! $this->get_size() ) return false; return "{$this->size['width']}x{$this->size['height']}"; } /** * Either calls editor's save function or handles file as a stream. * * @since 3.5.0 * @access protected * * @param string|stream $filename * @param callable $function * @param array $arguments * @return boolean */ protected function make_image( $filename, $function, $arguments ) { $dst_file = $filename; if ( $stream = wp_is_stream( $filename ) ) { $filename = null; ob_start(); } $result = call_user_func_array( $function, $arguments ); if ( $result && $stream ) { $contents = ob_get_contents(); $fp = fopen( $dst_file, 'w' ); if ( ! $fp ) return false; fwrite( $fp, $contents ); fclose( $fp ); } if ( $stream ) { ob_end_clean(); } return $result; } /** * Returns first matched mime-type from extension, * as mapped from wp_get_mime_types() * * @since 3.5.0 * @access protected * * @param string $extension * @return string|boolean */ protected static function get_mime_type( $extension = null ) { if ( ! $extension ) return false; $mime_types = wp_get_mime_types(); $extensions = array_keys( $mime_types ); foreach( $extensions as $_extension ) { if ( preg_match( "/{$extension}/i", $_extension ) ) { return $mime_types[$_extension]; } } return false; } /** * Returns first matched extension from Mime-type, * as mapped from wp_get_mime_types() * * @since 3.5.0 * @access protected * * @param string $mime_type * @return string|boolean */ protected static function get_extension( $mime_type = null ) { $extensions = explode( '|', array_search( $mime_type, wp_get_mime_types() ) ); if ( empty( $extensions[0] ) ) return false; return $extensions[0]; } }
zyblog
trunk/zyblog/wp-includes/class-wp-image-editor.php
PHP
asf20
9,201
<?php /** * RSS2 Feed Template for displaying RSS2 Comments feed. * * @package WordPress */ header('Content-Type: ' . feed_content_type('rss-http') . '; charset=' . get_option('blog_charset'), true); echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?> <rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" <?php do_action('rss2_ns'); do_action('rss2_comments_ns'); ?> > <channel> <title><?php if ( is_singular() ) printf( ent2ncr( __( 'Comments on: %s' ) ), get_the_title_rss() ); elseif ( is_search() ) printf( ent2ncr( __( 'Comments for %1$s searching on %2$s' ) ), get_bloginfo_rss( 'name' ), get_search_query() ); else printf( ent2ncr( __( 'Comments for %s' ) ), get_bloginfo_rss( 'name' ) . get_wp_title_rss() ); ?></title> <atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" /> <link><?php (is_single()) ? the_permalink_rss() : bloginfo_rss("url") ?></link> <description><?php bloginfo_rss("description") ?></description> <lastBuildDate><?php echo mysql2date('r', get_lastcommentmodified('GMT')); ?></lastBuildDate> <sy:updatePeriod><?php echo apply_filters( 'rss_update_period', 'hourly' ); ?></sy:updatePeriod> <sy:updateFrequency><?php echo apply_filters( 'rss_update_frequency', '1' ); ?></sy:updateFrequency> <?php do_action('commentsrss2_head'); ?> <?php if ( have_comments() ) : while ( have_comments() ) : the_comment(); $comment_post = $GLOBALS['post'] = get_post( $comment->comment_post_ID ); ?> <item> <title><?php if ( !is_singular() ) { $title = get_the_title($comment_post->ID); $title = apply_filters('the_title_rss', $title); printf(ent2ncr(__('Comment on %1$s by %2$s')), $title, get_comment_author_rss()); } else { printf(ent2ncr(__('By: %s')), get_comment_author_rss()); } ?></title> <link><?php comment_link() ?></link> <dc:creator><?php echo get_comment_author_rss() ?></dc:creator> <pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_comment_time('Y-m-d H:i:s', true, false), false); ?></pubDate> <guid isPermaLink="false"><?php comment_guid() ?></guid> <?php if ( post_password_required($comment_post) ) : ?> <description><?php echo ent2ncr(__('Protected Comments: Please enter your password to view comments.')); ?></description> <content:encoded><![CDATA[<?php echo get_the_password_form() ?>]]></content:encoded> <?php else : // post pass ?> <description><![CDATA[<?php comment_text_rss() ?>]]></description> <content:encoded><![CDATA[<?php comment_text() ?>]]></content:encoded> <?php endif; // post pass do_action('commentrss2_item', $comment->comment_ID, $comment_post->ID); ?> </item> <?php endwhile; endif; ?> </channel> </rss>
zyblog
trunk/zyblog/wp-includes/feed-rss2-comments.php
PHP
asf20
2,872
<?php /** * kses 0.2.2 - HTML/XHTML filter that only allows some elements and attributes * Copyright (C) 2002, 2003, 2005 Ulf Harnhammar * * This program is free software and open source software; you can redistribute * it and/or modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the License, * or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * http://www.gnu.org/licenses/gpl.html * * [kses strips evil scripts!] * * Added wp_ prefix to avoid conflicts with existing kses users * * @version 0.2.2 * @copyright (C) 2002, 2003, 2005 * @author Ulf Harnhammar <http://advogato.org/person/metaur/> * * @package External * @subpackage KSES * */ /** * You can override this in a plugin. * * The wp_kses_allowed_html filter is more powerful and supplies context. * CUSTOM_TAGS is not recommended and should be considered deprecated. * * @see wp_kses_allowed_html() * * @since 1.2.0 */ if ( ! defined( 'CUSTOM_TAGS' ) ) define( 'CUSTOM_TAGS', false ); if ( ! CUSTOM_TAGS ) { /** * Kses global for default allowable HTML tags. * * Can be override by using CUSTOM_TAGS constant. * * @global array $allowedposttags * @since 2.0.0 */ $allowedposttags = array( 'address' => array(), 'a' => array( 'href' => true, 'rel' => true, 'rev' => true, 'name' => true, 'target' => true, ), 'abbr' => array(), 'acronym' => array(), 'area' => array( 'alt' => true, 'coords' => true, 'href' => true, 'nohref' => true, 'shape' => true, 'target' => true, ), 'article' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'aside' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'b' => array(), 'big' => array(), 'blockquote' => array( 'cite' => true, 'lang' => true, 'xml:lang' => true, ), 'br' => array(), 'button' => array( 'disabled' => true, 'name' => true, 'type' => true, 'value' => true, ), 'caption' => array( 'align' => true, ), 'cite' => array( 'dir' => true, 'lang' => true, ), 'code' => array(), 'col' => array( 'align' => true, 'char' => true, 'charoff' => true, 'span' => true, 'dir' => true, 'valign' => true, 'width' => true, ), 'del' => array( 'datetime' => true, ), 'dd' => array(), 'details' => array( 'align' => true, 'dir' => true, 'lang' => true, 'open' => true, 'xml:lang' => true, ), 'div' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'dl' => array(), 'dt' => array(), 'em' => array(), 'fieldset' => array(), 'figure' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'figcaption' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'font' => array( 'color' => true, 'face' => true, 'size' => true, ), 'footer' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'form' => array( 'action' => true, 'accept' => true, 'accept-charset' => true, 'enctype' => true, 'method' => true, 'name' => true, 'target' => true, ), 'h1' => array( 'align' => true, ), 'h2' => array( 'align' => true, ), 'h3' => array( 'align' => true, ), 'h4' => array( 'align' => true, ), 'h5' => array( 'align' => true, ), 'h6' => array( 'align' => true, ), 'header' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'hgroup' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'hr' => array( 'align' => true, 'noshade' => true, 'size' => true, 'width' => true, ), 'i' => array(), 'img' => array( 'alt' => true, 'align' => true, 'border' => true, 'height' => true, 'hspace' => true, 'longdesc' => true, 'vspace' => true, 'src' => true, 'usemap' => true, 'width' => true, ), 'ins' => array( 'datetime' => true, 'cite' => true, ), 'kbd' => array(), 'label' => array( 'for' => true, ), 'legend' => array( 'align' => true, ), 'li' => array( 'align' => true, ), 'map' => array( 'name' => true, ), 'menu' => array( 'type' => true, ), 'nav' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'p' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'pre' => array( 'width' => true, ), 'q' => array( 'cite' => true, ), 's' => array(), 'span' => array( 'dir' => true, 'align' => true, 'lang' => true, 'xml:lang' => true, ), 'section' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'small' => array(), 'strike' => array(), 'strong' => array(), 'sub' => array(), 'summary' => array( 'align' => true, 'dir' => true, 'lang' => true, 'xml:lang' => true, ), 'sup' => array(), 'table' => array( 'align' => true, 'bgcolor' => true, 'border' => true, 'cellpadding' => true, 'cellspacing' => true, 'dir' => true, 'rules' => true, 'summary' => true, 'width' => true, ), 'tbody' => array( 'align' => true, 'char' => true, 'charoff' => true, 'valign' => true, ), 'td' => array( 'abbr' => true, 'align' => true, 'axis' => true, 'bgcolor' => true, 'char' => true, 'charoff' => true, 'colspan' => true, 'dir' => true, 'headers' => true, 'height' => true, 'nowrap' => true, 'rowspan' => true, 'scope' => true, 'valign' => true, 'width' => true, ), 'textarea' => array( 'cols' => true, 'rows' => true, 'disabled' => true, 'name' => true, 'readonly' => true, ), 'tfoot' => array( 'align' => true, 'char' => true, 'charoff' => true, 'valign' => true, ), 'th' => array( 'abbr' => true, 'align' => true, 'axis' => true, 'bgcolor' => true, 'char' => true, 'charoff' => true, 'colspan' => true, 'headers' => true, 'height' => true, 'nowrap' => true, 'rowspan' => true, 'scope' => true, 'valign' => true, 'width' => true, ), 'thead' => array( 'align' => true, 'char' => true, 'charoff' => true, 'valign' => true, ), 'title' => array(), 'tr' => array( 'align' => true, 'bgcolor' => true, 'char' => true, 'charoff' => true, 'valign' => true, ), 'tt' => array(), 'u' => array(), 'ul' => array( 'type' => true, ), 'ol' => array( 'start' => true, 'type' => true, ), 'var' => array(), ); /** * Kses allowed HTML elements. * * @global array $allowedtags * @since 1.0.0 */ $allowedtags = array( 'a' => array( 'href' => true, 'title' => true, ), 'abbr' => array( 'title' => true, ), 'acronym' => array( 'title' => true, ), 'b' => array(), 'blockquote' => array( 'cite' => true, ), 'cite' => array(), 'code' => array(), 'del' => array( 'datetime' => true, ), 'em' => array(), 'i' => array(), 'q' => array( 'cite' => true, ), 'strike' => array(), 'strong' => array(), ); $allowedentitynames = array( 'nbsp', 'iexcl', 'cent', 'pound', 'curren', 'yen', 'brvbar', 'sect', 'uml', 'copy', 'ordf', 'laquo', 'not', 'shy', 'reg', 'macr', 'deg', 'plusmn', 'acute', 'micro', 'para', 'middot', 'cedil', 'ordm', 'raquo', 'iquest', 'Agrave', 'Aacute', 'Acirc', 'Atilde', 'Auml', 'Aring', 'AElig', 'Ccedil', 'Egrave', 'Eacute', 'Ecirc', 'Euml', 'Igrave', 'Iacute', 'Icirc', 'Iuml', 'ETH', 'Ntilde', 'Ograve', 'Oacute', 'Ocirc', 'Otilde', 'Ouml', 'times', 'Oslash', 'Ugrave', 'Uacute', 'Ucirc', 'Uuml', 'Yacute', 'THORN', 'szlig', 'agrave', 'aacute', 'acirc', 'atilde', 'auml', 'aring', 'aelig', 'ccedil', 'egrave', 'eacute', 'ecirc', 'euml', 'igrave', 'iacute', 'icirc', 'iuml', 'eth', 'ntilde', 'ograve', 'oacute', 'ocirc', 'otilde', 'ouml', 'divide', 'oslash', 'ugrave', 'uacute', 'ucirc', 'uuml', 'yacute', 'thorn', 'yuml', 'quot', 'amp', 'lt', 'gt', 'apos', 'OElig', 'oelig', 'Scaron', 'scaron', 'Yuml', 'circ', 'tilde', 'ensp', 'emsp', 'thinsp', 'zwnj', 'zwj', 'lrm', 'rlm', 'ndash', 'mdash', 'lsquo', 'rsquo', 'sbquo', 'ldquo', 'rdquo', 'bdquo', 'dagger', 'Dagger', 'permil', 'lsaquo', 'rsaquo', 'euro', 'fnof', 'Alpha', 'Beta', 'Gamma', 'Delta', 'Epsilon', 'Zeta', 'Eta', 'Theta', 'Iota', 'Kappa', 'Lambda', 'Mu', 'Nu', 'Xi', 'Omicron', 'Pi', 'Rho', 'Sigma', 'Tau', 'Upsilon', 'Phi', 'Chi', 'Psi', 'Omega', 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta', 'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu', 'xi', 'omicron', 'pi', 'rho', 'sigmaf', 'sigma', 'tau', 'upsilon', 'phi', 'chi', 'psi', 'omega', 'thetasym', 'upsih', 'piv', 'bull', 'hellip', 'prime', 'Prime', 'oline', 'frasl', 'weierp', 'image', 'real', 'trade', 'alefsym', 'larr', 'uarr', 'rarr', 'darr', 'harr', 'crarr', 'lArr', 'uArr', 'rArr', 'dArr', 'hArr', 'forall', 'part', 'exist', 'empty', 'nabla', 'isin', 'notin', 'ni', 'prod', 'sum', 'minus', 'lowast', 'radic', 'prop', 'infin', 'ang', 'and', 'or', 'cap', 'cup', 'int', 'sim', 'cong', 'asymp', 'ne', 'equiv', 'le', 'ge', 'sub', 'sup', 'nsub', 'sube', 'supe', 'oplus', 'otimes', 'perp', 'sdot', 'lceil', 'rceil', 'lfloor', 'rfloor', 'lang', 'rang', 'loz', 'spades', 'clubs', 'hearts', 'diams', ); $allowedposttags = array_map( '_wp_add_global_attributes', $allowedposttags ); } else { $allowedtags = wp_kses_array_lc( $allowedtags ); $allowedposttags = wp_kses_array_lc( $allowedposttags ); } /** * Filters content and keeps only allowable HTML elements. * * This function makes sure that only the allowed HTML element names, attribute * names and attribute values plus only sane HTML entities will occur in * $string. You have to remove any slashes from PHP's magic quotes before you * call this function. * * The default allowed protocols are 'http', 'https', 'ftp', 'mailto', 'news', * 'irc', 'gopher', 'nntp', 'feed', 'telnet, 'mms', 'rtsp' and 'svn'. This * covers all common link protocols, except for 'javascript' which should not * be allowed for untrusted users. * * @since 1.0.0 * * @param string $string Content to filter through kses * @param array $allowed_html List of allowed HTML elements * @param array $allowed_protocols Optional. Allowed protocol in links. * @return string Filtered content with only allowed HTML elements */ function wp_kses( $string, $allowed_html, $allowed_protocols = array() ) { if ( empty( $allowed_protocols ) ) $allowed_protocols = wp_allowed_protocols(); $string = wp_kses_no_null($string); $string = wp_kses_js_entities($string); $string = wp_kses_normalize_entities($string); $string = wp_kses_hook($string, $allowed_html, $allowed_protocols); // WP changed the order of these funcs and added args to wp_kses_hook return wp_kses_split($string, $allowed_html, $allowed_protocols); } /** * Return a list of allowed tags and attributes for a given context. * * @since 3.5.0 * * @param string $context The context for which to retrieve tags. Allowed values are * post | strip | data | entities or the name of a field filter such as pre_user_description. * @return array List of allowed tags and their allowed attributes. */ function wp_kses_allowed_html( $context = '' ) { global $allowedposttags, $allowedtags, $allowedentitynames; if ( is_array( $context ) ) return apply_filters( 'wp_kses_allowed_html', $context, 'explicit' ); switch ( $context ) { case 'post': return apply_filters( 'wp_kses_allowed_html', $allowedposttags, $context ); break; case 'user_description': case 'pre_user_description': $tags = $allowedtags; $tags['a']['rel'] = true; return apply_filters( 'wp_kses_allowed_html', $tags, $context ); break; case 'strip': return apply_filters( 'wp_kses_allowed_html', array(), $context ); break; case 'entities': return apply_filters( 'wp_kses_allowed_html', $allowedentitynames, $context); break; case 'data': default: return apply_filters( 'wp_kses_allowed_html', $allowedtags, $context ); } } /** * You add any kses hooks here. * * There is currently only one kses WordPress hook and it is called here. All * parameters are passed to the hooks and expected to receive a string. * * @since 1.0.0 * * @param string $string Content to filter through kses * @param array $allowed_html List of allowed HTML elements * @param array $allowed_protocols Allowed protocol in links * @return string Filtered content through 'pre_kses' hook */ function wp_kses_hook( $string, $allowed_html, $allowed_protocols ) { $string = apply_filters('pre_kses', $string, $allowed_html, $allowed_protocols); return $string; } /** * This function returns kses' version number. * * @since 1.0.0 * * @return string KSES Version Number */ function wp_kses_version() { return '0.2.2'; } /** * Searches for HTML tags, no matter how malformed. * * It also matches stray ">" characters. * * @since 1.0.0 * * @param string $string Content to filter * @param array $allowed_html Allowed HTML elements * @param array $allowed_protocols Allowed protocols to keep * @return string Content with fixed HTML tags */ function wp_kses_split( $string, $allowed_html, $allowed_protocols ) { global $pass_allowed_html, $pass_allowed_protocols; $pass_allowed_html = $allowed_html; $pass_allowed_protocols = $allowed_protocols; return preg_replace_callback( '%(<!--.*?(-->|$))|(<[^>]*(>|$)|>)%', '_wp_kses_split_callback', $string ); } /** * Callback for wp_kses_split. * * @since 3.1.0 * @access private */ function _wp_kses_split_callback( $match ) { global $pass_allowed_html, $pass_allowed_protocols; return wp_kses_split2( $match[0], $pass_allowed_html, $pass_allowed_protocols ); } /** * Callback for wp_kses_split for fixing malformed HTML tags. * * This function does a lot of work. It rejects some very malformed things like * <:::>. It returns an empty string, if the element isn't allowed (look ma, no * strip_tags()!). Otherwise it splits the tag into an element and an attribute * list. * * After the tag is split into an element and an attribute list, it is run * through another filter which will remove illegal attributes and once that is * completed, will be returned. * * @access private * @since 1.0.0 * @uses wp_kses_attr() * * @param string $string Content to filter * @param array $allowed_html Allowed HTML elements * @param array $allowed_protocols Allowed protocols to keep * @return string Fixed HTML element */ function wp_kses_split2($string, $allowed_html, $allowed_protocols) { $string = wp_kses_stripslashes($string); if (substr($string, 0, 1) != '<') return '&gt;'; # It matched a ">" character if ( '<!--' == substr( $string, 0, 4 ) ) { $string = str_replace( array('<!--', '-->'), '', $string ); while ( $string != ($newstring = wp_kses($string, $allowed_html, $allowed_protocols)) ) $string = $newstring; if ( $string == '' ) return ''; // prevent multiple dashes in comments $string = preg_replace('/--+/', '-', $string); // prevent three dashes closing a comment $string = preg_replace('/-$/', '', $string); return "<!--{$string}-->"; } # Allow HTML comments if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches)) return ''; # It's seriously malformed $slash = trim($matches[1]); $elem = $matches[2]; $attrlist = $matches[3]; if ( ! is_array( $allowed_html ) ) $allowed_html = wp_kses_allowed_html( $allowed_html ); if ( ! isset($allowed_html[strtolower($elem)]) ) return ''; # They are using a not allowed HTML element if ($slash != '') return "</$elem>"; # No attributes are allowed for closing elements return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols ); } /** * Removes all attributes, if none are allowed for this element. * * If some are allowed it calls wp_kses_hair() to split them further, and then * it builds up new HTML code from the data that kses_hair() returns. It also * removes "<" and ">" characters, if there are any left. One more thing it does * is to check if the tag has a closing XHTML slash, and if it does, it puts one * in the returned code as well. * * @since 1.0.0 * * @param string $element HTML element/tag * @param string $attr HTML attributes from HTML element to closing HTML element tag * @param array $allowed_html Allowed HTML elements * @param array $allowed_protocols Allowed protocols to keep * @return string Sanitized HTML element */ function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) { # Is there a closing XHTML slash at the end of the attributes? if ( ! is_array( $allowed_html ) ) $allowed_html = wp_kses_allowed_html( $allowed_html ); $xhtml_slash = ''; if (preg_match('%\s*/\s*$%', $attr)) $xhtml_slash = ' /'; # Are any attributes allowed at all for this element? if ( ! isset($allowed_html[strtolower($element)]) || count($allowed_html[strtolower($element)]) == 0 ) return "<$element$xhtml_slash>"; # Split it $attrarr = wp_kses_hair($attr, $allowed_protocols); # Go through $attrarr, and save the allowed attributes for this element # in $attr2 $attr2 = ''; $allowed_attr = $allowed_html[strtolower($element)]; foreach ($attrarr as $arreach) { if ( ! isset( $allowed_attr[strtolower($arreach['name'])] ) ) continue; # the attribute is not allowed $current = $allowed_attr[strtolower($arreach['name'])]; if ( $current == '' ) continue; # the attribute is not allowed if ( strtolower( $arreach['name'] ) == 'style' ) { $orig_value = $arreach['value']; $value = safecss_filter_attr( $orig_value ); if ( empty( $value ) ) continue; $arreach['value'] = $value; $arreach['whole'] = str_replace( $orig_value, $value, $arreach['whole'] ); } if ( ! is_array($current) ) { $attr2 .= ' '.$arreach['whole']; # there are no checks } else { # there are some checks $ok = true; foreach ($current as $currkey => $currval) { if ( ! wp_kses_check_attr_val($arreach['value'], $arreach['vless'], $currkey, $currval) ) { $ok = false; break; } } if ( $ok ) $attr2 .= ' '.$arreach['whole']; # it passed them } # if !is_array($current) } # foreach # Remove any "<" or ">" characters $attr2 = preg_replace('/[<>]/', '', $attr2); return "<$element$attr2$xhtml_slash>"; } /** * Builds an attribute list from string containing attributes. * * This function does a lot of work. It parses an attribute list into an array * with attribute data, and tries to do the right thing even if it gets weird * input. It will add quotes around attribute values that don't have any quotes * or apostrophes around them, to make it easier to produce HTML code that will * conform to W3C's HTML specification. It will also remove bad URL protocols * from attribute values. It also reduces duplicate attributes by using the * attribute defined first (foo='bar' foo='baz' will result in foo='bar'). * * @since 1.0.0 * * @param string $attr Attribute list from HTML element to closing HTML element tag * @param array $allowed_protocols Allowed protocols to keep * @return array List of attributes after parsing */ function wp_kses_hair($attr, $allowed_protocols) { $attrarr = array(); $mode = 0; $attrname = ''; $uris = array('xmlns', 'profile', 'href', 'src', 'cite', 'classid', 'codebase', 'data', 'usemap', 'longdesc', 'action'); # Loop through the whole attribute list while (strlen($attr) != 0) { $working = 0; # Was the last operation successful? switch ($mode) { case 0 : # attribute name, href for instance if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) { $attrname = $match[1]; $working = $mode = 1; $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr); } break; case 1 : # equals sign or valueless ("selected") if (preg_match('/^\s*=\s*/', $attr)) # equals sign { $working = 1; $mode = 2; $attr = preg_replace('/^\s*=\s*/', '', $attr); break; } if (preg_match('/^\s+/', $attr)) # valueless { $working = 1; $mode = 0; if(false === array_key_exists($attrname, $attrarr)) { $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y'); } $attr = preg_replace('/^\s+/', '', $attr); } break; case 2 : # attribute value, a URL after href= for instance if (preg_match('%^"([^"]*)"(\s+|/?$)%', $attr, $match)) # "value" { $thisval = $match[1]; if ( in_array(strtolower($attrname), $uris) ) $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols); if(false === array_key_exists($attrname, $attrarr)) { $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n'); } $working = 1; $mode = 0; $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr); break; } if (preg_match("%^'([^']*)'(\s+|/?$)%", $attr, $match)) # 'value' { $thisval = $match[1]; if ( in_array(strtolower($attrname), $uris) ) $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols); if(false === array_key_exists($attrname, $attrarr)) { $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname='$thisval'", 'vless' => 'n'); } $working = 1; $mode = 0; $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr); break; } if (preg_match("%^([^\s\"']+)(\s+|/?$)%", $attr, $match)) # value { $thisval = $match[1]; if ( in_array(strtolower($attrname), $uris) ) $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols); if(false === array_key_exists($attrname, $attrarr)) { $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n'); } # We add quotes to conform to W3C's HTML spec. $working = 1; $mode = 0; $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr); } break; } # switch if ($working == 0) # not well formed, remove and try again { $attr = wp_kses_html_error($attr); $mode = 0; } } # while if ($mode == 1 && false === array_key_exists($attrname, $attrarr)) # special case, for when the attribute list ends with a valueless # attribute like "selected" $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y'); return $attrarr; } /** * Performs different checks for attribute values. * * The currently implemented checks are "maxlen", "minlen", "maxval", "minval" * and "valueless". * * @since 1.0.0 * * @param string $value Attribute value * @param string $vless Whether the value is valueless. Use 'y' or 'n' * @param string $checkname What $checkvalue is checking for. * @param mixed $checkvalue What constraint the value should pass * @return bool Whether check passes */ function wp_kses_check_attr_val($value, $vless, $checkname, $checkvalue) { $ok = true; switch (strtolower($checkname)) { case 'maxlen' : # The maxlen check makes sure that the attribute value has a length not # greater than the given value. This can be used to avoid Buffer Overflows # in WWW clients and various Internet servers. if (strlen($value) > $checkvalue) $ok = false; break; case 'minlen' : # The minlen check makes sure that the attribute value has a length not # smaller than the given value. if (strlen($value) < $checkvalue) $ok = false; break; case 'maxval' : # The maxval check does two things: it checks that the attribute value is # an integer from 0 and up, without an excessive amount of zeroes or # whitespace (to avoid Buffer Overflows). It also checks that the attribute # value is not greater than the given value. # This check can be used to avoid Denial of Service attacks. if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value)) $ok = false; if ($value > $checkvalue) $ok = false; break; case 'minval' : # The minval check makes sure that the attribute value is a positive integer, # and that it is not smaller than the given value. if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value)) $ok = false; if ($value < $checkvalue) $ok = false; break; case 'valueless' : # The valueless check makes sure if the attribute has a value # (like <a href="blah">) or not (<option selected>). If the given value # is a "y" or a "Y", the attribute must not have a value. # If the given value is an "n" or an "N", the attribute must have one. if (strtolower($checkvalue) != $vless) $ok = false; break; } # switch return $ok; } /** * Sanitize string from bad protocols. * * This function removes all non-allowed protocols from the beginning of * $string. It ignores whitespace and the case of the letters, and it does * understand HTML entities. It does its work in a while loop, so it won't be * fooled by a string like "javascript:javascript:alert(57)". * * @since 1.0.0 * * @param string $string Content to filter bad protocols from * @param array $allowed_protocols Allowed protocols to keep * @return string Filtered content */ function wp_kses_bad_protocol($string, $allowed_protocols) { $string = wp_kses_no_null($string); $iterations = 0; do { $original_string = $string; $string = wp_kses_bad_protocol_once($string, $allowed_protocols); } while ( $original_string != $string && ++$iterations < 6 ); if ( $original_string != $string ) return ''; return $string; } /** * Removes any null characters in $string. * * @since 1.0.0 * * @param string $string * @return string */ function wp_kses_no_null($string) { $string = preg_replace('/\0+/', '', $string); $string = preg_replace('/(\\\\0)+/', '', $string); return $string; } /** * Strips slashes from in front of quotes. * * This function changes the character sequence \" to just ". It leaves all * other slashes alone. It's really weird, but the quoting from * preg_replace(//e) seems to require this. * * @since 1.0.0 * * @param string $string String to strip slashes * @return string Fixed string with quoted slashes */ function wp_kses_stripslashes($string) { return preg_replace('%\\\\"%', '"', $string); } /** * Goes through an array and changes the keys to all lower case. * * @since 1.0.0 * * @param array $inarray Unfiltered array * @return array Fixed array with all lowercase keys */ function wp_kses_array_lc($inarray) { $outarray = array (); foreach ( (array) $inarray as $inkey => $inval) { $outkey = strtolower($inkey); $outarray[$outkey] = array (); foreach ( (array) $inval as $inkey2 => $inval2) { $outkey2 = strtolower($inkey2); $outarray[$outkey][$outkey2] = $inval2; } # foreach $inval } # foreach $inarray return $outarray; } /** * Removes the HTML JavaScript entities found in early versions of Netscape 4. * * @since 1.0.0 * * @param string $string * @return string */ function wp_kses_js_entities($string) { return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string); } /** * Handles parsing errors in wp_kses_hair(). * * The general plan is to remove everything to and including some whitespace, * but it deals with quotes and apostrophes as well. * * @since 1.0.0 * * @param string $string * @return string */ function wp_kses_html_error($string) { return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string); } /** * Sanitizes content from bad protocols and other characters. * * This function searches for URL protocols at the beginning of $string, while * handling whitespace and HTML entities. * * @since 1.0.0 * * @param string $string Content to check for bad protocols * @param string $allowed_protocols Allowed protocols * @return string Sanitized content */ function wp_kses_bad_protocol_once($string, $allowed_protocols, $count = 1 ) { $string2 = preg_split( '/:|&#0*58;|&#x0*3a;/i', $string, 2 ); if ( isset($string2[1]) && ! preg_match('%/\?%', $string2[0]) ) { $string = trim( $string2[1] ); $protocol = wp_kses_bad_protocol_once2( $string2[0], $allowed_protocols ); if ( 'feed:' == $protocol ) { if ( $count > 2 ) return ''; $string = wp_kses_bad_protocol_once( $string, $allowed_protocols, ++$count ); if ( empty( $string ) ) return $string; } $string = $protocol . $string; } return $string; } /** * Callback for wp_kses_bad_protocol_once() regular expression. * * This function processes URL protocols, checks to see if they're in the * whitelist or not, and returns different data depending on the answer. * * @access private * @since 1.0.0 * * @param string $string URI scheme to check against the whitelist * @param string $allowed_protocols Allowed protocols * @return string Sanitized content */ function wp_kses_bad_protocol_once2( $string, $allowed_protocols ) { $string2 = wp_kses_decode_entities($string); $string2 = preg_replace('/\s/', '', $string2); $string2 = wp_kses_no_null($string2); $string2 = strtolower($string2); $allowed = false; foreach ( (array) $allowed_protocols as $one_protocol ) if ( strtolower($one_protocol) == $string2 ) { $allowed = true; break; } if ($allowed) return "$string2:"; else return ''; } /** * Converts and fixes HTML entities. * * This function normalizes HTML entities. It will convert "AT&T" to the correct * "AT&amp;T", "&#00058;" to "&#58;", "&#XYZZY;" to "&amp;#XYZZY;" and so on. * * @since 1.0.0 * * @param string $string Content to normalize entities * @return string Content with normalized entities */ function wp_kses_normalize_entities($string) { # Disarm all entities by converting & to &amp; $string = str_replace('&', '&amp;', $string); # Change back the allowed entities in our entity whitelist $string = preg_replace_callback('/&amp;([A-Za-z]{2,8});/', 'wp_kses_named_entities', $string); $string = preg_replace_callback('/&amp;#(0*[0-9]{1,7});/', 'wp_kses_normalize_entities2', $string); $string = preg_replace_callback('/&amp;#[Xx](0*[0-9A-Fa-f]{1,6});/', 'wp_kses_normalize_entities3', $string); return $string; } /** * Callback for wp_kses_normalize_entities() regular expression. * * This function only accepts valid named entity references, which are finite, * case-sensitive, and highly scrutinized by HTML and XML validators. * * @since 3.0.0 * * @param array $matches preg_replace_callback() matches array * @return string Correctly encoded entity */ function wp_kses_named_entities($matches) { global $allowedentitynames; if ( empty($matches[1]) ) return ''; $i = $matches[1]; return ( ( ! in_array($i, $allowedentitynames) ) ? "&amp;$i;" : "&$i;" ); } /** * Callback for wp_kses_normalize_entities() regular expression. * * This function helps wp_kses_normalize_entities() to only accept 16-bit values * and nothing more for &#number; entities. * * @access private * @since 1.0.0 * * @param array $matches preg_replace_callback() matches array * @return string Correctly encoded entity */ function wp_kses_normalize_entities2($matches) { if ( empty($matches[1]) ) return ''; $i = $matches[1]; if (valid_unicode($i)) { $i = str_pad(ltrim($i,'0'), 3, '0', STR_PAD_LEFT); $i = "&#$i;"; } else { $i = "&amp;#$i;"; } return $i; } /** * Callback for wp_kses_normalize_entities() for regular expression. * * This function helps wp_kses_normalize_entities() to only accept valid Unicode * numeric entities in hex form. * * @access private * * @param array $matches preg_replace_callback() matches array * @return string Correctly encoded entity */ function wp_kses_normalize_entities3($matches) { if ( empty($matches[1]) ) return ''; $hexchars = $matches[1]; return ( ( ! valid_unicode(hexdec($hexchars)) ) ? "&amp;#x$hexchars;" : '&#x'.ltrim($hexchars,'0').';' ); } /** * Helper function to determine if a Unicode value is valid. * * @param int $i Unicode value * @return bool True if the value was a valid Unicode number */ function valid_unicode($i) { return ( $i == 0x9 || $i == 0xa || $i == 0xd || ($i >= 0x20 && $i <= 0xd7ff) || ($i >= 0xe000 && $i <= 0xfffd) || ($i >= 0x10000 && $i <= 0x10ffff) ); } /** * Convert all entities to their character counterparts. * * This function decodes numeric HTML entities (&#65; and &#x41;). It doesn't do * anything with other entities like &auml;, but we don't need them in the URL * protocol whitelisting system anyway. * * @since 1.0.0 * * @param string $string Content to change entities * @return string Content after decoded entities */ function wp_kses_decode_entities($string) { $string = preg_replace_callback('/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $string); $string = preg_replace_callback('/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $string); return $string; } /** * Regex callback for wp_kses_decode_entities() * * @param array $match preg match * @return string */ function _wp_kses_decode_entities_chr( $match ) { return chr( $match[1] ); } /** * Regex callback for wp_kses_decode_entities() * * @param array $match preg match * @return string */ function _wp_kses_decode_entities_chr_hexdec( $match ) { return chr( hexdec( $match[1] ) ); } /** * Sanitize content with allowed HTML Kses rules. * * @since 1.0.0 * @uses $allowedtags * * @param string $data Content to filter, expected to be escaped with slashes * @return string Filtered content */ function wp_filter_kses( $data ) { return addslashes( wp_kses( stripslashes( $data ), current_filter() ) ); } /** * Sanitize content with allowed HTML Kses rules. * * @since 2.9.0 * @uses $allowedtags * * @param string $data Content to filter, expected to not be escaped * @return string Filtered content */ function wp_kses_data( $data ) { return wp_kses( $data , current_filter() ); } /** * Sanitize content for allowed HTML tags for post content. * * Post content refers to the page contents of the 'post' type and not $_POST * data from forms. * * @since 2.0.0 * * @param string $data Post content to filter, expected to be escaped with slashes * @return string Filtered post content with allowed HTML tags and attributes intact. */ function wp_filter_post_kses($data) { return addslashes ( wp_kses( stripslashes( $data ), 'post' ) ); } /** * Sanitize content for allowed HTML tags for post content. * * Post content refers to the page contents of the 'post' type and not $_POST * data from forms. * * @since 2.9.0 * * @param string $data Post content to filter * @return string Filtered post content with allowed HTML tags and attributes intact. */ function wp_kses_post($data) { return wp_kses( $data , 'post' ); } /** * Strips all of the HTML in the content. * * @since 2.1.0 * * @param string $data Content to strip all HTML from * @return string Filtered content without any HTML */ function wp_filter_nohtml_kses( $data ) { return addslashes ( wp_kses( stripslashes( $data ), 'strip' ) ); } /** * Adds all Kses input form content filters. * * All hooks have default priority. The wp_filter_kses() function is added to * the 'pre_comment_content' and 'title_save_pre' hooks. * * The wp_filter_post_kses() function is added to the 'content_save_pre', * 'excerpt_save_pre', and 'content_filtered_save_pre' hooks. * * @since 2.0.0 * @uses add_filter() See description for what functions are added to what hooks. */ function kses_init_filters() { // Normal filtering add_filter('title_save_pre', 'wp_filter_kses'); // Comment filtering if ( current_user_can( 'unfiltered_html' ) ) add_filter( 'pre_comment_content', 'wp_filter_post_kses' ); else add_filter( 'pre_comment_content', 'wp_filter_kses' ); // Post filtering add_filter('content_save_pre', 'wp_filter_post_kses'); add_filter('excerpt_save_pre', 'wp_filter_post_kses'); add_filter('content_filtered_save_pre', 'wp_filter_post_kses'); } /** * Removes all Kses input form content filters. * * A quick procedural method to removing all of the filters that kses uses for * content in WordPress Loop. * * Does not remove the kses_init() function from 'init' hook (priority is * default). Also does not remove kses_init() function from 'set_current_user' * hook (priority is also default). * * @since 2.0.6 */ function kses_remove_filters() { // Normal filtering remove_filter('title_save_pre', 'wp_filter_kses'); // Comment filtering remove_filter( 'pre_comment_content', 'wp_filter_post_kses' ); remove_filter( 'pre_comment_content', 'wp_filter_kses' ); // Post filtering remove_filter('content_save_pre', 'wp_filter_post_kses'); remove_filter('excerpt_save_pre', 'wp_filter_post_kses'); remove_filter('content_filtered_save_pre', 'wp_filter_post_kses'); } /** * Sets up most of the Kses filters for input form content. * * If you remove the kses_init() function from 'init' hook and * 'set_current_user' (priority is default), then none of the Kses filter hooks * will be added. * * First removes all of the Kses filters in case the current user does not need * to have Kses filter the content. If the user does not have unfiltered_html * capability, then Kses filters are added. * * @uses kses_remove_filters() Removes the Kses filters * @uses kses_init_filters() Adds the Kses filters back if the user * does not have unfiltered HTML capability. * @since 2.0.0 */ function kses_init() { kses_remove_filters(); if (current_user_can('unfiltered_html') == false) kses_init_filters(); } add_action('init', 'kses_init'); add_action('set_current_user', 'kses_init'); /** * Inline CSS filter * * @since 2.8.1 */ function safecss_filter_attr( $css, $deprecated = '' ) { if ( !empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented $css = wp_kses_no_null($css); $css = str_replace(array("\n","\r","\t"), '', $css); if ( preg_match( '%[\\(&=}]|/\*%', $css ) ) // remove any inline css containing \ ( & } = or comments return ''; $css_array = explode( ';', trim( $css ) ); $allowed_attr = apply_filters( 'safe_style_css', array( 'text-align', 'margin', 'color', 'float', 'border', 'background', 'background-color', 'border-bottom', 'border-bottom-color', 'border-bottom-style', 'border-bottom-width', 'border-collapse', 'border-color', 'border-left', 'border-left-color', 'border-left-style', 'border-left-width', 'border-right', 'border-right-color', 'border-right-style', 'border-right-width', 'border-spacing', 'border-style', 'border-top', 'border-top-color', 'border-top-style', 'border-top-width', 'border-width', 'caption-side', 'clear', 'cursor', 'direction', 'font', 'font-family', 'font-size', 'font-style', 'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'overflow', 'padding', 'padding-bottom', 'padding-left', 'padding-right', 'padding-top', 'text-decoration', 'text-indent', 'vertical-align', 'width' ) ); if ( empty($allowed_attr) ) return $css; $css = ''; foreach ( $css_array as $css_item ) { if ( $css_item == '' ) continue; $css_item = trim( $css_item ); $found = false; if ( strpos( $css_item, ':' ) === false ) { $found = true; } else { $parts = explode( ':', $css_item ); if ( in_array( trim( $parts[0] ), $allowed_attr ) ) $found = true; } if ( $found ) { if( $css != '' ) $css .= ';'; $css .= $css_item; } } return $css; } /** * Helper function to add global attributes to a tag in the allowed html list. * * @since 3.5.0 * @access private * * @param array $value An array of attributes. * @return array The array of attributes with global attributes added. */ function _wp_add_global_attributes( $value ) { $global_attributes = array( 'class' => true, 'id' => true, 'style' => true, 'title' => true, ); if ( true === $value ) $value = array(); if ( is_array( $value ) ) return array_merge( $value, $global_attributes ); return $value; }
zyblog
trunk/zyblog/wp-includes/kses.php
PHP
asf20
41,273
<?php /** * Bookmark Template Functions for usage in Themes * * @package WordPress * @subpackage Template */ /** * The formatted output of a list of bookmarks. * * The $bookmarks array must contain bookmark objects and will be iterated over * to retrieve the bookmark to be used in the output. * * The output is formatted as HTML with no way to change that format. However, * what is between, before, and after can be changed. The link itself will be * HTML. * * This function is used internally by wp_list_bookmarks() and should not be * used by themes. * * The defaults for overwriting are: * 'show_updated' - Default is 0 (integer). Will show the time of when the * bookmark was last updated. * 'show_description' - Default is 0 (integer). Whether to show the description * of the bookmark. * 'show_images' - Default is 1 (integer). Whether to show link image if * available. * 'show_name' - Default is 0 (integer). Whether to show link name if * available. * 'before' - Default is '<li>' (string). The html or text to prepend to each * bookmarks. * 'after' - Default is '</li>' (string). The html or text to append to each * bookmarks. * 'link_before' - Default is '' (string). The html or text to prepend to each * bookmarks inside the <a> tag. * 'link_after' - Default is '' (string). The html or text to append to each * bookmarks inside the <a> tag. * 'between' - Default is '\n' (string). The string for use in between the link, * description, and image. * 'show_rating' - Default is 0 (integer). Whether to show the link rating. * * @since 2.1.0 * @access private * * @param array $bookmarks List of bookmarks to traverse * @param string|array $args Optional. Overwrite the defaults. * @return string Formatted output in HTML */ function _walk_bookmarks($bookmarks, $args = '' ) { $defaults = array( 'show_updated' => 0, 'show_description' => 0, 'show_images' => 1, 'show_name' => 0, 'before' => '<li>', 'after' => '</li>', 'between' => "\n", 'show_rating' => 0, 'link_before' => '', 'link_after' => '' ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $output = ''; // Blank string to start with. foreach ( (array) $bookmarks as $bookmark ) { if ( !isset($bookmark->recently_updated) ) $bookmark->recently_updated = false; $output .= $before; if ( $show_updated && $bookmark->recently_updated ) $output .= get_option('links_recently_updated_prepend'); $the_link = '#'; if ( !empty($bookmark->link_url) ) $the_link = esc_url($bookmark->link_url); $desc = esc_attr(sanitize_bookmark_field('link_description', $bookmark->link_description, $bookmark->link_id, 'display')); $name = esc_attr(sanitize_bookmark_field('link_name', $bookmark->link_name, $bookmark->link_id, 'display')); $title = $desc; if ( $show_updated ) if ( '00' != substr($bookmark->link_updated_f, 0, 2) ) { $title .= ' ('; $title .= sprintf(__('Last updated: %s'), date(get_option('links_updated_date_format'), $bookmark->link_updated_f + (get_option('gmt_offset') * HOUR_IN_SECONDS))); $title .= ')'; } $alt = ' alt="' . $name . ( $show_description ? ' ' . $title : '' ) . '"'; if ( '' != $title ) $title = ' title="' . $title . '"'; $rel = $bookmark->link_rel; if ( '' != $rel ) $rel = ' rel="' . esc_attr($rel) . '"'; $target = $bookmark->link_target; if ( '' != $target ) $target = ' target="' . $target . '"'; $output .= '<a href="' . $the_link . '"' . $rel . $title . $target . '>'; $output .= $link_before; if ( $bookmark->link_image != null && $show_images ) { if ( strpos($bookmark->link_image, 'http') === 0 ) $output .= "<img src=\"$bookmark->link_image\" $alt $title />"; else // If it's a relative path $output .= "<img src=\"" . get_option('siteurl') . "$bookmark->link_image\" $alt $title />"; if ( $show_name ) $output .= " $name"; } else { $output .= $name; } $output .= $link_after; $output .= '</a>'; if ( $show_updated && $bookmark->recently_updated ) $output .= get_option('links_recently_updated_append'); if ( $show_description && '' != $desc ) $output .= $between . $desc; if ( $show_rating ) $output .= $between . sanitize_bookmark_field('link_rating', $bookmark->link_rating, $bookmark->link_id, 'display'); $output .= "$after\n"; } // end while return $output; } /** * Retrieve or echo all of the bookmarks. * * List of default arguments are as follows: * 'orderby' - Default is 'name' (string). How to order the links by. String is * based off of the bookmark scheme. * 'order' - Default is 'ASC' (string). Either 'ASC' or 'DESC'. Orders in either * ascending or descending order. * 'limit' - Default is -1 (integer) or show all. The amount of bookmarks to * display. * 'category' - Default is empty string (string). Include the links in what * category ID(s). * 'category_name' - Default is empty string (string). Get links by category * name. * 'hide_invisible' - Default is 1 (integer). Whether to show (default) or hide * links marked as 'invisible'. * 'show_updated' - Default is 0 (integer). Will show the time of when the * bookmark was last updated. * 'echo' - Default is 1 (integer). Whether to echo (default) or return the * formatted bookmarks. * 'categorize' - Default is 1 (integer). Whether to show links listed by * category (default) or show links in one column. * 'show_description' - Default is 0 (integer). Whether to show the description * of the bookmark. * * These options define how the Category name will appear before the category * links are displayed, if 'categorize' is 1. If 'categorize' is 0, then it will * display for only the 'title_li' string and only if 'title_li' is not empty. * 'title_li' - Default is 'Bookmarks' (translatable string). What to show * before the links appear. * 'title_before' - Default is '<h2>' (string). The HTML or text to show before * the 'title_li' string. * 'title_after' - Default is '</h2>' (string). The HTML or text to show after * the 'title_li' string. * 'class' - Default is 'linkcat' (string). The CSS class to use for the * 'title_li'. * * 'category_before' - Default is '<li id="%id" class="%class">'. String must * contain '%id' and '%class' to get * the id of the category and the 'class' argument. These are used for * formatting in themes. * Argument will be displayed before the 'title_before' argument. * 'category_after' - Default is '</li>' (string). The HTML or text that will * appear after the list of links. * * These are only used if 'categorize' is set to 1 or true. * 'category_orderby' - Default is 'name'. How to order the bookmark category * based on term scheme. * 'category_order' - Default is 'ASC'. Set the order by either ASC (ascending) * or DESC (descending). * * @see _walk_bookmarks() For other arguments that can be set in this function * and passed to _walk_bookmarks(). * @see get_bookmarks() For other arguments that can be set in this function and * passed to get_bookmarks(). * @link http://codex.wordpress.org/Template_Tags/wp_list_bookmarks * * @since 2.1.0 * @uses _walk_bookmarks() Used to iterate over all of the bookmarks and return * the html * @uses get_terms() Gets all of the categories that are for links. * * @param string|array $args Optional. Overwrite the defaults of the function * @return string|null Will only return if echo option is set to not echo. * Default is not return anything. */ function wp_list_bookmarks($args = '') { $defaults = array( 'orderby' => 'name', 'order' => 'ASC', 'limit' => -1, 'category' => '', 'exclude_category' => '', 'category_name' => '', 'hide_invisible' => 1, 'show_updated' => 0, 'echo' => 1, 'categorize' => 1, 'title_li' => __('Bookmarks'), 'title_before' => '<h2>', 'title_after' => '</h2>', 'category_orderby' => 'name', 'category_order' => 'ASC', 'class' => 'linkcat', 'category_before' => '<li id="%id" class="%class">', 'category_after' => '</li>' ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $output = ''; if ( $categorize ) { $cats = get_terms( 'link_category', array( 'name__like' => $category_name, 'include' => $category, 'exclude' => $exclude_category, 'orderby' => $category_orderby, 'order' => $category_order, 'hierarchical' => 0 ) ); if ( empty( $cats ) ) $categorize = false; } if ( $categorize ) { // Split the bookmarks into ul's for each category foreach ( (array) $cats as $cat ) { $params = array_merge($r, array('category'=>$cat->term_id)); $bookmarks = get_bookmarks($params); if ( empty($bookmarks) ) continue; $output .= str_replace(array('%id', '%class'), array("linkcat-$cat->term_id", $class), $category_before); $catname = apply_filters( "link_category", $cat->name ); $output .= "$title_before$catname$title_after\n\t<ul class='xoxo blogroll'>\n"; $output .= _walk_bookmarks($bookmarks, $r); $output .= "\n\t</ul>\n$category_after\n"; } } else { //output one single list using title_li for the title $bookmarks = get_bookmarks($r); if ( !empty($bookmarks) ) { if ( !empty( $title_li ) ){ $output .= str_replace(array('%id', '%class'), array("linkcat-$category", $class), $category_before); $output .= "$title_before$title_li$title_after\n\t<ul class='xoxo blogroll'>\n"; $output .= _walk_bookmarks($bookmarks, $r); $output .= "\n\t</ul>\n$category_after\n"; } else { $output .= _walk_bookmarks($bookmarks, $r); } } } $output = apply_filters( 'wp_list_bookmarks', $output ); if ( !$echo ) return $output; echo $output; }
zyblog
trunk/zyblog/wp-includes/bookmark-template.php
PHP
asf20
9,678
<?php /** * Deprecated functions from past WordPress versions. You shouldn't use these * functions and look for the alternatives instead. The functions will be * removed in a later version. * * @package WordPress * @subpackage Deprecated */ /* * Deprecated functions come here to die. */ /** * Entire Post data. * * @since 0.71 * @deprecated 1.5.1 * @deprecated Use get_post() * @see get_post() * * @param int $postid * @return array */ function get_postdata($postid) { _deprecated_function( __FUNCTION__, '1.5.1', 'get_post()' ); $post = get_post($postid); $postdata = array ( 'ID' => $post->ID, 'Author_ID' => $post->post_author, 'Date' => $post->post_date, 'Content' => $post->post_content, 'Excerpt' => $post->post_excerpt, 'Title' => $post->post_title, 'Category' => $post->post_category, 'post_status' => $post->post_status, 'comment_status' => $post->comment_status, 'ping_status' => $post->ping_status, 'post_password' => $post->post_password, 'to_ping' => $post->to_ping, 'pinged' => $post->pinged, 'post_type' => $post->post_type, 'post_name' => $post->post_name ); return $postdata; } /** * Sets up the WordPress Loop. * * @since 1.0.1 * @deprecated 1.5 * @deprecated Use The Loop - {@link http://codex.wordpress.org/The_Loop Use new WordPress Loop} */ function start_wp() { global $wp_query; _deprecated_function( __FUNCTION__, '1.5', __('new WordPress Loop') ); // Since the old style loop is being used, advance the query iterator here. $wp_query->next_post(); setup_postdata( get_post() ); } /** * Return or Print Category ID. * * @since 0.71 * @deprecated 0.71 * @deprecated use get_the_category() * @see get_the_category() * * @param bool $echo * @return null|int */ function the_category_ID($echo = true) { _deprecated_function( __FUNCTION__, '0.71', 'get_the_category()' ); // Grab the first cat in the list. $categories = get_the_category(); $cat = $categories[0]->term_id; if ( $echo ) echo $cat; return $cat; } /** * Print category with optional text before and after. * * @since 0.71 * @deprecated 0.71 * @deprecated use get_the_category_by_ID() * @see get_the_category_by_ID() * * @param string $before * @param string $after */ function the_category_head($before='', $after='') { global $currentcat, $previouscat; _deprecated_function( __FUNCTION__, '0.71', 'get_the_category_by_ID()' ); // Grab the first cat in the list. $categories = get_the_category(); $currentcat = $categories[0]->category_id; if ( $currentcat != $previouscat ) { echo $before; echo get_the_category_by_ID($currentcat); echo $after; $previouscat = $currentcat; } } /** * Prints link to the previous post. * * @since 1.5 * @deprecated 2.0 * @deprecated Use previous_post_link() * @see previous_post_link() * * @param string $format * @param string $previous * @param string $title * @param string $in_same_cat * @param int $limitprev * @param string $excluded_categories */ function previous_post($format='%', $previous='previous post: ', $title='yes', $in_same_cat='no', $limitprev=1, $excluded_categories='') { _deprecated_function( __FUNCTION__, '2.0', 'previous_post_link()' ); if ( empty($in_same_cat) || 'no' == $in_same_cat ) $in_same_cat = false; else $in_same_cat = true; $post = get_previous_post($in_same_cat, $excluded_categories); if ( !$post ) return; $string = '<a href="'.get_permalink($post->ID).'">'.$previous; if ( 'yes' == $title ) $string .= apply_filters('the_title', $post->post_title, $post->ID); $string .= '</a>'; $format = str_replace('%', $string, $format); echo $format; } /** * Prints link to the next post. * * @since 0.71 * @deprecated 2.0 * @deprecated Use next_post_link() * @see next_post_link() * * @param string $format * @param string $next * @param string $title * @param string $in_same_cat * @param int $limitnext * @param string $excluded_categories */ function next_post($format='%', $next='next post: ', $title='yes', $in_same_cat='no', $limitnext=1, $excluded_categories='') { _deprecated_function( __FUNCTION__, '2.0', 'next_post_link()' ); if ( empty($in_same_cat) || 'no' == $in_same_cat ) $in_same_cat = false; else $in_same_cat = true; $post = get_next_post($in_same_cat, $excluded_categories); if ( !$post ) return; $string = '<a href="'.get_permalink($post->ID).'">'.$next; if ( 'yes' == $title ) $string .= apply_filters('the_title', $post->post_title, $post->ID); $string .= '</a>'; $format = str_replace('%', $string, $format); echo $format; } /** * Whether user can create a post. * * @since 1.5 * @deprecated 2.0 * @deprecated Use current_user_can() * @see current_user_can() * * @param int $user_id * @param int $blog_id Not Used * @param int $category_id Not Used * @return bool */ function user_can_create_post($user_id, $blog_id = 1, $category_id = 'None') { _deprecated_function( __FUNCTION__, '2.0', 'current_user_can()' ); $author_data = get_userdata($user_id); return ($author_data->user_level > 1); } /** * Whether user can create a post. * * @since 1.5 * @deprecated 2.0 * @deprecated Use current_user_can() * @see current_user_can() * * @param int $user_id * @param int $blog_id Not Used * @param int $category_id Not Used * @return bool */ function user_can_create_draft($user_id, $blog_id = 1, $category_id = 'None') { _deprecated_function( __FUNCTION__, '2.0', 'current_user_can()' ); $author_data = get_userdata($user_id); return ($author_data->user_level >= 1); } /** * Whether user can edit a post. * * @since 1.5 * @deprecated 2.0 * @deprecated Use current_user_can() * @see current_user_can() * * @param int $user_id * @param int $post_id * @param int $blog_id Not Used * @return bool */ function user_can_edit_post($user_id, $post_id, $blog_id = 1) { _deprecated_function( __FUNCTION__, '2.0', 'current_user_can()' ); $author_data = get_userdata($user_id); $post = get_post($post_id); $post_author_data = get_userdata($post->post_author); if ( (($user_id == $post_author_data->ID) && !($post->post_status == 'publish' && $author_data->user_level < 2)) || ($author_data->user_level > $post_author_data->user_level) || ($author_data->user_level >= 10) ) { return true; } else { return false; } } /** * Whether user can delete a post. * * @since 1.5 * @deprecated 2.0 * @deprecated Use current_user_can() * @see current_user_can() * * @param int $user_id * @param int $post_id * @param int $blog_id Not Used * @return bool */ function user_can_delete_post($user_id, $post_id, $blog_id = 1) { _deprecated_function( __FUNCTION__, '2.0', 'current_user_can()' ); // right now if one can edit, one can delete return user_can_edit_post($user_id, $post_id, $blog_id); } /** * Whether user can set new posts' dates. * * @since 1.5 * @deprecated 2.0 * @deprecated Use current_user_can() * @see current_user_can() * * @param int $user_id * @param int $blog_id Not Used * @param int $category_id Not Used * @return bool */ function user_can_set_post_date($user_id, $blog_id = 1, $category_id = 'None') { _deprecated_function( __FUNCTION__, '2.0', 'current_user_can()' ); $author_data = get_userdata($user_id); return (($author_data->user_level > 4) && user_can_create_post($user_id, $blog_id, $category_id)); } /** * Whether user can delete a post. * * @since 1.5 * @deprecated 2.0 * @deprecated Use current_user_can() * @see current_user_can() * * @param int $user_id * @param int $post_id * @param int $blog_id Not Used * @return bool returns true if $user_id can edit $post_id's date */ function user_can_edit_post_date($user_id, $post_id, $blog_id = 1) { _deprecated_function( __FUNCTION__, '2.0', 'current_user_can()' ); $author_data = get_userdata($user_id); return (($author_data->user_level > 4) && user_can_edit_post($user_id, $post_id, $blog_id)); } /** * Whether user can delete a post. * * @since 1.5 * @deprecated 2.0 * @deprecated Use current_user_can() * @see current_user_can() * * @param int $user_id * @param int $post_id * @param int $blog_id Not Used * @return bool returns true if $user_id can edit $post_id's comments */ function user_can_edit_post_comments($user_id, $post_id, $blog_id = 1) { _deprecated_function( __FUNCTION__, '2.0', 'current_user_can()' ); // right now if one can edit a post, one can edit comments made on it return user_can_edit_post($user_id, $post_id, $blog_id); } /** * Whether user can delete a post. * * @since 1.5 * @deprecated 2.0 * @deprecated Use current_user_can() * @see current_user_can() * * @param int $user_id * @param int $post_id * @param int $blog_id Not Used * @return bool returns true if $user_id can delete $post_id's comments */ function user_can_delete_post_comments($user_id, $post_id, $blog_id = 1) { _deprecated_function( __FUNCTION__, '2.0', 'current_user_can()' ); // right now if one can edit comments, one can delete comments return user_can_edit_post_comments($user_id, $post_id, $blog_id); } /** * Can user can edit other user. * * @since 1.5 * @deprecated 2.0 * @deprecated Use current_user_can() * @see current_user_can() * * @param int $user_id * @param int $other_user * @return bool */ function user_can_edit_user($user_id, $other_user) { _deprecated_function( __FUNCTION__, '2.0', 'current_user_can()' ); $user = get_userdata($user_id); $other = get_userdata($other_user); if ( $user->user_level > $other->user_level || $user->user_level > 8 || $user->ID == $other->ID ) return true; else return false; } /** * Gets the links associated with category $cat_name. * * @since 0.71 * @deprecated 2.1 * @deprecated Use get_bookmarks() * @see get_bookmarks() * * @param string $cat_name Optional. The category name to use. If no match is found uses all. * @param string $before Optional. The html to output before the link. * @param string $after Optional. The html to output after the link. * @param string $between Optional. The html to output between the link/image and it's description. Not used if no image or $show_images is true. * @param bool $show_images Optional. Whether to show images (if defined). * @param string $orderby Optional. The order to output the links. E.g. 'id', 'name', 'url', 'description' or 'rating'. Or maybe owner. * If you start the name with an underscore the order will be reversed. You can also specify 'rand' as the order which will return links in a * random order. * @param bool $show_description Optional. Whether to show the description if show_images=false/not defined. * @param bool $show_rating Optional. Show rating stars/chars. * @param int $limit Optional. Limit to X entries. If not specified, all entries are shown. * @param int $show_updated Optional. Whether to show last updated timestamp */ function get_linksbyname($cat_name = "noname", $before = '', $after = '<br />', $between = " ", $show_images = true, $orderby = 'id', $show_description = true, $show_rating = false, $limit = -1, $show_updated = 0) { _deprecated_function( __FUNCTION__, '2.1', 'get_bookmarks()' ); $cat_id = -1; $cat = get_term_by('name', $cat_name, 'link_category'); if ( $cat ) $cat_id = $cat->term_id; get_links($cat_id, $before, $after, $between, $show_images, $orderby, $show_description, $show_rating, $limit, $show_updated); } /** * Gets the links associated with the named category. * * @since 1.0.1 * @deprecated 2.1 * @deprecated Use wp_list_bookmarks() * @see wp_list_bookmarks() * * @param string $category The category to use. * @param string $args * @return bool|null */ function wp_get_linksbyname($category, $args = '') { _deprecated_function(__FUNCTION__, '2.1', 'wp_list_bookmarks()'); $defaults = array( 'after' => '<br />', 'before' => '', 'categorize' => 0, 'category_after' => '', 'category_before' => '', 'category_name' => $category, 'show_description' => 1, 'title_li' => '', ); $r = wp_parse_args( $args, $defaults ); return wp_list_bookmarks($r); } /** * Gets an array of link objects associated with category $cat_name. * * <code> * $links = get_linkobjectsbyname('fred'); * foreach ($links as $link) { * echo '<li>'.$link->link_name.'</li>'; * } * </code> * * @since 1.0.1 * @deprecated 2.1 * @deprecated Use get_bookmarks() * @see get_bookmarks() * * @param string $cat_name The category name to use. If no match is found uses all. * @param string $orderby The order to output the links. E.g. 'id', 'name', 'url', 'description', or 'rating'. * Or maybe owner. If you start the name with an underscore the order will be reversed. You can also * specify 'rand' as the order which will return links in a random order. * @param int $limit Limit to X entries. If not specified, all entries are shown. * @return unknown */ function get_linkobjectsbyname($cat_name = "noname" , $orderby = 'name', $limit = -1) { _deprecated_function( __FUNCTION__, '2.1', 'get_bookmarks()' ); $cat_id = -1; $cat = get_term_by('name', $cat_name, 'link_category'); if ( $cat ) $cat_id = $cat->term_id; return get_linkobjects($cat_id, $orderby, $limit); } /** * Gets an array of link objects associated with category n. * * Usage: * <code> * $links = get_linkobjects(1); * if ($links) { * foreach ($links as $link) { * echo '<li>'.$link->link_name.'<br />'.$link->link_description.'</li>'; * } * } * </code> * * Fields are: * <ol> * <li>link_id</li> * <li>link_url</li> * <li>link_name</li> * <li>link_image</li> * <li>link_target</li> * <li>link_category</li> * <li>link_description</li> * <li>link_visible</li> * <li>link_owner</li> * <li>link_rating</li> * <li>link_updated</li> * <li>link_rel</li> * <li>link_notes</li> * </ol> * * @since 1.0.1 * @deprecated 2.1 * @deprecated Use get_bookmarks() * @see get_bookmarks() * * @param int $category The category to use. If no category supplied uses all * @param string $orderby the order to output the links. E.g. 'id', 'name', 'url', * 'description', or 'rating'. Or maybe owner. If you start the name with an * underscore the order will be reversed. You can also specify 'rand' as the * order which will return links in a random order. * @param int $limit Limit to X entries. If not specified, all entries are shown. * @return unknown */ function get_linkobjects($category = 0, $orderby = 'name', $limit = 0) { _deprecated_function( __FUNCTION__, '2.1', 'get_bookmarks()' ); $links = get_bookmarks( array( 'category' => $category, 'orderby' => $orderby, 'limit' => $limit ) ) ; $links_array = array(); foreach ($links as $link) $links_array[] = $link; return $links_array; } /** * Gets the links associated with category 'cat_name' and display rating stars/chars. * * @since 0.71 * @deprecated 2.1 * @deprecated Use get_bookmarks() * @see get_bookmarks() * * @param string $cat_name The category name to use. If no match is found uses all * @param string $before The html to output before the link * @param string $after The html to output after the link * @param string $between The html to output between the link/image and it's description. Not used if no image or show_images is true * @param bool $show_images Whether to show images (if defined). * @param string $orderby the order to output the links. E.g. 'id', 'name', 'url', * 'description', or 'rating'. Or maybe owner. If you start the name with an * underscore the order will be reversed. You can also specify 'rand' as the * order which will return links in a random order. * @param bool $show_description Whether to show the description if show_images=false/not defined * @param int $limit Limit to X entries. If not specified, all entries are shown. * @param int $show_updated Whether to show last updated timestamp */ function get_linksbyname_withrating($cat_name = "noname", $before = '', $after = '<br />', $between = " ", $show_images = true, $orderby = 'id', $show_description = true, $limit = -1, $show_updated = 0) { _deprecated_function( __FUNCTION__, '2.1', 'get_bookmarks()' ); get_linksbyname($cat_name, $before, $after, $between, $show_images, $orderby, $show_description, true, $limit, $show_updated); } /** * Gets the links associated with category n and display rating stars/chars. * * @since 0.71 * @deprecated 2.1 * @deprecated Use get_bookmarks() * @see get_bookmarks() * * @param int $category The category to use. If no category supplied uses all * @param string $before The html to output before the link * @param string $after The html to output after the link * @param string $between The html to output between the link/image and it's description. Not used if no image or show_images == true * @param bool $show_images Whether to show images (if defined). * @param string $orderby The order to output the links. E.g. 'id', 'name', 'url', * 'description', or 'rating'. Or maybe owner. If you start the name with an * underscore the order will be reversed. You can also specify 'rand' as the * order which will return links in a random order. * @param bool $show_description Whether to show the description if show_images=false/not defined. * @param string $limit Limit to X entries. If not specified, all entries are shown. * @param int $show_updated Whether to show last updated timestamp */ function get_links_withrating($category = -1, $before = '', $after = '<br />', $between = " ", $show_images = true, $orderby = 'id', $show_description = true, $limit = -1, $show_updated = 0) { _deprecated_function( __FUNCTION__, '2.1', 'get_bookmarks()' ); get_links($category, $before, $after, $between, $show_images, $orderby, $show_description, true, $limit, $show_updated); } /** * Gets the auto_toggle setting. * * @since 0.71 * @deprecated 2.1 * @deprecated No alternative function available * * @param int $id The category to get. If no category supplied uses 0 * @return int Only returns 0. */ function get_autotoggle($id = 0) { _deprecated_function( __FUNCTION__, '2.1' ); return 0; } /** * @since 0.71 * @deprecated 2.1 * @deprecated Use wp_list_categories() * @see wp_list_categories() * * @param int $optionall * @param string $all * @param string $sort_column * @param string $sort_order * @param string $file * @param bool $list * @param int $optiondates * @param int $optioncount * @param int $hide_empty * @param int $use_desc_for_title * @param bool $children * @param int $child_of * @param int $categories * @param int $recurse * @param string $feed * @param string $feed_image * @param string $exclude * @param bool $hierarchical * @return unknown */ function list_cats($optionall = 1, $all = 'All', $sort_column = 'ID', $sort_order = 'asc', $file = '', $list = true, $optiondates = 0, $optioncount = 0, $hide_empty = 1, $use_desc_for_title = 1, $children=false, $child_of=0, $categories=0, $recurse=0, $feed = '', $feed_image = '', $exclude = '', $hierarchical=false) { _deprecated_function( __FUNCTION__, '2.1', 'wp_list_categories()' ); $query = compact('optionall', 'all', 'sort_column', 'sort_order', 'file', 'list', 'optiondates', 'optioncount', 'hide_empty', 'use_desc_for_title', 'children', 'child_of', 'categories', 'recurse', 'feed', 'feed_image', 'exclude', 'hierarchical'); return wp_list_cats($query); } /** * @since 1.2 * @deprecated 2.1 * @deprecated Use wp_list_categories() * @see wp_list_categories() * * @param string|array $args * @return unknown */ function wp_list_cats($args = '') { _deprecated_function( __FUNCTION__, '2.1', 'wp_list_categories()' ); $r = wp_parse_args( $args ); // Map to new names. if ( isset($r['optionall']) && isset($r['all'])) $r['show_option_all'] = $r['all']; if ( isset($r['sort_column']) ) $r['orderby'] = $r['sort_column']; if ( isset($r['sort_order']) ) $r['order'] = $r['sort_order']; if ( isset($r['optiondates']) ) $r['show_last_update'] = $r['optiondates']; if ( isset($r['optioncount']) ) $r['show_count'] = $r['optioncount']; if ( isset($r['list']) ) $r['style'] = $r['list'] ? 'list' : 'break'; $r['title_li'] = ''; return wp_list_categories($r); } /** * @since 0.71 * @deprecated 2.1 * @deprecated Use wp_dropdown_categories() * @see wp_dropdown_categories() * * @param int $optionall * @param string $all * @param string $orderby * @param string $order * @param int $show_last_update * @param int $show_count * @param int $hide_empty * @param bool $optionnone * @param int $selected * @param int $exclude * @return unknown */ function dropdown_cats($optionall = 1, $all = 'All', $orderby = 'ID', $order = 'asc', $show_last_update = 0, $show_count = 0, $hide_empty = 1, $optionnone = false, $selected = 0, $exclude = 0) { _deprecated_function( __FUNCTION__, '2.1', 'wp_dropdown_categories()' ); $show_option_all = ''; if ( $optionall ) $show_option_all = $all; $show_option_none = ''; if ( $optionnone ) $show_option_none = __('None'); $vars = compact('show_option_all', 'show_option_none', 'orderby', 'order', 'show_last_update', 'show_count', 'hide_empty', 'selected', 'exclude'); $query = add_query_arg($vars, ''); return wp_dropdown_categories($query); } /** * @since 1.2 * @deprecated 2.1 * @deprecated Use wp_list_authors() * @see wp_list_authors() * * @param bool $optioncount * @param bool $exclude_admin * @param bool $show_fullname * @param bool $hide_empty * @param string $feed * @param string $feed_image * @return unknown */ function list_authors($optioncount = false, $exclude_admin = true, $show_fullname = false, $hide_empty = true, $feed = '', $feed_image = '') { _deprecated_function( __FUNCTION__, '2.1', 'wp_list_authors()' ); $args = compact('optioncount', 'exclude_admin', 'show_fullname', 'hide_empty', 'feed', 'feed_image'); return wp_list_authors($args); } /** * @since 1.0.1 * @deprecated 2.1 * @deprecated Use wp_get_post_categories() * @see wp_get_post_categories() * * @param int $blogid Not Used * @param int $post_ID * @return unknown */ function wp_get_post_cats($blogid = '1', $post_ID = 0) { _deprecated_function( __FUNCTION__, '2.1', 'wp_get_post_categories()' ); return wp_get_post_categories($post_ID); } /** * Sets the categories that the post id belongs to. * * @since 1.0.1 * @deprecated 2.1 * @deprecated Use wp_set_post_categories() * @see wp_set_post_categories() * * @param int $blogid Not used * @param int $post_ID * @param array $post_categories * @return unknown */ function wp_set_post_cats($blogid = '1', $post_ID = 0, $post_categories = array()) { _deprecated_function( __FUNCTION__, '2.1', 'wp_set_post_categories()' ); return wp_set_post_categories($post_ID, $post_categories); } /** * @since 0.71 * @deprecated 2.1 * @deprecated Use wp_get_archives() * @see wp_get_archives() * * @param string $type * @param string $limit * @param string $format * @param string $before * @param string $after * @param bool $show_post_count * @return unknown */ function get_archives($type='', $limit='', $format='html', $before = '', $after = '', $show_post_count = false) { _deprecated_function( __FUNCTION__, '2.1', 'wp_get_archives()' ); $args = compact('type', 'limit', 'format', 'before', 'after', 'show_post_count'); return wp_get_archives($args); } /** * Returns or Prints link to the author's posts. * * @since 1.2 * @deprecated 2.1 * @deprecated Use get_author_posts_url() * @see get_author_posts_url() * * @param bool $echo Optional. * @param int $author_id Required. * @param string $author_nicename Optional. * @return string|null */ function get_author_link($echo = false, $author_id, $author_nicename = '') { _deprecated_function( __FUNCTION__, '2.1', 'get_author_posts_url()' ); $link = get_author_posts_url($author_id, $author_nicename); if ( $echo ) echo $link; return $link; } /** * Print list of pages based on arguments. * * @since 0.71 * @deprecated 2.1 * @deprecated Use wp_link_pages() * @see wp_link_pages() * * @param string $before * @param string $after * @param string $next_or_number * @param string $nextpagelink * @param string $previouspagelink * @param string $pagelink * @param string $more_file * @return string */ function link_pages($before='<br />', $after='<br />', $next_or_number='number', $nextpagelink='next page', $previouspagelink='previous page', $pagelink='%', $more_file='') { _deprecated_function( __FUNCTION__, '2.1', 'wp_link_pages()' ); $args = compact('before', 'after', 'next_or_number', 'nextpagelink', 'previouspagelink', 'pagelink', 'more_file'); return wp_link_pages($args); } /** * Get value based on option. * * @since 0.71 * @deprecated 2.1 * @deprecated Use get_option() * @see get_option() * * @param string $option * @return string */ function get_settings($option) { _deprecated_function( __FUNCTION__, '2.1', 'get_option()' ); return get_option($option); } /** * Print the permalink of the current post in the loop. * * @since 0.71 * @deprecated 1.2 * @deprecated Use the_permalink() * @see the_permalink() */ function permalink_link() { _deprecated_function( __FUNCTION__, '1.2', 'the_permalink()' ); the_permalink(); } /** * Print the permalink to the RSS feed. * * @since 0.71 * @deprecated 2.3 * @deprecated Use the_permalink_rss() * @see the_permalink_rss() * * @param string $deprecated */ function permalink_single_rss($deprecated = '') { _deprecated_function( __FUNCTION__, '2.3', 'the_permalink_rss()' ); the_permalink_rss(); } /** * Gets the links associated with category. * * @see get_links() for argument information that can be used in $args * @since 1.0.1 * @deprecated 2.1 * @deprecated Use wp_list_bookmarks() * @see wp_list_bookmarks() * * @param string $args a query string * @return null|string */ function wp_get_links($args = '') { _deprecated_function( __FUNCTION__, '2.1', 'wp_list_bookmarks()' ); if ( strpos( $args, '=' ) === false ) { $cat_id = $args; $args = add_query_arg( 'category', $cat_id, $args ); } $defaults = array( 'after' => '<br />', 'before' => '', 'between' => ' ', 'categorize' => 0, 'category' => '', 'echo' => true, 'limit' => -1, 'orderby' => 'name', 'show_description' => true, 'show_images' => true, 'show_rating' => false, 'show_updated' => true, 'title_li' => '', ); $r = wp_parse_args( $args, $defaults ); return wp_list_bookmarks($r); } /** * Gets the links associated with category by id. * * @since 0.71 * @deprecated 2.1 * @deprecated Use get_bookmarks() * @see get_bookmarks() * * @param int $category The category to use. If no category supplied uses all * @param string $before the html to output before the link * @param string $after the html to output after the link * @param string $between the html to output between the link/image and its description. * Not used if no image or show_images == true * @param bool $show_images whether to show images (if defined). * @param string $orderby the order to output the links. E.g. 'id', 'name', 'url', * 'description', or 'rating'. Or maybe owner. If you start the name with an * underscore the order will be reversed. You can also specify 'rand' as the order * which will return links in a random order. * @param bool $show_description whether to show the description if show_images=false/not defined. * @param bool $show_rating show rating stars/chars * @param int $limit Limit to X entries. If not specified, all entries are shown. * @param int $show_updated whether to show last updated timestamp * @param bool $echo whether to echo the results, or return them instead * @return null|string */ function get_links($category = -1, $before = '', $after = '<br />', $between = ' ', $show_images = true, $orderby = 'name', $show_description = true, $show_rating = false, $limit = -1, $show_updated = 1, $echo = true) { _deprecated_function( __FUNCTION__, '2.1', 'get_bookmarks()' ); $order = 'ASC'; if ( substr($orderby, 0, 1) == '_' ) { $order = 'DESC'; $orderby = substr($orderby, 1); } if ( $category == -1 ) //get_bookmarks uses '' to signify all categories $category = ''; $results = get_bookmarks(array('category' => $category, 'orderby' => $orderby, 'order' => $order, 'show_updated' => $show_updated, 'limit' => $limit)); if ( !$results ) return; $output = ''; foreach ( (array) $results as $row ) { if ( !isset($row->recently_updated) ) $row->recently_updated = false; $output .= $before; if ( $show_updated && $row->recently_updated ) $output .= get_option('links_recently_updated_prepend'); $the_link = '#'; if ( !empty($row->link_url) ) $the_link = esc_url($row->link_url); $rel = $row->link_rel; if ( '' != $rel ) $rel = ' rel="' . $rel . '"'; $desc = esc_attr(sanitize_bookmark_field('link_description', $row->link_description, $row->link_id, 'display')); $name = esc_attr(sanitize_bookmark_field('link_name', $row->link_name, $row->link_id, 'display')); $title = $desc; if ( $show_updated ) if (substr($row->link_updated_f, 0, 2) != '00') $title .= ' ('.__('Last updated') . ' ' . date(get_option('links_updated_date_format'), $row->link_updated_f + (get_option('gmt_offset') * HOUR_IN_SECONDS)) . ')'; if ( '' != $title ) $title = ' title="' . $title . '"'; $alt = ' alt="' . $name . '"'; $target = $row->link_target; if ( '' != $target ) $target = ' target="' . $target . '"'; $output .= '<a href="' . $the_link . '"' . $rel . $title . $target. '>'; if ( $row->link_image != null && $show_images ) { if ( strpos($row->link_image, 'http') !== false ) $output .= "<img src=\"$row->link_image\" $alt $title />"; else // If it's a relative path $output .= "<img src=\"" . get_option('siteurl') . "$row->link_image\" $alt $title />"; } else { $output .= $name; } $output .= '</a>'; if ( $show_updated && $row->recently_updated ) $output .= get_option('links_recently_updated_append'); if ( $show_description && '' != $desc ) $output .= $between . $desc; if ($show_rating) { $output .= $between . get_linkrating($row); } $output .= "$after\n"; } // end while if ( !$echo ) return $output; echo $output; } /** * Output entire list of links by category. * * Output a list of all links, listed by category, using the settings in * $wpdb->linkcategories and output it as a nested HTML unordered list. * * @since 1.0.1 * @deprecated 2.1 * @deprecated Use wp_list_bookmarks() * @see wp_list_bookmarks() * * @param string $order Sort link categories by 'name' or 'id' */ function get_links_list($order = 'name') { _deprecated_function( __FUNCTION__, '2.1', 'wp_list_bookmarks()' ); $order = strtolower($order); // Handle link category sorting $direction = 'ASC'; if ( '_' == substr($order,0,1) ) { $direction = 'DESC'; $order = substr($order,1); } if ( !isset($direction) ) $direction = ''; $cats = get_categories(array('type' => 'link', 'orderby' => $order, 'order' => $direction, 'hierarchical' => 0)); // Display each category if ( $cats ) { foreach ( (array) $cats as $cat ) { // Handle each category. // Display the category name echo ' <li id="linkcat-' . $cat->term_id . '" class="linkcat"><h2>' . apply_filters('link_category', $cat->name ) . "</h2>\n\t<ul>\n"; // Call get_links() with all the appropriate params get_links($cat->term_id, '<li>', "</li>", "\n", true, 'name', false); // Close the last category echo "\n\t</ul>\n</li>\n"; } } } /** * Show the link to the links popup and the number of links. * * @since 0.71 * @deprecated 2.1 * @deprecated {@internal Use function instead is unknown}} * * @param string $text the text of the link * @param int $width the width of the popup window * @param int $height the height of the popup window * @param string $file the page to open in the popup window * @param bool $count the number of links in the db */ function links_popup_script($text = 'Links', $width=400, $height=400, $file='links.all.php', $count = true) { _deprecated_function( __FUNCTION__, '2.1' ); if ( $count ) $counts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->links"); $javascript = "<a href=\"#\" onclick=\"javascript:window.open('$file?popup=1', '_blank', 'width=$width,height=$height,scrollbars=yes,status=no'); return false\">"; $javascript .= $text; if ( $count ) $javascript .= " ($counts)"; $javascript .= "</a>\n\n"; echo $javascript; } /** * @since 1.0.1 * @deprecated 2.1 * @deprecated Use sanitize_bookmark_field() * @see sanitize_bookmark_field() * * @param object $link * @return unknown */ function get_linkrating($link) { _deprecated_function( __FUNCTION__, '2.1', 'sanitize_bookmark_field()' ); return sanitize_bookmark_field('link_rating', $link->link_rating, $link->link_id, 'display'); } /** * Gets the name of category by id. * * @since 0.71 * @deprecated 2.1 * @deprecated Use get_category() * @see get_category() * * @param int $id The category to get. If no category supplied uses 0 * @return string */ function get_linkcatname($id = 0) { _deprecated_function( __FUNCTION__, '2.1', 'get_category()' ); $id = (int) $id; if ( empty($id) ) return ''; $cats = wp_get_link_cats($id); if ( empty($cats) || ! is_array($cats) ) return ''; $cat_id = (int) $cats[0]; // Take the first cat. $cat = get_category($cat_id); return $cat->name; } /** * Print RSS comment feed link. * * @since 1.0.1 * @deprecated 2.5 * @deprecated Use post_comments_feed_link() * @see post_comments_feed_link() * * @param string $link_text */ function comments_rss_link($link_text = 'Comments RSS') { _deprecated_function( __FUNCTION__, '2.5', 'post_comments_feed_link()' ); post_comments_feed_link($link_text); } /** * Print/Return link to category RSS2 feed. * * @since 1.2 * @deprecated 2.5 * @deprecated Use get_category_feed_link() * @see get_category_feed_link() * * @param bool $echo * @param int $cat_ID * @return string|null */ function get_category_rss_link($echo = false, $cat_ID = 1) { _deprecated_function( __FUNCTION__, '2.5', 'get_category_feed_link()' ); $link = get_category_feed_link($cat_ID, 'rss2'); if ( $echo ) echo $link; return $link; } /** * Print/Return link to author RSS feed. * * @since 1.2 * @deprecated 2.5 * @deprecated Use get_author_feed_link() * @see get_author_feed_link() * * @param bool $echo * @param int $author_id * @return string|null */ function get_author_rss_link($echo = false, $author_id = 1) { _deprecated_function( __FUNCTION__, '2.5', 'get_author_feed_link()' ); $link = get_author_feed_link($author_id); if ( $echo ) echo $link; return $link; } /** * Return link to the post RSS feed. * * @since 1.5 * @deprecated 2.2 * @deprecated Use get_post_comments_feed_link() * @see get_post_comments_feed_link() * * @return string */ function comments_rss() { _deprecated_function( __FUNCTION__, '2.2', 'get_post_comments_feed_link()' ); return esc_url( get_post_comments_feed_link() ); } /** * An alias of wp_create_user(). * * @since 2.0 * @deprecated 2.0 * @deprecated Use wp_create_user() * @see wp_create_user() * * @param string $username The user's username. * @param string $password The user's password. * @param string $email The user's email (optional). * @return int The new user's ID. */ function create_user($username, $password, $email) { _deprecated_function( __FUNCTION__, '2.0', 'wp_create_user()' ); return wp_create_user($username, $password, $email); } /** * Unused function. * * @deprecated 2.5 */ function gzip_compression() { _deprecated_function( __FUNCTION__, '2.5' ); return false; } /** * Retrieve an array of comment data about comment $comment_ID. * * @since 0.71 * @deprecated 2.7 * @deprecated Use get_comment() * @see get_comment() * * @param int $comment_ID The ID of the comment * @param int $no_cache Whether to use the cache (cast to bool) * @param bool $include_unapproved Whether to include unapproved comments * @return array The comment data */ function get_commentdata( $comment_ID, $no_cache = 0, $include_unapproved = false ) { _deprecated_function( __FUNCTION__, '2.7', 'get_comment()' ); return get_comment($comment_ID, ARRAY_A); } /** * Retrieve the category name by the category ID. * * @since 0.71 * @deprecated 2.8 * @deprecated Use get_cat_name() * @see get_cat_name() * * @param int $cat_ID Category ID * @return string category name */ function get_catname( $cat_ID ) { _deprecated_function( __FUNCTION__, '2.8', 'get_cat_name()' ); return get_cat_name( $cat_ID ); } /** * Retrieve category children list separated before and after the term IDs. * * @since 1.2.0 * @deprecated 2.8 * @deprecated Use get_term_children() * @see get_term_children() * * @param int $id Category ID to retrieve children. * @param string $before Optional. Prepend before category term ID. * @param string $after Optional, default is empty string. Append after category term ID. * @param array $visited Optional. Category Term IDs that have already been added. * @return string */ function get_category_children( $id, $before = '/', $after = '', $visited = array() ) { _deprecated_function( __FUNCTION__, '2.8', 'get_term_children()' ); if ( 0 == $id ) return ''; $chain = ''; /** TODO: consult hierarchy */ $cat_ids = get_all_category_ids(); foreach ( (array) $cat_ids as $cat_id ) { if ( $cat_id == $id ) continue; $category = get_category( $cat_id ); if ( is_wp_error( $category ) ) return $category; if ( $category->parent == $id && !in_array( $category->term_id, $visited ) ) { $visited[] = $category->term_id; $chain .= $before.$category->term_id.$after; $chain .= get_category_children( $category->term_id, $before, $after ); } } return $chain; } /** * Retrieve the description of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('description') * @see get_the_author_meta() * * @return string The author's description. */ function get_the_author_description() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'description\')' ); return get_the_author_meta('description'); } /** * Display the description of the author of the current post. * * @since 1.0.0 * @deprecated 2.8 * @deprecated Use the_author_meta('description') * @see the_author_meta() */ function the_author_description() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'description\')' ); the_author_meta('description'); } /** * Retrieve the login name of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('login') * @see get_the_author_meta() * * @return string The author's login name (username). */ function get_the_author_login() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'login\')' ); return get_the_author_meta('login'); } /** * Display the login name of the author of the current post. * * @since 0.71 * @deprecated 2.8 * @deprecated Use the_author_meta('login') * @see the_author_meta() */ function the_author_login() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'login\')' ); the_author_meta('login'); } /** * Retrieve the first name of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('first_name') * @see get_the_author_meta() * * @return string The author's first name. */ function get_the_author_firstname() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'first_name\')' ); return get_the_author_meta('first_name'); } /** * Display the first name of the author of the current post. * * @since 0.71 * @deprecated 2.8 * @deprecated Use the_author_meta('first_name') * @see the_author_meta() */ function the_author_firstname() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'first_name\')' ); the_author_meta('first_name'); } /** * Retrieve the last name of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('last_name') * @see get_the_author_meta() * * @return string The author's last name. */ function get_the_author_lastname() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'last_name\')' ); return get_the_author_meta('last_name'); } /** * Display the last name of the author of the current post. * * @since 0.71 * @deprecated 2.8 * @deprecated Use the_author_meta('last_name') * @see the_author_meta() */ function the_author_lastname() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'last_name\')' ); the_author_meta('last_name'); } /** * Retrieve the nickname of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('nickname') * @see get_the_author_meta() * * @return string The author's nickname. */ function get_the_author_nickname() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'nickname\')' ); return get_the_author_meta('nickname'); } /** * Display the nickname of the author of the current post. * * @since 0.71 * @deprecated 2.8 * @deprecated Use the_author_meta('nickname') * @see the_author_meta() */ function the_author_nickname() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'nickname\')' ); the_author_meta('nickname'); } /** * Retrieve the email of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('email') * @see get_the_author_meta() * * @return string The author's username. */ function get_the_author_email() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'email\')' ); return get_the_author_meta('email'); } /** * Display the email of the author of the current post. * * @since 0.71 * @deprecated 2.8 * @deprecated Use the_author_meta('email') * @see the_author_meta() */ function the_author_email() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'email\')' ); the_author_meta('email'); } /** * Retrieve the ICQ number of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('icq') * @see get_the_author_meta() * * @return string The author's ICQ number. */ function get_the_author_icq() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'icq\')' ); return get_the_author_meta('icq'); } /** * Display the ICQ number of the author of the current post. * * @since 0.71 * @deprecated 2.8 * @deprecated Use the_author_meta('icq') * @see the_author_meta() */ function the_author_icq() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'icq\')' ); the_author_meta('icq'); } /** * Retrieve the Yahoo! IM name of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('yim') * @see get_the_author_meta() * * @return string The author's Yahoo! IM name. */ function get_the_author_yim() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'yim\')' ); return get_the_author_meta('yim'); } /** * Display the Yahoo! IM name of the author of the current post. * * @since 0.71 * @deprecated 2.8 * @deprecated Use the_author_meta('yim') * @see the_author_meta() */ function the_author_yim() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'yim\')' ); the_author_meta('yim'); } /** * Retrieve the MSN address of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('msn') * @see get_the_author_meta() * * @return string The author's MSN address. */ function get_the_author_msn() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'msn\')' ); return get_the_author_meta('msn'); } /** * Display the MSN address of the author of the current post. * * @since 0.71 * @deprecated 2.8 * @deprecated Use the_author_meta('msn') * @see the_author_meta() */ function the_author_msn() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'msn\')' ); the_author_meta('msn'); } /** * Retrieve the AIM address of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('aim') * @see get_the_author_meta() * * @return string The author's AIM address. */ function get_the_author_aim() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'aim\')' ); return get_the_author_meta('aim'); } /** * Display the AIM address of the author of the current post. * * @since 0.71 * @see the_author_meta() * @deprecated 2.8 * @deprecated Use the_author_meta('aim') */ function the_author_aim() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'aim\')' ); the_author_meta('aim'); } /** * Retrieve the specified author's preferred display name. * * @since 1.0.0 * @deprecated 2.8 * @deprecated Use get_the_author_meta('display_name') * @see get_the_author_meta() * * @param int $auth_id The ID of the author. * @return string The author's display name. */ function get_author_name( $auth_id = false ) { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'display_name\')' ); return get_the_author_meta('display_name', $auth_id); } /** * Retrieve the URL to the home page of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('url') * @see get_the_author_meta() * * @return string The URL to the author's page. */ function get_the_author_url() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'url\')' ); return get_the_author_meta('url'); } /** * Display the URL to the home page of the author of the current post. * * @since 0.71 * @deprecated 2.8 * @deprecated Use the_author_meta('url') * @see the_author_meta() */ function the_author_url() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'url\')' ); the_author_meta('url'); } /** * Retrieve the ID of the author of the current post. * * @since 1.5 * @deprecated 2.8 * @deprecated Use get_the_author_meta('ID') * @see get_the_author_meta() * * @return int The author's ID. */ function get_the_author_ID() { _deprecated_function( __FUNCTION__, '2.8', 'get_the_author_meta(\'ID\')' ); return get_the_author_meta('ID'); } /** * Display the ID of the author of the current post. * * @since 0.71 * @deprecated 2.8 * @deprecated Use the_author_meta('ID') * @see the_author_meta() */ function the_author_ID() { _deprecated_function( __FUNCTION__, '2.8', 'the_author_meta(\'ID\')' ); the_author_meta('ID'); } /** * Display the post content for the feed. * * For encoding the html or the $encode_html parameter, there are three possible * values. '0' will make urls footnotes and use make_url_footnote(). '1' will * encode special characters and automatically display all of the content. The * value of '2' will strip all HTML tags from the content. * * Also note that you cannot set the amount of words and not set the html * encoding. If that is the case, then the html encoding will default to 2, * which will strip all HTML tags. * * To restrict the amount of words of the content, you can use the cut * parameter. If the content is less than the amount, then there won't be any * dots added to the end. If there is content left over, then dots will be added * and the rest of the content will be removed. * * @package WordPress * @subpackage Feed * @since 0.71 * @uses apply_filters() Calls 'the_content_rss' on the content before processing. * @see get_the_content() For the $more_link_text, $stripteaser, and $more_file * parameters. * * @deprecated 2.9.0 * @deprecated Use the_content_feed() * @see the_content_feed() * * @param string $more_link_text Optional. Text to display when more content is available but not displayed. * @param int|bool $stripteaser Optional. Default is 0. * @param string $more_file Optional. * @param int $cut Optional. Amount of words to keep for the content. * @param int $encode_html Optional. How to encode the content. */ function the_content_rss($more_link_text='(more...)', $stripteaser=0, $more_file='', $cut = 0, $encode_html = 0) { _deprecated_function( __FUNCTION__, '2.9', 'the_content_feed' ); $content = get_the_content($more_link_text, $stripteaser, $more_file); $content = apply_filters('the_content_rss', $content); if ( $cut && !$encode_html ) $encode_html = 2; if ( 1== $encode_html ) { $content = esc_html($content); $cut = 0; } elseif ( 0 == $encode_html ) { $content = make_url_footnote($content); } elseif ( 2 == $encode_html ) { $content = strip_tags($content); } if ( $cut ) { $blah = explode(' ', $content); if ( count($blah) > $cut ) { $k = $cut; $use_dotdotdot = 1; } else { $k = count($blah); $use_dotdotdot = 0; } /** @todo Check performance, might be faster to use array slice instead. */ for ( $i=0; $i<$k; $i++ ) $excerpt .= $blah[$i].' '; $excerpt .= ($use_dotdotdot) ? '...' : ''; $content = $excerpt; } $content = str_replace(']]>', ']]&gt;', $content); echo $content; } /** * Strip HTML and put links at the bottom of stripped content. * * Searches for all of the links, strips them out of the content, and places * them at the bottom of the content with numbers. * * @since 0.71 * @deprecated 2.9.0 * * @param string $content Content to get links * @return string HTML stripped out of content with links at the bottom. */ function make_url_footnote( $content ) { _deprecated_function( __FUNCTION__, '2.9', '' ); preg_match_all( '/<a(.+?)href=\"(.+?)\"(.*?)>(.+?)<\/a>/', $content, $matches ); $links_summary = "\n"; for ( $i=0; $i<count($matches[0]); $i++ ) { $link_match = $matches[0][$i]; $link_number = '['.($i+1).']'; $link_url = $matches[2][$i]; $link_text = $matches[4][$i]; $content = str_replace( $link_match, $link_text . ' ' . $link_number, $content ); $link_url = ( ( strtolower( substr( $link_url, 0, 7 ) ) != 'http://' ) && ( strtolower( substr( $link_url, 0, 8 ) ) != 'https://' ) ) ? get_option( 'home' ) . $link_url : $link_url; $links_summary .= "\n" . $link_number . ' ' . $link_url; } $content = strip_tags( $content ); $content .= $links_summary; return $content; } /** * Retrieve translated string with vertical bar context * * Quite a few times, there will be collisions with similar translatable text * found in more than two places but with different translated context. * * In order to use the separate contexts, the _c() function is used and the * translatable string uses a pipe ('|') which has the context the string is in. * * When the translated string is returned, it is everything before the pipe, not * including the pipe character. If there is no pipe in the translated text then * everything is returned. * * @since 2.2.0 * @deprecated 2.9.0 * @deprecated Use _x() * @see _x() * * @param string $text Text to translate * @param string $domain Optional. Domain to retrieve the translated text * @return string Translated context string without pipe */ function _c( $text, $domain = 'default' ) { _deprecated_function( __FUNCTION__, '2.9', '_x()' ); return before_last_bar( translate( $text, $domain ) ); } /** * Translates $text like translate(), but assumes that the text * contains a context after its last vertical bar. * * @since 2.5 * @uses translate() * @deprecated 3.0.0 * @deprecated Use _x() * @see _x() * * @param string $text Text to translate * @param string $domain Domain to retrieve the translated text * @return string Translated text */ function translate_with_context( $text, $domain = 'default' ) { _deprecated_function( __FUNCTION__, '2.9', '_x()' ); return before_last_bar( translate( $text, $domain ) ); } /** * A version of _n(), which supports contexts. * Strips everything from the translation after the last bar. * * @since 2.7.0 * @deprecated 3.0.0 * @deprecated Use _nx() * @see _nx() * @see _n() For parameters. * @see _c() For parameters. _c() is deprecated. * */ function _nc( $single, $plural, $number, $domain = 'default' ) { _deprecated_function( __FUNCTION__, '2.9', '_nx()' ); return before_last_bar( _n( $single, $plural, $number, $domain ) ); } /** * Retrieve the plural or single form based on the amount. * * @since 1.2.0 * @deprecated 2.8.0 * @deprecated Use _n() * @see _n() */ function __ngettext() { _deprecated_function( __FUNCTION__, '2.8', '_n()' ); $args = func_get_args(); return call_user_func_array('_n', $args); } /** * Register plural strings in POT file, but don't translate them. * * @since 2.5 * @deprecated 2.8.0 * @deprecated Use _n_noop() * @see _n_noop() */ function __ngettext_noop() { _deprecated_function( __FUNCTION__, '2.8', '_n_noop()' ); $args = func_get_args(); return call_user_func_array('_n_noop', $args); } /** * Retrieve all autoload options, or all options if no autoloaded ones exist. * * @since 1.0.0 * @deprecated 3.0.0 * @deprecated Use wp_load_alloptions()) * @see wp_load_alloptions() * * @return array List of all options. */ function get_alloptions() { _deprecated_function( __FUNCTION__, '3.0', 'wp_load_alloptions()' ); return wp_load_alloptions(); } /** * Retrieve HTML content of attachment image with link. * * @since 2.0.0 * @deprecated 2.5.0 * @deprecated Use wp_get_attachment_link() * @see wp_get_attachment_link() * * @param int $id Optional. Post ID. * @param bool $fullsize Optional, default is false. Whether to use full size image. * @param array $max_dims Optional. Max image dimensions. * @param bool $permalink Optional, default is false. Whether to include permalink to image. * @return string */ function get_the_attachment_link($id = 0, $fullsize = false, $max_dims = false, $permalink = false) { _deprecated_function( __FUNCTION__, '2.5', 'wp_get_attachment_link()' ); $id = (int) $id; $_post = get_post($id); if ( ('attachment' != $_post->post_type) || !$url = wp_get_attachment_url($_post->ID) ) return __('Missing Attachment'); if ( $permalink ) $url = get_attachment_link($_post->ID); $post_title = esc_attr($_post->post_title); $innerHTML = get_attachment_innerHTML($_post->ID, $fullsize, $max_dims); return "<a href='$url' title='$post_title'>$innerHTML</a>"; } /** * Retrieve icon URL and Path. * * @since 2.1.0 * @deprecated 2.5.0 * @deprecated Use wp_get_attachment_image_src() * @see wp_get_attachment_image_src() * * @param int $id Optional. Post ID. * @param bool $fullsize Optional, default to false. Whether to have full image. * @return array Icon URL and full path to file, respectively. */ function get_attachment_icon_src( $id = 0, $fullsize = false ) { _deprecated_function( __FUNCTION__, '2.5', 'wp_get_attachment_image_src()' ); $id = (int) $id; if ( !$post = get_post($id) ) return false; $file = get_attached_file( $post->ID ); if ( !$fullsize && $src = wp_get_attachment_thumb_url( $post->ID ) ) { // We have a thumbnail desired, specified and existing $src_file = basename($src); $class = 'attachmentthumb'; } elseif ( wp_attachment_is_image( $post->ID ) ) { // We have an image without a thumbnail $src = wp_get_attachment_url( $post->ID ); $src_file = & $file; $class = 'attachmentimage'; } elseif ( $src = wp_mime_type_icon( $post->ID ) ) { // No thumb, no image. We'll look for a mime-related icon instead. $icon_dir = apply_filters( 'icon_dir', get_template_directory() . '/images' ); $src_file = $icon_dir . '/' . basename($src); } if ( !isset($src) || !$src ) return false; return array($src, $src_file); } /** * Retrieve HTML content of icon attachment image element. * * @since 2.0.0 * @deprecated 2.5.0 * @deprecated Use wp_get_attachment_image() * @see wp_get_attachment_image() * * @param int $id Optional. Post ID. * @param bool $fullsize Optional, default to false. Whether to have full size image. * @param array $max_dims Optional. Dimensions of image. * @return string HTML content. */ function get_attachment_icon( $id = 0, $fullsize = false, $max_dims = false ) { _deprecated_function( __FUNCTION__, '2.5', 'wp_get_attachment_image()' ); $id = (int) $id; if ( !$post = get_post($id) ) return false; if ( !$src = get_attachment_icon_src( $post->ID, $fullsize ) ) return false; list($src, $src_file) = $src; // Do we need to constrain the image? if ( ($max_dims = apply_filters('attachment_max_dims', $max_dims)) && file_exists($src_file) ) { $imagesize = getimagesize($src_file); if (($imagesize[0] > $max_dims[0]) || $imagesize[1] > $max_dims[1] ) { $actual_aspect = $imagesize[0] / $imagesize[1]; $desired_aspect = $max_dims[0] / $max_dims[1]; if ( $actual_aspect >= $desired_aspect ) { $height = $actual_aspect * $max_dims[0]; $constraint = "width='{$max_dims[0]}' "; $post->iconsize = array($max_dims[0], $height); } else { $width = $max_dims[1] / $actual_aspect; $constraint = "height='{$max_dims[1]}' "; $post->iconsize = array($width, $max_dims[1]); } } else { $post->iconsize = array($imagesize[0], $imagesize[1]); $constraint = ''; } } else { $constraint = ''; } $post_title = esc_attr($post->post_title); $icon = "<img src='$src' title='$post_title' alt='$post_title' $constraint/>"; return apply_filters( 'attachment_icon', $icon, $post->ID ); } /** * Retrieve HTML content of image element. * * @since 2.0.0 * @deprecated 2.5.0 * @deprecated Use wp_get_attachment_image() * @see wp_get_attachment_image() * * @param int $id Optional. Post ID. * @param bool $fullsize Optional, default to false. Whether to have full size image. * @param array $max_dims Optional. Dimensions of image. * @return string */ function get_attachment_innerHTML($id = 0, $fullsize = false, $max_dims = false) { _deprecated_function( __FUNCTION__, '2.5', 'wp_get_attachment_image()' ); $id = (int) $id; if ( !$post = get_post($id) ) return false; if ( $innerHTML = get_attachment_icon($post->ID, $fullsize, $max_dims)) return $innerHTML; $innerHTML = esc_attr($post->post_title); return apply_filters('attachment_innerHTML', $innerHTML, $post->ID); } /** * Retrieve bookmark data based on ID. * * @since 2.0.0 * @deprecated 2.1.0 * @deprecated Use get_bookmark() * @see get_bookmark() * * @param int $bookmark_id ID of link * @param string $output OBJECT, ARRAY_N, or ARRAY_A * @return object|array */ function get_link($bookmark_id, $output = OBJECT, $filter = 'raw') { _deprecated_function( __FUNCTION__, '2.1', 'get_bookmark()' ); return get_bookmark($bookmark_id, $output, $filter); } /** * Performs esc_url() for database or redirect usage. * * @since 2.3.1 * @deprecated 2.8.0 * @deprecated Use esc_url_raw() * @see esc_url_raw() * * @param string $url The URL to be cleaned. * @param array $protocols An array of acceptable protocols. * @return string The cleaned URL. */ function sanitize_url( $url, $protocols = null ) { _deprecated_function( __FUNCTION__, '2.8', 'esc_url_raw()' ); return esc_url_raw( $url, $protocols ); } /** * Checks and cleans a URL. * * A number of characters are removed from the URL. If the URL is for displaying * (the default behaviour) ampersands are also replaced. The 'clean_url' filter * is applied to the returned cleaned URL. * * @since 1.2.0 * @deprecated 3.0.0 * @deprecated Use esc_url() * @see Alias for esc_url() * * @param string $url The URL to be cleaned. * @param array $protocols Optional. An array of acceptable protocols. * @param string $context Optional. How the URL will be used. Default is 'display'. * @return string The cleaned $url after the 'clean_url' filter is applied. */ function clean_url( $url, $protocols = null, $context = 'display' ) { if ( $context == 'db' ) _deprecated_function( 'clean_url( $context = \'db\' )', '3.0', 'esc_url_raw()' ); else _deprecated_function( __FUNCTION__, '3.0', 'esc_url()' ); return esc_url( $url, $protocols, $context ); } /** * Escape single quotes, specialchar double quotes, and fix line endings. * * The filter 'js_escape' is also applied by esc_js() * * @since 2.0.4 * @deprecated 2.8.0 * @deprecated Use esc_js() * @see esc_js() * * @param string $text The text to be escaped. * @return string Escaped text. */ function js_escape( $text ) { _deprecated_function( __FUNCTION__, '2.8', 'esc_js()' ); return esc_js( $text ); } /** * Escaping for HTML blocks. * * @deprecated 2.8.0 * @deprecated Use esc_html() * @see esc_html() */ function wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) { _deprecated_function( __FUNCTION__, '2.8', 'esc_html()' ); if ( func_num_args() > 1 ) { // Maintain backwards compat for people passing additional args $args = func_get_args(); return call_user_func_array( '_wp_specialchars', $args ); } else { return esc_html( $string ); } } /** * Escaping for HTML attributes. * * @since 2.0.6 * @deprecated 2.8.0 * @deprecated Use esc_attr() * @see esc_attr() * * @param string $text * @return string */ function attribute_escape( $text ) { _deprecated_function( __FUNCTION__, '2.8', 'esc_attr()' ); return esc_attr( $text ); } /** * Register widget for sidebar with backwards compatibility. * * Allows $name to be an array that accepts either three elements to grab the * first element and the third for the name or just uses the first element of * the array for the name. * * Passes to {@link wp_register_sidebar_widget()} after argument list and * backwards compatibility is complete. * * @since 2.2.0 * @deprecated 2.8.0 * @deprecated Use wp_register_sidebar_widget() * @see wp_register_sidebar_widget() * * @param string|int $name Widget ID. * @param callback $output_callback Run when widget is called. * @param string $classname Classname widget option. * @param mixed $params,... Widget parameters. */ function register_sidebar_widget($name, $output_callback, $classname = '') { _deprecated_function( __FUNCTION__, '2.8', 'wp_register_sidebar_widget()' ); // Compat if ( is_array($name) ) { if ( count($name) == 3 ) $name = sprintf($name[0], $name[2]); else $name = $name[0]; } $id = sanitize_title($name); $options = array(); if ( !empty($classname) && is_string($classname) ) $options['classname'] = $classname; $params = array_slice(func_get_args(), 2); $args = array($id, $name, $output_callback, $options); if ( !empty($params) ) $args = array_merge($args, $params); call_user_func_array('wp_register_sidebar_widget', $args); } /** * Alias of {@link wp_unregister_sidebar_widget()}. * * @since 2.2.0 * @deprecated 2.8.0 * @deprecated Use wp_unregister_sidebar_widget() * @see wp_unregister_sidebar_widget() * * @param int|string $id Widget ID. */ function unregister_sidebar_widget($id) { _deprecated_function( __FUNCTION__, '2.8', 'wp_unregister_sidebar_widget()' ); return wp_unregister_sidebar_widget($id); } /** * Registers widget control callback for customizing options. * * Allows $name to be an array that accepts either three elements to grab the * first element and the third for the name or just uses the first element of * the array for the name. * * Passes to {@link wp_register_widget_control()} after the argument list has * been compiled. * * @since 2.2.0 * @deprecated 2.8.0 * @deprecated Use wp_register_widget_control() * @see wp_register_widget_control() * * @param int|string $name Sidebar ID. * @param callback $control_callback Widget control callback to display and process form. * @param int $width Widget width. * @param int $height Widget height. */ function register_widget_control($name, $control_callback, $width = '', $height = '') { _deprecated_function( __FUNCTION__, '2.8', 'wp_register_widget_control()' ); // Compat if ( is_array($name) ) { if ( count($name) == 3 ) $name = sprintf($name[0], $name[2]); else $name = $name[0]; } $id = sanitize_title($name); $options = array(); if ( !empty($width) ) $options['width'] = $width; if ( !empty($height) ) $options['height'] = $height; $params = array_slice(func_get_args(), 4); $args = array($id, $name, $control_callback, $options); if ( !empty($params) ) $args = array_merge($args, $params); call_user_func_array('wp_register_widget_control', $args); } /** * Alias of {@link wp_unregister_widget_control()}. * * @since 2.2.0 * @deprecated 2.8.0 * @deprecated Use wp_unregister_widget_control() * @see wp_unregister_widget_control() * * @param int|string $id Widget ID. */ function unregister_widget_control($id) { _deprecated_function( __FUNCTION__, '2.8', 'wp_unregister_widget_control()' ); return wp_unregister_widget_control($id); } /** * Remove user meta data. * * @since 2.0.0 * @deprecated 3.0.0 * @deprecated Use delete_user_meta() * @see delete_user_meta() * * @param int $user_id User ID. * @param string $meta_key Metadata key. * @param mixed $meta_value Metadata value. * @return bool True deletion completed and false if user_id is not a number. */ function delete_usermeta( $user_id, $meta_key, $meta_value = '' ) { _deprecated_function( __FUNCTION__, '3.0', 'delete_user_meta()' ); global $wpdb; if ( !is_numeric( $user_id ) ) return false; $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key); if ( is_array($meta_value) || is_object($meta_value) ) $meta_value = serialize($meta_value); $meta_value = trim( $meta_value ); $cur = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) ); if ( $cur && $cur->umeta_id ) do_action( 'delete_usermeta', $cur->umeta_id, $user_id, $meta_key, $meta_value ); if ( ! empty($meta_value) ) $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s AND meta_value = %s", $user_id, $meta_key, $meta_value) ); else $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) ); clean_user_cache( $user_id ); wp_cache_delete( $user_id, 'user_meta' ); if ( $cur && $cur->umeta_id ) do_action( 'deleted_usermeta', $cur->umeta_id, $user_id, $meta_key, $meta_value ); return true; } /** * Retrieve user metadata. * * If $user_id is not a number, then the function will fail over with a 'false' * boolean return value. Other returned values depend on whether there is only * one item to be returned, which be that single item type. If there is more * than one metadata value, then it will be list of metadata values. * * @since 2.0.0 * @deprecated 3.0.0 * @deprecated Use get_user_meta() * @see get_user_meta() * * @param int $user_id User ID * @param string $meta_key Optional. Metadata key. * @return mixed */ function get_usermeta( $user_id, $meta_key = '' ) { _deprecated_function( __FUNCTION__, '3.0', 'get_user_meta()' ); global $wpdb; $user_id = (int) $user_id; if ( !$user_id ) return false; if ( !empty($meta_key) ) { $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key); $user = wp_cache_get($user_id, 'users'); // Check the cached user object if ( false !== $user && isset($user->$meta_key) ) $metas = array($user->$meta_key); else $metas = $wpdb->get_col( $wpdb->prepare("SELECT meta_value FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) ); } else { $metas = $wpdb->get_col( $wpdb->prepare("SELECT meta_value FROM $wpdb->usermeta WHERE user_id = %d", $user_id) ); } if ( empty($metas) ) { if ( empty($meta_key) ) return array(); else return ''; } $metas = array_map('maybe_unserialize', $metas); if ( count($metas) == 1 ) return $metas[0]; else return $metas; } /** * Update metadata of user. * * There is no need to serialize values, they will be serialized if it is * needed. The metadata key can only be a string with underscores. All else will * be removed. * * Will remove the metadata, if the meta value is empty. * * @since 2.0.0 * @deprecated 3.0.0 * @deprecated Use update_user_meta() * @see update_user_meta() * * @param int $user_id User ID * @param string $meta_key Metadata key. * @param mixed $meta_value Metadata value. * @return bool True on successful update, false on failure. */ function update_usermeta( $user_id, $meta_key, $meta_value ) { _deprecated_function( __FUNCTION__, '3.0', 'update_user_meta()' ); global $wpdb; if ( !is_numeric( $user_id ) ) return false; $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key); /** @todo Might need fix because usermeta data is assumed to be already escaped */ if ( is_string($meta_value) ) $meta_value = stripslashes($meta_value); $meta_value = maybe_serialize($meta_value); if (empty($meta_value)) { return delete_usermeta($user_id, $meta_key); } $cur = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->usermeta WHERE user_id = %d AND meta_key = %s", $user_id, $meta_key) ); if ( $cur ) do_action( 'update_usermeta', $cur->umeta_id, $user_id, $meta_key, $meta_value ); if ( !$cur ) $wpdb->insert($wpdb->usermeta, compact('user_id', 'meta_key', 'meta_value') ); else if ( $cur->meta_value != $meta_value ) $wpdb->update($wpdb->usermeta, compact('meta_value'), compact('user_id', 'meta_key') ); else return false; clean_user_cache( $user_id ); wp_cache_delete( $user_id, 'user_meta' ); if ( !$cur ) do_action( 'added_usermeta', $wpdb->insert_id, $user_id, $meta_key, $meta_value ); else do_action( 'updated_usermeta', $cur->umeta_id, $user_id, $meta_key, $meta_value ); return true; } /** * Get users for the blog. * * For setups that use the multi-blog feature. Can be used outside of the * multi-blog feature. * * @since 2.2.0 * @deprecated 3.1.0 * @uses $wpdb WordPress database object for queries * @uses $blog_id The Blog id of the blog for those that use more than one blog * * @param int $id Blog ID. * @return array List of users that are part of that Blog ID */ function get_users_of_blog( $id = '' ) { _deprecated_function( __FUNCTION__, '3.1', 'get_users()' ); global $wpdb, $blog_id; if ( empty($id) ) $id = (int) $blog_id; $blog_prefix = $wpdb->get_blog_prefix($id); $users = $wpdb->get_results( "SELECT user_id, user_id AS ID, user_login, display_name, user_email, meta_value FROM $wpdb->users, $wpdb->usermeta WHERE {$wpdb->users}.ID = {$wpdb->usermeta}.user_id AND meta_key = '{$blog_prefix}capabilities' ORDER BY {$wpdb->usermeta}.user_id" ); return $users; } /** * Enable/disable automatic general feed link outputting. * * @since 2.8.0 * @deprecated 3.0.0 * @deprecated Use add_theme_support( 'automatic-feed-links' ) * * @param boolean $add Optional, default is true. Add or remove links. Defaults to true. */ function automatic_feed_links( $add = true ) { _deprecated_function( __FUNCTION__, '3.0', "add_theme_support( 'automatic-feed-links' )" ); if ( $add ) add_theme_support( 'automatic-feed-links' ); else remove_action( 'wp_head', 'feed_links_extra', 3 ); // Just do this yourself in 3.0+ } /** * Retrieve user data based on field. * * @since 1.5.0 * @deprecated 3.0.0 * @deprecated Use get_the_author_meta() * @see get_the_author_meta() */ function get_profile( $field, $user = false ) { _deprecated_function( __FUNCTION__, '3.0', 'get_the_author_meta()' ); if ( $user ) { $user = get_user_by( 'login', $user ); $user = $user->ID; } return get_the_author_meta( $field, $user ); } /** * Number of posts user has written. * * @since 0.71 * @deprecated 3.0.0 * @deprecated Use count_user_posts() * @see count_user_posts() */ function get_usernumposts( $userid ) { _deprecated_function( __FUNCTION__, '3.0', 'count_user_posts()' ); return count_user_posts( $userid ); } /** * Callback used to change %uXXXX to &#YYY; syntax * * @since 2.8.0 * @access private * @deprecated 3.0.0 * * @param array $matches Single Match * @return string An HTML entity */ function funky_javascript_callback($matches) { return "&#".base_convert($matches[1],16,10).";"; } /** * Fixes javascript bugs in browsers. * * Converts unicode characters to HTML numbered entities. * * @since 1.5.0 * @uses $is_macIE * @uses $is_winIE * @deprecated 3.0.0 * * @param string $text Text to be made safe. * @return string Fixed text. */ function funky_javascript_fix($text) { _deprecated_function( __FUNCTION__, '3.0' ); // Fixes for browsers' javascript bugs global $is_macIE, $is_winIE; if ( $is_winIE || $is_macIE ) $text = preg_replace_callback("/\%u([0-9A-F]{4,4})/", "funky_javascript_callback", $text); return $text; } /** * Checks that the taxonomy name exists. * * @since 2.3.0 * @deprecated 3.0.0 * @deprecated Use taxonomy_exists() * @see taxonomy_exists() * * @param string $taxonomy Name of taxonomy object * @return bool Whether the taxonomy exists. */ function is_taxonomy( $taxonomy ) { _deprecated_function( __FUNCTION__, '3.0', 'taxonomy_exists()' ); return taxonomy_exists( $taxonomy ); } /** * Check if Term exists. * * @since 2.3.0 * @deprecated 3.0.0 * @deprecated Use term_exists() * @see term_exists() * * @param int|string $term The term to check * @param string $taxonomy The taxonomy name to use * @param int $parent ID of parent term under which to confine the exists search. * @return mixed Get the term id or Term Object, if exists. */ function is_term( $term, $taxonomy = '', $parent = 0 ) { _deprecated_function( __FUNCTION__, '3.0', 'term_exists()' ); return term_exists( $term, $taxonomy, $parent ); } /** * Is the current admin page generated by a plugin? * * @since 1.5.0 * @deprecated 3.1.0 * @deprecated Use global $plugin_page and/or get_plugin_page_hookname() hooks. * * @global $plugin_page * * @return bool */ function is_plugin_page() { _deprecated_function( __FUNCTION__, '3.1' ); global $plugin_page; if ( isset($plugin_page) ) return true; return false; } /** * Update the categories cache. * * This function does not appear to be used anymore or does not appear to be * needed. It might be a legacy function left over from when there was a need * for updating the category cache. * * @since 1.5.0 * @deprecated 3.1.0 * * @return bool Always return True */ function update_category_cache() { _deprecated_function( __FUNCTION__, '3.1' ); return true; } /** * Check for PHP timezone support * * @since 2.9.0 * @deprecated 3.2.0 * * @return bool */ function wp_timezone_supported() { _deprecated_function( __FUNCTION__, '3.2' ); return true; } /** * Display editor: TinyMCE, HTML, or both. * * @since 2.1.0 * @deprecated 3.3.0 * @deprecated Use wp_editor() * @see wp_editor() * * @param string $content Textarea content. * @param string $id Optional, default is 'content'. HTML ID attribute value. * @param string $prev_id Optional, not used * @param bool $media_buttons Optional, default is true. Whether to display media buttons. * @param int $tab_index Optional, not used */ function the_editor($content, $id = 'content', $prev_id = 'title', $media_buttons = true, $tab_index = 2, $extended = true) { _deprecated_function( __FUNCTION__, '3.3', 'wp_editor()' ); wp_editor( $content, $id, array( 'media_buttons' => $media_buttons ) ); return; } /** * Perform the query to get the $metavalues array(s) needed by _fill_user and _fill_many_users * * @since 3.0.0 * @deprecated 3.3.0 * * @param array $ids User ID numbers list. * @return array of arrays. The array is indexed by user_id, containing $metavalues object arrays. */ function get_user_metavalues($ids) { _deprecated_function( __FUNCTION__, '3.3' ); $objects = array(); $ids = array_map('intval', $ids); foreach ( $ids as $id ) $objects[$id] = array(); $metas = update_meta_cache('user', $ids); foreach ( $metas as $id => $meta ) { foreach ( $meta as $key => $metavalues ) { foreach ( $metavalues as $value ) { $objects[$id][] = (object)array( 'user_id' => $id, 'meta_key' => $key, 'meta_value' => $value); } } } return $objects; } /** * Sanitize every user field. * * If the context is 'raw', then the user object or array will get minimal santization of the int fields. * * @since 2.3.0 * @deprecated 3.3.0 * * @param object|array $user The User Object or Array * @param string $context Optional, default is 'display'. How to sanitize user fields. * @return object|array The now sanitized User Object or Array (will be the same type as $user) */ function sanitize_user_object($user, $context = 'display') { _deprecated_function( __FUNCTION__, '3.3' ); if ( is_object($user) ) { if ( !isset($user->ID) ) $user->ID = 0; if ( !is_a( $user, 'WP_User' ) ) { $vars = get_object_vars($user); foreach ( array_keys($vars) as $field ) { if ( is_string($user->$field) || is_numeric($user->$field) ) $user->$field = sanitize_user_field($field, $user->$field, $user->ID, $context); } } $user->filter = $context; } else { if ( !isset($user['ID']) ) $user['ID'] = 0; foreach ( array_keys($user) as $field ) $user[$field] = sanitize_user_field($field, $user[$field], $user['ID'], $context); $user['filter'] = $context; } return $user; } /** * Get boundary post relational link. * * Can either be start or end post relational link. * * @since 2.8.0 * @deprecated 3.3.0 * * @param string $title Optional. Link title format. * @param bool $in_same_cat Optional. Whether link should be in a same category. * @param string $excluded_categories Optional. Excluded categories IDs. * @param bool $start Optional, default is true. Whether to display link to first or last post. * @return string */ function get_boundary_post_rel_link($title = '%title', $in_same_cat = false, $excluded_categories = '', $start = true) { _deprecated_function( __FUNCTION__, '3.3' ); $posts = get_boundary_post($in_same_cat, $excluded_categories, $start); // If there is no post stop. if ( empty($posts) ) return; // Even though we limited get_posts to return only 1 item it still returns an array of objects. $post = $posts[0]; if ( empty($post->post_title) ) $post->post_title = $start ? __('First Post') : __('Last Post'); $date = mysql2date(get_option('date_format'), $post->post_date); $title = str_replace('%title', $post->post_title, $title); $title = str_replace('%date', $date, $title); $title = apply_filters('the_title', $title, $post->ID); $link = $start ? "<link rel='start' title='" : "<link rel='end' title='"; $link .= esc_attr($title); $link .= "' href='" . get_permalink($post) . "' />\n"; $boundary = $start ? 'start' : 'end'; return apply_filters( "{$boundary}_post_rel_link", $link ); } /** * Display relational link for the first post. * * @since 2.8.0 * @deprecated 3.3.0 * * @param string $title Optional. Link title format. * @param bool $in_same_cat Optional. Whether link should be in a same category. * @param string $excluded_categories Optional. Excluded categories IDs. */ function start_post_rel_link($title = '%title', $in_same_cat = false, $excluded_categories = '') { _deprecated_function( __FUNCTION__, '3.3' ); echo get_boundary_post_rel_link($title, $in_same_cat, $excluded_categories, true); } /** * Get site index relational link. * * @since 2.8.0 * @deprecated 3.3.0 * * @return string */ function get_index_rel_link() { _deprecated_function( __FUNCTION__, '3.3' ); $link = "<link rel='index' title='" . esc_attr( get_bloginfo( 'name', 'display' ) ) . "' href='" . esc_url( user_trailingslashit( get_bloginfo( 'url', 'display' ) ) ) . "' />\n"; return apply_filters( "index_rel_link", $link ); } /** * Display relational link for the site index. * * @since 2.8.0 * @deprecated 3.3.0 */ function index_rel_link() { _deprecated_function( __FUNCTION__, '3.3' ); echo get_index_rel_link(); } /** * Get parent post relational link. * * @since 2.8.0 * @deprecated 3.3.0 * * @param string $title Optional. Link title format. * @return string */ function get_parent_post_rel_link($title = '%title') { _deprecated_function( __FUNCTION__, '3.3' ); if ( ! empty( $GLOBALS['post'] ) && ! empty( $GLOBALS['post']->post_parent ) ) $post = get_post($GLOBALS['post']->post_parent); if ( empty($post) ) return; $date = mysql2date(get_option('date_format'), $post->post_date); $title = str_replace('%title', $post->post_title, $title); $title = str_replace('%date', $date, $title); $title = apply_filters('the_title', $title, $post->ID); $link = "<link rel='up' title='"; $link .= esc_attr( $title ); $link .= "' href='" . get_permalink($post) . "' />\n"; return apply_filters( "parent_post_rel_link", $link ); } /** * Display relational link for parent item * * @since 2.8.0 * @deprecated 3.3.0 */ function parent_post_rel_link($title = '%title') { _deprecated_function( __FUNCTION__, '3.3' ); echo get_parent_post_rel_link($title); } /** * Add the "Dashboard"/"Visit Site" menu. * * @since 3.2.0 * @deprecated 3.3.0 */ function wp_admin_bar_dashboard_view_site_menu( $wp_admin_bar ) { _deprecated_function( __FUNCTION__, '3.3' ); $user_id = get_current_user_id(); if ( 0 != $user_id ) { if ( is_admin() ) $wp_admin_bar->add_menu( array( 'id' => 'view-site', 'title' => __( 'Visit Site' ), 'href' => home_url() ) ); elseif ( is_multisite() ) $wp_admin_bar->add_menu( array( 'id' => 'dashboard', 'title' => __( 'Dashboard' ), 'href' => get_dashboard_url( $user_id ) ) ); else $wp_admin_bar->add_menu( array( 'id' => 'dashboard', 'title' => __( 'Dashboard' ), 'href' => admin_url() ) ); } } /** * Checks if the current user belong to a given blog. * * @since MU * @deprecated 3.3.0 * @deprecated Use is_user_member_of_blog() * @see is_user_member_of_blog() * * @param int $blog_id Blog ID * @return bool True if the current users belong to $blog_id, false if not. */ function is_blog_user( $blog_id = 0 ) { _deprecated_function( __FUNCTION__, '3.3', 'is_user_member_of_blog()' ); return is_user_member_of_blog( get_current_user_id(), $blog_id ); } /** * Open the file handle for debugging. * * @since 0.71 * @deprecated Use error_log() * @link http://www.php.net/manual/en/function.error-log.php * @deprecated 3.4.0 */ function debug_fopen( $filename, $mode ) { _deprecated_function( __FUNCTION__, 'error_log()' ); return false; } /** * Write contents to the file used for debugging. * * @since 0.71 * @deprecated Use error_log() instead. * @link http://www.php.net/manual/en/function.error-log.php * @deprecated 3.4.0 */ function debug_fwrite( $fp, $string ) { _deprecated_function( __FUNCTION__, 'error_log()' ); if ( ! empty( $GLOBALS['debug'] ) ) error_log( $string ); } /** * Close the debugging file handle. * * @since 0.71 * @deprecated Use error_log() * @link http://www.php.net/manual/en/function.error-log.php * @deprecated 3.4.0 */ function debug_fclose( $fp ) { _deprecated_function( __FUNCTION__, 'error_log()' ); } /** * Retrieve list of themes with theme data in theme directory. * * The theme is broken, if it doesn't have a parent theme and is missing either * style.css and, or index.php. If the theme has a parent theme then it is * broken, if it is missing style.css; index.php is optional. * * @since 1.5.0 * @deprecated 3.4.0 * @deprecated Use wp_get_themes() * @see wp_get_themes() * * @return array Theme list with theme data. */ function get_themes() { _deprecated_function( __FUNCTION__, '3.4', 'wp_get_themes()' ); global $wp_themes; if ( isset( $wp_themes ) ) return $wp_themes; $themes = wp_get_themes(); $wp_themes = array(); foreach ( $themes as $theme ) { $name = $theme->get('Name'); if ( isset( $wp_themes[ $name ] ) ) $wp_themes[ $name . '/' . $theme->get_stylesheet() ] = $theme; else $wp_themes[ $name ] = $theme; } return $wp_themes; } /** * Retrieve theme data. * * @since 1.5.0 * @deprecated 3.4.0 * @deprecated Use wp_get_theme() * @see wp_get_theme() * * @param string $theme Theme name. * @return array|null Null, if theme name does not exist. Theme data, if exists. */ function get_theme( $theme ) { _deprecated_function( __FUNCTION__, '3.4', 'wp_get_theme( $stylesheet )' ); $themes = get_themes(); if ( is_array( $themes ) && array_key_exists( $theme, $themes ) ) return $themes[ $theme ]; return null; } /** * Retrieve current theme name. * * @since 1.5.0 * @deprecated 3.4.0 * @deprecated Use (string) wp_get_theme() * @see wp_get_theme() * * @return string */ function get_current_theme() { _deprecated_function( __FUNCTION__, '3.4', 'wp_get_theme()' ); if ( $theme = get_option( 'current_theme' ) ) return $theme; return wp_get_theme()->get('Name'); } /** * Accepts matches array from preg_replace_callback in wpautop() or a string. * * Ensures that the contents of a <<pre>>...<</pre>> HTML block are not * converted into paragraphs or line-breaks. * * @since 1.2.0 * @deprecated 3.4.0 * * @param array|string $matches The array or string * @return string The pre block without paragraph/line-break conversion. */ function clean_pre($matches) { _deprecated_function( __FUNCTION__, '3.4' ); if ( is_array($matches) ) $text = $matches[1] . $matches[2] . "</pre>"; else $text = $matches; $text = str_replace(array('<br />', '<br/>', '<br>'), array('', '', ''), $text); $text = str_replace('<p>', "\n", $text); $text = str_replace('</p>', '', $text); return $text; } /** * Add callbacks for image header display. * * @since 2.1.0 * @deprecated 3.4.0 * @deprecated Use add_theme_support('custom-header', $args) * @see add_theme_support() * * @param callback $wp_head_callback Call on 'wp_head' action. * @param callback $admin_head_callback Call on custom header administration screen. * @param callback $admin_preview_callback Output a custom header image div on the custom header administration screen. Optional. */ function add_custom_image_header( $wp_head_callback, $admin_head_callback, $admin_preview_callback = '' ) { _deprecated_function( __FUNCTION__, '3.4', 'add_theme_support( \'custom-header\', $args )' ); $args = array( 'wp-head-callback' => $wp_head_callback, 'admin-head-callback' => $admin_head_callback, ); if ( $admin_preview_callback ) $args['admin-preview-callback'] = $admin_preview_callback; return add_theme_support( 'custom-header', $args ); } /** * Remove image header support. * * @since 3.1.0 * @deprecated 3.4.0 * @deprecated Use remove_theme_support('custom-header') * @see remove_theme_support() * * @return bool Whether support was removed. */ function remove_custom_image_header() { _deprecated_function( __FUNCTION__, '3.4', 'remove_theme_support( \'custom-header\' )' ); return remove_theme_support( 'custom-header' ); } /** * Add callbacks for background image display. * * @since 3.0.0 * @deprecated 3.4.0 * @deprecated Use add_theme_support('custom-background, $args) * @see add_theme_support() * * @param callback $wp_head_callback Call on 'wp_head' action. * @param callback $admin_head_callback Call on custom background administration screen. * @param callback $admin_preview_callback Output a custom background image div on the custom background administration screen. Optional. */ function add_custom_background( $wp_head_callback = '', $admin_head_callback = '', $admin_preview_callback = '' ) { _deprecated_function( __FUNCTION__, '3.4', 'add_theme_support( \'custom-background\', $args )' ); $args = array(); if ( $wp_head_callback ) $args['wp-head-callback'] = $wp_head_callback; if ( $admin_head_callback ) $args['admin-head-callback'] = $admin_head_callback; if ( $admin_preview_callback ) $args['admin-preview-callback'] = $admin_preview_callback; return add_theme_support( 'custom-background', $args ); } /** * Remove custom background support. * * @since 3.1.0 * @see add_custom_background() * * @return bool Whether support was removed. */ function remove_custom_background() { _deprecated_function( __FUNCTION__, '3.4', 'remove_theme_support( \'custom-background\' )' ); return remove_theme_support( 'custom-background' ); } /** * Retrieve theme data from parsed theme file. * * @since 1.5.0 * @deprecated 3.4.0 * @deprecated Use wp_get_theme() * @see wp_get_theme() * * @param string $theme_file Theme file path. * @return array Theme data. */ function get_theme_data( $theme_file ) { _deprecated_function( __FUNCTION__, '3.4', 'wp_get_theme()' ); $theme = new WP_Theme( basename( dirname( $theme_file ) ), dirname( dirname( $theme_file ) ) ); $theme_data = array( 'Name' => $theme->get('Name'), 'URI' => $theme->display('ThemeURI', true, false), 'Description' => $theme->display('Description', true, false), 'Author' => $theme->display('Author', true, false), 'AuthorURI' => $theme->display('AuthorURI', true, false), 'Version' => $theme->get('Version'), 'Template' => $theme->get('Template'), 'Status' => $theme->get('Status'), 'Tags' => $theme->get('Tags'), 'Title' => $theme->get('Name'), 'AuthorName' => $theme->get('Author'), ); foreach ( apply_filters( 'extra_theme_headers', array() ) as $extra_header ) { if ( ! isset( $theme_data[ $extra_header ] ) ) $theme_data[ $extra_header ] = $theme->get( $extra_header ); } return $theme_data; } /** * Alias of update_post_cache(). * * @see update_post_cache() Posts and pages are the same, alias is intentional * * @since 1.5.1 * @deprecated 3.4.0 * * @param array $pages list of page objects */ function update_page_cache( &$pages ) { _deprecated_function( __FUNCTION__, '3.4', 'update_post_cache()' ); update_post_cache( $pages ); } /** * Will clean the page in the cache. * * Clean (read: delete) page from cache that matches $id. Will also clean cache * associated with 'all_page_ids' and 'get_pages'. * * @since 2.0.0 * @deprecated 3.4.0 * * @uses do_action() Will call the 'clean_page_cache' hook action. * * @param int $id Page ID to clean */ function clean_page_cache( $id ) { _deprecated_function( __FUNCTION__, '3.4', 'clean_post_cache()' ); clean_post_cache( $id ); } /** * Retrieve nonce action "Are you sure" message. * * Deprecated in 3.4.1 and 3.5.0. Backported to 3.3.3. * * @since 2.0.4 * @deprecated 3.4.1 * @deprecated Use wp_nonce_ays() * @see wp_nonce_ays() * * @param string $action Nonce action. * @return string Are you sure message. */ function wp_explain_nonce( $action ) { _deprecated_function( __FUNCTION__, '3.4.1', 'wp_nonce_ays()' ); return __( 'Are you sure you want to do this?' ); } /** * Display "sticky" CSS class, if a post is sticky. * * @since 2.7.0 * @deprecated 3.5.0 * @deprecated Use post_class() * @see post_class() * * @param int $post_id An optional post ID. */ function sticky_class( $post_id = null ) { _deprecated_function( __FUNCTION__, '3.5', 'post_class()' ); if ( is_sticky( $post_id ) ) echo ' sticky'; } /** * Retrieve post ancestors. * * This is no longer needed as WP_Post lazy-loads the ancestors * property with get_post_ancestors(). * * @since 2.3.4 * @deprecated 3.5.0 * @see get_post_ancestors() */ function _get_post_ancestors( &$post ) { _deprecated_function( __FUNCTION__, '3.5' ); } /** * Load an image from a string, if PHP supports it. * * @since 2.1.0 * @deprecated 3.5.0 * @see wp_get_image_editor() * * @param string $file Filename of the image to load. * @return resource The resulting image resource on success, Error string on failure. */ function wp_load_image( $file ) { _deprecated_function( __FUNCTION__, '3.5', 'wp_get_image_editor()' ); if ( is_numeric( $file ) ) $file = get_attached_file( $file ); if ( ! is_file( $file ) ) return sprintf(__('File &#8220;%s&#8221; doesn&#8217;t exist?'), $file); if ( ! function_exists('imagecreatefromstring') ) return __('The GD image library is not installed.'); // Set artificially high because GD uses uncompressed images in memory @ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) ); $image = imagecreatefromstring( file_get_contents( $file ) ); if ( !is_resource( $image ) ) return sprintf(__('File &#8220;%s&#8221; is not an image.'), $file); return $image; } /** * Scale down an image to fit a particular size and save a new copy of the image. * * The PNG transparency will be preserved using the function, as well as the * image type. If the file going in is PNG, then the resized image is going to * be PNG. The only supported image types are PNG, GIF, and JPEG. * * Some functionality requires API to exist, so some PHP version may lose out * support. This is not the fault of WordPress (where functionality is * downgraded, not actual defects), but of your PHP version. * * @since 2.5.0 * @deprecated 3.5.0 * @see wp_get_image_editor() * * @param string $file Image file path. * @param int $max_w Maximum width to resize to. * @param int $max_h Maximum height to resize to. * @param bool $crop Optional. Whether to crop image or resize. * @param string $suffix Optional. File suffix. * @param string $dest_path Optional. New image file path. * @param int $jpeg_quality Optional, default is 90. Image quality percentage. * @return mixed WP_Error on failure. String with new destination path. */ function image_resize( $file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90 ) { _deprecated_function( __FUNCTION__, '3.5', 'wp_get_image_editor()' ); $editor = wp_get_image_editor( $file ); if ( is_wp_error( $editor ) ) return $editor; $editor->set_quality( $jpeg_quality ); $resized = $editor->resize( $max_w, $max_h, $crop ); if ( is_wp_error( $resized ) ) return $resized; $dest_file = $editor->generate_filename( $suffix, $dest_path ); $saved = $editor->save( $dest_file ); if ( is_wp_error( $saved ) ) return $saved; return $dest_file; } /** * Retrieve a single post, based on post ID. * * Has categories in 'post_category' property or key. Has tags in 'tags_input' * property or key. * * @since 1.0.0 * @deprecated 3.5.0 * @see get_post() * * @param int $postid Post ID. * @param string $mode How to return result, either OBJECT, ARRAY_N, or ARRAY_A. * @return object|array Post object or array holding post contents and information */ function wp_get_single_post( $postid = 0, $mode = OBJECT ) { _deprecated_function( __FUNCTION__, '3.5', 'get_post()' ); return get_post( $postid, $mode, 'edit' ); } /** * Check that the user login name and password is correct. * * @since 0.71 * @deprecated 3.5.0 * @deprecated Use wp_authenticate() * @see wp_authenticate() * * @param string $user_login User name. * @param string $user_pass User password. * @return bool False if does not authenticate, true if username and password authenticates. */ function user_pass_ok($user_login, $user_pass) { _deprecated_function( __FUNCTION__, '3.5', 'wp_authenticate()' ); $user = wp_authenticate( $user_login, $user_pass ); if ( is_wp_error( $user ) ) return false; return true; } /** * Callback formerly fired on the save_post hook. No longer needed. * * @since 2.3.0 * @deprecated 3.5.0 */ function _save_post_hook() {} /** * Check if the installed version of GD supports particular image type * * @since 2.9.0 * @deprecated 3.5.0 * see wp_image_editor_supports() * * @param string $mime_type * @return bool */ function gd_edit_image_support($mime_type) { _deprecated_function( __FUNCTION__, '3.5', 'wp_image_editor_supports()' ); if ( function_exists('imagetypes') ) { switch( $mime_type ) { case 'image/jpeg': return (imagetypes() & IMG_JPG) != 0; case 'image/png': return (imagetypes() & IMG_PNG) != 0; case 'image/gif': return (imagetypes() & IMG_GIF) != 0; } } else { switch( $mime_type ) { case 'image/jpeg': return function_exists('imagecreatefromjpeg'); case 'image/png': return function_exists('imagecreatefrompng'); case 'image/gif': return function_exists('imagecreatefromgif'); } } return false; }
zyblog
trunk/zyblog/wp-includes/deprecated.php
PHP
asf20
96,384
<?php /** * MagpieRSS: a simple RSS integration tool * * A compiled file for RSS syndication * * @author Kellan Elliott-McCrea <kellan@protest.net> * @version 0.51 * @license GPL * * @package External * @subpackage MagpieRSS */ /** * Deprecated. Use SimplePie (class-simplepie.php) instead. */ _deprecated_file( basename( __FILE__ ), '3.0', WPINC . '/class-simplepie.php' ); /* * Hook to use another RSS object instead of MagpieRSS */ do_action('load_feed_engine'); /** RSS feed constant. */ define('RSS', 'RSS'); define('ATOM', 'Atom'); define('MAGPIE_USER_AGENT', 'WordPress/' . $GLOBALS['wp_version']); class MagpieRSS { var $parser; var $current_item = array(); // item currently being parsed var $items = array(); // collection of parsed items var $channel = array(); // hash of channel fields var $textinput = array(); var $image = array(); var $feed_type; var $feed_version; // parser variables var $stack = array(); // parser stack var $inchannel = false; var $initem = false; var $incontent = false; // if in Atom <content mode="xml"> field var $intextinput = false; var $inimage = false; var $current_field = ''; var $current_namespace = false; //var $ERROR = ""; var $_CONTENT_CONSTRUCTS = array('content', 'summary', 'info', 'title', 'tagline', 'copyright'); function MagpieRSS ($source) { # if PHP xml isn't compiled in, die # if ( !function_exists('xml_parser_create') ) trigger_error( "Failed to load PHP's XML Extension. http://www.php.net/manual/en/ref.xml.php" ); $parser = @xml_parser_create(); if ( !is_resource($parser) ) trigger_error( "Failed to create an instance of PHP's XML parser. http://www.php.net/manual/en/ref.xml.php"); $this->parser = $parser; # pass in parser, and a reference to this object # set up handlers # xml_set_object( $this->parser, $this ); xml_set_element_handler($this->parser, 'feed_start_element', 'feed_end_element' ); xml_set_character_data_handler( $this->parser, 'feed_cdata' ); $status = xml_parse( $this->parser, $source ); if (! $status ) { $errorcode = xml_get_error_code( $this->parser ); if ( $errorcode != XML_ERROR_NONE ) { $xml_error = xml_error_string( $errorcode ); $error_line = xml_get_current_line_number($this->parser); $error_col = xml_get_current_column_number($this->parser); $errormsg = "$xml_error at line $error_line, column $error_col"; $this->error( $errormsg ); } } xml_parser_free( $this->parser ); $this->normalize(); } function feed_start_element($p, $element, &$attrs) { $el = $element = strtolower($element); $attrs = array_change_key_case($attrs, CASE_LOWER); // check for a namespace, and split if found $ns = false; if ( strpos( $element, ':' ) ) { list($ns, $el) = split( ':', $element, 2); } if ( $ns and $ns != 'rdf' ) { $this->current_namespace = $ns; } # if feed type isn't set, then this is first element of feed # identify feed from root element # if (!isset($this->feed_type) ) { if ( $el == 'rdf' ) { $this->feed_type = RSS; $this->feed_version = '1.0'; } elseif ( $el == 'rss' ) { $this->feed_type = RSS; $this->feed_version = $attrs['version']; } elseif ( $el == 'feed' ) { $this->feed_type = ATOM; $this->feed_version = $attrs['version']; $this->inchannel = true; } return; } if ( $el == 'channel' ) { $this->inchannel = true; } elseif ($el == 'item' or $el == 'entry' ) { $this->initem = true; if ( isset($attrs['rdf:about']) ) { $this->current_item['about'] = $attrs['rdf:about']; } } // if we're in the default namespace of an RSS feed, // record textinput or image fields elseif ( $this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' ) { $this->intextinput = true; } elseif ( $this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' ) { $this->inimage = true; } # handle atom content constructs elseif ( $this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) ) { // avoid clashing w/ RSS mod_content if ($el == 'content' ) { $el = 'atom_content'; } $this->incontent = $el; } // if inside an Atom content construct (e.g. content or summary) field treat tags as text elseif ($this->feed_type == ATOM and $this->incontent ) { // if tags are inlined, then flatten $attrs_str = join(' ', array_map(array('MagpieRSS', 'map_attrs'), array_keys($attrs), array_values($attrs) ) ); $this->append_content( "<$element $attrs_str>" ); array_unshift( $this->stack, $el ); } // Atom support many links per containging element. // Magpie treats link elements of type rel='alternate' // as being equivalent to RSS's simple link element. // elseif ($this->feed_type == ATOM and $el == 'link' ) { if ( isset($attrs['rel']) and $attrs['rel'] == 'alternate' ) { $link_el = 'link'; } else { $link_el = 'link_' . $attrs['rel']; } $this->append($link_el, $attrs['href']); } // set stack[0] to current element else { array_unshift($this->stack, $el); } } function feed_cdata ($p, $text) { if ($this->feed_type == ATOM and $this->incontent) { $this->append_content( $text ); } else { $current_el = join('_', array_reverse($this->stack)); $this->append($current_el, $text); } } function feed_end_element ($p, $el) { $el = strtolower($el); if ( $el == 'item' or $el == 'entry' ) { $this->items[] = $this->current_item; $this->current_item = array(); $this->initem = false; } elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'textinput' ) { $this->intextinput = false; } elseif ($this->feed_type == RSS and $this->current_namespace == '' and $el == 'image' ) { $this->inimage = false; } elseif ($this->feed_type == ATOM and in_array($el, $this->_CONTENT_CONSTRUCTS) ) { $this->incontent = false; } elseif ($el == 'channel' or $el == 'feed' ) { $this->inchannel = false; } elseif ($this->feed_type == ATOM and $this->incontent ) { // balance tags properly // note: i don't think this is actually neccessary if ( $this->stack[0] == $el ) { $this->append_content("</$el>"); } else { $this->append_content("<$el />"); } array_shift( $this->stack ); } else { array_shift( $this->stack ); } $this->current_namespace = false; } function concat (&$str1, $str2="") { if (!isset($str1) ) { $str1=""; } $str1 .= $str2; } function append_content($text) { if ( $this->initem ) { $this->concat( $this->current_item[ $this->incontent ], $text ); } elseif ( $this->inchannel ) { $this->concat( $this->channel[ $this->incontent ], $text ); } } // smart append - field and namespace aware function append($el, $text) { if (!$el) { return; } if ( $this->current_namespace ) { if ( $this->initem ) { $this->concat( $this->current_item[ $this->current_namespace ][ $el ], $text); } elseif ($this->inchannel) { $this->concat( $this->channel[ $this->current_namespace][ $el ], $text ); } elseif ($this->intextinput) { $this->concat( $this->textinput[ $this->current_namespace][ $el ], $text ); } elseif ($this->inimage) { $this->concat( $this->image[ $this->current_namespace ][ $el ], $text ); } } else { if ( $this->initem ) { $this->concat( $this->current_item[ $el ], $text); } elseif ($this->intextinput) { $this->concat( $this->textinput[ $el ], $text ); } elseif ($this->inimage) { $this->concat( $this->image[ $el ], $text ); } elseif ($this->inchannel) { $this->concat( $this->channel[ $el ], $text ); } } } function normalize () { // if atom populate rss fields if ( $this->is_atom() ) { $this->channel['descripton'] = $this->channel['tagline']; for ( $i = 0; $i < count($this->items); $i++) { $item = $this->items[$i]; if ( isset($item['summary']) ) $item['description'] = $item['summary']; if ( isset($item['atom_content'])) $item['content']['encoded'] = $item['atom_content']; $this->items[$i] = $item; } } elseif ( $this->is_rss() ) { $this->channel['tagline'] = $this->channel['description']; for ( $i = 0; $i < count($this->items); $i++) { $item = $this->items[$i]; if ( isset($item['description'])) $item['summary'] = $item['description']; if ( isset($item['content']['encoded'] ) ) $item['atom_content'] = $item['content']['encoded']; $this->items[$i] = $item; } } } function is_rss () { if ( $this->feed_type == RSS ) { return $this->feed_version; } else { return false; } } function is_atom() { if ( $this->feed_type == ATOM ) { return $this->feed_version; } else { return false; } } function map_attrs($k, $v) { return "$k=\"$v\""; } function error( $errormsg, $lvl = E_USER_WARNING ) { // append PHP's error message if track_errors enabled if ( isset($php_errormsg) ) { $errormsg .= " ($php_errormsg)"; } if ( MAGPIE_DEBUG ) { trigger_error( $errormsg, $lvl); } else { error_log( $errormsg, 0); } } } if ( !function_exists('fetch_rss') ) : /** * Build Magpie object based on RSS from URL. * * @since 1.5.0 * @package External * @subpackage MagpieRSS * * @param string $url URL to retrieve feed * @return bool|MagpieRSS false on failure or MagpieRSS object on success. */ function fetch_rss ($url) { // initialize constants init(); if ( !isset($url) ) { // error("fetch_rss called without a url"); return false; } // if cache is disabled if ( !MAGPIE_CACHE_ON ) { // fetch file, and parse it $resp = _fetch_remote_file( $url ); if ( is_success( $resp->status ) ) { return _response_to_rss( $resp ); } else { // error("Failed to fetch $url and cache is off"); return false; } } // else cache is ON else { // Flow // 1. check cache // 2. if there is a hit, make sure its fresh // 3. if cached obj fails freshness check, fetch remote // 4. if remote fails, return stale object, or error $cache = new RSSCache( MAGPIE_CACHE_DIR, MAGPIE_CACHE_AGE ); if (MAGPIE_DEBUG and $cache->ERROR) { debug($cache->ERROR, E_USER_WARNING); } $cache_status = 0; // response of check_cache $request_headers = array(); // HTTP headers to send with fetch $rss = 0; // parsed RSS object $errormsg = 0; // errors, if any if (!$cache->ERROR) { // return cache HIT, MISS, or STALE $cache_status = $cache->check_cache( $url ); } // if object cached, and cache is fresh, return cached obj if ( $cache_status == 'HIT' ) { $rss = $cache->get( $url ); if ( isset($rss) and $rss ) { $rss->from_cache = 1; if ( MAGPIE_DEBUG > 1) { debug("MagpieRSS: Cache HIT", E_USER_NOTICE); } return $rss; } } // else attempt a conditional get // set up headers if ( $cache_status == 'STALE' ) { $rss = $cache->get( $url ); if ( isset($rss->etag) and $rss->last_modified ) { $request_headers['If-None-Match'] = $rss->etag; $request_headers['If-Last-Modified'] = $rss->last_modified; } } $resp = _fetch_remote_file( $url, $request_headers ); if (isset($resp) and $resp) { if ($resp->status == '304' ) { // we have the most current copy if ( MAGPIE_DEBUG > 1) { debug("Got 304 for $url"); } // reset cache on 304 (at minutillo insistent prodding) $cache->set($url, $rss); return $rss; } elseif ( is_success( $resp->status ) ) { $rss = _response_to_rss( $resp ); if ( $rss ) { if (MAGPIE_DEBUG > 1) { debug("Fetch successful"); } // add object to cache $cache->set( $url, $rss ); return $rss; } } else { $errormsg = "Failed to fetch $url. "; if ( $resp->error ) { # compensate for Snoopy's annoying habbit to tacking # on '\n' $http_error = substr($resp->error, 0, -2); $errormsg .= "(HTTP Error: $http_error)"; } else { $errormsg .= "(HTTP Response: " . $resp->response_code .')'; } } } else { $errormsg = "Unable to retrieve RSS file for unknown reasons."; } // else fetch failed // attempt to return cached object if ($rss) { if ( MAGPIE_DEBUG ) { debug("Returning STALE object for $url"); } return $rss; } // else we totally failed // error( $errormsg ); return false; } // end if ( !MAGPIE_CACHE_ON ) { } // end fetch_rss() endif; /** * Retrieve URL headers and content using WP HTTP Request API. * * @since 1.5.0 * @package External * @subpackage MagpieRSS * * @param string $url URL to retrieve * @param array $headers Optional. Headers to send to the URL. * @return Snoopy style response */ function _fetch_remote_file($url, $headers = "" ) { $resp = wp_remote_request($url, array('headers' => $headers, 'timeout' => MAGPIE_FETCH_TIME_OUT)); if ( is_wp_error($resp) ) { $error = array_shift($resp->errors); $resp = new stdClass; $resp->status = 500; $resp->response_code = 500; $resp->error = $error[0] . "\n"; //\n = Snoopy compatibility return $resp; } // Snoopy returns headers unprocessed. // Also note, WP_HTTP lowercases all keys, Snoopy did not. $return_headers = array(); foreach ( wp_remote_retrieve_headers( $resp ) as $key => $value ) { if ( !is_array($value) ) { $return_headers[] = "$key: $value"; } else { foreach ( $value as $v ) $return_headers[] = "$key: $v"; } } $response = new stdClass; $response->status = wp_remote_retrieve_response_code( $resp ); $response->response_code = wp_remote_retrieve_response_code( $resp ); $response->headers = $return_headers; $response->results = wp_remote_retrieve_body( $resp ); return $response; } /** * Retrieve * * @since 1.5.0 * @package External * @subpackage MagpieRSS * * @param unknown_type $resp * @return unknown */ function _response_to_rss ($resp) { $rss = new MagpieRSS( $resp->results ); // if RSS parsed successfully if ( $rss && (!isset($rss->ERROR) || !$rss->ERROR) ) { // find Etag, and Last-Modified foreach( (array) $resp->headers as $h) { // 2003-03-02 - Nicola Asuni (www.tecnick.com) - fixed bug "Undefined offset: 1" if (strpos($h, ": ")) { list($field, $val) = explode(": ", $h, 2); } else { $field = $h; $val = ""; } if ( $field == 'etag' ) { $rss->etag = $val; } if ( $field == 'last-modified' ) { $rss->last_modified = $val; } } return $rss; } // else construct error message else { $errormsg = "Failed to parse RSS file."; if ($rss) { $errormsg .= " (" . $rss->ERROR . ")"; } // error($errormsg); return false; } // end if ($rss and !$rss->error) } /** * Set up constants with default values, unless user overrides. * * @since 1.5.0 * @package External * @subpackage MagpieRSS */ function init () { if ( defined('MAGPIE_INITALIZED') ) { return; } else { define('MAGPIE_INITALIZED', 1); } if ( !defined('MAGPIE_CACHE_ON') ) { define('MAGPIE_CACHE_ON', 1); } if ( !defined('MAGPIE_CACHE_DIR') ) { define('MAGPIE_CACHE_DIR', './cache'); } if ( !defined('MAGPIE_CACHE_AGE') ) { define('MAGPIE_CACHE_AGE', 60*60); // one hour } if ( !defined('MAGPIE_CACHE_FRESH_ONLY') ) { define('MAGPIE_CACHE_FRESH_ONLY', 0); } if ( !defined('MAGPIE_DEBUG') ) { define('MAGPIE_DEBUG', 0); } if ( !defined('MAGPIE_USER_AGENT') ) { $ua = 'WordPress/' . $GLOBALS['wp_version']; if ( MAGPIE_CACHE_ON ) { $ua = $ua . ')'; } else { $ua = $ua . '; No cache)'; } define('MAGPIE_USER_AGENT', $ua); } if ( !defined('MAGPIE_FETCH_TIME_OUT') ) { define('MAGPIE_FETCH_TIME_OUT', 2); // 2 second timeout } // use gzip encoding to fetch rss files if supported? if ( !defined('MAGPIE_USE_GZIP') ) { define('MAGPIE_USE_GZIP', true); } } function is_info ($sc) { return $sc >= 100 && $sc < 200; } function is_success ($sc) { return $sc >= 200 && $sc < 300; } function is_redirect ($sc) { return $sc >= 300 && $sc < 400; } function is_error ($sc) { return $sc >= 400 && $sc < 600; } function is_client_error ($sc) { return $sc >= 400 && $sc < 500; } function is_server_error ($sc) { return $sc >= 500 && $sc < 600; } class RSSCache { var $BASE_CACHE; // where the cache files are stored var $MAX_AGE = 43200; // when are files stale, default twelve hours var $ERROR = ''; // accumulate error messages function RSSCache ($base='', $age='') { $this->BASE_CACHE = WP_CONTENT_DIR . '/cache'; if ( $base ) { $this->BASE_CACHE = $base; } if ( $age ) { $this->MAX_AGE = $age; } } /*=======================================================================*\ Function: set Purpose: add an item to the cache, keyed on url Input: url from wich the rss file was fetched Output: true on sucess \*=======================================================================*/ function set ($url, $rss) { $cache_option = 'rss_' . $this->file_name( $url ); set_transient($cache_option, $rss, $this->MAX_AGE); return $cache_option; } /*=======================================================================*\ Function: get Purpose: fetch an item from the cache Input: url from wich the rss file was fetched Output: cached object on HIT, false on MISS \*=======================================================================*/ function get ($url) { $this->ERROR = ""; $cache_option = 'rss_' . $this->file_name( $url ); if ( ! $rss = get_transient( $cache_option ) ) { $this->debug( "Cache doesn't contain: $url (cache option: $cache_option)" ); return 0; } return $rss; } /*=======================================================================*\ Function: check_cache Purpose: check a url for membership in the cache and whether the object is older then MAX_AGE (ie. STALE) Input: url from wich the rss file was fetched Output: cached object on HIT, false on MISS \*=======================================================================*/ function check_cache ( $url ) { $this->ERROR = ""; $cache_option = 'rss_' . $this->file_name( $url ); if ( get_transient($cache_option) ) { // object exists and is current return 'HIT'; } else { // object does not exist return 'MISS'; } } /*=======================================================================*\ Function: serialize \*=======================================================================*/ function serialize ( $rss ) { return serialize( $rss ); } /*=======================================================================*\ Function: unserialize \*=======================================================================*/ function unserialize ( $data ) { return unserialize( $data ); } /*=======================================================================*\ Function: file_name Purpose: map url to location in cache Input: url from wich the rss file was fetched Output: a file name \*=======================================================================*/ function file_name ($url) { return md5( $url ); } /*=======================================================================*\ Function: error Purpose: register error \*=======================================================================*/ function error ($errormsg, $lvl=E_USER_WARNING) { // append PHP's error message if track_errors enabled if ( isset($php_errormsg) ) { $errormsg .= " ($php_errormsg)"; } $this->ERROR = $errormsg; if ( MAGPIE_DEBUG ) { trigger_error( $errormsg, $lvl); } else { error_log( $errormsg, 0); } } function debug ($debugmsg, $lvl=E_USER_NOTICE) { if ( MAGPIE_DEBUG ) { $this->error("MagpieRSS [debug] $debugmsg", $lvl); } } } if ( !function_exists('parse_w3cdtf') ) : function parse_w3cdtf ( $date_str ) { # regex to match wc3dtf $pat = "/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(:(\d{2}))?(?:([-+])(\d{2}):?(\d{2})|(Z))?/"; if ( preg_match( $pat, $date_str, $match ) ) { list( $year, $month, $day, $hours, $minutes, $seconds) = array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[7]); # calc epoch for current date assuming GMT $epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year); $offset = 0; if ( $match[11] == 'Z' ) { # zulu time, aka GMT } else { list( $tz_mod, $tz_hour, $tz_min ) = array( $match[8], $match[9], $match[10]); # zero out the variables if ( ! $tz_hour ) { $tz_hour = 0; } if ( ! $tz_min ) { $tz_min = 0; } $offset_secs = (($tz_hour*60)+$tz_min)*60; # is timezone ahead of GMT? then subtract offset # if ( $tz_mod == '+' ) { $offset_secs = $offset_secs * -1; } $offset = $offset_secs; } $epoch = $epoch + $offset; return $epoch; } else { return -1; } } endif; if ( !function_exists('wp_rss') ) : /** * Display all RSS items in a HTML ordered list. * * @since 1.5.0 * @package External * @subpackage MagpieRSS * * @param string $url URL of feed to display. Will not auto sense feed URL. * @param int $num_items Optional. Number of items to display, default is all. */ function wp_rss( $url, $num_items = -1 ) { if ( $rss = fetch_rss( $url ) ) { echo '<ul>'; if ( $num_items !== -1 ) { $rss->items = array_slice( $rss->items, 0, $num_items ); } foreach ( (array) $rss->items as $item ) { printf( '<li><a href="%1$s" title="%2$s">%3$s</a></li>', esc_url( $item['link'] ), esc_attr( strip_tags( $item['description'] ) ), esc_html( $item['title'] ) ); } echo '</ul>'; } else { _e( 'An error has occurred, which probably means the feed is down. Try again later.' ); } } endif; if ( !function_exists('get_rss') ) : /** * Display RSS items in HTML list items. * * You have to specify which HTML list you want, either ordered or unordered * before using the function. You also have to specify how many items you wish * to display. You can't display all of them like you can with wp_rss() * function. * * @since 1.5.0 * @package External * @subpackage MagpieRSS * * @param string $url URL of feed to display. Will not auto sense feed URL. * @param int $num_items Optional. Number of items to display, default is all. * @return bool False on failure. */ function get_rss ($url, $num_items = 5) { // Like get posts, but for RSS $rss = fetch_rss($url); if ( $rss ) { $rss->items = array_slice($rss->items, 0, $num_items); foreach ( (array) $rss->items as $item ) { echo "<li>\n"; echo "<a href='$item[link]' title='$item[description]'>"; echo esc_html($item['title']); echo "</a><br />\n"; echo "</li>\n"; } } else { return false; } } endif;
zyblog
trunk/zyblog/wp-includes/rss.php
PHP
asf20
22,898
<?php /** * Atom Feed Template for displaying Atom Comments feed. * * @package WordPress */ header('Content-Type: ' . feed_content_type('atom') . '; charset=' . get_option('blog_charset'), true); echo '<?xml version="1.0" encoding="' . get_option('blog_charset') . '" ?' . '>'; ?> <feed xmlns="http://www.w3.org/2005/Atom" xml:lang="<?php bloginfo_rss( 'language' ); ?>" xmlns:thr="http://purl.org/syndication/thread/1.0" <?php do_action('atom_ns'); do_action('atom_comments_ns'); ?> > <title type="text"><?php if ( is_singular() ) printf( ent2ncr( __( 'Comments on %s' ) ), get_the_title_rss() ); elseif ( is_search() ) printf( ent2ncr( __( 'Comments for %1$s searching on %2$s' ) ), get_bloginfo_rss( 'name' ), get_search_query() ); else printf( ent2ncr( __( 'Comments for %s' ) ), get_bloginfo_rss( 'name' ) . get_wp_title_rss() ); ?></title> <subtitle type="text"><?php bloginfo_rss('description'); ?></subtitle> <updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastcommentmodified('GMT'), false); ?></updated> <?php if ( is_singular() ) { ?> <link rel="alternate" type="<?php bloginfo_rss('html_type'); ?>" href="<?php comments_link_feed(); ?>" /> <link rel="self" type="application/atom+xml" href="<?php echo esc_url( get_post_comments_feed_link('', 'atom') ); ?>" /> <id><?php echo esc_url( get_post_comments_feed_link('', 'atom') ); ?></id> <?php } elseif(is_search()) { ?> <link rel="alternate" type="<?php bloginfo_rss('html_type'); ?>" href="<?php echo home_url() . '?s=' . get_search_query(); ?>" /> <link rel="self" type="application/atom+xml" href="<?php echo get_search_comments_feed_link('', 'atom'); ?>" /> <id><?php echo get_search_comments_feed_link('', 'atom'); ?></id> <?php } else { ?> <link rel="alternate" type="<?php bloginfo_rss('html_type'); ?>" href="<?php bloginfo_rss('url'); ?>" /> <link rel="self" type="application/atom+xml" href="<?php bloginfo_rss('comments_atom_url'); ?>" /> <id><?php bloginfo_rss('comments_atom_url'); ?></id> <?php } ?> <?php do_action('comments_atom_head'); ?> <?php if ( have_comments() ) : while ( have_comments() ) : the_comment(); $comment_post = $GLOBALS['post'] = get_post( $comment->comment_post_ID ); ?> <entry> <title><?php if ( !is_singular() ) { $title = get_the_title($comment_post->ID); $title = apply_filters('the_title_rss', $title); printf(ent2ncr(__('Comment on %1$s by %2$s')), $title, get_comment_author_rss()); } else { printf(ent2ncr(__('By: %s')), get_comment_author_rss()); } ?></title> <link rel="alternate" href="<?php comment_link(); ?>" type="<?php bloginfo_rss('html_type'); ?>" /> <author> <name><?php comment_author_rss(); ?></name> <?php if (get_comment_author_url()) echo '<uri>' . get_comment_author_url() . '</uri>'; ?> </author> <id><?php comment_guid(); ?></id> <updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_comment_time('Y-m-d H:i:s', true, false), false); ?></updated> <published><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_comment_time('Y-m-d H:i:s', true, false), false); ?></published> <?php if ( post_password_required($comment_post) ) : ?> <content type="html" xml:base="<?php comment_link(); ?>"><![CDATA[<?php echo get_the_password_form(); ?>]]></content> <?php else : // post pass ?> <content type="html" xml:base="<?php comment_link(); ?>"><![CDATA[<?php comment_text(); ?>]]></content> <?php endif; // post pass // Return comment threading information (http://www.ietf.org/rfc/rfc4685.txt) if ( $comment->comment_parent == 0 ) : // This comment is top level ?> <thr:in-reply-to ref="<?php the_guid(); ?>" href="<?php the_permalink_rss() ?>" type="<?php bloginfo_rss('html_type'); ?>" /> <?php else : // This comment is in reply to another comment $parent_comment = get_comment($comment->comment_parent); // The rel attribute below and the id tag above should be GUIDs, but WP doesn't create them for comments (unlike posts). Either way, its more important that they both use the same system ?> <thr:in-reply-to ref="<?php comment_guid($parent_comment) ?>" href="<?php echo get_comment_link($parent_comment) ?>" type="<?php bloginfo_rss('html_type'); ?>" /> <?php endif; do_action('comment_atom_entry', $comment->comment_ID, $comment_post->ID); ?> </entry> <?php endwhile; endif; ?> </feed>
zyblog
trunk/zyblog/wp-includes/feed-atom-comments.php
PHP
asf20
4,311
<?php /** * Deprecated. No longer needed. * * @package WordPress */ _deprecated_file( basename(__FILE__), '2.1', null, __( 'This file no longer needs to be included.' ) );
zyblog
trunk/zyblog/wp-includes/registration-functions.php
PHP
asf20
176
<?php /** * WordPress Query API * * The query API attempts to get which part of WordPress to the user is on. It * also provides functionality to getting URL query information. * * @link http://codex.wordpress.org/The_Loop More information on The Loop. * * @package WordPress * @subpackage Query */ /** * Retrieve variable in the WP_Query class. * * @see WP_Query::get() * @since 1.5.0 * @uses $wp_query * * @param string $var The variable key to retrieve. * @return mixed */ function get_query_var($var) { global $wp_query; return $wp_query->get($var); } /** * Retrieve the currently-queried object. Wrapper for $wp_query->get_queried_object() * * @uses WP_Query::get_queried_object * * @since 3.1.0 * @access public * * @return object */ function get_queried_object() { global $wp_query; return $wp_query->get_queried_object(); } /** * Retrieve ID of the current queried object. Wrapper for $wp_query->get_queried_object_id() * * @uses WP_Query::get_queried_object_id() * * @since 3.1.0 * @access public * * @return int */ function get_queried_object_id() { global $wp_query; return $wp_query->get_queried_object_id(); } /** * Set query variable. * * @see WP_Query::set() * @since 2.2.0 * @uses $wp_query * * @param string $var Query variable key. * @param mixed $value * @return null */ function set_query_var($var, $value) { global $wp_query; return $wp_query->set($var, $value); } /** * Set up The Loop with query parameters. * * This will override the current WordPress Loop and shouldn't be used more than * once. This must not be used within the WordPress Loop. * * @since 1.5.0 * @uses $wp_query * * @param string $query * @return array List of posts */ function query_posts($query) { $GLOBALS['wp_query'] = new WP_Query(); return $GLOBALS['wp_query']->query($query); } /** * Destroy the previous query and set up a new query. * * This should be used after {@link query_posts()} and before another {@link * query_posts()}. This will remove obscure bugs that occur when the previous * wp_query object is not destroyed properly before another is set up. * * @since 2.3.0 * @uses $wp_query */ function wp_reset_query() { $GLOBALS['wp_query'] = $GLOBALS['wp_the_query']; wp_reset_postdata(); } /** * After looping through a separate query, this function restores * the $post global to the current post in the main query * * @since 3.0.0 * @uses $wp_query */ function wp_reset_postdata() { global $wp_query; if ( !empty($wp_query->post) ) { $GLOBALS['post'] = $wp_query->post; setup_postdata($wp_query->post); } } /* * Query type checks. */ /** * Is the query for an existing archive page? * * Month, Year, Category, Author, Post Type archive... * * @see WP_Query::is_archive() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_archive() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_archive(); } /** * Is the query for an existing post type archive page? * * @see WP_Query::is_post_type_archive() * @since 3.1.0 * @uses $wp_query * * @param mixed $post_types Optional. Post type or array of posts types to check against. * @return bool */ function is_post_type_archive( $post_types = '' ) { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_post_type_archive( $post_types ); } /** * Is the query for an existing attachment page? * * @see WP_Query::is_attachment() * @since 2.0.0 * @uses $wp_query * * @return bool */ function is_attachment() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_attachment(); } /** * Is the query for an existing author archive page? * * If the $author parameter is specified, this function will additionally * check if the query is for one of the authors specified. * * @see WP_Query::is_author() * @since 1.5.0 * @uses $wp_query * * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames * @return bool */ function is_author( $author = '' ) { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_author( $author ); } /** * Is the query for an existing category archive page? * * If the $category parameter is specified, this function will additionally * check if the query is for one of the categories specified. * * @see WP_Query::is_category() * @since 1.5.0 * @uses $wp_query * * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs. * @return bool */ function is_category( $category = '' ) { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_category( $category ); } /** * Is the query for an existing tag archive page? * * If the $tag parameter is specified, this function will additionally * check if the query is for one of the tags specified. * * @see WP_Query::is_tag() * @since 2.3.0 * @uses $wp_query * * @param mixed $slug Optional. Tag slug or array of slugs. * @return bool */ function is_tag( $slug = '' ) { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_tag( $slug ); } /** * Is the query for an existing taxonomy archive page? * * If the $taxonomy parameter is specified, this function will additionally * check if the query is for that specific $taxonomy. * * If the $term parameter is specified in addition to the $taxonomy parameter, * this function will additionally check if the query is for one of the terms * specified. * * @see WP_Query::is_tax() * @since 2.5.0 * @uses $wp_query * * @param mixed $taxonomy Optional. Taxonomy slug or slugs. * @param mixed $term Optional. Term ID, name, slug or array of Term IDs, names, and slugs. * @return bool */ function is_tax( $taxonomy = '', $term = '' ) { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_tax( $taxonomy, $term ); } /** * Whether the current URL is within the comments popup window. * * @see WP_Query::is_comments_popup() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_comments_popup() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_comments_popup(); } /** * Is the query for an existing date archive? * * @see WP_Query::is_date() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_date() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_date(); } /** * Is the query for an existing day archive? * * @see WP_Query::is_day() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_day() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_day(); } /** * Is the query for a feed? * * @see WP_Query::is_feed() * @since 1.5.0 * @uses $wp_query * * @param string|array $feeds Optional feed types to check. * @return bool */ function is_feed( $feeds = '' ) { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_feed( $feeds ); } /** * Is the query for a comments feed? * * @see WP_Query::is_comments_feed() * @since 3.0.0 * @uses $wp_query * * @return bool */ function is_comment_feed() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_comment_feed(); } /** * Is the query for the front page of the site? * * This is for what is displayed at your site's main URL. * * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'. * * If you set a static page for the front page of your site, this function will return * true when viewing that page. * * Otherwise the same as @see is_home() * * @see WP_Query::is_front_page() * @since 2.5.0 * @uses is_home() * @uses get_option() * * @return bool True, if front of site. */ function is_front_page() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_front_page(); } /** * Is the query for the blog homepage? * * This is the page which shows the time based blog content of your site. * * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'. * * If you set a static page for the front page of your site, this function will return * true only on the page you set as the "Posts page". * * @see is_front_page() * * @see WP_Query::is_home() * @since 1.5.0 * @uses $wp_query * * @return bool True if blog view homepage. */ function is_home() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_home(); } /** * Is the query for an existing month archive? * * @see WP_Query::is_month() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_month() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_month(); } /** * Is the query for an existing single page? * * If the $page parameter is specified, this function will additionally * check if the query is for one of the pages specified. * * @see is_single() * @see is_singular() * * @see WP_Query::is_page() * @since 1.5.0 * @uses $wp_query * * @param mixed $page Page ID, title, slug, or array of such. * @return bool */ function is_page( $page = '' ) { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_page( $page ); } /** * Is the query for paged result and not for the first page? * * @see WP_Query::is_paged() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_paged() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_paged(); } /** * Is the query for a post or page preview? * * @see WP_Query::is_preview() * @since 2.0.0 * @uses $wp_query * * @return bool */ function is_preview() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_preview(); } /** * Is the query for the robots file? * * @see WP_Query::is_robots() * @since 2.1.0 * @uses $wp_query * * @return bool */ function is_robots() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_robots(); } /** * Is the query for a search? * * @see WP_Query::is_search() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_search() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_search(); } /** * Is the query for an existing single post? * * Works for any post type, except attachments and pages * * If the $post parameter is specified, this function will additionally * check if the query is for one of the Posts specified. * * @see is_page() * @see is_singular() * * @see WP_Query::is_single() * @since 1.5.0 * @uses $wp_query * * @param mixed $post Post ID, title, slug, or array of such. * @return bool */ function is_single( $post = '' ) { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_single( $post ); } /** * Is the query for an existing single post of any post type (post, attachment, page, ... )? * * If the $post_types parameter is specified, this function will additionally * check if the query is for one of the Posts Types specified. * * @see is_page() * @see is_single() * * @see WP_Query::is_singular() * @since 1.5.0 * @uses $wp_query * * @param mixed $post_types Optional. Post Type or array of Post Types * @return bool */ function is_singular( $post_types = '' ) { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_singular( $post_types ); } /** * Is the query for a specific time? * * @see WP_Query::is_time() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_time() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_time(); } /** * Is the query for a trackback endpoint call? * * @see WP_Query::is_trackback() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_trackback() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_trackback(); } /** * Is the query for an existing year archive? * * @see WP_Query::is_year() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_year() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_year(); } /** * Is the query a 404 (returns no results)? * * @see WP_Query::is_404() * @since 1.5.0 * @uses $wp_query * * @return bool */ function is_404() { global $wp_query; if ( ! isset( $wp_query ) ) { _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' ); return false; } return $wp_query->is_404(); } /** * Is the query the main query? * * @since 3.3.0 * * @return bool */ function is_main_query() { global $wp_query; return $wp_query->is_main_query(); } /* * The Loop. Post loop control. */ /** * Whether current WordPress query has results to loop over. * * @see WP_Query::have_posts() * @since 1.5.0 * @uses $wp_query * * @return bool */ function have_posts() { global $wp_query; return $wp_query->have_posts(); } /** * Whether the caller is in the Loop. * * @since 2.0.0 * @uses $wp_query * * @return bool True if caller is within loop, false if loop hasn't started or ended. */ function in_the_loop() { global $wp_query; return $wp_query->in_the_loop; } /** * Rewind the loop posts. * * @see WP_Query::rewind_posts() * @since 1.5.0 * @uses $wp_query * * @return null */ function rewind_posts() { global $wp_query; return $wp_query->rewind_posts(); } /** * Iterate the post index in the loop. * * @see WP_Query::the_post() * @since 1.5.0 * @uses $wp_query */ function the_post() { global $wp_query; $wp_query->the_post(); } /* * Comments loop. */ /** * Whether there are comments to loop over. * * @see WP_Query::have_comments() * @since 2.2.0 * @uses $wp_query * * @return bool */ function have_comments() { global $wp_query; return $wp_query->have_comments(); } /** * Iterate comment index in the comment loop. * * @see WP_Query::the_comment() * @since 2.2.0 * @uses $wp_query * * @return object */ function the_comment() { global $wp_query; return $wp_query->the_comment(); } /* * WP_Query */ /** * The WordPress Query class. * * @link http://codex.wordpress.org/Function_Reference/WP_Query Codex page. * * @since 1.5.0 */ class WP_Query { /** * Query vars set by the user * * @since 1.5.0 * @access public * @var array */ var $query; /** * Query vars, after parsing * * @since 1.5.0 * @access public * @var array */ var $query_vars = array(); /** * Taxonomy query, as passed to get_tax_sql() * * @since 3.1.0 * @access public * @var object WP_Tax_Query */ var $tax_query; /** * Metadata query container * * @since 3.2.0 * @access public * @var object WP_Meta_Query */ var $meta_query = false; /** * Holds the data for a single object that is queried. * * Holds the contents of a post, page, category, attachment. * * @since 1.5.0 * @access public * @var object|array */ var $queried_object; /** * The ID of the queried object. * * @since 1.5.0 * @access public * @var int */ var $queried_object_id; /** * Get post database query. * * @since 2.0.1 * @access public * @var string */ var $request; /** * List of posts. * * @since 1.5.0 * @access public * @var array */ var $posts; /** * The amount of posts for the current query. * * @since 1.5.0 * @access public * @var int */ var $post_count = 0; /** * Index of the current item in the loop. * * @since 1.5.0 * @access public * @var int */ var $current_post = -1; /** * Whether the loop has started and the caller is in the loop. * * @since 2.0.0 * @access public * @var bool */ var $in_the_loop = false; /** * The current post ID. * * @since 1.5.0 * @access public * @var object */ var $post; /** * The list of comments for current post. * * @since 2.2.0 * @access public * @var array */ var $comments; /** * The amount of comments for the posts. * * @since 2.2.0 * @access public * @var int */ var $comment_count = 0; /** * The index of the comment in the comment loop. * * @since 2.2.0 * @access public * @var int */ var $current_comment = -1; /** * Current comment ID. * * @since 2.2.0 * @access public * @var int */ var $comment; /** * The amount of found posts for the current query. * * If limit clause was not used, equals $post_count. * * @since 2.1.0 * @access public * @var int */ var $found_posts = 0; /** * The amount of pages. * * @since 2.1.0 * @access public * @var int */ var $max_num_pages = 0; /** * The amount of comment pages. * * @since 2.7.0 * @access public * @var int */ var $max_num_comment_pages = 0; /** * Set if query is single post. * * @since 1.5.0 * @access public * @var bool */ var $is_single = false; /** * Set if query is preview of blog. * * @since 2.0.0 * @access public * @var bool */ var $is_preview = false; /** * Set if query returns a page. * * @since 1.5.0 * @access public * @var bool */ var $is_page = false; /** * Set if query is an archive list. * * @since 1.5.0 * @access public * @var bool */ var $is_archive = false; /** * Set if query is part of a date. * * @since 1.5.0 * @access public * @var bool */ var $is_date = false; /** * Set if query contains a year. * * @since 1.5.0 * @access public * @var bool */ var $is_year = false; /** * Set if query contains a month. * * @since 1.5.0 * @access public * @var bool */ var $is_month = false; /** * Set if query contains a day. * * @since 1.5.0 * @access public * @var bool */ var $is_day = false; /** * Set if query contains time. * * @since 1.5.0 * @access public * @var bool */ var $is_time = false; /** * Set if query contains an author. * * @since 1.5.0 * @access public * @var bool */ var $is_author = false; /** * Set if query contains category. * * @since 1.5.0 * @access public * @var bool */ var $is_category = false; /** * Set if query contains tag. * * @since 2.3.0 * @access public * @var bool */ var $is_tag = false; /** * Set if query contains taxonomy. * * @since 2.5.0 * @access public * @var bool */ var $is_tax = false; /** * Set if query was part of a search result. * * @since 1.5.0 * @access public * @var bool */ var $is_search = false; /** * Set if query is feed display. * * @since 1.5.0 * @access public * @var bool */ var $is_feed = false; /** * Set if query is comment feed display. * * @since 2.2.0 * @access public * @var bool */ var $is_comment_feed = false; /** * Set if query is trackback. * * @since 1.5.0 * @access public * @var bool */ var $is_trackback = false; /** * Set if query is blog homepage. * * @since 1.5.0 * @access public * @var bool */ var $is_home = false; /** * Set if query couldn't found anything. * * @since 1.5.0 * @access public * @var bool */ var $is_404 = false; /** * Set if query is within comments popup window. * * @since 1.5.0 * @access public * @var bool */ var $is_comments_popup = false; /** * Set if query is paged * * @since 1.5.0 * @access public * @var bool */ var $is_paged = false; /** * Set if query is part of administration page. * * @since 1.5.0 * @access public * @var bool */ var $is_admin = false; /** * Set if query is an attachment. * * @since 2.0.0 * @access public * @var bool */ var $is_attachment = false; /** * Set if is single, is a page, or is an attachment. * * @since 2.1.0 * @access public * @var bool */ var $is_singular = false; /** * Set if query is for robots. * * @since 2.1.0 * @access public * @var bool */ var $is_robots = false; /** * Set if query contains posts. * * Basically, the homepage if the option isn't set for the static homepage. * * @since 2.1.0 * @access public * @var bool */ var $is_posts_page = false; /** * Set if query is for a post type archive. * * @since 3.1.0 * @access public * @var bool */ var $is_post_type_archive = false; /** * Stores the ->query_vars state like md5(serialize( $this->query_vars ) ) so we know * whether we have to re-parse because something has changed * * @since 3.1.0 * @access private */ var $query_vars_hash = false; /** * Whether query vars have changed since the initial parse_query() call. Used to catch modifications to query vars made * via pre_get_posts hooks. * * @since 3.1.1 * @access private */ var $query_vars_changed = true; /** * Set if post thumbnails are cached * * @since 3.2.0 * @access public * @var bool */ var $thumbnails_cached = false; /** * Resets query flags to false. * * The query flags are what page info WordPress was able to figure out. * * @since 2.0.0 * @access private */ function init_query_flags() { $this->is_single = false; $this->is_preview = false; $this->is_page = false; $this->is_archive = false; $this->is_date = false; $this->is_year = false; $this->is_month = false; $this->is_day = false; $this->is_time = false; $this->is_author = false; $this->is_category = false; $this->is_tag = false; $this->is_tax = false; $this->is_search = false; $this->is_feed = false; $this->is_comment_feed = false; $this->is_trackback = false; $this->is_home = false; $this->is_404 = false; $this->is_comments_popup = false; $this->is_paged = false; $this->is_admin = false; $this->is_attachment = false; $this->is_singular = false; $this->is_robots = false; $this->is_posts_page = false; $this->is_post_type_archive = false; } /** * Initiates object properties and sets default values. * * @since 1.5.0 * @access public */ function init() { unset($this->posts); unset($this->query); $this->query_vars = array(); unset($this->queried_object); unset($this->queried_object_id); $this->post_count = 0; $this->current_post = -1; $this->in_the_loop = false; unset( $this->request ); unset( $this->post ); unset( $this->comments ); unset( $this->comment ); $this->comment_count = 0; $this->current_comment = -1; $this->found_posts = 0; $this->max_num_pages = 0; $this->max_num_comment_pages = 0; $this->init_query_flags(); } /** * Reparse the query vars. * * @since 1.5.0 * @access public */ function parse_query_vars() { $this->parse_query(); } /** * Fills in the query variables, which do not exist within the parameter. * * @since 2.1.0 * @access public * * @param array $array Defined query variables. * @return array Complete query variables with undefined ones filled in empty. */ function fill_query_vars($array) { $keys = array( 'error' , 'm' , 'p' , 'post_parent' , 'subpost' , 'subpost_id' , 'attachment' , 'attachment_id' , 'name' , 'static' , 'pagename' , 'page_id' , 'second' , 'minute' , 'hour' , 'day' , 'monthnum' , 'year' , 'w' , 'category_name' , 'tag' , 'cat' , 'tag_id' , 'author_name' , 'feed' , 'tb' , 'paged' , 'comments_popup' , 'meta_key' , 'meta_value' , 'preview' , 's' , 'sentence' , 'fields' , 'menu_order' ); foreach ( $keys as $key ) { if ( !isset($array[$key]) ) $array[$key] = ''; } $array_keys = array('category__in', 'category__not_in', 'category__and', 'post__in', 'post__not_in', 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and'); foreach ( $array_keys as $key ) { if ( !isset($array[$key]) ) $array[$key] = array(); } return $array; } /** * Parse a query string and set query type booleans. * * @since 1.5.0 * @access public * * @param string|array $query Optional query. */ function parse_query( $query = '' ) { if ( ! empty( $query ) ) { $this->init(); $this->query = $this->query_vars = wp_parse_args( $query ); } elseif ( ! isset( $this->query ) ) { $this->query = $this->query_vars; } $this->query_vars = $this->fill_query_vars($this->query_vars); $qv = &$this->query_vars; $this->query_vars_changed = true; if ( ! empty($qv['robots']) ) $this->is_robots = true; $qv['p'] = absint($qv['p']); $qv['page_id'] = absint($qv['page_id']); $qv['year'] = absint($qv['year']); $qv['monthnum'] = absint($qv['monthnum']); $qv['day'] = absint($qv['day']); $qv['w'] = absint($qv['w']); $qv['m'] = absint($qv['m']); $qv['paged'] = absint($qv['paged']); $qv['cat'] = preg_replace( '|[^0-9,-]|', '', $qv['cat'] ); // comma separated list of positive or negative integers $qv['pagename'] = trim( $qv['pagename'] ); $qv['name'] = trim( $qv['name'] ); if ( '' !== $qv['hour'] ) $qv['hour'] = absint($qv['hour']); if ( '' !== $qv['minute'] ) $qv['minute'] = absint($qv['minute']); if ( '' !== $qv['second'] ) $qv['second'] = absint($qv['second']); if ( '' !== $qv['menu_order'] ) $qv['menu_order'] = absint($qv['menu_order']); // Compat. Map subpost to attachment. if ( '' != $qv['subpost'] ) $qv['attachment'] = $qv['subpost']; if ( '' != $qv['subpost_id'] ) $qv['attachment_id'] = $qv['subpost_id']; $qv['attachment_id'] = absint($qv['attachment_id']); if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) { $this->is_single = true; $this->is_attachment = true; } elseif ( '' != $qv['name'] ) { $this->is_single = true; } elseif ( $qv['p'] ) { $this->is_single = true; } elseif ( ('' !== $qv['hour']) && ('' !== $qv['minute']) &&('' !== $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) { // If year, month, day, hour, minute, and second are set, a single // post is being queried. $this->is_single = true; } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) { $this->is_page = true; $this->is_single = false; } else { // Look for archive queries. Dates, categories, authors, search, post type archives. if ( !empty($qv['s']) ) { $this->is_search = true; } if ( '' !== $qv['second'] ) { $this->is_time = true; $this->is_date = true; } if ( '' !== $qv['minute'] ) { $this->is_time = true; $this->is_date = true; } if ( '' !== $qv['hour'] ) { $this->is_time = true; $this->is_date = true; } if ( $qv['day'] ) { if ( ! $this->is_date ) { $this->is_day = true; $this->is_date = true; } } if ( $qv['monthnum'] ) { if ( ! $this->is_date ) { $this->is_month = true; $this->is_date = true; } } if ( $qv['year'] ) { if ( ! $this->is_date ) { $this->is_year = true; $this->is_date = true; } } if ( $qv['m'] ) { $this->is_date = true; if ( strlen($qv['m']) > 9 ) { $this->is_time = true; } else if ( strlen($qv['m']) > 7 ) { $this->is_day = true; } else if ( strlen($qv['m']) > 5 ) { $this->is_month = true; } else { $this->is_year = true; } } if ( '' != $qv['w'] ) { $this->is_date = true; } $this->query_vars_hash = false; $this->parse_tax_query( $qv ); foreach ( $this->tax_query->queries as $tax_query ) { if ( 'NOT IN' != $tax_query['operator'] ) { switch ( $tax_query['taxonomy'] ) { case 'category': $this->is_category = true; break; case 'post_tag': $this->is_tag = true; break; default: $this->is_tax = true; } } } unset( $tax_query ); if ( empty($qv['author']) || ($qv['author'] == '0') ) { $this->is_author = false; } else { $this->is_author = true; } if ( '' != $qv['author_name'] ) $this->is_author = true; if ( !empty( $qv['post_type'] ) && ! is_array( $qv['post_type'] ) ) { $post_type_obj = get_post_type_object( $qv['post_type'] ); if ( ! empty( $post_type_obj->has_archive ) ) $this->is_post_type_archive = true; } if ( $this->is_post_type_archive || $this->is_date || $this->is_author || $this->is_category || $this->is_tag || $this->is_tax ) $this->is_archive = true; } if ( '' != $qv['feed'] ) $this->is_feed = true; if ( '' != $qv['tb'] ) $this->is_trackback = true; if ( '' != $qv['paged'] && ( intval($qv['paged']) > 1 ) ) $this->is_paged = true; if ( '' != $qv['comments_popup'] ) $this->is_comments_popup = true; // if we're previewing inside the write screen if ( '' != $qv['preview'] ) $this->is_preview = true; if ( is_admin() ) $this->is_admin = true; if ( false !== strpos($qv['feed'], 'comments-') ) { $qv['feed'] = str_replace('comments-', '', $qv['feed']); $qv['withcomments'] = 1; } $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment; if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) ) $this->is_comment_feed = true; if ( !( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_comments_popup || $this->is_robots ) ) $this->is_home = true; // Correct is_* for page_on_front and page_for_posts if ( $this->is_home && 'page' == get_option('show_on_front') && get_option('page_on_front') ) { $_query = wp_parse_args($this->query); // pagename can be set and empty depending on matched rewrite rules. Ignore an empty pagename. if ( isset($_query['pagename']) && '' == $_query['pagename'] ) unset($_query['pagename']); if ( empty($_query) || !array_diff( array_keys($_query), array('preview', 'page', 'paged', 'cpage') ) ) { $this->is_page = true; $this->is_home = false; $qv['page_id'] = get_option('page_on_front'); // Correct <!--nextpage--> for page_on_front if ( !empty($qv['paged']) ) { $qv['page'] = $qv['paged']; unset($qv['paged']); } } } if ( '' != $qv['pagename'] ) { $this->queried_object = get_page_by_path($qv['pagename']); if ( !empty($this->queried_object) ) $this->queried_object_id = (int) $this->queried_object->ID; else unset($this->queried_object); if ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) { $this->is_page = false; $this->is_home = true; $this->is_posts_page = true; } } if ( $qv['page_id'] ) { if ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) { $this->is_page = false; $this->is_home = true; $this->is_posts_page = true; } } if ( !empty($qv['post_type']) ) { if ( is_array($qv['post_type']) ) $qv['post_type'] = array_map('sanitize_key', $qv['post_type']); else $qv['post_type'] = sanitize_key($qv['post_type']); } if ( ! empty( $qv['post_status'] ) ) { if ( is_array( $qv['post_status'] ) ) $qv['post_status'] = array_map('sanitize_key', $qv['post_status']); else $qv['post_status'] = preg_replace('|[^a-z0-9_,-]|', '', $qv['post_status']); } if ( $this->is_posts_page && ( ! isset($qv['withcomments']) || ! $qv['withcomments'] ) ) $this->is_comment_feed = false; $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment; // Done correcting is_* for page_on_front and page_for_posts if ( '404' == $qv['error'] ) $this->set_404(); $this->query_vars_hash = md5( serialize( $this->query_vars ) ); $this->query_vars_changed = false; do_action_ref_array('parse_query', array(&$this)); } /* * Parses various taxonomy related query vars. * * @access protected * @since 3.1.0 * * @param array &$q The query variables */ function parse_tax_query( &$q ) { if ( ! empty( $q['tax_query'] ) && is_array( $q['tax_query'] ) ) { $tax_query = $q['tax_query']; } else { $tax_query = array(); } if ( !empty($q['taxonomy']) && !empty($q['term']) ) { $tax_query[] = array( 'taxonomy' => $q['taxonomy'], 'terms' => array( $q['term'] ), 'field' => 'slug', ); } foreach ( $GLOBALS['wp_taxonomies'] as $taxonomy => $t ) { if ( 'post_tag' == $taxonomy ) continue; // Handled further down in the $q['tag'] block if ( $t->query_var && !empty( $q[$t->query_var] ) ) { $tax_query_defaults = array( 'taxonomy' => $taxonomy, 'field' => 'slug', ); if ( isset( $t->rewrite['hierarchical'] ) && $t->rewrite['hierarchical'] ) { $q[$t->query_var] = wp_basename( $q[$t->query_var] ); } $term = $q[$t->query_var]; if ( strpos($term, '+') !== false ) { $terms = preg_split( '/[+]+/', $term ); foreach ( $terms as $term ) { $tax_query[] = array_merge( $tax_query_defaults, array( 'terms' => array( $term ) ) ); } } else { $tax_query[] = array_merge( $tax_query_defaults, array( 'terms' => preg_split( '/[,]+/', $term ) ) ); } } } // Category stuff if ( !empty($q['cat']) && '0' != $q['cat'] && !$this->is_singular && $this->query_vars_changed ) { $q['cat'] = ''.urldecode($q['cat']).''; $q['cat'] = addslashes_gpc($q['cat']); $cat_array = preg_split('/[,\s]+/', $q['cat']); $q['cat'] = ''; $req_cats = array(); foreach ( (array) $cat_array as $cat ) { $cat = intval($cat); $req_cats[] = $cat; $in = ($cat > 0); $cat = abs($cat); if ( $in ) { $q['category__in'][] = $cat; $q['category__in'] = array_merge( $q['category__in'], get_term_children($cat, 'category') ); } else { $q['category__not_in'][] = $cat; $q['category__not_in'] = array_merge( $q['category__not_in'], get_term_children($cat, 'category') ); } } $q['cat'] = implode(',', $req_cats); } if ( !empty($q['category__in']) ) { $q['category__in'] = array_map('absint', array_unique( (array) $q['category__in'] ) ); $tax_query[] = array( 'taxonomy' => 'category', 'terms' => $q['category__in'], 'field' => 'term_id', 'include_children' => false ); } if ( !empty($q['category__not_in']) ) { $q['category__not_in'] = array_map('absint', array_unique( (array) $q['category__not_in'] ) ); $tax_query[] = array( 'taxonomy' => 'category', 'terms' => $q['category__not_in'], 'operator' => 'NOT IN', 'include_children' => false ); } if ( !empty($q['category__and']) ) { $q['category__and'] = array_map('absint', array_unique( (array) $q['category__and'] ) ); $tax_query[] = array( 'taxonomy' => 'category', 'terms' => $q['category__and'], 'field' => 'term_id', 'operator' => 'AND', 'include_children' => false ); } // Tag stuff if ( '' != $q['tag'] && !$this->is_singular && $this->query_vars_changed ) { if ( strpos($q['tag'], ',') !== false ) { $tags = preg_split('/[,\r\n\t ]+/', $q['tag']); foreach ( (array) $tags as $tag ) { $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db'); $q['tag_slug__in'][] = $tag; } } else if ( preg_match('/[+\r\n\t ]+/', $q['tag']) || !empty($q['cat']) ) { $tags = preg_split('/[+\r\n\t ]+/', $q['tag']); foreach ( (array) $tags as $tag ) { $tag = sanitize_term_field('slug', $tag, 0, 'post_tag', 'db'); $q['tag_slug__and'][] = $tag; } } else { $q['tag'] = sanitize_term_field('slug', $q['tag'], 0, 'post_tag', 'db'); $q['tag_slug__in'][] = $q['tag']; } } if ( !empty($q['tag_id']) ) { $q['tag_id'] = absint( $q['tag_id'] ); $tax_query[] = array( 'taxonomy' => 'post_tag', 'terms' => $q['tag_id'] ); } if ( !empty($q['tag__in']) ) { $q['tag__in'] = array_map('absint', array_unique( (array) $q['tag__in'] ) ); $tax_query[] = array( 'taxonomy' => 'post_tag', 'terms' => $q['tag__in'] ); } if ( !empty($q['tag__not_in']) ) { $q['tag__not_in'] = array_map('absint', array_unique( (array) $q['tag__not_in'] ) ); $tax_query[] = array( 'taxonomy' => 'post_tag', 'terms' => $q['tag__not_in'], 'operator' => 'NOT IN' ); } if ( !empty($q['tag__and']) ) { $q['tag__and'] = array_map('absint', array_unique( (array) $q['tag__and'] ) ); $tax_query[] = array( 'taxonomy' => 'post_tag', 'terms' => $q['tag__and'], 'operator' => 'AND' ); } if ( !empty($q['tag_slug__in']) ) { $q['tag_slug__in'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__in'] ) ); $tax_query[] = array( 'taxonomy' => 'post_tag', 'terms' => $q['tag_slug__in'], 'field' => 'slug' ); } if ( !empty($q['tag_slug__and']) ) { $q['tag_slug__and'] = array_map('sanitize_title_for_query', array_unique( (array) $q['tag_slug__and'] ) ); $tax_query[] = array( 'taxonomy' => 'post_tag', 'terms' => $q['tag_slug__and'], 'field' => 'slug', 'operator' => 'AND' ); } $this->tax_query = new WP_Tax_Query( $tax_query ); } /** * Sets the 404 property and saves whether query is feed. * * @since 2.0.0 * @access public */ function set_404() { $is_feed = $this->is_feed; $this->init_query_flags(); $this->is_404 = true; $this->is_feed = $is_feed; } /** * Retrieve query variable. * * @since 1.5.0 * @access public * * @param string $query_var Query variable key. * @return mixed */ function get($query_var) { if ( isset($this->query_vars[$query_var]) ) return $this->query_vars[$query_var]; return ''; } /** * Set query variable. * * @since 1.5.0 * @access public * * @param string $query_var Query variable key. * @param mixed $value Query variable value. */ function set($query_var, $value) { $this->query_vars[$query_var] = $value; } /** * Retrieve the posts based on query variables. * * There are a few filters and actions that can be used to modify the post * database query. * * @since 1.5.0 * @access public * @uses do_action_ref_array() Calls 'pre_get_posts' hook before retrieving posts. * * @return array List of posts. */ function get_posts() { global $wpdb, $user_ID, $_wp_using_ext_object_cache; $this->parse_query(); do_action_ref_array('pre_get_posts', array(&$this)); // Shorthand. $q = &$this->query_vars; // Fill again in case pre_get_posts unset some vars. $q = $this->fill_query_vars($q); // Parse meta query $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars( $q ); // Set a flag if a pre_get_posts hook changed the query vars. $hash = md5( serialize( $this->query_vars ) ); if ( $hash != $this->query_vars_hash ) { $this->query_vars_changed = true; $this->query_vars_hash = $hash; } unset($hash); // First let's clear some variables $distinct = ''; $whichauthor = ''; $whichmimetype = ''; $where = ''; $limits = ''; $join = ''; $search = ''; $groupby = ''; $fields = ''; $post_status_join = false; $page = 1; if ( isset( $q['caller_get_posts'] ) ) { _deprecated_argument( 'WP_Query', '3.1', __( '"caller_get_posts" is deprecated. Use "ignore_sticky_posts" instead.' ) ); if ( !isset( $q['ignore_sticky_posts'] ) ) $q['ignore_sticky_posts'] = $q['caller_get_posts']; } if ( !isset( $q['ignore_sticky_posts'] ) ) $q['ignore_sticky_posts'] = false; if ( !isset($q['suppress_filters']) ) $q['suppress_filters'] = false; if ( !isset($q['cache_results']) ) { if ( $_wp_using_ext_object_cache ) $q['cache_results'] = false; else $q['cache_results'] = true; } if ( !isset($q['update_post_term_cache']) ) $q['update_post_term_cache'] = true; if ( !isset($q['update_post_meta_cache']) ) $q['update_post_meta_cache'] = true; if ( !isset($q['post_type']) ) { if ( $this->is_search ) $q['post_type'] = 'any'; else $q['post_type'] = ''; } $post_type = $q['post_type']; if ( !isset($q['posts_per_page']) || $q['posts_per_page'] == 0 ) $q['posts_per_page'] = get_option('posts_per_page'); if ( isset($q['showposts']) && $q['showposts'] ) { $q['showposts'] = (int) $q['showposts']; $q['posts_per_page'] = $q['showposts']; } if ( (isset($q['posts_per_archive_page']) && $q['posts_per_archive_page'] != 0) && ($this->is_archive || $this->is_search) ) $q['posts_per_page'] = $q['posts_per_archive_page']; if ( !isset($q['nopaging']) ) { if ( $q['posts_per_page'] == -1 ) { $q['nopaging'] = true; } else { $q['nopaging'] = false; } } if ( $this->is_feed ) { $q['posts_per_page'] = get_option('posts_per_rss'); $q['nopaging'] = false; } $q['posts_per_page'] = (int) $q['posts_per_page']; if ( $q['posts_per_page'] < -1 ) $q['posts_per_page'] = abs($q['posts_per_page']); else if ( $q['posts_per_page'] == 0 ) $q['posts_per_page'] = 1; if ( !isset($q['comments_per_page']) || $q['comments_per_page'] == 0 ) $q['comments_per_page'] = get_option('comments_per_page'); if ( $this->is_home && (empty($this->query) || $q['preview'] == 'true') && ( 'page' == get_option('show_on_front') ) && get_option('page_on_front') ) { $this->is_page = true; $this->is_home = false; $q['page_id'] = get_option('page_on_front'); } if ( isset($q['page']) ) { $q['page'] = trim($q['page'], '/'); $q['page'] = absint($q['page']); } // If true, forcibly turns off SQL_CALC_FOUND_ROWS even when limits are present. if ( isset($q['no_found_rows']) ) $q['no_found_rows'] = (bool) $q['no_found_rows']; else $q['no_found_rows'] = false; switch ( $q['fields'] ) { case 'ids': $fields = "$wpdb->posts.ID"; break; case 'id=>parent': $fields = "$wpdb->posts.ID, $wpdb->posts.post_parent"; break; default: $fields = "$wpdb->posts.*"; } if ( '' !== $q['menu_order'] ) $where .= " AND $wpdb->posts.menu_order = " . $q['menu_order']; // If a month is specified in the querystring, load that month if ( $q['m'] ) { $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']); $where .= " AND YEAR($wpdb->posts.post_date)=" . substr($q['m'], 0, 4); if ( strlen($q['m']) > 5 ) $where .= " AND MONTH($wpdb->posts.post_date)=" . substr($q['m'], 4, 2); if ( strlen($q['m']) > 7 ) $where .= " AND DAYOFMONTH($wpdb->posts.post_date)=" . substr($q['m'], 6, 2); if ( strlen($q['m']) > 9 ) $where .= " AND HOUR($wpdb->posts.post_date)=" . substr($q['m'], 8, 2); if ( strlen($q['m']) > 11 ) $where .= " AND MINUTE($wpdb->posts.post_date)=" . substr($q['m'], 10, 2); if ( strlen($q['m']) > 13 ) $where .= " AND SECOND($wpdb->posts.post_date)=" . substr($q['m'], 12, 2); } if ( '' !== $q['hour'] ) $where .= " AND HOUR($wpdb->posts.post_date)='" . $q['hour'] . "'"; if ( '' !== $q['minute'] ) $where .= " AND MINUTE($wpdb->posts.post_date)='" . $q['minute'] . "'"; if ( '' !== $q['second'] ) $where .= " AND SECOND($wpdb->posts.post_date)='" . $q['second'] . "'"; if ( $q['year'] ) $where .= " AND YEAR($wpdb->posts.post_date)='" . $q['year'] . "'"; if ( $q['monthnum'] ) $where .= " AND MONTH($wpdb->posts.post_date)='" . $q['monthnum'] . "'"; if ( $q['day'] ) $where .= " AND DAYOFMONTH($wpdb->posts.post_date)='" . $q['day'] . "'"; // If we've got a post_type AND its not "any" post_type. if ( !empty($q['post_type']) && 'any' != $q['post_type'] ) { foreach ( (array)$q['post_type'] as $_post_type ) { $ptype_obj = get_post_type_object($_post_type); if ( !$ptype_obj || !$ptype_obj->query_var || empty($q[ $ptype_obj->query_var ]) ) continue; if ( ! $ptype_obj->hierarchical || strpos($q[ $ptype_obj->query_var ], '/') === false ) { // Non-hierarchical post_types & parent-level-hierarchical post_types can directly use 'name' $q['name'] = $q[ $ptype_obj->query_var ]; } else { // Hierarchical post_types will operate through the $q['pagename'] = $q[ $ptype_obj->query_var ]; $q['name'] = ''; } // Only one request for a slug is possible, this is why name & pagename are overwritten above. break; } //end foreach unset($ptype_obj); } if ( '' != $q['name'] ) { $q['name'] = sanitize_title_for_query( $q['name'] ); $where .= " AND $wpdb->posts.post_name = '" . $q['name'] . "'"; } elseif ( '' != $q['pagename'] ) { if ( isset($this->queried_object_id) ) { $reqpage = $this->queried_object_id; } else { if ( 'page' != $q['post_type'] ) { foreach ( (array)$q['post_type'] as $_post_type ) { $ptype_obj = get_post_type_object($_post_type); if ( !$ptype_obj || !$ptype_obj->hierarchical ) continue; $reqpage = get_page_by_path($q['pagename'], OBJECT, $_post_type); if ( $reqpage ) break; } unset($ptype_obj); } else { $reqpage = get_page_by_path($q['pagename']); } if ( !empty($reqpage) ) $reqpage = $reqpage->ID; else $reqpage = 0; } $page_for_posts = get_option('page_for_posts'); if ( ('page' != get_option('show_on_front') ) || empty($page_for_posts) || ( $reqpage != $page_for_posts ) ) { $q['pagename'] = sanitize_title_for_query( wp_basename( $q['pagename'] ) ); $q['name'] = $q['pagename']; $where .= " AND ($wpdb->posts.ID = '$reqpage')"; $reqpage_obj = get_post( $reqpage ); if ( is_object($reqpage_obj) && 'attachment' == $reqpage_obj->post_type ) { $this->is_attachment = true; $post_type = $q['post_type'] = 'attachment'; $this->is_page = true; $q['attachment_id'] = $reqpage; } } } elseif ( '' != $q['attachment'] ) { $q['attachment'] = sanitize_title_for_query( wp_basename( $q['attachment'] ) ); $q['name'] = $q['attachment']; $where .= " AND $wpdb->posts.post_name = '" . $q['attachment'] . "'"; } if ( $q['w'] ) $where .= ' AND ' . _wp_mysql_week( "`$wpdb->posts`.`post_date`" ) . " = '" . $q['w'] . "'"; if ( intval($q['comments_popup']) ) $q['p'] = absint($q['comments_popup']); // If an attachment is requested by number, let it supersede any post number. if ( $q['attachment_id'] ) $q['p'] = absint($q['attachment_id']); // If a post number is specified, load that post if ( $q['p'] ) { $where .= " AND {$wpdb->posts}.ID = " . $q['p']; } elseif ( $q['post__in'] ) { $post__in = implode(',', array_map( 'absint', $q['post__in'] )); $where .= " AND {$wpdb->posts}.ID IN ($post__in)"; } elseif ( $q['post__not_in'] ) { $post__not_in = implode(',', array_map( 'absint', $q['post__not_in'] )); $where .= " AND {$wpdb->posts}.ID NOT IN ($post__not_in)"; } if ( is_numeric($q['post_parent']) ) $where .= $wpdb->prepare( " AND $wpdb->posts.post_parent = %d ", $q['post_parent'] ); if ( $q['page_id'] ) { if ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) { $q['p'] = $q['page_id']; $where = " AND {$wpdb->posts}.ID = " . $q['page_id']; } } // If a search pattern is specified, load the posts that match if ( !empty($q['s']) ) { // added slashes screw with quote grouping when done early, so done later $q['s'] = stripslashes($q['s']); if ( empty( $_GET['s'] ) && $this->is_main_query() ) $q['s'] = urldecode($q['s']); if ( !empty($q['sentence']) ) { $q['search_terms'] = array($q['s']); } else { preg_match_all('/".*?("|$)|((?<=[\r\n\t ",+])|^)[^\r\n\t ",+]+/', $q['s'], $matches); $q['search_terms'] = array_map('_search_terms_tidy', $matches[0]); } $n = !empty($q['exact']) ? '' : '%'; $searchand = ''; foreach( (array) $q['search_terms'] as $term ) { $term = esc_sql( like_escape( $term ) ); $search .= "{$searchand}(($wpdb->posts.post_title LIKE '{$n}{$term}{$n}') OR ($wpdb->posts.post_content LIKE '{$n}{$term}{$n}'))"; $searchand = ' AND '; } if ( !empty($search) ) { $search = " AND ({$search}) "; if ( !is_user_logged_in() ) $search .= " AND ($wpdb->posts.post_password = '') "; } } // Allow plugins to contextually add/remove/modify the search section of the database query $search = apply_filters_ref_array('posts_search', array( $search, &$this ) ); // Taxonomies if ( !$this->is_singular ) { $this->parse_tax_query( $q ); $clauses = $this->tax_query->get_sql( $wpdb->posts, 'ID' ); $join .= $clauses['join']; $where .= $clauses['where']; } if ( $this->is_tax ) { if ( empty($post_type) ) { // Do a fully inclusive search for currently registered post types of queried taxonomies $post_type = array(); $taxonomies = wp_list_pluck( $this->tax_query->queries, 'taxonomy' ); foreach ( get_post_types( array( 'exclude_from_search' => false ) ) as $pt ) { $object_taxonomies = $pt === 'attachment' ? get_taxonomies_for_attachments() : get_object_taxonomies( $pt ); if ( array_intersect( $taxonomies, $object_taxonomies ) ) $post_type[] = $pt; } if ( ! $post_type ) $post_type = 'any'; $post_status_join = true; } elseif ( in_array('attachment', (array) $post_type) ) { $post_status_join = true; } } // Back-compat if ( !empty($this->tax_query->queries) ) { $tax_query_in_and = wp_list_filter( $this->tax_query->queries, array( 'operator' => 'NOT IN' ), 'NOT' ); if ( !empty( $tax_query_in_and ) ) { if ( !isset( $q['taxonomy'] ) ) { foreach ( $tax_query_in_and as $a_tax_query ) { if ( !in_array( $a_tax_query['taxonomy'], array( 'category', 'post_tag' ) ) ) { $q['taxonomy'] = $a_tax_query['taxonomy']; if ( 'slug' == $a_tax_query['field'] ) $q['term'] = $a_tax_query['terms'][0]; else $q['term_id'] = $a_tax_query['terms'][0]; break; } } } $cat_query = wp_list_filter( $tax_query_in_and, array( 'taxonomy' => 'category' ) ); if ( !empty( $cat_query ) ) { $cat_query = reset( $cat_query ); $the_cat = get_term_by( $cat_query['field'], $cat_query['terms'][0], 'category' ); if ( $the_cat ) { $this->set( 'cat', $the_cat->term_id ); $this->set( 'category_name', $the_cat->slug ); } unset( $the_cat ); } unset( $cat_query ); $tag_query = wp_list_filter( $tax_query_in_and, array( 'taxonomy' => 'post_tag' ) ); if ( !empty( $tag_query ) ) { $tag_query = reset( $tag_query ); $the_tag = get_term_by( $tag_query['field'], $tag_query['terms'][0], 'post_tag' ); if ( $the_tag ) { $this->set( 'tag_id', $the_tag->term_id ); } unset( $the_tag ); } unset( $tag_query ); } } if ( !empty( $this->tax_query->queries ) || !empty( $this->meta_query->queries ) ) { $groupby = "{$wpdb->posts}.ID"; } // Author/user stuff if ( empty($q['author']) || ($q['author'] == '0') ) { $whichauthor = ''; } else { $q['author'] = (string)urldecode($q['author']); $q['author'] = addslashes_gpc($q['author']); if ( strpos($q['author'], '-') !== false ) { $eq = '!='; $andor = 'AND'; $q['author'] = explode('-', $q['author']); $q['author'] = (string)absint($q['author'][1]); } else { $eq = '='; $andor = 'OR'; } $author_array = preg_split('/[,\s]+/', $q['author']); $_author_array = array(); foreach ( $author_array as $key => $_author ) $_author_array[] = "$wpdb->posts.post_author " . $eq . ' ' . absint($_author); $whichauthor .= ' AND (' . implode(" $andor ", $_author_array) . ')'; unset($author_array, $_author_array); } // Author stuff for nice URLs if ( '' != $q['author_name'] ) { if ( strpos($q['author_name'], '/') !== false ) { $q['author_name'] = explode('/', $q['author_name']); if ( $q['author_name'][ count($q['author_name'])-1 ] ) { $q['author_name'] = $q['author_name'][count($q['author_name'])-1]; // no trailing slash } else { $q['author_name'] = $q['author_name'][count($q['author_name'])-2]; // there was a trailing slash } } $q['author_name'] = sanitize_title_for_query( $q['author_name'] ); $q['author'] = get_user_by('slug', $q['author_name']); if ( $q['author'] ) $q['author'] = $q['author']->ID; $whichauthor .= " AND ($wpdb->posts.post_author = " . absint($q['author']) . ')'; } // MIME-Type stuff for attachment browsing if ( isset( $q['post_mime_type'] ) && '' != $q['post_mime_type'] ) $whichmimetype = wp_post_mime_type_where( $q['post_mime_type'], $wpdb->posts ); $where .= $search . $whichauthor . $whichmimetype; if ( empty($q['order']) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC')) ) $q['order'] = 'DESC'; // Order by if ( empty($q['orderby']) ) { $orderby = "$wpdb->posts.post_date " . $q['order']; } elseif ( 'none' == $q['orderby'] ) { $orderby = ''; } elseif ( $q['orderby'] == 'post__in' && ! empty( $post__in ) ) { $orderby = "FIELD( {$wpdb->posts}.ID, $post__in )"; } else { // Used to filter values $allowed_keys = array('name', 'author', 'date', 'title', 'modified', 'menu_order', 'parent', 'ID', 'rand', 'comment_count'); if ( !empty($q['meta_key']) ) { $allowed_keys[] = $q['meta_key']; $allowed_keys[] = 'meta_value'; $allowed_keys[] = 'meta_value_num'; } $q['orderby'] = urldecode($q['orderby']); $q['orderby'] = addslashes_gpc($q['orderby']); $orderby_array = array(); foreach ( explode( ' ', $q['orderby'] ) as $i => $orderby ) { // Only allow certain values for safety if ( ! in_array($orderby, $allowed_keys) ) continue; switch ( $orderby ) { case 'menu_order': $orderby = "$wpdb->posts.menu_order"; break; case 'ID': $orderby = "$wpdb->posts.ID"; break; case 'rand': $orderby = 'RAND()'; break; case $q['meta_key']: case 'meta_value': $orderby = "$wpdb->postmeta.meta_value"; break; case 'meta_value_num': $orderby = "$wpdb->postmeta.meta_value+0"; break; case 'comment_count': $orderby = "$wpdb->posts.comment_count"; break; default: $orderby = "$wpdb->posts.post_" . $orderby; } $orderby_array[] = $orderby; } $orderby = implode( ',', $orderby_array ); if ( empty( $orderby ) ) $orderby = "$wpdb->posts.post_date ".$q['order']; else $orderby .= " {$q['order']}"; } if ( is_array( $post_type ) ) { $post_type_cap = 'multiple_post_type'; } else { $post_type_object = get_post_type_object( $post_type ); if ( empty( $post_type_object ) ) $post_type_cap = $post_type; } if ( 'any' == $post_type ) { $in_search_post_types = get_post_types( array('exclude_from_search' => false) ); if ( ! empty( $in_search_post_types ) ) $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $in_search_post_types ) . "')"; } elseif ( !empty( $post_type ) && is_array( $post_type ) ) { $where .= " AND $wpdb->posts.post_type IN ('" . join("', '", $post_type) . "')"; } elseif ( ! empty( $post_type ) ) { $where .= " AND $wpdb->posts.post_type = '$post_type'"; $post_type_object = get_post_type_object ( $post_type ); } elseif ( $this->is_attachment ) { $where .= " AND $wpdb->posts.post_type = 'attachment'"; $post_type_object = get_post_type_object ( 'attachment' ); } elseif ( $this->is_page ) { $where .= " AND $wpdb->posts.post_type = 'page'"; $post_type_object = get_post_type_object ( 'page' ); } else { $where .= " AND $wpdb->posts.post_type = 'post'"; $post_type_object = get_post_type_object ( 'post' ); } if ( ! empty( $post_type_object ) ) { $edit_cap = $post_type_object->cap->edit_post; $read_cap = $post_type_object->cap->read_post; $edit_others_cap = $post_type_object->cap->edit_others_posts; $read_private_cap = $post_type_object->cap->read_private_posts; } else { $edit_cap = 'edit_' . $post_type_cap; $read_cap = 'read_' . $post_type_cap; $edit_others_cap = 'edit_others_' . $post_type_cap . 's'; $read_private_cap = 'read_private_' . $post_type_cap . 's'; } if ( ! empty( $q['post_status'] ) ) { $statuswheres = array(); $q_status = $q['post_status']; if ( ! is_array( $q_status ) ) $q_status = explode(',', $q_status); $r_status = array(); $p_status = array(); $e_status = array(); if ( in_array('any', $q_status) ) { foreach ( get_post_stati( array('exclude_from_search' => true) ) as $status ) $e_status[] = "$wpdb->posts.post_status <> '$status'"; } else { foreach ( get_post_stati() as $status ) { if ( in_array( $status, $q_status ) ) { if ( 'private' == $status ) $p_status[] = "$wpdb->posts.post_status = '$status'"; else $r_status[] = "$wpdb->posts.post_status = '$status'"; } } } if ( empty($q['perm'] ) || 'readable' != $q['perm'] ) { $r_status = array_merge($r_status, $p_status); unset($p_status); } if ( !empty($e_status) ) { $statuswheres[] = "(" . join( ' AND ', $e_status ) . ")"; } if ( !empty($r_status) ) { if ( !empty($q['perm'] ) && 'editable' == $q['perm'] && !current_user_can($edit_others_cap) ) $statuswheres[] = "($wpdb->posts.post_author = $user_ID " . "AND (" . join( ' OR ', $r_status ) . "))"; else $statuswheres[] = "(" . join( ' OR ', $r_status ) . ")"; } if ( !empty($p_status) ) { if ( !empty($q['perm'] ) && 'readable' == $q['perm'] && !current_user_can($read_private_cap) ) $statuswheres[] = "($wpdb->posts.post_author = $user_ID " . "AND (" . join( ' OR ', $p_status ) . "))"; else $statuswheres[] = "(" . join( ' OR ', $p_status ) . ")"; } if ( $post_status_join ) { $join .= " LEFT JOIN $wpdb->posts AS p2 ON ($wpdb->posts.post_parent = p2.ID) "; foreach ( $statuswheres as $index => $statuswhere ) $statuswheres[$index] = "($statuswhere OR ($wpdb->posts.post_status = 'inherit' AND " . str_replace($wpdb->posts, 'p2', $statuswhere) . "))"; } foreach ( $statuswheres as $statuswhere ) $where .= " AND $statuswhere"; } elseif ( !$this->is_singular ) { $where .= " AND ($wpdb->posts.post_status = 'publish'"; // Add public states. $public_states = get_post_stati( array('public' => true) ); foreach ( (array) $public_states as $state ) { if ( 'publish' == $state ) // Publish is hard-coded above. continue; $where .= " OR $wpdb->posts.post_status = '$state'"; } if ( $this->is_admin ) { // Add protected states that should show in the admin all list. $admin_all_states = get_post_stati( array('protected' => true, 'show_in_admin_all_list' => true) ); foreach ( (array) $admin_all_states as $state ) $where .= " OR $wpdb->posts.post_status = '$state'"; } if ( is_user_logged_in() ) { // Add private states that are limited to viewing by the author of a post or someone who has caps to read private states. $private_states = get_post_stati( array('private' => true) ); foreach ( (array) $private_states as $state ) $where .= current_user_can( $read_private_cap ) ? " OR $wpdb->posts.post_status = '$state'" : " OR $wpdb->posts.post_author = $user_ID AND $wpdb->posts.post_status = '$state'"; } $where .= ')'; } if ( !empty( $this->meta_query->queries ) ) { $clauses = $this->meta_query->get_sql( 'post', $wpdb->posts, 'ID', $this ); $join .= $clauses['join']; $where .= $clauses['where']; } // Apply filters on where and join prior to paging so that any // manipulations to them are reflected in the paging by day queries. if ( !$q['suppress_filters'] ) { $where = apply_filters_ref_array('posts_where', array( $where, &$this ) ); $join = apply_filters_ref_array('posts_join', array( $join, &$this ) ); } // Paging if ( empty($q['nopaging']) && !$this->is_singular ) { $page = absint($q['paged']); if ( !$page ) $page = 1; if ( empty($q['offset']) ) { $pgstrt = ($page - 1) * $q['posts_per_page'] . ', '; } else { // we're ignoring $page and using 'offset' $q['offset'] = absint($q['offset']); $pgstrt = $q['offset'] . ', '; } $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page']; } // Comments feeds if ( $this->is_comment_feed && ( $this->is_archive || $this->is_search || !$this->is_singular ) ) { if ( $this->is_archive || $this->is_search ) { $cjoin = "JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join "; $cwhere = "WHERE comment_approved = '1' $where"; $cgroupby = "$wpdb->comments.comment_id"; } else { // Other non singular e.g. front $cjoin = "JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )"; $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'"; $cgroupby = ''; } if ( !$q['suppress_filters'] ) { $cjoin = apply_filters_ref_array('comment_feed_join', array( $cjoin, &$this ) ); $cwhere = apply_filters_ref_array('comment_feed_where', array( $cwhere, &$this ) ); $cgroupby = apply_filters_ref_array('comment_feed_groupby', array( $cgroupby, &$this ) ); $corderby = apply_filters_ref_array('comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) ); $climits = apply_filters_ref_array('comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) ); } $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : ''; $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : ''; $this->comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits"); $this->comment_count = count($this->comments); $post_ids = array(); foreach ( $this->comments as $comment ) $post_ids[] = (int) $comment->comment_post_ID; $post_ids = join(',', $post_ids); $join = ''; if ( $post_ids ) $where = "AND $wpdb->posts.ID IN ($post_ids) "; else $where = "AND 0"; } $pieces = array( 'where', 'groupby', 'join', 'orderby', 'distinct', 'fields', 'limits' ); // Apply post-paging filters on where and join. Only plugins that // manipulate paging queries should use these hooks. if ( !$q['suppress_filters'] ) { $where = apply_filters_ref_array( 'posts_where_paged', array( $where, &$this ) ); $groupby = apply_filters_ref_array( 'posts_groupby', array( $groupby, &$this ) ); $join = apply_filters_ref_array( 'posts_join_paged', array( $join, &$this ) ); $orderby = apply_filters_ref_array( 'posts_orderby', array( $orderby, &$this ) ); $distinct = apply_filters_ref_array( 'posts_distinct', array( $distinct, &$this ) ); $limits = apply_filters_ref_array( 'post_limits', array( $limits, &$this ) ); $fields = apply_filters_ref_array( 'posts_fields', array( $fields, &$this ) ); // Filter all clauses at once, for convenience $clauses = (array) apply_filters_ref_array( 'posts_clauses', array( compact( $pieces ), &$this ) ); foreach ( $pieces as $piece ) $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : ''; } // Announce current selection parameters. For use by caching plugins. do_action( 'posts_selection', $where . $groupby . $orderby . $limits . $join ); // Filter again for the benefit of caching plugins. Regular plugins should use the hooks above. if ( !$q['suppress_filters'] ) { $where = apply_filters_ref_array( 'posts_where_request', array( $where, &$this ) ); $groupby = apply_filters_ref_array( 'posts_groupby_request', array( $groupby, &$this ) ); $join = apply_filters_ref_array( 'posts_join_request', array( $join, &$this ) ); $orderby = apply_filters_ref_array( 'posts_orderby_request', array( $orderby, &$this ) ); $distinct = apply_filters_ref_array( 'posts_distinct_request', array( $distinct, &$this ) ); $fields = apply_filters_ref_array( 'posts_fields_request', array( $fields, &$this ) ); $limits = apply_filters_ref_array( 'post_limits_request', array( $limits, &$this ) ); // Filter all clauses at once, for convenience $clauses = (array) apply_filters_ref_array( 'posts_clauses_request', array( compact( $pieces ), &$this ) ); foreach ( $pieces as $piece ) $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : ''; } if ( ! empty($groupby) ) $groupby = 'GROUP BY ' . $groupby; if ( !empty( $orderby ) ) $orderby = 'ORDER BY ' . $orderby; $found_rows = ''; if ( !$q['no_found_rows'] && !empty($limits) ) $found_rows = 'SQL_CALC_FOUND_ROWS'; $this->request = $old_request = "SELECT $found_rows $distinct $fields FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits"; if ( !$q['suppress_filters'] ) { $this->request = apply_filters_ref_array( 'posts_request', array( $this->request, &$this ) ); } if ( 'ids' == $q['fields'] ) { $this->posts = $wpdb->get_col( $this->request ); $this->post_count = count( $this->posts ); $this->set_found_posts( $q, $limits ); return $this->posts; } if ( 'id=>parent' == $q['fields'] ) { $this->posts = $wpdb->get_results( $this->request ); $this->post_count = count( $this->posts ); $this->set_found_posts( $q, $limits ); $r = array(); foreach ( $this->posts as $post ) $r[ $post->ID ] = $post->post_parent; return $r; } $split_the_query = ( $old_request == $this->request && "$wpdb->posts.*" == $fields && !empty( $limits ) && $q['posts_per_page'] < 500 ); $split_the_query = apply_filters( 'split_the_query', $split_the_query, $this ); if ( $split_the_query ) { // First get the IDs and then fill in the objects $this->request = "SELECT $found_rows $distinct $wpdb->posts.ID FROM $wpdb->posts $join WHERE 1=1 $where $groupby $orderby $limits"; $this->request = apply_filters( 'posts_request_ids', $this->request, $this ); $ids = $wpdb->get_col( $this->request ); if ( $ids ) { $this->posts = $ids; $this->set_found_posts( $q, $limits ); _prime_post_caches( $ids, $q['update_post_term_cache'], $q['update_post_meta_cache'] ); } else { $this->posts = array(); } } else { $this->posts = $wpdb->get_results( $this->request ); $this->set_found_posts( $q, $limits ); } // Convert to WP_Post objects if ( $this->posts ) $this->posts = array_map( 'get_post', $this->posts ); // Raw results filter. Prior to status checks. if ( !$q['suppress_filters'] ) $this->posts = apply_filters_ref_array('posts_results', array( $this->posts, &$this ) ); if ( !empty($this->posts) && $this->is_comment_feed && $this->is_singular ) { $cjoin = apply_filters_ref_array('comment_feed_join', array( '', &$this ) ); $cwhere = apply_filters_ref_array('comment_feed_where', array( "WHERE comment_post_ID = '{$this->posts[0]->ID}' AND comment_approved = '1'", &$this ) ); $cgroupby = apply_filters_ref_array('comment_feed_groupby', array( '', &$this ) ); $cgroupby = ( ! empty( $cgroupby ) ) ? 'GROUP BY ' . $cgroupby : ''; $corderby = apply_filters_ref_array('comment_feed_orderby', array( 'comment_date_gmt DESC', &$this ) ); $corderby = ( ! empty( $corderby ) ) ? 'ORDER BY ' . $corderby : ''; $climits = apply_filters_ref_array('comment_feed_limits', array( 'LIMIT ' . get_option('posts_per_rss'), &$this ) ); $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby $corderby $climits"; $this->comments = $wpdb->get_results($comments_request); $this->comment_count = count($this->comments); } // Check post status to determine if post should be displayed. if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) { $status = get_post_status($this->posts[0]); $post_status_obj = get_post_status_object($status); //$type = get_post_type($this->posts[0]); if ( !$post_status_obj->public ) { if ( ! is_user_logged_in() ) { // User must be logged in to view unpublished posts. $this->posts = array(); } else { if ( $post_status_obj->protected ) { // User must have edit permissions on the draft to preview. if ( ! current_user_can($edit_cap, $this->posts[0]->ID) ) { $this->posts = array(); } else { $this->is_preview = true; if ( 'future' != $status ) $this->posts[0]->post_date = current_time('mysql'); } } elseif ( $post_status_obj->private ) { if ( ! current_user_can($read_cap, $this->posts[0]->ID) ) $this->posts = array(); } else { $this->posts = array(); } } } if ( $this->is_preview && $this->posts && current_user_can( $edit_cap, $this->posts[0]->ID ) ) $this->posts[0] = get_post( apply_filters_ref_array( 'the_preview', array( $this->posts[0], &$this ) ) ); } // Put sticky posts at the top of the posts array $sticky_posts = get_option('sticky_posts'); if ( $this->is_home && $page <= 1 && is_array($sticky_posts) && !empty($sticky_posts) && !$q['ignore_sticky_posts'] ) { $num_posts = count($this->posts); $sticky_offset = 0; // Loop over posts and relocate stickies to the front. for ( $i = 0; $i < $num_posts; $i++ ) { if ( in_array($this->posts[$i]->ID, $sticky_posts) ) { $sticky_post = $this->posts[$i]; // Remove sticky from current position array_splice($this->posts, $i, 1); // Move to front, after other stickies array_splice($this->posts, $sticky_offset, 0, array($sticky_post)); // Increment the sticky offset. The next sticky will be placed at this offset. $sticky_offset++; // Remove post from sticky posts array $offset = array_search($sticky_post->ID, $sticky_posts); unset( $sticky_posts[$offset] ); } } // If any posts have been excluded specifically, Ignore those that are sticky. if ( !empty($sticky_posts) && !empty($q['post__not_in']) ) $sticky_posts = array_diff($sticky_posts, $q['post__not_in']); // Fetch sticky posts that weren't in the query results if ( !empty($sticky_posts) ) { $stickies = get_posts( array( 'post__in' => $sticky_posts, 'post_type' => $post_type, 'post_status' => 'publish', 'nopaging' => true ) ); foreach ( $stickies as $sticky_post ) { array_splice( $this->posts, $sticky_offset, 0, array( $sticky_post ) ); $sticky_offset++; } } } if ( !$q['suppress_filters'] ) $this->posts = apply_filters_ref_array('the_posts', array( $this->posts, &$this ) ); // Ensure that any posts added/modified via one of the filters above are // of the type WP_Post and are filtered. if ( $this->posts ) { $this->post_count = count( $this->posts ); $this->posts = array_map( 'get_post', $this->posts ); if ( $q['cache_results'] ) update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']); $this->post = reset( $this->posts ); } else { $this->post_count = 0; $this->posts = array(); } return $this->posts; } /** * Set up the amount of found posts and the number of pages (if limit clause was used) * for the current query. * * @since 3.5.0 * @access private */ function set_found_posts( $q, $limits ) { global $wpdb; // Bail if posts is an empty array. Continue if posts is an empty string // null, or false to accommodate caching plugins that fill posts later. if ( $q['no_found_rows'] || ( is_array( $this->posts ) && ! $this->posts ) ) return; if ( ! empty( $limits ) ) $this->found_posts = $wpdb->get_var( apply_filters_ref_array( 'found_posts_query', array( 'SELECT FOUND_ROWS()', &$this ) ) ); else $this->found_posts = count( $this->posts ); $this->found_posts = apply_filters_ref_array( 'found_posts', array( $this->found_posts, &$this ) ); if ( ! empty( $limits ) ) $this->max_num_pages = ceil( $this->found_posts / $q['posts_per_page'] ); } /** * Set up the next post and iterate current post index. * * @since 1.5.0 * @access public * * @return WP_Post Next post. */ function next_post() { $this->current_post++; $this->post = $this->posts[$this->current_post]; return $this->post; } /** * Sets up the current post. * * Retrieves the next post, sets up the post, sets the 'in the loop' * property to true. * * @since 1.5.0 * @access public * @uses $post * @uses do_action_ref_array() Calls 'loop_start' if loop has just started */ function the_post() { global $post; $this->in_the_loop = true; if ( $this->current_post == -1 ) // loop has just started do_action_ref_array('loop_start', array(&$this)); $post = $this->next_post(); setup_postdata($post); } /** * Whether there are more posts available in the loop. * * Calls action 'loop_end', when the loop is complete. * * @since 1.5.0 * @access public * @uses do_action_ref_array() Calls 'loop_end' if loop is ended * * @return bool True if posts are available, false if end of loop. */ function have_posts() { if ( $this->current_post + 1 < $this->post_count ) { return true; } elseif ( $this->current_post + 1 == $this->post_count && $this->post_count > 0 ) { do_action_ref_array('loop_end', array(&$this)); // Do some cleaning up after the loop $this->rewind_posts(); } $this->in_the_loop = false; return false; } /** * Rewind the posts and reset post index. * * @since 1.5.0 * @access public */ function rewind_posts() { $this->current_post = -1; if ( $this->post_count > 0 ) { $this->post = $this->posts[0]; } } /** * Iterate current comment index and return comment object. * * @since 2.2.0 * @access public * * @return object Comment object. */ function next_comment() { $this->current_comment++; $this->comment = $this->comments[$this->current_comment]; return $this->comment; } /** * Sets up the current comment. * * @since 2.2.0 * @access public * @global object $comment Current comment. * @uses do_action() Calls 'comment_loop_start' hook when first comment is processed. */ function the_comment() { global $comment; $comment = $this->next_comment(); if ( $this->current_comment == 0 ) { do_action('comment_loop_start'); } } /** * Whether there are more comments available. * * Automatically rewinds comments when finished. * * @since 2.2.0 * @access public * * @return bool True, if more comments. False, if no more posts. */ function have_comments() { if ( $this->current_comment + 1 < $this->comment_count ) { return true; } elseif ( $this->current_comment + 1 == $this->comment_count ) { $this->rewind_comments(); } return false; } /** * Rewind the comments, resets the comment index and comment to first. * * @since 2.2.0 * @access public */ function rewind_comments() { $this->current_comment = -1; if ( $this->comment_count > 0 ) { $this->comment = $this->comments[0]; } } /** * Sets up the WordPress query by parsing query string. * * @since 1.5.0 * @access public * * @param string $query URL query string. * @return array List of posts. */ function query( $query ) { $this->init(); $this->query = $this->query_vars = wp_parse_args( $query ); return $this->get_posts(); } /** * Retrieve queried object. * * If queried object is not set, then the queried object will be set from * the category, tag, taxonomy, posts page, single post, page, or author * query variable. After it is set up, it will be returned. * * @since 1.5.0 * @access public * * @return object */ function get_queried_object() { if ( isset($this->queried_object) ) return $this->queried_object; $this->queried_object = null; $this->queried_object_id = 0; if ( $this->is_category || $this->is_tag || $this->is_tax ) { $tax_query_in_and = wp_list_filter( $this->tax_query->queries, array( 'operator' => 'NOT IN' ), 'NOT' ); $query = reset( $tax_query_in_and ); if ( 'term_id' == $query['field'] ) $term = get_term( reset( $query['terms'] ), $query['taxonomy'] ); elseif ( $query['terms'] ) $term = get_term_by( $query['field'], reset( $query['terms'] ), $query['taxonomy'] ); if ( ! empty( $term ) && ! is_wp_error( $term ) ) { $this->queried_object = $term; $this->queried_object_id = (int) $term->term_id; if ( $this->is_category ) _make_cat_compat( $this->queried_object ); } } elseif ( $this->is_post_type_archive ) { $this->queried_object = get_post_type_object( $this->get('post_type') ); } elseif ( $this->is_posts_page ) { $page_for_posts = get_option('page_for_posts'); $this->queried_object = get_post( $page_for_posts ); $this->queried_object_id = (int) $this->queried_object->ID; } elseif ( $this->is_singular && !is_null($this->post) ) { $this->queried_object = $this->post; $this->queried_object_id = (int) $this->post->ID; } elseif ( $this->is_author ) { $this->queried_object_id = (int) $this->get('author'); $this->queried_object = get_userdata( $this->queried_object_id ); } return $this->queried_object; } /** * Retrieve ID of the current queried object. * * @since 1.5.0 * @access public * * @return int */ function get_queried_object_id() { $this->get_queried_object(); if ( isset($this->queried_object_id) ) { return $this->queried_object_id; } return 0; } /** * Constructor. * * Sets up the WordPress query, if parameter is not empty. * * @since 1.5.0 * @access public * * @param string $query URL query string. * @return WP_Query */ function __construct($query = '') { if ( ! empty($query) ) { $this->query($query); } } /** * Is the query for an existing archive page? * * Month, Year, Category, Author, Post Type archive... * * @since 3.1.0 * * @return bool */ function is_archive() { return (bool) $this->is_archive; } /** * Is the query for an existing post type archive page? * * @since 3.1.0 * * @param mixed $post_types Optional. Post type or array of posts types to check against. * @return bool */ function is_post_type_archive( $post_types = '' ) { if ( empty( $post_types ) || !$this->is_post_type_archive ) return (bool) $this->is_post_type_archive; $post_type_object = $this->get_queried_object(); return in_array( $post_type_object->name, (array) $post_types ); } /** * Is the query for an existing attachment page? * * @since 3.1.0 * * @return bool */ function is_attachment() { return (bool) $this->is_attachment; } /** * Is the query for an existing author archive page? * * If the $author parameter is specified, this function will additionally * check if the query is for one of the authors specified. * * @since 3.1.0 * * @param mixed $author Optional. User ID, nickname, nicename, or array of User IDs, nicknames, and nicenames * @return bool */ function is_author( $author = '' ) { if ( !$this->is_author ) return false; if ( empty($author) ) return true; $author_obj = $this->get_queried_object(); $author = (array) $author; if ( in_array( $author_obj->ID, $author ) ) return true; elseif ( in_array( $author_obj->nickname, $author ) ) return true; elseif ( in_array( $author_obj->user_nicename, $author ) ) return true; return false; } /** * Is the query for an existing category archive page? * * If the $category parameter is specified, this function will additionally * check if the query is for one of the categories specified. * * @since 3.1.0 * * @param mixed $category Optional. Category ID, name, slug, or array of Category IDs, names, and slugs. * @return bool */ function is_category( $category = '' ) { if ( !$this->is_category ) return false; if ( empty($category) ) return true; $cat_obj = $this->get_queried_object(); $category = (array) $category; if ( in_array( $cat_obj->term_id, $category ) ) return true; elseif ( in_array( $cat_obj->name, $category ) ) return true; elseif ( in_array( $cat_obj->slug, $category ) ) return true; return false; } /** * Is the query for an existing tag archive page? * * If the $tag parameter is specified, this function will additionally * check if the query is for one of the tags specified. * * @since 3.1.0 * * @param mixed $slug Optional. Tag slug or array of slugs. * @return bool */ function is_tag( $slug = '' ) { if ( !$this->is_tag ) return false; if ( empty( $slug ) ) return true; $tag_obj = $this->get_queried_object(); $slug = (array) $slug; if ( in_array( $tag_obj->slug, $slug ) ) return true; return false; } /** * Is the query for an existing taxonomy archive page? * * If the $taxonomy parameter is specified, this function will additionally * check if the query is for that specific $taxonomy. * * If the $term parameter is specified in addition to the $taxonomy parameter, * this function will additionally check if the query is for one of the terms * specified. * * @since 3.1.0 * * @param mixed $taxonomy Optional. Taxonomy slug or slugs. * @param mixed $term. Optional. Term ID, name, slug or array of Term IDs, names, and slugs. * @return bool */ function is_tax( $taxonomy = '', $term = '' ) { global $wp_taxonomies; if ( !$this->is_tax ) return false; if ( empty( $taxonomy ) ) return true; $queried_object = $this->get_queried_object(); $tax_array = array_intersect( array_keys( $wp_taxonomies ), (array) $taxonomy ); $term_array = (array) $term; // Check that the taxonomy matches. if ( ! ( isset( $queried_object->taxonomy ) && count( $tax_array ) && in_array( $queried_object->taxonomy, $tax_array ) ) ) return false; // Only a Taxonomy provided. if ( empty( $term ) ) return true; return isset( $queried_object->term_id ) && count( array_intersect( array( $queried_object->term_id, $queried_object->name, $queried_object->slug ), $term_array ) ); } /** * Whether the current URL is within the comments popup window. * * @since 3.1.0 * * @return bool */ function is_comments_popup() { return (bool) $this->is_comments_popup; } /** * Is the query for an existing date archive? * * @since 3.1.0 * * @return bool */ function is_date() { return (bool) $this->is_date; } /** * Is the query for an existing day archive? * * @since 3.1.0 * * @return bool */ function is_day() { return (bool) $this->is_day; } /** * Is the query for a feed? * * @since 3.1.0 * * @param string|array $feeds Optional feed types to check. * @return bool */ function is_feed( $feeds = '' ) { if ( empty( $feeds ) || ! $this->is_feed ) return (bool) $this->is_feed; $qv = $this->get( 'feed' ); if ( 'feed' == $qv ) $qv = get_default_feed(); return in_array( $qv, (array) $feeds ); } /** * Is the query for a comments feed? * * @since 3.1.0 * * @return bool */ function is_comment_feed() { return (bool) $this->is_comment_feed; } /** * Is the query for the front page of the site? * * This is for what is displayed at your site's main URL. * * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_on_front'. * * If you set a static page for the front page of your site, this function will return * true when viewing that page. * * Otherwise the same as @see WP_Query::is_home() * * @since 3.1.0 * @uses is_home() * @uses get_option() * * @return bool True, if front of site. */ function is_front_page() { // most likely case if ( 'posts' == get_option( 'show_on_front') && $this->is_home() ) return true; elseif ( 'page' == get_option( 'show_on_front') && get_option( 'page_on_front' ) && $this->is_page( get_option( 'page_on_front' ) ) ) return true; else return false; } /** * Is the query for the blog homepage? * * This is the page which shows the time based blog content of your site. * * Depends on the site's "Front page displays" Reading Settings 'show_on_front' and 'page_for_posts'. * * If you set a static page for the front page of your site, this function will return * true only on the page you set as the "Posts page". * * @see WP_Query::is_front_page() * * @since 3.1.0 * * @return bool True if blog view homepage. */ function is_home() { return (bool) $this->is_home; } /** * Is the query for an existing month archive? * * @since 3.1.0 * * @return bool */ function is_month() { return (bool) $this->is_month; } /** * Is the query for an existing single page? * * If the $page parameter is specified, this function will additionally * check if the query is for one of the pages specified. * * @see WP_Query::is_single() * @see WP_Query::is_singular() * * @since 3.1.0 * * @param mixed $page Page ID, title, slug, or array of such. * @return bool */ function is_page( $page = '' ) { if ( !$this->is_page ) return false; if ( empty( $page ) ) return true; $page_obj = $this->get_queried_object(); $page = (array) $page; if ( in_array( $page_obj->ID, $page ) ) return true; elseif ( in_array( $page_obj->post_title, $page ) ) return true; else if ( in_array( $page_obj->post_name, $page ) ) return true; return false; } /** * Is the query for paged result and not for the first page? * * @since 3.1.0 * * @return bool */ function is_paged() { return (bool) $this->is_paged; } /** * Is the query for a post or page preview? * * @since 3.1.0 * * @return bool */ function is_preview() { return (bool) $this->is_preview; } /** * Is the query for the robots file? * * @since 3.1.0 * * @return bool */ function is_robots() { return (bool) $this->is_robots; } /** * Is the query for a search? * * @since 3.1.0 * * @return bool */ function is_search() { return (bool) $this->is_search; } /** * Is the query for an existing single post? * * Works for any post type, except attachments and pages * * If the $post parameter is specified, this function will additionally * check if the query is for one of the Posts specified. * * @see WP_Query::is_page() * @see WP_Query::is_singular() * * @since 3.1.0 * * @param mixed $post Post ID, title, slug, or array of such. * @return bool */ function is_single( $post = '' ) { if ( !$this->is_single ) return false; if ( empty($post) ) return true; $post_obj = $this->get_queried_object(); $post = (array) $post; if ( in_array( $post_obj->ID, $post ) ) return true; elseif ( in_array( $post_obj->post_title, $post ) ) return true; elseif ( in_array( $post_obj->post_name, $post ) ) return true; return false; } /** * Is the query for an existing single post of any post type (post, attachment, page, ... )? * * If the $post_types parameter is specified, this function will additionally * check if the query is for one of the Posts Types specified. * * @see WP_Query::is_page() * @see WP_Query::is_single() * * @since 3.1.0 * * @param mixed $post_types Optional. Post Type or array of Post Types * @return bool */ function is_singular( $post_types = '' ) { if ( empty( $post_types ) || !$this->is_singular ) return (bool) $this->is_singular; $post_obj = $this->get_queried_object(); return in_array( $post_obj->post_type, (array) $post_types ); } /** * Is the query for a specific time? * * @since 3.1.0 * * @return bool */ function is_time() { return (bool) $this->is_time; } /** * Is the query for a trackback endpoint call? * * @since 3.1.0 * * @return bool */ function is_trackback() { return (bool) $this->is_trackback; } /** * Is the query for an existing year archive? * * @since 3.1.0 * * @return bool */ function is_year() { return (bool) $this->is_year; } /** * Is the query a 404 (returns no results)? * * @since 3.1.0 * * @return bool */ function is_404() { return (bool) $this->is_404; } /** * Is the query the main query? * * @since 3.3.0 * * @return bool */ function is_main_query() { global $wp_the_query; return $wp_the_query === $this; } } /** * Redirect old slugs to the correct permalink. * * Attempts to find the current slug from the past slugs. * * @since 2.1.0 * @uses $wp_query * @uses $wpdb * * @return null If no link is found, null is returned. */ function wp_old_slug_redirect() { global $wp_query; if ( is_404() && '' != $wp_query->query_vars['name'] ) : global $wpdb; // Guess the current post_type based on the query vars. if ( get_query_var('post_type') ) $post_type = get_query_var('post_type'); elseif ( !empty($wp_query->query_vars['pagename']) ) $post_type = 'page'; else $post_type = 'post'; if ( is_array( $post_type ) ) { if ( count( $post_type ) > 1 ) return; $post_type = array_shift( $post_type ); } // Do not attempt redirect for hierarchical post types if ( is_post_type_hierarchical( $post_type ) ) return; $query = $wpdb->prepare("SELECT post_id FROM $wpdb->postmeta, $wpdb->posts WHERE ID = post_id AND post_type = %s AND meta_key = '_wp_old_slug' AND meta_value = %s", $post_type, $wp_query->query_vars['name']); // if year, monthnum, or day have been specified, make our query more precise // just in case there are multiple identical _wp_old_slug values if ( '' != $wp_query->query_vars['year'] ) $query .= $wpdb->prepare(" AND YEAR(post_date) = %d", $wp_query->query_vars['year']); if ( '' != $wp_query->query_vars['monthnum'] ) $query .= $wpdb->prepare(" AND MONTH(post_date) = %d", $wp_query->query_vars['monthnum']); if ( '' != $wp_query->query_vars['day'] ) $query .= $wpdb->prepare(" AND DAYOFMONTH(post_date) = %d", $wp_query->query_vars['day']); $id = (int) $wpdb->get_var($query); if ( ! $id ) return; $link = get_permalink($id); if ( !$link ) return; wp_redirect( $link, 301 ); // Permanent redirect exit; endif; } /** * Set up global post data. * * @since 1.5.0 * * @param object $post Post data. * @uses do_action_ref_array() Calls 'the_post' * @return bool True when finished. */ function setup_postdata($post) { global $id, $authordata, $currentday, $currentmonth, $page, $pages, $multipage, $more, $numpages; $id = (int) $post->ID; $authordata = get_userdata($post->post_author); $currentday = mysql2date('d.m.y', $post->post_date, false); $currentmonth = mysql2date('m', $post->post_date, false); $numpages = 1; $page = get_query_var('page'); if ( !$page ) $page = 1; if ( is_single() || is_page() || is_feed() ) $more = 1; $content = $post->post_content; if ( strpos( $content, '<!--nextpage-->' ) ) { if ( $page > 1 ) $more = 1; $multipage = 1; $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content); $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content); $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content); $pages = explode('<!--nextpage-->', $content); $numpages = count($pages); } else { $pages = array( $post->post_content ); $multipage = 0; } do_action_ref_array('the_post', array(&$post)); return true; }
zyblog
trunk/zyblog/wp-includes/query.php
PHP
asf20
95,688
<?php /** * Multisite upload handler. * * @since 3.0.0 * * @package WordPress * @subpackage Multisite */ define( 'SHORTINIT', true ); require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' ); if( !is_multisite() ) die( 'Multisite support not enabled' ); ms_file_constants(); error_reporting( 0 ); if ( $current_blog->archived == '1' || $current_blog->spam == '1' || $current_blog->deleted == '1' ) { status_header( 404 ); die( '404 &#8212; File not found.' ); } $file = rtrim( BLOGUPLOADDIR, '/' ) . '/' . str_replace( '..', '', $_GET[ 'file' ] ); if ( !is_file( $file ) ) { status_header( 404 ); die( '404 &#8212; File not found.' ); } $mime = wp_check_filetype( $file ); if( false === $mime[ 'type' ] && function_exists( 'mime_content_type' ) ) $mime[ 'type' ] = mime_content_type( $file ); if( $mime[ 'type' ] ) $mimetype = $mime[ 'type' ]; else $mimetype = 'image/' . substr( $file, strrpos( $file, '.' ) + 1 ); header( 'Content-Type: ' . $mimetype ); // always send this if ( false === strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS' ) ) header( 'Content-Length: ' . filesize( $file ) ); // Optional support for X-Sendfile and X-Accel-Redirect if ( WPMU_ACCEL_REDIRECT ) { header( 'X-Accel-Redirect: ' . str_replace( WP_CONTENT_DIR, '', $file ) ); exit; } elseif ( WPMU_SENDFILE ) { header( 'X-Sendfile: ' . $file ); exit; } $last_modified = gmdate( 'D, d M Y H:i:s', filemtime( $file ) ); $etag = '"' . md5( $last_modified ) . '"'; header( "Last-Modified: $last_modified GMT" ); header( 'ETag: ' . $etag ); header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 100000000 ) . ' GMT' ); // Support for Conditional GET $client_etag = isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ? stripslashes( $_SERVER['HTTP_IF_NONE_MATCH'] ) : false; if( ! isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) ) $_SERVER['HTTP_IF_MODIFIED_SINCE'] = false; $client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ); // If string is empty, return 0. If not, attempt to parse into a timestamp $client_modified_timestamp = $client_last_modified ? strtotime( $client_last_modified ) : 0; // Make a timestamp for our most recent modification... $modified_timestamp = strtotime($last_modified); if ( ( $client_last_modified && $client_etag ) ? ( ( $client_modified_timestamp >= $modified_timestamp) && ( $client_etag == $etag ) ) : ( ( $client_modified_timestamp >= $modified_timestamp) || ( $client_etag == $etag ) ) ) { status_header( 304 ); exit; } // If we made it this far, just serve the file readfile( $file );
zyblog
trunk/zyblog/wp-includes/ms-files.php
PHP
asf20
2,553
<?php /** * The WordPress version string * * @global string $wp_version */ $wp_version = '3.5'; /** * Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema. * * @global int $wp_db_version */ $wp_db_version = 22441; /** * Holds the TinyMCE version * * @global string $tinymce_version */ $tinymce_version = '358-23156'; /** * Holds the required PHP version * * @global string $required_php_version */ $required_php_version = '5.2.4'; /** * Holds the required MySQL version * * @global string $required_mysql_version */ $required_mysql_version = '5.0'; $wp_local_package = 'zh_CN';
zyblog
trunk/zyblog/wp-includes/version.php
PHP
asf20
643
<?php /** * WordPress Category API * * @package WordPress */ /** * Retrieves all category IDs. * * @since 2.0.0 * @link http://codex.wordpress.org/Function_Reference/get_all_category_ids * * @return object List of all of the category IDs. */ function get_all_category_ids() { if ( ! $cat_ids = wp_cache_get( 'all_category_ids', 'category' ) ) { $cat_ids = get_terms( 'category', array('fields' => 'ids', 'get' => 'all') ); wp_cache_add( 'all_category_ids', $cat_ids, 'category' ); } return $cat_ids; } /** * Retrieve list of category objects. * * If you change the type to 'link' in the arguments, then the link categories * will be returned instead. Also all categories will be updated to be backwards * compatible with pre-2.3 plugins and themes. * * @since 2.1.0 * @see get_terms() Type of arguments that can be changed. * @link http://codex.wordpress.org/Function_Reference/get_categories * * @param string|array $args Optional. Change the defaults retrieving categories. * @return array List of categories. */ function get_categories( $args = '' ) { $defaults = array( 'taxonomy' => 'category' ); $args = wp_parse_args( $args, $defaults ); $taxonomy = apply_filters( 'get_categories_taxonomy', $args['taxonomy'], $args ); // Back compat if ( isset($args['type']) && 'link' == $args['type'] ) { _deprecated_argument( __FUNCTION__, '3.0', '' ); $taxonomy = $args['taxonomy'] = 'link_category'; } $categories = (array) get_terms( $taxonomy, $args ); foreach ( array_keys( $categories ) as $k ) _make_cat_compat( $categories[$k] ); return $categories; } /** * Retrieves category data given a category ID or category object. * * If you pass the $category parameter an object, which is assumed to be the * category row object retrieved the database. It will cache the category data. * * If you pass $category an integer of the category ID, then that category will * be retrieved from the database, if it isn't already cached, and pass it back. * * If you look at get_term(), then both types will be passed through several * filters and finally sanitized based on the $filter parameter value. * * The category will converted to maintain backwards compatibility. * * @since 1.5.1 * @uses get_term() Used to get the category data from the taxonomy. * * @param int|object $category Category ID or Category row object * @param string $output Optional. Constant OBJECT, ARRAY_A, or ARRAY_N * @param string $filter Optional. Default is raw or no WordPress defined filter will applied. * @return mixed Category data in type defined by $output parameter. */ function get_category( $category, $output = OBJECT, $filter = 'raw' ) { $category = get_term( $category, 'category', $output, $filter ); if ( is_wp_error( $category ) ) return $category; _make_cat_compat( $category ); return $category; } /** * Retrieve category based on URL containing the category slug. * * Breaks the $category_path parameter up to get the category slug. * * Tries to find the child path and will return it. If it doesn't find a * match, then it will return the first category matching slug, if $full_match, * is set to false. If it does not, then it will return null. * * It is also possible that it will return a WP_Error object on failure. Check * for it when using this function. * * @since 2.1.0 * * @param string $category_path URL containing category slugs. * @param bool $full_match Optional. Whether full path should be matched. * @param string $output Optional. Constant OBJECT, ARRAY_A, or ARRAY_N * @return null|object|array Null on failure. Type is based on $output value. */ function get_category_by_path( $category_path, $full_match = true, $output = OBJECT ) { $category_path = rawurlencode( urldecode( $category_path ) ); $category_path = str_replace( '%2F', '/', $category_path ); $category_path = str_replace( '%20', ' ', $category_path ); $category_paths = '/' . trim( $category_path, '/' ); $leaf_path = sanitize_title( basename( $category_paths ) ); $category_paths = explode( '/', $category_paths ); $full_path = ''; foreach ( (array) $category_paths as $pathdir ) $full_path .= ( $pathdir != '' ? '/' : '' ) . sanitize_title( $pathdir ); $categories = get_terms( 'category', array('get' => 'all', 'slug' => $leaf_path) ); if ( empty( $categories ) ) return null; foreach ( $categories as $category ) { $path = '/' . $leaf_path; $curcategory = $category; while ( ( $curcategory->parent != 0 ) && ( $curcategory->parent != $curcategory->term_id ) ) { $curcategory = get_term( $curcategory->parent, 'category' ); if ( is_wp_error( $curcategory ) ) return $curcategory; $path = '/' . $curcategory->slug . $path; } if ( $path == $full_path ) return get_category( $category->term_id, $output ); } // If full matching is not required, return the first cat that matches the leaf. if ( ! $full_match ) return get_category( $categories[0]->term_id, $output ); return null; } /** * Retrieve category object by category slug. * * @since 2.3.0 * * @param string $slug The category slug. * @return object Category data object */ function get_category_by_slug( $slug ) { $category = get_term_by( 'slug', $slug, 'category' ); if ( $category ) _make_cat_compat( $category ); return $category; } /** * Retrieve the ID of a category from its name. * * @since 1.0.0 * * @param string $cat_name Category name. * @return int 0, if failure and ID of category on success. */ function get_cat_ID( $cat_name ) { $cat = get_term_by( 'name', $cat_name, 'category' ); if ( $cat ) return $cat->term_id; return 0; } /** * Retrieve the name of a category from its ID. * * @since 1.0.0 * * @param int $cat_id Category ID * @return string Category name, or an empty string if category doesn't exist. */ function get_cat_name( $cat_id ) { $cat_id = (int) $cat_id; $category = get_category( $cat_id ); if ( ! $category || is_wp_error( $category ) ) return ''; return $category->name; } /** * Check if a category is an ancestor of another category. * * You can use either an id or the category object for both parameters. If you * use an integer the category will be retrieved. * * @since 2.1.0 * * @param int|object $cat1 ID or object to check if this is the parent category. * @param int|object $cat2 The child category. * @return bool Whether $cat2 is child of $cat1 */ function cat_is_ancestor_of( $cat1, $cat2 ) { return term_is_ancestor_of( $cat1, $cat2, 'category' ); } /** * Sanitizes category data based on context. * * @since 2.3.0 * @uses sanitize_term() See this function for what context are supported. * * @param object|array $category Category data * @param string $context Optional. Default is 'display'. * @return object|array Same type as $category with sanitized data for safe use. */ function sanitize_category( $category, $context = 'display' ) { return sanitize_term( $category, 'category', $context ); } /** * Sanitizes data in single category key field. * * @since 2.3.0 * @uses sanitize_term_field() See function for more details. * * @param string $field Category key to sanitize * @param mixed $value Category value to sanitize * @param int $cat_id Category ID * @param string $context What filter to use, 'raw', 'display', etc. * @return mixed Same type as $value after $value has been sanitized. */ function sanitize_category_field( $field, $value, $cat_id, $context ) { return sanitize_term_field( $field, $value, $cat_id, 'category', $context ); } /* Tags */ /** * Retrieves all post tags. * * @since 2.3.0 * @see get_terms() For list of arguments to pass. * @uses apply_filters() Calls 'get_tags' hook on array of tags and with $args. * * @param string|array $args Tag arguments to use when retrieving tags. * @return array List of tags. */ function get_tags( $args = '' ) { $tags = get_terms( 'post_tag', $args ); if ( empty( $tags ) ) { $return = array(); return $return; } $tags = apply_filters( 'get_tags', $tags, $args ); return $tags; } /** * Retrieve post tag by tag ID or tag object. * * If you pass the $tag parameter an object, which is assumed to be the tag row * object retrieved the database. It will cache the tag data. * * If you pass $tag an integer of the tag ID, then that tag will * be retrieved from the database, if it isn't already cached, and pass it back. * * If you look at get_term(), then both types will be passed through several * filters and finally sanitized based on the $filter parameter value. * * @since 2.3.0 * * @param int|object $tag * @param string $output Optional. Constant OBJECT, ARRAY_A, or ARRAY_N * @param string $filter Optional. Default is raw or no WordPress defined filter will applied. * @return object|array Return type based on $output value. */ function get_tag( $tag, $output = OBJECT, $filter = 'raw' ) { return get_term( $tag, 'post_tag', $output, $filter ); } /* Cache */ /** * Remove the category cache data based on ID. * * @since 2.1.0 * @uses clean_term_cache() Clears the cache for the category based on ID * * @param int $id Category ID */ function clean_category_cache( $id ) { clean_term_cache( $id, 'category' ); } /** * Update category structure to old pre 2.3 from new taxonomy structure. * * This function was added for the taxonomy support to update the new category * structure with the old category one. This will maintain compatibility with * plugins and themes which depend on the old key or property names. * * The parameter should only be passed a variable and not create the array or * object inline to the parameter. The reason for this is that parameter is * passed by reference and PHP will fail unless it has the variable. * * There is no return value, because everything is updated on the variable you * pass to it. This is one of the features with using pass by reference in PHP. * * @since 2.3.0 * @access private * * @param array|object $category Category Row object or array */ function _make_cat_compat( &$category ) { if ( is_object( $category ) ) { $category->cat_ID = &$category->term_id; $category->category_count = &$category->count; $category->category_description = &$category->description; $category->cat_name = &$category->name; $category->category_nicename = &$category->slug; $category->category_parent = &$category->parent; } elseif ( is_array( $category ) && isset( $category['term_id'] ) ) { $category['cat_ID'] = &$category['term_id']; $category['category_count'] = &$category['count']; $category['category_description'] = &$category['description']; $category['cat_name'] = &$category['name']; $category['category_nicename'] = &$category['slug']; $category['category_parent'] = &$category['parent']; } }
zyblog
trunk/zyblog/wp-includes/category.php
PHP
asf20
10,827
<?php /** * Navigation Menu functions * * @package WordPress * @subpackage Nav_Menus * @since 3.0.0 */ /** * Returns a navigation menu object. * * @since 3.0.0 * * @uses get_term * @uses get_term_by * * @param string $menu Menu id, slug or name * @return mixed false if $menu param isn't supplied or term does not exist, menu object if successful. */ function wp_get_nav_menu_object( $menu ) { if ( ! $menu ) return false; $menu_obj = get_term( $menu, 'nav_menu' ); if ( ! $menu_obj ) $menu_obj = get_term_by( 'slug', $menu, 'nav_menu' ); if ( ! $menu_obj ) $menu_obj = get_term_by( 'name', $menu, 'nav_menu' ); if ( ! $menu_obj ) $menu_obj = false; return $menu_obj; } /** * Check if the given ID is a navigation menu. * * Returns true if it is; false otherwise. * * @since 3.0.0 * * @param int|string $menu The menu to check (id, slug, or name) * @return bool Whether the menu exists. */ function is_nav_menu( $menu ) { if ( ! $menu ) return false; $menu_obj = wp_get_nav_menu_object( $menu ); if ( $menu_obj && ! is_wp_error( $menu_obj ) && ! empty( $menu_obj->taxonomy ) && 'nav_menu' == $menu_obj->taxonomy ) return true; return false; } /** * Register navigation menus for a theme. * * @since 3.0.0 * * @param array $locations Associative array of menu location identifiers (like a slug) and descriptive text. */ function register_nav_menus( $locations = array() ) { global $_wp_registered_nav_menus; add_theme_support( 'menus' ); $_wp_registered_nav_menus = array_merge( (array) $_wp_registered_nav_menus, $locations ); } /** * Unregisters a navigation menu for a theme. * * @param array $location the menu location identifier * * @return bool True on success, false on failure. */ function unregister_nav_menu( $location ) { global $_wp_registered_nav_menus; if ( is_array( $_wp_registered_nav_menus ) && isset( $_wp_registered_nav_menus[$location] ) ) { unset( $_wp_registered_nav_menus[$location] ); return true; } return false; } /** * Register a navigation menu for a theme. * * @since 3.0.0 * * @param string $location Menu location identifier, like a slug. * @param string $description Menu location descriptive text. */ function register_nav_menu( $location, $description ) { register_nav_menus( array( $location => $description ) ); } /** * Returns an array of all registered navigation menus in a theme * * @since 3.0.0 * @return array */ function get_registered_nav_menus() { global $_wp_registered_nav_menus; if ( isset( $_wp_registered_nav_menus ) ) return $_wp_registered_nav_menus; return array(); } /** * Returns an array with the registered navigation menu locations and the menu assigned to it * * @since 3.0.0 * @return array */ function get_nav_menu_locations() { return get_theme_mod( 'nav_menu_locations' ); } /** * Whether a registered nav menu location has a menu assigned to it. * * @since 3.0.0 * @param string $location Menu location identifier. * @return bool Whether location has a menu. */ function has_nav_menu( $location ) { $locations = get_nav_menu_locations(); return ( ! empty( $locations[ $location ] ) ); } /** * Determine whether the given ID is a nav menu item. * * @since 3.0.0 * * @param int $menu_item_id The ID of the potential nav menu item. * @return bool Whether the given ID is that of a nav menu item. */ function is_nav_menu_item( $menu_item_id = 0 ) { return ( ! is_wp_error( $menu_item_id ) && ( 'nav_menu_item' == get_post_type( $menu_item_id ) ) ); } /** * Create a Navigation Menu. * * @since 3.0.0 * * @param string $menu_name Menu Name * @return mixed Menu object on success|WP_Error on failure */ function wp_create_nav_menu( $menu_name ) { return wp_update_nav_menu_object( 0, array( 'menu-name' => $menu_name ) ); } /** * Delete a Navigation Menu. * * @since 3.0.0 * * @param string $menu name|id|slug * @return mixed Menu object on success|WP_Error on failure */ function wp_delete_nav_menu( $menu ) { $menu = wp_get_nav_menu_object( $menu ); if ( ! $menu ) return false; $menu_objects = get_objects_in_term( $menu->term_id, 'nav_menu' ); if ( ! empty( $menu_objects ) ) { foreach ( $menu_objects as $item ) { wp_delete_post( $item ); } } $result = wp_delete_term( $menu->term_id, 'nav_menu' ); if ( $result && !is_wp_error($result) ) do_action( 'wp_delete_nav_menu', $menu->term_id ); return $result; } /** * Save the properties of a menu or create a new menu with those properties. * * @since 3.0.0 * * @param int $menu_id The ID of the menu or "0" to create a new menu. * @param array $menu_data The array of menu data. * @return int|error object The menu's ID or WP_Error object. */ function wp_update_nav_menu_object( $menu_id = 0, $menu_data = array() ) { $menu_id = (int) $menu_id; $_menu = wp_get_nav_menu_object( $menu_id ); $args = array( 'description' => ( isset( $menu_data['description'] ) ? $menu_data['description'] : '' ), 'name' => ( isset( $menu_data['menu-name'] ) ? $menu_data['menu-name'] : '' ), 'parent' => ( isset( $menu_data['parent'] ) ? (int) $menu_data['parent'] : 0 ), 'slug' => null, ); // double-check that we're not going to have one menu take the name of another $_possible_existing = get_term_by( 'name', $menu_data['menu-name'], 'nav_menu' ); if ( $_possible_existing && ! is_wp_error( $_possible_existing ) && isset( $_possible_existing->term_id ) && $_possible_existing->term_id != $menu_id ) return new WP_Error( 'menu_exists', sprintf( __('The menu name <strong>%s</strong> conflicts with another menu name. Please try another.'), esc_html( $menu_data['menu-name'] ) ) ); // menu doesn't already exist, so create a new menu if ( ! $_menu || is_wp_error( $_menu ) ) { $menu_exists = get_term_by( 'name', $menu_data['menu-name'], 'nav_menu' ); if ( $menu_exists ) return new WP_Error( 'menu_exists', sprintf( __('The menu name <strong>%s</strong> conflicts with another menu name. Please try another.'), esc_html( $menu_data['menu-name'] ) ) ); $_menu = wp_insert_term( $menu_data['menu-name'], 'nav_menu', $args ); if ( is_wp_error( $_menu ) ) return $_menu; do_action( 'wp_create_nav_menu', $_menu['term_id'], $menu_data ); return (int) $_menu['term_id']; } if ( ! $_menu || ! isset( $_menu->term_id ) ) return 0; $menu_id = (int) $_menu->term_id; $update_response = wp_update_term( $menu_id, 'nav_menu', $args ); if ( is_wp_error( $update_response ) ) return $update_response; do_action( 'wp_update_nav_menu', $menu_id, $menu_data ); return $menu_id; } /** * Save the properties of a menu item or create a new one. * * @since 3.0.0 * * @param int $menu_id The ID of the menu. Required. If "0", makes the menu item a draft orphan. * @param int $menu_item_db_id The ID of the menu item. If "0", creates a new menu item. * @param array $menu_item_data The menu item's data. * @return int The menu item's database ID or WP_Error object on failure. */ function wp_update_nav_menu_item( $menu_id = 0, $menu_item_db_id = 0, $menu_item_data = array() ) { $menu_id = (int) $menu_id; $menu_item_db_id = (int) $menu_item_db_id; // make sure that we don't convert non-nav_menu_item objects into nav_menu_item objects if ( ! empty( $menu_item_db_id ) && ! is_nav_menu_item( $menu_item_db_id ) ) return new WP_Error('update_nav_menu_item_failed', __('The given object ID is not that of a menu item.')); $menu = wp_get_nav_menu_object( $menu_id ); if ( ( ! $menu && 0 !== $menu_id ) || is_wp_error( $menu ) ) return $menu; $defaults = array( 'menu-item-db-id' => $menu_item_db_id, 'menu-item-object-id' => 0, 'menu-item-object' => '', 'menu-item-parent-id' => 0, 'menu-item-position' => 0, 'menu-item-type' => 'custom', 'menu-item-title' => '', 'menu-item-url' => '', 'menu-item-description' => '', 'menu-item-attr-title' => '', 'menu-item-target' => '', 'menu-item-classes' => '', 'menu-item-xfn' => '', 'menu-item-status' => '', ); $args = wp_parse_args( $menu_item_data, $defaults ); if ( 0 == $menu_id ) { $args['menu-item-position'] = 1; } elseif ( 0 == (int) $args['menu-item-position'] ) { $menu_items = 0 == $menu_id ? array() : (array) wp_get_nav_menu_items( $menu_id, array( 'post_status' => 'publish,draft' ) ); $last_item = array_pop( $menu_items ); $args['menu-item-position'] = ( $last_item && isset( $last_item->menu_order ) ) ? 1 + $last_item->menu_order : count( $menu_items ); } $original_parent = 0 < $menu_item_db_id ? get_post_field( 'post_parent', $menu_item_db_id ) : 0; if ( 'custom' != $args['menu-item-type'] ) { /* if non-custom menu item, then: * use original object's URL * blank default title to sync with original object's */ $args['menu-item-url'] = ''; $original_title = ''; if ( 'taxonomy' == $args['menu-item-type'] ) { $original_parent = get_term_field( 'parent', $args['menu-item-object-id'], $args['menu-item-object'], 'raw' ); $original_title = get_term_field( 'name', $args['menu-item-object-id'], $args['menu-item-object'], 'raw' ); } elseif ( 'post_type' == $args['menu-item-type'] ) { $original_object = get_post( $args['menu-item-object-id'] ); $original_parent = (int) $original_object->post_parent; $original_title = $original_object->post_title; } if ( empty( $args['menu-item-title'] ) || $args['menu-item-title'] == $original_title ) { $args['menu-item-title'] = ''; // hack to get wp to create a post object when too many properties are empty if ( empty( $args['menu-item-description'] ) ) $args['menu-item-description'] = ' '; } } // Populate the menu item object $post = array( 'menu_order' => $args['menu-item-position'], 'ping_status' => 0, 'post_content' => $args['menu-item-description'], 'post_excerpt' => $args['menu-item-attr-title'], 'post_parent' => $original_parent, 'post_title' => $args['menu-item-title'], 'post_type' => 'nav_menu_item', ); $update = 0 != $menu_item_db_id; // Only set the menu term if it isn't set to avoid unnecessary wp_get_object_terms() if ( $menu_id && ( ! $update || ! is_object_in_term( $menu_item_db_id, 'nav_menu', (int) $menu->term_id ) ) ) $post['tax_input'] = array( 'nav_menu' => array( intval( $menu->term_id ) ) ); // New menu item. Default is draft status if ( ! $update ) { $post['ID'] = 0; $post['post_status'] = 'publish' == $args['menu-item-status'] ? 'publish' : 'draft'; $menu_item_db_id = wp_insert_post( $post ); if ( ! $menu_item_db_id || is_wp_error( $menu_item_db_id ) ) return $menu_item_db_id; } if ( 'custom' == $args['menu-item-type'] ) { $args['menu-item-object-id'] = $menu_item_db_id; $args['menu-item-object'] = 'custom'; } $menu_item_db_id = (int) $menu_item_db_id; update_post_meta( $menu_item_db_id, '_menu_item_type', sanitize_key($args['menu-item-type']) ); update_post_meta( $menu_item_db_id, '_menu_item_menu_item_parent', strval( (int) $args['menu-item-parent-id'] ) ); update_post_meta( $menu_item_db_id, '_menu_item_object_id', strval( (int) $args['menu-item-object-id'] ) ); update_post_meta( $menu_item_db_id, '_menu_item_object', sanitize_key($args['menu-item-object']) ); update_post_meta( $menu_item_db_id, '_menu_item_target', sanitize_key($args['menu-item-target']) ); $args['menu-item-classes'] = array_map( 'sanitize_html_class', explode( ' ', $args['menu-item-classes'] ) ); $args['menu-item-xfn'] = implode( ' ', array_map( 'sanitize_html_class', explode( ' ', $args['menu-item-xfn'] ) ) ); update_post_meta( $menu_item_db_id, '_menu_item_classes', $args['menu-item-classes'] ); update_post_meta( $menu_item_db_id, '_menu_item_xfn', $args['menu-item-xfn'] ); update_post_meta( $menu_item_db_id, '_menu_item_url', esc_url_raw($args['menu-item-url']) ); if ( 0 == $menu_id ) update_post_meta( $menu_item_db_id, '_menu_item_orphaned', (string) time() ); elseif ( get_post_meta( $menu_item_db_id, '_menu_item_orphaned' ) ) delete_post_meta( $menu_item_db_id, '_menu_item_orphaned' ); // Update existing menu item. Default is publish status if ( $update ) { $post['ID'] = $menu_item_db_id; $post['post_status'] = 'draft' == $args['menu-item-status'] ? 'draft' : 'publish'; wp_update_post( $post ); } do_action('wp_update_nav_menu_item', $menu_id, $menu_item_db_id, $args ); return $menu_item_db_id; } /** * Returns all navigation menu objects. * * @since 3.0.0 * * @param array $args Array of arguments passed on to get_terms(). * @return array menu objects */ function wp_get_nav_menus( $args = array() ) { $defaults = array( 'hide_empty' => false, 'orderby' => 'none' ); $args = wp_parse_args( $args, $defaults ); return apply_filters( 'wp_get_nav_menus', get_terms( 'nav_menu', $args), $args ); } /** * Sort menu items by the desired key. * * @since 3.0.0 * @access private * * @param object $a The first object to compare * @param object $b The second object to compare * @return int -1, 0, or 1 if $a is considered to be respectively less than, equal to, or greater than $b. */ function _sort_nav_menu_items( $a, $b ) { global $_menu_item_sort_prop; if ( empty( $_menu_item_sort_prop ) ) return 0; if ( ! isset( $a->$_menu_item_sort_prop ) || ! isset( $b->$_menu_item_sort_prop ) ) return 0; $_a = (int) $a->$_menu_item_sort_prop; $_b = (int) $b->$_menu_item_sort_prop; if ( $a->$_menu_item_sort_prop == $b->$_menu_item_sort_prop ) return 0; elseif ( $_a == $a->$_menu_item_sort_prop && $_b == $b->$_menu_item_sort_prop ) return $_a < $_b ? -1 : 1; else return strcmp( $a->$_menu_item_sort_prop, $b->$_menu_item_sort_prop ); } /** * Returns if a menu item is valid. Bug #13958 * * @since 3.2.0 * @access private * * @param object $menu_item The menu item to check * @return bool false if invalid, else true. */ function _is_valid_nav_menu_item( $item ) { if ( ! empty( $item->_invalid ) ) return false; return true; } /** * Returns all menu items of a navigation menu. * * @since 3.0.0 * * @param string $menu menu name, id, or slug * @param string $args * @return mixed $items array of menu items, else false. */ function wp_get_nav_menu_items( $menu, $args = array() ) { global $_wp_using_ext_object_cache; $menu = wp_get_nav_menu_object( $menu ); if ( ! $menu ) return false; static $fetched = array(); $items = get_objects_in_term( $menu->term_id, 'nav_menu' ); if ( empty( $items ) ) return $items; $defaults = array( 'order' => 'ASC', 'orderby' => 'menu_order', 'post_type' => 'nav_menu_item', 'post_status' => 'publish', 'output' => ARRAY_A, 'output_key' => 'menu_order', 'nopaging' => true ); $args = wp_parse_args( $args, $defaults ); if ( count( $items ) > 1 ) $args['include'] = implode( ',', $items ); else $args['include'] = $items[0]; $items = get_posts( $args ); if ( is_wp_error( $items ) || ! is_array( $items ) ) return false; // Get all posts and terms at once to prime the caches if ( empty( $fetched[$menu->term_id] ) || $_wp_using_ext_object_cache ) { $fetched[$menu->term_id] = true; $posts = array(); $terms = array(); foreach ( $items as $item ) { $object_id = get_post_meta( $item->ID, '_menu_item_object_id', true ); $object = get_post_meta( $item->ID, '_menu_item_object', true ); $type = get_post_meta( $item->ID, '_menu_item_type', true ); if ( 'post_type' == $type ) $posts[$object][] = $object_id; elseif ( 'taxonomy' == $type) $terms[$object][] = $object_id; } if ( ! empty( $posts ) ) { foreach ( array_keys($posts) as $post_type ) { get_posts( array('post__in' => $posts[$post_type], 'post_type' => $post_type, 'nopaging' => true, 'update_post_term_cache' => false) ); } } unset($posts); if ( ! empty( $terms ) ) { foreach ( array_keys($terms) as $taxonomy ) { get_terms($taxonomy, array('include' => $terms[$taxonomy]) ); } } unset($terms); } $items = array_map( 'wp_setup_nav_menu_item', $items ); if ( ! is_admin() ) // Remove invalid items only in frontend $items = array_filter( $items, '_is_valid_nav_menu_item' ); if ( ARRAY_A == $args['output'] ) { $GLOBALS['_menu_item_sort_prop'] = $args['output_key']; usort($items, '_sort_nav_menu_items'); $i = 1; foreach( $items as $k => $item ) { $items[$k]->$args['output_key'] = $i++; } } return apply_filters( 'wp_get_nav_menu_items', $items, $menu, $args ); } /** * Decorates a menu item object with the shared navigation menu item properties. * * Properties: * - db_id: The DB ID of this item as a nav_menu_item object, if it exists (0 if it doesn't exist). * - object_id: The DB ID of the original object this menu item represents, e.g. ID for posts and term_id for categories. * - type: The family of objects originally represented, such as "post_type" or "taxonomy." * - object: The type of object originally represented, such as "category," "post", or "attachment." * - type_label: The singular label used to describe this type of menu item. * - post_parent: The DB ID of the original object's parent object, if any (0 otherwise). * - menu_item_parent: The DB ID of the nav_menu_item that is this item's menu parent, if any. 0 otherwise. * - url: The URL to which this menu item points. * - title: The title of this menu item. * - target: The target attribute of the link element for this menu item. * - attr_title: The title attribute of the link element for this menu item. * - classes: The array of class attribute values for the link element of this menu item. * - xfn: The XFN relationship expressed in the link of this menu item. * - description: The description of this menu item. * * @since 3.0.0 * * @param object $menu_item The menu item to modify. * @return object $menu_item The menu item with standard menu item properties. */ function wp_setup_nav_menu_item( $menu_item ) { if ( isset( $menu_item->post_type ) ) { if ( 'nav_menu_item' == $menu_item->post_type ) { $menu_item->db_id = (int) $menu_item->ID; $menu_item->menu_item_parent = empty( $menu_item->menu_item_parent ) ? get_post_meta( $menu_item->ID, '_menu_item_menu_item_parent', true ) : $menu_item->menu_item_parent; $menu_item->object_id = empty( $menu_item->object_id ) ? get_post_meta( $menu_item->ID, '_menu_item_object_id', true ) : $menu_item->object_id; $menu_item->object = empty( $menu_item->object ) ? get_post_meta( $menu_item->ID, '_menu_item_object', true ) : $menu_item->object; $menu_item->type = empty( $menu_item->type ) ? get_post_meta( $menu_item->ID, '_menu_item_type', true ) : $menu_item->type; if ( 'post_type' == $menu_item->type ) { $object = get_post_type_object( $menu_item->object ); if ( $object ) { $menu_item->type_label = $object->labels->singular_name; } else { $menu_item->type_label = $menu_item->object; $menu_item->_invalid = true; } $menu_item->url = get_permalink( $menu_item->object_id ); $original_object = get_post( $menu_item->object_id ); $original_title = $original_object->post_title; $menu_item->title = '' == $menu_item->post_title ? $original_title : $menu_item->post_title; } elseif ( 'taxonomy' == $menu_item->type ) { $object = get_taxonomy( $menu_item->object ); if ( $object ) { $menu_item->type_label = $object->labels->singular_name; } else { $menu_item->type_label = $menu_item->object; $menu_item->_invalid = true; } $term_url = get_term_link( (int) $menu_item->object_id, $menu_item->object ); $menu_item->url = !is_wp_error( $term_url ) ? $term_url : ''; $original_title = get_term_field( 'name', $menu_item->object_id, $menu_item->object, 'raw' ); if ( is_wp_error( $original_title ) ) $original_title = false; $menu_item->title = '' == $menu_item->post_title ? $original_title : $menu_item->post_title; } else { $menu_item->type_label = __('Custom'); $menu_item->title = $menu_item->post_title; $menu_item->url = empty( $menu_item->url ) ? get_post_meta( $menu_item->ID, '_menu_item_url', true ) : $menu_item->url; } $menu_item->target = empty( $menu_item->target ) ? get_post_meta( $menu_item->ID, '_menu_item_target', true ) : $menu_item->target; $menu_item->attr_title = empty( $menu_item->attr_title ) ? apply_filters( 'nav_menu_attr_title', $menu_item->post_excerpt ) : $menu_item->attr_title; if ( empty( $menu_item->description ) ) $menu_item->description = apply_filters( 'nav_menu_description', wp_trim_words( $menu_item->post_content, 200 ) ); $menu_item->classes = empty( $menu_item->classes ) ? (array) get_post_meta( $menu_item->ID, '_menu_item_classes', true ) : $menu_item->classes; $menu_item->xfn = empty( $menu_item->xfn ) ? get_post_meta( $menu_item->ID, '_menu_item_xfn', true ) : $menu_item->xfn; } else { $menu_item->db_id = 0; $menu_item->menu_item_parent = 0; $menu_item->object_id = (int) $menu_item->ID; $menu_item->type = 'post_type'; $object = get_post_type_object( $menu_item->post_type ); $menu_item->object = $object->name; $menu_item->type_label = $object->labels->singular_name; $menu_item->title = $menu_item->post_title; $menu_item->url = get_permalink( $menu_item->ID ); $menu_item->target = ''; $menu_item->attr_title = apply_filters( 'nav_menu_attr_title', '' ); $menu_item->description = apply_filters( 'nav_menu_description', '' ); $menu_item->classes = array(); $menu_item->xfn = ''; } } elseif ( isset( $menu_item->taxonomy ) ) { $menu_item->ID = $menu_item->term_id; $menu_item->db_id = 0; $menu_item->menu_item_parent = 0; $menu_item->object_id = (int) $menu_item->term_id; $menu_item->post_parent = (int) $menu_item->parent; $menu_item->type = 'taxonomy'; $object = get_taxonomy( $menu_item->taxonomy ); $menu_item->object = $object->name; $menu_item->type_label = $object->labels->singular_name; $menu_item->title = $menu_item->name; $menu_item->url = get_term_link( $menu_item, $menu_item->taxonomy ); $menu_item->target = ''; $menu_item->attr_title = ''; $menu_item->description = get_term_field( 'description', $menu_item->term_id, $menu_item->taxonomy ); $menu_item->classes = array(); $menu_item->xfn = ''; } return apply_filters( 'wp_setup_nav_menu_item', $menu_item ); } /** * Get the menu items associated with a particular object. * * @since 3.0.0 * * @param int $object_id The ID of the original object. * @param string $object_type The type of object, such as "taxonomy" or "post_type." * @return array The array of menu item IDs; empty array if none; */ function wp_get_associated_nav_menu_items( $object_id = 0, $object_type = 'post_type' ) { $object_id = (int) $object_id; $menu_item_ids = array(); $query = new WP_Query; $menu_items = $query->query( array( 'meta_key' => '_menu_item_object_id', 'meta_value' => $object_id, 'post_status' => 'any', 'post_type' => 'nav_menu_item', 'posts_per_page' => -1, ) ); foreach( (array) $menu_items as $menu_item ) { if ( isset( $menu_item->ID ) && is_nav_menu_item( $menu_item->ID ) ) { if ( get_post_meta( $menu_item->ID, '_menu_item_type', true ) != $object_type ) continue; $menu_item_ids[] = (int) $menu_item->ID; } } return array_unique( $menu_item_ids ); } /** * Callback for handling a menu item when its original object is deleted. * * @since 3.0.0 * @access private * * @param int $object_id The ID of the original object being trashed. * */ function _wp_delete_post_menu_item( $object_id = 0 ) { $object_id = (int) $object_id; $menu_item_ids = wp_get_associated_nav_menu_items( $object_id, 'post_type' ); foreach( (array) $menu_item_ids as $menu_item_id ) { wp_delete_post( $menu_item_id, true ); } } /** * Callback for handling a menu item when its original object is deleted. * * @since 3.0.0 * @access private * * @param int $object_id The ID of the original object being trashed. * */ function _wp_delete_tax_menu_item( $object_id = 0 ) { $object_id = (int) $object_id; $menu_item_ids = wp_get_associated_nav_menu_items( $object_id, 'taxonomy' ); foreach( (array) $menu_item_ids as $menu_item_id ) { wp_delete_post( $menu_item_id, true ); } } /** * Automatically add newly published page objects to menus with that as an option. * * @since 3.0.0 * @access private * * @param string $new_status The new status of the post object. * @param string $old_status The old status of the post object. * @param object $post The post object being transitioned from one status to another. * @return void */ function _wp_auto_add_pages_to_menu( $new_status, $old_status, $post ) { if ( 'publish' != $new_status || 'publish' == $old_status || 'page' != $post->post_type ) return; if ( ! empty( $post->post_parent ) ) return; $auto_add = get_option( 'nav_menu_options' ); if ( empty( $auto_add ) || ! is_array( $auto_add ) || ! isset( $auto_add['auto_add'] ) ) return; $auto_add = $auto_add['auto_add']; if ( empty( $auto_add ) || ! is_array( $auto_add ) ) return; $args = array( 'menu-item-object-id' => $post->ID, 'menu-item-object' => $post->post_type, 'menu-item-type' => 'post_type', 'menu-item-status' => 'publish', ); foreach ( $auto_add as $menu_id ) { $items = wp_get_nav_menu_items( $menu_id, array( 'post_status' => 'publish,draft' ) ); if ( ! is_array( $items ) ) continue; foreach ( $items as $item ) { if ( $post->ID == $item->object_id ) continue 2; } wp_update_nav_menu_item( $menu_id, 0, $args ); } }
zyblog
trunk/zyblog/wp-includes/nav-menu.php
PHP
asf20
25,638
<?php /** * Site/blog functions that work with the blogs table and related data. * * @package WordPress * @subpackage Multisite * @since MU */ /** * Update the last_updated field for the current blog. * * @since MU */ function wpmu_update_blogs_date() { global $wpdb; update_blog_details( $wpdb->blogid, array('last_updated' => current_time('mysql', true)) ); do_action( 'wpmu_blog_updated', $wpdb->blogid ); } /** * Get a full blog URL, given a blog id. * * @since MU * * @param int $blog_id Blog ID * @return string */ function get_blogaddress_by_id( $blog_id ) { $bloginfo = get_blog_details( (int) $blog_id, false ); // only get bare details! return esc_url( 'http://' . $bloginfo->domain . $bloginfo->path ); } /** * Get a full blog URL, given a blog name. * * @since MU * * @param string $blogname The (subdomain or directory) name * @return string */ function get_blogaddress_by_name( $blogname ) { global $current_site; if ( is_subdomain_install() ) { if ( $blogname == 'main' ) $blogname = 'www'; $url = rtrim( network_home_url(), '/' ); if ( !empty( $blogname ) ) $url = preg_replace( '|^([^\.]+://)|', '$1' . $blogname . '.', $url ); } else { $url = network_home_url( $blogname ); } return esc_url( $url . '/' ); } /** * Get a full blog URL, given a domain and a path. * * @since MU * * @param string $domain * @param string $path * @return string */ function get_blogaddress_by_domain( $domain, $path ) { if ( is_subdomain_install() ) { $url = "http://" . $domain.$path; } else { if ( $domain != $_SERVER['HTTP_HOST'] ) { $blogname = substr( $domain, 0, strpos( $domain, '.' ) ); $url = 'http://' . substr( $domain, strpos( $domain, '.' ) + 1 ) . $path; // we're not installing the main blog if ( $blogname != 'www.' ) $url .= $blogname . '/'; } else { // main blog $url = 'http://' . $domain . $path; } } return esc_url( $url ); } /** * Given a blog's (subdomain or directory) slug, retrieve it's id. * * @since MU * * @param string $slug * @return int A blog id */ function get_id_from_blogname( $slug ) { global $wpdb, $current_site; $slug = trim( $slug, '/' ); $blog_id = wp_cache_get( 'get_id_from_blogname_' . $slug, 'blog-details' ); if ( $blog_id ) return $blog_id; if ( is_subdomain_install() ) { $domain = $slug . '.' . $current_site->domain; $path = $current_site->path; } else { $domain = $current_site->domain; $path = $current_site->path . $slug . '/'; } $blog_id = $wpdb->get_var( $wpdb->prepare("SELECT blog_id FROM {$wpdb->blogs} WHERE domain = %s AND path = %s", $domain, $path) ); wp_cache_set( 'get_id_from_blogname_' . $slug, $blog_id, 'blog-details' ); return $blog_id; } /** * Retrieve the details for a blog from the blogs table and blog options. * * @since MU * * @param int|string|array $fields A blog ID, a blog slug, or an array of fields to query against. Optional. If not specified the current blog ID is used. * @param bool $get_all Whether to retrieve all details or only the details in the blogs table. Default is true. * @return object Blog details. */ function get_blog_details( $fields = null, $get_all = true ) { global $wpdb; if ( is_array($fields ) ) { if ( isset($fields['blog_id']) ) { $blog_id = $fields['blog_id']; } elseif ( isset($fields['domain']) && isset($fields['path']) ) { $key = md5( $fields['domain'] . $fields['path'] ); $blog = wp_cache_get($key, 'blog-lookup'); if ( false !== $blog ) return $blog; if ( substr( $fields['domain'], 0, 4 ) == 'www.' ) { $nowww = substr( $fields['domain'], 4 ); $blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain IN (%s,%s) AND path = %s ORDER BY CHAR_LENGTH(domain) DESC", $nowww, $fields['domain'], $fields['path'] ) ); } else { $blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s AND path = %s", $fields['domain'], $fields['path'] ) ); } if ( $blog ) { wp_cache_set($blog->blog_id . 'short', $blog, 'blog-details'); $blog_id = $blog->blog_id; } else { return false; } } elseif ( isset($fields['domain']) && is_subdomain_install() ) { $key = md5( $fields['domain'] ); $blog = wp_cache_get($key, 'blog-lookup'); if ( false !== $blog ) return $blog; if ( substr( $fields['domain'], 0, 4 ) == 'www.' ) { $nowww = substr( $fields['domain'], 4 ); $blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain IN (%s,%s) ORDER BY CHAR_LENGTH(domain) DESC", $nowww, $fields['domain'] ) ); } else { $blog = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE domain = %s", $fields['domain'] ) ); } if ( $blog ) { wp_cache_set($blog->blog_id . 'short', $blog, 'blog-details'); $blog_id = $blog->blog_id; } else { return false; } } else { return false; } } else { if ( ! $fields ) $blog_id = get_current_blog_id(); elseif ( ! is_numeric( $fields ) ) $blog_id = get_id_from_blogname( $fields ); else $blog_id = $fields; } $blog_id = (int) $blog_id; $all = $get_all == true ? '' : 'short'; $details = wp_cache_get( $blog_id . $all, 'blog-details' ); if ( $details ) { if ( ! is_object( $details ) ) { if ( $details == -1 ) { return false; } else { // Clear old pre-serialized objects. Cache clients do better with that. wp_cache_delete( $blog_id . $all, 'blog-details' ); unset($details); } } else { return $details; } } // Try the other cache. if ( $get_all ) { $details = wp_cache_get( $blog_id . 'short', 'blog-details' ); } else { $details = wp_cache_get( $blog_id, 'blog-details' ); // If short was requested and full cache is set, we can return. if ( $details ) { if ( ! is_object( $details ) ) { if ( $details == -1 ) { return false; } else { // Clear old pre-serialized objects. Cache clients do better with that. wp_cache_delete( $blog_id, 'blog-details' ); unset($details); } } else { return $details; } } } if ( empty($details) ) { $details = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->blogs WHERE blog_id = %d /* get_blog_details */", $blog_id ) ); if ( ! $details ) { // Set the full cache. wp_cache_set( $blog_id, -1, 'blog-details' ); return false; } } if ( ! $get_all ) { wp_cache_set( $blog_id . $all, $details, 'blog-details' ); return $details; } switch_to_blog( $blog_id ); $details->blogname = get_option( 'blogname' ); $details->siteurl = get_option( 'siteurl' ); $details->post_count = get_option( 'post_count' ); restore_current_blog(); $details = apply_filters( 'blog_details', $details ); wp_cache_set( $blog_id . $all, $details, 'blog-details' ); $key = md5( $details->domain . $details->path ); wp_cache_set( $key, $details, 'blog-lookup' ); return $details; } /** * Clear the blog details cache. * * @since MU * * @param int $blog_id Blog ID */ function refresh_blog_details( $blog_id ) { $blog_id = (int) $blog_id; $details = get_blog_details( $blog_id, false ); clean_blog_cache( $details ); do_action( 'refresh_blog_details', $blog_id ); } /** * Update the details for a blog. Updates the blogs table for a given blog id. * * @since MU * * @param int $blog_id Blog ID * @param array $details Array of details keyed by blogs table field names. * @return bool True if update succeeds, false otherwise. */ function update_blog_details( $blog_id, $details = array() ) { global $wpdb; if ( empty($details) ) return false; if ( is_object($details) ) $details = get_object_vars($details); $current_details = get_blog_details($blog_id, false); if ( empty($current_details) ) return false; $current_details = get_object_vars($current_details); $details = array_merge($current_details, $details); $details['last_updated'] = current_time('mysql', true); $update_details = array(); $fields = array( 'site_id', 'domain', 'path', 'registered', 'last_updated', 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id'); foreach ( array_intersect( array_keys( $details ), $fields ) as $field ) $update_details[$field] = $details[$field]; $result = $wpdb->update( $wpdb->blogs, $update_details, array('blog_id' => $blog_id) ); if ( false === $result ) return false; // If spam status changed, issue actions. if ( $details[ 'spam' ] != $current_details[ 'spam' ] ) { if ( $details[ 'spam' ] == 1 ) do_action( 'make_spam_blog', $blog_id ); else do_action( 'make_ham_blog', $blog_id ); } // If mature status changed, issue actions. if ( $details[ 'mature' ] != $current_details[ 'mature' ] ) { if ( $details[ 'mature' ] == 1 ) do_action( 'mature_blog', $blog_id ); else do_action( 'unmature_blog', $blog_id ); } // If archived status changed, issue actions. if ( $details[ 'archived' ] != $current_details[ 'archived' ] ) { if ( $details[ 'archived' ] == 1 ) do_action( 'archive_blog', $blog_id ); else do_action( 'unarchive_blog', $blog_id ); } // If deleted status changed, issue actions. if ( $details[ 'deleted' ] != $current_details[ 'deleted' ] ) { if ( $details[ 'deleted' ] == 1 ) do_action( 'make_delete_blog', $blog_id ); else do_action( 'make_undelete_blog', $blog_id ); } if ( isset( $details[ 'public' ] ) ) { switch_to_blog( $blog_id ); update_option( 'blog_public', $details[ 'public' ] ); restore_current_blog(); } refresh_blog_details($blog_id); return true; } /** * Clean the blog cache * * @since 3.5.0 * * @param stdClass $blog The blog details as returned from get_blog_details() */ function clean_blog_cache( $blog ) { $blog_id = $blog->blog_id; $domain_path_key = md5( $blog->domain . $blog->path ); wp_cache_delete( $blog_id , 'blog-details' ); wp_cache_delete( $blog_id . 'short' , 'blog-details' ); wp_cache_delete( $domain_path_key, 'blog-lookup' ); wp_cache_delete( 'current_blog_' . $blog->domain, 'site-options' ); wp_cache_delete( 'current_blog_' . $blog->domain . $blog->path, 'site-options' ); wp_cache_delete( 'get_id_from_blogname_' . trim( $blog->path, '/' ), 'blog-details' ); wp_cache_delete( $domain_path_key, 'blog-id-cache' ); } /** * Retrieve option value for a given blog id based on name of option. * * If the option does not exist or does not have a value, then the return value * will be false. This is useful to check whether you need to install an option * and is commonly used during installation of plugin options and to test * whether upgrading is required. * * If the option was serialized then it will be unserialized when it is returned. * * @since MU * * @param int $id A blog ID. Can be null to refer to the current blog. * @param string $option Name of option to retrieve. Expected to not be SQL-escaped. * @param mixed $default Optional. Default value to return if the option does not exist. * @return mixed Value set for the option. */ function get_blog_option( $id, $option, $default = false ) { $id = (int) $id; if ( empty( $id ) ) $id = get_current_blog_id(); if ( get_current_blog_id() == $id ) return get_option( $option, $default ); switch_to_blog( $id ); $value = get_option( $option, $default ); restore_current_blog(); return apply_filters( 'blog_option_' . $option, $value, $id ); } /** * Add a new option for a given blog id. * * You do not need to serialize values. If the value needs to be serialized, then * it will be serialized before it is inserted into the database. Remember, * resources can not be serialized or added as an option. * * You can create options without values and then update the values later. * Existing options will not be updated and checks are performed to ensure that you * aren't adding a protected WordPress option. Care should be taken to not name * options the same as the ones which are protected. * * @since MU * * @param int $id A blog ID. Can be null to refer to the current blog. * @param string $option Name of option to add. Expected to not be SQL-escaped. * @param mixed $value Optional. Option value, can be anything. Expected to not be SQL-escaped. * @return bool False if option was not added and true if option was added. */ function add_blog_option( $id, $option, $value ) { $id = (int) $id; if ( empty( $id ) ) $id = get_current_blog_id(); if ( get_current_blog_id() == $id ) return add_option( $option, $value ); switch_to_blog( $id ); $return = add_option( $option, $value ); restore_current_blog(); return $return; } /** * Removes option by name for a given blog id. Prevents removal of protected WordPress options. * * @since MU * * @param int $id A blog ID. Can be null to refer to the current blog. * @param string $option Name of option to remove. Expected to not be SQL-escaped. * @return bool True, if option is successfully deleted. False on failure. */ function delete_blog_option( $id, $option ) { $id = (int) $id; if ( empty( $id ) ) $id = get_current_blog_id(); if ( get_current_blog_id() == $id ) return delete_option( $option ); switch_to_blog( $id ); $return = delete_option( $option ); restore_current_blog(); return $return; } /** * Update an option for a particular blog. * * @since MU * * @param int $id The blog id * @param string $option The option key * @param mixed $value The option value * @return bool True on success, false on failrue. */ function update_blog_option( $id, $option, $value, $deprecated = null ) { $id = (int) $id; if ( null !== $deprecated ) _deprecated_argument( __FUNCTION__, '3.1' ); if ( get_current_blog_id() == $id ) return update_option( $option, $value ); switch_to_blog( $id ); $return = update_option( $option, $value ); restore_current_blog(); refresh_blog_details( $id ); return $return; } /** * Switch the current blog. * * This function is useful if you need to pull posts, or other information, * from other blogs. You can switch back afterwards using restore_current_blog(). * * Things that aren't switched: * - autoloaded options. See #14992 * - plugins. See #14941 * * @see restore_current_blog() * @since MU * * @param int $new_blog The id of the blog you want to switch to. Default: current blog * @param bool $deprecated Deprecated argument * @return bool True on success, false if the validation failed */ function switch_to_blog( $new_blog, $deprecated = null ) { global $wpdb, $wp_roles; if ( empty( $new_blog ) ) $new_blog = $GLOBALS['blog_id']; $GLOBALS['_wp_switched_stack'][] = $GLOBALS['blog_id']; /* If we're switching to the same blog id that we're on, * set the right vars, do the associated actions, but skip * the extra unnecessary work */ if ( $new_blog == $GLOBALS['blog_id'] ) { do_action( 'switch_blog', $new_blog, $new_blog ); $GLOBALS['switched'] = true; return true; } $wpdb->set_blog_id( $new_blog ); $GLOBALS['table_prefix'] = $wpdb->prefix; $prev_blog_id = $GLOBALS['blog_id']; $GLOBALS['blog_id'] = $new_blog; if ( function_exists( 'wp_cache_switch_to_blog' ) ) { wp_cache_switch_to_blog( $new_blog ); } else { global $wp_object_cache; if ( is_object( $wp_object_cache ) && isset( $wp_object_cache->global_groups ) ) $global_groups = $wp_object_cache->global_groups; else $global_groups = false; wp_cache_init(); if ( function_exists( 'wp_cache_add_global_groups' ) ) { if ( is_array( $global_groups ) ) wp_cache_add_global_groups( $global_groups ); else wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'user_meta', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts', ' blog-id-cache' ) ); wp_cache_add_non_persistent_groups( array( 'comment', 'counts', 'plugins' ) ); } } if ( did_action( 'init' ) ) { $wp_roles->reinit(); $current_user = wp_get_current_user(); $current_user->for_blog( $new_blog ); } do_action( 'switch_blog', $new_blog, $prev_blog_id ); $GLOBALS['switched'] = true; return true; } /** * Restore the current blog, after calling switch_to_blog() * * @see switch_to_blog() * @since MU * * @return bool True on success, false if we're already on the current blog */ function restore_current_blog() { global $wpdb, $wp_roles; if ( empty( $GLOBALS['_wp_switched_stack'] ) ) return false; $blog = array_pop( $GLOBALS['_wp_switched_stack'] ); if ( $GLOBALS['blog_id'] == $blog ) { do_action( 'switch_blog', $blog, $blog ); // If we still have items in the switched stack, consider ourselves still 'switched' $GLOBALS['switched'] = ! empty( $GLOBALS['_wp_switched_stack'] ); return true; } $wpdb->set_blog_id( $blog ); $prev_blog_id = $GLOBALS['blog_id']; $GLOBALS['blog_id'] = $blog; $GLOBALS['table_prefix'] = $wpdb->prefix; if ( function_exists( 'wp_cache_switch_to_blog' ) ) { wp_cache_switch_to_blog( $blog ); } else { global $wp_object_cache; if ( is_object( $wp_object_cache ) && isset( $wp_object_cache->global_groups ) ) $global_groups = $wp_object_cache->global_groups; else $global_groups = false; wp_cache_init(); if ( function_exists( 'wp_cache_add_global_groups' ) ) { if ( is_array( $global_groups ) ) wp_cache_add_global_groups( $global_groups ); else wp_cache_add_global_groups( array( 'users', 'userlogins', 'usermeta', 'user_meta', 'site-transient', 'site-options', 'site-lookup', 'blog-lookup', 'blog-details', 'rss', 'global-posts', ' blog-id-cache' ) ); wp_cache_add_non_persistent_groups( array( 'comment', 'counts', 'plugins' ) ); } } if ( did_action( 'init' ) ) { $wp_roles->reinit(); $current_user = wp_get_current_user(); $current_user->for_blog( $blog ); } do_action( 'switch_blog', $blog, $prev_blog_id ); // If we still have items in the switched stack, consider ourselves still 'switched' $GLOBALS['switched'] = ! empty( $GLOBALS['_wp_switched_stack'] ); return true; } /** * Determines if switch_to_blog() is in effect * * @since 3.5.0 * * @return bool True if switched, false otherwise. */ function ms_is_switched() { return ! empty( $GLOBALS['_wp_switched_stack'] ); } /** * Check if a particular blog is archived. * * @since MU * * @param int $id The blog id * @return string Whether the blog is archived or not */ function is_archived( $id ) { return get_blog_status($id, 'archived'); } /** * Update the 'archived' status of a particular blog. * * @since MU * * @param int $id The blog id * @param string $archived The new status * @return string $archived */ function update_archived( $id, $archived ) { update_blog_status($id, 'archived', $archived); return $archived; } /** * Update a blog details field. * * @since MU * * @param int $blog_id BLog ID * @param string $pref A field name * @param string $value Value for $pref * @return string $value */ function update_blog_status( $blog_id, $pref, $value, $deprecated = null ) { global $wpdb; if ( null !== $deprecated ) _deprecated_argument( __FUNCTION__, '3.1' ); if ( ! in_array( $pref, array( 'site_id', 'domain', 'path', 'registered', 'last_updated', 'public', 'archived', 'mature', 'spam', 'deleted', 'lang_id') ) ) return $value; $result = $wpdb->update( $wpdb->blogs, array($pref => $value, 'last_updated' => current_time('mysql', true)), array('blog_id' => $blog_id) ); if ( false === $result ) return false; refresh_blog_details( $blog_id ); if ( 'spam' == $pref ) ( $value == 1 ) ? do_action( 'make_spam_blog', $blog_id ) : do_action( 'make_ham_blog', $blog_id ); elseif ( 'mature' == $pref ) ( $value == 1 ) ? do_action( 'mature_blog', $blog_id ) : do_action( 'unmature_blog', $blog_id ); elseif ( 'archived' == $pref ) ( $value == 1 ) ? do_action( 'archive_blog', $blog_id ) : do_action( 'unarchive_blog', $blog_id ); elseif ( 'deleted' == $pref ) ( $value == 1 ) ? do_action( 'make_delete_blog', $blog_id ) : do_action( 'make_undelete_blog', $blog_id ); return $value; } /** * Get a blog details field. * * @since MU * * @param int $id The blog id * @param string $pref A field name * @return bool $value */ function get_blog_status( $id, $pref ) { global $wpdb; $details = get_blog_details( $id, false ); if ( $details ) return $details->$pref; return $wpdb->get_var( $wpdb->prepare("SELECT %s FROM {$wpdb->blogs} WHERE blog_id = %d", $pref, $id) ); } /** * Get a list of most recently updated blogs. * * @since MU * * @param mixed $deprecated Not used * @param int $start The offset * @param int $quantity The maximum number of blogs to retrieve. Default is 40. * @return array The list of blogs */ function get_last_updated( $deprecated = '', $start = 0, $quantity = 40 ) { global $wpdb; if ( ! empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, 'MU' ); // never used return $wpdb->get_results( $wpdb->prepare("SELECT blog_id, domain, path FROM $wpdb->blogs WHERE site_id = %d AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0' AND last_updated != '0000-00-00 00:00:00' ORDER BY last_updated DESC limit %d, %d", $wpdb->siteid, $start, $quantity ) , ARRAY_A ); } /** * Handler for updating the blog date when a post is published or an already published post is changed. * * @since 3.3.0 * * @param string $new_status The new post status * @param string $old_status The old post status * @param object $post Post object */ function _update_blog_date_on_post_publish( $new_status, $old_status, $post ) { $post_type_obj = get_post_type_object( $post->post_type ); if ( ! $post_type_obj->public ) return; if ( 'publish' != $new_status && 'publish' != $old_status ) return; // Post was freshly published, published post was saved, or published post was unpublished. wpmu_update_blogs_date(); } /** * Handler for updating the blog date when a published post is deleted. * * @since 3.4.0 * * @param int $post_id Post ID */ function _update_blog_date_on_post_delete( $post_id ) { $post = get_post( $post_id ); $post_type_obj = get_post_type_object( $post->post_type ); if ( ! $post_type_obj->public ) return; if ( 'publish' != $post->post_status ) return; wpmu_update_blogs_date(); }
zyblog
trunk/zyblog/wp-includes/ms-blogs.php
PHP
asf20
22,249
<?php /** * @package WordPress * @subpackage Theme_Compat * @deprecated 3.0 * * This file is here for Backwards compatibility with old themes and will be removed in a future version * */ _deprecated_file( sprintf( __( 'Theme without %1$s' ), basename(__FILE__) ), '3.0', null, sprintf( __('Please include a %1$s template in your theme.'), basename(__FILE__) ) ); ?><!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?php printf(__('%1$s - Comments on %2$s'), get_option('blogname'), the_title('','',false)); ?></title> <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php echo get_option('blog_charset'); ?>" /> <style type="text/css" media="screen"> @import url( <?php bloginfo('stylesheet_url'); ?> ); body { margin: 3px; } </style> </head> <body id="commentspopup"> <h1 id="header"><a href="" title="<?php echo get_option('blogname'); ?>"><?php echo get_option('blogname'); ?></a></h1> <?php /* Don't remove these lines. */ add_filter('comment_text', 'popuplinks'); if ( have_posts() ) : while( have_posts()) : the_post(); ?> <h2 id="comments"><?php _e('Comments'); ?></h2> <p><a href="<?php echo esc_url( get_post_comments_feed_link($post->ID) ); ?>"><?php _e('<abbr title="Really Simple Syndication">RSS</abbr> feed for comments on this post.'); ?></a></p> <?php if ( pings_open() ) { ?> <p><?php printf(__('The <abbr title="Universal Resource Locator">URL</abbr> to TrackBack this entry is: <em>%s</em>'), get_trackback_url()); ?></p> <?php } ?> <?php // this line is WordPress' motor, do not delete it. $commenter = wp_get_current_commenter(); extract($commenter); $comments = get_approved_comments($id); $post = get_post($id); if ( post_password_required($post) ) { // and it doesn't match the cookie echo(get_the_password_form()); } else { ?> <?php if ($comments) { ?> <ol id="commentlist"> <?php foreach ($comments as $comment) { ?> <li id="comment-<?php comment_ID() ?>"> <?php comment_text() ?> <p><cite><?php comment_type(); ?> <?php printf(__('by %1$s &#8212; %2$s @ <a href="#comment-%3$s">%4$s</a>'), get_comment_author_link(), get_comment_date(), get_comment_ID(), get_comment_time()); ?></cite></p> </li> <?php } // end for each comment ?> </ol> <?php } else { // this is displayed if there are no comments so far ?> <p><?php _e('No comments yet.'); ?></p> <?php } ?> <?php if ( comments_open() ) { ?> <h2><?php _e('Leave a comment'); ?></h2> <p><?php printf(__('Line and paragraph breaks automatic, e-mail address never displayed, <acronym title="Hypertext Markup Language">HTML</acronym> allowed: <code>%s</code>'), allowed_tags()); ?></p> <form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform"> <?php if ( $user_ID ) : ?> <p><?php printf(__('Logged in as <a href="%1$s">%2$s</a>. <a href="%3$s" title="Log out of this account">Log out &raquo;</a>'), get_edit_user_link(), $user_identity, wp_logout_url(get_permalink())); ?></p> <?php else : ?> <p> <input type="text" name="author" id="author" class="textarea" value="<?php echo esc_attr($comment_author); ?>" size="28" tabindex="1" /> <label for="author"><?php _e('Name'); ?></label> </p> <p> <input type="text" name="email" id="email" value="<?php echo esc_attr($comment_author_email); ?>" size="28" tabindex="2" /> <label for="email"><?php _e('E-mail'); ?></label> </p> <p> <input type="text" name="url" id="url" value="<?php echo esc_attr($comment_author_url); ?>" size="28" tabindex="3" /> <label for="url"><?php _e('<abbr title="Universal Resource Locator">URL</abbr>'); ?></label> </p> <?php endif; ?> <p> <label for="comment"><?php _e('Your Comment'); ?></label> <br /> <textarea name="comment" id="comment" cols="70" rows="4" tabindex="4"></textarea> </p> <p> <input type="hidden" name="comment_post_ID" value="<?php echo $id; ?>" /> <input type="hidden" name="redirect_to" value="<?php echo esc_attr($_SERVER["REQUEST_URI"]); ?>" /> <input name="submit" type="submit" tabindex="5" value="<?php esc_attr_e('Say It!' ); ?>" /> </p> <?php do_action('comment_form', $post->ID); ?> </form> <?php } else { // comments are closed ?> <p><?php _e('Sorry, the comment form is closed at this time.'); ?></p> <?php } } // end password check ?> <div><strong><a href="javascript:window.close()"><?php _e('Close this window.'); ?></a></strong></div> <?php // if you delete this the sky will fall on your head endwhile; // have_posts() else: // have_posts() ?> <p><?php _e('Sorry, no posts matched your criteria.'); ?></p> <?php endif; ?> <!-- // this is just the end of the motor - don't touch that line either :) --> <?php //} ?> <p class="credit"><?php timer_stop(1); ?> <cite><?php printf(__('Powered by <a href="%s" title="Powered by WordPress, state-of-the-art semantic personal publishing platform"><strong>WordPress</strong></a>'), 'http://wordpress.org/'); ?></cite></p> <?php // Seen at http://www.mijnkopthee.nl/log2/archive/2003/05/28/esc(18) ?> <script type="text/javascript"> <!-- document.onkeypress = function esc(e) { if(typeof(e) == "undefined") { e=event; } if (e.keyCode == 27) { self.close(); } } // --> </script> </body> </html>
zyblog
trunk/zyblog/wp-includes/theme-compat/comments-popup.php
PHP
asf20
5,217
<?php /** * @package WordPress * @subpackage Theme_Compat * @deprecated 3.0 * * This file is here for Backwards compatibility with old themes and will be removed in a future version * */ _deprecated_file( sprintf( __( 'Theme without %1$s' ), basename(__FILE__) ), '3.0', null, sprintf( __('Please include a %1$s template in your theme.'), basename(__FILE__) ) ); ?> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" /> <title><?php wp_title('&laquo;', true, 'right'); ?> <?php bloginfo('name'); ?></title> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css" media="screen" /> <link rel="pingback" href="<?php bloginfo('pingback_url'); ?>" /> <style type="text/css" media="screen"> <?php // Checks to see whether it needs a sidebar if ( empty($withcomments) && !is_single() ) { ?> #page { background: url("<?php bloginfo('stylesheet_directory'); ?>/images/kubrickbg-<?php bloginfo('text_direction'); ?>.jpg") repeat-y top; border: none; } <?php } else { // No sidebar ?> #page { background: url("<?php bloginfo('stylesheet_directory'); ?>/images/kubrickbgwide.jpg") repeat-y top; border: none; } <?php } ?> </style> <?php if ( is_singular() ) wp_enqueue_script( 'comment-reply' ); ?> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <div id="page"> <div id="header" role="banner"> <div id="headerimg"> <h1><a href="<?php echo home_url(); ?>/"><?php bloginfo('name'); ?></a></h1> <div class="description"><?php bloginfo('description'); ?></div> </div> </div> <hr />
zyblog
trunk/zyblog/wp-includes/theme-compat/header.php
PHP
asf20
1,723
<?php /** * @package WordPress * @subpackage Theme_Compat * @deprecated 3.0 * * This file is here for Backwards compatibility with old themes and will be removed in a future version * */ _deprecated_file( sprintf( __( 'Theme without %1$s' ), basename(__FILE__) ), '3.0', null, sprintf( __('Please include a %1$s template in your theme.'), basename(__FILE__) ) ); ?> <div id="sidebar" role="complementary"> <ul> <?php /* Widgetized sidebar, if you have the plugin installed. */ if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?> <li> <?php get_search_form(); ?> </li> <!-- Author information is disabled per default. Uncomment and fill in your details if you want to use it. <li><h2><?php _e('Author'); ?></h2> <p>A little something about you, the author. Nothing lengthy, just an overview.</p> </li> --> <?php if ( is_404() || is_category() || is_day() || is_month() || is_year() || is_search() || is_paged() ) { ?> <li> <?php /* If this is a 404 page */ if (is_404()) { ?> <?php /* If this is a category archive */ } elseif (is_category()) { ?> <p><?php printf(__('You are currently browsing the archives for the %s category.'), single_cat_title('', false)); ?></p> <?php /* If this is a daily archive */ } elseif (is_day()) { ?> <p><?php printf(__('You are currently browsing the <a href="%1$s/">%2$s</a> blog archives for the day %3$s.'), get_bloginfo('url'), get_bloginfo('name'), get_the_time(__('l, F jS, Y'))); ?></p> <?php /* If this is a monthly archive */ } elseif (is_month()) { ?> <p><?php printf(__('You are currently browsing the <a href="%1$s/">%2$s</a> blog archives for %3$s.'), get_bloginfo('url'), get_bloginfo('name'), get_the_time(__('F, Y'))); ?></p> <?php /* If this is a yearly archive */ } elseif (is_year()) { ?> <p><?php printf(__('You are currently browsing the <a href="%1$s/">%2$s</a> blog archives for the year %3$s.'), get_bloginfo('url'), get_bloginfo('name'), get_the_time('Y')); ?></p> <?php /* If this is a search result */ } elseif (is_search()) { ?> <p><?php printf(__('You have searched the <a href="%1$s/">%2$s</a> blog archives for <strong>&#8216;%3$s&#8217;</strong>. If you are unable to find anything in these search results, you can try one of these links.'), get_bloginfo('url'), get_bloginfo('name'), esc_html( get_search_query() ) ); ?></p> <?php /* If this set is paginated */ } elseif (isset($_GET['paged']) && !empty($_GET['paged'])) { ?> <p><?php printf(__('You are currently browsing the <a href="%1$s/">%2$s</a> blog archives.'), get_bloginfo('url'), get_bloginfo('name')); ?></p> <?php } ?> </li> <?php }?> </ul> <ul role="navigation"> <?php wp_list_pages('title_li=<h2>' . __('Pages') . '</h2>' ); ?> <li><h2><?php _e('Archives'); ?></h2> <ul> <?php wp_get_archives(array('type' => 'monthly')); ?> </ul> </li> <?php wp_list_categories(array('show_count' => 1, 'title_li' => '<h2>' . __('Categories') . '</h2>')); ?> </ul> <ul> <?php /* If this is the frontpage */ if ( is_home() || is_page() ) { ?> <?php wp_list_bookmarks(); ?> <li><h2><?php _e('Meta'); ?></h2> <ul> <?php wp_register(); ?> <li><?php wp_loginout(); ?></li> <li><a href="http://validator.w3.org/check/referer" title="<?php esc_attr_e('This page validates as XHTML 1.0 Transitional'); ?>"><?php _e('Valid <abbr title="eXtensible HyperText Markup Language">XHTML</abbr>'); ?></a></li> <li><a href="http://gmpg.org/xfn/"><abbr title="<?php esc_attr_e('XHTML Friends Network'); ?>"><?php _e('XFN'); ?></abbr></a></li> <li><a href="http://wordpress.org/" title="<?php esc_attr_e('Powered by WordPress, state-of-the-art semantic personal publishing platform.'); ?>">WordPress</a></li> <?php wp_meta(); ?> </ul> </li> <?php } ?> <?php endif; ?> </ul> </div>
zyblog
trunk/zyblog/wp-includes/theme-compat/sidebar.php
PHP
asf20
3,904
<?php /** * @package WordPress * @subpackage Theme_Compat * @deprecated 3.0 * * This file is here for Backwards compatibility with old themes and will be removed in a future version * */ _deprecated_file( sprintf( __( 'Theme without %1$s' ), basename(__FILE__) ), '3.0', null, sprintf( __('Please include a %1$s template in your theme.'), basename(__FILE__) ) ); // Do not delete these lines if (!empty($_SERVER['SCRIPT_FILENAME']) && 'comments.php' == basename($_SERVER['SCRIPT_FILENAME'])) die ('Please do not load this page directly. Thanks!'); if ( post_password_required() ) { ?> <p class="nocomments"><?php _e('This post is password protected. Enter the password to view comments.'); ?></p> <?php return; } ?> <!-- You can start editing here. --> <?php if ( have_comments() ) : ?> <h3 id="comments"><?php printf( _n( 'One Response to %2$s', '%1$s Responses to %2$s', get_comments_number() ), number_format_i18n( get_comments_number() ), '&#8220;' . get_the_title() . '&#8221;' ); ?></h3> <div class="navigation"> <div class="alignleft"><?php previous_comments_link() ?></div> <div class="alignright"><?php next_comments_link() ?></div> </div> <ol class="commentlist"> <?php wp_list_comments();?> </ol> <div class="navigation"> <div class="alignleft"><?php previous_comments_link() ?></div> <div class="alignright"><?php next_comments_link() ?></div> </div> <?php else : // this is displayed if there are no comments so far ?> <?php if ( comments_open() ) : ?> <!-- If comments are open, but there are no comments. --> <?php else : // comments are closed ?> <!-- If comments are closed. --> <p class="nocomments"><?php _e('Comments are closed.'); ?></p> <?php endif; ?> <?php endif; ?> <?php if ( comments_open() ) : ?> <div id="respond"> <h3><?php comment_form_title( __('Leave a Reply'), __('Leave a Reply to %s' ) ); ?></h3> <div id="cancel-comment-reply"> <small><?php cancel_comment_reply_link() ?></small> </div> <?php if ( get_option('comment_registration') && !is_user_logged_in() ) : ?> <p><?php printf(__('You must be <a href="%s">logged in</a> to post a comment.'), wp_login_url( get_permalink() )); ?></p> <?php else : ?> <form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform"> <?php if ( is_user_logged_in() ) : ?> <p><?php printf(__('Logged in as <a href="%1$s">%2$s</a>.'), get_edit_user_link(), $user_identity); ?> <a href="<?php echo wp_logout_url(get_permalink()); ?>" title="<?php esc_attr_e('Log out of this account'); ?>"><?php _e('Log out &raquo;'); ?></a></p> <?php else : ?> <p><input type="text" name="author" id="author" value="<?php echo esc_attr($comment_author); ?>" size="22" tabindex="1" <?php if ($req) echo "aria-required='true'"; ?> /> <label for="author"><small><?php _e('Name'); ?> <?php if ($req) _e('(required)'); ?></small></label></p> <p><input type="text" name="email" id="email" value="<?php echo esc_attr($comment_author_email); ?>" size="22" tabindex="2" <?php if ($req) echo "aria-required='true'"; ?> /> <label for="email"><small><?php _e('Mail (will not be published)'); ?> <?php if ($req) _e('(required)'); ?></small></label></p> <p><input type="text" name="url" id="url" value="<?php echo esc_attr($comment_author_url); ?>" size="22" tabindex="3" /> <label for="url"><small><?php _e('Website'); ?></small></label></p> <?php endif; ?> <!--<p><small><?php printf(__('<strong>XHTML:</strong> You can use these tags: <code>%s</code>'), allowed_tags()); ?></small></p>--> <p><textarea name="comment" id="comment" cols="58" rows="10" tabindex="4"></textarea></p> <p><input name="submit" type="submit" id="submit" tabindex="5" value="<?php esc_attr_e('Submit Comment'); ?>" /> <?php comment_id_fields(); ?> </p> <?php do_action('comment_form', $post->ID); ?> </form> <?php endif; // If registration required and not logged in ?> </div> <?php endif; // if you delete this the sky will fall on your head ?>
zyblog
trunk/zyblog/wp-includes/theme-compat/comments.php
PHP
asf20
3,985
<?php /** * @package WordPress * @subpackage Theme_Compat * @deprecated 3.0 * * This file is here for Backwards compatibility with old themes and will be removed in a future version * */ _deprecated_file( sprintf( __( 'Theme without %1$s' ), basename(__FILE__) ), '3.0', null, sprintf( __('Please include a %1$s template in your theme.'), basename(__FILE__) ) ); ?> <hr /> <div id="footer" role="contentinfo"> <!-- If you'd like to support WordPress, having the "powered by" link somewhere on your blog is the best way; it's our only promotion or advertising. --> <p> <?php printf(__('%1$s is proudly powered by %2$s'), get_bloginfo('name'), '<a href="http://wordpress.org/">WordPress</a>'); ?> <br /><?php printf(__('%1$s and %2$s.'), '<a href="' . get_bloginfo('rss2_url') . '">' . __('Entries (RSS)') . '</a>', '<a href="' . get_bloginfo('comments_rss2_url') . '">' . __('Comments (RSS)') . '</a>'); ?> <!-- <?php printf(__('%d queries. %s seconds.'), get_num_queries(), timer_stop(0, 3)); ?> --> </p> </div> </div> <!-- Gorgeous design by Michael Heilemann - http://binarybonsai.com/kubrick/ --> <?php /* "Just what do you think you're doing Dave?" */ ?> <?php wp_footer(); ?> </body> </html>
zyblog
trunk/zyblog/wp-includes/theme-compat/footer.php
PHP
asf20
1,219
<?php /** * WordPress Error API. * * Contains the WP_Error class and the is_wp_error() function. * * @package WordPress */ /** * WordPress Error class. * * Container for checking for WordPress errors and error messages. Return * WP_Error and use {@link is_wp_error()} to check if this class is returned. * Many core WordPress functions pass this class in the event of an error and * if not handled properly will result in code errors. * * @package WordPress * @since 2.1.0 */ class WP_Error { /** * Stores the list of errors. * * @since 2.1.0 * @var array * @access private */ var $errors = array(); /** * Stores the list of data for error codes. * * @since 2.1.0 * @var array * @access private */ var $error_data = array(); /** * Constructor - Sets up error message. * * If code parameter is empty then nothing will be done. It is possible to * add multiple messages to the same code, but with other methods in the * class. * * All parameters are optional, but if the code parameter is set, then the * data parameter is optional. * * @since 2.1.0 * * @param string|int $code Error code * @param string $message Error message * @param mixed $data Optional. Error data. * @return WP_Error */ function __construct($code = '', $message = '', $data = '') { if ( empty($code) ) return; $this->errors[$code][] = $message; if ( ! empty($data) ) $this->error_data[$code] = $data; } /** * Retrieve all error codes. * * @since 2.1.0 * @access public * * @return array List of error codes, if available. */ function get_error_codes() { if ( empty($this->errors) ) return array(); return array_keys($this->errors); } /** * Retrieve first error code available. * * @since 2.1.0 * @access public * * @return string|int Empty string, if no error codes. */ function get_error_code() { $codes = $this->get_error_codes(); if ( empty($codes) ) return ''; return $codes[0]; } /** * Retrieve all error messages or error messages matching code. * * @since 2.1.0 * * @param string|int $code Optional. Retrieve messages matching code, if exists. * @return array Error strings on success, or empty array on failure (if using code parameter). */ function get_error_messages($code = '') { // Return all messages if no code specified. if ( empty($code) ) { $all_messages = array(); foreach ( (array) $this->errors as $code => $messages ) $all_messages = array_merge($all_messages, $messages); return $all_messages; } if ( isset($this->errors[$code]) ) return $this->errors[$code]; else return array(); } /** * Get single error message. * * This will get the first message available for the code. If no code is * given then the first code available will be used. * * @since 2.1.0 * * @param string|int $code Optional. Error code to retrieve message. * @return string */ function get_error_message($code = '') { if ( empty($code) ) $code = $this->get_error_code(); $messages = $this->get_error_messages($code); if ( empty($messages) ) return ''; return $messages[0]; } /** * Retrieve error data for error code. * * @since 2.1.0 * * @param string|int $code Optional. Error code. * @return mixed Null, if no errors. */ function get_error_data($code = '') { if ( empty($code) ) $code = $this->get_error_code(); if ( isset($this->error_data[$code]) ) return $this->error_data[$code]; return null; } /** * Append more error messages to list of error messages. * * @since 2.1.0 * @access public * * @param string|int $code Error code. * @param string $message Error message. * @param mixed $data Optional. Error data. */ function add($code, $message, $data = '') { $this->errors[$code][] = $message; if ( ! empty($data) ) $this->error_data[$code] = $data; } /** * Add data for error code. * * The error code can only contain one error data. * * @since 2.1.0 * * @param mixed $data Error data. * @param string|int $code Error code. */ function add_data($data, $code = '') { if ( empty($code) ) $code = $this->get_error_code(); $this->error_data[$code] = $data; } } /** * Check whether variable is a WordPress Error. * * Looks at the object and if a WP_Error class. Does not check to see if the * parent is also WP_Error, so can't inherit WP_Error and still use this * function. * * @since 2.1.0 * * @param mixed $thing Check if unknown variable is WordPress Error object. * @return bool True, if WP_Error. False, if not WP_Error. */ function is_wp_error($thing) { if ( is_object($thing) && is_a($thing, 'WP_Error') ) return true; return false; }
zyblog
trunk/zyblog/wp-includes/class-wp-error.php
PHP
asf20
4,753
<?php /*~ class.smtp.php .---------------------------------------------------------------------------. | Software: PHPMailer - PHP email class | | Version: 5.2.1 | | Site: https://code.google.com/a/apache-extras.org/p/phpmailer/ | | ------------------------------------------------------------------------- | | Admin: Jim Jagielski (project admininistrator) | | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net | | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net | | : Jim Jagielski (jimjag) jimjag@gmail.com | | Founder: Brent R. Matzelle (original founder) | | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. | | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. | | Copyright (c) 2001-2003, Brent R. Matzelle | | ------------------------------------------------------------------------- | | License: Distributed under the Lesser General Public License (LGPL) | | http://www.gnu.org/copyleft/lesser.html | | This program is distributed in the hope that it will be useful - WITHOUT | | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | | FITNESS FOR A PARTICULAR PURPOSE. | '---------------------------------------------------------------------------' */ /** * PHPMailer - PHP SMTP email transport class * NOTE: Designed for use with PHP version 5 and up * @package PHPMailer * @author Andy Prevost * @author Marcus Bointon * @copyright 2004 - 2008 Andy Prevost * @author Jim Jagielski * @copyright 2010 - 2012 Jim Jagielski * @license http://www.gnu.org/copyleft/lesser.html Distributed under the Lesser General Public License (LGPL) * @version $Id: class.smtp.php 450 2010-06-23 16:46:33Z coolbru $ */ /** * SMTP is rfc 821 compliant and implements all the rfc 821 SMTP * commands except TURN which will always return a not implemented * error. SMTP also provides some utility methods for sending mail * to an SMTP server. * original author: Chris Ryan */ class SMTP { /** * SMTP server port * @var int */ public $SMTP_PORT = 25; /** * SMTP reply line ending * @var string */ public $CRLF = "\r\n"; /** * Sets whether debugging is turned on * @var bool */ public $do_debug; // the level of debug to perform /** * Sets VERP use on/off (default is off) * @var bool */ public $do_verp = false; /** * Sets the SMTP PHPMailer Version number * @var string */ public $Version = '5.2.1'; ///////////////////////////////////////////////// // PROPERTIES, PRIVATE AND PROTECTED ///////////////////////////////////////////////// private $smtp_conn; // the socket to the server private $error; // error if any on the last call private $helo_rply; // the reply the server sent to us for HELO /** * Initialize the class so that the data is in a known state. * @access public * @return void */ public function __construct() { $this->smtp_conn = 0; $this->error = null; $this->helo_rply = null; $this->do_debug = 0; } ///////////////////////////////////////////////// // CONNECTION FUNCTIONS ///////////////////////////////////////////////// /** * Connect to the server specified on the port specified. * If the port is not specified use the default SMTP_PORT. * If tval is specified then a connection will try and be * established with the server for that number of seconds. * If tval is not specified the default is 30 seconds to * try on the connection. * * SMTP CODE SUCCESS: 220 * SMTP CODE FAILURE: 421 * @access public * @return bool */ public function Connect($host, $port = 0, $tval = 30) { // set the error val to null so there is no confusion $this->error = null; // make sure we are __not__ connected if($this->connected()) { // already connected, generate error $this->error = array("error" => "Already connected to a server"); return false; } if(empty($port)) { $port = $this->SMTP_PORT; } // connect to the smtp server $this->smtp_conn = @fsockopen($host, // the host of the server $port, // the port to use $errno, // error number if any $errstr, // error message if any $tval); // give up after ? secs // verify we connected properly if(empty($this->smtp_conn)) { $this->error = array("error" => "Failed to connect to server", "errno" => $errno, "errstr" => $errstr); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": $errstr ($errno)" . $this->CRLF . '<br />'; } return false; } // SMTP server can take longer to respond, give longer timeout for first read // Windows does not have support for this timeout function if(substr(PHP_OS, 0, 3) != "WIN") socket_set_timeout($this->smtp_conn, $tval, 0); // get any announcement $announce = $this->get_lines(); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $announce . $this->CRLF . '<br />'; } return true; } /** * Initiate a TLS communication with the server. * * SMTP CODE 220 Ready to start TLS * SMTP CODE 501 Syntax error (no parameters allowed) * SMTP CODE 454 TLS not available due to temporary reason * @access public * @return bool success */ public function StartTLS() { $this->error = null; # to avoid confusion if(!$this->connected()) { $this->error = array("error" => "Called StartTLS() without being connected"); return false; } fputs($this->smtp_conn,"STARTTLS" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if($code != 220) { $this->error = array("error" => "STARTTLS not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } // Begin encrypted connection if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { return false; } return true; } /** * Performs SMTP authentication. Must be run after running the * Hello() method. Returns true if successfully authenticated. * @access public * @return bool */ public function Authenticate($username, $password) { // Start authentication fputs($this->smtp_conn,"AUTH LOGIN" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($code != 334) { $this->error = array("error" => "AUTH not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } // Send encoded username fputs($this->smtp_conn, base64_encode($username) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($code != 334) { $this->error = array("error" => "Username not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } // Send encoded password fputs($this->smtp_conn, base64_encode($password) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($code != 235) { $this->error = array("error" => "Password not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * Returns true if connected to a server otherwise false * @access public * @return bool */ public function Connected() { if(!empty($this->smtp_conn)) { $sock_status = socket_get_status($this->smtp_conn); if($sock_status["eof"]) { // the socket is valid but we are not connected if($this->do_debug >= 1) { echo "SMTP -> NOTICE:" . $this->CRLF . "EOF caught while checking if connected"; } $this->Close(); return false; } return true; // everything looks good } return false; } /** * Closes the socket and cleans up the state of the class. * It is not considered good to use this function without * first trying to use QUIT. * @access public * @return void */ public function Close() { $this->error = null; // so there is no confusion $this->helo_rply = null; if(!empty($this->smtp_conn)) { // close the connection and cleanup fclose($this->smtp_conn); $this->smtp_conn = 0; } } ///////////////////////////////////////////////// // SMTP COMMANDS ///////////////////////////////////////////////// /** * Issues a data command and sends the msg_data to the server * finializing the mail transaction. $msg_data is the message * that is to be send with the headers. Each header needs to be * on a single line followed by a <CRLF> with the message headers * and the message body being seperated by and additional <CRLF>. * * Implements rfc 821: DATA <CRLF> * * SMTP CODE INTERMEDIATE: 354 * [data] * <CRLF>.<CRLF> * SMTP CODE SUCCESS: 250 * SMTP CODE FAILURE: 552,554,451,452 * SMTP CODE FAILURE: 451,554 * SMTP CODE ERROR : 500,501,503,421 * @access public * @return bool */ public function Data($msg_data) { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Data() without being connected"); return false; } fputs($this->smtp_conn,"DATA" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if($code != 354) { $this->error = array("error" => "DATA command not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } /* the server is ready to accept data! * according to rfc 821 we should not send more than 1000 * including the CRLF * characters on a single line so we will break the data up * into lines by \r and/or \n then if needed we will break * each of those into smaller lines to fit within the limit. * in addition we will be looking for lines that start with * a period '.' and append and additional period '.' to that * line. NOTE: this does not count towards limit. */ // normalize the line breaks so we know the explode works $msg_data = str_replace("\r\n","\n",$msg_data); $msg_data = str_replace("\r","\n",$msg_data); $lines = explode("\n",$msg_data); /* we need to find a good way to determine is headers are * in the msg_data or if it is a straight msg body * currently I am assuming rfc 822 definitions of msg headers * and if the first field of the first line (':' sperated) * does not contain a space then it _should_ be a header * and we can process all lines before a blank "" line as * headers. */ $field = substr($lines[0],0,strpos($lines[0],":")); $in_headers = false; if(!empty($field) && !strstr($field," ")) { $in_headers = true; } $max_line_length = 998; // used below; set here for ease in change while(list(,$line) = @each($lines)) { $lines_out = null; if($line == "" && $in_headers) { $in_headers = false; } // ok we need to break this line up into several smaller lines while(strlen($line) > $max_line_length) { $pos = strrpos(substr($line,0,$max_line_length)," "); // Patch to fix DOS attack if(!$pos) { $pos = $max_line_length - 1; $lines_out[] = substr($line,0,$pos); $line = substr($line,$pos); } else { $lines_out[] = substr($line,0,$pos); $line = substr($line,$pos + 1); } /* if processing headers add a LWSP-char to the front of new line * rfc 822 on long msg headers */ if($in_headers) { $line = "\t" . $line; } } $lines_out[] = $line; // send the lines to the server while(list(,$line_out) = @each($lines_out)) { if(strlen($line_out) > 0) { if(substr($line_out, 0, 1) == ".") { $line_out = "." . $line_out; } } fputs($this->smtp_conn,$line_out . $this->CRLF); } } // message data has been sent fputs($this->smtp_conn, $this->CRLF . "." . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if($code != 250) { $this->error = array("error" => "DATA not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * Sends the HELO command to the smtp server. * This makes sure that we and the server are in * the same known state. * * Implements from rfc 821: HELO <SP> <domain> <CRLF> * * SMTP CODE SUCCESS: 250 * SMTP CODE ERROR : 500, 501, 504, 421 * @access public * @return bool */ public function Hello($host = '') { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Hello() without being connected"); return false; } // if hostname for HELO was not specified send default if(empty($host)) { // determine appropriate default to send to server $host = "localhost"; } // Send extended hello first (RFC 2821) if(!$this->SendHello("EHLO", $host)) { if(!$this->SendHello("HELO", $host)) { return false; } } return true; } /** * Sends a HELO/EHLO command. * @access private * @return bool */ private function SendHello($hello, $host) { fputs($this->smtp_conn, $hello . " " . $host . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER: " . $rply . $this->CRLF . '<br />'; } if($code != 250) { $this->error = array("error" => $hello . " not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } $this->helo_rply = $rply; return true; } /** * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more Recipient * commands may be called followed by a Data command. * * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF> * * SMTP CODE SUCCESS: 250 * SMTP CODE SUCCESS: 552,451,452 * SMTP CODE SUCCESS: 500,501,421 * @access public * @return bool */ public function Mail($from) { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Mail() without being connected"); return false; } $useVerp = ($this->do_verp ? "XVERP" : ""); fputs($this->smtp_conn,"MAIL FROM:<" . $from . ">" . $useVerp . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if($code != 250) { $this->error = array("error" => "MAIL not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * Sends the quit command to the server and then closes the socket * if there is no error or the $close_on_error argument is true. * * Implements from rfc 821: QUIT <CRLF> * * SMTP CODE SUCCESS: 221 * SMTP CODE ERROR : 500 * @access public * @return bool */ public function Quit($close_on_error = true) { $this->error = null; // so there is no confusion if(!$this->connected()) { $this->error = array( "error" => "Called Quit() without being connected"); return false; } // send the quit command to the server fputs($this->smtp_conn,"quit" . $this->CRLF); // get any good-bye messages $byemsg = $this->get_lines(); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $byemsg . $this->CRLF . '<br />'; } $rval = true; $e = null; $code = substr($byemsg,0,3); if($code != 221) { // use e as a tmp var cause Close will overwrite $this->error $e = array("error" => "SMTP server rejected quit command", "smtp_code" => $code, "smtp_rply" => substr($byemsg,4)); $rval = false; if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $e["error"] . ": " . $byemsg . $this->CRLF . '<br />'; } } if(empty($e) || $close_on_error) { $this->Close(); } return $rval; } /** * Sends the command RCPT to the SMTP server with the TO: argument of $to. * Returns true if the recipient was accepted false if it was rejected. * * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF> * * SMTP CODE SUCCESS: 250,251 * SMTP CODE FAILURE: 550,551,552,553,450,451,452 * SMTP CODE ERROR : 500,501,503,421 * @access public * @return bool */ public function Recipient($to) { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Recipient() without being connected"); return false; } fputs($this->smtp_conn,"RCPT TO:<" . $to . ">" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if($code != 250 && $code != 251) { $this->error = array("error" => "RCPT not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * Sends the RSET command to abort and transaction that is * currently in progress. Returns true if successful false * otherwise. * * Implements rfc 821: RSET <CRLF> * * SMTP CODE SUCCESS: 250 * SMTP CODE ERROR : 500,501,504,421 * @access public * @return bool */ public function Reset() { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called Reset() without being connected"); return false; } fputs($this->smtp_conn,"RSET" . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if($code != 250) { $this->error = array("error" => "RSET failed", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more Recipient * commands may be called followed by a Data command. This command * will send the message to the users terminal if they are logged * in and send them an email. * * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF> * * SMTP CODE SUCCESS: 250 * SMTP CODE SUCCESS: 552,451,452 * SMTP CODE SUCCESS: 500,501,502,421 * @access public * @return bool */ public function SendAndMail($from) { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( "error" => "Called SendAndMail() without being connected"); return false; } fputs($this->smtp_conn,"SAML FROM:" . $from . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply,0,3); if($this->do_debug >= 2) { echo "SMTP -> FROM SERVER:" . $rply . $this->CRLF . '<br />'; } if($code != 250) { $this->error = array("error" => "SAML not accepted from server", "smtp_code" => $code, "smtp_msg" => substr($rply,4)); if($this->do_debug >= 1) { echo "SMTP -> ERROR: " . $this->error["error"] . ": " . $rply . $this->CRLF . '<br />'; } return false; } return true; } /** * This is an optional command for SMTP that this class does not * support. This method is here to make the RFC821 Definition * complete for this class and __may__ be implimented in the future * * Implements from rfc 821: TURN <CRLF> * * SMTP CODE SUCCESS: 250 * SMTP CODE FAILURE: 502 * SMTP CODE ERROR : 500, 503 * @access public * @return bool */ public function Turn() { $this->error = array("error" => "This method, TURN, of the SMTP ". "is not implemented"); if($this->do_debug >= 1) { echo "SMTP -> NOTICE: " . $this->error["error"] . $this->CRLF . '<br />'; } return false; } /** * Get the current error * @access public * @return array */ public function getError() { return $this->error; } ///////////////////////////////////////////////// // INTERNAL FUNCTIONS ///////////////////////////////////////////////// /** * Read in as many lines as possible * either before eof or socket timeout occurs on the operation. * With SMTP we can tell if we have more lines to read if the * 4th character is '-' symbol. If it is a space then we don't * need to read anything else. * @access private * @return string */ private function get_lines() { $data = ""; while(!feof($this->smtp_conn)) { $str = @fgets($this->smtp_conn,515); if($this->do_debug >= 4) { echo "SMTP -> get_lines(): \$data was \"$data\"" . $this->CRLF . '<br />'; echo "SMTP -> get_lines(): \$str is \"$str\"" . $this->CRLF . '<br />'; } $data .= $str; if($this->do_debug >= 4) { echo "SMTP -> get_lines(): \$data is \"$data\"" . $this->CRLF . '<br />'; } // if 4th character is a space, we are done reading, break the loop if(substr($str,3,1) == " ") { break; } } return $data; } } ?>
zyblog
trunk/zyblog/wp-includes/class-smtp.php
PHP
asf20
24,618
<?php /** * API for fetching the HTML to embed remote content based on a provided URL. * Used internally by the {@link WP_Embed} class, but is designed to be generic. * * @link http://codex.wordpress.org/oEmbed oEmbed Codex Article * @link http://oembed.com/ oEmbed Homepage * * @package WordPress * @subpackage oEmbed */ /** * oEmbed class. * * @package WordPress * @subpackage oEmbed * @since 2.9.0 */ class WP_oEmbed { var $providers = array(); /** * Constructor * * @uses apply_filters() Filters a list of pre-defined oEmbed providers. */ function __construct() { // List out some popular sites that support oEmbed. // The WP_Embed class disables discovery for non-unfiltered_html users, so only providers in this array will be used for them. // Add to this list using the wp_oembed_add_provider() function (see its PHPDoc for details). $this->providers = apply_filters( 'oembed_providers', array( '#https?://(www\.)?youtube.com/watch.*#i' => array( 'http://www.youtube.com/oembed', true ), 'http://youtu.be/*' => array( 'http://www.youtube.com/oembed', false ), 'http://blip.tv/*' => array( 'http://blip.tv/oembed/', false ), '#https?://(www\.)?vimeo\.com/.*#i' => array( 'http://vimeo.com/api/oembed.{format}', true ), '#https?://(www\.)?dailymotion\.com/.*#i' => array( 'http://www.dailymotion.com/services/oembed', true ), '#https?://(www\.)?flickr\.com/.*#i' => array( 'http://www.flickr.com/services/oembed/', true ), '#https?://(.+\.)?smugmug\.com/.*#i' => array( 'http://api.smugmug.com/services/oembed/', true ), '#https?://(www\.)?hulu\.com/watch/.*#i' => array( 'http://www.hulu.com/api/oembed.{format}', true ), '#https?://(www\.)?viddler\.com/.*#i' => array( 'http://lab.viddler.com/services/oembed/', true ), 'http://qik.com/*' => array( 'http://qik.com/api/oembed.{format}', false ), 'http://revision3.com/*' => array( 'http://revision3.com/api/oembed/', false ), 'http://i*.photobucket.com/albums/*' => array( 'http://photobucket.com/oembed', false ), 'http://gi*.photobucket.com/groups/*' => array( 'http://photobucket.com/oembed', false ), '#https?://(www\.)?scribd\.com/.*#i' => array( 'http://www.scribd.com/services/oembed', true ), 'http://wordpress.tv/*' => array( 'http://wordpress.tv/oembed/', false ), '#https?://(.+\.)?polldaddy\.com/.*#i' => array( 'http://polldaddy.com/oembed/', true ), '#https?://(www\.)?funnyordie\.com/videos/.*#i' => array( 'http://www.funnyordie.com/oembed', true ), '#https?://(www\.)?twitter.com/.+?/status(es)?/.*#i' => array( 'http://api.twitter.com/1/statuses/oembed.{format}', true ), '#https?://(www\.)?soundcloud\.com/.*#i' => array( 'http://soundcloud.com/oembed', true ), '#https?://(www\.)?slideshare.net/*#' => array( 'http://www.slideshare.net/api/oembed/2', true ), '#http://instagr(\.am|am\.com)/p/.*#i' => array( 'http://api.instagram.com/oembed', true ), ) ); // Fix any embeds that contain new lines in the middle of the HTML which breaks wpautop(). add_filter( 'oembed_dataparse', array($this, '_strip_newlines'), 10, 3 ); } /** * The do-it-all function that takes a URL and attempts to return the HTML. * * @see WP_oEmbed::discover() * @see WP_oEmbed::fetch() * @see WP_oEmbed::data2html() * * @param string $url The URL to the content that should be attempted to be embedded. * @param array $args Optional arguments. Usually passed from a shortcode. * @return bool|string False on failure, otherwise the UNSANITIZED (and potentially unsafe) HTML that should be used to embed. */ function get_html( $url, $args = '' ) { $provider = false; if ( !isset($args['discover']) ) $args['discover'] = true; foreach ( $this->providers as $matchmask => $data ) { list( $providerurl, $regex ) = $data; // Turn the asterisk-type provider URLs into regex if ( !$regex ) { $matchmask = '#' . str_replace( '___wildcard___', '(.+)', preg_quote( str_replace( '*', '___wildcard___', $matchmask ), '#' ) ) . '#i'; $matchmask = preg_replace( '|^#http\\\://|', '#https?\://', $matchmask ); } if ( preg_match( $matchmask, $url ) ) { $provider = str_replace( '{format}', 'json', $providerurl ); // JSON is easier to deal with than XML break; } } if ( !$provider && $args['discover'] ) $provider = $this->discover( $url ); if ( !$provider || false === $data = $this->fetch( $provider, $url, $args ) ) return false; return apply_filters( 'oembed_result', $this->data2html( $data, $url ), $url, $args ); } /** * Attempts to find oEmbed provider discovery <link> tags at the given URL. * * @param string $url The URL that should be inspected for discovery <link> tags. * @return bool|string False on failure, otherwise the oEmbed provider URL. */ function discover( $url ) { $providers = array(); // Fetch URL content if ( $html = wp_remote_retrieve_body( wp_remote_get( $url ) ) ) { // <link> types that contain oEmbed provider URLs $linktypes = apply_filters( 'oembed_linktypes', array( 'application/json+oembed' => 'json', 'text/xml+oembed' => 'xml', 'application/xml+oembed' => 'xml', // Incorrect, but used by at least Vimeo ) ); // Strip <body> $html = substr( $html, 0, stripos( $html, '</head>' ) ); // Do a quick check $tagfound = false; foreach ( $linktypes as $linktype => $format ) { if ( stripos($html, $linktype) ) { $tagfound = true; break; } } if ( $tagfound && preg_match_all( '/<link([^<>]+)>/i', $html, $links ) ) { foreach ( $links[1] as $link ) { $atts = shortcode_parse_atts( $link ); if ( !empty($atts['type']) && !empty($linktypes[$atts['type']]) && !empty($atts['href']) ) { $providers[$linktypes[$atts['type']]] = $atts['href']; // Stop here if it's JSON (that's all we need) if ( 'json' == $linktypes[$atts['type']] ) break; } } } } // JSON is preferred to XML if ( !empty($providers['json']) ) return $providers['json']; elseif ( !empty($providers['xml']) ) return $providers['xml']; else return false; } /** * Connects to a oEmbed provider and returns the result. * * @param string $provider The URL to the oEmbed provider. * @param string $url The URL to the content that is desired to be embedded. * @param array $args Optional arguments. Usually passed from a shortcode. * @return bool|object False on failure, otherwise the result in the form of an object. */ function fetch( $provider, $url, $args = '' ) { $args = wp_parse_args( $args, wp_embed_defaults() ); $provider = add_query_arg( 'maxwidth', (int) $args['width'], $provider ); $provider = add_query_arg( 'maxheight', (int) $args['height'], $provider ); $provider = add_query_arg( 'url', urlencode($url), $provider ); $provider = apply_filters( 'oembed_fetch_url', $provider, $url, $args ); foreach( array( 'json', 'xml' ) as $format ) { $result = $this->_fetch_with_format( $provider, $format ); if ( is_wp_error( $result ) && 'not-implemented' == $result->get_error_code() ) continue; return ( $result && ! is_wp_error( $result ) ) ? $result : false; } return false; } /** * Fetches result from an oEmbed provider for a specific format and complete provider URL * * @since 3.0.0 * @access private * @param string $provider_url_with_args URL to the provider with full arguments list (url, maxheight, etc.) * @param string $format Format to use * @return bool|object False on failure, otherwise the result in the form of an object. */ function _fetch_with_format( $provider_url_with_args, $format ) { $provider_url_with_args = add_query_arg( 'format', $format, $provider_url_with_args ); $response = wp_remote_get( $provider_url_with_args ); if ( 501 == wp_remote_retrieve_response_code( $response ) ) return new WP_Error( 'not-implemented' ); if ( ! $body = wp_remote_retrieve_body( $response ) ) return false; $parse_method = "_parse_$format"; return $this->$parse_method( $body ); } /** * Parses a json response body. * * @since 3.0.0 * @access private */ function _parse_json( $response_body ) { return ( ( $data = json_decode( trim( $response_body ) ) ) && is_object( $data ) ) ? $data : false; } /** * Parses an XML response body. * * @since 3.0.0 * @access private */ function _parse_xml( $response_body ) { if ( !function_exists('simplexml_load_string') ) { return false; } if ( ! class_exists( 'DOMDocument' ) ) return false; $errors = libxml_use_internal_errors( true ); $old_value = null; if ( function_exists( 'libxml_disable_entity_loader' ) ) { $old_value = libxml_disable_entity_loader( true ); } $dom = new DOMDocument; $success = $dom->loadXML( $response_body ); if ( ! is_null( $old_value ) ) { libxml_disable_entity_loader( $old_value ); } libxml_use_internal_errors( $errors ); if ( ! $success || isset( $dom->doctype ) ) { return false; } $data = simplexml_import_dom( $dom ); if ( ! is_object( $data ) ) return false; $return = new stdClass; foreach ( $data as $key => $value ) $return->$key = (string) $value; return $return; } /** * Converts a data object from {@link WP_oEmbed::fetch()} and returns the HTML. * * @param object $data A data object result from an oEmbed provider. * @param string $url The URL to the content that is desired to be embedded. * @return bool|string False on error, otherwise the HTML needed to embed. */ function data2html( $data, $url ) { if ( ! is_object( $data ) || empty( $data->type ) ) return false; $return = false; switch ( $data->type ) { case 'photo': if ( empty( $data->url ) || empty( $data->width ) || empty( $data->height ) ) break; if ( ! is_string( $data->url ) || ! is_numeric( $data->width ) || ! is_numeric( $data->height ) ) break; $title = ! empty( $data->title ) && is_string( $data->title ) ? $data->title : ''; $return = '<a href="' . esc_url( $url ) . '"><img src="' . esc_url( $data->url ) . '" alt="' . esc_attr($title) . '" width="' . esc_attr($data->width) . '" height="' . esc_attr($data->height) . '" /></a>'; break; case 'video': case 'rich': if ( ! empty( $data->html ) && is_string( $data->html ) ) $return = $data->html; break; case 'link': if ( ! empty( $data->title ) && is_string( $data->title ) ) $return = '<a href="' . esc_url( $url ) . '">' . esc_html( $data->title ) . '</a>'; break; default: $return = false; } // You can use this filter to add support for custom data types or to filter the result return apply_filters( 'oembed_dataparse', $return, $data, $url ); } /** * Strip any new lines from the HTML. * * @access private * @param string $html Existing HTML. * @param object $data Data object from WP_oEmbed::data2html() * @param string $url The original URL passed to oEmbed. * @return string Possibly modified $html */ function _strip_newlines( $html, $data, $url ) { if ( false !== strpos( $html, "\n" ) ) $html = str_replace( array( "\r\n", "\n" ), '', $html ); return $html; } } /** * Returns the initialized {@link WP_oEmbed} object * * @since 2.9.0 * @access private * * @see WP_oEmbed * @uses WP_oEmbed * * @return WP_oEmbed object. */ function _wp_oembed_get_object() { static $wp_oembed; if ( is_null($wp_oembed) ) $wp_oembed = new WP_oEmbed(); return $wp_oembed; }
zyblog
trunk/zyblog/wp-includes/class-oembed.php
PHP
asf20
12,213
<?php /** * WordPress Post Thumbnail Template Functions. * * Support for post thumbnails * Themes function.php must call add_theme_support( 'post-thumbnails' ) to use these. * * @package WordPress * @subpackage Template */ /** * Check if post has an image attached. * * @since 2.9.0 * * @param int $post_id Optional. Post ID. * @return bool Whether post has an image attached. */ function has_post_thumbnail( $post_id = null ) { return (bool) get_post_thumbnail_id( $post_id ); } /** * Retrieve Post Thumbnail ID. * * @since 2.9.0 * * @param int $post_id Optional. Post ID. * @return int */ function get_post_thumbnail_id( $post_id = null ) { $post_id = ( null === $post_id ) ? get_the_ID() : $post_id; return get_post_meta( $post_id, '_thumbnail_id', true ); } /** * Display Post Thumbnail. * * @since 2.9.0 * * @param int $size Optional. Image size. Defaults to 'post-thumbnail', which theme sets using set_post_thumbnail_size( $width, $height, $crop_flag );. * @param string|array $attr Optional. Query string or array of attributes. */ function the_post_thumbnail( $size = 'post-thumbnail', $attr = '' ) { echo get_the_post_thumbnail( null, $size, $attr ); } /** * Update cache for thumbnails in the current loop * * @since 3.2 * * @param object $wp_query Optional. A WP_Query instance. Defaults to the $wp_query global. */ function update_post_thumbnail_cache( $wp_query = null ) { if ( ! $wp_query ) $wp_query = $GLOBALS['wp_query']; if ( $wp_query->thumbnails_cached ) return; $thumb_ids = array(); foreach ( $wp_query->posts as $post ) { if ( $id = get_post_thumbnail_id( $post->ID ) ) $thumb_ids[] = $id; } if ( ! empty ( $thumb_ids ) ) { _prime_post_caches( $thumb_ids, false, true ); } $wp_query->thumbnails_cached = true; } /** * Retrieve Post Thumbnail. * * @since 2.9.0 * * @param int $post_id Optional. Post ID. * @param string $size Optional. Image size. Defaults to 'post-thumbnail'. * @param string|array $attr Optional. Query string or array of attributes. */ function get_the_post_thumbnail( $post_id = null, $size = 'post-thumbnail', $attr = '' ) { $post_id = ( null === $post_id ) ? get_the_ID() : $post_id; $post_thumbnail_id = get_post_thumbnail_id( $post_id ); $size = apply_filters( 'post_thumbnail_size', $size ); if ( $post_thumbnail_id ) { do_action( 'begin_fetch_post_thumbnail_html', $post_id, $post_thumbnail_id, $size ); // for "Just In Time" filtering of all of wp_get_attachment_image()'s filters if ( in_the_loop() ) update_post_thumbnail_cache(); $html = wp_get_attachment_image( $post_thumbnail_id, $size, false, $attr ); do_action( 'end_fetch_post_thumbnail_html', $post_id, $post_thumbnail_id, $size ); } else { $html = ''; } return apply_filters( 'post_thumbnail_html', $html, $post_id, $post_thumbnail_id, $size, $attr ); }
zyblog
trunk/zyblog/wp-includes/post-thumbnail-template.php
PHP
asf20
2,861
<?php /** * Facilitates adding of the WordPress editor as used on the Write and Edit screens. * * @package WordPress * @since 3.3.0 * * Private, not included by default. See wp_editor() in wp-includes/general-template.php. */ final class _WP_Editors { public static $mce_locale; private static $mce_settings = array(); private static $qt_settings = array(); private static $plugins = array(); private static $qt_buttons = array(); private static $ext_plugins; private static $baseurl; private static $first_init; private static $this_tinymce = false; private static $this_quicktags = false; private static $has_tinymce = false; private static $has_quicktags = false; private static $has_medialib = false; private static $editor_buttons_css = true; private function __construct() {} public static function parse_settings($editor_id, $settings) { $set = wp_parse_args( $settings, array( 'wpautop' => true, // use wpautop? 'media_buttons' => true, // show insert/upload button(s) 'textarea_name' => $editor_id, // set the textarea name to something different, square brackets [] can be used here 'textarea_rows' => 20, 'tabindex' => '', 'tabfocus_elements' => ':prev,:next', // the previous and next element ID to move the focus to when pressing the Tab key in TinyMCE 'editor_css' => '', // intended for extra styles for both visual and Text editors buttons, needs to include the <style> tags, can use "scoped". 'editor_class' => '', // add extra class(es) to the editor textarea 'teeny' => false, // output the minimal editor config used in Press This 'dfw' => false, // replace the default fullscreen with DFW (needs specific DOM elements and css) 'tinymce' => true, // load TinyMCE, can be used to pass settings directly to TinyMCE using an array() 'quicktags' => true // load Quicktags, can be used to pass settings directly to Quicktags using an array() ) ); self::$this_tinymce = ( $set['tinymce'] && user_can_richedit() ); self::$this_quicktags = (bool) $set['quicktags']; if ( self::$this_tinymce ) self::$has_tinymce = true; if ( self::$this_quicktags ) self::$has_quicktags = true; if ( empty( $set['editor_height'] ) ) return $set; if ( 'content' === $editor_id ) { // A cookie (set when a user resizes the editor) overrides the height. $cookie = (int) get_user_setting( 'ed_size' ); // Upgrade an old TinyMCE cookie if it is still around, and the new one isn't. if ( ! $cookie && isset( $_COOKIE['TinyMCE_content_size'] ) ) { parse_str( $_COOKIE['TinyMCE_content_size'], $cookie ); $cookie = $cookie['ch']; } if ( $cookie ) $set['editor_height'] = $cookie; } if ( $set['editor_height'] < 50 ) $set['editor_height'] = 50; elseif ( $set['editor_height'] > 5000 ) $set['editor_height'] = 5000; return $set; } /** * Outputs the HTML for a single instance of the editor. * * @param string $content The initial content of the editor. * @param string $editor_id ID for the textarea and TinyMCE and Quicktags instances (can contain only ASCII letters and numbers). * @param array $settings See the _parse_settings() method for description. */ public static function editor( $content, $editor_id, $settings = array() ) { $set = self::parse_settings($editor_id, $settings); $editor_class = ' class="' . trim( $set['editor_class'] . ' wp-editor-area' ) . '"'; $tabindex = $set['tabindex'] ? ' tabindex="' . (int) $set['tabindex'] . '"' : ''; $switch_class = 'html-active'; $toolbar = $buttons = ''; if ( ! empty( $set['editor_height'] ) ) $height = ' style="height: ' . $set['editor_height'] . 'px"'; else $height = ' rows="' . $set['textarea_rows'] . '"'; if ( !current_user_can( 'upload_files' ) ) $set['media_buttons'] = false; if ( self::$this_quicktags && self::$this_tinymce ) { $switch_class = 'html-active'; // 'html' and 'switch-html' are used for the "Text" editor tab. if ( 'html' == wp_default_editor() ) { add_filter('the_editor_content', 'wp_htmledit_pre'); } else { add_filter('the_editor_content', 'wp_richedit_pre'); $switch_class = 'tmce-active'; } $buttons .= '<a id="' . $editor_id . '-html" class="wp-switch-editor switch-html" onclick="switchEditors.switchto(this);">' . _x( 'Text', 'Name for the Text editor tab (formerly HTML)' ) . "</a>\n"; $buttons .= '<a id="' . $editor_id . '-tmce" class="wp-switch-editor switch-tmce" onclick="switchEditors.switchto(this);">' . __('Visual') . "</a>\n"; } echo '<div id="wp-' . $editor_id . '-wrap" class="wp-core-ui wp-editor-wrap ' . $switch_class . '">'; if ( self::$editor_buttons_css ) { wp_print_styles('editor-buttons'); self::$editor_buttons_css = false; } if ( !empty($set['editor_css']) ) echo $set['editor_css'] . "\n"; if ( !empty($buttons) || $set['media_buttons'] ) { echo '<div id="wp-' . $editor_id . '-editor-tools" class="wp-editor-tools hide-if-no-js">'; echo $buttons; if ( $set['media_buttons'] ) { self::$has_medialib = true; if ( !function_exists('media_buttons') ) include(ABSPATH . 'wp-admin/includes/media.php'); echo '<div id="wp-' . $editor_id . '-media-buttons" class="wp-media-buttons">'; do_action('media_buttons', $editor_id); echo "</div>\n"; } echo "</div>\n"; } $the_editor = apply_filters('the_editor', '<div id="wp-' . $editor_id . '-editor-container" class="wp-editor-container"><textarea' . $editor_class . $height . $tabindex . ' cols="40" name="' . $set['textarea_name'] . '" id="' . $editor_id . '">%s</textarea></div>'); $content = apply_filters('the_editor_content', $content); printf($the_editor, $content); echo "\n</div>\n\n"; self::editor_settings($editor_id, $set); } public static function editor_settings($editor_id, $set) { global $editor_styles; $first_run = false; if ( empty(self::$first_init) ) { if ( is_admin() ) { add_action( 'admin_print_footer_scripts', array( __CLASS__, 'editor_js'), 50 ); add_action( 'admin_footer', array( __CLASS__, 'enqueue_scripts'), 1 ); } else { add_action( 'wp_print_footer_scripts', array( __CLASS__, 'editor_js'), 50 ); add_action( 'wp_footer', array( __CLASS__, 'enqueue_scripts'), 1 ); } } if ( self::$this_quicktags ) { $qtInit = array( 'id' => $editor_id, 'buttons' => '' ); if ( is_array($set['quicktags']) ) $qtInit = array_merge($qtInit, $set['quicktags']); if ( empty($qtInit['buttons']) ) $qtInit['buttons'] = 'strong,em,link,block,del,ins,img,ul,ol,li,code,more,spell,close'; if ( $set['dfw'] ) $qtInit['buttons'] .= ',fullscreen'; $qtInit = apply_filters('quicktags_settings', $qtInit, $editor_id); self::$qt_settings[$editor_id] = $qtInit; self::$qt_buttons = array_merge( self::$qt_buttons, explode(',', $qtInit['buttons']) ); } if ( self::$this_tinymce ) { if ( empty(self::$first_init) ) { self::$baseurl = includes_url('js/tinymce'); self::$mce_locale = $mce_locale = ( '' == get_locale() ) ? 'en' : strtolower( substr(get_locale(), 0, 2) ); // only ISO 639-1 $no_captions = (bool) apply_filters( 'disable_captions', '' ); $plugins = array( 'inlinepopups', 'spellchecker', 'tabfocus', 'paste', 'media', 'fullscreen', 'wordpress', 'wpeditimage', 'wpgallery', 'wplink', 'wpdialogs' ); $first_run = true; $ext_plugins = ''; if ( $set['teeny'] ) { self::$plugins = $plugins = apply_filters( 'teeny_mce_plugins', array('inlinepopups', 'fullscreen', 'wordpress', 'wplink', 'wpdialogs' ), $editor_id ); } else { /* The following filter takes an associative array of external plugins for TinyMCE in the form 'plugin_name' => 'url'. It adds the plugin's name to TinyMCE's plugins init and the call to PluginManager to load the plugin. The url should be absolute and should include the js file name to be loaded. Example: array( 'myplugin' => 'http://my-site.com/wp-content/plugins/myfolder/mce_plugin.js' ) If the plugin uses a button, it should be added with one of the "$mce_buttons" filters. */ $mce_external_plugins = apply_filters('mce_external_plugins', array()); if ( ! empty($mce_external_plugins) ) { /* The following filter loads external language files for TinyMCE plugins. It takes an associative array 'plugin_name' => 'path', where path is the include path to the file. The language file should follow the same format as /tinymce/langs/wp-langs.php and should define a variable $strings that holds all translated strings. When this filter is not used, the function will try to load {mce_locale}.js. If that is not found, en.js will be tried next. */ $mce_external_languages = apply_filters('mce_external_languages', array()); $loaded_langs = array(); $strings = ''; if ( ! empty($mce_external_languages) ) { foreach ( $mce_external_languages as $name => $path ) { if ( @is_file($path) && @is_readable($path) ) { include_once($path); $ext_plugins .= $strings . "\n"; $loaded_langs[] = $name; } } } foreach ( $mce_external_plugins as $name => $url ) { $url = set_url_scheme( $url ); $plugins[] = '-' . $name; $plugurl = dirname($url); $strings = $str1 = $str2 = ''; if ( ! in_array($name, $loaded_langs) ) { $path = str_replace( content_url(), '', $plugurl ); $path = WP_CONTENT_DIR . $path . '/langs/'; if ( function_exists('realpath') ) $path = trailingslashit( realpath($path) ); if ( @is_file($path . $mce_locale . '.js') ) $strings .= @file_get_contents($path . $mce_locale . '.js') . "\n"; if ( @is_file($path . $mce_locale . '_dlg.js') ) $strings .= @file_get_contents($path . $mce_locale . '_dlg.js') . "\n"; if ( 'en' != $mce_locale && empty($strings) ) { if ( @is_file($path . 'en.js') ) { $str1 = @file_get_contents($path . 'en.js'); $strings .= preg_replace( '/([\'"])en\./', '$1' . $mce_locale . '.', $str1, 1 ) . "\n"; } if ( @is_file($path . 'en_dlg.js') ) { $str2 = @file_get_contents($path . 'en_dlg.js'); $strings .= preg_replace( '/([\'"])en\./', '$1' . $mce_locale . '.', $str2, 1 ) . "\n"; } } if ( ! empty($strings) ) $ext_plugins .= "\n" . $strings . "\n"; } $ext_plugins .= 'tinyMCEPreInit.load_ext("' . $plugurl . '", "' . $mce_locale . '");' . "\n"; $ext_plugins .= 'tinymce.PluginManager.load("' . $name . '", "' . $url . '");' . "\n"; } } $plugins = array_unique( apply_filters('tiny_mce_plugins', $plugins) ); } if ( $set['dfw'] ) $plugins[] = 'wpfullscreen'; self::$plugins = $plugins; self::$ext_plugins = $ext_plugins; /* translators: These languages show up in the spellchecker drop-down menu, in the order specified, and with the first language listed being the default language. They must be comma-separated and take the format of name=code, where name is the language name (which you may internationalize), and code is a valid ISO 639 language code. Please test the spellchecker with your values. */ $mce_spellchecker_languages = __( 'English=en,Danish=da,Dutch=nl,Finnish=fi,French=fr,German=de,Italian=it,Polish=pl,Portuguese=pt,Spanish=es,Swedish=sv' ); /* The following filter allows localization scripts to change the languages displayed in the spellchecker's drop-down menu. By default it uses Google's spellchecker API, but can be configured to use PSpell/ASpell if installed on the server. The + sign marks the default language. More: http://www.tinymce.com/wiki.php/Plugin:spellchecker. */ $mce_spellchecker_languages = apply_filters( 'mce_spellchecker_languages', '+' . $mce_spellchecker_languages ); self::$first_init = array( 'mode' => 'exact', 'width' => '100%', 'theme' => 'advanced', 'skin' => 'wp_theme', 'language' => self::$mce_locale, 'spellchecker_languages' => $mce_spellchecker_languages, 'theme_advanced_toolbar_location' => 'top', 'theme_advanced_toolbar_align' => 'left', 'theme_advanced_statusbar_location' => 'bottom', 'theme_advanced_resizing' => true, 'theme_advanced_resize_horizontal' => false, 'dialog_type' => 'modal', 'formats' => "{ alignleft : [ {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'left'}}, {selector : 'img,table', classes : 'alignleft'} ], aligncenter : [ {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'center'}}, {selector : 'img,table', classes : 'aligncenter'} ], alignright : [ {selector : 'p,h1,h2,h3,h4,h5,h6,td,th,div,ul,ol,li', styles : {textAlign : 'right'}}, {selector : 'img,table', classes : 'alignright'} ], strikethrough : {inline : 'del'} }", 'relative_urls' => false, 'remove_script_host' => false, 'convert_urls' => false, 'remove_linebreaks' => true, 'gecko_spellcheck' => true, 'fix_list_elements' => true, 'keep_styles' => false, 'entities' => '38,amp,60,lt,62,gt', 'accessibility_focus' => true, 'media_strict' => false, 'paste_remove_styles' => true, 'paste_remove_spans' => true, 'paste_strip_class_attributes' => 'all', 'paste_text_use_dialog' => true, 'webkit_fake_resize' => false, 'spellchecker_rpc_url' => self::$baseurl . '/plugins/spellchecker/rpc.php', 'schema' => 'html5', 'wpeditimage_disable_captions' => $no_captions, 'wp_fullscreen_content_css' => self::$baseurl . '/plugins/wpfullscreen/css/wp-fullscreen.css', 'plugins' => implode( ',', $plugins ) ); // load editor_style.css if the current theme supports it if ( ! empty( $editor_styles ) && is_array( $editor_styles ) ) { $mce_css = array(); $editor_styles = array_unique($editor_styles); $style_uri = get_stylesheet_directory_uri(); $style_dir = get_stylesheet_directory(); if ( is_child_theme() ) { $template_uri = get_template_directory_uri(); $template_dir = get_template_directory(); foreach ( $editor_styles as $key => $file ) { if ( $file && file_exists( "$template_dir/$file" ) ) $mce_css[] = "$template_uri/$file"; } } foreach ( $editor_styles as $file ) { if ( $file && file_exists( "$style_dir/$file" ) ) $mce_css[] = "$style_uri/$file"; } $mce_css = implode( ',', $mce_css ); } else { $mce_css = ''; } $mce_css = trim( apply_filters( 'mce_css', $mce_css ), ' ,' ); if ( ! empty($mce_css) ) self::$first_init['content_css'] = $mce_css; } if ( $set['teeny'] ) { $mce_buttons = apply_filters( 'teeny_mce_buttons', array('bold', 'italic', 'underline', 'blockquote', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'undo', 'redo', 'link', 'unlink', 'fullscreen'), $editor_id ); $mce_buttons_2 = $mce_buttons_3 = $mce_buttons_4 = array(); } else { $mce_buttons = apply_filters('mce_buttons', array('bold', 'italic', 'strikethrough', 'bullist', 'numlist', 'blockquote', 'justifyleft', 'justifycenter', 'justifyright', 'link', 'unlink', 'wp_more', 'spellchecker', 'fullscreen', 'wp_adv' ), $editor_id); $mce_buttons_2 = apply_filters('mce_buttons_2', array( 'formatselect', 'underline', 'justifyfull', 'forecolor', 'pastetext', 'pasteword', 'removeformat', 'charmap', 'outdent', 'indent', 'undo', 'redo', 'wp_help' ), $editor_id); $mce_buttons_3 = apply_filters('mce_buttons_3', array(), $editor_id); $mce_buttons_4 = apply_filters('mce_buttons_4', array(), $editor_id); } $body_class = $editor_id; if ( $post = get_post() ) $body_class .= ' post-type-' . $post->post_type; if ( !empty($set['tinymce']['body_class']) ) { $body_class .= ' ' . $set['tinymce']['body_class']; unset($set['tinymce']['body_class']); } if ( $set['dfw'] ) { // replace the first 'fullscreen' with 'wp_fullscreen' if ( ($key = array_search('fullscreen', $mce_buttons)) !== false ) $mce_buttons[$key] = 'wp_fullscreen'; elseif ( ($key = array_search('fullscreen', $mce_buttons_2)) !== false ) $mce_buttons_2[$key] = 'wp_fullscreen'; elseif ( ($key = array_search('fullscreen', $mce_buttons_3)) !== false ) $mce_buttons_3[$key] = 'wp_fullscreen'; elseif ( ($key = array_search('fullscreen', $mce_buttons_4)) !== false ) $mce_buttons_4[$key] = 'wp_fullscreen'; } $mceInit = array ( 'elements' => $editor_id, 'wpautop' => (bool) $set['wpautop'], 'remove_linebreaks' => (bool) $set['wpautop'], 'apply_source_formatting' => (bool) !$set['wpautop'], 'theme_advanced_buttons1' => implode($mce_buttons, ','), 'theme_advanced_buttons2' => implode($mce_buttons_2, ','), 'theme_advanced_buttons3' => implode($mce_buttons_3, ','), 'theme_advanced_buttons4' => implode($mce_buttons_4, ','), 'tabfocus_elements' => $set['tabfocus_elements'], 'body_class' => $body_class ); // The main editor doesn't use the TinyMCE resizing cookie. $mceInit['theme_advanced_resizing_use_cookie'] = 'content' !== $editor_id || empty( $set['editor_height'] ); if ( $first_run ) $mceInit = array_merge(self::$first_init, $mceInit); if ( is_array($set['tinymce']) ) $mceInit = array_merge($mceInit, $set['tinymce']); // For people who really REALLY know what they're doing with TinyMCE // You can modify $mceInit to add, remove, change elements of the config before tinyMCE.init // Setting "valid_elements", "invalid_elements" and "extended_valid_elements" can be done through this filter. // Best is to use the default cleanup by not specifying valid_elements, as TinyMCE contains full set of XHTML 1.0. if ( $set['teeny'] ) { $mceInit = apply_filters('teeny_mce_before_init', $mceInit, $editor_id); } else { $mceInit = apply_filters('tiny_mce_before_init', $mceInit, $editor_id); } if ( empty($mceInit['theme_advanced_buttons3']) && !empty($mceInit['theme_advanced_buttons4']) ) { $mceInit['theme_advanced_buttons3'] = $mceInit['theme_advanced_buttons4']; $mceInit['theme_advanced_buttons4'] = ''; } self::$mce_settings[$editor_id] = $mceInit; } // end if self::$this_tinymce } private static function _parse_init($init) { $options = ''; foreach ( $init as $k => $v ) { if ( is_bool($v) ) { $val = $v ? 'true' : 'false'; $options .= $k . ':' . $val . ','; continue; } elseif ( !empty($v) && is_string($v) && ( ('{' == $v{0} && '}' == $v{strlen($v) - 1}) || ('[' == $v{0} && ']' == $v{strlen($v) - 1}) || preg_match('/^\(?function ?\(/', $v) ) ) { $options .= $k . ':' . $v . ','; continue; } $options .= $k . ':"' . $v . '",'; } return '{' . trim( $options, ' ,' ) . '}'; } public static function enqueue_scripts() { wp_enqueue_script('word-count'); if ( self::$has_tinymce ) wp_enqueue_script('editor'); if ( self::$has_quicktags ) wp_enqueue_script('quicktags'); if ( in_array('wplink', self::$plugins, true) || in_array('link', self::$qt_buttons, true) ) { wp_enqueue_script('wplink'); wp_enqueue_script('wpdialogs-popup'); wp_enqueue_style('wp-jquery-ui-dialog'); } if ( in_array('wpfullscreen', self::$plugins, true) || in_array('fullscreen', self::$qt_buttons, true) ) wp_enqueue_script('wp-fullscreen'); if ( self::$has_medialib ) { add_thickbox(); wp_enqueue_script('media-upload'); } } public static function editor_js() { global $tinymce_version, $concatenate_scripts, $compress_scripts; /** * Filter "tiny_mce_version" is deprecated * * The tiny_mce_version filter is not needed since external plugins are loaded directly by TinyMCE. * These plugins can be refreshed by appending query string to the URL passed to "mce_external_plugins" filter. * If the plugin has a popup dialog, a query string can be added to the button action that opens it (in the plugin's code). */ $version = 'ver=' . $tinymce_version; $tmce_on = !empty(self::$mce_settings); if ( ! isset($concatenate_scripts) ) script_concat_settings(); $compressed = $compress_scripts && $concatenate_scripts && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && false !== stripos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'); if ( $tmce_on && 'en' != self::$mce_locale ) include_once(ABSPATH . WPINC . '/js/tinymce/langs/wp-langs.php'); $mceInit = $qtInit = ''; if ( $tmce_on ) { foreach ( self::$mce_settings as $editor_id => $init ) { $options = self::_parse_init( $init ); $mceInit .= "'$editor_id':{$options},"; } $mceInit = '{' . trim($mceInit, ',') . '}'; } else { $mceInit = '{}'; } if ( !empty(self::$qt_settings) ) { foreach ( self::$qt_settings as $editor_id => $init ) { $options = self::_parse_init( $init ); $qtInit .= "'$editor_id':{$options},"; } $qtInit = '{' . trim($qtInit, ',') . '}'; } else { $qtInit = '{}'; } $ref = array( 'plugins' => implode( ',', self::$plugins ), 'theme' => 'advanced', 'language' => self::$mce_locale ); $suffix = ( defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ) ? '_src' : ''; do_action('before_wp_tiny_mce', self::$mce_settings); ?> <script type="text/javascript"> tinyMCEPreInit = { base : "<?php echo self::$baseurl; ?>", suffix : "<?php echo $suffix; ?>", query : "<?php echo $version; ?>", mceInit : <?php echo $mceInit; ?>, qtInit : <?php echo $qtInit; ?>, ref : <?php echo self::_parse_init( $ref ); ?>, load_ext : function(url,lang){var sl=tinymce.ScriptLoader;sl.markDone(url+'/langs/'+lang+'.js');sl.markDone(url+'/langs/'+lang+'_dlg.js');} }; </script> <?php $baseurl = self::$baseurl; if ( $tmce_on ) { if ( $compressed ) { echo "<script type='text/javascript' src='{$baseurl}/wp-tinymce.php?c=1&amp;$version'></script>\n"; } else { echo "<script type='text/javascript' src='{$baseurl}/tiny_mce.js?$version'></script>\n"; echo "<script type='text/javascript' src='{$baseurl}/wp-tinymce-schema.js?$version'></script>\n"; } if ( 'en' != self::$mce_locale && isset($lang) ) echo "<script type='text/javascript'>\n$lang\n</script>\n"; else echo "<script type='text/javascript' src='{$baseurl}/langs/wp-langs-en.js?$version'></script>\n"; } $mce = ( self::$has_tinymce && wp_default_editor() == 'tinymce' ) || ! self::$has_quicktags; ?> <script type="text/javascript"> var wpActiveEditor; (function(){ var init, ed, qt, first_init, DOM, el, i, mce = <?php echo (int) $mce; ?>; if ( typeof(tinymce) == 'object' ) { DOM = tinymce.DOM; // mark wp_theme/ui.css as loaded DOM.files[tinymce.baseURI.getURI() + '/themes/advanced/skins/wp_theme/ui.css'] = true; DOM.events.add( DOM.select('.wp-editor-wrap'), 'mousedown', function(e){ if ( this.id ) wpActiveEditor = this.id.slice(3, -5); }); for ( ed in tinyMCEPreInit.mceInit ) { if ( first_init ) { init = tinyMCEPreInit.mceInit[ed] = tinymce.extend( {}, first_init, tinyMCEPreInit.mceInit[ed] ); } else { init = first_init = tinyMCEPreInit.mceInit[ed]; } if ( mce ) try { tinymce.init(init); } catch(e){} } } else { if ( tinyMCEPreInit.qtInit ) { for ( i in tinyMCEPreInit.qtInit ) { el = tinyMCEPreInit.qtInit[i].id; if ( el ) document.getElementById('wp-'+el+'-wrap').onmousedown = function(){ wpActiveEditor = this.id.slice(3, -5); } } } } if ( typeof(QTags) == 'function' ) { for ( qt in tinyMCEPreInit.qtInit ) { try { quicktags( tinyMCEPreInit.qtInit[qt] ); } catch(e){} } } })(); <?php if ( self::$ext_plugins ) echo self::$ext_plugins . "\n"; if ( ! $compressed && $tmce_on ) { ?> (function(){var t=tinyMCEPreInit,sl=tinymce.ScriptLoader,ln=t.ref.language,th=t.ref.theme,pl=t.ref.plugins;sl.markDone(t.base+'/langs/'+ln+'.js');sl.markDone(t.base+'/themes/'+th+'/langs/'+ln+'.js');sl.markDone(t.base+'/themes/'+th+'/langs/'+ln+'_dlg.js');sl.markDone(t.base+'/themes/advanced/skins/wp_theme/ui.css');tinymce.each(pl.split(','),function(n){if(n&&n.charAt(0)!='-'){sl.markDone(t.base+'/plugins/'+n+'/langs/'+ln+'.js');sl.markDone(t.base+'/plugins/'+n+'/langs/'+ln+'_dlg.js');}});})(); <?php } if ( !is_admin() ) echo 'var ajaxurl = "' . admin_url( 'admin-ajax.php', 'relative' ) . '";'; ?> </script> <?php if ( in_array('wplink', self::$plugins, true) || in_array('link', self::$qt_buttons, true) ) self::wp_link_dialog(); if ( in_array('wpfullscreen', self::$plugins, true) || in_array('fullscreen', self::$qt_buttons, true) ) self::wp_fullscreen_html(); do_action('after_wp_tiny_mce', self::$mce_settings); } public static function wp_fullscreen_html() { global $content_width; $post = get_post(); $width = isset($content_width) && 800 > $content_width ? $content_width : 800; $width = $width + 22; // compensate for the padding and border $dfw_width = get_user_setting( 'dfw_width', $width ); $save = isset($post->post_status) && $post->post_status == 'publish' ? __('Update') : __('Save'); ?> <div id="wp-fullscreen-body"<?php if ( is_rtl() ) echo ' class="rtl"'; ?>> <div id="fullscreen-topbar"> <div id="wp-fullscreen-toolbar"> <div id="wp-fullscreen-close"><a href="#" onclick="fullscreen.off();return false;"><?php _e('Exit fullscreen'); ?></a></div> <div id="wp-fullscreen-central-toolbar" style="width:<?php echo $width; ?>px;"> <div id="wp-fullscreen-mode-bar"><div id="wp-fullscreen-modes"> <a href="#" onclick="fullscreen.switchmode('tinymce');return false;"><?php _e( 'Visual' ); ?></a> <a href="#" onclick="fullscreen.switchmode('html');return false;"><?php _ex( 'Text', 'Name for the Text editor tab (formerly HTML)' ); ?></a> </div></div> <div id="wp-fullscreen-button-bar"><div id="wp-fullscreen-buttons" class="wp_themeSkin"> <?php $buttons = array( // format: title, onclick, show in both editors 'bold' => array( 'title' => __('Bold (Ctrl + B)'), 'onclick' => 'fullscreen.b();', 'both' => false ), 'italic' => array( 'title' => __('Italic (Ctrl + I)'), 'onclick' => 'fullscreen.i();', 'both' => false ), '0' => 'separator', 'bullist' => array( 'title' => __('Unordered list (Alt + Shift + U)'), 'onclick' => 'fullscreen.ul();', 'both' => false ), 'numlist' => array( 'title' => __('Ordered list (Alt + Shift + O)'), 'onclick' => 'fullscreen.ol();', 'both' => false ), '1' => 'separator', 'blockquote' => array( 'title' => __('Blockquote (Alt + Shift + Q)'), 'onclick' => 'fullscreen.blockquote();', 'both' => false ), 'image' => array( 'title' => __('Insert/edit image (Alt + Shift + M)'), 'onclick' => "fullscreen.medialib();", 'both' => true ), '2' => 'separator', 'link' => array( 'title' => __('Insert/edit link (Alt + Shift + A)'), 'onclick' => 'fullscreen.link();', 'both' => true ), 'unlink' => array( 'title' => __('Unlink (Alt + Shift + S)'), 'onclick' => 'fullscreen.unlink();', 'both' => false ), '3' => 'separator', 'help' => array( 'title' => __('Help (Alt + Shift + H)'), 'onclick' => 'fullscreen.help();', 'both' => false ) ); $buttons = apply_filters( 'wp_fullscreen_buttons', $buttons ); foreach ( $buttons as $button => $args ) { if ( 'separator' == $args ) { ?> <div><span aria-orientation="vertical" role="separator" class="mceSeparator"></span></div> <?php continue; } ?> <div<?php if ( $args['both'] ) { ?> class="wp-fullscreen-both"<?php } ?>> <a title="<?php echo $args['title']; ?>" onclick="<?php echo $args['onclick']; ?>return false;" class="mceButton mceButtonEnabled mce_<?php echo $button; ?>" href="#" id="wp_fs_<?php echo $button; ?>" role="button" aria-pressed="false"> <span class="mceIcon mce_<?php echo $button; ?>"></span> </a> </div> <?php } ?> </div></div> <div id="wp-fullscreen-save"> <input type="button" class="button-primary right" value="<?php echo $save; ?>" onclick="fullscreen.save();" /> <span class="spinner"></span> <span class="fs-saved"><?php if ( $post->post_status == 'publish' ) _e('Updated.'); else _e('Saved.'); ?></span> </div> </div> </div> </div> <div id="wp-fullscreen-wrap" style="width:<?php echo $dfw_width; ?>px;"> <?php if ( post_type_supports($post->post_type, 'title') ) { ?> <label id="wp-fullscreen-title-prompt-text" for="wp-fullscreen-title"><?php echo apply_filters( 'enter_title_here', __( 'Enter title here' ), $post ); ?></label> <input type="text" id="wp-fullscreen-title" value="" autocomplete="off" /> <?php } ?> <div id="wp-fullscreen-container"> <textarea id="wp_mce_fullscreen"></textarea> </div> <div id="wp-fullscreen-status"> <div id="wp-fullscreen-count"><?php printf( __( 'Word count: %s' ), '<span class="word-count">0</span>' ); ?></div> <div id="wp-fullscreen-tagline"><?php _e('Just write.'); ?></div> </div> </div> </div> <div class="fullscreen-overlay" id="fullscreen-overlay"></div> <div class="fullscreen-overlay fullscreen-fader fade-600" id="fullscreen-fader"></div> <?php } /** * Performs post queries for internal linking. * * @since 3.1.0 * * @param array $args Optional. Accepts 'pagenum' and 's' (search) arguments. * @return array Results. */ public static function wp_link_query( $args = array() ) { $pts = get_post_types( array( 'public' => true ), 'objects' ); $pt_names = array_keys( $pts ); $query = array( 'post_type' => $pt_names, 'suppress_filters' => true, 'update_post_term_cache' => false, 'update_post_meta_cache' => false, 'post_status' => 'publish', 'order' => 'DESC', 'orderby' => 'post_date', 'posts_per_page' => 20, ); $args['pagenum'] = isset( $args['pagenum'] ) ? absint( $args['pagenum'] ) : 1; if ( isset( $args['s'] ) ) $query['s'] = $args['s']; $query['offset'] = $args['pagenum'] > 1 ? $query['posts_per_page'] * ( $args['pagenum'] - 1 ) : 0; // Do main query. $get_posts = new WP_Query; $posts = $get_posts->query( $query ); // Check if any posts were found. if ( ! $get_posts->post_count ) return false; // Build results. $results = array(); foreach ( $posts as $post ) { if ( 'post' == $post->post_type ) $info = mysql2date( __( 'Y/m/d' ), $post->post_date ); else $info = $pts[ $post->post_type ]->labels->singular_name; $results[] = array( 'ID' => $post->ID, 'title' => trim( esc_html( strip_tags( get_the_title( $post ) ) ) ), 'permalink' => get_permalink( $post->ID ), 'info' => $info, ); } return $results; } /** * Dialog for internal linking. * * @since 3.1.0 */ public static function wp_link_dialog() { ?> <div style="display:none;"> <form id="wp-link" tabindex="-1"> <?php wp_nonce_field( 'internal-linking', '_ajax_linking_nonce', false ); ?> <div id="link-selector"> <div id="link-options"> <p class="howto"><?php _e( 'Enter the destination URL' ); ?></p> <div> <label><span><?php _e( 'URL' ); ?></span><input id="url-field" type="text" name="href" /></label> </div> <div> <label><span><?php _e( 'Title' ); ?></span><input id="link-title-field" type="text" name="linktitle" /></label> </div> <div class="link-target"> <label><input type="checkbox" id="link-target-checkbox" /> <?php _e( 'Open link in a new window/tab' ); ?></label> </div> </div> <?php $show_internal = '1' == get_user_setting( 'wplink', '0' ); ?> <p class="howto toggle-arrow <?php if ( $show_internal ) echo 'toggle-arrow-active'; ?>" id="internal-toggle"><?php _e( 'Or link to existing content' ); ?></p> <div id="search-panel"<?php if ( ! $show_internal ) echo ' style="display:none"'; ?>> <div class="link-search-wrapper"> <label> <span class="search-label"><?php _e( 'Search' ); ?></span> <input type="search" id="search-field" class="link-search-field" autocomplete="off" /> <span class="spinner"></span> </label> </div> <div id="search-results" class="query-results"> <ul></ul> <div class="river-waiting"> <span class="spinner"></span> </div> </div> <div id="most-recent-results" class="query-results"> <div class="query-notice"><em><?php _e( 'No search term specified. Showing recent items.' ); ?></em></div> <ul></ul> <div class="river-waiting"> <span class="spinner"></span> </div> </div> </div> </div> <div class="submitbox"> <div id="wp-link-update"> <input type="submit" value="<?php esc_attr_e( 'Add Link' ); ?>" class="button-primary" id="wp-link-submit" name="wp-link-submit"> </div> <div id="wp-link-cancel"> <a class="submitdelete deletion" href="#"><?php _e( 'Cancel' ); ?></a> </div> </div> </form> </div> <?php } }
zyblog
trunk/zyblog/wp-includes/class-wp-editor.php
PHP
asf20
33,112
<?php /** * Navigation Menu template functions * * @package WordPress * @subpackage Nav_Menus * @since 3.0.0 */ /** * Create HTML list of nav menu items. * * @package WordPress * @since 3.0.0 * @uses Walker */ class Walker_Nav_Menu extends Walker { /** * @see Walker::$tree_type * @since 3.0.0 * @var string */ var $tree_type = array( 'post_type', 'taxonomy', 'custom' ); /** * @see Walker::$db_fields * @since 3.0.0 * @todo Decouple this. * @var array */ var $db_fields = array( 'parent' => 'menu_item_parent', 'id' => 'db_id' ); /** * @see Walker::start_lvl() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param int $depth Depth of page. Used for padding. */ function start_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<ul class=\"sub-menu\">\n"; } /** * @see Walker::end_lvl() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param int $depth Depth of page. Used for padding. */ function end_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "$indent</ul>\n"; } /** * @see Walker::start_el() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $item Menu item data object. * @param int $depth Depth of menu item. Used for padding. * @param int $current_page Menu item ID. * @param object $args */ function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) { $indent = ( $depth ) ? str_repeat( "\t", $depth ) : ''; $class_names = $value = ''; $classes = empty( $item->classes ) ? array() : (array) $item->classes; $classes[] = 'menu-item-' . $item->ID; $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item, $args ) ); $class_names = $class_names ? ' class="' . esc_attr( $class_names ) . '"' : ''; $id = apply_filters( 'nav_menu_item_id', 'menu-item-'. $item->ID, $item, $args ); $id = $id ? ' id="' . esc_attr( $id ) . '"' : ''; $output .= $indent . '<li' . $id . $value . $class_names .'>'; $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : ''; $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : ''; $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : ''; $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : ''; $item_output = $args->before; $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args ); } /** * @see Walker::end_el() * @since 3.0.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $item Page data object. Not used. * @param int $depth Depth of page. Not Used. */ function end_el( &$output, $item, $depth = 0, $args = array() ) { $output .= "</li>\n"; } } /** * Displays a navigation menu. * * Optional $args contents: * * menu - The menu that is desired. Accepts (matching in order) id, slug, name. Defaults to blank. * menu_class - CSS class to use for the ul element which forms the menu. Defaults to 'menu'. * menu_id - The ID that is applied to the ul element which forms the menu. Defaults to the menu slug, incremented. * container - Whether to wrap the ul, and what to wrap it with. Defaults to 'div'. * container_class - the class that is applied to the container. Defaults to 'menu-{menu slug}-container'. * container_id - The ID that is applied to the container. Defaults to blank. * fallback_cb - If the menu doesn't exists, a callback function will fire. Defaults to 'wp_page_menu'. Set to false for no fallback. * before - Text before the link text. * after - Text after the link text. * link_before - Text before the link. * link_after - Text after the link. * echo - Whether to echo the menu or return it. Defaults to echo. * depth - how many levels of the hierarchy are to be included. 0 means all. Defaults to 0. * walker - allows a custom walker to be specified. * theme_location - the location in the theme to be used. Must be registered with register_nav_menu() in order to be selectable by the user. * items_wrap - How the list items should be wrapped. Defaults to a ul with an id and class. Uses printf() format with numbered placeholders. * * @since 3.0.0 * * @param array $args Arguments */ function wp_nav_menu( $args = array() ) { static $menu_id_slugs = array(); $defaults = array( 'menu' => '', 'container' => 'div', 'container_class' => '', 'container_id' => '', 'menu_class' => 'menu', 'menu_id' => '', 'echo' => true, 'fallback_cb' => 'wp_page_menu', 'before' => '', 'after' => '', 'link_before' => '', 'link_after' => '', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 0, 'walker' => '', 'theme_location' => '' ); $args = wp_parse_args( $args, $defaults ); $args = apply_filters( 'wp_nav_menu_args', $args ); $args = (object) $args; // Get the nav menu based on the requested menu $menu = wp_get_nav_menu_object( $args->menu ); // Get the nav menu based on the theme_location if ( ! $menu && $args->theme_location && ( $locations = get_nav_menu_locations() ) && isset( $locations[ $args->theme_location ] ) ) $menu = wp_get_nav_menu_object( $locations[ $args->theme_location ] ); // get the first menu that has items if we still can't find a menu if ( ! $menu && !$args->theme_location ) { $menus = wp_get_nav_menus(); foreach ( $menus as $menu_maybe ) { if ( $menu_items = wp_get_nav_menu_items( $menu_maybe->term_id, array( 'update_post_term_cache' => false ) ) ) { $menu = $menu_maybe; break; } } } // If the menu exists, get its items. if ( $menu && ! is_wp_error($menu) && !isset($menu_items) ) $menu_items = wp_get_nav_menu_items( $menu->term_id, array( 'update_post_term_cache' => false ) ); /* * If no menu was found: * - Fallback (if one was specified), or bail. * * If no menu items were found: * - Fallback, but only if no theme location was specified. * - Otherwise, bail. */ if ( ( !$menu || is_wp_error($menu) || ( isset($menu_items) && empty($menu_items) && !$args->theme_location ) ) && $args->fallback_cb && is_callable( $args->fallback_cb ) ) return call_user_func( $args->fallback_cb, (array) $args ); if ( !$menu || is_wp_error( $menu ) || empty( $menu_items ) ) return false; $nav_menu = $items = ''; $show_container = false; if ( $args->container ) { $allowed_tags = apply_filters( 'wp_nav_menu_container_allowedtags', array( 'div', 'nav' ) ); if ( in_array( $args->container, $allowed_tags ) ) { $show_container = true; $class = $args->container_class ? ' class="' . esc_attr( $args->container_class ) . '"' : ' class="menu-'. $menu->slug .'-container"'; $id = $args->container_id ? ' id="' . esc_attr( $args->container_id ) . '"' : ''; $nav_menu .= '<'. $args->container . $id . $class . '>'; } } // Set up the $menu_item variables _wp_menu_item_classes_by_context( $menu_items ); $sorted_menu_items = array(); foreach ( (array) $menu_items as $key => $menu_item ) $sorted_menu_items[$menu_item->menu_order] = $menu_item; unset($menu_items); $sorted_menu_items = apply_filters( 'wp_nav_menu_objects', $sorted_menu_items, $args ); $items .= walk_nav_menu_tree( $sorted_menu_items, $args->depth, $args ); unset($sorted_menu_items); // Attributes if ( ! empty( $args->menu_id ) ) { $wrap_id = $args->menu_id; } else { $wrap_id = 'menu-' . $menu->slug; while ( in_array( $wrap_id, $menu_id_slugs ) ) { if ( preg_match( '#-(\d+)$#', $wrap_id, $matches ) ) $wrap_id = preg_replace('#-(\d+)$#', '-' . ++$matches[1], $wrap_id ); else $wrap_id = $wrap_id . '-1'; } } $menu_id_slugs[] = $wrap_id; $wrap_class = $args->menu_class ? $args->menu_class : ''; // Allow plugins to hook into the menu to add their own <li>'s $items = apply_filters( 'wp_nav_menu_items', $items, $args ); $items = apply_filters( "wp_nav_menu_{$menu->slug}_items", $items, $args ); $nav_menu .= sprintf( $args->items_wrap, esc_attr( $wrap_id ), esc_attr( $wrap_class ), $items ); unset( $items ); if ( $show_container ) $nav_menu .= '</' . $args->container . '>'; $nav_menu = apply_filters( 'wp_nav_menu', $nav_menu, $args ); if ( $args->echo ) echo $nav_menu; else return $nav_menu; } /** * Add the class property classes for the current context, if applicable. * * @access private * @since 3.0 * * @param array $menu_items The current menu item objects to which to add the class property information. */ function _wp_menu_item_classes_by_context( &$menu_items ) { global $wp_query; $queried_object = $wp_query->get_queried_object(); $queried_object_id = (int) $wp_query->queried_object_id; $active_object = ''; $active_ancestor_item_ids = array(); $active_parent_item_ids = array(); $active_parent_object_ids = array(); $possible_taxonomy_ancestors = array(); $possible_object_parents = array(); $home_page_id = (int) get_option( 'page_for_posts' ); if ( $wp_query->is_singular && ! empty( $queried_object->post_type ) && ! is_post_type_hierarchical( $queried_object->post_type ) ) { foreach ( (array) get_object_taxonomies( $queried_object->post_type ) as $taxonomy ) { if ( is_taxonomy_hierarchical( $taxonomy ) ) { $term_hierarchy = _get_term_hierarchy( $taxonomy ); $terms = wp_get_object_terms( $queried_object_id, $taxonomy, array( 'fields' => 'ids' ) ); if ( is_array( $terms ) ) { $possible_object_parents = array_merge( $possible_object_parents, $terms ); $term_to_ancestor = array(); foreach ( (array) $term_hierarchy as $anc => $descs ) { foreach ( (array) $descs as $desc ) $term_to_ancestor[ $desc ] = $anc; } foreach ( $terms as $desc ) { do { $possible_taxonomy_ancestors[ $taxonomy ][] = $desc; if ( isset( $term_to_ancestor[ $desc ] ) ) { $_desc = $term_to_ancestor[ $desc ]; unset( $term_to_ancestor[ $desc ] ); $desc = $_desc; } else { $desc = 0; } } while ( ! empty( $desc ) ); } } } } } elseif ( ! empty( $queried_object->taxonomy ) && is_taxonomy_hierarchical( $queried_object->taxonomy ) ) { $term_hierarchy = _get_term_hierarchy( $queried_object->taxonomy ); $term_to_ancestor = array(); foreach ( (array) $term_hierarchy as $anc => $descs ) { foreach ( (array) $descs as $desc ) $term_to_ancestor[ $desc ] = $anc; } $desc = $queried_object->term_id; do { $possible_taxonomy_ancestors[ $queried_object->taxonomy ][] = $desc; if ( isset( $term_to_ancestor[ $desc ] ) ) { $_desc = $term_to_ancestor[ $desc ]; unset( $term_to_ancestor[ $desc ] ); $desc = $_desc; } else { $desc = 0; } } while ( ! empty( $desc ) ); } $possible_object_parents = array_filter( $possible_object_parents ); $front_page_url = home_url(); foreach ( (array) $menu_items as $key => $menu_item ) { $menu_items[$key]->current = false; $classes = (array) $menu_item->classes; $classes[] = 'menu-item'; $classes[] = 'menu-item-type-' . $menu_item->type; $classes[] = 'menu-item-object-' . $menu_item->object; // if the menu item corresponds to a taxonomy term for the currently-queried non-hierarchical post object if ( $wp_query->is_singular && 'taxonomy' == $menu_item->type && in_array( $menu_item->object_id, $possible_object_parents ) ) { $active_parent_object_ids[] = (int) $menu_item->object_id; $active_parent_item_ids[] = (int) $menu_item->db_id; $active_object = $queried_object->post_type; // if the menu item corresponds to the currently-queried post or taxonomy object } elseif ( $menu_item->object_id == $queried_object_id && ( ( ! empty( $home_page_id ) && 'post_type' == $menu_item->type && $wp_query->is_home && $home_page_id == $menu_item->object_id ) || ( 'post_type' == $menu_item->type && $wp_query->is_singular ) || ( 'taxonomy' == $menu_item->type && ( $wp_query->is_category || $wp_query->is_tag || $wp_query->is_tax ) && $queried_object->taxonomy == $menu_item->object ) ) ) { $classes[] = 'current-menu-item'; $menu_items[$key]->current = true; $_anc_id = (int) $menu_item->db_id; while( ( $_anc_id = get_post_meta( $_anc_id, '_menu_item_menu_item_parent', true ) ) && ! in_array( $_anc_id, $active_ancestor_item_ids ) ) { $active_ancestor_item_ids[] = $_anc_id; } if ( 'post_type' == $menu_item->type && 'page' == $menu_item->object ) { // Back compat classes for pages to match wp_page_menu() $classes[] = 'page_item'; $classes[] = 'page-item-' . $menu_item->object_id; $classes[] = 'current_page_item'; } $active_parent_item_ids[] = (int) $menu_item->menu_item_parent; $active_parent_object_ids[] = (int) $menu_item->post_parent; $active_object = $menu_item->object; // if the menu item corresponds to the currently-requested URL } elseif ( 'custom' == $menu_item->object ) { $_root_relative_current = untrailingslashit( $_SERVER['REQUEST_URI'] ); $current_url = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_root_relative_current ); $raw_item_url = strpos( $menu_item->url, '#' ) ? substr( $menu_item->url, 0, strpos( $menu_item->url, '#' ) ) : $menu_item->url; $item_url = untrailingslashit( $raw_item_url ); $_indexless_current = untrailingslashit( preg_replace( '/index.php$/', '', $current_url ) ); if ( $raw_item_url && in_array( $item_url, array( $current_url, $_indexless_current, $_root_relative_current ) ) ) { $classes[] = 'current-menu-item'; $menu_items[$key]->current = true; $_anc_id = (int) $menu_item->db_id; while( ( $_anc_id = get_post_meta( $_anc_id, '_menu_item_menu_item_parent', true ) ) && ! in_array( $_anc_id, $active_ancestor_item_ids ) ) { $active_ancestor_item_ids[] = $_anc_id; } if ( in_array( home_url(), array( untrailingslashit( $current_url ), untrailingslashit( $_indexless_current ) ) ) ) { // Back compat for home link to match wp_page_menu() $classes[] = 'current_page_item'; } $active_parent_item_ids[] = (int) $menu_item->menu_item_parent; $active_parent_object_ids[] = (int) $menu_item->post_parent; $active_object = $menu_item->object; // give front page item current-menu-item class when extra query arguments involved } elseif ( $item_url == $front_page_url && is_front_page() ) { $classes[] = 'current-menu-item'; } if ( untrailingslashit($item_url) == home_url() ) $classes[] = 'menu-item-home'; } // back-compat with wp_page_menu: add "current_page_parent" to static home page link for any non-page query if ( ! empty( $home_page_id ) && 'post_type' == $menu_item->type && empty( $wp_query->is_page ) && $home_page_id == $menu_item->object_id ) $classes[] = 'current_page_parent'; $menu_items[$key]->classes = array_unique( $classes ); } $active_ancestor_item_ids = array_filter( array_unique( $active_ancestor_item_ids ) ); $active_parent_item_ids = array_filter( array_unique( $active_parent_item_ids ) ); $active_parent_object_ids = array_filter( array_unique( $active_parent_object_ids ) ); // set parent's class foreach ( (array) $menu_items as $key => $parent_item ) { $classes = (array) $parent_item->classes; $menu_items[$key]->current_item_ancestor = false; $menu_items[$key]->current_item_parent = false; if ( isset( $parent_item->type ) && ( // ancestral post object ( 'post_type' == $parent_item->type && ! empty( $queried_object->post_type ) && is_post_type_hierarchical( $queried_object->post_type ) && in_array( $parent_item->object_id, $queried_object->ancestors ) && $parent_item->object != $queried_object->ID ) || // ancestral term ( 'taxonomy' == $parent_item->type && isset( $possible_taxonomy_ancestors[ $parent_item->object ] ) && in_array( $parent_item->object_id, $possible_taxonomy_ancestors[ $parent_item->object ] ) && ( ! isset( $queried_object->term_id ) || $parent_item->object_id != $queried_object->term_id ) ) ) ) { $classes[] = empty( $queried_object->taxonomy ) ? 'current-' . $queried_object->post_type . '-ancestor' : 'current-' . $queried_object->taxonomy . '-ancestor'; } if ( in_array( intval( $parent_item->db_id ), $active_ancestor_item_ids ) ) { $classes[] = 'current-menu-ancestor'; $menu_items[$key]->current_item_ancestor = true; } if ( in_array( $parent_item->db_id, $active_parent_item_ids ) ) { $classes[] = 'current-menu-parent'; $menu_items[$key]->current_item_parent = true; } if ( in_array( $parent_item->object_id, $active_parent_object_ids ) ) $classes[] = 'current-' . $active_object . '-parent'; if ( 'post_type' == $parent_item->type && 'page' == $parent_item->object ) { // Back compat classes for pages to match wp_page_menu() if ( in_array('current-menu-parent', $classes) ) $classes[] = 'current_page_parent'; if ( in_array('current-menu-ancestor', $classes) ) $classes[] = 'current_page_ancestor'; } $menu_items[$key]->classes = array_unique( $classes ); } } /** * Retrieve the HTML list content for nav menu items. * * @uses Walker_Nav_Menu to create HTML list content. * @since 3.0.0 * @see Walker::walk() for parameters and return description. */ function walk_nav_menu_tree( $items, $depth, $r ) { $walker = ( empty($r->walker) ) ? new Walker_Nav_Menu : $r->walker; $args = array( $items, $depth, $r ); return call_user_func_array( array($walker, 'walk'), $args ); } /** * Prevents a menu item ID from being used more than once. * * @since 3.0.1 * @access private */ function _nav_menu_item_id_use_once( $id, $item ) { static $_used_ids = array(); if ( in_array( $item->ID, $_used_ids ) ) return ''; $_used_ids[] = $item->ID; return $id; } add_filter( 'nav_menu_item_id', '_nav_menu_item_id_use_once', 10, 2 );
zyblog
trunk/zyblog/wp-includes/nav-menu-template.php
PHP
asf20
18,431
<?php /** * Post functions and post utility function. * * @package WordPress * @subpackage Post * @since 1.5.0 */ // // Post Type Registration // /** * Creates the initial post types when 'init' action is fired. * * @since 2.9.0 */ function create_initial_post_types() { register_post_type( 'post', array( 'labels' => array( 'name_admin_bar' => _x( 'Post', 'add new on admin bar' ), ), 'public' => true, '_builtin' => true, /* internal use only. don't use this when registering your own post type. */ '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */ 'capability_type' => 'post', 'map_meta_cap' => true, 'hierarchical' => false, 'rewrite' => false, 'query_var' => false, 'delete_with_user' => true, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ), ) ); register_post_type( 'page', array( 'labels' => array( 'name_admin_bar' => _x( 'Page', 'add new on admin bar' ), ), 'public' => true, 'publicly_queryable' => false, '_builtin' => true, /* internal use only. don't use this when registering your own post type. */ '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */ 'capability_type' => 'page', 'map_meta_cap' => true, 'hierarchical' => true, 'rewrite' => false, 'query_var' => false, 'delete_with_user' => true, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'page-attributes', 'custom-fields', 'comments', 'revisions' ), ) ); register_post_type( 'attachment', array( 'labels' => array( 'name' => _x('Media', 'post type general name'), 'name_admin_bar' => _x( 'Media', 'add new from admin bar' ), 'add_new' => _x( 'Add New', 'add new media' ), 'edit_item' => __( 'Edit Media' ), 'view_item' => __( 'View Attachment Page' ), ), 'public' => true, 'show_ui' => true, '_builtin' => true, /* internal use only. don't use this when registering your own post type. */ '_edit_link' => 'post.php?post=%d', /* internal use only. don't use this when registering your own post type. */ 'capability_type' => 'post', 'capabilities' => array( 'create_posts' => 'upload_files', ), 'map_meta_cap' => true, 'hierarchical' => false, 'rewrite' => false, 'query_var' => false, 'show_in_nav_menus' => false, 'delete_with_user' => true, 'supports' => array( 'title', 'author', 'comments' ), ) ); register_post_type( 'revision', array( 'labels' => array( 'name' => __( 'Revisions' ), 'singular_name' => __( 'Revision' ), ), 'public' => false, '_builtin' => true, /* internal use only. don't use this when registering your own post type. */ '_edit_link' => 'revision.php?revision=%d', /* internal use only. don't use this when registering your own post type. */ 'capability_type' => 'post', 'map_meta_cap' => true, 'hierarchical' => false, 'rewrite' => false, 'query_var' => false, 'can_export' => false, 'delete_with_user' => true, 'supports' => array( 'author' ), ) ); register_post_type( 'nav_menu_item', array( 'labels' => array( 'name' => __( 'Navigation Menu Items' ), 'singular_name' => __( 'Navigation Menu Item' ), ), 'public' => false, '_builtin' => true, /* internal use only. don't use this when registering your own post type. */ 'hierarchical' => false, 'rewrite' => false, 'delete_with_user' => false, 'query_var' => false, ) ); register_post_status( 'publish', array( 'label' => _x( 'Published', 'post' ), 'public' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop( 'Published <span class="count">(%s)</span>', 'Published <span class="count">(%s)</span>' ), ) ); register_post_status( 'future', array( 'label' => _x( 'Scheduled', 'post' ), 'protected' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop('Scheduled <span class="count">(%s)</span>', 'Scheduled <span class="count">(%s)</span>' ), ) ); register_post_status( 'draft', array( 'label' => _x( 'Draft', 'post' ), 'protected' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop( 'Draft <span class="count">(%s)</span>', 'Drafts <span class="count">(%s)</span>' ), ) ); register_post_status( 'pending', array( 'label' => _x( 'Pending', 'post' ), 'protected' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop( 'Pending <span class="count">(%s)</span>', 'Pending <span class="count">(%s)</span>' ), ) ); register_post_status( 'private', array( 'label' => _x( 'Private', 'post' ), 'private' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop( 'Private <span class="count">(%s)</span>', 'Private <span class="count">(%s)</span>' ), ) ); register_post_status( 'trash', array( 'label' => _x( 'Trash', 'post' ), 'internal' => true, '_builtin' => true, /* internal use only. */ 'label_count' => _n_noop( 'Trash <span class="count">(%s)</span>', 'Trash <span class="count">(%s)</span>' ), 'show_in_admin_status_list' => true, ) ); register_post_status( 'auto-draft', array( 'label' => 'auto-draft', 'internal' => true, '_builtin' => true, /* internal use only. */ ) ); register_post_status( 'inherit', array( 'label' => 'inherit', 'internal' => true, '_builtin' => true, /* internal use only. */ 'exclude_from_search' => false, ) ); } add_action( 'init', 'create_initial_post_types', 0 ); // highest priority /** * Retrieve attached file path based on attachment ID. * * You can optionally send it through the 'get_attached_file' filter, but by * default it will just return the file path unfiltered. * * The function works by getting the single post meta name, named * '_wp_attached_file' and returning it. This is a convenience function to * prevent looking up the meta name and provide a mechanism for sending the * attached filename through a filter. * * @since 2.0.0 * @uses apply_filters() Calls 'get_attached_file' on file path and attachment ID. * * @param int $attachment_id Attachment ID. * @param bool $unfiltered Whether to apply filters. * @return string|bool The file path to the attached file, or false if the attachment does not exist. */ function get_attached_file( $attachment_id, $unfiltered = false ) { $file = get_post_meta( $attachment_id, '_wp_attached_file', true ); // If the file is relative, prepend upload dir if ( $file && 0 !== strpos($file, '/') && !preg_match('|^.:\\\|', $file) && ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) ) $file = $uploads['basedir'] . "/$file"; if ( $unfiltered ) return $file; return apply_filters( 'get_attached_file', $file, $attachment_id ); } /** * Update attachment file path based on attachment ID. * * Used to update the file path of the attachment, which uses post meta name * '_wp_attached_file' to store the path of the attachment. * * @since 2.1.0 * @uses apply_filters() Calls 'update_attached_file' on file path and attachment ID. * * @param int $attachment_id Attachment ID * @param string $file File path for the attachment * @return bool False on failure, true on success. */ function update_attached_file( $attachment_id, $file ) { if ( !get_post( $attachment_id ) ) return false; $file = apply_filters( 'update_attached_file', $file, $attachment_id ); if ( $file = _wp_relative_upload_path( $file ) ) return update_post_meta( $attachment_id, '_wp_attached_file', $file ); else return delete_post_meta( $attachment_id, '_wp_attached_file' ); } /** * Return relative path to an uploaded file. * * The path is relative to the current upload dir. * * @since 2.9.0 * @uses apply_filters() Calls '_wp_relative_upload_path' on file path. * * @param string $path Full path to the file * @return string relative path on success, unchanged path on failure. */ function _wp_relative_upload_path( $path ) { $new_path = $path; $uploads = wp_upload_dir(); if ( 0 === strpos( $new_path, $uploads['basedir'] ) ) { $new_path = str_replace( $uploads['basedir'], '', $new_path ); $new_path = ltrim( $new_path, '/' ); } return apply_filters( '_wp_relative_upload_path', $new_path, $path ); } /** * Retrieve all children of the post parent ID. * * Normally, without any enhancements, the children would apply to pages. In the * context of the inner workings of WordPress, pages, posts, and attachments * share the same table, so therefore the functionality could apply to any one * of them. It is then noted that while this function does not work on posts, it * does not mean that it won't work on posts. It is recommended that you know * what context you wish to retrieve the children of. * * Attachments may also be made the child of a post, so if that is an accurate * statement (which needs to be verified), it would then be possible to get * all of the attachments for a post. Attachments have since changed since * version 2.5, so this is most likely unaccurate, but serves generally as an * example of what is possible. * * The arguments listed as defaults are for this function and also of the * {@link get_posts()} function. The arguments are combined with the * get_children defaults and are then passed to the {@link get_posts()} * function, which accepts additional arguments. You can replace the defaults in * this function, listed below and the additional arguments listed in the * {@link get_posts()} function. * * The 'post_parent' is the most important argument and important attention * needs to be paid to the $args parameter. If you pass either an object or an * integer (number), then just the 'post_parent' is grabbed and everything else * is lost. If you don't specify any arguments, then it is assumed that you are * in The Loop and the post parent will be grabbed for from the current post. * * The 'post_parent' argument is the ID to get the children. The 'numberposts' * is the amount of posts to retrieve that has a default of '-1', which is * used to get all of the posts. Giving a number higher than 0 will only * retrieve that amount of posts. * * The 'post_type' and 'post_status' arguments can be used to choose what * criteria of posts to retrieve. The 'post_type' can be anything, but WordPress * post types are 'post', 'pages', and 'attachments'. The 'post_status' * argument will accept any post status within the write administration panels. * * @see get_posts() Has additional arguments that can be replaced. * @internal Claims made in the long description might be inaccurate. * * @since 2.0.0 * * @param mixed $args Optional. User defined arguments for replacing the defaults. * @param string $output Optional. Constant for return type, either OBJECT (default), ARRAY_A, ARRAY_N. * @return array|bool False on failure and the type will be determined by $output parameter. */ function get_children($args = '', $output = OBJECT) { $kids = array(); if ( empty( $args ) ) { if ( isset( $GLOBALS['post'] ) ) { $args = array('post_parent' => (int) $GLOBALS['post']->post_parent ); } else { return $kids; } } elseif ( is_object( $args ) ) { $args = array('post_parent' => (int) $args->post_parent ); } elseif ( is_numeric( $args ) ) { $args = array('post_parent' => (int) $args); } $defaults = array( 'numberposts' => -1, 'post_type' => 'any', 'post_status' => 'any', 'post_parent' => 0, ); $r = wp_parse_args( $args, $defaults ); $children = get_posts( $r ); if ( !$children ) return $kids; update_post_cache($children); foreach ( $children as $key => $child ) $kids[$child->ID] = $children[$key]; if ( $output == OBJECT ) { return $kids; } elseif ( $output == ARRAY_A ) { foreach ( (array) $kids as $kid ) $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]); return $weeuns; } elseif ( $output == ARRAY_N ) { foreach ( (array) $kids as $kid ) $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID])); return $babes; } else { return $kids; } } /** * Get extended entry info (<!--more-->). * * There should not be any space after the second dash and before the word * 'more'. There can be text or space(s) after the word 'more', but won't be * referenced. * * The returned array has 'main', 'extended', and 'more_text' keys. Main has the text before * the <code><!--more--></code>. The 'extended' key has the content after the * <code><!--more--></code> comment. The 'more_text' key has the custom "Read More" text. * * @since 1.0.0 * * @param string $post Post content. * @return array Post before ('main'), after ('extended'), and custom readmore ('more_text'). */ function get_extended($post) { //Match the new style more links if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) { list($main, $extended) = explode($matches[0], $post, 2); $more_text = $matches[1]; } else { $main = $post; $extended = ''; $more_text = ''; } // Strip leading and trailing whitespace $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main); $extended = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $extended); $more_text = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $more_text); return array( 'main' => $main, 'extended' => $extended, 'more_text' => $more_text ); } /** * Retrieves post data given a post ID or post object. * * See {@link sanitize_post()} for optional $filter values. Also, the parameter * $post, must be given as a variable, since it is passed by reference. * * @since 1.5.1 * @uses $wpdb * @link http://codex.wordpress.org/Function_Reference/get_post * * @param int|object $post Post ID or post object. Optional, default is the current post from the loop. * @param string $output Optional, default is Object. Either OBJECT, ARRAY_A, or ARRAY_N. * @param string $filter Optional, default is raw. * @return WP_Post|null WP_Post on success or null on failure */ function get_post( $post = null, $output = OBJECT, $filter = 'raw' ) { if ( empty( $post ) && isset( $GLOBALS['post'] ) ) $post = $GLOBALS['post']; if ( is_a( $post, 'WP_Post' ) ) { $_post = $post; } elseif ( is_object( $post ) ) { if ( empty( $post->filter ) ) { $_post = sanitize_post( $post, 'raw' ); $_post = new WP_Post( $_post ); } elseif ( 'raw' == $post->filter ) { $_post = new WP_Post( $post ); } else { $_post = WP_Post::get_instance( $post->ID ); } } else { $_post = WP_Post::get_instance( $post ); } if ( ! $_post ) return null; $_post = $_post->filter( $filter ); if ( $output == ARRAY_A ) return $_post->to_array(); elseif ( $output == ARRAY_N ) return array_values( $_post->to_array() ); return $_post; } /** * WordPress Post class. * * @since 3.5.0 * */ final class WP_Post { /** * * @var int */ public $ID; /** * * @var int */ public $post_author = 0; /** * * @var string */ public $post_date = '0000-00-00 00:00:00'; /** * * @var string */ public $post_date_gmt = '0000-00-00 00:00:00'; /** * * @var string */ public $post_content = ''; /** * * @var string */ public $post_title = ''; /** * * @var string */ public $post_excerpt = ''; /** * * @var string */ public $post_status = 'publish'; /** * * @var string */ public $comment_status = 'open'; /** * * @var string */ public $ping_status = 'open'; /** * * @var string */ public $post_password = ''; /** * * @var string */ public $post_name = ''; /** * * @var string */ public $to_ping = ''; /** * * @var string */ public $pinged = ''; /** * * @var string */ public $post_modified = '0000-00-00 00:00:00'; /** * * @var string */ public $post_modified_gmt = '0000-00-00 00:00:00'; /** * * @var string */ public $post_content_filtered = ''; /** * * @var int */ public $post_parent = 0; /** * * @var string */ public $guid = ''; /** * * @var int */ public $menu_order = 0; /** * * @var string */ public $post_type = 'post'; /** * * @var string */ public $post_mime_type = ''; /** * * @var int */ public $comment_count = 0; /** * * @var string */ public $filter; public static function get_instance( $post_id ) { global $wpdb; $post_id = (int) $post_id; if ( ! $post_id ) return false; $_post = wp_cache_get( $post_id, 'posts' ); if ( ! $_post ) { $_post = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE ID = %d LIMIT 1", $post_id ) ); if ( ! $_post ) return false; $_post = sanitize_post( $_post, 'raw' ); wp_cache_add( $_post->ID, $_post, 'posts' ); } elseif ( empty( $_post->filter ) ) { $_post = sanitize_post( $_post, 'raw' ); } return new WP_Post( $_post ); } public function __construct( $post ) { foreach ( get_object_vars( $post ) as $key => $value ) $this->$key = $value; } public function __isset( $key ) { if ( 'ancestors' == $key ) return true; if ( 'page_template' == $key ) return ( 'page' == $this->post_type ); if ( 'post_category' == $key ) return true; if ( 'tags_input' == $key ) return true; return metadata_exists( 'post', $this->ID, $key ); } public function __get( $key ) { if ( 'page_template' == $key && $this->__isset( $key ) ) { return get_post_meta( $this->ID, '_wp_page_template', true ); } if ( 'post_category' == $key ) { if ( is_object_in_taxonomy( $this->post_type, 'category' ) ) $terms = get_the_terms( $this, 'category' ); if ( empty( $terms ) ) return array(); return wp_list_pluck( $terms, 'term_id' ); } if ( 'tags_input' == $key ) { if ( is_object_in_taxonomy( $this->post_type, 'post_tag' ) ) $terms = get_the_terms( $this, 'post_tag' ); if ( empty( $terms ) ) return array(); return wp_list_pluck( $terms, 'name' ); } // Rest of the values need filtering if ( 'ancestors' == $key ) $value = get_post_ancestors( $this ); else $value = get_post_meta( $this->ID, $key, true ); if ( $this->filter ) $value = sanitize_post_field( $key, $value, $this->ID, $this->filter ); return $value; } public function filter( $filter ) { if ( $this->filter == $filter ) return $this; if ( $filter == 'raw' ) return self::get_instance( $this->ID ); return sanitize_post( $this, $filter ); } public function to_array() { $post = get_object_vars( $this ); foreach ( array( 'ancestors', 'page_template', 'post_category', 'tags_input' ) as $key ) { if ( $this->__isset( $key ) ) $post[ $key ] = $this->__get( $key ); } return $post; } } /** * Retrieve ancestors of a post. * * @since 2.5.0 * * @param int|object $post Post ID or post object * @return array Ancestor IDs or empty array if none are found. */ function get_post_ancestors( $post ) { if ( ! $post ) return false; $post = get_post( $post ); if ( empty( $post->post_parent ) || $post->post_parent == $post->ID ) return array(); $ancestors = array(); $id = $ancestors[] = $post->post_parent; while ( $ancestor = get_post( $id ) ) { // Loop detection: If the ancestor has been seen before, break. if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors ) ) break; $id = $ancestors[] = $ancestor->post_parent; } return $ancestors; } /** * Retrieve data from a post field based on Post ID. * * Examples of the post field will be, 'post_type', 'post_status', 'post_content', * etc and based off of the post object property or key names. * * The context values are based off of the taxonomy filter functions and * supported values are found within those functions. * * @since 2.3.0 * @uses sanitize_post_field() See for possible $context values. * * @param string $field Post field name * @param id $post Post ID * @param string $context Optional. How to filter the field. Default is display. * @return bool|string False on failure or returns the value in post field */ function get_post_field( $field, $post, $context = 'display' ) { $post = get_post( $post ); if ( !$post ) return ''; if ( !isset($post->$field) ) return ''; return sanitize_post_field($field, $post->$field, $post->ID, $context); } /** * Retrieve the mime type of an attachment based on the ID. * * This function can be used with any post type, but it makes more sense with * attachments. * * @since 2.0.0 * * @param int $ID Optional. Post ID. * @return bool|string False on failure or returns the mime type */ function get_post_mime_type($ID = '') { $post = get_post($ID); if ( is_object($post) ) return $post->post_mime_type; return false; } /** * Retrieve the format slug for a post * * @since 3.1.0 * * @param int|object $post A post * * @return mixed The format if successful. False if no format is set. WP_Error if errors. */ function get_post_format( $post = null ) { $post = get_post($post); if ( ! post_type_supports( $post->post_type, 'post-formats' ) ) return false; $_format = get_the_terms( $post->ID, 'post_format' ); if ( empty( $_format ) ) return false; $format = array_shift( $_format ); return ( str_replace('post-format-', '', $format->slug ) ); } /** * Check if a post has a particular format * * @since 3.1.0 * @uses has_term() * * @param string $format The format to check for * @param object|id $post The post to check. If not supplied, defaults to the current post if used in the loop. * @return bool True if the post has the format, false otherwise. */ function has_post_format( $format, $post = null ) { return has_term('post-format-' . sanitize_key($format), 'post_format', $post); } /** * Assign a format to a post * * @since 3.1.0 * * @param int|object $post The post for which to assign a format * @param string $format A format to assign. Use an empty string or array to remove all formats from the post. * @return mixed WP_Error on error. Array of affected term IDs on success. */ function set_post_format( $post, $format ) { $post = get_post($post); if ( empty($post) ) return new WP_Error('invalid_post', __('Invalid post')); if ( !empty($format) ) { $format = sanitize_key($format); if ( 'standard' == $format || !in_array( $format, array_keys( get_post_format_slugs() ) ) ) $format = ''; else $format = 'post-format-' . $format; } return wp_set_post_terms($post->ID, $format, 'post_format'); } /** * Retrieve the post status based on the Post ID. * * If the post ID is of an attachment, then the parent post status will be given * instead. * * @since 2.0.0 * * @param int $ID Post ID * @return string|bool Post status or false on failure. */ function get_post_status($ID = '') { $post = get_post($ID); if ( !is_object($post) ) return false; if ( 'attachment' == $post->post_type ) { if ( 'private' == $post->post_status ) return 'private'; // Unattached attachments are assumed to be published if ( ( 'inherit' == $post->post_status ) && ( 0 == $post->post_parent) ) return 'publish'; // Inherit status from the parent if ( $post->post_parent && ( $post->ID != $post->post_parent ) ) return get_post_status($post->post_parent); } return $post->post_status; } /** * Retrieve all of the WordPress supported post statuses. * * Posts have a limited set of valid status values, this provides the * post_status values and descriptions. * * @since 2.5.0 * * @return array List of post statuses. */ function get_post_statuses( ) { $status = array( 'draft' => __('Draft'), 'pending' => __('Pending Review'), 'private' => __('Private'), 'publish' => __('Published') ); return $status; } /** * Retrieve all of the WordPress support page statuses. * * Pages have a limited set of valid status values, this provides the * post_status values and descriptions. * * @since 2.5.0 * * @return array List of page statuses. */ function get_page_statuses( ) { $status = array( 'draft' => __('Draft'), 'private' => __('Private'), 'publish' => __('Published') ); return $status; } /** * Register a post status. Do not use before init. * * A simple function for creating or modifying a post status based on the * parameters given. The function will accept an array (second optional * parameter), along with a string for the post status name. * * * Optional $args contents: * * label - A descriptive name for the post status marked for translation. Defaults to $post_status. * public - Whether posts of this status should be shown in the front end of the site. Defaults to true. * exclude_from_search - Whether to exclude posts with this post status from search results. Defaults to false. * show_in_admin_all_list - Whether to include posts in the edit listing for their post type * show_in_admin_status_list - Show in the list of statuses with post counts at the top of the edit * listings, e.g. All (12) | Published (9) | My Custom Status (2) ... * * Arguments prefixed with an _underscore shouldn't be used by plugins and themes. * * @package WordPress * @subpackage Post * @since 3.0.0 * @uses $wp_post_statuses Inserts new post status object into the list * * @param string $post_status Name of the post status. * @param array|string $args See above description. */ function register_post_status($post_status, $args = array()) { global $wp_post_statuses; if (!is_array($wp_post_statuses)) $wp_post_statuses = array(); // Args prefixed with an underscore are reserved for internal use. $defaults = array( 'label' => false, 'label_count' => false, 'exclude_from_search' => null, '_builtin' => false, 'public' => null, 'internal' => null, 'protected' => null, 'private' => null, 'publicly_queryable' => null, 'show_in_admin_status_list' => null, 'show_in_admin_all_list' => null, ); $args = wp_parse_args($args, $defaults); $args = (object) $args; $post_status = sanitize_key($post_status); $args->name = $post_status; if ( null === $args->public && null === $args->internal && null === $args->protected && null === $args->private ) $args->internal = true; if ( null === $args->public ) $args->public = false; if ( null === $args->private ) $args->private = false; if ( null === $args->protected ) $args->protected = false; if ( null === $args->internal ) $args->internal = false; if ( null === $args->publicly_queryable ) $args->publicly_queryable = $args->public; if ( null === $args->exclude_from_search ) $args->exclude_from_search = $args->internal; if ( null === $args->show_in_admin_all_list ) $args->show_in_admin_all_list = !$args->internal; if ( null === $args->show_in_admin_status_list ) $args->show_in_admin_status_list = !$args->internal; if ( false === $args->label ) $args->label = $post_status; if ( false === $args->label_count ) $args->label_count = array( $args->label, $args->label ); $wp_post_statuses[$post_status] = $args; return $args; } /** * Retrieve a post status object by name * * @package WordPress * @subpackage Post * @since 3.0.0 * @uses $wp_post_statuses * @see register_post_status * @see get_post_statuses * * @param string $post_status The name of a registered post status * @return object A post status object */ function get_post_status_object( $post_status ) { global $wp_post_statuses; if ( empty($wp_post_statuses[$post_status]) ) return null; return $wp_post_statuses[$post_status]; } /** * Get a list of all registered post status objects. * * @package WordPress * @subpackage Post * @since 3.0.0 * @uses $wp_post_statuses * @see register_post_status * @see get_post_status_object * * @param array|string $args An array of key => value arguments to match against the post status objects. * @param string $output The type of output to return, either post status 'names' or 'objects'. 'names' is the default. * @param string $operator The logical operation to perform. 'or' means only one element * from the array needs to match; 'and' means all elements must match. The default is 'and'. * @return array A list of post status names or objects */ function get_post_stati( $args = array(), $output = 'names', $operator = 'and' ) { global $wp_post_statuses; $field = ('names' == $output) ? 'name' : false; return wp_filter_object_list($wp_post_statuses, $args, $operator, $field); } /** * Whether the post type is hierarchical. * * A false return value might also mean that the post type does not exist. * * @since 3.0.0 * @see get_post_type_object * * @param string $post_type Post type name * @return bool Whether post type is hierarchical. */ function is_post_type_hierarchical( $post_type ) { if ( ! post_type_exists( $post_type ) ) return false; $post_type = get_post_type_object( $post_type ); return $post_type->hierarchical; } /** * Checks if a post type is registered. * * @since 3.0.0 * @uses get_post_type_object() * * @param string $post_type Post type name * @return bool Whether post type is registered. */ function post_type_exists( $post_type ) { return (bool) get_post_type_object( $post_type ); } /** * Retrieve the post type of the current post or of a given post. * * @since 2.1.0 * * @uses $post The Loop current post global * * @param mixed $post Optional. Post object or post ID. * @return bool|string post type or false on failure. */ function get_post_type( $post = null ) { if ( $post = get_post( $post ) ) return $post->post_type; return false; } /** * Retrieve a post type object by name * * @package WordPress * @subpackage Post * @since 3.0.0 * @uses $wp_post_types * @see register_post_type * @see get_post_types * * @param string $post_type The name of a registered post type * @return object A post type object */ function get_post_type_object( $post_type ) { global $wp_post_types; if ( empty($wp_post_types[$post_type]) ) return null; return $wp_post_types[$post_type]; } /** * Get a list of all registered post type objects. * * @package WordPress * @subpackage Post * @since 2.9.0 * @uses $wp_post_types * @see register_post_type * * @param array|string $args An array of key => value arguments to match against the post type objects. * @param string $output The type of output to return, either post type 'names' or 'objects'. 'names' is the default. * @param string $operator The logical operation to perform. 'or' means only one element * from the array needs to match; 'and' means all elements must match. The default is 'and'. * @return array A list of post type names or objects */ function get_post_types( $args = array(), $output = 'names', $operator = 'and' ) { global $wp_post_types; $field = ('names' == $output) ? 'name' : false; return wp_filter_object_list($wp_post_types, $args, $operator, $field); } /** * Register a post type. Do not use before init. * * A function for creating or modifying a post type based on the * parameters given. The function will accept an array (second optional * parameter), along with a string for the post type name. * * Optional $args contents: * * - label - Name of the post type shown in the menu. Usually plural. If not set, labels['name'] will be used. * - labels - An array of labels for this post type. * * If not set, post labels are inherited for non-hierarchical types and page labels for hierarchical ones. * * You can see accepted values in {@link get_post_type_labels()}. * - description - A short descriptive summary of what the post type is. Defaults to blank. * - public - Whether a post type is intended for use publicly either via the admin interface or by front-end users. * * Defaults to false. * * While the default settings of exclude_from_search, publicly_queryable, show_ui, and show_in_nav_menus are * inherited from public, each does not rely on this relationship and controls a very specific intention. * - exclude_from_search - Whether to exclude posts with this post type from front end search results. * * If not set, the the opposite of public's current value is used. * - publicly_queryable - Whether queries can be performed on the front end for the post type as part of parse_request(). * * ?post_type={post_type_key} * * ?{post_type_key}={single_post_slug} * * ?{post_type_query_var}={single_post_slug} * * If not set, the default is inherited from public. * - show_ui - Whether to generate a default UI for managing this post type in the admin. * * If not set, the default is inherited from public. * - show_in_nav_menus - Makes this post type available for selection in navigation menus. * * If not set, the default is inherited from public. * - show_in_menu - Where to show the post type in the admin menu. * * If true, the post type is shown in its own top level menu. * * If false, no menu is shown * * If a string of an existing top level menu (eg. 'tools.php' or 'edit.php?post_type=page'), the post type will * be placed as a sub menu of that. * * show_ui must be true. * * If not set, the default is inherited from show_ui * - show_in_admin_bar - Makes this post type available via the admin bar. * * If not set, the default is inherited from show_in_menu * - menu_position - The position in the menu order the post type should appear. * * show_in_menu must be true * * Defaults to null, which places it at the bottom of its area. * - menu_icon - The url to the icon to be used for this menu. Defaults to use the posts icon. * - capability_type - The string to use to build the read, edit, and delete capabilities. Defaults to 'post'. * * May be passed as an array to allow for alternative plurals when using this argument as a base to construct the * capabilities, e.g. array('story', 'stories'). * - capabilities - Array of capabilities for this post type. * * By default the capability_type is used as a base to construct capabilities. * * You can see accepted values in {@link get_post_type_capabilities()}. * - map_meta_cap - Whether to use the internal default meta capability handling. Defaults to false. * - hierarchical - Whether the post type is hierarchical (e.g. page). Defaults to false. * - supports - An alias for calling add_post_type_support() directly. Defaults to title and editor. * * See {@link add_post_type_support()} for documentation. * - register_meta_box_cb - Provide a callback function that will be called when setting up the * meta boxes for the edit form. Do remove_meta_box() and add_meta_box() calls in the callback. * - taxonomies - An array of taxonomy identifiers that will be registered for the post type. * * Default is no taxonomies. * * Taxonomies can be registered later with register_taxonomy() or register_taxonomy_for_object_type(). * - has_archive - True to enable post type archives. Default is false. * * Will generate the proper rewrite rules if rewrite is enabled. * - rewrite - Triggers the handling of rewrites for this post type. Defaults to true, using $post_type as slug. * * To prevent rewrite, set to false. * * To specify rewrite rules, an array can be passed with any of these keys * * 'slug' => string Customize the permastruct slug. Defaults to $post_type key * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true. * * 'feeds' => bool Should a feed permastruct be built for this post type. Inherits default from has_archive. * * 'pages' => bool Should the permastruct provide for pagination. Defaults to true. * * 'ep_mask' => const Assign an endpoint mask. * * If not specified and permalink_epmask is set, inherits from permalink_epmask. * * If not specified and permalink_epmask is not set, defaults to EP_PERMALINK * - query_var - Sets the query_var key for this post type. Defaults to $post_type key * * If false, a post type cannot be loaded at ?{query_var}={post_slug} * * If specified as a string, the query ?{query_var_string}={post_slug} will be valid. * - can_export - Allows this post type to be exported. Defaults to true. * - delete_with_user - Whether to delete posts of this type when deleting a user. * * If true, posts of this type belonging to the user will be moved to trash when then user is deleted. * * If false, posts of this type belonging to the user will *not* be trashed or deleted. * * If not set (the default), posts are trashed if post_type_supports('author'). Otherwise posts are not trashed or deleted. * - _builtin - true if this post type is a native or "built-in" post_type. THIS IS FOR INTERNAL USE ONLY! * - _edit_link - URL segement to use for edit link of this post type. THIS IS FOR INTERNAL USE ONLY! * * @since 2.9.0 * @uses $wp_post_types Inserts new post type object into the list * * @param string $post_type Post type key, must not exceed 20 characters * @param array|string $args See optional args description above. * @return object|WP_Error the registered post type object, or an error object */ function register_post_type( $post_type, $args = array() ) { global $wp_post_types, $wp_rewrite, $wp; if ( !is_array($wp_post_types) ) $wp_post_types = array(); // Args prefixed with an underscore are reserved for internal use. $defaults = array( 'labels' => array(), 'description' => '', 'publicly_queryable' => null, 'exclude_from_search' => null, 'capability_type' => 'post', 'capabilities' => array(), 'map_meta_cap' => null, '_builtin' => false, '_edit_link' => 'post.php?post=%d', 'hierarchical' => false, 'public' => false, 'rewrite' => true, 'has_archive' => false, 'query_var' => true, 'supports' => array(), 'register_meta_box_cb' => null, 'taxonomies' => array(), 'show_ui' => null, 'menu_position' => null, 'menu_icon' => null, 'can_export' => true, 'show_in_nav_menus' => null, 'show_in_menu' => null, 'show_in_admin_bar' => null, 'delete_with_user' => null, ); $args = wp_parse_args($args, $defaults); $args = (object) $args; $post_type = sanitize_key($post_type); $args->name = $post_type; if ( strlen( $post_type ) > 20 ) return new WP_Error( 'post_type_too_long', __( 'Post types cannot exceed 20 characters in length' ) ); // If not set, default to the setting for public. if ( null === $args->publicly_queryable ) $args->publicly_queryable = $args->public; // If not set, default to the setting for public. if ( null === $args->show_ui ) $args->show_ui = $args->public; // If not set, default to the setting for show_ui. if ( null === $args->show_in_menu || ! $args->show_ui ) $args->show_in_menu = $args->show_ui; // If not set, default to the whether the full UI is shown. if ( null === $args->show_in_admin_bar ) $args->show_in_admin_bar = true === $args->show_in_menu; // Whether to show this type in nav-menus.php. Defaults to the setting for public. if ( null === $args->show_in_nav_menus ) $args->show_in_nav_menus = $args->public; // If not set, default to true if not public, false if public. if ( null === $args->exclude_from_search ) $args->exclude_from_search = !$args->public; // Back compat with quirky handling in version 3.0. #14122 if ( empty( $args->capabilities ) && null === $args->map_meta_cap && in_array( $args->capability_type, array( 'post', 'page' ) ) ) $args->map_meta_cap = true; if ( null === $args->map_meta_cap ) $args->map_meta_cap = false; $args->cap = get_post_type_capabilities( $args ); unset($args->capabilities); if ( is_array( $args->capability_type ) ) $args->capability_type = $args->capability_type[0]; if ( ! empty($args->supports) ) { add_post_type_support($post_type, $args->supports); unset($args->supports); } elseif ( false !== $args->supports ) { // Add default features add_post_type_support($post_type, array('title', 'editor')); } if ( false !== $args->query_var && !empty($wp) ) { if ( true === $args->query_var ) $args->query_var = $post_type; else $args->query_var = sanitize_title_with_dashes($args->query_var); $wp->add_query_var($args->query_var); } if ( false !== $args->rewrite && ( is_admin() || '' != get_option('permalink_structure') ) ) { if ( ! is_array( $args->rewrite ) ) $args->rewrite = array(); if ( empty( $args->rewrite['slug'] ) ) $args->rewrite['slug'] = $post_type; if ( ! isset( $args->rewrite['with_front'] ) ) $args->rewrite['with_front'] = true; if ( ! isset( $args->rewrite['pages'] ) ) $args->rewrite['pages'] = true; if ( ! isset( $args->rewrite['feeds'] ) || ! $args->has_archive ) $args->rewrite['feeds'] = (bool) $args->has_archive; if ( ! isset( $args->rewrite['ep_mask'] ) ) { if ( isset( $args->permalink_epmask ) ) $args->rewrite['ep_mask'] = $args->permalink_epmask; else $args->rewrite['ep_mask'] = EP_PERMALINK; } if ( $args->hierarchical ) add_rewrite_tag("%$post_type%", '(.+?)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name="); else add_rewrite_tag("%$post_type%", '([^/]+)', $args->query_var ? "{$args->query_var}=" : "post_type=$post_type&name="); if ( $args->has_archive ) { $archive_slug = $args->has_archive === true ? $args->rewrite['slug'] : $args->has_archive; if ( $args->rewrite['with_front'] ) $archive_slug = substr( $wp_rewrite->front, 1 ) . $archive_slug; else $archive_slug = $wp_rewrite->root . $archive_slug; add_rewrite_rule( "{$archive_slug}/?$", "index.php?post_type=$post_type", 'top' ); if ( $args->rewrite['feeds'] && $wp_rewrite->feeds ) { $feeds = '(' . trim( implode( '|', $wp_rewrite->feeds ) ) . ')'; add_rewrite_rule( "{$archive_slug}/feed/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' ); add_rewrite_rule( "{$archive_slug}/$feeds/?$", "index.php?post_type=$post_type" . '&feed=$matches[1]', 'top' ); } if ( $args->rewrite['pages'] ) add_rewrite_rule( "{$archive_slug}/{$wp_rewrite->pagination_base}/([0-9]{1,})/?$", "index.php?post_type=$post_type" . '&paged=$matches[1]', 'top' ); } add_permastruct( $post_type, "{$args->rewrite['slug']}/%$post_type%", $args->rewrite ); } if ( $args->register_meta_box_cb ) add_action('add_meta_boxes_' . $post_type, $args->register_meta_box_cb, 10, 1); $args->labels = get_post_type_labels( $args ); $args->label = $args->labels->name; $wp_post_types[$post_type] = $args; add_action( 'future_' . $post_type, '_future_post_hook', 5, 2 ); foreach ( $args->taxonomies as $taxonomy ) { register_taxonomy_for_object_type( $taxonomy, $post_type ); } do_action( 'registered_post_type', $post_type, $args ); return $args; } /** * Builds an object with all post type capabilities out of a post type object * * Post type capabilities use the 'capability_type' argument as a base, if the * capability is not set in the 'capabilities' argument array or if the * 'capabilities' argument is not supplied. * * The capability_type argument can optionally be registered as an array, with * the first value being singular and the second plural, e.g. array('story, 'stories') * Otherwise, an 's' will be added to the value for the plural form. After * registration, capability_type will always be a string of the singular value. * * By default, seven keys are accepted as part of the capabilities array: * * - edit_post, read_post, and delete_post are meta capabilities, which are then * generally mapped to corresponding primitive capabilities depending on the * context, which would be the post being edited/read/deleted and the user or * role being checked. Thus these capabilities would generally not be granted * directly to users or roles. * * - edit_posts - Controls whether objects of this post type can be edited. * - edit_others_posts - Controls whether objects of this type owned by other users * can be edited. If the post type does not support an author, then this will * behave like edit_posts. * - publish_posts - Controls publishing objects of this post type. * - read_private_posts - Controls whether private objects can be read. * * These four primitive capabilities are checked in core in various locations. * There are also seven other primitive capabilities which are not referenced * directly in core, except in map_meta_cap(), which takes the three aforementioned * meta capabilities and translates them into one or more primitive capabilities * that must then be checked against the user or role, depending on the context. * * - read - Controls whether objects of this post type can be read. * - delete_posts - Controls whether objects of this post type can be deleted. * - delete_private_posts - Controls whether private objects can be deleted. * - delete_published_posts - Controls whether published objects can be deleted. * - delete_others_posts - Controls whether objects owned by other users can be * can be deleted. If the post type does not support an author, then this will * behave like delete_posts. * - edit_private_posts - Controls whether private objects can be edited. * - edit_published_posts - Controls whether published objects can be edited. * * These additional capabilities are only used in map_meta_cap(). Thus, they are * only assigned by default if the post type is registered with the 'map_meta_cap' * argument set to true (default is false). * * @see map_meta_cap() * @since 3.0.0 * * @param object $args Post type registration arguments * @return object object with all the capabilities as member variables */ function get_post_type_capabilities( $args ) { if ( ! is_array( $args->capability_type ) ) $args->capability_type = array( $args->capability_type, $args->capability_type . 's' ); // Singular base for meta capabilities, plural base for primitive capabilities. list( $singular_base, $plural_base ) = $args->capability_type; $default_capabilities = array( // Meta capabilities 'edit_post' => 'edit_' . $singular_base, 'read_post' => 'read_' . $singular_base, 'delete_post' => 'delete_' . $singular_base, // Primitive capabilities used outside of map_meta_cap(): 'edit_posts' => 'edit_' . $plural_base, 'edit_others_posts' => 'edit_others_' . $plural_base, 'publish_posts' => 'publish_' . $plural_base, 'read_private_posts' => 'read_private_' . $plural_base, ); // Primitive capabilities used within map_meta_cap(): if ( $args->map_meta_cap ) { $default_capabilities_for_mapping = array( 'read' => 'read', 'delete_posts' => 'delete_' . $plural_base, 'delete_private_posts' => 'delete_private_' . $plural_base, 'delete_published_posts' => 'delete_published_' . $plural_base, 'delete_others_posts' => 'delete_others_' . $plural_base, 'edit_private_posts' => 'edit_private_' . $plural_base, 'edit_published_posts' => 'edit_published_' . $plural_base, ); $default_capabilities = array_merge( $default_capabilities, $default_capabilities_for_mapping ); } $capabilities = array_merge( $default_capabilities, $args->capabilities ); // Post creation capability simply maps to edit_posts by default: if ( ! isset( $capabilities['create_posts'] ) ) $capabilities['create_posts'] = $capabilities['edit_posts']; // Remember meta capabilities for future reference. if ( $args->map_meta_cap ) _post_type_meta_capabilities( $capabilities ); return (object) $capabilities; } /** * Stores or returns a list of post type meta caps for map_meta_cap(). * * @since 3.1.0 * @access private */ function _post_type_meta_capabilities( $capabilities = null ) { static $meta_caps = array(); if ( null === $capabilities ) return $meta_caps; foreach ( $capabilities as $core => $custom ) { if ( in_array( $core, array( 'read_post', 'delete_post', 'edit_post' ) ) ) $meta_caps[ $custom ] = $core; } } /** * Builds an object with all post type labels out of a post type object * * Accepted keys of the label array in the post type object: * - name - general name for the post type, usually plural. The same and overridden by $post_type_object->label. Default is Posts/Pages * - singular_name - name for one object of this post type. Default is Post/Page * - add_new - Default is Add New for both hierarchical and non-hierarchical types. When internationalizing this string, please use a {@link http://codex.wordpress.org/I18n_for_WordPress_Developers#Disambiguation_by_context gettext context} matching your post type. Example: <code>_x('Add New', 'product');</code> * - add_new_item - Default is Add New Post/Add New Page * - edit_item - Default is Edit Post/Edit Page * - new_item - Default is New Post/New Page * - view_item - Default is View Post/View Page * - search_items - Default is Search Posts/Search Pages * - not_found - Default is No posts found/No pages found * - not_found_in_trash - Default is No posts found in Trash/No pages found in Trash * - parent_item_colon - This string isn't used on non-hierarchical types. In hierarchical ones the default is Parent Page: * - all_items - String for the submenu. Default is All Posts/All Pages * - menu_name - Default is the same as <code>name</code> * * Above, the first default value is for non-hierarchical post types (like posts) and the second one is for hierarchical post types (like pages). * * @since 3.0.0 * @param object $post_type_object * @return object object with all the labels as member variables */ function get_post_type_labels( $post_type_object ) { $nohier_vs_hier_defaults = array( 'name' => array( _x('Posts', 'post type general name'), _x('Pages', 'post type general name') ), 'singular_name' => array( _x('Post', 'post type singular name'), _x('Page', 'post type singular name') ), 'add_new' => array( _x('Add New', 'post'), _x('Add New', 'page') ), 'add_new_item' => array( __('Add New Post'), __('Add New Page') ), 'edit_item' => array( __('Edit Post'), __('Edit Page') ), 'new_item' => array( __('New Post'), __('New Page') ), 'view_item' => array( __('View Post'), __('View Page') ), 'search_items' => array( __('Search Posts'), __('Search Pages') ), 'not_found' => array( __('No posts found.'), __('No pages found.') ), 'not_found_in_trash' => array( __('No posts found in Trash.'), __('No pages found in Trash.') ), 'parent_item_colon' => array( null, __('Parent Page:') ), 'all_items' => array( __( 'All Posts' ), __( 'All Pages' ) ) ); $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name']; $labels = _get_custom_object_labels( $post_type_object, $nohier_vs_hier_defaults ); $post_type = $post_type_object->name; return apply_filters( "post_type_labels_{$post_type}", $labels ); } /** * Builds an object with custom-something object (post type, taxonomy) labels out of a custom-something object * * @access private * @since 3.0.0 */ function _get_custom_object_labels( $object, $nohier_vs_hier_defaults ) { if ( isset( $object->label ) && empty( $object->labels['name'] ) ) $object->labels['name'] = $object->label; if ( !isset( $object->labels['singular_name'] ) && isset( $object->labels['name'] ) ) $object->labels['singular_name'] = $object->labels['name']; if ( ! isset( $object->labels['name_admin_bar'] ) ) $object->labels['name_admin_bar'] = isset( $object->labels['singular_name'] ) ? $object->labels['singular_name'] : $object->name; if ( !isset( $object->labels['menu_name'] ) && isset( $object->labels['name'] ) ) $object->labels['menu_name'] = $object->labels['name']; if ( !isset( $object->labels['all_items'] ) && isset( $object->labels['menu_name'] ) ) $object->labels['all_items'] = $object->labels['menu_name']; foreach ( $nohier_vs_hier_defaults as $key => $value ) $defaults[$key] = $object->hierarchical ? $value[1] : $value[0]; $labels = array_merge( $defaults, $object->labels ); return (object)$labels; } /** * Adds submenus for post types. * * @access private * @since 3.1.0 */ function _add_post_type_submenus() { foreach ( get_post_types( array( 'show_ui' => true ) ) as $ptype ) { $ptype_obj = get_post_type_object( $ptype ); // Submenus only. if ( ! $ptype_obj->show_in_menu || $ptype_obj->show_in_menu === true ) continue; add_submenu_page( $ptype_obj->show_in_menu, $ptype_obj->labels->name, $ptype_obj->labels->all_items, $ptype_obj->cap->edit_posts, "edit.php?post_type=$ptype" ); } } add_action( 'admin_menu', '_add_post_type_submenus' ); /** * Register support of certain features for a post type. * * All features are directly associated with a functional area of the edit screen, such as the * editor or a meta box: 'title', 'editor', 'comments', 'revisions', 'trackbacks', 'author', * 'excerpt', 'page-attributes', 'thumbnail', and 'custom-fields'. * * Additionally, the 'revisions' feature dictates whether the post type will store revisions, * and the 'comments' feature dictates whether the comments count will show on the edit screen. * * @since 3.0.0 * @param string $post_type The post type for which to add the feature * @param string|array $feature the feature being added, can be an array of feature strings or a single string */ function add_post_type_support( $post_type, $feature ) { global $_wp_post_type_features; $features = (array) $feature; foreach ($features as $feature) { if ( func_num_args() == 2 ) $_wp_post_type_features[$post_type][$feature] = true; else $_wp_post_type_features[$post_type][$feature] = array_slice( func_get_args(), 2 ); } } /** * Remove support for a feature from a post type. * * @since 3.0.0 * @param string $post_type The post type for which to remove the feature * @param string $feature The feature being removed */ function remove_post_type_support( $post_type, $feature ) { global $_wp_post_type_features; if ( !isset($_wp_post_type_features[$post_type]) ) return; if ( isset($_wp_post_type_features[$post_type][$feature]) ) unset($_wp_post_type_features[$post_type][$feature]); } /** * Get all the post type features * * @since 3.4.0 * @param string $post_type The post type * @return array */ function get_all_post_type_supports( $post_type ) { global $_wp_post_type_features; if ( isset( $_wp_post_type_features[$post_type] ) ) return $_wp_post_type_features[$post_type]; return array(); } /** * Checks a post type's support for a given feature * * @since 3.0.0 * @param string $post_type The post type being checked * @param string $feature the feature being checked * @return boolean */ function post_type_supports( $post_type, $feature ) { global $_wp_post_type_features; if ( !isset( $_wp_post_type_features[$post_type][$feature] ) ) return false; // If no args passed then no extra checks need be performed if ( func_num_args() <= 2 ) return true; // @todo Allow pluggable arg checking //$args = array_slice( func_get_args(), 2 ); return true; } /** * Updates the post type for the post ID. * * The page or post cache will be cleaned for the post ID. * * @since 2.5.0 * * @uses $wpdb * * @param int $post_id Post ID to change post type. Not actually optional. * @param string $post_type Optional, default is post. Supported values are 'post' or 'page' to * name a few. * @return int Amount of rows changed. Should be 1 for success and 0 for failure. */ function set_post_type( $post_id = 0, $post_type = 'post' ) { global $wpdb; $post_type = sanitize_post_field('post_type', $post_type, $post_id, 'db'); $return = $wpdb->update( $wpdb->posts, array('post_type' => $post_type), array('ID' => $post_id) ); clean_post_cache( $post_id ); return $return; } /** * Retrieve list of latest posts or posts matching criteria. * * The defaults are as follows: * 'numberposts' - Default is 5. Total number of posts to retrieve. * 'offset' - Default is 0. See {@link WP_Query::query()} for more. * 'category' - What category to pull the posts from. * 'orderby' - Default is 'post_date'. How to order the posts. * 'order' - Default is 'DESC'. The order to retrieve the posts. * 'include' - See {@link WP_Query::query()} for more. * 'exclude' - See {@link WP_Query::query()} for more. * 'meta_key' - See {@link WP_Query::query()} for more. * 'meta_value' - See {@link WP_Query::query()} for more. * 'post_type' - Default is 'post'. Can be 'page', or 'attachment' to name a few. * 'post_parent' - The parent of the post or post type. * 'post_status' - Default is 'publish'. Post status to retrieve. * * @since 1.2.0 * @uses $wpdb * @uses WP_Query::query() See for more default arguments and information. * @link http://codex.wordpress.org/Template_Tags/get_posts * * @param array $args Optional. Overrides defaults. * @return array List of posts. */ function get_posts($args = null) { $defaults = array( 'numberposts' => 5, 'offset' => 0, 'category' => 0, 'orderby' => 'post_date', 'order' => 'DESC', 'include' => array(), 'exclude' => array(), 'meta_key' => '', 'meta_value' =>'', 'post_type' => 'post', 'suppress_filters' => true ); $r = wp_parse_args( $args, $defaults ); if ( empty( $r['post_status'] ) ) $r['post_status'] = ( 'attachment' == $r['post_type'] ) ? 'inherit' : 'publish'; if ( ! empty($r['numberposts']) && empty($r['posts_per_page']) ) $r['posts_per_page'] = $r['numberposts']; if ( ! empty($r['category']) ) $r['cat'] = $r['category']; if ( ! empty($r['include']) ) { $incposts = wp_parse_id_list( $r['include'] ); $r['posts_per_page'] = count($incposts); // only the number of posts included $r['post__in'] = $incposts; } elseif ( ! empty($r['exclude']) ) $r['post__not_in'] = wp_parse_id_list( $r['exclude'] ); $r['ignore_sticky_posts'] = true; $r['no_found_rows'] = true; $get_posts = new WP_Query; return $get_posts->query($r); } // // Post meta functions // /** * Add meta data field to a post. * * Post meta data is called "Custom Fields" on the Administration Screen. * * @since 1.5.0 * @uses $wpdb * @link http://codex.wordpress.org/Function_Reference/add_post_meta * * @param int $post_id Post ID. * @param string $meta_key Metadata name. * @param mixed $meta_value Metadata value. * @param bool $unique Optional, default is false. Whether the same key should not be added. * @return bool False for failure. True for success. */ function add_post_meta($post_id, $meta_key, $meta_value, $unique = false) { // make sure meta is added to the post, not a revision if ( $the_post = wp_is_post_revision($post_id) ) $post_id = $the_post; return add_metadata('post', $post_id, $meta_key, $meta_value, $unique); } /** * Remove metadata matching criteria from a post. * * You can match based on the key, or key and value. Removing based on key and * value, will keep from removing duplicate metadata with the same key. It also * allows removing all metadata matching key, if needed. * * @since 1.5.0 * @uses $wpdb * @link http://codex.wordpress.org/Function_Reference/delete_post_meta * * @param int $post_id post ID * @param string $meta_key Metadata name. * @param mixed $meta_value Optional. Metadata value. * @return bool False for failure. True for success. */ function delete_post_meta($post_id, $meta_key, $meta_value = '') { // make sure meta is added to the post, not a revision if ( $the_post = wp_is_post_revision($post_id) ) $post_id = $the_post; return delete_metadata('post', $post_id, $meta_key, $meta_value); } /** * Retrieve post meta field for a post. * * @since 1.5.0 * @uses $wpdb * @link http://codex.wordpress.org/Function_Reference/get_post_meta * * @param int $post_id Post ID. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys. * @param bool $single Whether to return a single value. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single * is true. */ function get_post_meta($post_id, $key = '', $single = false) { return get_metadata('post', $post_id, $key, $single); } /** * Update post meta field based on post ID. * * Use the $prev_value parameter to differentiate between meta fields with the * same key and post ID. * * If the meta field for the post does not exist, it will be added. * * @since 1.5.0 * @uses $wpdb * @link http://codex.wordpress.org/Function_Reference/update_post_meta * * @param int $post_id Post ID. * @param string $meta_key Metadata key. * @param mixed $meta_value Metadata value. * @param mixed $prev_value Optional. Previous value to check before removing. * @return bool False on failure, true if success. */ function update_post_meta($post_id, $meta_key, $meta_value, $prev_value = '') { // make sure meta is added to the post, not a revision if ( $the_post = wp_is_post_revision($post_id) ) $post_id = $the_post; return update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value); } /** * Delete everything from post meta matching meta key. * * @since 2.3.0 * @uses $wpdb * * @param string $post_meta_key Key to search for when deleting. * @return bool Whether the post meta key was deleted from the database */ function delete_post_meta_by_key($post_meta_key) { return delete_metadata( 'post', null, $post_meta_key, '', true ); } /** * Retrieve post meta fields, based on post ID. * * The post meta fields are retrieved from the cache where possible, * so the function is optimized to be called more than once. * * @since 1.2.0 * @link http://codex.wordpress.org/Function_Reference/get_post_custom * * @param int $post_id Post ID. * @return array */ function get_post_custom( $post_id = 0 ) { $post_id = absint( $post_id ); if ( ! $post_id ) $post_id = get_the_ID(); return get_post_meta( $post_id ); } /** * Retrieve meta field names for a post. * * If there are no meta fields, then nothing (null) will be returned. * * @since 1.2.0 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_keys * * @param int $post_id post ID * @return array|null Either array of the keys, or null if keys could not be retrieved. */ function get_post_custom_keys( $post_id = 0 ) { $custom = get_post_custom( $post_id ); if ( !is_array($custom) ) return; if ( $keys = array_keys($custom) ) return $keys; } /** * Retrieve values for a custom post field. * * The parameters must not be considered optional. All of the post meta fields * will be retrieved and only the meta field key values returned. * * @since 1.2.0 * @link http://codex.wordpress.org/Function_Reference/get_post_custom_values * * @param string $key Meta field key. * @param int $post_id Post ID * @return array Meta field values. */ function get_post_custom_values( $key = '', $post_id = 0 ) { if ( !$key ) return null; $custom = get_post_custom($post_id); return isset($custom[$key]) ? $custom[$key] : null; } /** * Check if post is sticky. * * Sticky posts should remain at the top of The Loop. If the post ID is not * given, then The Loop ID for the current post will be used. * * @since 2.7.0 * * @param int $post_id Optional. Post ID. * @return bool Whether post is sticky. */ function is_sticky( $post_id = 0 ) { $post_id = absint( $post_id ); if ( ! $post_id ) $post_id = get_the_ID(); $stickies = get_option( 'sticky_posts' ); if ( ! is_array( $stickies ) ) return false; if ( in_array( $post_id, $stickies ) ) return true; return false; } /** * Sanitize every post field. * * If the context is 'raw', then the post object or array will get minimal santization of the int fields. * * @since 2.3.0 * @uses sanitize_post_field() Used to sanitize the fields. * * @param object|WP_Post|array $post The Post Object or Array * @param string $context Optional, default is 'display'. How to sanitize post fields. * @return object|WP_Post|array The now sanitized Post Object or Array (will be the same type as $post) */ function sanitize_post($post, $context = 'display') { if ( is_object($post) ) { // Check if post already filtered for this context if ( isset($post->filter) && $context == $post->filter ) return $post; if ( !isset($post->ID) ) $post->ID = 0; foreach ( array_keys(get_object_vars($post)) as $field ) $post->$field = sanitize_post_field($field, $post->$field, $post->ID, $context); $post->filter = $context; } else { // Check if post already filtered for this context if ( isset($post['filter']) && $context == $post['filter'] ) return $post; if ( !isset($post['ID']) ) $post['ID'] = 0; foreach ( array_keys($post) as $field ) $post[$field] = sanitize_post_field($field, $post[$field], $post['ID'], $context); $post['filter'] = $context; } return $post; } /** * Sanitize post field based on context. * * Possible context values are: 'raw', 'edit', 'db', 'display', 'attribute' and 'js'. The * 'display' context is used by default. 'attribute' and 'js' contexts are treated like 'display' * when calling filters. * * @since 2.3.0 * @uses apply_filters() Calls 'edit_$field' and '{$field_no_prefix}_edit_pre' passing $value and * $post_id if $context == 'edit' and field name prefix == 'post_'. * * @uses apply_filters() Calls 'edit_post_$field' passing $value and $post_id if $context == 'db'. * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db' and field name prefix == 'post_'. * @uses apply_filters() Calls '{$field}_pre' passing $value if $context == 'db' and field name prefix != 'post_'. * * @uses apply_filters() Calls '$field' passing $value, $post_id and $context if $context == anything * other than 'raw', 'edit' and 'db' and field name prefix == 'post_'. * @uses apply_filters() Calls 'post_$field' passing $value if $context == anything other than 'raw', * 'edit' and 'db' and field name prefix != 'post_'. * * @param string $field The Post Object field name. * @param mixed $value The Post Object value. * @param int $post_id Post ID. * @param string $context How to sanitize post fields. Looks for 'raw', 'edit', 'db', 'display', * 'attribute' and 'js'. * @return mixed Sanitized value. */ function sanitize_post_field($field, $value, $post_id, $context) { $int_fields = array('ID', 'post_parent', 'menu_order'); if ( in_array($field, $int_fields) ) $value = (int) $value; // Fields which contain arrays of ints. $array_int_fields = array( 'ancestors' ); if ( in_array($field, $array_int_fields) ) { $value = array_map( 'absint', $value); return $value; } if ( 'raw' == $context ) return $value; $prefixed = false; if ( false !== strpos($field, 'post_') ) { $prefixed = true; $field_no_prefix = str_replace('post_', '', $field); } if ( 'edit' == $context ) { $format_to_edit = array('post_content', 'post_excerpt', 'post_title', 'post_password'); if ( $prefixed ) { $value = apply_filters("edit_{$field}", $value, $post_id); // Old school $value = apply_filters("{$field_no_prefix}_edit_pre", $value, $post_id); } else { $value = apply_filters("edit_post_{$field}", $value, $post_id); } if ( in_array($field, $format_to_edit) ) { if ( 'post_content' == $field ) $value = format_to_edit($value, user_can_richedit()); else $value = format_to_edit($value); } else { $value = esc_attr($value); } } else if ( 'db' == $context ) { if ( $prefixed ) { $value = apply_filters("pre_{$field}", $value); $value = apply_filters("{$field_no_prefix}_save_pre", $value); } else { $value = apply_filters("pre_post_{$field}", $value); $value = apply_filters("{$field}_pre", $value); } } else { // Use display filters by default. if ( $prefixed ) $value = apply_filters($field, $value, $post_id, $context); else $value = apply_filters("post_{$field}", $value, $post_id, $context); } if ( 'attribute' == $context ) $value = esc_attr($value); else if ( 'js' == $context ) $value = esc_js($value); return $value; } /** * Make a post sticky. * * Sticky posts should be displayed at the top of the front page. * * @since 2.7.0 * * @param int $post_id Post ID. */ function stick_post($post_id) { $stickies = get_option('sticky_posts'); if ( !is_array($stickies) ) $stickies = array($post_id); if ( ! in_array($post_id, $stickies) ) $stickies[] = $post_id; update_option('sticky_posts', $stickies); } /** * Unstick a post. * * Sticky posts should be displayed at the top of the front page. * * @since 2.7.0 * * @param int $post_id Post ID. */ function unstick_post($post_id) { $stickies = get_option('sticky_posts'); if ( !is_array($stickies) ) return; if ( ! in_array($post_id, $stickies) ) return; $offset = array_search($post_id, $stickies); if ( false === $offset ) return; array_splice($stickies, $offset, 1); update_option('sticky_posts', $stickies); } /** * Count number of posts of a post type and is user has permissions to view. * * This function provides an efficient method of finding the amount of post's * type a blog has. Another method is to count the amount of items in * get_posts(), but that method has a lot of overhead with doing so. Therefore, * when developing for 2.5+, use this function instead. * * The $perm parameter checks for 'readable' value and if the user can read * private posts, it will display that for the user that is signed in. * * @since 2.5.0 * @link http://codex.wordpress.org/Template_Tags/wp_count_posts * * @param string $type Optional. Post type to retrieve count * @param string $perm Optional. 'readable' or empty. * @return object Number of posts for each status */ function wp_count_posts( $type = 'post', $perm = '' ) { global $wpdb; $user = wp_get_current_user(); $cache_key = $type; $query = "SELECT post_status, COUNT( * ) AS num_posts FROM {$wpdb->posts} WHERE post_type = %s"; if ( 'readable' == $perm && is_user_logged_in() ) { $post_type_object = get_post_type_object($type); if ( !current_user_can( $post_type_object->cap->read_private_posts ) ) { $cache_key .= '_' . $perm . '_' . $user->ID; $query .= " AND (post_status != 'private' OR ( post_author = '$user->ID' AND post_status = 'private' ))"; } } $query .= ' GROUP BY post_status'; $count = wp_cache_get($cache_key, 'counts'); if ( false !== $count ) return $count; $count = $wpdb->get_results( $wpdb->prepare( $query, $type ), ARRAY_A ); $stats = array(); foreach ( get_post_stati() as $state ) $stats[$state] = 0; foreach ( (array) $count as $row ) $stats[$row['post_status']] = $row['num_posts']; $stats = (object) $stats; wp_cache_set($cache_key, $stats, 'counts'); return $stats; } /** * Count number of attachments for the mime type(s). * * If you set the optional mime_type parameter, then an array will still be * returned, but will only have the item you are looking for. It does not give * you the number of attachments that are children of a post. You can get that * by counting the number of children that post has. * * @since 2.5.0 * * @param string|array $mime_type Optional. Array or comma-separated list of MIME patterns. * @return array Number of posts for each mime type. */ function wp_count_attachments( $mime_type = '' ) { global $wpdb; $and = wp_post_mime_type_where( $mime_type ); $count = $wpdb->get_results( "SELECT post_mime_type, COUNT( * ) AS num_posts FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status != 'trash' $and GROUP BY post_mime_type", ARRAY_A ); $stats = array( ); foreach( (array) $count as $row ) { $stats[$row['post_mime_type']] = $row['num_posts']; } $stats['trash'] = $wpdb->get_var( "SELECT COUNT( * ) FROM $wpdb->posts WHERE post_type = 'attachment' AND post_status = 'trash' $and"); return (object) $stats; } /** * Get default post mime types * * @since 2.9.0 * * @return array */ function get_post_mime_types() { $post_mime_types = array( // array( adj, noun ) 'image' => array(__('Images'), __('Manage Images'), _n_noop('Image <span class="count">(%s)</span>', 'Images <span class="count">(%s)</span>')), 'audio' => array(__('Audio'), __('Manage Audio'), _n_noop('Audio <span class="count">(%s)</span>', 'Audio <span class="count">(%s)</span>')), 'video' => array(__('Video'), __('Manage Video'), _n_noop('Video <span class="count">(%s)</span>', 'Video <span class="count">(%s)</span>')), ); return apply_filters('post_mime_types', $post_mime_types); } /** * Check a MIME-Type against a list. * * If the wildcard_mime_types parameter is a string, it must be comma separated * list. If the real_mime_types is a string, it is also comma separated to * create the list. * * @since 2.5.0 * * @param string|array $wildcard_mime_types e.g. audio/mpeg or image (same as image/*) or * flash (same as *flash*). * @param string|array $real_mime_types post_mime_type values * @return array array(wildcard=>array(real types)) */ function wp_match_mime_types($wildcard_mime_types, $real_mime_types) { $matches = array(); if ( is_string($wildcard_mime_types) ) $wildcard_mime_types = array_map('trim', explode(',', $wildcard_mime_types)); if ( is_string($real_mime_types) ) $real_mime_types = array_map('trim', explode(',', $real_mime_types)); $wild = '[-._a-z0-9]*'; foreach ( (array) $wildcard_mime_types as $type ) { $type = str_replace('*', $wild, $type); $patternses[1][$type] = "^$type$"; if ( false === strpos($type, '/') ) { $patternses[2][$type] = "^$type/"; $patternses[3][$type] = $type; } } asort($patternses); foreach ( $patternses as $patterns ) foreach ( $patterns as $type => $pattern ) foreach ( (array) $real_mime_types as $real ) if ( preg_match("#$pattern#", $real) && ( empty($matches[$type]) || false === array_search($real, $matches[$type]) ) ) $matches[$type][] = $real; return $matches; } /** * Convert MIME types into SQL. * * @since 2.5.0 * * @param string|array $post_mime_types List of mime types or comma separated string of mime types. * @param string $table_alias Optional. Specify a table alias, if needed. * @return string The SQL AND clause for mime searching. */ function wp_post_mime_type_where($post_mime_types, $table_alias = '') { $where = ''; $wildcards = array('', '%', '%/%'); if ( is_string($post_mime_types) ) $post_mime_types = array_map('trim', explode(',', $post_mime_types)); foreach ( (array) $post_mime_types as $mime_type ) { $mime_type = preg_replace('/\s/', '', $mime_type); $slashpos = strpos($mime_type, '/'); if ( false !== $slashpos ) { $mime_group = preg_replace('/[^-*.a-zA-Z0-9]/', '', substr($mime_type, 0, $slashpos)); $mime_subgroup = preg_replace('/[^-*.+a-zA-Z0-9]/', '', substr($mime_type, $slashpos + 1)); if ( empty($mime_subgroup) ) $mime_subgroup = '*'; else $mime_subgroup = str_replace('/', '', $mime_subgroup); $mime_pattern = "$mime_group/$mime_subgroup"; } else { $mime_pattern = preg_replace('/[^-*.a-zA-Z0-9]/', '', $mime_type); if ( false === strpos($mime_pattern, '*') ) $mime_pattern .= '/*'; } $mime_pattern = preg_replace('/\*+/', '%', $mime_pattern); if ( in_array( $mime_type, $wildcards ) ) return ''; if ( false !== strpos($mime_pattern, '%') ) $wheres[] = empty($table_alias) ? "post_mime_type LIKE '$mime_pattern'" : "$table_alias.post_mime_type LIKE '$mime_pattern'"; else $wheres[] = empty($table_alias) ? "post_mime_type = '$mime_pattern'" : "$table_alias.post_mime_type = '$mime_pattern'"; } if ( !empty($wheres) ) $where = ' AND (' . join(' OR ', $wheres) . ') '; return $where; } /** * Trashes or deletes a post or page. * * When the post and page is permanently deleted, everything that is tied to it is deleted also. * This includes comments, post meta fields, and terms associated with the post. * * The post or page is moved to trash instead of permanently deleted unless trash is * disabled, item is already in the trash, or $force_delete is true. * * @since 1.0.0 * @uses do_action() on 'delete_post' before deletion unless post type is 'attachment'. * @uses do_action() on 'deleted_post' after deletion unless post type is 'attachment'. * @uses wp_delete_attachment() if post type is 'attachment'. * @uses wp_trash_post() if item should be trashed. * * @param int $postid Post ID. * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false. * @return mixed False on failure */ function wp_delete_post( $postid = 0, $force_delete = false ) { global $wpdb; if ( !$post = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $postid)) ) return $post; if ( !$force_delete && ( $post->post_type == 'post' || $post->post_type == 'page') && get_post_status( $postid ) != 'trash' && EMPTY_TRASH_DAYS ) return wp_trash_post($postid); if ( $post->post_type == 'attachment' ) return wp_delete_attachment( $postid, $force_delete ); do_action('before_delete_post', $postid); delete_post_meta($postid,'_wp_trash_meta_status'); delete_post_meta($postid,'_wp_trash_meta_time'); wp_delete_object_term_relationships($postid, get_object_taxonomies($post->post_type)); $parent_data = array( 'post_parent' => $post->post_parent ); $parent_where = array( 'post_parent' => $postid ); if ( is_post_type_hierarchical( $post->post_type ) ) { // Point children of this page to its parent, also clean the cache of affected children $children_query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_parent = %d AND post_type = %s", $postid, $post->post_type ); $children = $wpdb->get_results( $children_query ); $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => $post->post_type ) ); } if ( 'page' == $post->post_type) { // if the page is defined in option page_on_front or post_for_posts, // adjust the corresponding options if ( get_option('page_on_front') == $postid ) { update_option('show_on_front', 'posts'); delete_option('page_on_front'); } if ( get_option('page_for_posts') == $postid ) { delete_option('page_for_posts'); } } else { unstick_post($postid); } // Do raw query. wp_get_post_revisions() is filtered $revision_ids = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'revision'", $postid ) ); // Use wp_delete_post (via wp_delete_post_revision) again. Ensures any meta/misplaced data gets cleaned up. foreach ( $revision_ids as $revision_id ) wp_delete_post_revision( $revision_id ); // Point all attachments to this post up one level $wpdb->update( $wpdb->posts, $parent_data, $parent_where + array( 'post_type' => 'attachment' ) ); $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $postid )); foreach ( $comment_ids as $comment_id ) wp_delete_comment( $comment_id, true ); $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $postid )); foreach ( $post_meta_ids as $mid ) delete_metadata_by_mid( 'post', $mid ); do_action( 'delete_post', $postid ); $wpdb->delete( $wpdb->posts, array( 'ID' => $postid ) ); do_action( 'deleted_post', $postid ); clean_post_cache( $post ); if ( is_post_type_hierarchical( $post->post_type ) && $children ) { foreach ( $children as $child ) clean_post_cache( $child ); } wp_clear_scheduled_hook('publish_future_post', array( $postid ) ); do_action('after_delete_post', $postid); return $post; } /** * Moves a post or page to the Trash * * If trash is disabled, the post or page is permanently deleted. * * @since 2.9.0 * @uses do_action() on 'trash_post' before trashing * @uses do_action() on 'trashed_post' after trashing * @uses wp_delete_post() if trash is disabled * * @param int $post_id Post ID. * @return mixed False on failure */ function wp_trash_post($post_id = 0) { if ( !EMPTY_TRASH_DAYS ) return wp_delete_post($post_id, true); if ( !$post = get_post($post_id, ARRAY_A) ) return $post; if ( $post['post_status'] == 'trash' ) return false; do_action('wp_trash_post', $post_id); add_post_meta($post_id,'_wp_trash_meta_status', $post['post_status']); add_post_meta($post_id,'_wp_trash_meta_time', time()); $post['post_status'] = 'trash'; wp_insert_post($post); wp_trash_post_comments($post_id); do_action('trashed_post', $post_id); return $post; } /** * Restores a post or page from the Trash * * @since 2.9.0 * @uses do_action() on 'untrash_post' before undeletion * @uses do_action() on 'untrashed_post' after undeletion * * @param int $post_id Post ID. * @return mixed False on failure */ function wp_untrash_post($post_id = 0) { if ( !$post = get_post($post_id, ARRAY_A) ) return $post; if ( $post['post_status'] != 'trash' ) return false; do_action('untrash_post', $post_id); $post_status = get_post_meta($post_id, '_wp_trash_meta_status', true); $post['post_status'] = $post_status; delete_post_meta($post_id, '_wp_trash_meta_status'); delete_post_meta($post_id, '_wp_trash_meta_time'); wp_insert_post($post); wp_untrash_post_comments($post_id); do_action('untrashed_post', $post_id); return $post; } /** * Moves comments for a post to the trash * * @since 2.9.0 * @uses do_action() on 'trash_post_comments' before trashing * @uses do_action() on 'trashed_post_comments' after trashing * * @param int $post Post ID or object. * @return mixed False on failure */ function wp_trash_post_comments($post = null) { global $wpdb; $post = get_post($post); if ( empty($post) ) return; $post_id = $post->ID; do_action('trash_post_comments', $post_id); $comments = $wpdb->get_results( $wpdb->prepare("SELECT comment_ID, comment_approved FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id) ); if ( empty($comments) ) return; // Cache current status for each comment $statuses = array(); foreach ( $comments as $comment ) $statuses[$comment->comment_ID] = $comment->comment_approved; add_post_meta($post_id, '_wp_trash_meta_comments_status', $statuses); // Set status for all comments to post-trashed $result = $wpdb->update($wpdb->comments, array('comment_approved' => 'post-trashed'), array('comment_post_ID' => $post_id)); clean_comment_cache( array_keys($statuses) ); do_action('trashed_post_comments', $post_id, $statuses); return $result; } /** * Restore comments for a post from the trash * * @since 2.9.0 * @uses do_action() on 'untrash_post_comments' before trashing * @uses do_action() on 'untrashed_post_comments' after trashing * * @param int $post Post ID or object. * @return mixed False on failure */ function wp_untrash_post_comments($post = null) { global $wpdb; $post = get_post($post); if ( empty($post) ) return; $post_id = $post->ID; $statuses = get_post_meta($post_id, '_wp_trash_meta_comments_status', true); if ( empty($statuses) ) return true; do_action('untrash_post_comments', $post_id); // Restore each comment to its original status $group_by_status = array(); foreach ( $statuses as $comment_id => $comment_status ) $group_by_status[$comment_status][] = $comment_id; foreach ( $group_by_status as $status => $comments ) { // Sanity check. This shouldn't happen. if ( 'post-trashed' == $status ) $status = '0'; $comments_in = implode( "', '", $comments ); $wpdb->query( "UPDATE $wpdb->comments SET comment_approved = '$status' WHERE comment_ID IN ('" . $comments_in . "')" ); } clean_comment_cache( array_keys($statuses) ); delete_post_meta($post_id, '_wp_trash_meta_comments_status'); do_action('untrashed_post_comments', $post_id); } /** * Retrieve the list of categories for a post. * * Compatibility layer for themes and plugins. Also an easy layer of abstraction * away from the complexity of the taxonomy layer. * * @since 2.1.0 * * @uses wp_get_object_terms() Retrieves the categories. Args details can be found here. * * @param int $post_id Optional. The Post ID. * @param array $args Optional. Overwrite the defaults. * @return array */ function wp_get_post_categories( $post_id = 0, $args = array() ) { $post_id = (int) $post_id; $defaults = array('fields' => 'ids'); $args = wp_parse_args( $args, $defaults ); $cats = wp_get_object_terms($post_id, 'category', $args); return $cats; } /** * Retrieve the tags for a post. * * There is only one default for this function, called 'fields' and by default * is set to 'all'. There are other defaults that can be overridden in * {@link wp_get_object_terms()}. * * @package WordPress * @subpackage Post * @since 2.3.0 * * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here * * @param int $post_id Optional. The Post ID * @param array $args Optional. Overwrite the defaults * @return array List of post tags. */ function wp_get_post_tags( $post_id = 0, $args = array() ) { return wp_get_post_terms( $post_id, 'post_tag', $args); } /** * Retrieve the terms for a post. * * There is only one default for this function, called 'fields' and by default * is set to 'all'. There are other defaults that can be overridden in * {@link wp_get_object_terms()}. * * @package WordPress * @subpackage Post * @since 2.8.0 * * @uses wp_get_object_terms() Gets the tags for returning. Args can be found here * * @param int $post_id Optional. The Post ID * @param string $taxonomy The taxonomy for which to retrieve terms. Defaults to post_tag. * @param array $args Optional. Overwrite the defaults * @return array List of post tags. */ function wp_get_post_terms( $post_id = 0, $taxonomy = 'post_tag', $args = array() ) { $post_id = (int) $post_id; $defaults = array('fields' => 'all'); $args = wp_parse_args( $args, $defaults ); $tags = wp_get_object_terms($post_id, $taxonomy, $args); return $tags; } /** * Retrieve number of recent posts. * * @since 1.0.0 * @uses wp_parse_args() * @uses get_posts() * * @param string $deprecated Deprecated. * @param array $args Optional. Overrides defaults. * @param string $output Optional. * @return unknown. */ function wp_get_recent_posts( $args = array(), $output = ARRAY_A ) { if ( is_numeric( $args ) ) { _deprecated_argument( __FUNCTION__, '3.1', __( 'Passing an integer number of posts is deprecated. Pass an array of arguments instead.' ) ); $args = array( 'numberposts' => absint( $args ) ); } // Set default arguments $defaults = array( 'numberposts' => 10, 'offset' => 0, 'category' => 0, 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' =>'', 'post_type' => 'post', 'post_status' => 'draft, publish, future, pending, private', 'suppress_filters' => true ); $r = wp_parse_args( $args, $defaults ); $results = get_posts( $r ); // Backward compatibility. Prior to 3.1 expected posts to be returned in array if ( ARRAY_A == $output ){ foreach( $results as $key => $result ) { $results[$key] = get_object_vars( $result ); } return $results ? $results : array(); } return $results ? $results : false; } /** * Insert a post. * * If the $postarr parameter has 'ID' set to a value, then post will be updated. * * You can set the post date manually, but setting the values for 'post_date' * and 'post_date_gmt' keys. You can close the comments or open the comments by * setting the value for 'comment_status' key. * * The defaults for the parameter $postarr are: * 'post_status' - Default is 'draft'. * 'post_type' - Default is 'post'. * 'post_author' - Default is current user ID ($user_ID). The ID of the user who added the post. * 'ping_status' - Default is the value in 'default_ping_status' option. * Whether the attachment can accept pings. * 'post_parent' - Default is 0. Set this for the post it belongs to, if any. * 'menu_order' - Default is 0. The order it is displayed. * 'to_ping' - Whether to ping. * 'pinged' - Default is empty string. * 'post_password' - Default is empty string. The password to access the attachment. * 'guid' - Global Unique ID for referencing the attachment. * 'post_content_filtered' - Post content filtered. * 'post_excerpt' - Post excerpt. * * @since 1.0.0 * @uses $wpdb * @uses $user_ID * @uses do_action() Calls 'pre_post_update' on post ID if this is an update. * @uses do_action() Calls 'edit_post' action on post ID and post data if this is an update. * @uses do_action() Calls 'save_post' and 'wp_insert_post' on post id and post data just before returning. * @uses apply_filters() Calls 'wp_insert_post_data' passing $data, $postarr prior to database update or insert. * @uses wp_transition_post_status() * * @param array $postarr Elements that make up post to insert. * @param bool $wp_error Optional. Allow return of WP_Error on failure. * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success. */ function wp_insert_post($postarr, $wp_error = false) { global $wpdb, $user_ID; $defaults = array('post_status' => 'draft', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'post_content' => '', 'post_title' => ''); $postarr = wp_parse_args($postarr, $defaults); unset( $postarr[ 'filter' ] ); $postarr = sanitize_post($postarr, 'db'); // export array as variables extract($postarr, EXTR_SKIP); // Are we updating or creating? $update = false; if ( !empty($ID) ) { $update = true; $previous_status = get_post_field('post_status', $ID); } else { $previous_status = 'new'; } $maybe_empty = ! $post_content && ! $post_title && ! $post_excerpt && post_type_supports( $post_type, 'editor' ) && post_type_supports( $post_type, 'title' ) && post_type_supports( $post_type, 'excerpt' ); if ( apply_filters( 'wp_insert_post_empty_content', $maybe_empty, $postarr ) ) { if ( $wp_error ) return new WP_Error( 'empty_content', __( 'Content, title, and excerpt are empty.' ) ); else return 0; } if ( empty($post_type) ) $post_type = 'post'; if ( empty($post_status) ) $post_status = 'draft'; if ( !empty($post_category) ) $post_category = array_filter($post_category); // Filter out empty terms // Make sure we set a valid category. if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) { // 'post' requires at least one category. if ( 'post' == $post_type && 'auto-draft' != $post_status ) $post_category = array( get_option('default_category') ); else $post_category = array(); } if ( empty($post_author) ) $post_author = $user_ID; $post_ID = 0; // Get the post ID and GUID if ( $update ) { $post_ID = (int) $ID; $guid = get_post_field( 'guid', $post_ID ); $post_before = get_post($post_ID); } // Don't allow contributors to set the post slug for pending review posts if ( 'pending' == $post_status && !current_user_can( 'publish_posts' ) ) $post_name = ''; // Create a valid post name. Drafts and pending posts are allowed to have an empty // post name. if ( empty($post_name) ) { if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) $post_name = sanitize_title($post_title); else $post_name = ''; } else { // On updates, we need to check to see if it's using the old, fixed sanitization context. $check_name = sanitize_title( $post_name, '', 'old-save' ); if ( $update && strtolower( urlencode( $post_name ) ) == $check_name && get_post_field( 'post_name', $ID ) == $check_name ) $post_name = $check_name; else // new post, or slug has changed. $post_name = sanitize_title($post_name); } // If the post date is empty (due to having been new or a draft) and status is not 'draft' or 'pending', set date to now if ( empty($post_date) || '0000-00-00 00:00:00' == $post_date ) $post_date = current_time('mysql'); // validate the date $mm = substr( $post_date, 5, 2 ); $jj = substr( $post_date, 8, 2 ); $aa = substr( $post_date, 0, 4 ); $valid_date = wp_checkdate( $mm, $jj, $aa, $post_date ); if ( !$valid_date ) { if ( $wp_error ) return new WP_Error( 'invalid_date', __( 'Whoops, the provided date is invalid.' ) ); else return 0; } if ( empty($post_date_gmt) || '0000-00-00 00:00:00' == $post_date_gmt ) { if ( !in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) $post_date_gmt = get_gmt_from_date($post_date); else $post_date_gmt = '0000-00-00 00:00:00'; } if ( $update || '0000-00-00 00:00:00' == $post_date ) { $post_modified = current_time( 'mysql' ); $post_modified_gmt = current_time( 'mysql', 1 ); } else { $post_modified = $post_date; $post_modified_gmt = $post_date_gmt; } if ( 'publish' == $post_status ) { $now = gmdate('Y-m-d H:i:59'); if ( mysql2date('U', $post_date_gmt, false) > mysql2date('U', $now, false) ) $post_status = 'future'; } elseif( 'future' == $post_status ) { $now = gmdate('Y-m-d H:i:59'); if ( mysql2date('U', $post_date_gmt, false) <= mysql2date('U', $now, false) ) $post_status = 'publish'; } if ( empty($comment_status) ) { if ( $update ) $comment_status = 'closed'; else $comment_status = get_option('default_comment_status'); } if ( empty($ping_status) ) $ping_status = get_option('default_ping_status'); if ( isset($to_ping) ) $to_ping = sanitize_trackback_urls( $to_ping ); else $to_ping = ''; if ( ! isset($pinged) ) $pinged = ''; if ( isset($post_parent) ) $post_parent = (int) $post_parent; else $post_parent = 0; // Check the post_parent to see if it will cause a hierarchy loop $post_parent = apply_filters( 'wp_insert_post_parent', $post_parent, $post_ID, compact( array_keys( $postarr ) ), $postarr ); if ( isset($menu_order) ) $menu_order = (int) $menu_order; else $menu_order = 0; if ( !isset($post_password) || 'private' == $post_status ) $post_password = ''; $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent); // expected_slashed (everything!) $data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'guid' ) ); $data = apply_filters('wp_insert_post_data', $data, $postarr); $data = stripslashes_deep( $data ); $where = array( 'ID' => $post_ID ); if ( $update ) { do_action( 'pre_post_update', $post_ID ); if ( false === $wpdb->update( $wpdb->posts, $data, $where ) ) { if ( $wp_error ) return new WP_Error('db_update_error', __('Could not update post in the database'), $wpdb->last_error); else return 0; } } else { if ( isset($post_mime_type) ) $data['post_mime_type'] = stripslashes( $post_mime_type ); // This isn't in the update // If there is a suggested ID, use it if not already present if ( !empty($import_id) ) { $import_id = (int) $import_id; if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) { $data['ID'] = $import_id; } } if ( false === $wpdb->insert( $wpdb->posts, $data ) ) { if ( $wp_error ) return new WP_Error('db_insert_error', __('Could not insert post into the database'), $wpdb->last_error); else return 0; } $post_ID = (int) $wpdb->insert_id; // use the newly generated $post_ID $where = array( 'ID' => $post_ID ); } if ( empty($data['post_name']) && !in_array( $data['post_status'], array( 'draft', 'pending', 'auto-draft' ) ) ) { $data['post_name'] = sanitize_title($data['post_title'], $post_ID); $wpdb->update( $wpdb->posts, array( 'post_name' => $data['post_name'] ), $where ); } if ( is_object_in_taxonomy($post_type, 'category') ) wp_set_post_categories( $post_ID, $post_category ); if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') ) wp_set_post_tags( $post_ID, $tags_input ); // new-style support for all custom taxonomies if ( !empty($tax_input) ) { foreach ( $tax_input as $taxonomy => $tags ) { $taxonomy_obj = get_taxonomy($taxonomy); if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical. $tags = array_filter($tags); if ( current_user_can($taxonomy_obj->cap->assign_terms) ) wp_set_post_terms( $post_ID, $tags, $taxonomy ); } } $current_guid = get_post_field( 'guid', $post_ID ); // Set GUID if ( !$update && '' == $current_guid ) $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post_ID ) ), $where ); clean_post_cache( $post_ID ); $post = get_post($post_ID); if ( !empty($page_template) && 'page' == $data['post_type'] ) { $post->page_template = $page_template; $page_templates = wp_get_theme()->get_page_templates(); if ( 'default' != $page_template && ! isset( $page_templates[ $page_template ] ) ) { if ( $wp_error ) return new WP_Error('invalid_page_template', __('The page template is invalid.')); else return 0; } update_post_meta($post_ID, '_wp_page_template', $page_template); } wp_transition_post_status($data['post_status'], $previous_status, $post); if ( $update ) { do_action('edit_post', $post_ID, $post); $post_after = get_post($post_ID); do_action( 'post_updated', $post_ID, $post_after, $post_before); } do_action('save_post', $post_ID, $post); do_action('wp_insert_post', $post_ID, $post); return $post_ID; } /** * Update a post with new post data. * * The date does not have to be set for drafts. You can set the date and it will * not be overridden. * * @since 1.0.0 * * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not. * @param bool $wp_error Optional. Allow return of WP_Error on failure. * @return int|WP_Error The value 0 or WP_Error on failure. The post ID on success. */ function wp_update_post( $postarr = array(), $wp_error = false ) { if ( is_object($postarr) ) { // non-escaped post was passed $postarr = get_object_vars($postarr); $postarr = add_magic_quotes($postarr); } // First, get all of the original fields $post = get_post($postarr['ID'], ARRAY_A); // Escape data pulled from DB. $post = add_magic_quotes($post); // Passed post category list overwrites existing category list if not empty. if ( isset($postarr['post_category']) && is_array($postarr['post_category']) && 0 != count($postarr['post_category']) ) $post_cats = $postarr['post_category']; else $post_cats = $post['post_category']; // Drafts shouldn't be assigned a date unless explicitly done so by the user if ( isset( $post['post_status'] ) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) && ('0000-00-00 00:00:00' == $post['post_date_gmt']) ) $clear_date = true; else $clear_date = false; // Merge old and new fields with new fields overwriting old ones. $postarr = array_merge($post, $postarr); $postarr['post_category'] = $post_cats; if ( $clear_date ) { $postarr['post_date'] = current_time('mysql'); $postarr['post_date_gmt'] = ''; } if ($postarr['post_type'] == 'attachment') return wp_insert_attachment($postarr); return wp_insert_post( $postarr, $wp_error ); } /** * Publish a post by transitioning the post status. * * @since 2.1.0 * @uses wp_update_post() * * @param mixed $post Post ID or object. */ function wp_publish_post( $post ) { if ( ! $post = get_post( $post ) ) return; if ( 'publish' == $post->post_status ) return; $post->post_status = 'publish'; wp_update_post( $post ); } /** * Publish future post and make sure post ID has future post status. * * Invoked by cron 'publish_future_post' event. This safeguard prevents cron * from publishing drafts, etc. * * @since 2.5.0 * * @param int $post_id Post ID. * @return null Nothing is returned. Which can mean that no action is required or post was published. */ function check_and_publish_future_post($post_id) { $post = get_post($post_id); if ( empty($post) ) return; if ( 'future' != $post->post_status ) return; $time = strtotime( $post->post_date_gmt . ' GMT' ); if ( $time > time() ) { // Uh oh, someone jumped the gun! wp_clear_scheduled_hook( 'publish_future_post', array( $post_id ) ); // clear anything else in the system wp_schedule_single_event( $time, 'publish_future_post', array( $post_id ) ); return; } return wp_publish_post($post_id); } /** * Computes a unique slug for the post, when given the desired slug and some post details. * * @since 2.8.0 * * @global wpdb $wpdb * @global WP_Rewrite $wp_rewrite * @param string $slug the desired slug (post_name) * @param integer $post_ID * @param string $post_status no uniqueness checks are made if the post is still draft or pending * @param string $post_type * @param integer $post_parent * @return string unique slug for the post, based on $post_name (with a -1, -2, etc. suffix) */ function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) { if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) return $slug; global $wpdb, $wp_rewrite; $original_slug = $slug; $feeds = $wp_rewrite->feeds; if ( ! is_array( $feeds ) ) $feeds = array(); $hierarchical_post_types = get_post_types( array('hierarchical' => true) ); if ( 'attachment' == $post_type ) { // Attachment slugs must be unique across all types. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND ID != %d LIMIT 1"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID ) ); if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_attachment_slug', false, $slug ) ) { $suffix = 2; do { $alt_post_name = substr ($slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; $post_name_check = $wpdb->get_var( $wpdb->prepare($check_sql, $alt_post_name, $post_ID ) ); $suffix++; } while ( $post_name_check ); $slug = $alt_post_name; } } elseif ( in_array( $post_type, $hierarchical_post_types ) ) { if ( 'nav_menu_item' == $post_type ) return $slug; // Page slugs must be unique within their own trees. Pages are in a separate // namespace than posts so page slugs are allowed to overlap post slugs. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type IN ( '" . implode( "', '", esc_sql( $hierarchical_post_types ) ) . "' ) AND ID != %d AND post_parent = %d LIMIT 1"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_ID, $post_parent ) ); if ( $post_name_check || in_array( $slug, $feeds ) || preg_match( "@^($wp_rewrite->pagination_base)?\d+$@", $slug ) || apply_filters( 'wp_unique_post_slug_is_bad_hierarchical_slug', false, $slug, $post_type, $post_parent ) ) { $suffix = 2; do { $alt_post_name = substr( $slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) ); $suffix++; } while ( $post_name_check ); $slug = $alt_post_name; } } else { // Post slugs must be unique across all posts. $check_sql = "SELECT post_name FROM $wpdb->posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $slug, $post_type, $post_ID ) ); if ( $post_name_check || in_array( $slug, $feeds ) || apply_filters( 'wp_unique_post_slug_is_bad_flat_slug', false, $slug, $post_type ) ) { $suffix = 2; do { $alt_post_name = substr( $slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; $post_name_check = $wpdb->get_var( $wpdb->prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) ); $suffix++; } while ( $post_name_check ); $slug = $alt_post_name; } } return apply_filters( 'wp_unique_post_slug', $slug, $post_ID, $post_status, $post_type, $post_parent, $original_slug ); } /** * Adds tags to a post. * * @uses wp_set_post_tags() Same first two parameters, but the last parameter is always set to true. * * @package WordPress * @subpackage Post * @since 2.3.0 * * @param int $post_id Post ID * @param string $tags The tags to set for the post, separated by commas. * @return bool|null Will return false if $post_id is not an integer or is 0. Will return null otherwise */ function wp_add_post_tags($post_id = 0, $tags = '') { return wp_set_post_tags($post_id, $tags, true); } /** * Set the tags for a post. * * @since 2.3.0 * @uses wp_set_object_terms() Sets the tags for the post. * * @param int $post_id Post ID. * @param string $tags The tags to set for the post, separated by commas. * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags. * @return mixed Array of affected term IDs. WP_Error or false on failure. */ function wp_set_post_tags( $post_id = 0, $tags = '', $append = false ) { return wp_set_post_terms( $post_id, $tags, 'post_tag', $append); } /** * Set the terms for a post. * * @since 2.8.0 * @uses wp_set_object_terms() Sets the tags for the post. * * @param int $post_id Post ID. * @param string $tags The tags to set for the post, separated by commas. * @param string $taxonomy Taxonomy name. Defaults to 'post_tag'. * @param bool $append If true, don't delete existing tags, just add on. If false, replace the tags with the new tags. * @return mixed Array of affected term IDs. WP_Error or false on failure. */ function wp_set_post_terms( $post_id = 0, $tags = '', $taxonomy = 'post_tag', $append = false ) { $post_id = (int) $post_id; if ( !$post_id ) return false; if ( empty($tags) ) $tags = array(); if ( ! is_array( $tags ) ) { $comma = _x( ',', 'tag delimiter' ); if ( ',' !== $comma ) $tags = str_replace( $comma, ',', $tags ); $tags = explode( ',', trim( $tags, " \n\t\r\0\x0B," ) ); } // Hierarchical taxonomies must always pass IDs rather than names so that children with the same // names but different parents aren't confused. if ( is_taxonomy_hierarchical( $taxonomy ) ) { $tags = array_unique( array_map( 'intval', $tags ) ); } return wp_set_object_terms( $post_id, $tags, $taxonomy, $append ); } /** * Set categories for a post. * * If the post categories parameter is not set, then the default category is * going used. * * @since 2.1.0 * * @param int $post_ID Post ID. * @param array $post_categories Optional. List of categories. * @return bool|mixed */ function wp_set_post_categories($post_ID = 0, $post_categories = array()) { $post_ID = (int) $post_ID; $post_type = get_post_type( $post_ID ); $post_status = get_post_status( $post_ID ); // If $post_categories isn't already an array, make it one: if ( !is_array($post_categories) || empty($post_categories) ) { if ( 'post' == $post_type && 'auto-draft' != $post_status ) $post_categories = array( get_option('default_category') ); else $post_categories = array(); } else if ( 1 == count($post_categories) && '' == reset($post_categories) ) { return true; } return wp_set_post_terms($post_ID, $post_categories, 'category'); } /** * Transition the post status of a post. * * Calls hooks to transition post status. * * The first is 'transition_post_status' with new status, old status, and post data. * * The next action called is 'OLDSTATUS_to_NEWSTATUS' the 'NEWSTATUS' is the * $new_status parameter and the 'OLDSTATUS' is $old_status parameter; it has the * post data. * * The final action is named 'NEWSTATUS_POSTTYPE', 'NEWSTATUS' is from the $new_status * parameter and POSTTYPE is post_type post data. * * @since 2.3.0 * @link http://codex.wordpress.org/Post_Status_Transitions * * @uses do_action() Calls 'transition_post_status' on $new_status, $old_status and * $post if there is a status change. * @uses do_action() Calls '{$old_status}_to_{$new_status}' on $post if there is a status change. * @uses do_action() Calls '{$new_status}_{$post->post_type}' on post ID and $post. * * @param string $new_status Transition to this post status. * @param string $old_status Previous post status. * @param object $post Post data. */ function wp_transition_post_status($new_status, $old_status, $post) { do_action('transition_post_status', $new_status, $old_status, $post); do_action("{$old_status}_to_{$new_status}", $post); do_action("{$new_status}_{$post->post_type}", $post->ID, $post); } // // Trackback and ping functions // /** * Add a URL to those already pung. * * @since 1.5.0 * @uses $wpdb * * @param int $post_id Post ID. * @param string $uri Ping URI. * @return int How many rows were updated. */ function add_ping($post_id, $uri) { global $wpdb; $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id )); $pung = trim($pung); $pung = preg_split('/\s/', $pung); $pung[] = $uri; $new = implode("\n", $pung); $new = apply_filters('add_ping', $new); // expected_slashed ($new) $new = stripslashes($new); return $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post_id ) ); } /** * Retrieve enclosures already enclosed for a post. * * @since 1.5.0 * @uses $wpdb * * @param int $post_id Post ID. * @return array List of enclosures */ function get_enclosed($post_id) { $custom_fields = get_post_custom( $post_id ); $pung = array(); if ( !is_array( $custom_fields ) ) return $pung; foreach ( $custom_fields as $key => $val ) { if ( 'enclosure' != $key || !is_array( $val ) ) continue; foreach( $val as $enc ) { $enclosure = explode( "\n", $enc ); $pung[] = trim( $enclosure[ 0 ] ); } } $pung = apply_filters('get_enclosed', $pung, $post_id); return $pung; } /** * Retrieve URLs already pinged for a post. * * @since 1.5.0 * @uses $wpdb * * @param int $post_id Post ID. * @return array */ function get_pung($post_id) { global $wpdb; $pung = $wpdb->get_var( $wpdb->prepare( "SELECT pinged FROM $wpdb->posts WHERE ID = %d", $post_id )); $pung = trim($pung); $pung = preg_split('/\s/', $pung); $pung = apply_filters('get_pung', $pung); return $pung; } /** * Retrieve URLs that need to be pinged. * * @since 1.5.0 * @uses $wpdb * * @param int $post_id Post ID * @return array */ function get_to_ping($post_id) { global $wpdb; $to_ping = $wpdb->get_var( $wpdb->prepare( "SELECT to_ping FROM $wpdb->posts WHERE ID = %d", $post_id )); $to_ping = sanitize_trackback_urls( $to_ping ); $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY); $to_ping = apply_filters('get_to_ping', $to_ping); return $to_ping; } /** * Do trackbacks for a list of URLs. * * @since 1.0.0 * * @param string $tb_list Comma separated list of URLs * @param int $post_id Post ID */ function trackback_url_list($tb_list, $post_id) { if ( ! empty( $tb_list ) ) { // get post data $postdata = get_post($post_id, ARRAY_A); // import postdata as variables extract($postdata, EXTR_SKIP); // form an excerpt $excerpt = strip_tags($post_excerpt ? $post_excerpt : $post_content); if (strlen($excerpt) > 255) { $excerpt = substr($excerpt,0,252) . '...'; } $trackback_urls = explode(',', $tb_list); foreach( (array) $trackback_urls as $tb_url) { $tb_url = trim($tb_url); trackback($tb_url, stripslashes($post_title), $excerpt, $post_id); } } } // // Page functions // /** * Get a list of page IDs. * * @since 2.0.0 * @uses $wpdb * * @return array List of page IDs. */ function get_all_page_ids() { global $wpdb; $page_ids = wp_cache_get('all_page_ids', 'posts'); if ( ! is_array( $page_ids ) ) { $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'"); wp_cache_add('all_page_ids', $page_ids, 'posts'); } return $page_ids; } /** * Retrieves page data given a page ID or page object. * * Use get_post() instead of get_page(). * * @since 1.5.1 * @deprecated 3.5.0 * * @param mixed $page Page object or page ID. Passed by reference. * @param string $output What to output. OBJECT, ARRAY_A, or ARRAY_N. * @param string $filter How the return value should be filtered. * @return WP_Post|null WP_Post on success or null on failure */ function get_page( $page, $output = OBJECT, $filter = 'raw') { return get_post( $page, $output, $filter ); } /** * Retrieves a page given its path. * * @since 2.1.0 * @uses $wpdb * * @param string $page_path Page path * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT. * @param string $post_type Optional. Post type. Default page. * @return WP_Post|null WP_Post on success or null on failure */ function get_page_by_path($page_path, $output = OBJECT, $post_type = 'page') { global $wpdb; $page_path = rawurlencode(urldecode($page_path)); $page_path = str_replace('%2F', '/', $page_path); $page_path = str_replace('%20', ' ', $page_path); $parts = explode( '/', trim( $page_path, '/' ) ); $parts = array_map( 'esc_sql', $parts ); $parts = array_map( 'sanitize_title_for_query', $parts ); $in_string = "'". implode( "','", $parts ) . "'"; $post_type_sql = $post_type; $wpdb->escape_by_ref( $post_type_sql ); $pages = $wpdb->get_results( "SELECT ID, post_name, post_parent, post_type FROM $wpdb->posts WHERE post_name IN ($in_string) AND (post_type = '$post_type_sql' OR post_type = 'attachment')", OBJECT_K ); $revparts = array_reverse( $parts ); $foundid = 0; foreach ( (array) $pages as $page ) { if ( $page->post_name == $revparts[0] ) { $count = 0; $p = $page; while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) { $count++; $parent = $pages[ $p->post_parent ]; if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] ) break; $p = $parent; } if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) { $foundid = $page->ID; if ( $page->post_type == $post_type ) break; } } } if ( $foundid ) return get_post( $foundid, $output ); return null; } /** * Retrieve a page given its title. * * @since 2.1.0 * @uses $wpdb * * @param string $page_title Page title * @param string $output Optional. Output type. OBJECT, ARRAY_N, or ARRAY_A. Default OBJECT. * @param string $post_type Optional. Post type. Default page. * @return WP_Post|null WP_Post on success or null on failure */ function get_page_by_title($page_title, $output = OBJECT, $post_type = 'page' ) { global $wpdb; $page = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $page_title, $post_type ) ); if ( $page ) return get_post( $page, $output ); return null; } /** * Retrieve child pages from list of pages matching page ID. * * Matches against the pages parameter against the page ID. Also matches all * children for the same to retrieve all children of a page. Does not make any * SQL queries to get the children. * * @since 1.5.1 * * @param int $page_id Page ID. * @param array $pages List of pages' objects. * @return array */ function get_page_children($page_id, $pages) { $page_list = array(); foreach ( (array) $pages as $page ) { if ( $page->post_parent == $page_id ) { $page_list[] = $page; if ( $children = get_page_children($page->ID, $pages) ) $page_list = array_merge($page_list, $children); } } return $page_list; } /** * Order the pages with children under parents in a flat list. * * It uses auxiliary structure to hold parent-children relationships and * runs in O(N) complexity * * @since 2.0.0 * * @param array $pages Posts array. * @param int $page_id Parent page ID. * @return array A list arranged by hierarchy. Children immediately follow their parents. */ function get_page_hierarchy( &$pages, $page_id = 0 ) { if ( empty( $pages ) ) { $result = array(); return $result; } $children = array(); foreach ( (array) $pages as $p ) { $parent_id = intval( $p->post_parent ); $children[ $parent_id ][] = $p; } $result = array(); _page_traverse_name( $page_id, $children, $result ); return $result; } /** * function to traverse and return all the nested children post names of a root page. * $children contains parent-children relations * * @since 2.9.0 */ function _page_traverse_name( $page_id, &$children, &$result ){ if ( isset( $children[ $page_id ] ) ){ foreach( (array)$children[ $page_id ] as $child ) { $result[ $child->ID ] = $child->post_name; _page_traverse_name( $child->ID, $children, $result ); } } } /** * Builds URI for a page. * * Sub pages will be in the "directory" under the parent page post name. * * @since 1.5.0 * * @param mixed $page Page object or page ID. * @return string Page URI. */ function get_page_uri($page) { if ( ! is_object($page) ) $page = get_post( $page ); $uri = $page->post_name; foreach ( $page->ancestors as $parent ) { $uri = get_post( $parent )->post_name . "/" . $uri; } return $uri; } /** * Retrieve a list of pages. * * The defaults that can be overridden are the following: 'child_of', * 'sort_order', 'sort_column', 'post_title', 'hierarchical', 'exclude', * 'include', 'meta_key', 'meta_value','authors', 'number', and 'offset'. * * @since 1.5.0 * @uses $wpdb * * @param mixed $args Optional. Array or string of options that overrides defaults. * @return array List of pages matching defaults or $args */ function get_pages($args = '') { global $wpdb; $pages = false; $defaults = array( 'child_of' => 0, 'sort_order' => 'ASC', 'sort_column' => 'post_title', 'hierarchical' => 1, 'exclude' => array(), 'include' => array(), 'meta_key' => '', 'meta_value' => '', 'authors' => '', 'parent' => -1, 'exclude_tree' => '', 'number' => '', 'offset' => 0, 'post_type' => 'page', 'post_status' => 'publish', ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $number = (int) $number; $offset = (int) $offset; // Make sure the post type is hierarchical $hierarchical_post_types = get_post_types( array( 'hierarchical' => true ) ); if ( !in_array( $post_type, $hierarchical_post_types ) ) return $pages; // Make sure we have a valid post status if ( !is_array( $post_status ) ) $post_status = explode( ',', $post_status ); if ( array_diff( $post_status, get_post_stati() ) ) return $pages; $cache = array(); $key = md5( serialize( compact(array_keys($defaults)) ) ); if ( $cache = wp_cache_get( 'get_pages', 'posts' ) ) { if ( is_array($cache) && isset( $cache[ $key ] ) && is_array( $cache[ $key ] ) ) { // Convert to WP_Post instances $pages = array_map( 'get_post', $cache[ $key ] ); $pages = apply_filters( 'get_pages', $pages, $r ); return $pages; } } if ( !is_array($cache) ) $cache = array(); $inclusions = ''; if ( !empty($include) ) { $child_of = 0; //ignore child_of, parent, exclude, meta_key, and meta_value params if using include $parent = -1; $exclude = ''; $meta_key = ''; $meta_value = ''; $hierarchical = false; $incpages = wp_parse_id_list( $include ); if ( ! empty( $incpages ) ) { foreach ( $incpages as $incpage ) { if (empty($inclusions)) $inclusions = $wpdb->prepare(' AND ( ID = %d ', $incpage); else $inclusions .= $wpdb->prepare(' OR ID = %d ', $incpage); } } } if (!empty($inclusions)) $inclusions .= ')'; $exclusions = ''; if ( !empty($exclude) ) { $expages = wp_parse_id_list( $exclude ); if ( ! empty( $expages ) ) { foreach ( $expages as $expage ) { if (empty($exclusions)) $exclusions = $wpdb->prepare(' AND ( ID <> %d ', $expage); else $exclusions .= $wpdb->prepare(' AND ID <> %d ', $expage); } } } if (!empty($exclusions)) $exclusions .= ')'; $author_query = ''; if (!empty($authors)) { $post_authors = preg_split('/[\s,]+/',$authors); if ( ! empty( $post_authors ) ) { foreach ( $post_authors as $post_author ) { //Do we have an author id or an author login? if ( 0 == intval($post_author) ) { $post_author = get_user_by('login', $post_author); if ( empty($post_author) ) continue; if ( empty($post_author->ID) ) continue; $post_author = $post_author->ID; } if ( '' == $author_query ) $author_query = $wpdb->prepare(' post_author = %d ', $post_author); else $author_query .= $wpdb->prepare(' OR post_author = %d ', $post_author); } if ( '' != $author_query ) $author_query = " AND ($author_query)"; } } $join = ''; $where = "$exclusions $inclusions "; if ( ! empty( $meta_key ) || ! empty( $meta_value ) ) { $join = " LEFT JOIN $wpdb->postmeta ON ( $wpdb->posts.ID = $wpdb->postmeta.post_id )"; // meta_key and meta_value might be slashed $meta_key = stripslashes($meta_key); $meta_value = stripslashes($meta_value); if ( ! empty( $meta_key ) ) $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_key = %s", $meta_key); if ( ! empty( $meta_value ) ) $where .= $wpdb->prepare(" AND $wpdb->postmeta.meta_value = %s", $meta_value); } if ( $parent >= 0 ) $where .= $wpdb->prepare(' AND post_parent = %d ', $parent); if ( 1 == count( $post_status ) ) { $where_post_type = $wpdb->prepare( "post_type = %s AND post_status = %s", $post_type, array_shift( $post_status ) ); } else { $post_status = implode( "', '", $post_status ); $where_post_type = $wpdb->prepare( "post_type = %s AND post_status IN ('$post_status')", $post_type ); } $orderby_array = array(); $allowed_keys = array('author', 'post_author', 'date', 'post_date', 'title', 'post_title', 'name', 'post_name', 'modified', 'post_modified', 'modified_gmt', 'post_modified_gmt', 'menu_order', 'parent', 'post_parent', 'ID', 'rand', 'comment_count'); foreach ( explode( ',', $sort_column ) as $orderby ) { $orderby = trim( $orderby ); if ( !in_array( $orderby, $allowed_keys ) ) continue; switch ( $orderby ) { case 'menu_order': break; case 'ID': $orderby = "$wpdb->posts.ID"; break; case 'rand': $orderby = 'RAND()'; break; case 'comment_count': $orderby = "$wpdb->posts.comment_count"; break; default: if ( 0 === strpos( $orderby, 'post_' ) ) $orderby = "$wpdb->posts." . $orderby; else $orderby = "$wpdb->posts.post_" . $orderby; } $orderby_array[] = $orderby; } $sort_column = ! empty( $orderby_array ) ? implode( ',', $orderby_array ) : "$wpdb->posts.post_title"; $sort_order = strtoupper( $sort_order ); if ( '' !== $sort_order && !in_array( $sort_order, array( 'ASC', 'DESC' ) ) ) $sort_order = 'ASC'; $query = "SELECT * FROM $wpdb->posts $join WHERE ($where_post_type) $where "; $query .= $author_query; $query .= " ORDER BY " . $sort_column . " " . $sort_order ; if ( !empty($number) ) $query .= ' LIMIT ' . $offset . ',' . $number; $pages = $wpdb->get_results($query); if ( empty($pages) ) { $pages = apply_filters('get_pages', array(), $r); return $pages; } // Sanitize before caching so it'll only get done once $num_pages = count($pages); for ($i = 0; $i < $num_pages; $i++) { $pages[$i] = sanitize_post($pages[$i], 'raw'); } // Update cache. update_post_cache( $pages ); if ( $child_of || $hierarchical ) $pages = get_page_children($child_of, $pages); if ( !empty($exclude_tree) ) { $exclude = (int) $exclude_tree; $children = get_page_children($exclude, $pages); $excludes = array(); foreach ( $children as $child ) $excludes[] = $child->ID; $excludes[] = $exclude; $num_pages = count($pages); for ( $i = 0; $i < $num_pages; $i++ ) { if ( in_array($pages[$i]->ID, $excludes) ) unset($pages[$i]); } } $cache[ $key ] = $pages; wp_cache_set( 'get_pages', $cache, 'posts' ); // Convert to WP_Post instances $pages = array_map( 'get_post', $pages ); $pages = apply_filters('get_pages', $pages, $r); return $pages; } // // Attachment functions // /** * Check if the attachment URI is local one and is really an attachment. * * @since 2.0.0 * * @param string $url URL to check * @return bool True on success, false on failure. */ function is_local_attachment($url) { if (strpos($url, home_url()) === false) return false; if (strpos($url, home_url('/?attachment_id=')) !== false) return true; if ( $id = url_to_postid($url) ) { $post = get_post($id); if ( 'attachment' == $post->post_type ) return true; } return false; } /** * Insert an attachment. * * If you set the 'ID' in the $object parameter, it will mean that you are * updating and attempt to update the attachment. You can also set the * attachment name or title by setting the key 'post_name' or 'post_title'. * * You can set the dates for the attachment manually by setting the 'post_date' * and 'post_date_gmt' keys' values. * * By default, the comments will use the default settings for whether the * comments are allowed. You can close them manually or keep them open by * setting the value for the 'comment_status' key. * * The $object parameter can have the following: * 'post_status' - Default is 'draft'. Can not be overridden, set the same as parent post. * 'post_type' - Default is 'post', will be set to attachment. Can not override. * 'post_author' - Default is current user ID. The ID of the user, who added the attachment. * 'ping_status' - Default is the value in default ping status option. Whether the attachment * can accept pings. * 'post_parent' - Default is 0. Can use $parent parameter or set this for the post it belongs * to, if any. * 'menu_order' - Default is 0. The order it is displayed. * 'to_ping' - Whether to ping. * 'pinged' - Default is empty string. * 'post_password' - Default is empty string. The password to access the attachment. * 'guid' - Global Unique ID for referencing the attachment. * 'post_content_filtered' - Attachment post content filtered. * 'post_excerpt' - Attachment excerpt. * * @since 2.0.0 * @uses $wpdb * @uses $user_ID * @uses do_action() Calls 'edit_attachment' on $post_ID if this is an update. * @uses do_action() Calls 'add_attachment' on $post_ID if this is not an update. * * @param string|array $object Arguments to override defaults. * @param string $file Optional filename. * @param int $parent Parent post ID. * @return int Attachment ID. */ function wp_insert_attachment($object, $file = false, $parent = 0) { global $wpdb, $user_ID; $defaults = array('post_status' => 'inherit', 'post_type' => 'post', 'post_author' => $user_ID, 'ping_status' => get_option('default_ping_status'), 'post_parent' => 0, 'menu_order' => 0, 'to_ping' => '', 'pinged' => '', 'post_password' => '', 'guid' => '', 'post_content_filtered' => '', 'post_excerpt' => '', 'import_id' => 0, 'context' => ''); $object = wp_parse_args($object, $defaults); if ( !empty($parent) ) $object['post_parent'] = $parent; unset( $object[ 'filter' ] ); $object = sanitize_post($object, 'db'); // export array as variables extract($object, EXTR_SKIP); if ( empty($post_author) ) $post_author = $user_ID; $post_type = 'attachment'; if ( ! in_array( $post_status, array( 'inherit', 'private' ) ) ) $post_status = 'inherit'; if ( !empty($post_category) ) $post_category = array_filter($post_category); // Filter out empty terms // Make sure we set a valid category. if ( empty($post_category) || 0 == count($post_category) || !is_array($post_category) ) { $post_category = array(); } // Are we updating or creating? if ( !empty($ID) ) { $update = true; $post_ID = (int) $ID; } else { $update = false; $post_ID = 0; } // Create a valid post name. if ( empty($post_name) ) $post_name = sanitize_title($post_title); else $post_name = sanitize_title($post_name); // expected_slashed ($post_name) $post_name = wp_unique_post_slug($post_name, $post_ID, $post_status, $post_type, $post_parent); if ( empty($post_date) ) $post_date = current_time('mysql'); if ( empty($post_date_gmt) ) $post_date_gmt = current_time('mysql', 1); if ( empty($post_modified) ) $post_modified = $post_date; if ( empty($post_modified_gmt) ) $post_modified_gmt = $post_date_gmt; if ( empty($comment_status) ) { if ( $update ) $comment_status = 'closed'; else $comment_status = get_option('default_comment_status'); } if ( empty($ping_status) ) $ping_status = get_option('default_ping_status'); if ( isset($to_ping) ) $to_ping = preg_replace('|\s+|', "\n", $to_ping); else $to_ping = ''; if ( isset($post_parent) ) $post_parent = (int) $post_parent; else $post_parent = 0; if ( isset($menu_order) ) $menu_order = (int) $menu_order; else $menu_order = 0; if ( !isset($post_password) ) $post_password = ''; if ( ! isset($pinged) ) $pinged = ''; // expected_slashed (everything!) $data = compact( array( 'post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_content_filtered', 'post_title', 'post_excerpt', 'post_status', 'post_type', 'comment_status', 'ping_status', 'post_password', 'post_name', 'to_ping', 'pinged', 'post_modified', 'post_modified_gmt', 'post_parent', 'menu_order', 'post_mime_type', 'guid' ) ); $data = stripslashes_deep( $data ); if ( $update ) { $wpdb->update( $wpdb->posts, $data, array( 'ID' => $post_ID ) ); } else { // If there is a suggested ID, use it if not already present if ( !empty($import_id) ) { $import_id = (int) $import_id; if ( ! $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE ID = %d", $import_id) ) ) { $data['ID'] = $import_id; } } $wpdb->insert( $wpdb->posts, $data ); $post_ID = (int) $wpdb->insert_id; } if ( empty($post_name) ) { $post_name = sanitize_title($post_title, $post_ID); $wpdb->update( $wpdb->posts, compact("post_name"), array( 'ID' => $post_ID ) ); } if ( is_object_in_taxonomy($post_type, 'category') ) wp_set_post_categories( $post_ID, $post_category ); if ( isset( $tags_input ) && is_object_in_taxonomy($post_type, 'post_tag') ) wp_set_post_tags( $post_ID, $tags_input ); // support for all custom taxonomies if ( !empty($tax_input) ) { foreach ( $tax_input as $taxonomy => $tags ) { $taxonomy_obj = get_taxonomy($taxonomy); if ( is_array($tags) ) // array = hierarchical, string = non-hierarchical. $tags = array_filter($tags); if ( current_user_can($taxonomy_obj->cap->assign_terms) ) wp_set_post_terms( $post_ID, $tags, $taxonomy ); } } if ( $file ) update_attached_file( $post_ID, $file ); clean_post_cache( $post_ID ); if ( ! empty( $context ) ) add_post_meta( $post_ID, '_wp_attachment_context', $context, true ); if ( $update) { do_action('edit_attachment', $post_ID); } else { do_action('add_attachment', $post_ID); } return $post_ID; } /** * Trashes or deletes an attachment. * * When an attachment is permanently deleted, the file will also be removed. * Deletion removes all post meta fields, taxonomy, comments, etc. associated * with the attachment (except the main post). * * The attachment is moved to the trash instead of permanently deleted unless trash * for media is disabled, item is already in the trash, or $force_delete is true. * * @since 2.0.0 * @uses $wpdb * @uses do_action() Calls 'delete_attachment' hook on Attachment ID. * * @param int $post_id Attachment ID. * @param bool $force_delete Whether to bypass trash and force deletion. Defaults to false. * @return mixed False on failure. Post data on success. */ function wp_delete_attachment( $post_id, $force_delete = false ) { global $wpdb; if ( !$post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) ) ) return $post; if ( 'attachment' != $post->post_type ) return false; if ( !$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status ) return wp_trash_post( $post_id ); delete_post_meta($post_id, '_wp_trash_meta_status'); delete_post_meta($post_id, '_wp_trash_meta_time'); $meta = wp_get_attachment_metadata( $post_id ); $backup_sizes = get_post_meta( $post->ID, '_wp_attachment_backup_sizes', true ); $file = get_attached_file( $post_id ); $intermediate_sizes = array(); foreach ( get_intermediate_image_sizes() as $size ) { if ( $intermediate = image_get_intermediate_size( $post_id, $size ) ) $intermediate_sizes[] = $intermediate; } if ( is_multisite() ) delete_transient( 'dirsize_cache' ); do_action('delete_attachment', $post_id); wp_delete_object_term_relationships($post_id, array('category', 'post_tag')); wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type)); delete_metadata( 'post', null, '_thumbnail_id', $post_id, true ); // delete all for any posts. $comment_ids = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d", $post_id )); foreach ( $comment_ids as $comment_id ) wp_delete_comment( $comment_id, true ); $post_meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d ", $post_id )); foreach ( $post_meta_ids as $mid ) delete_metadata_by_mid( 'post', $mid ); do_action( 'delete_post', $post_id ); $wpdb->delete( $wpdb->posts, array( 'ID' => $post_id ) ); do_action( 'deleted_post', $post_id ); $uploadpath = wp_upload_dir(); if ( ! empty($meta['thumb']) ) { // Don't delete the thumb if another attachment uses it if (! $wpdb->get_row( $wpdb->prepare( "SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $meta['thumb'] . '%', $post_id)) ) { $thumbfile = str_replace(basename($file), $meta['thumb'], $file); $thumbfile = apply_filters('wp_delete_file', $thumbfile); @ unlink( path_join($uploadpath['basedir'], $thumbfile) ); } } // remove intermediate and backup images if there are any foreach ( $intermediate_sizes as $intermediate ) { $intermediate_file = apply_filters( 'wp_delete_file', $intermediate['path'] ); @ unlink( path_join($uploadpath['basedir'], $intermediate_file) ); } if ( is_array($backup_sizes) ) { foreach ( $backup_sizes as $size ) { $del_file = path_join( dirname($meta['file']), $size['file'] ); $del_file = apply_filters('wp_delete_file', $del_file); @ unlink( path_join($uploadpath['basedir'], $del_file) ); } } $file = apply_filters('wp_delete_file', $file); if ( ! empty($file) ) @ unlink($file); clean_post_cache( $post ); return $post; } /** * Retrieve attachment meta field for attachment ID. * * @since 2.1.0 * * @param int $post_id Attachment ID * @param bool $unfiltered Optional, default is false. If true, filters are not run. * @return string|bool Attachment meta field. False on failure. */ function wp_get_attachment_metadata( $post_id = 0, $unfiltered = false ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; $data = get_post_meta( $post->ID, '_wp_attachment_metadata', true ); if ( $unfiltered ) return $data; return apply_filters( 'wp_get_attachment_metadata', $data, $post->ID ); } /** * Update metadata for an attachment. * * @since 2.1.0 * * @param int $post_id Attachment ID. * @param array $data Attachment data. * @return int */ function wp_update_attachment_metadata( $post_id, $data ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; if ( $data = apply_filters( 'wp_update_attachment_metadata', $data, $post->ID ) ) return update_post_meta( $post->ID, '_wp_attachment_metadata', $data ); else return delete_post_meta( $post->ID, '_wp_attachment_metadata' ); } /** * Retrieve the URL for an attachment. * * @since 2.1.0 * * @param int $post_id Attachment ID. * @return string */ function wp_get_attachment_url( $post_id = 0 ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; if ( 'attachment' != $post->post_type ) return false; $url = ''; if ( $file = get_post_meta( $post->ID, '_wp_attached_file', true) ) { //Get attached file if ( ($uploads = wp_upload_dir()) && false === $uploads['error'] ) { //Get upload directory if ( 0 === strpos($file, $uploads['basedir']) ) //Check that the upload base exists in the file location $url = str_replace($uploads['basedir'], $uploads['baseurl'], $file); //replace file location with url location elseif ( false !== strpos($file, 'wp-content/uploads') ) $url = $uploads['baseurl'] . substr( $file, strpos($file, 'wp-content/uploads') + 18 ); else $url = $uploads['baseurl'] . "/$file"; //Its a newly uploaded file, therefor $file is relative to the basedir. } } if ( empty($url) ) //If any of the above options failed, Fallback on the GUID as used pre-2.7, not recommended to rely upon this. $url = get_the_guid( $post->ID ); $url = apply_filters( 'wp_get_attachment_url', $url, $post->ID ); if ( empty( $url ) ) return false; return $url; } /** * Retrieve thumbnail for an attachment. * * @since 2.1.0 * * @param int $post_id Attachment ID. * @return mixed False on failure. Thumbnail file path on success. */ function wp_get_attachment_thumb_file( $post_id = 0 ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; if ( !is_array( $imagedata = wp_get_attachment_metadata( $post->ID ) ) ) return false; $file = get_attached_file( $post->ID ); if ( !empty($imagedata['thumb']) && ($thumbfile = str_replace(basename($file), $imagedata['thumb'], $file)) && file_exists($thumbfile) ) return apply_filters( 'wp_get_attachment_thumb_file', $thumbfile, $post->ID ); return false; } /** * Retrieve URL for an attachment thumbnail. * * @since 2.1.0 * * @param int $post_id Attachment ID * @return string|bool False on failure. Thumbnail URL on success. */ function wp_get_attachment_thumb_url( $post_id = 0 ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; if ( !$url = wp_get_attachment_url( $post->ID ) ) return false; $sized = image_downsize( $post_id, 'thumbnail' ); if ( $sized ) return $sized[0]; if ( !$thumb = wp_get_attachment_thumb_file( $post->ID ) ) return false; $url = str_replace(basename($url), basename($thumb), $url); return apply_filters( 'wp_get_attachment_thumb_url', $url, $post->ID ); } /** * Check if the attachment is an image. * * @since 2.1.0 * * @param int $post_id Attachment ID * @return bool */ function wp_attachment_is_image( $post_id = 0 ) { $post_id = (int) $post_id; if ( !$post = get_post( $post_id ) ) return false; if ( !$file = get_attached_file( $post->ID ) ) return false; $ext = preg_match('/\.([^.]+)$/', $file, $matches) ? strtolower($matches[1]) : false; $image_exts = array( 'jpg', 'jpeg', 'jpe', 'gif', 'png' ); if ( 'image/' == substr($post->post_mime_type, 0, 6) || $ext && 'import' == $post->post_mime_type && in_array($ext, $image_exts) ) return true; return false; } /** * Retrieve the icon for a MIME type. * * @since 2.1.0 * * @param string|int $mime MIME type or attachment ID. * @return string|bool */ function wp_mime_type_icon( $mime = 0 ) { if ( !is_numeric($mime) ) $icon = wp_cache_get("mime_type_icon_$mime"); $post_id = 0; if ( empty($icon) ) { $post_mimes = array(); if ( is_numeric($mime) ) { $mime = (int) $mime; if ( $post = get_post( $mime ) ) { $post_id = (int) $post->ID; $ext = preg_replace('/^.+?\.([^.]+)$/', '$1', $post->guid); if ( !empty($ext) ) { $post_mimes[] = $ext; if ( $ext_type = wp_ext2type( $ext ) ) $post_mimes[] = $ext_type; } $mime = $post->post_mime_type; } else { $mime = 0; } } else { $post_mimes[] = $mime; } $icon_files = wp_cache_get('icon_files'); if ( !is_array($icon_files) ) { $icon_dir = apply_filters( 'icon_dir', ABSPATH . WPINC . '/images/crystal' ); $icon_dir_uri = apply_filters( 'icon_dir_uri', includes_url('images/crystal') ); $dirs = apply_filters( 'icon_dirs', array($icon_dir => $icon_dir_uri) ); $icon_files = array(); while ( $dirs ) { $keys = array_keys( $dirs ); $dir = array_shift( $keys ); $uri = array_shift($dirs); if ( $dh = opendir($dir) ) { while ( false !== $file = readdir($dh) ) { $file = basename($file); if ( substr($file, 0, 1) == '.' ) continue; if ( !in_array(strtolower(substr($file, -4)), array('.png', '.gif', '.jpg') ) ) { if ( is_dir("$dir/$file") ) $dirs["$dir/$file"] = "$uri/$file"; continue; } $icon_files["$dir/$file"] = "$uri/$file"; } closedir($dh); } } wp_cache_add( 'icon_files', $icon_files, 'default', 600 ); } // Icon basename - extension = MIME wildcard foreach ( $icon_files as $file => $uri ) $types[ preg_replace('/^([^.]*).*$/', '$1', basename($file)) ] =& $icon_files[$file]; if ( ! empty($mime) ) { $post_mimes[] = substr($mime, 0, strpos($mime, '/')); $post_mimes[] = substr($mime, strpos($mime, '/') + 1); $post_mimes[] = str_replace('/', '_', $mime); } $matches = wp_match_mime_types(array_keys($types), $post_mimes); $matches['default'] = array('default'); foreach ( $matches as $match => $wilds ) { if ( isset($types[$wilds[0]])) { $icon = $types[$wilds[0]]; if ( !is_numeric($mime) ) wp_cache_add("mime_type_icon_$mime", $icon); break; } } } return apply_filters( 'wp_mime_type_icon', $icon, $mime, $post_id ); // Last arg is 0 if function pass mime type. } /** * Checked for changed slugs for published post objects and save the old slug. * * The function is used when a post object of any type is updated, * by comparing the current and previous post objects. * * If the slug was changed and not already part of the old slugs then it will be * added to the post meta field ('_wp_old_slug') for storing old slugs for that * post. * * The most logically usage of this function is redirecting changed post objects, so * that those that linked to an changed post will be redirected to the new post. * * @since 2.1.0 * * @param int $post_id Post ID. * @param object $post The Post Object * @param object $post_before The Previous Post Object * @return int Same as $post_id */ function wp_check_for_changed_slugs($post_id, $post, $post_before) { // dont bother if it hasnt changed if ( $post->post_name == $post_before->post_name ) return; // we're only concerned with published, non-hierarchical objects if ( $post->post_status != 'publish' || is_post_type_hierarchical( $post->post_type ) ) return; $old_slugs = (array) get_post_meta($post_id, '_wp_old_slug'); // if we haven't added this old slug before, add it now if ( !empty( $post_before->post_name ) && !in_array($post_before->post_name, $old_slugs) ) add_post_meta($post_id, '_wp_old_slug', $post_before->post_name); // if the new slug was used previously, delete it from the list if ( in_array($post->post_name, $old_slugs) ) delete_post_meta($post_id, '_wp_old_slug', $post->post_name); } /** * Retrieve the private post SQL based on capability. * * This function provides a standardized way to appropriately select on the * post_status of a post type. The function will return a piece of SQL code * that can be added to a WHERE clause; this SQL is constructed to allow all * published posts, and all private posts to which the user has access. * * @since 2.2.0 * * @uses $user_ID * * @param string $post_type currently only supports 'post' or 'page'. * @return string SQL code that can be added to a where clause. */ function get_private_posts_cap_sql( $post_type ) { return get_posts_by_author_sql( $post_type, false ); } /** * Retrieve the post SQL based on capability, author, and type. * * @see get_private_posts_cap_sql() for full description. * * @since 3.0.0 * @param string $post_type Post type. * @param bool $full Optional. Returns a full WHERE statement instead of just an 'andalso' term. * @param int $post_author Optional. Query posts having a single author ID. * @param bool $public_only Optional. Only return public posts. Skips cap checks for $current_user. Default is false. * @return string SQL WHERE code that can be added to a query. */ function get_posts_by_author_sql( $post_type, $full = true, $post_author = null, $public_only = false ) { global $user_ID, $wpdb; // Private posts $post_type_obj = get_post_type_object( $post_type ); if ( ! $post_type_obj ) return $full ? 'WHERE 1 = 0' : ' 1 = 0 '; // This hook is deprecated. Why you'd want to use it, I dunno. if ( ! $cap = apply_filters( 'pub_priv_sql_capability', '' ) ) $cap = $post_type_obj->cap->read_private_posts; if ( $full ) { if ( null === $post_author ) { $sql = $wpdb->prepare( 'WHERE post_type = %s AND ', $post_type ); } else { $sql = $wpdb->prepare( 'WHERE post_author = %d AND post_type = %s AND ', $post_author, $post_type ); } } else { $sql = ''; } $sql .= "(post_status = 'publish'"; // Only need to check the cap if $public_only is false if ( false === $public_only ) { if ( current_user_can( $cap ) ) { // Does the user have the capability to view private posts? Guess so. $sql .= " OR post_status = 'private'"; } elseif ( is_user_logged_in() ) { // Users can view their own private posts. $id = (int) $user_ID; if ( null === $post_author || ! $full ) { $sql .= " OR post_status = 'private' AND post_author = $id"; } elseif ( $id == (int) $post_author ) { $sql .= " OR post_status = 'private'"; } // else none } // else none } $sql .= ')'; return $sql; } /** * Retrieve the date that the last post was published. * * The server timezone is the default and is the difference between GMT and * server time. The 'blog' value is the date when the last post was posted. The * 'gmt' is when the last post was posted in GMT formatted date. * * @since 0.71 * * @uses apply_filters() Calls 'get_lastpostdate' filter * * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. * @return string The date of the last post. */ function get_lastpostdate($timezone = 'server') { return apply_filters( 'get_lastpostdate', _get_last_post_time( $timezone, 'date' ), $timezone ); } /** * Retrieve last post modified date depending on timezone. * * The server timezone is the default and is the difference between GMT and * server time. The 'blog' value is just when the last post was modified. The * 'gmt' is when the last post was modified in GMT time. * * @since 1.2.0 * @uses apply_filters() Calls 'get_lastpostmodified' filter * * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. * @return string The date the post was last modified. */ function get_lastpostmodified($timezone = 'server') { $lastpostmodified = _get_last_post_time( $timezone, 'modified' ); $lastpostdate = get_lastpostdate($timezone); if ( $lastpostdate > $lastpostmodified ) $lastpostmodified = $lastpostdate; return apply_filters( 'get_lastpostmodified', $lastpostmodified, $timezone ); } /** * Retrieve latest post date data based on timezone. * * @access private * @since 3.1.0 * * @param string $timezone The location to get the time. Can be 'gmt', 'blog', or 'server'. * @param string $field Field to check. Can be 'date' or 'modified'. * @return string The date. */ function _get_last_post_time( $timezone, $field ) { global $wpdb; if ( !in_array( $field, array( 'date', 'modified' ) ) ) return false; $timezone = strtolower( $timezone ); $key = "lastpost{$field}:$timezone"; $date = wp_cache_get( $key, 'timeinfo' ); if ( !$date ) { $add_seconds_server = date('Z'); $post_types = get_post_types( array( 'public' => true ) ); array_walk( $post_types, array( &$wpdb, 'escape_by_ref' ) ); $post_types = "'" . implode( "', '", $post_types ) . "'"; switch ( $timezone ) { case 'gmt': $date = $wpdb->get_var("SELECT post_{$field}_gmt FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1"); break; case 'blog': $date = $wpdb->get_var("SELECT post_{$field} FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1"); break; case 'server': $date = $wpdb->get_var("SELECT DATE_ADD(post_{$field}_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->posts WHERE post_status = 'publish' AND post_type IN ({$post_types}) ORDER BY post_{$field}_gmt DESC LIMIT 1"); break; } if ( $date ) wp_cache_set( $key, $date, 'timeinfo' ); } return $date; } /** * Updates posts in cache. * * @package WordPress * @subpackage Cache * @since 1.5.1 * * @param array $posts Array of post objects */ function update_post_cache( &$posts ) { if ( ! $posts ) return; foreach ( $posts as $post ) wp_cache_add( $post->ID, $post, 'posts' ); } /** * Will clean the post in the cache. * * Cleaning means delete from the cache of the post. Will call to clean the term * object cache associated with the post ID. * * This function not run if $_wp_suspend_cache_invalidation is not empty. See * wp_suspend_cache_invalidation(). * * @package WordPress * @subpackage Cache * @since 2.0.0 * * @uses do_action() Calls 'clean_post_cache' on $id before adding children (if any). * * @param object|int $post The post object or ID to remove from the cache */ function clean_post_cache( $post ) { global $_wp_suspend_cache_invalidation, $wpdb; if ( ! empty( $_wp_suspend_cache_invalidation ) ) return; $post = get_post( $post ); if ( empty( $post ) ) return; wp_cache_delete( $post->ID, 'posts' ); wp_cache_delete( $post->ID, 'post_meta' ); clean_object_term_cache( $post->ID, $post->post_type ); wp_cache_delete( 'wp_get_archives', 'general' ); do_action( 'clean_post_cache', $post->ID, $post ); if ( is_post_type_hierarchical( $post->post_type ) ) wp_cache_delete( 'get_pages', 'posts' ); if ( 'page' == $post->post_type ) { wp_cache_delete( 'all_page_ids', 'posts' ); do_action( 'clean_page_cache', $post->ID ); } } /** * Call major cache updating functions for list of Post objects. * * @package WordPress * @subpackage Cache * @since 1.5.0 * * @uses $wpdb * @uses update_post_cache() * @uses update_object_term_cache() * @uses update_postmeta_cache() * * @param array $posts Array of Post objects * @param string $post_type The post type of the posts in $posts. Default is 'post'. * @param bool $update_term_cache Whether to update the term cache. Default is true. * @param bool $update_meta_cache Whether to update the meta cache. Default is true. */ function update_post_caches(&$posts, $post_type = 'post', $update_term_cache = true, $update_meta_cache = true) { // No point in doing all this work if we didn't match any posts. if ( !$posts ) return; update_post_cache($posts); $post_ids = array(); foreach ( $posts as $post ) $post_ids[] = $post->ID; if ( ! $post_type ) $post_type = 'any'; if ( $update_term_cache ) { if ( is_array($post_type) ) { $ptypes = $post_type; } elseif ( 'any' == $post_type ) { // Just use the post_types in the supplied posts. foreach ( $posts as $post ) $ptypes[] = $post->post_type; $ptypes = array_unique($ptypes); } else { $ptypes = array($post_type); } if ( ! empty($ptypes) ) update_object_term_cache($post_ids, $ptypes); } if ( $update_meta_cache ) update_postmeta_cache($post_ids); } /** * Updates metadata cache for list of post IDs. * * Performs SQL query to retrieve the metadata for the post IDs and updates the * metadata cache for the posts. Therefore, the functions, which call this * function, do not need to perform SQL queries on their own. * * @package WordPress * @subpackage Cache * @since 2.1.0 * * @uses $wpdb * * @param array $post_ids List of post IDs. * @return bool|array Returns false if there is nothing to update or an array of metadata. */ function update_postmeta_cache($post_ids) { return update_meta_cache('post', $post_ids); } /** * Will clean the attachment in the cache. * * Cleaning means delete from the cache. Optionally will clean the term * object cache associated with the attachment ID. * * This function will not run if $_wp_suspend_cache_invalidation is not empty. See * wp_suspend_cache_invalidation(). * * @package WordPress * @subpackage Cache * @since 3.0.0 * * @uses do_action() Calls 'clean_attachment_cache' on $id. * * @param int $id The attachment ID in the cache to clean * @param bool $clean_terms optional. Whether to clean terms cache */ function clean_attachment_cache($id, $clean_terms = false) { global $_wp_suspend_cache_invalidation; if ( !empty($_wp_suspend_cache_invalidation) ) return; $id = (int) $id; wp_cache_delete($id, 'posts'); wp_cache_delete($id, 'post_meta'); if ( $clean_terms ) clean_object_term_cache($id, 'attachment'); do_action('clean_attachment_cache', $id); } // // Hooks // /** * Hook for managing future post transitions to published. * * @since 2.3.0 * @access private * @uses $wpdb * @uses do_action() Calls 'private_to_published' on post ID if this is a 'private_to_published' call. * @uses wp_clear_scheduled_hook() with 'publish_future_post' and post ID. * * @param string $new_status New post status * @param string $old_status Previous post status * @param object $post Object type containing the post information */ function _transition_post_status($new_status, $old_status, $post) { global $wpdb; if ( $old_status != 'publish' && $new_status == 'publish' ) { // Reset GUID if transitioning to publish and it is empty if ( '' == get_the_guid($post->ID) ) $wpdb->update( $wpdb->posts, array( 'guid' => get_permalink( $post->ID ) ), array( 'ID' => $post->ID ) ); do_action('private_to_published', $post->ID); // Deprecated, use private_to_publish } // If published posts changed clear the lastpostmodified cache if ( 'publish' == $new_status || 'publish' == $old_status) { foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) { wp_cache_delete( "lastpostmodified:$timezone", 'timeinfo' ); wp_cache_delete( "lastpostdate:$timezone", 'timeinfo' ); } } // Always clears the hook in case the post status bounced from future to draft. wp_clear_scheduled_hook('publish_future_post', array( $post->ID ) ); } /** * Hook used to schedule publication for a post marked for the future. * * The $post properties used and must exist are 'ID' and 'post_date_gmt'. * * @since 2.3.0 * @access private * * @param int $deprecated Not used. Can be set to null. Never implemented. * Not marked as deprecated with _deprecated_argument() as it conflicts with * wp_transition_post_status() and the default filter for _future_post_hook(). * @param object $post Object type containing the post information */ function _future_post_hook( $deprecated = '', $post ) { wp_clear_scheduled_hook( 'publish_future_post', array( $post->ID ) ); wp_schedule_single_event( strtotime( get_gmt_from_date( $post->post_date ) . ' GMT') , 'publish_future_post', array( $post->ID ) ); } /** * Hook to schedule pings and enclosures when a post is published. * * @since 2.3.0 * @access private * @uses $wpdb * @uses XMLRPC_REQUEST constant. * @uses do_action() Calls 'xmlprc_publish_post' on post ID if XMLRPC_REQUEST is defined. * * @param int $post_id The ID in the database table of the post being published */ function _publish_post_hook($post_id) { global $wpdb; if ( defined('XMLRPC_REQUEST') ) do_action('xmlrpc_publish_post', $post_id); if ( defined('WP_IMPORTING') ) return; if ( get_option('default_pingback_flag') ) add_post_meta( $post_id, '_pingme', '1' ); add_post_meta( $post_id, '_encloseme', '1' ); wp_schedule_single_event(time(), 'do_pings'); } /** * Determines which fields of posts are to be saved in revisions. * * Does two things. If passed a post *array*, it will return a post array ready * to be inserted into the posts table as a post revision. Otherwise, returns * an array whose keys are the post fields to be saved for post revisions. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * @access private * @uses apply_filters() Calls '_wp_post_revision_fields' on 'title', 'content' and 'excerpt' fields. * * @param array $post Optional a post array to be processed for insertion as a post revision. * @param bool $autosave optional Is the revision an autosave? * @return array Post array ready to be inserted as a post revision or array of fields that can be versioned. */ function _wp_post_revision_fields( $post = null, $autosave = false ) { static $fields = false; if ( !$fields ) { // Allow these to be versioned $fields = array( 'post_title' => __( 'Title' ), 'post_content' => __( 'Content' ), 'post_excerpt' => __( 'Excerpt' ), ); // Runs only once $fields = apply_filters( '_wp_post_revision_fields', $fields ); // WP uses these internally either in versioning or elsewhere - they cannot be versioned foreach ( array( 'ID', 'post_name', 'post_parent', 'post_date', 'post_date_gmt', 'post_status', 'post_type', 'comment_count', 'post_author' ) as $protect ) unset( $fields[$protect] ); } if ( !is_array($post) ) return $fields; $return = array(); foreach ( array_intersect( array_keys( $post ), array_keys( $fields ) ) as $field ) $return[$field] = $post[$field]; $return['post_parent'] = $post['ID']; $return['post_status'] = 'inherit'; $return['post_type'] = 'revision'; $return['post_name'] = $autosave ? "$post[ID]-autosave" : "$post[ID]-revision"; $return['post_date'] = isset($post['post_modified']) ? $post['post_modified'] : ''; $return['post_date_gmt'] = isset($post['post_modified_gmt']) ? $post['post_modified_gmt'] : ''; return $return; } /** * Saves an already existing post as a post revision. * * Typically used immediately prior to post updates. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @uses _wp_put_post_revision() * * @param int $post_id The ID of the post to save as a revision. * @return mixed Null or 0 if error, new revision ID, if success. */ function wp_save_post_revision( $post_id ) { // We do autosaves manually with wp_create_post_autosave() if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; // WP_POST_REVISIONS = 0, false if ( ! WP_POST_REVISIONS ) return; if ( !$post = get_post( $post_id, ARRAY_A ) ) return; if ( 'auto-draft' == $post['post_status'] ) return; if ( !post_type_supports($post['post_type'], 'revisions') ) return; $return = _wp_put_post_revision( $post ); // WP_POST_REVISIONS = true (default), -1 if ( !is_numeric( WP_POST_REVISIONS ) || WP_POST_REVISIONS < 0 ) return $return; // all revisions and (possibly) one autosave $revisions = wp_get_post_revisions( $post_id, array( 'order' => 'ASC' ) ); // WP_POST_REVISIONS = (int) (# of autosaves to save) $delete = count($revisions) - WP_POST_REVISIONS; if ( $delete < 1 ) return $return; $revisions = array_slice( $revisions, 0, $delete ); for ( $i = 0; isset($revisions[$i]); $i++ ) { if ( false !== strpos( $revisions[$i]->post_name, 'autosave' ) ) continue; wp_delete_post_revision( $revisions[$i]->ID ); } return $return; } /** * Retrieve the autosaved data of the specified post. * * Returns a post object containing the information that was autosaved for the * specified post. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @param int $post_id The post ID. * @return object|bool The autosaved data or false on failure or when no autosave exists. */ function wp_get_post_autosave( $post_id ) { if ( !$post = get_post( $post_id ) ) return false; $q = array( 'name' => "{$post->ID}-autosave", 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ); // Use WP_Query so that the result gets cached $autosave_query = new WP_Query; add_action( 'parse_query', '_wp_get_post_autosave_hack' ); $autosave = $autosave_query->query( $q ); remove_action( 'parse_query', '_wp_get_post_autosave_hack' ); if ( $autosave && is_array($autosave) && is_object($autosave[0]) ) return $autosave[0]; return false; } /** * Internally used to hack WP_Query into submission. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @param object $query WP_Query object */ function _wp_get_post_autosave_hack( $query ) { $query->is_single = false; } /** * Determines if the specified post is a revision. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @param int|object $post Post ID or post object. * @return bool|int False if not a revision, ID of revision's parent otherwise. */ function wp_is_post_revision( $post ) { if ( !$post = wp_get_post_revision( $post ) ) return false; return (int) $post->post_parent; } /** * Determines if the specified post is an autosave. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @param int|object $post Post ID or post object. * @return bool|int False if not a revision, ID of autosave's parent otherwise */ function wp_is_post_autosave( $post ) { if ( !$post = wp_get_post_revision( $post ) ) return false; if ( "{$post->post_parent}-autosave" !== $post->post_name ) return false; return (int) $post->post_parent; } /** * Inserts post data into the posts table as a post revision. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @uses wp_insert_post() * * @param int|object|array $post Post ID, post object OR post array. * @param bool $autosave Optional. Is the revision an autosave? * @return mixed Null or 0 if error, new revision ID if success. */ function _wp_put_post_revision( $post = null, $autosave = false ) { if ( is_object($post) ) $post = get_object_vars( $post ); elseif ( !is_array($post) ) $post = get_post($post, ARRAY_A); if ( !$post || empty($post['ID']) ) return; if ( isset($post['post_type']) && 'revision' == $post['post_type'] ) return new WP_Error( 'post_type', __( 'Cannot create a revision of a revision' ) ); $post = _wp_post_revision_fields( $post, $autosave ); $post = add_magic_quotes($post); //since data is from db $revision_id = wp_insert_post( $post ); if ( is_wp_error($revision_id) ) return $revision_id; if ( $revision_id ) do_action( '_wp_put_post_revision', $revision_id ); return $revision_id; } /** * Gets a post revision. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @uses get_post() * * @param int|object $post Post ID or post object * @param string $output Optional. OBJECT, ARRAY_A, or ARRAY_N. * @param string $filter Optional sanitation filter. @see sanitize_post() * @return mixed Null if error or post object if success */ function wp_get_post_revision(&$post, $output = OBJECT, $filter = 'raw') { $null = null; if ( !$revision = get_post( $post, OBJECT, $filter ) ) return $revision; if ( 'revision' !== $revision->post_type ) return $null; if ( $output == OBJECT ) { return $revision; } elseif ( $output == ARRAY_A ) { $_revision = get_object_vars($revision); return $_revision; } elseif ( $output == ARRAY_N ) { $_revision = array_values(get_object_vars($revision)); return $_revision; } return $revision; } /** * Restores a post to the specified revision. * * Can restore a past revision using all fields of the post revision, or only selected fields. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @uses wp_get_post_revision() * @uses wp_update_post() * @uses do_action() Calls 'wp_restore_post_revision' on post ID and revision ID if wp_update_post() * is successful. * * @param int|object $revision_id Revision ID or revision object. * @param array $fields Optional. What fields to restore from. Defaults to all. * @return mixed Null if error, false if no fields to restore, (int) post ID if success. */ function wp_restore_post_revision( $revision_id, $fields = null ) { if ( !$revision = wp_get_post_revision( $revision_id, ARRAY_A ) ) return $revision; if ( !is_array( $fields ) ) $fields = array_keys( _wp_post_revision_fields() ); $update = array(); foreach( array_intersect( array_keys( $revision ), $fields ) as $field ) $update[$field] = $revision[$field]; if ( !$update ) return false; $update['ID'] = $revision['post_parent']; $update = add_magic_quotes( $update ); //since data is from db $post_id = wp_update_post( $update ); if ( is_wp_error( $post_id ) ) return $post_id; if ( $post_id ) do_action( 'wp_restore_post_revision', $post_id, $revision['ID'] ); return $post_id; } /** * Deletes a revision. * * Deletes the row from the posts table corresponding to the specified revision. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @uses wp_get_post_revision() * @uses wp_delete_post() * * @param int|object $revision_id Revision ID or revision object. * @return mixed Null or WP_Error if error, deleted post if success. */ function wp_delete_post_revision( $revision_id ) { if ( !$revision = wp_get_post_revision( $revision_id ) ) return $revision; $delete = wp_delete_post( $revision->ID ); if ( is_wp_error( $delete ) ) return $delete; if ( $delete ) do_action( 'wp_delete_post_revision', $revision->ID, $revision ); return $delete; } /** * Returns all revisions of specified post. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @uses get_children() * * @param int|object $post_id Post ID or post object * @return array empty if no revisions */ function wp_get_post_revisions( $post_id = 0, $args = null ) { if ( ! WP_POST_REVISIONS ) return array(); if ( ( !$post = get_post( $post_id ) ) || empty( $post->ID ) ) return array(); $defaults = array( 'order' => 'DESC', 'orderby' => 'date' ); $args = wp_parse_args( $args, $defaults ); $args = array_merge( $args, array( 'post_parent' => $post->ID, 'post_type' => 'revision', 'post_status' => 'inherit' ) ); if ( !$revisions = get_children( $args ) ) return array(); return $revisions; } function _set_preview($post) { if ( ! is_object($post) ) return $post; $preview = wp_get_post_autosave($post->ID); if ( ! is_object($preview) ) return $post; $preview = sanitize_post($preview); $post->post_content = $preview->post_content; $post->post_title = $preview->post_title; $post->post_excerpt = $preview->post_excerpt; return $post; } function _show_post_preview() { if ( isset($_GET['preview_id']) && isset($_GET['preview_nonce']) ) { $id = (int) $_GET['preview_id']; if ( false == wp_verify_nonce( $_GET['preview_nonce'], 'post_preview_' . $id ) ) wp_die( __('You do not have permission to preview drafts.') ); add_filter('the_preview', '_set_preview'); } } /** * Returns the post's parent's post_ID * * @since 3.1.0 * * @param int $post_id * * @return int|bool false on error */ function wp_get_post_parent_id( $post_ID ) { $post = get_post( $post_ID ); if ( !$post || is_wp_error( $post ) ) return false; return (int) $post->post_parent; } /** * Checks the given subset of the post hierarchy for hierarchy loops. * Prevents loops from forming and breaks those that it finds. * * Attached to the wp_insert_post_parent filter. * * @since 3.1.0 * @uses wp_find_hierarchy_loop() * * @param int $post_parent ID of the parent for the post we're checking. * @param int $post_ID ID of the post we're checking. * * @return int The new post_parent for the post. */ function wp_check_post_hierarchy_for_loops( $post_parent, $post_ID ) { // Nothing fancy here - bail if ( !$post_parent ) return 0; // New post can't cause a loop if ( empty( $post_ID ) ) return $post_parent; // Can't be its own parent if ( $post_parent == $post_ID ) return 0; // Now look for larger loops if ( !$loop = wp_find_hierarchy_loop( 'wp_get_post_parent_id', $post_ID, $post_parent ) ) return $post_parent; // No loop // Setting $post_parent to the given value causes a loop if ( isset( $loop[$post_ID] ) ) return 0; // There's a loop, but it doesn't contain $post_ID. Break the loop. foreach ( array_keys( $loop ) as $loop_member ) wp_update_post( array( 'ID' => $loop_member, 'post_parent' => 0 ) ); return $post_parent; } /** * Returns an array of post format slugs to their translated and pretty display versions * * @since 3.1.0 * * @return array The array of translations */ function get_post_format_strings() { $strings = array( 'standard' => _x( 'Standard', 'Post format' ), // Special case. any value that evals to false will be considered standard 'aside' => _x( 'Aside', 'Post format' ), 'chat' => _x( 'Chat', 'Post format' ), 'gallery' => _x( 'Gallery', 'Post format' ), 'link' => _x( 'Link', 'Post format' ), 'image' => _x( 'Image', 'Post format' ), 'quote' => _x( 'Quote', 'Post format' ), 'status' => _x( 'Status', 'Post format' ), 'video' => _x( 'Video', 'Post format' ), 'audio' => _x( 'Audio', 'Post format' ), ); return $strings; } /** * Retrieves an array of post format slugs. * * @since 3.1.0 * * @return array The array of post format slugs. */ function get_post_format_slugs() { $slugs = array_keys( get_post_format_strings() ); return array_combine( $slugs, $slugs ); } /** * Returns a pretty, translated version of a post format slug * * @since 3.1.0 * * @param string $slug A post format slug * @return string The translated post format name */ function get_post_format_string( $slug ) { $strings = get_post_format_strings(); if ( !$slug ) return $strings['standard']; else return ( isset( $strings[$slug] ) ) ? $strings[$slug] : ''; } /** * Sets a post thumbnail. * * @since 3.1.0 * * @param int|object $post Post ID or object where thumbnail should be attached. * @param int $thumbnail_id Thumbnail to attach. * @return bool True on success, false on failure. */ function set_post_thumbnail( $post, $thumbnail_id ) { $post = get_post( $post ); $thumbnail_id = absint( $thumbnail_id ); if ( $post && $thumbnail_id && get_post( $thumbnail_id ) ) { if ( $thumbnail_html = wp_get_attachment_image( $thumbnail_id, 'thumbnail' ) ) return update_post_meta( $post->ID, '_thumbnail_id', $thumbnail_id ); else return delete_post_meta( $post->ID, '_thumbnail_id' ); } return false; } /** * Removes a post thumbnail. * * @since 3.3.0 * * @param int|object $post Post ID or object where thumbnail should be removed from. * @return bool True on success, false on failure. */ function delete_post_thumbnail( $post ) { $post = get_post( $post ); if ( $post ) return delete_post_meta( $post->ID, '_thumbnail_id' ); return false; } /** * Returns a link to a post format index. * * @since 3.1.0 * * @param string $format Post format * @return string Link */ function get_post_format_link( $format ) { $term = get_term_by('slug', 'post-format-' . $format, 'post_format' ); if ( ! $term || is_wp_error( $term ) ) return false; return get_term_link( $term ); } /** * Deletes auto-drafts for new posts that are > 7 days old * * @since 3.4.0 */ function wp_delete_auto_drafts() { global $wpdb; // Cleanup old auto-drafts more than 7 days old $old_posts = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'auto-draft' AND DATE_SUB( NOW(), INTERVAL 7 DAY ) > post_date" ); foreach ( (array) $old_posts as $delete ) wp_delete_post( $delete, true ); // Force delete } /** * Filters the request to allow for the format prefix. * * @access private * @since 3.1.0 */ function _post_format_request( $qvs ) { if ( ! isset( $qvs['post_format'] ) ) return $qvs; $slugs = get_post_format_slugs(); if ( isset( $slugs[ $qvs['post_format'] ] ) ) $qvs['post_format'] = 'post-format-' . $slugs[ $qvs['post_format'] ]; $tax = get_taxonomy( 'post_format' ); if ( ! is_admin() ) $qvs['post_type'] = $tax->object_type; return $qvs; } add_filter( 'request', '_post_format_request' ); /** * Filters the post format term link to remove the format prefix. * * @access private * @since 3.1.0 */ function _post_format_link( $link, $term, $taxonomy ) { global $wp_rewrite; if ( 'post_format' != $taxonomy ) return $link; if ( $wp_rewrite->get_extra_permastruct( $taxonomy ) ) { return str_replace( "/{$term->slug}", '/' . str_replace( 'post-format-', '', $term->slug ), $link ); } else { $link = remove_query_arg( 'post_format', $link ); return add_query_arg( 'post_format', str_replace( 'post-format-', '', $term->slug ), $link ); } } add_filter( 'term_link', '_post_format_link', 10, 3 ); /** * Remove the post format prefix from the name property of the term object created by get_term(). * * @access private * @since 3.1.0 */ function _post_format_get_term( $term ) { if ( isset( $term->slug ) ) { $term->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) ); } return $term; } add_filter( 'get_post_format', '_post_format_get_term' ); /** * Remove the post format prefix from the name property of the term objects created by get_terms(). * * @access private * @since 3.1.0 */ function _post_format_get_terms( $terms, $taxonomies, $args ) { if ( in_array( 'post_format', (array) $taxonomies ) ) { if ( isset( $args['fields'] ) && 'names' == $args['fields'] ) { foreach( $terms as $order => $name ) { $terms[$order] = get_post_format_string( str_replace( 'post-format-', '', $name ) ); } } else { foreach ( (array) $terms as $order => $term ) { if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) { $terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) ); } } } } return $terms; } add_filter( 'get_terms', '_post_format_get_terms', 10, 3 ); /** * Remove the post format prefix from the name property of the term objects created by wp_get_object_terms(). * * @access private * @since 3.1.0 */ function _post_format_wp_get_object_terms( $terms ) { foreach ( (array) $terms as $order => $term ) { if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) { $terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) ); } } return $terms; } add_filter( 'wp_get_object_terms', '_post_format_wp_get_object_terms' ); /** * Update the custom taxonomies' term counts when a post's status is changed. For example, default posts term counts (for custom taxonomies) don't include private / draft posts. * * @access private * @param string $new_status * @param string $old_status * @param object $post * @since 3.3.0 */ function _update_term_count_on_transition_post_status( $new_status, $old_status, $post ) { // Update counts for the post's terms. foreach ( (array) get_object_taxonomies( $post->post_type ) as $taxonomy ) { $tt_ids = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'tt_ids' ) ); wp_update_term_count( $tt_ids, $taxonomy ); } } /** * Adds any posts from the given ids to the cache that do not already exist in cache * * @since 3.4.0 * * @access private * * @param array $post_ids ID list * @param bool $update_term_cache Whether to update the term cache. Default is true. * @param bool $update_meta_cache Whether to update the meta cache. Default is true. */ function _prime_post_caches( $ids, $update_term_cache = true, $update_meta_cache = true ) { global $wpdb; $non_cached_ids = _get_non_cached_ids( $ids, 'posts' ); if ( !empty( $non_cached_ids ) ) { $fresh_posts = $wpdb->get_results( sprintf( "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE ID IN (%s)", join( ",", $non_cached_ids ) ) ); update_post_caches( $fresh_posts, 'any', $update_term_cache, $update_meta_cache ); } }
zyblog
trunk/zyblog/wp-includes/post.php
PHP
asf20
177,007
/* * jQuery UI CSS Framework @VERSION * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Theming/API */ /* Layout helpers ----------------------------------*/ .ui-helper-hidden { display: none; } .ui-helper-hidden-accessible { position: absolute; left: -99999999px; } .ui-helper-reset { margin: 0; padding: 0; border: 0; outline: 0; line-height: 1.3; text-decoration: none; font-size: 100%; list-style: none; } .ui-helper-clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; } .ui-helper-clearfix { display: inline-block; } /* required comment for clearfix to work in Opera \*/ * html .ui-helper-clearfix { height:1%; } .ui-helper-clearfix { display:block; } /* end clearfix */ .ui-helper-zfix { width: 100%; height: 100%; top: 0; left: 0; position: absolute; opacity: 0; filter:Alpha(Opacity=0); } /* Interaction Cues ----------------------------------*/ .ui-state-disabled { cursor: default !important; } /* Icons ----------------------------------*/ /* states and images */ .ui-icon { display: block; text-indent: -99999px; overflow: hidden; background-repeat: no-repeat; } /* Misc visuals ----------------------------------*/ /* Overlays */ .ui-widget-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } /* * jQuery UI Resizable * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Resizable#theming */ .ui-resizable { position: relative;} .ui-resizable-handle { position: absolute;font-size: 0.1px;z-index: 99999; display: block;} .ui-resizable-disabled .ui-resizable-handle, .ui-resizable-autohide .ui-resizable-handle { display: none; } .ui-resizable-n { cursor: n-resize; height: 7px; width: 100%; top: -5px; left: 0; } .ui-resizable-s { cursor: s-resize; height: 7px; width: 100%; bottom: -5px; left: 0; } .ui-resizable-e { cursor: e-resize; width: 7px; right: -5px; top: 0; height: 100%; } .ui-resizable-w { cursor: w-resize; width: 7px; left: -5px; top: 0; height: 100%; } .ui-resizable-se { cursor: se-resize; width: 12px; height: 12px; right: 1px; bottom: 1px; } .ui-resizable-sw { cursor: sw-resize; width: 9px; height: 9px; left: -5px; bottom: -5px; } .ui-resizable-nw { cursor: nw-resize; width: 9px; height: 9px; left: -5px; top: -5px; } .ui-resizable-ne { cursor: ne-resize; width: 9px; height: 9px; right: -5px; top: -5px;} /* * jQuery UI Dialog * * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Dialog#theming */ .wp-dialog { position: absolute; width: 300px; overflow: hidden; } .wp-dialog .ui-dialog-titlebar { position: relative; } .wp-dialog .ui-dialog-titlebar-close span { display: block; margin: 1px; } .wp-dialog .ui-dialog-content { position: relative; border: 0; padding: 0; background: none; overflow: auto; zoom: 1; } .wp-dialog .ui-dialog-buttonpane { text-align: left; border-width: 1px 0 0 0; background-image: none; margin: .5em 0 0 0; padding: .3em 1em .5em .4em; } .wp-dialog .ui-dialog-buttonpane .ui-dialog-buttonset { float: right; } .wp-dialog .ui-dialog-buttonpane button { margin: .5em .4em .5em 0; cursor: pointer; } .wp-dialog .ui-resizable-se { width: 14px; height: 14px; right: 3px; bottom: 3px; } .ui-draggable .ui-dialog-titlebar { cursor: move; } /* WP jQuery Dialog Theme */ .wp-dialog { border: 1px solid #999; -webkit-box-shadow: 0px 0px 16px rgba( 0,0,0,0.3 ); box-shadow: 0px 0px 16px rgba( 0,0,0,0.3 ); } .wp-dialog .ui-dialog-title { display: block; text-align: center; padding: 1px 0 2px; } .wp-dialog .ui-dialog-titlebar { padding: 0 1em; background-color: #444; font-weight: bold; font-size: 11px; line-height: 18px; color: #e5e5e5; } .wp-dialog { background-color: #f5f5f5; -webkit-border-top-left-radius: 4px; border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; border-top-right-radius: 4px; } .wp-dialog .ui-dialog-titlebar { -webkit-border-top-left-radius: 3px; border-top-left-radius: 3px; -webkit-border-top-right-radius: 3px; border-top-right-radius: 3px; } .wp-dialog .ui-dialog-titlebar-close { position: absolute; width: 29px; height: 16px; top: 2px; right: 6px; background: url('../js/tinymce/plugins/inlinepopups/skins/clearlooks2/img/buttons.gif') no-repeat -87px -16px; padding: 0; } .wp-dialog .ui-dialog-titlebar-close:hover, .wp-dialog .ui-dialog-titlebar-close:focus { background-position: -87px -32px; } .ui-widget-overlay { background-color: #000; opacity: 0.6; filter: alpha(opacity=60); }
zyblog
trunk/zyblog/wp-includes/css/jquery-ui-dialog.css
CSS
asf20
4,795
/** * Modal */ .media-modal-close { right: auto; left: 7px; } /** * Toolbar */ .media-toolbar-primary { float: left; } .media-toolbar-secondary { float: right; } .media-toolbar-primary > .media-button, .media-toolbar-primary > .media-button-group { margin-left: 0; margin-right: 10px; float: right; } .media-toolbar-secondary > .media-button, .media-toolbar-secondary > .media-button-group { margin-right: 0; margin-left: 10px; float: right; } /** * Sidebar */ .media-sidebar { right: auto; left: 0; border-left: 0; border-right: 1px solid #dfdfdf; } .media-sidebar .setting { float: right; } .media-sidebar .setting span { margin-right: 0; margin-left: 4%; } .media-sidebar .setting span, .compat-item label span { float: right; text-align: left; } .media-sidebar .setting input, .media-sidebar .setting textarea { float: left; } .compat-item { float: right; } .compat-item .label { margin-right: 0; margin-left: 4%; float: right; text-align: left; } .compat-item .field { float: left; padding-right: 0; padding-left: 1px; } /** * Menu */ .media-menu { border-right: 0; border-left: 1px solid #d9d9d9; box-shadow: inset 6px 0 6px -6px rgba( 0, 0, 0, 0.2 ) } /** * Router */ .media-router > a { float: right; border-right: 0; border-left: 1px solid #dfdfdf; } .media-router > a:last-child { border-left: 0; } /** * Frame */ .media-frame-menu { left: auto; right: 0; } .media-frame-title, .media-frame-router, .media-frame-content, .media-frame-toolbar { left: 0; right: 200px; } .media-frame.hide-menu .media-frame-title, .media-frame.hide-menu .media-frame-router, .media-frame.hide-menu .media-frame-toolbar, .media-frame.hide-menu .media-frame-content { right: 0; } .media-frame.hide-menu .media-frame-menu { left: auto; right: -200px; } /** * Attachment Browser Filters */ .media-frame select.attachment-filters { margin-right: 0; margin-left: 10px; } /** * Search */ .media-toolbar-secondary .search { margin-right: 0; margin-left: 16px; } /** * Attachments */ .attachments { padding-right: 0; padding-left: 16px; } /** * Attachment */ .attachment { float: right; } .attachment .thumbnail { left: auto; right: 0; } .attachment .close { right: auto; left: 5px; } .attachment .check { right: auto; left: -7px; } /** * Attachments Browser */ .attachments-browser .media-toolbar { right: 0; left: 300px; } .attachments-browser .attachments, .attachments-browser .uploader-inline { right: 0; left: 300px; } /** * Progress Bar */ .attachment-preview .media-progress-bar { left: auto; right: 15%; } .media-sidebar .media-uploader-status .upload-dismiss-errors { right: auto; left: 0; } .upload-errors .upload-error-label { margin-right: 0; margin-left: 8px; float: right; margin-top: -3px; } /** * Selection */ .media-selection { right: 0; left: 350px; padding: 0 16px 0 0; } .media-selection .selection-info { margin-right: 0; margin-left: 10px; } .media-selection .selection-info a { float: right; border-right: 0; border-left: 1px solid #dfdfdf; margin: 1px -8px 1px 8px; } .media-selection .selection-info a:last-child { border-right: 1px; border-left: 0; margin-left: 0; margin-right: -8px; } .media-selection:after { right: auto; left: 0; background-image: -webkit-gradient(linear, left top, right top, from( rgba( 255, 255, 255, 1 ) ), to( rgba( 255, 255, 255, 0 ) )); background-image: -webkit-linear-gradient(left, rgba( 255, 255, 255, 1 ) , rgba( 255, 255, 255, 0 ) ); background-image: -moz-linear-gradient(left, rgba( 255, 255, 255, 1 ) , rgba( 255, 255, 255, 0 ) ); background-image: -o-linear-gradient(left, rgba( 255, 255, 255, 1 ) , rgba( 255, 255, 255, 0 ) ); background-image: linear-gradient(to right, rgba( 255, 255, 255, 1 ) , rgba( 255, 255, 255, 0 ) ); } /** * Attachment Details */ .attachment-info .thumbnail { float: right; margin-right: 0; margin-left: 10px; } .attachment-info .details { float: right; } /** * Attachment Display Settings */ .attachment-display-settings { float: right; } /** * Embed from URL */ .embed-url span { display: block; padding: 4px 2px 6px 0; } .media-embed .thumbnail { float: right; } .media-embed .setting { float: right; } /** * Responsive layout */ @media only screen and (max-width: 900px) { .media-frame-title, .media-frame-router, .media-frame-content, .media-frame-toolbar { left: 0; right: 140px; } .attachments-browser .attachments, .attachments-browser .uploader-inline, .attachments-browser .media-toolbar { right: 0; left: 180px; } }
zyblog
trunk/zyblog/wp-includes/css/media-views-rtl.css
CSS
asf20
4,606
/** * Base Styles */ .media-modal, .media-frame { font-family: sans-serif; font-size: 12px; } .media-frame input, .media-frame textarea { padding: 6px 8px; line-height: 16px; } .media-frame select, .wp-admin .media-frame select { line-height: 28px; margin-top: 3px; } .media-frame a { border-bottom: none; color: #21759b; } .media-frame a:hover { color: #d54e21; } .media-frame a.button { color: #333; } .media-frame a.button:hover { color: #222; } .media-frame a.button-primary, .media-frame a.button-primary:hover { color: #fff; } .media-frame input[type="text"], .media-frame input[type="password"], .media-frame input[type="number"], .media-frame input[type="search"], .media-frame input[type="email"], .media-frame input[type="url"], .media-frame textarea, .media-frame select { font-family: sans-serif; font-size: 12px; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; -ms-box-sizing: border-box; /* ie8 only */ box-sizing: border-box; -webkit-border-radius: 3px; border-radius: 3px; border-width: 1px; border-style: solid; border-color: #dfdfdf; } .media-frame select { height: 24px; padding: 2px; } .media-frame input:disabled, .media-frame textarea:disabled, .media-frame input[readonly], .media-frame textarea[readonly] { background-color: #eee; } .media-frame input[type="search"] { -webkit-appearance: textfield; } .media-frame :-moz-placeholder { color: #a9a9a9; } /* Enable draggable on IE10 touch events until it's rolled into jQuery UI core */ .ui-sortable, .ui-draggable { -ms-touch-action: none; } /** * Modal */ .media-modal { position: fixed; top: 30px; left: 30px; right: 30px; bottom: 30px; z-index: 160000; } .media-modal-backdrop { position: fixed; top: 0; left: 0; right: 0; bottom: 0; min-height: 360px; background: #000; opacity: 0.7; z-index: 159900; } .media-modal-close { position: absolute; top: 7px; right: 7px; width: 30px; height: 30px; z-index: 1000; } .media-modal-close span { display: block; margin: 8px auto 0; width: 15px; height: 15px; background-position: -100px 0; } .media-modal-close:active { outline: 0; } .media-modal-content { position: absolute; top: 0; left: 0; right: 0; bottom: 0; overflow: auto; min-height: 300px; background: #fff; } .media-modal-icon { background-image: url(../images/uploader-icons.png); background-repeat: no-repeat; } /** * Toolbar */ .media-toolbar { position: absolute; top: 0; left: 0; right: 0; z-index: 100; height: 60px; padding: 0 16px; border: 0 solid #dfdfdf; overflow: hidden; } .media-toolbar-primary { float: right; height: 100%; } .media-toolbar-secondary { float: left; height: 100%; } .media-toolbar-primary > .media-button, .media-toolbar-primary > .media-button-group { margin-left: 10px; float: left; margin-top: 15px; } .media-toolbar-secondary > .media-button, .media-toolbar-secondary > .media-button-group { margin-right: 10px; float: left; margin-top: 15px; } /** * Sidebar */ .media-sidebar { position: absolute; top: 0; right: 0; bottom: 0; width: 267px; padding: 0 16px 24px; z-index: 75; background: #f5f5f5; border-left: 1px solid #dfdfdf; overflow: auto; -webkit-overflow-scrolling: touch; } .hide-toolbar .media-sidebar { bottom: 0; } .media-sidebar .sidebar-title { font-weight: 200; font-size: 20px; margin: 0; padding: 12px 10px 10px; line-height: 28px; } .media-sidebar .sidebar-content { padding: 0 10px; margin-bottom: 130px; } .media-sidebar .search { display: block; width: 100%; } .media-sidebar h3 { position: relative; font-weight: bold; text-transform: uppercase; font-size: 12px; color: #777; text-shadow: 0 1px 0 #fff; margin: 24px 0 8px; } .media-sidebar .setting { display: block; float: left; width: 100%; margin: 1px 0; } .media-sidebar .setting label { display: block; } .media-sidebar .setting .link-to-custom { margin: 3px 0; } .media-sidebar .setting span { min-width: 30%; margin-right: 4%; font-size: 12px; } .media-sidebar .setting select { max-width: 65%; } .media-sidebar .setting input[type="checkbox"] { width: auto; float: none; margin-top: 8px; padding: 0; } .media-sidebar .setting span, .compat-item label span { float: left; min-height: 22px; padding-top: 8px; line-height: 16px; text-align: right; font-weight: normal; color: #999; text-shadow: 0 1px 0 #fff; } .media-sidebar .setting input, .media-sidebar .setting textarea { width: 65%; float: right; } .media-sidebar .setting textarea, .compat-item .field textarea { height: 62px; resize: vertical; } .media-sidebar select { margin-top: 3px; } .compat-item { float: left; width: 100%; overflow: hidden; } .compat-item table { width: 100%; table-layout: fixed; border-spacing: 0; border: 0; } .compat-item tr { padding: 2px 0; display: block; overflow: hidden; } .compat-item .label, .compat-item .field { display: block; margin: 0; padding: 0; } .compat-item .label { min-width: 30%; margin-right: 4%; float: left; text-align: right; } .compat-item .label span { display: block; width: 100%; } .compat-item .field { float: right; width: 65%; padding-right: 1px; } .compat-item .field input { width: 100%; margin: 0; } /** * Menu */ .media-menu { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: 0; padding: 16px 0; border-right: 1px solid #d9d9d9; box-shadow: inset -6px 0 6px -6px rgba( 0, 0, 0, 0.2 ); -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .media-menu > a { display: block; position: relative; padding: 4px 20px; margin: 0; line-height: 18px; font-size: 14px; color: #21759B; text-shadow: 0 1px 0 #fff; text-decoration: none; } .media-menu > a:hover { color: #21759B; background: rgba( 0, 0, 0, 0.04 ); } .media-menu > a:active { outline: none; } .media-menu .active, .media-menu .active:hover { color: #333; font-weight: bold; } .media-menu .separator { height: 0; margin: 12px 20px; padding: 0; border-top: 1px solid #dfdfdf; border-bottom: 1px solid #fff; } /** * Menu */ .media-router { position: relative; padding: 0 6px; margin: 0; clear: both; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .media-router > a { position: relative; float: left; padding: 2px 10px; margin: 0; height: 18px; line-height: 18px; font-size: 14px; border-right: 1px solid #dfdfdf; text-shadow: 0 1px 0 #fff; text-decoration: none; } .media-router > a:last-child { border-right: 0; } .media-router > a:active, .media-router > a:focus { outline: none; } .media-router .active, .media-router .active:hover { color: #333; } .media-router .active:after { content: ''; display: block; margin: -100px auto 0; width: 7px; height: 7px; background: #fff; box-shadow: 1px 1px 1px rgba( 0, 0, 0, 0.2 ); z-index: 300; -webkit-transform: rotate( 45deg ) translate( 75px, 75px ); -moz-transform: rotate( 45deg ) translate( 75px, 75px ); -ms-transform: rotate( 45deg ) translate( 75px, 75px ); -o-transform: rotate( 45deg ) translate( 75px, 75px ); transform: rotate( 45deg ) translate( 75px, 75px ); } /** * Frame */ .media-frame { overflow: hidden; position: absolute; top: 0; left: 0; right: 0; bottom: 0; } .media-frame-menu { position: absolute; top: 0; left: 0; bottom: 0; width: 199px; z-index: 150; } .media-frame-title { position: absolute; top: 0; left: 200px; right: 0; height: 45px; z-index: 200; } .media-frame-router { position: absolute; top: 45px; left: 200px; right: 0; height: 30px; z-index: 200; border-bottom: 1px solid #dfdfdf; box-shadow: 0 4px 4px -4px rgba( 0, 0, 0, 0.1 ); } .media-frame-content { position: absolute; top: 75px; left: 200px; right: 0; bottom: 61px; height: auto; width: auto; margin: 0; overflow: auto; } .media-frame-toolbar { position: absolute; left: 200px; right: 0; bottom: 0; height: 60px; z-index: 100; border: 0 solid #dfdfdf; border-width: 1px 0 0 0; box-shadow: 0 -4px 4px -4px rgba( 0, 0, 0, 0.1 ); } .media-frame.hide-menu .media-frame-title, .media-frame.hide-menu .media-frame-router, .media-frame.hide-menu .media-frame-toolbar, .media-frame.hide-menu .media-frame-content { left: 0; } .media-frame.hide-menu .media-frame-menu { left: -200px; } .media-frame.hide-toolbar .media-frame-content { bottom: 0; } .media-frame.hide-toolbar .media-frame-toolbar { bottom: -61px; } .media-frame.hide-router .media-frame-content { top: 45px; } .media-frame.hide-router .media-frame-router { display: none; } .media-frame.hide-router .media-frame-title { border-bottom: 1px solid #dfdfdf; box-shadow: 0 4px 4px -4px rgba( 0, 0, 0, 0.1 ); } .media-frame .media-toolbar .add-to-gallery { display: none; } .media-frame-title h1 { padding: 0 16px; font-size: 22px; font-weight: 200; line-height: 45px; margin: 0; } /** * Iframes */ .media-frame .media-iframe { overflow: hidden; } .media-frame .media-iframe, .media-frame .media-iframe iframe { height: 100%; width: 100%; border: 0; } /** * Attachment Browser Filters */ .media-frame select.attachment-filters { margin-top: 11px; margin-right: 10px; } /** * Search */ .media-frame .search { margin-top: 11px; padding: 4px; line-height: 18px; font-size: 13px; color: #464646; font-family: sans-serif; -webkit-appearance: none; } .media-toolbar-secondary .search { margin-right: 16px; } /** * Attachments */ .attachments { margin: 0; padding-right: 16px; -webkit-overflow-scrolling: touch; } /** * Attachment */ .attachment { position: relative; float: left; padding: 0; margin: 0 10px 20px; color: #464646; list-style: none; text-align: center; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none; } .selected.attachment { box-shadow: 0 0 0 1px #fff, 0 0 0 3px #ccc; } .details.attachment { box-shadow: 0 0 0 1px #fff, 0 0 0 5px #1e8cbe; } .attachment-preview { position: relative; width: 199px; height: 199px; box-shadow: inset 0 0 15px rgba( 0, 0, 0, 0.1 ), inset 0 0 0 1px rgba( 0, 0, 0, 0.05 ); background: #eee; cursor: pointer; } .attachment .icon { margin: 0 auto; overflow: hidden; padding-top: 20%; } .attachment .thumbnail { display: block; position: absolute; top: 0; left: 0; margin: 0 auto; overflow: hidden; max-width: 100%; max-height: 100%; } .attachment-preview .thumbnail:after { content: ''; display: block; position: absolute; top: 0; left: 0; right: 0; bottom: 0; box-shadow: inset 0 0 0 1px rgba( 0, 0, 0, 0.1 ); overflow: hidden; } .attachment .thumbnail img { top: 0; left: 0; } .attachment .thumbnail .centered { position: absolute; top: 0; left: 0; width: 100%; height: 100%; -webkit-transform: translate( 50%, 50% ); -moz-transform: translate( 50%, 50% ); -ms-transform: translate( 50%, 50% ); -o-transform: translate( 50%, 50% ); transform: translate( 50%, 50% ); } .attachment .thumbnail .centered img { -webkit-transform: translate( -50%, -50% ); -moz-transform: translate( -50%, -50% ); -ms-transform: translate( -50%, -50% ); -o-transform: translate( -50%, -50% ); transform: translate( -50%, -50% ); } .attachment .filename { position: absolute; left: 0; right: 0; bottom: 0; overflow: hidden; max-height: 100%; word-wrap: break-word; text-align: center; font-weight: bold; background: rgba( 255, 255, 255, 0.8 ); box-shadow: inset 0 0 0 1px rgba( 0, 0, 0, 0.15 ); } .attachment .filename div { padding: 5px 10px; } .attachment-preview .thumbnail { width: 199px; height: 199px; } .attachment .thumbnail img { position: absolute; } .attachment .close { display: none; position: absolute; top: 5px; right: 5px; height: 22px; width: 22px; padding: 0; font-size: 20px; line-height: 20px; text-align: center; text-decoration: none; color: #464646; background-color: #fff; background-position: -96px 4px; border-width: 0; border-radius: 3px; box-shadow: 0 0 0 1px rgba( 0, 0, 0, 0.3 ); } .attachment .close:hover { box-shadow: 0 0 0 1px rgba( 0, 0, 0, 0.6 ); } .attachment:hover .close { display: block; } .attachment .check { display: none; height: 24px; width: 24px; position: absolute; top: -7px; right: -7px; outline: none; border: 1px solid #fff; border-radius: 3px; box-shadow: 0 0 0 1px rgba( 0, 0, 0, 0.4 ); background: #f1f1f1; background-image: -webkit-gradient(linear, left top, left bottom, from(#f1f1f1), to(#e1e1e1)); background-image: -webkit-linear-gradient(top, #f1f1f1, #e1e1e1); background-image: -moz-linear-gradient(top, #f1f1f1, #e1e1e1); background-image: -o-linear-gradient(top, #f1f1f1, #e1e1e1); background-image: linear-gradient(to bottom, #f1f1f1, #e1e1e1); } .attachment .check div { background-position: -1px 0; height: 15px; width: 15px; margin: 5px; } .attachment .check:hover div { background-position: -40px 0; } .attachment.selected .check { display: block; } .attachment.details .check { box-shadow: 0 0 0 1px #1e8cbe; background: #1e8cbe; background-image: -webkit-gradient(linear, left top, left bottom, from(#1e8cbe), to(#0074a2)); background-image: -webkit-linear-gradient(top, #1e8cbe, #0074a2); background-image: -moz-linear-gradient(top, #1e8cbe, #0074a2); background-image: -o-linear-gradient(top, #1e8cbe, #0074a2); background-image: linear-gradient(to bottom, #1e8cbe, #0074a2); } .attachment.details .check div { background-position: -21px 0; } .attachment.details .check:hover div { background-position: -60px 0; } .media-frame .attachment .describe { position: relative; display: block; width: 100%; margin: -1px 0 0; padding: 8px; font-size: 12px; border-radius: 0; } /** * Attachments Browser */ .media-frame .attachments-browser { position: relative; width: 100%; height: 100%; overflow: hidden; } .attachments-browser .media-toolbar { right: 300px; height: 50px; } .attachments-browser .media-toolbar-primary > .media-button, .attachments-browser .media-toolbar-primary > .media-button-group, .attachments-browser .media-toolbar-secondary > .media-button, .attachments-browser .media-toolbar-secondary > .media-button-group { margin-top: 10px; } .attachments-browser .attachments, .attachments-browser .uploader-inline { position: absolute; top: 50px; left: 0; right: 300px; bottom: 0; overflow: auto; } .attachments-browser .instructions { display: inline-block; margin-top: 16px; line-height: 18px; font-size: 13px; color: #999; } /** * Progress Bar */ .media-progress-bar { position: relative; height: 10px; width: 70%; margin: 10px auto; border-radius: 10px; background: #dfdfdf; background: rgba( 0, 0, 0, 0.1 ); } .media-progress-bar div { height: 10px; min-width: 20px; width: 0; background: #aaa; background: rgba( 0, 0, 0, 0.2 ); border-radius: 10px; -webkit-transition: width 300ms; -moz-transition: width 300ms; -ms-transition: width 300ms; -o-transition: width 300ms; transition: width 300ms; } .media-uploader-status .media-progress-bar { display: none; width: 100%; } .uploading.media-uploader-status .media-progress-bar { display: block; } .attachment-preview .media-progress-bar { position: absolute; top: 50%; left: 15%; width: 70%; margin: -5px 0 0 0; } .media-uploader-status { position: relative; margin: 0 auto; padding-bottom: 10px; max-width: 400px; } .media-sidebar .media-uploader-status { border-bottom: 1px solid #dfdfdf; box-shadow: 0 1px 0 #fff; } .uploader-inline .media-uploader-status h3 { display: none; } .media-uploader-status .upload-details { display: none; font-size: 12px; color: #666; text-shadow: 0 1px 0 #fff; } .uploading.media-uploader-status .upload-details { display: block; } .media-uploader-status .upload-detail-separator { padding: 0 4px; } .media-uploader-status .upload-count { color: #464646; } .media-uploader-status .upload-dismiss-errors, .media-uploader-status .upload-errors { display: none; } .errors.media-uploader-status .upload-dismiss-errors, .errors.media-uploader-status .upload-errors { display: block; } .media-uploader-status .upload-dismiss-errors { text-decoration: none; } .media-sidebar .media-uploader-status .upload-dismiss-errors { position: absolute; top: 0; right: 0; } .upload-errors .upload-error { margin: 8px auto 0 auto; padding: 8px; border: 1px #c00 solid; background: #ffebe8; border-radius: 3px; } .upload-errors .upload-error-label { padding: 2px 4px; margin-right: 8px; font-weight: bold; color: #fff; background: #e00; background-image: -webkit-gradient(linear, left top, left bottom, from(#e00), to(#a00)); background-image: -webkit-linear-gradient(top, #e00, #a00); background-image: -moz-linear-gradient(top, #e00, #a00); background-image: -o-linear-gradient(top, #e00, #a00); background-image: linear-gradient(to bottom, #e00, #a00); border-radius: 3px; } .upload-errors .upload-error-message { display: block; padding-top: 8px; color: #b44; word-wrap: break-word; } .uploader-window { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba( 0, 86, 132, 0.9 ); z-index: 250000; display: none; text-align: center; opacity: 0; -webkit-transition: opacity 250ms; -moz-transition: opacity 250ms; -ms-transition: opacity 250ms; -o-transition: opacity 250ms; transition: opacity 250ms; } .uploader-window-content { position: absolute; top: 10px; left: 10px; right: 10px; bottom: 10px; border: 1px dashed #fff; } .uploader-window h3 { position: absolute; top: 50%; left: 0; right: 0; -webkit-transform: translateY( -50% ); -moz-transform: translateY( -50% ); -ms-transform: translateY( -50% ); -o-transform: translateY( -50% ); transform: translateY( -50% ); font-size: 20px; font-weight: 200; color: #fff; padding: 0; } .uploader-window .media-progress-bar { margin-top: 20px; max-width: 300px; background: transparent; border-color: #fff; display: none; } .uploader-window .media-progress-bar div { background: #fff; } .uploading .uploader-window .media-progress-bar { display: block; } .media-frame .uploader-inline { margin: 20px; padding: 20px; text-align: center; } .uploader-inline-content { position: absolute; top: 30%; left: 0; right: 0; } .uploader-inline-content .upload-ui { margin: 4em 0; } .uploader-inline-content .post-upload-ui { margin-bottom: 2em; } .uploader-inline .has-upload-message .upload-ui { margin: 0 0 4em; } .uploader-inline h3 { font-size: 20px; line-height: 28px; font-weight: 200; margin-bottom: 1.6em; } .uploader-inline .has-upload-message .upload-instructions { font-size: 14px; color: #464646; font-weight: normal; } .uploader-inline .drop-instructions { display: none; } .supports-drag-drop .uploader-inline .drop-instructions { display: block; } .uploader-inline p { font-size: 12px; } .uploader-inline .media-progress-bar { display: none; } .uploading.uploader-inline .media-progress-bar { display: block; } .uploader-inline .browser { display: inline-block !important; } /** * Selection */ .media-selection { position: absolute; top: 0; left: 0; right: 350px; height: 60px; padding: 0 0 0 16px; overflow: hidden; white-space: nowrap; } .media-selection .selection-info { display: inline-block; font-size: 12px; height: 60px; margin-right: 10px; vertical-align: top; } .media-selection.empty, .media-selection.editing { display: none; } .media-selection.one .edit-selection { display: none; } .media-selection .count { display: block; padding-top: 12px; font-size: 14px; line-height: 20px; font-weight: bold; } .media-selection .selection-info a { display: block; float: left; padding: 1px 8px; margin: 1px 8px 1px -8px; line-height: 16px; text-decoration: none; border-right: 1px solid #dfdfdf; color: #21759B; } .media-selection .selection-info a:hover { background: #21759B; color: #fff; border-color: transparent; } .media-selection .selection-info a:last-child { border-right: 0; margin-right: 0; } .media-selection .selection-info .clear-selection { color: red; } .media-selection .selection-info .clear-selection:hover { background: red; } .media-selection .selection-view { display: inline-block; vertical-align: top; } .media-selection .attachments { display: inline-block; height: 48px; margin-top: 5px; overflow: hidden; vertical-align: top; } .media-selection .attachment .icon { width: 50%; } .attachment.selection.selected { box-shadow: none; } .attachment.selection.details { box-shadow: 0 0 0 1px #fff, 0 0 0 4px #1e8cbe; } .media-selection .attachment.selection.details { box-shadow: 0 0 0 1px #fff, 0 0 0 3px #1e8cbe; } .media-selection:after { content: ''; display: block; position: absolute; top: 0; right: 0; bottom: 0; width: 25px; background-image: -webkit-gradient(linear, right top, left top, from( rgba( 255, 255, 255, 1 ) ), to( rgba( 255, 255, 255, 0 ) )); background-image: -webkit-linear-gradient(right, rgba( 255, 255, 255, 1 ) , rgba( 255, 255, 255, 0 ) ); background-image: -moz-linear-gradient(right, rgba( 255, 255, 255, 1 ) , rgba( 255, 255, 255, 0 ) ); background-image: -o-linear-gradient(right, rgba( 255, 255, 255, 1 ) , rgba( 255, 255, 255, 0 ) ); background-image: linear-gradient(to left, rgba( 255, 255, 255, 1 ) , rgba( 255, 255, 255, 0 ) ); } .media-selection .attachment .filename { display: none; } /** * Spinner */ .media-frame .spinner { background: url(../images/wpspin.gif) no-repeat; background-size: 16px 16px; display: none; opacity: 0.7; filter: alpha(opacity=70); width: 16px; height: 16px; margin: 0; } .media-sidebar .settings-save-status { background: #f5f5f5; float: right; text-transform: none; z-index: 10; } .media-sidebar .settings-save-status .spinner { margin: 0 5px 0; } .media-sidebar .settings-save-status .saved { float: right; display: none; } .media-sidebar .save-waiting .settings-save-status .spinner, .media-sidebar .save-complete .settings-save-status .saved { display: block; } /** * Attachment Details */ .attachment-details { position: relative; overflow: auto; } .attachment-info { overflow: hidden; min-height: 60px; margin-bottom: 16px; line-height: 18px; color: #999; border-bottom: 1px solid #e5e5e5; box-shadow: 0 1px 0 #fff; padding-bottom: 11px; } .attachment-info .filename { font-weight: bold; color: #464646; word-wrap: break-word; } .attachment-info .thumbnail { position: relative; float: left; max-width: 120px; max-height: 120px; margin-top: 5px; margin-right: 10px; margin-bottom: 5px; } .uploading .attachment-info .thumbnail { width: 120px; height: 80px; box-shadow: inset 0 0 15px rgba( 0, 0, 0, 0.1 ); } .uploading .attachment-info .media-progress-bar { margin-top: 35px; } .attachment-info .thumbnail:after { content: ''; display: block; position: absolute; top: 0; left: 0; right: 0; bottom: 0; box-shadow: inset 0 0 0 1px rgba( 0, 0, 0, 0.15 ); overflow: hidden; } .attachment-info .thumbnail img { display: block; max-width: 120px; max-height: 120px; margin: 0 auto; } .attachment-info .details { float: left; font-size: 12px; max-width: 100%; } .attachment-info .edit-attachment, .attachment-info .refresh-attachment, .attachment-info .delete-attachment { display: block; text-decoration: none; white-space: nowrap; } .attachment-info .refresh-attachment, .attachment-details.needs-refresh .attachment-info .edit-attachment { display: none; } .attachment-details.needs-refresh .attachment-info .refresh-attachment, .attachment-info .edit-attachment { display: block; } .attachment-info .delete-attachment { color: #bc0b0b; } .attachment-info .delete-attachment:hover { color: red; } /** * Attachment Display Settings */ .attachment-display-settings { width: 100%; float: left; overflow: hidden; } .attachment-display-settings h4 { margin: 1.4em 0 0.4em; } .gallery-settings { overflow: hidden; } /** * Embed from URL */ .embed-url { display: block; position: relative; padding: 0 16px 7px; margin: 0; z-index: 250; background: #fff; border-bottom: 1px solid #dfdfdf; box-shadow: 0 4px 4px -4px rgba( 0, 0, 0, 0.1 ); font-size: 18px; font-weight: 200; } .media-frame .embed-url input { font-size: 18px; padding: 12px 14px; width: 100%; min-width: 200px; box-shadow: inset 2px 2px 4px -2px rgba( 0, 0, 0, 0.1 ); } .media-frame .embed-url .spinner { position: absolute; top: 16px; right: 26px; } .media-frame .embed-loading .embed-url .spinner { display: block; } .embed-link-settings, .embed-image-settings { position: absolute; background: #f5f5f5; top: 57px; left: 0; right: 0; bottom: 0; padding: 16px 16px 32px; overflow: auto; } .media-embed .thumbnail { max-width: 100%; max-height: 200px; position: relative; float: left; } .media-embed .thumbnail img { max-height: 200px; display: block; } .media-embed .thumbnail:after { content: ''; display: block; position: absolute; top: 0; left: 0; right: 0; bottom: 0; box-shadow: inset 0 0 0 1px rgba( 0, 0, 0, 0.1 ); overflow: hidden; } .media-embed .setting { width: 100%; margin-top: 10px; float: left; display: block; clear: both; } .media-embed .setting span { display: block; width: 200px; font-size: 13px; line-height: 24px; color: #999; text-shadow: 0 1px 0 #fff; } .media-embed .setting .button-group { margin: 2px 0; } .media-embed .setting input, .media-embed .setting textarea { display: block; width: 100%; max-width: 400px; margin: 1px 0; } /** * IE7 Fixes */ .ie7 .media-frame .attachments-browser { position: static; } .ie7 .media-frame .embed-url input { margin-top: 4px; width: 90%; } .ie7 .compat-item { width: 99%; } .ie7 .attachment-display-settings { width: auto; } .ie7 .attachment-preview, .ie7 .attachment-preview .thumbnail { width: 120px; height: 120px; } .ie7 .media-frame .attachment .describe { width: 102px; } .ie7 .media-sidebar .setting select { max-width: 55%; } .ie7 .media-sidebar .setting input, .ie7 .media-sidebar .setting textarea { width: 55%; } .ie7 .media-sidebar .setting .link-to-custom { float: left; } @media only screen and (max-width: 960px) { .media-frame-content .media-toolbar-primary .search, .media-frame-content .media-toolbar-secondary .attachment-filters { max-width: 120px; } } /** * Responsive layout */ @media only screen and (max-width: 900px) { .media-frame-menu { width: 139px; } .media-menu > a { padding: 4px 10px; } .media-frame-title, .media-frame-router, .media-frame-content, .media-frame-toolbar { left: 140px; } .media-sidebar { width: 159px; padding: 0 10px 24px; } .attachments-browser .attachments, .attachments-browser .uploader-inline, .attachments-browser .media-toolbar { right: 180px; } .media-sidebar .setting input, .media-sidebar .setting textarea, .media-sidebar .setting span, .compat-item label span { float: none; } .media-sidebar .setting span, .compat-item label span { text-align: inherit; display: block; min-height: 16px; margin: 0; padding: 8px 2px 0; } .media-sidebar .setting input, .media-sidebar .setting textarea, .media-sidebar .setting select { width: 98%; max-width: none; } .media-sidebar .setting select.columns { width: auto; } .media-frame input, .media-frame textarea, .media-frame .search { padding: 3px 6px; } .media-frame-content .attachment .icon { top: 40%; } .media-selection { min-width: 120px; } .media-selection:after { background: none; } .media-selection .attachments { display: none; } .media-menu .separator { margin: 12px 10px; } } @media only screen and (max-width: 800px) { .media-frame-content .media-toolbar .instructions { display: none; } } @media only screen and (max-width: 680px) { .media-frame-content .media-toolbar .search, .media-frame-content .media-toolbar .attachment-filters { max-width: 85px; } } /* Use the same min-width as in the admin */ @media only screen and (max-width: 600px) { .media-modal { width: 540px; position: absolute; } .media-modal-backdrop { width: 600px; position: absolute; } } /** * HiDPI Displays */ @media print, (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .media-modal-icon { background-image: url(../images/uploader-icons-2x.png); background-size: 134px 15px; } .media-frame .spinner { background-image: url(../images/wpspin-2x.gif); } }
zyblog
trunk/zyblog/wp-includes/css/media-views.css
CSS
asf20
28,795