ClientSort.php 12 KB
Newer Older
1 2
<?php
/**
3
 * Copyright 2012-2017 Horde LLC (http://www.horde.org/)
4
 *
5
 * See the enclosed file LICENSE for license information (LGPL). If you
6 7 8
 * did not receive this file, see http://www.horde.org/licenses/lgpl21.
 *
 * @category  Horde
9
 * @copyright 2012-2017 Horde LLC
10 11 12 13 14 15 16 17 18 19 20 21 22
 * @license   http://www.horde.org/licenses/lgpl21 LGPL 2.1
 * @package   Imap_Client
 */

/**
 * Client sorting methods for the Socket driver.
 *
 * NOTE: This class is NOT intended to be accessed outside of a Base object.
 * There is NO guarantees that the API of this class will not change across
 * versions.
 *
 * @author    Michael Slusarz <slusarz@horde.org>
 * @category  Horde
23
 * @copyright 2012-2017 Horde LLC
24 25 26 27 28 29
 * @internal
 * @license   http://www.horde.org/licenses/lgpl21 LGPL 2.1
 * @package   Imap_Client
 */
class Horde_Imap_Client_Socket_ClientSort
{
30 31 32 33 34 35 36
    /**
     * Collator object to use for sotring.
     *
     * @var Collator
     */
    protected $_collator;

37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    /**
     * Socket object.
     *
     * @var Horde_Imap_Client_Socket
     */
    protected $_socket;

    /**
     * Constructor.
     *
     * @param Horde_Imap_Client_Socket $socket  Socket object.
     */
    public function __construct(Horde_Imap_Client_Socket $socket)
    {
        $this->_socket = $socket;
52 53 54 55

        if (class_exists('Collator')) {
            $this->_collator = new Collator(null);
        }
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
    }

    /**
     * Sort search results client side if the server does not support the SORT
     * IMAP extension (RFC 5256).
     *
     * @param Horde_Imap_Client_Ids $res  The search results.
     * @param array $opts                 The options to _search().
     *
     * @return array  The sort results.
     *
     * @throws Horde_Imap_Client_Exception
     */
    public function clientSort($res, $opts)
    {
        if (!count($res)) {
            return $res;
        }

        /* Generate the FETCH command needed. */
        $query = new Horde_Imap_Client_Fetch_Query();

        foreach ($opts['sort'] as $val) {
            switch ($val) {
            case Horde_Imap_Client::SORT_ARRIVAL:
                $query->imapDate();
                break;

            case Horde_Imap_Client::SORT_DATE:
                $query->imapDate();
                $query->envelope();
                break;

            case Horde_Imap_Client::SORT_CC:
            case Horde_Imap_Client::SORT_DISPLAYFROM:
            case Horde_Imap_Client::SORT_DISPLAYTO:
            case Horde_Imap_Client::SORT_FROM:
            case Horde_Imap_Client::SORT_SUBJECT:
            case Horde_Imap_Client::SORT_TO:
                $query->envelope();
                break;

98 99 100 101
            case Horde_Imap_Client::SORT_SEQUENCE:
                $query->seq();
                break;

102 103 104 105 106 107 108 109 110 111 112
            case Horde_Imap_Client::SORT_SIZE:
                $query->size();
                break;
            }
        }

        if (!count($query)) {
            return $res;
        }

        $mbox = $this->_socket->currentMailbox();
113
        $fetch_res = $this->_socket->fetch(isset($mbox['mailbox']) ? $mbox['mailbox'] : null, $query, array(
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
            'ids' => $res
        ));

        return $this->_clientSortProcess($res->ids, $fetch_res, $opts['sort']);
    }

    /**
     * If server does not support the THREAD IMAP extension (RFC 5256), do
     * ORDEREDSUBJECT threading on the client side.
     *
     * @param Horde_Imap_Client_Fetch_Results $data  Fetch results.
     * @param boolean $uids                          Are IDs UIDs?
     *
     * @return array  The thread sort results.
     */
    public function threadOrderedSubject(Horde_Imap_Client_Fetch_Results $data,
                                         $uids)
    {
        $dates = $this->_getSentDates($data, $data->ids());
        $out = $sorted = $tsort = array();

        foreach ($data as $k => $v) {
            $subject = strval(new Horde_Imap_Client_Data_BaseSubject($v->getEnvelope()->subject));
            $sorted[$subject][$k] = $dates[$k];
        }

        /* Step 1: Sort by base subject (already done).
         * Step 2: Sort by sent date within each thread. */
        foreach (array_keys($sorted) as $key) {
143
            $this->_stableAsort($sorted[$key]);
144 145 146 147 148
            $tsort[$key] = reset($sorted[$key]);
        }

        /* Step 3: Sort by the sent date of the first message in the
         * thread. */
149
        $this->_stableAsort($tsort);
150 151 152 153 154 155 156 157 158 159

        /* Now, $tsort contains the order of the threads, and each thread
         * is sorted in $sorted. */
        foreach (array_keys($tsort) as $key) {
            $keys = array_keys($sorted[$key]);
            $out[$keys[0]] = array(
                $keys[0] => 0
            ) + array_fill_keys(array_slice($keys, 1) , 1);
        }

160 161 162 163
        return new Horde_Imap_Client_Data_Thread(
            $out,
            $uids ? 'uid' : 'sequence'
        );
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
    }

    /**
     */
    protected function _clientSortProcess($res, $fetch_res, $sort)
    {
        /* The initial sort is on the entire set. */
        $slices = array(0 => $res);
        $reverse = false;

        foreach ($sort as $val) {
            if ($val == Horde_Imap_Client::SORT_REVERSE) {
                $reverse = true;
                continue;
            }

            $slices_list = $slices;
            $slices = array();

            foreach ($slices_list as $slice_start => $slice) {
                $sorted = array();

                switch ($val) {
                case Horde_Imap_Client::SORT_SEQUENCE:
                    /* There is no requirement that IDs be returned in
                     * sequence order (see RFC 4549 [4.3.1]). So we must sort
                     * ourselves. */
                    $sorted = array_flip($slice);
                    ksort($sorted, SORT_NUMERIC);
                    break;

                case Horde_Imap_Client::SORT_SIZE:
                    foreach ($slice as $num) {
                        $sorted[$num] = $fetch_res[$num]->getSize();
                    }
                    asort($sorted, SORT_NUMERIC);
                    break;

                case Horde_Imap_Client::SORT_DISPLAYFROM:
                case Horde_Imap_Client::SORT_DISPLAYTO:
                    $field = ($val == Horde_Imap_Client::SORT_DISPLAYFROM)
                        ? 'from'
                        : 'to';

                    foreach ($slice as $num) {
209 210 211 212
                        $ob = $fetch_res[$num]->getEnvelope()->$field;
                        $sorted[$num] = ($addr_ob = $ob[0])
                            ? $addr_ob->personal ?: $addr_ob->mailbox
                            : null;
213 214
                    }

215
                    $this->_sortString($sorted);
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
                    break;

                case Horde_Imap_Client::SORT_CC:
                case Horde_Imap_Client::SORT_FROM:
                case Horde_Imap_Client::SORT_TO:
                    if ($val == Horde_Imap_Client::SORT_CC) {
                        $field = 'cc';
                    } elseif ($val == Horde_Imap_Client::SORT_FROM) {
                        $field = 'from';
                    } else {
                        $field = 'to';
                    }

                    foreach ($slice as $num) {
                        $tmp = $fetch_res[$num]->getEnvelope()->$field;
                        $sorted[$num] = count($tmp)
                            ? $tmp[0]->mailbox
                            : null;
                    }
235 236

                    $this->_sortString($sorted);
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
                    break;

                case Horde_Imap_Client::SORT_ARRIVAL:
                    $sorted = $this->_getSentDates($fetch_res, $slice, true);
                    asort($sorted, SORT_NUMERIC);
                    break;

                case Horde_Imap_Client::SORT_DATE:
                    // Date sorting rules in RFC 5256 [2.2]
                    $sorted = $this->_getSentDates($fetch_res, $slice);
                    asort($sorted, SORT_NUMERIC);
                    break;

                case Horde_Imap_Client::SORT_SUBJECT:
                    // Subject sorting rules in RFC 5256 [2.1]
                    foreach ($slice as $num) {
                        $sorted[$num] = strval(new Horde_Imap_Client_Data_BaseSubject($fetch_res[$num]->getEnvelope()->subject));
                    }
255 256

                    $this->_sortString($sorted);
257 258 259 260 261 262
                    break;
                }

                // At this point, keys of $sorted are sequence/UID and values
                // are the sort strings
                if (!empty($sorted)) {
263 264 265 266
                    if ($reverse) {
                        $sorted = array_reverse($sorted, true);
                    }

267 268 269 270 271 272 273 274 275
                    if (count($sorted) === count($res)) {
                        $res = array_keys($sorted);
                    } else {
                        array_splice($res, $slice_start, count($slice), array_keys($sorted));
                    }

                    // Check for ties.
                    $last = $start = null;
                    $i = 0;
276 277 278
                    $todo = array();

                    foreach ($sorted as $k => $v) {
279 280
                        if (is_null($last) || ($last != $v)) {
                            if ($i) {
281
                                $todo[] = array($start, $i);
282 283 284 285 286 287 288 289 290
                                $i = 0;
                            }
                            $last = $v;
                            $start = $k;
                        } else {
                            ++$i;
                        }
                    }
                    if ($i) {
291 292 293 294 295 296 297 298 299 300 301 302
                        $todo[] = array($start, $i);
                    }

                    foreach ($todo as $v) {
                        $slices[array_search($v[0], $res)] = array_keys(
                            array_slice(
                                $sorted,
                                array_search($v[0], $sorted),
                                $v[1] + 1,
                                true
                            )
                        );
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
                    }
                }
            }

            $reverse = false;
        }

        return $res;
    }

