File: Fetchmail.php

package info (click to toggle)
imp4 4.2-4lenny3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 18,252 kB
  • ctags: 5,316
  • sloc: php: 21,340; xml: 19,302; makefile: 68; sql: 14
file content (457 lines) | stat: -rw-r--r-- 13,987 bytes parent folder | download
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
<?php
/**
 * The IMP_Fetchmail:: class provides an interface to download mail from
 * remote mail servers.
 *
 * $Horde: imp/lib/Fetchmail.php,v 1.41.8.14 2008/01/02 11:31:16 jan Exp $
 *
 * Copyright 2002-2008 The Horde Project (http://www.horde.org/)
 *
 * See the enclosed file COPYING for license information (GPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/gpl.html.
 *
 * @author  Nuno Loureiro <nuno@co.sapo.pt>
 * @author  Michael Slusarz <slusarz@horde.org>
 * @package IMP
 */
class IMP_Fetchmail {

    /**
     * Parameters used by the driver.
     *
     * @var array
     */
    var $_params;

    /**
     * The list of active fetchmail parameters for the current driver.
     * ALL DRIVERS SHOULD UNSET ANY FETCHMAIL PARAMETERS THEY DO NOT USE
     * OR ELSE THEY WILL APPEAR IN THE PREFERENCES PAGE.
     * The following parameters are available:
     *   'id'          --  The account name.
     *   'driver'      --  The driver to use.
     *   'protocol'    --  The protocol type.
     *   'username'    --  The username on the remote server.
     *   'password'    --  The password on the remote server.
     *   'server'      --  The remote server name/address.
     *   'rmailbox'    --  The remote mailbox name.
     *   'lmailbox'    --  The local mailbox to download messages to.
     *   'onlynew'     --  Only retrieve new messages?
     *   'markseen'    --  Mark messages as seen?
     *   'del'         --  Delete messages after fetching?
     *   'loginfetch'  --  Fetch mail from other accounts on login?
     *   'acctcolor'   --  Should these messages be colored differently
     *                     in mailbox view?
     *
     * @var array
     */
    var $_activeparams = array(
        'id', 'driver', 'type', 'protocol', 'username', 'password', 'server',
        'rmailbox', 'lmailbox', 'onlynew', 'markseen', 'del', 'loginfetch',
        'acctcolor'
    );

    /**
     * Attempts to return a concrete IMP_Fetchmail instance based on $driver.
     *
     * @param string $driver  The type of concrete IMP_Fetchmail subclass to
     *                        return, based on the driver indicated. The code
     *                        is dynamically included.
     *
     * @param array $params   The configuration parameter array.
     *
     * @return mixed  The newly created concrete IMP_Fetchmail instance, or
     *                false on error.
     */
    function &factory($driver, $params = array())
    {
        $driver = basename($driver);
        require_once dirname(__FILE__) . '/Fetchmail/' . $driver . '.php';
        $class = 'IMP_Fetchmail_' . $driver;
        if (class_exists($class)) {
            $fetchmail = new $class($params);
        } else {
            $fetchmail = false;
        }

        return $fetchmail;
    }

    /**
     * Returns a list of available drivers, with a description of each.
     * This function can be called statically:
     *   $list = IMP_Fetchmail::listDrivers();
     *
     * @return array  The list of available drivers, with the driver name as
     *                the key and the description as the value.
     */
    function listDrivers()
    {
        $drivers = array();

        if (($dir = opendir(dirname(__FILE__) . '/Fetchmail'))) {
            while (false !== ($file = readdir($dir))) {
                if (!is_dir($file)) {
                    $driver = basename($file, '.php');
                    $class = 'IMP_Fetchmail_' . $driver;
                    require_once dirname(__FILE__) . '/Fetchmail/' . $file;
                    if (is_callable(array($class, 'description')) &&
                        ($descrip = call_user_func(array($class, 'description')))) {
                        $drivers[$driver] = $descrip;
                    }
                }
            }
            closedir($dir);
        }

        return $drivers;
    }

    /**
     * List the colors available for coloring fetched messages.
     * This function can be called statically:
     *   $list = IMP_Fetchmail::listColors();
     *
     * @return array  The list of available colors;
     */
    function listColors()
    {
        return array(
            'purple', 'lime', 'teal', 'blue', 'olive', 'fuchsia', 'navy',
            'aqua'
        );
    }

