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
<?php /** * A simple set of functions to check our version 1.0 update service. * * @package WordPress * @since 2.3.0 */ /** * Check WordPress version against the newest version. * * The WordPress version, PHP version, and Locale is sent. Checks against the * WordPress server at api.wordpress.org server. Will only check if WordPress * isn't installing. * * @since 2.3.0 * @uses $wp_version Used to check against the newest WordPress version. * * @param array $extra_stats Extra statistics to report to the WordPress.org API. * @param bool $force_check Whether to bypass the transient cache and force a fresh update check. Defaults to false, true if $extra_stats is set. * @return mixed Returns null if update is unsupported. Returns false if check is too soon. */ function wp_version_check( $extra_stats = array(), $force_check = false ) { if ( defined('WP_INSTALLING') ) return; global $wpdb, $wp_local_package; include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version $php_version = phpversion(); $current = get_site_transient( 'update_core' ); $translations = wp_get_installed_translations( 'core' ); // Invalidate the transient when $wp_version changes if ( is_object( $current ) && $wp_version != $current->version_checked ) $current = false; if ( ! is_object($current) ) { $current = new stdClass; $current->updates = array(); $current->version_checked = $wp_version; } if ( ! empty( $extra_stats ) ) $force_check = true; // Wait 60 seconds between multiple version check requests $timeout = 60; $time_not_changed = isset( $current->last_checked ) && $timeout > ( time() - $current->last_checked ); if ( ! $force_check && $time_not_changed ) return false; $locale = get_locale(); /** * Filter the locale requested for WordPress core translations. * * @since 2.8.0 * * @param string $locale Current locale. */ $locale = apply_filters( 'core_version_check_locale', $locale ); // Update last_checked for current to prevent multiple blocking requests if request hangs $current->last_checked = time(); set_site_transient( 'update_core', $current ); if ( method_exists( $wpdb, 'db_version' ) ) $mysql_version = preg_replace('/[^0-9.].*/', '', $wpdb->db_version()); else $mysql_version = 'N/A'; if ( is_multisite() ) { $user_count = get_user_count(); $num_blogs = get_blog_count(); $wp_install = network_site_url(); $multisite_enabled = 1; } else { $user_count = count_users(); $user_count = $user_count['total_users']; $multisite_enabled = 0; $num_blogs = 1; $wp_install = home_url( '/' ); } $query = array( 'version' => $wp_version, 'php' => $php_version, 'locale' => $locale, 'mysql' => $mysql_version, 'local_package' => isset( $wp_local_package ) ? $wp_local_package : '', 'blogs' => $num_blogs, 'users' => $user_count, 'multisite_enabled' => $multisite_enabled, ); $post_body = array( 'translations' => json_encode( $translations ), ); if ( is_array( $extra_stats ) ) $post_body = array_merge( $post_body, $extra_stats ); $url = $http_url = 'http://api.wordpress.org/core/version-check/1.7/?' . http_build_query( $query, null, '&' ); if ( $ssl = wp_http_supports( array( 'ssl' ) ) ) $url = set_url_scheme( $url, 'https' ); $options = array( 'timeout' => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 3 ), 'user-agent' => 'WordPress/' . $wp_version . '; ' . home_url( '/' ), 'headers' => array( 'wp_install' => $wp_install, 'wp_blog' => home_url( '/' ) ), 'body' => $post_body, ); $response = wp_remote_post( $url, $options ); if ( $ssl && is_wp_error( $response ) ) { trigger_error( __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="https://wordpress.org/support/">support forums</a>.' ) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ), headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE ); $response = wp_remote_post( $http_url, $options ); } if ( is_wp_error( $response ) || 200 != wp_remote_retrieve_response_code( $response ) ) return false; $body = trim( wp_remote_retrieve_body( $response ) ); $body = json_decode( $body, true ); if ( ! is_array( $body ) || ! isset( $body['offers'] ) ) return false; $offers = $body['offers']; foreach ( $offers as &$offer ) { foreach ( $offer as $offer_key => $value ) { if ( 'packages' == $offer_key ) $offer['packages'] = (object) array_intersect_key( array_map( 'esc_url', $offer['packages'] ), array_fill_keys( array( 'full', 'no_content', 'new_bundled', 'partial', 'rollback' ), '' ) ); elseif ( 'download' == $offer_key ) $offer['download'] = esc_url( $value ); else $offer[ $offer_key ] = esc_html( $value ); } $offer = (object) array_intersect_key( $offer, array_fill_keys( array( 'response', 'download', 'locale', 'packages', 'current', 'version', 'php_version', 'mysql_version', 'new_bundled', 'partial_version', 'notify_email', 'support_email' ), '' ) ); } $updates = new stdClass(); $updates->updates = $offers; $updates->last_checked = time(); $updates->version_checked = $wp_version; if ( isset( $body['translations'] ) ) $updates->translations = $body['translations']; set_site_transient( 'update_core', $updates ); if ( ! empty( $body['ttl'] ) ) { $ttl = (int) $body['ttl']; if ( $ttl && ( time() + $ttl < wp_next_scheduled( 'wp_version_check' ) ) ) { // Queue an event to re-run the update check in $ttl seconds. wp_schedule_single_event( time() + $ttl, 'wp_version_check' ); } } // Trigger a background updates check if running non-interactively, and we weren't called from the update handler. if ( defined( 'DOING_CRON' ) && DOING_CRON && ! doing_action( 'wp_maybe_auto_update' ) ) { do_action( 'wp_maybe_auto_update' ); } } /** * Check plugin versions against the latest versions hosted on WordPress.org. * * The WordPress version, PHP version, and Locale is sent along with a list of * all plugins installed. Checks against the WordPress server at * api.wordpress.org. Will only check if WordPress isn't installing. * * @since 2.3.0 * @uses $wp_version Used to notify the WordPress version. * * @param array $extra_stats Extra statistics to report to the WordPress.org API. * @return mixed Returns null if update is unsupported. Returns false if check is too soon. */ function wp_update_plugins( $extra_stats = array() ) { include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version if ( defined('WP_INSTALLING') ) return false; // If running blog-side, bail unless we've not checked in the last 12 hours if ( !function_exists( 'get_plugins' ) ) require_once( ABSPATH . 'wp-admin/includes/plugin.php' ); $plugins = get_plugins(); $translations = wp_get_installed_translations( 'plugins' ); $active = get_option( 'active_plugins', array() ); $current = get_site_transient( 'update_plugins' ); if ( ! is_object($current) ) $current = new stdClass; $new_option = new stdClass; $new_option->last_checked = time(); // Check for update on a different schedule, depending on the page. switch ( current_filter() ) { case 'upgrader_process_complete' : $timeout = 0; break; case 'load-update-core.php' : $timeout = MINUTE_IN_SECONDS; break; case 'load-plugins.php' : case 'load-update.php' : $timeout = HOUR_IN_SECONDS; break; default : if ( defined( 'DOING_CRON' ) && DOING_CRON ) { $timeout = 0; } else { $timeout = 12 * HOUR_IN_SECONDS; } } $time_not_changed = isset( $current->last_checked ) && $timeout > ( time() - $current->last_checked ); if ( $time_not_changed && ! $extra_stats ) { $plugin_changed = false; foreach ( $plugins as $file => $p ) { $new_option->checked[ $file ] = $p['Version']; if ( !isset( $current->checked[ $file ] ) || strval($current->checked[ $file ]) !== strval($p['Version']) ) $plugin_changed = true; } if ( isset ( $current->response ) && is_array( $current->response ) ) { foreach ( $current->response as $plugin_file => $update_details ) { if ( ! isset($plugins[ $plugin_file ]) ) { $plugin_changed = true; break; } } } // Bail if we've checked recently and if nothing has changed if ( ! $plugin_changed ) return false; } // Update last_checked for current to prevent multiple blocking requests if request hangs $current->last_checked = time(); set_site_transient( 'update_plugins', $current ); $to_send = compact( 'plugins', 'active' ); $locales = array( get_locale() ); /** * Filter the locales requested for plugin translations. * * @since 3.7.0 * * @param array $locales Plugin locale. Default is current locale of the site. */ $locales = apply_filters( 'plugins_update_check_locales', $locales ); $options = array( 'timeout' => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 3), 'body' => array( 'plugins' => json_encode( $to_send ), 'translations' => json_encode( $translations ), 'locale' => json_encode( $locales ), ), 'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ); if ( $extra_stats ) { $options['body']['update_stats'] = json_encode( $extra_stats ); } $url = $http_url = 'http://api.wordpress.org/plugins/update-check/1.1/'; if ( $ssl = wp_http_supports( array( 'ssl' ) ) ) $url = set_url_scheme( $url, 'https' ); $raw_response = wp_remote_post( $url, $options ); if ( $ssl && is_wp_error( $raw_response ) ) { trigger_error( __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="https://wordpress.org/support/">support forums</a>.' ) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ), headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE ); $raw_response = wp_remote_post( $http_url, $options ); } if ( is_wp_error( $raw_response ) || 200 != wp_remote_retrieve_response_code( $raw_response ) ) return false; $response = json_decode( wp_remote_retrieve_body( $raw_response ), true ); foreach ( $response['plugins'] as &$plugin ) { $plugin = (object) $plugin; } unset( $plugin ); if ( is_array( $response ) ) { $new_option->response = $response['plugins']; $new_option->translations = $response['translations']; } else { $new_option->response = array(); $new_option->translations = array(); } set_site_transient( 'update_plugins', $new_option ); } /** * Check theme versions against the latest versions hosted on WordPress.org. * * A list of all themes installed in sent to WP. Checks against the * WordPress server at api.wordpress.org. Will only check if WordPress isn't * installing. * * @since 2.7.0 * @uses $wp_version Used to notify the WordPress version. * * @param array $extra_stats Extra statistics to report to the WordPress.org API. * @return mixed Returns null if update is unsupported. Returns false if check is too soon. */ function wp_update_themes( $extra_stats = array() ) { include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version if ( defined( 'WP_INSTALLING' ) ) return false; $installed_themes = wp_get_themes(); $translations = wp_get_installed_translations( 'themes' ); $last_update = get_site_transient( 'update_themes' ); if ( ! is_object($last_update) ) $last_update = new stdClass; $themes = $checked = $request = array(); // Put slug of current theme into request. $request['active'] = get_option( 'stylesheet' ); foreach ( $installed_themes as $theme ) { $checked[ $theme->get_stylesheet() ] = $theme->get('Version'); $themes[ $theme->get_stylesheet() ] = array( 'Name' => $theme->get('Name'), 'Title' => $theme->get('Name'), 'Version' => $theme->get('Version'), 'Author' => $theme->get('Author'), 'Author URI' => $theme->get('AuthorURI'), 'Template' => $theme->get_template(), 'Stylesheet' => $theme->get_stylesheet(), ); } // Check for update on a different schedule, depending on the page. switch ( current_filter() ) { case 'upgrader_process_complete' : $timeout = 0; break; case 'load-update-core.php' : $timeout = MINUTE_IN_SECONDS; break; case 'load-themes.php' : case 'load-update.php' : $timeout = HOUR_IN_SECONDS; break; default : if ( defined( 'DOING_CRON' ) && DOING_CRON ) { $timeout = 0; } else { $timeout = 12 * HOUR_IN_SECONDS; } } $time_not_changed = isset( $last_update->last_checked ) && $timeout > ( time() - $last_update->last_checked ); if ( $time_not_changed && ! $extra_stats ) { $theme_changed = false; foreach ( $checked as $slug => $v ) { if ( !isset( $last_update->checked[ $slug ] ) || strval($last_update->checked[ $slug ]) !== strval($v) ) $theme_changed = true; } if ( isset ( $last_update->response ) && is_array( $last_update->response ) ) { foreach ( $last_update->response as $slug => $update_details ) { if ( ! isset($checked[ $slug ]) ) { $theme_changed = true; break; } } } // Bail if we've checked recently and if nothing has changed if ( ! $theme_changed ) return false; } // Update last_checked for current to prevent multiple blocking requests if request hangs $last_update->last_checked = time(); set_site_transient( 'update_themes', $last_update ); $request['themes'] = $themes; $locales = array( get_locale() ); /** * Filter the locales requested for theme translations. * * @since 3.7.0 * * @param array $locales Theme locale. Default is current locale of the site. */ $locales = apply_filters( 'themes_update_check_locales', $locales ); $options = array( 'timeout' => ( ( defined('DOING_CRON') && DOING_CRON ) ? 30 : 3), 'body' => array( 'themes' => json_encode( $request ), 'translations' => json_encode( $translations ), 'locale' => json_encode( $locales ), ), 'user-agent' => 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ) ); if ( $extra_stats ) { $options['body']['update_stats'] = json_encode( $extra_stats ); } $url = $http_url = 'http://api.wordpress.org/themes/update-check/1.1/'; if ( $ssl = wp_http_supports( array( 'ssl' ) ) ) $url = set_url_scheme( $url, 'https' ); $raw_response = wp_remote_post( $url, $options ); if ( $ssl && is_wp_error( $raw_response ) ) { trigger_error( __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="https://wordpress.org/support/">support forums</a>.' ) . ' ' . __( '(WordPress could not establish a secure connection to WordPress.org. Please contact your server administrator.)' ), headers_sent() || WP_DEBUG ? E_USER_WARNING : E_USER_NOTICE ); $raw_response = wp_remote_post( $http_url, $options ); } if ( is_wp_error( $raw_response ) || 200 != wp_remote_retrieve_response_code( $raw_response ) ) return false; $new_update = new stdClass; $new_update->last_checked = time(); $new_update->checked = $checked; $response = json_decode( wp_remote_retrieve_body( $raw_response ), true ); if ( is_array( $response ) ) { $new_update->response = $response['themes']; $new_update->translations = $response['translations']; } set_site_transient( 'update_themes', $new_update ); } /** * Performs WordPress automatic background updates. * * @since 3.7.0 */ function wp_maybe_auto_update() { include_once ABSPATH . '/wp-admin/includes/admin.php'; include_once ABSPATH . '/wp-admin/includes/class-wp-upgrader.php'; $upgrader = new WP_Automatic_Updater; $upgrader->run(); } /** * Retrieves a list of all language updates available. * * @since 3.7.0 */ function wp_get_translation_updates() { $updates = array(); $transients = array( 'update_core' => 'core', 'update_plugins' => 'plugin', 'update_themes' => 'theme' ); foreach ( $transients as $transient => $type ) { $transient = get_site_transient( $transient ); if ( empty( $transient->translations ) ) continue; foreach ( $transient->translations as $translation ) { $updates[] = (object) $translation; } } return $updates; } /** * Collect counts and UI strings for available updates * * @since 3.3.0 * * @return array */ function wp_get_update_data() { $counts = array( 'plugins' => 0, 'themes' => 0, 'wordpress' => 0, 'translations' => 0 ); if ( $plugins = current_user_can( 'update_plugins' ) ) { $update_plugins = get_site_transient( 'update_plugins' ); if ( ! empty( $update_plugins->response ) ) $counts['plugins'] = count( $update_plugins->response ); } if ( $themes = current_user_can( 'update_themes' ) ) { $update_themes = get_site_transient( 'update_themes' ); if ( ! empty( $update_themes->response ) ) $counts['themes'] = count( $update_themes->response ); } if ( ( $core = current_user_can( 'update_core' ) ) && function_exists( 'get_core_updates' ) ) { $update_wordpress = get_core_updates( array('dismissed' => false) ); if ( ! empty( $update_wordpress ) && ! in_array( $update_wordpress[0]->response, array('development', 'latest') ) && current_user_can('update_core') ) $counts['wordpress'] = 1; } if ( ( $core || $plugins || $themes ) && wp_get_translation_updates() ) $counts['translations'] = 1; $counts['total'] = $counts['plugins'] + $counts['themes'] + $counts['wordpress'] + $counts['translations']; $titles = array(); if ( $counts['wordpress'] ) $titles['wordpress'] = sprintf( __( '%d WordPress Update'), $counts['wordpress'] ); if ( $counts['plugins'] ) $titles['plugins'] = sprintf( _n( '%d Plugin Update', '%d Plugin Updates', $counts['plugins'] ), $counts['plugins'] ); if ( $counts['themes'] ) $titles['themes'] = sprintf( _n( '%d Theme Update', '%d Theme Updates', $counts['themes'] ), $counts['themes'] ); if ( $counts['translations'] ) $titles['translations'] = __( 'Translation Updates' ); $update_title = $titles ? esc_attr( implode( ', ', $titles ) ) : ''; $update_data = array( 'counts' => $counts, 'title' => $update_title ); /** * Filter the returned array of update data for plugins, themes, and WordPress core. * * @since 3.5.0 * * @param array $update_data { * Fetched update data. * * @type array $counts An array of counts for available plugin, theme, and WordPress updates. * @type string $update_title Titles of available updates. * } * @param array $titles An array of update counts and UI strings for available updates. */ return apply_filters( 'wp_get_update_data', $update_data, $titles ); } function _maybe_update_core() { include ABSPATH . WPINC . '/version.php'; // include an unmodified $wp_version $current = get_site_transient( 'update_core' ); if ( isset( $current->last_checked ) && 12 * HOUR_IN_SECONDS > ( time() - $current->last_checked ) && isset( $current->version_checked ) && $current->version_checked == $wp_version ) return; wp_version_check(); } /** * Check the last time plugins were run before checking plugin versions. * * This might have been backported to WordPress 2.6.1 for performance reasons. * This is used for the wp-admin to check only so often instead of every page * load. * * @since 2.7.0 * @access private */ function _maybe_update_plugins() { $current = get_site_transient( 'update_plugins' ); if ( isset( $current->last_checked ) && 12 * HOUR_IN_SECONDS > ( time() - $current->last_checked ) ) return; wp_update_plugins(); } /** * Check themes versions only after a duration of time. * * This is for performance reasons to make sure that on the theme version * checker is not run on every page load. * * @since 2.7.0 * @access private */ function _maybe_update_themes() { $current = get_site_transient( 'update_themes' ); if ( isset( $current->last_checked ) && 12 * HOUR_IN_SECONDS > ( time() - $current->last_checked ) ) return; wp_update_themes(); } /** * Schedule core, theme, and plugin update checks. * * @since 3.1.0 */ function wp_schedule_update_checks() { if ( !wp_next_scheduled('wp_version_check') && !defined('WP_INSTALLING') ) wp_schedule_event(time(), 'twicedaily', 'wp_version_check'); if ( !wp_next_scheduled('wp_update_plugins') && !defined('WP_INSTALLING') ) wp_schedule_event(time(), 'twicedaily', 'wp_update_plugins'); if ( !wp_next_scheduled('wp_update_themes') && !defined('WP_INSTALLING') ) wp_schedule_event(time(), 'twicedaily', 'wp_update_themes'); if ( ! wp_next_scheduled( 'wp_maybe_auto_update' ) && ! defined( 'WP_INSTALLING' ) ) { // Schedule auto updates for 7 a.m. and 7 p.m. in the timezone of the site. $next = strtotime( 'today 7am' ); $now = time(); // Find the next instance of 7 a.m. or 7 p.m., but skip it if it is within 3 hours from now. while ( ( $now + 3 * HOUR_IN_SECONDS ) > $next ) { $next += 12 * HOUR_IN_SECONDS; } $next = $next - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS; // Add a random number of minutes, so we don't have all sites trying to update exactly on the hour $next = $next + rand( 0, 59 ) * MINUTE_IN_SECONDS; wp_schedule_event( $next, 'twicedaily', 'wp_maybe_auto_update' ); } } if ( ( ! is_main_site() && ! is_network_admin() ) || ( defined( 'DOING_AJAX' ) && DOING_AJAX ) ) return; add_action( 'admin_init', '_maybe_update_core' ); add_action( 'wp_version_check', 'wp_version_check' ); add_action( 'upgrader_process_complete', 'wp_version_check', 10, 0 ); add_action( 'load-plugins.php', 'wp_update_plugins' ); add_action( 'load-update.php', 'wp_update_plugins' ); add_action( 'load-update-core.php', 'wp_update_plugins' ); add_action( 'admin_init', '_maybe_update_plugins' ); add_action( 'wp_update_plugins', 'wp_update_plugins' ); add_action( 'upgrader_process_complete', 'wp_update_plugins', 10, 0 ); add_action( 'load-themes.php', 'wp_update_themes' ); add_action( 'load-update.php', 'wp_update_themes' ); add_action( 'load-update-core.php', 'wp_update_themes' ); add_action( 'admin_init', '_maybe_update_themes' ); add_action( 'wp_update_themes', 'wp_update_themes' ); add_action( 'upgrader_process_complete', 'wp_update_themes', 10, 0 ); add_action( 'wp_maybe_auto_update', 'wp_maybe_auto_update' ); add_action('init', 'wp_schedule_update_checks');
01-wordpress-paypal
trunk/wp-includes/update.php
PHP
gpl3
22,602
<?php if ( ! class_exists( 'Services_JSON' ) ) : /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ /** * Converts to and from JSON format. * * JSON (JavaScript Object Notation) is a lightweight data-interchange * format. It is easy for humans to read and write. It is easy for machines * to parse and generate. It is based on a subset of the JavaScript * Programming Language, Standard ECMA-262 3rd Edition - December 1999. * This feature can also be found in Python. JSON is a text format that is * completely language independent but uses conventions that are familiar * to programmers of the C-family of languages, including C, C++, C#, Java, * JavaScript, Perl, TCL, and many others. These properties make JSON an * ideal data-interchange language. * * This package provides a simple encoder and decoder for JSON notation. It * is intended for use with client-side Javascript applications that make * use of HTTPRequest to perform server communication functions - data can * be encoded into JSON notation for use in a client-side javascript, or * decoded from incoming Javascript requests. JSON format is native to * Javascript, and can be directly eval()'ed with no further parsing * overhead * * All strings should be in ASCII or UTF-8 format! * * LICENSE: 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. * * THIS SOFTWARE IS PROVIDED ``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 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. * * @category * @package Services_JSON * @author Michal Migurski <mike-json@teczno.com> * @author Matt Knapp <mdknapp[at]gmail[dot]com> * @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com> * @copyright 2005 Michal Migurski * @version CVS: $Id: JSON.php 305040 2010-11-02 23:19:03Z alan_k $ * @license http://www.opensource.org/licenses/bsd-license.php * @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198 */ /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_SLICE', 1); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_STR', 2); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_ARR', 3); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_OBJ', 4); /** * Marker constant for Services_JSON::decode(), used to flag stack state */ define('SERVICES_JSON_IN_CMT', 5); /** * Behavior switch for Services_JSON::decode() */ define('SERVICES_JSON_LOOSE_TYPE', 16); /** * Behavior switch for Services_JSON::decode() */ define('SERVICES_JSON_SUPPRESS_ERRORS', 32); /** * Behavior switch for Services_JSON::decode() */ define('SERVICES_JSON_USE_TO_JSON', 64); /** * Converts to and from JSON format. * * Brief example of use: * * <code> * // create a new instance of Services_JSON * $json = new Services_JSON(); * * // convert a complexe value to JSON notation, and send it to the browser * $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4))); * $output = $json->encode($value); * * print($output); * // prints: ["foo","bar",[1,2,"baz"],[3,[4]]] * * // accept incoming POST data, assumed to be in JSON notation * $input = file_get_contents('php://input', 1000000); * $value = $json->decode($input); * </code> */ class Services_JSON { /** * constructs a new JSON instance * * @param int $use object behavior flags; combine with boolean-OR * * possible values: * - SERVICES_JSON_LOOSE_TYPE: loose typing. * "{...}" syntax creates associative arrays * instead of objects in decode(). * - SERVICES_JSON_SUPPRESS_ERRORS: error suppression. * Values which can't be encoded (e.g. resources) * appear as NULL instead of throwing errors. * By default, a deeply-nested resource will * bubble up with an error, so all return values * from encode() should be checked with isError() * - SERVICES_JSON_USE_TO_JSON: call toJSON when serializing objects * It serializes the return value from the toJSON call rather * than the object it'self, toJSON can return associative arrays, * strings or numbers, if you return an object, make sure it does * not have a toJSON method, otherwise an error will occur. */ function Services_JSON($use = 0) { $this->use = $use; $this->_mb_strlen = function_exists('mb_strlen'); $this->_mb_convert_encoding = function_exists('mb_convert_encoding'); $this->_mb_substr = function_exists('mb_substr'); } // private - cache the mbstring lookup results.. var $_mb_strlen = false; var $_mb_substr = false; var $_mb_convert_encoding = false; /** * convert a string from one UTF-16 char to one UTF-8 char * * Normally should be handled by mb_convert_encoding, but * provides a slower PHP-only method for installations * that lack the multibye string extension. * * @param string $utf16 UTF-16 character * @return string UTF-8 character * @access private */ function utf162utf8($utf16) { // oh please oh please oh please oh please oh please if($this->_mb_convert_encoding) { return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16'); } $bytes = (ord($utf16{0}) << 8) | ord($utf16{1}); switch(true) { case ((0x7F & $bytes) == $bytes): // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x7F & $bytes); case (0x07FF & $bytes) == $bytes: // return a 2-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xC0 | (($bytes >> 6) & 0x1F)) . chr(0x80 | ($bytes & 0x3F)); case (0xFFFF & $bytes) == $bytes: // return a 3-byte UTF-8 character // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0xE0 | (($bytes >> 12) & 0x0F)) . chr(0x80 | (($bytes >> 6) & 0x3F)) . chr(0x80 | ($bytes & 0x3F)); } // ignoring UTF-32 for now, sorry return ''; } /** * convert a string from one UTF-8 char to one UTF-16 char * * Normally should be handled by mb_convert_encoding, but * provides a slower PHP-only method for installations * that lack the multibye string extension. * * @param string $utf8 UTF-8 character * @return string UTF-16 character * @access private */ function utf82utf16($utf8) { // oh please oh please oh please oh please oh please if($this->_mb_convert_encoding) { return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8'); } switch($this->strlen8($utf8)) { case 1: // this case should never be reached, because we are in ASCII range // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return $utf8; case 2: // return a UTF-16 character from a 2-byte UTF-8 char // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr(0x07 & (ord($utf8{0}) >> 2)) . chr((0xC0 & (ord($utf8{0}) << 6)) | (0x3F & ord($utf8{1}))); case 3: // return a UTF-16 character from a 3-byte UTF-8 char // see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 return chr((0xF0 & (ord($utf8{0}) << 4)) | (0x0F & (ord($utf8{1}) >> 2))) . chr((0xC0 & (ord($utf8{1}) << 6)) | (0x7F & ord($utf8{2}))); } // ignoring UTF-32 for now, sorry return ''; } /** * encodes an arbitrary variable into JSON format (and sends JSON Header) * * @param mixed $var any number, boolean, string, array, or object to be encoded. * see argument 1 to Services_JSON() above for array-parsing behavior. * if var is a strng, note that encode() always expects it * to be in ASCII or UTF-8 format! * * @return mixed JSON string representation of input var or an error if a problem occurs * @access public */ function encode($var) { header('Content-type: application/json'); return $this->encodeUnsafe($var); } /** * encodes an arbitrary variable into JSON format without JSON Header - warning - may allow XSS!!!!) * * @param mixed $var any number, boolean, string, array, or object to be encoded. * see argument 1 to Services_JSON() above for array-parsing behavior. * if var is a strng, note that encode() always expects it * to be in ASCII or UTF-8 format! * * @return mixed JSON string representation of input var or an error if a problem occurs * @access public */ function encodeUnsafe($var) { // see bug #16908 - regarding numeric locale printing $lc = setlocale(LC_NUMERIC, 0); setlocale(LC_NUMERIC, 'C'); $ret = $this->_encode($var); setlocale(LC_NUMERIC, $lc); return $ret; } /** * PRIVATE CODE that does the work of encodes an arbitrary variable into JSON format * * @param mixed $var any number, boolean, string, array, or object to be encoded. * see argument 1 to Services_JSON() above for array-parsing behavior. * if var is a strng, note that encode() always expects it * to be in ASCII or UTF-8 format! * * @return mixed JSON string representation of input var or an error if a problem occurs * @access public */ function _encode($var) { switch (gettype($var)) { case 'boolean': return $var ? 'true' : 'false'; case 'NULL': return 'null'; case 'integer': return (int) $var; case 'double': case 'float': return (float) $var; case 'string': // STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT $ascii = ''; $strlen_var = $this->strlen8($var); /* * Iterate over every character in the string, * escaping with a slash or encoding to UTF-8 where necessary */ for ($c = 0; $c < $strlen_var; ++$c) { $ord_var_c = ord($var{$c}); switch (true) { case $ord_var_c == 0x08: $ascii .= '\b'; break; case $ord_var_c == 0x09: $ascii .= '\t'; break; case $ord_var_c == 0x0A: $ascii .= '\n'; break; case $ord_var_c == 0x0C: $ascii .= '\f'; break; case $ord_var_c == 0x0D: $ascii .= '\r'; break; case $ord_var_c == 0x22: case $ord_var_c == 0x2F: case $ord_var_c == 0x5C: // double quote, slash, slosh $ascii .= '\\'.$var{$c}; break; case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)): // characters U-00000000 - U-0000007F (same as ASCII) $ascii .= $var{$c}; break; case (($ord_var_c & 0xE0) == 0xC0): // characters U-00000080 - U-000007FF, mask 110XXXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 if ($c+1 >= $strlen_var) { $c += 1; $ascii .= '?'; break; } $char = pack('C*', $ord_var_c, ord($var{$c + 1})); $c += 1; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF0) == 0xE0): if ($c+2 >= $strlen_var) { $c += 2; $ascii .= '?'; break; } // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, @ord($var{$c + 1}), @ord($var{$c + 2})); $c += 2; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xF8) == 0xF0): if ($c+3 >= $strlen_var) { $c += 3; $ascii .= '?'; break; } // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3})); $c += 3; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFC) == 0xF8): // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 if ($c+4 >= $strlen_var) { $c += 4; $ascii .= '?'; break; } $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3}), ord($var{$c + 4})); $c += 4; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; case (($ord_var_c & 0xFE) == 0xFC): if ($c+5 >= $strlen_var) { $c += 5; $ascii .= '?'; break; } // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $char = pack('C*', $ord_var_c, ord($var{$c + 1}), ord($var{$c + 2}), ord($var{$c + 3}), ord($var{$c + 4}), ord($var{$c + 5})); $c += 5; $utf16 = $this->utf82utf16($char); $ascii .= sprintf('\u%04s', bin2hex($utf16)); break; } } return '"'.$ascii.'"'; case 'array': /* * As per JSON spec if any array key is not an integer * we must treat the the whole array as an object. We * also try to catch a sparsely populated associative * array with numeric keys here because some JS engines * will create an array with empty indexes up to * max_index which can cause memory issues and because * the keys, which may be relevant, will be remapped * otherwise. * * As per the ECMA and JSON specification an object may * have any string as a property. Unfortunately due to * a hole in the ECMA specification if the key is a * ECMA reserved word or starts with a digit the * parameter is only accessible using ECMAScript's * bracket notation. */ // treat as a JSON object if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) { $properties = array_map(array($this, 'name_value'), array_keys($var), array_values($var)); foreach($properties as $property) { if(Services_JSON::isError($property)) { return $property; } } return '{' . join(',', $properties) . '}'; } // treat it like a regular array $elements = array_map(array($this, '_encode'), $var); foreach($elements as $element) { if(Services_JSON::isError($element)) { return $element; } } return '[' . join(',', $elements) . ']'; case 'object': // support toJSON methods. if (($this->use & SERVICES_JSON_USE_TO_JSON) && method_exists($var, 'toJSON')) { // this may end up allowing unlimited recursion // so we check the return value to make sure it's not got the same method. $recode = $var->toJSON(); if (method_exists($recode, 'toJSON')) { return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) ? 'null' : new Services_JSON_Error(get_class($var). " toJSON returned an object with a toJSON method."); } return $this->_encode( $recode ); } $vars = get_object_vars($var); $properties = array_map(array($this, 'name_value'), array_keys($vars), array_values($vars)); foreach($properties as $property) { if(Services_JSON::isError($property)) { return $property; } } return '{' . join(',', $properties) . '}'; default: return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS) ? 'null' : new Services_JSON_Error(gettype($var)." can not be encoded as JSON string"); } } /** * array-walking function for use in generating JSON-formatted name-value pairs * * @param string $name name of key to use * @param mixed $value reference to an array element to be encoded * * @return string JSON-formatted name-value pair, like '"name":value' * @access private */ function name_value($name, $value) { $encoded_value = $this->_encode($value); if(Services_JSON::isError($encoded_value)) { return $encoded_value; } return $this->_encode(strval($name)) . ':' . $encoded_value; } /** * reduce a string by removing leading and trailing comments and whitespace * * @param $str string string value to strip of comments and whitespace * * @return string string value stripped of comments and whitespace * @access private */ function reduce_string($str) { $str = preg_replace(array( // eliminate single line comments in '// ...' form '#^\s*//(.+)$#m', // eliminate multi-line comments in '/* ... */' form, at start of string '#^\s*/\*(.+)\*/#Us', // eliminate multi-line comments in '/* ... */' form, at end of string '#/\*(.+)\*/\s*$#Us' ), '', $str); // eliminate extraneous space return trim($str); } /** * decodes a JSON string into appropriate variable * * @param string $str JSON-formatted string * * @return mixed number, boolean, string, array, or object * corresponding to given JSON input string. * See argument 1 to Services_JSON() above for object-output behavior. * Note that decode() always returns strings * in ASCII or UTF-8 format! * @access public */ function decode($str) { $str = $this->reduce_string($str); switch (strtolower($str)) { case 'true': return true; case 'false': return false; case 'null': return null; default: $m = array(); if (is_numeric($str)) { // Lookie-loo, it's a number // This would work on its own, but I'm trying to be // good about returning integers where appropriate: // return (float)$str; // Return float or int, as appropriate return ((float)$str == (integer)$str) ? (integer)$str : (float)$str; } elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) { // STRINGS RETURNED IN UTF-8 FORMAT $delim = $this->substr8($str, 0, 1); $chrs = $this->substr8($str, 1, -1); $utf8 = ''; $strlen_chrs = $this->strlen8($chrs); for ($c = 0; $c < $strlen_chrs; ++$c) { $substr_chrs_c_2 = $this->substr8($chrs, $c, 2); $ord_chrs_c = ord($chrs{$c}); switch (true) { case $substr_chrs_c_2 == '\b': $utf8 .= chr(0x08); ++$c; break; case $substr_chrs_c_2 == '\t': $utf8 .= chr(0x09); ++$c; break; case $substr_chrs_c_2 == '\n': $utf8 .= chr(0x0A); ++$c; break; case $substr_chrs_c_2 == '\f': $utf8 .= chr(0x0C); ++$c; break; case $substr_chrs_c_2 == '\r': $utf8 .= chr(0x0D); ++$c; break; case $substr_chrs_c_2 == '\\"': case $substr_chrs_c_2 == '\\\'': case $substr_chrs_c_2 == '\\\\': case $substr_chrs_c_2 == '\\/': if (($delim == '"' && $substr_chrs_c_2 != '\\\'') || ($delim == "'" && $substr_chrs_c_2 != '\\"')) { $utf8 .= $chrs{++$c}; } break; case preg_match('/\\\u[0-9A-F]{4}/i', $this->substr8($chrs, $c, 6)): // single, escaped unicode character $utf16 = chr(hexdec($this->substr8($chrs, ($c + 2), 2))) . chr(hexdec($this->substr8($chrs, ($c + 4), 2))); $utf8 .= $this->utf162utf8($utf16); $c += 5; break; case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F): $utf8 .= $chrs{$c}; break; case ($ord_chrs_c & 0xE0) == 0xC0: // characters U-00000080 - U-000007FF, mask 110XXXXX //see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= $this->substr8($chrs, $c, 2); ++$c; break; case ($ord_chrs_c & 0xF0) == 0xE0: // characters U-00000800 - U-0000FFFF, mask 1110XXXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= $this->substr8($chrs, $c, 3); $c += 2; break; case ($ord_chrs_c & 0xF8) == 0xF0: // characters U-00010000 - U-001FFFFF, mask 11110XXX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= $this->substr8($chrs, $c, 4); $c += 3; break; case ($ord_chrs_c & 0xFC) == 0xF8: // characters U-00200000 - U-03FFFFFF, mask 111110XX // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= $this->substr8($chrs, $c, 5); $c += 4; break; case ($ord_chrs_c & 0xFE) == 0xFC: // characters U-04000000 - U-7FFFFFFF, mask 1111110X // see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8 $utf8 .= $this->substr8($chrs, $c, 6); $c += 5; break; } } return $utf8; } elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) { // array, or object notation if ($str{0} == '[') { $stk = array(SERVICES_JSON_IN_ARR); $arr = array(); } else { if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $stk = array(SERVICES_JSON_IN_OBJ); $obj = array(); } else { $stk = array(SERVICES_JSON_IN_OBJ); $obj = new stdClass(); } } array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => 0, 'delim' => false)); $chrs = $this->substr8($str, 1, -1); $chrs = $this->reduce_string($chrs); if ($chrs == '') { if (reset($stk) == SERVICES_JSON_IN_ARR) { return $arr; } else { return $obj; } } //print("\nparsing {$chrs}\n"); $strlen_chrs = $this->strlen8($chrs); for ($c = 0; $c <= $strlen_chrs; ++$c) { $top = end($stk); $substr_chrs_c_2 = $this->substr8($chrs, $c, 2); if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) { // found a comma that is not inside a string, array, etc., // OR we've reached the end of the character list $slice = $this->substr8($chrs, $top['where'], ($c - $top['where'])); array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false)); //print("Found split at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n"); if (reset($stk) == SERVICES_JSON_IN_ARR) { // we are in an array, so just push an element onto the stack array_push($arr, $this->decode($slice)); } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { // we are in an object, so figure // out the property name and set an // element in an associative array, // for now $parts = array(); if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:/Uis', $slice, $parts)) { // "name":value pair $key = $this->decode($parts[1]); $val = $this->decode(trim(substr($slice, strlen($parts[0])), ", \t\n\r\0\x0B")); if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $obj[$key] = $val; } else { $obj->$key = $val; } } elseif (preg_match('/^\s*(\w+)\s*:/Uis', $slice, $parts)) { // name:value pair, where name is unquoted $key = $parts[1]; $val = $this->decode(trim(substr($slice, strlen($parts[0])), ", \t\n\r\0\x0B")); if ($this->use & SERVICES_JSON_LOOSE_TYPE) { $obj[$key] = $val; } else { $obj->$key = $val; } } } } elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) { // found a quote, and we are not inside a string array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c})); //print("Found start of string at {$c}\n"); } elseif (($chrs{$c} == $top['delim']) && ($top['what'] == SERVICES_JSON_IN_STR) && (($this->strlen8($this->substr8($chrs, 0, $c)) - $this->strlen8(rtrim($this->substr8($chrs, 0, $c), '\\'))) % 2 != 1)) { // found a quote, we're in a string, and it's not escaped // we know that it's not escaped becase there is _not_ an // odd number of backslashes at the end of the string so far array_pop($stk); //print("Found end of string at {$c}: ".$this->substr8($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n"); } elseif (($chrs{$c} == '[') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a left-bracket, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false)); //print("Found start of array at {$c}\n"); } elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) { // found a right-bracket, and we're in an array array_pop($stk); //print("Found end of array at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } elseif (($chrs{$c} == '{') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a left-brace, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false)); //print("Found start of object at {$c}\n"); } elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) { // found a right-brace, and we're in an object array_pop($stk); //print("Found end of object at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } elseif (($substr_chrs_c_2 == '/*') && in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) { // found a comment start, and we are in an array, object, or slice array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false)); $c++; //print("Found start of comment at {$c}\n"); } elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) { // found a comment end, and we're in one now array_pop($stk); $c++; for ($i = $top['where']; $i <= $c; ++$i) $chrs = substr_replace($chrs, ' ', $i, 1); //print("Found end of comment at {$c}: ".$this->substr8($chrs, $top['where'], (1 + $c - $top['where']))."\n"); } } if (reset($stk) == SERVICES_JSON_IN_ARR) { return $arr; } elseif (reset($stk) == SERVICES_JSON_IN_OBJ) { return $obj; } } } } /** * @todo Ultimately, this should just call PEAR::isError() */ function isError($data, $code = null) { if (class_exists('pear')) { return PEAR::isError($data, $code); } elseif (is_object($data) && (get_class($data) == 'services_json_error' || is_subclass_of($data, 'services_json_error'))) { return true; } return false; } /** * Calculates length of string in bytes * @param string * @return integer length */ function strlen8( $str ) { if ( $this->_mb_strlen ) { return mb_strlen( $str, "8bit" ); } return strlen( $str ); } /** * Returns part of a string, interpreting $start and $length as number of bytes. * @param string * @param integer start * @param integer length * @return integer length */ function substr8( $string, $start, $length=false ) { if ( $length === false ) { $length = $this->strlen8( $string ) - $start; } if ( $this->_mb_substr ) { return mb_substr( $string, $start, $length, "8bit" ); } return substr( $string, $start, $length ); } } if (class_exists('PEAR_Error')) { class Services_JSON_Error extends PEAR_Error { function Services_JSON_Error($message = 'unknown error', $code = null, $mode = null, $options = null, $userinfo = null) { parent::PEAR_Error($message, $code, $mode, $options, $userinfo); } } } else { /** * @todo Ultimately, this class shall be descended from PEAR_Error */ class Services_JSON_Error { function Services_JSON_Error($message = 'unknown error', $code = null, $mode = null, $options = null, $userinfo = null) { } } } endif;
01-wordpress-paypal
trunk/wp-includes/class-json.php
PHP
gpl3
39,729
<?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.0 */ /** * 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($parser)), xml_get_current_line_number($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 ); } }
01-wordpress-paypal
trunk/wp-includes/atomlib.php
PHP
gpl3
10,918
<?php /** * Taxonomy API * * @package WordPress * @subpackage Taxonomy * @since 2.3.0 */ // // Taxonomy Registration // /** * Creates the initial taxonomies. * * This function fires twice: in wp-settings.php before plugins are loaded (for * backwards compatibility reasons), and again on the 'init' action. We must avoid * registering rewrite rules before the 'init' action. */ function create_initial_taxonomies() { global $wp_rewrite; if ( ! did_action( 'init' ) ) { $rewrite = array( 'category' => false, 'post_tag' => false, 'post_format' => false ); } else { /** * Filter the post formats rewrite base. * * @since 3.1.0 * * @param string $context Context of the rewrite base. Default 'type'. */ $post_format_base = apply_filters( 'post_format_rewrite_base', 'type' ); $rewrite = array( 'category' => array( 'hierarchical' => true, 'slug' => get_option('category_base') ? get_option('category_base') : 'category', 'with_front' => ! get_option('category_base') || $wp_rewrite->using_index_permalinks(), 'ep_mask' => EP_CATEGORIES, ), 'post_tag' => array( 'slug' => get_option('tag_base') ? get_option('tag_base') : 'tag', 'with_front' => ! get_option('tag_base') || $wp_rewrite->using_index_permalinks(), 'ep_mask' => EP_TAGS, ), 'post_format' => $post_format_base ? array( 'slug' => $post_format_base ) : false, ); } register_taxonomy( 'category', 'post', array( 'hierarchical' => true, 'query_var' => 'category_name', 'rewrite' => $rewrite['category'], 'public' => true, 'show_ui' => true, 'show_admin_column' => true, '_builtin' => true, ) ); register_taxonomy( 'post_tag', 'post', array( 'hierarchical' => false, 'query_var' => 'tag', 'rewrite' => $rewrite['post_tag'], 'public' => true, 'show_ui' => true, 'show_admin_column' => true, '_builtin' => true, ) ); register_taxonomy( 'nav_menu', 'nav_menu_item', array( 'public' => false, 'hierarchical' => false, 'labels' => array( 'name' => __( 'Navigation Menus' ), 'singular_name' => __( 'Navigation Menu' ), ), 'query_var' => false, 'rewrite' => false, 'show_ui' => false, '_builtin' => true, 'show_in_nav_menus' => false, ) ); register_taxonomy( 'link_category', 'link', array( 'hierarchical' => false, 'labels' => array( 'name' => __( 'Link Categories' ), 'singular_name' => __( 'Link Category' ), 'search_items' => __( 'Search Link Categories' ), 'popular_items' => null, 'all_items' => __( 'All Link Categories' ), 'edit_item' => __( 'Edit Link Category' ), 'update_item' => __( 'Update Link Category' ), 'add_new_item' => __( 'Add New Link Category' ), 'new_item_name' => __( 'New Link Category Name' ), 'separate_items_with_commas' => null, 'add_or_remove_items' => null, 'choose_from_most_used' => null, ), 'capabilities' => array( 'manage_terms' => 'manage_links', 'edit_terms' => 'manage_links', 'delete_terms' => 'manage_links', 'assign_terms' => 'manage_links', ), 'query_var' => false, 'rewrite' => false, 'public' => false, 'show_ui' => false, '_builtin' => true, ) ); register_taxonomy( 'post_format', 'post', array( 'public' => true, 'hierarchical' => false, 'labels' => array( 'name' => _x( 'Format', 'post format' ), 'singular_name' => _x( 'Format', 'post format' ), ), 'query_var' => true, 'rewrite' => $rewrite['post_format'], 'show_ui' => false, '_builtin' => true, 'show_in_nav_menus' => current_theme_supports( 'post-formats' ), ) ); } add_action( 'init', 'create_initial_taxonomies', 0 ); // highest priority /** * Get a list of registered taxonomy objects. * * @since 3.0.0 * @uses $wp_taxonomies * @see register_taxonomy * * @param array $args An array of key => value arguments to match against the taxonomy objects. * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default. * @param string $operator The logical operation to perform. 'or' means only one element * from the array needs to match; 'and' means all elements must match. The default is 'and'. * @return array A list of taxonomy names or objects */ function get_taxonomies( $args = array(), $output = 'names', $operator = 'and' ) { global $wp_taxonomies; $field = ('names' == $output) ? 'name' : false; return wp_filter_object_list($wp_taxonomies, $args, $operator, $field); } /** * Return all of the taxonomy names that are of $object_type. * * It appears that this function can be used to find all of the names inside of * $wp_taxonomies global variable. * * <code><?php $taxonomies = get_object_taxonomies('post'); ?></code> Should * result in <code>Array('category', 'post_tag')</code> * * @since 2.3.0 * * @uses $wp_taxonomies * * @param array|string|object $object Name of the type of taxonomy object, or an object (row from posts) * @param string $output The type of output to return, either taxonomy 'names' or 'objects'. 'names' is the default. * @return array The names of all taxonomy of $object_type. */ function get_object_taxonomies($object, $output = 'names') { global $wp_taxonomies; if ( is_object($object) ) { if ( $object->post_type == 'attachment' ) return get_attachment_taxonomies($object); $object = $object->post_type; } $object = (array) $object; $taxonomies = array(); foreach ( (array) $wp_taxonomies as $tax_name => $tax_obj ) { if ( array_intersect($object, (array) $tax_obj->object_type) ) { if ( 'names' == $output ) $taxonomies[] = $tax_name; else $taxonomies[ $tax_name ] = $tax_obj; } } return $taxonomies; } /** * Retrieves the taxonomy object of $taxonomy. * * The get_taxonomy function will first check that the parameter string given * is a taxonomy object and if it is, it will return it. * * @since 2.3.0 * * @uses $wp_taxonomies * @uses taxonomy_exists() Checks whether taxonomy exists * * @param string $taxonomy Name of taxonomy object to return * @return object|bool The Taxonomy Object or false if $taxonomy doesn't exist */ function get_taxonomy( $taxonomy ) { global $wp_taxonomies; if ( ! taxonomy_exists( $taxonomy ) ) return false; return $wp_taxonomies[$taxonomy]; } /** * Checks that the taxonomy name exists. * * Formerly is_taxonomy(), introduced in 2.3.0. * * @since 3.0.0 * * @uses $wp_taxonomies * * @param string $taxonomy Name of taxonomy object * @return bool Whether the taxonomy exists. */ function taxonomy_exists( $taxonomy ) { global $wp_taxonomies; return isset( $wp_taxonomies[$taxonomy] ); } /** * Whether the taxonomy object is hierarchical. * * Checks to make sure that the taxonomy is an object first. Then Gets the * object, and finally returns the hierarchical value in the object. * * A false return value might also mean that the taxonomy does not exist. * * @since 2.3.0 * * @uses taxonomy_exists() Checks whether taxonomy exists * @uses get_taxonomy() Used to get the taxonomy object * * @param string $taxonomy Name of taxonomy object * @return bool Whether the taxonomy is hierarchical */ function is_taxonomy_hierarchical($taxonomy) { if ( ! taxonomy_exists($taxonomy) ) return false; $taxonomy = get_taxonomy($taxonomy); return $taxonomy->hierarchical; } /** * Create or modify a taxonomy object. Do not use before init. * * A simple function for creating or modifying a taxonomy object based on the * parameters given. The function will accept an array (third optional * parameter), along with strings for the taxonomy name and another string for * the object type. * * Nothing is returned, so expect error maybe or use taxonomy_exists() to check * whether taxonomy exists. * * Optional $args contents: * * - label - Name of the taxonomy shown in the menu. Usually plural. If not set, labels['name'] will be used. * - labels - An array of labels for this taxonomy. * * By default tag labels are used for non-hierarchical types and category labels for hierarchical ones. * * You can see accepted values in {@link get_taxonomy_labels()}. * - description - A short descriptive summary of what the taxonomy is for. Defaults to blank. * - public - If the taxonomy should be publicly queryable; //@TODO not implemented. * * Defaults to true. * - hierarchical - Whether the taxonomy is hierarchical (e.g. category). Defaults to false. * - show_ui -Whether to generate a default UI for managing this taxonomy in the admin. * * If not set, the default is inherited from public. * - show_in_menu - Where to show the taxonomy in the admin menu. * * If true, the taxonomy is shown as a submenu of the object type menu. * * If false, no menu is shown. * * show_ui must be true. * * If not set, the default is inherited from show_ui. * - show_in_nav_menus - Makes this taxonomy available for selection in navigation menus. * * If not set, the default is inherited from public. * - show_tagcloud - Whether to list the taxonomy in the Tag Cloud Widget. * * If not set, the default is inherited from show_ui. * - show_admin_column - Whether to display a column for the taxonomy on its post type listing screens. * * Defaults to false. * - meta_box_cb - Provide a callback function for the meta box display. * * If not set, defaults to post_categories_meta_box for hierarchical taxonomies * and post_tags_meta_box for non-hierarchical. * * If false, no meta box is shown. * - capabilities - Array of capabilities for this taxonomy. * * You can see accepted values in this function. * - rewrite - Triggers the handling of rewrites for this taxonomy. Defaults to true, using $taxonomy as slug. * * To prevent rewrite, set to false. * * To specify rewrite rules, an array can be passed with any of these keys * * 'slug' => string Customize the permastruct slug. Defaults to $taxonomy key * * 'with_front' => bool Should the permastruct be prepended with WP_Rewrite::$front. Defaults to true. * * 'hierarchical' => bool Either hierarchical rewrite tag or not. Defaults to false. * * 'ep_mask' => const Assign an endpoint mask. * * If not specified, defaults to EP_NONE. * - query_var - Sets the query_var key for this taxonomy. Defaults to $taxonomy key * * If false, a taxonomy cannot be loaded at ?{query_var}={term_slug} * * If specified as a string, the query ?{query_var_string}={term_slug} will be valid. * - update_count_callback - Works much like a hook, in that it will be called when the count is updated. * * Defaults to _update_post_term_count() for taxonomies attached to post types, which then confirms * that the objects are published before counting them. * * Defaults to _update_generic_term_count() for taxonomies attached to other object types, such as links. * - _builtin - true if this taxonomy is a native or "built-in" taxonomy. THIS IS FOR INTERNAL USE ONLY! * * @since 2.3.0 * @uses $wp_taxonomies Inserts new taxonomy object into the list * @uses $wp Adds query vars * * @param string $taxonomy Taxonomy key, must not exceed 32 characters. * @param array|string $object_type Name of the object type for the taxonomy object. * @param array|string $args See optional args description above. * @return null|WP_Error WP_Error if errors, otherwise null. */ function register_taxonomy( $taxonomy, $object_type, $args = array() ) { global $wp_taxonomies, $wp; if ( ! is_array( $wp_taxonomies ) ) $wp_taxonomies = array(); $defaults = array( 'labels' => array(), 'description' => '', 'public' => true, 'hierarchical' => false, 'show_ui' => null, 'show_in_menu' => null, 'show_in_nav_menus' => null, 'show_tagcloud' => null, 'show_admin_column' => false, 'meta_box_cb' => null, 'capabilities' => array(), 'rewrite' => true, 'query_var' => $taxonomy, 'update_count_callback' => '', '_builtin' => false, ); $args = wp_parse_args( $args, $defaults ); if ( strlen( $taxonomy ) > 32 ) return new WP_Error( 'taxonomy_too_long', __( 'Taxonomies cannot exceed 32 characters in length' ) ); if ( false !== $args['query_var'] && ! empty( $wp ) ) { if ( true === $args['query_var'] ) $args['query_var'] = $taxonomy; else $args['query_var'] = sanitize_title_with_dashes( $args['query_var'] ); $wp->add_query_var( $args['query_var'] ); } if ( false !== $args['rewrite'] && ( is_admin() || '' != get_option( 'permalink_structure' ) ) ) { $args['rewrite'] = wp_parse_args( $args['rewrite'], array( 'with_front' => true, 'hierarchical' => false, 'ep_mask' => EP_NONE, ) ); if ( empty( $args['rewrite']['slug'] ) ) $args['rewrite']['slug'] = sanitize_title_with_dashes( $taxonomy ); if ( $args['hierarchical'] && $args['rewrite']['hierarchical'] ) $tag = '(.+?)'; else $tag = '([^/]+)'; add_rewrite_tag( "%$taxonomy%", $tag, $args['query_var'] ? "{$args['query_var']}=" : "taxonomy=$taxonomy&term=" ); add_permastruct( $taxonomy, "{$args['rewrite']['slug']}/%$taxonomy%", $args['rewrite'] ); } // If not set, default to the setting for public. if ( null === $args['show_ui'] ) $args['show_ui'] = $args['public']; // If not set, default to the setting for show_ui. if ( null === $args['show_in_menu' ] || ! $args['show_ui'] ) $args['show_in_menu' ] = $args['show_ui']; // If not set, default to the setting for public. if ( null === $args['show_in_nav_menus'] ) $args['show_in_nav_menus'] = $args['public']; // If not set, default to the setting for show_ui. if ( null === $args['show_tagcloud'] ) $args['show_tagcloud'] = $args['show_ui']; $default_caps = array( 'manage_terms' => 'manage_categories', 'edit_terms' => 'manage_categories', 'delete_terms' => 'manage_categories', 'assign_terms' => 'edit_posts', ); $args['cap'] = (object) array_merge( $default_caps, $args['capabilities'] ); unset( $args['capabilities'] ); $args['name'] = $taxonomy; $args['object_type'] = array_unique( (array) $object_type ); $args['labels'] = get_taxonomy_labels( (object) $args ); $args['label'] = $args['labels']->name; // If not set, use the default meta box if ( null === $args['meta_box_cb'] ) { if ( $args['hierarchical'] ) $args['meta_box_cb'] = 'post_categories_meta_box'; else $args['meta_box_cb'] = 'post_tags_meta_box'; } $wp_taxonomies[ $taxonomy ] = (object) $args; // register callback handling for metabox add_filter( 'wp_ajax_add-' . $taxonomy, '_wp_ajax_add_hierarchical_term' ); /** * Fires after a taxonomy is registered. * * @since 3.3.0 * * @param string $taxonomy Taxonomy slug. * @param array|string $object_type Object type or array of object types. * @param array|string $args Array or string of taxonomy registration arguments. */ do_action( 'registered_taxonomy', $taxonomy, $object_type, $args ); } /** * Builds an object with all taxonomy labels out of a taxonomy object * * Accepted keys of the label array in the taxonomy object: * - name - general name for the taxonomy, usually plural. The same as and overridden by $tax->label. Default is Tags/Categories * - singular_name - name for one object of this taxonomy. Default is Tag/Category * - search_items - Default is Search Tags/Search Categories * - popular_items - This string isn't used on hierarchical taxonomies. Default is Popular Tags * - all_items - Default is All Tags/All Categories * - parent_item - This string isn't used on non-hierarchical taxonomies. In hierarchical ones the default is Parent Category * - parent_item_colon - The same as <code>parent_item</code>, but with colon <code>:</code> in the end * - edit_item - Default is Edit Tag/Edit Category * - view_item - Default is View Tag/View Category * - update_item - Default is Update Tag/Update Category * - add_new_item - Default is Add New Tag/Add New Category * - new_item_name - Default is New Tag Name/New Category Name * - separate_items_with_commas - This string isn't used on hierarchical taxonomies. Default is "Separate tags with commas", used in the meta box. * - add_or_remove_items - This string isn't used on hierarchical taxonomies. Default is "Add or remove tags", used in the meta box when JavaScript is disabled. * - choose_from_most_used - This string isn't used on hierarchical taxonomies. Default is "Choose from the most used tags", used in the meta box. * - not_found - This string isn't used on hierarchical taxonomies. Default is "No tags found", used in the meta box. * * Above, the first default value is for non-hierarchical taxonomies (like tags) and the second one is for hierarchical taxonomies (like categories). * * @since 3.0.0 * @param object $tax Taxonomy object * @return object object with all the labels as member variables */ function get_taxonomy_labels( $tax ) { $tax->labels = (array) $tax->labels; if ( isset( $tax->helps ) && empty( $tax->labels['separate_items_with_commas'] ) ) $tax->labels['separate_items_with_commas'] = $tax->helps; if ( isset( $tax->no_tagcloud ) && empty( $tax->labels['not_found'] ) ) $tax->labels['not_found'] = $tax->no_tagcloud; $nohier_vs_hier_defaults = array( 'name' => array( _x( 'Tags', 'taxonomy general name' ), _x( 'Categories', 'taxonomy general name' ) ), 'singular_name' => array( _x( 'Tag', 'taxonomy singular name' ), _x( 'Category', 'taxonomy singular name' ) ), 'search_items' => array( __( 'Search Tags' ), __( 'Search Categories' ) ), 'popular_items' => array( __( 'Popular Tags' ), null ), 'all_items' => array( __( 'All Tags' ), __( 'All Categories' ) ), 'parent_item' => array( null, __( 'Parent Category' ) ), 'parent_item_colon' => array( null, __( 'Parent Category:' ) ), 'edit_item' => array( __( 'Edit Tag' ), __( 'Edit Category' ) ), 'view_item' => array( __( 'View Tag' ), __( 'View Category' ) ), 'update_item' => array( __( 'Update Tag' ), __( 'Update Category' ) ), 'add_new_item' => array( __( 'Add New Tag' ), __( 'Add New Category' ) ), 'new_item_name' => array( __( 'New Tag Name' ), __( 'New Category Name' ) ), 'separate_items_with_commas' => array( __( 'Separate tags with commas' ), null ), 'add_or_remove_items' => array( __( 'Add or remove tags' ), null ), 'choose_from_most_used' => array( __( 'Choose from the most used tags' ), null ), 'not_found' => array( __( 'No tags found.' ), null ), ); $nohier_vs_hier_defaults['menu_name'] = $nohier_vs_hier_defaults['name']; return _get_custom_object_labels( $tax, $nohier_vs_hier_defaults ); } /** * Add an already registered taxonomy to an object type. * * @since 3.0.0 * @uses $wp_taxonomies Modifies taxonomy object * * @param string $taxonomy Name of taxonomy object * @param string $object_type Name of the object type * @return bool True if successful, false if not */ function register_taxonomy_for_object_type( $taxonomy, $object_type) { global $wp_taxonomies; if ( !isset($wp_taxonomies[$taxonomy]) ) return false; if ( ! get_post_type_object($object_type) ) return false; if ( ! in_array( $object_type, $wp_taxonomies[$taxonomy]->object_type ) ) $wp_taxonomies[$taxonomy]->object_type[] = $object_type; return true; } /** * Remove an already registered taxonomy from an object type. * * @since 3.7.0 * * @param string $taxonomy Name of taxonomy object. * @param string $object_type Name of the object type. * @return bool True if successful, false if not. */ function unregister_taxonomy_for_object_type( $taxonomy, $object_type ) { global $wp_taxonomies; if ( ! isset( $wp_taxonomies[ $taxonomy ] ) ) return false; if ( ! get_post_type_object( $object_type ) ) return false; $key = array_search( $object_type, $wp_taxonomies[ $taxonomy ]->object_type, true ); if ( false === $key ) return false; unset( $wp_taxonomies[ $taxonomy ]->object_type[ $key ] ); return true; } // // Term API // /** * Retrieve object_ids of valid taxonomy and term. * * The strings of $taxonomies must exist before this function will continue. On * failure of finding a valid taxonomy, it will return an WP_Error class, kind * of like Exceptions in PHP 5, except you can't catch them. Even so, you can * still test for the WP_Error class and get the error message. * * The $terms aren't checked the same as $taxonomies, but still need to exist * for $object_ids to be returned. * * It is possible to change the order that object_ids is returned by either * using PHP sort family functions or using the database by using $args with * either ASC or DESC array. The value should be in the key named 'order'. * * @since 2.3.0 * * @uses $wpdb * @uses wp_parse_args() Creates an array from string $args. * * @param int|array $term_ids Term id or array of term ids of terms that will be used * @param string|array $taxonomies String of taxonomy name or Array of string values of taxonomy names * @param array|string $args Change the order of the object_ids, either ASC or DESC * @return WP_Error|array If the taxonomy does not exist, then WP_Error will be returned. On success * the array can be empty meaning that there are no $object_ids found or it will return the $object_ids found. */ function get_objects_in_term( $term_ids, $taxonomies, $args = array() ) { global $wpdb; if ( ! is_array( $term_ids ) ) $term_ids = array( $term_ids ); if ( ! is_array( $taxonomies ) ) $taxonomies = array( $taxonomies ); foreach ( (array) $taxonomies as $taxonomy ) { if ( ! taxonomy_exists( $taxonomy ) ) return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy' ) ); } $defaults = array( 'order' => 'ASC' ); $args = wp_parse_args( $args, $defaults ); extract( $args, EXTR_SKIP ); $order = ( 'desc' == strtolower( $order ) ) ? 'DESC' : 'ASC'; $term_ids = array_map('intval', $term_ids ); $taxonomies = "'" . implode( "', '", $taxonomies ) . "'"; $term_ids = "'" . implode( "', '", $term_ids ) . "'"; $object_ids = $wpdb->get_col("SELECT tr.object_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tt.term_id IN ($term_ids) ORDER BY tr.object_id $order"); if ( ! $object_ids ) return array(); return $object_ids; } /** * Given a taxonomy query, generates SQL to be appended to a main query. * * @since 3.1.0 * * @see WP_Tax_Query * * @param array $tax_query A compact tax query * @param string $primary_table * @param string $primary_id_column * @return array */ function get_tax_sql( $tax_query, $primary_table, $primary_id_column ) { $tax_query_obj = new WP_Tax_Query( $tax_query ); return $tax_query_obj->get_sql( $primary_table, $primary_id_column ); } /** * Container class for a multiple taxonomy query. * * @since 3.1.0 */ class WP_Tax_Query { /** * List of taxonomy queries. A single taxonomy query is an associative array: * - 'taxonomy' string The taxonomy being queried * - 'terms' string|array The list of terms * - 'field' string (optional) Which term field is being used. * Possible values: 'term_id', 'slug' or 'name' * Default: 'term_id' * - 'operator' string (optional) * Possible values: 'AND', 'IN' or 'NOT IN'. * Default: 'IN' * - 'include_children' bool (optional) Whether to include child terms. * Default: true * * @since 3.1.0 * @access public * @var array */ public $queries = array(); /** * The relation between the queries. Can be one of 'AND' or 'OR'. * * @since 3.1.0 * @access public * @var string */ public $relation; /** * Standard response when the query should not return any rows. * * @since 3.2.0 * @access private * @var string */ private static $no_results = array( 'join' => '', 'where' => ' AND 0 = 1' ); /** * Constructor. * * Parses a compact tax query and sets defaults. * * @since 3.1.0 * @access public * * @param array $tax_query A compact tax query: * array( * 'relation' => 'OR', * array( * 'taxonomy' => 'tax1', * 'terms' => array( 'term1', 'term2' ), * 'field' => 'slug', * ), * array( * 'taxonomy' => 'tax2', * 'terms' => array( 'term-a', 'term-b' ), * 'field' => 'slug', * ), * ) */ public function __construct( $tax_query ) { if ( isset( $tax_query['relation'] ) && strtoupper( $tax_query['relation'] ) == 'OR' ) { $this->relation = 'OR'; } else { $this->relation = 'AND'; } $defaults = array( 'taxonomy' => '', 'terms' => array(), 'include_children' => true, 'field' => 'term_id', 'operator' => 'IN', ); foreach ( $tax_query as $query ) { if ( ! is_array( $query ) ) continue; $query = array_merge( $defaults, $query ); $query['terms'] = (array) $query['terms']; $this->queries[] = $query; } } /** * Generates SQL clauses to be appended to a main query. * * @since 3.1.0 * @access public * * @param string $primary_table * @param string $primary_id_column * @return array */ public function get_sql( $primary_table, $primary_id_column ) { global $wpdb; $join = ''; $where = array(); $i = 0; $count = count( $this->queries ); foreach ( $this->queries as $index => $query ) { $this->clean_query( $query ); if ( is_wp_error( $query ) ) return self::$no_results; extract( $query ); if ( 'IN' == $operator ) { if ( empty( $terms ) ) { if ( 'OR' == $this->relation ) { if ( ( $index + 1 === $count ) && empty( $where ) ) return self::$no_results; continue; } else { return self::$no_results; } } $terms = implode( ',', $terms ); $alias = $i ? 'tt' . $i : $wpdb->term_relationships; $join .= " INNER JOIN $wpdb->term_relationships"; $join .= $i ? " AS $alias" : ''; $join .= " ON ($primary_table.$primary_id_column = $alias.object_id)"; $where[] = "$alias.term_taxonomy_id $operator ($terms)"; } elseif ( 'NOT IN' == $operator ) { if ( empty( $terms ) ) continue; $terms = implode( ',', $terms ); $where[] = "$primary_table.$primary_id_column NOT IN ( SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id IN ($terms) )"; } elseif ( 'AND' == $operator ) { if ( empty( $terms ) ) continue; $num_terms = count( $terms ); $terms = implode( ',', $terms ); $where[] = "( SELECT COUNT(1) FROM $wpdb->term_relationships WHERE term_taxonomy_id IN ($terms) AND object_id = $primary_table.$primary_id_column ) = $num_terms"; } $i++; } if ( ! empty( $where ) ) $where = ' AND ( ' . implode( " $this->relation ", $where ) . ' )'; else $where = ''; return compact( 'join', 'where' ); } /** * Validates a single query. * * @since 3.2.0 * @access private * * @param array &$query The single query */ private function clean_query( &$query ) { if ( ! taxonomy_exists( $query['taxonomy'] ) ) { $query = new WP_Error( 'Invalid taxonomy' ); return; } $query['terms'] = array_unique( (array) $query['terms'] ); if ( is_taxonomy_hierarchical( $query['taxonomy'] ) && $query['include_children'] ) { $this->transform_query( $query, 'term_id' ); if ( is_wp_error( $query ) ) return; $children = array(); foreach ( $query['terms'] as $term ) { $children = array_merge( $children, get_term_children( $term, $query['taxonomy'] ) ); $children[] = $term; } $query['terms'] = $children; } $this->transform_query( $query, 'term_taxonomy_id' ); } /** * Transforms a single query, from one field to another. * * @since 3.2.0 * * @param array &$query The single query * @param string $resulting_field The resulting field */ public function transform_query( &$query, $resulting_field ) { global $wpdb; if ( empty( $query['terms'] ) ) return; if ( $query['field'] == $resulting_field ) return; $resulting_field = sanitize_key( $resulting_field ); switch ( $query['field'] ) { case 'slug': case 'name': $terms = "'" . implode( "','", array_map( 'sanitize_title_for_query', $query['terms'] ) ) . "'"; $terms = $wpdb->get_col( " SELECT $wpdb->term_taxonomy.$resulting_field FROM $wpdb->term_taxonomy INNER JOIN $wpdb->terms USING (term_id) WHERE taxonomy = '{$query['taxonomy']}' AND $wpdb->terms.{$query['field']} IN ($terms) " ); break; case 'term_taxonomy_id': $terms = implode( ',', array_map( 'intval', $query['terms'] ) ); $terms = $wpdb->get_col( " SELECT $resulting_field FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($terms) " ); break; default: $terms = implode( ',', array_map( 'intval', $query['terms'] ) ); $terms = $wpdb->get_col( " SELECT $resulting_field FROM $wpdb->term_taxonomy WHERE taxonomy = '{$query['taxonomy']}' AND term_id IN ($terms) " ); } if ( 'AND' == $query['operator'] && count( $terms ) < count( $query['terms'] ) ) { $query = new WP_Error( 'Inexistent terms' ); return; } $query['terms'] = $terms; $query['field'] = $resulting_field; } } /** * Get all Term data from database by Term ID. * * The usage of the get_term function is to apply filters to a term object. It * is possible to get a term object from the database before applying the * filters. * * $term ID must be part of $taxonomy, to get from the database. Failure, might * be able to be captured by the hooks. Failure would be the same value as $wpdb * returns for the get_row method. * * There are two hooks, one is specifically for each term, named 'get_term', and * the second is for the taxonomy name, 'term_$taxonomy'. Both hooks gets the * term object, and the taxonomy name as parameters. Both hooks are expected to * return a Term object. * * 'get_term' hook - Takes two parameters the term Object and the taxonomy name. * Must return term object. Used in get_term() as a catch-all filter for every * $term. * * 'get_$taxonomy' hook - Takes two parameters the term Object and the taxonomy * name. Must return term object. $taxonomy will be the taxonomy name, so for * example, if 'category', it would be 'get_category' as the filter name. Useful * for custom taxonomies or plugging into default taxonomies. * * @since 2.3.0 * * @uses $wpdb * @uses sanitize_term() Cleanses the term based on $filter context before returning. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param. * * @param int|object $term If integer, will get from database. If object will apply filters and return $term. * @param string $taxonomy Taxonomy name that $term is part of. * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N * @param string $filter Optional, default is raw or no WordPress defined filter will applied. * @return mixed|null|WP_Error Term Row from database. Will return null if $term is empty. If taxonomy does not * exist then WP_Error will be returned. */ function get_term($term, $taxonomy, $output = OBJECT, $filter = 'raw') { global $wpdb; if ( empty($term) ) { $error = new WP_Error('invalid_term', __('Empty Term')); return $error; } if ( ! taxonomy_exists($taxonomy) ) { $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy')); return $error; } if ( is_object($term) && empty($term->filter) ) { wp_cache_add($term->term_id, $term, $taxonomy); $_term = $term; } else { if ( is_object($term) ) $term = $term->term_id; if ( !$term = (int) $term ) return null; if ( ! $_term = wp_cache_get($term, $taxonomy) ) { $_term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND t.term_id = %d LIMIT 1", $taxonomy, $term) ); if ( ! $_term ) return null; wp_cache_add($term, $_term, $taxonomy); } } /** * Filter a term. * * @since 2.3.0 * * @param int|object $_term Term object or ID. * @param string $taxonomy The taxonomy slug. */ $_term = apply_filters( 'get_term', $_term, $taxonomy ); /** * Filter a taxonomy. * * The dynamic portion of the filter name, $taxonomy, refers * to the taxonomy slug. * * @since 2.3.0 * * @param int|object $_term Term object or ID. * @param string $taxonomy The taxonomy slug. */ $_term = apply_filters( "get_$taxonomy", $_term, $taxonomy ); $_term = sanitize_term($_term, $taxonomy, $filter); if ( $output == OBJECT ) { return $_term; } elseif ( $output == ARRAY_A ) { $__term = get_object_vars($_term); return $__term; } elseif ( $output == ARRAY_N ) { $__term = array_values(get_object_vars($_term)); return $__term; } else { return $_term; } } /** * Get all Term data from database by Term field and data. * * Warning: $value is not escaped for 'name' $field. You must do it yourself, if * required. * * The default $field is 'id', therefore it is possible to also use null for * field, but not recommended that you do so. * * If $value does not exist, the return value will be false. If $taxonomy exists * and $field and $value combinations exist, the Term will be returned. * * @since 2.3.0 * * @uses $wpdb * @uses sanitize_term() Cleanses the term based on $filter context before returning. * @see sanitize_term_field() The $context param lists the available values for get_term_by() $filter param. * * @param string $field Either 'slug', 'name', 'id' (term_id), or 'term_taxonomy_id' * @param string|int $value Search for this term value * @param string $taxonomy Taxonomy Name * @param string $output Constant OBJECT, ARRAY_A, or ARRAY_N * @param string $filter Optional, default is raw or no WordPress defined filter will applied. * @return mixed Term Row from database. Will return false if $taxonomy does not exist or $term was not found. */ function get_term_by($field, $value, $taxonomy, $output = OBJECT, $filter = 'raw') { global $wpdb; if ( ! taxonomy_exists($taxonomy) ) return false; if ( 'slug' == $field ) { $field = 't.slug'; $value = sanitize_title($value); if ( empty($value) ) return false; } else if ( 'name' == $field ) { // Assume already escaped $value = wp_unslash($value); $field = 't.name'; } else if ( 'term_taxonomy_id' == $field ) { $value = (int) $value; $field = 'tt.term_taxonomy_id'; } else { $term = get_term( (int) $value, $taxonomy, $output, $filter); if ( is_wp_error( $term ) ) $term = false; return $term; } $term = $wpdb->get_row( $wpdb->prepare( "SELECT t.*, tt.* FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id WHERE tt.taxonomy = %s AND $field = %s LIMIT 1", $taxonomy, $value) ); if ( !$term ) return false; wp_cache_add($term->term_id, $term, $taxonomy); /** This filter is documented in wp-includes/taxonomy.php */ $term = apply_filters( 'get_term', $term, $taxonomy ); /** This filter is documented in wp-includes/taxonomy.php */ $term = apply_filters( "get_$taxonomy", $term, $taxonomy ); $term = sanitize_term($term, $taxonomy, $filter); if ( $output == OBJECT ) { return $term; } elseif ( $output == ARRAY_A ) { return get_object_vars($term); } elseif ( $output == ARRAY_N ) { return array_values(get_object_vars($term)); } else { return $term; } } /** * Merge all term children into a single array of their IDs. * * This recursive function will merge all of the children of $term into the same * array of term IDs. Only useful for taxonomies which are hierarchical. * * Will return an empty array if $term does not exist in $taxonomy. * * @since 2.3.0 * * @uses $wpdb * @uses _get_term_hierarchy() * @uses get_term_children() Used to get the children of both $taxonomy and the parent $term * * @param string $term_id ID of Term to get children * @param string $taxonomy Taxonomy Name * @return array|WP_Error List of Term IDs. WP_Error returned if $taxonomy does not exist */ function get_term_children( $term_id, $taxonomy ) { if ( ! taxonomy_exists($taxonomy) ) return new WP_Error('invalid_taxonomy', __('Invalid taxonomy')); $term_id = intval( $term_id ); $terms = _get_term_hierarchy($taxonomy); if ( ! isset($terms[$term_id]) ) return array(); $children = $terms[$term_id]; foreach ( (array) $terms[$term_id] as $child ) { if ( $term_id == $child ) { continue; } if ( isset($terms[$child]) ) $children = array_merge($children, get_term_children($child, $taxonomy)); } return $children; } /** * Get sanitized Term field. * * Does checks for $term, based on the $taxonomy. The function is for contextual * reasons and for simplicity of usage. See sanitize_term_field() for more * information. * * @since 2.3.0 * * @uses sanitize_term_field() Passes the return value in sanitize_term_field on success. * * @param string $field Term field to fetch * @param int $term Term ID * @param string $taxonomy Taxonomy Name * @param string $context Optional, default is display. Look at sanitize_term_field() for available options. * @return mixed Will return an empty string if $term is not an object or if $field is not set in $term. */ function get_term_field( $field, $term, $taxonomy, $context = 'display' ) { $term = (int) $term; $term = get_term( $term, $taxonomy ); if ( is_wp_error($term) ) return $term; if ( !is_object($term) ) return ''; if ( !isset($term->$field) ) return ''; return sanitize_term_field($field, $term->$field, $term->term_id, $taxonomy, $context); } /** * Sanitizes Term for editing. * * Return value is sanitize_term() and usage is for sanitizing the term for * editing. Function is for contextual and simplicity. * * @since 2.3.0 * * @uses sanitize_term() Passes the return value on success * * @param int|object $id Term ID or Object * @param string $taxonomy Taxonomy Name * @return mixed|null|WP_Error Will return empty string if $term is not an object. */ function get_term_to_edit( $id, $taxonomy ) { $term = get_term( $id, $taxonomy ); if ( is_wp_error($term) ) return $term; if ( !is_object($term) ) return ''; return sanitize_term($term, $taxonomy, 'edit'); } /** * Retrieve the terms in a given taxonomy or list of taxonomies. * * You can fully inject any customizations to the query before it is sent, as * well as control the output with a filter. * * The 'get_terms' filter will be called when the cache has the term and will * pass the found term along with the array of $taxonomies and array of $args. * This filter is also called before the array of terms is passed and will pass * the array of terms, along with the $taxonomies and $args. * * The 'list_terms_exclusions' filter passes the compiled exclusions along with * the $args. * * The 'get_terms_orderby' filter passes the ORDER BY clause for the query * along with the $args array. * * The 'get_terms_fields' filter passes the fields for the SELECT query * along with the $args array. * * The list of arguments that $args can contain, which will overwrite the defaults: * * orderby - Default is 'name'. Can be name, count, term_group, slug or nothing * (will use term_id), Passing a custom value other than these will cause it to * order based on the custom value. * * order - Default is ASC. Can use DESC. * * hide_empty - Default is true. Will not return empty terms, which means * terms whose count is 0 according to the given taxonomy. * * exclude - Default is an empty array. An array, comma- or space-delimited string * of term ids to exclude from the return array. If 'include' is non-empty, * 'exclude' is ignored. * * exclude_tree - Default is an empty array. An array, comma- or space-delimited * string of term ids to exclude from the return array, along with all of their * descendant terms according to the primary taxonomy. If 'include' is non-empty, * 'exclude_tree' is ignored. * * include - Default is an empty array. An array, comma- or space-delimited string * of term ids to include in the return array. * * number - The maximum number of terms to return. Default is to return them all. * * offset - The number by which to offset the terms query. * * fields - Default is 'all', which returns an array of term objects. * If 'fields' is 'ids' or 'names', returns an array of * integers or strings, respectively. * * slug - Returns terms whose "slug" matches this value. Default is empty string. * * hierarchical - Whether to include terms that have non-empty descendants * (even if 'hide_empty' is set to true). * * search - Returned terms' names will contain the value of 'search', * case-insensitive. Default is an empty string. * * name__like - Returned terms' names will contain the value of 'name__like', * case-insensitive. Default is empty string. * * description__like - Returned terms' descriptions will contain the value of * 'description__like', case-insensitive. Default is empty string. * * The argument 'pad_counts', if set to true will include the quantity of a term's * children in the quantity of each term's "count" object variable. * * The 'get' argument, if set to 'all' instead of its default empty string, * returns terms regardless of ancestry or whether the terms are empty. * * The 'child_of' argument, when used, should be set to the integer of a term ID. Its default * is 0. If set to a non-zero value, all returned terms will be descendants * of that term according to the given taxonomy. Hence 'child_of' is set to 0 * if more than one taxonomy is passed in $taxonomies, because multiple taxonomies * make term ancestry ambiguous. * * The 'parent' argument, when used, should be set to the integer of a term ID. Its default is * the empty string '', which has a different meaning from the integer 0. * If set to an integer value, all returned terms will have as an immediate * ancestor the term whose ID is specified by that integer according to the given taxonomy. * The 'parent' argument is different from 'child_of' in that a term X is considered a 'parent' * of term Y only if term X is the father of term Y, not its grandfather or great-grandfather, etc. * * The 'cache_domain' argument enables a unique cache key to be produced when this query is stored * in object cache. For instance, if you are using one of this function's filters to modify the * query (such as 'terms_clauses'), setting 'cache_domain' to a unique value will not overwrite * the cache for similar queries. Default value is 'core'. * * @since 2.3.0 * * @uses $wpdb * @uses wp_parse_args() Merges the defaults with those defined by $args and allows for strings. * * @param string|array $taxonomies Taxonomy name or list of Taxonomy names * @param string|array $args The values of what to search for when returning terms * @return array|WP_Error List of Term Objects and their children. Will return WP_Error, if any of $taxonomies do not exist. */ function get_terms($taxonomies, $args = '') { global $wpdb; $empty_array = array(); $single_taxonomy = ! is_array( $taxonomies ) || 1 === count( $taxonomies ); if ( ! is_array( $taxonomies ) ) $taxonomies = array( $taxonomies ); foreach ( $taxonomies as $taxonomy ) { if ( ! taxonomy_exists($taxonomy) ) { $error = new WP_Error('invalid_taxonomy', __('Invalid taxonomy')); return $error; } } $defaults = array('orderby' => 'name', 'order' => 'ASC', 'hide_empty' => true, 'exclude' => array(), 'exclude_tree' => array(), 'include' => array(), 'number' => '', 'fields' => 'all', 'slug' => '', 'parent' => '', 'hierarchical' => true, 'child_of' => 0, 'get' => '', 'name__like' => '', 'description__like' => '', 'pad_counts' => false, 'offset' => '', 'search' => '', 'cache_domain' => 'core' ); $args = wp_parse_args( $args, $defaults ); $args['number'] = absint( $args['number'] ); $args['offset'] = absint( $args['offset'] ); if ( !$single_taxonomy || ! is_taxonomy_hierarchical( reset( $taxonomies ) ) || ( '' !== $args['parent'] && 0 !== $args['parent'] ) ) { $args['child_of'] = 0; $args['hierarchical'] = false; $args['pad_counts'] = false; } if ( 'all' == $args['get'] ) { $args['child_of'] = 0; $args['hide_empty'] = 0; $args['hierarchical'] = false; $args['pad_counts'] = false; } /** * Filter the terms query arguments. * * @since 3.1.0 * * @param array $args An array of arguments. * @param string|array $taxonomies A taxonomy or array of taxonomies. */ $args = apply_filters( 'get_terms_args', $args, $taxonomies ); extract($args, EXTR_SKIP); if ( $child_of ) { $hierarchy = _get_term_hierarchy( reset( $taxonomies ) ); if ( ! isset( $hierarchy[ $child_of ] ) ) return $empty_array; } if ( $parent ) { $hierarchy = _get_term_hierarchy( reset( $taxonomies ) ); if ( ! isset( $hierarchy[ $parent ] ) ) return $empty_array; } // $args can be whatever, only use the args defined in defaults to compute the key $filter_key = ( has_filter('list_terms_exclusions') ) ? serialize($GLOBALS['wp_filter']['list_terms_exclusions']) : ''; $key = md5( serialize( compact(array_keys($defaults)) ) . serialize( $taxonomies ) . $filter_key ); $last_changed = wp_cache_get( 'last_changed', 'terms' ); if ( ! $last_changed ) { $last_changed = microtime(); wp_cache_set( 'last_changed', $last_changed, 'terms' ); } $cache_key = "get_terms:$key:$last_changed"; $cache = wp_cache_get( $cache_key, 'terms' ); if ( false !== $cache ) { /** * Filter the given taxonomy's terms cache. * * @since 2.3.0 * * @param array $cache Cached array of terms for the given taxonomy. * @param string|array $taxonomies A taxonomy or array of taxonomies. * @param array $args An array of arguments to get terms. */ $cache = apply_filters( 'get_terms', $cache, $taxonomies, $args ); return $cache; } $_orderby = strtolower($orderby); if ( 'count' == $_orderby ) $orderby = 'tt.count'; else if ( 'name' == $_orderby ) $orderby = 't.name'; else if ( 'slug' == $_orderby ) $orderby = 't.slug'; else if ( 'term_group' == $_orderby ) $orderby = 't.term_group'; else if ( 'none' == $_orderby ) $orderby = ''; elseif ( empty($_orderby) || 'id' == $_orderby ) $orderby = 't.term_id'; else $orderby = 't.name'; /** * Filter the ORDERBY clause of the terms query. * * @since 2.8.0 * * @param string $orderby ORDERBY clause of the terms query. * @param array $args An array of terms query arguments. * @param string|array $taxonomies A taxonomy or array of taxonomies. */ $orderby = apply_filters( 'get_terms_orderby', $orderby, $args, $taxonomies ); if ( !empty($orderby) ) $orderby = "ORDER BY $orderby"; else $order = ''; $order = strtoupper( $order ); if ( '' !== $order && !in_array( $order, array( 'ASC', 'DESC' ) ) ) $order = 'ASC'; $where = "tt.taxonomy IN ('" . implode("', '", $taxonomies) . "')"; $inclusions = ''; if ( ! empty( $include ) ) { $exclude = ''; $exclude_tree = ''; $inclusions = implode( ',', wp_parse_id_list( $include ) ); } if ( ! empty( $inclusions ) ) { $inclusions = ' AND t.term_id IN ( ' . $inclusions . ' )'; $where .= $inclusions; } $exclusions = ''; if ( ! empty( $exclude_tree ) ) { $exclude_tree = wp_parse_id_list( $exclude_tree ); $excluded_children = $exclude_tree; foreach ( $exclude_tree as $extrunk ) { $excluded_children = array_merge( $excluded_children, (array) get_terms( $taxonomies[0], array( 'child_of' => intval( $extrunk ), 'fields' => 'ids', 'hide_empty' => 0 ) ) ); } $exclusions = implode( ',', array_map( 'intval', $excluded_children ) ); } if ( ! empty( $exclude ) ) { $exterms = wp_parse_id_list( $exclude ); if ( empty( $exclusions ) ) $exclusions = implode( ',', $exterms ); else $exclusions .= ', ' . implode( ',', $exterms ); } if ( ! empty( $exclusions ) ) $exclusions = ' AND t.term_id NOT IN (' . $exclusions . ')'; /** * Filter the terms to exclude from the terms query. * * @since 2.3.0 * * @param string $exclusions NOT IN clause of the terms query. * @param array $args An array of terms query arguments. * @param string|array $taxonomies A taxonomy or array of taxonomies. */ $exclusions = apply_filters( 'list_terms_exclusions', $exclusions, $args, $taxonomies ); if ( ! empty( $exclusions ) ) $where .= $exclusions; if ( !empty($slug) ) { $slug = sanitize_title($slug); $where .= " AND t.slug = '$slug'"; } if ( !empty($name__like) ) { $name__like = like_escape( $name__like ); $where .= $wpdb->prepare( " AND t.name LIKE %s", '%' . $name__like . '%' ); } if ( ! empty( $description__like ) ) { $description__like = like_escape( $description__like ); $where .= $wpdb->prepare( " AND tt.description LIKE %s", '%' . $description__like . '%' ); } if ( '' !== $parent ) { $parent = (int) $parent; $where .= " AND tt.parent = '$parent'"; } if ( 'count' == $fields ) $hierarchical = false; if ( $hide_empty && !$hierarchical ) $where .= ' AND tt.count > 0'; // don't limit the query results when we have to descend the family tree if ( $number && ! $hierarchical && ! $child_of && '' === $parent ) { if ( $offset ) $limits = 'LIMIT ' . $offset . ',' . $number; else $limits = 'LIMIT ' . $number; } else { $limits = ''; } if ( ! empty( $search ) ) { $search = like_escape( $search ); $where .= $wpdb->prepare( ' AND ((t.name LIKE %s) OR (t.slug LIKE %s))', '%' . $search . '%', '%' . $search . '%' ); } $selects = array(); switch ( $fields ) { case 'all': $selects = array( 't.*', 'tt.*' ); break; case 'ids': case 'id=>parent': $selects = array( 't.term_id', 'tt.parent', 'tt.count' ); break; case 'names': $selects = array( 't.term_id', 'tt.parent', 'tt.count', 't.name' ); break; case 'count': $orderby = ''; $order = ''; $selects = array( 'COUNT(*)' ); break; case 'id=>name': $selects = array( 't.term_id', 't.name' ); break; case 'id=>slug': $selects = array( 't.term_id', 't.slug' ); break; } $_fields = $fields; /** * Filter the fields to select in the terms query. * * @since 2.8.0 * * @param array $selects An array of fields to select for the terms query. * @param array $args An array of term query arguments. * @param string|array $taxonomies A taxonomy or array of taxonomies. */ $fields = implode( ', ', apply_filters( 'get_terms_fields', $selects, $args, $taxonomies ) ); $join = "INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id"; $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' ); /** * Filter the terms query SQL clauses. * * @since 3.1.0 * * @param array $pieces Terms query SQL clauses. * @param string|array $taxonomies A taxonomy or array of taxonomies. * @param array $args An array of terms query arguments. */ $clauses = apply_filters( 'terms_clauses', compact( $pieces ), $taxonomies, $args ); foreach ( $pieces as $piece ) $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : ''; $query = "SELECT $fields FROM $wpdb->terms AS t $join WHERE $where $orderby $order $limits"; $fields = $_fields; if ( 'count' == $fields ) { $term_count = $wpdb->get_var($query); return $term_count; } $terms = $wpdb->get_results($query); if ( 'all' == $fields ) { update_term_cache($terms); } if ( empty($terms) ) { wp_cache_add( $cache_key, array(), 'terms', DAY_IN_SECONDS ); /** This filter is documented in wp-includes/taxonomy.php */ $terms = apply_filters( 'get_terms', array(), $taxonomies, $args ); return $terms; } if ( $child_of ) { $children = _get_term_hierarchy( reset( $taxonomies ) ); if ( ! empty( $children ) ) $terms = _get_term_children( $child_of, $terms, reset( $taxonomies ) ); } // Update term counts to include children. if ( $pad_counts && 'all' == $fields ) _pad_term_counts( $terms, reset( $taxonomies ) ); // Make sure we show empty categories that have children. if ( $hierarchical && $hide_empty && is_array( $terms ) ) { foreach ( $terms as $k => $term ) { if ( ! $term->count ) { $children = get_term_children( $term->term_id, reset( $taxonomies ) ); if ( is_array( $children ) ) { foreach ( $children as $child_id ) { $child = get_term( $child_id, reset( $taxonomies ) ); if ( $child->count ) { continue 2; } } } // It really is empty unset($terms[$k]); } } } reset( $terms ); $_terms = array(); if ( 'id=>parent' == $fields ) { while ( $term = array_shift( $terms ) ) $_terms[$term->term_id] = $term->parent; } elseif ( 'ids' == $fields ) { while ( $term = array_shift( $terms ) ) $_terms[] = $term->term_id; } elseif ( 'names' == $fields ) { while ( $term = array_shift( $terms ) ) $_terms[] = $term->name; } elseif ( 'id=>name' == $fields ) { while ( $term = array_shift( $terms ) ) $_terms[$term->term_id] = $term->name; } elseif ( 'id=>slug' == $fields ) { while ( $term = array_shift( $terms ) ) $_terms[$term->term_id] = $term->slug; } if ( ! empty( $_terms ) ) $terms = $_terms; if ( $number && is_array( $terms ) && count( $terms ) > $number ) $terms = array_slice( $terms, $offset, $number ); wp_cache_add( $cache_key, $terms, 'terms', DAY_IN_SECONDS ); /** This filter is documented in wp-includes/taxonomy */ $terms = apply_filters( 'get_terms', $terms, $taxonomies, $args ); return $terms; } /** * Check if Term exists. * * Formerly is_term(), introduced in 2.3.0. * * @since 3.0.0 * * @uses $wpdb * * @param int|string $term The term to check * @param string $taxonomy The taxonomy name to use * @param int $parent ID of parent term under which to confine the exists search. * @return mixed Returns 0 if the term does not exist. Returns the term ID if no taxonomy is specified * and the term ID exists. Returns an array of the term ID and the taxonomy if the pairing exists. */ function term_exists($term, $taxonomy = '', $parent = 0) { global $wpdb; $select = "SELECT term_id FROM $wpdb->terms as t WHERE "; $tax_select = "SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE "; if ( is_int($term) ) { if ( 0 == $term ) return 0; $where = 't.term_id = %d'; if ( !empty($taxonomy) ) return $wpdb->get_row( $wpdb->prepare( $tax_select . $where . " AND tt.taxonomy = %s", $term, $taxonomy ), ARRAY_A ); else return $wpdb->get_var( $wpdb->prepare( $select . $where, $term ) ); } $term = trim( wp_unslash( $term ) ); if ( '' === $slug = sanitize_title($term) ) return 0; $where = 't.slug = %s'; $else_where = 't.name = %s'; $where_fields = array($slug); $else_where_fields = array($term); if ( !empty($taxonomy) ) { $parent = (int) $parent; if ( $parent > 0 ) { $where_fields[] = $parent; $else_where_fields[] = $parent; $where .= ' AND tt.parent = %d'; $else_where .= ' AND tt.parent = %d'; } $where_fields[] = $taxonomy; $else_where_fields[] = $taxonomy; if ( $result = $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $where AND tt.taxonomy = %s", $where_fields), ARRAY_A) ) return $result; return $wpdb->get_row( $wpdb->prepare("SELECT tt.term_id, tt.term_taxonomy_id FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy as tt ON tt.term_id = t.term_id WHERE $else_where AND tt.taxonomy = %s", $else_where_fields), ARRAY_A); } if ( $result = $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $where", $where_fields) ) ) return $result; return $wpdb->get_var( $wpdb->prepare("SELECT term_id FROM $wpdb->terms as t WHERE $else_where", $else_where_fields) ); } /** * Check if a term is an ancestor of another term. * * You can use either an id or the term object for both parameters. * * @since 3.4.0 * * @param int|object $term1 ID or object to check if this is the parent term. * @param int|object $term2 The child term. * @param string $taxonomy Taxonomy name that $term1 and $term2 belong to. * @return bool Whether $term2 is child of $term1 */ function term_is_ancestor_of( $term1, $term2, $taxonomy ) { if ( ! isset( $term1->term_id ) ) $term1 = get_term( $term1, $taxonomy ); if ( ! isset( $term2->parent ) ) $term2 = get_term( $term2, $taxonomy ); if ( empty( $term1->term_id ) || empty( $term2->parent ) ) return false; if ( $term2->parent == $term1->term_id ) return true; return term_is_ancestor_of( $term1, get_term( $term2->parent, $taxonomy ), $taxonomy ); } /** * Sanitize Term all fields. * * Relies on sanitize_term_field() to sanitize the term. The difference is that * this function will sanitize <strong>all</strong> fields. The context is based * on sanitize_term_field(). * * The $term is expected to be either an array or an object. * * @since 2.3.0 * * @uses sanitize_term_field Used to sanitize all fields in a term * * @param array|object $term The term to check * @param string $taxonomy The taxonomy name to use * @param string $context Default is 'display'. * @return array|object Term with all fields sanitized */ function sanitize_term($term, $taxonomy, $context = 'display') { $fields = array( 'term_id', 'name', 'description', 'slug', 'count', 'parent', 'term_group', 'term_taxonomy_id', 'object_id' ); $do_object = is_object( $term ); $term_id = $do_object ? $term->term_id : (isset($term['term_id']) ? $term['term_id'] : 0); foreach ( (array) $fields as $field ) { if ( $do_object ) { if ( isset($term->$field) ) $term->$field = sanitize_term_field($field, $term->$field, $term_id, $taxonomy, $context); } else { if ( isset($term[$field]) ) $term[$field] = sanitize_term_field($field, $term[$field], $term_id, $taxonomy, $context); } } if ( $do_object ) $term->filter = $context; else $term['filter'] = $context; return $term; } /** * Cleanse the field value in the term based on the context. * * Passing a term field value through the function should be assumed to have * cleansed the value for whatever context the term field is going to be used. * * If no context or an unsupported context is given, then default filters will * be applied. * * There are enough filters for each context to support a custom filtering * without creating your own filter function. Simply create a function that * hooks into the filter you need. * * @since 2.3.0 * * @uses $wpdb * * @param string $field Term field to sanitize * @param string $value Search for this term value * @param int $term_id Term ID * @param string $taxonomy Taxonomy Name * @param string $context Either edit, db, display, attribute, or js. * @return mixed sanitized field */ function sanitize_term_field($field, $value, $term_id, $taxonomy, $context) { $int_fields = array( 'parent', 'term_id', 'count', 'term_group', 'term_taxonomy_id', 'object_id' ); if ( in_array( $field, $int_fields ) ) { $value = (int) $value; if ( $value < 0 ) $value = 0; } if ( 'raw' == $context ) return $value; if ( 'edit' == $context ) { /** * Filter a term field to edit before it is sanitized. * * The dynamic portion of the filter name, $field, refers to the term field. * * @since 2.3.0 * * @param mixed $value Value of the term field. * @param int $term_id Term ID. * @param string $taxonomy Taxonomy slug. */ $value = apply_filters( "edit_term_{$field}", $value, $term_id, $taxonomy ); /** * Filter the taxonomy field to edit before it is sanitized. * * The dynamic portions of the filter name, $taxonomy, and $field, refer * to the taxonomy slug and taxonomy field, respectively. * * @since 2.3.0 * * @param mixed $value Value of the taxonomy field to edit. * @param int $term_id Term ID. */ $value = apply_filters( "edit_{$taxonomy}_{$field}", $value, $term_id ); if ( 'description' == $field ) $value = esc_html($value); // textarea_escaped else $value = esc_attr($value); } else if ( 'db' == $context ) { /** * Filter a term field value before it is sanitized. * * The dynamic portion of the filter name, $field, refers to the term field. * * @since 2.3.0 * * @param mixed $value Value of the term field. * @param string $taxonomy Taxonomy slug. */ $value = apply_filters( "pre_term_{$field}", $value, $taxonomy ); /** * Filter a taxonomy field before it is sanitized. * * The dynamic portions of the filter name, $taxonomy, and $field, refer * to the taxonomy slug and field name, respectively. * * @since 2.3.0 * * @param mixed $value Value of the taxonomy field. */ $value = apply_filters( "pre_{$taxonomy}_{$field}", $value ); // Back compat filters if ( 'slug' == $field ) { /** * Filter the category nicename before it is sanitized. * * Use the pre_{$taxonomy}_{$field} hook instead. * * @since 2.0.3 * * @param string $value The category nicename. */ $value = apply_filters( 'pre_category_nicename', $value ); } } else if ( 'rss' == $context ) { /** * Filter the term field for use in RSS. * * The dynamic portion of the filter name, $field, refers to the term field. * * @since 2.3.0 * * @param mixed $value Value of the term field. * @param string $taxonomy Taxonomy slug. */ $value = apply_filters( "term_{$field}_rss", $value, $taxonomy ); /** * Filter the taxonomy field for use in RSS. * * The dynamic portions of the hook name, $taxonomy, and $field, refer * to the taxonomy slug and field name, respectively. * * @since 2.3.0 * * @param mixed $value Value of the taxonomy field. */ $value = apply_filters( "{$taxonomy}_{$field}_rss", $value ); } else { // Use display filters by default. /** * Filter the term field sanitized for display. * * The dynamic portion of the filter name, $field, refers to the term field name. * * @since 2.3.0 * * @param mixed $value Value of the term field. * @param int $term_id Term ID. * @param string $taxonomy Taxonomy slug. * @param string $context Context to retrieve the term field value. */ $value = apply_filters( "term_{$field}", $value, $term_id, $taxonomy, $context ); /** * Filter the taxonomy field sanitized for display. * * The dynamic portions of the filter name, $taxonomy, and $field, refer * to the taxonomy slug and taxonomy field, respectively. * * @since 2.3.0 * * @param mixed $value Value of the taxonomy field. * @param int $term_id Term ID. * @param string $context Context to retrieve the taxonomy field value. */ $value = apply_filters( "{$taxonomy}_{$field}", $value, $term_id, $context ); } if ( 'attribute' == $context ) $value = esc_attr($value); else if ( 'js' == $context ) $value = esc_js($value); return $value; } /** * Count how many terms are in Taxonomy. * * Default $args is 'hide_empty' which can be 'hide_empty=true' or array('hide_empty' => true). * * @since 2.3.0 * * @uses get_terms() * @uses wp_parse_args() Turns strings into arrays and merges defaults into an array. * * @param string $taxonomy Taxonomy name * @param array|string $args Overwrite defaults. See get_terms() * @return int|WP_Error How many terms are in $taxonomy. WP_Error if $taxonomy does not exist. */ function wp_count_terms( $taxonomy, $args = array() ) { $defaults = array('hide_empty' => false); $args = wp_parse_args($args, $defaults); // backwards compatibility if ( isset($args['ignore_empty']) ) { $args['hide_empty'] = $args['ignore_empty']; unset($args['ignore_empty']); } $args['fields'] = 'count'; return get_terms($taxonomy, $args); } /** * Will unlink the object from the taxonomy or taxonomies. * * Will remove all relationships between the object and any terms in * a particular taxonomy or taxonomies. Does not remove the term or * taxonomy itself. * * @since 2.3.0 * @uses wp_remove_object_terms() * * @param int $object_id The term Object Id that refers to the term * @param string|array $taxonomies List of Taxonomy Names or single Taxonomy name. */ function wp_delete_object_term_relationships( $object_id, $taxonomies ) { $object_id = (int) $object_id; if ( !is_array($taxonomies) ) $taxonomies = array($taxonomies); foreach ( (array) $taxonomies as $taxonomy ) { $term_ids = wp_get_object_terms( $object_id, $taxonomy, array( 'fields' => 'ids' ) ); $term_ids = array_map( 'intval', $term_ids ); wp_remove_object_terms( $object_id, $term_ids, $taxonomy ); } } /** * Removes a term from the database. * * If the term is a parent of other terms, then the children will be updated to * that term's parent. * * The $args 'default' will only override the terms found, if there is only one * term found. Any other and the found terms are used. * * The $args 'force_default' will force the term supplied as default to be * assigned even if the object was not going to be termless * * @since 2.3.0 * * @uses $wpdb * * @param int $term Term ID * @param string $taxonomy Taxonomy Name * @param array|string $args Optional. Change 'default' term id and override found term ids. * @return bool|WP_Error Returns false if not term; true if completes delete action. */ function wp_delete_term( $term, $taxonomy, $args = array() ) { global $wpdb; $term = (int) $term; if ( ! $ids = term_exists($term, $taxonomy) ) return false; if ( is_wp_error( $ids ) ) return $ids; $tt_id = $ids['term_taxonomy_id']; $defaults = array(); if ( 'category' == $taxonomy ) { $defaults['default'] = get_option( 'default_category' ); if ( $defaults['default'] == $term ) return 0; // Don't delete the default category } $args = wp_parse_args($args, $defaults); extract($args, EXTR_SKIP); if ( isset( $default ) ) { $default = (int) $default; if ( ! term_exists($default, $taxonomy) ) unset($default); } // Update children to point to new parent if ( is_taxonomy_hierarchical($taxonomy) ) { $term_obj = get_term($term, $taxonomy); if ( is_wp_error( $term_obj ) ) return $term_obj; $parent = $term_obj->parent; $edit_tt_ids = $wpdb->get_col( "SELECT `term_taxonomy_id` FROM $wpdb->term_taxonomy WHERE `parent` = " . (int)$term_obj->term_id ); /** * Fires immediately before a term to delete's children are reassigned a parent. * * @since 2.9.0 * * @param array $edit_tt_ids An array of term taxonomy IDs for the given term. */ do_action( 'edit_term_taxonomies', $edit_tt_ids ); $wpdb->update( $wpdb->term_taxonomy, compact( 'parent' ), array( 'parent' => $term_obj->term_id) + compact( 'taxonomy' ) ); /** * Fires immediately after a term to delete's children are reassigned a parent. * * @since 2.9.0 * * @param array $edit_tt_ids An array of term taxonomy IDs for the given term. */ do_action( 'edited_term_taxonomies', $edit_tt_ids ); } $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) ); foreach ( (array) $objects as $object ) { $terms = wp_get_object_terms($object, $taxonomy, array('fields' => 'ids', 'orderby' => 'none')); if ( 1 == count($terms) && isset($default) ) { $terms = array($default); } else { $terms = array_diff($terms, array($term)); if (isset($default) && isset($force_default) && $force_default) $terms = array_merge($terms, array($default)); } $terms = array_map('intval', $terms); wp_set_object_terms($object, $terms, $taxonomy); } // Clean the relationship caches for all object types using this term $tax_object = get_taxonomy( $taxonomy ); foreach ( $tax_object->object_type as $object_type ) clean_object_term_cache( $objects, $object_type ); // Get the object before deletion so we can pass to actions below $deleted_term = get_term( $term, $taxonomy ); /** * Fires immediately before a term taxonomy ID is deleted. * * @since 2.9.0 * * @param int $tt_id Term taxonomy ID. */ do_action( 'delete_term_taxonomy', $tt_id ); $wpdb->delete( $wpdb->term_taxonomy, array( 'term_taxonomy_id' => $tt_id ) ); /** * Fires immediately after a term taxonomy ID is deleted. * * @since 2.9.0 * * @param int $tt_id Term taxonomy ID. */ do_action( 'deleted_term_taxonomy', $tt_id ); // Delete the term if no taxonomies use it. if ( !$wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_taxonomy WHERE term_id = %d", $term) ) ) $wpdb->delete( $wpdb->terms, array( 'term_id' => $term ) ); clean_term_cache($term, $taxonomy); /** * Fires after a term is deleted from the database and the cache is cleaned. * * @since 2.5.0 * * @param int $term Term ID. * @param int $tt_id Term taxonomy ID. * @param string $taxonomy Taxonomy slug. * @param mixed $deleted_term Copy of the already-deleted term, in the form specified * by the parent function. WP_Error otherwise. */ do_action( 'delete_term', $term, $tt_id, $taxonomy, $deleted_term ); /** * Fires after a term in a specific taxonomy is deleted. * * The dynamic portion of the hook name, $taxonomy, refers to the specific * taxonomy the term belonged to. * * @since 2.3.0 * * @param int $term Term ID. * @param int $tt_id Term taxonomy ID. * @param mixed $deleted_term Copy of the already-deleted term, in the form specified * by the parent function. WP_Error otherwise. */ do_action( "delete_$taxonomy", $term, $tt_id, $deleted_term ); return true; } /** * Deletes one existing category. * * @since 2.0.0 * @uses wp_delete_term() * * @param int $cat_ID * @return mixed Returns true if completes delete action; false if term doesn't exist; * Zero on attempted deletion of default Category; WP_Error object is also a possibility. */ function wp_delete_category( $cat_ID ) { return wp_delete_term( $cat_ID, 'category' ); } /** * Retrieves the terms associated with the given object(s), in the supplied taxonomies. * * The following information has to do the $args parameter and for what can be * contained in the string or array of that parameter, if it exists. * * The first argument is called, 'orderby' and has the default value of 'name'. * The other value that is supported is 'count'. * * The second argument is called, 'order' and has the default value of 'ASC'. * The only other value that will be acceptable is 'DESC'. * * The final argument supported is called, 'fields' and has the default value of * 'all'. There are multiple other options that can be used instead. Supported * values are as follows: 'all', 'ids', 'names', and finally * 'all_with_object_id'. * * The fields argument also decides what will be returned. If 'all' or * 'all_with_object_id' is chosen or the default kept intact, then all matching * terms objects will be returned. If either 'ids' or 'names' is used, then an * array of all matching term ids or term names will be returned respectively. * * @since 2.3.0 * @uses $wpdb * * @param int|array $object_ids The ID(s) of the object(s) to retrieve. * @param string|array $taxonomies The taxonomies to retrieve terms from. * @param array|string $args Change what is returned * @return array|WP_Error The requested term data or empty array if no terms found. WP_Error if any of the $taxonomies don't exist. */ function wp_get_object_terms($object_ids, $taxonomies, $args = array()) { global $wpdb; if ( empty( $object_ids ) || empty( $taxonomies ) ) return array(); if ( !is_array($taxonomies) ) $taxonomies = array($taxonomies); foreach ( $taxonomies as $taxonomy ) { if ( ! taxonomy_exists($taxonomy) ) return new WP_Error('invalid_taxonomy', __('Invalid taxonomy')); } if ( !is_array($object_ids) ) $object_ids = array($object_ids); $object_ids = array_map('intval', $object_ids); $defaults = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'all'); $args = wp_parse_args( $args, $defaults ); $terms = array(); if ( count($taxonomies) > 1 ) { foreach ( $taxonomies as $index => $taxonomy ) { $t = get_taxonomy($taxonomy); if ( isset($t->args) && is_array($t->args) && $args != array_merge($args, $t->args) ) { unset($taxonomies[$index]); $terms = array_merge($terms, wp_get_object_terms($object_ids, $taxonomy, array_merge($args, $t->args))); } } } else { $t = get_taxonomy($taxonomies[0]); if ( isset($t->args) && is_array($t->args) ) $args = array_merge($args, $t->args); } extract($args, EXTR_SKIP); if ( 'count' == $orderby ) $orderby = 'tt.count'; else if ( 'name' == $orderby ) $orderby = 't.name'; else if ( 'slug' == $orderby ) $orderby = 't.slug'; else if ( 'term_group' == $orderby ) $orderby = 't.term_group'; else if ( 'term_order' == $orderby ) $orderby = 'tr.term_order'; else if ( 'none' == $orderby ) { $orderby = ''; $order = ''; } else { $orderby = 't.term_id'; } // tt_ids queries can only be none or tr.term_taxonomy_id if ( ('tt_ids' == $fields) && !empty($orderby) ) $orderby = 'tr.term_taxonomy_id'; if ( !empty($orderby) ) $orderby = "ORDER BY $orderby"; $order = strtoupper( $order ); if ( '' !== $order && ! in_array( $order, array( 'ASC', 'DESC' ) ) ) $order = 'ASC'; $taxonomies = "'" . implode("', '", $taxonomies) . "'"; $object_ids = implode(', ', $object_ids); $select_this = ''; if ( 'all' == $fields ) $select_this = 't.*, tt.*'; else if ( 'ids' == $fields ) $select_this = 't.term_id'; else if ( 'names' == $fields ) $select_this = 't.name'; else if ( 'slugs' == $fields ) $select_this = 't.slug'; else if ( 'all_with_object_id' == $fields ) $select_this = 't.*, tt.*, tr.object_id'; $query = "SELECT $select_this FROM $wpdb->terms AS t INNER JOIN $wpdb->term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN $wpdb->term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ($taxonomies) AND tr.object_id IN ($object_ids) $orderby $order"; if ( 'all' == $fields || 'all_with_object_id' == $fields ) { $_terms = $wpdb->get_results( $query ); foreach ( $_terms as $key => $term ) { $_terms[$key] = sanitize_term( $term, $taxonomy, 'raw' ); } $terms = array_merge( $terms, $_terms ); update_term_cache( $terms ); } else if ( 'ids' == $fields || 'names' == $fields || 'slugs' == $fields ) { $_terms = $wpdb->get_col( $query ); $_field = ( 'ids' == $fields ) ? 'term_id' : 'name'; foreach ( $_terms as $key => $term ) { $_terms[$key] = sanitize_term_field( $_field, $term, $term, $taxonomy, 'raw' ); } $terms = array_merge( $terms, $_terms ); } else if ( 'tt_ids' == $fields ) { $terms = $wpdb->get_col("SELECT tr.term_taxonomy_id FROM $wpdb->term_relationships AS tr INNER JOIN $wpdb->term_taxonomy AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tr.object_id IN ($object_ids) AND tt.taxonomy IN ($taxonomies) $orderby $order"); foreach ( $terms as $key => $tt_id ) { $terms[$key] = sanitize_term_field( 'term_taxonomy_id', $tt_id, 0, $taxonomy, 'raw' ); // 0 should be the term id, however is not needed when using raw context. } } if ( ! $terms ) $terms = array(); /** * Filter the terms for a given object or objects. * * @since 2.8.0 * * @param array $terms An array of terms for the given object or objects. * @param array|int $object_ids Object ID or array of IDs. * @param array|string $taxonomies A taxonomy or array of taxonomies. * @param array $args An array of arguments for retrieving terms for * the given object(s). */ return apply_filters( 'wp_get_object_terms', $terms, $object_ids, $taxonomies, $args ); } /** * Add a new term to the database. * * A non-existent term is inserted in the following sequence: * 1. The term is added to the term table, then related to the taxonomy. * 2. If everything is correct, several actions are fired. * 3. The 'term_id_filter' is evaluated. * 4. The term cache is cleaned. * 5. Several more actions are fired. * 6. An array is returned containing the term_id and term_taxonomy_id. * * If the 'slug' argument is not empty, then it is checked to see if the term * is invalid. If it is not a valid, existing term, it is added and the term_id * is given. * * If the taxonomy is hierarchical, and the 'parent' argument is not empty, * the term is inserted and the term_id will be given. * Error handling: * If $taxonomy does not exist or $term is empty, * a WP_Error object will be returned. * * If the term already exists on the same hierarchical level, * or the term slug and name are not unique, a WP_Error object will be returned. * * @global wpdb $wpdb The WordPress database object. * @since 2.3.0 * * @param string $term The term to add or update. * @param string $taxonomy The taxonomy to which to add the term * @param array|string $args { * Arguments to change values of the inserted term. * * @type string 'alias_of' Slug of the term to make this term an alias of. * Default empty string. Accepts a term slug. * @type string 'description' The term description. * Default empty string. * @type int 'parent' The id of the parent term. * Default 0. * @type string 'slug' The term slug to use. * Default empty string. * } * @return array|WP_Error An array containing the term_id and term_taxonomy_id, WP_Error otherwise. */ function wp_insert_term( $term, $taxonomy, $args = array() ) { global $wpdb; if ( ! taxonomy_exists($taxonomy) ) return new WP_Error('invalid_taxonomy', __('Invalid taxonomy')); /** * Filter a term before it is sanitized and inserted into the database. * * @since 3.0.0 * * @param string $term The term to add or update. * @param string $taxonomy Taxonomy slug. */ $term = apply_filters( 'pre_insert_term', $term, $taxonomy ); if ( is_wp_error( $term ) ) return $term; if ( is_int($term) && 0 == $term ) return new WP_Error('invalid_term_id', __('Invalid term ID')); if ( '' == trim($term) ) return new WP_Error('empty_term_name', __('A name is required for this term')); $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => ''); $args = wp_parse_args($args, $defaults); $args['name'] = $term; $args['taxonomy'] = $taxonomy; $args = sanitize_term($args, $taxonomy, 'db'); extract($args, EXTR_SKIP); // expected_slashed ($name) $name = wp_unslash($name); $description = wp_unslash($description); $slug_provided = ! empty( $slug ); if ( ! $slug_provided ) { $slug = sanitize_title($name); } $term_group = 0; if ( $alias_of ) { $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) ); if ( $alias->term_group ) { // The alias we want is already in a group, so let's use that one. $term_group = $alias->term_group; } else { // The alias isn't in a group, so let's create a new one and firstly add the alias term to it. $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1; /** * Fires immediately before the given terms are edited. * * @since 2.9.0 * * @param int $term_id Term ID. * @param string $taxonomy Taxonomy slug. */ do_action( 'edit_terms', $alias->term_id, $taxonomy ); $wpdb->update($wpdb->terms, compact('term_group'), array('term_id' => $alias->term_id) ); /** * Fires immediately after the given terms are edited. * * @since 2.9.0 * * @param int $term_id Term ID * @param string $taxonomy Taxonomy slug. */ do_action( 'edited_terms', $alias->term_id, $taxonomy ); } } if ( $term_id = term_exists($slug) ) { $existing_term = $wpdb->get_row( $wpdb->prepare( "SELECT name FROM $wpdb->terms WHERE term_id = %d", $term_id), ARRAY_A ); // We've got an existing term in the same taxonomy, which matches the name of the new term: if ( is_taxonomy_hierarchical($taxonomy) && $existing_term['name'] == $name && $exists = term_exists( (int) $term_id, $taxonomy ) ) { // Hierarchical, and it matches an existing term, Do not allow same "name" in the same level. $siblings = get_terms($taxonomy, array('fields' => 'names', 'get' => 'all', 'parent' => (int)$parent) ); if ( in_array($name, $siblings) ) { if ( $slug_provided ) { return new WP_Error( 'term_exists', __( 'A term with the name and slug provided already exists with this parent.' ), $exists['term_id'] ); } else { return new WP_Error( 'term_exists', __( 'A term with the name provided already exists with this parent.' ), $exists['term_id'] ); } } else { $slug = wp_unique_term_slug($slug, (object) $args); if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) ) return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error); $term_id = (int) $wpdb->insert_id; } } elseif ( $existing_term['name'] != $name ) { // We've got an existing term, with a different name, Create the new term. $slug = wp_unique_term_slug($slug, (object) $args); if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) ) return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error); $term_id = (int) $wpdb->insert_id; } elseif ( $exists = term_exists( (int) $term_id, $taxonomy ) ) { // Same name, same slug. return new WP_Error( 'term_exists', __( 'A term with the name and slug provided already exists.' ), $exists['term_id'] ); } } else { // This term does not exist at all in the database, Create it. $slug = wp_unique_term_slug($slug, (object) $args); if ( false === $wpdb->insert( $wpdb->terms, compact( 'name', 'slug', 'term_group' ) ) ) return new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error); $term_id = (int) $wpdb->insert_id; } // Seems unreachable, However, Is used in the case that a term name is provided, which sanitizes to an empty string. if ( empty($slug) ) { $slug = sanitize_title($slug, $term_id); /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edit_terms', $term_id, $taxonomy ); $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) ); /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edited_terms', $term_id, $taxonomy ); } $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id ) ); if ( !empty($tt_id) ) return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id); $wpdb->insert( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent') + array( 'count' => 0 ) ); $tt_id = (int) $wpdb->insert_id; /** * Fires immediately after a new term is created, before the term cache is cleaned. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. * @param string $taxonomy Taxonomy slug. */ do_action( "create_term", $term_id, $tt_id, $taxonomy ); /** * Fires after a new term is created for a specific taxonomy. * * The dynamic portion of the hook name, $taxonomy, refers * to the slug of the taxonomy the term was created for. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. */ do_action( "create_$taxonomy", $term_id, $tt_id ); /** * Filter the term ID after a new term is created. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Taxonomy term ID. */ $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id ); clean_term_cache($term_id, $taxonomy); /** * Fires after a new term is created, and after the term cache has been cleaned. * * @since 2.3.0 */ do_action( "created_term", $term_id, $tt_id, $taxonomy ); /** * Fires after a new term in a specific taxonomy is created, and after the term * cache has been cleaned. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. */ do_action( "created_$taxonomy", $term_id, $tt_id ); return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id); } /** * Create Term and Taxonomy Relationships. * * Relates an object (post, link etc) to a term and taxonomy type. Creates the * term and taxonomy relationship if it doesn't already exist. Creates a term if * it doesn't exist (using the slug). * * A relationship means that the term is grouped in or belongs to the taxonomy. * A term has no meaning until it is given context by defining which taxonomy it * exists under. * * @since 2.3.0 * @uses wp_remove_object_terms() * * @param int $object_id The object to relate to. * @param array|int|string $terms The slug or id of the term, will replace all existing * related terms in this taxonomy. * @param array|string $taxonomy The context in which to relate the term to the object. * @param bool $append If false will delete difference of terms. * @return array|WP_Error Affected Term IDs */ function wp_set_object_terms($object_id, $terms, $taxonomy, $append = false) { global $wpdb; $object_id = (int) $object_id; if ( ! taxonomy_exists($taxonomy) ) return new WP_Error('invalid_taxonomy', __('Invalid taxonomy')); if ( !is_array($terms) ) $terms = array($terms); if ( ! $append ) $old_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids', 'orderby' => 'none')); else $old_tt_ids = array(); $tt_ids = array(); $term_ids = array(); $new_tt_ids = array(); foreach ( (array) $terms as $term) { if ( !strlen(trim($term)) ) continue; if ( !$term_info = term_exists($term, $taxonomy) ) { // Skip if a non-existent term ID is passed. if ( is_int($term) ) continue; $term_info = wp_insert_term($term, $taxonomy); } if ( is_wp_error($term_info) ) return $term_info; $term_ids[] = $term_info['term_id']; $tt_id = $term_info['term_taxonomy_id']; $tt_ids[] = $tt_id; if ( $wpdb->get_var( $wpdb->prepare( "SELECT term_taxonomy_id FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id = %d", $object_id, $tt_id ) ) ) continue; /** * Fires immediately before an object-term relationship is added. * * @since 2.9.0 * * @param int $object_id Object ID. * @param int $tt_id Term taxonomy ID. */ do_action( 'add_term_relationship', $object_id, $tt_id ); $wpdb->insert( $wpdb->term_relationships, array( 'object_id' => $object_id, 'term_taxonomy_id' => $tt_id ) ); /** * Fires immediately after an object-term relationship is added. * * @since 2.9.0 * * @param int $object_id Object ID. * @param int $tt_id Term taxonomy ID. */ do_action( 'added_term_relationship', $object_id, $tt_id ); $new_tt_ids[] = $tt_id; } if ( $new_tt_ids ) wp_update_term_count( $new_tt_ids, $taxonomy ); if ( ! $append ) { $delete_tt_ids = array_diff( $old_tt_ids, $tt_ids ); if ( $delete_tt_ids ) { $in_delete_tt_ids = "'" . implode( "', '", $delete_tt_ids ) . "'"; $delete_term_ids = $wpdb->get_col( $wpdb->prepare( "SELECT tt.term_id FROM $wpdb->term_taxonomy AS tt WHERE tt.taxonomy = %s AND tt.term_taxonomy_id IN ($in_delete_tt_ids)", $taxonomy ) ); $delete_term_ids = array_map( 'intval', $delete_term_ids ); $remove = wp_remove_object_terms( $object_id, $delete_term_ids, $taxonomy ); if ( is_wp_error( $remove ) ) { return $remove; } } } $t = get_taxonomy($taxonomy); if ( ! $append && isset($t->sort) && $t->sort ) { $values = array(); $term_order = 0; $final_tt_ids = wp_get_object_terms($object_id, $taxonomy, array('fields' => 'tt_ids')); foreach ( $tt_ids as $tt_id ) if ( in_array($tt_id, $final_tt_ids) ) $values[] = $wpdb->prepare( "(%d, %d, %d)", $object_id, $tt_id, ++$term_order); if ( $values ) if ( false === $wpdb->query( "INSERT INTO $wpdb->term_relationships (object_id, term_taxonomy_id, term_order) VALUES " . join( ',', $values ) . " ON DUPLICATE KEY UPDATE term_order = VALUES(term_order)" ) ) return new WP_Error( 'db_insert_error', __( 'Could not insert term relationship into the database' ), $wpdb->last_error ); } wp_cache_delete( $object_id, $taxonomy . '_relationships' ); /** * Fires after an object's terms have been set. * * @since 2.8.0 * * @param int $object_id Object ID. * @param array $terms An array of object terms. * @param array $tt_ids An array of term taxonomy IDs. * @param string $taxonomy Taxonomy slug. * @param bool $append Whether to append new terms to the old terms. * @param array $old_tt_ids Old array of term taxonomy IDs. */ do_action( 'set_object_terms', $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ); return $tt_ids; } /** * Add term(s) associated with a given object. * * @since 3.6.0 * @uses wp_set_object_terms() * * @param int $object_id The ID of the object to which the terms will be added. * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to add. * @param array|string $taxonomy Taxonomy name. * @return array|WP_Error Affected Term IDs */ function wp_add_object_terms( $object_id, $terms, $taxonomy ) { return wp_set_object_terms( $object_id, $terms, $taxonomy, true ); } /** * Remove term(s) associated with a given object. * * @since 3.6.0 * @uses $wpdb * * @param int $object_id The ID of the object from which the terms will be removed. * @param array|int|string $terms The slug(s) or ID(s) of the term(s) to remove. * @param array|string $taxonomy Taxonomy name. * @return bool|WP_Error True on success, false or WP_Error on failure. */ function wp_remove_object_terms( $object_id, $terms, $taxonomy ) { global $wpdb; $object_id = (int) $object_id; if ( ! taxonomy_exists( $taxonomy ) ) { return new WP_Error( 'invalid_taxonomy', __( 'Invalid Taxonomy' ) ); } if ( ! is_array( $terms ) ) { $terms = array( $terms ); } $tt_ids = array(); foreach ( (array) $terms as $term ) { if ( ! strlen( trim( $term ) ) ) { continue; } if ( ! $term_info = term_exists( $term, $taxonomy ) ) { // Skip if a non-existent term ID is passed. if ( is_int( $term ) ) { continue; } } if ( is_wp_error( $term_info ) ) { return $term_info; } $tt_ids[] = $term_info['term_taxonomy_id']; } if ( $tt_ids ) { $in_tt_ids = "'" . implode( "', '", $tt_ids ) . "'"; /** * Fires immediately before an object-term relationship is deleted. * * @since 2.9.0 * * @param int $object_id Object ID. * @param array $tt_ids An array of term taxonomy IDs. */ do_action( 'delete_term_relationships', $object_id, $tt_ids ); $deleted = $wpdb->query( $wpdb->prepare( "DELETE FROM $wpdb->term_relationships WHERE object_id = %d AND term_taxonomy_id IN ($in_tt_ids)", $object_id ) ); /** * Fires immediately after an object-term relationship is deleted. * * @since 2.9.0 * * @param int $object_id Object ID. * @param array $tt_ids An array of term taxonomy IDs. */ do_action( 'deleted_term_relationships', $object_id, $tt_ids ); wp_update_term_count( $tt_ids, $taxonomy ); return (bool) $deleted; } return false; } /** * Will make slug unique, if it isn't already. * * The $slug has to be unique global to every taxonomy, meaning that one * taxonomy term can't have a matching slug with another taxonomy term. Each * slug has to be globally unique for every taxonomy. * * The way this works is that if the taxonomy that the term belongs to is * hierarchical and has a parent, it will append that parent to the $slug. * * If that still doesn't return an unique slug, then it try to append a number * until it finds a number that is truly unique. * * The only purpose for $term is for appending a parent, if one exists. * * @since 2.3.0 * @uses $wpdb * * @param string $slug The string that will be tried for a unique slug * @param object $term The term object that the $slug will belong too * @return string Will return a true unique slug. */ function wp_unique_term_slug($slug, $term) { global $wpdb; if ( ! term_exists( $slug ) ) return $slug; // If the taxonomy supports hierarchy and the term has a parent, make the slug unique // by incorporating parent slugs. if ( is_taxonomy_hierarchical($term->taxonomy) && !empty($term->parent) ) { $the_parent = $term->parent; while ( ! empty($the_parent) ) { $parent_term = get_term($the_parent, $term->taxonomy); if ( is_wp_error($parent_term) || empty($parent_term) ) break; $slug .= '-' . $parent_term->slug; if ( ! term_exists( $slug ) ) return $slug; if ( empty($parent_term->parent) ) break; $the_parent = $parent_term->parent; } } // If we didn't get a unique slug, try appending a number to make it unique. if ( ! empty( $term->term_id ) ) $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s AND term_id != %d", $slug, $term->term_id ); else $query = $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $slug ); if ( $wpdb->get_var( $query ) ) { $num = 2; do { $alt_slug = $slug . "-$num"; $num++; $slug_check = $wpdb->get_var( $wpdb->prepare( "SELECT slug FROM $wpdb->terms WHERE slug = %s", $alt_slug ) ); } while ( $slug_check ); $slug = $alt_slug; } return $slug; } /** * Update term based on arguments provided. * * The $args will indiscriminately override all values with the same field name. * Care must be taken to not override important information need to update or * update will fail (or perhaps create a new term, neither would be acceptable). * * Defaults will set 'alias_of', 'description', 'parent', and 'slug' if not * defined in $args already. * * 'alias_of' will create a term group, if it doesn't already exist, and update * it for the $term. * * If the 'slug' argument in $args is missing, then the 'name' in $args will be * used. It should also be noted that if you set 'slug' and it isn't unique then * a WP_Error will be passed back. If you don't pass any slug, then a unique one * will be created for you. * * For what can be overrode in $args, check the term scheme can contain and stay * away from the term keys. * * @since 2.3.0 * * @uses $wpdb * * @param int $term_id The ID of the term * @param string $taxonomy The context in which to relate the term to the object. * @param array|string $args Overwrite term field values * @return array|WP_Error Returns Term ID and Taxonomy Term ID */ function wp_update_term( $term_id, $taxonomy, $args = array() ) { global $wpdb; if ( ! taxonomy_exists($taxonomy) ) return new WP_Error('invalid_taxonomy', __('Invalid taxonomy')); $term_id = (int) $term_id; // First, get all of the original args $term = get_term ($term_id, $taxonomy, ARRAY_A); if ( is_wp_error( $term ) ) return $term; // Escape data pulled from DB. $term = wp_slash($term); // Merge old and new args with new args overwriting old ones. $args = array_merge($term, $args); $defaults = array( 'alias_of' => '', 'description' => '', 'parent' => 0, 'slug' => ''); $args = wp_parse_args($args, $defaults); $args = sanitize_term($args, $taxonomy, 'db'); extract($args, EXTR_SKIP); // expected_slashed ($name) $name = wp_unslash($name); $description = wp_unslash($description); if ( '' == trim($name) ) return new WP_Error('empty_term_name', __('A name is required for this term')); $empty_slug = false; if ( empty($slug) ) { $empty_slug = true; $slug = sanitize_title($name); } if ( $alias_of ) { $alias = $wpdb->get_row( $wpdb->prepare( "SELECT term_id, term_group FROM $wpdb->terms WHERE slug = %s", $alias_of) ); if ( $alias->term_group ) { // The alias we want is already in a group, so let's use that one. $term_group = $alias->term_group; } else { // The alias isn't in a group, so let's create a new one and firstly add the alias term to it. $term_group = $wpdb->get_var("SELECT MAX(term_group) FROM $wpdb->terms") + 1; /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edit_terms', $alias->term_id, $taxonomy ); $wpdb->update( $wpdb->terms, compact('term_group'), array( 'term_id' => $alias->term_id ) ); /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edited_terms', $alias->term_id, $taxonomy ); } } /** * Filter the term parent. * * Hook to this filter to see if it will cause a hierarchy loop. * * @since 3.1.0 * * @param int $parent ID of the parent term. * @param int $term_id Term ID. * @param string $taxonomy Taxonomy slug. * @param array $args Compacted array of update arguments for the given term. * @param array $args An array of update arguments for the given term. */ $parent = apply_filters( 'wp_update_term_parent', $parent, $term_id, $taxonomy, compact( array_keys( $args ) ), $args ); // Check for duplicate slug $id = $wpdb->get_var( $wpdb->prepare( "SELECT term_id FROM $wpdb->terms WHERE slug = %s", $slug ) ); if ( $id && ($id != $term_id) ) { // If an empty slug was passed or the parent changed, reset the slug to something unique. // Otherwise, bail. if ( $empty_slug || ( $parent != $term['parent']) ) $slug = wp_unique_term_slug($slug, (object) $args); else return new WP_Error('duplicate_term_slug', sprintf(__('The slug &#8220;%s&#8221; is already in use by another term'), $slug)); } /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edit_terms', $term_id, $taxonomy ); $wpdb->update($wpdb->terms, compact( 'name', 'slug', 'term_group' ), compact( 'term_id' ) ); if ( empty($slug) ) { $slug = sanitize_title($name, $term_id); $wpdb->update( $wpdb->terms, compact( 'slug' ), compact( 'term_id' ) ); } /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edited_terms', $term_id, $taxonomy ); $tt_id = $wpdb->get_var( $wpdb->prepare( "SELECT tt.term_taxonomy_id FROM $wpdb->term_taxonomy AS tt INNER JOIN $wpdb->terms AS t ON tt.term_id = t.term_id WHERE tt.taxonomy = %s AND t.term_id = %d", $taxonomy, $term_id) ); /** * Fires immediate before a term-taxonomy relationship is updated. * * @since 2.9.0 * * @param int $tt_id Term taxonomy ID. * @param string $taxonomy Taxonomy slug. */ do_action( 'edit_term_taxonomy', $tt_id, $taxonomy ); $wpdb->update( $wpdb->term_taxonomy, compact( 'term_id', 'taxonomy', 'description', 'parent' ), array( 'term_taxonomy_id' => $tt_id ) ); /** * Fires immediately after a term-taxonomy relationship is updated. * * @since 2.9.0 * * @param int $tt_id Term taxonomy ID. * @param string $taxonomy Taxonomy slug. */ do_action( 'edited_term_taxonomy', $tt_id, $taxonomy ); // Clean the relationship caches for all object types using this term $objects = $wpdb->get_col( $wpdb->prepare( "SELECT object_id FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $tt_id ) ); $tax_object = get_taxonomy( $taxonomy ); foreach ( $tax_object->object_type as $object_type ) { clean_object_term_cache( $objects, $object_type ); } /** * Fires after a term has been updated, but before the term cache has been cleaned. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. * @param string $taxonomy Taxonomy slug. */ do_action( "edit_term", $term_id, $tt_id, $taxonomy ); /** * Fires after a term in a specific taxonomy has been updated, but before the term * cache has been cleaned. * * The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. */ do_action( "edit_$taxonomy", $term_id, $tt_id ); /** This filter is documented in wp-includes/taxonomy.php */ $term_id = apply_filters( 'term_id_filter', $term_id, $tt_id ); clean_term_cache($term_id, $taxonomy); /** * Fires after a term has been updated, and the term cache has been cleaned. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. * @param string $taxonomy Taxonomy slug. */ do_action( "edited_term", $term_id, $tt_id, $taxonomy ); /** * Fires after a term for a specific taxonomy has been updated, and the term * cache has been cleaned. * * The dynamic portion of the hook name, $taxonomy, refers to the taxonomy slug. * * @since 2.3.0 * * @param int $term_id Term ID. * @param int $tt_id Term taxonomy ID. */ do_action( "edited_$taxonomy", $term_id, $tt_id ); return array('term_id' => $term_id, 'term_taxonomy_id' => $tt_id); } /** * Enable or disable term counting. * * @since 2.5.0 * * @param bool $defer Optional. Enable if true, disable if false. * @return bool Whether term counting is enabled or disabled. */ function wp_defer_term_counting($defer=null) { static $_defer = false; if ( is_bool($defer) ) { $_defer = $defer; // flush any deferred counts if ( !$defer ) wp_update_term_count( null, null, true ); } return $_defer; } /** * Updates the amount of terms in taxonomy. * * If there is a taxonomy callback applied, then it will be called for updating * the count. * * The default action is to count what the amount of terms have the relationship * of term ID. Once that is done, then update the database. * * @since 2.3.0 * @uses $wpdb * * @param int|array $terms The term_taxonomy_id of the terms * @param string $taxonomy The context of the term. * @return bool If no terms will return false, and if successful will return true. */ function wp_update_term_count( $terms, $taxonomy, $do_deferred=false ) { static $_deferred = array(); if ( $do_deferred ) { foreach ( (array) array_keys($_deferred) as $tax ) { wp_update_term_count_now( $_deferred[$tax], $tax ); unset( $_deferred[$tax] ); } } if ( empty($terms) ) return false; if ( !is_array($terms) ) $terms = array($terms); if ( wp_defer_term_counting() ) { if ( !isset($_deferred[$taxonomy]) ) $_deferred[$taxonomy] = array(); $_deferred[$taxonomy] = array_unique( array_merge($_deferred[$taxonomy], $terms) ); return true; } return wp_update_term_count_now( $terms, $taxonomy ); } /** * Perform term count update immediately. * * @since 2.5.0 * * @param array $terms The term_taxonomy_id of terms to update. * @param string $taxonomy The context of the term. * @return bool Always true when complete. */ function wp_update_term_count_now( $terms, $taxonomy ) { global $wpdb; $terms = array_map('intval', $terms); $taxonomy = get_taxonomy($taxonomy); if ( !empty($taxonomy->update_count_callback) ) { call_user_func($taxonomy->update_count_callback, $terms, $taxonomy); } else { $object_types = (array) $taxonomy->object_type; foreach ( $object_types as &$object_type ) { if ( 0 === strpos( $object_type, 'attachment:' ) ) list( $object_type ) = explode( ':', $object_type ); } if ( $object_types == array_filter( $object_types, 'post_type_exists' ) ) { // Only post types are attached to this taxonomy _update_post_term_count( $terms, $taxonomy ); } else { // Default count updater _update_generic_term_count( $terms, $taxonomy ); } } clean_term_cache($terms, '', false); return true; } // // Cache // /** * Removes the taxonomy relationship to terms from the cache. * * Will remove the entire taxonomy relationship containing term $object_id. The * term IDs have to exist within the taxonomy $object_type for the deletion to * take place. * * @since 2.3.0 * * @see get_object_taxonomies() for more on $object_type * * @param int|array $object_ids Single or list of term object ID(s) * @param array|string $object_type The taxonomy object type */ function clean_object_term_cache($object_ids, $object_type) { if ( !is_array($object_ids) ) $object_ids = array($object_ids); $taxonomies = get_object_taxonomies( $object_type ); foreach ( $object_ids as $id ) { foreach ( $taxonomies as $taxonomy ) { wp_cache_delete($id, "{$taxonomy}_relationships"); } } /** * Fires after the object term cache has been cleaned. * * @since 2.5.0 * * @param array $object_ids An array of object IDs. * @param string $objet_type Object type. */ do_action( 'clean_object_term_cache', $object_ids, $object_type ); } /** * Will remove all of the term ids from the cache. * * @since 2.3.0 * @uses $wpdb * * @param int|array $ids Single or list of Term IDs * @param string $taxonomy Can be empty and will assume tt_ids, else will use for context. * @param bool $clean_taxonomy Whether to clean taxonomy wide caches (true), or just individual term object caches (false). Default is true. */ function clean_term_cache($ids, $taxonomy = '', $clean_taxonomy = true) { global $wpdb; if ( !is_array($ids) ) $ids = array($ids); $taxonomies = array(); // If no taxonomy, assume tt_ids. if ( empty($taxonomy) ) { $tt_ids = array_map('intval', $ids); $tt_ids = implode(', ', $tt_ids); $terms = $wpdb->get_results("SELECT term_id, taxonomy FROM $wpdb->term_taxonomy WHERE term_taxonomy_id IN ($tt_ids)"); $ids = array(); foreach ( (array) $terms as $term ) { $taxonomies[] = $term->taxonomy; $ids[] = $term->term_id; wp_cache_delete($term->term_id, $term->taxonomy); } $taxonomies = array_unique($taxonomies); } else { $taxonomies = array($taxonomy); foreach ( $taxonomies as $taxonomy ) { foreach ( $ids as $id ) { wp_cache_delete($id, $taxonomy); } } } foreach ( $taxonomies as $taxonomy ) { if ( $clean_taxonomy ) { wp_cache_delete('all_ids', $taxonomy); wp_cache_delete('get', $taxonomy); delete_option("{$taxonomy}_children"); // Regenerate {$taxonomy}_children _get_term_hierarchy($taxonomy); } /** * Fires once after each taxonomy's term cache has been cleaned. * * @since 2.5.0 * * @param array $ids An array of term IDs. * @param string $taxonomy Taxonomy slug. */ do_action( 'clean_term_cache', $ids, $taxonomy ); } wp_cache_set( 'last_changed', microtime(), 'terms' ); } /** * Retrieves the taxonomy relationship to the term object id. * * @since 2.3.0 * * @uses wp_cache_get() Retrieves taxonomy relationship from cache * * @param int|array $id Term object ID * @param string $taxonomy Taxonomy Name * @return bool|array Empty array if $terms found, but not $taxonomy. False if nothing is in cache for $taxonomy and $id. */ function get_object_term_cache($id, $taxonomy) { $cache = wp_cache_get($id, "{$taxonomy}_relationships"); return $cache; } /** * Updates the cache for Term ID(s). * * Will only update the cache for terms not already cached. * * The $object_ids expects that the ids be separated by commas, if it is a * string. * * It should be noted that update_object_term_cache() is very time extensive. It * is advised that the function is not called very often or at least not for a * lot of terms that exist in a lot of taxonomies. The amount of time increases * for each term and it also increases for each taxonomy the term belongs to. * * @since 2.3.0 * @uses wp_get_object_terms() Used to get terms from the database to update * * @param string|array $object_ids Single or list of term object ID(s) * @param array|string $object_type The taxonomy object type * @return null|bool Null value is given with empty $object_ids. False if */ function update_object_term_cache($object_ids, $object_type) { if ( empty($object_ids) ) return; if ( !is_array($object_ids) ) $object_ids = explode(',', $object_ids); $object_ids = array_map('intval', $object_ids); $taxonomies = get_object_taxonomies($object_type); $ids = array(); foreach ( (array) $object_ids as $id ) { foreach ( $taxonomies as $taxonomy ) { if ( false === wp_cache_get($id, "{$taxonomy}_relationships") ) { $ids[] = $id; break; } } } if ( empty( $ids ) ) return false; $terms = wp_get_object_terms($ids, $taxonomies, array('fields' => 'all_with_object_id')); $object_terms = array(); foreach ( (array) $terms as $term ) $object_terms[$term->object_id][$term->taxonomy][$term->term_id] = $term; foreach ( $ids as $id ) { foreach ( $taxonomies as $taxonomy ) { if ( ! isset($object_terms[$id][$taxonomy]) ) { if ( !isset($object_terms[$id]) ) $object_terms[$id] = array(); $object_terms[$id][$taxonomy] = array(); } } } foreach ( $object_terms as $id => $value ) { foreach ( $value as $taxonomy => $terms ) { wp_cache_add( $id, $terms, "{$taxonomy}_relationships" ); } } } /** * Updates Terms to Taxonomy in cache. * * @since 2.3.0 * * @param array $terms List of Term objects to change * @param string $taxonomy Optional. Update Term to this taxonomy in cache */ function update_term_cache($terms, $taxonomy = '') { foreach ( (array) $terms as $term ) { $term_taxonomy = $taxonomy; if ( empty($term_taxonomy) ) $term_taxonomy = $term->taxonomy; wp_cache_add($term->term_id, $term, $term_taxonomy); } } // // Private // /** * Retrieves children of taxonomy as Term IDs. * * @access private * @since 2.3.0 * * @uses update_option() Stores all of the children in "$taxonomy_children" * option. That is the name of the taxonomy, immediately followed by '_children'. * * @param string $taxonomy Taxonomy Name * @return array Empty if $taxonomy isn't hierarchical or returns children as Term IDs. */ function _get_term_hierarchy($taxonomy) { if ( !is_taxonomy_hierarchical($taxonomy) ) return array(); $children = get_option("{$taxonomy}_children"); if ( is_array($children) ) return $children; $children = array(); $terms = get_terms($taxonomy, array('get' => 'all', 'orderby' => 'id', 'fields' => 'id=>parent')); foreach ( $terms as $term_id => $parent ) { if ( $parent > 0 ) $children[$parent][] = $term_id; } update_option("{$taxonomy}_children", $children); return $children; } /** * Get the subset of $terms that are descendants of $term_id. * * If $terms is an array of objects, then _get_term_children returns an array of objects. * If $terms is an array of IDs, then _get_term_children returns an array of IDs. * * @access private * @since 2.3.0 * * @param int $term_id The ancestor term: all returned terms should be descendants of $term_id. * @param array $terms The set of terms---either an array of term objects or term IDs---from which those that are descendants of $term_id will be chosen. * @param string $taxonomy The taxonomy which determines the hierarchy of the terms. * @return array The subset of $terms that are descendants of $term_id. */ function _get_term_children($term_id, $terms, $taxonomy) { $empty_array = array(); if ( empty($terms) ) return $empty_array; $term_list = array(); $has_children = _get_term_hierarchy($taxonomy); if ( ( 0 != $term_id ) && ! isset($has_children[$term_id]) ) return $empty_array; foreach ( (array) $terms as $term ) { $use_id = false; if ( !is_object($term) ) { $term = get_term($term, $taxonomy); if ( is_wp_error( $term ) ) return $term; $use_id = true; } if ( $term->term_id == $term_id ) { continue; } if ( $term->parent == $term_id ) { if ( $use_id ) $term_list[] = $term->term_id; else $term_list[] = $term; if ( !isset($has_children[$term->term_id]) ) continue; if ( $children = _get_term_children($term->term_id, $terms, $taxonomy) ) $term_list = array_merge($term_list, $children); } } return $term_list; } /** * Add count of children to parent count. * * Recalculates term counts by including items from child terms. Assumes all * relevant children are already in the $terms argument. * * @access private * @since 2.3.0 * @uses $wpdb * * @param array $terms List of Term IDs * @param string $taxonomy Term Context * @return null Will break from function if conditions are not met. */ function _pad_term_counts(&$terms, $taxonomy) { global $wpdb; // This function only works for hierarchical taxonomies like post categories. if ( !is_taxonomy_hierarchical( $taxonomy ) ) return; $term_hier = _get_term_hierarchy($taxonomy); if ( empty($term_hier) ) return; $term_items = array(); foreach ( (array) $terms as $key => $term ) { $terms_by_id[$term->term_id] = & $terms[$key]; $term_ids[$term->term_taxonomy_id] = $term->term_id; } // Get the object and term ids and stick them in a lookup table $tax_obj = get_taxonomy($taxonomy); $object_types = esc_sql($tax_obj->object_type); $results = $wpdb->get_results("SELECT object_id, term_taxonomy_id FROM $wpdb->term_relationships INNER JOIN $wpdb->posts ON object_id = ID WHERE term_taxonomy_id IN (" . implode(',', array_keys($term_ids)) . ") AND post_type IN ('" . implode("', '", $object_types) . "') AND post_status = 'publish'"); foreach ( $results as $row ) { $id = $term_ids[$row->term_taxonomy_id]; $term_items[$id][$row->object_id] = isset($term_items[$id][$row->object_id]) ? ++$term_items[$id][$row->object_id] : 1; } // Touch every ancestor's lookup row for each post in each term foreach ( $term_ids as $term_id ) { $child = $term_id; while ( !empty( $terms_by_id[$child] ) && $parent = $terms_by_id[$child]->parent ) { if ( !empty( $term_items[$term_id] ) ) foreach ( $term_items[$term_id] as $item_id => $touches ) { $term_items[$parent][$item_id] = isset($term_items[$parent][$item_id]) ? ++$term_items[$parent][$item_id]: 1; } $child = $parent; } } // Transfer the touched cells foreach ( (array) $term_items as $id => $items ) if ( isset($terms_by_id[$id]) ) $terms_by_id[$id]->count = count($items); } // // Default callbacks // /** * Will update term count based on object types of the current taxonomy. * * Private function for the default callback for post_tag and category * taxonomies. * * @access private * @since 2.3.0 * @uses $wpdb * * @param array $terms List of Term taxonomy IDs * @param object $taxonomy Current taxonomy object of terms */ function _update_post_term_count( $terms, $taxonomy ) { global $wpdb; $object_types = (array) $taxonomy->object_type; foreach ( $object_types as &$object_type ) list( $object_type ) = explode( ':', $object_type ); $object_types = array_unique( $object_types ); if ( false !== ( $check_attachments = array_search( 'attachment', $object_types ) ) ) { unset( $object_types[ $check_attachments ] ); $check_attachments = true; } if ( $object_types ) $object_types = esc_sql( array_filter( $object_types, 'post_type_exists' ) ); foreach ( (array) $terms as $term ) { $count = 0; // Attachments can be 'inherit' status, we need to base count off the parent's status if so if ( $check_attachments ) $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts p1 WHERE p1.ID = $wpdb->term_relationships.object_id AND ( post_status = 'publish' OR ( post_status = 'inherit' AND post_parent > 0 AND ( SELECT post_status FROM $wpdb->posts WHERE ID = p1.post_parent ) = 'publish' ) ) AND post_type = 'attachment' AND term_taxonomy_id = %d", $term ) ); if ( $object_types ) $count += (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships, $wpdb->posts WHERE $wpdb->posts.ID = $wpdb->term_relationships.object_id AND post_status = 'publish' AND post_type IN ('" . implode("', '", $object_types ) . "') AND term_taxonomy_id = %d", $term ) ); /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edit_term_taxonomy', $term, $taxonomy ); $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) ); /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edited_term_taxonomy', $term, $taxonomy ); } } /** * Will update term count based on number of objects. * * Default callback for the link_category taxonomy. * * @since 3.3.0 * @uses $wpdb * * @param array $terms List of Term taxonomy IDs * @param object $taxonomy Current taxonomy object of terms */ function _update_generic_term_count( $terms, $taxonomy ) { global $wpdb; foreach ( (array) $terms as $term ) { $count = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->term_relationships WHERE term_taxonomy_id = %d", $term ) ); /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edit_term_taxonomy', $term, $taxonomy ); $wpdb->update( $wpdb->term_taxonomy, compact( 'count' ), array( 'term_taxonomy_id' => $term ) ); /** This action is documented in wp-includes/taxonomy.php */ do_action( 'edited_term_taxonomy', $term, $taxonomy ); } } /** * Generates a permalink for a taxonomy term archive. * * @since 2.5.0 * * @param object|int|string $term * @param string $taxonomy (optional if $term is object) * @return string|WP_Error HTML link to taxonomy term archive on success, WP_Error if term does not exist. */ function get_term_link( $term, $taxonomy = '') { global $wp_rewrite; if ( !is_object($term) ) { if ( is_int($term) ) { $term = get_term($term, $taxonomy); } else { $term = get_term_by('slug', $term, $taxonomy); } } if ( !is_object($term) ) $term = new WP_Error('invalid_term', __('Empty Term')); if ( is_wp_error( $term ) ) return $term; $taxonomy = $term->taxonomy; $termlink = $wp_rewrite->get_extra_permastruct($taxonomy); $slug = $term->slug; $t = get_taxonomy($taxonomy); if ( empty($termlink) ) { if ( 'category' == $taxonomy ) $termlink = '?cat=' . $term->term_id; elseif ( $t->query_var ) $termlink = "?$t->query_var=$slug"; else $termlink = "?taxonomy=$taxonomy&term=$slug"; $termlink = home_url($termlink); } else { if ( $t->rewrite['hierarchical'] ) { $hierarchical_slugs = array(); $ancestors = get_ancestors($term->term_id, $taxonomy); foreach ( (array)$ancestors as $ancestor ) { $ancestor_term = get_term($ancestor, $taxonomy); $hierarchical_slugs[] = $ancestor_term->slug; } $hierarchical_slugs = array_reverse($hierarchical_slugs); $hierarchical_slugs[] = $slug; $termlink = str_replace("%$taxonomy%", implode('/', $hierarchical_slugs), $termlink); } else { $termlink = str_replace("%$taxonomy%", $slug, $termlink); } $termlink = home_url( user_trailingslashit($termlink, 'category') ); } // Back Compat filters. if ( 'post_tag' == $taxonomy ) { /** * Filter the tag link. * * @since 2.3.0 * @deprecated 2.5.0 Use 'term_link' instead. * * @param string $termlink Tag link URL. * @param int $term_id Term ID. */ $termlink = apply_filters( 'tag_link', $termlink, $term->term_id ); } elseif ( 'category' == $taxonomy ) { /** * Filter the category link. * * @since 1.5.0 * @deprecated 2.5.0 Use 'term_link' instead. * * @param string $termlink Category link URL. * @param int $term_id Term ID. */ $termlink = apply_filters( 'category_link', $termlink, $term->term_id ); } /** * Filter the term link. * * @since 2.5.0 * * @param string $termlink Term link URL. * @param object $term Term object. * @param string $taxonomy Taxonomy slug. */ return apply_filters( 'term_link', $termlink, $term, $taxonomy ); } /** * Display the taxonomies of a post with available options. * * This function can be used within the loop to display the taxonomies for a * post without specifying the Post ID. You can also use it outside the Loop to * display the taxonomies for a specific post. * * The available defaults are: * 'post' : default is 0. The post ID to get taxonomies of. * 'before' : default is empty string. Display before taxonomies list. * 'sep' : default is empty string. Separate every taxonomy with value in this. * 'after' : default is empty string. Display this after the taxonomies list. * 'template' : The template to use for displaying the taxonomy terms. * * @since 2.5.0 * @uses get_the_taxonomies() * * @param array $args Override the defaults. */ function the_taxonomies($args = array()) { $defaults = array( 'post' => 0, 'before' => '', 'sep' => ' ', 'after' => '', 'template' => '%s: %l.' ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); echo $before . join($sep, get_the_taxonomies($post, $r)) . $after; } /** * Retrieve all taxonomies associated with a post. * * This function can be used within the loop. It will also return an array of * the taxonomies with links to the taxonomy and name. * * @since 2.5.0 * * @param int|WP_Post $post Optional. Post ID or post object. * @param array $args Override the defaults. * @return array */ function get_the_taxonomies($post = 0, $args = array() ) { $post = get_post( $post ); $args = wp_parse_args( $args, array( 'template' => '%s: %l.', ) ); extract( $args, EXTR_SKIP ); $taxonomies = array(); if ( !$post ) return $taxonomies; foreach ( get_object_taxonomies($post) as $taxonomy ) { $t = (array) get_taxonomy($taxonomy); if ( empty($t['label']) ) $t['label'] = $taxonomy; if ( empty($t['args']) ) $t['args'] = array(); if ( empty($t['template']) ) $t['template'] = $template; $terms = get_object_term_cache($post->ID, $taxonomy); if ( false === $terms ) $terms = wp_get_object_terms($post->ID, $taxonomy, $t['args']); $links = array(); foreach ( $terms as $term ) $links[] = "<a href='" . esc_attr( get_term_link($term) ) . "'>$term->name</a>"; if ( $links ) $taxonomies[$taxonomy] = wp_sprintf($t['template'], $t['label'], $links, $terms); } return $taxonomies; } /** * Retrieve all taxonomies of a post with just the names. * * @since 2.5.0 * @uses get_object_taxonomies() * * @param int|WP_Post $post Optional. Post ID or post object. * @return array */ function get_post_taxonomies($post = 0) { $post = get_post( $post ); return get_object_taxonomies($post); } /** * Determine if the given object is associated with any of the given terms. * * The given terms are checked against the object's terms' term_ids, names and slugs. * Terms given as integers will only be checked against the object's terms' term_ids. * If no terms are given, determines if object is associated with any terms in the given taxonomy. * * @since 2.7.0 * @uses get_object_term_cache() * @uses wp_get_object_terms() * * @param int $object_id ID of the object (post ID, link ID, ...) * @param string $taxonomy Single taxonomy name * @param int|string|array $terms Optional. Term term_id, name, slug or array of said * @return bool|WP_Error. WP_Error on input error. */ function is_object_in_term( $object_id, $taxonomy, $terms = null ) { if ( !$object_id = (int) $object_id ) return new WP_Error( 'invalid_object', __( 'Invalid object ID' ) ); $object_terms = get_object_term_cache( $object_id, $taxonomy ); if ( false === $object_terms ) $object_terms = wp_get_object_terms( $object_id, $taxonomy ); if ( is_wp_error( $object_terms ) ) return $object_terms; if ( empty( $object_terms ) ) return false; if ( empty( $terms ) ) return ( !empty( $object_terms ) ); $terms = (array) $terms; if ( $ints = array_filter( $terms, 'is_int' ) ) $strs = array_diff( $terms, $ints ); else $strs =& $terms; foreach ( $object_terms as $object_term ) { if ( $ints && in_array( $object_term->term_id, $ints ) ) return true; // If int, check against term_id if ( $strs ) { if ( in_array( $object_term->term_id, $strs ) ) return true; if ( in_array( $object_term->name, $strs ) ) return true; if ( in_array( $object_term->slug, $strs ) ) return true; } } return false; } /** * Determine if the given object type is associated with the given taxonomy. * * @since 3.0.0 * @uses get_object_taxonomies() * * @param string $object_type Object type string * @param string $taxonomy Single taxonomy name * @return bool True if object is associated with the taxonomy, otherwise false. */ function is_object_in_taxonomy($object_type, $taxonomy) { $taxonomies = get_object_taxonomies($object_type); if ( empty($taxonomies) ) return false; if ( in_array($taxonomy, $taxonomies) ) return true; return false; } /** * Get an array of ancestor IDs for a given object. * * @param int $object_id The ID of the object * @param string $object_type The type of object for which we'll be retrieving ancestors. * @return array of ancestors from lowest to highest in the hierarchy. */ function get_ancestors($object_id = 0, $object_type = '') { $object_id = (int) $object_id; $ancestors = array(); if ( empty( $object_id ) ) { /** This filter is documented in wp-includes/taxonomy.php */ return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type ); } if ( is_taxonomy_hierarchical( $object_type ) ) { $term = get_term($object_id, $object_type); while ( ! is_wp_error($term) && ! empty( $term->parent ) && ! in_array( $term->parent, $ancestors ) ) { $ancestors[] = (int) $term->parent; $term = get_term($term->parent, $object_type); } } elseif ( post_type_exists( $object_type ) ) { $ancestors = get_post_ancestors($object_id); } /** * Filter a given object's ancestors. * * @since 3.1.0 * * @param array $ancestors An array of object ancestors. * @param int $object_id Object ID. * @param string $object_type Type of object. */ return apply_filters( 'get_ancestors', $ancestors, $object_id, $object_type ); } /** * Returns the term's parent's term_ID * * @since 3.1.0 * * @param int $term_id * @param string $taxonomy * * @return int|bool false on error */ function wp_get_term_taxonomy_parent_id( $term_id, $taxonomy ) { $term = get_term( $term_id, $taxonomy ); if ( !$term || is_wp_error( $term ) ) return false; return (int) $term->parent; } /** * Checks the given subset of the term hierarchy for hierarchy loops. * Prevents loops from forming and breaks those that it finds. * * Attached to the wp_update_term_parent filter. * * @since 3.1.0 * @uses wp_find_hierarchy_loop() * * @param int $parent term_id of the parent for the term we're checking. * @param int $term_id The term we're checking. * @param string $taxonomy The taxonomy of the term we're checking. * * @return int The new parent for the term. */ function wp_check_term_hierarchy_for_loops( $parent, $term_id, $taxonomy ) { // Nothing fancy here - bail if ( !$parent ) return 0; // Can't be its own parent if ( $parent == $term_id ) return 0; // Now look for larger loops if ( !$loop = wp_find_hierarchy_loop( 'wp_get_term_taxonomy_parent_id', $term_id, $parent, array( $taxonomy ) ) ) return $parent; // No loop // Setting $parent to the given value causes a loop if ( isset( $loop[$term_id] ) ) return 0; // There's a loop, but it doesn't contain $term_id. Break the loop. foreach ( array_keys( $loop ) as $loop_member ) wp_update_term( $loop_member, $taxonomy, array( 'parent' => 0 ) ); return $parent; }
01-wordpress-paypal
trunk/wp-includes/taxonomy.php
PHP
gpl3
128,227
<?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 = '' ) { $defaults = array('before' => '', 'after' => '', 'echo' => true, 'post' => get_post() ); $r = wp_parse_args($args, $defaults); extract( $r, EXTR_SKIP ); $title = get_the_title( $post ); if ( strlen($title) == 0 ) return; $title = $before . $title . $after; $title = esc_attr(strip_tags($title)); if ( $echo ) echo $title; else return $title; } /** * Retrieve post title. * * If the post is protected and the visitor is not an admin, then "Protected" * will be displayed before the post title. If the post is private, then * "Private" will be located before the post title. * * @since 0.71 * * @param int|WP_Post $post Optional. Post ID or post 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 ) ) { /** * Filter the text prepended to the post title for protected posts. * * The filter is only applied on the front end. * * @since 2.8.0 * * @param string $prepend Text displayed before the post title. * Default 'Protected: %s'. */ $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 ) { /** * Filter the text prepended to the post title of private posts. * * The filter is only applied on the front end. * * @since 2.8.0 * * @param string $prepend Text displayed before the post title. * Default 'Private: %s'. */ $private_title_format = apply_filters( 'private_title_format', __( 'Private: %s' ) ); $title = sprintf( $private_title_format, $title ); } } /** * Filter the post title. * * @since 0.71 * * @param string $title The post title. * @param int $id The post ID. */ 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|WP_Post $id Optional. Post ID or post object. */ 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|WP_Post $id Optional. Post ID or post object. * @return string */ function get_the_guid( $id = 0 ) { $post = get_post($id); /** * Filter the Global Unique Identifier (guid) of the post. * * @since 1.5.0 * * @param string $post_guid Global Unique Identifier (guid) of the post. */ 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 $strip_teaser Optional. Strip teaser content before the more text. Default is false. */ function the_content( $more_link_text = null, $strip_teaser = false) { $content = get_the_content( $more_link_text, $strip_teaser ); /** * Filter the post content. * * @since 0.71 * * @param string $content Content of the current post. */ $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, $strip_teaser = false ) { global $page, $more, $preview, $pages, $multipage; $post = get_post(); if ( null === $more_link_text ) $more_link_text = __( '(more&hellip;)' ); $output = ''; $has_teaser = false; // If post password required and it doesn't match the cookie. if ( post_password_required( $post ) ) return get_the_password_form( $post ); 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] ) ) ); $has_teaser = true; } else { $content = array( $content ); } if ( false !== strpos( $post->post_content, '<!--noteaser-->' ) && ( ! $multipage || $page == 1 ) ) $strip_teaser = true; $teaser = $content[0]; if ( $more && $strip_teaser && $has_teaser ) $teaser = ''; $output .= $teaser; if ( count( $content ) > 1 ) { if ( $more ) { $output .= '<span id="more-' . $post->ID . '"></span>' . $content[1]; } else { if ( ! empty( $more_link_text ) ) /** * Filter the Read More link text. * * @since 2.8.0 * * @param string $more_link_element Read More link element. * @param string $more_link_text Read More 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 */ function the_excerpt() { /** * Filter the displayed post excerpt. * * @since 0.71 * * @see get_the_excerpt() * * @param string $post_excerpt The post 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.' ); } /** * Filter the retrieved post excerpt. * * @since 1.2.0 * * @param string $post_excerpt The post excerpt. */ return apply_filters( 'get_the_excerpt', $post->post_excerpt ); } /** * Whether post has excerpt. * * @since 2.3.0 * * @param int|WP_Post $id Optional. Post ID or post object. * @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|WP_Post $post_id Optional. Post ID or post object. */ 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 many. If the post is a sticky, then the 'sticky' * class name. The class 'hentry' is always added to each post. If the post has a * post thumbnail, 'has-post-thumbnail' is added as a class. 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|WP_Post $post_id Optional. Post ID or post object. * @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'; // Post thumbnails } elseif ( ! is_attachment( $post ) && current_theme_supports( 'post-thumbnails' ) && has_post_thumbnail( $post->ID ) ) { $classes[] = 'has-post-thumbnail'; } // 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); /** * Filter the list of CSS classes for the current post. * * @since 2.7.0 * * @param array $classes An array of post classes. * @param string $class A comma-separated list of additional classes added to the post. * @param int $post_id The post ID. */ 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'; $post_type = get_query_var( 'post_type' ); if ( is_array( $post_type ) ) $post_type = reset( $post_type ); $classes[] = 'post-type-archive-' . sanitize_html_class( $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 ); /** * Filter the list of CSS body classes for the current post or page. * * @since 2.8.0 * * @param array $classes An array of body classes. * @param string $class A comma-separated list of additional classes added to the body. */ return apply_filters( 'body_class', $classes, $class ); } /** * Whether post requires password and correct password has been provided. * * @since 2.7.0 * * @param int|WP_Post $post An optional post. Global $post used if not provided. * @return bool false if a password is not required or the correct password cookie is present, true otherwise. */ function post_password_required( $post = null ) { $post = get_post($post); if ( empty( $post->post_password ) ) return false; if ( ! isset( $_COOKIE['wp-postpass_' . COOKIEHASH] ) ) return true; require_once ABSPATH . 'wp-includes/class-phpass.php'; $hasher = new PasswordHash( 8, true ); $hash = wp_unslash( $_COOKIE[ 'wp-postpass_' . COOKIEHASH ] ); if ( 0 !== strpos( $hash, '$P$B' ) ) return true; return ! $hasher->CheckPassword( $post->post_password, $hash ); } // // Page Template Functions for usage in Themes // /** * 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: * '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. * 'next_or_number' - Default is 'number' (string). Indicates whether page * numbers should be used. Valid values are number and next. * 'separator' - Default is ' ' (string). Text used between pagination links. * '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. * 'echo' - Default is 1 (integer). When not 0, this triggers the HTML to be * echoed and then returned. * * @since 1.2.0 * * @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', 'separator' => ' ', 'nextpagelink' => __( 'Next page' ), 'previouspagelink' => __( 'Previous page' ), 'pagelink' => '%', 'echo' => 1 ); $r = wp_parse_args( $args, $defaults ); /** * Filter the arguments used in retrieving page links for paginated posts. * * @since 3.0.0 * * @param array $r An array of arguments for page links for paginated posts. */ $r = apply_filters( 'wp_link_pages_args', $r ); extract( $r, EXTR_SKIP ); global $page, $numpages, $multipage, $more; $output = ''; if ( $multipage ) { if ( 'number' == $next_or_number ) { $output .= $before; for ( $i = 1; $i <= $numpages; $i++ ) { $link = $link_before . str_replace( '%', $i, $pagelink ) . $link_after; if ( $i != $page || ! $more && 1 == $page ) $link = _wp_link_page( $i ) . $link . '</a>'; /** * Filter the HTML output of individual page number links. * * @since 3.6.0 * * @param string $link The page number HTML output. * @param int $i Page number for paginated posts' page links. */ $link = apply_filters( 'wp_link_pages_link', $link, $i ); $output .= $separator . $link; } $output .= $after; } elseif ( $more ) { $output .= $before; $i = $page - 1; if ( $i ) { $link = _wp_link_page( $i ) . $link_before . $previouspagelink . $link_after . '</a>'; /** This filter is documented in wp-includes/post-template.php */ $link = apply_filters( 'wp_link_pages_link', $link, $i ); $output .= $separator . $link; } $i = $page + 1; if ( $i <= $numpages ) { $link = _wp_link_page( $i ) . $link_before . $nextpagelink . $link_after . '</a>'; /** This filter is documented in wp-includes/post-template.php */ $link = apply_filters( 'wp_link_pages_link', $link, $i ); $output .= $separator . $link; } $output .= $after; } } /** * Filter the HTML output of page links for paginated posts. * * @since 3.6.0 * * @param string $output HTML output of paginated posts' page links. * @param array $args An array of arguments. */ $output = apply_filters( 'wp_link_pages', $output, $args ); 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'); } if ( is_preview() ) { $url = add_query_arg( array( 'preview' => 'true' ), $url ); if ( ( 'draft' !== $post->post_status ) && isset( $_GET['preview_id'], $_GET['preview_nonce'] ) ) { $url = add_query_arg( array( 'preview_id' => wp_unslash( $_GET['preview_id'] ), 'preview_nonce' => wp_unslash( $_GET['preview_nonce'] ) ), $url ); } } 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,', '); /** * Filter the HTML output of the li element in the post custom fields list. * * @since 2.2.0 * * @param string $html The HTML output for the li element. * @param string $key Meta key. * @param string $value Meta value. */ 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"; } /** * Filter the HTML output of a list of pages as a drop down. * * @since 2.1.0 * * @param string $output HTML output for drop down list of pages. */ $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(); /** * Filter the array of pages to exclude from the pages list. * * @since 2.1.0 * * @param array $exclude_array An array of page IDs to exclude. */ $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 = get_queried_object_id(); } elseif ( is_singular() ) { $queried_object = get_queried_object(); if ( is_post_type_hierarchical( $queried_object->post_type ) ) { $current_page = $queried_object->ID; } } $output .= walk_page_tree($pages, $r['depth'], $current_page, $r); if ( $r['title_li'] ) $output .= '</ul></li>'; } /** * Filter the HTML output of the pages to list. * * @since 1.5.1 * * @see wp_list_pages() * * @param string $output HTML output of the pages list. * @param array $r An array of page-listing arguments. */ $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 'menu_order, post_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 ); /** * Filter the arguments used to generate a page-based menu. * * @since 2.7.0 * * @see wp_page_menu() * * @param array $args An array of page menu arguments. */ $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( '/' ) . '">' . $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"; /** * Filter the HTML output of a page-based menu. * * @since 2.7.0 * * @see wp_page_menu() * * @param string $menu The HTML output. * @param array $args An array of arguments. */ $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']; foreach ( (array) $pages as $page ) { if ( $page->post_parent ) $r['pages_with_children'][ $page->post_parent ] = true; } $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. * * @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 = 0, $args = array(), $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( isset( $args['pages_with_children'][ $page->ID ] ) ) $css_class[] = 'page_item_has_children'; 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'; } /** * Filter the list of CSS classes to include with each page item in the list. * * @since 2.8.0 * * @see wp_list_pages() * * @param array $css_class An array of CSS classes to be applied * to each list item. * @param WP_Post $page Page data object. * @param int $depth Depth of page, used for padding. * @param array $args An array of arguments. * @param int $current_page ID of the current page. */ $css_class = implode( ' ', apply_filters( 'page_css_class', $css_class, $page, $depth, $args, $current_page ) ); if ( '' === $page->post_title ) $page->post_title = sprintf( __( '#%d (no title)' ), $page->ID ); /** This filter is documented in wp-includes/post-template.php */ $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. * * @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 = 0, $args = array(), $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 = $page->post_title; if ( '' === $title ) { $title = sprintf( __( '#%d (no title)' ), $page->ID ); } /** * Filter the page title when creating an HTML drop-down list of pages. * * @since 3.1.0 * * @param string $title Page title. * @param object $page Page data object. */ $title = apply_filters( 'list_pages', $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|WP_Post $id Optional. Post ID or post object. * @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|WP_Post $id Optional. Post ID or post object. * @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; /** * Filter a retrieved attachment page link. * * @since 2.7.0 * * @param string $link_html The page link HTML output. * @param int $id Post ID. * @param string $size Image size. Default 'thumbnail'. * @param bool $permalink Whether to add permalink to image. Default false. * @param bool $icon Whether to include an icon. Default false. * @param string|bool $text If string, will be link text. Default false. */ return apply_filters( 'wp_get_attachment_link', "<a href='$url'>$link_text</a>", $id, $size, $permalink, $icon, $text ); } /** * Wrap attachment in <<p>> element before content. * * @since 2.0.0 * * @param string $content * @return string */ function prepend_attachment($content) { $post = get_post(); if ( empty($post->post_type) || $post->post_type != 'attachment' ) return $content; if ( 0 === strpos( $post->post_mime_type, 'video' ) ) { $meta = wp_get_attachment_metadata( get_the_ID() ); $atts = array( 'src' => wp_get_attachment_url() ); if ( ! empty( $meta['width'] ) && ! empty( $meta['height'] ) ) { $atts['width'] = (int) $meta['width']; $atts['height'] = (int) $meta['height']; } $p = wp_video_shortcode( $atts ); } elseif ( 0 === strpos( $post->post_mime_type, 'audio' ) ) { $p = wp_audio_shortcode( array( 'src' => wp_get_attachment_url() ) ); } else { $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>'; } /** * Filter the attachment markup to be prepended to the post content. * * @since 2.0.0 * * @see prepend_attachment() * * @param string $p The attachment HTML output. */ $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. * @param int|WP_Post $post Optional. A post ID or post object. * @return string HTML content for password form for password protected post. */ function get_the_password_form( $post = 0 ) { $post = get_post( $post ); $label = 'pwbox-' . ( empty($post->ID) ? rand() : $post->ID ); $output = '<form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" class="post-password-form" method="post"> <p>' . __( 'This content 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> '; /** * Filter the HTML output for the protected post password form. * * If modifying the password field, please note that the core database schema * limits the password field to 20 characters regardless of the value of the * size attribute in the form input. * * @since 2.7.0 * * @param string $output The password form HTML output. */ 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 True on success, false on failure. */ 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 Optional. 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 ( ! $post || '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). * * @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 = _x( '%1$s [Autosave]', 'post revision title extra' ); /* translators: 1: date */ $currentf = _x( '%1$s [Current Revision]', 'post revision title extra' ); $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; } /** * Retrieve formatted date timestamp of a revision (linked to that revisions's page). * * @since 3.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 gravatar, user, i18n formatted datetimestamp or localized 'Current Revision'. */ function wp_post_revision_title_expanded( $revision, $link = true ) { if ( !$revision = get_post( $revision ) ) return $revision; if ( !in_array( $revision->post_type, array( 'post', 'page', 'revision' ) ) ) return false; $author = get_the_author_meta( 'display_name', $revision->post_author ); /* translators: revision date format, see http://php.net/date */ $datef = _x( 'j F, Y @ G:i:s', 'revision date format'); $gravatar = get_avatar( $revision->post_author, 24 ); $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>"; $revision_date_author = sprintf( /* translators: post revision title: 1: author avatar, 2: author name, 3: time ago, 4: date */ _x( '%1$s %2$s, %3$s ago (%4$s)', 'post revision title' ), $gravatar, $author, human_time_diff( strtotime( $revision->post_modified ), current_time( 'timestamp' ) ), $date ); $autosavef = __( '%1$s [Autosave]' ); $currentf = __( '%1$s [Current Revision]' ); if ( !wp_is_post_revision( $revision ) ) $revision_date_author = sprintf( $currentf, $revision_date_author ); elseif ( wp_is_post_autosave( $revision ) ) $revision_date_author = sprintf( $autosavef, $revision_date_author ); return $revision_date_author; } /** * 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. * * @since 2.6.0 * * @uses wp_get_post_revisions() * @uses wp_post_revision_title_expanded() * @uses get_edit_post_link() * @uses get_the_author_meta() * * @param int|WP_Post $post_id Optional. Post ID or post object. * @param string $type 'all' (default), 'revision' or 'autosave' * @return null */ function wp_list_post_revisions( $post_id = 0, $type = 'all' ) { if ( ! $post = get_post( $post_id ) ) return; // $args array with (parent, format, right, left, type) deprecated since 3.6 if ( is_array( $type ) ) { $type = ! empty( $type['type'] ) ? $type['type'] : $type; _deprecated_argument( __FUNCTION__, '3.6' ); } if ( ! $revisions = wp_get_post_revisions( $post->ID ) ) return; $rows = ''; foreach ( $revisions as $revision ) { if ( ! current_user_can( 'read_post', $revision->ID ) ) continue; $is_autosave = wp_is_post_autosave( $revision ); if ( ( 'revision' === $type && $is_autosave ) || ( 'autosave' === $type && ! $is_autosave ) ) continue; $rows .= "\t<li>" . wp_post_revision_title_expanded( $revision ) . "</li>\n"; } echo "<div class='hide-if-js'><p>" . __( 'JavaScript must be enabled to use this feature.' ) . "</p></div>\n"; echo "<ul class='post-revisions hide-if-no-js'>\n"; echo $rows; echo "</ul>"; }
01-wordpress-paypal
trunk/wp-includes/post-template.php
PHP
gpl3
49,877
<?php /** * WordPress implementation for PHP functions either missing from older PHP versions or not included by default. * * @package PHP * @access private */ // If gettext isn't available if ( !function_exists('_') ) { function _($string) { return $string; } } if ( !function_exists('mb_substr') ): function mb_substr( $str, $start, $length=null, $encoding=null ) { return _mb_substr($str, $start, $length, $encoding); } endif; function _mb_substr( $str, $start, $length=null, $encoding=null ) { // the solution below, works only for utf-8, so in case of a different // charset, just use built-in substr $charset = get_option( 'blog_charset' ); if ( !in_array( $charset, array('utf8', 'utf-8', 'UTF8', 'UTF-8') ) ) { return is_null( $length )? substr( $str, $start ) : substr( $str, $start, $length); } // use the regex unicode support to separate the UTF-8 characters into an array preg_match_all( '/./us', $str, $match ); $chars = is_null( $length )? array_slice( $match[0], $start ) : array_slice( $match[0], $start, $length ); return implode( '', $chars ); } if ( !function_exists('hash_hmac') ): function hash_hmac($algo, $data, $key, $raw_output = false) { return _hash_hmac($algo, $data, $key, $raw_output); } endif; function _hash_hmac($algo, $data, $key, $raw_output = false) { $packs = array('md5' => 'H32', 'sha1' => 'H40'); if ( !isset($packs[$algo]) ) return false; $pack = $packs[$algo]; if (strlen($key) > 64) $key = pack($pack, $algo($key)); $key = str_pad($key, 64, chr(0)); $ipad = (substr($key, 0, 64) ^ str_repeat(chr(0x36), 64)); $opad = (substr($key, 0, 64) ^ str_repeat(chr(0x5C), 64)); $hmac = $algo($opad . pack($pack, $algo($ipad . $data))); if ( $raw_output ) return pack( $pack, $hmac ); return $hmac; } if ( !function_exists('json_encode') ) { function json_encode( $string ) { global $wp_json; if ( !is_a($wp_json, 'Services_JSON') ) { require_once( ABSPATH . WPINC . '/class-json.php' ); $wp_json = new Services_JSON(); } return $wp_json->encodeUnsafe( $string ); } } if ( !function_exists('json_decode') ) { function json_decode( $string, $assoc_array = false ) { global $wp_json; if ( !is_a($wp_json, 'Services_JSON') ) { require_once( ABSPATH . WPINC . '/class-json.php' ); $wp_json = new Services_JSON(); } $res = $wp_json->decode( $string ); if ( $assoc_array ) $res = _json_decode_object_helper( $res ); return $res; } function _json_decode_object_helper($data) { if ( is_object($data) ) $data = get_object_vars($data); return is_array($data) ? array_map(__FUNCTION__, $data) : $data; } }
01-wordpress-paypal
trunk/wp-includes/compat.php
PHP
gpl3
2,635
<?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. Optional. * * @type int $width Width of the embed in pixels. * @type int $height Height of the embed in pixels. * } * @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 ) ) /** * Filter the returned embed handler. * * @since 2.9.0 * * @see WP_Embed::shortcode() * * @param mixed $return The shortcode callback function to call. * @param string $url The attempted embed URL. * @param array $attr An array of shortcode attributes. */ 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 ) ) /** * Filter the cached oEmbed HTML. * * @since 2.9.0 * * @see WP_Embed::shortcode() * * @param mixed $cache The cached HTML result, stored in post meta. * @param string $url The attempted embed URL. * @param array $attr An array of shortcode attributes. * @param int $post_ID Post ID. */ return apply_filters( 'embed_oembed_html', $cache, $url, $attr, $post_ID ); } /** * Filter whether to inspect the given URL for discoverable <link> tags. * * @since 2.9.0 * * @see WP_oEmbed::discover() * * @param bool false Whether to enable <link> tag discovery. Default false. */ $attr['discover'] = ( apply_filters( 'embed_oembed_discover', false ) && author_can( $post_ID, 'unfiltered_html' ) ); // Use oEmbed to get the 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 ) { /** This filter is documented in wp-includes/class-wp-embed.php */ 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 ); $post_types = array( 'post', 'page' ); /** * Filter the array of post types to cache oEmbed results for. * * @since 2.9.0 * * @param array $post_types Array of post types to cache oEmbed results for. Default 'post', 'page'. */ if ( empty($post->ID) || !in_array( $post->post_type, apply_filters( 'embed_cache_oembed_types', $post_types ) ) ) 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_url($url) . '">' . esc_html($url) . '</a>' : $url; /** * Filter the returned, maybe-linked embed URL. * * @since 2.9.0 * * @param string $output The linked or original URL. * @param string $url The original URL. */ return apply_filters( 'embed_maybe_make_link', $output, $url ); } } $GLOBALS['wp_embed'] = new WP_Embed();
01-wordpress-paypal
trunk/wp-includes/class-wp-embed.php
PHP
gpl3
10,429
<?php /** * RSS 0.92 Feed Template for displaying RSS 0.92 Posts feed. * * @package WordPress */ header('Content-Type: ' . feed_content_type('rss-http') . '; charset=' . get_option('blog_charset'), true); $more = 1; echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?> <rss version="0.92"> <channel> <title><?php bloginfo_rss('name'); wp_title_rss(); ?></title> <link><?php bloginfo_rss('url') ?></link> <description><?php bloginfo_rss('description') ?></description> <lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></lastBuildDate> <docs>http://backend.userland.com/rss092</docs> <language><?php bloginfo_rss( 'language' ); ?></language> <?php /** * Fires at the end of the RSS Feed Header. * * @since 2.0.0 */ do_action( 'rss_head' ); ?> <?php while (have_posts()) : the_post(); ?> <item> <title><?php the_title_rss() ?></title> <description><![CDATA[<?php the_excerpt_rss() ?>]]></description> <link><?php the_permalink_rss() ?></link> <?php /** * Fires at the end of each RSS feed item. * * @since 2.0.0 */ do_action( 'rss_item' ); ?> </item> <?php endwhile; ?> </channel> </rss>
01-wordpress-paypal
trunk/wp-includes/feed-rss.php
PHP
gpl3
1,215
<?php /** * WordPress Roles and Capabilities. * * @package WordPress * @subpackage User */ /** * WordPress User Roles. * * The role option is simple, the structure is organized by role name that store * the name in value of the 'name' key. The capabilities are stored as an array * in the value of the 'capability' key. * * <code> * array ( * 'rolename' => array ( * 'name' => 'rolename', * 'capabilities' => array() * ) * ) * </code> * * @since 2.0.0 * @package WordPress * @subpackage User */ class WP_Roles { /** * List of roles and capabilities. * * @since 2.0.0 * @access public * @var array */ var $roles; /** * List of the role objects. * * @since 2.0.0 * @access public * @var array */ var $role_objects = array(); /** * List of role names. * * @since 2.0.0 * @access public * @var array */ var $role_names = array(); /** * Option name for storing role list. * * @since 2.0.0 * @access public * @var string */ var $role_key; /** * Whether to use the database for retrieval and storage. * * @since 2.1.0 * @access public * @var bool */ var $use_db = true; /** * Constructor * * @since 2.0.0 */ function __construct() { $this->_init(); } /** * Set up the object properties. * * The role key is set to the current prefix for the $wpdb object with * 'user_roles' appended. If the $wp_user_roles global is set, then it will * be used and the role option will not be updated or used. * * @since 2.1.0 * @access protected * @uses $wpdb Used to get the database prefix. * @global array $wp_user_roles Used to set the 'roles' property value. */ function _init () { global $wpdb, $wp_user_roles; $this->role_key = $wpdb->get_blog_prefix() . 'user_roles'; if ( ! empty( $wp_user_roles ) ) { $this->roles = $wp_user_roles; $this->use_db = false; } else { $this->roles = get_option( $this->role_key ); } if ( empty( $this->roles ) ) return; $this->role_objects = array(); $this->role_names = array(); foreach ( array_keys( $this->roles ) as $role ) { $this->role_objects[$role] = new WP_Role( $role, $this->roles[$role]['capabilities'] ); $this->role_names[$role] = $this->roles[$role]['name']; } } /** * Reinitialize the object * * Recreates the role objects. This is typically called only by switch_to_blog() * after switching wpdb to a new blog ID. * * @since 3.5.0 * @access public */ function reinit() { // There is no need to reinit if using the wp_user_roles global. if ( ! $this->use_db ) return; global $wpdb, $wp_user_roles; // Duplicated from _init() to avoid an extra function call. $this->role_key = $wpdb->get_blog_prefix() . 'user_roles'; $this->roles = get_option( $this->role_key ); if ( empty( $this->roles ) ) return; $this->role_objects = array(); $this->role_names = array(); foreach ( array_keys( $this->roles ) as $role ) { $this->role_objects[$role] = new WP_Role( $role, $this->roles[$role]['capabilities'] ); $this->role_names[$role] = $this->roles[$role]['name']; } } /** * Add role name with capabilities to list. * * Updates the list of roles, if the role doesn't already exist. * * The capabilities are defined in the following format `array( 'read' => true );` * To explicitly deny a role a capability you set the value for that capability to false. * * @since 2.0.0 * @access public * * @param string $role Role name. * @param string $display_name Role display name. * @param array $capabilities List of role capabilities in the above format. * @return WP_Role|null WP_Role object if role is added, null if already exists. */ function add_role( $role, $display_name, $capabilities = array() ) { if ( isset( $this->roles[$role] ) ) return; $this->roles[$role] = array( 'name' => $display_name, 'capabilities' => $capabilities ); if ( $this->use_db ) update_option( $this->role_key, $this->roles ); $this->role_objects[$role] = new WP_Role( $role, $capabilities ); $this->role_names[$role] = $display_name; return $this->role_objects[$role]; } /** * Remove role by name. * * @since 2.0.0 * @access public * * @param string $role Role name. */ function remove_role( $role ) { if ( ! isset( $this->role_objects[$role] ) ) return; unset( $this->role_objects[$role] ); unset( $this->role_names[$role] ); unset( $this->roles[$role] ); if ( $this->use_db ) update_option( $this->role_key, $this->roles ); if ( get_option( 'default_role' ) == $role ) update_option( 'default_role', 'subscriber' ); } /** * Add capability to role. * * @since 2.0.0 * @access public * * @param string $role Role name. * @param string $cap Capability name. * @param bool $grant Optional, default is true. Whether role is capable of performing capability. */ function add_cap( $role, $cap, $grant = true ) { if ( ! isset( $this->roles[$role] ) ) return; $this->roles[$role]['capabilities'][$cap] = $grant; if ( $this->use_db ) update_option( $this->role_key, $this->roles ); } /** * Remove capability from role. * * @since 2.0.0 * @access public * * @param string $role Role name. * @param string $cap Capability name. */ function remove_cap( $role, $cap ) { if ( ! isset( $this->roles[$role] ) ) return; unset( $this->roles[$role]['capabilities'][$cap] ); if ( $this->use_db ) update_option( $this->role_key, $this->roles ); } /** * Retrieve role object by name. * * @since 2.0.0 * @access public * * @param string $role Role name. * @return WP_Role|null WP_Role object if found, null if the role does not exist. */ function get_role( $role ) { if ( isset( $this->role_objects[$role] ) ) return $this->role_objects[$role]; else return null; } /** * Retrieve list of role names. * * @since 2.0.0 * @access public * * @return array List of role names. */ function get_names() { return $this->role_names; } /** * Whether role name is currently in the list of available roles. * * @since 2.0.0 * @access public * * @param string $role Role name to look up. * @return bool */ function is_role( $role ) { return isset( $this->role_names[$role] ); } } /** * WordPress Role class. * * @since 2.0.0 * @package WordPress * @subpackage User */ class WP_Role { /** * Role name. * * @since 2.0.0 * @access public * @var string */ var $name; /** * List of capabilities the role contains. * * @since 2.0.0 * @access public * @var array */ var $capabilities; /** * Constructor - Set up object properties. * * The list of capabilities, must have the key as the name of the capability * and the value a boolean of whether it is granted to the role. * * @since 2.0.0 * @access public * * @param string $role Role name. * @param array $capabilities List of capabilities. */ function __construct( $role, $capabilities ) { $this->name = $role; $this->capabilities = $capabilities; } /** * Assign role a capability. * * @see WP_Roles::add_cap() Method uses implementation for role. * @since 2.0.0 * @access public * * @param string $cap Capability name. * @param bool $grant Whether role has capability privilege. */ function add_cap( $cap, $grant = true ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); $this->capabilities[$cap] = $grant; $wp_roles->add_cap( $this->name, $cap, $grant ); } /** * Remove capability from role. * * This is a container for {@link WP_Roles::remove_cap()} to remove the * capability from the role. That is to say, that {@link * WP_Roles::remove_cap()} implements the functionality, but it also makes * sense to use this class, because you don't need to enter the role name. * * @since 2.0.0 * @access public * * @param string $cap Capability name. */ function remove_cap( $cap ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); unset( $this->capabilities[$cap] ); $wp_roles->remove_cap( $this->name, $cap ); } /** * Whether role has capability. * * The capabilities is passed through the 'role_has_cap' filter. The first * parameter for the hook is the list of capabilities the class has * assigned. The second parameter is the capability name to look for. The * third and final parameter for the hook is the role name. * * @since 2.0.0 * @access public * * @param string $cap Capability name. * @return bool True, if user has capability. False, if doesn't have capability. */ function has_cap( $cap ) { /** * Filter which capabilities a role has. * * @since 2.0.0 * * @param array $capabilities Array of role capabilities. * @param string $cap Capability name. * @param string $name Role name. */ $capabilities = apply_filters( 'role_has_cap', $this->capabilities, $cap, $this->name ); if ( !empty( $capabilities[$cap] ) ) return $capabilities[$cap]; else return false; } } /** * WordPress User class. * * @since 2.0.0 * @package WordPress * @subpackage User */ class WP_User { /** * User data container. * * @since 2.0.0 * @access private * @var array */ var $data; /** * The user's ID. * * @since 2.1.0 * @access public * @var int */ var $ID = 0; /** * The individual capabilities the user has been given. * * @since 2.0.0 * @access public * @var array */ var $caps = array(); /** * User metadata option name. * * @since 2.0.0 * @access public * @var string */ var $cap_key; /** * The roles the user is part of. * * @since 2.0.0 * @access public * @var array */ var $roles = array(); /** * All capabilities the user has, including individual and role based. * * @since 2.0.0 * @access public * @var array */ var $allcaps = array(); /** * The filter context applied to user data fields. * * @since 2.9.0 * @access private * @var string */ var $filter = null; private static $back_compat_keys; /** * Constructor * * Retrieves the userdata and passes it to {@link WP_User::init()}. * * @since 2.0.0 * @access public * * @param int|string|stdClass|WP_User $id User's ID, a WP_User object, or a user object from the DB. * @param string $name Optional. User's username * @param int $blog_id Optional Blog ID, defaults to current blog. * @return WP_User */ function __construct( $id = 0, $name = '', $blog_id = '' ) { if ( ! isset( self::$back_compat_keys ) ) { $prefix = $GLOBALS['wpdb']->prefix; self::$back_compat_keys = array( 'user_firstname' => 'first_name', 'user_lastname' => 'last_name', 'user_description' => 'description', 'user_level' => $prefix . 'user_level', $prefix . 'usersettings' => $prefix . 'user-settings', $prefix . 'usersettingstime' => $prefix . 'user-settings-time', ); } if ( is_a( $id, 'WP_User' ) ) { $this->init( $id->data, $blog_id ); return; } elseif ( is_object( $id ) ) { $this->init( $id, $blog_id ); return; } if ( ! empty( $id ) && ! is_numeric( $id ) ) { $name = $id; $id = 0; } if ( $id ) $data = self::get_data_by( 'id', $id ); else $data = self::get_data_by( 'login', $name ); if ( $data ) $this->init( $data, $blog_id ); } /** * Sets up object properties, including capabilities. * * @param object $data User DB row object * @param int $blog_id Optional. The blog id to initialize for */ function init( $data, $blog_id = '' ) { $this->data = $data; $this->ID = (int) $data->ID; $this->for_blog( $blog_id ); } /** * Return only the main user fields * * @since 3.3.0 * * @param string $field The field to query against: 'id', 'slug', 'email' or 'login' * @param string|int $value The field value * @return object Raw user object */ static function get_data_by( $field, $value ) { global $wpdb; if ( 'id' == $field ) { // Make sure the value is numeric to avoid casting objects, for example, // to int 1. if ( ! is_numeric( $value ) ) return false; $value = intval( $value ); if ( $value < 1 ) return false; } else { $value = trim( $value ); } if ( !$value ) return false; switch ( $field ) { case 'id': $user_id = $value; $db_field = 'ID'; break; case 'slug': $user_id = wp_cache_get($value, 'userslugs'); $db_field = 'user_nicename'; break; case 'email': $user_id = wp_cache_get($value, 'useremail'); $db_field = 'user_email'; break; case 'login': $value = sanitize_user( $value ); $user_id = wp_cache_get($value, 'userlogins'); $db_field = 'user_login'; break; default: return false; } if ( false !== $user_id ) { if ( $user = wp_cache_get( $user_id, 'users' ) ) return $user; } if ( !$user = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->users WHERE $db_field = %s", $value ) ) ) return false; update_user_caches( $user ); return $user; } /** * Magic method for checking the existence of a certain custom field * * @since 3.3.0 */ function __isset( $key ) { if ( 'id' == $key ) { _deprecated_argument( 'WP_User->id', '2.1', __( 'Use <code>WP_User->ID</code> instead.' ) ); $key = 'ID'; } if ( isset( $this->data->$key ) ) return true; if ( isset( self::$back_compat_keys[ $key ] ) ) $key = self::$back_compat_keys[ $key ]; return metadata_exists( 'user', $this->ID, $key ); } /** * Magic method for accessing custom fields * * @since 3.3.0 */ function __get( $key ) { if ( 'id' == $key ) { _deprecated_argument( 'WP_User->id', '2.1', __( 'Use <code>WP_User->ID</code> instead.' ) ); return $this->ID; } if ( isset( $this->data->$key ) ) { $value = $this->data->$key; } else { if ( isset( self::$back_compat_keys[ $key ] ) ) $key = self::$back_compat_keys[ $key ]; $value = get_user_meta( $this->ID, $key, true ); } if ( $this->filter ) { $value = sanitize_user_field( $key, $value, $this->ID, $this->filter ); } return $value; } /** * Magic method for setting custom fields * * @since 3.3.0 */ function __set( $key, $value ) { if ( 'id' == $key ) { _deprecated_argument( 'WP_User->id', '2.1', __( 'Use <code>WP_User->ID</code> instead.' ) ); $this->ID = $value; return; } $this->data->$key = $value; } /** * Determine whether the user exists in the database. * * @since 3.4.0 * @access public * * @return bool True if user exists in the database, false if not. */ function exists() { return ! empty( $this->ID ); } /** * Retrieve the value of a property or meta key. * * Retrieves from the users and usermeta table. * * @since 3.3.0 * * @param string $key Property */ function get( $key ) { return $this->__get( $key ); } /** * Determine whether a property or meta key is set * * Consults the users and usermeta tables. * * @since 3.3.0 * * @param string $key Property */ function has_prop( $key ) { return $this->__isset( $key ); } /** * Return an array representation. * * @since 3.5.0 * * @return array Array representation. */ function to_array() { return get_object_vars( $this->data ); } /** * Set up capability object properties. * * Will set the value for the 'cap_key' property to current database table * prefix, followed by 'capabilities'. Will then check to see if the * property matching the 'cap_key' exists and is an array. If so, it will be * used. * * @access protected * @since 2.1.0 * * @param string $cap_key Optional capability key */ function _init_caps( $cap_key = '' ) { global $wpdb; if ( empty($cap_key) ) $this->cap_key = $wpdb->get_blog_prefix() . 'capabilities'; else $this->cap_key = $cap_key; $this->caps = get_user_meta( $this->ID, $this->cap_key, true ); if ( ! is_array( $this->caps ) ) $this->caps = array(); $this->get_role_caps(); } /** * Retrieve all of the role capabilities and merge with individual capabilities. * * All of the capabilities of the roles the user belongs to are merged with * the users individual roles. This also means that the user can be denied * specific roles that their role might have, but the specific user isn't * granted permission to. * * @since 2.0.0 * @uses $wp_roles * @access public * * @return array List of all capabilities for the user. */ function get_role_caps() { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); //Filter out caps that are not role names and assign to $this->roles if ( is_array( $this->caps ) ) $this->roles = array_filter( array_keys( $this->caps ), array( $wp_roles, 'is_role' ) ); //Build $allcaps from role caps, overlay user's $caps $this->allcaps = array(); foreach ( (array) $this->roles as $role ) { $the_role = $wp_roles->get_role( $role ); $this->allcaps = array_merge( (array) $this->allcaps, (array) $the_role->capabilities ); } $this->allcaps = array_merge( (array) $this->allcaps, (array) $this->caps ); return $this->allcaps; } /** * Add role to user. * * Updates the user's meta data option with capabilities and roles. * * @since 2.0.0 * @access public * * @param string $role Role name. */ function add_role( $role ) { $this->caps[$role] = true; update_user_meta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); $this->update_user_level_from_caps(); } /** * Remove role from user. * * @since 2.0.0 * @access public * * @param string $role Role name. */ function remove_role( $role ) { if ( !in_array($role, $this->roles) ) return; unset( $this->caps[$role] ); update_user_meta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); $this->update_user_level_from_caps(); } /** * Set the role of the user. * * This will remove the previous roles of the user and assign the user the * new one. You can set the role to an empty string and it will remove all * of the roles from the user. * * @since 2.0.0 * @access public * * @param string $role Role name. */ function set_role( $role ) { if ( 1 == count( $this->roles ) && $role == current( $this->roles ) ) return; foreach ( (array) $this->roles as $oldrole ) unset( $this->caps[$oldrole] ); $old_roles = $this->roles; if ( !empty( $role ) ) { $this->caps[$role] = true; $this->roles = array( $role => true ); } else { $this->roles = false; } update_user_meta( $this->ID, $this->cap_key, $this->caps ); $this->get_role_caps(); $this->update_user_level_from_caps(); /** * Fires after the user's role has changed. * * @since 2.9.0 * @since 3.6.0 Added $old_roles to include an array of the user's previous roles. * * @param int $user_id The user ID. * @param string $role The new role. * @param array $old_roles An array of the user's previous roles. */ do_action( 'set_user_role', $this->ID, $role, $old_roles ); } /** * Choose the maximum level the user has. * * Will compare the level from the $item parameter against the $max * parameter. If the item is incorrect, then just the $max parameter value * will be returned. * * Used to get the max level based on the capabilities the user has. This * is also based on roles, so if the user is assigned the Administrator role * then the capability 'level_10' will exist and the user will get that * value. * * @since 2.0.0 * @access public * * @param int $max Max level of user. * @param string $item Level capability name. * @return int Max Level. */ function level_reduction( $max, $item ) { if ( preg_match( '/^level_(10|[0-9])$/i', $item, $matches ) ) { $level = intval( $matches[1] ); return max( $max, $level ); } else { return $max; } } /** * Update the maximum user level for the user. * * Updates the 'user_level' user metadata (includes prefix that is the * database table prefix) with the maximum user level. Gets the value from * the all of the capabilities that the user has. * * @since 2.0.0 * @access public */ function update_user_level_from_caps() { global $wpdb; $this->user_level = array_reduce( array_keys( $this->allcaps ), array( $this, 'level_reduction' ), 0 ); update_user_meta( $this->ID, $wpdb->get_blog_prefix() . 'user_level', $this->user_level ); } /** * Add capability and grant or deny access to capability. * * @since 2.0.0 * @access public * * @param string $cap Capability name. * @param bool $grant Whether to grant capability to user. */ function add_cap( $cap, $grant = true ) { $this->caps[$cap] = $grant; update_user_meta( $this->ID, $this->cap_key, $this->caps ); } /** * Remove capability from user. * * @since 2.0.0 * @access public * * @param string $cap Capability name. */ function remove_cap( $cap ) { if ( ! isset( $this->caps[$cap] ) ) return; unset( $this->caps[$cap] ); update_user_meta( $this->ID, $this->cap_key, $this->caps ); } /** * Remove all of the capabilities of the user. * * @since 2.1.0 * @access public */ function remove_all_caps() { global $wpdb; $this->caps = array(); delete_user_meta( $this->ID, $this->cap_key ); delete_user_meta( $this->ID, $wpdb->get_blog_prefix() . 'user_level' ); $this->get_role_caps(); } /** * Whether user has capability or role name. * * This is useful for looking up whether the user has a specific role * assigned to the user. The second optional parameter can also be used to * check for capabilities against a specific object, such as a post or user. * * @since 2.0.0 * @access public * * @param string|int $cap Capability or role name to search. * @return bool True, if user has capability; false, if user does not have capability. */ function has_cap( $cap ) { if ( is_numeric( $cap ) ) { _deprecated_argument( __FUNCTION__, '2.0', __('Usage of user levels by plugins and themes is deprecated. Use roles and capabilities instead.') ); $cap = $this->translate_level_to_cap( $cap ); } $args = array_slice( func_get_args(), 1 ); $args = array_merge( array( $cap, $this->ID ), $args ); $caps = call_user_func_array( 'map_meta_cap', $args ); // Multisite super admin has all caps by definition, Unless specifically denied. if ( is_multisite() && is_super_admin( $this->ID ) ) { if ( in_array('do_not_allow', $caps) ) return false; return true; } /** * Dynamically filter a user's capabilities. * * @since 2.0.0 * @since 3.7.0 Added the user object. * * @param array $allcaps An array of all the role's capabilities. * @param array $caps Actual capabilities for meta capability. * @param array $args Optional parameters passed to has_cap(), typically object ID. * @param WP_User $user The user object. */ // Must have ALL requested caps $capabilities = apply_filters( 'user_has_cap', $this->allcaps, $caps, $args, $this ); $capabilities['exist'] = true; // Everyone is allowed to exist foreach ( (array) $caps as $cap ) { if ( empty( $capabilities[ $cap ] ) ) return false; } return true; } /** * Convert numeric level to level capability name. * * Prepends 'level_' to level number. * * @since 2.0.0 * @access public * * @param int $level Level number, 1 to 10. * @return string */ function translate_level_to_cap( $level ) { return 'level_' . $level; } /** * Set the blog to operate on. Defaults to the current blog. * * @since 3.0.0 * * @param int $blog_id Optional Blog ID, defaults to current blog. */ function for_blog( $blog_id = '' ) { global $wpdb; if ( ! empty( $blog_id ) ) $cap_key = $wpdb->get_blog_prefix( $blog_id ) . 'capabilities'; else $cap_key = ''; $this->_init_caps( $cap_key ); } } /** * Map meta capabilities to primitive capabilities. * * This does not actually compare whether the user ID has the actual capability, * just what the capability or capabilities are. Meta capability list value can * be 'delete_user', 'edit_user', 'remove_user', 'promote_user', 'delete_post', * 'delete_page', 'edit_post', 'edit_page', 'read_post', or 'read_page'. * * @since 2.0.0 * * @param string $cap Capability name. * @param int $user_id User ID. * @return array Actual capabilities for meta capability. */ function map_meta_cap( $cap, $user_id ) { $args = array_slice( func_get_args(), 2 ); $caps = array(); switch ( $cap ) { case 'remove_user': $caps[] = 'remove_users'; break; case 'promote_user': $caps[] = 'promote_users'; break; case 'edit_user': case 'edit_users': // Allow user to edit itself if ( 'edit_user' == $cap && isset( $args[0] ) && $user_id == $args[0] ) break; // If multisite these caps are allowed only for super admins. if ( is_multisite() && !is_super_admin( $user_id ) ) $caps[] = 'do_not_allow'; else $caps[] = 'edit_users'; // edit_user maps to edit_users. break; case 'delete_post': case 'delete_page': $post = get_post( $args[0] ); if ( 'revision' == $post->post_type ) { $post = get_post( $post->post_parent ); } $post_type = get_post_type_object( $post->post_type ); if ( ! $post_type->map_meta_cap ) { $caps[] = $post_type->cap->$cap; // Prior to 3.1 we would re-call map_meta_cap here. if ( 'delete_post' == $cap ) $cap = $post_type->cap->$cap; break; } // If the post author is set and the user is the author... if ( $post->post_author && $user_id == $post->post_author ) { // If the post is published... if ( 'publish' == $post->post_status ) { $caps[] = $post_type->cap->delete_published_posts; } elseif ( 'trash' == $post->post_status ) { if ( 'publish' == get_post_meta( $post->ID, '_wp_trash_meta_status', true ) ) { $caps[] = $post_type->cap->delete_published_posts; } } else { // If the post is draft... $caps[] = $post_type->cap->delete_posts; } } else { // The user is trying to edit someone else's post. $caps[] = $post_type->cap->delete_others_posts; // The post is published, extra cap required. if ( 'publish' == $post->post_status ) { $caps[] = $post_type->cap->delete_published_posts; } elseif ( 'private' == $post->post_status ) { $caps[] = $post_type->cap->delete_private_posts; } } break; // edit_post breaks down to edit_posts, edit_published_posts, or // edit_others_posts case 'edit_post': case 'edit_page': $post = get_post( $args[0] ); if ( empty( $post ) ) break; if ( 'revision' == $post->post_type ) { $post = get_post( $post->post_parent ); } $post_type = get_post_type_object( $post->post_type ); if ( ! $post_type->map_meta_cap ) { $caps[] = $post_type->cap->$cap; // Prior to 3.1 we would re-call map_meta_cap here. if ( 'edit_post' == $cap ) $cap = $post_type->cap->$cap; break; } // If the post author is set and the user is the author... if ( $post->post_author && $user_id == $post->post_author ) { // If the post is published... if ( 'publish' == $post->post_status ) { $caps[] = $post_type->cap->edit_published_posts; } elseif ( 'trash' == $post->post_status ) { if ( 'publish' == get_post_meta( $post->ID, '_wp_trash_meta_status', true ) ) { $caps[] = $post_type->cap->edit_published_posts; } } else { // If the post is draft... $caps[] = $post_type->cap->edit_posts; } } else { // The user is trying to edit someone else's post. $caps[] = $post_type->cap->edit_others_posts; // The post is published, extra cap required. if ( 'publish' == $post->post_status ) { $caps[] = $post_type->cap->edit_published_posts; } elseif ( 'private' == $post->post_status ) { $caps[] = $post_type->cap->edit_private_posts; } } break; case 'read_post': case 'read_page': $post = get_post( $args[0] ); if ( 'revision' == $post->post_type ) { $post = get_post( $post->post_parent ); } $post_type = get_post_type_object( $post->post_type ); if ( ! $post_type->map_meta_cap ) { $caps[] = $post_type->cap->$cap; // Prior to 3.1 we would re-call map_meta_cap here. if ( 'read_post' == $cap ) $cap = $post_type->cap->$cap; break; } $status_obj = get_post_status_object( $post->post_status ); if ( $status_obj->public ) { $caps[] = $post_type->cap->read; break; } if ( $post->post_author && $user_id == $post->post_author ) { $caps[] = $post_type->cap->read; } elseif ( $status_obj->private ) { $caps[] = $post_type->cap->read_private_posts; } else { $caps = map_meta_cap( 'edit_post', $user_id, $post->ID ); } break; case 'publish_post': $post = get_post( $args[0] ); $post_type = get_post_type_object( $post->post_type ); $caps[] = $post_type->cap->publish_posts; break; case 'edit_post_meta': case 'delete_post_meta': case 'add_post_meta': $post = get_post( $args[0] ); $caps = map_meta_cap( 'edit_post', $user_id, $post->ID ); $meta_key = isset( $args[ 1 ] ) ? $args[ 1 ] : false; if ( $meta_key && has_filter( "auth_post_meta_{$meta_key}" ) ) { /** * Filter whether the user is allowed to add post meta to a post. * * The dynamic portion of the hook name, $meta_key, refers to the * meta key passed to map_meta_cap(). * * @since 3.3.0 * * @param bool $allowed Whether the user can add the post meta. Default false. * @param string $meta_key The meta key. * @param int $post_id Post ID. * @param int $user_id User ID. * @param string $cap Capability name. * @param array $caps User capabilities. */ $allowed = apply_filters( "auth_post_meta_{$meta_key}", false, $meta_key, $post->ID, $user_id, $cap, $caps ); if ( ! $allowed ) $caps[] = $cap; } elseif ( $meta_key && is_protected_meta( $meta_key, 'post' ) ) { $caps[] = $cap; } break; case 'edit_comment': $comment = get_comment( $args[0] ); if ( empty( $comment ) ) break; $post = get_post( $comment->comment_post_ID ); $caps = map_meta_cap( 'edit_post', $user_id, $post->ID ); break; case 'unfiltered_upload': if ( defined('ALLOW_UNFILTERED_UPLOADS') && ALLOW_UNFILTERED_UPLOADS && ( !is_multisite() || is_super_admin( $user_id ) ) ) $caps[] = $cap; else $caps[] = 'do_not_allow'; break; case 'unfiltered_html' : // Disallow unfiltered_html for all users, even admins and super admins. if ( defined( 'DISALLOW_UNFILTERED_HTML' ) && DISALLOW_UNFILTERED_HTML ) $caps[] = 'do_not_allow'; elseif ( is_multisite() && ! is_super_admin( $user_id ) ) $caps[] = 'do_not_allow'; else $caps[] = $cap; break; case 'edit_files': case 'edit_plugins': case 'edit_themes': // Disallow the file editors. if ( defined( 'DISALLOW_FILE_EDIT' ) && DISALLOW_FILE_EDIT ) $caps[] = 'do_not_allow'; elseif ( defined( 'DISALLOW_FILE_MODS' ) && DISALLOW_FILE_MODS ) $caps[] = 'do_not_allow'; elseif ( is_multisite() && ! is_super_admin( $user_id ) ) $caps[] = 'do_not_allow'; else $caps[] = $cap; break; case 'update_plugins': case 'delete_plugins': case 'install_plugins': case 'update_themes': case 'delete_themes': case 'install_themes': case 'update_core': // Disallow anything that creates, deletes, or updates core, plugin, or theme files. // Files in uploads are excepted. if ( defined( 'DISALLOW_FILE_MODS' ) && DISALLOW_FILE_MODS ) $caps[] = 'do_not_allow'; elseif ( is_multisite() && ! is_super_admin( $user_id ) ) $caps[] = 'do_not_allow'; else $caps[] = $cap; break; case 'activate_plugins': $caps[] = $cap; if ( is_multisite() ) { // update_, install_, and delete_ are handled above with is_super_admin(). $menu_perms = get_site_option( 'menu_items', array() ); if ( empty( $menu_perms['plugins'] ) ) $caps[] = 'manage_network_plugins'; } break; case 'delete_user': case 'delete_users': // If multisite only super admins can delete users. if ( is_multisite() && ! is_super_admin( $user_id ) ) $caps[] = 'do_not_allow'; else $caps[] = 'delete_users'; // delete_user maps to delete_users. break; case 'create_users': if ( !is_multisite() ) $caps[] = $cap; elseif ( is_super_admin() || get_site_option( 'add_new_users' ) ) $caps[] = $cap; else $caps[] = 'do_not_allow'; break; case 'manage_links' : if ( get_option( 'link_manager_enabled' ) ) $caps[] = $cap; else $caps[] = 'do_not_allow'; break; default: // Handle meta capabilities for custom post types. $post_type_meta_caps = _post_type_meta_capabilities(); if ( isset( $post_type_meta_caps[ $cap ] ) ) { $args = array_merge( array( $post_type_meta_caps[ $cap ], $user_id ), $args ); return call_user_func_array( 'map_meta_cap', $args ); } // If no meta caps match, return the original cap. $caps[] = $cap; } /** * Filter a user's capabilities depending on specific context and/or privilege. * * @since 2.8.0 * * @param array $caps Returns the user's actual capabilities. * @param string $cap Capability name. * @param int $user_id The user ID. * @param array $args Adds the context to the cap. Typically the object ID. */ return apply_filters( 'map_meta_cap', $caps, $cap, $user_id, $args ); } /** * Whether current user has capability or role. * * @since 2.0.0 * * @param string $capability Capability or role name. * @return bool */ function current_user_can( $capability ) { $current_user = wp_get_current_user(); if ( empty( $current_user ) ) return false; $args = array_slice( func_get_args(), 1 ); $args = array_merge( array( $capability ), $args ); return call_user_func_array( array( $current_user, 'has_cap' ), $args ); } /** * Whether current user has a capability or role for a given blog. * * @since 3.0.0 * * @param int $blog_id Blog ID * @param string $capability Capability or role name. * @return bool */ function current_user_can_for_blog( $blog_id, $capability ) { if ( is_multisite() ) switch_to_blog( $blog_id ); $current_user = wp_get_current_user(); if ( empty( $current_user ) ) return false; $args = array_slice( func_get_args(), 2 ); $args = array_merge( array( $capability ), $args ); $can = call_user_func_array( array( $current_user, 'has_cap' ), $args ); if ( is_multisite() ) restore_current_blog(); return $can; } /** * Whether author of supplied post has capability or role. * * @since 2.9.0 * * @param int|object $post Post ID or post object. * @param string $capability Capability or role name. * @return bool */ function author_can( $post, $capability ) { if ( !$post = get_post($post) ) return false; $author = get_userdata( $post->post_author ); if ( ! $author ) return false; $args = array_slice( func_get_args(), 2 ); $args = array_merge( array( $capability ), $args ); return call_user_func_array( array( $author, 'has_cap' ), $args ); } /** * Whether a particular user has capability or role. * * @since 3.1.0 * * @param int|object $user User ID or object. * @param string $capability Capability or role name. * @return bool */ function user_can( $user, $capability ) { if ( ! is_object( $user ) ) $user = get_userdata( $user ); if ( ! $user || ! $user->exists() ) return false; $args = array_slice( func_get_args(), 2 ); $args = array_merge( array( $capability ), $args ); return call_user_func_array( array( $user, 'has_cap' ), $args ); } /** * Retrieve role object. * * @see WP_Roles::get_role() Uses method to retrieve role object. * @since 2.0.0 * * @param string $role Role name. * @return WP_Role|null WP_Role object if found, null if the role does not exist. */ function get_role( $role ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); return $wp_roles->get_role( $role ); } /** * Add role, if it does not exist. * * @see WP_Roles::add_role() Uses method to add role. * @since 2.0.0 * * @param string $role Role name. * @param string $display_name Display name for role. * @param array $capabilities List of capabilities, e.g. array( 'edit_posts' => true, 'delete_posts' => false ); * @return WP_Role|null WP_Role object if role is added, null if already exists. */ function add_role( $role, $display_name, $capabilities = array() ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); return $wp_roles->add_role( $role, $display_name, $capabilities ); } /** * Remove role, if it exists. * * @see WP_Roles::remove_role() Uses method to remove role. * @since 2.0.0 * * @param string $role Role name. */ function remove_role( $role ) { global $wp_roles; if ( ! isset( $wp_roles ) ) $wp_roles = new WP_Roles(); $wp_roles->remove_role( $role ); } /** * Retrieve a list of super admins. * * @since 3.0.0 * * @uses $super_admins Super admins global variable, if set. * * @return array List of super admin logins */ function get_super_admins() { global $super_admins; if ( isset($super_admins) ) return $super_admins; else return get_site_option( 'site_admins', array('admin') ); } /** * Determine if user is a site admin. * * @since 3.0.0 * * @param int $user_id (Optional) The ID of a user. Defaults to the current user. * @return bool True if the user is a site admin. */ function is_super_admin( $user_id = false ) { if ( ! $user_id || $user_id == get_current_user_id() ) $user = wp_get_current_user(); else $user = get_userdata( $user_id ); if ( ! $user || ! $user->exists() ) return false; if ( is_multisite() ) { $super_admins = get_super_admins(); if ( is_array( $super_admins ) && in_array( $user->user_login, $super_admins ) ) return true; } else { if ( $user->has_cap('delete_users') ) return true; } return false; }
01-wordpress-paypal
trunk/wp-includes/capabilities.php
PHP
gpl3
38,094
<?php /** * WordPress Diff bastard child of old MediaWiki Diff Formatter. * * Basically all that remains is the table structure and some method names. * * @package WordPress * @subpackage Diff */ if ( !class_exists( 'Text_Diff' ) ) { /** Text_Diff class */ require( dirname(__FILE__).'/Text/Diff.php' ); /** Text_Diff_Renderer class */ require( dirname(__FILE__).'/Text/Diff/Renderer.php' ); /** Text_Diff_Renderer_inline class */ require( dirname(__FILE__).'/Text/Diff/Renderer/inline.php' ); } /** * Table renderer to display the diff lines. * * @since 2.6.0 * @uses Text_Diff_Renderer Extends */ class WP_Text_Diff_Renderer_Table extends Text_Diff_Renderer { /** * @see Text_Diff_Renderer::_leading_context_lines * @var int * @access protected * @since 2.6.0 */ var $_leading_context_lines = 10000; /** * @see Text_Diff_Renderer::_trailing_context_lines * @var int * @access protected * @since 2.6.0 */ var $_trailing_context_lines = 10000; /** * {@internal Missing Description}} * * @var float * @access protected * @since 2.6.0 */ var $_diff_threshold = 0.6; /** * Inline display helper object name. * * @var string * @access protected * @since 2.6.0 */ var $inline_diff_renderer = 'WP_Text_Diff_Renderer_inline'; /** * Should we show the split view or not * * @var string * @access protected * @since 3.6.0 */ var $_show_split_view = true; /** * Constructor - Call parent constructor with params array. * * This will set class properties based on the key value pairs in the array. * * @since 2.6.0 * * @param array $params */ function __construct( $params = array() ) { parent::__construct( $params ); if ( isset( $params[ 'show_split_view' ] ) ) $this->_show_split_view = $params[ 'show_split_view' ]; } /** * @ignore * * @param string $header * @return string */ function _startBlock( $header ) { return ''; } /** * @ignore * * @param array $lines * @param string $prefix */ function _lines( $lines, $prefix=' ' ) { } /** * @ignore * * @param string $line HTML-escape the value. * @return string */ function addedLine( $line ) { return "<td class='diff-addedline'>{$line}</td>"; } /** * @ignore * * @param string $line HTML-escape the value. * @return string */ function deletedLine( $line ) { return "<td class='diff-deletedline'>{$line}</td>"; } /** * @ignore * * @param string $line HTML-escape the value. * @return string */ function contextLine( $line ) { return "<td class='diff-context'>{$line}</td>"; } /** * @ignore * * @return string */ function emptyLine() { return '<td>&nbsp;</td>'; } /** * @ignore * @access private * * @param array $lines * @param bool $encode * @return string */ function _added( $lines, $encode = true ) { $r = ''; foreach ($lines as $line) { if ( $encode ) $line = htmlspecialchars( $line ); if ( $this->_show_split_view ) { $r .= '<tr>' . $this->emptyLine() . $this->emptyLine() . $this->addedLine( $line ) . "</tr>\n"; } else { $r .= '<tr>' . $this->addedLine( $line ) . "</tr>\n"; } } return $r; } /** * @ignore * @access private * * @param array $lines * @param bool $encode * @return string */ function _deleted( $lines, $encode = true ) { $r = ''; foreach ($lines as $line) { if ( $encode ) $line = htmlspecialchars( $line ); if ( $this->_show_split_view ) { $r .= '<tr>' . $this->deletedLine( $line ) . $this->emptyLine() . $this->emptyLine() . "</tr>\n"; } else { $r .= '<tr>' . $this->deletedLine( $line ) . "</tr>\n"; } } return $r; } /** * @ignore * @access private * * @param array $lines * @param bool $encode * @return string */ function _context( $lines, $encode = true ) { $r = ''; foreach ($lines as $line) { if ( $encode ) $line = htmlspecialchars( $line ); if ( $this->_show_split_view ) { $r .= '<tr>' . $this->contextLine( $line ) . $this->emptyLine() . $this->contextLine( $line ) . "</tr>\n"; } else { $r .= '<tr>' . $this->contextLine( $line ) . "</tr>\n"; } } return $r; } /** * Process changed lines to do word-by-word diffs for extra highlighting. * * (TRAC style) sometimes these lines can actually be deleted or added rows. * We do additional processing to figure that out * * @access private * @since 2.6.0 * * @param array $orig * @param array $final * @return string */ function _changed( $orig, $final ) { $r = ''; // Does the aforementioned additional processing // *_matches tell what rows are "the same" in orig and final. Those pairs will be diffed to get word changes // match is numeric: an index in other column // match is 'X': no match. It is a new row // *_rows are column vectors for the orig column and the final column. // row >= 0: an indix of the $orig or $final array // row < 0: a blank row for that column list($orig_matches, $final_matches, $orig_rows, $final_rows) = $this->interleave_changed_lines( $orig, $final ); // These will hold the word changes as determined by an inline diff $orig_diffs = array(); $final_diffs = array(); // Compute word diffs for each matched pair using the inline diff foreach ( $orig_matches as $o => $f ) { if ( is_numeric($o) && is_numeric($f) ) { $text_diff = new Text_Diff( 'auto', array( array($orig[$o]), array($final[$f]) ) ); $renderer = new $this->inline_diff_renderer; $diff = $renderer->render( $text_diff ); // If they're too different, don't include any <ins> or <dels> if ( $diff_count = preg_match_all( '!(<ins>.*?</ins>|<del>.*?</del>)!', $diff, $diff_matches ) ) { // length of all text between <ins> or <del> $stripped_matches = strlen(strip_tags( join(' ', $diff_matches[0]) )); // since we count lengith of text between <ins> or <del> (instead of picking just one), // we double the length of chars not in those tags. $stripped_diff = strlen(strip_tags( $diff )) * 2 - $stripped_matches; $diff_ratio = $stripped_matches / $stripped_diff; if ( $diff_ratio > $this->_diff_threshold ) continue; // Too different. Don't save diffs. } // Un-inline the diffs by removing del or ins $orig_diffs[$o] = preg_replace( '|<ins>.*?</ins>|', '', $diff ); $final_diffs[$f] = preg_replace( '|<del>.*?</del>|', '', $diff ); } } foreach ( array_keys($orig_rows) as $row ) { // Both columns have blanks. Ignore them. if ( $orig_rows[$row] < 0 && $final_rows[$row] < 0 ) continue; // If we have a word based diff, use it. Otherwise, use the normal line. if ( isset( $orig_diffs[$orig_rows[$row]] ) ) $orig_line = $orig_diffs[$orig_rows[$row]]; elseif ( isset( $orig[$orig_rows[$row]] ) ) $orig_line = htmlspecialchars($orig[$orig_rows[$row]]); else $orig_line = ''; if ( isset( $final_diffs[$final_rows[$row]] ) ) $final_line = $final_diffs[$final_rows[$row]]; elseif ( isset( $final[$final_rows[$row]] ) ) $final_line = htmlspecialchars($final[$final_rows[$row]]); else $final_line = ''; if ( $orig_rows[$row] < 0 ) { // Orig is blank. This is really an added row. $r .= $this->_added( array($final_line), false ); } elseif ( $final_rows[$row] < 0 ) { // Final is blank. This is really a deleted row. $r .= $this->_deleted( array($orig_line), false ); } else { // A true changed row. if ( $this->_show_split_view ) { $r .= '<tr>' . $this->deletedLine( $orig_line ) . $this->emptyLine() . $this->addedLine( $final_line ) . "</tr>\n"; } else { $r .= '<tr>' . $this->deletedLine( $orig_line ) . "</tr><tr>" . $this->addedLine( $final_line ) . "</tr>\n"; } } } return $r; } /** * Takes changed blocks and matches which rows in orig turned into which rows in final. * * Returns * *_matches ( which rows match with which ) * *_rows ( order of rows in each column interleaved with blank rows as * necessary ) * * @since 2.6.0 * * @param unknown_type $orig * @param unknown_type $final * @return unknown */ function interleave_changed_lines( $orig, $final ) { // Contains all pairwise string comparisons. Keys are such that this need only be a one dimensional array. $matches = array(); foreach ( array_keys($orig) as $o ) { foreach ( array_keys($final) as $f ) { $matches["$o,$f"] = $this->compute_string_distance( $orig[$o], $final[$f] ); } } asort($matches); // Order by string distance. $orig_matches = array(); $final_matches = array(); foreach ( $matches as $keys => $difference ) { list($o, $f) = explode(',', $keys); $o = (int) $o; $f = (int) $f; // Already have better matches for these guys if ( isset($orig_matches[$o]) && isset($final_matches[$f]) ) continue; // First match for these guys. Must be best match if ( !isset($orig_matches[$o]) && !isset($final_matches[$f]) ) { $orig_matches[$o] = $f; $final_matches[$f] = $o; continue; } // Best match of this final is already taken? Must mean this final is a new row. if ( isset($orig_matches[$o]) ) $final_matches[$f] = 'x'; // Best match of this orig is already taken? Must mean this orig is a deleted row. elseif ( isset($final_matches[$f]) ) $orig_matches[$o] = 'x'; } // We read the text in this order ksort($orig_matches); ksort($final_matches); // Stores rows and blanks for each column. $orig_rows = $orig_rows_copy = array_keys($orig_matches); $final_rows = array_keys($final_matches); // Interleaves rows with blanks to keep matches aligned. // We may end up with some extraneous blank rows, but we'll just ignore them later. foreach ( $orig_rows_copy as $orig_row ) { $final_pos = array_search($orig_matches[$orig_row], $final_rows, true); $orig_pos = (int) array_search($orig_row, $orig_rows, true); if ( false === $final_pos ) { // This orig is paired with a blank final. array_splice( $final_rows, $orig_pos, 0, -1 ); } elseif ( $final_pos < $orig_pos ) { // This orig's match is up a ways. Pad final with blank rows. $diff_pos = $final_pos - $orig_pos; while ( $diff_pos < 0 ) array_splice( $final_rows, $orig_pos, 0, $diff_pos++ ); } elseif ( $final_pos > $orig_pos ) { // This orig's match is down a ways. Pad orig with blank rows. $diff_pos = $orig_pos - $final_pos; while ( $diff_pos < 0 ) array_splice( $orig_rows, $orig_pos, 0, $diff_pos++ ); } } // Pad the ends with blank rows if the columns aren't the same length $diff_count = count($orig_rows) - count($final_rows); if ( $diff_count < 0 ) { while ( $diff_count < 0 ) array_push($orig_rows, $diff_count++); } elseif ( $diff_count > 0 ) { $diff_count = -1 * $diff_count; while ( $diff_count < 0 ) array_push($final_rows, $diff_count++); } return array($orig_matches, $final_matches, $orig_rows, $final_rows); } /** * Computes a number that is intended to reflect the "distance" between two strings. * * @since 2.6.0 * * @param string $string1 * @param string $string2 * @return int */ function compute_string_distance( $string1, $string2 ) { // Vectors containing character frequency for all chars in each string $chars1 = count_chars($string1); $chars2 = count_chars($string2); // L1-norm of difference vector. $difference = array_sum( array_map( array($this, 'difference'), $chars1, $chars2 ) ); // $string1 has zero length? Odd. Give huge penalty by not dividing. if ( !$string1 ) return $difference; // Return distance per charcter (of string1) return $difference / strlen($string1); } /** * @ignore * @since 2.6.0 * * @param int $a * @param int $b * @return int */ function difference( $a, $b ) { return abs( $a - $b ); } } /** * Better word splitting than the PEAR package provides. * * @since 2.6.0 * @uses Text_Diff_Renderer_inline Extends */ class WP_Text_Diff_Renderer_inline extends Text_Diff_Renderer_inline { /** * @ignore * @since 2.6.0 * * @param string $string * @param string $newlineEscape * @return string */ function _splitOnWords($string, $newlineEscape = "\n") { $string = str_replace("\0", '', $string); $words = preg_split( '/([^\w])/u', $string, -1, PREG_SPLIT_DELIM_CAPTURE ); $words = str_replace( "\n", $newlineEscape, $words ); return $words; } }
01-wordpress-paypal
trunk/wp-includes/wp-diff.php
PHP
gpl3
12,484
<?php /** * Base WordPress Image Editor * * @package WordPress * @subpackage Image_Editor */ /** * Base image editor class from which implementations extend * * @since 3.5.0 */ abstract class WP_Image_Editor { protected $file = null; protected $size = null; protected $mime_type = null; protected $default_mime_type = 'image/jpeg'; protected $quality = 90; /** * Each instance handles a single file. */ public function __construct( $file ) { $this->file = $file; } /** * Checks to see if current environment supports the editor chosen. * Must be overridden in a sub-class. * * @since 3.5.0 * @access public * @abstract * * @param array $args * @return boolean */ public static function test( $args = array() ) { return false; } /** * Checks to see if editor supports the mime-type specified. * Must be overridden in a sub-class. * * @since 3.5.0 * @access public * @abstract * * @param string $mime_type * @return boolean */ public static function supports_mime_type( $mime_type ) { return false; } /** * Loads image from $this->file into editor. * * @since 3.5.0 * @access protected * @abstract * * @return boolean|WP_Error True if loaded; WP_Error on failure. */ abstract public function load(); /** * Saves current image to file. * * @since 3.5.0 * @access public * @abstract * * @param string $destfilename * @param string $mime_type * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string} */ abstract public function save( $destfilename = null, $mime_type = null ); /** * Resizes current image. * * At minimum, either a height or width must be provided. * If one of the two is set to null, the resize will * maintain aspect ratio according to the provided dimension. * * @since 3.5.0 * @access public * @abstract * * @param int|null $max_w Image width. * @param int|null $max_h Image height. * @param boolean $crop * @return boolean|WP_Error */ abstract public function resize( $max_w, $max_h, $crop = false ); /** * Resize multiple images from a single source. * * @since 3.5.0 * @access public * @abstract * * @param array $sizes { * An array of image size arrays. Default sizes are 'small', 'medium', 'large'. * * @type array $size { * @type int $width Image width. * @type int $height Image height. * @type bool $crop Optional. Whether to crop the image. Default false. * } * } * @return array An array of resized images metadata by size. */ abstract public function multi_resize( $sizes ); /** * Crops Image. * * @since 3.5.0 * @access public * @abstract * * @param string|int $src The source file or Attachment ID. * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. * @param int $src_w The width to crop. * @param int $src_h The height to crop. * @param int $dst_w Optional. The destination width. * @param int $dst_h Optional. The destination height. * @param boolean $src_abs Optional. If the source crop points are absolute. * @return boolean|WP_Error */ abstract public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ); /** * Rotates current image counter-clockwise by $angle. * * @since 3.5.0 * @access public * @abstract * * @param float $angle * @return boolean|WP_Error */ abstract public function rotate( $angle ); /** * Flips current image. * * @since 3.5.0 * @access public * @abstract * * @param boolean $horz Flip along Horizontal Axis * @param boolean $vert Flip along Vertical Axis * @return boolean|WP_Error */ abstract public function flip( $horz, $vert ); /** * Streams current image to browser. * * @since 3.5.0 * @access public * @abstract * * @param string $mime_type * @return boolean|WP_Error */ abstract public function stream( $mime_type = null ); /** * Gets dimensions of image. * * @since 3.5.0 * @access public * * @return array {'width'=>int, 'height'=>int} */ public function get_size() { return $this->size; } /** * Sets current image size. * * @since 3.5.0 * @access protected * * @param int $width * @param int $height */ protected function update_size( $width = null, $height = null ) { $this->size = array( 'width' => (int) $width, 'height' => (int) $height ); return true; } /** * Sets Image Compression quality on a 1-100% scale. * * @since 3.5.0 * @access public * * @param int $quality Compression Quality. Range: [1,100] * @return boolean|WP_Error True if set successfully; WP_Error on failure. */ public function set_quality( $quality = null ) { if ( $quality == null ) { $quality = $this->quality; } /** * Filter the default image compression quality setting. * * @since 3.5.0 * * @param int $quality Quality level between 1 (low) and 100 (high). * @param string $mime_type Image mime type. */ $quality = apply_filters( 'wp_editor_set_quality', $quality, $this->mime_type ); if ( 'image/jpeg' == $this->mime_type ) { /** * Filter the JPEG compression quality for backward-compatibility. * * The filter is evaluated under two contexts: 'image_resize', and 'edit_image', * (when a JPEG image is saved to file). * * @since 2.5.0 * * @param int $quality Quality level between 0 (low) and 100 (high) of the JPEG. * @param string $context Context of the filter. */ $quality = apply_filters( 'jpeg_quality', $quality, 'image_resize' ); // Allow 0, but squash to 1 due to identical images in GD, and for backwards compatibility. if ( $quality == 0 ) { $quality = 1; } } if ( ( $quality >= 1 ) && ( $quality <= 100 ) ){ $this->quality = $quality; return true; } else { return new WP_Error( 'invalid_image_quality', __('Attempted to set image quality outside of the range [1,100].') ); } } /** * Returns preferred mime-type and extension based on provided * file's extension and mime, or current file's extension and mime. * * Will default to $this->default_mime_type if requested is not supported. * * Provides corrected filename only if filename is provided. * * @since 3.5.0 * @access protected * * @param string $filename * @param string $mime_type * @return array { filename|null, extension, mime-type } */ protected function get_output_format( $filename = null, $mime_type = null ) { $new_ext = $file_ext = null; $file_mime = null; // By default, assume specified type takes priority if ( $mime_type ) { $new_ext = $this->get_extension( $mime_type ); } if ( $filename ) { $file_ext = strtolower( pathinfo( $filename, PATHINFO_EXTENSION ) ); $file_mime = $this->get_mime_type( $file_ext ); } else { // If no file specified, grab editor's current extension and mime-type. $file_ext = strtolower( pathinfo( $this->file, PATHINFO_EXTENSION ) ); $file_mime = $this->mime_type; } // Check to see if specified mime-type is the same as type implied by // file extension. If so, prefer extension from file. if ( ! $mime_type || ( $file_mime == $mime_type ) ) { $mime_type = $file_mime; $new_ext = $file_ext; } // Double-check that the mime-type selected is supported by the editor. // If not, choose a default instead. if ( ! $this->supports_mime_type( $mime_type ) ) { /** * Filter default mime type prior to getting the file extension. * * @see wp_get_mime_types() * * @since 3.5.0 * * @param string $mime_type Mime type string. */ $mime_type = apply_filters( 'image_editor_default_mime_type', $this->default_mime_type ); $new_ext = $this->get_extension( $mime_type ); } if ( $filename ) { $ext = ''; $info = pathinfo( $filename ); $dir = $info['dirname']; if( isset( $info['extension'] ) ) $ext = $info['extension']; $filename = trailingslashit( $dir ) . wp_basename( $filename, ".$ext" ) . ".{$new_ext}"; } return array( $filename, $new_ext, $mime_type ); } /** * Builds an output filename based on current file, and adding proper suffix * * @since 3.5.0 * @access public * * @param string $suffix * @param string $dest_path * @param string $extension * @return string filename */ public function generate_filename( $suffix = null, $dest_path = null, $extension = null ) { // $suffix will be appended to the destination filename, just before the extension if ( ! $suffix ) $suffix = $this->get_suffix(); $info = pathinfo( $this->file ); $dir = $info['dirname']; $ext = $info['extension']; $name = wp_basename( $this->file, ".$ext" ); $new_ext = strtolower( $extension ? $extension : $ext ); if ( ! is_null( $dest_path ) && $_dest_path = realpath( $dest_path ) ) $dir = $_dest_path; return trailingslashit( $dir ) . "{$name}-{$suffix}.{$new_ext}"; } /** * Builds and returns proper suffix for file based on height and width. * * @since 3.5.0 * @access public * * @return string suffix */ public function get_suffix() { if ( ! $this->get_size() ) return false; return "{$this->size['width']}x{$this->size['height']}"; } /** * Either calls editor's save function or handles file as a stream. * * @since 3.5.0 * @access protected * * @param string|stream $filename * @param callable $function * @param array $arguments * @return boolean */ protected function make_image( $filename, $function, $arguments ) { if ( $stream = wp_is_stream( $filename ) ) { ob_start(); } else { // The directory containing the original file may no longer exist when using a replication plugin. wp_mkdir_p( dirname( $filename ) ); } $result = call_user_func_array( $function, $arguments ); if ( $result && $stream ) { $contents = ob_get_contents(); $fp = fopen( $filename, 'w' ); if ( ! $fp ) return false; fwrite( $fp, $contents ); fclose( $fp ); } if ( $stream ) { ob_end_clean(); } return $result; } /** * Returns first matched mime-type from extension, * as mapped from wp_get_mime_types() * * @since 3.5.0 * @access protected * * @param string $extension * @return string|boolean */ protected static function get_mime_type( $extension = null ) { if ( ! $extension ) return false; $mime_types = wp_get_mime_types(); $extensions = array_keys( $mime_types ); foreach( $extensions as $_extension ) { if ( preg_match( "/{$extension}/i", $_extension ) ) { return $mime_types[$_extension]; } } return false; } /** * Returns first matched extension from Mime-type, * as mapped from wp_get_mime_types() * * @since 3.5.0 * @access protected * * @param string $mime_type * @return string|boolean */ protected static function get_extension( $mime_type = null ) { $extensions = explode( '|', array_search( $mime_type, wp_get_mime_types() ) ); if ( empty( $extensions[0] ) ) return false; return $extensions[0]; } }
01-wordpress-paypal
trunk/wp-includes/class-wp-image-editor.php
PHP
gpl3
11,221
<?php /** * Post format functions. * * @package WordPress * @subpackage Post */ /** * Retrieve the format slug for a post * * @since 3.1.0 * * @param int|object $post Post ID or post object. Optional, default is the current post from the loop. * @return mixed The format if successful. False otherwise. */ function get_post_format( $post = null ) { if ( ! $post = get_post( $post ) ) return false; if ( ! post_type_supports( $post->post_type, 'post-formats' ) ) return false; $_format = get_the_terms( $post->ID, 'post_format' ); if ( empty( $_format ) ) return false; $format = array_shift( $_format ); return str_replace('post-format-', '', $format->slug ); } /** * Check if a post has any of the given formats, or any format. * * @since 3.1.0 * * @uses has_term() * * @param string|array $format Optional. The format or formats to check. * @param object|int $post Optional. The post to check. If not supplied, defaults to the current post if used in the loop. * @return bool True if the post has any of the given formats (or any format, if no format specified), false otherwise. */ function has_post_format( $format = array(), $post = null ) { $prefixed = array(); if ( $format ) { foreach ( (array) $format as $single ) { $prefixed[] = 'post-format-' . sanitize_key( $single ); } } return has_term( $prefixed, 'post_format', $post ); } /** * Assign a format to a post * * @since 3.1.0 * * @param int|object $post The post for which to assign a format. * @param string $format A format to assign. Use an empty string or array to remove all formats from the post. * @return mixed WP_Error on error. Array of affected term IDs on success. */ function set_post_format( $post, $format ) { $post = get_post( $post ); if ( empty( $post ) ) return new WP_Error( 'invalid_post', __( 'Invalid post' ) ); if ( ! empty( $format ) ) { $format = sanitize_key( $format ); if ( 'standard' === $format || ! in_array( $format, get_post_format_slugs() ) ) $format = ''; else $format = 'post-format-' . $format; } return wp_set_post_terms( $post->ID, $format, 'post_format' ); } /** * Returns an array of post format slugs to their translated and pretty display versions * * @since 3.1.0 * * @return array The array of translated post format names. */ function get_post_format_strings() { $strings = array( 'standard' => _x( 'Standard', 'Post format' ), // Special case. any value that evals to false will be considered standard 'aside' => _x( 'Aside', 'Post format' ), 'chat' => _x( 'Chat', 'Post format' ), 'gallery' => _x( 'Gallery', 'Post format' ), 'link' => _x( 'Link', 'Post format' ), 'image' => _x( 'Image', 'Post format' ), 'quote' => _x( 'Quote', 'Post format' ), 'status' => _x( 'Status', 'Post format' ), 'video' => _x( 'Video', 'Post format' ), 'audio' => _x( 'Audio', 'Post format' ), ); return $strings; } /** * Retrieves an array of post format slugs. * * @since 3.1.0 * * @uses get_post_format_strings() * * @return array The array of post format slugs. */ function get_post_format_slugs() { $slugs = array_keys( get_post_format_strings() ); return array_combine( $slugs, $slugs ); } /** * Returns a pretty, translated version of a post format slug * * @since 3.1.0 * * @uses get_post_format_strings() * * @param string $slug A post format slug. * @return string The translated post format name. */ function get_post_format_string( $slug ) { $strings = get_post_format_strings(); if ( !$slug ) return $strings['standard']; else return ( isset( $strings[$slug] ) ) ? $strings[$slug] : ''; } /** * Returns a link to a post format index. * * @since 3.1.0 * * @param string $format The post format slug. * @return string The post format term link. */ function get_post_format_link( $format ) { $term = get_term_by('slug', 'post-format-' . $format, 'post_format' ); if ( ! $term || is_wp_error( $term ) ) return false; return get_term_link( $term ); } /** * Filters the request to allow for the format prefix. * * @access private * @since 3.1.0 */ function _post_format_request( $qvs ) { if ( ! isset( $qvs['post_format'] ) ) return $qvs; $slugs = get_post_format_slugs(); if ( isset( $slugs[ $qvs['post_format'] ] ) ) $qvs['post_format'] = 'post-format-' . $slugs[ $qvs['post_format'] ]; $tax = get_taxonomy( 'post_format' ); if ( ! is_admin() ) $qvs['post_type'] = $tax->object_type; return $qvs; } add_filter( 'request', '_post_format_request' ); /** * Filters the post format term link to remove the format prefix. * * @access private * @since 3.1.0 */ function _post_format_link( $link, $term, $taxonomy ) { global $wp_rewrite; if ( 'post_format' != $taxonomy ) return $link; if ( $wp_rewrite->get_extra_permastruct( $taxonomy ) ) { return str_replace( "/{$term->slug}", '/' . str_replace( 'post-format-', '', $term->slug ), $link ); } else { $link = remove_query_arg( 'post_format', $link ); return add_query_arg( 'post_format', str_replace( 'post-format-', '', $term->slug ), $link ); } } add_filter( 'term_link', '_post_format_link', 10, 3 ); /** * Remove the post format prefix from the name property of the term object created by get_term(). * * @access private * @since 3.1.0 */ function _post_format_get_term( $term ) { if ( isset( $term->slug ) ) { $term->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) ); } return $term; } add_filter( 'get_post_format', '_post_format_get_term' ); /** * Remove the post format prefix from the name property of the term objects created by get_terms(). * * @access private * @since 3.1.0 */ function _post_format_get_terms( $terms, $taxonomies, $args ) { if ( in_array( 'post_format', (array) $taxonomies ) ) { if ( isset( $args['fields'] ) && 'names' == $args['fields'] ) { foreach( $terms as $order => $name ) { $terms[$order] = get_post_format_string( str_replace( 'post-format-', '', $name ) ); } } else { foreach ( (array) $terms as $order => $term ) { if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) { $terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) ); } } } } return $terms; } add_filter( 'get_terms', '_post_format_get_terms', 10, 3 ); /** * Remove the post format prefix from the name property of the term objects created by wp_get_object_terms(). * * @access private * @since 3.1.0 */ function _post_format_wp_get_object_terms( $terms ) { foreach ( (array) $terms as $order => $term ) { if ( isset( $term->taxonomy ) && 'post_format' == $term->taxonomy ) { $terms[$order]->name = get_post_format_string( str_replace( 'post-format-', '', $term->slug ) ); } } return $terms; } add_filter( 'wp_get_object_terms', '_post_format_wp_get_object_terms' );
01-wordpress-paypal
trunk/wp-includes/post-formats.php
PHP
gpl3
6,913
<?php /** * Deprecated. No longer needed. * * @package WordPress */ _deprecated_file( basename(__FILE__), '2.1', null, __( 'This file no longer needs to be included.' ) );
01-wordpress-paypal
trunk/wp-includes/registration-functions.php
PHP
gpl3
176
<?php /** * WordPress Feed API * * Many of the functions used in here belong in The Loop, or The Loop for the * Feeds. * * @package WordPress * @subpackage Feed */ /** * RSS container for the bloginfo function. * * You can retrieve anything that you can using the get_bloginfo() function. * Everything will be stripped of tags and characters converted, when the values * are retrieved for use in the feeds. * * @since 1.5.1 * @see get_bloginfo() For the list of possible values to display. * * @param string $show See get_bloginfo() for possible values. * @return string */ function get_bloginfo_rss($show = '') { $info = strip_tags(get_bloginfo($show)); /** * Filter the bloginfo for use in RSS feeds. * * @since 2.2.0 * * @see convert_chars() * @see get_bloginfo() * * @param string $info Converted string value of the blog information. * @param string $show The type of blog information to retrieve. */ return apply_filters( 'get_bloginfo_rss', convert_chars( $info ), $show ); } /** * Display RSS container for the bloginfo function. * * You can retrieve anything that you can using the get_bloginfo() function. * Everything will be stripped of tags and characters converted, when the values * are retrieved for use in the feeds. * * @since 0.71 * @see get_bloginfo() For the list of possible values to display. * * @param string $show See get_bloginfo() for possible values. */ function bloginfo_rss($show = '') { /** * Filter the bloginfo for display in RSS feeds. * * @since 2.1.0 * * @see get_bloginfo() * * @param string $rss_container RSS container for the blog information. * @param string $show The type of blog information to retrieve. */ echo apply_filters( 'bloginfo_rss', get_bloginfo_rss( $show ), $show ); } /** * Retrieve the default feed. * * The default feed is 'rss2', unless a plugin changes it through the * 'default_feed' filter. * * @since 2.5.0 * @uses apply_filters() Calls 'default_feed' hook on the default feed string. * * @return string Default feed, or for example 'rss2', 'atom', etc. */ function get_default_feed() { /** * Filter the default feed type. * * @since 2.5.0 * * @param string $feed_type Type of default feed. Possible values include 'rss2', 'atom'. * Default 'rss2'. */ $default_feed = apply_filters( 'default_feed', 'rss2' ); return 'rss' == $default_feed ? 'rss2' : $default_feed; } /** * Retrieve the blog title for the feed title. * * @since 2.2.0 * * @param string $sep Optional.How to separate the title. See wp_title() for more info. * @return string Error message on failure or blog title on success. */ function get_wp_title_rss($sep = '&#187;') { $title = wp_title($sep, false); if ( is_wp_error( $title ) ) return $title->get_error_message(); /** * Filter the blog title for use as the feed title. * * @since 2.2.0 * * @param string $title The current blog title. * @param string $sep Separator used by wp_title(). */ $title = apply_filters( 'get_wp_title_rss', $title, $sep ); return $title; } /** * Display the blog title for display of the feed title. * * @since 2.2.0 * @see wp_title() $sep parameter usage. * * @param string $sep Optional. */ function wp_title_rss( $sep = '&#187;' ) { /** * Filter the blog title for display of the feed title. * * @since 2.2.0 * * @see get_wp_title_rss() * * @param string $wp_title The current blog title. * @param string $sep Separator used by wp_title(). */ echo apply_filters( 'wp_title_rss', get_wp_title_rss( $sep ), $sep ); } /** * Retrieve the current post title for the feed. * * @since 2.0.0 * * @return string Current post title. */ function get_the_title_rss() { $title = get_the_title(); /** * Filter the post title for use in a feed. * * @since 1.2.0 * * @param string $title The current post title. */ $title = apply_filters( 'the_title_rss', $title ); return $title; } /** * Display the post title in the feed. * * @since 0.71 * @uses get_the_title_rss() Used to retrieve current post title. */ function the_title_rss() { echo get_the_title_rss(); } /** * Retrieve the post content for feeds. * * @since 2.9.0 * @see get_the_content() * * @param string $feed_type The type of feed. rss2 | atom | rss | rdf * @return string The filtered content. */ function get_the_content_feed($feed_type = null) { if ( !$feed_type ) $feed_type = get_default_feed(); /** This filter is documented in wp-admin/post-template.php */ $content = apply_filters( 'the_content', get_the_content() ); $content = str_replace(']]>', ']]&gt;', $content); /** * Filter the post content for use in feeds. * * @since 2.9.0 * * @param string $content The current post content. * @param string $feed_type Type of feed. Possible values include 'rss2', 'atom'. * Default 'rss2'. */ return apply_filters( 'the_content_feed', $content, $feed_type ); } /** * Display the post content for feeds. * * @since 2.9.0 * @uses apply_filters() Calls 'the_content_feed' on the content before processing. * @see get_the_content() * * @param string $feed_type The type of feed. rss2 | atom | rss | rdf */ function the_content_feed($feed_type = null) { echo get_the_content_feed($feed_type); } /** * Display the post excerpt for the feed. * * @since 0.71 */ function the_excerpt_rss() { $output = get_the_excerpt(); /** * Filter the post excerpt for a feed. * * @since 1.2.0 * * @param string $output The current post excerpt. */ echo apply_filters( 'the_excerpt_rss', $output ); } /** * Display the permalink to the post for use in feeds. * * @since 2.3.0 */ function the_permalink_rss() { /** * Filter the permalink to the post for use in feeds. * * @since 2.3.0 * * @param string $post_permalink The current post permalink. */ echo esc_url( apply_filters( 'the_permalink_rss', get_permalink() ) ); } /** * Outputs the link to the comments for the current post in an xml safe way * * @since 3.0.0 * @return none */ function comments_link_feed() { /** * Filter the comments permalink for the current post. * * @since 3.6.0 * * @param string $comment_permalink The current comment permalink with * '#comments' appended. */ echo esc_url( apply_filters( 'comments_link_feed', get_comments_link() ) ); } /** * Display the feed GUID for the current comment. * * @since 2.5.0 * * @param int|object $comment_id Optional comment object or id. Defaults to global comment object. */ function comment_guid($comment_id = null) { echo esc_url( get_comment_guid($comment_id) ); } /** * Retrieve the feed GUID for the current comment. * * @since 2.5.0 * * @param int|object $comment_id Optional comment object or id. Defaults to global comment object. * @return bool|string false on failure or guid for comment on success. */ function get_comment_guid($comment_id = null) { $comment = get_comment($comment_id); if ( !is_object($comment) ) return false; return get_the_guid($comment->comment_post_ID) . '#comment-' . $comment->comment_ID; } /** * Display the link to the comments. * * @since 1.5.0 */ function comment_link() { /** * Filter the current comment's permalink. * * @since 3.6.0 * * @see get_comment_link() * * @param string $comment_permalink The current comment permalink. */ echo esc_url( apply_filters( 'comment_link', get_comment_link() ) ); } /** * Retrieve the current comment author for use in the feeds. * * @since 2.0.0 * @uses get_comment_author() * * @return string Comment Author */ function get_comment_author_rss() { /** * Filter the current comment author for use in a feed. * * @since 1.5.0 * * @see get_comment_author() * * @param string $comment_author The current comment author. */ return apply_filters( 'comment_author_rss', get_comment_author() ); } /** * Display the current comment author in the feed. * * @since 1.0.0 */ function comment_author_rss() { echo get_comment_author_rss(); } /** * Display the current comment content for use in the feeds. * * @since 1.0.0 * @uses get_comment_text() */ function comment_text_rss() { $comment_text = get_comment_text(); /** * Filter the current comment content for use in a feed. * * @since 1.5.0 * * @param string $comment_text The content of the current comment. */ $comment_text = apply_filters( 'comment_text_rss', $comment_text ); echo $comment_text; } /** * Retrieve all of the post categories, formatted for use in feeds. * * All of the categories for the current post in the feed loop, will be * retrieved and have feed markup added, so that they can easily be added to the * RSS2, Atom, or RSS1 and RSS0.91 RDF feeds. * * @since 2.1.0 * * @param string $type Optional, default is the type returned by get_default_feed(). * @return string All of the post categories for displaying in the feed. */ function get_the_category_rss($type = null) { if ( empty($type) ) $type = get_default_feed(); $categories = get_the_category(); $tags = get_the_tags(); $the_list = ''; $cat_names = array(); $filter = 'rss'; if ( 'atom' == $type ) $filter = 'raw'; if ( !empty($categories) ) foreach ( (array) $categories as $category ) { $cat_names[] = sanitize_term_field('name', $category->name, $category->term_id, 'category', $filter); } if ( !empty($tags) ) foreach ( (array) $tags as $tag ) { $cat_names[] = sanitize_term_field('name', $tag->name, $tag->term_id, 'post_tag', $filter); } $cat_names = array_unique($cat_names); foreach ( $cat_names as $cat_name ) { if ( 'rdf' == $type ) $the_list .= "\t\t<dc:subject><![CDATA[$cat_name]]></dc:subject>\n"; elseif ( 'atom' == $type ) /** This filter is documented in wp-includes/feed.php */ $the_list .= sprintf( '<category scheme="%1$s" term="%2$s" />', esc_attr( apply_filters( 'get_bloginfo_rss', get_bloginfo( 'url' ) ) ), esc_attr( $cat_name ) ); else $the_list .= "\t\t<category><![CDATA[" . @html_entity_decode( $cat_name, ENT_COMPAT, get_option('blog_charset') ) . "]]></category>\n"; } /** * Filter all of the post categories for display in a feed. * * @since 1.2.0 * * @param string $the_list All of the RSS post categories. * @param string $type Type of feed. Possible values include 'rss2', 'atom'. * Default 'rss2'. */ return apply_filters( 'the_category_rss', $the_list, $type ); } /** * Display the post categories in the feed. * * @since 0.71 * @see get_the_category_rss() For better explanation. * * @param string $type Optional, default is the type returned by get_default_feed(). */ function the_category_rss($type = null) { echo get_the_category_rss($type); } /** * Display the HTML type based on the blog setting. * * The two possible values are either 'xhtml' or 'html'. * * @since 2.2.0 */ function html_type_rss() { $type = get_bloginfo('html_type'); if (strpos($type, 'xhtml') !== false) $type = 'xhtml'; else $type = 'html'; echo $type; } /** * Display the rss enclosure for the current post. * * Uses the global $post to check whether the post requires a password and if * the user has the password for the post. If not then it will return before * displaying. * * Also uses the function get_post_custom() to get the post's 'enclosure' * metadata field and parses the value to display the enclosure(s). The * enclosure(s) consist of enclosure HTML tag(s) with a URI and other * attributes. * * @since 1.5.0 * @uses get_post_custom() To get the current post enclosure metadata. */ function rss_enclosure() { if ( post_password_required() ) return; foreach ( (array) get_post_custom() as $key => $val) { if ($key == 'enclosure') { foreach ( (array) $val as $enc ) { $enclosure = explode("\n", $enc); // only get the first element, e.g. audio/mpeg from 'audio/mpeg mpga mp2 mp3' $t = preg_split('/[ \t]/', trim($enclosure[2]) ); $type = $t[0]; /** * Filter the RSS enclosure HTML link tag for the current post. * * @since 2.2.0 * * @param string $html_link_tag The HTML link tag with a URI and other attributes. */ echo apply_filters( 'rss_enclosure', '<enclosure url="' . trim( htmlspecialchars( $enclosure[0] ) ) . '" length="' . trim( $enclosure[1] ) . '" type="' . $type . '" />' . "\n" ); } } } } /** * Display the atom enclosure for the current post. * * Uses the global $post to check whether the post requires a password and if * the user has the password for the post. If not then it will return before * displaying. * * Also uses the function get_post_custom() to get the post's 'enclosure' * metadata field and parses the value to display the enclosure(s). The * enclosure(s) consist of link HTML tag(s) with a URI and other attributes. * * @since 2.2.0 * @uses get_post_custom() To get the current post enclosure metadata. */ function atom_enclosure() { if ( post_password_required() ) return; foreach ( (array) get_post_custom() as $key => $val ) { if ($key == 'enclosure') { foreach ( (array) $val as $enc ) { $enclosure = explode("\n", $enc); /** * Filter the atom enclosure HTML link tag for the current post. * * @since 2.2.0 * * @param string $html_link_tag The HTML link tag with a URI and other attributes. */ echo apply_filters( 'atom_enclosure', '<link href="' . trim( htmlspecialchars( $enclosure[0] ) ) . '" rel="enclosure" length="' . trim( $enclosure[1] ) . '" type="' . trim( $enclosure[2] ) . '" />' . "\n" ); } } } } /** * Determine the type of a string of data with the data formatted. * * Tell whether the type is text, html, or xhtml, per RFC 4287 section 3.1. * * In the case of WordPress, text is defined as containing no markup, * xhtml is defined as "well formed", and html as tag soup (i.e., the rest). * * Container div tags are added to xhtml values, per section 3.1.1.3. * * @link http://www.atomenabled.org/developers/syndication/atom-format-spec.php#rfc.section.3.1 * * @since 2.5.0 * * @param string $data Input string * @return array array(type, value) */ function prep_atom_text_construct($data) { if (strpos($data, '<') === false && strpos($data, '&') === false) { return array('text', $data); } $parser = xml_parser_create(); xml_parse($parser, '<div>' . $data . '</div>', true); $code = xml_get_error_code($parser); xml_parser_free($parser); if (!$code) { if (strpos($data, '<') === false) { return array('text', $data); } else { $data = "<div xmlns='http://www.w3.org/1999/xhtml'>$data</div>"; return array('xhtml', $data); } } if (strpos($data, ']]>') == false) { return array('html', "<![CDATA[$data]]>"); } else { return array('html', htmlspecialchars($data)); } } /** * Display the link for the currently displayed feed in a XSS safe way. * * Generate a correct link for the atom:self element. * * @since 2.5.0 */ function self_link() { $host = @parse_url(home_url()); /** * Filter the current feed URL. * * @since 3.6.0 * * @see set_url_scheme() * @see wp_unslash() * * @param string $feed_link The link for the feed with set URL scheme. */ echo esc_url( apply_filters( 'self_link', set_url_scheme( 'http://' . $host['host'] . wp_unslash( $_SERVER['REQUEST_URI'] ) ) ) ); } /** * Return the content type for specified feed type. * * @since 2.8.0 */ function feed_content_type( $type = '' ) { if ( empty($type) ) $type = get_default_feed(); $types = array( 'rss' => 'application/rss+xml', 'rss2' => 'application/rss+xml', 'rss-http' => 'text/xml', 'atom' => 'application/atom+xml', 'rdf' => 'application/rdf+xml' ); $content_type = ( !empty($types[$type]) ) ? $types[$type] : 'application/octet-stream'; /** * Filter the content type for a specific feed type. * * @since 2.8.0 * * @param string $content_type Content type indicating the type of data that a feed contains. * @param string $type Type of feed. Possible values include 'rss2', 'atom'. * Default 'rss2'. */ return apply_filters( 'feed_content_type', $content_type, $type ); } /** * Build SimplePie object based on RSS or Atom feed from URL. * * @since 2.8.0 * * @param mixed $url URL of feed to retrieve. If an array of URLs, the feeds are merged * using SimplePie's multifeed feature. * See also {@link ​http://simplepie.org/wiki/faq/typical_multifeed_gotchas} * * @return WP_Error|SimplePie WP_Error object on failure or SimplePie object on success */ function fetch_feed( $url ) { require_once( ABSPATH . WPINC . '/class-feed.php' ); $feed = new SimplePie(); $feed->set_sanitize_class( 'WP_SimplePie_Sanitize_KSES' ); // We must manually overwrite $feed->sanitize because SimplePie's // constructor sets it before we have a chance to set the sanitization class $feed->sanitize = new WP_SimplePie_Sanitize_KSES(); $feed->set_cache_class( 'WP_Feed_Cache' ); $feed->set_file_class( 'WP_SimplePie_File' ); $feed->set_feed_url( $url ); /** This filter is documented in wp-includes/class-feed.php */ $feed->set_cache_duration( apply_filters( 'wp_feed_cache_transient_lifetime', 12 * HOUR_IN_SECONDS, $url ) ); /** * Fires just before processing the SimplePie feed object. * * @since 3.0.0 * * @param object &$feed SimplePie feed object, passed by reference. * @param mixed $url URL of feed to retrieve. If an array of URLs, the feeds are merged. */ do_action_ref_array( 'wp_feed_options', array( &$feed, $url ) ); $feed->init(); $feed->handle_content_type(); if ( $feed->error() ) return new WP_Error( 'simplepie-error', $feed->error() ); return $feed; }
01-wordpress-paypal
trunk/wp-includes/feed.php
PHP
gpl3
17,862
<?php /** * Send XML response back to AJAX request. * * @package WordPress * @since 2.1.0 */ class WP_Ajax_Response { /** * Store XML responses to send. * * @since 2.1.0 * @var array * @access private */ var $responses = array(); /** * Constructor - Passes args to {@link WP_Ajax_Response::add()}. * * @since 2.1.0 * @see WP_Ajax_Response::add() * * @param string|array $args Optional. Will be passed to add() method. * @return WP_Ajax_Response */ function __construct( $args = '' ) { if ( !empty($args) ) $this->add($args); } /** * Append to XML response based on given arguments. * * The arguments that can be passed in the $args parameter are below. It is * also possible to pass a WP_Error object in either the 'id' or 'data' * argument. The parameter isn't actually optional, content should be given * in order to send the correct response. * * 'what' argument is a string that is the XMLRPC response type. * 'action' argument is a boolean or string that acts like a nonce. * 'id' argument can be WP_Error or an integer. * 'old_id' argument is false by default or an integer of the previous ID. * 'position' argument is an integer or a string with -1 = top, 1 = bottom, * html ID = after, -html ID = before. * 'data' argument is a string with the content or message. * 'supplemental' argument is an array of strings that will be children of * the supplemental element. * * @since 2.1.0 * * @param string|array $args Override defaults. * @return string XML response. */ function add( $args = '' ) { $defaults = array( 'what' => 'object', 'action' => false, 'id' => '0', 'old_id' => false, 'position' => 1, 'data' => '', 'supplemental' => array() ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $position = preg_replace( '/[^a-z0-9:_-]/i', '', $position ); if ( is_wp_error($id) ) { $data = $id; $id = 0; } $response = ''; if ( is_wp_error($data) ) { foreach ( (array) $data->get_error_codes() as $code ) { $response .= "<wp_error code='$code'><![CDATA[" . $data->get_error_message($code) . "]]></wp_error>"; if ( !$error_data = $data->get_error_data($code) ) continue; $class = ''; if ( is_object($error_data) ) { $class = ' class="' . get_class($error_data) . '"'; $error_data = get_object_vars($error_data); } $response .= "<wp_error_data code='$code'$class>"; if ( is_scalar($error_data) ) { $response .= "<![CDATA[$error_data]]>"; } elseif ( is_array($error_data) ) { foreach ( $error_data as $k => $v ) $response .= "<$k><![CDATA[$v]]></$k>"; } $response .= "</wp_error_data>"; } } else { $response = "<response_data><![CDATA[$data]]></response_data>"; } $s = ''; if ( is_array($supplemental) ) { foreach ( $supplemental as $k => $v ) $s .= "<$k><![CDATA[$v]]></$k>"; $s = "<supplemental>$s</supplemental>"; } if ( false === $action ) $action = $_POST['action']; $x = ''; $x .= "<response action='{$action}_$id'>"; // The action attribute in the xml output is formatted like a nonce action $x .= "<$what id='$id' " . ( false === $old_id ? '' : "old_id='$old_id' " ) . "position='$position'>"; $x .= $response; $x .= $s; $x .= "</$what>"; $x .= "</response>"; $this->responses[] = $x; return $x; } /** * Display XML formatted responses. * * Sets the content type header to text/xml. * * @since 2.1.0 */ function send() { header( 'Content-Type: text/xml; charset=' . get_option( 'blog_charset' ) ); echo "<?xml version='1.0' encoding='" . get_option( 'blog_charset' ) . "' standalone='yes'?><wp_ajax>"; foreach ( (array) $this->responses as $response ) echo $response; echo '</wp_ajax>'; if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) wp_die(); else die(); } }
01-wordpress-paypal
trunk/wp-includes/class-wp-ajax-response.php
PHP
gpl3
3,887
<?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 template file. */ function get_query_template( $type, $templates = array() ) { $type = preg_replace( '|[^a-z0-9-]+|', '', $type ); if ( empty( $templates ) ) $templates = array("{$type}.php"); $template = locate_template( $templates ); /** * Filter the path of the queried template by type. * * The dynamic portion of the hook name, $type, refers to the filename * -- minus the extension -- of the file to load. This hook also applies * to various types of files loaded as part of the Template Hierarchy. * * @since 1.5.0 * * @param string $template Path to the template. @see locate_template() */ return apply_filters( "{$type}_template", $template ); } /** * Retrieve path of index template in current or parent template. * * The template path is filterable via the 'index_template' hook. * * @since 3.0.0 * * @see get_query_template() * * @return string Full path to index template file. */ function get_index_template() { return get_query_template('index'); } /** * Retrieve path of 404 template in current or parent template. * * The template path is filterable via the '404_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to 404 template file. */ function get_404_template() { return get_query_template('404'); } /** * Retrieve path of archive template in current or parent template. * * The template path is filterable via the 'archive_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to archive template file. */ function get_archive_template() { $post_types = array_filter( (array) get_query_var( 'post_type' ) ); $templates = array(); if ( count( $post_types ) == 1 ) { $post_type = reset( $post_types ); $templates[] = "archive-{$post_type}.php"; } $templates[] = 'archive.php'; return get_query_template( 'archive', $templates ); } /** * Retrieve path of post type archive template in current or parent template. * * The template path is filterable via the 'archive_template' hook. * * @since 3.7.0 * * @see get_archive_template() * * @return string Full path to archive template file. */ function get_post_type_archive_template() { $post_type = get_query_var( 'post_type' ); if ( is_array( $post_type ) ) $post_type = reset( $post_type ); $obj = get_post_type_object( $post_type ); if ( ! $obj->has_archive ) return ''; return get_archive_template(); } /** * Retrieve path of author template in current or parent template. * * The template path is filterable via the 'author_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to author template file. */ function get_author_template() { $author = get_queried_object(); $templates = array(); if ( is_a( $author, 'WP_User' ) ) { $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 fall back to category.php * template, if those files don't exist. * * The template path is filterable via the 'category_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to category template file. */ function get_category_template() { $category = get_queried_object(); $templates = array(); if ( ! empty( $category->slug ) ) { $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 fall back to tag.php * template, if those files don't exist. * * The template path is filterable via the 'tag_template' hook. * * @since 2.3.0 * * @see get_query_template() * * @return string Full path to tag template file. */ function get_tag_template() { $tag = get_queried_object(); $templates = array(); if ( ! empty( $tag->slug ) ) { $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. * * The template path is filterable via the 'taxonomy_template' hook. * * @since 2.5.0 * * @see get_query_template() * * @return string Full path to taxonomy template file. */ function get_taxonomy_template() { $term = get_queried_object(); $templates = array(); if ( ! empty( $term->slug ) ) { $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. * * The template path is filterable via the 'date_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to date template file. */ 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'. * * The template path is filterable via the 'home_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to home template file. */ 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'. The template path is filterable via the * 'front_page_template' hook. * * @since 3.0.0 * * @see get_query_template() * * @return string Full path to front page template file. */ 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. * Then will search for 'page-{slug}.php', followed by 'page-{id}.php', * and finally 'page.php'. * * The template path is filterable via the 'page_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to page template file. */ 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(); if ( $post ) $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. * * The template path is filterable via the 'paged_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to paged template file. */ function get_paged_template() { return get_query_template('paged'); } /** * Retrieve path of search template in current or parent template. * * The template path is filterable via the 'search_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to search template file. */ function get_search_template() { return get_query_template('search'); } /** * Retrieve path of single template in current or parent template. * * The template path is filterable via the 'single_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to single template file. */ function get_single_template() { $object = get_queried_object(); $templates = array(); if ( ! empty( $object->post_type ) ) $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'. * * The template path is filterable via the 'attachment_template' hook. * * @since 2.0.0 * * @see get_query_template() * * @return string Full path to attachment template file. */ 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 ( ! empty( $type[1] ) ) { if ( $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. * * The template path is filterable via the 'comments_popup_template' hook. * * @since 1.5.0 * * @see get_query_template() * * @return string Full path to comments popup template file. */ 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 ); }
01-wordpress-paypal
trunk/wp-includes/template.php
PHP
gpl3
13,550
<?php /** * Atom Feed Template for displaying Atom Posts feed. * * @package WordPress */ header('Content-Type: ' . feed_content_type('atom') . '; charset=' . get_option('blog_charset'), true); $more = 1; echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?> <feed xmlns="http://www.w3.org/2005/Atom" xmlns:thr="http://purl.org/syndication/thread/1.0" xml:lang="<?php bloginfo_rss( 'language' ); ?>" xml:base="<?php bloginfo_rss('url') ?>/wp-atom.php" <?php /** * Fires at end of the Atom feed root to add namespaces. * * @since 2.0.0 */ do_action( 'atom_ns' ); ?> > <title type="text"><?php bloginfo_rss('name'); wp_title_rss(); ?></title> <subtitle type="text"><?php bloginfo_rss("description") ?></subtitle> <updated><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT'), false); ?></updated> <link rel="alternate" type="<?php bloginfo_rss('html_type'); ?>" href="<?php bloginfo_rss('url') ?>" /> <id><?php bloginfo('atom_url'); ?></id> <link rel="self" type="application/atom+xml" href="<?php self_link(); ?>" /> <?php /** * Fires just before the first Atom feed entry. * * @since 2.0.0 */ do_action( 'atom_head' ); while ( have_posts() ) : the_post(); ?> <entry> <author> <name><?php the_author() ?></name> <?php $author_url = get_the_author_meta('url'); if ( !empty($author_url) ) : ?> <uri><?php the_author_meta('url')?></uri> <?php endif; /** * Fires at the end of each Atom feed author entry. * * @since 3.2.0 */ do_action( 'atom_author' ); ?> </author> <title type="<?php html_type_rss(); ?>"><![CDATA[<?php the_title_rss() ?>]]></title> <link rel="alternate" type="<?php bloginfo_rss('html_type'); ?>" href="<?php the_permalink_rss() ?>" /> <id><?php the_guid() ; ?></id> <updated><?php echo get_post_modified_time('Y-m-d\TH:i:s\Z', true); ?></updated> <published><?php echo get_post_time('Y-m-d\TH:i:s\Z', true); ?></published> <?php the_category_rss('atom') ?> <summary type="<?php html_type_rss(); ?>"><![CDATA[<?php the_excerpt_rss(); ?>]]></summary> <?php if ( !get_option('rss_use_excerpt') ) : ?> <content type="<?php html_type_rss(); ?>" xml:base="<?php the_permalink_rss() ?>"><![CDATA[<?php the_content_feed('atom') ?>]]></content> <?php endif; ?> <?php atom_enclosure(); /** * Fires at the end of each Atom feed item. * * @since 2.0.0 */ do_action( 'atom_entry' ); ?> <link rel="replies" type="<?php bloginfo_rss('html_type'); ?>" href="<?php the_permalink_rss() ?>#comments" thr:count="<?php echo get_comments_number()?>"/> <link rel="replies" type="application/atom+xml" href="<?php echo esc_url( get_post_comments_feed_link(0, 'atom') ); ?>" thr:count="<?php echo get_comments_number()?>"/> <thr:total><?php echo get_comments_number()?></thr:total> </entry> <?php endwhile ; ?> </feed>
01-wordpress-paypal
trunk/wp-includes/feed-atom.php
PHP
gpl3
2,885
<?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 ] ) ) { $bookmarks = $cache[ $key ]; /** * Filter the returned list of bookmarks. * * The first time the hook is evaluated in this file, it returns the cached * bookmarks list. The second evaluation returns a cached bookmarks list if the * link category is passed but does not exist. The third evaluation returns * the full cached results. * * @since 2.1.0 * * @see get_bookmarks() * * @param array $bookmarks List of the cached bookmarks. * @param array $r An array of bookmark query arguments. */ return apply_filters( 'get_bookmarks', $bookmarks, $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' ); /** This filter is documented in wp-includes/bookmark.php */ return apply_filters( 'get_bookmarks', array(), $r ); } } if ( ! empty($search) ) { $search = esc_sql( 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 ) { $recently_updated_test = ", IF (DATE_ADD(link_updated, INTERVAL 120 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' ); /** This filter is documented in wp-includes/bookmark.php */ 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 ) { /** This filter is documented in wp-includes/post.php */ $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 ) { /** This filter is documented in wp-includes/post.php */ $value = apply_filters( "pre_$field", $value ); } else { /** This filter is documented in wp-includes/post.php */ $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'); }
01-wordpress-paypal
trunk/wp-includes/bookmark.php
PHP
gpl3
12,871
<?php /** * XML-RPC protocol support for WordPress * * @package WordPress */ /** * Whether this is an XML-RPC Request * * @var bool */ define('XMLRPC_REQUEST', true); // Some browser-embedded clients send cookies. We don't want them. $_COOKIE = array(); // A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default, // but we can do it ourself. if ( !isset( $HTTP_RAW_POST_DATA ) ) { $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' ); } // fix for mozBlog and other cases where '<?xml' isn't on the very first line if ( isset($HTTP_RAW_POST_DATA) ) $HTTP_RAW_POST_DATA = trim($HTTP_RAW_POST_DATA); /** Include the bootstrap for setting up WordPress environment */ include('./wp-load.php'); if ( isset( $_GET['rsd'] ) ) { // http://cyber.law.harvard.edu/blogs/gems/tech/rsd.html header('Content-Type: text/xml; charset=' . get_option('blog_charset'), true); ?> <?php echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?> <rsd version="1.0" xmlns="http://archipelago.phrasewise.com/rsd"> <service> <engineName>WordPress</engineName> <engineLink>http://wordpress.org/</engineLink> <homePageLink><?php bloginfo_rss('url') ?></homePageLink> <apis> <api name="WordPress" blogID="1" preferred="true" apiLink="<?php echo site_url('xmlrpc.php', 'rpc') ?>" /> <api name="Movable Type" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php', 'rpc') ?>" /> <api name="MetaWeblog" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php', 'rpc') ?>" /> <api name="Blogger" blogID="1" preferred="false" apiLink="<?php echo site_url('xmlrpc.php', 'rpc') ?>" /> <?php /** * Add additional APIs to the Really Simple Discovery (RSD) endpoint. * * @link http://cyber.law.harvard.edu/blogs/gems/tech/rsd.html * * @since 3.5.0 */ do_action( 'xmlrpc_rsd_apis' ); ?> </apis> </service> </rsd> <?php exit; } include_once(ABSPATH . 'wp-admin/includes/admin.php'); include_once(ABSPATH . WPINC . '/class-IXR.php'); include_once(ABSPATH . WPINC . '/class-wp-xmlrpc-server.php'); /** * Posts submitted via the XML-RPC interface get that title * @name post_default_title * @var string */ $post_default_title = ""; /** * Filter the class used for handling XML-RPC requests. * * @since 3.1.0 * * @param string $class The name of the XML-RPC server class. */ $wp_xmlrpc_server_class = apply_filters( 'wp_xmlrpc_server_class', 'wp_xmlrpc_server' ); $wp_xmlrpc_server = new $wp_xmlrpc_server_class; // Fire off the request $wp_xmlrpc_server->serve_request(); exit; /** * logIO() - Writes logging info to a file. * * @deprecated 3.4.0 * @deprecated Use error_log() * * @param string $io Whether input or output * @param string $msg Information describing logging reason. */ function logIO( $io, $msg ) { _deprecated_function( __FUNCTION__, '3.4', 'error_log()' ); if ( ! empty( $GLOBALS['xmlrpc_logging'] ) ) error_log( $io . ' - ' . $msg ); }
01-wordpress-paypal
trunk/xmlrpc.php
PHP
gpl3
3,032
<?php /** * Gets the email message from the user's mailbox to add as * a WordPress post. Mailbox connection information must be * configured under Settings > Writing * * @package WordPress */ /** Make sure that the WordPress bootstrap has run before continuing. */ require(dirname(__FILE__) . '/wp-load.php'); /** This filter is documented in wp-admin/options.php */ if ( ! apply_filters( 'enable_post_by_email_configuration', true ) ) wp_die( __( 'This action has been disabled by the administrator.' ) ); /** * Fires to allow a plugin to do a complete takeover of Post by Email. * * @since 2.9.0 */ do_action( 'wp-mail.php' ); /** Get the POP3 class with which to access the mailbox. */ require_once( ABSPATH . WPINC . '/class-pop3.php' ); /** Only check at this interval for new messages. */ if ( !defined('WP_MAIL_INTERVAL') ) define('WP_MAIL_INTERVAL', 300); // 5 minutes $last_checked = get_transient('mailserver_last_checked'); if ( $last_checked ) wp_die(__('Slow down cowboy, no need to check for new mails so often!')); set_transient('mailserver_last_checked', true, WP_MAIL_INTERVAL); $time_difference = get_option('gmt_offset') * HOUR_IN_SECONDS; $phone_delim = '::'; $pop3 = new POP3(); if ( !$pop3->connect( get_option('mailserver_url'), get_option('mailserver_port') ) || !$pop3->user( get_option('mailserver_login') ) ) wp_die( esc_html( $pop3->ERROR ) ); $count = $pop3->pass( get_option('mailserver_pass') ); if( false === $count ) wp_die( esc_html( $pop3->ERROR ) ); if( 0 === $count ) { $pop3->quit(); wp_die( __('There doesn&#8217;t seem to be any new mail.') ); } for ( $i = 1; $i <= $count; $i++ ) { $message = $pop3->get($i); $bodysignal = false; $boundary = ''; $charset = ''; $content = ''; $content_type = ''; $content_transfer_encoding = ''; $post_author = 1; $author_found = false; $dmonths = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); foreach ($message as $line) { // body signal if ( strlen($line) < 3 ) $bodysignal = true; if ( $bodysignal ) { $content .= $line; } else { if ( preg_match('/Content-Type: /i', $line) ) { $content_type = trim($line); $content_type = substr($content_type, 14, strlen($content_type) - 14); $content_type = explode(';', $content_type); if ( ! empty( $content_type[1] ) ) { $charset = explode('=', $content_type[1]); $charset = ( ! empty( $charset[1] ) ) ? trim($charset[1]) : ''; } $content_type = $content_type[0]; } if ( preg_match('/Content-Transfer-Encoding: /i', $line) ) { $content_transfer_encoding = trim($line); $content_transfer_encoding = substr($content_transfer_encoding, 27, strlen($content_transfer_encoding) - 27); $content_transfer_encoding = explode(';', $content_transfer_encoding); $content_transfer_encoding = $content_transfer_encoding[0]; } if ( ( $content_type == 'multipart/alternative' ) && ( false !== strpos($line, 'boundary="') ) && ( '' == $boundary ) ) { $boundary = trim($line); $boundary = explode('"', $boundary); $boundary = $boundary[1]; } if (preg_match('/Subject: /i', $line)) { $subject = trim($line); $subject = substr($subject, 9, strlen($subject) - 9); // Captures any text in the subject before $phone_delim as the subject if ( function_exists('iconv_mime_decode') ) { $subject = iconv_mime_decode($subject, 2, get_option('blog_charset')); } else { $subject = wp_iso_descrambler($subject); } $subject = explode($phone_delim, $subject); $subject = $subject[0]; } // Set the author using the email address (From or Reply-To, the last used) // otherwise use the site admin if ( ! $author_found && preg_match( '/^(From|Reply-To): /', $line ) ) { if ( preg_match('|[a-z0-9_.-]+@[a-z0-9_.-]+(?!.*<)|i', $line, $matches) ) $author = $matches[0]; else $author = trim($line); $author = sanitize_email($author); if ( is_email($author) ) { echo '<p>' . sprintf(__('Author is %s'), $author) . '</p>'; $userdata = get_user_by('email', $author); if ( ! empty( $userdata ) ) { $post_author = $userdata->ID; $author_found = true; } } } if (preg_match('/Date: /i', $line)) { // of the form '20 Mar 2002 20:32:37' $ddate = trim($line); $ddate = str_replace('Date: ', '', $ddate); if (strpos($ddate, ',')) { $ddate = trim(substr($ddate, strpos($ddate, ',') + 1, strlen($ddate))); } $date_arr = explode(' ', $ddate); $date_time = explode(':', $date_arr[3]); $ddate_H = $date_time[0]; $ddate_i = $date_time[1]; $ddate_s = $date_time[2]; $ddate_m = $date_arr[1]; $ddate_d = $date_arr[0]; $ddate_Y = $date_arr[2]; for ( $j = 0; $j < 12; $j++ ) { if ( $ddate_m == $dmonths[$j] ) { $ddate_m = $j+1; } } $time_zn = intval($date_arr[4]) * 36; $ddate_U = gmmktime($ddate_H, $ddate_i, $ddate_s, $ddate_m, $ddate_d, $ddate_Y); $ddate_U = $ddate_U - $time_zn; $post_date = gmdate('Y-m-d H:i:s', $ddate_U + $time_difference); $post_date_gmt = gmdate('Y-m-d H:i:s', $ddate_U); } } } // Set $post_status based on $author_found and on author's publish_posts capability if ( $author_found ) { $user = new WP_User($post_author); $post_status = ( $user->has_cap('publish_posts') ) ? 'publish' : 'pending'; } else { // Author not found in DB, set status to pending. Author already set to admin. $post_status = 'pending'; } $subject = trim($subject); if ( $content_type == 'multipart/alternative' ) { $content = explode('--'.$boundary, $content); $content = $content[2]; // match case-insensitive content-transfer-encoding if ( preg_match( '/Content-Transfer-Encoding: quoted-printable/i', $content, $delim) ) { $content = explode($delim[0], $content); $content = $content[1]; } $content = strip_tags($content, '<img><p><br><i><b><u><em><strong><strike><font><span><div>'); } $content = trim($content); /** * Filter the original content of the email. * * Give Post-By-Email extending plugins full access to the content, either * the raw content, or the content of the last quoted-printable section. * * @since 2.8.0 * * @param string $content The original email content. */ $content = apply_filters( 'wp_mail_original_content', $content ); if ( false !== stripos($content_transfer_encoding, "quoted-printable") ) { $content = quoted_printable_decode($content); } if ( function_exists('iconv') && ! empty( $charset ) ) { $content = iconv($charset, get_option('blog_charset'), $content); } // Captures any text in the body after $phone_delim as the body $content = explode($phone_delim, $content); $content = empty( $content[1] ) ? $content[0] : $content[1]; $content = trim($content); /** * Filter the content of the post submitted by email before saving. * * @since 1.2.0 * * @param string $content The email content. */ $post_content = apply_filters( 'phone_content', $content ); $post_title = xmlrpc_getposttitle($content); if ($post_title == '') $post_title = $subject; $post_category = array(get_option('default_email_category')); $post_data = compact('post_content','post_title','post_date','post_date_gmt','post_author','post_category', 'post_status'); $post_data = wp_slash($post_data); $post_ID = wp_insert_post($post_data); if ( is_wp_error( $post_ID ) ) echo "\n" . $post_ID->get_error_message(); // We couldn't post, for whatever reason. Better move forward to the next email. if ( empty( $post_ID ) ) continue; /** * Fires after a post submitted by email is published. * * @since 1.2.0 * * @param int $post_ID The post ID. */ do_action( 'publish_phone', $post_ID ); echo "\n<p>" . sprintf(__('<strong>Author:</strong> %s'), esc_html($post_author)) . '</p>'; echo "\n<p>" . sprintf(__('<strong>Posted title:</strong> %s'), esc_html($post_title)) . '</p>'; if(!$pop3->delete($i)) { echo '<p>' . sprintf(__('Oops: %s'), esc_html($pop3->ERROR)) . '</p>'; $pop3->reset(); exit; } else { echo '<p>' . sprintf(__('Mission complete. Message <strong>%s</strong> deleted.'), $i) . '</p>'; } } $pop3->quit();
01-wordpress-paypal
trunk/wp-mail.php
PHP
gpl3
8,235
Public Class LopBUS Public Shared Function SelectAll() As List(Of LopDTO) Return LopDAO.SelectAll() End Function Public Shared Function LayDSLopHoc() As List(Of LopDTO) Return LopDAO.LayDSLopHoc() End Function Public Shared Function SuaLopHoc(ByVal lop As LopDTO) As Integer Return LopDAO.SuaLopHoc(lop) End Function Public Shared Function SelectByMaKhoi(ByVal MaKhoi As Integer) As List(Of LopDTO) Return LopDAO.SelectByMaKhoi(MaKhoi) End Function Public Shared Function DemSoHSTheoLop() As List(Of LopDTO) Return LopDAO.DemSoHSTheoLop() End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/BUS/LopBUS.vb
Visual Basic .NET
asf20
674
Public Class KhoiBUS Public Shared Function SelectAll() As List(Of KhoiDTO) Return KhoiDAO.SelectAll() End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/BUS/KhoiBUS.vb
Visual Basic .NET
asf20
150
Public Class GiaoVienBUS Public Shared Function SelectAll() As List(Of GiaoVienDTO) Return GiaoVienDAO.SelectAll() End Function Public Shared Function Them(ByVal gv As GiaoVienDTO) As Integer Return GiaoVienDAO.Them(gv) End Function Public Shared Function LayDSGiaoVien() As List(Of GiaoVienDTO) Return GiaoVienDAO.LayDSGiaoVien() End Function Public Shared Function SuaGiaoVien(ByVal gv As GiaoVienDTO) As Integer Return GiaoVienDAO.SuaGiaoVien(gv) End Function Public Shared Function XoaGiaoVien(ByVal gv As GiaoVienDTO) As Integer Return GiaoVienDAO.XoaGiaoVien(gv) End Function Public Shared Function SelectByMaMon(ByVal MaMon As Integer) As List(Of GiaoVienDTO) Return GiaoVienDAO.SelectByMaMon(MaMon) End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/BUS/GiaoVienBUS.vb
Visual Basic .NET
asf20
849
Public Class HocSinhBUS Public Shared Function Them(ByVal cn As HocSinhDTO) As Integer Return HocSinhDAO.Them(cn) End Function 'Public Shared Function Sua(ByVal cn As HocSinhDTO) As Integer ' Return HocSinhDAO.Sua(cn) 'End Function Public Shared Function SuaKhachHang(ByVal cn As HocSinhDTO) As Integer Return HocSinhDAO.SuaKhachHang(cn) End Function 'Public Shared Function Xoa(ByVal Id As Integer) As Integer ' Return HocSinhDAO.Xoa(Id) 'End Function Public Shared Function SelectAll() As List(Of HocSinhDTO) Return HocSinhDAO.SelectAll() End Function 'Public Shared Function SelectAll1() As List(Of HocSinhDTO) ' Return HocSinhDAO.SelectAll1() 'End Function Public Shared Function SelectByMaLop(ByVal MaLop As Integer) As List(Of HocSinhDTO) Return HocSinhDAO.SelectByMaLop(MaLop) End Function Public Shared Function SelectByKey(ByVal Id As Integer) As HocSinhDTO Return HocSinhDAO.SelectByKey(Id) End Function 'Public Shared Function LayDSHocSinh(ByVal Id As Integer) As HocSinhDTO ' Return HocSinhDAO.SelectByKey(Id) 'End Function Public Shared Function LayDSHocSinh() As List(Of HocSinhDTO) Return HocSinhDAO.LayDSHocSinh() End Function Public Shared Function XoaKhachHang(ByVal hs As HocSinhDTO) As Integer 'Dim hsDAO As New HocSinhDAO() Return HocSinhDAO.XoaKhachHang(hs) End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/BUS/HocSinhBUS.vb
Visual Basic .NET
asf20
1,536
Public Class MonHocBUS Public Shared Function SelectAll() As List(Of MonHocDTO) Return MonHocDAO.SelectAll() End Function Public Shared Function DemSoGVTheoMon() As List(Of MonHocDTO) Return MonHocDAO.DemSoGVTheoMon() End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/BUS/MonHocBUS.vb
Visual Basic .NET
asf20
284
Imports System.Data.OleDb Public Class HocSinhDAO Public Shared Function SelectAll() As List(Of HocSinhDTO) Const strSql As String = "select MAHOCSINH, TENHOCSINH, GIOITINH, NGAYSINH, DIACHI, SODT, EMAIL, MALOP from HOCSINH" Dim ds = New List(Of HocSinhDTO) Using db = New SQLProvider() Using re = db.ExecuteReader(strSql) While re.Read() Dim obj = New HocSinhDTO obj.MAHOCSINH = re.GetInt32(0) obj.TENHOCSINH = re.GetString(1) obj.GIOITINH = re.GetString(2) obj.NGAYSINH = re.GetString(3) obj.DIACHI = re.GetString(4) obj.SODT = re.GetString(5) obj.EMAIL = re.GetString(6) obj.MALOP = re.GetInt32(7) ds.Add(obj) End While End Using End Using Return ds End Function 'Public Shared Function SelectAll1() As List(Of HocSinhDTO) ' Const strSql As String = "select * from LOP" ' Dim ds1 = New List(Of HocSinhDTO) ' Using db1 = New SQLProvider() ' Using re1 = db1.ExecuteReader(strSql) ' While re1.Read() ' Dim obj1 = New HocSinhDTO ' obj1.MALOP1 = re1.GetString(0) ' End While ' End Using ' End Using ' Return ds1 'End Function Public Shared Function SelectByMaLop(ByVal MaLop As Integer) As List(Of HocSinhDTO) Dim strSql As String = String.Format("select MAHOCSINH,TENHOCSINH, GIOITINH,NGAYSINH,DIACHI,SODT,EMAIL,MALOP from HOCSINH where MaLop = {0}", MaLop) Dim ds = New List(Of HocSinhDTO) Using db = New SQLProvider() Using re = db.ExecuteReader(strSql) While re.Read() Dim obj = New HocSinhDTO 'obj.MALOP = re.GetString(0) obj.MAHOCSINH = re.GetInt32(0) obj.TENHOCSINH = re.GetString(1) obj.GIOITINH = re.GetString(2) obj.NGAYSINH = re.GetString(3) obj.DIACHI = re.GetString(4) obj.SODT = re.GetString(5) obj.EMAIL = re.GetString(6) obj.MALOP = re.GetInt32(7) ds.Add(obj) End While End Using End Using Return ds End Function Public Shared Function SelectByKey(ByVal MaCN As Integer) As HocSinhDTO Dim strSql As String = String.Format("select MaHS, TenHS, GioiTinh, Cmnd ,NgaySinh,DiaChi, MaCN from ChiNhanh where MaCN = '{0}'", MaCN) Using db = New SQLProvider() Using re = db.ExecuteReader(strSql) If re.Read() Then Dim obj = New HocSinhDTO obj.MAHOCSINH = re.GetInt32(0) obj.TENHOCSINH = re.GetString(1) obj.GIOITINH = re.GetString(2) obj.NGAYSINH = re.GetDateTime(3) obj.DIACHI = re.GetString(4) obj.SODT = re.GetString(5) obj.EMAIL = re.GetString(6) obj.MALOP = re.GetString(7) Return obj End If End Using End Using Return Nothing End Function Public Shared Function LayDSHocSinh() As List(Of HocSinhDTO) Dim str = "select * from HOCSINH" Dim conn = SQLProvider.ConnectDB("QuanLiHocSinh.mdb") Dim cmd As New OleDbCommand(str, conn) Dim reader = cmd.ExecuteReader() Dim ds As New List(Of HocSinhDTO) While reader.Read() Dim hs As New HocSinhDTO hs.MAHOCSINH = reader.GetInt32(0) hs.TENHOCSINH = reader.GetString(1) hs.GIOITINH = reader.GetString(2) hs.NGAYSINH = reader.GetString(3) hs.DIACHI = reader.GetString(4) hs.SODT = reader.GetString(5) hs.EMAIL = reader.GetString(6) hs.MALOP = reader.GetInt32(7) ds.Add(hs) End While conn.Close() Return ds End Function Public Shared Function Them(ByVal cn As HocSinhDTO) As Integer Using db = New SQLProvider Dim strSql = String.Format("Insert into HOCSINH ( MAHOCSINH,TENHOCSINH, GIOITINH,NGAYSINH,DIACHI,SODT,EMAIL,MALOP) values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}','{6}','{7}')", _ cn.MAHOCSINH, cn.TENHOCSINH, cn.GIOITINH, cn.NGAYSINH, cn.DIACHI, cn.SODT, cn.EMAIL, cn.MALOP) Return db.ExecNoneQuery(strSql) End Using End Function 'Public Shared Function Sua(ByVal cn As HocSinhDTO) As Integer ' Using db = New SQLProvider ' Dim strSql = String.Format("Update HOCSINH set MAHOCSINH = '{0}, TENHOCSINH = '{1}', GIOITINH = '{2}', NGAYSINH = '{3}', DIACHI = '{4}', SODT = '{5}', EMAIL = '{6}' where MALOP = '{7}'", _ ' cn.MAHOCSINH, cn.TENHOCSINH, cn.GIOITINH, cn.NGAYSINH, cn.DIACHI, cn.SODT, cn.EMAIL, cn.MALOP) ' Return db.ExecNoneQuery(strSql) ' End Using 'End Function Public Shared Function SuaKhachHang(ByVal hs As HocSinhDTO) As Integer Dim str = String.Format("update HOCSINH set TENHOCSINH='{0}', GIOITINH='{1}', NGAYSINH='{2}', DIACHI='{3}', SODT='{4}', EMAIL='{5}',MALOP ={6} where MAHOCSINH={7}", hs.TENHOCSINH, hs.GIOITINH, hs.NGAYSINH, hs.DIACHI, hs.SODT, hs.EMAIL, hs.MALOP, hs.MAHOCSINH) Dim conn = SQLProvider.ConnectDB("QuanLiHocSinh.mdb") Dim cmd As New OleDbCommand(str, conn) Dim result = -1 result = cmd.ExecuteNonQuery() conn.Close() Return result End Function 'Public Shared Function Xoa(ByVal MAHOCSINH As Integer) As Integer ' Using db = New SQLProvider ' Dim strSql = String.Format("Delete HOCSINH where MAHOCSINH = '{0}'", _ ' MAHOCSINH) ' Return db.ExecNoneQuery(strSql) ' End Using 'End Function Public Shared Function XoaKhachHang(ByVal hs As HocSinhDTO) As Integer Dim str = String.Format("delete from HOCSINH where MAHOCSINH={0}", hs.MAHOCSINH) Dim conn = SQLProvider.ConnectDB("QuanLiHocSinh.mdb") Dim cmd As New OleDbCommand(str, conn) Dim result = -1 result = cmd.ExecuteNonQuery() conn.Close() Return result End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DAO/HocSinhDAO.vb
Visual Basic .NET
asf20
6,756
Imports System.Data.OleDb Public Class LopDAO Public Shared Function SelectAll() As List(Of LopDTO) Const strSql As String = "select * from LOP" Dim ds = New List(Of LopDTO) Using db = New SQLProvider() Using re = db.ExecuteReader(strSql) While re.Read() Dim obj = New LopDTO obj.MALOP = re.GetInt32(0) obj.TENLOP = re.GetString(1) obj.SISO = re.GetString(2) obj.KHOI = re.GetString(3) obj.NAM = re.GetString(4) obj.MAKHOI = re.GetInt32(5) ds.Add(obj) End While End Using End Using Return ds End Function Public Shared Function LayDSLopHoc() As List(Of LopDTO) Dim str = "select * from LOP" Dim conn = SQLProvider.ConnectDB("QuanLiHocSinh.mdb") Dim cmd As New OleDbCommand(str, conn) Dim reader = cmd.ExecuteReader() Dim ds As New List(Of LopDTO) While reader.Read() Dim hs As New LopDTO hs.MALOP = reader.GetInt32(0) hs.TENLOP = reader.GetString(1) hs.SISO = reader.GetString(2) hs.KHOI = reader.GetString(3) hs.NAM = reader.GetString(4) 'hs.SODT = reader.GetString(5) hs.MAKHOI = reader.GetInt32(5) 'hs.MALOP = reader.GetInt32(7) ds.Add(hs) End While conn.Close() Return ds End Function Public Shared Function SuaLopHoc(ByVal lop As LopDTO) As Integer Dim str = String.Format("update LOP set TENLOP='{0}', SISO='{1}', KHOI='{2}', NAM='{3}', MAKHOI={4} where MALOP={5}", lop.TENLOP, lop.SISO, lop.KHOI, lop.NAM, lop.MAKHOI, lop.MALOP) Dim conn = SQLProvider.ConnectDB("QuanLiHocSinh.mdb") Dim cmd As New OleDbCommand(Str, conn) Dim result = -1 result = cmd.ExecuteNonQuery() conn.Close() Return result End Function Public Shared Function SelectByMaKhoi(ByVal MaKhoi As Integer) As List(Of LopDTO) Dim strSql As String = String.Format("select MALOP,TENLOP, SISO, KHOI, NAM, MAKHOI from LOP where MaKhoi = {0}", MaKhoi) Dim ds = New List(Of LopDTO) Using db = New SQLProvider() Using re = db.ExecuteReader(strSql) While re.Read() Dim obj = New LopDTO 'obj.MALOP = re.GetString(0) obj.MALOP = re.GetInt32(0) obj.TENLOP = re.GetString(1) obj.SISO = re.GetString(2) obj.KHOI = re.GetString(3) obj.NAM = re.GetString(4) 'obj.SODT = re.GetString(5) 'obj.EMAIL = re.GetString(6) obj.MAKHOI = re.GetInt32(5) ds.Add(obj) End While End Using End Using Return ds End Function Public Shared Function DemSoHSTheoLop() As List(Of LopDTO) Dim str = "select l.MALOP, TENLOP, SISO, KHOI, NAM, MAKHOI ,count(h.MAHOCSINH) " str &= "from LOP l, HOCSINH h where l.MALOP=h.MALOP " str &= "group by l.MALOP, TENLOP, SISO, KHOI, NAM, MAKHOI" Dim conn = SQLProvider.ConnectDB("QuanLiHocSinh.mdb") Dim cmd As New OleDbCommand(str, conn) Dim reader = cmd.ExecuteReader() Dim ds As New List(Of LopDTO) While reader.Read() Dim obj As New LopDTO obj.MALOP = reader.GetInt32(0) obj.TENLOP = reader.GetString(1) obj.SISO = reader.GetString(2) obj.KHOI = reader.GetString(3) obj.NAM = reader.GetString(4) obj.MAKHOI = reader.GetInt32(5) obj.SOLUONGHS = reader.GetInt32(6) ds.Add(obj) End While conn.Close() Return ds End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DAO/LopDAO.vb
Visual Basic .NET
asf20
4,084
Imports System.Data.OleDb Public Class GiaoVienDAO Public Shared Function SelectAll() As List(Of GiaoVienDTO) Const strSql As String = "select MAGIAOVIEN, TENGIAOVIEN, GIOITINH, NGAYSINH, DIACHI, SODT, EMAIL, MAMON from GIAOVIEN" Dim ds = New List(Of GiaoVienDTO) Using db = New SQLProvider() Using re = db.ExecuteReader(strSql) While re.Read() Dim obj = New GiaoVienDTO obj.MAGIAOVIEN = re.GetInt32(0) obj.TENGIAOVIEN = re.GetString(1) obj.GIOITINH = re.GetString(2) obj.NGAYSINH = re.GetString(3) obj.DIACHI = re.GetString(4) obj.SODT = re.GetString(5) obj.EMAIL = re.GetString(6) obj.MAMON = re.GetInt32(7) 'obj.TENMON = re.GetString(8) ds.Add(obj) End While End Using End Using Return ds End Function Public Shared Function LayDSGiaoVien() As List(Of GiaoVienDTO) Dim str = "select * from GIAOVIEN" Dim conn = SQLProvider.ConnectDB("QuanLiHocSinh.mdb") Dim cmd As New OleDbCommand(str, conn) Dim reader = cmd.ExecuteReader() Dim ds As New List(Of GiaoVienDTO) While reader.Read() Dim gv As New GiaoVienDTO gv.MAGIAOVIEN = reader.GetInt32(0) gv.TENGIAOVIEN = reader.GetString(1) gv.GIOITINH = reader.GetString(2) gv.NGAYSINH = reader.GetString(3) gv.DIACHI = reader.GetString(4) gv.SODT = reader.GetString(5) gv.EMAIL = reader.GetString(6) gv.MAMON = reader.GetInt32(7) ds.Add(gv) End While conn.Close() Return ds End Function Public Shared Function Them(ByVal gv As GiaoVienDTO) As Integer Using db = New SQLProvider Dim strSql = String.Format("Insert into GIAOVIEN ( MAGIAOVIEN,TENGIAOVIEN, GIOITINH,NGAYSINH,DIACHI,SODT,EMAIL,MAMON) values ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}','{6}','{7}')", _ gv.MAGIAOVIEN, gv.TENGIAOVIEN, gv.GIOITINH, gv.NGAYSINH, gv.DIACHI, gv.SODT, gv.EMAIL, gv.MAMON) Return db.ExecNoneQuery(strSql) End Using End Function Public Shared Function SuaGiaoVien(ByVal gv As GiaoVienDTO) As Integer Dim str = String.Format("update GIAOVIEN set TENGIAOVIEN='{0}', GIOITINH='{1}', NGAYSINH='{2}', DIACHI='{3}', SODT='{4}', EMAIL='{5}',MAMON ={6} where MAGIAOVIEN={7}", gv.TENGIAOVIEN, gv.GIOITINH, gv.NGAYSINH, gv.DIACHI, gv.SODT, gv.EMAIL, gv.MAMON, gv.MAGIAOVIEN) Dim conn = SQLProvider.ConnectDB("QuanLiHocSinh.mdb") Dim cmd As New OleDbCommand(Str, conn) Dim result = -1 result = cmd.ExecuteNonQuery() conn.Close() Return result End Function Public Shared Function XoaGiaoVien(ByVal gv As GiaoVienDTO) As Integer Dim str = String.Format("delete from GIAOVIEN where MAGIAOVIEN={0}", gv.MAGIAOVIEN) Dim conn = SQLProvider.ConnectDB("QuanLiHocSinh.mdb") Dim cmd As New OleDbCommand(str, conn) Dim result = -1 result = cmd.ExecuteNonQuery() conn.Close() Return result End Function Public Shared Function SelectByMaMon(ByVal MaMon As Integer) As List(Of GiaoVienDTO) Dim strSql As String = String.Format("select MAGIAOVIEN,TENGIAOVIEN, GIOITINH, NGAYSINH, DIACHI, SODT, EMAIL, MAMON from GIAOVIEN where MaMon = {0}", MaMon) Dim ds = New List(Of GiaoVienDTO) Using db = New SQLProvider() Using re = db.ExecuteReader(strSql) While re.Read() Dim obj = New GiaoVienDTO 'obj.MALOP = re.GetString(0) obj.MAGIAOVIEN = re.GetInt32(0) obj.TENGIAOVIEN = re.GetString(1) obj.GIOITINH = re.GetString(2) obj.NGAYSINH = re.GetString(3) obj.DIACHI = re.GetString(4) obj.SODT = re.GetString(5) obj.EMAIL = re.GetString(6) obj.MAMON = re.GetInt32(7) ds.Add(obj) End While End Using End Using Return ds End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DAO/GiaoVienDAO.vb
Visual Basic .NET
asf20
4,519
Public Class KhoiDAO Public Shared Function SelectAll() As List(Of KhoiDTO) Const strSql As String = "select * from KHOI" Dim ds = New List(Of KhoiDTO) Using db = New SQLProvider() Using re = db.ExecuteReader(strSql) While re.Read() Dim obj = New KhoiDTO obj.MAKHOI = re.GetInt32(0) obj.TENKHOI = re.GetString(1) ds.Add(obj) End While End Using End Using Return ds End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DAO/KhoiDAO.vb
Visual Basic .NET
asf20
594
Imports System.Data.OleDb Imports System.Data.SqlClient Public Class SQLProvider Implements IDisposable Private m_strConnection As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\QuanLiHocSinh.mdb;User Id=;Password=;" Private m_connection As OleDbConnection Public Sub Open() If m_connection Is Nothing Then m_connection = New OleDbConnection(m_strConnection) End If m_connection.Open() End Sub Public Sub Close() m_connection.Close() End Sub Public Function ExecNoneQuery(ByVal strSql As String) As Integer ' Mo ket noi Open() ' Thuc thi cau truy van Dim command As OleDbCommand = New OleDbCommand(strSql, m_connection) Dim intR = command.ExecuteNonQuery() ' Dong ket noi Close() Return intR End Function Public Function FillDataTable(ByVal strSql As String) As DataTable ' Mo ket noi Open() ' Thuc thi cau truy van Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(strSql, m_connection) Dim dt As DataTable = New DataTable adapter.Fill(dt) ' Doc du lieu Close() Return dt ' Dong ket noi End Function Public Function ExecuteReader(ByVal strSql As String) As IDataReader Try Open() ' Thuc thi cau truy van Dim command As OleDbCommand = New OleDbCommand(strSql, m_connection) Return command.ExecuteReader() Catch ex As Exception Close() Throw New Exception(ex.Message) End Try End Function Public Sub Dispose() Implements IDisposable.Dispose If m_connection.State = ConnectionState.Open Then m_connection.Close() m_connection.Dispose() End If GC.SuppressFinalize(Me) End Sub Public Shared Function ConnectDB(ByVal dbName As String) As OleDbConnection Dim strCon = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = " & dbName Dim conn As New OleDbConnection(strCon) conn.Open() Return conn End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DAO/SQLProvider.vb
Visual Basic .NET
asf20
2,261
Imports System.Data.OleDb Public Class MonHocDAO Public Shared Function SelectAll() As List(Of MonHocDTO) Const strSql As String = "select * from MONHOC" Dim ds = New List(Of MonHocDTO) Using db = New SQLProvider() Using re = db.ExecuteReader(strSql) While re.Read() Dim obj = New MonHocDTO obj.MAMON = re.GetInt32(0) obj.KYHIEUMON = re.GetString(1) obj.TENMON = re.GetString(2) ds.Add(obj) End While End Using End Using Return ds End Function Public Shared Function DemSoGVTheoMon() As List(Of MonHocDTO) Dim str = "select m.MAMON, KYHIEUMON, TENMON, count(g.MAGIAOVIEN) " str &= "from MONHOC m, GIAOVIEN g where m.MAMON=g.MAMON " str &= "group by m.MAMON, KYHIEUMON, TENMON" Dim conn = SQLProvider.ConnectDB("QuanLiHocSinh.mdb") Dim cmd As New OleDbCommand(str, conn) Dim reader = cmd.ExecuteReader() Dim ds As New List(Of MonHocDTO) While reader.Read() Dim obj As New MonHocDTO obj.MAMON = reader.GetInt32(0) obj.KYHIEUMON = reader.GetString(1) obj.TENMON = reader.GetString(2) obj.SLGIAOVIEN = reader.GetInt32(3) ds.Add(obj) End While conn.Close() Return ds End Function End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DAO/MonHocDAO.vb
Visual Basic .NET
asf20
1,508
Public Class LopDTO Public Property MALOP() As Integer Public Property TENLOP() As String Public Property SISO() As String Public Property KHOI() As String Public Property NAM() As String Public Property MAKHOI() As Integer Public Property SOLUONGHS() As Integer End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DTO/LopDTO.vb
Visual Basic .NET
asf20
313
Public Class KhoiDTO Public Property MAKHOI() As Integer Public Property TENKHOI() As String End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DTO/KhoiDTO.vb
Visual Basic .NET
asf20
118
Public Class GiaoVienDTO Public Property MAGIAOVIEN() As Integer Public Property TENGIAOVIEN() As String Public Property GIOITINH() As String Public Property NGAYSINH() As String Public Property DIACHI() As String Public Property SODT() As String Public Property EMAIL() As String Public Property MAMON() As Integer 'Public Property TENMON() As String End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DTO/GiaoVienDTO.vb
Visual Basic .NET
asf20
412
Public Class MonHocDTO Public Property MAMON() As Integer Public Property KYHIEUMON() As String Public Property TENMON() As String Public Property SLGIAOVIEN() As Integer End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DTO/MonHocDTO.vb
Visual Basic .NET
asf20
206
Public Class HocSinhDTO Public Property MAHOCSINH() As Integer Public Property TENHOCSINH() As String Public Property GIOITINH() As String Public Property NGAYSINH() As String Public Property DIACHI() As String Public Property SODT() As String Public Property EMAIL() As String Public Property MALOP() As Integer 'Public Property MALOP1() As String End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/DTO/HocSinhDTO.vb
Visual Basic .NET
asf20
409
Imports System Imports System.Reflection Imports System.Runtime.InteropServices ' General Information about an assembly is controlled through the following ' set of attributes. Change these attribute values to modify the information ' associated with an assembly. ' Review the values of the assembly attributes <Assembly: AssemblyTitle("QuanLiHocSinh")> <Assembly: AssemblyDescription("")> <Assembly: AssemblyCompany("")> <Assembly: AssemblyProduct("QuanLiHocSinh")> <Assembly: AssemblyCopyright("Copyright © 2013")> <Assembly: AssemblyTrademark("")> <Assembly: ComVisible(False)> 'The following GUID is for the ID of the typelib if this project is exposed to COM <Assembly: Guid("a7497dc7-b132-47f5-9000-3f3360c98037")> ' Version information for an assembly consists of the following four values: ' ' Major Version ' Minor Version ' Build Number ' Revision ' ' You can specify all the values or you can default the Build and Revision Numbers ' by using the '*' as shown below: ' <Assembly: AssemblyVersion("1.0.*")> <Assembly: AssemblyVersion("1.0.0.0")> <Assembly: AssemblyFileVersion("1.0.0.0")>
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/My Project/AssemblyInfo.vb
Visual Basic .NET
asf20
1,179
Public Class Form1 End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Form1.vb
Visual Basic .NET
asf20
36
Public Class frmMainForm Private Sub TiếpNhậnHọcSinhToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TiếpNhậnHọcSinhToolStripMenuItem.Click Dim frm = New frmTiepNhanHocSinh() frm.ShowDialog() End Sub Private Sub DanhSachLopToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DanhSachLopToolStripMenuItem.Click Dim frm = New frmDanhSachLop() frm.ShowDialog() End Sub Private Sub QuanLyHocSinhcToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuanLyHocSinhToolStripMenuItem.Click Dim frm = New frmQuanLiHocSinh() frm.ShowDialog() End Sub Private Sub NhậpĐiểmToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NhậpĐiểmToolStripMenuItem.Click Dim frm = New frmNhapDiem() frm.ShowDialog() End Sub Private Sub QuảnLýLớpHọcToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuảnLýLớpHọcToolStripMenuItem.Click Dim frm = New frmQuanLiLopHoc() frm.ShowDialog() End Sub Private Sub TiếpNhậnGiáoViênToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TiếpNhậnGiáoViênToolStripMenuItem.Click Dim frm = New frmTiepNhanGiaoVien() frm.ShowDialog() End Sub Private Sub QuảnLýGiáoViênToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles QuảnLýGiáoViênToolStripMenuItem.Click Dim frm = New frmQuanLiGiaoVien() frm.ShowDialog() End Sub Private Sub TraCứuHọcSinhToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TraCứuHọcSinhToolStripMenuItem1.Click Dim frm = New frmTraCuuHocSinh() frm.ShowDialog() End Sub Private Sub TraCứuGiáoViênToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TraCứuGiáoViênToolStripMenuItem.Click Dim frm = New frmTraCuuGiaoVien() frm.ShowDialog() End Sub Private Sub TraCứuLớpHọcToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TraCứuLớpHọcToolStripMenuItem.Click Dim frm = New frmTraCuuLopHoc() frm.ShowDialog() End Sub Private Sub TraCứuĐiểmToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TraCứuĐiểmToolStripMenuItem.Click Dim frm = New frmTraCuuDiem() frm.ShowDialog() End Sub Private Sub ThoátToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ThoátToolStripMenuItem1.Click Me.Close() End Sub Private Sub ThoátToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ThoátToolStripMenuItem.Click Me.Close() End Sub Private Sub TựGiớiThiệuToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TựGiớiThiệuToolStripMenuItem.Click Dim frm = New frmTacGia() frm.ShowDialog() End Sub Private Sub SốHọcSinhTrongMỗiLớpToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SốHọcSinhTrongMỗiLớpToolStripMenuItem.Click Dim frm = New frmDemSoLuongHSTheoLop() frm.ShowDialog() End Sub Private Sub SốGiáoViênTheoMônToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SốGiáoViênTheoMônToolStripMenuItem.Click Dim frm = New frmDemSoLuongGVTheoMon() frm.ShowDialog() End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/frmMainForm.vb
Visual Basic .NET
asf20
3,935
Public Class frmQuanLiLopHoc Private Sub frmQuanLiLopHoc_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim lopBUS As New LopBUS() Dim ds As List(Of LopDTO) ds = lopBUS.LayDSLopHoc() dgvDSLop.Rows.Clear() For Each lop As LopDTO In ds dgvDSLop.Rows.Add(lop.MALOP, lop.TENLOP, lop.SISO, lop.KHOI, lop.NAM, lop.MAKHOI) Next End Sub Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click Try If (dgvDSLop.SelectedRows.Count > 0) Then Dim lopBUS As New LopBUS() Dim row As DataGridViewRow = dgvDSLop.SelectedRows(0) Dim maKHOI As Integer = Integer.Parse(row.Cells(0).Value) Dim frm As New frmSuaChiTietLopHoc() 'frm.MaHS = maHS frm.txtTenLop.Text = row.Cells(1).Value.ToString() frm.txtSiSo.Text = row.Cells(2).Value.ToString() frm.txtTenKhoi.Text = row.Cells(3).Value.ToString() frm.txtNam.Text = row.Cells(4).Value.ToString() frm.MaLop = maKHOI frm.ShowDialog() Dim ds As List(Of LopDTO) ds = lopBUS.LayDSLopHoc() dgvDSLop.Rows.Clear() For Each lop As LopDTO In ds dgvDSLop.Rows.Add(lop.MALOP, lop.TENLOP, lop.SISO, lop.KHOI, lop.NAM, lop.MAKHOI) Next End If Catch ex As Exception End Try End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Me.Close() End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmQuanLiLopHoc.vb
Visual Basic .NET
asf20
1,793
Public Class frmTraCuuDiem End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmTraCuuDiem.vb
Visual Basic .NET
asf20
42
Public Class frmSuaChiTietLopHoc Public MaLop As Integer Public MaKhoi As Integer = -1 Private Sub frmSuaChiTietLopHoc_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ds As New List(Of LopDTO) Dim hsBUS As New LopBUS() ds = LopBUS.SelectAll() cboKhoi.DataSource = ds cboKhoi.ValueMember = "MAKHOI" cboKhoi.DisplayMember = "TENKHOI" If MaKhoi > -1 Then cboKhoi.SelectedValue = MaKhoi End If End Sub Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click Dim lopDTO As New LopDTO() 'Dim hsDTO = New HocSinhDTO lopDTO.MALOP = MaLop lopDTO.TENLOP = txtTenLop.Text lopDTO.SISO = txtSiSo.Text lopDTO.KHOI = txtTenKhoi.Text lopDTO.NAM = txtNam.Text lopDTO.MAKHOI = cboKhoi.SelectedValue Dim lopBUS As New LopBUS() Dim res = lopBUS.SuaLopHoc(lopDTO) If res >= 0 Then MessageBox.Show("Sửa thành công") Else MessageBox.Show("Sửa thất bại") End If End Sub Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click txtMaLop.Text = String.Empty txtTenLop.Text = String.Empty txtSiSo.Text = String.Empty txtTenKhoi.Text = String.Empty txtNam.Text = String.Empty cboKhoi.Text = String.Empty End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Me.Close() End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmSuaChiTietLopHoc.vb
Visual Basic .NET
asf20
1,735
Public Class frmDemSoLuongHSTheoLop Private Sub frmDemSoLuongHSTheoLop_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ds As New List(Of LopDTO) Dim lopBUS As New LopBUS() ds = lopBUS.DemSoHSTheoLop() dgvDSCN.Rows.Clear() For Each l As LopDTO In ds dgvDSCN.Rows.Add(l.TENLOP, l.SOLUONGHS) Next End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmDemSoLuongHSTheoLop.vb
Visual Basic .NET
asf20
447
Public Class frmTiepNhanGiaoVien Private Sub frmTiepNhanGiaoVien_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cboMon.DataSource = MonHocBUS.SelectAll() cboMon.ValueMember = "MAMON" cboMon.DisplayMember = "TENMON" dgvDSGV.DataSource = GiaoVienBUS.SelectAll() End Sub Sub LoadDanhSach() dgvDSGV.DataSource = GiaoVienBUS.SelectAll() End Sub Private Sub btnThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThem.Click Dim gv = New GiaoVienDTO gv.MAGIAOVIEN = txtMaGV.Text gv.TENGIAOVIEN = txtTenGV.Text gv.GIOITINH = IIf(rbNam.Checked, "Nam", "Nữ") gv.NGAYSINH = txtNgaySinh.Text gv.DIACHI = txtDiaChi.Text gv.SODT = txtSoDT.Text gv.EMAIL = txtEmail.Text gv.MAMON = cboMon.SelectedValue Dim re = GiaoVienBUS.Them(gv) If re >= 1 Then MessageBox.Show("Thêm thành công") Else MessageBox.Show("Thêm thất bại") End If LoadDanhSach() End Sub Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click txtMaGV.Text = String.Empty txtTenGV.Text = String.Empty rbNam.Checked = True txtNgaySinh.Text = String.Empty txtDiaChi.Text = String.Empty txtEmail.Text = String.Empty txtSoDT.Text = String.Empty End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Me.Close() End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmTiepNhanGiaoVien.vb
Visual Basic .NET
asf20
1,698
Public Class frmNhapDiem End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmNhapDiem.vb
Visual Basic .NET
asf20
40
Public Class frmTacGia End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmTacGia.vb
Visual Basic .NET
asf20
38
Public Class frmQuanLiHocSinh Private Sub frmQuanLiHocSinh_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim hsBUS As New HocSinhBUS() Dim ds As List(Of HocSinhDTO) ds = HocSinhBUS.LayDSHocSinh() dgvDSHS.Rows.Clear() For Each hs As HocSinhDTO In ds dgvDSHS.Rows.Add(hs.MAHOCSINH, hs.TENHOCSINH, hs.GIOITINH, hs.NGAYSINH, hs.DIACHI, hs.SODT, hs.EMAIL, hs.MALOP) Next 'dgvDSHS.DataSource = HocSinhBUS.SelectAll() End Sub Sub LoadDanhSach() dgvDSHS.DataSource = HocSinhBUS.SelectAll() End Sub Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click Try If (dgvDSHS.SelectedRows.Count > 0) Then Dim hsBUS As New HocSinhBUS() Dim row As DataGridViewRow = dgvDSHS.SelectedRows(0) Dim maLOP As Integer = Integer.Parse(row.Cells(0).Value) Dim frm As New frmSuaHoSoHocSinh() 'frm.MaHS = maHS frm.txtTenHS.Text = row.Cells(1).Value.ToString() If row.Cells(2).Value.ToString() = "Nam" Then frm.rbNam.Checked = True Else frm.rbNu.Checked = True End If frm.txtNgaySinh.Text = row.Cells(3).Value.ToString() frm.txtDiaChi.Text = row.Cells(4).Value.ToString() 'frm.dtpNgaySinh.Value = row.Cells(4).Value frm.txtSoDT.Text = row.Cells(5).Value.ToString() frm.txtEmail.Text = row.Cells(6).Value.ToString() 'frm.MaLop = row.Cells(7).Value.ToString() 'frm.MaLop = row.Cells(7).Value.ToString() 'frm.MaCN = row.Cells(6).Value 'frm.MaLop = row.Cells(7).Value.ToString() 'frm.cboLop.Text = row.Cells(7).Value.ToString() frm.MaLop = maLOP frm.ShowDialog() Dim ds As List(Of HocSinhDTO) ds = HocSinhBUS.LayDSHocSinh() dgvDSHS.Rows.Clear() For Each hs As HocSinhDTO In ds dgvDSHS.Rows.Add(hs.MAHOCSINH, hs.TENHOCSINH, hs.GIOITINH, hs.NGAYSINH, hs.DIACHI, hs.SODT, hs.EMAIL, hs.MALOP) Next End If Catch ex As Exception End Try 'LoadDanhSach() End Sub Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click Try Dim hsBUS As New HocSinhBUS() If (dgvDSHS.SelectedRows.Count > 0) Then For Each row As DataGridViewRow In dgvDSHS.SelectedRows Dim hsDAO As New HocSinhDTO hsDAO.MAHOCSINH = Integer.Parse(row.Cells(0).Value) 'hsDTO.MAHOCSINH = HocSinhBUS.XoaKhachHang(hsDAO) Next MessageBox.Show("Xóa thành công") Dim ds As List(Of HocSinhDTO) ds = HocSinhBUS.LayDSHocSinh() dgvDSHS.Rows.Clear() For Each hs As HocSinhDTO In ds dgvDSHS.Rows.Add(hs.MAHOCSINH, hs.TENHOCSINH, hs.GIOITINH, hs.NGAYSINH, hs.DIACHI, hs.SODT, hs.EMAIL, hs.MALOP) Next End If Catch ex As Exception 'MessageBox.Show("Lỗi: " + ex.Message) End Try 'LoadDanhSach() End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Me.Close() End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmQuanLiHocSinh.vb
Visual Basic .NET
asf20
3,758
Public Class frmTraCuuLopHoc Private Sub frmTraCuuLopHoc_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cboKhoi.DataSource = KhoiBUS.SelectAll() cboKhoi.ValueMember = "MAKHOI" cboKhoi.DisplayMember = "TENKHOI" End Sub Private Sub btnTraCuu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTraCuu.Click Dim maKhoi As Integer = cboKhoi.SelectedValue dgvDSLop.Rows.Clear() For Each l As LopDTO In LopBUS.SelectByMaKhoi(maKhoi) dgvDSLop.Rows.Add(l.MALOP, l.TENLOP, l.SISO, l.KHOI, l.NAM, l.MAKHOI) Next End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmTraCuuLopHoc.vb
Visual Basic .NET
asf20
686
Public Class frmDanhSachLop Private Sub frmDanhSachLop_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim lopBUS As New LopBUS() Dim ds As List(Of LopDTO) ds = lopBUS.SelectAll() dgvDSLop.Rows.Clear() For Each l As LopDTO In ds dgvDSLop.Rows.Add(l.MALOP, l.TENLOP, l.SISO, l.KHOI, l.NAM) Next 'dgvDSLop.DataSource = LopBUS.SelectAll() End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmDanhSachLop.vb
Visual Basic .NET
asf20
484
Public Class frmTraCuuHocSinh Private Sub frmTraCuuHocSinh_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cboLop.DataSource = LopBUS.SelectAll() cboLop.ValueMember = "MALOP" cboLop.DisplayMember = "TENLOP" End Sub Private Sub btnTraCuu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTraCuu.Click Dim maLop As Integer = cboLop.SelectedValue dgvDSHS.Rows.Clear() For Each k As HocSinhDTO In HocSinhBUS.SelectByMaLop(maLop) dgvDSHS.Rows.Add(k.MAHOCSINH, k.TENHOCSINH, k.GIOITINH, k.NGAYSINH, k.DIACHI, k.EMAIL) Next End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmTraCuuHocSinh.vb
Visual Basic .NET
asf20
702
Public Class frmQuanLiGiaoVien Private Sub frmQuanLiGiaoVien_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim gvBUS As New GiaoVienBUS() Dim ds As List(Of GiaoVienDTO) ds = GiaoVienBUS.LayDSGiaoVien() dgvDSGV.Rows.Clear() For Each gv As GiaoVienDTO In ds dgvDSGV.Rows.Add(gv.MAGIAOVIEN, gv.TENGIAOVIEN, gv.GIOITINH, gv.NGAYSINH, gv.DIACHI, gv.SODT, gv.EMAIL, gv.MAMON) Next End Sub Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click Try If (dgvDSGV.SelectedRows.Count > 0) Then Dim gvBUS As New GiaoVienBUS() Dim row As DataGridViewRow = dgvDSGV.SelectedRows(0) Dim maMON As Integer = Integer.Parse(row.Cells(0).Value) Dim frm As New frmSuaHoSoGiaoVien() 'frm.MaHS = maHS frm.txtTenGV.Text = row.Cells(1).Value.ToString() If row.Cells(2).Value.ToString() = "Nam" Then frm.rbNam.Checked = True Else frm.rbNu.Checked = True End If frm.txtNgaySinh.Text = row.Cells(3).Value.ToString() frm.txtDiaChi.Text = row.Cells(4).Value.ToString() frm.txtSoDT.Text = row.Cells(5).Value.ToString() frm.txtEmail.Text = row.Cells(6).Value.ToString() frm.MaMon = maMON frm.ShowDialog() Dim ds As List(Of GiaoVienDTO) ds = GiaoVienBUS.LayDSGiaoVien() dgvDSGV.Rows.Clear() For Each gv As GiaoVienDTO In ds dgvDSGV.Rows.Add(gv.MAGIAOVIEN, gv.TENGIAOVIEN, gv.GIOITINH, gv.NGAYSINH, gv.DIACHI, gv.SODT, gv.EMAIL, gv.MAMON) Next End If Catch ex As Exception End Try End Sub Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click Try Dim hsBUS As New HocSinhBUS() If (dgvDSGV.SelectedRows.Count > 0) Then For Each row As DataGridViewRow In dgvDSGV.SelectedRows Dim gvDAO As New GiaoVienDTO gvDAO.MAGIAOVIEN = Integer.Parse(row.Cells(0).Value) 'hsDTO.MAHOCSINH = GiaoVienBUS.XoaGiaoVien(gvDAO) Next MessageBox.Show("Xóa thành công") Dim ds As List(Of GiaoVienDTO) ds = GiaoVienBUS.LayDSGiaoVien() dgvDSGV.Rows.Clear() For Each gv As GiaoVienDTO In ds dgvDSGV.Rows.Add(gv.MAGIAOVIEN, gv.TENGIAOVIEN, gv.GIOITINH, gv.NGAYSINH, gv.DIACHI, gv.SODT, gv.EMAIL, gv.MAMON) Next End If Catch ex As Exception 'MessageBox.Show("Lỗi: " + ex.Message) End Try End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Me.Close() End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmQuanLiGiaoVien.vb
Visual Basic .NET
asf20
3,230
Public Class frmDemSoLuongGVTheoMon Private Sub frmDemSoLuongGVTheoMon_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ds1 As New List(Of MonHocDTO) Dim monBUS As New MonHocBUS() ds1 = monBUS.DemSoGVTheoMon() dgvDSCN.Rows.Clear() For Each l As MonHocDTO In ds1 dgvDSCN.Rows.Add(l.TENMON, l.SLGIAOVIEN) Next End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmDemSoLuongGVTheoMon.vb
Visual Basic .NET
asf20
452
Public Class frmTiepNhanHocSinh Private Sub frmTiepNhanHocSinh_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cboLop.DataSource = LopBUS.SelectAll() cboLop.ValueMember = "MALOP" cboLop.DisplayMember = "TENLOP" dgvDSHS.DataSource = HocSinhBUS.SelectAll() End Sub Sub LoadDanhSach() dgvDSHS.DataSource = HocSinhBUS.SelectAll() End Sub Private Sub btnThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThem.Click Dim hs = New HocSinhDTO hs.MAHOCSINH = txtMaHS.Text hs.TENHOCSINH = txtTenHS.Text hs.GIOITINH = IIf(rbNam.Checked, "Nam", "Nữ") hs.NGAYSINH = txtNgaySinh.Text hs.DIACHI = txtDiaChi.Text hs.SODT = txtSoDT.Text hs.EMAIL = txtEmail.Text hs.MALOP = cboLop.SelectedValue Dim re = HocSinhBUS.Them(hs) If re >= 1 Then MessageBox.Show("Thêm thành công") Else MessageBox.Show("Thêm thất bại") End If LoadDanhSach() End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Me.Close() End Sub Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click txtMaHS.Text = String.Empty txtTenHS.Text = String.Empty rbNam.Checked = True txtNgaySinh.Text = String.Empty txtDiaChi.Text = String.Empty txtEmail.Text = String.Empty txtSoDT.Text = String.Empty End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmTiepNhanHocSinh.vb
Visual Basic .NET
asf20
1,693
Public Class frmTraCuuGiaoVien Private Sub frmTraCuuGiaoVien_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load cboMon.DataSource = MonHocBUS.SelectAll() cboMon.ValueMember = "MAMON" cboMon.DisplayMember = "TENMON" End Sub Private Sub btnTraCuu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTraCuu.Click Dim maMon As Integer = cboMon.SelectedValue dgvDSGV.Rows.Clear() For Each gv As GiaoVienDTO In GiaoVienBUS.SelectByMaMon(maMon) dgvDSGV.Rows.Add(gv.MAGIAOVIEN, gv.TENGIAOVIEN, gv.GIOITINH, gv.NGAYSINH, gv.DIACHI, gv.EMAIL, gv.MAMON) Next End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmTraCuuGiaoVien.vb
Visual Basic .NET
asf20
730
Public Class frmSuaHoSoHocSinh Public MaHS As Integer Public MaLop As Integer = -1 Private Sub frmSuaHoSoHocSinh_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ds As New List(Of LopDTO) Dim hsBUS As New LopBUS() ds = LopBUS.SelectAll() cboLop.DataSource = ds cboLop.ValueMember = "MALOP" cboLop.DisplayMember = "TENLOP" If MaLop > -1 Then cboLop.SelectedValue = MaLop End If End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Me.Close() End Sub Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click Dim hsDTO As New HocSinhDTO() 'Dim hsDTO = New HocSinhDTO hsDTO.MAHOCSINH = MaHS hsDTO.TENHOCSINH = txtTenHS.Text If (rbNam.Checked) Then hsDTO.GIOITINH = "Nam" Else hsDTO.GIOITINH = "Nữ" End If hsDTO.NGAYSINH = txtNgaySinh.Text 'hsDTO.cmnd = txtCMND.Text 'hsDTO.NGAYSINH = dtpNgaySinh.Value hsDTO.DIACHI = txtDiaChi.Text hsDTO.SODT = txtSoDT.Text hsDTO.EMAIL = txtEmail.Text hsDTO.MALOP = cboLop.SelectedValue Dim hsBUS As New HocSinhBUS() Dim res = HocSinhBUS.SuaKhachHang(hsDTO) If res >= 0 Then MessageBox.Show("Sửa thành công") Else MessageBox.Show("Sửa thất bại") End If End Sub Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click txtMaHS.Text = String.Empty txtTenHS.Text = String.Empty rbNam.Checked = True txtNgaySinh.Text = String.Empty txtDiaChi.Text = String.Empty txtEmail.Text = String.Empty txtSoDT.Text = String.Empty End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmSuaHoSoHocSinh.vb
Visual Basic .NET
asf20
2,129
Public Class frmSuaHoSoGiaoVien Public MaGV As Integer Public MaMon As Integer = -1 Private Sub frmSuaHoSoGiaoVien_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ds As New List(Of MonHocDTO) Dim hsBUS As New MonHocBUS() ds = MonHocBUS.SelectAll() cboMon.DataSource = ds cboMon.ValueMember = "MAMON" cboMon.DisplayMember = "TENMON" If MaMon > -1 Then cboMon.SelectedValue = MaMon End If End Sub Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click Dim gvDTO As New GiaoVienDTO() gvDTO.MAGIAOVIEN = MaGV gvDTO.TENGIAOVIEN = txtTenGV.Text If (rbNam.Checked) Then gvDTO.GIOITINH = "Nam" Else gvDTO.GIOITINH = "Nữ" End If gvDTO.NGAYSINH = txtNgaySinh.Text 'hsDTO.cmnd = txtCMND.Text 'hsDTO.NGAYSINH = dtpNgaySinh.Value gvDTO.DIACHI = txtDiaChi.Text gvDTO.SODT = txtSoDT.Text gvDTO.EMAIL = txtEmail.Text gvDTO.MAMON = cboMon.SelectedValue Dim gvBUS As New GiaoVienBUS() Dim res = GiaoVienBUS.SuaGiaoVien(gvDTO) If res >= 0 Then MessageBox.Show("Sửa thành công") Else MessageBox.Show("Sửa thất bại") End If End Sub Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click txtMaGV.Text = String.Empty txtTenGV.Text = String.Empty rbNam.Checked = True txtNgaySinh.Text = String.Empty txtDiaChi.Text = String.Empty txtEmail.Text = String.Empty txtSoDT.Text = String.Empty End Sub Private Sub btnThoat_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThoat.Click Me.Close() End Sub End Class
0971006-0971075--do-an-cuoi-ky
trunk/0971006_0971075--QuanLiHocSinh/QuanLiHocSinh/Presentation/frmSuaHoSoGiaoVien.vb
Visual Basic .NET
asf20
2,017
package ru.gelin.android.bells.timers; import java.util.Calendar; import java.util.Date; /** * Timer. */ public class Timer { /** ID of the timer in the collection */ int id; /** Is this timer enabled? */ boolean enabled = true; /** Start time */ Date start = new Date(); /** Period */ Period period = new Period(0, 30); /** Timer message to display */ String message = ""; /** Timer alarm type */ String alarm; public Timer() { } /** * Creates timer with specified ID. */ Timer(int id) { this.id = id; } /** * Returns the ID of the timer. * ID is meaningful only inside the collection of timers. * @return */ public int getId() { return id; } /** * Sets the ID of the timer. */ void setId(int id) { this.id = id; } /** * Returns true if this timer is enabled. */ public boolean isEnabled() { return enabled; } /** * Sets enabled flag for the timer. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Returns the timer message to display to the user. */ public String getMessage() { return message; } /** * Sets the timer message to display to the user. */ public void setMessage(String message) { this.message = message; } /** * Returns the alarm type. */ public String getAlarm() { return alarm; } /** * Sets the alarm type. */ public void setAlarm(String alarm) { this.alarm = alarm; } /** * Gets the start time of the timer. * Each time the alarm happens the start time is shifted to * period. */ public Date getStartTime() { return start; } /** * Sets the start time of the timer. */ public void setStartTime(Date start) { this.start = normalizeDate(start); } /** * Gets the period of the timer. */ public Period getPeriod() { return period; } /** * Sets the period for the timer. */ public void setPeriod(int hours, int minutes) { this.period = new Period(hours, minutes); } /** * Returns the alarm time. * It time in the future when the timer should alarm. * @param now current time * @return some time in future */ public Date getAlarmTime(Date now) { Date nowMinute = normalizeDate(now); Date result = start; while (!result.after(nowMinute)) { result = period.add(result); } return result; } /** * Normalizes the timer, i.e. start time is set to not more than one period * in the past or now or in the future. * @param now time relative to which normalize the timer */ public void normalize(Date now) { Date nowMinute = normalizeDate(now); if (!start.before(nowMinute)) { return; //start is now or in the future } start = period.sub(getAlarmTime(now)); } /** * Normalizes dates, i.e. sets seconds and milliseconds to zero. */ public static Date normalizeDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); return calendar.getTime(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; if (id > 0) { return result; //just hash code of id } result = prime * result + ((start == null) ? 0 : start.hashCode()); result = prime * result + ((period == null) ? 0 : period.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Timer other = (Timer) obj; if (id != other.id) return false; if (id > 0 && id == other.id) { return true; //equals by ID } if (start == null) { if (other.start != null) return false; } else if (!start.equals(other.start)) return false; if (period == null) { if (other.period != null) return false; } else if (!period.equals(other.period)) return false; return true; } /** * Prints main properties of the timer. */ public String toString() { return "Timer: id = " + id; } /** * Creates new timer equals to this. */ public Timer copy() { Timer result = new Timer(); result.id = id; result.enabled = enabled; result.start = start; result.period = period; result.message = message; result.alarm = alarm; return result; } }
0911aihara-bells
src/ru/gelin/android/bells/timers/Timer.java
Java
gpl2
5,247
package ru.gelin.android.bells.timers; import java.util.Calendar; import java.util.Date; /** * Period of the timer, in hours and minutes. */ public class Period { /** Hours of the timer period */ int hours; /** Minutes of the timer period */ int minutes; /** * Creates new period. * @param hours 0-24 * @param minutes 0-59 */ public Period(int hours, int minutes) { this.hours = hours; this.minutes = minutes; if (hours * 60 + minutes <= 0) { this.hours = 0; this.minutes = 1; } } public int getHours() { return hours; } public int getMinutes() { return minutes; } /** * Adds the period to the date. */ public Date add(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(Timer.normalizeDate(date)); calendar.add(Calendar.HOUR_OF_DAY, hours); calendar.add(Calendar.MINUTE, minutes); return calendar.getTime(); } /** * Subtracts the period from the date. */ public Date sub(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(Timer.normalizeDate(date)); calendar.add(Calendar.HOUR_OF_DAY, -hours); calendar.add(Calendar.MINUTE, -minutes); return calendar.getTime(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + hours; result = prime * result + minutes; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Period other = (Period) obj; if (hours != other.hours) return false; if (minutes != other.minutes) return false; return true; } }
0911aihara-bells
src/ru/gelin/android/bells/timers/Period.java
Java
gpl2
2,032
package ru.gelin.android.bells.timers; import java.util.Comparator; import java.util.Date; /** * Order timers by the alarm time. * Because of the alarm time depends on the current time * (can be equal to the start time when the start time is in the future), * the constructor of this comparator takes the current time as argument. */ class TimerComparator implements Comparator<Timer> { /** Current time to compare */ Date now = new Date(); /** * Creates new comparator for the current time. * @param current time */ TimerComparator(Date now) { this.now = now; } /** * Order timers by alarm time and ID. * If IDs of both timers are equal, timers are considered equal too. */ @Override public int compare(Timer timer1, Timer timer2) { if (timer1.id > 0 && timer1.id == timer2.id) { return 0; //equals by ID } Date alarm1 = timer1.getAlarmTime(now); Date alarm2 = timer2.getAlarmTime(now); int alarmCompare = alarm1.compareTo(alarm2); if (alarmCompare != 0) { return alarmCompare; } //ordering by ID return timer1.id - timer2.id; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((now == null) ? 0 : now.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; TimerComparator other = (TimerComparator) obj; if (now == null) { if (other.now != null) return false; } else if (!now.equals(other.now)) return false; return true; } }
0911aihara-bells
src/ru/gelin/android/bells/timers/TimerComparator.java
Java
gpl2
1,898
package ru.gelin.android.bells.timers; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Collections of timers. * Each timer in the collection is identified by the ID. * ID is assigned to the timer during insertion. * ID is used to find timer in the collection during update. */ public class TimerCollection { /** Map of timers by ID */ Map<Integer, Timer> timers = new HashMap<Integer, Timer>(); /** IDs counter */ int idCounter; /** * Inserts new timer to collection. * Sets the ID for the timer. * @param timer ID of this timer is set */ public void insert(Timer timer) { int id = getNextId(); timer.setId(id); timers.put(id, timer.copy()); } /** * Updates timer in the collection. * The timer with specified ID is updated * @param timer timer (ID and values) to update */ public void update(Timer timer) { timers.put(timer.getId(), timer.copy()); } /** * Selects one timer by ID. */ public Timer select(int id) { return timers.get(id).copy(); } /** * Deletes one timer by ID. */ public Timer delete(int id) { return timers.remove(id); } /** * Deletes all timers from the collection. */ public void delete() { timers.clear(); } /** * Returns the list of timers in the collection. * The timers are ordered by the time of the alarm time acceding. * Not the actual, but the deep copy of the original collection * is returned, to modify any element of the collection perform * {@link #update}. * @param now current time, is used to sort the list */ public List<Timer> select(Date now) { List<Timer> result = new ArrayList<Timer>(timers.size()); for (Timer timer : internalList(now)) { result.add(timer.copy()); } return result; } /** * Returns sorted list of actual timers saved in the collection. * @param now current time, is used to sort the list */ protected List<Timer> internalList(Date now) { List<Timer> result = new ArrayList<Timer>(timers.size()); result.addAll(timers.values()); Collections.sort(result, new TimerComparator(now)); return result; } /** * Returns unsorted list of actual timers saved in the collection. */ protected List<Timer> internalList() { List<Timer> result = new ArrayList<Timer>(timers.size()); result.addAll(timers.values()); return result; } /** * Returns the current size of the collection. */ public int size() { return timers.size(); } /** * Selects all timers which alarms have came. * <pre> * now * -------------|--------------- * start alarm * ----------------|------------ * start alarm * ----period---- * </pre> */ public List<Timer> selectAlarms(Date now) { Date nowMinute = Timer.normalizeDate(now); List<Timer> result = new ArrayList<Timer>(); for (Timer timer : internalList(now)) { if (!timer.isEnabled()) { continue; } Date start = timer.getStartTime(); if (!start.before(nowMinute)) { continue; //will start in future } Date startPlusPeriod = timer.getPeriod().add(timer.getStartTime()); if (!startPlusPeriod.after(nowMinute)) { result.add(timer.copy()); } else { break; } } return result; } /** * Normalizes all alarms. I.e. shifts all it's times to make alarm time * in future. * Note that after calling this method {@link #selectAlarms} will * return empty list. */ public void normalize(Date now) { for (Timer timer : internalList(now)) { timer.normalize(now); } } /** * Returns nearest alarm time, i.e. the alarm time of the first * enabled timer in the sorted list. * @return next alarm date or <code>null</code> if there is no enabled timers */ public Date alarmTime(Date now) { for (Timer timer : internalList(now)) { if (timer.isEnabled()) { return timer.getAlarmTime(now); } } return null; } /** * Returns next ID for the inserting Timer */ int getNextId() { return ++idCounter; } }
0911aihara-bells
src/ru/gelin/android/bells/timers/TimerCollection.java
Java
gpl2
4,798
package ru.gelin.android.bells; import java.util.Date; import android.app.Activity; import android.os.Bundle; /** * Activity which tracks (saves into instance state) the time * when it is started. */ public class NowActivity extends Activity { /** Key in the instance state bundle to save activity start time */ static final String NOW_KEY = "now"; /** Current time (when activity is started) */ Date now; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { //first start now = new Date(); } else { //restart now = new Date( savedInstanceState.getLong(NOW_KEY, System.currentTimeMillis())); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putLong(NOW_KEY, now.getTime()); } }
0911aihara-bells
src/ru/gelin/android/bells/NowActivity.java
Java
gpl2
977
package ru.gelin.android.bells; import java.util.Date; import ru.gelin.android.bells.timers.Timer; import android.content.Intent; import android.media.AudioManager; import android.net.Uri; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; public class TimersListActivity extends NowActivity implements Constants { /** Storage of the timers */ TimerStorage timers; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.timers_list); timers = TimerStorage.getInstance(this); ListView timersList = (ListView)findViewById(R.id.timers_list); registerForContextMenu(timersList); timersList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { editTimer((int)id); } }); setVolumeControlStream(AudioManager.STREAM_ALARM); } @Override public void onResume() { super.onResume(); loadTimers(); if (timers.size() > 0) { findViewById(R.id.add_timer_warn).setVisibility(View.GONE); findViewById(R.id.timers_list).setVisibility(View.VISIBLE); } else { findViewById(R.id.add_timer_warn).setVisibility(View.VISIBLE); findViewById(R.id.timers_list).setVisibility(View.GONE); } } @Override public void onPause() { super.onPause(); timers.save(); timers.scheduleAlarm(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.timers_list, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_add_timer: addTimer(); return true; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.timers_list_item, menu); View itemView = ((AdapterContextMenuInfo)menuInfo).targetView; TextView timerName = (TextView)itemView.findViewById(R.id.timer_name); menu.setHeaderTitle(timerName.getText()); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo(); switch (item.getItemId()) { case R.id.menu_edit_timer: editTimer((int)info.id); return true; case R.id.menu_delete_timer: deleteTimer((int)info.id); return true; case R.id.menu_start_now_timer: startNowTimer((int)info.id); return true; } return super.onContextItemSelected(item); } void loadTimers() { now = new Date(); //we updating and normalizing the timer according actually current time timers.load(); timers.normalize(now); ListView list = (ListView)findViewById(R.id.timers_list); ListAdapter adapter = new TimersListAdapter(this, timers, now); list.setAdapter(adapter); } void addTimer() { Intent intent = new Intent(this, AddTimerActivity.class); startActivity(intent); } void editTimer(int id) { Intent intent = new Intent(this, EditTimerActivity.class); intent.setData(new Uri.Builder().scheme(TIMER_SCHEME). opaquePart(String.valueOf(id)).build()); startActivity(intent); } void deleteTimer(int id) { timers.delete(id); timers.save(); loadTimers(); } void startNowTimer(int id) { Timer timer = timers.select(id); timer.setStartTime(now); timer.normalize(now); timers.update(timer); timers.save(); loadTimers(); } }
0911aihara-bells
src/ru/gelin/android/bells/TimersListActivity.java
Java
gpl2
4,770
package ru.gelin.android.bells; import java.util.Date; import android.content.Context; import android.content.Intent; import android.content.BroadcastReceiver; /** * Broadcast receiver which receives event about boot complete. * Starts AlarmActitity. */ public class BootCompletedReceiver extends BroadcastReceiver implements Constants { public void onReceive (Context context, Intent intent) { Date now = new Date(); TimerStorage timers = TimerStorage.getInstance(context); timers.load(); timers.normalize(now); timers.save(); timers.scheduleAlarm(now); } }
0911aihara-bells
src/ru/gelin/android/bells/BootCompletedReceiver.java
Java
gpl2
633
package ru.gelin.android.bells; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class TimerDbOpenHelper extends SQLiteOpenHelper { static final String DATABASE_NAME = "timers"; static final int DATABASE_VERSION = 1; static final String TIMER_TABLE = "timer"; static final String ID = "id"; static final String ENABLED = "enabled"; static final String START = "start"; static final String PERIOD_HOURS = "period_hours"; static final String PERIOD_MINUTES = "period_minutes"; static final String MESSAGE = "message"; static final String ALARM = "alarm"; private static final String TIMER_TABLE_CREATE = "CREATE TABLE " + TIMER_TABLE + " (" + ID + " INTEGER PRIMARY KEY, " + ENABLED + " BOOLEAN, " + START + " DATETIME, " + PERIOD_HOURS + " INTEGER, " + PERIOD_MINUTES + " INTEGER, " + MESSAGE + " TEXT, " + ALARM + " TEXT" + ");"; TimerDbOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(TIMER_TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //we have only one (first) version of our database //nothing to do here } }
0911aihara-bells
src/ru/gelin/android/bells/TimerDbOpenHelper.java
Java
gpl2
1,526
package ru.gelin.android.bells; import static ru.gelin.android.bells.Utils.isTomorrow; import java.util.ArrayList; import java.util.Date; import java.util.List; import ru.gelin.android.bells.timers.Timer; import android.content.Context; import android.content.res.Resources; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import android.widget.CompoundButton.OnCheckedChangeListener; /** * Adapter for collection of timers. */ public class TimersListAdapter extends BaseAdapter { /** Application context */ Context context; /** Collection of timers */ TimerStorage timers; /** List of timers (to map positions and IDs) */ List<Timer> timersList = new ArrayList<Timer>(); /** Current time (when the activity starts) */ Date now; public TimersListAdapter(Context context, TimerStorage timers, Date now) { this.context = context; this.timers = timers; this.now = now; timersList = timers.select(now); } @Override public int getCount() { return timers.size(); } @Override public Object getItem(int position) { return timersList.get(position); } @Override public long getItemId(int position) { return timersList.get(position).getId(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = LayoutInflater.from(context).inflate( R.layout.timers_list_item, parent, false); } final Timer timer = timersList.get(position); Resources resources = context.getResources(); TextView timerName = (TextView)view.findViewById(R.id.timer_name); timerName.setText(getTimerName(resources, timer)); TextView timerPeriod = (TextView)view.findViewById(R.id.timer_period); timerPeriod.setText(resources.getString( R.string.list_timer_period, timer.getPeriod().getHours(), timer.getPeriod().getMinutes())); TextView timerAlarm = (TextView)view.findViewById(R.id.timer_alarm); Date alarmTime = timer.getAlarmTime(now); timerAlarm.setText(resources.getString( isTomorrow(now, alarmTime) ? R.string.timer_alarm_time_tomorrow : R.string.timer_alarm_time, alarmTime)); CheckBox enabledCheckBox = (CheckBox)view.findViewById(R.id.timer_enabled); enabledCheckBox.setChecked(timer.isEnabled()); enabledCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { enableTimer(timer, isChecked); } }); return view; } /** * Makes timer name. It is the message if the message is set, * or the period and next start time if the message is not set. */ String getTimerName(Resources resources, Timer timer) { String name = timer.getMessage(); if (name == null || "".equals(name)) { name = resources.getString( R.string.list_default_timer_name, timer.getPeriod().getHours(), timer.getPeriod().getMinutes(), timer.getStartTime()); } return name; } void enableTimer(Timer timer, boolean isChecked) { timer.setEnabled(isChecked); timers.update(timer); timers.save(); } @Override public boolean hasStableIds() { return true; } }
0911aihara-bells
src/ru/gelin/android/bells/TimersListAdapter.java
Java
gpl2
3,838
package ru.gelin.android.bells; import ru.gelin.android.bells.timers.Timer; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TimePicker; /** * Activity to add a timer. */ public class AddTimerActivity extends SaveTimerActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); TimePicker period = (TimePicker)findViewById(R.id.timer_period); period.setIs24HourView(true); period.setCurrentHour(0); period.setCurrentMinute(30); View nowButton = findViewById(R.id.timer_start_now); nowButton.setVisibility(View.GONE); final Button button = (Button)findViewById(R.id.submit_button); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { addTimer(); } }); } void addTimer() { Timer timer = new Timer(); saveTimer(timer); } }
0911aihara-bells
src/ru/gelin/android/bells/AddTimerActivity.java
Java
gpl2
1,092
package ru.gelin.android.bells; import static ru.gelin.android.bells.Utils.isTomorrow; import java.util.Calendar; import java.util.Date; import ru.gelin.android.bells.timers.Timer; import android.database.Cursor; import android.media.AudioManager; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.CheckBox; import android.widget.SimpleCursorAdapter; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; import android.widget.TimePicker; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.TimePicker.OnTimeChangedListener; public class SaveTimerActivity extends NowActivity implements Constants { /** Key in the instance state bundle to save selected ringtone */ static final String SELECTED_RINGTONE_KEY = "selectedRingtone"; /** Key in the instance state bundle to save initial timer start time */ static final String INITIAL_START_KEY = "initialStart"; /** Storage of the timers */ protected TimerStorage timers; /** Ringtone manager */ protected RingtoneManager ringtoneManager; /** Previously selected alarm ringtone */ protected int selectedRingtone = 0; //first in the list /** Original start time of the edited timer */ protected Date initialStart; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { initialStart = now; } else { initialStart = new Date( savedInstanceState.getLong(INITIAL_START_KEY, System.currentTimeMillis())); } setContentView(R.layout.timer); timers = TimerStorage.getInstance(this); TimePicker start = (TimePicker)findViewById(R.id.timer_start); start.setIs24HourView(true); start.setOnTimeChangedListener(new OnTimeChangedListener() { public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { updateAlarmTime(); } }); TimePicker period = (TimePicker)findViewById(R.id.timer_period); period.setIs24HourView(true); period.setOnTimeChangedListener(new OnTimeChangedListener() { public void onTimeChanged(TimePicker view, int hourOfDay, int minute) { updateAlarmTime(); } }); Spinner alarm = (Spinner)findViewById(R.id.timer_alarm); ringtoneManager = new RingtoneManager(this); ringtoneManager.setType(RingtoneManager.TYPE_ALARM); ringtoneManager.setStopPreviousRingtone(true); Cursor cursor = ringtoneManager.getCursor(); //DatabaseUtils.dumpCursor(cursor); SpinnerAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_spinner_item, cursor, new String[] {cursor.getColumnName(RingtoneManager.TITLE_COLUMN_INDEX)}, new int[] {android.R.id.text1}); alarm.setAdapter(adapter); setVolumeControlStream(AudioManager.STREAM_ALARM); } @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); if (savedInstanceState != null) { selectedRingtone = savedInstanceState.getInt(SELECTED_RINGTONE_KEY, selectedRingtone); } Spinner alarm = (Spinner)findViewById(R.id.timer_alarm); alarm.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { if (position != selectedRingtone) { //another ringtone is selected ringtoneManager.getRingtone(position).play(); } selectedRingtone = position; } @Override public void onNothingSelected(AdapterView<?> parent) { //nothing to do } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(SELECTED_RINGTONE_KEY, selectedRingtone); outState.putLong(INITIAL_START_KEY, initialStart.getTime()); } @Override public void onPause() { super.onPause(); ringtoneManager.stopPreviousRingtone(); } /** * Converts entered hour and minute to date. * Tries to avoid this situation: * current time is 23:50, entered time is 00:10. * The date should always be in the future * (relative to the startTime of the timer during the activity creation). */ protected Date toDate(int hour, int minute) { Calendar calendar = Calendar.getInstance(); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minute); Date timer = calendar.getTime(); Date boundary = initialStart.before(now) ? initialStart : now; if (timer.before(boundary)) { calendar.add(Calendar.DAY_OF_MONTH, 1); return calendar.getTime(); } else { return timer; } } protected void updateAlarmTime() { Timer timer = new Timer(); TimePicker start = (TimePicker)findViewById(R.id.timer_start); TimePicker period = (TimePicker)findViewById(R.id.timer_period); timer.setStartTime(toDate(start.getCurrentHour(), start.getCurrentMinute())); timer.setPeriod(period.getCurrentHour(), period.getCurrentMinute()); timer.normalize(now); TextView nextStart = (TextView)findViewById(R.id.timer_next_start); Date alarmTime = timer.getAlarmTime(now); nextStart.setText(getResources().getString( isTomorrow(now, alarmTime) ? R.string.timer_alarm_time_tomorrow : R.string.timer_alarm_time, alarmTime)); } protected void saveTimer(Timer timer) { CheckBox enabled = (CheckBox)findViewById(R.id.timer_enabled); timer.setEnabled(enabled.isChecked()); TimePicker start = (TimePicker)findViewById(R.id.timer_start); timer.setStartTime(toDate(start.getCurrentHour(), start.getCurrentMinute())); TimePicker period = (TimePicker)findViewById(R.id.timer_period); timer.setPeriod(period.getCurrentHour(), period.getCurrentMinute()); TextView message = (TextView)findViewById(R.id.timer_message); timer.setMessage(String.valueOf(message.getText())); Spinner alarm = (Spinner)findViewById(R.id.timer_alarm); Uri ringtoneUri = ringtoneManager.getRingtoneUri(alarm.getSelectedItemPosition()); Log.d(TAG, "alarm sound: " + ringtoneUri); timer.setAlarm(String.valueOf(ringtoneUri)); timer.normalize(now); if (timer.getId() == 0) { timers.insert(timer); } else { timers.update(timer); } timers.save(); finish(); } }
0911aihara-bells
src/ru/gelin/android/bells/SaveTimerActivity.java
Java
gpl2
7,330
package ru.gelin.android.bells; import java.util.Calendar; import java.util.Date; import ru.gelin.android.bells.timers.Timer; /** * Static utility methods. */ public class Utils { /** * Returns true if the specified date is tomorrow date (or after tomorrow...). * @param now current time * @param date time to check */ public static boolean isTomorrow(Date now, Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(Timer.normalizeDate(now)); calendar.add(Calendar.DAY_OF_MONTH, 1); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); return !Timer.normalizeDate(date).before(calendar.getTime()); } }
0911aihara-bells
src/ru/gelin/android/bells/Utils.java
Java
gpl2
746
package ru.gelin.android.bells; import static ru.gelin.android.bells.Utils.isTomorrow; import java.util.ArrayList; import java.util.Date; import java.util.List; import ru.gelin.android.bells.timers.Timer; import android.content.Context; import android.content.res.Resources; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; /** * Adapter for collection of alarms (timers). */ public class AlarmsListAdapter extends BaseAdapter { /** Application context */ Context context; /** List of timers (to map positions and IDs) */ List<Timer> alarms = new ArrayList<Timer>(); /** Current time (when Alarm activity is displayed) */ Date now; public AlarmsListAdapter(Context context, List<Timer> alarms, Date now) { this.context = context; this.alarms = alarms; this.now = now; //for (Timer alarm : this.alarms) { // alarm.normalize(now); //to show next alarm time //} } @Override public int getCount() { return alarms.size(); } @Override public Object getItem(int position) { return alarms.get(position); } @Override public long getItemId(int position) { return alarms.get(position).getId(); } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = convertView; if (view == null) { view = LayoutInflater.from(context).inflate( R.layout.alarms_list_item, parent, false); } final Timer timer = alarms.get(position); Resources resources = context.getResources(); TextView timerName = (TextView)view.findViewById(R.id.timer_name); timerName.setText(getTimerName(resources, timer)); TextView timerAlarm = (TextView)view.findViewById(R.id.timer_alarm); Date alarmTime = timer.getAlarmTime(now); timerAlarm.setText(resources.getString( isTomorrow(now, alarmTime) ? R.string.list_timer_next_alarm_tomorrow : R.string.list_timer_next_alarm, alarmTime)); return view; } /** * Makes timer name. It is the message if the message is set, * or the period and next start time if the message is not set. */ String getTimerName(Resources resources, Timer timer) { String name = timer.getMessage(); if (name == null || "".equals(name)) { name = resources.getString( R.string.list_default_timer_name, timer.getPeriod().getHours(), timer.getPeriod().getMinutes(), timer.getStartTime()); } return name; } @Override public boolean hasStableIds() { return true; } }
0911aihara-bells
src/ru/gelin/android/bells/AlarmsListAdapter.java
Java
gpl2
2,929
package ru.gelin.android.bells; public interface Constants { /** Tag for logs */ String TAG = "ru.gelin.android.bells"; /** Scheme for URIs referencing to timers */ String TIMER_SCHEME = "timer"; }
0911aihara-bells
src/ru/gelin/android/bells/Constants.java
Java
gpl2
226
package ru.gelin.android.bells; import java.util.ArrayList; import java.util.List; import ru.gelin.android.bells.timers.Timer; import android.content.Context; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.util.Log; /** * The list of ringtones to be played on alarm. * It is populated from the list of alarmed timers. The set of different * alarm ringtones is created. The first ringtone is started by {@link #playNext()} * method call. * The next ringtone is tried to start by {@link #playNext()} call. If the * previous ringtone is playing, nothing is happened. If the previous ringtone * is stopped, the next ringtone is started. * After the last, the first ringtone will be played again. */ public class RingtoneList implements Constants { /** Set of ringtone URIs */ List<Uri> ringtones = new ArrayList<Uri>(); /** Current application context */ Context context; /** Ringtone manager to play a ringtone */ RingtoneManager ringtoneManager; /** Current playing ringtone */ Ringtone ringtone; /** Next ringtone index */ int nextRingtone = 0; /** * Constructs the list * @param context to get ringtone manager * @param list of alarmed timers */ public RingtoneList(Context context, List<Timer> timers) { this.context = context; ringtoneManager = new RingtoneManager(context); ringtoneManager.setType(RingtoneManager.TYPE_ALARM); //ringtoneManager.setStopPreviousRingtone(true); for (Timer timer : timers) { String alarm = timer.getAlarm(); if (!ringtones.contains(alarm)) { try { ringtones.add(Uri.parse(alarm)); } catch (Exception e) { Log.w(TAG, "invalid alarm: " + alarm); } } } if (ringtones.size() == 0) { ringtones.add(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)); } } /** * Starts playing of the next (or the first) ringtone. */ public void playNext() { if (ringtone == null || !ringtone.isPlaying()) { ringtone = getNextRingtone(); ringtone.play(); } } /** * Stops playing of the currect ringtone. */ public void stop() { if (ringtone != null && ringtone.isPlaying()) { ringtone.stop(); } } /** * Returns the next ringtone. */ Ringtone getNextRingtone() { Uri uri = ringtones.get(nextRingtone); int position = ringtoneManager.getRingtonePosition(uri); if (position < 0) { position = 0; } Ringtone ringtone = ringtoneManager.getRingtone(position); Log.d(TAG, "playing " + uri + " - " + ringtone.getTitle(context)); nextRingtone++; if (nextRingtone >= ringtones.size()) { nextRingtone = 0; } return ringtone; } }
0911aihara-bells
src/ru/gelin/android/bells/RingtoneList.java
Java
gpl2
3,086
package ru.gelin.android.bells; import java.util.Calendar; import ru.gelin.android.bells.timers.Timer; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; /** * Activity to edit the timer. */ public class EditTimerActivity extends SaveTimerActivity implements Constants { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Uri uri = intent.getData(); Log.d(TAG, "editing " + uri); final Timer timer = timers.select( Integer.parseInt(uri.getSchemeSpecificPart())); if (savedInstanceState == null) { initialStart = timer.getStartTime(); } loadTimer(timer); final Button nowButton = (Button)findViewById(R.id.timer_start_now); nowButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { setStartNow(); } }); final Button submitButton = (Button)findViewById(R.id.submit_button); submitButton.setText(R.string.button_save); submitButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { saveTimer(timer); } }); } void loadTimer(Timer timer) { CheckBox enabled = (CheckBox)findViewById(R.id.timer_enabled); enabled.setChecked(timer.isEnabled()); TimePicker start = (TimePicker)findViewById(R.id.timer_start); Calendar calendar = Calendar.getInstance(); calendar.setTime(timer.getStartTime()); start.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY)); start.setCurrentMinute(calendar.get(Calendar.MINUTE)); TimePicker period = (TimePicker)findViewById(R.id.timer_period); period.setCurrentHour(timer.getPeriod().getHours()); period.setCurrentMinute(timer.getPeriod().getMinutes()); TextView message = (TextView)findViewById(R.id.timer_message); message.setText(timer.getMessage()); Spinner alarm = (Spinner)findViewById(R.id.timer_alarm); Uri ringtoneUri = Uri.parse(timer.getAlarm()); int ringtonePosition = ringtoneManager.getRingtonePosition(ringtoneUri); if (ringtonePosition >= 0) { selectedRingtone = ringtonePosition; alarm.setSelection(ringtonePosition, false); } } void setStartNow() { Calendar now = Calendar.getInstance(); TimePicker start = (TimePicker)findViewById(R.id.timer_start); start.setCurrentHour(now.get(Calendar.HOUR_OF_DAY)); start.setCurrentMinute(now.get(Calendar.MINUTE)); } }
0911aihara-bells
src/ru/gelin/android/bells/EditTimerActivity.java
Java
gpl2
3,029
package ru.gelin.android.bells; import static ru.gelin.android.bells.TimerDbOpenHelper.*; import java.util.Date; import java.util.HashMap; import java.util.Map; import ru.gelin.android.bells.timers.Timer; import ru.gelin.android.bells.timers.TimerCollection; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class TimerStorage extends TimerCollection implements Constants { /** Name of the preferences */ static final String PREFERENCES_NAME = "TimerStorage"; /** "enabled" property suffix */ static final String ENABLED_SUFFIX = "_enabled"; /** "start" property suffix */ static final String START_SUFFIX = "_start"; /** "period hours" property suffix */ static final String PERIOD_HOURS_SUFFIX = "_period_hours"; /** "period minutes" property suffix */ static final String PERIOD_MINUTES_SUFFIX = "_period_minutes"; /** "message" property suffix */ static final String MESSAGE_SUFFIX = "_message"; /** "alarm" property suffix */ static final String ALARM_SUFFIX = "_alarm"; /** Storage instance */ static TimerStorage instance; /** Context which uses this storage */ Context context; /** Preferences which saves the timers */ SharedPreferences preferences; /** Database open helper */ SQLiteOpenHelper dbHelper; /** * Private constructor. */ private TimerStorage(Context context) { this.context = context; preferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE); dbHelper = new TimerDbOpenHelper(context); } public static TimerStorage getInstance(Context context) { if (instance == null) { instance = new TimerStorage(context); } return instance; } public void load() { delete(); loadFromPreferences(); //backward compatibility SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); SQLiteDatabase db = dbHelper.getReadableDatabase(); Cursor cursor = db.query(TIMER_TABLE, new String[] {ENABLED, START, PERIOD_HOURS, PERIOD_MINUTES, MESSAGE, ALARM}, null, null, null, null, null); int enabledIndex = cursor.getColumnIndex(ENABLED); int startIndex = cursor.getColumnIndex(START); int periodHoursIndex = cursor.getColumnIndex(PERIOD_HOURS); int periodMinutesIndex = cursor.getColumnIndex(PERIOD_MINUTES); int messageIndex = cursor.getColumnIndex(MESSAGE); int alarmIndex = cursor.getColumnIndex(ALARM); if (cursor.moveToFirst()) { do { Timer timer = new Timer(); timer.setEnabled(cursor.getInt(enabledIndex) != 0); timer.setStartTime(new Date(cursor.getLong(startIndex))); timer.setPeriod(cursor.getInt(periodHoursIndex), cursor.getInt(periodMinutesIndex)); timer.setMessage(cursor.getString(messageIndex)); timer.setAlarm(cursor.getString(alarmIndex)); insert(timer); } while (cursor.moveToNext()); } cursor.close(); db.close(); } /** * Saves timers to the persistent storage. */ public void save() { SQLiteDatabase db = dbHelper.getWritableDatabase(); db.beginTransaction(); try { db.delete(TIMER_TABLE, null, null); for (Timer timer : internalList()) { ContentValues values = new ContentValues(); values.put(ID, timer.getId()); values.put(ENABLED, timer.isEnabled()); values.put(START, timer.getStartTime().getTime()); values.put(PERIOD_HOURS, timer.getPeriod().getHours()); values.put(PERIOD_MINUTES, timer.getPeriod().getMinutes()); values.put(MESSAGE, timer.getMessage()); values.put(ALARM, timer.getAlarm()); db.insert(TIMER_TABLE, null, values); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } db.close(); } /** * Schedulers next alarm using AlarmManager. * On alarm AlarmActivity will start. * @param now current time */ public void scheduleAlarm(Date now) { Intent intent = new Intent(context, AlarmActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0); AlarmManager alarmManager = (AlarmManager)context.getSystemService( Context.ALARM_SERVICE); Date nextAlarm = alarmTime(now); if (nextAlarm == null) { Log.i(TAG, "cancelling alarm scheduler"); alarmManager.cancel(pendingIntent); return; } Log.i(TAG, "scheduling alarm on " + nextAlarm); alarmManager.set(AlarmManager.RTC_WAKEUP, nextAlarm.getTime(), pendingIntent); } /** * Schedulers next alarm relative the the current time. */ public void scheduleAlarm() { scheduleAlarm(new Date()); } /** * Loads timers from the persistent storage. */ void loadFromPreferences() { Map<String, ?> values = preferences.getAll(); Map<Integer, Timer> result = new HashMap<Integer, Timer>(); for (Map.Entry<String, ?> entry : values.entrySet()) { String key = entry.getKey(); int id; try { id = Integer.parseInt(key.substring(0, key.indexOf('_'))); } catch (Exception e) { Log.w(TAG, "invalid preferences key: " + key); continue; } Timer timer = result.get(id); if (timer == null) { timer = new Timer(); result.put(id, timer); } try { if (key.endsWith(ENABLED_SUFFIX)) { timer.setEnabled((Boolean)entry.getValue()); } else if (key.endsWith(START_SUFFIX)) { timer.setStartTime(new Date((Long)entry.getValue())); } else if (key.endsWith(PERIOD_HOURS_SUFFIX)) { timer.setPeriod((Integer)entry.getValue(), timer.getPeriod().getMinutes()); } else if (key.endsWith(PERIOD_MINUTES_SUFFIX)) { timer.setPeriod(timer.getPeriod().getHours(), (Integer)entry.getValue()); } else if (key.endsWith(MESSAGE_SUFFIX)) { timer.setMessage((String)entry.getValue()); } else if (key.endsWith(ALARM_SUFFIX)) { timer.setAlarm((String)entry.getValue()); } } catch (Exception e) { Log.w(TAG, "invalid preferences value: " + key + " = " + entry.getValue()); result.remove(id); } } //delete(); for (Timer timer : result.values()) { insert(timer); } } }
0911aihara-bells
src/ru/gelin/android/bells/TimerStorage.java
Java
gpl2
7,547
package ru.gelin.android.bells; import java.util.List; import ru.gelin.android.bells.timers.Timer; import android.content.Intent; import android.media.AudioManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; public class AlarmActivity extends NowActivity implements Constants { /** Time (in millis) to show this activity */ static final long SHOW_TIME = 55000; //55 seconds //static final long SHOW_TIME = 10000; //10 seconds /** Period (in millis) to check ringtone */ static final int RINGTONE_TIME = 5000; //5 seconds /** What property of a message to a ring handler */ static final int RING_WHAT = 0; /** Storage of the timers */ TimerStorage timers; /** Ringtones to play */ RingtoneList ringtones; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.alarm); timers = TimerStorage.getInstance(this); Button ok = (Button)findViewById(R.id.ok_button); ok.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); setVolumeControlStream(AudioManager.STREAM_ALARM); if (savedInstanceState == null) { //first start if (isPlaying() && loadAlarms()) { ringtones.playNext(); ringHandler.sendEmptyMessageDelayed(RING_WHAT, RINGTONE_TIME); } else { finish(); //immediately close activity Intent intent = new Intent(this, TimersListActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); //open timers list } } else { //restart loadAlarms(); } TextView time = (TextView)findViewById(R.id.alarm_time); time.setText(getResources().getString(R.string.alarm_time, now)); } @Override public void onStop() { super.onStop(); if (ringtones != null) { ringtones.stop(); } } /** * Finished the activity. Updates timer's list to the next alarm. */ @Override public void finish() { super.finish(); ringHandler.removeMessages(RING_WHAT); timers.normalize(now); timers.scheduleAlarm(now); timers.save(); } /** * Loads list of alarms. * @return false if there is no alarms */ boolean loadAlarms() { timers.load(); List<Timer> alarms = timers.selectAlarms(now); if (alarms.size() == 0) { return false; } ListView list = (ListView)findViewById(R.id.alarms_list); ListAdapter adapter = new AlarmsListAdapter(this, alarms, now); list.setAdapter(adapter); ringtones = new RingtoneList(this, alarms); return true; } /** * Returns true if we should still play alarm and display timers descriptions. * Returns false if we should not, i.e. 50 seconds came from the * start of the activity. */ boolean isPlaying() { return now != null && System.currentTimeMillis() <= now.getTime() + SHOW_TIME; } /** * Handles ringtone playing. Restarts ringtone if it stops. */ final Handler ringHandler = new Handler() { public void handleMessage(Message msg) { ringtones.playNext(); if (isPlaying()) { ringHandler.sendEmptyMessageDelayed(RING_WHAT, RINGTONE_TIME); } else { finish(); } }; }; }
0911aihara-bells
src/ru/gelin/android/bells/AlarmActivity.java
Java
gpl2
4,082
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.vending.billing; import android.os.Bundle; /** * InAppBillingService is the service that provides in-app billing version 3 and beyond. * This service provides the following features: * 1. Provides a new API to get details of in-app items published for the app including * price, type, title and description. * 2. The purchase flow is synchronous and purchase information is available immediately * after it completes. * 3. Purchase information of in-app purchases is maintained within the Google Play system * till the purchase is consumed. * 4. An API to consume a purchase of an inapp item. All purchases of one-time * in-app items are consumable and thereafter can be purchased again. * 5. An API to get current purchases of the user immediately. This will not contain any * consumed purchases. * * All calls will give a response code with the following possible values * RESULT_OK = 0 - success * RESULT_USER_CANCELED = 1 - user pressed back or canceled a dialog * RESULT_BILLING_UNAVAILABLE = 3 - this billing API version is not supported for the type requested * RESULT_ITEM_UNAVAILABLE = 4 - requested SKU is not available for purchase * RESULT_DEVELOPER_ERROR = 5 - invalid arguments provided to the API * RESULT_ERROR = 6 - Fatal error during the API action * RESULT_ITEM_ALREADY_OWNED = 7 - Failure to purchase since item is already owned * RESULT_ITEM_NOT_OWNED = 8 - Failure to consume since item is not owned */ interface IInAppBillingService { /** * Checks support for the requested billing API version, package and in-app type. * Minimum API version supported by this interface is 3. * @param apiVersion the billing version which the app is using * @param packageName the package name of the calling app * @param type type of the in-app item being purchased "inapp" for one-time purchases * and "subs" for subscription. * @return RESULT_OK(0) on success, corresponding result code on failures */ int isBillingSupported(int apiVersion, String packageName, String type); /** * Provides details of a list of SKUs * Given a list of SKUs of a valid type in the skusBundle, this returns a bundle * with a list JSON strings containing the productId, price, title and description. * This API can be called with a maximum of 20 SKUs. * @param apiVersion billing API version that the Third-party is using * @param packageName the package name of the calling app * @param skusBundle bundle containing a StringArrayList of SKUs with key "ITEM_ID_LIST" * @return Bundle containing the following key-value pairs * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on * failure as listed above. * "DETAILS_LIST" with a StringArrayList containing purchase information * in JSON format similar to: * '{ "productId" : "exampleSku", "type" : "inapp", "price" : "$5.00", * "title : "Example Title", "description" : "This is an example description" }' */ Bundle getSkuDetails(int apiVersion, String packageName, String type, in Bundle skusBundle); /** * Returns a pending intent to launch the purchase flow for an in-app item by providing a SKU, * the type, a unique purchase token and an optional developer payload. * @param apiVersion billing API version that the app is using * @param packageName package name of the calling app * @param sku the SKU of the in-app item as published in the developer console * @param type the type of the in-app item ("inapp" for one-time purchases * and "subs" for subscription). * @param developerPayload optional argument to be sent back with the purchase information * @return Bundle containing the following key-value pairs * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on * failure as listed above. * "BUY_INTENT" - PendingIntent to start the purchase flow * * The Pending intent should be launched with startIntentSenderForResult. When purchase flow * has completed, the onActivityResult() will give a resultCode of OK or CANCELED. * If the purchase is successful, the result data will contain the following key-value pairs * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on * failure as listed above. * "INAPP_PURCHASE_DATA" - String in JSON format similar to * '{"orderId":"12999763169054705758.1371079406387615", * "packageName":"com.example.app", * "productId":"exampleSku", * "purchaseTime":1345678900000, * "purchaseToken" : "122333444455555", * "developerPayload":"example developer payload" }' * "INAPP_DATA_SIGNATURE" - String containing the signature of the purchase data that * was signed with the private key of the developer * TODO: change this to app-specific keys. */ Bundle getBuyIntent(int apiVersion, String packageName, String sku, String type, String developerPayload); /** * Returns the current SKUs owned by the user of the type and package name specified along with * purchase information and a signature of the data to be validated. * This will return all SKUs that have been purchased in V3 and managed items purchased using * V1 and V2 that have not been consumed. * @param apiVersion billing API version that the app is using * @param packageName package name of the calling app * @param type the type of the in-app items being requested * ("inapp" for one-time purchases and "subs" for subscription). * @param continuationToken to be set as null for the first call, if the number of owned * skus are too many, a continuationToken is returned in the response bundle. * This method can be called again with the continuation token to get the next set of * owned skus. * @return Bundle containing the following key-value pairs * "RESPONSE_CODE" with int value, RESULT_OK(0) if success, other response codes on * failure as listed above. * "INAPP_PURCHASE_ITEM_LIST" - StringArrayList containing the list of SKUs * "INAPP_PURCHASE_DATA_LIST" - StringArrayList containing the purchase information * "INAPP_DATA_SIGNATURE_LIST"- StringArrayList containing the signatures * of the purchase information * "INAPP_CONTINUATION_TOKEN" - String containing a continuation token for the * next set of in-app purchases. Only set if the * user has more owned skus than the current list. */ Bundle getPurchases(int apiVersion, String packageName, String type, String continuationToken); /** * Consume the last purchase of the given SKU. This will result in this item being removed * from all subsequent responses to getPurchases() and allow re-purchase of this item. * @param apiVersion billing API version that the app is using * @param packageName package name of the calling app * @param purchaseToken token in the purchase information JSON that identifies the purchase * to be consumed * @return 0 if consumption succeeded. Appropriate error values for failures. */ int consumePurchase(int apiVersion, String packageName, String purchaseToken); }
0vishalvijay0-v4
v3/src/com/android/vending/billing/IInAppBillingService.aidl
AIDL
asf20
8,443
/* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trivialdrivesample.util; /** * Represents the result of an in-app billing operation. * A result is composed of a response code (an integer) and possibly a * message (String). You can get those by calling * {@link #getResponse} and {@link #getMessage()}, respectively. You * can also inquire whether a result is a success or a failure by * calling {@link #isSuccess()} and {@link #isFailure()}. */ public class IabResult { int mResponse; String mMessage; public IabResult(int response, String message) { mResponse = response; if (message == null || message.trim().length() == 0) { mMessage = IabHelper.getResponseDesc(response); } else { mMessage = message + " (response: " + IabHelper.getResponseDesc(response) + ")"; } } public int getResponse() { return mResponse; } public String getMessage() { return mMessage; } public boolean isSuccess() { return mResponse == IabHelper.BILLING_RESPONSE_RESULT_OK; } public boolean isFailure() { return !isSuccess(); } public String toString() { return "IabResult: " + getMessage(); } }
0vishalvijay0-v4
v3/src/com/example/android/trivialdrivesample/util/IabResult.java
Java
asf20
1,761
/* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trivialdrivesample.util; import org.json.JSONException; import org.json.JSONObject; /** * Represents an in-app product's listing details. */ public class SkuDetails { String mItemType; String mSku; String mType; String mPrice; String mTitle; String mDescription; String mJson; public SkuDetails(String jsonSkuDetails) throws JSONException { this(IabHelper.ITEM_TYPE_INAPP, jsonSkuDetails); } public SkuDetails(String itemType, String jsonSkuDetails) throws JSONException { mItemType = itemType; mJson = jsonSkuDetails; JSONObject o = new JSONObject(mJson); mSku = o.optString("productId"); mType = o.optString("type"); mPrice = o.optString("price"); mTitle = o.optString("title"); mDescription = o.optString("description"); } public String getSku() { return mSku; } public String getType() { return mType; } public String getPrice() { return mPrice; } public String getTitle() { return mTitle; } public String getDescription() { return mDescription; } @Override public String toString() { return "SkuDetails:" + mJson; } }
0vishalvijay0-v4
v3/src/com/example/android/trivialdrivesample/util/SkuDetails.java
Java
asf20
1,812
/* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trivialdrivesample.util; /** * Exception thrown when something went wrong with in-app billing. * An IabException has an associated IabResult (an error). * To get the IAB result that caused this exception to be thrown, * call {@link #getResult()}. */ public class IabException extends Exception { IabResult mResult; public IabException(IabResult r) { this(r, null); } public IabException(int response, String message) { this(new IabResult(response, message)); } public IabException(IabResult r, Exception cause) { super(r.getMessage(), cause); mResult = r; } public IabException(int response, String message, Exception cause) { this(new IabResult(response, message), cause); } /** Returns the IAB result (error) that this exception signals. */ public IabResult getResult() { return mResult; } }
0vishalvijay0-v4
v3/src/com/example/android/trivialdrivesample/util/IabException.java
Java
asf20
1,510
// Copyright 2002, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.android.trivialdrivesample.util; /** * Exception thrown when encountering an invalid Base64 input character. * * @author nelson */ public class Base64DecoderException extends Exception { public Base64DecoderException() { super(); } public Base64DecoderException(String s) { super(s); } private static final long serialVersionUID = 1L; }
0vishalvijay0-v4
v3/src/com/example/android/trivialdrivesample/util/Base64DecoderException.java
Java
asf20
991
/* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trivialdrivesample.util; import org.json.JSONException; import org.json.JSONObject; /** * Represents an in-app billing purchase. */ public class Purchase { String mItemType; // ITEM_TYPE_INAPP or ITEM_TYPE_SUBS String mOrderId; String mPackageName; String mSku; long mPurchaseTime; int mPurchaseState; String mDeveloperPayload; String mToken; String mOriginalJson; String mSignature; public Purchase(String itemType, String jsonPurchaseInfo, String signature) throws JSONException { mItemType = itemType; mOriginalJson = jsonPurchaseInfo; JSONObject o = new JSONObject(mOriginalJson); mOrderId = o.optString("orderId"); mPackageName = o.optString("packageName"); mSku = o.optString("productId"); mPurchaseTime = o.optLong("purchaseTime"); mPurchaseState = o.optInt("purchaseState"); mDeveloperPayload = o.optString("developerPayload"); mToken = o.optString("token", o.optString("purchaseToken")); mSignature = signature; } public String getItemType() { return mItemType; } public String getOrderId() { return mOrderId; } public String getPackageName() { return mPackageName; } public String getSku() { return mSku; } public long getPurchaseTime() { return mPurchaseTime; } public int getPurchaseState() { return mPurchaseState; } public String getDeveloperPayload() { return mDeveloperPayload; } public String getToken() { return mToken; } public String getOriginalJson() { return mOriginalJson; } public String getSignature() { return mSignature; } @Override public String toString() { return "PurchaseInfo(type:" + mItemType + "):" + mOriginalJson; } }
0vishalvijay0-v4
v3/src/com/example/android/trivialdrivesample/util/Purchase.java
Java
asf20
2,372
// Portions copyright 2002, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.android.trivialdrivesample.util; // This code was converted from code at http://iharder.sourceforge.net/base64/ // Lots of extraneous features were removed. /* The original code said: * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit * <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rharder@usa.net * @version 1.3 */ /** * Base64 converter class. This code is not a complete MIME encoder; * it simply converts binary data to base64 data and back. * * <p>Note {@link CharBase64} is a GWT-compatible implementation of this * class. */ public class Base64 { /** Specify encoding (value is {@code true}). */ public final static boolean ENCODE = true; /** Specify decoding (value is {@code false}). */ public final static boolean DECODE = false; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte) '\n'; /** * The 64 valid Base64 values. */ private final static byte[] ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'}; /** * The 64 valid web safe Base64 values. */ private final static byte[] WEBSAFE_ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'}; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; /** The web safe decodabet */ private final static byte[] WEBSAFE_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44 62, // Dash '-' sign at decimal 45 -9, -9, // Decimal 46-47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, // Decimal 91-94 63, // Underscore '_' at decimal 95 -9, // Decimal 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // Indicates white space in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates equals sign in encoding private final static byte EQUALS_SIGN_ENC = -1; /** Defeats instantiation. */ private Base64() { } /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param alphabet is the encoding alphabet * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index alphabet // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = alphabet[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Encodes a byte array into Base64 notation. * Equivalent to calling * {@code encodeBytes(source, 0, source.length)} * * @param source The data to convert * @since 1.4 */ public static String encode(byte[] source) { return encode(source, 0, source.length, ALPHABET, true); } /** * Encodes a byte array into web safe Base64 notation. * * @param source The data to convert * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries */ public static String encodeWebSafe(byte[] source, boolean doPadding) { return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet the encoding alphabet * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries * @since 1.4 */ public static String encode(byte[] source, int off, int len, byte[] alphabet, boolean doPadding) { byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE); int outLen = outBuff.length; // If doPadding is false, set length to truncate '=' // padding characters while (doPadding == false && outLen > 0) { if (outBuff[outLen - 1] != '=') { break; } outLen -= 1; } return new String(outBuff, 0, outLen); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet is the encoding alphabet * @param maxLineLength maximum length of one line. * @return the BASE64-encoded byte array */ public static byte[] encode(byte[] source, int off, int len, byte[] alphabet, int maxLineLength) { int lenDiv3 = (len + 2) / 3; // ceil(len / 3) int len43 = lenDiv3 * 4; byte[] outBuff = new byte[len43 // Main 4:3 + (len43 / maxLineLength)]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d += 3, e += 4) { // The following block of code is the same as // encode3to4( source, d + off, 3, outBuff, e, alphabet ); // but inlined for faster encoding (~20% improvement) int inBuff = ((source[d + off] << 24) >>> 8) | ((source[d + 1 + off] << 24) >>> 16) | ((source[d + 2 + off] << 24) >>> 24); outBuff[e] = alphabet[(inBuff >>> 18)]; outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f]; outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f]; outBuff[e + 3] = alphabet[(inBuff) & 0x3f]; lineLength += 4; if (lineLength == maxLineLength) { outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // end for: each piece of array if (d < len) { encode3to4(source, d + off, len - d, outBuff, e, alphabet); lineLength += 4; if (lineLength == maxLineLength) { // Add a last newline outBuff[e + 4] = NEW_LINE; e++; } e += 4; } assert (e == outBuff.length); return outBuff; } /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param decodabet the decodabet for decoding Base64 content * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, byte[] decodabet) { // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12); destination[destOffset] = (byte) (outBuff >>> 16); return 1; } else if (source[srcOffset + 3] == EQUALS_SIGN) { // Example: DkL= int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18); destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } else { // Example: DkLE int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18) | ((decodabet[source[srcOffset + 3]] << 24) >>> 24); destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) (outBuff); return 3; } } // end decodeToBytes /** * Decodes data from Base64 notation. * * @param s the string to decode (decoded in default encoding) * @return the decoded data * @since 1.4 */ public static byte[] decode(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decode(bytes, 0, bytes.length); } /** * Decodes data from web safe Base64 notation. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param s the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decodeWebSafe(bytes, 0, bytes.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source The Base64 encoded data * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source) throws Base64DecoderException { return decode(source, 0, source.length); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded data. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(byte[] source) throws Base64DecoderException { return decodeWebSafe(source, 0, source.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, DECODABET); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded byte array. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data */ public static byte[] decodeWebSafe(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, WEBSAFE_DECODABET); } /** * Decodes Base64 content using the supplied decodabet and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @param decodabet the decodabet for decoding Base64 content * @return decoded data */ public static byte[] decode(byte[] source, int off, int len, byte[] decodabet) throws Base64DecoderException { int len34 = len * 3 / 4; byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = 0; i < len; i++) { sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits sbiDecode = decodabet[sbiCrop]; if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better if (sbiDecode >= EQUALS_SIGN_ENC) { // An equals sign (for padding) must not occur at position 0 or 1 // and must be the last byte[s] in the encoded value if (sbiCrop == EQUALS_SIGN) { int bytesLeft = len - i; byte lastByte = (byte) (source[len - 1 + off] & 0x7f); if (b4Posn == 0 || b4Posn == 1) { throw new Base64DecoderException( "invalid padding byte '=' at byte offset " + i); } else if ((b4Posn == 3 && bytesLeft > 2) || (b4Posn == 4 && bytesLeft > 1)) { throw new Base64DecoderException( "padding byte '=' falsely signals end of encoded value " + "at offset " + i); } else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) { throw new Base64DecoderException( "encoded value has invalid trailing byte"); } break; } b4[b4Posn++] = sbiCrop; if (b4Posn == 4) { outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); b4Posn = 0; } } } else { throw new Base64DecoderException("Bad Base64 input character at " + i + ": " + source[i + off] + "(decimal)"); } } // Because web safe encoding allows non padding base64 encodes, we // need to pad the rest of the b4 buffer with equal signs when // b4Posn != 0. There can be at most 2 equal signs at the end of // four characters, so the b4 buffer must have two or three // characters. This also catches the case where the input is // padded with EQUALS_SIGN if (b4Posn != 0) { if (b4Posn == 1) { throw new Base64DecoderException("single trailing character at offset " + (len - 1)); } b4[b4Posn++] = EQUALS_SIGN; outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); } byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } }
0vishalvijay0-v4
v3/src/com/example/android/trivialdrivesample/util/Base64.java
Java
asf20
24,284
/* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trivialdrivesample.util; import android.text.TextUtils; import android.util.Log; import org.json.JSONException; import org.json.JSONObject; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; /** * Security-related methods. For a secure implementation, all of this code * should be implemented on a server that communicates with the * application on the device. For the sake of simplicity and clarity of this * example, this code is included here and is executed on the device. If you * must verify the purchases on the phone, you should obfuscate this code to * make it harder for an attacker to replace the code with stubs that treat all * purchases as verified. */ public class Security { private static final String TAG = "IABUtil/Security"; private static final String KEY_FACTORY_ALGORITHM = "RSA"; private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; /** * Verifies that the data was signed with the given signature, and returns * the verified purchase. The data is in JSON format and signed * with a private key. The data also contains the {@link PurchaseState} * and product ID of the purchase. * @param base64PublicKey the base64-encoded public key to use for verifying. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key */ public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) { if (signedData == null) { Log.e(TAG, "data is null"); return false; } boolean verified = false; if (!TextUtils.isEmpty(signature)) { PublicKey key = Security.generatePublicKey(base64PublicKey); verified = Security.verify(key, signedData, signature); if (!verified) { Log.w(TAG, "signature does not match data."); return false; } } return true; } /** * Generates a PublicKey instance from a string containing the * Base64-encoded public key. * * @param encodedPublicKey Base64-encoded public key * @throws IllegalArgumentException if encodedPublicKey is invalid */ public static PublicKey generatePublicKey(String encodedPublicKey) { try { byte[] decodedKey = Base64.decode(encodedPublicKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM); return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { Log.e(TAG, "Invalid key specification."); throw new IllegalArgumentException(e); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); throw new IllegalArgumentException(e); } } /** * Verifies that the signature from the server matches the computed * signature on the data. Returns true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server * @param signature server signature * @return true if the data and signature match */ public static boolean verify(PublicKey publicKey, String signedData, String signature) { Signature sig; try { sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes()); if (!sig.verify(Base64.decode(signature))) { Log.e(TAG, "Signature verification failed."); return false; } return true; } catch (NoSuchAlgorithmException e) { Log.e(TAG, "NoSuchAlgorithmException."); } catch (InvalidKeyException e) { Log.e(TAG, "Invalid key specification."); } catch (SignatureException e) { Log.e(TAG, "Signature exception."); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); } return false; } }
0vishalvijay0-v4
v3/src/com/example/android/trivialdrivesample/util/Security.java
Java
asf20
5,162
/* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trivialdrivesample.util; import android.app.Activity; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.RemoteException; import android.text.TextUtils; import android.util.Log; import com.android.vending.billing.IInAppBillingService; import org.json.JSONException; import java.util.ArrayList; import java.util.List; /** * Provides convenience methods for in-app billing. You can create one instance of this * class for your application and use it to process in-app billing operations. * It provides synchronous (blocking) and asynchronous (non-blocking) methods for * many common in-app billing operations, as well as automatic signature * verification. * * After instantiating, you must perform setup in order to start using the object. * To perform setup, call the {@link #startSetup} method and provide a listener; * that listener will be notified when setup is complete, after which (and not before) * you may call other methods. * * After setup is complete, you will typically want to request an inventory of owned * items and subscriptions. See {@link #queryInventory}, {@link #queryInventoryAsync} * and related methods. * * When you are done with this object, don't forget to call {@link #dispose} * to ensure proper cleanup. This object holds a binding to the in-app billing * service, which will leak unless you dispose of it correctly. If you created * the object on an Activity's onCreate method, then the recommended * place to dispose of it is the Activity's onDestroy method. * * A note about threading: When using this object from a background thread, you may * call the blocking versions of methods; when using from a UI thread, call * only the asynchronous versions and handle the results via callbacks. * Also, notice that you can only call one asynchronous operation at a time; * attempting to start a second asynchronous operation while the first one * has not yet completed will result in an exception being thrown. * * @author Bruno Oliveira (Google) * */ public class IabHelper { // Is debug logging enabled? boolean mDebugLog = false; String mDebugTag = "IabHelper"; // Is setup done? boolean mSetupDone = false; // Has this object been disposed of? (If so, we should ignore callbacks, etc) boolean mDisposed = false; // Are subscriptions supported? boolean mSubscriptionsSupported = false; // Is an asynchronous operation in progress? // (only one at a time can be in progress) boolean mAsyncInProgress = false; // (for logging/debugging) // if mAsyncInProgress == true, what asynchronous operation is in progress? String mAsyncOperation = ""; // Context we were passed during initialization Context mContext; // Connection to the service IInAppBillingService mService; ServiceConnection mServiceConn; // The request code used to launch purchase flow int mRequestCode; // The item type of the current purchase flow String mPurchasingItemType; // Public key for verifying signature, in base64 encoding String mSignatureBase64 = null; // Billing response codes public static final int BILLING_RESPONSE_RESULT_OK = 0; public static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1; public static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3; public static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4; public static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5; public static final int BILLING_RESPONSE_RESULT_ERROR = 6; public static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7; public static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8; // IAB Helper error codes public static final int IABHELPER_ERROR_BASE = -1000; public static final int IABHELPER_REMOTE_EXCEPTION = -1001; public static final int IABHELPER_BAD_RESPONSE = -1002; public static final int IABHELPER_VERIFICATION_FAILED = -1003; public static final int IABHELPER_SEND_INTENT_FAILED = -1004; public static final int IABHELPER_USER_CANCELLED = -1005; public static final int IABHELPER_UNKNOWN_PURCHASE_RESPONSE = -1006; public static final int IABHELPER_MISSING_TOKEN = -1007; public static final int IABHELPER_UNKNOWN_ERROR = -1008; public static final int IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE = -1009; public static final int IABHELPER_INVALID_CONSUMPTION = -1010; // Keys for the responses from InAppBillingService public static final String RESPONSE_CODE = "RESPONSE_CODE"; public static final String RESPONSE_GET_SKU_DETAILS_LIST = "DETAILS_LIST"; public static final String RESPONSE_BUY_INTENT = "BUY_INTENT"; public static final String RESPONSE_INAPP_PURCHASE_DATA = "INAPP_PURCHASE_DATA"; public static final String RESPONSE_INAPP_SIGNATURE = "INAPP_DATA_SIGNATURE"; public static final String RESPONSE_INAPP_ITEM_LIST = "INAPP_PURCHASE_ITEM_LIST"; public static final String RESPONSE_INAPP_PURCHASE_DATA_LIST = "INAPP_PURCHASE_DATA_LIST"; public static final String RESPONSE_INAPP_SIGNATURE_LIST = "INAPP_DATA_SIGNATURE_LIST"; public static final String INAPP_CONTINUATION_TOKEN = "INAPP_CONTINUATION_TOKEN"; // Item types public static final String ITEM_TYPE_INAPP = "inapp"; public static final String ITEM_TYPE_SUBS = "subs"; // some fields on the getSkuDetails response bundle public static final String GET_SKU_DETAILS_ITEM_LIST = "ITEM_ID_LIST"; public static final String GET_SKU_DETAILS_ITEM_TYPE_LIST = "ITEM_TYPE_LIST"; /** * Creates an instance. After creation, it will not yet be ready to use. You must perform * setup by calling {@link #startSetup} and wait for setup to complete. This constructor does not * block and is safe to call from a UI thread. * * @param ctx Your application or Activity context. Needed to bind to the in-app billing service. * @param base64PublicKey Your application's public key, encoded in base64. * This is used for verification of purchase signatures. You can find your app's base64-encoded * public key in your application's page on Google Play Developer Console. Note that this * is NOT your "developer public key". */ public IabHelper(Context ctx, String base64PublicKey) { mContext = ctx.getApplicationContext(); mSignatureBase64 = base64PublicKey; logDebug("IAB helper created."); } /** * Enables or disable debug logging through LogCat. */ public void enableDebugLogging(boolean enable, String tag) { checkNotDisposed(); mDebugLog = enable; mDebugTag = tag; } public void enableDebugLogging(boolean enable) { checkNotDisposed(); mDebugLog = enable; } /** * Callback for setup process. This listener's {@link #onIabSetupFinished} method is called * when the setup process is complete. */ public interface OnIabSetupFinishedListener { /** * Called to notify that setup is complete. * * @param result The result of the setup process. */ public void onIabSetupFinished(IabResult result); } /** * Starts the setup process. This will start up the setup process asynchronously. * You will be notified through the listener when the setup process is complete. * This method is safe to call from a UI thread. * * @param listener The listener to notify when the setup process is complete. */ public void startSetup(final OnIabSetupFinishedListener listener) { // If already set up, can't do it again. checkNotDisposed(); if (mSetupDone) throw new IllegalStateException("IAB helper is already set up."); // Connection to IAB service logDebug("Starting in-app billing setup."); mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { logDebug("Billing service disconnected."); mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { if (mDisposed) return; logDebug("Billing service connected."); mService = IInAppBillingService.Stub.asInterface(service); String packageName = mContext.getPackageName(); try { logDebug("Checking for in-app billing 3 support."); // check for in-app billing v3 support int response = mService.isBillingSupported(3, packageName, ITEM_TYPE_INAPP); if (response != BILLING_RESPONSE_RESULT_OK) { if (listener != null) listener.onIabSetupFinished(new IabResult(response, "Error checking for billing v3 support.")); // if in-app purchases aren't supported, neither are subscriptions. mSubscriptionsSupported = false; return; } logDebug("In-app billing version 3 supported for " + packageName); // check for v3 subscriptions support response = mService.isBillingSupported(3, packageName, ITEM_TYPE_SUBS); if (response == BILLING_RESPONSE_RESULT_OK) { logDebug("Subscriptions AVAILABLE."); mSubscriptionsSupported = true; } else { logDebug("Subscriptions NOT AVAILABLE. Response: " + response); } mSetupDone = true; } catch (RemoteException e) { if (listener != null) { listener.onIabSetupFinished(new IabResult(IABHELPER_REMOTE_EXCEPTION, "RemoteException while setting up in-app billing.")); } e.printStackTrace(); return; } if (listener != null) { listener.onIabSetupFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Setup successful.")); } } }; Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); if (!mContext.getPackageManager().queryIntentServices(serviceIntent, 0).isEmpty()) { // service available to handle that Intent mContext.bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); } else { // no service available to handle that Intent if (listener != null) { listener.onIabSetupFinished( new IabResult(BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE, "Billing service unavailable on device.")); } } } /** * Dispose of object, releasing resources. It's very important to call this * method when you are done with this object. It will release any resources * used by it such as service connections. Naturally, once the object is * disposed of, it can't be used again. */ public void dispose() { logDebug("Disposing."); mSetupDone = false; if (mServiceConn != null) { logDebug("Unbinding from service."); if (mContext != null) mContext.unbindService(mServiceConn); } mDisposed = true; mContext = null; mServiceConn = null; mService = null; mPurchaseListener = null; } private void checkNotDisposed() { if (mDisposed) throw new IllegalStateException("IabHelper was disposed of, so it cannot be used."); } /** Returns whether subscriptions are supported. */ public boolean subscriptionsSupported() { checkNotDisposed(); return mSubscriptionsSupported; } /** * Callback that notifies when a purchase is finished. */ public interface OnIabPurchaseFinishedListener { /** * Called to notify that an in-app purchase finished. If the purchase was successful, * then the sku parameter specifies which item was purchased. If the purchase failed, * the sku and extraData parameters may or may not be null, depending on how far the purchase * process went. * * @param result The result of the purchase. * @param info The purchase information (null if purchase failed) */ public void onIabPurchaseFinished(IabResult result, Purchase info); } // The listener registered on launchPurchaseFlow, which we have to call back when // the purchase finishes OnIabPurchaseFinishedListener mPurchaseListener; public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) { launchPurchaseFlow(act, sku, requestCode, listener, ""); } public void launchPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { launchPurchaseFlow(act, sku, ITEM_TYPE_INAPP, requestCode, listener, extraData); } public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener) { launchSubscriptionPurchaseFlow(act, sku, requestCode, listener, ""); } public void launchSubscriptionPurchaseFlow(Activity act, String sku, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { launchPurchaseFlow(act, sku, ITEM_TYPE_SUBS, requestCode, listener, extraData); } /** * Initiate the UI flow for an in-app purchase. Call this method to initiate an in-app purchase, * which will involve bringing up the Google Play screen. The calling activity will be paused while * the user interacts with Google Play, and the result will be delivered via the activity's * {@link android.app.Activity#onActivityResult} method, at which point you must call * this object's {@link #handleActivityResult} method to continue the purchase flow. This method * MUST be called from the UI thread of the Activity. * * @param act The calling activity. * @param sku The sku of the item to purchase. * @param itemType indicates if it's a product or a subscription (ITEM_TYPE_INAPP or ITEM_TYPE_SUBS) * @param requestCode A request code (to differentiate from other responses -- * as in {@link android.app.Activity#startActivityForResult}). * @param listener The listener to notify when the purchase process finishes * @param extraData Extra data (developer payload), which will be returned with the purchase data * when the purchase completes. This extra data will be permanently bound to that purchase * and will always be returned when the purchase is queried. */ public void launchPurchaseFlow(Activity act, String sku, String itemType, int requestCode, OnIabPurchaseFinishedListener listener, String extraData) { checkNotDisposed(); checkSetupDone("launchPurchaseFlow"); flagStartAsync("launchPurchaseFlow"); IabResult result; if (itemType.equals(ITEM_TYPE_SUBS) && !mSubscriptionsSupported) { IabResult r = new IabResult(IABHELPER_SUBSCRIPTIONS_NOT_AVAILABLE, "Subscriptions are not available."); flagEndAsync(); if (listener != null) listener.onIabPurchaseFinished(r, null); return; } try { logDebug("Constructing buy intent for " + sku + ", item type: " + itemType); Bundle buyIntentBundle = mService.getBuyIntent(3, mContext.getPackageName(), sku, itemType, extraData); int response = getResponseCodeFromBundle(buyIntentBundle); if (response != BILLING_RESPONSE_RESULT_OK) { logError("Unable to buy item, Error response: " + getResponseDesc(response)); flagEndAsync(); result = new IabResult(response, "Unable to buy item"); if (listener != null) listener.onIabPurchaseFinished(result, null); return; } PendingIntent pendingIntent = buyIntentBundle.getParcelable(RESPONSE_BUY_INTENT); logDebug("Launching buy intent for " + sku + ". Request code: " + requestCode); mRequestCode = requestCode; mPurchaseListener = listener; mPurchasingItemType = itemType; act.startIntentSenderForResult(pendingIntent.getIntentSender(), requestCode, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0)); } catch (SendIntentException e) { logError("SendIntentException while launching purchase flow for sku " + sku); e.printStackTrace(); flagEndAsync(); result = new IabResult(IABHELPER_SEND_INTENT_FAILED, "Failed to send intent."); if (listener != null) listener.onIabPurchaseFinished(result, null); } catch (RemoteException e) { logError("RemoteException while launching purchase flow for sku " + sku); e.printStackTrace(); flagEndAsync(); result = new IabResult(IABHELPER_REMOTE_EXCEPTION, "Remote exception while starting purchase flow"); if (listener != null) listener.onIabPurchaseFinished(result, null); } } /** * Handles an activity result that's part of the purchase flow in in-app billing. If you * are calling {@link #launchPurchaseFlow}, then you must call this method from your * Activity's {@link android.app.Activity@onActivityResult} method. This method * MUST be called from the UI thread of the Activity. * * @param requestCode The requestCode as you received it. * @param resultCode The resultCode as you received it. * @param data The data (Intent) as you received it. * @return Returns true if the result was related to a purchase flow and was handled; * false if the result was not related to a purchase, in which case you should * handle it normally. */ public boolean handleActivityResult(int requestCode, int resultCode, Intent data) { IabResult result; if (requestCode != mRequestCode) return false; checkNotDisposed(); checkSetupDone("handleActivityResult"); // end of async purchase operation that started on launchPurchaseFlow flagEndAsync(); if (data == null) { logError("Null data in IAB activity result."); result = new IabResult(IABHELPER_BAD_RESPONSE, "Null data in IAB result"); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } int responseCode = getResponseCodeFromIntent(data); String purchaseData = data.getStringExtra(RESPONSE_INAPP_PURCHASE_DATA); String dataSignature = data.getStringExtra(RESPONSE_INAPP_SIGNATURE); if (resultCode == Activity.RESULT_OK && responseCode == BILLING_RESPONSE_RESULT_OK) { logDebug("Successful resultcode from purchase activity."); logDebug("Purchase data: " + purchaseData); logDebug("Data signature: " + dataSignature); logDebug("Extras: " + data.getExtras()); logDebug("Expected item type: " + mPurchasingItemType); if (purchaseData == null || dataSignature == null) { logError("BUG: either purchaseData or dataSignature is null."); logDebug("Extras: " + data.getExtras().toString()); result = new IabResult(IABHELPER_UNKNOWN_ERROR, "IAB returned null purchaseData or dataSignature"); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } Purchase purchase = null; try { purchase = new Purchase(mPurchasingItemType, purchaseData, dataSignature); String sku = purchase.getSku(); // Verify signature if (!Security.verifyPurchase(mSignatureBase64, purchaseData, dataSignature)) { logError("Purchase signature verification FAILED for sku " + sku); result = new IabResult(IABHELPER_VERIFICATION_FAILED, "Signature verification failed for sku " + sku); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, purchase); return true; } logDebug("Purchase signature successfully verified."); } catch (JSONException e) { logError("Failed to parse purchase data."); e.printStackTrace(); result = new IabResult(IABHELPER_BAD_RESPONSE, "Failed to parse purchase data."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); return true; } if (mPurchaseListener != null) { mPurchaseListener.onIabPurchaseFinished(new IabResult(BILLING_RESPONSE_RESULT_OK, "Success"), purchase); } } else if (resultCode == Activity.RESULT_OK) { // result code was OK, but in-app billing response was not OK. logDebug("Result code was OK but in-app billing response was not OK: " + getResponseDesc(responseCode)); if (mPurchaseListener != null) { result = new IabResult(responseCode, "Problem purchashing item."); mPurchaseListener.onIabPurchaseFinished(result, null); } } else if (resultCode == Activity.RESULT_CANCELED) { logDebug("Purchase canceled - Response: " + getResponseDesc(responseCode)); result = new IabResult(IABHELPER_USER_CANCELLED, "User canceled."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); } else { logError("Purchase failed. Result code: " + Integer.toString(resultCode) + ". Response: " + getResponseDesc(responseCode)); result = new IabResult(IABHELPER_UNKNOWN_PURCHASE_RESPONSE, "Unknown purchase response."); if (mPurchaseListener != null) mPurchaseListener.onIabPurchaseFinished(result, null); } return true; } public Inventory queryInventory(boolean querySkuDetails, List<String> moreSkus) throws IabException { return queryInventory(querySkuDetails, moreSkus, null); } /** * Queries the inventory. This will query all owned items from the server, as well as * information on additional skus, if specified. This method may block or take long to execute. * Do not call from a UI thread. For that, use the non-blocking version {@link #refreshInventoryAsync}. * * @param querySkuDetails if true, SKU details (price, description, etc) will be queried as well * as purchase information. * @param moreItemSkus additional PRODUCT skus to query information on, regardless of ownership. * Ignored if null or if querySkuDetails is false. * @param moreSubsSkus additional SUBSCRIPTIONS skus to query information on, regardless of ownership. * Ignored if null or if querySkuDetails is false. * @throws IabException if a problem occurs while refreshing the inventory. */ public Inventory queryInventory(boolean querySkuDetails, List<String> moreItemSkus, List<String> moreSubsSkus) throws IabException { checkNotDisposed(); checkSetupDone("queryInventory"); try { Inventory inv = new Inventory(); int r = queryPurchases(inv, ITEM_TYPE_INAPP); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying owned items)."); } if (querySkuDetails) { r = querySkuDetails(ITEM_TYPE_INAPP, inv, moreItemSkus); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying prices of items)."); } } // if subscriptions are supported, then also query for subscriptions if (mSubscriptionsSupported) { r = queryPurchases(inv, ITEM_TYPE_SUBS); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying owned subscriptions)."); } if (querySkuDetails) { r = querySkuDetails(ITEM_TYPE_SUBS, inv, moreItemSkus); if (r != BILLING_RESPONSE_RESULT_OK) { throw new IabException(r, "Error refreshing inventory (querying prices of subscriptions)."); } } } return inv; } catch (RemoteException e) { throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while refreshing inventory.", e); } catch (JSONException e) { throw new IabException(IABHELPER_BAD_RESPONSE, "Error parsing JSON response while refreshing inventory.", e); } } /** * Listener that notifies when an inventory query operation completes. */ public interface QueryInventoryFinishedListener { /** * Called to notify that an inventory query operation completed. * * @param result The result of the operation. * @param inv The inventory. */ public void onQueryInventoryFinished(IabResult result, Inventory inv); } /** * Asynchronous wrapper for inventory query. This will perform an inventory * query as described in {@link #queryInventory}, but will do so asynchronously * and call back the specified listener upon completion. This method is safe to * call from a UI thread. * * @param querySkuDetails as in {@link #queryInventory} * @param moreSkus as in {@link #queryInventory} * @param listener The listener to notify when the refresh operation completes. */ public void queryInventoryAsync(final boolean querySkuDetails, final List<String> moreSkus, final QueryInventoryFinishedListener listener) { final Handler handler = new Handler(); checkNotDisposed(); checkSetupDone("queryInventory"); flagStartAsync("refresh inventory"); (new Thread(new Runnable() { public void run() { IabResult result = new IabResult(BILLING_RESPONSE_RESULT_OK, "Inventory refresh successful."); Inventory inv = null; try { inv = queryInventory(querySkuDetails, moreSkus); } catch (IabException ex) { result = ex.getResult(); } flagEndAsync(); final IabResult result_f = result; final Inventory inv_f = inv; if (!mDisposed && listener != null) { handler.post(new Runnable() { public void run() { listener.onQueryInventoryFinished(result_f, inv_f); } }); } } })).start(); } public void queryInventoryAsync(QueryInventoryFinishedListener listener) { queryInventoryAsync(true, null, listener); } public void queryInventoryAsync(boolean querySkuDetails, QueryInventoryFinishedListener listener) { queryInventoryAsync(querySkuDetails, null, listener); } /** * Consumes a given in-app product. Consuming can only be done on an item * that's owned, and as a result of consumption, the user will no longer own it. * This method may block or take long to return. Do not call from the UI thread. * For that, see {@link #consumeAsync}. * * @param itemInfo The PurchaseInfo that represents the item to consume. * @throws IabException if there is a problem during consumption. */ void consume(Purchase itemInfo) throws IabException { checkNotDisposed(); checkSetupDone("consume"); if (!itemInfo.mItemType.equals(ITEM_TYPE_INAPP)) { throw new IabException(IABHELPER_INVALID_CONSUMPTION, "Items of type '" + itemInfo.mItemType + "' can't be consumed."); } try { String token = itemInfo.getToken(); String sku = itemInfo.getSku(); if (token == null || token.equals("")) { logError("Can't consume "+ sku + ". No token."); throw new IabException(IABHELPER_MISSING_TOKEN, "PurchaseInfo is missing token for sku: " + sku + " " + itemInfo); } logDebug("Consuming sku: " + sku + ", token: " + token); int response = mService.consumePurchase(3, mContext.getPackageName(), token); if (response == BILLING_RESPONSE_RESULT_OK) { logDebug("Successfully consumed sku: " + sku); } else { logDebug("Error consuming consuming sku " + sku + ". " + getResponseDesc(response)); throw new IabException(response, "Error consuming sku " + sku); } } catch (RemoteException e) { throw new IabException(IABHELPER_REMOTE_EXCEPTION, "Remote exception while consuming. PurchaseInfo: " + itemInfo, e); } } /** * Callback that notifies when a consumption operation finishes. */ public interface OnConsumeFinishedListener { /** * Called to notify that a consumption has finished. * * @param purchase The purchase that was (or was to be) consumed. * @param result The result of the consumption operation. */ public void onConsumeFinished(Purchase purchase, IabResult result); } /** * Callback that notifies when a multi-item consumption operation finishes. */ public interface OnConsumeMultiFinishedListener { /** * Called to notify that a consumption of multiple items has finished. * * @param purchases The purchases that were (or were to be) consumed. * @param results The results of each consumption operation, corresponding to each * sku. */ public void onConsumeMultiFinished(List<Purchase> purchases, List<IabResult> results); } /** * Asynchronous wrapper to item consumption. Works like {@link #consume}, but * performs the consumption in the background and notifies completion through * the provided listener. This method is safe to call from a UI thread. * * @param purchase The purchase to be consumed. * @param listener The listener to notify when the consumption operation finishes. */ public void consumeAsync(Purchase purchase, OnConsumeFinishedListener listener) { checkNotDisposed(); checkSetupDone("consume"); List<Purchase> purchases = new ArrayList<Purchase>(); purchases.add(purchase); consumeAsyncInternal(purchases, listener, null); } /** * Same as {@link consumeAsync}, but for multiple items at once. * @param purchases The list of PurchaseInfo objects representing the purchases to consume. * @param listener The listener to notify when the consumption operation finishes. */ public void consumeAsync(List<Purchase> purchases, OnConsumeMultiFinishedListener listener) { checkNotDisposed(); checkSetupDone("consume"); consumeAsyncInternal(purchases, null, listener); } /** * Returns a human-readable description for the given response code. * * @param code The response code * @return A human-readable string explaining the result code. * It also includes the result code numerically. */ public static String getResponseDesc(int code) { String[] iab_msgs = ("0:OK/1:User Canceled/2:Unknown/" + "3:Billing Unavailable/4:Item unavailable/" + "5:Developer Error/6:Error/7:Item Already Owned/" + "8:Item not owned").split("/"); String[] iabhelper_msgs = ("0:OK/-1001:Remote exception during initialization/" + "-1002:Bad response received/" + "-1003:Purchase signature verification failed/" + "-1004:Send intent failed/" + "-1005:User cancelled/" + "-1006:Unknown purchase response/" + "-1007:Missing token/" + "-1008:Unknown error/" + "-1009:Subscriptions not available/" + "-1010:Invalid consumption attempt").split("/"); if (code <= IABHELPER_ERROR_BASE) { int index = IABHELPER_ERROR_BASE - code; if (index >= 0 && index < iabhelper_msgs.length) return iabhelper_msgs[index]; else return String.valueOf(code) + ":Unknown IAB Helper Error"; } else if (code < 0 || code >= iab_msgs.length) return String.valueOf(code) + ":Unknown"; else return iab_msgs[code]; } // Checks that setup was done; if not, throws an exception. void checkSetupDone(String operation) { if (!mSetupDone) { logError("Illegal state for operation (" + operation + "): IAB helper is not set up."); throw new IllegalStateException("IAB helper is not set up. Can't perform operation: " + operation); } } // Workaround to bug where sometimes response codes come as Long instead of Integer int getResponseCodeFromBundle(Bundle b) { Object o = b.get(RESPONSE_CODE); if (o == null) { logDebug("Bundle with null response code, assuming OK (known issue)"); return BILLING_RESPONSE_RESULT_OK; } else if (o instanceof Integer) return ((Integer)o).intValue(); else if (o instanceof Long) return (int)((Long)o).longValue(); else { logError("Unexpected type for bundle response code."); logError(o.getClass().getName()); throw new RuntimeException("Unexpected type for bundle response code: " + o.getClass().getName()); } } // Workaround to bug where sometimes response codes come as Long instead of Integer int getResponseCodeFromIntent(Intent i) { Object o = i.getExtras().get(RESPONSE_CODE); if (o == null) { logError("Intent with no response code, assuming OK (known issue)"); return BILLING_RESPONSE_RESULT_OK; } else if (o instanceof Integer) return ((Integer)o).intValue(); else if (o instanceof Long) return (int)((Long)o).longValue(); else { logError("Unexpected type for intent response code."); logError(o.getClass().getName()); throw new RuntimeException("Unexpected type for intent response code: " + o.getClass().getName()); } } void flagStartAsync(String operation) { if (mAsyncInProgress) throw new IllegalStateException("Can't start async operation (" + operation + ") because another async operation(" + mAsyncOperation + ") is in progress."); mAsyncOperation = operation; mAsyncInProgress = true; logDebug("Starting async operation: " + operation); } void flagEndAsync() { logDebug("Ending async operation: " + mAsyncOperation); mAsyncOperation = ""; mAsyncInProgress = false; } int queryPurchases(Inventory inv, String itemType) throws JSONException, RemoteException { // Query purchases logDebug("Querying owned items, item type: " + itemType); logDebug("Package name: " + mContext.getPackageName()); boolean verificationFailed = false; String continueToken = null; do { logDebug("Calling getPurchases with continuation token: " + continueToken); Bundle ownedItems = mService.getPurchases(3, mContext.getPackageName(), itemType, continueToken); int response = getResponseCodeFromBundle(ownedItems); logDebug("Owned items response: " + String.valueOf(response)); if (response != BILLING_RESPONSE_RESULT_OK) { logDebug("getPurchases() failed: " + getResponseDesc(response)); return response; } if (!ownedItems.containsKey(RESPONSE_INAPP_ITEM_LIST) || !ownedItems.containsKey(RESPONSE_INAPP_PURCHASE_DATA_LIST) || !ownedItems.containsKey(RESPONSE_INAPP_SIGNATURE_LIST)) { logError("Bundle returned from getPurchases() doesn't contain required fields."); return IABHELPER_BAD_RESPONSE; } ArrayList<String> ownedSkus = ownedItems.getStringArrayList( RESPONSE_INAPP_ITEM_LIST); ArrayList<String> purchaseDataList = ownedItems.getStringArrayList( RESPONSE_INAPP_PURCHASE_DATA_LIST); ArrayList<String> signatureList = ownedItems.getStringArrayList( RESPONSE_INAPP_SIGNATURE_LIST); for (int i = 0; i < purchaseDataList.size(); ++i) { String purchaseData = purchaseDataList.get(i); String signature = signatureList.get(i); String sku = ownedSkus.get(i); if (Security.verifyPurchase(mSignatureBase64, purchaseData, signature)) { logDebug("Sku is owned: " + sku); Purchase purchase = new Purchase(itemType, purchaseData, signature); if (TextUtils.isEmpty(purchase.getToken())) { logWarn("BUG: empty/null token!"); logDebug("Purchase data: " + purchaseData); } // Record ownership and token inv.addPurchase(purchase); } else { logWarn("Purchase signature verification **FAILED**. Not adding item."); logDebug(" Purchase data: " + purchaseData); logDebug(" Signature: " + signature); verificationFailed = true; } } continueToken = ownedItems.getString(INAPP_CONTINUATION_TOKEN); logDebug("Continuation token: " + continueToken); } while (!TextUtils.isEmpty(continueToken)); return verificationFailed ? IABHELPER_VERIFICATION_FAILED : BILLING_RESPONSE_RESULT_OK; } int querySkuDetails(String itemType, Inventory inv, List<String> moreSkus) throws RemoteException, JSONException { logDebug("Querying SKU details."); ArrayList<String> skuList = new ArrayList<String>(); skuList.addAll(inv.getAllOwnedSkus(itemType)); if (moreSkus != null) { for (String sku : moreSkus) { if (!skuList.contains(sku)) { skuList.add(sku); } } } if (skuList.size() == 0) { logDebug("queryPrices: nothing to do because there are no SKUs."); return BILLING_RESPONSE_RESULT_OK; } Bundle querySkus = new Bundle(); querySkus.putStringArrayList(GET_SKU_DETAILS_ITEM_LIST, skuList); Bundle skuDetails = mService.getSkuDetails(3, mContext.getPackageName(), itemType, querySkus); if (!skuDetails.containsKey(RESPONSE_GET_SKU_DETAILS_LIST)) { int response = getResponseCodeFromBundle(skuDetails); if (response != BILLING_RESPONSE_RESULT_OK) { logDebug("getSkuDetails() failed: " + getResponseDesc(response)); return response; } else { logError("getSkuDetails() returned a bundle with neither an error nor a detail list."); return IABHELPER_BAD_RESPONSE; } } ArrayList<String> responseList = skuDetails.getStringArrayList( RESPONSE_GET_SKU_DETAILS_LIST); for (String thisResponse : responseList) { SkuDetails d = new SkuDetails(itemType, thisResponse); logDebug("Got sku details: " + d); inv.addSkuDetails(d); } return BILLING_RESPONSE_RESULT_OK; } void consumeAsyncInternal(final List<Purchase> purchases, final OnConsumeFinishedListener singleListener, final OnConsumeMultiFinishedListener multiListener) { final Handler handler = new Handler(); flagStartAsync("consume"); (new Thread(new Runnable() { public void run() { final List<IabResult> results = new ArrayList<IabResult>(); for (Purchase purchase : purchases) { try { consume(purchase); results.add(new IabResult(BILLING_RESPONSE_RESULT_OK, "Successful consume of sku " + purchase.getSku())); } catch (IabException ex) { results.add(ex.getResult()); } } flagEndAsync(); if (!mDisposed && singleListener != null) { handler.post(new Runnable() { public void run() { singleListener.onConsumeFinished(purchases.get(0), results.get(0)); } }); } if (!mDisposed && multiListener != null) { handler.post(new Runnable() { public void run() { multiListener.onConsumeMultiFinished(purchases, results); } }); } } })).start(); } void logDebug(String msg) { if (mDebugLog) Log.d(mDebugTag, msg); } void logError(String msg) { Log.e(mDebugTag, "In-app billing error: " + msg); } void logWarn(String msg) { Log.w(mDebugTag, "In-app billing warning: " + msg); } }
0vishalvijay0-v4
v3/src/com/example/android/trivialdrivesample/util/IabHelper.java
Java
asf20
44,332
/* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trivialdrivesample.util; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents a block of information about in-app items. * An Inventory is returned by such methods as {@link IabHelper#queryInventory}. */ public class Inventory { Map<String,SkuDetails> mSkuMap = new HashMap<String,SkuDetails>(); Map<String,Purchase> mPurchaseMap = new HashMap<String,Purchase>(); Inventory() { } /** Returns the listing details for an in-app product. */ public SkuDetails getSkuDetails(String sku) { return mSkuMap.get(sku); } /** Returns purchase information for a given product, or null if there is no purchase. */ public Purchase getPurchase(String sku) { return mPurchaseMap.get(sku); } /** Returns whether or not there exists a purchase of the given product. */ public boolean hasPurchase(String sku) { return mPurchaseMap.containsKey(sku); } /** Return whether or not details about the given product are available. */ public boolean hasDetails(String sku) { return mSkuMap.containsKey(sku); } /** * Erase a purchase (locally) from the inventory, given its product ID. This just * modifies the Inventory object locally and has no effect on the server! This is * useful when you have an existing Inventory object which you know to be up to date, * and you have just consumed an item successfully, which means that erasing its * purchase data from the Inventory you already have is quicker than querying for * a new Inventory. */ public void erasePurchase(String sku) { if (mPurchaseMap.containsKey(sku)) mPurchaseMap.remove(sku); } /** Returns a list of all owned product IDs. */ List<String> getAllOwnedSkus() { return new ArrayList<String>(mPurchaseMap.keySet()); } /** Returns a list of all owned product IDs of a given type */ List<String> getAllOwnedSkus(String itemType) { List<String> result = new ArrayList<String>(); for (Purchase p : mPurchaseMap.values()) { if (p.getItemType().equals(itemType)) result.add(p.getSku()); } return result; } /** Returns a list of all purchases. */ List<Purchase> getAllPurchases() { return new ArrayList<Purchase>(mPurchaseMap.values()); } void addSkuDetails(SkuDetails d) { mSkuMap.put(d.getSku(), d); } void addPurchase(Purchase p) { mPurchaseMap.put(p.getSku(), p); } }
0vishalvijay0-v4
v3/src/com/example/android/trivialdrivesample/util/Inventory.java
Java
asf20
3,182
/* Copyright (c) 2012 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.trivialdrivesample; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageView; import com.example.android.trivialdrivesample.util.IabHelper; import com.example.android.trivialdrivesample.util.IabResult; import com.example.android.trivialdrivesample.util.Inventory; import com.example.android.trivialdrivesample.util.Purchase; /** * Example game using in-app billing version 3. * * Before attempting to run this sample, please read the README file. It * contains important information on how to set up this project. * * All the game-specific logic is implemented here in MainActivity, while the * general-purpose boilerplate that can be reused in any app is provided in the * classes in the util/ subdirectory. When implementing your own application, * you can copy over util/*.java to make use of those utility classes. * * This game is a simple "driving" game where the player can buy gas * and drive. The car has a tank which stores gas. When the player purchases * gas, the tank fills up (1/4 tank at a time). When the player drives, the gas * in the tank diminishes (also 1/4 tank at a time). * * The user can also purchase a "premium upgrade" that gives them a red car * instead of the standard blue one (exciting!). * * The user can also purchase a subscription ("infinite gas") that allows them * to drive without using up any gas while that subscription is active. * * It's important to note the consumption mechanics for each item. * * PREMIUM: the item is purchased and NEVER consumed. So, after the original * purchase, the player will always own that item. The application knows to * display the red car instead of the blue one because it queries whether * the premium "item" is owned or not. * * INFINITE GAS: this is a subscription, and subscriptions can't be consumed. * * GAS: when gas is purchased, the "gas" item is then owned. We consume it * when we apply that item's effects to our app's world, which to us means * filling up 1/4 of the tank. This happens immediately after purchase! * It's at this point (and not when the user drives) that the "gas" * item is CONSUMED. Consumption should always happen when your game * world was safely updated to apply the effect of the purchase. So, * in an example scenario: * * BEFORE: tank at 1/2 * ON PURCHASE: tank at 1/2, "gas" item is owned * IMMEDIATELY: "gas" is consumed, tank goes to 3/4 * AFTER: tank at 3/4, "gas" item NOT owned any more * * Another important point to notice is that it may so happen that * the application crashed (or anything else happened) after the user * purchased the "gas" item, but before it was consumed. That's why, * on startup, we check if we own the "gas" item, and, if so, * we have to apply its effects to our world and consume it. This * is also very important! * * @author Bruno Oliveira (Google) */ public class MainActivity extends Activity { // Debug tag, for logging static final String TAG = "TrivialDrive"; // Does the user have the premium upgrade? boolean mIsPremium = false; // Does the user have an active subscription to the infinite gas plan? boolean mSubscribedToInfiniteGas = false; // SKUs for our products: the premium upgrade (non-consumable) and gas (consumable) static final String SKU_PREMIUM = "premium"; static final String SKU_GAS = "gas"; // SKU for our subscription (infinite gas) static final String SKU_INFINITE_GAS = "infinite_gas"; // (arbitrary) request code for the purchase flow static final int RC_REQUEST = 10001; // Graphics for the gas gauge static int[] TANK_RES_IDS = { R.drawable.gas0, R.drawable.gas1, R.drawable.gas2, R.drawable.gas3, R.drawable.gas4 }; // How many units (1/4 tank is our unit) fill in the tank. static final int TANK_MAX = 4; // Current amount of gas in tank, in units int mTank; // The helper object IabHelper mHelper; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // load game data loadData(); /* base64EncodedPublicKey should be YOUR APPLICATION'S PUBLIC KEY * (that you got from the Google Play developer console). This is not your * developer public key, it's the *app-specific* public key. * * Instead of just storing the entire literal string here embedded in the * program, construct the key at runtime from pieces or * use bit manipulation (for example, XOR with some other string) to hide * the actual key. The key itself is not secret information, but we don't * want to make it easy for an attacker to replace the public key with one * of their own and then fake messages from the server. */ String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; // Some sanity checks to see if the developer (that's you!) really followed the // instructions to run this sample (don't put these checks on your app!) if (base64EncodedPublicKey.contains("CONSTRUCT_YOUR")) { throw new RuntimeException("Please put your app's public key in MainActivity.java. See README."); } if (getPackageName().startsWith("com.example")) { throw new RuntimeException("Please change the sample's package name! See README."); } // Create the helper, passing it our context and the public key to verify signatures with Log.d(TAG, "Creating IAB helper."); mHelper = new IabHelper(this, base64EncodedPublicKey); // enable debug logging (for a production application, you should set this to false). mHelper.enableDebugLogging(true); // Start setup. This is asynchronous and the specified listener // will be called once setup completes. Log.d(TAG, "Starting setup."); mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { public void onIabSetupFinished(IabResult result) { Log.d(TAG, "Setup finished."); if (!result.isSuccess()) { // Oh noes, there was a problem. complain("Problem setting up in-app billing: " + result); return; } // Have we been disposed of in the meantime? If so, quit. if (mHelper == null) return; // IAB is fully set up. Now, let's get an inventory of stuff we own. Log.d(TAG, "Setup successful. Querying inventory."); mHelper.queryInventoryAsync(mGotInventoryListener); } }); } // Listener that's called when we finish querying the items and subscriptions we own IabHelper.QueryInventoryFinishedListener mGotInventoryListener = new IabHelper.QueryInventoryFinishedListener() { public void onQueryInventoryFinished(IabResult result, Inventory inventory) { Log.d(TAG, "Query inventory finished."); // Have we been disposed of in the meantime? If so, quit. if (mHelper == null) return; // Is it a failure? if (result.isFailure()) { complain("Failed to query inventory: " + result); return; } Log.d(TAG, "Query inventory was successful."); /* * Check for items we own. Notice that for each purchase, we check * the developer payload to see if it's correct! See * verifyDeveloperPayload(). */ // Do we have the premium upgrade? Purchase premiumPurchase = inventory.getPurchase(SKU_PREMIUM); mIsPremium = (premiumPurchase != null && verifyDeveloperPayload(premiumPurchase)); Log.d(TAG, "User is " + (mIsPremium ? "PREMIUM" : "NOT PREMIUM")); // Do we have the infinite gas plan? Purchase infiniteGasPurchase = inventory.getPurchase(SKU_INFINITE_GAS); mSubscribedToInfiniteGas = (infiniteGasPurchase != null && verifyDeveloperPayload(infiniteGasPurchase)); Log.d(TAG, "User " + (mSubscribedToInfiniteGas ? "HAS" : "DOES NOT HAVE") + " infinite gas subscription."); if (mSubscribedToInfiniteGas) mTank = TANK_MAX; // Check for gas delivery -- if we own gas, we should fill up the tank immediately Purchase gasPurchase = inventory.getPurchase(SKU_GAS); if (gasPurchase != null && verifyDeveloperPayload(gasPurchase)) { Log.d(TAG, "We have gas. Consuming it."); mHelper.consumeAsync(inventory.getPurchase(SKU_GAS), mConsumeFinishedListener); return; } updateUi(); setWaitScreen(false); Log.d(TAG, "Initial inventory query finished; enabling main UI."); } }; // User clicked the "Buy Gas" button public void onBuyGasButtonClicked(View arg0) { Log.d(TAG, "Buy gas button clicked."); if (mSubscribedToInfiniteGas) { complain("No need! You're subscribed to infinite gas. Isn't that awesome?"); return; } if (mTank >= TANK_MAX) { complain("Your tank is full. Drive around a bit!"); return; } // launch the gas purchase UI flow. // We will be notified of completion via mPurchaseFinishedListener setWaitScreen(true); Log.d(TAG, "Launching purchase flow for gas."); /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use * an empty string, but on a production app you should carefully generate this. */ String payload = ""; mHelper.launchPurchaseFlow(this, SKU_GAS, RC_REQUEST, mPurchaseFinishedListener, payload); } // User clicked the "Upgrade to Premium" button. public void onUpgradeAppButtonClicked(View arg0) { Log.d(TAG, "Upgrade button clicked; launching purchase flow for upgrade."); setWaitScreen(true); /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use * an empty string, but on a production app you should carefully generate this. */ String payload = ""; mHelper.launchPurchaseFlow(this, SKU_PREMIUM, RC_REQUEST, mPurchaseFinishedListener, payload); } // "Subscribe to infinite gas" button clicked. Explain to user, then start purchase // flow for subscription. public void onInfiniteGasButtonClicked(View arg0) { if (!mHelper.subscriptionsSupported()) { complain("Subscriptions not supported on your device yet. Sorry!"); return; } /* TODO: for security, generate your payload here for verification. See the comments on * verifyDeveloperPayload() for more info. Since this is a SAMPLE, we just use * an empty string, but on a production app you should carefully generate this. */ String payload = ""; setWaitScreen(true); Log.d(TAG, "Launching purchase flow for infinite gas subscription."); mHelper.launchPurchaseFlow(this, SKU_INFINITE_GAS, IabHelper.ITEM_TYPE_SUBS, RC_REQUEST, mPurchaseFinishedListener, payload); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.d(TAG, "onActivityResult(" + requestCode + "," + resultCode + "," + data); if (mHelper == null) return; // Pass on the activity result to the helper for handling if (!mHelper.handleActivityResult(requestCode, resultCode, data)) { // not handled, so handle it ourselves (here's where you'd // perform any handling of activity results not related to in-app // billing... super.onActivityResult(requestCode, resultCode, data); } else { Log.d(TAG, "onActivityResult handled by IABUtil."); } } /** Verifies the developer payload of a purchase. */ boolean verifyDeveloperPayload(Purchase p) { String payload = p.getDeveloperPayload(); /* * TODO: verify that the developer payload of the purchase is correct. It will be * the same one that you sent when initiating the purchase. * * WARNING: Locally generating a random string when starting a purchase and * verifying it here might seem like a good approach, but this will fail in the * case where the user purchases an item on one device and then uses your app on * a different device, because on the other device you will not have access to the * random string you originally generated. * * So a good developer payload has these characteristics: * * 1. If two different users purchase an item, the payload is different between them, * so that one user's purchase can't be replayed to another user. * * 2. The payload must be such that you can verify it even when the app wasn't the * one who initiated the purchase flow (so that items purchased by the user on * one device work on other devices owned by the user). * * Using your own server to store and verify developer payloads across app * installations is recommended. */ return true; } // Callback for when a purchase is finished IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener = new IabHelper.OnIabPurchaseFinishedListener() { public void onIabPurchaseFinished(IabResult result, Purchase purchase) { Log.d(TAG, "Purchase finished: " + result + ", purchase: " + purchase); // if we were disposed of in the meantime, quit. if (mHelper == null) return; if (result.isFailure()) { complain("Error purchasing: " + result); setWaitScreen(false); return; } if (!verifyDeveloperPayload(purchase)) { complain("Error purchasing. Authenticity verification failed."); setWaitScreen(false); return; } Log.d(TAG, "Purchase successful."); if (purchase.getSku().equals(SKU_GAS)) { // bought 1/4 tank of gas. So consume it. Log.d(TAG, "Purchase is gas. Starting gas consumption."); mHelper.consumeAsync(purchase, mConsumeFinishedListener); } else if (purchase.getSku().equals(SKU_PREMIUM)) { // bought the premium upgrade! Log.d(TAG, "Purchase is premium upgrade. Congratulating user."); alert("Thank you for upgrading to premium!"); mIsPremium = true; updateUi(); setWaitScreen(false); } else if (purchase.getSku().equals(SKU_INFINITE_GAS)) { // bought the infinite gas subscription Log.d(TAG, "Infinite gas subscription purchased."); alert("Thank you for subscribing to infinite gas!"); mSubscribedToInfiniteGas = true; mTank = TANK_MAX; updateUi(); setWaitScreen(false); } } }; // Called when consumption is complete IabHelper.OnConsumeFinishedListener mConsumeFinishedListener = new IabHelper.OnConsumeFinishedListener() { public void onConsumeFinished(Purchase purchase, IabResult result) { Log.d(TAG, "Consumption finished. Purchase: " + purchase + ", result: " + result); // if we were disposed of in the meantime, quit. if (mHelper == null) return; // We know this is the "gas" sku because it's the only one we consume, // so we don't check which sku was consumed. If you have more than one // sku, you probably should check... if (result.isSuccess()) { // successfully consumed, so we apply the effects of the item in our // game world's logic, which in our case means filling the gas tank a bit Log.d(TAG, "Consumption successful. Provisioning."); mTank = mTank == TANK_MAX ? TANK_MAX : mTank + 1; saveData(); alert("You filled 1/4 tank. Your tank is now " + String.valueOf(mTank) + "/4 full!"); } else { complain("Error while consuming: " + result); } updateUi(); setWaitScreen(false); Log.d(TAG, "End consumption flow."); } }; // Drive button clicked. Burn gas! public void onDriveButtonClicked(View arg0) { Log.d(TAG, "Drive button clicked."); if (!mSubscribedToInfiniteGas && mTank <= 0) alert("Oh, no! You are out of gas! Try buying some!"); else { if (!mSubscribedToInfiniteGas) --mTank; saveData(); alert("Vroooom, you drove a few miles."); updateUi(); Log.d(TAG, "Vrooom. Tank is now " + mTank); } } // We're being destroyed. It's important to dispose of the helper here! @Override public void onDestroy() { super.onDestroy(); // very important: Log.d(TAG, "Destroying helper."); if (mHelper != null) { mHelper.dispose(); mHelper = null; } } // updates UI to reflect model public void updateUi() { // update the car color to reflect premium status or lack thereof ((ImageView)findViewById(R.id.free_or_premium)).setImageResource(mIsPremium ? R.drawable.premium : R.drawable.free); // "Upgrade" button is only visible if the user is not premium findViewById(R.id.upgrade_button).setVisibility(mIsPremium ? View.GONE : View.VISIBLE); // "Get infinite gas" button is only visible if the user is not subscribed yet findViewById(R.id.infinite_gas_button).setVisibility(mSubscribedToInfiniteGas ? View.GONE : View.VISIBLE); // update gas gauge to reflect tank status if (mSubscribedToInfiniteGas) { ((ImageView)findViewById(R.id.gas_gauge)).setImageResource(R.drawable.gas_inf); } else { int index = mTank >= TANK_RES_IDS.length ? TANK_RES_IDS.length - 1 : mTank; ((ImageView)findViewById(R.id.gas_gauge)).setImageResource(TANK_RES_IDS[index]); } } // Enables or disables the "please wait" screen. void setWaitScreen(boolean set) { findViewById(R.id.screen_main).setVisibility(set ? View.GONE : View.VISIBLE); findViewById(R.id.screen_wait).setVisibility(set ? View.VISIBLE : View.GONE); } void complain(String message) { Log.e(TAG, "**** TrivialDrive Error: " + message); alert("Error: " + message); } void alert(String message) { AlertDialog.Builder bld = new AlertDialog.Builder(this); bld.setMessage(message); bld.setNeutralButton("OK", null); Log.d(TAG, "Showing alert dialog: " + message); bld.create().show(); } void saveData() { /* * WARNING: on a real application, we recommend you save data in a secure way to * prevent tampering. For simplicity in this sample, we simply store the data using a * SharedPreferences. */ SharedPreferences.Editor spe = getPreferences(MODE_PRIVATE).edit(); spe.putInt("tank", mTank); spe.commit(); Log.d(TAG, "Saved data: tank = " + String.valueOf(mTank)); } void loadData() { SharedPreferences sp = getPreferences(MODE_PRIVATE); mTank = sp.getInt("tank", 2); Log.d(TAG, "Loaded data: tank = " + String.valueOf(mTank)); } }
0vishalvijay0-v4
v3/src/com/example/android/trivialdrivesample/MainActivity.java
Java
asf20
21,184
#!/bin/sh cd .git/hooks ln -sf ../../git_hooks/* .
0vishalvijay0-v4
setup_git_hooks
Shell
asf20
51
#!/bin/sh RIGHT_PKG_NAME=com.example.android.trivialdrivesample # Check that there isn't a NOCOMMIT flag if find . -name CONFIDENTIAL | grep -q CONFIDENTIAL; then echo "*** The working directory is marked as CONFIDENTIAL" echo "If you're really ready to commit, remove the CONFIDENTIAL files and try again:" find . -name CONFIDENTIAL exit 2 fi # Check that there's only one package name line in v3/AndroidManifest.xml echo "Checking package name in v3/AndroidManifest.xml" packages=`grep package= v3/AndroidManifest.xml | wc -l` if [ "$packages" -ne 1 ]; then echo "*** There are $packages package= lines in v3/AndroidManifest.xml." echo "There should be exactly 1." exit 1 fi # Check that it's the right package name if ! (grep package= v3/AndroidManifest.xml | grep -q $RIGHT_PKG_NAME); then echo "*** Package name is wrong in v3/AndroidManifest.xml." echo "It should be $RIGHT_PKG_NAME." exit 1 fi # Check that MainActivity.java has a placeholder key, not an actual key echo "Checking for placeholder keys." unexpected_keys=`find . -name Dungeons.java -o -name MainActivity.java -exec grep -E 'base64EncodedPublicKey *=' {} \; | grep -v CONSTRUCT_YOUR` if [ -n "$unexpected_keys" ]; then echo "*** There are unexpected keys lying around in the code." echo "Make sure all actual keys are replaced with the CONSTRUCT_YOUR_*" echo "placeholder key before comitting." echo echo "Unexpected keys:" echo "$unexpected_keys" exit 1 fi echo "All presubmit checks passed."
0vishalvijay0-v4
git_hooks/pre-commit
Shell
asf20
1,524
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.vending.billing; import android.os.Bundle; interface IMarketBillingService { /** Given the arguments in bundle form, returns a bundle for results. */ Bundle sendBillingRequest(in Bundle bundle); }
0vishalvijay0-v4
v2/src/com/android/vending/billing/IMarketBillingService.aidl
AIDL
asf20
848
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dungeons; /** * This class holds global constants that are used throughout the application * to support in-app billing. */ public class Consts { // The response codes for a request, defined by Android Market. public enum ResponseCode { RESULT_OK, RESULT_USER_CANCELED, RESULT_SERVICE_UNAVAILABLE, RESULT_BILLING_UNAVAILABLE, RESULT_ITEM_UNAVAILABLE, RESULT_DEVELOPER_ERROR, RESULT_ERROR; // Converts from an ordinal value to the ResponseCode public static ResponseCode valueOf(int index) { ResponseCode[] values = ResponseCode.values(); if (index < 0 || index >= values.length) { return RESULT_ERROR; } return values[index]; } } // The possible states of an in-app purchase, as defined by Android Market. public enum PurchaseState { // Responses to requestPurchase or restoreTransactions. PURCHASED, // User was charged for the order. CANCELED, // The charge failed on the server. REFUNDED; // User received a refund for the order. // Converts from an ordinal value to the PurchaseState public static PurchaseState valueOf(int index) { PurchaseState[] values = PurchaseState.values(); if (index < 0 || index >= values.length) { return CANCELED; } return values[index]; } } /** This is the action we use to bind to the MarketBillingService. */ public static final String MARKET_BILLING_SERVICE_ACTION = "com.android.vending.billing.MarketBillingService.BIND"; // Intent actions that we send from the BillingReceiver to the // BillingService. Defined by this application. public static final String ACTION_CONFIRM_NOTIFICATION = "com.example.dungeons.CONFIRM_NOTIFICATION"; public static final String ACTION_GET_PURCHASE_INFORMATION = "com.example.dungeons.GET_PURCHASE_INFORMATION"; public static final String ACTION_RESTORE_TRANSACTIONS = "com.example.dungeons.RESTORE_TRANSACTIONS"; // Intent actions that we receive in the BillingReceiver from Market. // These are defined by Market and cannot be changed. public static final String ACTION_NOTIFY = "com.android.vending.billing.IN_APP_NOTIFY"; public static final String ACTION_RESPONSE_CODE = "com.android.vending.billing.RESPONSE_CODE"; public static final String ACTION_PURCHASE_STATE_CHANGED = "com.android.vending.billing.PURCHASE_STATE_CHANGED"; // These are the names of the extras that are passed in an intent from // Market to this application and cannot be changed. public static final String NOTIFICATION_ID = "notification_id"; public static final String INAPP_SIGNED_DATA = "inapp_signed_data"; public static final String INAPP_SIGNATURE = "inapp_signature"; public static final String INAPP_REQUEST_ID = "request_id"; public static final String INAPP_RESPONSE_CODE = "response_code"; // These are the names of the fields in the request bundle. public static final String BILLING_REQUEST_METHOD = "BILLING_REQUEST"; public static final String BILLING_REQUEST_API_VERSION = "API_VERSION"; public static final String BILLING_REQUEST_PACKAGE_NAME = "PACKAGE_NAME"; public static final String BILLING_REQUEST_ITEM_ID = "ITEM_ID"; public static final String BILLING_REQUEST_DEVELOPER_PAYLOAD = "DEVELOPER_PAYLOAD"; public static final String BILLING_REQUEST_NOTIFY_IDS = "NOTIFY_IDS"; public static final String BILLING_REQUEST_NONCE = "NONCE"; public static final String BILLING_RESPONSE_RESPONSE_CODE = "RESPONSE_CODE"; public static final String BILLING_RESPONSE_PURCHASE_INTENT = "PURCHASE_INTENT"; public static final String BILLING_RESPONSE_REQUEST_ID = "REQUEST_ID"; public static long BILLING_RESPONSE_INVALID_REQUEST_ID = -1; public static final boolean DEBUG = false; }
0vishalvijay0-v4
v2/src/com/example/dungeons/Consts.java
Java
asf20
4,668
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dungeons; import com.android.vending.billing.IMarketBillingService; import com.example.dungeons.Consts.PurchaseState; import com.example.dungeons.Consts.ResponseCode; import com.example.dungeons.Security.VerifiedPurchase; import android.app.PendingIntent; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; /** * This class sends messages to Android Market on behalf of the application by * connecting (binding) to the MarketBillingService. The application * creates an instance of this class and invokes billing requests through this service. * * The {@link BillingReceiver} class starts this service to process commands * that it receives from Android Market. * * You should modify and obfuscate this code before using it. */ public class BillingService extends Service implements ServiceConnection { private static final String TAG = "BillingService"; /** The service connection to the remote MarketBillingService. */ private static IMarketBillingService mService; /** * The list of requests that are pending while we are waiting for the * connection to the MarketBillingService to be established. */ private static LinkedList<BillingRequest> mPendingRequests = new LinkedList<BillingRequest>(); /** * The list of requests that we have sent to Android Market but for which we have * not yet received a response code. The HashMap is indexed by the * request Id that each request receives when it executes. */ private static HashMap<Long, BillingRequest> mSentRequests = new HashMap<Long, BillingRequest>(); /** * The base class for all requests that use the MarketBillingService. * Each derived class overrides the run() method to call the appropriate * service interface. If we are already connected to the MarketBillingService, * then we call the run() method directly. Otherwise, we bind * to the service and save the request on a queue to be run later when * the service is connected. */ abstract class BillingRequest { private final int mStartId; protected long mRequestId; public BillingRequest(int startId) { mStartId = startId; } public int getStartId() { return mStartId; } /** * Run the request, starting the connection if necessary. * @return true if the request was executed or queued; false if there * was an error starting the connection */ public boolean runRequest() { if (runIfConnected()) { return true; } if (bindToMarketBillingService()) { // Add a pending request to run when the service is connected. mPendingRequests.add(this); return true; } return false; } /** * Try running the request directly if the service is already connected. * @return true if the request ran successfully; false if the service * is not connected or there was an error when trying to use it */ public boolean runIfConnected() { if (Consts.DEBUG) { Log.d(TAG, getClass().getSimpleName()); } if (mService != null) { try { mRequestId = run(); if (Consts.DEBUG) { Log.d(TAG, "request id: " + mRequestId); } if (mRequestId >= 0) { mSentRequests.put(mRequestId, this); } return true; } catch (RemoteException e) { onRemoteException(e); } } return false; } /** * Called when a remote exception occurs while trying to execute the * {@link #run()} method. The derived class can override this to * execute exception-handling code. * @param e the exception */ protected void onRemoteException(RemoteException e) { Log.w(TAG, "remote billing service crashed"); mService = null; } /** * The derived class must implement this method. * @throws RemoteException */ abstract protected long run() throws RemoteException; /** * This is called when Android Market sends a response code for this * request. * @param responseCode the response code */ protected void responseCodeReceived(ResponseCode responseCode) { } protected Bundle makeRequestBundle(String method) { Bundle request = new Bundle(); request.putString(Consts.BILLING_REQUEST_METHOD, method); request.putInt(Consts.BILLING_REQUEST_API_VERSION, 1); request.putString(Consts.BILLING_REQUEST_PACKAGE_NAME, getPackageName()); return request; } protected void logResponseCode(String method, Bundle response) { ResponseCode responseCode = ResponseCode.valueOf( response.getInt(Consts.BILLING_RESPONSE_RESPONSE_CODE)); if (Consts.DEBUG) { Log.e(TAG, method + " received " + responseCode.toString()); } } } /** * Wrapper class that checks if in-app billing is supported. */ class CheckBillingSupported extends BillingRequest { public CheckBillingSupported() { // This object is never created as a side effect of starting this // service so we pass -1 as the startId to indicate that we should // not stop this service after executing this request. super(-1); } @Override protected long run() throws RemoteException { Bundle request = makeRequestBundle("CHECK_BILLING_SUPPORTED"); Bundle response = mService.sendBillingRequest(request); int responseCode = response.containsKey(Consts.BILLING_RESPONSE_RESPONSE_CODE) ? response.getInt(Consts.BILLING_RESPONSE_RESPONSE_CODE) : ResponseCode.RESULT_BILLING_UNAVAILABLE.ordinal(); if (Consts.DEBUG) { Log.i(TAG, "CheckBillingSupported response code: " + ResponseCode.valueOf(responseCode)); } boolean billingSupported = (responseCode == ResponseCode.RESULT_OK.ordinal()); ResponseHandler.checkBillingSupportedResponse(billingSupported); return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID; } } /** * Wrapper class that requests a purchase. */ class RequestPurchase extends BillingRequest { public final String mProductId; public final String mDeveloperPayload; public RequestPurchase(String itemId) { this(itemId, null); } public RequestPurchase(String itemId, String developerPayload) { // This object is never created as a side effect of starting this // service so we pass -1 as the startId to indicate that we should // not stop this service after executing this request. super(-1); mProductId = itemId; mDeveloperPayload = developerPayload; } @Override protected long run() throws RemoteException { Bundle request = makeRequestBundle("REQUEST_PURCHASE"); request.putString(Consts.BILLING_REQUEST_ITEM_ID, mProductId); // Note that the developer payload is optional. if (mDeveloperPayload != null) { request.putString(Consts.BILLING_REQUEST_DEVELOPER_PAYLOAD, mDeveloperPayload); } Bundle response = mService.sendBillingRequest(request); PendingIntent pendingIntent = response.getParcelable(Consts.BILLING_RESPONSE_PURCHASE_INTENT); if (pendingIntent == null) { Log.e(TAG, "Error with requestPurchase"); return Consts.BILLING_RESPONSE_INVALID_REQUEST_ID; } Intent intent = new Intent(); ResponseHandler.buyPageIntentResponse(pendingIntent, intent); return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID); } @Override protected void responseCodeReceived(ResponseCode responseCode) { ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode); } } /** * Wrapper class that confirms a list of notifications to the server. */ class ConfirmNotifications extends BillingRequest { final String[] mNotifyIds; public ConfirmNotifications(int startId, String[] notifyIds) { super(startId); mNotifyIds = notifyIds; } @Override protected long run() throws RemoteException { Bundle request = makeRequestBundle("CONFIRM_NOTIFICATIONS"); request.putStringArray(Consts.BILLING_REQUEST_NOTIFY_IDS, mNotifyIds); Bundle response = mService.sendBillingRequest(request); logResponseCode("confirmNotifications", response); return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID); } } /** * Wrapper class that sends a GET_PURCHASE_INFORMATION message to the server. */ class GetPurchaseInformation extends BillingRequest { long mNonce; final String[] mNotifyIds; public GetPurchaseInformation(int startId, String[] notifyIds) { super(startId); mNotifyIds = notifyIds; } @Override protected long run() throws RemoteException { mNonce = Security.generateNonce(); Bundle request = makeRequestBundle("GET_PURCHASE_INFORMATION"); request.putLong(Consts.BILLING_REQUEST_NONCE, mNonce); request.putStringArray(Consts.BILLING_REQUEST_NOTIFY_IDS, mNotifyIds); Bundle response = mService.sendBillingRequest(request); logResponseCode("getPurchaseInformation", response); return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID); } @Override protected void onRemoteException(RemoteException e) { super.onRemoteException(e); Security.removeNonce(mNonce); } } /** * Wrapper class that sends a RESTORE_TRANSACTIONS message to the server. */ class RestoreTransactions extends BillingRequest { long mNonce; public RestoreTransactions() { // This object is never created as a side effect of starting this // service so we pass -1 as the startId to indicate that we should // not stop this service after executing this request. super(-1); } @Override protected long run() throws RemoteException { mNonce = Security.generateNonce(); Bundle request = makeRequestBundle("RESTORE_TRANSACTIONS"); request.putLong(Consts.BILLING_REQUEST_NONCE, mNonce); Bundle response = mService.sendBillingRequest(request); logResponseCode("restoreTransactions", response); return response.getLong(Consts.BILLING_RESPONSE_REQUEST_ID, Consts.BILLING_RESPONSE_INVALID_REQUEST_ID); } @Override protected void onRemoteException(RemoteException e) { super.onRemoteException(e); Security.removeNonce(mNonce); } @Override protected void responseCodeReceived(ResponseCode responseCode) { ResponseHandler.responseCodeReceived(BillingService.this, this, responseCode); } } public BillingService() { super(); } public void setContext(Context context) { attachBaseContext(context); } /** * We don't support binding to this service, only starting the service. */ @Override public IBinder onBind(Intent intent) { return null; } @Override public void onStart(Intent intent, int startId) { handleCommand(intent, startId); } // Overrides onStartCommand for people who build on SDK versions > 4. // Override annotation is commented out as the method does not always exist. // @Override public int onStartCommand(Intent intent, int flags, int startId) { if (intent == null) { stopSelfResult(startId); return; } handleCommand(intent, startId); return 0; // Service.START_STICKY_COMPATIBILITY } /** * The {@link BillingReceiver} sends messages to this service using intents. * Each intent has an action and some extra arguments specific to that action. * @param intent the intent containing one of the supported actions * @param startId an identifier for the invocation instance of this service */ public void handleCommand(Intent intent, int startId) { String action = intent.getAction(); if (Consts.DEBUG) { Log.i(TAG, "handleCommand() action: " + action); } if (Consts.ACTION_CONFIRM_NOTIFICATION.equals(action)) { String[] notifyIds = intent.getStringArrayExtra(Consts.NOTIFICATION_ID); confirmNotifications(startId, notifyIds); } else if (Consts.ACTION_GET_PURCHASE_INFORMATION.equals(action)) { String notifyId = intent.getStringExtra(Consts.NOTIFICATION_ID); getPurchaseInformation(startId, new String[] { notifyId }); } else if (Consts.ACTION_PURCHASE_STATE_CHANGED.equals(action)) { String signedData = intent.getStringExtra(Consts.INAPP_SIGNED_DATA); String signature = intent.getStringExtra(Consts.INAPP_SIGNATURE); purchaseStateChanged(startId, signedData, signature); } else if (Consts.ACTION_RESPONSE_CODE.equals(action)) { long requestId = intent.getLongExtra(Consts.INAPP_REQUEST_ID, -1); int responseCodeIndex = intent.getIntExtra(Consts.INAPP_RESPONSE_CODE, ResponseCode.RESULT_ERROR.ordinal()); ResponseCode responseCode = ResponseCode.valueOf(responseCodeIndex); checkResponseCode(requestId, responseCode); } } /** * Binds to the MarketBillingService and returns true if the bind * succeeded. * @return true if the bind succeeded; false otherwise */ private boolean bindToMarketBillingService() { try { if (Consts.DEBUG) { Log.i(TAG, "binding to Market billing service"); } boolean bindResult = bindService( new Intent(Consts.MARKET_BILLING_SERVICE_ACTION), this, // ServiceConnection. Context.BIND_AUTO_CREATE); if (bindResult) { return true; } else { Log.e(TAG, "Could not bind to service."); } } catch (SecurityException e) { Log.e(TAG, "Security exception: " + e); } return false; } /** * Checks if in-app billing is supported. The result is asynchronously returned to the * application via ResponseHandler.checkBillingSupported. * @return false if there was an error connecting to Android Market */ public boolean checkBillingSupported() { return new CheckBillingSupported().runRequest(); } /** * Requests that the given item be offered to the user for purchase. When * the purchase succeeds (or is canceled) the {@link BillingReceiver} * receives an intent with the action {@link Consts#ACTION_NOTIFY}. * Returns false if there was an error trying to connect to Android Market. * @param productId an identifier for the item being offered for purchase * @param developerPayload a payload that is associated with a given * purchase, if null, no payload is sent * @return false if there was an error connecting to Android Market */ public boolean requestPurchase(String productId, String developerPayload) { return new RequestPurchase(productId, developerPayload).runRequest(); } /** * Requests transaction information for all managed items. Call this only when the * application is first installed or after a database wipe. Do NOT call this * every time the application starts up. * @return false if there was an error connecting to Android Market */ public boolean restoreTransactions() { return new RestoreTransactions().runRequest(); } /** * Confirms receipt of a purchase state change. Each {@code notifyId} is * an opaque identifier that came from the server. This method sends those * identifiers back to the MarketBillingService, which ACKs them to the * server. Returns false if there was an error trying to connect to the * MarketBillingService. * @param startId an identifier for the invocation instance of this service * @param notifyIds a list of opaque identifiers associated with purchase * state changes. * @return false if there was an error connecting to Market */ private boolean confirmNotifications(int startId, String[] notifyIds) { return new ConfirmNotifications(startId, notifyIds).runRequest(); } /** * Gets the purchase information. This message includes a list of * notification IDs sent to us by Android Market, which we include in * our request. The server responds with the purchase information, * encoded as a JSON string, and sends that to the {@link BillingReceiver} * in an intent with the action {@link Consts#ACTION_PURCHASE_STATE_CHANGED}. * Returns false if there was an error trying to connect to the MarketBillingService. * * @param startId an identifier for the invocation instance of this service * @param notifyIds a list of opaque identifiers associated with purchase * state changes * @return false if there was an error connecting to Android Market */ private boolean getPurchaseInformation(int startId, String[] notifyIds) { return new GetPurchaseInformation(startId, notifyIds).runRequest(); } /** * Verifies that the data was signed with the given signature, and calls * {@link ResponseHandler#purchaseResponse(Context, PurchaseState, String, String, long)} * for each verified purchase. * @param startId an identifier for the invocation instance of this service * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key */ private void purchaseStateChanged(int startId, String signedData, String signature) { ArrayList<Security.VerifiedPurchase> purchases; purchases = Security.verifyPurchase(signedData, signature); if (purchases == null) { return; } ArrayList<String> notifyList = new ArrayList<String>(); for (VerifiedPurchase vp : purchases) { if (vp.notificationId != null) { notifyList.add(vp.notificationId); } ResponseHandler.purchaseResponse(this, vp.purchaseState, vp.productId, vp.orderId, vp.purchaseTime, vp.developerPayload); } if (!notifyList.isEmpty()) { String[] notifyIds = notifyList.toArray(new String[notifyList.size()]); confirmNotifications(startId, notifyIds); } } /** * This is called when we receive a response code from Android Market for a request * that we made. This is used for reporting various errors and for * acknowledging that an order was sent to the server. This is NOT used * for any purchase state changes. All purchase state changes are received * in the {@link BillingReceiver} and passed to this service, where they are * handled in {@link #purchaseStateChanged(int, String, String)}. * @param requestId a number that identifies a request, assigned at the * time the request was made to Android Market * @param responseCode a response code from Android Market to indicate the state * of the request */ private void checkResponseCode(long requestId, ResponseCode responseCode) { BillingRequest request = mSentRequests.get(requestId); if (request != null) { if (Consts.DEBUG) { Log.d(TAG, request.getClass().getSimpleName() + ": " + responseCode); } request.responseCodeReceived(responseCode); } mSentRequests.remove(requestId); } /** * Runs any pending requests that are waiting for a connection to the * service to be established. This runs in the main UI thread. */ private void runPendingRequests() { int maxStartId = -1; BillingRequest request; while ((request = mPendingRequests.peek()) != null) { if (request.runIfConnected()) { // Remove the request mPendingRequests.remove(); // Remember the largest startId, which is the most recent // request to start this service. if (maxStartId < request.getStartId()) { maxStartId = request.getStartId(); } } else { // The service crashed, so restart it. Note that this leaves // the current request on the queue. bindToMarketBillingService(); return; } } // If we get here then all the requests ran successfully. If maxStartId // is not -1, then one of the requests started the service, so we can // stop it now. if (maxStartId >= 0) { if (Consts.DEBUG) { Log.i(TAG, "stopping service, startId: " + maxStartId); } stopSelf(maxStartId); } } /** * This is called when we are connected to the MarketBillingService. * This runs in the main UI thread. */ public void onServiceConnected(ComponentName name, IBinder service) { if (Consts.DEBUG) { Log.d(TAG, "Billing service connected"); } mService = IMarketBillingService.Stub.asInterface(service); runPendingRequests(); } /** * This is called when we are disconnected from the MarketBillingService. */ public void onServiceDisconnected(ComponentName name) { Log.w(TAG, "Billing service disconnected"); mService = null; } /** * Unbinds from the MarketBillingService. Call this when the application * terminates to avoid leaking a ServiceConnection. */ public void unbind() { try { unbindService(this); } catch (IllegalArgumentException e) { // This might happen if the service was disconnected } } }
0vishalvijay0-v4
v2/src/com/example/dungeons/BillingService.java
Java
asf20
24,386
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dungeons; import com.example.dungeons.Consts.PurchaseState; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; /** * An example database that records the state of each purchase. You should use * an obfuscator before storing any information to persistent storage. The * obfuscator should use a key that is specific to the device and/or user. * Otherwise an attacker could copy a database full of valid purchases and * distribute it to others. */ public class PurchaseDatabase { private static final String TAG = "PurchaseDatabase"; private static final String DATABASE_NAME = "purchase.db"; private static final int DATABASE_VERSION = 1; private static final String PURCHASE_HISTORY_TABLE_NAME = "history"; private static final String PURCHASED_ITEMS_TABLE_NAME = "purchased"; // These are the column names for the purchase history table. We need a // column named "_id" if we want to use a CursorAdapter. The primary key is // the orderId so that we can be robust against getting multiple messages // from the server for the same purchase. static final String HISTORY_ORDER_ID_COL = "_id"; static final String HISTORY_STATE_COL = "state"; static final String HISTORY_PRODUCT_ID_COL = "productId"; static final String HISTORY_PURCHASE_TIME_COL = "purchaseTime"; static final String HISTORY_DEVELOPER_PAYLOAD_COL = "developerPayload"; private static final String[] HISTORY_COLUMNS = { HISTORY_ORDER_ID_COL, HISTORY_PRODUCT_ID_COL, HISTORY_STATE_COL, HISTORY_PURCHASE_TIME_COL, HISTORY_DEVELOPER_PAYLOAD_COL }; // These are the column names for the "purchased items" table. static final String PURCHASED_PRODUCT_ID_COL = "_id"; static final String PURCHASED_QUANTITY_COL = "quantity"; private static final String[] PURCHASED_COLUMNS = { PURCHASED_PRODUCT_ID_COL, PURCHASED_QUANTITY_COL }; private SQLiteDatabase mDb; private DatabaseHelper mDatabaseHelper; public PurchaseDatabase(Context context) { mDatabaseHelper = new DatabaseHelper(context); mDb = mDatabaseHelper.getWritableDatabase(); } public void close() { mDatabaseHelper.close(); } /** * Inserts a purchased product into the database. There may be multiple * rows in the table for the same product if it was purchased multiple times * or if it was refunded. * @param orderId the order ID (matches the value in the product list) * @param productId the product ID (sku) * @param state the state of the purchase * @param purchaseTime the purchase time (in milliseconds since the epoch) * @param developerPayload the developer provided "payload" associated with * the order. */ private void insertOrder(String orderId, String productId, PurchaseState state, long purchaseTime, String developerPayload) { ContentValues values = new ContentValues(); values.put(HISTORY_ORDER_ID_COL, orderId); values.put(HISTORY_PRODUCT_ID_COL, productId); values.put(HISTORY_STATE_COL, state.ordinal()); values.put(HISTORY_PURCHASE_TIME_COL, purchaseTime); values.put(HISTORY_DEVELOPER_PAYLOAD_COL, developerPayload); mDb.replace(PURCHASE_HISTORY_TABLE_NAME, null /* nullColumnHack */, values); } /** * Updates the quantity of the given product to the given value. If the * given value is zero, then the product is removed from the table. * @param productId the product to update * @param quantity the number of times the product has been purchased */ private void updatePurchasedItem(String productId, int quantity) { if (quantity == 0) { mDb.delete(PURCHASED_ITEMS_TABLE_NAME, PURCHASED_PRODUCT_ID_COL + "=?", new String[] { productId }); return; } ContentValues values = new ContentValues(); values.put(PURCHASED_PRODUCT_ID_COL, productId); values.put(PURCHASED_QUANTITY_COL, quantity); mDb.replace(PURCHASED_ITEMS_TABLE_NAME, null /* nullColumnHack */, values); } /** * Adds the given purchase information to the database and returns the total * number of times that the given product has been purchased. * @param orderId a string identifying the order * @param productId the product ID (sku) * @param purchaseState the purchase state of the product * @param purchaseTime the time the product was purchased, in milliseconds * since the epoch (Jan 1, 1970) * @param developerPayload the developer provided "payload" associated with * the order * @return the number of times the given product has been purchased. */ public synchronized int updatePurchase(String orderId, String productId, PurchaseState purchaseState, long purchaseTime, String developerPayload) { insertOrder(orderId, productId, purchaseState, purchaseTime, developerPayload); Cursor cursor = mDb.query(PURCHASE_HISTORY_TABLE_NAME, HISTORY_COLUMNS, HISTORY_PRODUCT_ID_COL + "=?", new String[] { productId }, null, null, null, null); if (cursor == null) { return 0; } int quantity = 0; try { // Count the number of times the product was purchased while (cursor.moveToNext()) { int stateIndex = cursor.getInt(2); PurchaseState state = PurchaseState.valueOf(stateIndex); // Note that a refunded purchase is treated as a purchase. Such // a friendly refund policy is nice for the user. if (state == PurchaseState.PURCHASED || state == PurchaseState.REFUNDED) { quantity += 1; } } // Update the "purchased items" table updatePurchasedItem(productId, quantity); } finally { if (cursor != null) { cursor.close(); } } return quantity; } /** * Returns a cursor that can be used to read all the rows and columns of * the "purchased items" table. */ public Cursor queryAllPurchasedItems() { return mDb.query(PURCHASED_ITEMS_TABLE_NAME, PURCHASED_COLUMNS, null, null, null, null, null); } /** * This is a standard helper class for constructing the database. */ private class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { createPurchaseTable(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Production-quality upgrade code should modify the tables when // the database version changes instead of dropping the tables and // re-creating them. if (newVersion != DATABASE_VERSION) { Log.w(TAG, "Database upgrade from old: " + oldVersion + " to: " + newVersion); db.execSQL("DROP TABLE IF EXISTS " + PURCHASE_HISTORY_TABLE_NAME); db.execSQL("DROP TABLE IF EXISTS " + PURCHASED_ITEMS_TABLE_NAME); createPurchaseTable(db); return; } } private void createPurchaseTable(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + PURCHASE_HISTORY_TABLE_NAME + "(" + HISTORY_ORDER_ID_COL + " TEXT PRIMARY KEY, " + HISTORY_STATE_COL + " INTEGER, " + HISTORY_PRODUCT_ID_COL + " TEXT, " + HISTORY_DEVELOPER_PAYLOAD_COL + " TEXT, " + HISTORY_PURCHASE_TIME_COL + " INTEGER)"); db.execSQL("CREATE TABLE " + PURCHASED_ITEMS_TABLE_NAME + "(" + PURCHASED_PRODUCT_ID_COL + " TEXT PRIMARY KEY, " + PURCHASED_QUANTITY_COL + " INTEGER)"); } } }
0vishalvijay0-v4
v2/src/com/example/dungeons/PurchaseDatabase.java
Java
asf20
8,953
// Copyright 2002, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.dungeons.util; /** * Exception thrown when encountering an invalid Base64 input character. * * @author nelson */ public class Base64DecoderException extends Exception { public Base64DecoderException() { super(); } public Base64DecoderException(String s) { super(s); } private static final long serialVersionUID = 1L; }
0vishalvijay0-v4
v2/src/com/example/dungeons/util/Base64DecoderException.java
Java
asf20
955
// Portions copyright 2002, Google, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.example.dungeons.util; // This code was converted from code at http://iharder.sourceforge.net/base64/ // Lots of extraneous features were removed. /* The original code said: * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit * <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rharder@usa.net * @version 1.3 */ /** * Base64 converter class. This code is not a complete MIME encoder; * it simply converts binary data to base64 data and back. * * <p>Note {@link CharBase64} is a GWT-compatible implementation of this * class. */ public class Base64 { /** Specify encoding (value is {@code true}). */ public final static boolean ENCODE = true; /** Specify decoding (value is {@code false}). */ public final static boolean DECODE = false; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte) '='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte) '\n'; /** * The 64 valid Base64 values. */ private final static byte[] ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/'}; /** * The 64 valid web safe Base64 values. */ private final static byte[] WEBSAFE_ALPHABET = {(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_'}; /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; /** The web safe decodabet */ private final static byte[] WEBSAFE_DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44 62, // Dash '-' sign at decimal 45 -9, -9, // Decimal 46-47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, // Decimal 91-94 63, // Underscore '_' at decimal 95 -9, // Decimal 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, -9 // Decimal 123 - 127 /* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // Indicates white space in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates equals sign in encoding private final static byte EQUALS_SIGN_ENC = -1; /** Defeats instantiation. */ private Base64() { } /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param alphabet is the encoding alphabet * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4(byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index alphabet // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0) | (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0) | (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0); switch (numSigBytes) { case 3: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = alphabet[(inBuff) & 0x3f]; return destination; case 2: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f]; destination[destOffset + 3] = EQUALS_SIGN; return destination; case 1: destination[destOffset] = alphabet[(inBuff >>> 18)]; destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f]; destination[destOffset + 2] = EQUALS_SIGN; destination[destOffset + 3] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Encodes a byte array into Base64 notation. * Equivalent to calling * {@code encodeBytes(source, 0, source.length)} * * @param source The data to convert * @since 1.4 */ public static String encode(byte[] source) { return encode(source, 0, source.length, ALPHABET, true); } /** * Encodes a byte array into web safe Base64 notation. * * @param source The data to convert * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries */ public static String encodeWebSafe(byte[] source, boolean doPadding) { return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet the encoding alphabet * @param doPadding is {@code true} to pad result with '=' chars * if it does not fall on 3 byte boundaries * @since 1.4 */ public static String encode(byte[] source, int off, int len, byte[] alphabet, boolean doPadding) { byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE); int outLen = outBuff.length; // If doPadding is false, set length to truncate '=' // padding characters while (doPadding == false && outLen > 0) { if (outBuff[outLen - 1] != '=') { break; } outLen -= 1; } return new String(outBuff, 0, outLen); } /** * Encodes a byte array into Base64 notation. * * @param source the data to convert * @param off offset in array where conversion should begin * @param len length of data to convert * @param alphabet is the encoding alphabet * @param maxLineLength maximum length of one line. * @return the BASE64-encoded byte array */ public static byte[] encode(byte[] source, int off, int len, byte[] alphabet, int maxLineLength) { int lenDiv3 = (len + 2) / 3; // ceil(len / 3) int len43 = lenDiv3 * 4; byte[] outBuff = new byte[len43 // Main 4:3 + (len43 / maxLineLength)]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d += 3, e += 4) { // The following block of code is the same as // encode3to4( source, d + off, 3, outBuff, e, alphabet ); // but inlined for faster encoding (~20% improvement) int inBuff = ((source[d + off] << 24) >>> 8) | ((source[d + 1 + off] << 24) >>> 16) | ((source[d + 2 + off] << 24) >>> 24); outBuff[e] = alphabet[(inBuff >>> 18)]; outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f]; outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f]; outBuff[e + 3] = alphabet[(inBuff) & 0x3f]; lineLength += 4; if (lineLength == maxLineLength) { outBuff[e + 4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // end for: each piece of array if (d < len) { encode3to4(source, d + off, len - d, outBuff, e, alphabet); lineLength += 4; if (lineLength == maxLineLength) { // Add a last newline outBuff[e + 4] = NEW_LINE; e++; } e += 4; } assert (e == outBuff.length); return outBuff; } /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accommodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @param decodabet the decodabet for decoding Base64 content * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3(byte[] source, int srcOffset, byte[] destination, int destOffset, byte[] decodabet) { // Example: Dk== if (source[srcOffset + 2] == EQUALS_SIGN) { int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12); destination[destOffset] = (byte) (outBuff >>> 16); return 1; } else if (source[srcOffset + 3] == EQUALS_SIGN) { // Example: DkL= int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18); destination[destOffset] = (byte) (outBuff >>> 16); destination[destOffset + 1] = (byte) (outBuff >>> 8); return 2; } else { // Example: DkLE int outBuff = ((decodabet[source[srcOffset]] << 24) >>> 6) | ((decodabet[source[srcOffset + 1]] << 24) >>> 12) | ((decodabet[source[srcOffset + 2]] << 24) >>> 18) | ((decodabet[source[srcOffset + 3]] << 24) >>> 24); destination[destOffset] = (byte) (outBuff >> 16); destination[destOffset + 1] = (byte) (outBuff >> 8); destination[destOffset + 2] = (byte) (outBuff); return 3; } } // end decodeToBytes /** * Decodes data from Base64 notation. * * @param s the string to decode (decoded in default encoding) * @return the decoded data * @since 1.4 */ public static byte[] decode(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decode(bytes, 0, bytes.length); } /** * Decodes data from web safe Base64 notation. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param s the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(String s) throws Base64DecoderException { byte[] bytes = s.getBytes(); return decodeWebSafe(bytes, 0, bytes.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source The Base64 encoded data * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source) throws Base64DecoderException { return decode(source, 0, source.length); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded data. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the string to decode (decoded in default encoding) * @return the decoded data */ public static byte[] decodeWebSafe(byte[] source) throws Base64DecoderException { return decodeWebSafe(source, 0, source.length); } /** * Decodes Base64 content in byte array format and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data * @since 1.3 * @throws Base64DecoderException */ public static byte[] decode(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, DECODABET); } /** * Decodes web safe Base64 content in byte array format and returns * the decoded byte array. * Web safe encoding uses '-' instead of '+', '_' instead of '/' * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @return decoded data */ public static byte[] decodeWebSafe(byte[] source, int off, int len) throws Base64DecoderException { return decode(source, off, len, WEBSAFE_DECODABET); } /** * Decodes Base64 content using the supplied decodabet and returns * the decoded byte array. * * @param source the Base64 encoded data * @param off the offset of where to begin decoding * @param len the length of characters to decode * @param decodabet the decodabet for decoding Base64 content * @return decoded data */ public static byte[] decode(byte[] source, int off, int len, byte[] decodabet) throws Base64DecoderException { int len34 = len * 3 / 4; byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = 0; i < len; i++) { sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits sbiDecode = decodabet[sbiCrop]; if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better if (sbiDecode >= EQUALS_SIGN_ENC) { // An equals sign (for padding) must not occur at position 0 or 1 // and must be the last byte[s] in the encoded value if (sbiCrop == EQUALS_SIGN) { int bytesLeft = len - i; byte lastByte = (byte) (source[len - 1 + off] & 0x7f); if (b4Posn == 0 || b4Posn == 1) { throw new Base64DecoderException( "invalid padding byte '=' at byte offset " + i); } else if ((b4Posn == 3 && bytesLeft > 2) || (b4Posn == 4 && bytesLeft > 1)) { throw new Base64DecoderException( "padding byte '=' falsely signals end of encoded value " + "at offset " + i); } else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) { throw new Base64DecoderException( "encoded value has invalid trailing byte"); } break; } b4[b4Posn++] = sbiCrop; if (b4Posn == 4) { outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); b4Posn = 0; } } } else { throw new Base64DecoderException("Bad Base64 input character at " + i + ": " + source[i + off] + "(decimal)"); } } // Because web safe encoding allows non padding base64 encodes, we // need to pad the rest of the b4 buffer with equal signs when // b4Posn != 0. There can be at most 2 equal signs at the end of // four characters, so the b4 buffer must have two or three // characters. This also catches the case where the input is // padded with EQUALS_SIGN if (b4Posn != 0) { if (b4Posn == 1) { throw new Base64DecoderException("single trailing character at offset " + (len - 1)); } b4[b4Posn++] = EQUALS_SIGN; outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet); } byte[] out = new byte[outBuffPosn]; System.arraycopy(outBuff, 0, out, 0, outBuffPosn); return out; } }
0vishalvijay0-v4
v2/src/com/example/dungeons/util/Base64.java
Java
asf20
22,622
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dungeons; import com.example.dungeons.BillingService.RequestPurchase; import com.example.dungeons.BillingService.RestoreTransactions; import com.example.dungeons.Consts.PurchaseState; import com.example.dungeons.Consts.ResponseCode; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.util.Log; /** * This class contains the methods that handle responses from Android Market. The * implementation of these methods is specific to a particular application. * The methods in this example update the database and, if the main application * has registered a {@llink PurchaseObserver}, will also update the UI. An * application might also want to forward some responses on to its own server, * and that could be done here (in a background thread) but this example does * not do that. * * You should modify and obfuscate this code before using it. */ public class ResponseHandler { private static final String TAG = "ResponseHandler"; /** * This is a static instance of {@link PurchaseObserver} that the * application creates and registers with this class. The PurchaseObserver * is used for updating the UI if the UI is visible. */ private static PurchaseObserver sPurchaseObserver; /** * Registers an observer that updates the UI. * @param observer the observer to register */ public static synchronized void register(PurchaseObserver observer) { sPurchaseObserver = observer; } /** * Unregisters a previously registered observer. * @param observer the previously registered observer. */ public static synchronized void unregister(PurchaseObserver observer) { sPurchaseObserver = null; } /** * Notifies the application of the availability of the MarketBillingService. * This method is called in response to the application calling * {@link BillingService#checkBillingSupported()}. * @param supported true if in-app billing is supported. */ public static void checkBillingSupportedResponse(boolean supported) { if (sPurchaseObserver != null) { sPurchaseObserver.onBillingSupported(supported); } } /** * Starts a new activity for the user to buy an item for sale. This method * forwards the intent on to the PurchaseObserver (if it exists) because * we need to start the activity on the activity stack of the application. * * @param pendingIntent a PendingIntent that we received from Android Market that * will create the new buy page activity * @param intent an intent containing a request id in an extra field that * will be passed to the buy page activity when it is created */ public static void buyPageIntentResponse(PendingIntent pendingIntent, Intent intent) { if (sPurchaseObserver == null) { if (Consts.DEBUG) { Log.d(TAG, "UI is not running"); } return; } sPurchaseObserver.startBuyPageActivity(pendingIntent, intent); } /** * Notifies the application of purchase state changes. The application * can offer an item for sale to the user via * {@link BillingService#requestPurchase(String)}. The BillingService * calls this method after it gets the response. Another way this method * can be called is if the user bought something on another device running * this same app. Then Android Market notifies the other devices that * the user has purchased an item, in which case the BillingService will * also call this method. Finally, this method can be called if the item * was refunded. * @param purchaseState the state of the purchase request (PURCHASED, * CANCELED, or REFUNDED) * @param productId a string identifying a product for sale * @param orderId a string identifying the order * @param purchaseTime the time the product was purchased, in milliseconds * since the epoch (Jan 1, 1970) * @param developerPayload the developer provided "payload" associated with * the order */ public static void purchaseResponse( final Context context, final PurchaseState purchaseState, final String productId, final String orderId, final long purchaseTime, final String developerPayload) { // Update the database with the purchase state. We shouldn't do that // from the main thread so we do the work in a background thread. // We don't update the UI here. We will update the UI after we update // the database because we need to read and update the current quantity // first. new Thread(new Runnable() { public void run() { PurchaseDatabase db = new PurchaseDatabase(context); int quantity = db.updatePurchase( orderId, productId, purchaseState, purchaseTime, developerPayload); db.close(); // This needs to be synchronized because the UI thread can change the // value of sPurchaseObserver. synchronized(ResponseHandler.class) { if (sPurchaseObserver != null) { sPurchaseObserver.postPurchaseStateChange( purchaseState, productId, quantity, purchaseTime, developerPayload); } } } }).start(); } /** * This is called when we receive a response code from Android Market for a * RequestPurchase request that we made. This is used for reporting various * errors and also for acknowledging that an order was sent successfully to * the server. This is NOT used for any purchase state changes. All * purchase state changes are received in the {@link BillingReceiver} and * are handled in {@link Security#verifyPurchase(String, String)}. * @param context the context * @param request the RequestPurchase request for which we received a * response code * @param responseCode a response code from Market to indicate the state * of the request */ public static void responseCodeReceived(Context context, RequestPurchase request, ResponseCode responseCode) { if (sPurchaseObserver != null) { sPurchaseObserver.onRequestPurchaseResponse(request, responseCode); } } /** * This is called when we receive a response code from Android Market for a * RestoreTransactions request. * @param context the context * @param request the RestoreTransactions request for which we received a * response code * @param responseCode a response code from Market to indicate the state * of the request */ public static void responseCodeReceived(Context context, RestoreTransactions request, ResponseCode responseCode) { if (sPurchaseObserver != null) { sPurchaseObserver.onRestoreTransactionsResponse(request, responseCode); } } }
0vishalvijay0-v4
v2/src/com/example/dungeons/ResponseHandler.java
Java
asf20
7,794
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dungeons; import com.example.dungeons.Consts.PurchaseState; import com.example.dungeons.util.Base64; import com.example.dungeons.util.Base64DecoderException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.text.TextUtils; import android.util.Log; import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.SecureRandom; import java.security.Signature; import java.security.SignatureException; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.HashSet; /** * Security-related methods. For a secure implementation, all of this code * should be implemented on a server that communicates with the * application on the device. For the sake of simplicity and clarity of this * example, this code is included here and is executed on the device. If you * must verify the purchases on the phone, you should obfuscate this code to * make it harder for an attacker to replace the code with stubs that treat all * purchases as verified. */ public class Security { private static final String TAG = "Security"; private static final String KEY_FACTORY_ALGORITHM = "RSA"; private static final String SIGNATURE_ALGORITHM = "SHA1withRSA"; private static final SecureRandom RANDOM = new SecureRandom(); /** * This keeps track of the nonces that we generated and sent to the * server. We need to keep track of these until we get back the purchase * state and send a confirmation message back to Android Market. If we are * killed and lose this list of nonces, it is not fatal. Android Market will * send us a new "notify" message and we will re-generate a new nonce. * This has to be "static" so that the {@link BillingReceiver} can * check if a nonce exists. */ private static HashSet<Long> sKnownNonces = new HashSet<Long>(); /** * A class to hold the verified purchase information. */ public static class VerifiedPurchase { public PurchaseState purchaseState; public String notificationId; public String productId; public String orderId; public long purchaseTime; public String developerPayload; public VerifiedPurchase(PurchaseState purchaseState, String notificationId, String productId, String orderId, long purchaseTime, String developerPayload) { this.purchaseState = purchaseState; this.notificationId = notificationId; this.productId = productId; this.orderId = orderId; this.purchaseTime = purchaseTime; this.developerPayload = developerPayload; } } /** Generates a nonce (a random number used once). */ public static long generateNonce() { long nonce = RANDOM.nextLong(); sKnownNonces.add(nonce); return nonce; } public static void removeNonce(long nonce) { sKnownNonces.remove(nonce); } public static boolean isNonceKnown(long nonce) { return sKnownNonces.contains(nonce); } /** * Verifies that the data was signed with the given signature, and returns * the list of verified purchases. The data is in JSON format and contains * a nonce (number used once) that we generated and that was signed * (as part of the whole data string) with a private key. The data also * contains the {@link PurchaseState} and product ID of the purchase. * In the general case, there can be an array of purchase transactions * because there may be delays in processing the purchase on the backend * and then several purchases can be batched together. * @param signedData the signed JSON string (signed, not encrypted) * @param signature the signature for the data, signed with the private key */ public static ArrayList<VerifiedPurchase> verifyPurchase(String signedData, String signature) { if (signedData == null) { Log.e(TAG, "data is null"); return null; } if (Consts.DEBUG) { Log.i(TAG, "signedData: " + signedData); } boolean verified = false; if (!TextUtils.isEmpty(signature)) { /** * Compute your public key (that you got from the Android Market publisher site). * * Instead of just storing the entire literal string here embedded in the * program, construct the key at runtime from pieces or * use bit manipulation (for example, XOR with some other string) to hide * the actual key. The key itself is not secret information, but we don't * want to make it easy for an adversary to replace the public key with one * of their own and then fake messages from the server. * * Generally, encryption keys / passwords should only be kept in memory * long enough to perform the operation they need to perform. */ String base64EncodedPublicKey = "CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE"; PublicKey key = Security.generatePublicKey(base64EncodedPublicKey); verified = Security.verify(key, signedData, signature); if (!verified) { Log.w(TAG, "signature does not match data."); return null; } } JSONObject jObject; JSONArray jTransactionsArray = null; int numTransactions = 0; long nonce = 0L; try { jObject = new JSONObject(signedData); // The nonce might be null if the user backed out of the buy page. nonce = jObject.optLong("nonce"); jTransactionsArray = jObject.optJSONArray("orders"); if (jTransactionsArray != null) { numTransactions = jTransactionsArray.length(); } } catch (JSONException e) { return null; } if (!Security.isNonceKnown(nonce)) { Log.w(TAG, "Nonce not found: " + nonce); return null; } ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>(); try { for (int i = 0; i < numTransactions; i++) { JSONObject jElement = jTransactionsArray.getJSONObject(i); int response = jElement.getInt("purchaseState"); PurchaseState purchaseState = PurchaseState.valueOf(response); String productId = jElement.getString("productId"); String packageName = jElement.getString("packageName"); long purchaseTime = jElement.getLong("purchaseTime"); String orderId = jElement.optString("orderId", ""); String notifyId = null; if (jElement.has("notificationId")) { notifyId = jElement.getString("notificationId"); } String developerPayload = jElement.optString("developerPayload", null); // If the purchase state is PURCHASED, then we require a // verified nonce. if (purchaseState == PurchaseState.PURCHASED && !verified) { continue; } purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime, developerPayload)); } } catch (JSONException e) { Log.e(TAG, "JSON exception: ", e); return null; } removeNonce(nonce); return purchases; } /** * Generates a PublicKey instance from a string containing the * Base64-encoded public key. * * @param encodedPublicKey Base64-encoded public key * @throws IllegalArgumentException if encodedPublicKey is invalid */ public static PublicKey generatePublicKey(String encodedPublicKey) { try { byte[] decodedKey = Base64.decode(encodedPublicKey); KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM); return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey)); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } catch (InvalidKeySpecException e) { Log.e(TAG, "Invalid key specification."); throw new IllegalArgumentException(e); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); throw new IllegalArgumentException(e); } } /** * Verifies that the signature from the server matches the computed * signature on the data. Returns true if the data is correctly signed. * * @param publicKey public key associated with the developer account * @param signedData signed data from server * @param signature server signature * @return true if the data and signature match */ public static boolean verify(PublicKey publicKey, String signedData, String signature) { if (Consts.DEBUG) { Log.i(TAG, "signature: " + signature); } Signature sig; try { sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(signedData.getBytes()); if (!sig.verify(Base64.decode(signature))) { Log.e(TAG, "Signature verification failed."); return false; } return true; } catch (NoSuchAlgorithmException e) { Log.e(TAG, "NoSuchAlgorithmException."); } catch (InvalidKeyException e) { Log.e(TAG, "Invalid key specification."); } catch (SignatureException e) { Log.e(TAG, "Signature exception."); } catch (Base64DecoderException e) { Log.e(TAG, "Base64 decoding failed."); } return false; } }
0vishalvijay0-v4
v2/src/com/example/dungeons/Security.java
Java
asf20
10,764
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dungeons; import com.example.dungeons.BillingService.RequestPurchase; import com.example.dungeons.BillingService.RestoreTransactions; import com.example.dungeons.Consts.PurchaseState; import com.example.dungeons.Consts.ResponseCode; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.text.Html; import android.text.Spanned; import android.text.SpannableStringBuilder; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.HashSet; import java.util.Locale; import java.util.Set; /** * A sample application that demonstrates in-app billing. */ public class Dungeons extends Activity implements OnClickListener, OnItemSelectedListener { private static final String TAG = "Dungeons"; /** * Used for storing the log text. */ private static final String LOG_TEXT_KEY = "DUNGEONS_LOG_TEXT"; /** * The SharedPreferences key for recording whether we initialized the * database. If false, then we perform a RestoreTransactions request * to get all the purchases for this user. */ private static final String DB_INITIALIZED = "db_initialized"; private DungeonsPurchaseObserver mDungeonsPurchaseObserver; private Handler mHandler; private BillingService mBillingService; private Button mBuyButton; private Button mEditPayloadButton; private TextView mLogTextView; private Spinner mSelectItemSpinner; private ListView mOwnedItemsTable; private SimpleCursorAdapter mOwnedItemsAdapter; private PurchaseDatabase mPurchaseDatabase; private Cursor mOwnedItemsCursor; private Set<String> mOwnedItems = new HashSet<String>(); /** * The developer payload that is sent with subsequent * purchase requests. */ private String mPayloadContents = null; private static final int DIALOG_CANNOT_CONNECT_ID = 1; private static final int DIALOG_BILLING_NOT_SUPPORTED_ID = 2; /** * Each product in the catalog is either MANAGED or UNMANAGED. MANAGED * means that the product can be purchased only once per user (such as a new * level in a game). The purchase is remembered by Android Market and * can be restored if this application is uninstalled and then * re-installed. UNMANAGED is used for products that can be used up and * purchased multiple times (such as poker chips). It is up to the * application to keep track of UNMANAGED products for the user. */ private enum Managed { MANAGED, UNMANAGED } /** * A {@link PurchaseObserver} is used to get callbacks when Android Market sends * messages to this application so that we can update the UI. */ private class DungeonsPurchaseObserver extends PurchaseObserver { public DungeonsPurchaseObserver(Handler handler) { super(Dungeons.this, handler); } @Override public void onBillingSupported(boolean supported) { if (Consts.DEBUG) { Log.i(TAG, "supported: " + supported); } if (supported) { restoreDatabase(); mBuyButton.setEnabled(true); mEditPayloadButton.setEnabled(true); } else { showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID); } } @Override public void onPurchaseStateChange(PurchaseState purchaseState, String itemId, int quantity, long purchaseTime, String developerPayload) { if (Consts.DEBUG) { Log.i(TAG, "onPurchaseStateChange() itemId: " + itemId + " " + purchaseState); } if (developerPayload == null) { logProductActivity(itemId, purchaseState.toString()); } else { logProductActivity(itemId, purchaseState + "\n\t" + developerPayload); } if (purchaseState == PurchaseState.PURCHASED) { mOwnedItems.add(itemId); } mCatalogAdapter.setOwnedItems(mOwnedItems); mOwnedItemsCursor.requery(); } @Override public void onRequestPurchaseResponse(RequestPurchase request, ResponseCode responseCode) { if (Consts.DEBUG) { Log.d(TAG, request.mProductId + ": " + responseCode); } if (responseCode == ResponseCode.RESULT_OK) { if (Consts.DEBUG) { Log.i(TAG, "purchase was successfully sent to server"); } logProductActivity(request.mProductId, "sending purchase request"); } else if (responseCode == ResponseCode.RESULT_USER_CANCELED) { if (Consts.DEBUG) { Log.i(TAG, "user canceled purchase"); } logProductActivity(request.mProductId, "dismissed purchase dialog"); } else { if (Consts.DEBUG) { Log.i(TAG, "purchase failed"); } logProductActivity(request.mProductId, "request purchase returned " + responseCode); } } @Override public void onRestoreTransactionsResponse(RestoreTransactions request, ResponseCode responseCode) { if (responseCode == ResponseCode.RESULT_OK) { if (Consts.DEBUG) { Log.d(TAG, "completed RestoreTransactions request"); } // Update the shared preferences so that we don't perform // a RestoreTransactions again. SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor edit = prefs.edit(); edit.putBoolean(DB_INITIALIZED, true); edit.commit(); } else { if (Consts.DEBUG) { Log.d(TAG, "RestoreTransactions error: " + responseCode); } } } } private static class CatalogEntry { public String sku; public int nameId; public Managed managed; public CatalogEntry(String sku, int nameId, Managed managed) { this.sku = sku; this.nameId = nameId; this.managed = managed; } } /** An array of product list entries for the products that can be purchased. */ private static final CatalogEntry[] CATALOG = new CatalogEntry[] { new CatalogEntry("sword_001", R.string.two_handed_sword, Managed.MANAGED), new CatalogEntry("potion_001", R.string.potions, Managed.UNMANAGED), new CatalogEntry("android.test.purchased", R.string.android_test_purchased, Managed.UNMANAGED), new CatalogEntry("android.test.canceled", R.string.android_test_canceled, Managed.UNMANAGED), new CatalogEntry("android.test.refunded", R.string.android_test_refunded, Managed.UNMANAGED), new CatalogEntry("android.test.item_unavailable", R.string.android_test_item_unavailable, Managed.UNMANAGED), }; private String mItemName; private String mSku; private CatalogAdapter mCatalogAdapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mHandler = new Handler(); mDungeonsPurchaseObserver = new DungeonsPurchaseObserver(mHandler); mBillingService = new BillingService(); mBillingService.setContext(this); mPurchaseDatabase = new PurchaseDatabase(this); setupWidgets(); // Check if billing is supported. ResponseHandler.register(mDungeonsPurchaseObserver); if (!mBillingService.checkBillingSupported()) { showDialog(DIALOG_CANNOT_CONNECT_ID); } } /** * Called when this activity becomes visible. */ @Override protected void onStart() { super.onStart(); ResponseHandler.register(mDungeonsPurchaseObserver); initializeOwnedItems(); } /** * Called when this activity is no longer visible. */ @Override protected void onStop() { super.onStop(); ResponseHandler.unregister(mDungeonsPurchaseObserver); } @Override protected void onDestroy() { super.onDestroy(); mPurchaseDatabase.close(); mBillingService.unbind(); } /** * Save the context of the log so simple things like rotation will not * result in the log being cleared. */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(LOG_TEXT_KEY, Html.toHtml((Spanned) mLogTextView.getText())); } /** * Restore the contents of the log if it has previously been saved. */ @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState != null) { mLogTextView.setText(Html.fromHtml(savedInstanceState.getString(LOG_TEXT_KEY))); } } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_CANNOT_CONNECT_ID: return createDialog(R.string.cannot_connect_title, R.string.cannot_connect_message); case DIALOG_BILLING_NOT_SUPPORTED_ID: return createDialog(R.string.billing_not_supported_title, R.string.billing_not_supported_message); default: return null; } } private Dialog createDialog(int titleId, int messageId) { String helpUrl = replaceLanguageAndRegion(getString(R.string.help_url)); if (Consts.DEBUG) { Log.i(TAG, helpUrl); } final Uri helpUri = Uri.parse(helpUrl); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(titleId) .setIcon(android.R.drawable.stat_sys_warning) .setMessage(messageId) .setCancelable(false) .setPositiveButton(android.R.string.ok, null) .setNegativeButton(R.string.learn_more, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Intent.ACTION_VIEW, helpUri); startActivity(intent); } }); return builder.create(); } /** * Replaces the language and/or country of the device into the given string. * The pattern "%lang%" will be replaced by the device's language code and * the pattern "%region%" will be replaced with the device's country code. * * @param str the string to replace the language/country within * @return a string containing the local language and region codes */ private String replaceLanguageAndRegion(String str) { // Substitute language and or region if present in string if (str.contains("%lang%") || str.contains("%region%")) { Locale locale = Locale.getDefault(); str = str.replace("%lang%", locale.getLanguage().toLowerCase()); str = str.replace("%region%", locale.getCountry().toLowerCase()); } return str; } /** * Sets up the UI. */ private void setupWidgets() { mLogTextView = (TextView) findViewById(R.id.log); mBuyButton = (Button) findViewById(R.id.buy_button); mBuyButton.setEnabled(false); mBuyButton.setOnClickListener(this); mEditPayloadButton = (Button) findViewById(R.id.payload_edit_button); mEditPayloadButton.setEnabled(false); mEditPayloadButton.setOnClickListener(this); mSelectItemSpinner = (Spinner) findViewById(R.id.item_choices); mCatalogAdapter = new CatalogAdapter(this, CATALOG); mSelectItemSpinner.setAdapter(mCatalogAdapter); mSelectItemSpinner.setOnItemSelectedListener(this); mOwnedItemsCursor = mPurchaseDatabase.queryAllPurchasedItems(); startManagingCursor(mOwnedItemsCursor); String[] from = new String[] { PurchaseDatabase.PURCHASED_PRODUCT_ID_COL, PurchaseDatabase.PURCHASED_QUANTITY_COL }; int[] to = new int[] { R.id.item_name, R.id.item_quantity }; mOwnedItemsAdapter = new SimpleCursorAdapter(this, R.layout.item_row, mOwnedItemsCursor, from, to); mOwnedItemsTable = (ListView) findViewById(R.id.owned_items); mOwnedItemsTable.setAdapter(mOwnedItemsAdapter); } private void prependLogEntry(CharSequence cs) { SpannableStringBuilder contents = new SpannableStringBuilder(cs); contents.append('\n'); contents.append(mLogTextView.getText()); mLogTextView.setText(contents); } private void logProductActivity(String product, String activity) { SpannableStringBuilder contents = new SpannableStringBuilder(); contents.append(Html.fromHtml("<b>" + product + "</b>: ")); contents.append(activity); prependLogEntry(contents); } /** * If the database has not been initialized, we send a * RESTORE_TRANSACTIONS request to Android Market to get the list of purchased items * for this user. This happens if the application has just been installed * or the user wiped data. We do not want to do this on every startup, rather, we want to do * only when the database needs to be initialized. */ private void restoreDatabase() { SharedPreferences prefs = getPreferences(MODE_PRIVATE); boolean initialized = prefs.getBoolean(DB_INITIALIZED, false); if (!initialized) { mBillingService.restoreTransactions(); Toast.makeText(this, R.string.restoring_transactions, Toast.LENGTH_LONG).show(); } } /** * Creates a background thread that reads the database and initializes the * set of owned items. */ private void initializeOwnedItems() { new Thread(new Runnable() { public void run() { doInitializeOwnedItems(); } }).start(); } /** * Reads the set of purchased items from the database in a background thread * and then adds those items to the set of owned items in the main UI * thread. */ private void doInitializeOwnedItems() { Cursor cursor = mPurchaseDatabase.queryAllPurchasedItems(); if (cursor == null) { return; } final Set<String> ownedItems = new HashSet<String>(); try { int productIdCol = cursor.getColumnIndexOrThrow( PurchaseDatabase.PURCHASED_PRODUCT_ID_COL); while (cursor.moveToNext()) { String productId = cursor.getString(productIdCol); ownedItems.add(productId); } } finally { cursor.close(); } // We will add the set of owned items in a new Runnable that runs on // the UI thread so that we don't need to synchronize access to // mOwnedItems. mHandler.post(new Runnable() { public void run() { mOwnedItems.addAll(ownedItems); mCatalogAdapter.setOwnedItems(mOwnedItems); } }); } /** * Called when a button is pressed. */ public void onClick(View v) { if (v == mBuyButton) { if (Consts.DEBUG) { Log.d(TAG, "buying: " + mItemName + " sku: " + mSku); } if (!mBillingService.requestPurchase(mSku, mPayloadContents)) { showDialog(DIALOG_BILLING_NOT_SUPPORTED_ID); } } else if (v == mEditPayloadButton) { showPayloadEditDialog(); } } /** * Displays the dialog used to edit the payload dialog. */ private void showPayloadEditDialog() { AlertDialog.Builder dialog = new AlertDialog.Builder(this); final View view = View.inflate(this, R.layout.edit_payload, null); final TextView payloadText = (TextView) view.findViewById(R.id.payload_text); if (mPayloadContents != null) { payloadText.setText(mPayloadContents); } dialog.setView(view); dialog.setPositiveButton( R.string.edit_payload_accept, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mPayloadContents = payloadText.getText().toString(); } }); dialog.setNegativeButton( R.string.edit_payload_clear, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (dialog != null) { mPayloadContents = null; dialog.cancel(); } } }); dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { public void onCancel(DialogInterface dialog) { if (dialog != null) { dialog.cancel(); } } }); dialog.show(); } /** * Called when an item in the spinner is selected. */ public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { mItemName = getString(CATALOG[position].nameId); mSku = CATALOG[position].sku; } public void onNothingSelected(AdapterView<?> arg0) { } /** * An adapter used for displaying a catalog of products. If a product is * managed by Android Market and already purchased, then it will be "grayed-out" in * the list and not selectable. */ private static class CatalogAdapter extends ArrayAdapter<String> { private CatalogEntry[] mCatalog; private Set<String> mOwnedItems = new HashSet<String>(); public CatalogAdapter(Context context, CatalogEntry[] catalog) { super(context, android.R.layout.simple_spinner_item); mCatalog = catalog; for (CatalogEntry element : catalog) { add(context.getString(element.nameId)); } setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); } public void setOwnedItems(Set<String> ownedItems) { mOwnedItems = ownedItems; notifyDataSetChanged(); } @Override public boolean areAllItemsEnabled() { // Return false to have the adapter call isEnabled() return false; } @Override public boolean isEnabled(int position) { // If the item at the given list position is not purchasable, // then prevent the list item from being selected. CatalogEntry entry = mCatalog[position]; if (entry.managed == Managed.MANAGED && mOwnedItems.contains(entry.sku)) { return false; } return true; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { // If the item at the given list position is not purchasable, then // "gray out" the list item. View view = super.getDropDownView(position, convertView, parent); view.setEnabled(isEnabled(position)); return view; } } }
0vishalvijay0-v4
v2/src/com/example/dungeons/Dungeons.java
Java
asf20
21,132
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dungeons; import com.example.dungeons.Consts.ResponseCode; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * This class implements the broadcast receiver for in-app billing. All asynchronous messages from * Android Market come to this app through this receiver. This class forwards all * messages to the {@link BillingService}, which can start background threads, * if necessary, to process the messages. This class runs on the UI thread and must not do any * network I/O, database updates, or any tasks that might take a long time to complete. * It also must not start a background thread because that may be killed as soon as * {@link #onReceive(Context, Intent)} returns. * * You should modify and obfuscate this code before using it. */ public class BillingReceiver extends BroadcastReceiver { private static final String TAG = "BillingReceiver"; /** * This is the entry point for all asynchronous messages sent from Android Market to * the application. This method forwards the messages on to the * {@link BillingService}, which handles the communication back to Android Market. * The {@link BillingService} also reports state changes back to the application through * the {@link ResponseHandler}. */ @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Consts.ACTION_PURCHASE_STATE_CHANGED.equals(action)) { String signedData = intent.getStringExtra(Consts.INAPP_SIGNED_DATA); String signature = intent.getStringExtra(Consts.INAPP_SIGNATURE); purchaseStateChanged(context, signedData, signature); } else if (Consts.ACTION_NOTIFY.equals(action)) { String notifyId = intent.getStringExtra(Consts.NOTIFICATION_ID); if (Consts.DEBUG) { Log.i(TAG, "notifyId: " + notifyId); } notify(context, notifyId); } else if (Consts.ACTION_RESPONSE_CODE.equals(action)) { long requestId = intent.getLongExtra(Consts.INAPP_REQUEST_ID, -1); int responseCodeIndex = intent.getIntExtra(Consts.INAPP_RESPONSE_CODE, ResponseCode.RESULT_ERROR.ordinal()); checkResponseCode(context, requestId, responseCodeIndex); } else { Log.w(TAG, "unexpected action: " + action); } } /** * This is called when Android Market sends information about a purchase state * change. The signedData parameter is a plaintext JSON string that is * signed by the server with the developer's private key. The signature * for the signed data is passed in the signature parameter. * @param context the context * @param signedData the (unencrypted) JSON string * @param signature the signature for the signedData */ private void purchaseStateChanged(Context context, String signedData, String signature) { Intent intent = new Intent(Consts.ACTION_PURCHASE_STATE_CHANGED); intent.setClass(context, BillingService.class); intent.putExtra(Consts.INAPP_SIGNED_DATA, signedData); intent.putExtra(Consts.INAPP_SIGNATURE, signature); context.startService(intent); } /** * This is called when Android Market sends a "notify" message indicating that transaction * information is available. The request includes a nonce (random number used once) that * we generate and Android Market signs and sends back to us with the purchase state and * other transaction details. This BroadcastReceiver cannot bind to the * MarketBillingService directly so it starts the {@link BillingService}, which does the * actual work of sending the message. * * @param context the context * @param notifyId the notification ID */ private void notify(Context context, String notifyId) { Intent intent = new Intent(Consts.ACTION_GET_PURCHASE_INFORMATION); intent.setClass(context, BillingService.class); intent.putExtra(Consts.NOTIFICATION_ID, notifyId); context.startService(intent); } /** * This is called when Android Market sends a server response code. The BillingService can * then report the status of the response if desired. * * @param context the context * @param requestId the request ID that corresponds to a previous request * @param responseCodeIndex the ResponseCode ordinal value for the request */ private void checkResponseCode(Context context, long requestId, int responseCodeIndex) { Intent intent = new Intent(Consts.ACTION_RESPONSE_CODE); intent.setClass(context, BillingService.class); intent.putExtra(Consts.INAPP_REQUEST_ID, requestId); intent.putExtra(Consts.INAPP_RESPONSE_CODE, responseCodeIndex); context.startService(intent); } }
0vishalvijay0-v4
v2/src/com/example/dungeons/BillingReceiver.java
Java
asf20
5,616
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.dungeons; import com.example.dungeons.BillingService.RequestPurchase; import com.example.dungeons.BillingService.RestoreTransactions; import com.example.dungeons.Consts.PurchaseState; import com.example.dungeons.Consts.ResponseCode; import android.app.Activity; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.content.Intent; import android.content.IntentSender; import android.os.Handler; import android.util.Log; import java.lang.reflect.Method; /** * An interface for observing changes related to purchases. The main application * extends this class and registers an instance of that derived class with * {@link ResponseHandler}. The main application implements the callbacks * {@link #onBillingSupported(boolean)} and * {@link #onPurchaseStateChange(PurchaseState, String, int, long)}. These methods * are used to update the UI. */ public abstract class PurchaseObserver { private static final String TAG = "PurchaseObserver"; private final Activity mActivity; private final Handler mHandler; private Method mStartIntentSender; private Object[] mStartIntentSenderArgs = new Object[5]; private static final Class[] START_INTENT_SENDER_SIG = new Class[] { IntentSender.class, Intent.class, int.class, int.class, int.class }; public PurchaseObserver(Activity activity, Handler handler) { mActivity = activity; mHandler = handler; initCompatibilityLayer(); } /** * This is the callback that is invoked when Android Market responds to the * {@link BillingService#checkBillingSupported()} request. * @param supported true if in-app billing is supported. */ public abstract void onBillingSupported(boolean supported); /** * This is the callback that is invoked when an item is purchased, * refunded, or canceled. It is the callback invoked in response to * calling {@link BillingService#requestPurchase(String)}. It may also * be invoked asynchronously when a purchase is made on another device * (if the purchase was for a Market-managed item), or if the purchase * was refunded, or the charge was canceled. This handles the UI * update. The database update is handled in * {@link ResponseHandler#purchaseResponse(Context, PurchaseState, * String, String, long)}. * @param purchaseState the purchase state of the item * @param itemId a string identifying the item (the "SKU") * @param quantity the current quantity of this item after the purchase * @param purchaseTime the time the product was purchased, in * milliseconds since the epoch (Jan 1, 1970) */ public abstract void onPurchaseStateChange(PurchaseState purchaseState, String itemId, int quantity, long purchaseTime, String developerPayload); /** * This is called when we receive a response code from Market for a * RequestPurchase request that we made. This is NOT used for any * purchase state changes. All purchase state changes are received in * {@link #onPurchaseStateChange(PurchaseState, String, int, long)}. * This is used for reporting various errors, or if the user backed out * and didn't purchase the item. The possible response codes are: * RESULT_OK means that the order was sent successfully to the server. * The onPurchaseStateChange() will be invoked later (with a * purchase state of PURCHASED or CANCELED) when the order is * charged or canceled. This response code can also happen if an * order for a Market-managed item was already sent to the server. * RESULT_USER_CANCELED means that the user didn't buy the item. * RESULT_SERVICE_UNAVAILABLE means that we couldn't connect to the * Android Market server (for example if the data connection is down). * RESULT_BILLING_UNAVAILABLE means that in-app billing is not * supported yet. * RESULT_ITEM_UNAVAILABLE means that the item this app offered for * sale does not exist (or is not published) in the server-side * catalog. * RESULT_ERROR is used for any other errors (such as a server error). */ public abstract void onRequestPurchaseResponse(RequestPurchase request, ResponseCode responseCode); /** * This is called when we receive a response code from Android Market for a * RestoreTransactions request that we made. A response code of * RESULT_OK means that the request was successfully sent to the server. */ public abstract void onRestoreTransactionsResponse(RestoreTransactions request, ResponseCode responseCode); private void initCompatibilityLayer() { try { mStartIntentSender = mActivity.getClass().getMethod("startIntentSender", START_INTENT_SENDER_SIG); } catch (SecurityException e) { mStartIntentSender = null; } catch (NoSuchMethodException e) { mStartIntentSender = null; } } void startBuyPageActivity(PendingIntent pendingIntent, Intent intent) { if (mStartIntentSender != null) { // This is on Android 2.0 and beyond. The in-app buy page activity // must be on the activity stack of the application. try { // This implements the method call: // mActivity.startIntentSender(pendingIntent.getIntentSender(), // intent, 0, 0, 0); mStartIntentSenderArgs[0] = pendingIntent.getIntentSender(); mStartIntentSenderArgs[1] = intent; mStartIntentSenderArgs[2] = Integer.valueOf(0); mStartIntentSenderArgs[3] = Integer.valueOf(0); mStartIntentSenderArgs[4] = Integer.valueOf(0); mStartIntentSender.invoke(mActivity, mStartIntentSenderArgs); } catch (Exception e) { Log.e(TAG, "error starting activity", e); } } else { // This is on Android version 1.6. The in-app buy page activity must be on its // own separate activity stack instead of on the activity stack of // the application. try { pendingIntent.send(mActivity, 0 /* code */, intent); } catch (CanceledException e) { Log.e(TAG, "error starting activity", e); } } } /** * Updates the UI after the database has been updated. This method runs * in a background thread so it has to post a Runnable to run on the UI * thread. * @param purchaseState the purchase state of the item * @param itemId a string identifying the item * @param quantity the quantity of items in this purchase */ void postPurchaseStateChange(final PurchaseState purchaseState, final String itemId, final int quantity, final long purchaseTime, final String developerPayload) { mHandler.post(new Runnable() { public void run() { onPurchaseStateChange( purchaseState, itemId, quantity, purchaseTime, developerPayload); } }); } }
0vishalvijay0-v4
v2/src/com/example/dungeons/PurchaseObserver.java
Java
asf20
7,923
#!/bin/sh # Copyright (c) 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # errors are fatal set -ve trap "echo '***ABORTED***'" ERR # directories and files TD=/tmp/make_deployable_$$_$RANDOM ZIPROOTNAME=play_billing ZIPROOT=$TD/$ZIPROOTNAME TRIVIALDRIVE=$ZIPROOT/samples/TrivialDrive V2ZIP=$PWD/market_billing_r02.zip ORIGWD=$PWD # work from v3 root directory cd ../v3 # make sure sample is in "public" mode, that is, with the # placeholder key in it MAINACTIVITY=src/com/example/android/trivialdrivesample/MainActivity.java if ! [ -f $MAINACTIVITY ]; then echo "Can't find $MAINACTIVITY." echo "Is the package name set to com.example.android.trivialdrivesample?" exit 2 fi if ! grep -q CONSTRUCT_YOUR_KEY_AND_PLACE_IT_HERE $MAINACTIVITY; then echo "The key in MainActivity.java must be the placeholder key!" exit 2 fi # make sure sample doesn't have bogus source directories that might # have been left behind as an artifact while testing set +e trash=`find src -type d | grep -v src/com/android | grep -v src/com/example | grep -v '^src$' | grep -v '^src/com$'` set -e if ! [ -z "$trash" ]; then echo "*** src dir has unexpected directories in it:" echo "$trash" exit 2 fi mkdir -p $TD echo "Making deployable ZIP (using $TD as temp directory)." rm -rf $TRIVIALDRIVE mkdir -p $TRIVIALDRIVE cp -va res src libs AndroidManifest.xml README project.properties $TRIVIALDRIVE cp -va src/com/android/vending/billing/IInAppBillingService.aidl $ZIPROOT cp -v $ORIGWD/../v3/README $ZIPROOT cp -v $V2ZIP $ZIPROOT cd $TD rm -f /tmp/$ZIPROOTNAME.zip zip -r /tmp/$ZIPROOTNAME.zip $ZIPROOTNAME rm -rf $TD echo "ZIP created: /tmp/$ZIPROOTNAME.zip"
0vishalvijay0-v4
deploy_scripts/make_sdkmanager_bundle
Shell
asf20
2,186
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; namespace ScheduleManagement.DAL { public class MainFrom_Dal { //读取配置文件,配置数据库连接字符串 string cn = Properties.Settings.Default.ConnectionString; public System.Data.DataSet List(int flag,int u_Id) { string commandText = "p_Dailytask"; SqlParameter[] commandParameters = new SqlParameter[2]; commandParameters[0] = new SqlParameter("@hc_Option", flag); commandParameters[1] = new SqlParameter("@u_Id", u_Id); System.Data.DataSet ds = SqlHelper.ExecuteDataset(cn,CommandType.StoredProcedure,commandText,commandParameters); return ds; } #region 查询区下拉列表框数据绑定 public SqlDataReader ListRemind() { string commandText = "p_Remindtype"; System.Data.SqlClient.SqlDataReader dr= SqlHelper.ExecuteReader(cn, CommandType.StoredProcedure, commandText); return dr; } public SqlDataReader ListSqType() { string commandText = "p_Schedulequlity"; System.Data.SqlClient.SqlDataReader dr = SqlHelper.ExecuteReader(cn, CommandType.StoredProcedure, commandText); return dr; } public SqlDataReader ListStpType() { string commandText = "p_Scheduletype"; System.Data.SqlClient.SqlDataReader dr = SqlHelper.ExecuteReader(cn, CommandType.StoredProcedure, commandText); return dr; } public SqlDataReader ListStatus() { string commandText = "p_Status"; System.Data.SqlClient.SqlDataReader dr = SqlHelper.ExecuteReader(cn, CommandType.StoredProcedure, commandText); return dr; } #endregion public DataSet SigleSelect(bool p_HideFinish, string p,string type) { string commandText = ""; switch (p) { case "Remind": commandText = "p_sRemindtype"; break; case "SqType": commandText = "p_sSchedulequlity"; break; case "StpType": commandText = "p_sScheduletype"; break; case "Cascade": commandText = "p_sCascade"; break; case "Announ": commandText = "p_sAnnoun"; break; case "Status": commandText = "p_sStatus"; break; default: break; } SqlParameter[] commandParameters = new SqlParameter[3]; commandParameters[0] = new SqlParameter("@hc_Option", p_HideFinish); commandParameters[1] = new SqlParameter("@temp", type); commandParameters[2] = new SqlParameter("@u_Id", ScheduleManagement.MODEL.Users.U_Id); System.Data.DataSet ds = SqlHelper.ExecuteDataset(cn, CommandType.StoredProcedure, commandText, commandParameters); return ds; } public System.Data.DataSet MergeSelect(bool p_HideFinish, string p) { //测试 string commandText = "p_Dailytask"; SqlParameter[] commandParameters = new SqlParameter[1]; commandParameters[0] = new SqlParameter("@hc_Option", p_HideFinish); System.Data.DataSet ds = SqlHelper.ExecuteDataset(cn, CommandType.StoredProcedure, commandText, commandParameters); return ds; } /// <summary> /// 查询并返回当前用户总日程 /// </summary> /// <returns></returns> public DataSet ListAll() { string commandText = "p_UserSchedule"; SqlParameter[] commandParameters = new SqlParameter[1]; commandParameters[0] = new SqlParameter("@u_Id", ScheduleManagement.MODEL.Users.U_Id); System.Data.DataSet ds = SqlHelper.ExecuteDataset(cn, CommandType.StoredProcedure, commandText, commandParameters); return ds; } //public ScheduleManagement.MODEL.Schedulequality GetStpId(string p) //{ // throw new Exception("The method or operation is not implemented."); //} //public ScheduleManagement.MODEL.Schedulequality GetSqId(string p) //{ // throw new Exception("The method or operation is not implemented."); //} public string GetStpId(string p) { string commandText = "p_selectstptype"; SqlParameter[] commandParameters = new SqlParameter[1]; commandParameters[0] = new SqlParameter("@stp_Type", p); return SqlHelper.ExecuteNonQuery(cn, CommandType.StoredProcedure, commandText, commandParameters).ToString(); } public string GetSqId(string p) { string commandText = "p_selectsqtype"; SqlParameter[] commandParameters = new SqlParameter[1]; commandParameters[0] = new SqlParameter("@sq_Type", p); return SqlHelper.ExecuteNonQuery(cn, CommandType.StoredProcedure, commandText, commandParameters).ToString(); } public void AddSchedule(ScheduleManagement.MODEL.Schedule sch) { string commandText = "p_AddSchedule"; SqlParameter[] commandParameters = new SqlParameter[10]; commandParameters[0] = new SqlParameter("@u_Id",ScheduleManagement.MODEL.Users.U_Id); commandParameters[1] = new SqlParameter("@sq_Id",sch.Schedulequality.Sq_Id ); commandParameters[2] = new SqlParameter("@stp_Id", sch.Scheduletype.Stp_Id); commandParameters[3] = new SqlParameter("@s_Quality",1 ); commandParameters[4] = new SqlParameter("@s_Content", sch.S_Content); commandParameters[5] = new SqlParameter("@r_Id", sch.Remindtype.R_Id); commandParameters[6] = new SqlParameter("@st_Id",sch.Status.St_Id ); commandParameters[7] = new SqlParameter("@s_Announcement", sch.S_Announcement); commandParameters[8] = new SqlParameter("@s_Cascade", sch.S_Cascade); commandParameters[9] = new SqlParameter("@s_Voice", sch.S_Voice); SqlHelper.ExecuteNonQuery(cn, CommandType.StoredProcedure, commandText, commandParameters); } } }
10ata3-crriculumdesign-schedulemanagementsystem
trunk/日程管理系统/ScheduleManagement/ScheduleManagement.DAL/MainFrom_Dal.cs
C#
mpl11
6,768