IMAP Copy to local file.

I had a mail server that only supported IMAP, but their webmail interface is horrible. So I decided to write a small script to grab the email from the imap server and save it locally. In my case the local directory is the mail directory in cpanel so I can use gmail to grab the emails via POP3 to use gmail. The mail flow is:

IMAP SERVER -> SCRIPT -> LOCAL POP3 -> GMAIL

imapscript

 Nmsgs}",0);
foreach ($result as $overview) 
{
	echo "$overview->subject\n";
	$mailfile = tempnam("/home/mth/mail/stephenjc.com/asa/cur/","EMAIL-");
	$message =  imap_fetchbody($srcstream,$overview->uid,"",FT_UID);
	$localmail = fopen($mailfile, "w");
	fwrite($localmail,$message);
	fclose($localmail);
	imap_mail_move($srcstream,$overview->msgno,'Forwarded'); 

}

imap_expunge($srcstream);
imap_close($srcstream);
echo "deleteing lock\n";
unlink($lockfile);

echo '     ]]> ';
?>

PHP hide download link

This is php code that I use to hide the download link to files.

$filename = strrev($downloads[$id]);
$filename = explode("/", $filename);

# Remote file size
$ary_header = get_headers($downloads[$id], 1);     
$filesize = $ary_header['Content-Length'];
$type = $ary_header['Content-Type'];

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header('Content-type: '.$type);
header('Content-Disposition: attachment; filename="'.strrev($filename[0]).'"');
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$filesize);
readfile($downloads[$id]);

This is a Email to Google Calendar Quickadd gateway.

You can email a special address and it will take the subject of the email and send it to googles quickadd feature. This is a simple way to add events to your google calendar via email.
http://www.google.com/calendar
http://framework.zend.com/download/gdata
http://www.google.com/support/calendar/bin/answer.py?hl=en&answer=36604

  • You need to have Zend’s Gdata framework installed.
  • The first code example you need to add your google calendar information
  • the 2nd peice of code parses the email and calls the the quickadd function
  • In cpanel setup a forwarder and pipe it to a program of TOGcal.php
<?php //GoogleCal-Functions.php

require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');

// Enter your Google account credentials
$email = '[email protected]';
$passwd = 'MyPass';
$ourCal = 'Cal Name';
$ourCalUrl = '';
try {
 $client = Zend_Gdata_ClientLogin::getHttpClient($email, $passwd, 'cl');
 }
catch(Zend_Gdata_App_AuthException $ex)
{
    echo "Unable to authenticate";
    exit(1);
 }

$cal = new Zend_Gdata_Calendar($client);

$calFeed = $cal->getCalendarListFeed();

foreach ($calFeed as $calendar)
{
    if ($calendar->title->text == $ourCal)
 {
  //$ourCalUrl = explode('/',$calendar->id);
  //$ourCalUrl = 'http://www.google.com/calendar/feeds/'. $ourCalUrl[6] . '/private/full';
  $ourCalUrl = $calendar->getSelfLink()->getHref() . '/private/full';
  $ourCalUrl = str_replace("default/", "",$ourCalUrl);
 }
 //echo $calendar->title->text . " || " . $calendar->getSelfLink()->getHref() . "
";
}
 //echo $ourCalUrl;
 //echo $client->getUri(true);
 //createQuickAddEvent ($client ,$ourCalUrl,'WO Test at Jun 2, 2008 8:00am - Jun 6, 2008 5:00pm');
 //createEvent($client,$ourCalUrl);

function createQuickAddEvent ($client, $URI = NULL, $quickAddText) {
  $gdataCal = new Zend_Gdata_Calendar($client);
  $event = $gdataCal->newEventEntry();
  $event->content = $gdataCal->newContent($quickAddText);
  $event->quickAdd = $gdataCal->newQuickAdd(true);

  $newEvent = $gdataCal->insertEvent($event,$URI);
  return $newEvent->id->text;
}

/**
 * Creates an event on the authenticated user's default calendar with the
 * specified event details.
 *
 * @param  Zend_Http_Client $client    The authenticated client object
 * @param  string           $title     The event title
 * @param  string           $desc      The detailed description of the event
 * @param  string           $where
 * @param  string           $startDate The start date of the event in YYYY-MM-DD format
 * @param  string           $startTime The start time of the event in HH:MM 24hr format
 * @param  string           $endDate   The end date of the event in YYYY-MM-DD format
 * @param  string           $endTime   The end time of the event in HH:MM 24hr format
 * @param  string           $tzOffset  The offset from GMT/UTC in [+-]DD format (eg -08)
 * @return string The ID URL for the event.
 */
