File: Headers.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 (471 lines) | stat: -rw-r--r-- 16,080 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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
<?php
/**
 * @package Horde_MIME
 */

require_once 'Horde/MIME/Headers.php';
require_once IMP_BASE . '/lib/version.php';

/**
 * The description of the IMP program to use in the 'User-Agent:' header.
 */
define('IMP_AGENT_HEADER', 'Internet Messaging Program (IMP) ' . IMP_VERSION);

/**
 * The IMP_Headers:: class contains all functions related to handling the
 * headers of mail messages in IMP.
 *
 * $Horde: imp/lib/MIME/Headers.php,v 1.92.2.31 2008/05/25 18:40:45 chuck 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  Michael Slusarz <slusarz@horde.org>
 * @package Horde_MIME
 */
class IMP_Headers extends MIME_Headers {

    /**
     * The User-Agent string to use.
     *
     * @var string
     */
    var $_agent = IMP_AGENT_HEADER;

    /**
     * The header object cache.
     *
     * @var array
     */
    var $_obCache = array();

    /**
     * Returns a reference to a currently open IMAP stream.
     *
     * @see MIME_Headers::_getStream()
     */
    function _getStream()
    {
        $imp_imap = &IMP_IMAP::singleton();
        return $imp_imap->stream();
    }

    /**
     * Parses all of the available mailing list headers.
     */
    function parseAllListHeaders()
    {
        foreach ($this->listHeaders() as $val => $str) {
            $this->parseListHeaders($val);
        }
    }

    /**
     * Parses the information in the mailing list headers.
     *
     * @param string $header  The header to process.
     * @param boolean $raw    Should the raw URL be returned instead of setting
     *                        the header value?
     *
     * @return string  The header value (if $raw == true).
     */
    function parseListHeaders($header, $raw = false)
    {
        if (!($data = $this->getValue($header))) {
            return;
        }

        $output = '';

        require_once 'Horde/Text.php';

        /* Split the incoming data by the ',' character. */
        foreach (preg_split("/,/", $data) as $entry) {
            /* Get the data inside of the brackets. If there is no brackets,
             * then return the raw text. */
            if (!preg_match("/\<([^\>]+)\>/", $entry, $matches)) {
                return trim($entry);
            }

            /* Remove all whitespace from between brackets (RFC 2369 [2]). */
            $match = preg_replace("/\s+/", '', $matches[1]);

            /* Determine if there are any comments. */
            preg_match("/(\(.+\))/", $entry, $comments);

            /* RFC 2369 [2] states that we should only show the *FIRST* URL
             * that appears in a header that we can adequately handle. */
            if (stristr($match, 'mailto:') !== false) {
                $match = substr($match, strpos($match, ':') + 1);
                if ($raw) {
                    return $match;
                }
                $output = Horde::link(IMP::composeLink($match)) . $match . '</a>';
                if (!empty($comments[1])) {
                    $output .= '&nbsp;' . $comments[1];
                }
                break;
            } else {
                require_once 'Horde/Text/Filter.php';
                if ($url = Text_Filter::filter($match, 'linkurls', array('callback' => 'Horde::externalUrl'))) {
                    if ($raw) {
                        return $match;
                    }
                    $output = $url;
                    if (!empty($comments[1])) {
                        $output .= '&nbsp;' . $comments[1];
                    }
                    break;
                } else {
                    /* Use this entry unless we can find a better one. */
                    $output = $match;
                }
            }
        }

        $this->setValue($header, $output);
    }

    /**
     * Adds any site-specific headers defined in config/header.php to the
     * internal header array.
     */
    function addSiteHeaders()
    {
        static $_header;

        /* Add the 'User-Agent' header. */
        $this->addAgentHeader();

        /* Tack on any site-specific headers. */
        if (is_callable(array('Horde', 'loadConfiguration'))) {
            $result = Horde::loadConfiguration('header.php', array('_header'));
            if (!is_a($result, 'PEAR_Error')) {
                extract($result);
            }
        } else {
            require IMP_BASE . '/config/header.php';
            $result = true;
        }

        if (!is_a($result, 'PEAR_Error')) {
            foreach ($_header as $key => $val) {
                $this->addHeader(trim($key), trim($val));
            }
        }
    }