    /**
     * Returns a description of the driver.
     * This function can be called statically:
     *   $description = IMP_Fetchmail::description();
     *
     * @abstract
     *
     * @return string  The description of the driver.
     */
    function description()
    {
        return '';
    }

    /**
     * Constructor.
     *
     * @param array $params  The configuration parameter array.
     */
    function IMP_Fetchmail($params)
    {
        /* Check for missing params. */
        $paramlist = $this->getParameterList();
        if (array_diff($paramlist, array_keys($params))) {
            // TODO: Error message here
        }

        $this->_params = $params;
    }

    /**
     * Return the list of parameters valid for this driver.
     *
     * @return array  The list of active parameters.
     */
    function getParameterList()
    {
        return $this->_activeparams;
    }

    /**
     * Return a list of protocols supported by this driver.
     *
     * @abstract
     *
     * @return array  The list of protocols.
     *                KEY: protocol ID
     *                VAL: protocol description
     */
    function getProtocolList()
    {
        return array();
    }

    /**
     * Gets the mail using the data in this object.
     *
     * @abstract
     *
     * @return mixed  Returns the number of messages retrieved on success.
     *                Returns PEAR_Error on error.
     */
    function getMail()
    {
        return PEAR::raiseError('not implemented');
    }

    /**
     * Processes a single mail message by calling any user defined functions,
     * stripping bare newlines, and adding color information to the headers.
     *
     * @access private
     *
     * @param string $header  The message header text.
     * @param string $body    The message body text.
     *
     * @return string  The complete message.
     */
    function _processMailMessage($header, $body)
    {
        $msg = rtrim($header);

        if (empty($this->_params['acctcolor'])) {
            $msg .= "\nX-color: " . $this->_params['acctcolor'];
        }
        $msg .= "\n\n" . $body;

        /* If there is a user defined function, call it with the current
         * message as an argument. */
        if ($GLOBALS['conf']['hooks']['fetchmail_filter']) {
            $msg = Horde::callHook('_imp_hook_fetchmail_filter', array($msg), 'imp');
        }

        return IMP::removeBareNewlines($msg);
    }

    /**
     * Checks the message size to see if it exceeds the maximum value
     * allowable in the configuration file.
     *
     * @access private
     *
     * @param integer $size    The size of the message.
     * @param string $subject  The subject of the message.
     * @param string $from     The message sender.
     *
     * @return boolean  False if message is too large, true if OK.
     */
    function _checkMessageSize($size, $subject, $from)
    {
        if (!empty($GLOBALS['conf']['fetchmail']['size_limit']) &&
            ($size > $GLOBALS['conf']['fetchmail']['size_limit'])) {
            require_once 'Horde/MIME.php';
            $GLOBALS['notification']->push(sprintf(_("The message \"%s\" from \"%s\" (%d bytes) exceeds fetch size limit."), MIME::Decode($subject), MIME::Decode($from), $size), 'horde.warning');
            return false;
        } else {
            return true;
        }
    }

    /**
     * Add the message to the requested local mailbox.
     *
     * @access private
     *
     * @param string $msg  The message text.
     *
     * @return boolean  True on success, false on failure.
     */
    function _addMessage($msg)
    {
        $imp_imap = &IMP_IMAP::singleton();
        return @imap_append($imp_imap->stream(), IMP::serverString($this->_params['lmailbox']), $msg);
    }

    /**
     * Perform fetchmail on the list of accounts given. Outputs informaton
     * to the global notification driver.
     * This function can be called statically.
     *
     * @param array $accounts  The list of account identifiers to fetch mail
     *                         for.
     */
    function fetchMail($accounts)
    {
        $fm_account = new IMP_Fetchmail_Account();

        foreach ($accounts as $val) {
            $params = $fm_account->getAllValues($val);
            $driver = &IMP_Fetchmail::factory($params['driver'], $params);
            if ($driver === false) {
                continue;
            }
            $res = $driver->getMail();

            if (is_a($res, 'PEAR_Error')) {
                $GLOBALS['notification']->push(_("Fetchmail: ") . $res->getMessage(), 'horde.warning');
            } elseif ($res == 1) {
                $GLOBALS['notification']->push(_("Fetchmail: ") . sprintf(_("Fetched 1 message from %s"), $fm_account->getValue('id', $val)), 'horde.success');
            } elseif ($res >= 0) {
                $GLOBALS['notification']->push(_("Fetchmail: ") . sprintf(_("Fetched %d messages from %s"), $res, $fm_account->getValue('id', $val)), 'horde.success');
            } else {
                $GLOBALS['notification']->push(_("Fetchmail: no new messages."), 'horde.success');
            }
        }
    }

}

