source: trunk/prototype/services/ImapServiceAdapter.php @ 5586

Revision 5586, 13.2 KB checked in by douglasz, 12 years ago (diff)

Ticket #2486 - Atualizar a lista de mensagens quando editar ou excluir um marcador

Line 
1<?php
2
3include_once ROOTPATH."/../expressoMail1_2/inc/class.imap_functions.inc.php";
4
5class ImapServiceAdapter extends imap_functions/* implements Service*/
6{
7    public function open( $config )
8    {
9                $this->init();
10    }
11
12//     public function connect( $config )
13//     {
14//                      $this->init();
15//     }
16       
17    public function find( $URI, $justthese = false, $criteria = false )
18        {
19                $context = $justthese['context'];
20                $URI = $URI['concept'];
21
22                switch( $URI )
23                {
24                        case 'folder':
25                        {
26                                $result = $this->to_utf8($this->get_folders_list());
27
28                                foreach ($result as $res) {
29
30                                        $response[] = array(
31                                                        'id' => $res['folder_id'],
32                                                        'commonName' => $res['folder_name'],
33                                                        'parentFolder' => $res['folder_parent'],
34                                                        'messageCount' => array('unseen' => isset($res['folder_unseen']) ? $res['folder_unseen'] : null, 'total' => null)
35                                                );
36                                }
37
38                                return $response;
39                        }
40                        case 'message':
41                        {
42                                //begin: for grid       
43                                $page  = $criteria['page']; //{1}    get the requested page
44                                $limit = $criteria['rows']; //{10}   get how many rows we want to have into the grid
45                                $sidx  = $criteria['sidx']; //{id}   get index row - i.e. user click to sort
46                                $sord  = $criteria['sord']; //{desc} get the direction
47
48                                $filter = $criteria['filter'];
49
50                                if( !$sidx ) $sidx = 1;
51
52                                $folder_name = str_replace( '.', $this->imap_delimiter, $context['folder'] );
53                               
54                                $count = imap_num_msg( $this->open_mbox( $folder_name ) );
55
56                                $total_pages = $count > 0 ? ceil( $count/$limit ) : 0;
57
58                                if( $page > $total_pages )
59                                        $page = $total_pages;
60
61                                $start = $limit * $page - $limit;
62
63                                // do not put $limit*($page - 1)
64                                //end: for grid
65
66                                if( $filter )
67                                {
68                                        if( $filter[0] !== 'msgNumber' )
69                                        {
70                                        for( $i = 0; $i < count($filter); $i++ )
71                                        {
72                                                if( count( $filter[$i] ) === 4 )
73                                                $criteria['isExact'] = ( array_shift( $filter[$i] ) === 'AND' );
74
75                                                $criteria[ $filter[$i][0] ] = array( 'criteria' => $filter[$i][2], 'filter' => $filter[$i][1] );
76                                        }
77
78                                        return $this->searchSieveRule($criteria);
79                                        }
80
81                                        $msgNumber = array();
82
83                                        for( $i = $start; $i < $start + $limit && isset( $filter[2][$i] ); $i++ )
84                                          $msgNumber[] = $filter[2][$i];
85
86                                        if( empty( $msgNumber ) )
87                                        return( false );
88
89                                        $result = $this->get_info_msgs( array( 'folder' => $folder_name,
90                                                                           'msgs_number' => implode( ',', $msgNumber ) ) );
91
92                                        foreach( $result as $i => $val )
93                                        $result[$i] = unserialize( $val );
94
95                                }
96                                else
97                                {
98                                        $result = $this->get_range_msgs2(
99                                                array(
100                                                        'folder' => $folder_name, //INBOX
101                                                        'msg_range_begin' => $start + 1, //??
102                                                        'msg_range_end' => $start + $limit, //$limit = $_GET['rows']; // get how many rows we want to have into the grid
103                                                        'sort_box_type' => 'SORTARRIVAL',
104                                                        'search_box_type' => 'ALL',
105                                                        'sort_box_reverse' => 1
106                                                )
107                                        );
108                                }
109                                //return var_export($result);
110
111                                $response = array( "page" => $page, "total" => $total_pages, "records" => $count );
112                               
113                                for ($i=0; $i<count($result); $i++)
114                                {
115                                        $flags_enum = array('Recent', 'Unseen',  'Answered',  'Draft',  'Deleted', 'Flagged');
116
117                                        foreach ($flags_enum as $key => $flag)
118                                        {
119                                                if ( !isset($result[$i][$flag]) || !trim($result[$i][$flag]) || trim($result[$i][$flag]) == '')
120                                                        unset($flags_enum[$key]);
121
122                                                unset($result[$i][$flag]);
123                                        }
124
125                                        if (array_key_exists($i, $result))
126                                        {
127                                                $response["rows"][$i] = $result[$i];
128                                                $response["rows"][$i]['timestamp'] = ( ( $result[$i]['udate'] + $this->functions->CalculateDateOffset() ) * 1000 );
129                                                $response["rows"][$i]['flags'] = implode(',', $flags_enum);
130                                                $response["rows"][$i]['size'] = $response["rows"][$i]['Size'];
131                                                //$response["rows"][$i]['udate'] = ( $result[$i]['udate'] + $this->functions->CalculateDateOffset()  * 1000 );
132                                                unset($response["rows"][$i]['Size']);
133                                        }
134                                 }
135
136                                return $this->to_utf8($response);
137                        }
138                       
139                        /**
140                         * Filtros suportados:
141                         * - ['=', 'folderName', $X]
142                         * - [
143                         *              'AND',
144                         *              [
145                         *                      'AND',
146                         *                      ['=', 'folderName', $X],
147                         *                      ['IN', 'messageNumber', $Ys]
148                         *              ],
149                         *              ['IN', 'labelId', $Zs]
150                         * ]
151                         * - ['=', 'labelId', $X]
152                         * - [
153                         *              'AND',
154                         *              ['=', 'folderName', $X],
155                         *              ['=', 'labelId', $Y]
156                         * ]
157                         * - ['IN', 'labelId', $Ys]
158                         * - [
159                         *              'AND',
160                         *              ['=', 'folderName', $X],
161                         *              ['IN', 'labelId', $Ys]
162                         * ]                   
163                         */
164                        case 'labeled':
165                        {
166                                $result = array ( );
167                                if (isset($criteria["filter"]) && is_array($criteria['filter'])) {
168                                        //TODO - melhorar o tratamento do filter com a lista de todos os labelIds dado pelo interceptor
169                                        $map = array(
170                                                'id' => array(),
171                                                'folderName' => array(),
172                                                'messageNumber' => array(),
173                                                'labelId' => array()
174                                        );
175                                       
176                                        self::parseFilter($criteria["filter"], &$map);
177                                       
178                                        if (count($map['folderName']) == 0) {
179                                                $folders = $this->get_folders_list();
180                                                foreach ($folders as $folder)
181                                                        if (isset($folder['folder_id']))
182                                                                $map['folderName'][] = $folder['folder_id'];
183                                        }
184
185                                        foreach ($map['folderName'] as $folder) {
186                                                $this->mbox = $this->open_mbox($folder);
187                                               
188                                                foreach ($map['labelId'] as $label) {
189                                                        $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$label.'"', SE_UID);
190                                                       
191                                                        foreach ($messagesLabeleds as $messageLabeled) {
192                                                                if (count($map['messageNumber']) > 0 && !in_array($messageLabeled, $map['messageNumber']))
193                                                                        continue;
194                                                                       
195                                                                $result[] = array (
196                                                                        'id' => $folder . '/' . $messageLabeled . '#' . $label,
197                                                                        'folderName' => $folder,
198                                                                        'messageNumber' => $messageLabeled,
199                                                                        'labelId' => $label
200                                                                );
201                                                        }
202                                                }
203                                               
204                                                imap_close($this->mbox);
205                                                $this->mbox = false;
206                                        }
207                                }
208                               
209                                return $result;
210                        }
211                       
212                        case 'followupflagged':
213                        {
214                       
215                                $result = array ( );
216                                if (isset($criteria["filter"]) && is_array($criteria['filter'])) {
217                                        //TODO - melhorar o tratamento do filter com a lista de todos os labelIds dado pelo interceptor
218                                        $map = array(
219                                                'id' => array(),
220                                                'folderName' => array(),
221                                                'messageNumber' => array()
222                                        );
223                                       
224                                        self::parseFilter($criteria["filter"], &$map);
225                                       
226                                        if (empty($map['folderName'])) {
227                                                $folders = $this->get_folders_list();
228                                                foreach ($folders as $folder)
229                                                        if (isset($folder['folder_id']))
230                                                                $map['folderName'][] = $folder['folder_id'];
231                                        }
232
233                                        foreach ($map['folderName'] as $folder) {
234                                                $this->mbox = $this->open_mbox($folder);
235                                               
236                                                foreach ($map['id'] as $followupflagged) {
237                                                        $messagesFlaggeds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflag'.$followupflagged.'"', SE_UID);
238                                                       
239                                                        foreach ($messagesFlaggeds as $messageFlagged) {
240                                                                if (count($map['messageNumber']) > 0 && !in_array($messageFlagged, $map['messageNumber']))
241                                                                        continue;
242                                                                       
243                                                                $result[] = array (
244                                                                        'id' => $folder . '/' . $messageFlagged . '#' . $followupflagged,
245                                                                        'folderName' => $folder,
246                                                                        'messageNumber' => $messageFlagged
247                                                                );
248                                                        }
249                                                }
250                                               
251                                                imap_close($this->mbox);
252                                                $this->mbox = false;
253                                        }
254                                }
255                                               
256                                return $result;                         
257                        }
258                }
259    }
260
261    public function read( $URI, $justthese = false )
262    {
263
264                switch( $URI['concept'] )
265                {
266                        case 'message':
267                        {
268                                return $this->to_utf8(
269                                        $this->get_info_msg( array('msg_number'=>$URI['id'],
270                                        'msg_folder'=>str_replace( '.', $this->imap_delimiter, $justthese['context']['folder'] )) )
271                                );
272                        }
273                        case 'labeled':
274                        {
275                                /**
276                                 * id looks like 'folder/subfolder/subsubfolder/65#13', meaning messageId#labelId
277                                 */
278                                list($messageId, $labelId) = explode('#', $URI['id']);
279                                $folderName = basename($messageId);
280                                $messageNumber = dirname($messageId);
281                               
282                                $result = array();
283
284                                if ($folderName && $messageNumber && $labelId) {
285                                        $this->mbox = $this->open_mbox($folderName);
286                                        $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$labelId.'"', SE_UID);
287                                       
288                                        if (in_array($messageNumber, $messagesLabeleds)) {
289                                                $result = array (
290                                                        'id' => $URI['id'],
291                                                        'folderName' => $folderName,
292                                                        'messageNumber' => $messageNumber,
293                                                        'labelId' => $labelId
294                                                );
295                                        }
296                                        imap_close($this->mbox);
297                                        $this->mbox = false;
298                                }
299                               
300                                return $result;
301                        }
302                       
303                        case 'followupflagged':
304                        {
305                                /**
306                                 * id looks like 'folder/subfolder/subsubfolder/65#13', meaning messageId#followupflaggedId
307                                 */
308                                list($messageId, $followupflaggedId) = explode('#', $URI['id']);
309                                $folderName = basename($messageId);
310                                $messageNumber = dirname($messageId);
311                               
312                                $result = array();
313
314                                if ($folderName && $messageNumber && $followupflaggedId) {
315                                        $this->mbox = $this->open_mbox($folderName);
316                                        $messagesFlaggeds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflag'.$followupflaggedId.'"', SE_UID);
317                                       
318                                        if (in_array($messageNumber, $messagesFlaggeds)) {
319                                                $result = array (
320                                                        'id' => $URI['id'],
321                                                        'folderName' => $folderName,
322                                                        'messageNumber' => $messageNumber
323                                                );
324                                        }
325                                        imap_close($this->mbox);
326                                        $this->mbox = false;
327                                }
328                               
329                                return $result;
330                        }
331                }
332    }
333
334    public function create( $URI, $data)
335    {
336                switch( $URI['concept'] )
337                {
338                        case 'labeled':
339                        {
340                                if (isset($data['folderName']) && isset($data['messageNumber']) && isset($data['labelId'])) {
341                                        $this->mbox = $this->open_mbox($data['folderName']);
342                                        imap_setflag_full($this->mbox, $data['messageNumber'], '$Label' . $data['labelId'], ST_UID);
343
344                                        imap_close($this->mbox);
345                                        $this->mbox = false;
346
347                                        return array ('id' => $data['folderName'].'/'.$data['messageNumber'].'#'.$data['labelId']);
348                                }
349                                return array ();
350                        }
351                        case 'followupflagged':
352                        {
353                                //deve ser gravado no banco primeiro, obtido o id e, depois, gravado no imap passando o id no parametro $data
354                                if (isset($data['folderName']) && isset($data['messageNumber']) && isset($data['id'])) {
355                                        list($messageId, $followupflaggedId) = explode('#', $data['id']);
356                                       
357                                        $this->mbox = $this->open_mbox($data['folderName']);
358                                        imap_setflag_full($this->mbox, $data['messageNumber'], '$Followupflag' . $followupflaggedId, ST_UID);
359
360                                        imap_close($this->mbox);
361                                        $this->mbox = false;
362
363                                        return array ('id' => $data['id']);
364                                }
365                                return array ();
366                        }
367                }
368        }
369
370    public function delete( $URI, $justthese = false, $criteria = false )
371    {
372                switch( $URI['concept'] )
373                {
374                        case 'labeled':
375                        {
376                                list($messageId, $labelId) = explode('#', $URI['id']);
377                                $folderName = dirname($messageId);
378                                $messageNumber = basename($messageId);
379
380                                if ($folderName && $messageNumber && $labelId) {
381                                        $this->mbox = $this->open_mbox($folderName);
382                                        imap_clearflag_full($this->mbox, $messageNumber, '$Label' . $labelId, ST_UID);
383
384                                        imap_close($this->mbox);
385                                        $this->mbox = false;
386                                }
387                        }
388                        case 'followupflagged':
389                        {
390                                list($messageId, $followupflaggedId) = explode('#', $URI['id']);
391                                $folderName = basename($messageId);
392                                $messageNumber = dirname($messageId);
393                       
394                                if ($folderName && $messageNumber && $followupflaggedId) {
395                                        $this->mbox = $this->open_mbox($folderName);
396                                        imap_clearflag_full($this->mbox, $messageNumber, '$Followupflag' . $followupflaggedId, ST_UID);
397
398                                        imap_close($this->mbox);
399                                        $this->mbox = false;
400                                }
401                        }
402                }
403
404                //TODO - return
405        }
406
407    public function deleteAll( $URI, $justthese = false, $criteria = false ) // avaliar
408    {}
409
410    public function update( $URI, $data, $criteria = false )
411    {
412                /**
413                 * Os únicos atributos que podem ser alterados no IMAP são folderName e messageId,
414                 * porém a operação de update desses atributos não faz sentido para o usuário da DataLayer,
415                 * pois na prática elas são executadas através das operações de CREATE e DELETE.
416                 * Assim, para os conceitos "labeled" e "followupflagged", só faz sentido o update de
417                 * atributos gravados no banco de dados e nunca no IMAP.
418                 */
419        }
420
421//     public function retrieve( $concept, $id, $parents, $justthese = false, $criteria = false )
422//     {
423//                      return $this->read( array( 'id' => $id,
424//                          'concept' => $concept,
425//                          'context' => $parents ), $justthese );
426//     }
427
428    public function replace( $URI, $data, $criteria = false )
429    {}
430
431    public function close()
432    {}
433
434    public function setup()
435    {}
436
437    public function commit( $uri )
438    { return( true ); }
439
440    public function rollback( $uri )
441    {}
442
443    public function begin( $uri )
444    {}
445
446
447    public function teardown()
448    {}
449
450    function to_utf8($in)
451    {
452                if (is_array($in)) {
453                        foreach ($in as $key => $value) {
454                                $out[$this->to_utf8($key)] = $this->to_utf8($value);
455                        }
456                } elseif(is_string($in)) {
457                                return mb_convert_encoding( $in , 'UTF-8' , 'UTF-8 , ISO-8859-1' );
458                } else {
459                        return $in;
460                }
461                return $out;
462    }
463       
464           
465    private static function parseFilter( $filter ,&$map){
466               
467                if( !is_array( $filter ) || count($filter) <= 0) return null;
468                                       
469                $op = array_shift( $filter );
470                switch(strtolower($op))
471                {
472                        case 'and': {
473                                foreach ($filter as $term)
474                                        self::parseFilter($term ,&$map);
475                                return;
476                        }
477                        case 'in': {
478                                if(is_array($map[$filter[0]]) && is_array($filter[1]))
479                                        $map[$filter[0]] = array_unique(array_merge($map[$filter[0]], $filter[1]));
480                                return;
481                        }
482                        case '=': {
483                                $map[$filter[0]][] = $filter[1];
484                        }
485                }
486        }
487       
488}
Note: See TracBrowser for help on using the repository browser.