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

Revision 6067, 23.8 KB checked in by marcieli, 12 years ago (diff)

Ticket #2633 - Corrigido ao sinalizar varias mensagens, excluia e criava padrao.

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                                // do not put $limit*($page - 1)
63                                //end: for grid
64                               
65                               
66                                /**
67                                 * Trata o caso específico de retorno do atributo messageId
68                                 *
69                                 * TODO - refazer todo a operação find do conceito message, uma vez que esta
70                                 * foi desenvolvida quando a nova API ainda era muito imatura e se encontra
71                                 * muito acoplada à estrutura de retorno esperada pelo plugin jqGrid
72                                 */
73                                if ( $justthese )
74                                {
75                                        if ($justthese[0] == 'messageId') {
76                                                $map = array(
77                                                        'folderName' => array(),
78                                                        'messageNumber' => array()
79                                                );
80                                               
81                                                self::parseFilter($criteria["filter"], &$map);
82                                               
83                                                if (count($map['folderName']) == 0) {
84                                                        $folders = $this->get_folders_list();
85                                                        foreach ($folders as $folder)
86                                                                if (isset($folder['folder_id']))
87                                                                        $map['folderName'][] = $folder['folder_id'];
88                                                }
89                                               
90                                                $result = array();
91                                                foreach ($map['folderName'] as $folder) {
92                                                        $this->mbox = $this->open_mbox($folder);
93
94                                                        /**
95                                                         * Se não foi passado messageNumber no filtro,
96                                                         * busca todas as mensagens de cada pasta
97                                                         */
98                                                        $messages = empty($map['messageNumber']) ? '1:*' : implode(',', $map['messageNumber']);
99                                                        $sequenceType = empty($map['messageNumber']) ? 0 : FT_UID;
100
101                                                        $headers = imap_fetch_overview($this->mbox, $messages, $sequenceType);
102                                                        foreach ($headers as $h) {
103                                                                $result[] = array ( 'messageId' => $h->message_id );
104                                                        }
105                                                                                                               
106                                                        imap_close($this->mbox);
107                                                        $this->mbox = false;
108                                                }
109                                                return $result;
110                                        }
111                                }
112                               
113                                if( $filter )
114                                {
115                                        if( $filter[0] !== 'msgNumber' )
116                                        {
117                                        for( $i = 0; $i < count($filter); $i++ )
118                                        {
119                                                if( count( $filter[$i] ) === 4 )
120                                                $criteria['isExact'] = ( array_shift( $filter[$i] ) === 'AND' );
121
122                                                $criteria[ $filter[$i][0] ] = array( 'criteria' => $filter[$i][2], 'filter' => $filter[$i][1] );
123                                        }
124
125                                        return $this->searchSieveRule($criteria);
126                                        }
127
128                                        $msgNumber = array();
129
130                                        for( $i = $start; $i < $start + $limit && isset( $filter[2][$i] ); $i++ )
131                                          $msgNumber[] = $filter[2][$i];
132
133                                        if( empty( $msgNumber ) )
134                                        return( false );
135
136                                        $result = $this->get_info_msgs( array( 'folder' => $folder_name,
137                                                                           'msgs_number' => implode( ',', $msgNumber ) ) );
138
139                                        foreach( $result as $i => $val )
140                                        $result[$i] = unserialize( $val );
141
142                                }
143                                else
144                                {
145                                        $result = $this->get_range_msgs2(
146                                                array(
147                                                        'folder' => $folder_name, //INBOX
148                                                        'msg_range_begin' => $start + 1, //??
149                                                        'msg_range_end' => $start + $limit, //$limit = $_GET['rows']; // get how many rows we want to have into the grid
150                                                        'sort_box_type' => 'SORTARRIVAL',
151                                                        'search_box_type' => 'ALL',
152                                                        'sort_box_reverse' => 1
153                                                )
154                                        );
155                                }
156                                //return var_export($result);
157
158                                $response = array( "page" => $page, "total" => $total_pages, "records" => $count );
159                               
160                                for ($i=0; $i<count($result); $i++)
161                                {
162                                        $flags_enum = array('Unseen'=> 1,  'Answered'=> 1, 'Forwarded'=> 1, 'Flagged'=> 1, 'Recent'=> 1, 'Draft'=> 1 );
163
164                                        foreach ($flags_enum as $key => $flag)
165                                        {
166                                                if ( !isset($result[$i][$key]) || !trim($result[$i][$key]) || trim($result[$i][$key]) == '') 
167                                                        $flags_enum[$key] = 0;
168
169                                                unset($result[$i][$flag]);
170                                        }
171
172                                        if (array_key_exists($i, $result))
173                                        {
174                                                $response["rows"][$i] = $result[$i];
175                                                $response["rows"][$i]['timestamp'] = ( ( $result[$i]['udate'] + $this->functions->CalculateDateOffset() ) * 1000 );
176                                                $response["rows"][$i]['flags'] = implode(',', $flags_enum);
177                                                $response["rows"][$i]['size'] = $response["rows"][$i]['Size'];
178                                                $response["rows"][$i]['folder'] = $folder_name;
179                                                //$response["rows"][$i]['udate'] = ( $result[$i]['udate'] + $this->functions->CalculateDateOffset()  * 1000 );
180                                                unset($response["rows"][$i]['Size']);
181                                        }
182                                 }
183
184                                return $this->to_utf8($response);
185                        }
186                       
187                        /**
188                         * Filtros suportados:
189                         * - ['=', 'folderName', $X]
190                         * - [
191                         *              'AND',
192                         *              [
193                         *                      'AND',
194                         *                      ['=', 'folderName', $X],
195                         *                      ['IN', 'messageNumber', $Ys]
196                         *              ],
197                         *              ['IN', 'labelId', $Zs]
198                         * ]
199                         * - ['=', 'labelId', $X]
200                         * - [
201                         *              'AND',
202                         *              ['=', 'folderName', $X],
203                         *              ['=', 'labelId', $Y]
204                         * ]
205                         * - ['IN', 'labelId', $Ys]
206                         * - [
207                         *              'AND',
208                         *              ['=', 'folderName', $X],
209                         *              ['IN', 'labelId', $Ys]
210                         * ]                   
211                         */
212                        case 'labeled':
213                        {
214                                $result = array ( );
215                                if (isset($criteria["filter"]) && is_array($criteria['filter'])) {
216                                        //TODO - melhorar o tratamento do filter com a lista de todos os labelIds dado pelo interceptor
217                                        $map = array(
218                                                'id' => array(),
219                                                'folderName' => array(),
220                                                'messageNumber' => array(),
221                                                'labelId' => array()
222                                        );
223                                       
224                                        self::parseFilter($criteria["filter"], &$map);
225                                       
226                                        if (count($map['folderName']) == 0) {
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['labelId'] as $label) {
237                                                        $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$label.'"', SE_UID);
238                                                       
239                                                        foreach ($messagesLabeleds as $messageLabeled) {
240                                                                if (count($map['messageNumber']) > 0 && !in_array($messageLabeled, $map['messageNumber']))
241                                                                        continue;
242                                                                       
243                                                                $result[] = array (
244                                                                        'id' => $folder . '/' . $messageLabeled . '#' . $label,
245                                                                        'folderName' => $folder,
246                                                                        'messageNumber' => $messageLabeled,
247                                                                        'labelId' => $label
248                                                                );
249                                                        }
250                                                }
251                                               
252                                                imap_close($this->mbox);
253                                                $this->mbox = false;
254                                        }
255                                }
256                               
257                                return $result;
258                        }
259                       
260                        case 'followupflagged':
261                        {                                       
262                                $result = array ( );
263
264                                $map = array(
265                                        //'id' => array(),
266                                        'folderName' => array(),
267                                        'messageNumber' => array(),
268                                        'messageId' => array()
269                                );
270                               
271                                self::parseFilter($criteria["filter"], &$map);
272       
273                                if (empty($map['folderName'])) {
274                                        $folders = $this->get_folders_list();
275                                        foreach ($folders as $folder)
276                                                if (isset($folder['folder_id']))
277                                                        $map['folderName'][] = $folder['folder_id'];
278                                }
279                               
280                                $messagesIds = $map['messageId'];
281
282                                foreach ($map['folderName'] as $folder) {
283                                        $messages = array();
284                                       
285                                        $this->mbox = $this->open_mbox($folder);
286
287                                        /**
288                                         * Se é uma busca por messageId
289                                         */
290                                        if (!empty($map['messageId'])) {
291                                                       
292                                                foreach ($messagesIds as $k => $v) {
293
294                                                        $r = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged" TEXT "Message-Id: '.$v.'"', SE_UID);
295
296
297                                                        if ($r) {
298
299                                                                $messages = array_merge($messages, $r);
300                                                                unset($messagesIds[$k]);
301                                                               
302                                                        }
303                                                }
304
305                                        /**
306                                         * Se é uma busca por messageNumber.
307                                         * Lembrando que, neste caso, só deve ser suportada uma única pasta no filtro.
308                                         */
309                                        } else {
310                                                $messages = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged"', SE_UID);
311                                        }
312
313                                        /**
314                                         * Se é uma busca por messageId, deve ser comparado com os messageNumbers
315                                         * passados no filtro, se houverem.
316                                         */
317                                        if (!empty($map['messageNumber'])) {
318                                                foreach ($messages as $k => $m)
319                                                        if (!in_array($m, $map['messageNumber']))
320                                                                unset($messages[$k]);
321                                        }
322
323                                        /**
324                                         * Adicionar demais atributos às mensagens para retorno
325                                         */
326
327                                        foreach ($messages as $k => $m) {
328                                                $headers = imap_fetch_overview($this->mbox, $m, FT_UID);
329
330                                                $result[] = array (
331                                                        'messageId' => $headers[0]->message_id,
332                                                        'messageNumber' => $m,
333                                                        'folderName' => $folder
334                                                );
335                                        }
336
337                                        imap_close($this->mbox);
338                                        $this->mbox = false;
339                                       
340                                        /**
341                                         * Se é uma busca por messageId e todos os messageIds foram econstrados:
342                                         * Stop searching in all folders
343                                         */
344                                        if (!empty($map['messageId']) && empty($messagesIds))
345                                                break;
346                                }
347                               
348                                if ($this->mbox) {
349                                        imap_close($this->mbox);
350                                        $this->mbox = false;
351                                }
352
353                                return $result;
354                               
355                        } //CASE 'followupflag'
356                }
357    }
358
359    public function read( $URI, $justthese = false )
360    {
361
362                switch( $URI['concept'] )
363                {
364                        case 'message':
365                        {
366                                return $this->to_utf8(
367                                        $this->get_info_msg( array('msg_number'=>$URI['id'],
368                                        'msg_folder'=>str_replace( '.', $this->imap_delimiter, $justthese['context']['folder'] )) )
369                                );
370                        }
371                        case 'labeled':
372                        {
373                                /**
374                                 * id looks like 'folder/subfolder/subsubfolder/65#13', meaning messageId#labelId
375                                 */
376                                list($messageId, $labelId) = explode('#', $URI['id']);
377                                $folderName = basename($messageId);
378                                $messageNumber = dirname($messageId);
379                               
380                                $result = array();
381
382                                if ($folderName && $messageNumber && $labelId) {
383                                        $this->mbox = $this->open_mbox($folderName);
384                                        $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$labelId.'"', SE_UID);
385                                       
386                                        if (in_array($messageNumber, $messagesLabeleds)) {
387                                                $result = array (
388                                                        'id' => $URI['id'],
389                                                        'folderName' => $folderName,
390                                                        'messageNumber' => $messageNumber,
391                                                        'labelId' => $labelId
392                                                );
393                                        }
394                                        imap_close($this->mbox);
395                                        $this->mbox = false;
396                                }
397                               
398                                return $result;
399                        }
400                       
401                        case 'followupflagged':
402                        {
403                       
404                                /**
405                                 * identifica se o formato de ID é "folder/subfolder/subsubfolder/<messageNumber>" ou "<message-id>"
406                                 */
407                                $folderName = $messageNumber = false;
408                                if(!($messageHasId = preg_match('/<.*>/', $URI['id']))) {
409                                        $folderName = dirname($URI['id']);
410                                        $messageNumber = basename($URI['id']);
411                                }
412
413                                $result = array();
414                                if ($folderName && $messageNumber) {
415
416                                        $this->mbox = $this->open_mbox($folderName);
417                                        $r = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged"', SE_UID);
418
419                                        if (in_array($messageNumber, $r)) {
420                                                $headers = imap_fetch_overview($this->mbox, $messageNumber, FT_UID);
421                                                       
422                                                $result = array (
423                                                        'messageId' => $headers[0]->message_id,
424                                                        'messageNumber' => $messageNumber,
425                                                        'folderName' => $folderName
426                                                );
427                                        }
428                                       
429                                        imap_close($this->mbox);
430                                        $this->mbox = false;
431                               
432                                } else {
433                                        /**
434                                         * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela,
435                                         * senão busca em todas.
436                                         */
437                                       
438                                        $folders = array ();
439                                        if ($folderName) {
440                                                $folders = array ($folderName);
441                                        } else {
442                                                $folder_list = $this->get_folders_list();
443                                                foreach ($folder_list as $folder)
444                                                        if (isset($folder['folder_id']))
445                                                                $folders[] = $folder['folder_id'];
446                                        }
447                                       
448                                        foreach ($folders as $folder) {
449                                               
450                                                $this->mbox = $this->open_mbox($folder);
451                                               
452                                                if ($messages = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged" TEXT "'.$URI['id'].'"', SE_UID)) {
453                               
454                                                        $result = array (
455                                                                'messageId' => $URI['id'],
456                                                                'messageNumber' => $messages[0],
457                                                                'folderName' => $folder
458                                                        );
459                                                       
460                                                        /**
461                                                         * Stop searching in all folders
462                                                         */
463                                                        break;
464                                                }
465                                               
466                                                imap_close($this->mbox);
467                                                $this->mbox = false;
468                                        }
469                                }
470                               
471                                if ($this->mbox) {
472                                        imap_close($this->mbox);
473                                        $this->mbox = false;
474                                }
475                               
476                                return $result;
477                        }
478                }
479    }
480
481    public function create($URI, &$data)
482    {               
483                switch( $URI['concept'] )
484                {
485                        case 'labeled':
486                        {
487                                if (isset($data['folderName']) && isset($data['messageNumber']) && isset($data['labelId'])) {
488                                        $this->mbox = $this->open_mbox($data['folderName']);
489                                        imap_setflag_full($this->mbox, $data['messageNumber'], '$Label' . $data['labelId'], ST_UID);
490
491                                        imap_close($this->mbox);
492                                        $this->mbox = false;
493
494                                        return array ('id' => $data['folderName'].'/'.$data['messageNumber'].'#'.$data['labelId']);
495                                }
496                                return array ();
497                        }
498                        case 'followupflagged':
499                        {
500                                //deve ser gravado primeiro no imap, obtido o message-id e, depois gravado no banco
501                               
502                                if (isset($data['folderName']) && isset($data['messageNumber'])) {
503                                       
504                                        $this->mbox = $this->open_mbox($data['folderName']);
505                                        $s = imap_setflag_full($this->mbox, $data['messageNumber'], '$Followupflagged', ST_UID);
506                                       
507                                        $headers = imap_fetch_overview($this->mbox, $data['messageNumber'], FT_UID);
508                                       
509                                        $data['messageId'] = $headers[0]->message_id;
510                                                       
511                                        imap_close($this->mbox);
512                                        $this->mbox = false;
513
514                                        return ($s) ? $data : array();
515
516                                } else if (isset($data['messageId'])) {
517                                        /**
518                                         * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela,
519                                         * senão busca em todas.
520                                         */
521                                        $folders = array ();
522                                        if (isset($data['folderName'])) {
523                                                $folders = array ($data['folderName']);
524                                        } else {
525                                                $folder_list = $this->get_folders_list();
526                                                foreach ($folder_list as $folder)
527                                                        if (isset($folder['folder_id']))
528                                                                $folders[] = $folder['folder_id'];
529                                        }
530                                       
531                                        foreach ($folders as $folder) {
532                                               
533                                                $this->mbox = $this->open_mbox($folder);
534                                                if ($messages = imap_search($this->mbox, 'TEXT "'.$data['messageId'].'"', SE_UID)) {
535                                                       
536                                                        $s = imap_setflag_full($this->mbox, $messages[0], '$Followupflagged', ST_UID);
537                                                       
538                                                        imap_close($this->mbox);
539                                                        $this->mbox = false;
540                                                       
541                                                        /**
542                                                         * Stop searching in all folders
543                                                         */
544                                                        return $data;
545                                                }
546                                               
547                                                imap_close($this->mbox);
548                                                $this->mbox = false;
549                                        }
550                                }
551                                return array ();
552                        }
553                       
554                        case 'message':
555                        {
556                                require_once ROOTPATH.'/library/uuid/class.uuid.php';
557                               
558                                $GLOBALS['phpgw_info']['flags'] = array( 'noheader' => true, 'nonavbar' => true,'currentapp' => 'expressoMail1_2','enable_nextmatchs_class' => True );
559                                $return = array();
560
561                                require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
562                                $mailService = ServiceLocator::getService('mail');
563
564                                $msg_uid = $data['msg_id'];
565                                $body = $data['body'];
566                                $body = str_replace("%nbsp;","&nbsp;",$body);
567                                $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );                                       
568
569                                $folder = mb_convert_encoding($data['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");
570                                $folder = @preg_replace('/INBOX[\/.]/i', "INBOX".$this->imap_delimiter, $folder);
571
572                                /**
573                                * Gera e preenche o field Message-Id do header
574                                */
575                                $mailService->addHeaderField('Message-Id', UUID::generate( UUID::UUID_RANDOM, UUID::FMT_STRING ) . '@Draft');
576
577                                $mailService->addTo(mb_convert_encoding(($data['input_to']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
578                                $mailService->addCc( mb_convert_encoding(($data['input_cc']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
579                                $mailService->addBcc(mb_convert_encoding(($data['input_cco']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
580                                $mailService->setSubject(mb_convert_encoding(($data['input_subject']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
581                               
582                                if(isset($data['input_important_message']))
583                                        $mailService->addHeaderField('Importance','High');
584
585                                if(isset($data['input_return_receipt']))
586                                        $mailService->addHeaderField('Disposition-Notification-To', Config::me('mail'));
587
588                                $isHTML = ( isset($data['type']) && $data['type'] == 'html' )?  true : false;
589
590                                if (!$body) $body = ' ';
591
592
593                                $mbox_stream = $this->open_mbox($folder);
594
595                                $attachment = json_decode($data['attachments'],TRUE);
596
597
598                                foreach ($attachment as &$value)
599                                {
600                                        if((int)$value > 0) //BD attachment
601                                        {
602                                                $att = Controller::read(array('id'=> $value , 'concept' => 'mailAttachment'));
603
604                                                if($att['disposition'] == 'embedded')
605                                                {
606                                                        $body = str_replace('"../prototype/getArchive.php?mailAttachment='.$att['id'].'"', $att['name'], $body);
607                                                        $mailService->addStringImage(base64_decode($att['source']), $att['type'], $att['name']);
608                                                }
609                                                else
610                                                        $mailService->addStringAttachment(base64_decode($att['source']), $att['name'], $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
611
612                                                unset($att);
613                                        }
614                                        else
615                                        {
616                                                $value = json_decode($value, true);
617
618                                                switch ($value['type']) {
619                                                        case 'imapPart':
620                                                                $att = $this->getForwardingAttachment($value['folder'],$value['uid'], $value['part']);
621                                                                if(strstr($body,'<img src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'" />') !== false)//Embeded IMG
622                                                                {   
623                                                                        $body = str_ireplace('<img src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'" />' , '<img src="'.$att['name'].'" />', $body);
624                                                                        $mailService->addStringImage($att['source'], $att['type'], $att['name']);
625                                                                }
626                                                                else
627                                                                        $mailService->addStringAttachment($att['source'], $att['name'], $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
628                                                                unset($att);
629                                                                break;
630                                                        case 'imapMSG':
631                                                                $sub =  $value['name'] ? $value['name'].'.eml' :'no title.eml';
632                                                                $mbox_stream = $this->open_mbox($value['folder']);
633                                                                $rawmsg = $this->getRawHeader($value['uid']) . "\r\n\r\n" . $this->getRawBody($value['uid']);
634                                                                $mailService->addStringAttachment($rawmsg, $sub, 'message/rfc822', '7bit', 'attachment' );
635                                                                unset($rawmsg);
636                                                                break;
637
638                                                        default:
639                                                        break;
640                                                }
641                                        }
642
643                                }
644
645                                if($isHTML) $mailService->setBodyHtml($body); else $mailService->setBodyText($body);
646
647                                if(imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft"))
648                                {
649                                        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
650                                        $return['id'] = $status->uidnext - 1;
651
652                                        if($data['uidsSave'] )
653                                                $this->delete_msgs(array('folder'=> $folder , 'msgs_number' => $data['uidsSave']));
654                                }
655
656                                if($mbox_stream) imap_close($mbox_stream);
657
658                                return $return;
659                        }
660                }
661        }
662
663    public function delete( $URI, $justthese = false, $criteria = false )
664    {
665                switch( $URI['concept'] )
666                {
667                        case 'labeled':
668                        {
669                                list($messageId, $labelId) = explode('#', $URI['id']);
670                                $folderName = dirname($messageId);
671                                $messageNumber = basename($messageId);
672
673                                if ($folderName && $messageNumber && $labelId) {
674                                        $this->mbox = $this->open_mbox($folderName);
675                                        imap_clearflag_full($this->mbox, $messageNumber, '$Label' . $labelId, ST_UID);
676
677                                        imap_close($this->mbox);
678                                        $this->mbox = false;
679                                }
680                        }
681                        case 'followupflagged':
682                        {
683                                $map = array(
684                                        'folderName' => array(),
685                                        'messageNumber' => array(),
686                                        'messageId' => array()
687                                );
688                               
689                                self::parseFilter($criteria["filter"], &$map);
690                               
691                                if (!$map['folderName']) {
692                                        $folders = array ();
693                                       
694                                        $folder_list = $this->get_folders_list();
695                                        foreach ($folder_list as $folder)
696                                                if (isset($folder['folder_id']))
697                                                        $folders[] = $folder['folder_id'];
698                                        $map['folderName'] = $folders;
699                                }
700
701                                $messagesIds = $map['messageId'];
702
703                                foreach ($map['folderName'] as $folder) {
704                                        $messages = array();
705                                       
706                                        $this->mbox = $this->open_mbox($folder);
707                               
708                                        /**
709                                         * Se é uma busca por messageId
710                                         */
711                                        if (!empty($map['messageId'])) {
712                                                       
713                                                foreach ($messagesIds as $k => $v) {
714                                                        $r = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged" TEXT "'.$v.'"', SE_UID);
715
716                                                        if ($r) {
717                                                                $messages = $messages + $r;
718                                                                unset($messagesIds[$k]);       
719                                                        }
720                                                }
721
722                                        /**
723                                         * Se é uma busca por messageNumber.
724                                         * Lembrando que, neste caso, só deve ser suportada uma única pasta no filtro.
725                                         */
726                                        } else {
727                                                $messages = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged"', SE_UID);
728                                        }
729
730                                        /**
731                                         * Se é uma busca por messageId, deve ser comparado com os messageNumbers
732                                         * passados no filtro, se houverem.
733                                         */
734                                        if (!empty($map['messageNumber'])) {
735                                                foreach ($messages as $k => $m)
736                                                        if (!in_array($m, $map['messageNumber']))
737                                                                unset($messages[$k]);
738                                        }
739
740                                        $s = true;
741                                        foreach ($messages as $k => $m) {                                               
742                                                $s = imap_clearflag_full($this->mbox, $m, '$Followupflagged', ST_UID) && $s;
743                                        }
744
745                                        imap_close($this->mbox);
746                                        $this->mbox = false;
747                                       
748                                        /**
749                                         * Se é uma busca por messageId e todos os messageIds foram econstrados:
750                                         * Stop searching in all folders
751                                         */
752                                        if (!empty($map['messageId']) && empty($messagesIds))
753                                                break;
754                                }
755                               
756                                return $s;
757                        }
758                }
759
760                //TODO - return
761        }
762
763    public function deleteAll( $URI, $justthese = false, $criteria = false )
764    {
765                /**
766                 * TODO - implementar a deleção de todos os followupflaggeds conforme filtro
767                 */
768        }
769
770    public function update( $URI, $data, $criteria = false )
771    {
772                /**
773                 * Os únicos atributos da sinalização presentes no IMAP são folderName, messageNumber e messageId,
774                 * porém a operação de update desses atributos não faz sentido para o usuário da DataLayer,
775                 * pois na prática elas são executadas através das operações de CREATE e DELETE.
776                 * Assim, para os conceitos "labeled" e "followupflagged", só faz sentido o update de
777                 * atributos gravados no banco de dados e nunca no IMAP.
778                 */
779        }
780
781//     public function retrieve( $concept, $id, $parents, $justthese = false, $criteria = false )
782//     {
783//                      return $this->read( array( 'id' => $id,
784//                          'concept' => $concept,
785//                          'context' => $parents ), $justthese );
786//     }
787
788    public function replace( $URI, $data, $criteria = false )
789    {}
790
791    public function close()
792    {}
793
794    public function setup()
795    {}
796
797    public function commit( $uri )
798    { return( true ); }
799
800    public function rollback( $uri )
801    {}
802
803    public function begin( $uri )
804    {}
805
806
807    public function teardown()
808    {}
809
810    function to_utf8($in)
811    {
812                if (is_array($in)) {
813                        foreach ($in as $key => $value) {
814                                $out[$this->to_utf8($key)] = $this->to_utf8($value);
815                        }
816                } elseif(is_string($in)) {
817                                return mb_convert_encoding( $in , 'UTF-8' , 'UTF-8 , ISO-8859-1' );
818                } else {
819                        return $in;
820                }
821                return $out;
822    }
823       
824           
825    private static function parseFilter($filter ,&$map){
826               
827                if( !is_array( $filter ) || count($filter) <= 0) return null;
828                                       
829                $op = array_shift( $filter );
830                switch(strtolower($op))
831                {
832                        case 'and': {
833                                foreach ($filter as $term)
834                                        self::parseFilter($term ,&$map);
835                                return;
836                        }
837                        case 'in': {
838                                if(is_array($map[$filter[0]]) && is_array($filter[1]))
839                                        $map[$filter[0]] = array_unique(array_merge($map[$filter[0]], $filter[1]));
840                                return;
841                        }
842                        case '=': {
843                                $map[$filter[0]][] = $filter[1];
844                        }
845                }
846        }
847
848}
Note: See TracBrowser for help on using the repository browser.