    /**
     * Builds a string containing a list of addresses.
     *
     * @param string $field    The address field to parse.
     * @param integer $addURL  The self URL.
     * @param boolean $set     Set the associated header with the return
     *                         string?
     * @param boolean $link    Link each address to the compose screen?
     *
     * @return string  String containing the formatted address list.
     */
    function buildAddressLinks($field, $addURL, $set = false, $link = true)
    {
        global $prefs, $registry;

        $add_link = null;

        /* Make sure this is a valid object address field. */
        $array = $this->getOb($field);
        if (empty($array) || !is_array($array)) {
            return null;
        }

        /* Set up the add address icon link if contact manager is
         * available. */
        if ($link && $prefs->getValue('add_source')) {
            $add_link = $registry->link('contacts/add', array('source' => $prefs->getValue('add_source')));
            if (is_a($add_link, 'PEAR_Error')) {
                if ($registry->hasMethod('contacts/import')) {
                    $add_link = Util::addParameter($addURL, 'actionID', 'add_address');
                } else {
                    $add_link = null;
                }
            }
        }

        $addr_array = array();

        foreach ($this->getAddressesFromObject($array) as $ob) {
            if (isset($ob->groupname)) {
                $group_array = array();
                foreach ($ob->addresses as $ad) {
                    if (empty($ad->address) || empty($ad->inner)) {
                        continue;
                    }

                    $ret = '';

                    /* If this is an incomplete e-mail address, don't link to
                     * anything. */
                    if (stristr($ad->host, 'UNKNOWN') !== false) {
                        $ret = $ad->address;
                    } else {
                        $ret = htmlspecialchars(str_replace('\"', '"', $ad->address));
                        if ($link) {
                            $ret = Horde::link(IMP::composeLink(array('to' => addslashes($ad->address))), sprintf(_("New Message to %s"), $ad->inner)) . $ret . '</a>';
                        }

                        /* Append the add address icon to every address if contact
                         * manager is available. */
                        if ($add_link) {
                            $curr_link = Util::addParameter($add_link, array('name' => $ad->personal, 'address' => $ad->inner));
                            $ret .= Horde::link($curr_link, sprintf(_("Add %s to my Address Book"), $ad->inner)) .
                                Horde::img('addressbook_add.png', sprintf(_("Add %s to my Address Book"), $ad->inner)) . '</a>';
                        }
                    }

                    $group_array[] = $ret;
                }

                $addr_array[] = htmlspecialchars($ob->groupname) . ':' . (count($group_array) ? ' ' . implode(', ', $group_array) : '');
            } elseif (!empty($ob->address) && !empty($ob->inner)) {
                $ret = '';

                /* If this is an incomplete e-mail address, don't link to
                 * anything. */
                if (stristr($ob->host, 'UNKNOWN') !== false) {
                    $ret = $ob->address;
                } else {
                    $ret = htmlspecialchars(str_replace('\"', '"', $ob->address));
                    if ($link) {
                        $ret = Horde::link(IMP::composeLink(array('to' => addslashes($ob->address))), sprintf(_("New Message to %s"), $ob->inner)) . $ret . '</a>';
                    }

                    /* Append the add address icon to every address if contact
                     * manager is available. */
                    if ($add_link) {
                        $curr_link = Util::addParameter($add_link, array('name' => $ob->personal, 'address' => $ob->inner));
                        $ret .= Horde::link($curr_link, sprintf(_("Add %s to my Address Book"), $ob->inner)) .
                            Horde::img('addressbook_add.png', sprintf(_("Add %s to my Address Book"), $ob->inner)) . '</a>';
                    }
                }

                $addr_array[] = $ret;
            }
        }

        /* If left with an empty address list ($ret), inform the user that the
         * recipient list is purposely "undisclosed". */
        if (empty($addr_array)) {
            $ret = _("Undisclosed Recipients");
        } else {
            /* Build the address line. */
            $addr_count = count($addr_array);
            if ($addr_count > 20) {
                Horde::addScriptFile('prototype.js', 'imp', true);
                Horde::addScriptFile('addressesBlocks.js', 'imp');

                $ret = '<div id="at_' . $field . '">' .
                    Horde::link('#', '', 'widget', '', 'toggleAddressesBlock(\'' . $field . '\', \'' . $addr_count . '\'); return false;', '', '') .
                    sprintf(_("[Show addresses - %s recipients]"), $addr_count) . '</a></div>' .
                    '<div id="ab_' . $field . '" style="display:none;"><span class="nowrap">' . implode(',</span> <span class="nowrap">', $addr_array) . '</span></div>';
            } else {
                $ret = '<span class="nowrap">' . implode(',</span> <span class="nowrap">', $addr_array) . '</span>';
            }
        }

        /* Set the header value, if requested. */
        if (!empty($set)) {
            $this->setValue($field, $ret);
        }

        return $ret;
    }

