mandrill.class.php 15.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
<?php

class Mandrill_Exception extends Exception {}

class Mandrill {
    const API_VERSION = '1.0';    
    const END_POINT = 'https://mandrillapp.com/api/';
    
    var $api;
    var $output;
    
    // PHP 5.0
    function __construct($api) {
        if ( empty($api) ) throw new Mandrill_Exception('Invalid API key');
        try {
        
            $response = $this->request('users/ping2', array( 'key' => $api ) );        
            if ( !isset($response['PING']) || $response['PING'] != 'PONG!' ) throw new Mandrill_Exception('Invalid API key');
            
            $this->api = $api;
            
        } catch ( Exception $e ) {
            throw new Mandrill_Exception($e->getMessage());
        }
    }
    
    // PHP 4.0
    function Mandrill($api) { $this->__construct($api); }
    
    /**
	 * Work horse. Every API call use this function to actually make the request to Mandrill's servers.
	 *
	 * @link https://mandrillapp.com/api/docs/
	 *
	 * @param string $method API method name
	 * @param array $args query arguments
	 * @param string $http GET or POST request type
	 * @param string $output API response format (json,php,xml,yaml). json and xml are decoded into arrays automatically.
	 * @return array|string|Mandrill_Exception
	 */
	function request($method, $args = array(), $http = 'POST', $output = 'json') {
		if( !isset($args['key']) )
			$args['key'] = $this->api;

        $this->output = $output;
        
		$api_version = self::API_VERSION;
		$dot_output = ('json' == $output) ? '' : ".{$output}";

		$url = self::END_POINT . "{$api_version}/{$method}{$dot_output}";

		switch ($http) {

			case 'GET':
                //some distribs change arg sep to &amp; by default
                $sep_changed = false;
                if (ini_get("arg_separator.output")!="&"){
                    $sep_changed = true;
                    $orig_sep = ini_get("arg_separator.output");
                    ini_set("arg_separator.output", "&");
                }

				$url .= '?' . http_build_query($args);
				
                if ($sep_changed){
                    ini_set("arg_separator.output", $orig_sep);
                }
                
				$response = $this->http_request($url, array(),'GET');
				break;

			case 'POST':
				$response = $this->http_request($url, $args, 'POST');
				break;

			default:
				throw new Mandrill_Exception('Unknown request type');
		}

		$response_code  = $response['header']['http_code'];
		$body           = $response['body'];

		switch ($output) {
			
			case 'json':

				$body = json_decode($body, true);
				break;

			case 'php':

				$body = unserialize($body);
				break;
		}		

		if( 200 == $response_code ) {
			return $body;
		} else {
			if( !is_array( $body ) ) {
				$code = 'Unknown';
				$message = 'Unknown';
			} else {
				$code = 'Unknown' ? !array_key_exists('code', $body) : $body['code'];
				$message = 'Unknown' ? !array_key_exists('message', $body) : $body['message'];
			}

			error_log("wpMandrill Error: Error {$code}: {$message}");
			throw new Mandrill_Exception("wpMandrill Error: {$code}: {$message}", $response_code);

		}
	}