/**
 * The IMP_Fetchmail_Account:: class provides an interface to accessing
 * fetchmail preferences for all mail accounts a user might have.
 *
 * @author  Nuno Loureiro <nuno@co.sapo.pt>
 * @package IMP
 */
class IMP_Fetchmail_Account {

    /**
     * Array containing all the user's accounts.
     *
     * @var array
     */
    var $_accounts = array();

    /**
     * Constructor.
     */
    function IMP_Fetchmail_Account()
    {
        /* Read all the user's accounts from the prefs object or build
         * a new account from the standard values given in prefs.php. */
        $accounts = @unserialize($GLOBALS['prefs']->getValue('fm_accounts'));
        if (is_array($accounts)) {
            $this->_accounts = $accounts;
        }
    }

    /**
     * Return the number of accounts.
     *
     * @return integer  Number of active accounts.
     */
    function count()
    {
        return count($this->_accounts);
    }

    /**
     * Saves all accounts in the prefs backend.
     *
     * @access private
     */
    function _save()
    {
        $GLOBALS['prefs']->setValue('fm_accounts', serialize($this->_accounts));
    }

    /**
     * Adds a new empty account to the array of accounts.
     *
     * @return integer  The pointer to the created account.
     */
    function add()
    {
        $this->_accounts[] = array();
        $this->_save();
        return count($this->_accounts) - 1;
    }

    /**
     * Remove an account from the array of accounts
     *
     * @param integer $account  The pointer to the account to be removed.
     *
     * @return array  The removed account.
     */
    function delete($account)
    {
        $deleted = $this->_accounts[$account];
        unset($this->_accounts[$account]);
        $this->_accounts = array_values($this->_accounts);
        $this->_save();
        return $deleted;
    }

    /**
     * Returns a property from one of the accounts.
     *
     * @param string $key       The property to retrieve.
     * @param integer $account  The account to retrieve the property from.
     *
     * @return mixed  The value of the property or false if the property
     *                doesn't exist.
     */
    function getValue($key, $account)
    {
        return (isset($this->_accounts[$account][$key])) ? $this->_accounts[$account][$key] : false;
    }

    /**
     * Returns all properties from the requested accounts.
     *
     * @param integer $account  The account to retrieve the properties from.
     *
     * @return array  The entire properties array, or false on error.
     */
    function getAllValues($account)
    {
        return (isset($this->_accounts[$account])) ? $this->_accounts[$account] : false;
    }

    /**
     * Returns an array with the specified property from all existing accounts.
     *
     * @param string $key  The property to retrieve.
     *
     * @return array  The array with the values from all accounts.
     */
    function getAll($key)
    {
        $list = array();
        foreach (array_keys($this->_accounts) as $account) {
            $list[$account] = $this->getValue($key, $account);
        }

        return $list;
    }

    /**
     * Sets a property with a specified value.
     *
     * @param string $key       The property to set.
     * @param mixed $val        The value the property should be set to.
     * @param integer $account  The account to set the property in.
     */
    function setValue($key, $val, $account)
    {
        /* These parameters are checkbox items - make sure they are stored
         * as boolean values. */
        $list = array('del', 'onlynew', 'markseen', 'loginfetch');
        if (in_array($key, $list) && !is_bool($val)) {
            if (($val == 'yes') || (intval($val) != 0)) {
                $val = true;
            } else {
                $val = false;
            }
        }

        $this->_accounts[$account][$key] = $val;
        $this->_save();
    }

    /**
     * Returns true if the pair key/value is already in the accounts array.
     *
     * @param string $key  The account key to search.
     * @param string $val  The value to search for in $key.
     *
     * @return boolean  True if the value was found in $key.
     */
    function hasValue($key, $val)
    {
        $list = $this->getAll($key);
        foreach ($list as $val2) {
            if (strpos(String::lower($val), String::lower($val2)) !== false) {
                return true;
            }
        }
        return false;
    }

}