    /**
     * Return the list of addresses for a header object.
     *
     * @TODO Merge back to Horde_Mime_Headers with the changes to support
     * groups.
     *
     * @param array $obs  An array of header objects (See imap_headerinfo()
     *                    for the object structure).
     *
     * @return array  An array of objects.
     * <pre>
     * Object elements:
     * 'address'   -  Full address
     * 'host'      -  Host name
     * 'inner'     -  Trimmed, bare address
     * 'personal'  -  Personal string
     * </pre>
     */
    function getAddressesFromObject($obs)
    {
        $retArray = array();

        if (!is_array($obs) || empty($obs)) {
            return $retArray;
        }

        foreach ($obs as $ob) {
            if (isset($ob->groupname)) {
                $newOb = new stdClass;
                $newOb->addresses = $this->getAddressesFromObject($ob->addresses);
                $newOb->groupname = $ob->groupname;

                $retArray[] = $newOb;
                continue;
            }

            /* Ensure we're working with initialized values. */
            if (isset($ob->personal)) {
                $ob->personal = MIME::decode($ob->personal);
                if ((substr($ob->personal, 0, 1) == '"') &&
                    (substr($ob->personal, -1) == '"')) {
                    $ob->personal = substr($ob->personal, 1, -1);
                }
            } else {
                $ob->personal = '';
            }

            if (isset($ob->mailbox)) {
                /* Don't process invalid addresses. */
                if (strpos($ob->mailbox, 'UNEXPECTED_DATA_AFTER_ADDRESS') !== false ||
                    strpos($ob->mailbox, 'INVALID_ADDRESS') !== false) {
                    continue;
                }
            } else {
                $ob->mailbox = '';
            }

            if (!isset($ob->host)) {
                $ob->host = '';
            }

            /* Generate the new object. */
            $newOb = new stdClass;
            $newOb->address = MIME::addrObject2String($ob, array('undisclosed-recipients@', 'Undisclosed recipients@'));
            $newOb->host = $ob->host;
            $newOb->inner = MIME::trimEmailAddress(MIME::rfc822WriteAddress($ob->mailbox, $ob->host, ''));
            $newOb->personal = $ob->personal;

            $retArray[] = $newOb;
        }

        return $retArray;
    }

    /**
     * Adds the local time string to the date header.
     *
     * @param string $date  The date string.
     *
     * @return string  The date string with the local time added on.
     */
    function addLocalTime($date)
    {
        if (empty($date)) {
            $ltime = false;
        } else {
            $date = preg_replace('/\s+\(\w+\)$/', '', $date);
            $ltime = strtotime($date);
        }
        if ($ltime !== false && $ltime !== -1) {
            $date_str = strftime($GLOBALS['prefs']->getValue('date_format'), $ltime);
            $time_str = strftime($GLOBALS['prefs']->getValue('time_format'), $ltime);
            $tz = strftime('%Z');
            if ((date('Y') != @date('Y', $ltime)) ||
                (date('M') != @date('M', $ltime)) ||
                (date('d') != @date('d', $ltime))) {
                /* Not today, use the date. */
                $date .= sprintf(' <small>[%s %s %s]</small>', $date_str, $time_str, $tz);
            } else {
                /* Else, it's today, use the time only. */
                $date .= sprintf(' <small>[%s %s]</small>', $time_str, $tz);
            }
        }

        return $date;
    }

    /**
     * Returns a header from the header object.
     *
     * @todo Move to framework for Horde 4.0.
     *
     * @param string $field  The header to return as an object.
     *
     * @return mixed  The field requested.
     */
    function getOb($field)
    {
        if (!isset($this->_obCache[$field])) {
            $ob = IMP::parseAddressList($this->getValue($field));
            if (is_a($ob, 'PEAR_Error')) {
                $ob = array();
            }
            $this->_obCache[$field] = $ob;
        }
        return $this->_obCache[$field];
    }

    /**
     * Explicitly sets the User-Agent string.
     *
     * @todo Move to framework for Horde 4.0.
     * @since IMP 4.2
     *
     * @param string $useragent  The User-Agent string to use.
     */
    function setUserAgent($useragent)
    {
        $this->_agent = $useragent;
    }

    /**
     * Determines the X-Priority of the message based on the headers.
     *
     * @since IMP 4.2
     *
     * @return string  'high', 'low', or 'normal'.
     */
    function getXpriority()
    {
        if (($priority = $this->getValue('x-priority')) &&
            preg_match('/\s*(\d+)\s*/', $priority, $matches)) {
            if (in_array($matches[1], array(1, 2))) {
                return 'high';
            } elseif (in_array($matches[1], array(4, 5))) {
                return 'low';
            }
        }

        return 'normal';
    }

    /**
     * Returns e-mail information for a mailing list.
     *
     * @since IMP 4.2
     *
     * @return array  An array with 2 elements: 'exists' and 'reply_list'.
     */
    function getListInformation()
    {
        $ret = array('exists' => false, 'reply_list' => null);

        if ($this->listHeadersExist()) {
            $ret['exists'] = true;

            /* See if the List-Post header provides an e-mail address for the
             * list. */
            if ($this->getValue('list-post')) {
                $ret['reply_list'] = $this->parseListHeaders('list-post', true);
            }
        }

        return $ret;
    }

}