Bin will be removed on June 1, 2014 in favor of http://gist.github.com. Please save all your pastes before then. So long, and thanks for all the fish!×
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
<?php
/**
 * Gmail Datasource
 *
 * Parse and search Gmail/Google Apps email atom feed.
 * Next version will include IMAP access
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * Usage Example:
 *
 * Use database.php to store config:
 * database.php:
var $gmail = array(
    'datasource'    => 'gmail',
    'username'      => 'user@gmail.com', // Google apps accounts also works! Just use user@yourdomain.com
    'password'      => 'secret',
);
 * your_controller.php:
class YourController extends AppController {
    function index(){
        // Use you database config
        $this->Gmail = ConnectionManager::getDataSource('gmail');
        // Or create a new config
        //$this->Gmail = ConnectionManager::create('gmail_user', array(
        //  'datasource'    => 'gmail',
        //  'email'         => 'user@gmail.com',
        //  'password'      => 'secret',
        //));
        $unread = $this->Gmail->inboxFeed();
        $unread_with_label = $this->Gmail->inboxFeed('label name');
        $search_all_fields = $this->Gmail->searchFeed('hello');
        $search_author_fields = $this->Gmail->searchFeed(array('author' => 'adrien'));
        // you can specify a label name as second argument in searchFeed, search terms can be usual string(s) or pattern(s)
        $search_summary_field_with_label = $this->Gmail->searchFeed(array('summary' => '/^ĥello,/i'), 'label name');
    }
 
}
 *
 * @author Adrein Gibrat <adrien.gibrat@gmail.com>
 * @license http://www.opensource.org/licenses/mit-license.php The MIT License
 * @created Jun 24, 2009
 * @version 0.1
 */
App::import('Core', array('Xml', 'HttpSocket'));
 
class GmailSource extends DataSource
{
    var $email          = '';
    var $password       = '';
    var $inbox          = '';
    var $domain         = 'gmail.com';
    var $feed           = 'https://mail.google.com/mail/feed/atom';
    var $description    = 'Gmail';
    var $Http           = null;
 
    /**
     *
     * @param array Configurations informations
     */
    function __construct($config) {
        parent::__construct($config);
        $this->Http     =& new HttpSocket();
        $this->email    = $this->config['email'];
        $this->password = $this->config['password'];
        if (preg_match('/^[A-Z0-9._%-+]+@(?<domain>[A-Z0-9.-]+\.[A-Z]{2,4})$/i', $this->email, $email) ) {
            $this->domain   = $email['domain'];
        }
        if ($this->domain != 'gmail.com') {
            $this->feed     = 'https://mail.google.com/a/' . $this->domain . '/feed/atom';
        }
        if (isset($this->config['inbox'])) {
            $this->inbox    = $this->config['inbox'];
        }
    }
 
    /**
     * Get unread messages list.
     * @param string Inbox to check (optional)
     * @return array Gmail unread messages or null if no new messages
     */
    function inboxFeed($inbox = null) {
        if ($inbox) {
            $this->inbox    = $inbox;
        }
        $header = array(
            'auth' => array(
                'method'    => 'Basic',
                'user'      => $this->email,
                'pass'      => $this->password
            )
        );
        if ($result = $this->__xmlToArray($this->Http->get($this->feed . '/' . $this->inbox, null, $header))) {
            if ($result['Feed']['fullcount'] > 0) {
                return $result['Feed']['Entry'];
            }
        }
    }
 
    /**
     * Get matching unread messages list.
     * @param string|array Words (space separated)/Pattern(s) to search, array use key to focus search on a field
     * @param string Inbox to check (optional)
     * @return array Matching gmail unread messages or null if no matching messages
     */
    function searchFeed($search, $inbox = null) {
        if ($messages = $this->inboxFeed($inbox)) {
            $search = is_array($search) ? array_map(array($this, '__quote'), $search) : self::__quote($search); // Make search pattern(s)
            foreach ($messages as $message) {
                $result[] = self::__grep($search, $message);
            }
            if ($result = array_filter($result)) { // Return null if empty
                return $result;
            }
        }
    }
 
    /**
     * Filter entries, return entry only if field(s) match the pattern
     * @param string|array Pattern(s) to search, array use key to focus search on a field
     * @param array Entries to search in
     * @param array Parents fields names (optional)
     * @return array
     */
    function __grep($pattern, $subject, $keys = array()) {
        foreach ($subject as $key => $value) {
            $fields = array_merge($keys, array(strtolower($key))); // Store parents fields
            if (call_user_func(array($this, is_array($value) ? '__grep' : '__match'), $pattern, $value, $fields)) { // Recursive check
                return $subject;
            }
        }
    }
 
    /**
     * Search for a match in content
     * @param string|array Pattern(s) to search, array use key to focus search on a field
     * @param string Content to search in
     * @param array Parents & current fields names (optional)
     * @return boolean Match found
     */
    function __match($pattern, $subject, $keys = array()) {
        if (is_array($pattern)) {
            foreach($pattern as $key => $expression) {
                if (in_array($key, $keys) && preg_match($expression, $subject)) { // Focus on given field(s)
                    return true;
                }
            }
        } else {
            return preg_match($pattern, $subject);
        }
    }
 
    /**
     * Validate/build regular expression
     * @param string Words or regular expression
     * @return string Quoted regular expression
     */
    function __quote($search) {
        if (preg_match('/^([^A-Z0-9]).*\1[imsxeADSUXJu]?$/mi', $search)) { // String is a regular expression
            return $search;
        }
        return '/' . preg_replace('/\s/m', '|', preg_quote($search, '/')) . '/mi'; // Make usual string a regular expression
    }
 
    /**
     * Process Xml to Array
     * @param string Gmail atom xml
     * @return array Gmail atom feed content
     */
    function __xmlToArray($response) {
        $xml = new XML($response);
        $xml->__killParent(true);
        $xml->__destruct(); // Free memory
        return $xml->toArray();
    }
}
?>