/**
* The WordPress version string
*
* @global string $wp_version
*/
$wp_version = '3.2.1';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.
*
* @global int $wp_db_version
*/
$wp_db_version = 18226;
/**
* Holds the TinyMCE version
*
* @global string $tinymce_version
*/
$tinymce_version = '342-20110630';
/**
* Holds the cache manifest version
*
* @global string $manifest_version
*/
$manifest_version = '20111113';
/**
* Holds the required PHP version
*
* @global string $required_php_version
*/
$required_php_version = '5.2.4';
/**
* Holds the required MySQL version
*
* @global string $required_mysql_version
*/
$required_mysql_version = '5.0';
/*
Plugin Name: Audio player
Plugin URI: http://wpaudioplayer.com
Description: Audio Player is a highly configurable but simple mp3 player for all your audio needs. You can customise the player's colour scheme to match your blog theme, have it automatically show track information from the encoded ID3 tags and more. Go to your Settings page to start configuring it.
Version: 2.0.4.1
Author: Martin Laine
Author URI: http://www.1pixelout.net
License:
Copyright (c) 2010 Martin Laine
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Pre-2.6 compatibility
if ( ! defined( 'WP_CONTENT_URL' ) )
define( 'WP_CONTENT_URL', get_option( 'siteurl' ) . '/wp-content' );
if ( ! defined( 'WP_CONTENT_DIR' ) )
define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' );
if ( ! defined( 'WP_PLUGIN_URL' ) )
define( 'WP_PLUGIN_URL', WP_CONTENT_URL. '/plugins' );
if ( ! defined( 'WP_PLUGIN_DIR' ) )
define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' );
if (!class_exists('AudioPlayer')) {
class AudioPlayer {
// Name for serialized options saved in database
var $optionsName = "AudioPlayer_options";
var $version = "2.0.4.1";
var $docURL = "http://wpaudioplayer.com/";
// Internationalisation
var $textDomain = "audio-player";
var $languageFileLoaded = false;
// Various path variables
var $pluginURL = "";
var $pluginPath = "";
var $playerURL = "";
var $audioRoot = "";
var $audioAbsPath = "";
var $isCustomAudioRoot = false;
// Options page name
var $optionsPageName = "audio-player-options";
// Colour scheme keys
var $colorKeys = array(
"bg",
"leftbg",
"lefticon",
"voltrack",
"volslider",
"rightbg",
"rightbghover",
"righticon",
"righticonhover",
"text",
"track",
"border",
"loader",
"tracker",
"skip"
);
// Default colour scheme
var $defaultColorScheme = array(
"bg" => "E5E5E5",
"text" => "333333",
"leftbg" => "CCCCCC",
"lefticon" => "333333",
"volslider" => "666666",
"voltrack" => "FFFFFF",
"rightbg" => "B4B4B4",
"rightbghover" => "999999",
"righticon" => "333333",
"righticonhover" => "FFFFFF",
"track" => "FFFFFF",
"loader" => "009900",
"border" => "CCCCCC",
"tracker" => "DDDDDD",
"skip" => "666666",
"pagebg" => "FFFFFF",
"transparentpagebg" => true
);
// Declare instances global variable
var $instances = array();
// Used to track what needs to be inserted in the footer
var $footerCode = "";
// Initialise playerID (each instance gets unique ID)
var $playerID = 0;
// Flag for dealing with excerpts
var $inExcerpt = false;
/**
* Constructor
*/
function AudioPlayer() {
// Get plugin URL and absolute path
$this->pluginPath = WP_PLUGIN_DIR . "/" . plugin_basename(dirname(__FILE__));
$this->pluginURL = WP_PLUGIN_URL . "/" . plugin_basename(dirname(__FILE__));
$this->playerURL = $this->pluginURL . "/assets/player.swf";
// Load options
$this->options = $this->getOptions();
// Set audio root from options
$this->setAudioRoot();
// Add action and filter hooks to WordPress
add_action("init", array(&$this, "optionsPanelAction"));
add_action("admin_menu", array(&$this, "addAdminPages"));
add_filter("plugin_action_links", array(&$this, "addConfigureLink"), 10, 2);
add_action("wp_head", array(&$this, "addHeaderCode"));
add_action("wp_footer", array(&$this, "addFooterCode"));
add_filter("the_content", array(&$this, "processContent"), 2);
if (in_array("comments", $this->options["behaviour"])) {
add_filter("comment_text", array(&$this, "processContent"));
}
add_filter("get_the_excerpt", array(&$this, "inExcerpt"), 1);
add_filter("get_the_excerpt", array(&$this, "outOfExcerpt"), 12);
add_filter("the_excerpt", array(&$this, "processContent"));
add_filter("the_excerpt_rss", array(&$this, "processContent"));
add_filter("attachment_fields_to_edit", array(&$this, "insertAudioPlayerButton"), 10, 2);
add_filter("media_send_to_editor", array(&$this, "sendToEditor"));
if ($this->options["disableEnclosures"]) {
add_filter("rss_enclosure", array(&$this, "removeEnclosures"));
add_filter("atom_enclosure", array(&$this, "removeEnclosures"));
}
}
/**
* Removes all enclosures from feeds
* @return empty string
*/
function removeEnclosures() {
return "";
}
/**
* Adds Audio Player options tab to admin menu
*/
function addAdminPages() {
global $wp_version;
$pageName = add_options_page("Audio player options", "Audio Player", 8, $this->optionsPageName, array(&$this, "outputOptionsSubpanel"));
add_action("admin_head-" . $pageName, array(&$this, "addAdminHeaderCode"), 12);
// Use the bundled jquery library if we are running WP 2.5 or above
if (version_compare($wp_version, "2.5", ">=")) {
wp_enqueue_script("jquery", false, false, "1.2.3");
}
}
/**
* Adds a settings link next to Audio Player on the plugins page
*/
function addConfigureLink($links, $file) {
static $this_plugin;
if (!$this_plugin) {
$this_plugin = plugin_basename(__FILE__);
}
if ($file == $this_plugin) {
$settings_link = '' . __('Settings') . ' ';
array_unshift($links, $settings_link);
}
return $links;
}
/**
* Adds subtle plugin credits to WP footer
*/
function addFooterCredits() {
$plugin_data = get_plugin_data(__FILE__);
printf('%1$s plugin | Version %2$s ', $plugin_data['Name'], $plugin_data['Version']);
}
/**
* Loads language files according to locale (only does this once per request)
*/
function loadLanguageFile() {
if(!$this->languageFileLoaded) {
load_plugin_textdomain($this->textDomain, "wp-content/plugins/audio-player/languages", dirname( plugin_basename( __FILE__ ) ) . "/languages");
$this->languageFileLoaded = true;
}
}
/**
* Retrieves options from DB. Also sets defaults if options not set
* @return array of options
*/
function getOptions() {
// Set default options array to make sure all the necessary options
// are available when called
$options = array(
"audioFolder" => "/audio",
"playerWidth" => "290",
"enableAnimation" => true,
"showRemaining" => false,
"encodeSource" => true,
"behaviour" => array("default"),
"enclosuresAtTop" => false,
"flashAlternate" => "",
"rssAlternate" => "nothing",
"rssCustomAlternate" => __("[Audio clip: view full post to listen]", $this->textDomain),
"excerptAlternate" => __("[Audio clip: view full post to listen]", $this->textDomain),
"introClip" => "",
"outroClip" => "",
"initialVolume" => "60",
"bufferTime" => "5",
"noInfo" => false,
"checkPolicy" => false,
"rtl" => false,
"disableEnclosures" => false,
"colorScheme" => $this->defaultColorScheme
);
$savedOptions = get_option($this->optionsName);
if (!empty($savedOptions)) {
foreach ($savedOptions as $key => $option) {
$options[$key] = $option;
}
}
// 1.x version upgrade
if (!array_key_exists("version", $options)) {
if (get_option("audio_player_web_path")) $options["audioFolder"] = get_option("audio_player_web_path");
if (get_option("audio_player_behaviour")) $options["behaviour"] = explode(",", get_option("audio_player_behaviour"));
if (get_option("audio_player_rssalternate")) $options["rssAlternate"] = get_option("audio_player_rssalternate");
if (get_option("audio_player_rsscustomalternate")) $options["rssCustomAlternate"] = get_option("audio_player_rsscustomalternate");
if (get_option("audio_player_prefixaudio")) $options["introClip"] = get_option("audio_player_prefixaudio");
if (get_option("audio_player_postfixaudio")) $options["outroClip"] = get_option("audio_player_postfixaudio");
if (get_option("audio_player_transparentpagebgcolor")) {
$options["colorScheme"]["bg"] = str_replace("0x", "", get_option("audio_player_bgcolor"));
$options["colorScheme"]["text"] = str_replace("0x", "", get_option("audio_player_textcolor"));
$options["colorScheme"]["skip"] = str_replace("0x", "", get_option("audio_player_textcolor"));
$options["colorScheme"]["leftbg"] = str_replace("0x", "", get_option("audio_player_leftbgcolor"));
$options["colorScheme"]["lefticon"] = str_replace("0x", "", get_option("audio_player_lefticoncolor"));
$options["colorScheme"]["volslider"] = str_replace("0x", "", get_option("audio_player_lefticoncolor"));
$options["colorScheme"]["rightbg"] = str_replace("0x", "", get_option("audio_player_rightbgcolor"));
$options["colorScheme"]["rightbghover"] = str_replace("0x", "", get_option("audio_player_rightbghovercolor"));
$options["colorScheme"]["righticon"] = str_replace("0x", "", get_option("audio_player_righticoncolor"));
$options["colorScheme"]["righticonhover"] = str_replace("0x", "", get_option("audio_player_righticonhovercolor"));
$options["colorScheme"]["track"] = str_replace("0x", "", get_option("audio_player_trackcolor"));
$options["colorScheme"]["loader"] = str_replace("0x", "", get_option("audio_player_loadercolor"));
$options["colorScheme"]["border"] = str_replace("0x", "", get_option("audio_player_bordercolor"));
$options["colorScheme"]["transparentpagebg"] = (bool) get_option("audio_player_transparentpagebgcolor");
$options["colorScheme"]["pagebg"] = str_replace("#", "", get_option("audio_player_pagebgcolor"));
}
} else if (version_compare($options["version"], $this->version) == -1) {
// Upgrade code
$options["colorScheme"]["transparentpagebg"] = (bool) $options["colorScheme"]["transparentpagebg"];
}
// Record current version in DB
$options["version"] = $this->version;
// Update DB if necessary
update_option($this->optionsName, $options);
return $options;
}
/**
* Writes options to DB
*/
function saveOptions() {
update_option($this->optionsName, $this->options);
}
/**
* Sets the real audio root from the audio folder option
*/
function setAudioRoot() {
$this->audioRoot = $this->options["audioFolder"];
$this->audioAbsPath = "";
$this->isCustomAudioRoot = true;
if (!$this->isAbsoluteURL($this->audioRoot)) {
$sysDelimiter = '/';
if (strpos(ABSPATH, '\\') !== false) $sysDelimiter = '\\';
$this->audioAbsPath = preg_replace('/[\\\\\/]+/', $sysDelimiter, ABSPATH . $this->audioRoot);
$this->isCustomAudioRoot = false;
$this->audioRoot = get_option('siteurl') . $this->audioRoot;
}
}
/**
* Builds and returns array of options to pass to Flash player
* @return array
*/
function getPlayerOptions() {
$playerOptions = array();
$playerOptions["width"] = $this->options["playerWidth"];
$playerOptions["animation"] = $this->options["enableAnimation"];
$playerOptions["encode"] = $this->options["encodeSource"];
$playerOptions["initialvolume"] = $this->options["initialVolume"];
$playerOptions["remaining"] = $this->options["showRemaining"];
$playerOptions["noinfo"] = $this->options["noInfo"];
$playerOptions["buffer"] = $this->options["bufferTime"];
$playerOptions["checkpolicy"] = $this->options["checkPolicy"];
$playerOptions["rtl"] = $this->options["rtl"];
return array_merge($playerOptions, $this->options["colorScheme"]);
}
// ------------------------------------------------------------------------------
// Excerpt helper functions
// Sets a flag so we know we are in an automatically created excerpt
// ------------------------------------------------------------------------------
/**
* Sets a flag when getting an excerpt
* @return excerpt text
* @param $text String[optional] unchanged excerpt text
*/
function inExcerpt($text = '') {
// Only set the flag when the excerpt is empty and WP creates one automatically)
if('' == $text) $this->inExcerpt = true;
return $text;
}
/**
* Resets a flag after getting an excerpt
* @return excerpt text
* @param $text String[optional] unchanged excerpt text
*/
function outOfExcerpt($text = '') {
$this->inExcerpt = false;
return $text;
}
/**
* Filter function (inserts player instances according to behaviour option)
* @return the parsed and formatted content
* @param $content String[optional] the content to parse
*/
function processContent($content = '') {
global $comment;
$this->loadLanguageFile();
// Reset instance array (this is so we don't insert duplicate players)
$this->instances = array();
// Replace mp3 links (don't do this in feeds and excerpts)
if ( !is_feed() && !$this->inExcerpt && in_array( "links", $this->options["behaviour"] ) ) {
$pattern = "/([^<]+)<\/a>/i";
$content = preg_replace_callback( $pattern, array(&$this, "insertPlayer"), $content );
}
// Replace [audio syntax]
if( in_array( "default", $this->options["behaviour"] ) ) {
$pattern = "/()?\[audio:(([^]]+))\](<\/p>)?/i";
$content = preg_replace_callback( $pattern, array(&$this, "insertPlayer"), $content );
}
// Enclosure integration (don't do this for feeds, excerpts and comments)
if( !is_feed() && !$this->inExcerpt && !$comment && in_array( "enclosure", $this->options["behaviour"] ) ) {
$enclosure = get_enclosed($post_id);
// Insert intro and outro clips if set
$introClip = $this->options["introClip"];
if( $introClip != "" ) $introClip .= ",";
$outroClip = $this->options["outroClip"];
if( $outroClip != "" ) $outroClip = "," . $outroClip;
if( count($enclosure) > 0 ) {
for($i = 0;$i < count($enclosure);$i++) {
// Make sure the enclosure is an mp3 file and it hasn't been inserted into the post yet
if( preg_match( "/.*\.mp3$/", $enclosure[$i] ) == 1 && !in_array( $enclosure[$i], $this->instances ) ) {
if ($this->options["enclosuresAtTop"]) {
$content = $this->getPlayer( $introClip . $enclosure[$i] . $outroClip, null, $enclosure[$i] ) . "\n\n" . $content;
} else {
$content .= "\n\n" . $this->getPlayer( $introClip . $enclosure[$i] . $outroClip, null, $enclosure[$i] );
}
}
}
}
}
return $content;
}
/**
* Callback function for preg_replace_callback
* @return string to replace matches with
* @param $matches Array
*/
function insertPlayer($matches) {
// Split options
$data = preg_split("/[\|]/", $matches[3]);
$files = array();
// Alternate content for excerpts (don't do this for feeds)
if($this->inExcerpt && !is_feed()) {
return $this->options["excerptAlternate"];
}
if (!is_feed()) {
// Insert intro clip if set
if ( $this->options["introClip"] != "" ) {
$afile = $this->options["introClip"];
if (!$this->isAbsoluteURL($afile)) {
$afile = $this->audioRoot . "/" . $afile;
}
array_push( $files, $afile );
}
}
$actualFiles = array();
$actualFile = "";
// Create an array of files to load in player
foreach ( explode( ",", trim($data[0]) ) as $afile ) {
$afile = trim($afile);
// Get absolute URLs for relative ones
if (!$this->isAbsoluteURL($afile)) {
$afile = $this->audioRoot . "/" . $afile;
}
array_push( $actualFiles, $afile );
array_push( $files, $afile );
// Add source file to instances already added to the post
array_push( $this->instances, $afile );
}
if (count($actualFiles) == 1) {
$actualFile = $actualFiles[0];
}
if (!is_feed()) {
// Insert outro clip if set
if ( $this->options["outroClip"] != "" ) {
$afile = $this->options["outroClip"];
if (!$this->isAbsoluteURL($afile)) {
$afile = $this->audioRoot . "/" . $afile;
}
array_push( $files, $afile );
}
}
// Build runtime options array
$playerOptions = array();
for ($i = 1; $i < count($data); $i++) {
$pair = explode("=", $data[$i]);
$playerOptions[trim($pair[0])] = trim($pair[1]);
}
// Return player instance code
return $this->getPlayer( implode( ",", $files ), $playerOptions, $actualFile );
}
/**
* Generic player instance function (returns player widget code to insert)
* @return String the html code to insert
* @param $source String list of mp3 file urls to load in player
* @param $playerOptions Object[optional] options to load in player
* @param $actualFile String[optional] url of main single file (empty if multiple files)
*/
function getPlayer($source, $playerOptions = array(), $actualFile = "") {
// Decode HTML entities in file names
if (function_exists("html_entity_decode")) {
$source = html_entity_decode($source);
}
// Add source to options and encode if necessary
if ($this->options["encodeSource"]) {
$playerOptions["soundFile"] = $this->encodeSource($source);
} else {
$playerOptions["soundFile"] = $source;
}
if (is_feed()) {
// We are in a feed so use RSS alternate content option
switch ( $this->options["rssAlternate"] ) {
case "download":
// Get filenames from path and output a link for each file in the sequence
$files = explode(",", $source);
$links = "";
for ($i = 0; $i < count($files); $i++) {
$fileparts = explode("/", $files[$i]);
$fileName = $fileparts[count($fileparts)-1];
$links .= '' . __('Download audio file', $this->textDomain) . ' (' . $fileName . ') ';
}
return $links;
break;
case "nothing":
return "";
break;
case "custom":
return $this->options["rssCustomAlternate"];
break;
}
} else {
// Not in a feed so return player widget
$playerElementID = "audioplayer_" . ++$this->playerID;
if (strlen($this->options["flashAlternate"]) > 0) {
$playerCode = str_replace(array("%playerID%", "%downloadURL%"), array($playerElementID, $actualFile), $this->options["flashAlternate"]);
} else {
$playerCode = '
' . sprintf(__('Audio clip: Adobe Flash Player (version 9 or above) is required to play this audio clip. Download the latest version here . You also need to have JavaScript enabled in your browser.', $this->textDomain), 'http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash&promoid=BIOW') . '
';
}
$this->footerCode .= 'AudioPlayer.embed("' . $playerElementID . '", ' . $this->php2js($playerOptions) . ');';
$this->footerCode .= "\n";
return $playerCode;
}
}
/**
* Outputs the options sub panel
*/
function outputOptionsSubpanel() {
$this->loadLanguageFile();
add_action("in_admin_footer", array(&$this, "addFooterCredits"));
// Include options panel
include($this->pluginPath . "/php/options-panel.php");
}
/**
* Handles submitted options (validates and saves modified options)
*/
function optionsPanelAction() {
if( isset($_POST['AudioPlayerReset']) && $_POST['AudioPlayerReset'] == "1" ) {
if( function_exists('current_user_can') && !current_user_can('manage_options') ) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
// Reset colour scheme back to default values
$this->options["colorScheme"] = $this->defaultColorScheme;
$this->saveOptions();
$goback = add_query_arg("updated", "true", "options-general.php?page=" . $this->optionsPageName);
wp_redirect($goback);
exit();
} else if( isset($_POST['AudioPlayerSubmit']) ) {
if( function_exists('current_user_can') && !current_user_can('manage_options') ) {
wp_die(__('You do not have sufficient permissions to access this page.'));
}
if ( function_exists('check_admin_referer') ) {
check_admin_referer('audio-player-action');
}
// Set audio web path
$_POST['ap_audiowebpath'] = trim($_POST['ap_audiowebpath']);
if ($_POST["ap_audiowebpath_iscustom"] != "true") {
if ( substr( $_POST['ap_audiowebpath'], -1, 1 ) == "/" ) {
$_POST['ap_audiowebpath'] = substr( $_POST['ap_audiowebpath'], 0, strlen( $_POST['ap_audiowebpath'] ) - 1 );
}
if ( substr( $_POST['ap_audiowebpath'], 0, 1 ) != "/" ) {
$_POST['ap_audiowebpath'] = "/" . $_POST['ap_audiowebpath'];
}
$this->options["audioFolder"] = $_POST['ap_audiowebpath'];
} else if ($this->isAbsoluteURL($_POST['ap_audiowebpath'])) {
$this->options["audioFolder"] = $_POST['ap_audiowebpath'];
}
// Update behaviour and rss alternate content options
$this->options["encodeSource"] = isset( $_POST["ap_encodeSource"] );
$this->options["enableAnimation"] = !isset( $_POST["ap_disableAnimation"] );
$this->options["showRemaining"] = isset( $_POST["ap_showRemaining"] );
$this->options["noInfo"] = isset( $_POST["ap_disableTrackInformation"] );
$this->options["checkPolicy"] = isset( $_POST["ap_checkPolicy"] );
$this->options["rtl"] = isset( $_POST["ap_rtlMode"] );
$this->options["enclosuresAtTop"] = isset( $_POST["ap_enclosuresAtTop"] );
$this->options["disableEnclosures"] = isset( $_POST["ap_disableEnclosures"] );
if (isset($_POST['ap_behaviour'])) {
$this->options["behaviour"] = $_POST['ap_behaviour'];
} else {
$this->options["behaviour"] = array();
}
//$this->options["flashAlternate"] = trim(stripslashes($_POST['ap_flashalternate']));
$this->options["excerptAlternate"] = trim(stripslashes($_POST['ap_excerptalternate']));
$this->options["rssAlternate"] = $_POST['ap_rssalternate'];
$this->options["rssCustomAlternate"] = trim(stripslashes($_POST['ap_rsscustomalternate']));
$this->options["introClip"] = trim($_POST['ap_audioprefixwebpath']);
$this->options["outroClip"] = trim($_POST['ap_audiopostfixwebpath']);
$_POST['ap_player_width'] = trim($_POST['ap_player_width']);
if ( preg_match("/^[0-9]+%?$/", $_POST['ap_player_width']) == 1 ) {
$this->options["playerWidth"] = $_POST['ap_player_width'];
}
$_POST['ap_initial_volume'] = trim($_POST['ap_initial_volume']);
if ( preg_match("/^[0-9]+$/", $_POST['ap_initial_volume']) == 1 ) {
$_POST['ap_initial_volume'] = intval($_POST['ap_initial_volume']);
if ($_POST['ap_initial_volume'] <= 100) {
$this->options["initialVolume"] = $_POST['ap_initial_volume'];
}
}
$_POST['ap_buffertime'] = trim($_POST['ap_buffertime']);
if ( preg_match("/^[0-9]+$/", $_POST['ap_buffertime']) == 1 ) {
$_POST['ap_buffertime'] = intval($_POST['ap_buffertime']);
if ($_POST['ap_buffertime'] > 0) {
$this->options["bufferTime"] = $_POST['ap_buffertime'];
}
}
// Update colour options
foreach ( $this->colorKeys as $colorKey ) {
// Ignore missing or invalid color values
if ( isset( $_POST["ap_" . $colorKey . "color"] ) && preg_match( "/^#[0-9A-Fa-f]{6}$/", $_POST["ap_" . $colorKey . "color"] ) == 1 ) {
$this->options["colorScheme"][$colorKey] = str_replace( "#", "", $_POST["ap_" . $colorKey . "color"] );
}
}
if ( isset( $_POST["ap_pagebgcolor"] ) && preg_match( "/^#[0-9A-Fa-f]{6}$/", $_POST["ap_pagebgcolor"] ) == 1 ) {
$this->options["colorScheme"]["pagebg"] = str_replace( "#", "", $_POST['ap_pagebgcolor']);
}
$this->options["colorScheme"]["transparentpagebg"] = isset( $_POST["ap_transparentpagebg"] );
$this->saveOptions();
$goback = add_query_arg("updated", "true", "options-general.php?page=" . $this->optionsPageName);
wp_redirect($goback);
exit();
}
}
/**
* Inserts Audio Player button into media library popup
* @return the amended form_fields structure
* @param $form_fields Object
* @param $post Object
*/
function insertAudioPlayerButton($form_fields, $post) {
global $wp_version;
$file = wp_get_attachment_url($post->ID);
// Only add the extra button if the attachment is an mp3 file
if ($post->post_mime_type == 'audio/mpeg') {
$form_fields["url"]["html"] .= "Audio Player ";
if (version_compare($wp_version, "2.7", "<")) {
$form_fields["url"]["html"] .= "\n";
}
}
return $form_fields;
}
/**
* Format the html inserted when the Audio Player button is used
* @param $html String
* @return String
*/
function sendToEditor($html) {
if (preg_match("/ ([^<]*)<\/a>/i", $html, $matches)) {
$html = $matches[2];
if (strlen($matches[5]) > 0) {
$html = preg_replace("/]$/i", "|titles=" . $matches[5] . "]", $html);
}
}
return $html;
}
/**
* Output necessary stuff to WP head section
*/
function addHeaderCode() {
echo '';
echo "\n";
echo '';
echo "\n";
}
/**
* Output necessary stuff to WP footer section (JS calls to embed players)
*/
function addFooterCode() {
if (strlen($this->footerCode) > 0) {
echo '';
echo "\n";
// Reset it now
$this->footerCode = "";
}
}
/**
* Override media-upload script to handle Audio Player inserts from media library
*/
function overrideMediaUpload() {
echo '';
echo "\n";
}
/**
* Output necessary stuff to WP admin head section
*/
function addAdminHeaderCode() {
global $wp_version;
echo ' ';
echo "\n";
echo ' ';
echo "\n";
// Include jquery library if we are not running WP 2.5 or above
if (version_compare($wp_version, "2.5", "<")) {
echo '';
echo "\n";
}
echo '';
echo "\n";
echo '';
echo "\n";
echo '';
echo "\n";
echo '';
echo "\n";
}
/**
* Verifies that the given audio folder exists on the server (Ajax call)
*/
function checkAudioFolder() {
$audioRoot = $_POST["audioFolder"];
$sysDelimiter = '/';
if (strpos(ABSPATH, '\\') !== false) $sysDelimiter = '\\';
$audioAbsPath = preg_replace('/[\\\\\/]+/', $sysDelimiter, ABSPATH . $audioRoot);
if (!file_exists($audioAbsPath)) {
echo $audioAbsPath;
} else {
echo "ok";
}
}
/**
* Parses theme style sheet
* @return array of colors from current theme
*/
function getThemeColors() {
$current_theme_data = get_theme(get_current_theme());
$theme_css = implode('', file( get_theme_root() . "/" . $current_theme_data["Stylesheet"] . "/style.css"));
preg_match_all('/:[^:,;\{\}].*?#([abcdef1234567890]{3,6})/i', $theme_css, $matches);
return array_unique($matches[1]);
}
/**
* Formats a php associative array into a javascript object
* @return formatted string
* @param $object Object containing the options to format
*/
function php2js($object) {
$js_options = '{';
$separator = "";
$real_separator = ",";
foreach($object as $key=>$value) {
// Format booleans
if (is_bool($value)) $value = $value?"yes":"no";
else if (in_array($key, array("soundFile", "titles", "artists"))) {
if (in_array($key, array("titles", "artists"))) {
// Decode HTML entities in titles and artists
if (function_exists("html_entity_decode")) {
$value = html_entity_decode($value);
}
}
$value = rawurlencode($value);
}
$js_options .= $separator . $key . ':"' . $value .'"';
$separator = $real_separator;
}
$js_options .= "}";
return $js_options;
}
/**
* @return true if $path is absolute
* @param $path Object
*/
function isAbsoluteURL($path) {
if (strpos($path, "http://") === 0) {
return true;
}
if (strpos($path, "https://") === 0) {
return true;
}
if (strpos($path, "ftp://") === 0) {
return true;
}
return false;
}
/**
* Encodes the given string
* @return the encoded string
* @param $string String the string to encode
*/
function encodeSource($string) {
$source = utf8_decode($string);
$ntexto = "";
$codekey = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
for ($i = 0; $i < strlen($string); $i++) {
$ntexto .= substr("0000".base_convert(ord($string{$i}), 10, 2), -8);
}
$ntexto .= substr("00000", 0, 6-strlen($ntexto)%6);
$string = "";
for ($i = 0; $i < strlen($ntexto)-1; $i = $i + 6) {
$string .= $codekey{intval(substr($ntexto, $i, 6), 2)};
}
return $string;
}
}
}
// Instantiate the class
if (class_exists('AudioPlayer')) {
global $AudioPlayer;
if (!isset($AudioPlayer)) {
if (version_compare(PHP_VERSION, '5.0.0', '<')) {
$AudioPlayer = &new AudioPlayer();
} else {
$AudioPlayer = new AudioPlayer();
}
}
}
/**
* Experimental "tag" function for inserting players anywhere (yuk)
* @return
* @param $source Object
*/
function insert_audio_player($source) {
global $AudioPlayer;
echo $AudioPlayer->processContent($source);
}
?>/*
Plugin Name: Sermon Browser
Plugin URI: http://www.sermonbrowser.com/
Description: Upload sermons to your website, where they can be searched, listened to, and downloaded. Easy to use with comprehensive help and tutorials.
Author: Mark Barnes
Version: 0.45.4
Author URI: http://www.4-14.org.uk/
Copyright (c) 2008-2011 Mark Barnes
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
The structure of this plugin is as follows:
===========================================
MAIN FILES
----------
sermon.php - This file. Contains common functions and initialisation routines.
admin.php - Functions required in the admin pages.
frontend.php - Functions required in the frontend (non-admin) pages.
OTHER FILES
-----------
ajax.php - Handles AJAX returns.
dictionary.php - Translates the template tags into php code. Used only when saving a template.
filetypes.php - User-editable file, which returns the correct mime-type for common file-extensions.
php4compat.php - Small number of functions required for PHP4 compatibility
podcast.php - Handles the podcast feed
sb-install.php - Used only when installing the plugin for the first time
style.php - Outputs the custom stylesheet
uninstall.php - Removes the plugin and its databases tables and rows
upgrade.php - Runs only when upgrading from earlier versions of SermonBrowser
If you want to follow the logic of the code, start with sb_sermon_init, and trace the Wordpress actions and filters.
The frontend output is inserted by sb_shortcode
*/
/**
* Initialisation
*
* Sets version constants and basic Wordpress hooks.
* @package common_functions
*/
define('SB_CURRENT_VERSION', '0.45.4');
define('SB_DATABASE_VERSION', '1.7');
sb_define_constants();
add_action ('plugins_loaded', 'sb_hijack');
add_action ('init', 'sb_sermon_init');
add_action ('widgets_init', 'sb_widget_sermon_init');
if (version_compare(PHP_VERSION, '5.0.0', '<'))
require(SB_INCLUDES_DIR.'/php4compat.php');
/**
* Display podcast, or download linked files
*
* Intercepts Wordpress at earliest opportunity. Checks whether the following are required before the full framework is loaded:
* Ajax data, stylesheet, file download
*/
function sb_hijack() {
global $filetypes, $wpdb, $sermon_domain;
if (function_exists('wp_timezone_supported') && wp_timezone_supported())
wp_timezone_override_offset();
if (isset($_POST['sermon']) && $_POST['sermon'] == 1)
require(SB_INCLUDES_DIR.'/ajax.php');
if (stripos($_SERVER['REQUEST_URI'], 'sb-style.css') !== FALSE || isset($_GET['sb-style']))
require(SB_INCLUDES_DIR.'/style.php');
//Forces sermon download of local file
if (isset($_GET['download']) AND isset($_GET['file_name'])) {
$file_name = $wpdb->escape(rawurldecode($_GET['file_name']));
$file_name = $wpdb->get_var("SELECT name FROM {$wpdb->prefix}sb_stuff WHERE name='{$file_name}'");
if (!is_null($file_name)) {
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Disposition: attachment; filename="'.$file_name.'";');
header("Content-Transfer-Encoding: binary");
sb_increase_download_count ($file_name);
$file_name = SB_ABSPATH.sb_get_option('upload_dir').$file_name;
$filesize = filesize($file_name);
if ($filesize != 0)
header("Content-Length: ".filesize($file_name));
output_file($file_name);
die();
} else
wp_die(htmlentities(rawurldecode($_GET['file_name'])).' '.__('not found', $sermon_domain), __('File not found', $sermon_domain), array('response' => 404));
}
//Forces sermon download of external URL
if (isset($_REQUEST['download']) AND isset($_REQUEST['url'])) {
$url = rawurldecode($_GET['url']);
if(ini_get('allow_url_fopen')) {
$headers = @get_headers($url, 1);
if ($headers === FALSE || (isset($headers[0]) && strstr($headers[0], '404') !== FALSE))
wp_die(htmlentities(rawurldecode($_GET['url'])).' '.__('not found', $sermon_domain), __('URL not found', $sermon_domain), array('response' => 404));
$headers = array_change_key_case($headers,CASE_LOWER);
if (isset($headers['location'])) {
$location = $headers['location'];
if (is_array($location))
$location = $location[0];
if ($location && substr($location,0,7) != "http://") {
preg_match('@^(?:http://)?([^/]+)@i', $url, $matches);
$location = "http://".$matches[1].'/'.$location;
}
if ($location) {
header('Location: '.site_url().'?download&url='.$location);
die();
}
}
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
if (isset($headers['last-modified']))
header('Last-Modified: '.$headers['last-modified']);
if (isset($headers['content-length']))
header("Content-Length: ".$headers['content-length']);
if (isset($headers['content-disposition']))
header ('Content-Disposition: '.$headers['content-disposition']);
else
header('Content-Disposition: attachment; filename="'.basename($url).'";');
header("Content-Transfer-Encoding: binary");
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
sb_increase_download_count($url);
session_write_close();
while (@ob_end_clean());
output_file($url);
die();
} else {
sb_increase_download_count ($url);
header('Location: '.$url);
die();
}
}
//Returns local file (doesn't force download)
if (isset($_GET['show']) AND isset($_GET['file_name'])) {
global $filetypes;
$file_name = $wpdb->escape(rawurldecode($_GET['file_name']));
$file_name = $wpdb->get_var("SELECT name FROM {$wpdb->prefix}sb_stuff WHERE name='{$file_name}'");
if (!is_null($file_name)) {
$url = sb_get_option('upload_url').$file_name;
sb_increase_download_count ($file_name);
header("Location: ".$url);
die();
} else
wp_die(htmlentities(rawurldecode($_GET['file_name'])).' '.__('not found', $sermon_domain), __('File not found', $sermon_domain), array('response' => 404));
}
//Returns contents of external URL(doesn't force download)
if (isset($_REQUEST['show']) AND isset($_REQUEST['url'])) {
$url = rawurldecode($_GET['url']);
sb_increase_download_count ($url);
header('Location: '.$url);
die();
}
}
/**
* Main initialisation function
*
* Sets up most Wordpress hooks and filters, depending on whether request is for front or back end.
*/
function sb_sermon_init () {
global $sermon_domain, $wpdb, $defaultMultiForm, $defaultSingleForm, $defaultStyle;
$sermon_domain = 'sermon-browser';
if (IS_MU) {
load_plugin_textdomain($sermon_domain, '', 'sb-includes');
} else {
load_plugin_textdomain($sermon_domain, '', 'sermon-browser/sb-includes');
}
if (WPLANG != '')
setlocale(LC_ALL, WPLANG.'.UTF-8');
//Display the podcast if that's what's requested
if (isset($_GET['podcast']))
require(SB_INCLUDES_DIR.'/podcast.php');
// Register custom CSS and javascript files
wp_register_script('sb_64', SB_PLUGIN_URL.'/sb-includes/64.js', false, SB_CURRENT_VERSION);
wp_register_script('sb_datepicker', SB_PLUGIN_URL.'/sb-includes/datePicker.js', array('jquery'), SB_CURRENT_VERSION);
wp_register_style('sb_datepicker', SB_PLUGIN_URL.'/sb-includes/datepicker.css', false, SB_CURRENT_VERSION);
if (get_option('permalink_structure') == '')
wp_register_style('sb_style', trailingslashit(site_url()).'?sb-style&', false, sb_get_option('style_date_modified'));
else
wp_register_style('sb_style', trailingslashit(site_url()).'sb-style.css', false, sb_get_option('style_date_modified'));
// Register [sermon] shortcode handler
add_shortcode('sermons', 'sb_shortcode');
add_shortcode('sermon', 'sb_shortcode');
// Attempt to set php.ini directives
if (sb_return_kbytes(ini_get('upload_max_filesize'))<15360)
ini_set('upload_max_filesize', '15M');
if (sb_return_kbytes(ini_get('post_max_size'))<15360)
ini_set('post_max_size', '15M');
if (sb_return_kbytes(ini_get('memory_limit'))<49152)
ini_set('memory_limit', '48M');
if (intval(ini_get('max_input_time'))<600)
ini_set('max_input_time','600');
if (intval(ini_get('max_execution_time'))<600)
ini_set('max_execution_time', '600');
if (ini_get('file_uploads')<>'1')
ini_set('file_uploads', '1');
// Check whether upgrade required
if (current_user_can('manage_options') && is_admin()) {
if (get_option('sb_sermon_db_version'))
$db_version = get_option('sb_sermon_db_version');
else
$db_version = sb_get_option('db_version');
if ($db_version && $db_version != SB_DATABASE_VERSION) {
require_once (SB_INCLUDES_DIR.'/upgrade.php');
sb_database_upgrade ($db_version);
} elseif (!$db_version) {
require (SB_INCLUDES_DIR.'/sb-install.php');
sb_install();
}
$sb_version = sb_get_option('code_version');
if ($sb_version != SB_CURRENT_VERSION) {
require_once (SB_INCLUDES_DIR.'/upgrade.php');
sb_version_upgrade ($sb_version, SB_CURRENT_VERSION);
}
}
// Load shared (admin/frontend) features
add_action ('save_post', 'update_podcast_url');
// Check to see what functions are required, and only load what is needed
if (stripos($_SERVER['REQUEST_URI'], '/wp-admin/') === FALSE) {
require (SB_INCLUDES_DIR.'/frontend.php');
add_action('wp_head', 'sb_add_headers', 0);
add_action('wp_head', 'wp_print_styles', 9);
add_action('admin_bar_menu', 'sb_admin_bar_menu', 45);
add_filter('wp_title', 'sb_page_title');
if (defined('SAVEQUERIES') && SAVEQUERIES)
add_action ('wp_footer', 'sb_footer_stats');
} else {
require (SB_INCLUDES_DIR.'/admin.php');
add_action ('admin_menu', 'sb_add_pages');
add_action ('rightnow_end', 'sb_rightnow');
add_action('admin_init', 'sb_add_admin_headers');
add_filter('contextual_help', 'sb_add_contextual_help');
if (defined('SAVEQUERIES') && SAVEQUERIES)
add_action('admin_footer', 'sb_footer_stats');
}
}
/**
* Add Sermons menu and sub-menus in admin
*/
function sb_add_pages() {
global $sermon_domain;
add_menu_page(__('Sermons', $sermon_domain), __('Sermons', $sermon_domain), 'publish_posts', __FILE__, 'sb_manage_sermons', SB_PLUGIN_URL.'/sb-includes/sb-icon.png');
add_submenu_page(__FILE__, __('Sermons', $sermon_domain), __('Sermons', $sermon_domain), 'publish_posts', __FILE__, 'sb_manage_sermons');
if (isset($_REQUEST['page']) && $_REQUEST['page'] == 'sermon-browser/new_sermon.php' && isset($_REQUEST['mid'])) {
add_submenu_page(__FILE__, __('Edit Sermon', $sermon_domain), __('Edit Sermon', $sermon_domain), 'publish_posts', 'sermon-browser/new_sermon.php', 'sb_new_sermon');
} else {
add_submenu_page(__FILE__, __('Add Sermon', $sermon_domain), __('Add Sermon', $sermon_domain), 'publish_posts', 'sermon-browser/new_sermon.php', 'sb_new_sermon');
}
add_submenu_page(__FILE__, __('Files', $sermon_domain), __('Files', $sermon_domain), 'upload_files', 'sermon-browser/files.php', 'sb_files');
add_submenu_page(__FILE__, __('Preachers', $sermon_domain), __('Preachers', $sermon_domain), 'manage_categories', 'sermon-browser/preachers.php', 'sb_manage_preachers');
add_submenu_page(__FILE__, __('Series & Services', $sermon_domain), __('Series & Services', $sermon_domain), 'manage_categories', 'sermon-browser/manage.php', 'sb_manage_everything');
add_submenu_page(__FILE__, __('Options', $sermon_domain), __('Options', $sermon_domain), 'manage_options', 'sermon-browser/options.php', 'sb_options');
add_submenu_page(__FILE__, __('Templates', $sermon_domain), __('Templates', $sermon_domain), 'manage_options', 'sermon-browser/templates.php', 'sb_templates');
add_submenu_page(__FILE__, __('Uninstall', $sermon_domain), __('Uninstall', $sermon_domain), 'edit_plugins', 'sermon-browser/uninstall.php', 'sb_uninstall');
add_submenu_page(__FILE__, __('Help', $sermon_domain), __('Help', $sermon_domain), 'publish_posts', 'sermon-browser/help.php', 'sb_help');
add_submenu_page(__FILE__, __('Pray for Japan', $sermon_domain), __('Pray for Japan', $sermon_domain), 'publish_posts', 'sermon-browser/japan.php', 'sb_japan');
}
/**
* Converts php.ini mega- or giga-byte numbers into kilobytes
*
* @param string $val
* @return integer
*/
function sb_return_kbytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
}
return intval($val);
}
/**
* Count download stats for sermon
*
* Returns the number of plays for a particular file
*
* @param integer $sermonid
* @return integer
*/
function sb_sermon_stats($sermonid) {
global $wpdb;
$stats = $wpdb->get_var("SELECT SUM(count) FROM ".$wpdb->prefix."sb_stuff WHERE sermon_id=".$sermonid);
if ($stats > 0)
return $stats;
}
/**
* Updates podcast URL in wp_options
*
* Function required if permalinks changed or [sermons] added to a different page
*/
function update_podcast_url () {
global $wp_rewrite;
$existing_url = sb_get_option('podcast_url');
if (substr($existing_url, 0, strlen(site_url())) == site_url()) {
if (sb_display_url(TRUE)=="") {
sb_update_option('podcast_url', site_url().sb_query_char(false).'podcast');
} else {
sb_update_option('podcast_url', sb_display_url().sb_query_char(false).'podcast');
}
}
}
/**
* Returns occassionally requested default values
*
* Not defined as constants to save memory
* @param string $default_type
* @return mixed
*/
function sb_get_default ($default_type) {
global $sermon_domain;
switch ($default_type) {
case 'sermon_path':
$upload_path = wp_upload_dir();
$upload_path = $upload_path['basedir'];
if (substr($upload_path, 0, strlen(ABSPATH)) == ABSPATH)
$upload_path = substr($upload_path, strlen(ABSPATH));
return trailingslashit($upload_path).'sermons/';
case 'attachment_url':
$upload_dir = wp_upload_dir();
$upload_dir = $upload_dir['baseurl'];
return trailingslashit($upload_dir).'sermons/';
case 'bible_books':
return array(__('Genesis', $sermon_domain), __('Exodus', $sermon_domain), __('Leviticus', $sermon_domain), __('Numbers', $sermon_domain), __('Deuteronomy', $sermon_domain), __('Joshua', $sermon_domain), __('Judges', $sermon_domain), __('Ruth', $sermon_domain), __('1 Samuel', $sermon_domain), __('2 Samuel', $sermon_domain), __('1 Kings', $sermon_domain), __('2 Kings', $sermon_domain), __('1 Chronicles', $sermon_domain), __('2 Chronicles',$sermon_domain), __('Ezra', $sermon_domain), __('Nehemiah', $sermon_domain), __('Esther', $sermon_domain), __('Job', $sermon_domain), __('Psalm', $sermon_domain), __('Proverbs', $sermon_domain), __('Ecclesiastes', $sermon_domain), __('Song of Solomon', $sermon_domain), __('Isaiah', $sermon_domain), __('Jeremiah', $sermon_domain), __('Lamentations', $sermon_domain), __('Ezekiel', $sermon_domain), __('Daniel', $sermon_domain), __('Hosea', $sermon_domain), __('Joel', $sermon_domain), __('Amos', $sermon_domain), __('Obadiah', $sermon_domain), __('Jonah', $sermon_domain), __('Micah', $sermon_domain), __('Nahum', $sermon_domain), __('Habakkuk', $sermon_domain), __('Zephaniah', $sermon_domain), __('Haggai', $sermon_domain), __('Zechariah', $sermon_domain), __('Malachi', $sermon_domain), __('Matthew', $sermon_domain), __('Mark', $sermon_domain), __('Luke', $sermon_domain), __('John', $sermon_domain), __('Acts', $sermon_domain), __('Romans', $sermon_domain), __('1 Corinthians', $sermon_domain), __('2 Corinthians', $sermon_domain), __('Galatians', $sermon_domain), __('Ephesians', $sermon_domain), __('Philippians', $sermon_domain), __('Colossians', $sermon_domain), __('1 Thessalonians', $sermon_domain), __('2 Thessalonians', $sermon_domain), __('1 Timothy', $sermon_domain), __('2 Timothy', $sermon_domain), __('Titus', $sermon_domain), __('Philemon', $sermon_domain), __('Hebrews', $sermon_domain), __('James', $sermon_domain), __('1 Peter', $sermon_domain), __('2 Peter', $sermon_domain), __('1 John', $sermon_domain), __('2 John', $sermon_domain), __('3 John', $sermon_domain), __('Jude', $sermon_domain), __('Revelation', $sermon_domain));
case 'eng_bible_books':
return array('Genesis', 'Exodus', 'Leviticus', 'Numbers', 'Deuteronomy', 'Joshua', 'Judges', 'Ruth', '1 Samuel', '2 Samuel', '1 Kings', '2 Kings', '1 Chronicles', '2 Chronicles', 'Ezra', 'Nehemiah', 'Esther', 'Job', 'Psalm', 'Proverbs', 'Ecclesiastes', 'Song of Solomon', 'Isaiah', 'Jeremiah', 'Lamentations', 'Ezekiel', 'Daniel', 'Hosea', 'Joel', 'Amos', 'Obadiah', 'Jonah', 'Micah', 'Nahum', 'Habakkuk', 'Zephaniah', 'Haggai', 'Zechariah', 'Malachi', 'Matthew', 'Mark', 'Luke', 'John', 'Acts', 'Romans', '1 Corinthians', '2 Corinthians', 'Galatians', 'Ephesians', 'Philippians', 'Colossians', '1 Thessalonians', '2 Thessalonians', '1 Timothy', '2 Timothy', 'Titus', 'Philemon', 'Hebrews', 'James', '1 Peter', '2 Peter', '1 John', '2 John', '3 John', 'Jude', 'Revelation');
}
}
/**
* Returns true if sermons are displayed on the current page
*
* @return bool
*/
function sb_display_front_end() {
global $wpdb, $post;
$pageid = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE post_content LIKE '%[sermon%' AND (post_status = 'publish' OR post_status = 'private') AND ID={$post->ID} AND post_date < NOW();");
if ($pageid === NULL)
return FALSE;
else
return TRUE;
}
/**
* Get the page_id of the main sermons page
*
* @return integer
*/
function sb_get_page_id() {
global $wpdb, $post;
$pageid = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE (post_content LIKE '%[sermons]%' OR post_content LIKE '%[sermon]%') AND (post_status = 'publish' OR post_status = 'private') AND post_date < NOW();");
if (!$pageid)
$pageid = $wpdb->get_var("SELECT ID FROM {$wpdb->posts} WHERE (post_content LIKE '%[sermon %' OR post_content LIKE '%[sermons %') AND (post_status = 'publish' OR post_status = 'private') AND post_date < NOW();");
if (!$pageid)
return 0;
else
return intval($pageid);
}
/**
* Get the URL of the main sermons page
*
* @return string
*/
function sb_display_url() {
global $wpdb, $post, $sb_display_url;
if ($sb_display_url == '') {
$pageid = sb_get_page_id();
if ($pageid == 0)
return '';
if (defined('SB_AJAX') && SB_AJAX)
return site_url().'/?page_id='.$pageid; // Don't use permalinks in Ajax calls
else {
$sb_display_url = get_permalink($pageid);
if ($sb_display_url == site_url() || $sb_display_url == '') // Hack to force true permalink even if page used for front page.
$sb_display_url = site_url().'/?page_id='.$pageid;
}
}
return $sb_display_url;
}
/**
* Fix to ensure AudioPlayer v2 and AudioPlayer v1 both work
*/
if (!function_exists('ap_insert_player_widgets') && function_exists('insert_audio_player')) {
function ap_insert_player_widgets($params) {
return insert_audio_player($params);
}
}
/**
* Adds database statistics to the HTML comments
*
* Requires define('SAVEQUERIES', true) in wp-config.php
* Useful for diagnostics
*/
function sb_footer_stats() {
global $wpdb;
echo '';
}
/**
* Returns the correct string to join the sermonbrowser parameters to the existing URL
*
* @param boolean $return_entity
* @return string (either '?', '&', or '&')
*/
function sb_query_char ($return_entity = true) {
if (strpos(sb_display_url(), '?')===FALSE)
return '?';
else
if ($return_entity)
return '&';
else
return '&';
}
/**
* Create the shortcode handler
*
* Standard shortcode handler that inserts the sermonbrowser output into the post/page
*
* @param array $atts
* @param string $content
* @return string
*/
function sb_shortcode($atts, $content=null) {
global $wpdb, $record_count, $sermon_domain;
ob_start();
$atts = shortcode_atts(array(
'filter' => sb_get_option('filter_type'),
'filterhide' => sb_get_option('filter_hide'),
'id' => isset($_REQUEST['sermon_id']) ? $_REQUEST['sermon_id'] : '',
'preacher' => isset($_REQUEST['preacher']) ? $_REQUEST['preacher'] : '',
'series' => isset($_REQUEST['series']) ? $_REQUEST['series'] : '',
'book' => isset($_REQUEST['book']) ? stripslashes($_REQUEST['book']) : '',
'service' => isset($_REQUEST['service']) ? $_REQUEST['service'] : '',
'date' => isset($_REQUEST['date']) ? $_REQUEST['date'] : '',
'enddate' => isset($_REQUEST['enddate']) ? $_REQUEST['enddate'] : '',
'tag' => isset($_REQUEST['stag']) ? stripslashes($_REQUEST['stag']) : '',
'title' => isset($_REQUEST['title']) ? stripslashes($_REQUEST['title']) : '',
'limit' => '0',
'dir' => isset($_REQUEST['dir']) ? stripslashes($_REQUEST['dir']) : '', ),
$atts);
if ($atts['id'] != '') {
if (strtolower($atts['id']) == 'latest') {
$atts['id'] = '';
$wpdb->query('SET SQL_BIG_SELECTS=1');
$query = $wpdb->get_results(sb_create_multi_sermon_query($atts, array(), 1, 1));
$atts['id'] = $query[0]->id;
}
$sermon = sb_get_single_sermon((int) $atts['id']);
if ($sermon)
eval('?>'.sb_get_option('single_output'));
else {
echo "";
_e ('No sermons found.', $sermon_domain);
echo "
";
}
} else {
if (isset($_REQUEST['sortby']))
$sort_criteria = $wpdb->escape($_REQUEST['sortby']);
else
$sort_criteria = 'm.datetime';
if (!empty($atts['dir']))
$dir = $wpdb->escape($atts['dir']);
elseif ($sort_criteria == 'm.datetime')
$dir = 'desc';
else
$dir = 'asc';
$sort_order = array('by' => $sort_criteria, 'dir' => $dir);
if (isset($_REQUEST['page']))
$page = $_REQUEST['page'];
else
$page = 1;
$hide_empty = sb_get_option('hide_no_attachments');
$sermons = sb_get_sermons($atts, $sort_order, $page, (int)$atts['limit'], $hide_empty);
$output = '?>'.sb_get_option('search_output');
eval($output);
}
$content = ob_get_contents();
ob_end_clean();
return $content;
}
/**
* Registers the Sermon Browser widgets
*/
function sb_widget_sermon_init() {
global $sermon_domain;
//Sermons Widget
if (!$options = sb_get_option('sermons_widget_options'))
$options = array();
$widget_ops = array('classname' => 'sermon', 'description' => __('Display a list of recent sermons.', $sermon_domain));
$control_ops = array('width' => 400, 'height' => 350, 'id_base' => 'sermon');
$name = __('Sermons', $sermon_domain);
$registered = false;
foreach (array_keys($options) as $o) {
if (!isset($options[$o]['limit']))
continue;
$id = "sermon-$o";
$registered = true;
wp_register_sidebar_widget($id, $name, 'sb_widget_sermon_wrapper', $widget_ops, array('number' => $o));
wp_register_widget_control($id, $name, 'sb_widget_sermon_control', $control_ops, array('number' => $o));
}
if (!$registered) {
wp_register_sidebar_widget('sermon-1', $name, 'sb_widget_sermon_wrapper', $widget_ops, array('number' => -1));
wp_register_widget_control('sermon-1', $name, 'sb_widget_sermon_control', $control_ops, array('number' => -1));
}
//Tags Widget
wp_register_sidebar_widget('sermon-browser-tags', __('Sermon Browser tags', $sermon_domain), 'sb_widget_tag_cloud_wrapper');
//Most popular widget
$name = __('Most popular sermons', $sermon_domain);
$description = __('Display a list of the most popular sermons, series or preachers.', $sermon_domain);
$widget_ops = array('classname' => 'sermon-browser-popular', 'description' => $description);
$control_ops = array('width' => 400, 'height' => 350, 'id_base' => 'sermon-browser-popular');
wp_register_sidebar_widget( 'sermon-browser-popular', $name, 'sb_widget_popular_wrapper', $widget_ops);
wp_register_widget_control( 'sermon-browser-popular', $name, 'sb_widget_popular_control', $control_ops);
}
/**
* Wrapper for sb_widget_sermon in frontend.php
*
* Allows main widget functionality to be in the frontend package, whilst still allowing widgets to be modified in admin
* @param array $args
* @param integer $widget_args
*/
function sb_widget_sermon_wrapper ($args, $widget_args = 1) {
require_once (SB_INCLUDES_DIR.'/frontend.php');
sb_widget_sermon($args, $widget_args);
}
/**
* Wrapper for sb_widget_tag_cloud in frontend.php
*
* Allows main widget functionality to be in the frontend package, whilst still allowing widgets to be modified in admin
* @param array $args
*/
function sb_widget_tag_cloud_wrapper ($args) {
require_once (SB_INCLUDES_DIR.'/frontend.php');
sb_widget_tag_cloud ($args);
}
/**
* Wrapper for sb_widget_popular in frontend.php
*
* Allows main widget functionality to be in the frontend package, whilst still allowing widgets to be modified in admin
* @param array $args
*/
function sb_widget_popular_wrapper ($args) {
require_once (SB_INCLUDES_DIR.'/frontend.php');
sb_widget_popular ($args);
}
/**
* Optimised replacement for get_option
*
* Returns any of the sermonbrowser options from one row of the database
* Large options (e.g. the template) are stored on additional rows by this function
* @param string $type
* @return mixed
*/
function sb_get_option($type) {
global $sermonbrowser_options;
$special_options = sb_special_option_names();
if (in_array($type, $special_options)) {
return stripslashes((get_option("sermonbrowser_{$type}")));
} else {
if (!$sermonbrowser_options) {
$options = get_option('sermonbrowser_options');
if ($options === FALSE)
return FALSE;
$sermonbrowser_options = unserialize(($options));
if ($sermonbrowser_options === FALSE)
wp_die ('Failed to get SermonBrowser options '.(get_option('sermonbrowser_options')));
}
if (isset($sermonbrowser_options[$type]))
return $sermonbrowser_options[$type];
else
return '';
}
}
/**
* Optimised replacement for update_option
*
* Stores all of sermonbrowser options on one row of the database
* Large options (e.g. the template) are stored on additional rows by this function
* @param string $type
* @param mixed $val
* @return bool
*/
function sb_update_option($type, $val) {
global $sermonbrowser_options;
$special_options = sb_special_option_names();
if (in_array($type, $special_options))
return update_option ("sermonbrowser_{$type}", base64_encode($val));
else {
if (!$sermonbrowser_options) {
$options = get_option('sermonbrowser_options');
if ($options !== FALSE) {
$sermonbrowser_options = unserialize(($options));
if ($sermonbrowser_options === FALSE)
wp_die ('Failed to get SermonBrowser options '.(get_option('sermonbrowser_options')));
}
}
if (!isset($sermonbrowser_options[$type]) || $sermonbrowser_options[$type] !== $val) {
$sermonbrowser_options[$type] = $val;
return update_option('sermonbrowser_options', base64_encode(serialize($sermonbrowser_options)));
} else
return false;
}
}
/**
* Returns which options need to be stored in individual base64 format (i.e. potentially large strings)
*
* @return array
*/
function sb_special_option_names() {
return array ('single_template', 'single_output', 'search_template', 'search_output', 'css_style');
}
/**
* Recursive mkdir function
*
* @param string $pathname
* @param string $mode
* return bool
*/
function sb_mkdir($pathname, $mode=0777) {
is_dir(dirname($pathname)) || sb_mkdir(dirname($pathname), $mode);
@mkdir($pathname, $mode);
return @chmod($pathname, $mode);
}
/**
* Defines a number of constants used throughout the plugin
*/
function sb_define_constants() {
$directories = explode(DIRECTORY_SEPARATOR,dirname(__FILE__));
if ($plugin_dir = $directories[count($directories)-1] == 'mu-plugins' || (function_exists('is_multisite') && is_multisite())) {
define('IS_MU', TRUE);
} else {
define('IS_MU', FALSE);
}
if ($directories[count($directories)-1] == 'mu-plugins' )
define ('SB_PLUGIN_URL', content_url().'/'.$plugin_dir);
else
define ('SB_PLUGIN_URL', rtrim(content_url().'/plugins/'.plugin_basename(dirname(__FILE__)), '/'));
define ('SB_PLUGIN_DIR', sb_sanitise_path(defined('WP_CONTENT_DIR') ? WP_CONTENT_DIR : ABSPATH.'wp-content').'/plugins');
define ('SB_WP_CONTENT_DIR', sb_sanitise_path(WP_CONTENT_DIR));
define ('SB_INCLUDES_DIR', SB_PLUGIN_DIR.'/sermon-browser/sb-includes');
define ('SB_ABSPATH', sb_sanitise_path(ABSPATH));
define ('GETID3_INCLUDEPATH', SB_PLUGIN_DIR.'/'.plugin_basename(dirname(__FILE__)).'/sb-includes/getid3/');
define ('GETID3_HELPERAPPSDIR', GETID3_INCLUDEPATH);
}
/**
* Returns list of bible books from the database
*
* @return array
*/
function sb_get_bible_books () {
global $wpdb;
return $wpdb->get_col("SELECT name FROM {$wpdb->prefix}sb_books order by id");
}
/**
* Get multiple sermons from the database
*
* Uses sb_create_multi_sermon_query to general the SQL statement
* @param array $filter
* @param string $order
* @param integer $page
* @param integer $limit
* @global integer record_count
* @return array
*/
function sb_get_sermons($filter, $order, $page = 1, $limit = 0, $hide_empty = false) {
global $wpdb, $record_count;
if ($limit == 0)
$limit = sb_get_option('sermons_per_page');
$wpdb->query('SET SQL_BIG_SELECTS=1');
$query = $wpdb->get_results(sb_create_multi_sermon_query($filter, $order, $page, $limit, $hide_empty));
$record_count = $wpdb->get_var("SELECT FOUND_ROWS()");
return $query;
}
/**
* Create SQL query for returning multiple sermons
*
* @param array $filter
* @param string $order
* @param integer $page
* @param integer $limit
* @return string SQL query
*/
function sb_create_multi_sermon_query ($filter, $order, $page = 1, $limit = 0, $hide_empty = false) {
global $wpdb;
$default_filter = array(
'title' => '',
'preacher' => 0,
'date' => '',
'enddate' => '',
'series' => 0,
'service' => 0,
'book' => '',
'tag' => '',
'id' => '',
);
$default_order = array(
'by' => 'm.datetime',
'dir' => 'desc',
);
$bs = '';
$filter = array_merge($default_filter, (array)$filter);
$order = array_merge($default_order, (array)$order);
$page = (int) $page;
$cond = '1=1 ';
if ($filter['title'] != '') {
$cond .= "AND (m.title LIKE '%" . $wpdb->escape($filter['title']) . "%' OR m.description LIKE '%" . $wpdb->escape($filter['title']). "%' OR t.name LIKE '%" . $wpdb->escape($filter['title']) . "%') ";
}
if ($filter['preacher'] != 0) {
$cond .= 'AND m.preacher_id = ' . (int) $filter['preacher'] . ' ';
}
if ($filter['date'] != '') {
$cond .= 'AND m.datetime >= "' . $wpdb->escape($filter['date']) . '" ';
}
if ($filter['enddate'] != '') {
$cond .= 'AND m.datetime <= "' . $wpdb->escape($filter['enddate']) . '" ';
}
if ($filter['series'] != 0) {
$cond .= 'AND m.series_id = ' . (int) $filter['series'] . ' ';
}
if ($filter['service'] != 0) {
$cond .= 'AND m.service_id = ' . (int) $filter['service'] . ' ';
}
if ($filter['book'] != '') {
$cond .= 'AND bs.book_name = "' . $wpdb->escape($filter['book']) . '" ';
} else {
$bs = "AND bs.order = 0 AND bs.type= 'start' ";
}
if ($filter['tag'] != '') {
$cond .= "AND t.name LIKE '%" . $wpdb->escape($filter['tag']) . "%' ";
}
if ($filter['id'] != '') {
$cond .= "AND m.id LIKE '" . $wpdb->escape($filter['id']) . "' ";
}
if ($hide_empty) {
$cond .= "AND stuff.name != '' ";
}
$offset = $limit * ($page - 1);
if ($order['by'] == 'b.id' ) {
$order['by'] = 'b.id '.$wpdb->escape($order['dir']).', bs.chapter '.$wpdb->escape($order['dir']).', bs.verse';
}
return "SELECT SQL_CALC_FOUND_ROWS DISTINCT m.id, m.title, m.description, m.datetime, m.time, m.start, m.end, p.id as pid, p.name as preacher, p.description as preacher_description, p.image, s.id as sid, s.name as service, ss.id as ssid, ss.name as series
FROM {$wpdb->prefix}sb_sermons as m
LEFT JOIN {$wpdb->prefix}sb_preachers as p ON m.preacher_id = p.id
LEFT JOIN {$wpdb->prefix}sb_services as s ON m.service_id = s.id
LEFT JOIN {$wpdb->prefix}sb_series as ss ON m.series_id = ss.id
LEFT JOIN {$wpdb->prefix}sb_books_sermons as bs ON bs.sermon_id = m.id {$bs}
LEFT JOIN {$wpdb->prefix}sb_books as b ON bs.book_name = b.name
LEFT JOIN {$wpdb->prefix}sb_sermons_tags as st ON st.sermon_id = m.id
LEFT JOIN {$wpdb->prefix}sb_tags as t ON t.id = st.tag_id
LEFT JOIN {$wpdb->prefix}sb_stuff as stuff ON stuff.sermon_id = m.id
WHERE {$cond} ORDER BY ". $order['by'] . " " . $order['dir'] . " LIMIT " . $offset . ", " . $limit;
}
/**
* Returns the default time for a particular service
*
* @param integer $service (id in database)
* @return string (service time)
*/
function sb_default_time($service) {
global $wpdb;
$sermon_time = $wpdb->get_var("SELECT time FROM {$wpdb->prefix}sb_services WHERE id='{$service}'");
if (isset($sermon_time)) {
return $sermon_time;
} else {
return "00:00";
}
}
/**
* Gets attachments from database
*
* @param integer $sermon (id in database)
* @param boolean $mp3_only (if true will only return MP3 files)
* @return array
*/
function sb_get_stuff($sermon, $mp3_only = FALSE) {
global $wpdb;
if ($mp3_only) {
$stuff = $wpdb->get_results("SELECT f.type, f.name FROM {$wpdb->prefix}sb_stuff as f WHERE sermon_id = $sermon->id AND name LIKE '%.mp3' ORDER BY id desc");
} else {
$stuff = $wpdb->get_results("SELECT f.type, f.name FROM {$wpdb->prefix}sb_stuff as f WHERE sermon_id = $sermon->id ORDER BY id desc");
}
$file = $url = $code = array();
foreach ($stuff as $cur)
${$cur->type}[] = $cur->name;
return array(
'Files' => $file,
'URLs' => $url,
'Code' => $code,
);
}
/**
* Increases the download count for file attachments
*
* Increases the download count for the file $stuff_name
*
* @param string $stuff_name
*/
function sb_increase_download_count ($stuff_name) {
if (function_exists('current_user_can')&&!(current_user_can('edit_posts')|current_user_can('publish_posts'))) {
global $wpdb;
$wpdb->query("UPDATE ".$wpdb->prefix."sb_stuff SET COUNT=COUNT+1 WHERE name='".$wpdb->escape($stuff_name)."'");
}
}
/**
* Outputs a remote or local file
*
* @param string $filename
* @return bool success or failure
*/
function output_file($filename) {
$handle = fopen($filename, 'rb');
if ($handle === false)
return false;
if (ob_get_level() == 0)
ob_start();
while (!feof($handle)) {
set_time_limit(ini_get('max_execution_time'));
$buffer = fread($handle, 1048576);
echo $buffer;
ob_flush();
flush();
}
return fclose($handle);
}
/**
* Sanitizes Windows paths
*/
function sb_sanitise_path ($path) {
$path = str_replace('\\','/',$path);
$path = preg_replace('|/+|','/', $path);
return $path;
}
?>
Warning : Cannot modify header information - headers already sent by (output started at /home/xtion/blog.calvaryav.org/wp-content/plugins/audio-player/audio-player.php:116) in /home/xtion/blog.calvaryav.org/wp-includes/feed-rss2-comments.php on line 8
Comments for Calvary Chapel Apple Valley
http://www.blog.calvaryav.org
Reaching people for Jesus in our community and to the uttermost parts of the earth.
Sun, 11 Sep 2011 22:45:46 +0000
hourly
1
http://wordpress.org/?v=
-
Comment on All Sermons by Dawn Hayes (Deputy Hayes's Wife)
http://www.blog.calvaryav.org/?cpage=1#comment-4200
Dawn Hayes (Deputy Hayes's Wife)
Sun, 11 Sep 2011 22:45:46 +0000
http://208.113.240.89/?page_id=26#comment-4200
Thank you for inviting us to your church today. Your sermon was very touching. God Bless You!!
Thank you for inviting us to your church today. Your sermon was very touching. God Bless You!!
]]>
-
Comment on Welcome to Calvary Chapel Apple Valley Sermons by Gary Jr
http://www.blog.calvaryav.org/?p=1&cpage=1#comment-3481
Gary Jr
Thu, 14 Jul 2011 15:30:34 +0000
http://208.113.240.89/?p=1#comment-3481
Praise Jesus!
Praise Jesus!
]]>
-
Comment on Welcome to Calvary Chapel Apple Valley Sermons by Jan Sandoval
http://www.blog.calvaryav.org/?p=1&cpage=1#comment-414
Jan Sandoval
Sun, 16 May 2010 21:20:44 +0000
http://208.113.240.89/?p=1#comment-414
I listened to your authority of Scripture, and it was so well done. thank you, Gary.
I listened to your authority of Scripture, and it was so well done. thank you, Gary.
]]>