	/**
	 * @link https://mandrillapp.com/api/docs/users.html#method=ping
	 *
	 * @return array|Mandrill_Exception
	 */
	function users_ping() {

		return $this->request('users/ping');
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/users.html#method=info
	 *
	 * @return array|Mandrill_Exception
	 */
	function users_info() {

		return $this->request('users/info');
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/users.html#method=senders
	 *
	 * @return array|Mandrill_Exception
	 */
	function users_senders() {

		return $this->request('users/senders');
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/users.html#method=disable-sender
	 *
	 * @return array|Mandrill_Exception
	 */
	function users_disable_sender($domain) {

		return $this->request('users/disable-senders', array('domain' => $domain) );
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/users.html#method=verify-sender
	 *
	 * @return array|Mandrill_Exception
	 */
	function users_verify_sender($email) {

		return $this->request('users/verify-senders', array('domain' => $email) );
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/senders.html#method=domains
	 *
	 * @return array|Mandrill_Exception
	 */
	function senders_domains() {

		return $this->request('senders/domains');
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/senders.html#method=list
	 *
	 * @return array|Mandrill_Exception
	 */
	function senders_list() {

		return $this->request('senders/list');
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/senders.html#method=info
	 *
	 * @return array|Mandrill_Exception
	 */
	function senders_info($email) {

		return $this->request('senders/info', array( 'address' => $email) );
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/senders.html#method=time-series
	 *
	 * @return array|Mandrill_Exception
	 */
	function senders_time_series($email) {

		return $this->request('senders/time-series', array( 'address' => $email) );
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/tags.html#method=list
	 *
	 * @return array|Mandrill_Exception
	 */
	function tags_list() {

		return $this->request('tags/list');
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/tags.html#method=info
	 *
	 * @return array|Mandrill_Exception
	 */
	function tags_info($tag) {

		return $this->request('tags/info', array( 'tag' => $tag) );
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/tags.html#method=time-series
	 *
	 * @return array|Mandrill_Exception
	 */
	function tags_time_series($tag) {

		return $this->request('tags/time-series', array( 'tag' => $tag) );
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/tags.html#method=all-time-series
	 *
	 * @return array|Mandrill_Exception
	 */
	function tags_all_time_series() {

		return $this->request('tags/all-time-series');
	}
	
	/**
	 * @link https://mandrillapp.com/api/docs/templates.html#method=add
	 *
	 * @return array|Mandrill_Exception
	 */
	function templates_add($name, $code) {

		return $this->request('templates/add', array('name' => $name, 'code' => $code) );
	}

	/**
	 * @link https://mandrillapp.com/api/docs/templates.html#method=update
	 *
	 * @return array|Mandrill_Exception
	 */
	function templates_update($name, $code) {

		return $this->request('templates/update', array('name' => $name, 'code' => $code) );
	}

	/**
	 * @link https://mandrillapp.com/api/docs/templates.html#method=delete
	 *
	 * @return array|Mandrill_Exception
	 */
	function templates_delete($name) {

		return $this->request('templates/delete', array('name' => $name) );
	}

	/**
	 * @link https://mandrillapp.com/api/docs/templates.html#method=info
	 *
	 * @return array|Mandrill_Exception
	 */
	function templates_info($name) {

		return $this->request('templates/info', array('name' => $name) );
	}

	/**
	 * @link https://mandrillapp.com/api/docs/templates.html#method=list
	 *
	 * @return array|Mandrill_Exception
	 */
	function templates_list() {

		return $this->request('templates/list');
	}

	/**
	 * @link https://mandrillapp.com/api/docs/templates.html#method=time-series
	 *
	 * @return array|Mandrill_Exception
	 */
	function templates_time_series($name) {

		return $this->request('templates/time-series', array('name' => $name) );
	}

	/**
	 * @link https://mandrillapp.com/api/docs/webhooks.html#method=add
	 *
	 * @return array|Mandrill_Exception
	 */
	function webhooks_add($url, $events) {

		return $this->request('webhooks/add', array('url' => $url, 'events' => $events) );
	}

	/**
	 * @link https://mandrillapp.com/api/docs/webhooks.html#method=update
	 *
	 * @return array|Mandrill_Exception
	 */
	function webhooks_update($url, $events) {

		return $this->request('webhooks/update', array('url' => $url, 'events' => $events) );
	}

	/**
	 * @link https://mandrillapp.com/api/docs/webhooks.html#method=delete
	 *
	 * @return array|Mandrill_Exception
	 */
	function webhooks_delete($id) {

		return $this->request('webhooks/delete', array('id' => $id) );
	}

	/**
	 * @link https://mandrillapp.com/api/docs/webhooks.html#method=info
	 *
	 * @return array|Mandrill_Exception
	 */
	function webhooks_info($id) {

		return $this->request('webhooks/info', array('id' => $id) );
	}

	/**
	 * @link https://mandrillapp.com/api/docs/webhooks.html#method=list
	 *
	 * @return array|Mandrill_Exception
	 */
	function webhooks_list() {
		return $this->request('webhooks/list');
	}

	/**
	 * @link https://mandrillapp.com/api/docs/messages.html#method=search
	 *
	 * @return array|Mandrill_Exception
	 */
	function messages_search($query, $date_from = '', $date_to = '', $tags = array(), $senders = array(), $limit = 100) {
		return $this->request('messages/search', compact('query', 'date_from', 'date_to', 'tags', 'senders', 'limit'));
	}

	/**
	 * @link https://mandrillapp.com/api/docs/messages.html#method=send
	 *
	 * @return array|Mandrill_Exception
	 */
	function messages_send($message) {
		$async = $message['async'];
		$ip_pool = $message['ip_pool'];
		$send_at = $message['send_at'];
		
		return $this->request('messages/send', array('message' => $message, 'async' => $async, 'ip_pool' => $ip_pool, 'send_at' => $send_at) );
	}
 
	/**
	 * @link https://mandrillapp.com/api/docs/messages.html#method=send-template
	 *
	 * @return array|Mandrill_Exception
	 */
	function messages_send_template($template_name, $template_content, $message) {
		$async = $message['async'];
		$ip_pool = $message['ip_pool'];
		$send_at = $message['send_at'];
		
		return $this->request('messages/send-template', compact('template_name', 'template_content','message', 'async', 'ip_pool', 'send_at') );
	}

    function http_request($url, $fields = array(), $method = 'POST') {

        if ( !in_array( $method, array('POST','GET') ) ) $method = 'POST';
        if ( !isset( $fields['key']) ) $fields['key'] = $this->api;

        //some distribs change arg sep to &amp; by default
        $sep_changed = false;
        if (ini_get("arg_separator.output")!="&"){
            $sep_changed = true;
            $orig_sep = ini_get("arg_separator.output");
            ini_set("arg_separator.output", "&");
        }

        $fields = is_array($fields) ? http_build_query($fields) : $fields;
        
        if ($sep_changed) {
            ini_set("arg_separator.output", $orig_sep);
        }
        
        $useragent = wpMandrill::getUserAgent();
        
        if( function_exists('curl_init') && function_exists('curl_exec') ) {

			set_time_limit(2 * 60);

            $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                
                curl_setopt($ch, CURLOPT_POST, $method == 'POST');
                
                curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
                
				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);	// @Bruno Braga:
				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);	//	Thanks for the hack!
				curl_setopt($ch, CURLOPT_USERAGENT,$useragent);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2 * 60 * 1000);
                
                $response   = curl_exec($ch);
                $info       = curl_getinfo($ch);
                $error      = curl_error($ch);
                
            curl_close($ch);
            
        } elseif( function_exists( 'fsockopen' ) ) {
	        $parsed_url = parse_url($url);

	        $host = $parsed_url['host'];
	        if ( isset($parsed_url['path']) ) {
		        $path = $parsed_url['path'];
	        } else {
		        $path = '/';
	        }

            $params = '';
            if (isset($parsed_url['query'])) {
                $params = $parsed_url['query'] . '&' . $fields;
            } elseif ( trim($fields) != '' ) {
                $params = $fields;
            }

	        if (isset($parsed_url['port'])) {
		        $port = $parsed_url['port'];
	        } else {
		        $port = ($parsed_url['scheme'] == 'https') ? 443 : 80;
	        }

	        $response = false;

	        $errno    = '';
	        $errstr   = '';
            ob_start();
            $fp = fsockopen( 'ssl://'.$host, $port, $errno, $errstr, 5 );

            if( $fp !== false ) {
                stream_set_timeout($fp, 30);
                
                $payload = "$method $path HTTP/1.0\r\n" .
		            "Host: $host\r\n" . 
		            "Connection: close\r\n"  .
                	"User-Agent: $useragent\r\n" .
                    "Content-type: application/x-www-form-urlencoded\r\n" .
                    "Content-length: " . strlen($params) . "\r\n" .
                    "Connection: close\r\n\r\n" .
                    $params;
                fwrite($fp, $payload);
                stream_set_timeout($fp, 30);
                
                $info = stream_get_meta_data($fp);
                while ((!feof($fp)) && (!$info["timed_out"])) {
                    $response .= fread($fp, 4096);
                    $info = stream_get_meta_data($fp);
                }
                
                fclose( $fp );
                ob_end_clean();
                
                list($headers, $response) = explode("\r\n\r\n", $response, 2);
				
    	        $info = array('http_code' => 200);
            } else {
                ob_end_clean();
    	        $info = array('http_code' => 500);
    	        throw new Exception($errstr,$errno);
            }
            $error = '';
        } else {
            throw new Mandrill_Exception("No valid HTTP transport found", -99);
        }
        
        return array('header' => $info, 'body' => $response, 'error' => $error);
    }
    
    static function getAttachmentStruct($path) {
        
        $struct = array();
        
        try {
            
            if ( !@is_file($path) ) throw new Exception($path.' is not a valid file.');

            $filename = basename($path);
            
            if ( !function_exists('get_magic_quotes') ) {
                function get_magic_quotes() { return false; }
            }
            if ( !function_exists('set_magic_quotes') ) {
                function set_magic_quotes($value) { return true;}
            }
            if ( !function_exists('get_magic_quotes_runtime') ) {
                function get_magic_quotes_runtime() { return false; }
            }
            if ( !function_exists('set_magic_quotes_runtime') ) {
                function set_magic_quotes_runtime($value) { return true; }
            }
            
            $file_buffer  = file_get_contents($path);
            $file_buffer  = chunk_split(base64_encode($file_buffer), 76, "\n");
            
            $mime_type = '';
			if ( function_exists('finfo_open') && function_exists('finfo_file') ) {
                $finfo = finfo_open(FILEINFO_MIME_TYPE);
                $mime_type = finfo_file($finfo, $path);
            } elseif ( function_exists('mime_content_type') ) {
                $mime_type = mime_content_type($path);
            }

            if ( !empty($mime_type) ) $struct['type']     = $mime_type;
            $struct['name']     = $filename;
            $struct['content']  = $file_buffer;

        } catch (Exception $e) {
            throw new Mandrill_Exception('Error creating the attachment structure: '.$e->getMessage());
        }
        
        return $struct;
    }
    
    static function isValidContentType($ct) {
        // Now Mandrill accepts any content type. 
        return true;
    }
    
    static function getValidContentTypes() {
        return array(
                  'image/',
                  'text/',
                  'application/pdf',
        		  'audio/',
        		  'video/'
              );
    }
}

?>