function createEvent ($client, $URI = NULL, $title = 'Tennis with Beth', $desc='Meet for a quick lesson', $where = 'On the courts',$startDate = '2008-06-20', $startTime = '9:00',$endDate = '2008-06-20', $endTime = '14:00', $tzOffset = '-04')
{
  $gc = new Zend_Gdata_Calendar($client);
  $newEntry = $gc->newEventEntry();
  $newEntry->title = $gc->newTitle(trim($title));
  $newEntry->where  = array($gc->newWhere($where));

  $newEntry->content = $gc->newContent($desc);
  $newEntry->content->type = 'text';

  $when = $gc->newWhen();
  $when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
  $when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
  $newEntry->when = array($when);

  echo $URI."||".$title."||".$desc."||".$where."||".$startDate."||".$startTime."||".$endDate."||".$endTime."||".$tzOffset;
  $createdEntry = $gc->insertEvent($newEntry, $URI);
  return $createdEntry->id->text;
}
?>
#!/usr/bin/php -q
<?php
//TOGcal.php
//Takes the subject and uses quickadd to create an event.
include "GoogleCal-Functions.php";

$msg = "";
$email ='';
$fd = fopen("php://stdin", "r");
while (!feof($fd))
{
 $email .= fread($fd, 1024);
}
fclose($fd);
$msg .= "got Email || ";

$mail = mailparse_msg_create();
mailparse_msg_parse($mail,$email);
$struct = mailparse_msg_get_structure($mail);
$section = mailparse_msg_get_part($mail, "1");
$info = mailparse_msg_get_part_data($section);

$msg .= $info['headers']['from'] . " || " . $info['headers']['subject']  . " || ";

//valid sending domains
if (preg_match('/@mydomain\.com/', $info['headers']['from']))
{
 createQuickAddEvent($client,$ourCalUrl,$info['headers']['subject']);
 $msg .= "regex matched || ";
} 
mailparse_msg_free($mail);

//emailError($msg);


?>

WHMCS Ahsay Plugin

<?php /* V1.0 Lite Version; Only Support suspend and unsuspend.  Installation and Setup -copy this file into <whmcsroot>/modules/servers/ahsayosb. You will have to create the folder ahsayosb in lower case.

-Add a new server and in Server Details select Ahsayosb as the type and put in your system administrator username and password. The Access Hash is not used and might be used for advanced settings in the future.
-If you select Secure the module will use ssl for connections (Highly Recommended)
-You can ignore all the Nameservers settings.

-Create a new product or modify an existing osb product and under module settings set the Modlue Name to Ahsayosb
-There are options for Language/Client Type/Bandwidth. These all can be ignored right now because this version only supports Suspend and Unsuspend.

-In the user account under the Products/Services make sure the correct username is listed the password can be ignored.

*/
$apiurl = "/obs/api/";

$auth = "AuthUser.do";
$adduser = "AddUser.do";
$moduser = "ModifyUser.do";
$removeuser = "RemoveUser.do";
$listuser = "ListUsers.do";
$getuser = "GetUser.do";

function ahsayosb_ConfigOptions() {
 # Should return an array of the module options for each product - maximum of 24
    $configarray = array(
  "Default Language" => array("Type" => "dropdown", "Options" => "English-en, Czech-cs, Danish-da, German-de, Spanish-es, French-fr,Finnish-fi,Icelandic-is,Italian-it,Japanese-ja,Lithuanian-lt,Dutch-nl,Norwegian-no,Portuguese-pt_PT, Slovenian-sl, Swedish-sv, Chinese(Simplified)-zh_CN, Chinese(Traditional)-zh_TW"),
  "Client Type" => array("Type" => "dropdown", "Options" => "OBM, ACB", "Description" => ""),
  "Bandwidth" => array("Type" => "text", "Size" => "5", "Description" => "MB, 0 = Unlimited"),
  "Fast Terminate" => array("Type" => "yesno", "Description" => "If enabled accounts will be instantly terminated"),
  "Add Group" => array("Type" => "text", "Size" => "7", "Description" => "Ad group name.(Only for ACB)"),
  //"Package Name" => array( "Type" => "text", "Size" => "25", ),
  //"Web Space Quota" => array( "Type" => "text", "Size" => "5", "Description" => "MB" ),
  //"FTP Access" => array( "Type" => "yesno", "Description" => "Tick to grant access" ),
     //"Subdomains" => array( "Type" => "dropdown", "Options" => "1,2,5,10,25,50,Unlimited"),
 );
 return $configarray;
}

function ahsayosb_CreateAccount($params) {

    # ** The variables listed below are passed into all module functions **

    $serviceid = $params["serviceid"]; # Unique ID of the product/service in the WHMCS Database
    $pid = $params["pid"]; # Product/Service ID
    $producttype = $params["producttype"]; # Product Type: hostingaccount, reselleraccount, server or other
    $domain = $params["domain"];
 $username = $params["username"];
 $password = $params["password"];
    $clientsdetails = $params["clientsdetails"]; # Array of clients details - firstname, lastname, email, country, etc...
    $customfields = $params["customfields"]; # Array of custom field values for the product
    $configoptions = $params["configoptions"]; # Array of configurable option values for the product

    # Product module option settings from ConfigOptions array above
    $configoption1 = $params["configoption1"];
    $configoption2 = $params["configoption2"];
    $configoption3 = $params["configoption3"];
    $configoption4 = $params["configoption4"];

    # Additional variables if the product/service is linked to a server
    $server = $params["server"]; # True if linked to a server
    $serverid = $params["serverid"];
    $serverip = $params["serverip"];
    $serverusername = $params["serverusername"];
    $serverpassword = $params["serverpassword"];
    $serveraccesshash = $params["serveraccesshash"];
    $serversecure = $params["serversecure"]; # If set, SSL Mode is enabled in the server config

 # Code to perform action goes here...

 if ($successful) {
  $result = "success";
 } else {
  $result = "Error Message Goes Here...";
 }
 #return $result;
 return "Not Implemented";
}

