Archive for the ‘PHP’ Category

Post via jQuery across domains (in this case to a Zend Controller and subsequent view) and display the results

Thursday, August 25th, 2011

the jQuery posting page, in brief:

<document…>
<head>
<script src=”http://code.jquery.com/jquery-1.5.js”></script>
</head>
<body>
<form id=”enewsform” name=”enewsform” action=”http://componentserver/controllername/post” method=”post”>
<input type=”text” name=”email” id=”email” value=”<?php echo $_REQUEST['email']; ?>” />
<a id=”submitsubscribe” title=”Subscribe” href=”javascript:{}” onclick=”return false;”>sign up</a>
</form>
<script src=”http://components.someserver.com/js/jquery.validation.js” type=”text/javascript”></script>
<script>
$(‘#submitsubscribe’).click(function(){
$(“#enewsform”).submit();
});

$(“#enewsform”).submit(function(event) {
event.preventDefault();
$( “#result” ).html (“submitting…”);
var $form = $( this ),
term = $form.find( ‘input[name="email"]‘ ).val(),
url = $form.attr( ‘action’ );

if($.validation.email(term)){
$.getJSON(url + “?email=” + term + “&jsoncallback=?”, function(data){
$( “#result” ).html( data['error'] );
if(data['error']== “errormatchingstring”){
$( “#result” ).html( “Seems like it worked” );
}else{ $( “#result” ).html(data['error']); }
});
}
else{ $( “#result” ).html (“Please enter your email address”); }

});
</script>

<div id=”result”></div>

// the component Zend controller in question receives the post, does whatever it does, renders its view, and we access the results from the view (don’t forget to pass data to the view with something like this:
$this-> view-> viewresult = $this-> viewData;)

<? php
echo $_REQUEST['jsoncallback'] . ‘(‘ . json_encode($this-> viewresult) . ‘)’;
? >

Bronto API PHP Class to Send a Contact a particular Message (Zend Helper)

Thursday, August 25th, 2011

< ? php
class
Zend_Controller_Action_Helper_BrontoSendMessage extends Zend_Controller_Action_Helper_Abstract {

public $message;
public $client;
public $viewData;
public $list;
public $now = “date(‘c’)”;
public $recipientObject;
public $email;
public $contact;
public $contactId;

private $fromName = ‘WHATEVERYOUWOULDLIKE’;
private $fromEmail = ‘YOU@YOURMAIL.COM’;

public function login(){
ini_set(“soap.wsdl_cache_enabled”, “0″);
date_default_timezone_set(‘America/New_York’);

$wsdl = “https://api.bronto.com/v4?wsdl”;
$url = “https://api.bronto.com/v4″;

$this-> client = new SoapClient($wsdl, array(‘trace’ => 1, ‘encoding’ => ‘UTF-8′));
$this-> client->__setLocation($url);

// Login
$token = “YOUR BRONTO TOKEN HERE”;
$sessionId = $this-> client->login(array(“apiToken” => $token))->return;
if (!$sessionId) {
return “Login failed”;
}
$this-> client->__setSoapHeaders(array(new SoapHeader(“http://api.bronto.com/v4″,
‘sessionHeader’,
array(‘sessionId’ => $sessionId))));

$this-> viewData['login'] = “logged in”;
}

public function setContact($email){
$this-> email = $email;

$filter = array(‘email’ => array(array(‘operator’ => ‘EqualTo’,'value’ => $this-> email)));

$this-> contact = $this-> client->readContacts(array(‘pageNumber’ => 1,
‘includeLists’ => true,
‘filter’ => $filter,
));
if(!isset($this->contact->return->id))
{
//return ‘Email not subscribed’;
}
else
{
$this-> contactId = $this->contact->return->id;
//return $this->contactId;
}

$this-> recipientObject = array(‘type’ => ‘contact’, ‘id’ => $this->contactId);
}

public function setDelivery($messageid){
$delivery = array(‘start’ => date(‘c’),
‘messageId’ => $messageid,
‘fromName’ => $this-> fromName,
‘fromEmail’ => $this-> fromEmail,
‘recipients’ => array($this-> recipientObject),
);

$this->client->addDeliveries(array($delivery));
}
}
? >

called from another Zend Controller as a helper in this fashion:

$this-> _helper-> BrontoSendMessage->login();
$this-> _helper-> BrontoSendMessage->setContact($this-> email);
$this-> _helper-> BrontoSendMessage->setDelivery($this-> messageid);

Bronto Direct Import API import .csv file (upload) via HTML form post or via PHP CURL with code examples

Tuesday, August 23rd, 2011

We are building a Cassandra based system (of record) to capture emails so that we can handle 100k users converging on an online event as quickly as possible.  Rather than relying on our third party email marketing vendor, Bronto, to handle the volume we could possibly experience, and risk possibly failing (as others doing the same thing recently have done…cough cough….Oprah and Eckhart Tolle), we’ll build our own system that can be tested correctly, and thus handle the volume, and then we’ll dump said new emails in reasonably sized files out to Bronto, who will then send out confirmation emails for us…

This post covers the script that will take file exports from Cassandra (sorry, no Cassandra in this one…), and Post them to Bronto.  Below is an example that uses a standard HTML form Post, for understanding and comprehensiveness, and an example that uses CURL (which easily allows this process to happen as part of an ordinary CRON job).

First we have to set up, and get some connection values, from Bronto:

  • Log into Bronto
  • From the top menu select Home->Settings
  • select Data Exchange
  • scroll to the bottom to Direct Import and grab the following connection values:
    • URL: http://app.bronto.com/mail/subscriber_upload/index/
    • site_id: YOUR_SITE_ID
    • user_id: YOUR_USER_ID
    • key: YOUR_KEY
Further reference, Bronto support docs are here:
https://app.bronto.com/mail/help/help_view/?k=mail:home:api_tracking:tracking_direct_import
 

Next let’s look at what this Post might look like as your common HTML form:

<form method=”post” action=”http://app.bronto.com/mail/subscriber_upload/index/” enctype=”multipart/form-data”>
<input type=”text” name=”source” value=”Test Contacts” />
<input type=”text” name=”format” value=”csv” />
<input type=”file” name=”filename” value=”C:\xampp\htdocs\YOUSITEFOLDERPATH\batch.csv” />
<input type=”text” name=”site_id” value=”YOUR_SITE_ID” />
<input type=”text” name=”user_id” value=”YOUR_USER_ID” />
<input type=”text” name=”key” value=”YOUR_KEY” />
<input type=”submit” name=”submit” value=”submit” />
</form>

Next let’s look at what this Post might look like in a PHP script using CURL:

<? php
$fields = array(
source‘=>”Test contacts“,
format‘=>csv,
filename‘=>’@‘.’C:\xampp\htdocs\YOURSITEFOLDERPATH\batch.csv‘,
site_id‘=>YOUR_SITE_ID,
user_id‘=>YOUR_USER_ID,
key‘=>’YOUR_KEY‘,
);

/* The key here is the ‘@’ above, which tells CURLOPT_POSTFIELDS to UPLOAD that file, parenthesis critical! */

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, ‘http://app.bronto.com/mail/subscriber_upload/index/‘);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$result = curl_exec($ch);
curl_close($ch);

var_dump($result);
? >

Last but not least, make (or in our case receive from Cassandra export dump) the .csv file to be Posted.
First column, Email, 2nd through n filled with email addresses, save it as .csv comma delineated.
Yes, it’s actually that simple.
I hope this helps somebody.

Create a php page with a form that searches (curls) two separate WordPress applications

Friday, July 29th, 2011

We have many installations where I work, some of them newer, some older, some severely whacked at by coders, some pretty much default installations.

Anyhow, now they want a page from which a visitor could enter a search term, click submit, and get results from all of the separate applications!

Here is my solution:

The new page has your basic self submitting form:

<form action=”" method=”post”>
<label for=”search”>Search:</label>
<input name=”s” type=”text” value=”"  />
<input type=”submit” />
</form>

Then, of course, it grabs what has been submitted:

<?php

/**
* Get Search parameters
*/
$search = $_POST['s'];
$search = str_replace(” “,”%20″,$search);
echo $search;

?>

This checks to ensure that the user didn’t submit nothing (as WordPress would give us every post as currently coded…! ick).  This would also be a great place to guard against injection attacks (or in the last step of course), to filter what may be searched for, etc., but I’ll leave those concerns for another discussion:

<?php
/**
* If desired search is NOT empty, search, otherwise don’t
*/
if(($search != ”) && ($search != null) && (!empty($search)) )
{
?>

Now we curl in the results from each installation:

<?php
/**
* Get Search results from WP app 1
*/
$sub_req_url = “http://YOURAPP1URLHERE/searchpage.php?s=” . $search;
$ch = curl_init($sub_req_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$podcast_return = curl_exec($ch);
curl_close($ch);
echo $podcast_return;

/**
* End
*/
?>

<?php
/**
* Get Search results from WP app 2
*/
$sub_req_url = “http://YOURAPP2URLHERE/searchpage.php?s=” . $search;
$ch = curl_init($sub_req_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$podcast_return = curl_exec($ch);
curl_close($ch);
echo $podcast_return;

/**
* End
*/
?>

Now let’s close our IF block, and maybe provide ELSE if we want to…

<?php
/**
* close if empty block
*/
}
else
{
}
?>

Ok, that’s the end of our new page, again, I’ll leave formatting of the results and the rest of the page to another discussion.  Now let’s make the above mentioned search pages “searchpage.php” (make one for EACH APP, lives in the ROOT of EACH WP installation that we’re searching!):

<?php
/**
* WordPress App 1 Post Results Pull-In
*/
define(‘WP_USE_THEMES‘, true);
include(‘wp-load.php’ );
$query = new WP_Query(‘s=’ . $_GET['s']);
if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>

/* Again, how you choose to skin the results could be implemented here, but I’ll leave that up to you… */

<div id=”post-<?php the_ID(); ?>“>
<h2><?php the_title(); ?></h2>
<div>
<?php the_content(‘<p>Read the rest of this page &raquo;</p>‘); ?>
<?php wp_link_pages(array(‘before’ => ‘<p><strong>Pages:</strong> ‘, ‘after’ => ‘</p>‘, ‘next_or_number’ => ‘number’)); ?>
</div>
</div>
<?php endwhile; endif; ?>

Whoohoo! Great Work!

PHP script to download .ics Outlook Event Schedule Calendar Alarm add

Thursday, July 28th, 2011

My boss wanted the ability to put a button on an event on our site that would book it in the user’s Outlook calendar.  Short story is the link downloads an .ics file to their computer, opened with Outlook it schedules the Event, Reminder, Priority, Schedule, and so on.  Thank you http://www.myhow2guru.com

<?php
//This is the most important coding.
header(“Content-Type: text/Calendar”);
header(“Content-Disposition: inline; filename=filename.ics”);
echo “BEGIN:VCALENDAR\n”;
echo “PRODID:-//Microsoft Corporation//Outlook 12.0 MIMEDIR//EN\n”;
echo “VERSION:2.0\n”;
echo “METHOD:PUBLISH\n”;
echo “X-MS-OLK-FORCEINSPECTOROPEN:TRUE\n”;
echo “BEGIN:VEVENT\n”;
echo “CLASS:PUBLIC\n”;
echo “CREATED:20091109T101015Z\n”;
echo “DESCRIPTION:How 2 Guru Event\\n\\n\\nEvent Page\\n\\nhttp://www.myhow2guru.com\n”;
echo “DTEND:20091208T040000Z\n”;
echo “DTSTAMP:20091109T093305Z\n”;
echo “DTSTART:20091208T003000Z\n”;
echo “LAST-MODIFIED:20091109T101015Z\n”;
echo “LOCATION:Anywhere have internet\n”;
echo “PRIORITY:5\n”;
echo “SEQUENCE:0\n”;
echo “SUMMARY;LANGUAGE=en-us:How2Guru Event\n”;
echo “TRANSP:OPAQUE\n”;
echo “UID:040000008200E00074C5B7101A82E008000000008062306C6261CA01000000000000000\n”;
echo “X-MICROSOFT-CDO-BUSYSTATUS:BUSY\n”;
echo “X-MICROSOFT-CDO-IMPORTANCE:1\n”;
echo “X-MICROSOFT-DISALLOW-COUNTER:FALSE\n”;
echo “X-MS-OLK-ALLOWEXTERNCHECK:TRUE\n”;
echo “X-MS-OLK-AUTOFILLLOCATION:FALSE\n”;
echo “X-MS-OLK-CONFTYPE:0\n”;
//Here is to set the reminder for the event.
echo “BEGIN:VALARM\n”;
echo “TRIGGER:-PT1440M\n”;
echo “ACTION:DISPLAY\n”;
echo “DESCRIPTION:Reminder\n”;
echo “END:VALARM\n”;
echo “END:VEVENT\n”;
echo “END:VCALENDAR\n”;
? >