Created
March 27, 2012 20:33
-
-
Save rocktronica/2220059 to your computer and use it in GitHub Desktop.
bubblejax.php before stripping wpdb stuff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: BubbleJax Wrapper | |
Plugin URI: http://bubblelifemedia.com/ | |
Description: Name pending. | |
Author: Tommy | |
Version: 0.1 | |
Author URI: http://bubblelifemedia.com/ | |
*/ | |
// ____ __ __ ___ _____ | |
// /\ _`\ /\ \ /\ \ /\_ \ /\___ \ | |
// \ \ \L\ \ __ __\ \ \____\ \ \____\//\ \ __\/__/\ \ __ __ _ | |
// \ \ _ <'/\ \/\ \\ \ '__`\\ \ '__`\ \ \ \ /'__`\ _\ \ \ /'__`\ /\ \/'\ | |
// \ \ \L\ \ \ \_\ \\ \ \L\ \\ \ \L\ \ \_\ \_/\ __//\ \_\ \/\ \L\.\_\/> </ | |
// \ \____/\ \____/ \ \_,__/ \ \_,__/ /\____\ \____\ \____/\ \__/.\_\/\_/\_\ | |
// \/___/ \/___/ \/___/ \/___/ \/____/\/____/\/___/ \/__/\/_/\//\/_/ | |
// | |
function bubblejax_admin() { include('bubblejax_admin.php'); } | |
function bubblejax_addpage() { add_options_page("BubbleJax", "BubbleJax", "update_core", "bubblejax", "bubblejax_admin"); } // page title, link text, permission function, url param | |
add_action('admin_menu', 'bubblejax_addpage'); | |
class BubbleJax { | |
// constants for employee use only | |
const VERSION = "1.0"; | |
// filled in constructor bellow | |
public $token; | |
public $groupdomain; | |
// this is where the authentication will go! | |
// for now, just make sure nothing's empty... | |
public function valid() { | |
if (!empty($this->token) && !empty($this->groupdomain)) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
public function url($action, $jsonp = false) { | |
if (!$this->valid()) { return ""; } | |
$action = strtolower($action); | |
// hmmm... protocols will get messed up with https | |
$url = "http://".$this->groupdomain."/bubblejax?action="; | |
// tommy, consider making this an enum or something like that. | |
switch ($action) { | |
case "ad": case "ads": | |
$url .= "ads&type=undefined&count=100&order=coupontype"; | |
break; | |
case "interstitial": case "interstitials": | |
$url .= "ads&type=magazine&count=100&order=coupontype"; | |
break; | |
case "magazine": | |
$url .= "magazine"; | |
break; | |
case "mail": | |
$url .= "mail"; | |
break; | |
case "survey": case "surveys": | |
$url = "survey"; | |
break; | |
} | |
if ($jsonp) { $url .= "&callback=?"; } | |
return $url; | |
} | |
// returns success boolean for output handling on frontend | |
function __construct() { | |
// need to check for sessionid (or WP equiv) before you start saving things, tommy... | |
if (isset($_POST["bubblejax_savesettings"])) { | |
$this->token = $_REQUEST["bubblejax_token"]; | |
update_option('bubblejax_token', $this->token); | |
$this->groupdomain = $_REQUEST["bubblejax_groupdomain"]; | |
update_option('bubblejax_groupdomain', $this->groupdomain); | |
if (!$this->valid()) { | |
{ ?><div class="error"><p><strong>Hmm...</strong> Something's missing. Want to try that again?</p></div><?php } | |
} else { | |
{ ?><div class="updated"><p><strong>Settings saved.</strong></p></div><?php } | |
} | |
} else { | |
$this->token = get_option("bubblejax_token"); | |
$this->groupdomain = get_option("bubblejax_groupdomain"); | |
if (!$this->valid()) { | |
{ ?><div class="updated"><p><strong>Let's get started.</strong> Please fill out the form below.</p></div><?php } | |
} | |
} | |
} // construct | |
// API data is JSON but kinda needs to be stored as mySQL | |
// this will make and fill DB tables to match schema | |
// takes a type string, which needs to be one of the switchcases in url() | |
// should work on all responses of { Items: [] } | |
// returns success boolean | |
public function updateTable($sType) { | |
if (!$this->valid()) { return false; } | |
// preface field with quick hungarian | |
$preface = substr($sType,0,2); | |
// get new ads from bubblejax | |
$newobjects = $this->BubbleJaxPost($this->url($sType)); | |
if (count($newobjects) < 1) { return false; } | |
// incoming objects may have empty props for undefined values. | |
// iterate through objects and make a list of all new used props and an assoc array w/ typical values | |
$allnewprops = array(); | |
$fullnewobject = array(); | |
foreach($newobjects->Items as $object) { | |
$props = get_object_vars($object); | |
foreach ($props as $key => $val) { | |
if (!in_array($key, $allnewprops)) { | |
$allnewprops[] = $key; | |
$fullnewobject[$key] = $val; | |
} | |
} | |
} | |
$allnewprops[] = "Date"; | |
sort($allnewprops); | |
p("All of the props used on these objects: ".implode(", ", $allnewprops)); | |
// use existing WP classes for db | |
global $wpdb; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); | |
$wpdb->show_errors(); | |
$tablename = $wpbd->prefix."bubblejax_".$sType; | |
h1("updateTable: ".$tablename); | |
// verify table exists | |
// if it does, verify schema and drop/create if inconsistent | |
$results = $wpdb->get_results($wpdb->prepare( | |
"SELECT COLUMN_NAME FROM information_schema.columns WHERE table_schema = 'wordpress' AND table_name = %s", | |
$tablename | |
)); | |
$existingcolumns = array(); | |
foreach ($results as $row) { $existingcolumns[] = $row->COLUMN_NAME; } | |
sort($existingcolumns); | |
$bMakeTable = false; | |
if (count($existingcolumns) == 0) { | |
h2("table does not exist"); | |
$bMakeTable = true; | |
} else { | |
h2("table exists, verifying schema"); | |
$bConsistent = true; | |
$i = 0; | |
echo "NEW PROP FROM API vs OLD FIELD IN DB<br />"; | |
foreach ($allnewprops as $prop) { | |
echo $preface.$prop." vs ".$existingcolumns[$i]."<br />"; | |
if ($preface.$prop !== $existingcolumns[$i]) { | |
$bMakeTable = true; | |
h3("Inconsistent schemas, deleting"); | |
$wpdb->query($wpdb->prepare( | |
"DROP TABLE %s", | |
$tablename | |
)); | |
break; | |
} | |
$i++; | |
} | |
} | |
if ($bMakeTable) { | |
h2("bMakeTable"); | |
$sql = "CREATE TABLE $tablename ( "; | |
$i = 0; | |
foreach ($fullnewobject as $name=>$val) { | |
if ($i > 0) { $sql .= ","; } | |
$sql .= "\n\t".$preface.$name; | |
// guessing on type here. keep an eye on this. | |
if (is_string($val)) { | |
$sql .= " VARCHAR(100) COLLATE utf8_general_ci NULL"; | |
} else { | |
$sql .= " int(10) unsigned NOT NULL"; | |
} | |
$i++; | |
} | |
$sql .= ",\n\t".$preface."Date datetime"; | |
// if (isset($fullnewobject["KeyEncoded"])) { $sql .= ",\n\tPRIMARY KEY (".$preface."KeyEncoded)"; } | |
$sql .= "\n);"; | |
pre($sql); | |
dbDelta($sql); | |
} else { | |
h2("table fine"); | |
} | |
// insert new data and remove old data | |
$dNow = current_time('mysql'); | |
foreach ($newobjects->Items as $obj) { | |
// make array from object, preface fields, add timestamp | |
$oldArr = get_object_vars($obj); | |
$newArr = array(); | |
foreach ($oldArr as $key=>$value) { | |
$newArr[$preface.$key] = $value; | |
}; | |
$newArr[$preface."Date"] = $dNow; | |
h3("Inserting"); | |
pre($newArr); | |
$wpdb->insert($tablename, $newArr); | |
// $wpdb->print_error(); | |
// with new in, we can delete old w/o worry | |
$wpdb->query($wpdb->prepare( | |
"DELETE FROM wordpress.".$wpdb->escape($tablename)." WHERE ".$wpdb->escape($preface)."Date < %s", | |
$dNow | |
)); | |
} | |
return true; | |
} // updateAds() | |
// function for posting to JSON API | |
// accepts URL, optional assoc array of form data | |
// returns assoc array | |
private function BubbleJaxPost($url, $arr = array()) { | |
if (!isset($url) || !$this->valid()) { return false; } | |
$ch = curl_init(); | |
// for testing object instead of array | |
// $url = "test2.saffie.com:49170/bubblejax?action=interstitial"; | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_HEADER, 0); | |
curl_setopt($ch, CURLOPT_REFERER, $_SERVER["HTTP_HOST"]); | |
if (is_array($arr)) { | |
$arr["token"] = $this->token; | |
curl_setopt($ch, CURLOPT_POST, count($arr)); | |
$params = ""; | |
foreach($arr as $key => $val) { | |
$params .= urlencode($key)."=".urlencode($val)."&"; | |
} | |
$params = rtrim($params, "&"); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $params); | |
// pre($params); | |
} | |
$output = curl_exec($ch); | |
curl_close($ch); | |
if ($output == false) { | |
echo "<p><strong>cURL Error: </strong></p><pre>"; | |
var_dump($ch); | |
echo "</pre>"; | |
} | |
$json = json_decode($output); | |
// $response = MagicObject::makeList($json); | |
// pre($response); | |
return $json; | |
} | |
// takes array of arrays where keys have hungarian prefix, optional count of letters | |
// returns array of arrays with normalized keys | |
static function deprefix($results, $iLetters=2) { | |
$newResults = array(); | |
foreach ($results as $r) { | |
$arr = get_object_vars($r); | |
$newArr = array(); | |
foreach ($arr as $key=>$val) { | |
$newArr[substr($key, $iLetters)] = $val; | |
} | |
$newResults[] = $newArr; | |
} | |
return $newResults; | |
} | |
// takes display string (ad, survey, etc), type (mag, sponsor), ad count, booleans to echo and to show errors | |
// returns output | |
// consider enumerating string variables, tommy | |
static function display($sDisplay, $sType, $iCount, $bEcho, $bShowErrors) { | |
// inject css | |
wp_register_style('bubblejax_style', plugin_dir_url(__FILE__)."style_client.css"); | |
wp_enqueue_style('bubblejax_style'); | |
// hmmm file exists doesn't like relative urls. this is hacky. | |
$template = ""; | |
@$template = file_get_contents(plugin_dir_url(__FILE__)."templates/".$sDisplay."_".$sType.".html"); | |
if ($template == "") { | |
$template = file_get_contents(plugin_dir_url(__FILE__)."templates/".$sDisplay."_default.html"); | |
} | |
$iCount = intval($iCount); | |
if ($iCount < 1) { $iCount = 1; } | |
if (empty($sType)) { return false; } | |
// use mustache templater and wpdb | |
require_once("mustache.php"); | |
$m = new Mustache; | |
global $wpdb; | |
$results = BubbleJax::deprefix( | |
$wpdb->get_results($wpdb->prepare( | |
"SELECT * FROM wordpress.bubblejax_ads WHERE adType=%s ORDER BY RAND() LIMIT 0, %d", | |
$sType, | |
$iCount | |
)) | |
); | |
if (count($results) < 1) { return false; } | |
$output = $m->render($template, array( | |
"Type" => $sType, | |
"Items" => $results | |
)); | |
// if results are more than a day old, update table | |
$hrsOld = (time() - strtotime($results[0]["Date"])) / 60 / 60; | |
if ($hrsOld > 24) { | |
$bubblejax = new BubbleJax(); | |
$bubblejax->updateTable($sDisplay); | |
} | |
if ($bEcho) { echo $output; } | |
return $output; | |
} | |
public function mailmessage($emailTo, $emailFrom, $subject, $message) { | |
$resp = $this->BubbleJaxPost($this->url("mail"), array( | |
emailto => $emailTo, | |
emailfrom => $emailFrom, | |
subject => $subject, | |
message => $message | |
)); | |
return $resp->success; | |
} | |
} // BubbleJax | |
// pardon me. i'm exposed. | |
function bubblejax_ads($sType, $iCount = 1, $bEcho = true, $bShowErrors = true) { return BubbleJax::display("ad", $sType, $iCount, $bEcho, $bShowErrors); } | |
function bubblejax_ads_shortcode($atts) { | |
extract(shortcode_atts(array("type"=>null,"count"=>1), $atts)); | |
return bubblejax_ads($atts["type"], $atts["count"], false); | |
} | |
add_shortcode('bubblejax_ads', 'bubblejax_ads_shortcode'); | |
// http://sillybean.net/2010/02/using-shortcodes-everywhere/ | |
add_filter('widget_text', 'shortcode_unautop'); | |
add_filter('widget_text', 'do_shortcode'); | |
// tommy's convenience functions. | |
function urlParamed($paramName, $paramValue, $bEcho=true) { | |
$url = $_SERVER["REQUEST_URI"]."&".urlencode($paramName)."=".urlencode($paramValue); | |
if ($bEcho) { echo $url; } | |
return $url; | |
} | |
function pre($arg) { echo "<pre>"; if (is_array($arg)) { print_r($arg); } elseif (is_string($arg)) { echo $arg; } else { var_dump($arg); } echo "</pre>"; } | |
function h1($s) { echo "<h1>$s</h2>"; } | |
function h2($s) { echo "<h2>$s</h2>"; } | |
function h3($s) { echo "<h3>$s</h3>"; } | |
function p($s) { echo "<p>$s</p>"; } | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment