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

Revision 5989, 23.7 KB checked in by adriano, 12 years ago (diff)

Ticket #2633 - correcao nos interceptors de consistencia para a funcionalidade de sinalizadores

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                                                        $r = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged" TEXT "'.$v.'"', SE_UID);
294
295                                                        if ($r) {
296                                                                $messages = $messages + $r;
297                                                                unset($messagesIds[$k]);       
298                                                        }
299                                                }
300
301                                        /**
302                                         * Se é uma busca por messageNumber.
303                                         * Lembrando que, neste caso, só deve ser suportada uma única pasta no filtro.
304                                         */
305                                        } else {
306                                                $messages = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged"', SE_UID);
307                                        }
308
309                                        /**
310                                         * Se é uma busca por messageId, deve ser comparado com os messageNumbers
311                                         * passados no filtro, se houverem.
312                                         */
313                                        if (!empty($map['messageNumber'])) {
314                                                foreach ($messages as $k => $m)
315                                                        if (!in_array($m, $map['messageNumber']))
316                                                                unset($messages[$k]);
317                                        }
318
319                                        /**
320                                         * Adicionar demais atributos às mensagens para retorno
321                                         */
322                                        foreach ($messages as $k => $m) {
323                                                $headers = imap_fetch_overview($this->mbox, $m, FT_UID);
324                                                       
325                                                $result[] = array (
326                                                        'messageId' => $headers[0]->message_id,
327                                                        'messageNumber' => $m,
328                                                        'folderName' => $folder
329                                                );
330                                        }
331
332                                        imap_close($this->mbox);
333                                        $this->mbox = false;
334                                       
335                                        /**
336                                         * Se é uma busca por messageId e todos os messageIds foram econstrados:
337                                         * Stop searching in all folders
338                                         */
339                                        if (!empty($map['messageId']) && empty($messagesIds))
340                                                break;
341                                }
342                               
343                                if ($this->mbox) {
344                                        imap_close($this->mbox);
345                                        $this->mbox = false;
346                                }
347
348                                return $result;
349                               
350                        } //CASE 'followupflag'
351                }
352    }
353
354    public function read( $URI, $justthese = false )
355    {
356
357                switch( $URI['concept'] )
358                {
359                        case 'message':
360                        {
361                                return $this->to_utf8(
362                                        $this->get_info_msg( array('msg_number'=>$URI['id'],
363                                        'msg_folder'=>str_replace( '.', $this->imap_delimiter, $justthese['context']['folder'] )) )
364                                );
365                        }
366                        case 'labeled':
367                        {
368                                /**
369                                 * id looks like 'folder/subfolder/subsubfolder/65#13', meaning messageId#labelId
370                                 */
371                                list($messageId, $labelId) = explode('#', $URI['id']);
372                                $folderName = basename($messageId);
373                                $messageNumber = dirname($messageId);
374                               
375                                $result = array();
376
377                                if ($folderName && $messageNumber && $labelId) {
378                                        $this->mbox = $this->open_mbox($folderName);
379                                        $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$labelId.'"', SE_UID);
380                                       
381                                        if (in_array($messageNumber, $messagesLabeleds)) {
382                                                $result = array (
383                                                        'id' => $URI['id'],
384                                                        'folderName' => $folderName,
385                                                        'messageNumber' => $messageNumber,
386                                                        'labelId' => $labelId
387                                                );
388                                        }
389                                        imap_close($this->mbox);
390                                        $this->mbox = false;
391                                }
392                               
393                                return $result;
394                        }
395                       
396                        case 'followupflagged':
397                        {
398                       
399                                /**
400                                 * identifica se o formato de ID é "folder/subfolder/subsubfolder/<messageNumber>" ou "<message-id>"
401                                 */
402                                $folderName = $messageNumber = false;
403                                if(!($messageHasId = preg_match('/<.*>/', $URI['id']))) {
404                                        $folderName = dirname($URI['id']);
405                                        $messageNumber = basename($URI['id']);
406                                }
407
408                                $result = array();
409                                if ($folderName && $messageNumber) {
410
411                                        $this->mbox = $this->open_mbox($folderName);
412                                        $r = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged"', SE_UID);
413
414                                        if (in_array($messageNumber, $r)) {
415                                                $headers = imap_fetch_overview($this->mbox, $messageNumber, FT_UID);
416                                                       
417                                                $result = array (
418                                                        'messageId' => $headers[0]->message_id,
419                                                        'messageNumber' => $messageNumber,
420                                                        'folderName' => $folderName
421                                                );
422                                        }
423                                       
424                                        imap_close($this->mbox);
425                                        $this->mbox = false;
426                               
427                                } else {
428                                        /**
429                                         * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela,
430                                         * senão busca em todas.
431                                         */
432                                       
433                                        $folders = array ();
434                                        if ($folderName) {
435                                                $folders = array ($folderName);
436                                        } else {
437                                                $folder_list = $this->get_folders_list();
438                                                foreach ($folder_list as $folder)
439                                                        if (isset($folder['folder_id']))
440                                                                $folders[] = $folder['folder_id'];
441                                        }
442                                       
443                                        foreach ($folders as $folder) {
444                                               
445                                                $this->mbox = $this->open_mbox($folder);
446                                               
447                                                if ($messages = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged" TEXT "'.$URI['id'].'"', SE_UID)) {
448                               
449                                                        $result = array (
450                                                                'messageId' => $URI['id'],
451                                                                'messageNumber' => $messages[0],
452                                                                'folderName' => $folder
453                                                        );
454                                                       
455                                                        /**
456                                                         * Stop searching in all folders
457                                                         */
458                                                        break;
459                                                }
460                                               
461                                                imap_close($this->mbox);
462                                                $this->mbox = false;
463                                        }
464                                }
465                               
466                                if ($this->mbox) {
467                                        imap_close($this->mbox);
468                                        $this->mbox = false;
469                                }
470                               
471                                return $result;
472                        }
473                }
474    }
475
476    public function create($URI, &$data)
477    {               
478                switch( $URI['concept'] )
479                {
480                        case 'labeled':
481                        {
482                                if (isset($data['folderName']) && isset($data['messageNumber']) && isset($data['labelId'])) {
483                                        $this->mbox = $this->open_mbox($data['folderName']);
484                                        imap_setflag_full($this->mbox, $data['messageNumber'], '$Label' . $data['labelId'], ST_UID);
485
486                                        imap_close($this->mbox);
487                                        $this->mbox = false;
488
489                                        return array ('id' => $data['folderName'].'/'.$data['messageNumber'].'#'.$data['labelId']);
490                                }
491                                return array ();
492                        }
493                        case 'followupflagged':
494                        {
495                                //deve ser gravado primeiro no imap, obtido o message-id e, depois gravado no banco
496                               
497                                if (isset($data['folderName']) && isset($data['messageNumber'])) {
498                                       
499                                        $this->mbox = $this->open_mbox($data['folderName']);
500                                        $s = imap_setflag_full($this->mbox, $data['messageNumber'], '$Followupflagged', ST_UID);
501                                       
502                                        $headers = imap_fetch_overview($this->mbox, $data['messageNumber'], FT_UID);
503                                       
504                                        $data['messageId'] = $headers[0]->message_id;
505                                                       
506                                        imap_close($this->mbox);
507                                        $this->mbox = false;
508
509                                        return ($s) ? $data : array();
510
511                                } else if (isset($data['messageId'])) {
512                                        /**
513                                         * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela,
514                                         * senão busca em todas.
515                                         */
516                                        $folders = array ();
517                                        if (isset($data['folderName'])) {
518                                                $folders = array ($data['folderName']);
519                                        } else {
520                                                $folder_list = $this->get_folders_list();
521                                                foreach ($folder_list as $folder)
522                                                        if (isset($folder['folder_id']))
523                                                                $folders[] = $folder['folder_id'];
524                                        }
525                                       
526                                        foreach ($folders as $folder) {
527                                               
528                                                $this->mbox = $this->open_mbox($folder);
529                                                if ($messages = imap_search($this->mbox, 'TEXT "'.$data['messageId'].'"', SE_UID)) {
530                                                       
531                                                        $s = imap_setflag_full($this->mbox, $messages[0], '$Followupflagged', ST_UID);
532                                                       
533                                                        imap_close($this->mbox);
534                                                        $this->mbox = false;
535                                                       
536                                                        /**
537                                                         * Stop searching in all folders
538                                                         */
539                                                        return $data;
540                                                }
541                                               
542                                                imap_close($this->mbox);
543                                                $this->mbox = false;
544                                        }
545                                }
546                                return array ();
547                        }
548                       
549                        case 'message':
550                        {
551                                require_once ROOTPATH.'/library/uuid/class.uuid.php';
552                               
553                                $GLOBALS['phpgw_info']['flags'] = array( 'noheader' => true, 'nonavbar' => true,'currentapp' => 'expressoMail1_2','enable_nextmatchs_class' => True );
554                                $return = array();
555
556                                require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
557                                $mailService = ServiceLocator::getService('mail');
558
559                                $msg_uid = $data['msg_id'];
560                                $body = $data['body'];
561                                $body = str_replace("%nbsp;","&nbsp;",$body);
562                                $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );                                       
563
564                                $folder = mb_convert_encoding($data['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");
565                                $folder = @eregi_replace("INBOX[/.]", "INBOX".$this->imap_delimiter, $folder);
566
567                                /**
568                                * Gera e preenche o field Message-Id do header
569                                */
570                                $mailService->addHeaderField('Message-Id', UUID::generate( UUID::UUID_RANDOM, UUID::FMT_STRING ) . '@Draft');
571
572                                $mailService->addTo(mb_convert_encoding(($data['input_to']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
573                                $mailService->addCc( mb_convert_encoding(($data['input_cc']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
574                                $mailService->addBcc(mb_convert_encoding(($data['input_cco']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
575                                $mailService->setSubject(mb_convert_encoding(($data['input_subject']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
576                               
577                                if(isset($data['input_important_message']))
578                                        $mailService->addHeaderField('Importance','High');
579
580                                if(isset($data['input_return_receipt']))
581                                        $mailService->addHeaderField('Disposition-Notification-To', Config::me('mail'));
582
583                                $isHTML = ( isset($data['type']) && $data['type'] == 'html' )?  true : false;
584
585                                if (!$body) $body = ' ';
586
587
588                                $mbox_stream = $this->open_mbox($folder);
589
590                                $attachment = json_decode($data['attachments'],TRUE);
591
592
593                                foreach ($attachment as &$value)
594                                {
595                                        if((int)$value > 0) //BD attachment
596                                        {
597                                                $att = Controller::read(array('id'=> $value , 'concept' => 'mailAttachment'));
598
599                                                if($att['disposition'] == 'embedded')
600                                                {
601                                                        $body = str_replace('"../prototype/getArchive.php?mailAttachment='.$att['id'].'"', $att['name'], $body);
602                                                        $mailService->addStringImage(base64_decode($att['source']), $att['type'], $att['name']);
603                                                }
604                                                else
605                                                        $mailService->addStringAttachment(base64_decode($att['source']), $att['name'], $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
606
607                                                unset($att);
608                                        }
609                                        else
610                                        {
611                                                $value = json_decode($value, true);
612
613                                                switch ($value['type']) {
614                                                        case 'imapPart':
615                                                                $att = $this->getForwardingAttachment($value['folder'],$value['uid'], $value['part']);
616                                                                if(strstr($body,'<img src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'" />') !== false)//Embeded IMG
617                                                                {   
618                                                                        $body = str_ireplace('<img src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'" />' , '<img src="'.$att['name'].'" />', $body);
619                                                                        $mailService->addStringImage($att['source'], $att['type'], $att['name']);
620                                                                }
621                                                                else
622                                                                        $mailService->addStringAttachment($att['source'], $att['name'], $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
623                                                                unset($att);
624                                                                break;
625                                                        case 'imapMSG':
626                                                                $sub =  $value['name'] ? $value['name'].'.eml' :'no title.eml';
627                                                                $mbox_stream = $this->open_mbox($value['folder']);
628                                                                $rawmsg = $this->getRawHeader($value['uid']) . "\r\n\r\n" . $this->getRawBody($value['uid']);
629                                                                $mailService->addStringAttachment($rawmsg, $sub, 'message/rfc822', '7bit', 'attachment' );
630                                                                unset($rawmsg);
631                                                                break;
632
633                                                        default:
634                                                        break;
635                                                }
636                                        }
637
638                                }
639
640                                if($isHTML) $mailService->setBodyHtml($body); else $mailService->setBodyText($body);
641
642                                if(imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft"))
643                                {
644                                        $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
645                                        $return['id'] = $status->uidnext - 1;
646
647                                        if($data['uidsSave'] )
648                                                $this->delete_msgs(array('folder'=> $folder , 'msgs_number' => $data['uidsSave']));
649                                }
650
651                                if($mbox_stream) imap_close($mbox_stream);
652
653                                return $return;
654                        }
655                }
656        }
657
658    public function delete( $URI, $justthese = false, $criteria = false )
659    {
660                switch( $URI['concept'] )
661                {
662                        case 'labeled':
663                        {
664                                list($messageId, $labelId) = explode('#', $URI['id']);
665                                $folderName = dirname($messageId);
666                                $messageNumber = basename($messageId);
667
668                                if ($folderName && $messageNumber && $labelId) {
669                                        $this->mbox = $this->open_mbox($folderName);
670                                        imap_clearflag_full($this->mbox, $messageNumber, '$Label' . $labelId, ST_UID);
671
672                                        imap_close($this->mbox);
673                                        $this->mbox = false;
674                                }
675                        }
676                        case 'followupflagged':
677                        {
678                                $map = array(
679                                        'folderName' => array(),
680                                        'messageNumber' => array(),
681                                        'messageId' => array()
682                                );
683                               
684                                self::parseFilter($criteria["filter"], &$map);
685                               
686                                if (!$map['folderName']) {
687                                        $folders = array ();
688                                       
689                                        $folder_list = $this->get_folders_list();
690                                        foreach ($folder_list as $folder)
691                                                if (isset($folder['folder_id']))
692                                                        $folders[] = $folder['folder_id'];
693                                        $map['folderName'] = $folders;
694                                }
695
696                                $messagesIds = $map['messageId'];
697
698                                foreach ($map['folderName'] as $folder) {
699                                        $messages = array();
700                                       
701                                        $this->mbox = $this->open_mbox($folder);
702                               
703                                        /**
704                                         * Se é uma busca por messageId
705                                         */
706                                        if (!empty($map['messageId'])) {
707                                                       
708                                                foreach ($messagesIds as $k => $v) {
709                                                        $r = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged" TEXT "'.$v.'"', SE_UID);
710
711                                                        if ($r) {
712                                                                $messages = $messages + $r;
713                                                                unset($messagesIds[$k]);       
714                                                        }
715                                                }
716
717                                        /**
718                                         * Se é uma busca por messageNumber.
719                                         * Lembrando que, neste caso, só deve ser suportada uma única pasta no filtro.
720                                         */
721                                        } else {
722                                                $messages = imap_search($this->mbox, 'UNDELETED KEYWORD "$Followupflagged"', SE_UID);
723                                        }
724
725                                        /**
726                                         * Se é uma busca por messageId, deve ser comparado com os messageNumbers
727                                         * passados no filtro, se houverem.
728                                         */
729                                        if (!empty($map['messageNumber'])) {
730                                                foreach ($messages as $k => $m)
731                                                        if (!in_array($m, $map['messageNumber']))
732                                                                unset($messages[$k]);
733                                        }
734
735                                        $s = true;
736                                        foreach ($messages as $k => $m) {                                               
737                                                $s = imap_clearflag_full($this->mbox, $m, '$Followupflagged', ST_UID) && $s;
738                                        }
739
740                                        imap_close($this->mbox);
741                                        $this->mbox = false;
742                                       
743                                        /**
744                                         * Se é uma busca por messageId e todos os messageIds foram econstrados:
745                                         * Stop searching in all folders
746                                         */
747                                        if (!empty($map['messageId']) && empty($messagesIds))
748                                                break;
749                                }
750                               
751                                return $s;
752                        }
753                }
754
755                //TODO - return
756        }
757
758    public function deleteAll( $URI, $justthese = false, $criteria = false )
759    {
760                /**
761                 * TODO - implementar a deleção de todos os followupflaggeds conforme filtro
762                 */
763        }
764
765    public function update( $URI, $data, $criteria = false )
766    {
767                /**
768                 * Os únicos atributos da sinalização presentes no IMAP são folderName, messageNumber e messageId,
769                 * porém a operação de update desses atributos não faz sentido para o usuário da DataLayer,
770                 * pois na prática elas são executadas através das operações de CREATE e DELETE.
771                 * Assim, para os conceitos "labeled" e "followupflagged", só faz sentido o update de
772                 * atributos gravados no banco de dados e nunca no IMAP.
773                 */
774        }
775
776//     public function retrieve( $concept, $id, $parents, $justthese = false, $criteria = false )
777//     {
778//                      return $this->read( array( 'id' => $id,
779//                          'concept' => $concept,
780//                          'context' => $parents ), $justthese );
781//     }
782
783    public function replace( $URI, $data, $criteria = false )
784    {}
785
786    public function close()
787    {}
788
789    public function setup()
790    {}
791
792    public function commit( $uri )
793    { return( true ); }
794
795    public function rollback( $uri )
796    {}
797
798    public function begin( $uri )
799    {}
800
801
802    public function teardown()
803    {}
804
805    function to_utf8($in)
806    {
807                if (is_array($in)) {
808                        foreach ($in as $key => $value) {
809                                $out[$this->to_utf8($key)] = $this->to_utf8($value);
810                        }
811                } elseif(is_string($in)) {
812                                return mb_convert_encoding( $in , 'UTF-8' , 'UTF-8 , ISO-8859-1' );
813                } else {
814                        return $in;
815                }
816                return $out;
817    }
818       
819           
820    private static function parseFilter($filter ,&$map){
821               
822                if( !is_array( $filter ) || count($filter) <= 0) return null;
823                                       
824                $op = array_shift( $filter );
825                switch(strtolower($op))
826                {
827                        case 'and': {
828                                foreach ($filter as $term)
829                                        self::parseFilter($term ,&$map);
830                                return;
831                        }
832                        case 'in': {
833                                if(is_array($map[$filter[0]]) && is_array($filter[1]))
834                                        $map[$filter[0]] = array_unique(array_merge($map[$filter[0]], $filter[1]));
835                                return;
836                        }
837                        case '=': {
838                                $map[$filter[0]][] = $filter[1];
839                        }
840                }
841        }
842
843}
Note: See TracBrowser for help on using the repository browser.