Documentation here.
Version: 4.0 beta1
Author: Casey Bisson
Author URI: http://maisonbisson.com/blog/
*/
$services_feed = array(
'bloglines' => array(
'name' => 'Bloglines'
, 'url' => 'http://www.bloglines.com/sub/{url_raw}'
)
, 'google' => array(
'name' => 'Google'
, 'url' => 'http://fusion.google.com/add?feedurl={url}'
)
, 'rssfwd' => array(
'name' => 'RSS:FWD Email'
, 'url' => 'http://www.rssfwd.com/rssfwd/preview?url={url}'
)
);
$services_translate = array(
'french' => array(
'name' => 'French'
, 'url' => 'http://translate.google.com/translate?u={url}&langpair=en%7Cfr'
)
, 'spanish' => array(
'name' => 'Spanish'
, 'url' => 'http://translate.google.com/translate?u={url}&langpair=en%7Ces'
)
, 'german' => array(
'name' => 'German'
, 'url' => 'http://translate.google.com/translate?u={url}&langpair=en%7Cde'
)
, 'japanese' => array(
'name' => 'Japanese'
, 'url' => 'http://translate.google.com/translate?u={url}&langpair=en%7Cja'
)
, 'korean' => array(
'name' => 'Korean'
, 'url' => 'http://translate.google.com/translate?u={url}&langpair=en%7Cko'
)
, 'chineses' => array(
'name' => 'Chinese (simplified)'
, 'url' => 'http://translate.google.com/translate?u={url}&langpair=en%7Czh-CN'
)
, 'chineset' => array(
'name' => 'Chinese (traditional)'
, 'url' => 'http://translate.google.com/translate?u={url}&langpair=en%7Czh-TW'
)
, 'russian' => array(
'name' => 'Russian'
, 'url' => 'http://translate.google.com/translate?u={url}&langpair=en%7Cru'
)
);
$services_bookmark = array(
'delicious' => array(
'name' => 'del.icio.us'
, 'url' => 'http://del.icio.us/post?url={url}&title={title}'
)
, 'facebook' => array(
'name' => 'Facebook'
, 'url' => 'http://www.facebook.com/share.php?u={url}'
)
, 'digg' => array(
'name' => 'Digg'
, 'url' => 'http://digg.com/submit?phase=2&url={url}&title={title}'
)
, 'stumbleupon' => array(
'name' => 'StumbleUpon'
, 'url' => 'http://www.stumbleupon.com/submit?url={url}&title={title}'
)
, 'reddit' => array(
'name' => 'reddit'
, 'url' => 'http://reddit.com/submit?url={url}&title={title}'
)
, 'blinklist' => array(
'name' => 'BlinkList'
, 'url' => 'http://blinklist.com/index.php?Action=Blink/addblink.php&Url={url}&Title={title}'
)
, 'newsvine' => array(
'name' => 'Newsvine'
, 'url' => 'http://www.newsvine.com/_tools/seed&save?popoff=0&u={url}&h={title}'
)
, 'furl' => array(
'name' => 'Furl'
, 'url' => 'http://furl.net/storeIt.jsp?u={url}&t={title}'
)
, 'tailrank' => array(
'name' => 'Tailrank'
, 'url' => 'http://tailrank.com/share/?link_href={url}&title={title}'
)
, 'magnolia' => array(
'name' => 'Ma.gnolia'
, 'url' => 'http://ma.gnolia.com/bookmarklet/add?url={url}&title={title}'
)
, 'netscape' => array(
'name' => 'Netscape'
, 'url' => ' http://www.netscape.com/submit/?U={url}&T={title}'
)
, 'yahoo_myweb' => array(
'name' => 'Yahoo! My Web'
, 'url' => 'http://myweb2.search.yahoo.com/myresults/bookmarklet?u={url}&t={title}'
)
, 'google_bmarks' => array(
'name' => 'Google Bookmarks'
, 'url' => ' http://www.google.com/bookmarks/mark?op=edit&bkmk={url}&title={title}'
)
, 'technorati' => array(
'name' => 'Technorati'
, 'url' => 'http://www.technorati.com/faves?add={url}'
)
, 'blinklist' => array(
'name' => 'BlinkList'
, 'url' => 'http://blinklist.com/index.php?Action=Blink/addblink.php&Url={url}&Title={title}'
)
, 'windows_live' => array(
'name' => 'Windows Live'
, 'url' => 'https://favorites.live.com/quickadd.aspx?marklet=1&mkt=en-us&url={url}&title={title}&top=1'
)
);
class bSuite {
function bSuite(){
global $wpdb;
$this->search_table = $wpdb->prefix . 'bsuite4_search';
$this->hits_incoming = $wpdb->prefix . 'bsuite4_hits_incoming';
$this->hits_terms = $wpdb->prefix . 'bsuite4_hits_terms';
$this->hits_targets = $wpdb->prefix . 'bsuite4_hits_targets';
$this->hits_searchphrases = $wpdb->prefix . 'bsuite4_hits_searchphrases';
// $this->hits_searchwords = $wpdb->prefix . 'bsuite4_hits_searchwords';
$this->hits_sessions = $wpdb->prefix . 'bsuite4_hits_sessions';
$this->hits_shistory = $wpdb->prefix . 'bsuite4_hits_shistory';
$this->hits_pop = $wpdb->prefix . 'bsuite4_hits_pop';
$this->lock_migrator = $wpdb->prefix . 'bsuite4_lock_migrator';
$this->lock_ftindexer = $wpdb->prefix . 'bsuite4_lock_ftindexer';
$this->loadavg = $this->get_loadavg();
// establish web path to this plugin's directory
$this->path_web = '/'. PLUGINDIR .'/'. plugin_basename( dirname( __FILE__ ));
// register and queue javascripts
wp_register_script( 'bsuite', $this->path_web . '/js/bsuite.js', array('jquery'), '20080503' );
wp_enqueue_script( 'bsuite' );
// jQuery text highlighting plugin http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
wp_register_script( 'highlight', $this->path_web . '/js/jquery.highlight-1.js', array('jquery'), '1' );
wp_enqueue_script( 'highlight' );
//
// register hooks
//
// shortcodes
add_shortcode('pagemenu', array(&$this, 'shortcode_pagemenu'));
add_shortcode('innerindex', array(&$this, 'shortcode_innerindex'));
add_shortcode('feed', array(&$this, 'shortcode_feed'));
// add_shortcode('redirect', array(&$this, 'shortcode_redirect'));
// tokens
// tokens are deprecated. please use shortcode functionality instead.
add_filter('bsuite_tokens', array(&$this, 'tokens_default'));
add_filter('the_content', array(&$this, 'tokens_the_content'), 0);
add_filter('the_content_rss', array(&$this, 'tokens_the_content_rss'), 0);
add_filter('the_excerpt', array(&$this, 'tokens_the_excerpt'), 0);
add_filter('the_excerpt_rss', array(&$this, 'tokens_the_excerpt_rss'), 0);
add_filter('get_the_excerpt ', array(&$this, 'tokens_the_excerpt'), 0);
add_filter('widget_text', array(&$this, 'tokens'), 0);
//innerindex
add_filter('content_save_pre', array(&$this, 'innerindex_nametags'));
add_filter('save_post', array(&$this, 'innerindex_delete_cache'));
add_filter('publish_post', array(&$this, 'innerindex_delete_cache'));
add_filter('publish_page', array(&$this, 'innerindex_delete_cache'));
$this->kses_allowedposttags(); // allow IDs on H1-H6 tags
// bsuggestive related posts
add_filter('save_post', array(&$this, 'bsuggestive_delete_cache'));
add_filter('publish_post', array(&$this, 'bsuggestive_delete_cache'));
add_filter('publish_page', array(&$this, 'bsuggestive_delete_cache'));
if( get_option( 'bsuite_insert_related' ))
add_filter('the_content', array(&$this, 'bsuggestive_the_content'), 5);
// sharelinks
if( get_option( 'bsuite_insert_sharelinks' ))
add_filter('the_content', array(&$this, 'sharelinks_the_content'), 6);
// searchsmart
if( get_option( 'bsuite_searchsmart' )){
add_filter('posts_request', array(&$this, 'searchsmart_posts_request'), 10);
add_filter('content_save_pre', array(&$this, 'searchsmart_upindex_onedit'));
}
add_filter('template_redirect', array(&$this, 'searchsmart_direct'), 8);
// default CSS
if( get_option( 'bsuite_insert_css' ))
add_action('wp_head', array(&$this, 'css_default' ));
// bstat
add_action('get_footer', array(&$this, 'bstat_js'));
// cron
add_filter('cron_schedules', array(&$this, 'cron_reccurences'));
if( $this->loadavg < get_option( 'bsuite_load_max' )){ // only do cron if load is low-ish
add_filter('bsuite_interval', array(&$this, 'bstat_migrator'));
if( get_option( 'bsuite_searchsmart' ))
add_filter('bsuite_interval', array(&$this, 'searchsmart_upindex_passive'));
}
// machine tags
add_action('save_post', array(&$this, 'machtag_save_post'), 2, 2);
// cms goodies
add_action('dbx_page_advanced', array(&$this, 'edit_insert_excerpt_form'));
add_action('dbx_page_sidebar', array(&$this, 'edit_insert_category_form'));
add_action('edit_form_advanced', array(&$this, 'edit_post_form'));
add_action('edit_page_form', array(&$this, 'edit_page_form'));
add_action('widgets_init', array(&$this, 'widgets_register'));
// activation and menu hooks
register_activation_hook(__FILE__, array(&$this, 'activate'));
add_action('admin_menu', array(&$this, 'addmenus'));
// end register WordPress hooks
// set things up so authors can edit their own pages
$role = get_role('author');
if ( ! empty($role) ) {
$role->add_cap('edit_pages');
$role->add_cap('edit_published_pages');
}
}
//
// shortcode functions
//
function shortcode_pagemenu( $arg ){
// [pagemenu ]
global $id;
$arg = shortcode_atts( array(
'title' => 'Contents',
'div_class' => 'contents pagemenu',
'ul_class' => 'contents pagemenu',
'ol_class' => FALSE,
'echo' => 0,
'child_of' => $id,
'depth' => 1,
'sort_column' => 'menu_order, post_title',
'title_li' => '',
'show_date' => '',
'date_format' => get_option('date_format'),
'exclude' => '',
'authors' => '',
), $arg );
$prefix = $suffix = '';
if( $arg['div_class'] ){
$prefix .= '
';
$suffix .= '
';
if( $arg['title'] )
$prefix .= ''. $arg['title'] .' ';
if( $arg['ul_class'] ){
$prefix .= ''. $suffix;
}else if( $arg['ol_class'] ){
$prefix .= '';
$suffix = ' '. $suffix;
}
}else{
if( $arg['title'] )
$prefix .= ''. $arg['title'] .' ';
if( $arg['ul_class'] ){
$prefix .= ''. $suffix;
}else if( $arg['ol_class'] ){
$prefix .= '';
$suffix = ' '. $suffix;
}
}
return( $prefix . wp_list_pages( $arg ) . $suffix );
}
function shortcode_innerindex( $arg ){
// [innerindex ]
global $id;
$arg = shortcode_atts( array(
'title' => 'Contents',
'div_class' => 'contents innerindex',
), $arg );
$prefix = $suffix = '';
if( $arg['div_class'] ){
$prefix .= '';
$suffix .= '
';
if( $arg['title'] )
$prefix .= ''. $arg['title'] .' ';
}else{
if( $arg['title'] )
$prefix .= ''. $arg['title'] .' ';
}
if ( !$menu = wp_cache_get( $id, 'bsuite_innerindex' )) {
$menu = $this->innerindex_build( get_post_field( 'post_content', $id ));
wp_cache_add( $id, $menu, 'bsuite_innerindex', 864000 );
}
return( $prefix . str_replace( '%%the_permalink%%', get_permalink( $id ), $menu ) . $suffix );
}
function shortcode_redirect($stuff){
// [[redirect|$url]]
if(!headers_sent())
header("Location: $stuff");
return('redirect: '. $stuff .' ');
}
function shortcode_feed( $arg ){
// [feed ]
$arg = shortcode_atts( array(
'title' => FALSE,
'div_class' => FALSE,
'ul_class' => 'feed',
'ol_class' => FALSE,
'feed_url' => FALSE,
'count' => 5,
'template' => '%%content%%
',
), $arg );
if( ! $arg[ 'feed_url' ] )
return( FALSE );
$prefix = $suffix = '';
if( $arg['div_class'] ){
$prefix .= '';
$suffix .= '
';
if( $arg['title'] )
$prefix .= ''. $arg['title'] .' ';
if( $arg['ul_class'] ){
$prefix .= ''. $suffix;
}else if( $arg['ol_class'] ){
$prefix .= '';
$suffix = ' '. $suffix;
}
}else{
if( $arg['title'] )
$prefix .= ''. $arg['title'] .' ';
if( $arg['ul_class'] ){
$prefix .= ''. $suffix;
}else if( $arg['ol_class'] ){
$prefix .= '';
$suffix = ' '. $suffix;
}
}
return( $prefix . $this->get_feed( $arg['feed_url'], $arg['count'], $arg['template'], TRUE) . $suffix );
}
//
// token functions
// tokens are [[token]] in the content of a post.
//
function tokens_get(){
// establish list of tokens
static $tokens = FALSE;
if($tokens)
return($tokens);
$tokens = array();
$tokens = apply_filters('bsuite_tokens', $tokens);
return($tokens);
}
function tokens_fill($thing) {
// match tokens
$return = $thing[0];
$thing = explode('|', trim($thing[0], '[]'), 2);
$tokens = &$this->tokens_get();
if($tokens[$thing[0]])
$return = call_user_func_array($tokens[$thing[0]], $thing[1]);
return($return);
}
function tokens($content) {
// find tokens in the page
$content = preg_replace_callback(
'/\[\[([^\]\]])*\]\]/',
array(&$this, 'tokens_fill'),
$content);
return($content);
}
public function tokens_the_content($content) {
$this->is_content = TRUE;
$content = $this->tokens($content);
$this->is_content = FALSE;
return($content);
}
public function tokens_the_content_rss($content) {
$this->is_content = TRUE;
$this->is_rss = TRUE;
$content = $this->tokens($content);
$this->is_content = FALSE;
$this->is_rss = FALSE;
return($content);
}
public function tokens_the_excerpt($content) {
$this->is_excerpt = TRUE;
$content = $this->tokens($content);
$this->is_excerpt = FALSE;
return($content);
}
public function tokens_the_excerpt_rss($content) {
$this->is_excerpt = TRUE;
$this->is_rss = TRUE;
$content = $this->tokens($content);
$this->is_excerpt = FALSE;
$this->is_rss = FALSE;
return($content);
}
function tokens_default($tokens){
// setup some default tokens
$tokens['date'] = array(&$this, 'token_get_date');
$tokens['pagemenu'] = array(&$this, 'token_get_pagemenu');
$tokens['innerindex'] = array(&$this, 'innerindex');
$tokens['feed'] = array(&$this, 'token_get_feed');
$tokens['redirect'] = array(&$this, 'token_get_redirect');
return($tokens);
}
function token_get_date($stuff = 'F j, Y, g:i a'){
// [[date|options]]
return(date($stuff));
}
function token_get_pagemenu($stuff = NULL){
// [[pagemenu|depth|extra]]
// [[pagemenu|1|sort_column=post_date&sort_order=DESC]]
global $id;
$stuff = explode('|', $stuff);
return(wp_list_pages("child_of=$id&depth=1&echo=0&sort_column=menu_order&title_li=&$stuff[0]"));
}
function token_get_redirect($stuff){
// [[redirect|$url]]
if(!headers_sent())
header("Location: $stuff");
return('redirect: '. $stuff .' ');
}
function token_get_feed($stuff){
// [[feed|feed_url|count]]
$stuff = explode('|', $stuff);
if(!$stuff[1])
$stuff[1] = 5;
if(!$stuff[2])
$stuff[2] = '%%title%% %%content%% ';
return($this->get_feed($stuff[0], $stuff[1], $stuff[2], TRUE));
}
// end token-related functions
//innerindex
function innerindex($title = 'Contents:'){
global $id, $post_cache;
if ( !$menu = wp_cache_get( $id, 'bsuite_innerindex' )) {
$menu = $this->innerindex_build( get_post_field( 'post_content', $id ));
wp_cache_add( $id, $menu, 'bsuite_innerindex', 864000 );
}
if($this->is_excerpt){
return( str_replace( '%%the_permalink%%', get_permalink( $id ), $menu ));
}else{
return( '
'. $title .' '. str_replace( '%%the_permalink%%', get_permalink( $id ), $menu ) .'' );
}
}
function innerindex_build($content){
// find tags with IDs in the content and build an index of them
preg_match_all(
'|]+>[^<]+ ]+>|U',
$content,
$things
);
$menu = '';
$closers = $count = 0;
foreach($things[0] as $thing){
preg_match('| $last){
$menu .= '';
$closers++;
}else if($count){
$menu .= '';
}
if(($h[1] < $last) && ($h[1] >= $low)){
$menu .= ' ';
$closers--;
}
$last = $h[1];
$menu .= ''. strip_tags($thing) .' ';
$count++;
}
}
$menu .= ' '. str_repeat(' ', $closers) . '';
return($menu);
}
function innerindex_delete_cache($id) {
$id = (int) $id;
wp_cache_delete( $id, 'bsuite_innerindex' );
}
function innerindex_nametags($content){
// find tags in the content
$content = preg_replace_callback(
"/(\]*)?\>)(.*?)(\<\/h[0-9]\>)/",
array(&$this,'innerindex_nametags_callback'),
$content
);
return($content);
}
function innerindex_nametags_callback($content){
// receive tags and insert the ID
static $slugs;
$slugs[] = $slug = substr(sanitize_title_with_dashes($content[4]), 0, 20);
$content = "{$content[4]}{$content[5]}";
return($content);
}
// end innerindex-related
//
// sharelinks
//
function sharelinks(){
global $wp_query;
// exit if 404
if($wp_query->is_404)
return(FALSE);
// identify the based post ID, if any, and establish some basics
$post_id = FALSE;
if(!empty($wp_query->is_singular) && !empty($wp_query->query_vars['p']))
$post_id = $wp_query->query_vars['p'];
else if(!empty($wp_query->is_singular) && !empty($wp_query->queried_object_id))
$post_id = $wp_query->queried_object_id;
else if( !empty( $this->bsuggestive_to ))
$post_id = $this->bsuggestive_to;
if($post_id){
$the_permalink = urlencode(get_permalink($post_id));
$the_title = urlencode(get_the_title($post_id));
$the_excerpt = apply_filters('the_excerpt', get_the_excerpt());
}else{
$the_permalink = strtolower(substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/'))) . '://' . $_SERVER['HTTP_HOST'] . add_query_arg('bsuite_share');
unset($wp_query->query['bsuite_share']);
unset($wp_query->query['attachment']);
if(count($wp_query->query))
$the_title = get_bloginfo('name') .' ('. wp_specialchars( implode(array_unique(explode('|', strtolower(implode(array_values($wp_query->query), '|')))), ', ')) .')';
else
$the_title = get_bloginfo('name');
$the_excerpt = '';
}
$content = '';
// the embed links
if( $post_id && ( $embed = $this->link2me( $post_id ))){
$content .= 'Link or embed this ' . $embed .' ';
}
// the bookmark links
$content .= 'Bookmark this at ';
global $services_bookmark;
foreach ($services_bookmark as $key => $data) {
$content .= ' '. $data['name'] .' ';
}
$content .= ' ';
// the email links
$content .= 'Email this page ';
// the feed links
$content .= 'Stay up to date ';
$feeds = array();
if($wp_query->is_singular)
$feeds[] = array('title' => 'Comments on this post', 'url' => get_post_comments_feed_link($post_id));
if($wp_query->is_search)
$feeds[] = array('title' => 'This Search', 'url' => $this->feedlink());
$feeds[] = array('title' => 'All Posts', 'url' => get_bloginfo('atom_url'));
$feeds[] = array('title' => 'All Comments', 'url' => get_bloginfo('comments_atom_url'));
global $services_feed;
foreach ($feeds as $feed) {
$subscribe_links = array();
foreach ($services_feed as $key => $data) {
$subscribe_links[] = ''. $data['name'] .' ';
}
$content .= ' '. $feed['title'] .' . Subscribe via '. implode($subscribe_links, ', ') .'. ';
}
$content .= ' ';
// the translation links
$content .= 'Automatically translate this to ';
global $services_translate;
foreach ($services_translate as $key => $data) {
$content .= ''. $data['name'] .' ';
}
$content .= ' ';
$content .= ' ';
// powered by
$content .= 'Powered by bSuite .
';
return( $content );
//return(array('the_id' => $post_id, 'the_title' => urldecode($the_title), 'the_permalink' => urldecode($the_permalink), 'the_content' => $content, ));
}
function sharelinks_the_content( $content ) {
if( is_single() && $sharelinks = $this->sharelinks() )
return( $content . $sharelinks);
return( $content );
}
// end sharelinks related functions
//
// link to me
//
function link2me_links( $post_id ){
if( !$post_id )
return( FALSE );
//''. strip_tags( get_the_title( $post_id )) .' '; //not using this now
//echo 'Hi! ';
return( apply_filters('bsuite_link2me', array( array('code' => get_permalink($post_id), 'name' => __( 'Permalink', 'bsuite' ))), $post_id));
}
function link2me( $post_id ){
if( !$post_id ){
global $id;
$post_id = $id;
}
if( !$links = $this->link2me_links( $post_id ))
return( FALSE );
if( count( $links ) ){
$return = '';
return( $return );
}
return( FALSE );
}
//
// Stats Related
//
function bstat_js() {
?>
get_var("SELECT name FROM $this->hits_terms WHERE ". $wpdb->prepare( "term_id = %s", (int) $id ));
wp_cache_add( $id, $name, 'bstat_terms', 0 );
}
return( $name );
}
function bstat_is_term( $term ) {
global $wpdb;
$cache_key = md5( substr( $term, 0, 255 ) );
if ( !$term_id = wp_cache_get( $cache_key, 'bstat_termids' )) {
$term_id = (int) $wpdb->get_var("SELECT term_id FROM $this->hits_terms WHERE ". $wpdb->prepare( "name = %s", substr( $term, 0, 255 )));
wp_cache_add( $cache_key, $term_id, 'bstat_termids', 0 );
}
return( $term_id );
}
function bstat_insert_term( $term ) {
global $wpdb;
if ( !$term_id = $this->bstat_is_term( $term )) {
if ( false === $wpdb->insert( $this->hits_terms, array( 'name' => $term ))){
new WP_Error('db_insert_error', __('Could not insert term into the database'), $wpdb->last_error);
return( 1 );
}
$term_id = (int) $wpdb->insert_id;
}
return( $term_id );
}
function bstat_is_session( $session_cookie ) {
global $wpdb;
if ( !$sess_id = wp_cache_get( $session_cookie, 'bstat_sessioncookies' )) {
$sess_id = (int) $wpdb->get_var("SELECT sess_id FROM $this->hits_sessions WHERE ". $wpdb->prepare( "sess_cookie = %s", $session_cookie ));
wp_cache_add( $session_cookie, $sess_id, 'bstat_sessioncookies', 10800 );
}
return($sess_id);
}
function bstat_insert_session( $session ) {
global $wpdb;
$s = array();
if ( !$session_id = $this->bstat_is_session( $session->in_session )) {
$this->session_new = TRUE;
$s['sess_cookie'] = $session->in_session;
$s['sess_date'] = $session->in_time;
$se = unserialize( $session->in_extra );
$s['sess_ip'] = $se['ip'];
$s['sess_br'] = $se['br'];
$s['sess_bb'] = $se['bb'];
$s['sess_bl'] = $se['bl'];
$s['sess_ba'] = urldecode( $se['ba'] );
// could use INET_ATON and INET_NTOA to reduce storage requirements for the IP address,
// but it's not human readable when browsing the table
if ( false === $wpdb->insert( $this->hits_sessions, $s )){
new WP_Error('db_insert_error', __('Could not insert session into the database'), $wpdb->last_error);
return( FALSE );
}
$session_id = (int) $wpdb->insert_id;
wp_cache_add($session->in_session, $session_id, 'bstat_sessioncookies', 10800 );
}
return( $session_id );
}
function bstat_migrator(){
global $wpdb;
// use a named mysql lock to prevent simultaneous execution
// locks automatically drop when the connection is dropped
// http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_get-lock
if( 0 == $wpdb->get_var( 'SELECT GET_LOCK("'. $this->lock_migrator .'", 2)' ))
return( TRUE );
// also use the options table
if ( get_option( 'bsuite_doing_migration') > time() )
return( TRUE );
update_option( 'bsuite_doing_migration', time() + 250 );
$status = get_option ( 'bsuite_doing_migration_status' );
$getcount = get_option( 'bsuite_migration_count' );
$since = date('Y-m-d H:i:s', strtotime('-1 minutes'));
$res = $targets = $searchwords = $shistory = array();
$res = $wpdb->get_results( "SELECT *
FROM $this->hits_incoming
WHERE in_time < '$since'
ORDER BY in_time ASC
LIMIT $getcount" );
$status['count_incoming'] = count( $res );
update_option( 'bsuite_doing_migration_status', $status );
foreach( $res as $hit ){
$object_id = $object_type = $session_id = 0;
if( !strlen( $hit->in_to ))
$hit->in_to = get_option( 'siteurl' ) .'/';
if( $hit->in_session )
$session_id = $this->bstat_insert_session( $hit );
$object_id = url_to_postid( $hit->in_to );
// determine the target
if( ( 1 > $object_id ) || (('posts' <> get_option( 'show_on_front' )) && $object_id == get_option( 'page_on_front' )) ){
$object_id = $this->bstat_insert_term( $hit->in_to );
$object_type = 1;
}
$targets[] = "($object_id, $object_type, 1, '$hit->in_time')";
// look for search words
if( ( $referers = implode( $this->get_search_terms( $hit->in_from ), ' ') ) && ( 0 < strlen( $referers ))) {
$term_id = $this->bstat_insert_term( $referers );
$searchwords[] = "($object_id, $object_type, $term_id, 1)";
}
if( $session_id ){
if( $referers )
$shistory[] = "($session_id, $term_id, 2)";
if( $this->session_new ){
$in_from = $this->bstat_insert_term( $hit->in_from );
if( $referers )
$shistory[] = "($session_id, $in_from, 3)";
}
$shistory[] = "($session_id, $object_id, $object_type)";
}
}
$status['count_targets'] = count( $targets );
$status['count_searchwords'] = count( $searchwords );
$status['count_shistory'] = count( $shistory );
update_option( 'bsuite_doing_migration_status', $status );
if( count( $targets ) && !$status['did_targets'] ){
if ( false === $wpdb->query( "INSERT INTO $this->hits_targets (object_id, object_type, hit_count, hit_date) VALUES ". implode( $targets, ',' ) ." ON DUPLICATE KEY UPDATE hit_count = hit_count + 1;" ))
return new WP_Error('db_insert_error', __('Could not insert bsuite_hits_target into the database'), $wpdb->last_error);
$status['did_targets'] = 1 ;
update_option( 'bsuite_doing_migration_status', $status );
}
if( count( $searchwords ) && !$status['did_searchwords'] ){
if ( false === $wpdb->query( "INSERT INTO $this->hits_searchphrases (object_id, object_type, term_id, hit_count) VALUES ". implode( $searchwords, ',' ) ." ON DUPLICATE KEY UPDATE hit_count = hit_count + 1;" ))
return new WP_Error('db_insert_error', __('Could not insert bsuite_hits_searchword into the database'), $wpdb->last_error);
$status['did_searchwords'] = 1;
update_option( 'bsuite_doing_migration_status', $status );
}
if( count( $shistory ) && !$status['did_shistory'] ){
if ( false === $wpdb->query( "INSERT INTO $this->hits_shistory (sess_id, object_id, object_type) VALUES ". implode( $shistory, ',' ) .';' ))
return new WP_Error('db_insert_error', __('Could not insert bsuite_hits_session_history into the database'), $wpdb->last_error);
$status['did_shistory'] = count( $shistory );
update_option( 'bsuite_doing_migration_status', $status );
}
if( count( $res )){
if ( false === $wpdb->query( "DELETE FROM $this->hits_incoming WHERE in_time < '$since' ORDER BY in_time ASC LIMIT ". count( $res ) .';'))
return new WP_Error('db_insert_error', __('Could not clean up the incoming stats table'), $wpdb->last_error);
if( $getcount > count( $res ))
$wpdb->query( "OPTIMIZE TABLE $this->hits_incoming;");
}
if ( get_option( 'bsuite_doing_migration_popr') < time() ){
if ( get_option( 'bsuite_doing_migration_popd') < time() ){
$wpdb->query( "TRUNCATE $this->hits_pop" );
$wpdb->query( "INSERT INTO $this->hits_pop (post_id, date_start, hits_total)
SELECT object_id AS post_id, MIN(hit_date) AS date_start, SUM(hit_count) AS hits_total
FROM $this->hits_targets
WHERE object_type = 0
AND hit_date >= DATE_SUB( NOW(), INTERVAL 45 DAY )
GROUP BY object_id" );
update_option( 'bsuite_doing_migration_popd', time() + 64800 );
}
$wpdb->query( "UPDATE $this->hits_pop p
LEFT JOIN (
SELECT object_id, COUNT(*) AS hit_count
FROM (
SELECT sess_id, sess_date
FROM (
SELECT sess_id, sess_date
FROM $this->hits_sessions
ORDER BY sess_id DESC
LIMIT 12500
) a
WHERE sess_date >= DATE_SUB( NOW(), INTERVAL 1 DAY )
) s
LEFT JOIN $this->hits_shistory h ON h.sess_id = s.sess_id
WHERE h.object_type = 0
GROUP BY object_id
) h ON h.object_id = p.post_id
SET hits_recent = h.hit_count" );
update_option( 'bsuite_doing_migration_popr', time() + 1500 );
}
/*
$posts = $wpdb->get_results("SELECT object_id, AVG(hit_count) AS hit_avg
FROM $this->hits_targets
WHERE hit_date >= DATE_SUB(CURDATE(),INTERVAL 30 DAY)
AND object_type = 0
GROUP BY object_id
ORDER BY object_id ASC", ARRAY_A);
$avg = array();
foreach($posts as $post)
$avg[$post['object_id']] = $post['hit_avg'];
$posts = $wpdb->get_results("SELECT object_id, hit_count * (86400/TIME_TO_SEC(TIME(NOW()))) AS hit_now
FROM $this->hits_targets
WHERE hit_date = CURDATE()
AND object_type = 0
ORDER BY object_id ASC", ARRAY_A);
$now = array();
foreach($posts as $post)
$now[$post['object_id']] = $post['hit_now'];
$diff = array();
foreach($posts as $post)
$diff[$post['object_id']] = intval(($now[$post['object_id']] - $avg[$post['object_id']]) * 1000 );
$win = count(array_filter($diff, create_function('$a', 'if($a > 0) return(TRUE);')));
$lose = count($diff) - $win;
$sort = array_flip($diff);
ksort($sort);
if(!empty($sort)){
foreach(array_slice(array_reverse($sort), 0, $detail_lines) as $object_id){
echo ''. get_the_title($object_id) .' Up: '. number_format($diff[$object_id] / 1000, 0) .' Avg: '. number_format($avg[$object_id], 0) .' Today: '. number_format($now[$object_id], 0) ." \n";
}
}
*/
//print_r($wpdb->queries);
update_option( 'bsuite_doing_migration', 0 );
update_option( 'bsuite_doing_migration_status', array() );
return(TRUE);
}
function get_search_engine( $ref ) {
// a lot of inspiration and code for this function was taken from
// Search Hilite by Ryan Boren and Matt Mullenweg
global $wp_query;
if( empty( $ref ))
return false;
$referer = urldecode( $ref );
if (preg_match('|^http://(www)?\.?google.*|i', $referer))
return('google');
if (preg_match('|^http://search\.yahoo.*|i', $referer))
return('yahoo');
if (preg_match('|^http://search\.live.*|i', $referer))
return('windowslive');
if (preg_match('|^http://search\.msn.*|i', $referer))
return('msn');
if (preg_match('|^http://search\.lycos.*|i', $referer))
return('lycos');
$home = parse_url( get_settings( 'siteurl' ));
$ref = parse_url( $referer );
if ( strpos( ' '. $ref['host'] , $home['host'] ))
return('internal');
return(FALSE);
}
function get_search_terms( $ref ) {
// a lot of inspiration and code for this function was taken from
// Search Hilite by Ryan Boren and Matt Mullenweg
// if( !$engine = $this->get_search_engine( $ref ))
// return(FALSE);
$engine = $this->get_search_engine( $ref );
$referer = parse_url( $ref );
parse_str( $referer['query'], $query_vars );
$query_array = array();
switch ($engine) {
case 'google':
if( $query_vars['q'] )
$query_array = explode(' ', urldecode( $query_vars['q'] ));
break;
case 'yahoo':
if( $query_vars['p'] )
$query_array = explode(' ', urldecode( $query_vars['p'] ));
break;
case 'windowslive':
if( $query_vars['q'] )
$query_array = explode(' ', urldecode( $query_vars['q'] ));
break;
case 'msn':
if( $query_vars['q'] )
$query_array = explode(' ', urldecode( $query_vars['q'] ));
break;
case 'lycos':
if( $query_vars['query'] )
$query_array = explode(' ', urldecode( $query_vars['query'] ));
break;
case 'internal':
if( $query_vars['s'] )
$query_array = explode(' ', urldecode( $query_vars['s'] ));
// also need to handle the case where a search matches the /search/ pattern
break;
}
$query_array = array_filter( array_map( array(&$this, 'trimquotes') , $query_array ));
return $query_array;
}
function post_hits( $args = '' ) {
global $wpdb;
$defaults = array(
'return' => 'formatted',
'days' => 0,
'template' => '%%title%% (%%hits%%) '
);
$args = wp_parse_args( $args, $defaults );
$post_id = (int) $args['post_id'] > 1 ? 'AND object_id = '. (int) $args['post_id'] : '';
$date = '';
if($args['days'] > 1)
$date = "AND hit_date > '". date("Y-m-d", mktime(0, 0, 0, date("m") , date("d") - $args['days'], date("Y"))) ."'";
// here's the query, but let's try to get the data from cache first
$request = "SELECT
FORMAT(SUM(hit_count), 0) AS hits,
FORMAT(AVG(hit_count), 0) AS average
FROM $this->hits_targets
WHERE 1=1
$post_id
AND object_type = 0
$date
";
if ( !$result = wp_cache_get( (int) $args['post_id'] .'_'. (int) $args['days'], 'bstat_post_hits' ) ) {
$result = $wpdb->get_results($request, ARRAY_A);
wp_cache_add( (int) $args['post_id'] .'_'. (int) $args['days'], $result, 'bstat_post_hits', 1800 );
}
if(empty($result))
return(NULL);
if($args['return'] == 'array')
return($result);
if($args['return'] == 'formatted'){
$list = str_replace(array('%%avg%%','%%hits%%'), array($result[0]['average'], $result[0]['hits']), $args['template']);
return($list);
}
}
function pop_posts( $args = '' ) {
global $wpdb, $bsuite;
$defaults = array(
'count' => 15,
'return' => 'formatted',
'template' => '%%title%% (%%hits%%) '
);
$args = wp_parse_args( $args, $defaults );
$date = 'AND hit_date = DATE(NOW())';
if($args['days'] > 1)
$date = "AND hit_date > '". date("Y-m-d", mktime(0, 0, 0, date("m") , date("d") - $args['days'], date("Y"))) ."'";
$limit = 'LIMIT '. (0 + $args['count']);
$request = "SELECT object_id, SUM(hit_count) AS hit_count
FROM $this->hits_targets
WHERE 1=1
AND object_type = 0
$date
GROUP BY object_id
ORDER BY hit_count DESC
$limit";
$result = $wpdb->get_results($request, ARRAY_A);
if(empty($result))
return(NULL);
if($args['return'] == 'array')
return($result);
if($args['return'] == 'formatted'){
$list = '';
foreach($result as $post){
$list .= str_replace(array('%%title%%','%%hits%%','%%link%%'), array(get_the_title($post['object_id']), $post['hit_count'], get_permalink($post['object_id'])), $args['template']);
}
return($list);
}
}
function pop_refs( $args = '' ) {
global $wpdb, $bsuite;
$defaults = array(
'count' => 15,
'return' => 'formatted',
'template' => '%%title%% (%%hits%%) '
);
$args = wp_parse_args( $args, $defaults );
$limit = 'LIMIT '. (int) $args['count'];
$request = "SELECT COUNT(*) AS hit_count, name
FROM (
SELECT object_id
FROM $this->hits_shistory
WHERE object_type = 2
ORDER BY sess_id DESC
LIMIT 1000
) a
LEFT JOIN $this->hits_terms t ON a.object_id = t.term_id
GROUP BY object_id
ORDER BY hit_count DESC
$limit";
$result = $wpdb->get_results($request, ARRAY_A);
if(empty($result))
return(NULL);
if($args['return'] == 'array')
return($result);
if($args['return'] == 'formatted'){
$list = '';
foreach($result as $row){
$list .= str_replace(array('%%title%%','%%hits%%'), array($row['name'], $row['hit_count']), $args['template']);
}
return($list);
}
}
// end stats functions
//
// Searchsmart
//
function searchsmart_posts_request( $query ){
global $wp_query, $wpdb;
if($wp_query->is_admin)
return($query);
if (!empty($wp_query->query_vars['s'])) {
$limit = explode('LIMIT', $query);
if(!$limit[1]){
// $paged, $posts_per_page, and $limit are here for cases
// where the query doesn't have an explicit LIMIT declaration
$paged = $wp_query->query_vars['paged'];
if(!$paged)
$paged = 1;
$posts_per_page = $wp_query->query_vars['posts_per_page'];
if(!$posts_per_page)
$posts_per_page = get_settings('posts_per_page');
$limit = explode('LIMIT', $query);
if(!$limit[1])
$limit[1] = ($paged - 1) * $posts_per_page .', '. $posts_per_page;
}
//print_r($wp_query);
//echo ''. $this->searchsmart_query( $wp_query->query_vars['s'], 'LIMIT '. $limit[1] ) .' ';
return( $this->searchsmart_query( $wp_query->query_vars['s'], 'LIMIT '. $limit[1] ));
}
return( $query );
}
function searchsmart_query( $searchphrase, $limit = 'LIMIT 0,5' ){
global $wpdb;
if( 3 < strlen( trim( $searchphrase ))){
return("SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.*
FROM (
SELECT post_id, MATCH (content, title) AGAINST (". $wpdb->prepare( '%s', $searchphrase ) .") AS score
FROM $this->search_table
WHERE MATCH (content, title) AGAINST (". $wpdb->prepare( '%s', $searchphrase ) .")
ORDER BY score DESC
LIMIT 1000
) s
LEFT JOIN $wpdb->posts ON ( s.post_id = $wpdb->posts.ID )
WHERE 1=1
AND post_status IN ('publish', 'private')
ORDER BY score DESC
$limit");
}else{
return("SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.*
FROM $wpdb->posts
WHERE 1=1
AND post_content LIKE ". $wpdb->prepare( '%s', '%'. $searchphrase .'%' ) ."
AND post_status IN ('publish', 'private')
ORDER BY post_date_gmt DESC $limit");
}
}
function searchsmart_direct(){
global $wp_query, $wp_rewrite;
// redirects ?s={search_term} to /search/{search_term} if permalinks are working
if( isset( $_GET['s'] ) && !empty( $wp_rewrite->permalink_structure ) )
wp_redirect(get_option('siteurl') .'/'. $wp_rewrite->search_base .'/'. urlencode( $_GET['s'] ), '301');
// redirects the search to the single page if the search returns only one item
if( !$wp_query->is_singular && 1 === $wp_query->post_count )
wp_redirect( get_permalink( $wp_query->post->ID ) , '302');
return(TRUE);
}
function searchsmart_delpost( $post_id ){
global $wpdb;
$wpdb->get_results( "DELETE FROM $this->search_table WHERE post_id = $post_id" );
}
function searchsmart_upindex($post_id, $content, $title = ''){
// put content in the keyword search index
global $wpdb;
$content = preg_replace(
'/\[\[([^\]])*\]\]/',
'',
strip_tags(
str_ireplace(array(' ', ' ', ' ', '', '', '', '', '', ''), "\n",
stripslashes(
html_entity_decode($content)))));
$content = trim(preg_replace(
'/([[:punct:]])*/',
'',
$content));
$content = apply_filters('bsuite_searchsmart_content', $content);
$title = preg_replace(
'/([[:punct:]])*/',
'',
html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
$request = "REPLACE INTO $this->search_table
(post_id, content, title)
VALUES ($post_id, '$content', '$title')";
$wpdb->get_results($request);
return(TRUE);
}
function searchsmart_upindex_passive(){
// finds unindexed posts and adds them to the fulltext index in groups of 10, runs via cron
// use a named mysql lock to prevent simultaneous execution
// locks automatically drop when the connection is dropped
// http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_get-lock
if( 0 == $wpdb->get_var( 'SELECT GET_LOCK("'. $this->lock_ftindexer .'", 2)' ))
return( TRUE );
// also use the options table
if ( get_option('bsuite_doing_ftindex') > time() )
return( TRUE );
update_option('bsuite_doing_ftindex', time() + 330 );
global $wpdb;
$posts = $wpdb->get_results("SELECT a.ID, a.post_content, a.post_title
FROM $wpdb->posts a
LEFT JOIN $this->search_table b ON a.ID = b.post_id
WHERE a.post_status = 'publish'
AND b.post_id IS NULL
LIMIT 10
", ARRAY_A);
if( count( $posts )) {
foreach( $posts as $post ) {
$this->searchsmart_upindex($post['ID'], $post['post_content'], $post['post_title']);
}
}
// diabled so that the update runs less often.
//update_option('bsuite_doing_ftindex', 0 );
return(TRUE);
}
function searchsmart_upindex_onedit($content){
// called when posts are edited or saved
if( (int) $_POST['post_ID'] )
$this->searchsmart_delpost( (int) $_POST['post_ID'] );
return($content);
}
// end Searchsmart
// bSuggestive related functions
function bsuggestive_query( $id ) {
global $wpdb;
$id = (int) $id;
if( $id ){
$taxonomies = ( array_filter( apply_filters( 'bsuite_suggestive_taxonomies', array( 'post_tag', 'category' ))));
if( is_array( $taxonomies ))
return( apply_filters('bsuite_suggestive_query',
"SELECT t_r.object_id AS post_id, COUNT(t_r.object_id) AS hits
FROM ( SELECT t_ra.term_taxonomy_id
FROM $wpdb->term_relationships t_ra
LEFT JOIN $wpdb->term_taxonomy t_ta ON t_ta.term_taxonomy_id = t_ra.term_taxonomy_id
WHERE t_ra.object_id = $id
AND t_ta.taxonomy IN ('". implode( $taxonomies, "','") ."')
) ttid
LEFT JOIN $wpdb->term_relationships t_r ON t_r.term_taxonomy_id = ttid.term_taxonomy_id
LEFT JOIN $wpdb->posts p ON t_r.object_id = p.ID
WHERE p.ID != $id
AND p.post_status = 'publish'
GROUP BY p.ID
ORDER BY hits DESC, p.post_date_gmt DESC
LIMIT 150", $id)
);
}
return FALSE;
}
function bsuggestive_getposts( $id ) {
global $wpdb;
if ( !$related_posts = wp_cache_get( $id, 'bsuite_related_posts' ) ) {
if( $the_query = $this->bsuggestive_query( $id ) ){
$related_posts = $wpdb->get_col($the_query);
wp_cache_add( $id, $related_posts, 'bsuite_related_posts', 864000 );
return($related_posts); // if we have to go to the DB to get the posts, then this will get returned
}
return( FALSE ); // if there's nothing in the cache and we've got no query
}
return($related_posts); // if the cache is still warm, then we return this
}
function bsuggestive_delete_cache( $id ) {
$id = (int) $id;
if ( !$id )
return FALSE;
wp_cache_delete( $id, 'bsuite_related_posts' );
}
function bsuggestive_the_related($before = '', $after = ' ') {
global $post;
$report = FALSE;
$id = (int) $post->ID;
if ( !$id )
return( FALSE ); // no ID, no service
$posts = array_slice($this->bsuggestive_getposts( $id ), 0, 5);
if($posts){
$report = '';
foreach($posts as $post_id){
// $post = &get_post( $post_id );
$url = get_permalink($post_id);
$linktext = get_the_title($post_id);
$report .= $before . "$linktext ". $after;
}
}
return($report);
}
function bsuggestive_the_content( $content ) {
if( $related = $this->bsuggestive_the_related() )
return( $content . '' );
return( $content );
}
// end bSuggestive
function pagetree(){
// identify the family tree of a page, return an array
global $wp_query;
$tree = NULL;
if ($wp_query->is_page){
$object = $wp_query->get_queried_object();
// cycle through the tree and build an array
$parent_id = $object->post_parent;
$tree[] = $object->ID;
while ($parent_id){
$page = get_page($parent_id);
$tree[] = $page->ID;
$parent_id = $page->post_parent;
}
// the tree is in reverse order.
$tree = array_reverse($tree);
}
return $tree;
}
//
// cron utility functions
//
function cron_reccurences( $schedules ) {
$schedules['bsuite_interval'] = array('interval' => get_option( 'bsuite_migration_interval' ), 'display' => __( 'bSuite interval. Set in bSuite options page.' ));
return( $schedules );
}
function cron_register() {
// take a look at Glenn Slaven's tutorial on WP's psudo-cron:
// http://blog.slaven.net.au/archives/2007/02/01/timing-is-everything
wp_clear_scheduled_hook('bsuite_interval');
wp_schedule_event( time() + 120, 'bsuite_interval', 'bsuite_interval' );
}
// end cron functions
//
// loadaverage related functions
//
function get_loadavg(){
static $result = FALSE;
if($result)
return($result);
if(function_exists('sys_getloadavg')){
$load_avg = sys_getloadavg();
}else{
$load_avg = &$this->sys_getloadavg();
}
return($load_avg[0]);
}
function sys_getloadavg(){
// the following code taken from tom pittlik's comment at
// http://php.net/manual/en/function.sys-getloadavg.php
$str = substr(strrchr(shell_exec('uptime'),':'),1);
$avs = array_map('trim',explode(',',$str));
return( $avs );
}
// end load average related functions
function trimquotes( $in ) {
return( trim( trim( $in ), "'\"" ));
}
function feedlink(){
return(strtolower(substr($_SERVER['SERVER_PROTOCOL'], 0, strpos($_SERVER['SERVER_PROTOCOL'], '/'))) . '://' . $_SERVER['HTTP_HOST'] . add_query_arg('feed', 'rss', add_query_arg('bsuite_share')));
}
// set a cookie
function cookie($name, $value = NULL) {
if($value === NULL){
if($_GET[$name]) return $_GET[$name];
elseif($_POST[$name]) return $_POST[$name];
elseif($_SESSION[$name]) return $_SESSION[$name];
elseif($_COOKIE[$name]) return $_COOKIE[$name];
else return false;
}else{
setcookie($name, $value, time()+60*60*24*30, '/', '.scriblio.net');
return($value);
}
}
// end
// get and display rss feeds
function get_feed($feed, $count = 15, $template = '%%title%% %%content%% ', $return = FALSE){
if(!function_exists('fetch_rss'))
require_once (ABSPATH . WPINC . '/rss.php');
$rss = fetch_rss($feed);
//print_r($rss);
$i = $list = NULL;
//print_r($rss);
foreach($rss->items as $item){
$i++;
if($i > $count)
break;
$link = $item['link'];
$title = '' . $item['title'] . ' ';
if($item['content']['encoded']){
$content = $item['content']['encoded'];
}else{
$content = $item['description'];
}
$list .= str_replace( array( '%%title%%','%%content%%','%%link%%' ), array( $title, $content, $link ), $template );
//echo $template;
}
if($return)
return($list);
echo $list;
}
// end function get_rss
// machine tags
function machtag_save_post($post_id, $post) {
// Passed machine tags overwrite existing if not empty
if ( isset( $_REQUEST['bsuite-machine-tags-input'] ))
foreach( $this->machtag_parse_tags( $_REQUEST['bsuite-machine-tags-input'] ) as $taxonomy => $tags ){
if( 'post_tag' == $taxonomy ){
wp_set_post_tags($post_id, $tags, true);
continue;
}
if(!is_taxonomy( $taxonomy ))
register_taxonomy($taxonomy, 'post');
wp_set_object_terms($post_id, $tags, $taxonomy);
}
}
function machtag_parse_tags( $tags_input ) {
$tags = $tags_parsed = array();
$tag_lines = explode( "\n", $tags_input );
foreach($tag_lines as $tag_line)
$tags_parsed[] = $this->machtag_parse_tag( $tag_line );
foreach( $tags_parsed as $tag_parsed )
$tags[$tag_parsed['taxonomy']][] = $tag_parsed['term'];
return( $tags );
}
function machtag_parse_tag( $tag ) {
$namespace = $taxonomy = $term = FALSE;
$taxonomy = 'post_tag';
$temp_a = explode(':', $tag, 2);
if($temp_a[1]){
$temp_b = explode('=', $temp_a[1], 2);
if($temp_b[1]){
// has namespace, fieldname, & value
$namespace = trim( $temp_a[0] );
$taxonomy = trim( $temp_b[0] );
$term = trim( $temp_b[1] );
}else{
// has just fieldname & value
$taxonomy = trim( $temp_a[0] );
$term = trim( $temp_b[0] );
}
}else{
$temp_b = explode('=', $temp_a[0], 2);
if($temp_b[1]){
// has just fieldname & value
$taxonomy = trim( $temp_b[0] );
$term = trim( $temp_b[1] );
}else{
// has just value
$term = trim( $temp_b[0] );
}
}
return(array('taxonomy' => $taxonomy, 'term' => $term));
}
// add tools to edit screens
function edit_page_form() {
$this->edit_insert_tag_form();
// $this->edit_insert_tools();
$this->edit_insert_machinetag_form();
}
function edit_post_form() {
// $this->edit_insert_tools();
$this->edit_insert_machinetag_form();
}
function edit_comment_form() {
// there's no edit_comment_form hook!!!
$this->edit_insert_tag_form();
$this->edit_insert_tools();
$this->edit_insert_machinetag_form();
}
function edit_insert_tag_form() {
global $post_ID;
?>
Tags (separate multiple tags with commas: cats, pet food, dogs)
bSuite Tools: Auto Tag Auto Excerpt (about these tools ) (NOT WORKING, for now)
taxonomy == 'post_tag' || $tag->taxonomy == 'category')
continue;
$tags_to_edit[] = $tag->taxonomy .'='. $tag->name;
}
natcasesort($tags_to_edit);
?>
bSuite Machine Tags (separate multiple tags with newlines, about machine tags )
ID; // needs an ID of that page/post
if(!$id)
return(NULL);
extract($args, EXTR_SKIP);
$options = get_option('bsuite_related_posts');
$title = empty($options['title']) ? __('Related Posts', 'bsuite') : $options['title'];
if ( !$number = (int) $options['number'] )
$number = 5;
else if ( $number < 1 )
$number = 1;
else if ( $number > 15 )
$number = 15;
if ( $related_posts = array_slice( $this->bsuggestive_getposts( $id ), 0, $number )) {
?>
';
echo ' Bookmark and Share ';
echo ' RSS Feeds ';
echo ' Translate ';
echo '';
echo $after_widget;
}
function widget_recently_commented_posts($args) {
// this code pretty much directly rips off WordPress' native recent comments widget,
// the difference here is that I'm displaying recently commented posts, not recent comments.
global $wpdb, $commented_posts;
extract($args, EXTR_SKIP);
$options = get_option('bsuite_recently_commented_posts');
$title = empty($options['title']) ? __('Recently Commented Posts', 'bsuite') : $options['title'];
if ( !$number = (int) $options['number'] )
$number = 5;
else if ( $number < 1 )
$number = 1;
else if ( $number > 15 )
$number = 15;
if ( !$commented_posts = wp_cache_get( 'recently_commented_posts', 'widget' ) ) {
$commented_posts = $wpdb->get_results("SELECT comment_ID, comment_post_ID, COUNT(comment_post_ID) as comment_count, MAX(comment_date_gmt) AS sort_order FROM $wpdb->comments WHERE comment_approved = '1' GROUP BY comment_post_ID ORDER BY sort_order DESC LIMIT $number");
wp_cache_add( 'recently_commented_posts', $commented_posts, 'widget' );
}
?>
widget_recently_commented_posts_delete_cache();
}
$title = attribute_escape($options['title']);
if ( !$number = (int) $options['number'] )
$number = 5;
?>
'bsuite_recently_commented_posts');
wp_register_sidebar_widget('bsuite-recently-commented-posts', __('bSuite Recently Commented', 'bsuite'), array($this, 'widget_recently_commented_posts'), $class);
wp_register_widget_control('bsuite-recently-commented-posts', __('bSuite Recently Commented', 'bsuite'), array($this, 'widget_recently_commented_posts_control'), $class, 'width=320&height=90');
if ( is_active_widget('widget_recently_commented_posts') ){
add_action('wp_head', 'wp_widget_recent_comments_style');
add_action( 'comment_post', array(&$this, 'widget_recently_commented_posts_delete_cache' ));
add_action( 'wp_set_comment_status', array(&$this, 'widget_recently_commented_posts_delete_cache' ));
}
}
function widget_popular_posts($args) {
global $post, $wpdb;
extract($args, EXTR_SKIP);
$options = get_option('bstat_pop_posts');
$title = empty($options['title']) ? __('Popular Posts') : $options['title'];
if ( !$number = (int) $options['number'] )
$number = 5;
else if ( $number < 1 )
$number = 1;
else if ( $number > 15 )
$number = 15;
if ( !$days = (int) $options['days'] )
$days = 7;
else if ( $days < 1 )
$days = 1;
else if ( $days > 30 )
$days = 30;
if ( !$pop_posts = wp_cache_get( 'bstat_pop_posts', 'widget' ) ) {
$pop_posts = $this->pop_posts("limit=$number&days=$days");
wp_cache_add( 'bstat_pop_posts', $pop_posts, 'widget', 3600 );
}
if ( !empty($pop_posts) ) {
?>
widget_popular_posts_delete_cache();
}
$title = attribute_escape($options['title']);
if ( !$number = (int) $options['number'] )
$number = 5;
if ( !$days = (int) $options['days'] )
$days = 7;
?>
15 )
$number = 15;
if ( !$days = (int) $options['days'] )
$days = 7;
else if ( $days < 1 )
$days = 1;
else if ( $days > 30 )
$days = 30;
if ( !$pop_refs = wp_cache_get( 'bstat_pop_refs', 'widget' ) ) {
$pop_refs = $this->pop_refs("limit=$number&days=$days");
wp_cache_add( 'bstat_pop_refs', $pop_refs, 'widget', 3600 );
}
if ( !empty($pop_refs) ) {
?>
widget_popular_refs_delete_cache();
}
$title = attribute_escape($options['title']);
if ( !$number = (int) $options['number'] )
$number = 5;
if ( !$days = (int) $options['days'] )
$days = 7;
?>
widget_recently_commented_posts_register();
wp_register_sidebar_widget('bsuite-related-posts', __('bSuite Related Posts', 'bsuite'), array(&$this, 'widget_related_posts'), 'bsuite_related_posts');
wp_register_widget_control('bsuite-related-posts', __('bSuite Related Posts', 'bsuite'), array(&$this, 'widget_related_posts_control'), 'width=320&height=90');
wp_register_sidebar_widget('bsuite-sharelinks', __('bSuite Share Links', 'bsuite'), array(&$this, 'widget_sharelinks'), 'bsuite_sharelinks');
wp_register_sidebar_widget('bstat-pop-posts', __('bStat Posts'), array(&$this, 'widget_popular_posts'), 'bstat-pop-posts');
wp_register_widget_control('bstat-pop-posts', __('bStat Posts'), array(&$this, 'widget_popular_posts_control'), 'width=320&height=90');
wp_register_sidebar_widget('bstat-pop-refs', __('bStat Refs'), array(&$this, 'widget_popular_refs'), 'bstat-pop-refs');
wp_register_widget_control('bstat-pop-refs', __('bStat Refs'), array(&$this, 'widget_popular_refs_control'), 'width=320&height=90');
}
// end widgets
// administrivia
function activate() {
update_option('bsuite_doing_migration', time() + 7200 );
$this->createtables();
$this->cron_register();
// set some defaults for the plugin
if(!get_option('bsuite_insert_related'))
update_option('bsuite_insert_related', TRUE);
if(!get_option('bsuite_insert_sharelinks'))
update_option('bsuite_insert_sharelinks', TRUE);
if(!get_option('bsuite_searchsmart'))
update_option('bsuite_searchsmart', TRUE);
if(!get_option('bsuite_swhl'))
update_option('bsuite_swhl', TRUE);
if(!get_option('bsuite_insert_css'))
update_option('bsuite_insert_css', TRUE);
if(!get_option('bsuite_migration_interval'))
update_option('bsuite_migration_interval', 90);
if(!get_option('bsuite_migration_count'))
update_option('bsuite_migration_count', 100);
if(!get_option('bsuite_load_max'))
update_option('bsuite_load_max', 4);
// set some defaults for the widgets
if(!get_option('bsuite_related_posts'))
update_option('bsuite_related_posts', array('title' => 'Related Posts', 'number' => 7));
if(!get_option('bsuite_recently_commented_posts'))
update_option('bsuite_recently_commented_posts', array('title' => 'Recently Commented Posts', 'number' => 7));
if(!get_option('bstat_pop_posts'))
update_option('bstat_pop_posts', array('title' => 'Popular Posts', 'number' => 5, 'days' => 7));
if(!get_option('bstat_pop_refs'))
update_option('bstat_pop_refs', array('title' => 'Popular Searches', 'number' => 5));
}
function createtables() {
global $wpdb;
$charset_collate = '';
if ( version_compare(mysql_get_server_info(), '4.1.0', '>=') ) {
if ( ! empty($wpdb->charset) )
$charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
if ( ! empty($wpdb->collate) )
$charset_collate .= " COLLATE $wpdb->collate";
}
require_once(ABSPATH . 'wp-admin/upgrade-functions.php');
dbDelta("
CREATE TABLE $this->search_table (
post_id bigint(20) NOT NULL,
content text,
title text,
PRIMARY KEY (post_id),
FULLTEXT KEY search (content, title)
) ENGINE=MyISAM $charset_collate
");
dbDelta("
CREATE TABLE $this->hits_incoming (
in_time timestamp NOT NULL default CURRENT_TIMESTAMP,
in_type tinyint(4) NOT NULL default '0',
in_session varchar(32) default '',
in_to text NOT NULL,
in_from text,
in_extra text
) ENGINE=MyISAM $charset_collate
");
dbDelta("
CREATE TABLE $this->hits_terms (
term_id bigint(20) NOT NULL auto_increment,
name varchar(255) NOT NULL default '',
PRIMARY KEY (term_id),
UNIQUE KEY name_uniq (name),
KEY name (name(8))
) ENGINE=MyISAM $charset_collate
");
dbDelta("
CREATE TABLE $this->hits_targets (
object_id bigint(20) unsigned NOT NULL default '0',
object_type smallint(6) NOT NULL,
hit_count smallint(6) unsigned NOT NULL default '0',
hit_date date NOT NULL default '0000-00-00',
PRIMARY KEY (object_id,object_type,hit_date)
) ENGINE=MyISAM $charset_collate
");
dbDelta("
CREATE TABLE $this->hits_searchphrases (
object_id bigint(20) unsigned NOT NULL default '0',
object_type smallint(6) NOT NULL,
term_id bigint(20) unsigned NOT NULL default '0',
hit_count smallint(6) unsigned NOT NULL default '0',
PRIMARY KEY (object_id,object_type,term_id),
KEY term_id (term_id)
) ENGINE=MyISAM $charset_collate
");
dbDelta("
CREATE TABLE $this->hits_sessions (
sess_id bigint(20) NOT NULL auto_increment,
sess_cookie varchar(32) NOT NULL default '',
sess_date datetime default NULL,
sess_ip varchar(16) NOT NULL default '',
sess_bl varchar(8) default '',
sess_bb varchar(24) default '',
sess_br varchar(24) default '',
sess_ba varchar(200) default '',
PRIMARY KEY (sess_id),
UNIQUE KEY sess_cookie_uniq (sess_cookie),
KEY sess_cookie (sess_cookie(2))
) ENGINE=MyISAM $charset_collate
");
dbDelta("
CREATE TABLE $this->hits_shistory (
sess_id bigint(20) NOT NULL auto_increment,
object_id bigint(20) NOT NULL,
object_type smallint(6) NOT NULL,
KEY sess_id (sess_id),
KEY object_id (object_id,object_type)
) ENGINE=MyISAM $charset_collate
");
dbDelta("
CREATE TABLE $this->hits_pop (
post_id bigint(20) NOT NULL,
date_start date NOT NULL,
hits_total bigint(20) NOT NULL,
hits_recent int(10) NOT NULL
) ENGINE=MyISAM $charset_collate
");
}
function addmenus() {
add_options_page('bSuite Settings', 'bSuite', 8, plugin_basename( dirname( __FILE__ )) .'/ui_options.php' );
// the bstat reports are handled in a seperate file
add_submenu_page('index.php', 'bSuite bStat Reports', 'bStat Reports', 2, plugin_basename( dirname( __FILE__ )) .'/ui_stats.php' );
}
function kses_allowedposttags() {
global $allowedposttags;
$allowedposttags['h1']['id'] = array();
$allowedposttags['h1']['class'] = array();
$allowedposttags['h2']['id'] = array();
$allowedposttags['h2']['class'] = array();
$allowedposttags['h3']['id'] = array();
$allowedposttags['h3']['class'] = array();
$allowedposttags['h4']['id'] = array();
$allowedposttags['h4']['class'] = array();
$allowedposttags['h5']['id'] = array();
$allowedposttags['h5']['class'] = array();
$allowedposttags['h6']['id'] = array();
$allowedposttags['h6']['class'] = array();
return(TRUE);
}
function makeXMLTree($data){
// create parser
$parser = xml_parser_create();
xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
xml_parse_into_struct($parser,$data,$values,$tags);
xml_parser_free($parser);
// we store our path here
$hash_stack = array();
// this is our target
$ret = array();
foreach ($values as $key => $val) {
switch ($val['type']) {
case 'open':
array_push($hash_stack, $val['tag']);
if (isset($val['attributes']))
$ret = $this->composeArray($ret, $hash_stack, $val['attributes']);
else
$ret = $this->composeArray($ret, $hash_stack);
break;
case 'close':
array_pop($hash_stack);
break;
case 'cdata':
array_push($hash_stack, 'cdata');
$ret = $this->composeArray($ret, $hash_stack, $val['value']);
array_pop($hash_stack);
break;
case 'complete':
array_push($hash_stack, $val['tag']);
$ret = $this->composeArray($ret, $hash_stack, $val['value']);
array_pop($hash_stack);
// handle attributes
if (isset($val['attributes'])){
foreach($val['attributes'] as $a_k=>$a_v){
$hash_stack[] = $val['tag'].'_attribute_'.$a_k;
$ret = $this->composeArray($ret, $hash_stack, $a_v);
array_pop($hash_stack);
}
}
break;
}
}
return($ret);
} // end makeXMLTree
function &composeArray($array, $elements, $value=array()){
// function used exclusively by makeXMLTree to help turn XML into an array
// get current element
$element = array_shift($elements);
// does the current element refer to a list
if(sizeof($elements) > 0){
$array[$element][sizeof($array[$element])-1] = &$this->composeArray($array[$element][sizeof($array[$element])-1], $elements, $value);
}else{ // if (is_array($value))
$array[$element][sizeof($array[$element])] = $value;
}
return($array);
} // end composeArray
function rebuildmetatables() {
// update search table with content from all posts
global $wpdb;
set_time_limit(0);
ignore_user_abort(TRUE);
$interval = 50;
if( !isset( $_REQUEST[ 'n' ] ) ) {
$n = 0;
$wpdb->hide_errors();
$this->createtables();
$wpdb->show_errors();
} else {
$n = (int) $_REQUEST[ 'n' ] ;
}
$posts = $wpdb->get_results("SELECT ID, post_content, post_title
FROM $wpdb->posts
ORDER BY ID
LIMIT $n, $interval
", ARRAY_A);
if( is_array( $posts ) ) {
echo '' . __('Rebuilding bSuite search index. Please be patient.', 'bsuite') . '
';
print "
";
foreach( $posts as $post ) {
$this->searchsmart_upindex($post['ID'], $post['post_content'], $post['post_title']);
echo 'updated post '. $post['ID'] ." \n ";
flush();
}
print " ";
?>
'. __('bSuite metdata index rebuilt.', 'bsuite') .'
';
?>
Code re-used under the terms of the GPL license
http://sourceforge.net/projects/sms-api/ SMS-API Sourceforge project page
get API ID and account at http://www.clickatell.com/ :
Clickatell documentation at https://www.clickatell.com/developers/api_http.php
it's worth knowing the Clickatell privacy policy too:
http://www.clickatell.com/company/privacy.php
example usage:
$mysms = new bSuite_sms( $API_ID, $USERNAME, $PASSWORD );
$mysms->send( $YOUR_MESSAGE, $TO_PHONE_NUMBER );
*/
var $use_ssl = FALSE;
var $balace_limit = 0;
var $balance = FALSE;
var $sending_method = 'fopen';
var $unicode = FALSE;
var $curl_use_proxy = FALSE;
var $curl_proxy = 'http://127.0.0.1:8080';
var $curl_proxyuserpwd = 'login:secretpass';
var $session;
var $error;
var $callback = 0;
var $msgstatuscodes = array(
'001' => 'Message unknown. The message ID is incorrect or reporting is delayed.',
'002' => 'Message queued. The message could not be delivered and has been queued for attempted redelivery.',
'003' => 'Delivered to gateway.Delivered to the upstream gateway or network (delivered to the recipient).',
'004' => 'Received by recipient. Confirmation of receipt on the handset of the recipient.',
'005' => 'Error with message. There was an error with the message, probably caused by the content of the message itself.',
'006' => 'User cancelled message delivery. The message was terminated by an internal mechanism.',
'007' => 'Error delivering message. An error occurred delivering the message to the handset.',
'008' => 'OK. Message received by gateway.',
'009' => 'Routing error. The routing gateway or network has had an error routing the message.',
'010' => 'Message expired. Message has expired before we were able to deliver it to the upstream gateway. No charge applies.',
'011' => 'Message queued for later delivery. Message has been queued at the gateway for delivery at a later time (delayed delivery).',
'012' => 'Out of credit. The message cannot be delivered due to a lack of funds in your account. Please re-purchase credits.'
); // codes come from clickatell docs https://www.clickatell.com/downloads/http/Clickatell_HTTP.pdf
function bSuite_sms( $api_id = '', $user = '', $password = '' ) {
/* authentication details */
if(( !$api_id ) || ( !$user ) || ( !$password )){
$this->error = 'You must specify an api id, username, and password.';
return( FALSE );
}
$this->api_id = $api_id;
$this->user = $user;
$this->password = $password;
/* SSL? */
if( $this->use_ssl ) {
$this->base = 'http://api.clickatell.com/http';
$this->base_s = 'https://api.clickatell.com/http';
} else {
$this->base = 'http://api.clickatell.com/http';
$this->base_s = $this->base;
}
$this->_auth();
}
function _auth() {
$comm = sprintf( '%s/auth?api_id=%s&user=%s&password=%s', $this->base_s, $this->api_id, $this->user, $this->password );
$this->session = $this->_parse_auth( $this->_execgw( $comm ));
}
function getbalance() {
$comm = sprintf( '%s/getbalance?session_id=%s', $this->base, $this->session );
$this->balance = $this->_parse_getbalance( $this->_execgw( $comm ));
return $this->balance;
}
/* check the status of a message by the ID returned from the API */
function querymsg( $msgid ) {
$comm = sprintf( '%s/querymsg?session_id=%s&apimsgid=%s',
$this->base,
$this->session,
$msgid
);
$result = $this->_execgw( $comm );
if( $this->msgstatuscodes[ substr( $result, stripos( $result, 'Status:' ) + 8 ) ] )
return( $this->msgstatuscodes[ substr( $result, stripos( $result, 'Status:' ) + 8 ) ]);
else
return( $result );
}
function send( $text=null, $to=null, $from=null ) {
/* Check SMS credits balance */
if( $this->getbalance() < $this->balace_limit ) {
$this->error = 'You have reach the SMS credit limit!';
return( FALSE );
};
/* Check SMS $text length */
if( $this->unicode == TRUE ) {
$this->_chk_mbstring();
if( mb_strlen( $text ) > 210 ) {
$this->error = 'Your unicode message is too long! (Current lenght='.mb_strlen ( $text ).')';
return( FALSE );
}
/* Does message need to be concatenate */
if( mb_strlen( $text ) > 70 ) {
$concat = '&concat=3';
} else {
$concat = '';
}
} else {
if( strlen( $text ) > 459 ) {
$this->error = 'Your message is too long! (Current lenght='.strlen( $text ).')';
return( FALSE );
}
/* Does message need to be concatenate */
if( strlen( $text ) > 160 ) {
$concat = '&concat=3';
} else {
$concat = '';
}
}
/* Check $to is not empty */
if( empty( $to )) {
$this->error = 'You not specify destination address (TO)!';
return( FALSE );
}
/* $from is optional and not universally supported */
/* Reformat $to number */
$cleanup_chr = array( '+', ' ', '(', ')', '\r', '\n', '\r\n');
$to = str_replace( $cleanup_chr, '', $to );
/* Mark this for later */
$this->last_to = $to;
$this->last_from = $from;
$this->last_message = $text;
/* Send SMS now */
$comm = sprintf( '%s/sendmsg?session_id=%s&to=%s&from=%s&text=%s&callback=%s&unicode=%s%s',
$this->base,
$this->session,
rawurlencode( $to ),
rawurlencode( $from ),
$this->encode_message( $text ),
$this->callback,
$this->unicode,
$concat
);
return $this->_parse_send( $this->_execgw( $comm ));
}
function encode_message( $text ) {
if( $this->unicode != TRUE ) {
//standard encoding
return rawurlencode( $text );
} else {
//unicode encoding
$uni_text_len = mb_strlen( $text, 'UTF-8' );
$out_text = '';
//encode each character in text
for( $i=0; $i<$uni_text_len; $i++ ) {
$out_text .= $this->uniord( mb_substr( $text, $i, 1, 'UTF-8' ));
}
return $out_text;
}
}
function uniord( $c ) {
$ud = 0;
if( ord( $c{0} )>=0 && ord( $c{0} )<=127 )
$ud = ord( $c{0} );
if( ord( $c{0} )>=192 && ord( $c{0} )<=223 )
$ud = ( ord( $c{0} )-192 )*64 + ( ord( $c{1} )-128 );
if( ord( $c{0} )>=224 && ord( $c{0} )<=239 )
$ud = ( ord( $c{0} )-224 )*4096 + ( ord( $c{1} )-128 )*64 + ( ord( $c{2} )-128 );
if( ord( $c{0} )>=240 && ord( $c{0} )<=247 )
$ud = ( ord( $c{0} )-240 )*262144 + ( ord( $c{1} )-128 )*4096 + ( ord( $c{2} )-128 )*64 + ( ord( $c{3} )-128 );
if( ord( $c{0} )>=248 && ord( $c{0} )<=251 )
$ud = ( ord( $c{0} )-248 )*16777216 + ( ord( $c{1} )-128 )*262144 + ( ord( $c{2} )-128 )*4096 + ( ord( $c{3} )-128 )*64 + ( ord( $c{4} )-128 );
if( ord( $c{0} )>=252 && ord( $c{0} )<=253 )
$ud = ( ord( $c{0} )-252 )*1073741824 + ( ord( $c{1} )-128 )*16777216 + ( ord( $c{2} )-128 )*262144 + ( ord( $c{3} )-128 )*4096 + ( ord( $c{4} )-128 )*64 + ( ord( $c{5} )-128 );
if( ord( $c{0} )>=254 && ord( $c{0} )<=255 ) //error
$ud = FALSE;
return sprintf( '%04x', $ud );
}
function token_pay( $token ) {
$comm = sprintf( '%s/http/token_pay?session_id=%s&token=%s',
$this->base,
$this->session,
$token );
return $this->_execgw( $comm );
}
function _execgw( $command ) {
if( $this->sending_method == 'curl' )
return $this->_curl( $command );
if( $this->sending_method == 'fopen' )
return $this->_fopen( $command );
$this->error = 'Unsupported sending method!';
return( FALSE );
}
function _curl( $command ) {
$this->_chk_curl();
$ch = curl_init( $command );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER,1 );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER,0 );
if( $this->curl_use_proxy ) {
curl_setopt( $ch, CURLOPT_PROXY, $this->curl_proxy );
curl_setopt( $ch, CURLOPT_PROXYUSERPWD, $this->curl_proxyuserpwd );
}
$result=curl_exec( $ch );
curl_close( $ch );
return $result;
}
function _fopen( $command ) {
$result = '';
$handler = @fopen( $command, 'r' );
if( $handler ) {
while( $line = @fgets( $handler,1024 )) {
$result .= $line;
}
fclose( $handler );
return $result;
} else {
$this->error = 'Error while executing fopen sending method! Please check does PHP have OpenSSL support and is PHP version is greater than 4.3.0.';
return( FALSE );
}
}
function _parse_auth( $result ) {
$session = substr( $result, 4 );
$code = substr( $result, 0, 2 );
if( $code!='OK' ) {
$this->error = "Error in SMS authorization! ($result)";
return( FALSE );
}
return $session;
}
function _parse_send( $result ) {
if( 'ID' <> substr( $result, 0, 2 )) {
$this->error = "Error sending SMS! ($result)";
$this->last_status = 'ERROR';
return( FALSE );
} else {
$this->last_id = trim( substr( $result, 3 ));
$this->last_status = 'OK';
return( 'OK' );
}
}
function _parse_getbalance( $result ) {
$result = substr( $result, 8 );
return (int ) $result;
}
function _chk_curl() {
if( !extension_loaded( 'curl' )) {
$this->error = 'This SMS API class can not work without CURL PHP module! Try using fopen sending method.';
return( FALSE );
}
}
function _chk_mbstring() {
if( !extension_loaded( 'mbstring' )) {
$this->error = 'Error. This SMS API class is setup to use Multibyte String Functions module - mbstring, but module not found. Please try to set unicode=false in class or install mbstring module into PHP.';
return( FALSE );
}
}
}
function the_related(){
global $bsuite;
echo $bsuite->bsuggestive_the_related();
}
function paginated_links(){
GLOBAL $wp_query;
$page = 1;
if( (int) $wp_query->query_vars['paged'] )
$page = (int) $wp_query->query_vars['paged'];
$total = (int) $wp_query->max_num_pages;
$page_links = paginate_links( array(
'base' => add_query_arg( 'paged', '%#%' ),
'format' => '',
'total' => $total,
'current' => $page
));
if ( $page_links )
echo "$page_links
";
}
function bsuite_feedlink() {
global $bsuite;
return( $bsuite->feedlink() );
}
function bsuite_link2me() {
global $bsuite;
echo $bsuite->link2me();
}
function bstat_hits($template = '%%hits%% hits, about %%avg%% daily', $post_id = NULL, $todayonly = 0, $return = NULL) {
global $bsuite;
if(!empty($return))
return($bsuite->post_hits(array('post_id' => $post_id,'days' => $todayonly, 'template' => $template )));
echo $bsuite->post_hits(array('post_id' => $post_id,'days' => $todayonly, 'template' => $template ));
}
// deprecated functions
function bstat_pulse($post_id = 0, $maxwidth = 400, $disptext = 1, $dispcredit = 1, $accurate = 4) {
// this one isn't so much deprecated as, well,
// the code sucks and I haven't re-written it yet
global $wpdb, $bstat;
$post_id = (int) $post_id;
$for_post_id = $post_id > 1 ? 'AND post_id = '. $post_id : '';
// here's the query, but let's try to get the data from cache first
$request = "SELECT
SUM(hit_count) AS hits,
hit_date
FROM $bstat->hits_table
WHERE 1=1
$for_post_id
GROUP BY hit_date
";
if ( !$result = wp_cache_get( $post_id, 'bstat_post_pulse' ) ) {
$result = $wpdb->get_results($request, ARRAY_A);
wp_cache_add( $post_id, $result, 'bstat_post_pulse', 3600 );
}
if(empty($result))
return(NULL);
$tot = count($result);
if(count($result)>0){
$point = null;
$point[] = 0;
foreach($result as $row){
$point[] = $row['hits'];
}
$sum = array_sum($point);
$max = max($point);
$avg = round($sum / $tot);
if($accurate == 4){
$graphaccurate = get_option('bstat_graphaccurate');
}else{
$graphaccurate = $accurate;
}
$minwidth = ($maxwidth / 8.1);
if($graphaccurate) $minwidth = ($maxwidth / 4.1);
while(count($point) <= $minwidth){
$newpoint = null;
for ($i = 0; $i < count($point); $i++) {
if($i > 0){
if(!$graphaccurate) $newpoint[] = ((($point[$i-1] * 2) + $point[$i]) / 3);
$newpoint[] = (($point[$i-1] + $point[$i]) / 2);
if(!$graphaccurate) $newpoint[] = (($point[$i-1] + ($point[$i-1] * 2)) / 3);
}
$newpoint[] = $point[$i];
}
$point = $newpoint;
}
$tot = count($point);
$width = round($maxwidth / $tot);
if($width > 3)
$width = 4;
if($width < 1)
$width = 1;
if(($width * $tot) > $maxwidth)
$skipstart = (($width * $tot) - $maxwidth) / $width;
$i = 1;
$hit_chart = "";
foreach($point as $row){
if((!$skipstart) || ($i > $skipstart)){
$hit_chart .= " ";
}
$i++;
}
$pre = "";
$post = "
";
$disptext = ($disptext == 1) ? (number_format($sum) .' total reads, averaging '. number_format($avg) .' daily') : ("");
$dispcredit = ($dispcredit == 1) ? ("stats powered by bSuite bStat ") : ("");
$disptext = (($disptext) || ($dispcredit)) ? ("\n$disptext\n $dispcredit
") : ("");
echo($pre . $hit_chart . "\n" . $disptext . $post);
}
}
// php4 compatibility, argh
if(!function_exists('str_ireplace')){
function str_ireplace($a, $b, $c){
return str_replace($a, $b, $c);
}
}
?>