plz help me out...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
calme_jai
Forum Newbie
Posts: 3
Joined: Thu Nov 08, 2007 11:49 pm

plz help me out...

Post by calme_jai »

hi friends.
i download this code form some site. this code is used to grab the contacts from address book from GMAIL. but when i run this code i am getting 4 errors.

the errors are
1. Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in /home/torque/public_html/addressbook/contacts/gmail/libgmailer.php on line 3290

2. Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in /home/torque/public_html/addressbook/contacts/gmail/libgmailer.php on line 3266

3. Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in /home/torque/public_html/addressbook/contacts/gmail/libgmailer.php on line 3266

4. Warning: curl_setopt() [function.curl-setopt]: CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir is set in /home/torque/public_html/addressbook/contacts/gmail/libgmailer.php on line 3266

The source code for ibgmailer.php is as follow

<?php

ob_start();

define("GM_USE_LIB_AS_MODULE", false); // Normal operation
define("GM_LNK_GMAIL", "https://mail.google.com/mail/");
define("GM_LNK_GMAIL_HTTP", "http://mail.google.com/mail/");
// Changed by Gan; 10 Sept 2005
define("GM_LNK_LOGIN", "https://www.google.com/accounts/ServiceLoginAuth");
// Added by Neerav; 4 Apr 2006
define("GM_LNK_LOGIN_REFER", "https://www.google.com/accounts/Service ... he=2&hl=en");
// Added by Neerav; 5 June 2005
define("GM_LNK_INVITE_REFER", "https://www.google.com/accounts/Service ... com%2Fmail");
// Updated by Neerav; 22 Aug 2006
define("GM_USER_AGENT", "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5.0.6");

/**
* @deprecated
*/
define("GM_LNK_LOGOUT", "https://mail.google.com/mail/?logout");
define("GM_LNK_REFER", "https://www.google.com/accounts/Service ... com%2Fmail");
define("GM_LNK_CONTACT", "https://mail.google.com/mail/?view=cl&s ... acts&pnl=a");
define("GM_LNK_ATTACHMENT", "https://mail.google.com/mail/?view=att&disp=att");
define("GM_LNK_ATTACHMENT_ZIPPED", "https://mail.google.com/mail/?view=att&disp=zip");
/**#@-*/

/**#@+
* Constants defining Gmail content's type.
* @var int
*/
define("GM_STANDARD", 0x001);
define("GM_LABEL", 0x002);
define("GM_CONVERSATION", 0x004);
define("GM_QUERY", 0x008);
define("GM_CONTACT", 0x010);
define("GM_PREFERENCE", 0x020);
/**#@-*/

/**#@+
* Constants defining Gmail action.
* @var int
*/
/**
* Apply label to conversation
*/
define("GM_ACT_APPLYLABEL", 1);
/**
* Remove label from conversation
*/
define("GM_ACT_REMOVELABEL", 2);
/**
* Star a conversation
*/
define("GM_ACT_STAR", 3);
/**
* Remove a star from (unstar) a conversation
*/
define("GM_ACT_UNSTAR", 4);
/**
* Mark a conversation as spam
*/
define("GM_ACT_SPAM", 5);
/**
* Unmark a conversation from spam
*/
define("GM_ACT_UNSPAM", 6);
/**
* Mark conversation as read
*/
define("GM_ACT_READ", 7);
/**
* Mark conversation as unread
*/
define("GM_ACT_UNREAD", 8);
/**
* Trash a conversation
*/
define("GM_ACT_TRASH", 9);
/**
* Directly delete a conversation
*/
define("GM_ACT_DELFOREVER", 10);
/**
* Archive a conversation
*/
define("GM_ACT_ARCHIVE", 11);
/**
* Move conversation to Inbox
*/
define("GM_ACT_INBOX", 12);
/**
* Move conversation out of Trash
*/
define("GM_ACT_UNTRASH", 13);
/**
* Discard a draft
*/
define("GM_ACT_UNDRAFT", 14);
/**
* Trash individual message.
*/
define("GM_ACT_TRASHMSG", 15);
/**
* Untrash (retrieve from trash) individual message.
* @since 27 Feb 2006
*/
define("GM_ACT_UNTRASHMSG", 18);
/**
* Delete spam, forever.
*/
define("GM_ACT_DELSPAM", 16);
/**
* Delete trash message, forever.
*/
define("GM_ACT_DELTRASHED", 17);
/**
* Deleted trashed messages from the thread forever.
* @since 27 Feb 2006
*/
define("GM_ACT_DELTRASHEDMSGS", 19);
/**#@-*/

/**#@+
* Other constants.
*/
define("GM_VER", "0.9 Beta 4");
define("GM_COOKIE_KEY", "LIBGMAILER");
define("GM_COOKIE_IK_KEY", "LIBGMAILER_IdKey"); // Added by Neerav; 6 July 2005
define("GM_USE_COOKIE", 0x001);
define("GM_USE_PHPSESSION", 0x002);
if (!defined("GM_COOKIE_TTL")) {
$ttl = 60*60*24*7;
define("GM_COOKIE_TTL", $ttl);
}
/**#@-*/