function ahsayosb_TerminateAccount($params) {

 # Code to perform action goes here...

    if ($successful) {
  $result = "success";
 } else {
  $result = "Error Message Goes Here...";
 }
 #return $result;
 return "Not Implemented";
}

function ahsayosb_SuspendAccount($params) {
 if ($params["serversecure"] == 'on')
 {
  $conn = "https://";
 }
 else
 {
  $conn = "http://";
 }

 $adminAuth = "?SysUser=" . $params["serverusername"]."&SysPwd=".$params["serverpassword"]. "&";
 #getRemoteData($conn, $server, $cmd, $getcmd = NULL)

 $response = getRemoteData($conn, $params["serverhostname"], $GLOBALS["moduser"], $adminAuth . "LoginName=" . $params["username"] . "&Status=SUSPENDED");

 #$moduser, $adminAuth . "LoginName=$user&Status=ENABLE");

 if ($response == "<ok/>") {
  $result = "success";
 } else {
  $result = "Error: The return was " . $response;
 }
 return $result;
}

function ahsayosb_UnsuspendAccount($params) {
 if ($params["serversecure"] == 'on')
 {
  $conn = "https://";
 }
 else
 {
  $conn = "http://";
 }

 $adminAuth = "?SysUser=" . $params["serverusername"]."&SysPwd=".$params["serverpassword"]. "&";
 #getRemoteData($conn, $server, $cmd, $getcmd = NULL)

 $response = getRemoteData($conn, $params["serverhostname"], $GLOBALS["moduser"], $adminAuth . "LoginName=" . $params["username"] . "&Status=ENABLE");

 #$moduser, $adminAuth . "LoginName=$user&Status=ENABLE");

 if ($response == "<ok/>") {
  $result = "success";
 } else {
  $result = "Error: The return was " . $response;
 }
 return $result;
}

function ahsayosb_ChangePassword($params) {

 # Code to perform action goes here...

    if ($successful) {
  $result = "success";
 } else {
  $result = "Error Message Goes Here...";
 }
 #return $result;
 return "Not Implemented";
}

function ahsayosb_ChangePackage($params) {

 # Code to perform action goes here...

    if ($successful) {
  $result = "success";
 } else {
  $result = "Error Message Goes Here...";
 }
 #return $result;
 return "Not Implemented";
}

function ahsayosb_ClientArea($params) {
 $code = '<form action="http://'.$serverip.'/controlpanel" method="post" target="_blank">
<input type="hidden" name="user" value="'.$params[">
<input type="hidden" name="pass" value="'.$params[">
<input type="submit" value="Login to Control Panel">
<input type="button" value="Login to Webmail" onclick="window.open(\'http://'.$serverip.'/webmail\')">
</form>';
 return $code;
}

function ahsayosb_AdminLink($params) {
 if ($params["serversecure"] == 'on')
 {
  $conn = "https://";
 }
 else
 {
  $conn = "http://";
 }

 $code = '<form action="'. $conn .$params[" method="post" target="_blank">
<input type="hidden" name="systemLoginName" value="'.$params[">
<input type="hidden" name="systemPassword" value="'.$params[">
<input type="submit" value="OSB Admin">
</form>';
 return $code;
}

function ahsayosb_LoginLink($params) {
 if ($params["serversecure"] == 'on')
 {
  $conn = "https://";
 }
 else
 {
  $conn = "http://";
 }
 echo "<a href="\" loginname=".$params[" target="\" style="\">login to control panel</a>";

}

function ahsayosb_AdminCustomButtonArray() {
 # This function can define additional functions your module supports, the example here is a reboot button and then the reboot function is defined below
    $buttonarray = array(
  #"Reboot Server" => "reboot",
 );
 return $buttonarray;
}

function ahsayosb_reboot($params) {

 # Code to perform action goes here...

    if ($successful) {
  $result = "success";
 } else {
  $result = "Error Message Goes Here...";
 }
 return $result;
}

#Inernal Functions ONLY
function getRemoteData($conn, $server, $cmd, $getcmd = NULL)
{
 $response = '';
 if (ini_get('allow_url_fopen') == '1')
 {
  $response = file_get_contents($conn . $server . $GLOBALS['apiurl'] . $cmd . $getcmd);

  //use filegetcontects
 }
 else
 {
  print "Have to use curl";
 }
 return $response;
}

?>

Here is a a module/plugin for whmcs that controls an Ahsay off-site backup server.

http://www.whmcs.com
http://www.ahsay.com

It will automatically suspend and un-suspend off-site backup accounts.