    /**
     * Get the sent dates for purposes of SORT/THREAD sorting under RFC 5256
     * [2.2].
     *
     * @param Horde_Imap_Client_Fetch_Results $data  Data returned from
     *                                               fetch() that includes
     *                                               both date and envelope
     *                                               items.
     * @param array $ids                             The IDs to process.
     * @param boolean $internal                      Only use internal date?
     *
     * @return array  A mapping of IDs -> UNIX timestamps.
     */
    protected function _getSentDates(Horde_Imap_Client_Fetch_Results $data,
                                     $ids, $internal = false)
    {
        $dates = array();

        foreach ($ids as $num) {
            $dt = ($internal || !isset($data[$num]->getEnvelope()->date))
                // RFC 5256 [3] & 3501 [6.4.4]: disregard timezone when
                // using internaldate.
                ? $data[$num]->getImapDate()
                : $data[$num]->getEnvelope()->date;
            $dates[$num] = $dt->format('U');
        }

        return $dates;
    }

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
    /**
     * Stable asort() function.
     *
     * PHP's asort() (BWT) is not a stable sort - identical values have no
     * guarantee of key order. Use Schwartzian Transform instead. See:
     * http://notmysock.org/blog/php/schwartzian-transform.html
     *
     * @param array &$a  Array to sort.
     */
    protected function _stableAsort(&$a)
    {
        array_walk($a, function(&$v, $k) { $v = array($v, $k); });
        asort($a);
        array_walk($a, function(&$v, $k) { $v = $v[0]; });
    }

    /**
     * Sort an array of strings based on current locale.
     *
     * @param array &$sorted  Array of strings.
     */
    protected function _sortString(&$sorted)
    {
        if (empty($this->_collator)) {
            asort($sorted, SORT_LOCALE_STRING);
        } else {
            $this->_collator->asort($sorted, Collator::SORT_STRING);
        }
    }

373
}