/**
* Class GMailer is the main class/library for interacting with Gmail (Google's
* free webmail service) with ease.
*
* <b>Acknowledgement</b><br/>It is not completely built from scratch. It is based on: "Gmail RSS feed in PHP"
* by thimal, "Gmail as an online backup system" by Ilia Alshanetsky, and "Gmail
* Agent API" by Johnvey Hwang and Eric Larson.
*
* Special thanks to Eric Larson and all other users, testers, and forum posters
* for their bug reports, comments and advices.
*
* @package GMailer
* @author Gan Ying Hung <ganyinghung|no@spam|users.sourceforge.net>
* @author Neerav Modi <neeravmodi|no@spam|users.sourceforge.net>
* @link http://gmail-lite.sourceforge.net Project homepage
* @link http://sourceforge.net/projects/gmail-lite Sourceforge project page
* @version 0.8.0-rc
*/
class GMailer {
/**#@+
* @access private
* @var string
*/
var $cookie_str;
var $login;
var $pwd;
/**
* Email domain
*
* Support for "Gmail for your domain".
* Domain name of email address to check.
*
* @access private
* @var string
* @author Neerav
* @since 8 Jun 2006
*/
var $domain;
var $GM_LNK_GMAIL = GM_LNK_GMAIL;
var $GM_LNK_GMAIL_HTTP = GM_LNK_GMAIL_HTTP;
var $GM_LNK_LOGIN = GM_LNK_LOGIN;
var $GM_LNK_LOGIN_REFER = GM_LNK_LOGIN_REFER;
var $GM_LNK_INVITE_REFER = GM_LNK_INVITE_REFER;

/**
* @author Neerav
* @since 13 Aug 2005
*/
var $gmail_data;
/**
* Raw packet
*/
var $raw;
/**
* Raw packet for contact list
*/
var $contact_raw;
var $timezone;
var $use_session;
var $proxy_host;
var $proxy_auth;
/**#@-*/

/**
* Reserved mailbox names
*/
var $gmail_reserved_names = array("inbox", "star", "starred", "chat", "chats", "draft", "drafts",
"sent", "sentmail", "sent-mail", "sent mail", "all", "allmail", "all-mail", "all mail",
"anywhere", "archive", "spam", "trash", "read", "unread");

/**
* @access public
* @var bool
*/
var $created;
/**
* Status of GMailer
*
* If something is wrong, check this class property to see what is
* going wrong.
*
* @author Neerav
* @since 8 July 2005
* @var mixed[]
* @access public
*/
var $return_status = array();


/**
* Constructor of GMailer
*
* During the creation of GMailer object, it will perform several tests to see
* if the cURL extension is available or not. However,
* note that the constructor will NOT return false or null even if these tests
* are failed. You will have to check the class property {@link GMailer::$created} to see if
* the object "created" is really, uh, created (i.e. working), and property
* {@link GMailer::$return_status} or method {@link GMailer::lastActionStatus()} to see what was going wrong.
*
* Example:
* <code>
* <?php
* $gmailer = new GMailer();
* if (!$gmailer->created) {
* echo "Error message: ".$gmailer->lastActionStatus("message");
* } else {
* // Do something with $gmailer
* }
* ? >
* </code>
*
* A typical usage of GMailer object would be like this:
* <code>
* <?php
* require_once("libgmailer.php");
*
* $gmailer = new GMailer();
* if ($gmailer->created) {
* $gmailer->setLoginInfo($gmail_acc, $gmail_pwd, $my_timezone);
* $gmailer->setProxy("proxy.company.com");
* if ($gmailer->connect()) {
* // GMailer connected to Gmail successfully.
* // Do something with it.
* } else {
* die("Fail to connect because: ".$gmailer->lastActionStatus());
* }
* } else {
* die("Failed to create GMailer because: ".$gmailer->lastActionStatus());
* }
* ? >
* </code>
*
* @see GMailer::$created, GMailer::$return_status, GMailer::lastActionStatus()
* @return GMailer
*/
function GMailer() {
// GMailer needs "curl" extension to work
$this->created = true;
if (!extension_loaded('curl')) {
// Added to gracefully handle multithreaded servers; by Neerav; 8 July 2005
if (isset($_ENV["NUMBER_OF_PROCESSORS"]) and ($_ENV["NUMBER_OF_PROCESSORS"] > 1)) {
$this->created = false;
$a = array(
"action" => "constructing GMailer object",
"status" => "failed",
"message" => "libgmailer: Using a multithread server. Ensure php_curl.dll has been enabled (uncommented) in your php.ini."
);
array_unshift($this->return_status, $a);

} else {
if (!dl('php_curl.dll') && !dl('curl.so')) {
$this->created = false;
$a = array(
"action" => "constructing GMailer object",
"status" => "failed",
"message" => "libgmailer: unable to load curl extension."
);
array_unshift($this->return_status, $a);
}
}
}
if (!function_exists("curl_setopt")) {
$this->created = false;
$a = array(
"action" => "constructing GMailer object",
"status" => "failed",
"message" => "libgmailer: No curl."
);
array_unshift($this->return_status, $a);
}

$this->login = 0;
$this->pwd = 0;
$this->domain = ""; // blank for @gmail.com and @googlemail.com
$this->proxy_host = "";
$this->proxy_auth = "";
$this->use_session = 2;

if ($this->created == true) {
$a = array(
"action" => "constructing GMailer object",
"status" => "success",
"message" => "libgmailer: Constructing completed."
);
array_unshift($this->return_status, $a);
}
}

/**
* Set Gmail's login information.
*
* @return void
* @param string $my_login Gmail's login name (without @gmail.com)
* @param string $my_pwd Password
* @param float $my_tz Timezone with respect to GMT, but in decimal. For example, -2.5 for -02:30GMT
*/
function setLoginInfo($my_login, $my_pwd, $my_tz) {
$this->login = $my_login;
$this->pwd = $my_pwd;
$this->timezone = strval($my_tz*-60);

// Added return_status; by Neerav; 16 July 2005
$a = array(
"action" => "set login info",
"status" => "success",
"message" => "libgmailer: LoginInfo set."
);
array_unshift($this->return_status, $a);
}

/**
* Set domain information if the account is on a hosted domain.
*
* @return void
* @param string $my_domain Hosted domain name (e.g., mydomain.org or sayni.net)
*/
function setDomain($my_domain) {
//return;
$my_domain = strtolower(trim($my_domain));
if ($my_domain === "") {
$a = array(
"action" => "set hosted domain info",
"status" => "sucess",
"message" => "libgmailer: Using the default gmail/googlemail domain."
);
array_unshift($this->return_status, $a);
return;
}
$success = true;
if (preg_match("/gmail\.com|googlemail\.com/i",$my_domain)) {
$a = array(
"action" => "set hosted domain info",
"status" => "failed",
"message" => "libgmailer: cannot use \"$my_domain\" as a hosted domain. The default gmail.com or googlemail.com will be used."
);
array_unshift($this->return_status, $a);
return;
}
$this->domain = $my_domain;
/* $this->GM_LNK_GMAIL = "https://mail.google.com/hosted/".$my_domain; */
/* $this->GM_LNK_GMAIL_HTTP = "http://mail.google.com/hosted/".$my_domain; */
/* $this->GM_LNK_LOGIN = "https://www.google.com/hosted/".$my_dom ... oginAction"; */
/* $this->GM_LNK_LOGIN_REFER = "https://www.google.com/hosted/".$my_dom ... mplcache=2"; */
// GFYD urls changed to GAFYD; Neerav; 1 Sept 2006
$this->GM_LNK_GMAIL = "https://mail.google.com/hosted/".$my_domain;
$this->GM_LNK_GMAIL_HTTP = "http://mail.google.com/hosted/".$my_domain;
$this->GM_LNK_LOGIN = "https://www.google.com/a/".$my_domain."/LoginAction";
$this->GM_LNK_LOGIN_REFER = "https://www.google.com/a/".$my_domain." ... mplcache=2";
$this->GM_LNK_INVITE_REFER = "";

$a = array(
"action" => "set hosted domain info",
"status" => "success",
"message" => "libgmailer: Domain set."
);
array_unshift($this->return_status, $a);
}

/**
* Setting proxy server.
*
* Example:
* <code>
* <?php
* // proxy server requiring login
* $gmailer->setProxy("proxy.company.com", "my_name", "my_pwd");
*
* // proxy server without login
* $gmailer->setProxy("proxy2.company.com", "", "");
* ? >
* </code>
*
* @return void
* @param string $host Proxy server's hostname
* @param string $username User name if login is required
* @param string $pwd Password if required
*/
function setProxy($host, $username, $pwd) {
if (strlen($this->proxy_host) > 0) {
$this->proxy_host = $host;
if (strlen($username) > 0 || strlen($pwd) > 0) {
$this->proxy_auth = $username.":".$pwd;
}
$a = array(
"action" => "set proxy",
"status" => "success",
"message" => "libgmailer: Proxy set."
);
array_unshift($this->return_status, $a);
} else {
$a = array(
"action" => "set proxy",
"status" => "failed",
"message" => "libgmailer: no hostname supplied."
);
array_unshift($this->return_status, $a);
}
}

/**
* Setting session management method.
*
* You have to select a session management method so that GMailer would "remember"
* your identity. Method has to be one of the following values:
* 1. {@link GM_USE_COOKIE} | !{@link GM_USE_PHPSESSION} (if your server does not have PHP Session installed)
* 2. !{@link GM_USE_COOKIE} | {@link GM_USE_PHPSESSION} (if your server have PHP Session installed, and don't want to set browser's cookie)
* 3. {@link GM_USE_COOKIE} | {@link GM_USE_PHPSESSION} (if your server have PHP Session installed, and would like to use cookie to store session)
*
* @return void
* @param int $method
*/
function setSessionMethod($method) {
if ($method & GM_USE_PHPSESSION) {
if (!extension_loaded('session')) {
// Added to gracefully handle multithreaded servers; by Neerav; 8 July 2005
if (isset($_ENV["NUMBER_OF_PROCESSORS"]) and ($_ENV["NUMBER_OF_PROCESSORS"] > 1)) {
$this->setSessionMethod(GM_USE_COOKIE | !GM_USE_PHPSESSION); // forced to use custom cookie
$a = array(
"action" => "load PHP session extension",
"status" => "failed",
"message" => "Using a multithread server. Ensure php_session.dll has been enabled (uncommented) in your php.ini."
);
array_unshift($this->return_status, $a);
return;
} else {
// Changed extension loading; by Neerav; 18 Aug 2005
//if (!dl('php_session.dll') && !dl('session.so')) {
if (dl(((PHP_SHLIB_SUFFIX == 'dll') ? 'php_' : '') . 'session.' . PHP_SHLIB_SUFFIX)) {
$a = array(
"action" => "load PHP session extension",
"status" => "failed",
"message" => "unable to load PHP session extension."
);
array_unshift($this->return_status, $a);
$this->setSessionMethod(GM_USE_COOKIE | !GM_USE_PHPSESSION); // forced to use custom cookie
return;
}
}
}
if (!($method & GM_USE_COOKIE)) {
@ini_set("session.use_cookies", 0);
@ini_set("session.use_trans_sid", 1);
$a = array(
"action" => "session",
"status" => "success",
"message" => "no using cookie"
);
array_unshift($this->return_status, $a);
} else {
@ini_set("session.use_cookies", 1);
@ini_set("session.use_trans_sid", 0);
$a = array(
"action" => "session",
"status" => "success",
"message" => "using cookie"
);
array_unshift($this->return_status, $a);
}
@ini_set("arg_separator.output", '&');
session_start();
$a = array(
"action" => "session",
"status" => "success",
"message" => "using PHP session"
);
array_unshift($this->return_status, $a);
$this->use_session = true;
} else {
//@ini_set("session.use_only_cookies", 1);
@ini_set("session.use_cookies", 1);
@ini_set("session.use_trans_sid", 0);
$a = array(
"action" => "session",
"status" => "success",
"message" => "using cookie"
);
array_unshift($this->return_status, $a);
$this->use_session = false;
}
}

/**
* @return binary image
* @desc
*/
/* function retrieveCaptcha($login, $logintoken) { */
/* Debugger::say("retLogin: ".$login); */
/* Debugger::say("retToken: ".$logintoken); */
/* */
/* $login = str_replace("@gmail.com",$login); */
/* $c = curl_init(); */
/* */
/* curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); */
/* curl_setopt($c, CURLOPT_BINARYTRANSFER, 1); */
/* curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1); */
/* curl_setopt($c, CURLOPT_URL, "https://www.google.com/accounts/Captcha ... @gmail.com"); */
/* curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 2); */
/* curl_setopt($c, CURLOPT_USERAGENT, GM_USER_AGENT); */
/* // curl_setopt($c, CURLOPT_COOKIE, $this->cookie_str); */
/* $this->CURL_PROXY($c); */
/* // curl_setopt($c, CURLOPT_HEADER, 1); */
/* curl_setopt($c, CURLOPT_SSL_VERIFYPEER, FALSE); */
/* curl_setopt($c, CURLOPT_REFERER, $this->GM_LNK_LOGIN); */
/* $this->gmail_data = curl_exec($c); */
/* curl_close($c); */
/* */
/* return $this->gmail_data; */
/* //return 1; */
/* } */

/**
* Connect to Gmail without setting any session/cookie
*
* @return bool Connect to Gmail successfully or not
*/
function connectNoCookie() {
$postdata = "";
if ($this->domain) {
$postdata .= "&at=null";
$postdata .= "&continue=".urlencode($this->GM_LNK_GMAIL);
$postdata .= "&service=mail";
$postdata .= "&userName=".urlencode($this->login);
$postdata .= "&password=".urlencode($this->pwd);
} else {
// pre 31 Aug 2006
/* $postdata .= "service=mail"; */
/* $postdata .= "&Email=".urlencode($this->login); */
/* $postdata .= "&Passwd=".urlencode($this->pwd); */
/* $postdata .= "&null=Sign%20in"; */
/* $postdata .= "&continue=".urlencode($this->GM_LNK_GMAIL); */
/* // Added by Neerav; 28 June 2005 */
/* $postdata .= "&rm=false"; // not required but appears */
/* $postdata .= "&hl=en"; */
// "fixed"?!?; by Neerav; 1 Sept 2006
$postdata .= "&ltmpl=yj_blanco";
$postdata .= "&ltmplcache=2";
$postdata .= "&continue=".urlencode($this->GM_LNK_GMAIL);
$postdata .= "&service=mail";
$postdata .= "&rm=false";
$postdata .= "&ltmpl=yj_blanco";
$postdata .= "&hl=en";
$postdata .= "&Email=".urlencode($this->login);
$postdata .= "&Passwd=".urlencode($this->pwd);
$postdata .= "&rmShown=1";
$postdata .= "&null=Sign+in";

}

/* Debugger::say(print_r($this->pwd,true)); */
/* Debugger::say(print_r(urlencode($this->pwd),true)); */
/* Debugger::say(print_r(urlencode(urldecode($this->pwd)),true)); */
/* Debugger::say(print_r($postdata,true)); */
/* exit; */

// Check for valid hosted domains; Added by Neerav; 10 June 2006
if ($this->domain) {
if (preg_match("/(^yahoo\.)|(^hotmail\.)|(^msn\.com$)|(^gala\.net$)|(^mail\.com$)|(^sayni\.net$)|(^gmail\.com$)|(^googlemail\.com$)/i",$this->domain)) {
$a = array(
"action" => "sign in",
"status" => "failed",
"message" => $this->domain." cannot be used as a 'Gmail for your domain' (hosted) domain.",
"login_error" => "invalid_domain"
);
array_unshift($this->return_status, $a);
return false;
}

// Domain test
$this->gmail_data = GMailer::execute_curl(
$this->GM_LNK_LOGIN_REFER,
"",
'get', "",
'nocookie', "",
false, // update cookie
true // follow
);

///Debugger::say("check for valid GFYD: ".print_r($this->gmail_data,true));
///exit;

if (
strpos($this->gmail_data,"<p>Domain does not exist</p>") > 0
or
strpos($this->gmail_data,"Gmail for your domain - Server error") > 0
) {

$a = array(
"action" => "sign in",
"status" => "failed",
"message" => "Gmail for your domain - Server error -- Domain does not exist",
"login_error" => "domain_nonexist"
);
array_unshift($this->return_status, $a);
return false;
}
}

// Added by Neerav; 8 July 2005
// login challenge
//id="logintoken" value="cpVIYkaTDTkVZ9ZHNM_384GVV79tjExj-ac2NFVgS3AVbm7lEn7Q967JHKe_sDzMP7plluysBDJRyUwkjuHQFw:D0cwussDwRyIgJGSdeMMnA" name="logintoken">
if (isset($this->logintoken) and $this->logintoken != "") $postdata .= "&logintoken=".$logintoken;
if (isset($this->logincaptcha) and $this->logincaptcha != "") $postdata .= "&logincaptcha=".$logincaptcha;

// just for testing
/* $this->gmail_data = GMailer::execute_curl( */
/* "https://www.google.com/accounts/Service ... mplcache=2", */
/* "", */
/* 'get', */
/* "", */
/* 'nocookie', "",true,false */
/* ); */
/* Debugger::say("temp: ".print_r($this->gmail_data,true)); */
/* $cookies = GMailer::get_cookies($this->gmail_data); */
/* Debugger::say("cookies: $cookies"); */
/* exit; */

// The GMAIL_LOGIN cookie is now required since 31 Aug 2006; by Neerav; 1 Sept 2006
$time = time();
// we fake that the user loaded the browser 8-20 seconds ago
$time_past = $time - rand(8,20);
// create the cookie
$cookie = "GMAIL_LOGIN=T$time_past/$time_past/$time";

// added in case it's needed in the future; Neerav; 1 Sept 2006
/* if ($this->domain) { */
/* // Gmail's "user ping" */
/* // pre first phase, sending word that this user is about to sign in. */
/* $this->gmail_data = GMailer::execute_curl( */
/* $this->GM_LNK_GMAIL."?gxlu=".urlencode($this->login)."&zx=".(time()-rand(2,6)).rand(100,999), */
/* (($this->domain) ? $this->GM_LNK_LOGIN : $this->GM_LNK_LOGIN_REFER), */
/* 'get', */
/* "", */
/* 'cookie', "GMAIL_LOGIN=T$time_past/$time_past/$time" */
/* ); */
/* Debugger::say("pre first phase: ".print_r($this->gmail_data,true)); */
/* } */

$this->gmail_data = GMailer::execute_curl(
$this->GM_LNK_LOGIN,
(($this->domain) ? $this->GM_LNK_LOGIN : $this->GM_LNK_LOGIN_REFER),
'post',
$postdata,
// changed to use the required time cookie; by Neerav; 1 Sept 2006
//'nocookie', ""
(($this->domain) ? 'nocookie': 'cookie'), (($this->domain) ? '' : "$cookie")
);

/* Debugger::say("first phase: ".print_r($this->gmail_data,true)); */
/* exit; */

$a = array(
"action" => "connecting to Gmail (without cookie)",
"status" => (($this->gmail_data != "") ? "success" : "failed"),
"message" => (($this->gmail_data != "") ? "connected to Gmail (without cookie)" : "no response"),
"login_error" => (($this->gmail_data != "") ? "" : "no response")
);
array_unshift($this->return_status, $a);
if ($this->gmail_data == "") return false;

/** from here we have to perform "cookie-handshaking"... **/
$cookies = GMailer::get_cookies($this->gmail_data);
///Debugger::say("first phase cookies: ".print_r($cookies,true));
///print_r($cookies);
///exit;

$this->logintoken = "";
$this->logincaptcha = "";

// updated if condition for hosted domains; by Neerav; 8 June 2006
if ((
strpos($this->gmail_data, "errormsg_0_Passwd") > 0
or
strpos($this->gmail_data, "errormsg_0_password") > 0
) and
strpos($this->gmail_data, "Username and password do not match") > 0
){

$this->cookie_str = "";
$this->cookie_ik_str = "";

// Added appropriate error message; by Neerav; 8 July 2005
// Added error message for suggested username; by Neerav; 28 July 2006
if (preg_match("/Did you mean(.*?)\?\)/i",$this->gmail_data,$userpass_match)) {
$suggest = trim($userpass_match[1]);
$a = array(
"action" => "sign in",
"status" => "failed",
"message" => "Username and password do not match. (Did you mean ".$suggest." ?)",
"login_error" => "userpass_suggest",
"login_suggest" => $suggest
);
} else {
$a = array(
"action" => "sign in",
"status" => "failed",
"message" => "Username and password do not match. (You provided ".$this->login.")",
"login_error" => "userpass"
);
}
array_unshift($this->return_status, $a);
return false;

// Blank username or password; Added by Neerav; 8 June 2006
} elseif (
(
strpos($this->gmail_data, "errormsg_0_password") > 0
or
strpos($this->gmail_data, "errormsg_0_userName") > 0
or
strpos($this->gmail_data, "errormsg_0_username") > 0
) and
strpos($this->gmail_data, "Required field must not be blank") > 0
) {
$this->cookie_str = "";
$this->cookie_ik_str = "";
$a = array(
"action" => "sign in",
"status" => "failed",
"message" => "Required field must not be blank",
"login_error" => "blank"
);
array_unshift($this->return_status, $a);
return false;

// Added to support login challenge; by Neerav; 8 July 2005
} elseif (strpos($this->gmail_data, "errormsg_0_logincaptcha") > 0) {
$this->cookie_str = "";
$this->cookie_ik_str = "";
//id="logintoken" value="cpVIYkaTDTkVZ9ZHNM_384GVV79tjExj-ac2NFVgS3AVbm7lEn7Q967JHKe_sDzMP7plluysBDJRyUwkjuHQFw:D0cwussDwRyIgJGSdeMMnA" name="logintoken">
ereg("id=\"logintoken\" value=\"([^\"]*)\" name=\"logintoken\"", $this->gmail_data, $matches);
//Debugger::say("Connect FAILED: login challenge: ".$this->gmail_data);
//Debugger::say("ErrorLogin: ".$this->login);
//Debugger::say("ErrorToken: ".$matches[1]);
//Debugger::say("logintoken: ".print_r($matches,true));
// Added appropriate error message; by Neerav; 8 July 2005
$a = array(
"action" => "sign in",
"status" => "failed",
"message" => "login challenge",
"login_token" => $matches[1],
//"login_token_img" => urlencode("Captcha?ctoken=".$matches[1]."&email=".$this->login."%40gmail.com"),
//"login_token_img" => $login_img,
//"login_cookie" => $login_cookie,
"login_error" => "challenge"

);
array_unshift($this->return_status, $a);
return false;

// Check if the Gmail URL has changed; Added by Neerav; 14 Sept 2005
} elseif (strpos($this->gmail_data, "Invalid request.")) {
$this->cookie_str = "";
$this->cookie_ik_str = "";

$a = array(
"action" => "sign in",
"status" => "failed",
"message" => "Gmail: Invalid request. (libgmailer: Gmail seems to have changed the URL again.)",
"login_error" => "URL"
);
array_unshift($this->return_status, $a);
return false;

// Check for a cookie as a way to check the Gmail URL; Added by Neerav; 14 Sept 2005
} elseif ($cookies == "") {
$this->cookie_str = "";
$this->cookie_ik_str = "";

$a = array(
"action" => "sign in",
"status" => "failed",
"message" => "libgmailer: Phase one cookie not obtained. Gmail may be down.",
"login_error" => "cookie"
);
array_unshift($this->return_status, $a);
return false;

}

$a = array(
"action" => "phase one cookie",
"status" => "success",
"message" => "Received: ".$cookies
);
array_unshift($this->return_status, $a);

// Phase for hosted domains
if (strpos($cookies, "HID=") !== false) {
$preg = preg_match("/HID=([^ ;]*)/",$cookies,$hosted_auth);

$a = array(
"action" => "phase 'hosted domain'",
"status" => "status",
"message" => "Redirect: to ".$this->GM_LNK_GMAIL_HTTP."?auth=[deleted]"
);
array_unshift($this->return_status, $a);

///Debugger::say("hosted phase auth: ".print_r($hosted_auth,true));
///print_r("hosted phase auth: ".print_r($hosted_auth,true));
//exit;

// execute hosted domain phase of signin
$this->gmail_data = GMailer::execute_curl(
$this->GM_LNK_GMAIL.'?auth='.$hosted_auth[1],
"", // no referrer
'get', "",
"cookie", $cookies,
true,
false // do not follow location
);

// hosted phase cookies
//$data = GMailer::get_cookies($this->gmail_data);
///Debugger::say("hosted phase: ".print_r($this->gmail_data,true));
///Debugger::say("hosted phase cookies: ".print_r($data,true));
//exit;

// status
$a = array(
"action" => "phase 'hosted domain'",
"status" => "status",
"message" => "done"
);
array_unshift($this->return_status, $a);
}

// Forward url is now absolute instead of relative; Fixed by Gan; 27 July 2005
$a = strpos($this->gmail_data, "Location: ");
$b = strpos($this->gmail_data, "\n", $a);
$forward = substr($this->gmail_data, $a+10, $b-($a+10));

$a = array(
"action" => "redirecting",
"status" => "success",
"message" => "Redirecting to: ".$forward
);
array_unshift($this->return_status, $a);
///Debugger::say("Redirecting to: ".$forward);

// Added extra required cookie; by Neerav; 4 Apr 2006
$second = GMailer::execute_curl(
$forward,
$this->GM_LNK_LOGIN_REFER,
'get', "",
"cookie", "GoogleAccountsLocale_session=en; ".$cookies
);

$data = GMailer::get_cookies($second);
///Debugger::say("second phase: ".print_r($second,true));
///Debugger::say("second phase cookies: ".print_r($data,true));

$a = array(
"action" => "phase two cookie",
"status" => "success",
"message" => "Obtained: ".$data
);
array_unshift($this->return_status, $a);

/* $this->cookie_str = $cookies.";".$d; // the cookie string obtained from gmail */

// Third phase required for some accounts. Added by Neerav; April 2006
if (strpos($second, "SetSID") !== false) {
$forward = preg_match("/<meta content=\"0;\s*url='?([^\"\']*)'?\"/",$second,$matches);
$a = array(
"action" => "phase three required",
"status" => "status",
"message" => "Redirect: ".str_replace("&","&",$matches[1])
);
array_unshift($this->return_status, $a);

///print_r($forward."<br />\n");
///print_r($matches);

// execute third phase of signin
$third = GMailer::execute_curl(
str_replace("&","&",$matches[1]),
"", // no referrer
'get', "",
"nocookie", "");
// third phase cookies
$data = GMailer::get_cookies($third);
///Debugger::say("third phase: ".print_r($third,true));
///Debugger::say("third phase cookies: ".print_r($data,true));

// status
$a = array(
"action" => "phase three cookie",
"status" => "success",
"message" => "Obtained: ".$data
);
array_unshift($this->return_status, $a);
}

$data = (($data) ? $data : $cookies)."; TZ=".$this->timezone;
///Debugger::say("cookies (pre-clean): ".print_r($data,true));

// remove duplicate cookies
$data = preg_replace("/GX=.*?;\s?GX=/","GX=",$data);
// remove unnecessary LSID, if it still exists.
$data = trim(preg_replace("/LSID=mail[^;]*?;/","",$data));
///Debugger::say("final cookies (corrected/cleaned): ".print_r($data,true));

$this->cookie_str = $data;

$a = array(
"action" => "final gmail cookie",
"status" => "status",
"message" => "Cookie: ".$data
);
array_unshift($this->return_status, $a);

return true;

}

/**
* Connect to GMail with default session management settings.
*
* @return bool Connect to Gmail successfully or not
*/
function connect() {
if ($this->use_session === 2)
$this->setSessionMethod(GM_USE_COOKIE | GM_USE_PHPSESSION); // by default

// already logged in
if ($this->login == 0 && $this->pwd == 0) {
if (!$this->getSessionFromBrowser()) {
return $this->connectNoCookie() && $this->saveSessionToBrowser();
} else {
$a = array(
"action" => "connect",
"status" => "success",
"message" => "Connect completed by getting cookie/session from browser/server."
);
array_unshift($this->return_status, $a);
return true;
}

// log in
} else {
// Changed to support login challenge; by Neerav; 8 July 2005
//return $this->connectNoCookie() && $this->saveSessionToBrowser();
if ($this->connectNoCookie()) {
return $this->saveSessionToBrowser();
} else {
return false;
}
}
}

/**
* See if it is connected to GMail.
*
* @return bool
*/
function isConnected() {
return (strlen($this->cookie_str) > 0);
}

/**
* Last action's action, status, message, and other info
*
* @param string $request What information you would like to request. Default is "message".
* @return string
*/
function lastActionStatus($request = "message") {
if ($request == "message") {
return preg_replace("/(\s|&nbsp;)*<(a|span)[^>]*[^<]*<\/(a|span)>/","",$this->return_status[0]["$request"]);
} else {
return $this->return_status[0]["$request"];
}
}

/**
* Append a random string to url to fool proxy
*
* @param string $type Set to "nodash" if you do not want a dash ("-") in random string. Otherwise just leave it blank.
* @access private
* @return string Complete URL
* @author Neerav
* @since June 2005
*/
function proxy_defeat($type = "") {
$length = 12;
$seeds = 'abcdefghijklmnopqrstuvwxyz0123456789';
$string = '';
$seeds_count = strlen($seeds);

// Generate
// Changed to also use without dash; by Neerav; 11 Aug 2005
if ($type == "nodash") {
for ($i = 0; $length > $i; $i++) {
$string .= $seeds{mt_rand(0, $seeds_count - 1)};
}
} else {
for ($i = 0; $length > $i; $i++) {
$string .= $seeds{mt_rand(0, $seeds_count - 1)};
if ($i == 5) $string .= "-"; // Added by Neerav; 28 June 2005
}
}

return "&zx=".$string;
}

/**
* Fetch contents by URL query.
*
* This is a "low-level" method. Please use {@link GMailer::fetchBox()} for fetching standard contents.
*
* @param string $query URL query string
* @return bool Success or not
*/
function fetch($query) {
if ($this->isConnected() == true) {
Debugger::say("Start fetching query: ".$query);
$query .= $this->proxy_defeat(); // to fool proxy

$this->gmail_data = GMailer::execute_curl(
$this->GM_LNK_GMAIL."?".$query,
GM_LNK_REFER,
'get'
);
GMailer::parse_gmail_response($this->gmail_data);

Debugger::say("Fetch completed.");
return 1;

} else { // not logged in yet
Debugger::say("Fetch FAILED: not connected.");
return 0;

}
}

/**
* Fetch contents from Gmail by type.
*
* Content can be one of the following categories:
* 1. {@link GM_STANDARD}: For standard mail-boxes like Inbox, Sent Mail, All, etc. In such case, $box should be the name of the mail-box: "inbox", "all", "sent", "draft", "spam", or "trash". $paramter would be used for paged results.
* 2. {@link GM_LABEL}: For user-defined label. In such case, $box should be the name of the label.
* 3. {@link GM_CONVERSATION}: For conversation. In such case, $box should be the conversation ID and $parameter should be the mailbox/label in which the message is found (if supplied 0, it will default to "inbox").
* 4. {@link GM_QUERY}: For search query. In such case, $box should be the query string.
* 5. {@link GM_PREFERENCE}: For Gmail preference. In such case, $box = "".
* 6. {@link GM_CONTACT}: For contact list. In such case, $box can be either "all", "search", "detail", "group", or "group detail". When $box = "detail", $parameter is the Contact ID. When $box = "search", $parameter is the search query string.
*
* @return bool Success or not
* @param constant $type Content category
* @param mixed $box Content type
* @param int $parameter Extra parameter. See above.
* @see GM_STANDARD, GM_LABEL, GM_CONVERSATION, GM_QUERY, GM_PREFERENCE, GM_CONTACT
*/
function fetchBox($type, $box, $parameter) {
if ($this->isConnected() == true) {
switch ($type) {
case GM_STANDARD:
$q = "search=".strtolower($box)."&view=tl&start=".$parameter;
break;
case GM_LABEL:
$q = "search=cat&cat=".$box."&view=tl&start=".$parameter;
break;
case GM_CONVERSATION:
if ($parameter === 0 or $parameter == "") $parameter = "inbox";
if (in_array(strtolower($parameter),$this->gmail_reserved_names)) {
$q = "search=".urlencode($parameter)."&ser=1&view=cv";
} else {
$q = "search=cat&cat=".urlencode($parameter)."&ser=1&view=cv";
}
if (is_array($box)) {
$q .= "&th=".$box[0];
for ($i = 1; $i < count($box); $i++)
$q .= "&msgs=".$box[$i];
} else {
$q .= "&th=".$box;
}
break;
case GM_QUERY:
$q = "search=query&q=".urlencode($box)."&view=tl&start=".$parameter;
break;
case GM_PREFERENCE:
$q = "view=pr&pnl=g";
break;
case GM_CONTACT:
if (strtolower($box) == "all")
$q = "view=cl&search=contacts&pnl=a";
elseif (strtolower($box) == "search") // Added by Neerav; 15 June 2005
$q = "view=cl&search=contacts&pnl=s&q=".urlencode($parameter);
elseif (strtolower($box) == "detail") // Added by Neerav; 1 July 2005
$q = "search=contacts&ct_id=".$parameter."&cvm=2&view=ct".$this->proxy_defeat();
elseif (strtolower($box) == "group_detail") // Added by Neerav; 6 Jan 2006
$q = "search=contacts&ct_id=".$parameter."&cvm=1&view=ctl".$this->proxy_defeat();
elseif (strtolower($box) == "group")
$q = "view=cl&search=contacts&pnl=l";
else // frequently mailed
$q = "view=cl&search=contacts&pnl=p";
break;
default:
$q = "search=inbox&view=tl&start=0&init=1";
break;
}
$this->fetch($q);
return true;
} else {
return false;
}
}

/**
* Save all attaching files of conversations to a path.
*
* Random number will be appended to the new filename if the file already exists.
*
* @return string[] Name of the files saved. False if failed.
* @param string[] $convs Conversations.
* @param string $path Local path.
*/
function getAttachmentsOf($convs, $path) {
if ($this->isConnected() == true) {
if (!is_array($convs)) {
$convs = array($convs); // array wrapper
}
$final = array();
foreach ($convs as $v) {
if (count($v["attachment"]) > 0) {
foreach ($v["attachment"] as $vv) {
$f = $path."/".$vv["filename"];
while (file_exists($f)) {
$f = $path."/".$vv["filename"].".".round(rand(0,1999));
}
if ($this->getAttachment($vv["id"],$v["id"],$f,false)) {
array_push($final, $f);
}
}
}
}
return $final;
} else {
return false;
}
}

/**
* Save attachment with attachment ID $attach_id and message ID $msg_id to file with name $filename.
*
* @return bool Success or not.
* @param string $attach_id Attachment ID.
* @param string $msg_id Message ID.
* @param string $filename File name.
* @param bool $action {zip = Save all attachments into a zip file; thumb = retrieve picture thumbnail; convert = view html converted form of doc/pdf/xls/rtf/ppt}.
* @param bool $thumbnail download the attachment's thumbnail.
*/
function getAttachment($attach_id, $msg_id, $filename, $action = "") {
if ($this->isConnected() == true) {
Debugger::say("Start getting attachment...");

if ($action == "thumb") {
// view thumbnail; Added by Neerav; 22 Aug 2006
$query = $this->GM_LNK_GMAIL."?view=att&disp=thd&attid=".urlencode($attach_id)."&th=".urlencode($msg_id);
} elseif ($action == "zip") {
// all attachments zipped
$query = $this->GM_LNK_GMAIL."?view=att&disp=zip&th=".urlencode($msg_id);
} elseif ($action == "convert") {
// pdf, rtf, xls, doc, ppt converted into html
// ** using Gmail Mobile to retrieve this **
$query = "x/".str_replace("&zx=","",$this->proxy_defeat("nodash"))."-/?disp=vah&attid=".urlencode($attach_id)."&th=".urlencode($msg_id)."&v=att";
$this->gmail_data = GMailer::execute_curl(
$this->GM_LNK_GMAIL_HTTP.$query,
/* $this->GM_LNK_GMAIL_HTTP."x/".str_replace("&zx=","",$this->proxy_defeat("nodash"))."-/?mi=0&th=".urlencode($msg_id)."&v=att", */
"",//$this->GM_LNK_GMAIL_HTTP."x/".$this->proxy_defeat("nodash")."-/?v=cmf",
'get',"",
"noheader"
);
//Debugger::say(print_r($this->gmail_data,true));
if (strpos($this->gmail_data,'gmail_error=') !== false) {
preg_match("/gmail_error=(\d+);/",$this->gmail_data,$error_num);
$error = (isset($error_num[1])) ? $error_num[1] : "" ;
if ( $error != 25 //
and $error != 15 // attachment cannot be viewed, e.g. trying to convert a jpeg into html!
and $error != 58 // server error (what's the real reason?)
and $error != 7 // attachment doesn't exist (gmail gives "server error")
) {
Debugger::say(print_r($this->gmail_data,true),"error_log.glib.as_html.php");
}

// tries to regex the error message from Gmail's response
if ($error == 58 or $error == 7) {
preg_match("@<p>(.*?)</p>@is",$this->gmail_data,$match_error);
} else {
preg_match('@<p><font size="-1">(.*?)</font></p>@is',$this->gmail_data,$match_error);
}

if (isset($match_error[1]) and trim($match_error[1]) != "") {
$message = trim($match_error[1]);
} else {
Debugger::say("The error message did not match the regex: \n".print_r($this->gmail_data,true),"error_log.glib.as_html.php");
$message = "Gmail reported an unknown error.<br/><br/><b>DO NOT REPEAT OR RELOAD.</b>";
}

$a = array(
"action" => "view as html",
"status" => "failed",
"message" => "<p>$message</p>",
"error" => $error
);
array_unshift($this->return_status, $a);
return false;
}
preg_match("/<body>(.*)<\/body>/",$this->gmail_data,$match);
//Debugger::say(print_r($match[1],true));
$a = array(
"action" => "view as html",
"status" => "success",
"message" => "attachment converted to html and received",
"error" => 0,
"as_html" => $match[1]
);
array_unshift($this->return_status, $a);
return true;
} else {
// download attachment
$query = $this->GM_LNK_GMAIL."?view=att&disp=attd&attid=".urlencode($attach_id)."&th=".urlencode($msg_id);
}

// view all images
/* $query = $this->GM_LNK_GMAIL."?view=att&disp=imgs&th=".urlencode($msg_id); */
// view image inline
/* $query = $this->GM_LNK_GMAIL."?view=att&disp=inline&attid=".urlencode($attach_id)."&th=".urlencode($msg_id); */


$fp = fopen($filename, "wb");
if ($fp) {
$c = curl_init();
curl_setopt($c, CURLOPT_FILE, $fp);
curl_setopt($c, CURLOPT_COOKIE, $this->cookie_str);
curl_setopt($c, CURLOPT_URL, $query);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
$this->CURL_PROXY($c);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($c, CURLOPT_USERAGENT, GM_USER_AGENT);
curl_setopt($c, CURLOPT_REFERER, GM_LNK_REFER);
curl_exec($c);
curl_close($c);
fclose($fp);
} else {
Debugger::say("FAILED to get attachment: cannot fopen the file.");
return false;
}
Debugger::say("Completed getting attachment.");
return true;
} else {
Debugger::say("FAILED to get attachment: not connected.");
return false;
}
}

/**
* Dump everything to output.
*
* This is a "low-level" method. Use the method {@link GMailer::fetchBox()} to fetch standard contents from Gmail.
*
* @return string Everything received from Gmail.
* @param string $query URL query string.
*/
function dump($query) {
if ($this->isConnected() == true) {
Debugger::say("Dumping...");
$query .= $this->proxy_defeat(); // to fool proxy
$this->gmail_data = GMailer::execute_curl(
$this->GM_LNK_GMAIL."?".$query,
GM_LNK_REFER,
'get', "", "noheader", ""
);
Debugger::say("Finished dumping ".strlen($this->gmail_data)." bytes.");
return $this->gmail_data;
} else { // not logged in yet
Debugger::say("FAILED to dump: not connected.");
return "";
}
}

/**
* Send Gmail. Or save a draft email.
*
* Examples:
* <code>
* <?php
* // Simplest usage: send a new mail to one person:
* $gmailer->send("who@what.com", "Hello World", "Cool!\r\nFirst mail!");
*
* // More than one recipients. And with CC:
* $gmailer->send("who@what.com, boss@company.com",
* "Hello World",
* "This is second mail.",
* "carbon-copy@company.com");
*
* // With file attachment
* $gmailer->send("who@what.com",
* "Your file",
* "Here you are!",
* "", "", "", "",
* array("path/to/file.zip", "path/to/another/file.tar.gz"));
*
* // more examples...
* ? >
* </code>
*
* @since 9 September 2005
* @return bool Success or not. If returned false, please check {@link GMailer::$return_status} or {@link GMailer::lastActionStatus()} for error message.
* @param string $to Recipient's address. Separated by comma for multiple recipients.
* @param string $subj Subject line of email.
* @param string $body Message body of email.
* @param string $cc Address for carbon-copy (CC). Separated by comma for multiple recipients. $cc = "" for none.
* @param string $bcc Address for blind-carbon-copy (BCC). Separated by comma for multiple recipients. $bcc = "" for none.
* @param string $mid Message ID of the replying email. $mid = "" if this is a newly composed email.
* @param string $tid Conversation (thread) ID of the replying email. $tid = "" if this is a newly composed email.
* @param string[] $files File names of files to be attached.
* @param bool $draft Indicate this email is saved as draft, or not.
* @param string $orig_df If this email is saved as a <i>modified</i> draft, then set $orig_df as the draft ID of the original draft.
* @param bool $is_html HTML/RTF-formatted mail, or not.
* @param array $attachments Attachments (forwards) in the form of 0_messageIDthatContainedTheAttachment_attachmentID (e.g. 0_17ab83d2f68n2b_0.1 , 0_17ab83d2f68n2b_0.2)
* @param string $from Send mail as this email address (personality). $from = "" to use default address in your settings. Note: the "default" behavior changed on 29 April 2006. Note: you will NOT send your mail successfully if you do not register this address in your Gmail settings panel.
*/
function send($to, $subj, $body, $cc="", $bcc="", $mid="", $tid="", $files=0, $draft=false, $orig_df="", $is_html=0, $from="", $attachments = array()) {
if ($this->isConnected()) {
$postdata = array();
if ($draft == true) {
$postdata["view"] = "sd";
$postdata["draft"] = $orig_df;
$postdata["rm"] = $mid;
$postdata["th"] = $tid;
} else {
$postdata["view"] = "sm";
$postdata["draft"] = $orig_df;
$postdata["rm"] = $mid;
$postdata["th"] = $tid;
}

$postdata["at"] = $this->at_value();

// These are in the POST form, but do not know what they are
// or what their values should be
// Send works ok despite these being left out.
/* $postdata["wid"] = 8; */
/* $postdata["jsid"] = xxxxxxxxxx; */
/* $postdata["ov"] = ""; */
//$postdata["cmid"] = 1;

if (strlen($from) > 0) {
$postdata["from"] = $from;
}
$postdata["to"] = stripslashes($to);
$postdata["cc"] = stripslashes($cc);
$postdata["bcc"] = stripslashes($bcc);
$postdata["subject"] = stripslashes($subj);
$postdata["ishtml"] = ($is_html) ? 1 : 0;
$postdata["msgbody"] = stripslashes($body);

// Added attachment/forward support; by Neerav; 22 Oct 2005
// should be POST, but we fake it in GET
$getdata = "";
if (count($attachments) > 0) {
for ($i=0; $i<count($attachments); $i++) {
$getdata .= "&attach=".$attachments[$i];
}
}

$new_attach = 0;
if (is_array($files)) {
// an array of files supplied
$new_attach = count($files);
for ($i = 0; $i < $new_attach; $i++) {
$postdata["file".$i] = "@".realpath($files[$i]);
}
} elseif ($files != 0) {
// only one file attachment supplied
$new_attach = 1;
$postdata["file"] = "@".realpath($files);
}
//echo $postdata;
// Changed to add attachment/forward support ($getdata); by Neerav; 22 Oct 2005
$this->gmail_data = GMailer::execute_curl(
$this->GM_LNK_GMAIL."?&search=inbox&qt=&cmid=&newatt=".$new_attach."&rematt=0".$getdata,
$this->GM_LNK_GMAIL."?&view=cv&search=inbox&th=".$tid/* ."&lvp=4&cvp=1" */."&qt=".$this->proxy_defeat("nodash"),
'post',
$postdata
);
GMailer::parse_gmail_response($this->gmail_data);

// Added by Neerav; 12 July 2005
$status = (isset($this->raw["sr"][2])) ? $this->raw["sr"][2] : false;
$a = array(
"action" => "send email",
// $this->raw["sr"][1] // what is this?? // always 1
"status" => ($status ? "success" : "failed"),
"message" => (isset($this->raw["sr"][3]) ? $this->raw["sr"][3] : ""),
"thread_id" => (isset($this->raw["sr"][4]) ? $this->raw["sr"][4] : ""),
// $this->raw["sr"][5] // what is this?? // always 0
// $this->raw["sr"][6] // what is this?? // always an empty array
// $this->raw["sr"][7] // what is this?? // always 0
// $this->raw["sr"][8] // what is this?? // always 0
// $this->raw["sr"][9] // what is this?? // always 0
// $this->raw["sr"][10] // what is this?? // always blank (or false)
// $this->raw["sr"][11] // what is this?? // some kind of message/server id, but doesn't match any header
// $this->raw["sr"][12] // what is this?? // always 0
"sent_num" => ((isset($this->raw["aa"][1])) ? count($this->raw["aa"][1]) : 0)
);
array_unshift($this->return_status, $a);
// Changed by Neerav; 12 July 2005
return $status;
} else {
// Added by Neerav; 12 July 2005
$a = array(
"action" => "send email",
"status" => "failed",
"message" => "libgmailer: not connected.",
"thread_id" => $tid,
"sent_num" => 0
);
array_unshift($this->return_status, $a);

return false;
}
}

/**
* Perform action on messages.
*
* Examples:
* <code>
* <?php
* // Apply label to $message_id
* $gmailer->performAction(GM_ACT_APPLYLABEL, $message_id, "my_label");
*
* // Star $message_id
* $gmailer->performAction(GM_ACT_STAR, $message_id);
*
* // more examples...
* ? >
* </code>
*
* @return bool Success or not. If returned false, please check {@link GMailer::$return_status} or {@link GMailer::lastActionStatus()} for error message.
Additional return: Gmail returns a full datapack in response
* @param constant $act Action to be performed.
* @param string[] $id Message ID.
* @param string $para Action's parameter:
* 1. {@link GM_ACT_APPLYLABEL}, {@link GM_ACT_REMOVELABEL}: Name of the label.
* @param string[] $mailbox Standard/Label mailbox name. If this left out, actions will only work on messages in the Inbox.
*/
function performAction($act, $id, $para="", $mailbox="") {
// Fixed (un)trash, added delTrashedMsgs action; by Neerav; 27 Feb 2006
/* $this->gmail_data = GMailer::execute_curl( */
/* $this->GM_LNK_GMAIL."?".$link */
/* $this->GM_LNK_GMAIL."?".$referrer, */
/* 'post', */
/* $postdata */
/* ); */
if ($this->isConnected()) {
$postdata = "";
$referrer = GM_LNK_REFER;
$action_codes = array(
"ib", // nothing / placeholder
"ac_", // GM_ACT_APPLYLABEL
"rc_", // GM_ACT_REMOVELABEL
"st", // GM_ACT_STAR
"xst", // GM_ACT_UNSTAR
"sp", // GM_ACT_SPAM
"us", // GM_ACT_UNSPAM
"rd", // GM_ACT_READ
"ur", // GM_ACT_UNREAD
"tr", // GM_ACT_TRASH
"dl", // GM_ACT_DELFOREVER
"rc_^i", // GM_ACT_ARCHIVE
"ib", // GM_ACT_INBOX
"ib", // GM_ACT_UNTRASH
"dd", // GM_ACT_UNDRAFT
"dm", // GM_ACT_TRASHMSG
"dl", // GM_ACT_DELSPAM
"dl", // GM_ACT_DELTRASHED
"rtr", // GM_ACT_UNTRASHMSG
"dt" // GM_ACT_DELTRASHEDMSGS
);

if ($act == GM_ACT_DELFOREVER)
$this->performAction(GM_ACT_TRASH, $id, 0, $mailbox); // trash it before

//$postdata .= "ik=".$this->cookie_ik_str;

$postdata .= "&act=";

$postdata .= (isset($action_codes[$act])) ? $action_codes[$act] : $action_codes[GM_ACT_INBOX];
if ($act == GM_ACT_APPLYLABEL || $act == GM_ACT_REMOVELABEL) {
$postdata .= $para;
}
$postdata .= "&at=".$this->at_value();

if ($act == GM_ACT_TRASHMSG || $act == GM_ACT_UNTRASHMSG) {
$postdata .= "&m=".$id;
} else {
if (is_array($id)) {
foreach ($id as $t) {
$postdata .= "&t=".$t;
}
} else {
$postdata .= "&t=".$id;
}
if ($act != GM_ACT_DELTRASHEDMSGS) {
$postdata .= "&vp=";
$postdata .= "&msq="; // Added by Neerav; 25 Nov 2005
$postdata .= "&ba=false"; // Added by Neerav; 25 Nov 2005
}
}

if ($act == GM_ACT_UNTRASH || $act == GM_ACT_DELFOREVER || $act == GM_ACT_DELTRASHED) {
$query = "&search=trash";
} elseif ($act == GM_ACT_DELSPAM) {
$query = "&search=spam";
} elseif ($mailbox != "") {
switch ($mailbox) {
case "inbox": $box_type = "std"; break;
case "starred": $box_type = "std"; break;
case "sent": $box_type = "std"; break;
case "drafts": $box_type = "std"; break;
case "all": $box_type = "std"; break;
case "spam": $box_type = "std"; break;
case "trash": $box_type = "std"; break;
case "chats": $box_type = "std"; break;
default: $box_type = "label"; break;
}

if ($box_type == "std") {
$query = "&search=".$mailbox;
} else {
$query = "&search=cat&cat=".urlencode($mailbox);
$referrer = $this->GM_LNK_GMAIL."?&search=cat&cat=".urlencode($mailbox)."&view=tl&start=0".$this->proxy_defeat();
}
} else {
$query = "&search=query&q=";
}

if ($act == GM_ACT_TRASHMSG || $act == GM_ACT_UNTRASHMSG || $act == GM_ACT_DELTRASHEDMSGS) {
$this->gmail_data = GMailer::execute_curl(
$this->GM_LNK_GMAIL."?"."&qt=".$query."&view=up".$postdata.$this->proxy_defeat(),
"",
'get'
);
} else {
$this->gmail_data = GMailer::execute_curl(
$this->GM_LNK_GMAIL."?".$query."&view=tl&start=0",
$referrer,
'post',
$postdata
);
}
GMailer::parse_gmail_response($this->gmail_data);

// Added additional return info; by Neerav; 13 July 2005
$status = (isset($this->raw["ar"][1])) ? $this->raw["ar"][1] : 0;
$message = (isset($this->raw["ar"][2])) ? $this->raw["ar"][2] : "";
$a = array(
"action" => "message action",
"status" => (($status) ? "success" : "failed"),
"message" => $message
);
array_unshift($this->return_status, $a);
return $status;
} else {
// Added by Neerav; 12 July 2005
$a = array(
"action" => "message action",
"status" => "failed",
"message" => "libgmailer: not connected"
);
array_unshift($this->return_status, $a);

return false;
}
}

/**
* @return bool Success or not.
* @desc Recover session information.
*/
function getSessionFromBrowser() {
Debugger::say("Start getting session from browser...");

if (!$this->use_session) {
return $this->getCookieFromBrowser();
}
// Changed to support IK; by Neerav; 13 July 2005
// Last modified by Neerav; 14 Aug 2005
if (isset($_SESSION[GM_COOKIE_KEY])) {
$this->cookie_str = base64_decode($_SESSION[GM_COOKIE_KEY]);
Debugger::say("Completed getting session from server: ".$this->cookie_str);

if (isset($_SESSION['id_key'])) {
$this->cookie_ik_str = $_SESSION['id_key'];
Debugger::say("Completed getting ik from server: ".$this->cookie_ik_str);
} else {
Debugger::say("FAILED to read id_key from server.");
}
return true;
} else {
Debugger::say("FAILED to read ".GM_COOKIE_KEY." or ".'id_key'." from server.");
/* Debugger::say("FAILED to read cookie ".GM_COOKIE_KEY." from browser."); */
return false;
}
}

/**
* @return bool Success or not.
* @desc Get cookies from browser.
*/
function getCookieFromBrowser() {
Debugger::say("Start getting cookie from browser...");

if (!isset($_COOKIE)) {
Debugger::say("FAILED to get any cookie from browser.");
return false;
}
if (count($_COOKIE) == 0) {
Debugger::say("FAILED to get non-empty cookie array from browser.");
return false;
}
// Changed to support IK cookie; by Neerav; 8 July 2005
// Disabled IK cookie requirement
//if (isset($_COOKIE[GM_COOKIE_KEY]) and isset($_COOKIE[GM_COOKIE_IK_KEY])) {
if (isset($_COOKIE[GM_COOKIE_KEY]) and $_COOKIE[GM_COOKIE_KEY]) {
$this->cookie_str = base64_decode($_COOKIE[GM_COOKIE_KEY]);
Debugger::say("Completed getting cookie from browser: ".$this->cookie_str);

if (isset($_COOKIE[GM_COOKIE_IK_KEY]) and $_COOKIE[GM_COOKIE_IK_KEY]) {
$this->cookie_ik_str = base64_decode($_COOKIE[GM_COOKIE_IK_KEY]);
Debugger::say("Completed getting ik cookie from browser: ".$this->cookie_ik_str);
}
return true;
} else {
//Debugger::say("FAILED to read cookie ".GM_COOKIE_KEY." or ".GM_COOKIE_IK_KEY." from browser.");
Debugger::say("FAILED to read cookie ".GM_COOKIE_KEY." from browser.");
return false;
}
}

/**
* @return bool Success or not.
* @desc Save session data.
*/
// Replaced Debugger calls with detailed status info; by Neerav; 2 May 2006
function saveSessionToBrowser() {
if ($this->isConnected()) {
if (!$this->use_session)
return $this->saveCookieToBrowser();

$_SESSION[GM_COOKIE_KEY] = base64_encode($this->cookie_str);
$a = array(
"action" => "save cookie to server",
"status" => "success",
"message" => "Saved cookie to server"
);
array_unshift($this->return_status, $a);
return true;
}

$a = array(
"action" => "save cookie to server",
"status" => "failed",
"message" => "not connected"
);
array_unshift($this->return_status, $a);
return false;
}

/**
* @return bool Success or not.
* @desc Save (send) cookies to browser.
*/
// Replaced Debugger calls with detailed status info; by Neerav; 2 May 2006
function saveCookieToBrowser() {
if ($this->isConnected()) {

if (strpos($_SERVER["HTTP_HOST"],":"))
$domain = substr($_SERVER["HTTP_HOST"],0,strpos($_SERVER["HTTP_HOST"],":"));
else
$domain = $_SERVER["HTTP_HOST"];

// Fixed cookie expiration bug; by Neerav; 1 May 2006
//header("Set-Cookie: ".GM_COOKIE_KEY."=".base64_encode($this->cookie_str)."; Domain=".$domain.";");
setcookie(GM_COOKIE_KEY, base64_encode($this->cookie_str), time()+GM_COOKIE_TTL, "", $domain);
$a = array(
"action" => "save gmail cookie to browser",
"status" => "success",
"message" => "Saved cookie with domain: ".$domain
);
array_unshift($this->return_status, $a);
return true;
}
$a = array(
"action" => "save gmail cookie to browser",
"status" => "failed",
"message" => "not connected"
);
array_unshift($this->return_status, $a);
return false;
}

/**
* @return bool Success or not.
* @desc Remove all session information related to Gmailer.
*/
// Replaced Debugger calls with detailed status info; by Neerav; 2 May 2006
function removeSessionFromBrowser() {
if (!$this->use_session)
return $this->removeCookieFromBrowser();

// Changed/Added by Neerav; 6 July 2005
// determines whether session should be preserved or normally destroyed
if (GM_USE_LIB_AS_MODULE) {
// if this lib is used as a Gmail module in some other app (e.g.
// "online office"), don't destroy session

// Let's unset session variables
if (isset($_SESSION[GM_COOKIE_KEY])) unset($_SESSION[GM_COOKIE_KEY]);
if (isset($_SESSION['id_key'])) unset($_SESSION['id_key']);
$a = array(
"action" => "clear session from browser",
"status" => "success",
"message" => "Cleared libgmailer related session info. Session preserved for other use."
);
array_unshift($this->return_status, $a);
} else {
// otherwise (normal) unset and destroy session
@session_unset();
@session_destroy();
$a = array(
"action" => "destroy session from browser",
"status" => "success",
"message" => "Removed session: ".GM_COOKIE_KEY.". Finished removing session from browser."
);
array_unshift($this->return_status, $a);
}
return true;
}

/**
* @return bool
* @desc Remove all related cookies stored in browser.
*/
// Replaced Debugger calls with detailed status info; by Neerav; 2 May 2006
function removeCookieFromBrowser() {
if (isset($_COOKIE)) {
// Changed to include IK cookie; by Neerav; 8 July 2005
if (isset($_COOKIE[GM_COOKIE_KEY]) or isset($_COOKIE[GM_COOKIE_IK_KEY])) {
//
Post Reply