1 | <?php
|
---|
2 | /**
|
---|
3 | *
|
---|
4 | * Copyright (C) 2012 Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
|
---|
5 | *
|
---|
6 | * This program is free software; you can redistribute it and/or modify it under
|
---|
7 | * the terms of the GNU Affero General Public License version 3 as published by
|
---|
8 | * the Free Software Foundation with the addition of the following permission
|
---|
9 | * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
|
---|
10 | * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
|
---|
11 | * WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
|
---|
12 | *
|
---|
13 | * This program is distributed in the hope that it will be useful, but WITHOUT
|
---|
14 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
|
---|
15 | * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
|
---|
16 | * details.
|
---|
17 | *
|
---|
18 | * You should have received a copy of the GNU Affero General Public License
|
---|
19 | * along with this program; if not, see www.gnu.org/licenses or write to
|
---|
20 | * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
|
---|
21 | * MA 02110-1301 USA.
|
---|
22 | *
|
---|
23 | * This code is based on the OpenXchange Connector and on the Prognus pSync
|
---|
24 | * Connector both developed by the community and licensed under the GPL
|
---|
25 | * version 2 or above as published by the Free Software Foundation.
|
---|
26 | *
|
---|
27 | * You can contact Prognus Software Livre headquarters at Av. Tancredo Neves,
|
---|
28 | * 6731, PTI, Edifício do Saber, 3º floor, room 306, Foz do Iguaçu - PR - Brasil or at
|
---|
29 | * e-mail address prognus@prognus.com.br.
|
---|
30 | *
|
---|
31 | * Classe de abstração que faz uma adaptação para manipulação de informações
|
---|
32 | * no IMAP a partir de vários métodos.
|
---|
33 | *
|
---|
34 | * @package Prototype
|
---|
35 | * @license http://www.gnu.org/copyleft/gpl.html GPL
|
---|
36 | * @author Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
|
---|
37 | * @version 2.4
|
---|
38 | * @sponsor Caixa Econômica Federal
|
---|
39 | * @since Arquivo disponibilizado na versão 2.4
|
---|
40 | */
|
---|
41 |
|
---|
42 | include_once ROOTPATH."/../expressoMail1_2/inc/class.imap_functions.inc.php";
|
---|
43 |
|
---|
44 | use prototype\api\Config as Config;
|
---|
45 |
|
---|
46 | /**
|
---|
47 | *
|
---|
48 | * @package Prototype (Mail)
|
---|
49 | * @license http://www.gnu.org/copyleft/gpl.html GPL
|
---|
50 | * @author Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
|
---|
51 | * @version 2.4
|
---|
52 | * @sponsor Caixa Econômica Federal
|
---|
53 | * @since Classe disponibilizada na versão 2.4
|
---|
54 | */
|
---|
55 | class ImapServiceAdapter extends imap_functions/* implements Service*/
|
---|
56 | {
|
---|
57 | public function open( $config )
|
---|
58 | {
|
---|
59 | $this->init();
|
---|
60 | }
|
---|
61 |
|
---|
62 | // public function connect( $config )
|
---|
63 | // {
|
---|
64 | // $this->init();
|
---|
65 | // }
|
---|
66 |
|
---|
67 | public function find( $URI, $justthese = false, $criteria = false )
|
---|
68 | {
|
---|
69 |
|
---|
70 | $context = isset($justthese['context']) ? $justthese['context'] : '' ;
|
---|
71 |
|
---|
72 | switch( $URI['concept'] )
|
---|
73 | {
|
---|
74 | case 'folder':
|
---|
75 | {
|
---|
76 | $result = $this->getFolders();
|
---|
77 |
|
---|
78 | foreach ($result as $res) {
|
---|
79 |
|
---|
80 | //monta o array padrao
|
---|
81 | $array = array(
|
---|
82 | 'id' => mb_convert_encoding( $res['folder_id'], 'UTF-8', 'UTF7-IMAP' ),
|
---|
83 | 'commonName' => mb_convert_encoding( $res['folder_name'], 'UTF-8' , 'UTF7-IMAP' ),
|
---|
84 | 'parentFolder' => mb_convert_encoding( $res['folder_parent'], 'UTF-8' , 'UTF7-IMAP' ),
|
---|
85 | 'messageCount' => array('unseen' => isset($res['folder_unseen']) ? $res['folder_unseen'] : null, 'total' => null)
|
---|
86 | );
|
---|
87 |
|
---|
88 | //se existir compartilhamento para pasta compartilhada
|
---|
89 | //adicionar array de permissoes
|
---|
90 | if(isset($res['acl_share'])){
|
---|
91 | $array['acl_share'] = $res['acl_share'];
|
---|
92 | }
|
---|
93 | $response[] = $array;
|
---|
94 | }
|
---|
95 | return $response;
|
---|
96 | }
|
---|
97 | case 'message':
|
---|
98 | {
|
---|
99 | //begin: for grid
|
---|
100 | $page = isset($criteria['page']) ? $criteria['page'] : 1 ; //{1} get the requested page
|
---|
101 | $limit = isset($criteria['rows']) ? $criteria['rows'] : 10 ; //{10} get how many rows we want to have into the grid
|
---|
102 | $sidx = isset($criteria['sidx']) ? $criteria['sidx'] : 0; //{id} get index row - i.e. user click to sort
|
---|
103 | $sord = isset($criteria['sord']) ? $criteria['sord'] : ''; //{desc} get the direction
|
---|
104 |
|
---|
105 | $filter = isset($criteria['filter']) ? $criteria['filter'] : '';
|
---|
106 |
|
---|
107 | if( !$sidx ) $sidx = 1;
|
---|
108 |
|
---|
109 | $folder_name = isset($URI['folder']) ? $URI['folder'] : str_replace( '.', $this->imap_delimiter, isset($context['folder']) ? $context['folder'] : 'INBOX');
|
---|
110 |
|
---|
111 | $count = imap_num_msg( $this->open_mbox( $folder_name ) );
|
---|
112 |
|
---|
113 | $total_pages = $count > 0 ? ceil( $count/$limit ) : 0;
|
---|
114 |
|
---|
115 | if( $page > $total_pages )
|
---|
116 | $page = $total_pages;
|
---|
117 |
|
---|
118 | $start = $limit * $page - $limit;
|
---|
119 | // do not put $limit*($page - 1)
|
---|
120 | //end: for grid
|
---|
121 |
|
---|
122 |
|
---|
123 | /**
|
---|
124 | * Trata o caso específico de retorno do atributo messageId
|
---|
125 | *
|
---|
126 | * TODO - refazer todo a operação find do conceito message, uma vez que esta
|
---|
127 | * foi desenvolvida quando a nova API ainda era muito imatura e se encontra
|
---|
128 | * muito acoplada à estrutura de retorno esperada pelo plugin jqGrid
|
---|
129 | */
|
---|
130 | if ( $justthese )
|
---|
131 | {
|
---|
132 | if (isset($justthese[0]) && $justthese[0] == 'messageId') {
|
---|
133 | $map = array(
|
---|
134 | 'folderName' => array(),
|
---|
135 | 'messageNumber' => array()
|
---|
136 | );
|
---|
137 |
|
---|
138 | self::parseFilter($criteria["filter"], &$map);
|
---|
139 |
|
---|
140 | if (count($map['folderName']) == 0) {
|
---|
141 | $folders = $this->get_folders_list();
|
---|
142 | foreach ($folders as $folder)
|
---|
143 | if (isset($folder['folder_id']))
|
---|
144 | $map['folderName'][] = $folder['folder_id'];
|
---|
145 | }
|
---|
146 |
|
---|
147 | $result = array();
|
---|
148 | foreach ($map['folderName'] as $folder) {
|
---|
149 | $this->mbox = $this->open_mbox($folder);
|
---|
150 |
|
---|
151 | /**
|
---|
152 | * Se não foi passado messageNumber no filtro,
|
---|
153 | * busca todas as mensagens de cada pasta
|
---|
154 | */
|
---|
155 | $messages = empty($map['messageNumber']) ? '1:*' : implode(',', $map['messageNumber']);
|
---|
156 | $sequenceType = empty($map['messageNumber']) ? 0 : FT_UID;
|
---|
157 |
|
---|
158 | $headers = imap_fetch_overview($this->mbox, $messages, $sequenceType);
|
---|
159 | foreach ($headers as $h) {
|
---|
160 | if(isset($h->message_id ))
|
---|
161 | $result[] = array ( 'messageId' => $h->message_id );
|
---|
162 | }
|
---|
163 |
|
---|
164 | }
|
---|
165 | return $result;
|
---|
166 | }
|
---|
167 | }
|
---|
168 |
|
---|
169 | if( $filter )
|
---|
170 | {
|
---|
171 | if( $filter[0] !== 'msgNumber' )
|
---|
172 | {
|
---|
173 | for( $i = 0; $i < count($filter); ++$i )
|
---|
174 | {
|
---|
175 | if( count( $filter[$i] ) === 4 )
|
---|
176 | $criteria['isExact'] = ( array_shift( $filter[$i] ) === 'AND' );
|
---|
177 |
|
---|
178 | $criteria[ $filter[$i][0] ] = array( 'criteria' => $filter[$i][2], 'filter' => $filter[$i][1] );
|
---|
179 | }
|
---|
180 |
|
---|
181 | return $this->searchSieveRule($criteria);
|
---|
182 | }
|
---|
183 |
|
---|
184 | $msgNumber = array();
|
---|
185 |
|
---|
186 | for( $i = $start; $i < $start + $limit && isset( $filter[2][$i] ); ++$i )
|
---|
187 | $msgNumber[] = $filter[2][$i];
|
---|
188 |
|
---|
189 | if( empty( $msgNumber ) )
|
---|
190 | return( false );
|
---|
191 |
|
---|
192 | $result = $this->get_info_msgs( array( 'folder' => $folder_name,
|
---|
193 | 'msgs_number' => implode( ',', $msgNumber ) ) );
|
---|
194 |
|
---|
195 | foreach( $result as $i => $val )
|
---|
196 | $result[$i] = unserialize( $val );
|
---|
197 |
|
---|
198 | }
|
---|
199 | else
|
---|
200 | {
|
---|
201 | $result = $this->get_range_msgs2(
|
---|
202 | array(
|
---|
203 | 'folder' => $folder_name, //INBOX
|
---|
204 | 'msg_range_begin' => $start + 1, //??
|
---|
205 | 'msg_range_end' => $start + $limit, //$limit = $_GET['rows']; // get how many rows we want to have into the grid
|
---|
206 | 'sort_box_type' => 'SORTARRIVAL',
|
---|
207 | 'search_box_type' => 'ALL',
|
---|
208 | 'sort_box_reverse' => 1
|
---|
209 | )
|
---|
210 | );
|
---|
211 | }
|
---|
212 | //return var_export($result);
|
---|
213 |
|
---|
214 | if($filter){
|
---|
215 | $total_pages = count($filter[2]) > 0 ? ceil( count($filter[2])/$limit ) : 0;
|
---|
216 | $response = array( "page" => $page, "total" => $total_pages, "records" => count($filter[2]) );
|
---|
217 | }else{
|
---|
218 | $response = array( "page" => $page, "total" => $total_pages, "records" => $count );
|
---|
219 | }
|
---|
220 |
|
---|
221 | for ($i=0; $i<count($result); ++$i)
|
---|
222 | {
|
---|
223 | $flags_enum = array('Unseen'=> 1, 'Answered'=> 1, 'Forwarded'=> 1, 'Flagged'=> 1, 'Recent'=> 1, 'Draft'=> 1 );
|
---|
224 |
|
---|
225 | foreach ($flags_enum as $key => $flag)
|
---|
226 | {
|
---|
227 | if ( !isset($result[$i][$key]) || !trim($result[$i][$key]) || trim($result[$i][$key]) == '')
|
---|
228 | $flags_enum[$key] = 0;
|
---|
229 |
|
---|
230 | unset($result[$i][$flag]);
|
---|
231 | }
|
---|
232 |
|
---|
233 | if (array_key_exists($i, $result))
|
---|
234 | {
|
---|
235 | $response["rows"][$i] = $result[$i];
|
---|
236 | $response["rows"][$i]['timestamp'] = $result[$i]['udate'] * 1000;
|
---|
237 | $response["rows"][$i]['flags'] = implode(',', $flags_enum);
|
---|
238 | $response["rows"][$i]['size'] = $response["rows"][$i]['Size'];
|
---|
239 | $response["rows"][$i]['folder'] = $folder_name;
|
---|
240 | //$response["rows"][$i]['udate'] = ( $result[$i]['udate'] + $this->functions->CalculateDateOffset() * 1000 );
|
---|
241 | unset($response["rows"][$i]['Size']);
|
---|
242 | }
|
---|
243 | }
|
---|
244 |
|
---|
245 | return $this->to_utf8($response);
|
---|
246 | }
|
---|
247 |
|
---|
248 | /**
|
---|
249 | * Filtros suportados:
|
---|
250 | * - ['=', 'folderName', $X]
|
---|
251 | * - [
|
---|
252 | * 'AND',
|
---|
253 | * [
|
---|
254 | * 'AND',
|
---|
255 | * ['=', 'folderName', $X],
|
---|
256 | * ['IN', 'messageNumber', $Ys]
|
---|
257 | * ],
|
---|
258 | * ['IN', 'labelId', $Zs]
|
---|
259 | * ]
|
---|
260 | * - ['=', 'labelId', $X]
|
---|
261 | * - [
|
---|
262 | * 'AND',
|
---|
263 | * ['=', 'folderName', $X],
|
---|
264 | * ['=', 'labelId', $Y]
|
---|
265 | * ]
|
---|
266 | * - ['IN', 'labelId', $Ys]
|
---|
267 | * - [
|
---|
268 | * 'AND',
|
---|
269 | * ['=', 'folderName', $X],
|
---|
270 | * ['IN', 'labelId', $Ys]
|
---|
271 | * ]
|
---|
272 | */
|
---|
273 | case 'labeled':
|
---|
274 | {
|
---|
275 | $result = array ( );
|
---|
276 | if (isset($criteria["filter"]) && is_array($criteria['filter'])) {
|
---|
277 | //TODO - melhorar o tratamento do filter com a lista de todos os labelIds dado pelo interceptor
|
---|
278 | $map = array(
|
---|
279 | 'id' => array(),
|
---|
280 | 'folderName' => array(),
|
---|
281 | 'messageNumber' => array(),
|
---|
282 | 'labelId' => array()
|
---|
283 | );
|
---|
284 |
|
---|
285 | self::parseFilter($criteria["filter"], &$map);
|
---|
286 |
|
---|
287 | if (count($map['folderName']) == 0) {
|
---|
288 | $folders = $this->get_folders_list();
|
---|
289 | foreach ($folders as $folder)
|
---|
290 | if (isset($folder['folder_id']))
|
---|
291 | $map['folderName'][] = $folder['folder_id'];
|
---|
292 | }
|
---|
293 |
|
---|
294 | foreach ($map['folderName'] as $folder) {
|
---|
295 | $this->mbox = $this->open_mbox($folder);
|
---|
296 |
|
---|
297 | foreach ($map['labelId'] as $label) {
|
---|
298 | $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$label.'"', SE_UID);
|
---|
299 |
|
---|
300 | if(is_array($messagesLabeleds))
|
---|
301 | foreach ($messagesLabeleds as $messageLabeled) {
|
---|
302 | if (count($map['messageNumber']) > 0 && !in_array($messageLabeled, $map['messageNumber']))
|
---|
303 | continue;
|
---|
304 |
|
---|
305 | $result[] = array (
|
---|
306 | 'id' => $folder . '/' . $messageLabeled . '#' . $label,
|
---|
307 | 'folderName' => $folder,
|
---|
308 | 'messageNumber' => $messageLabeled,
|
---|
309 | 'labelId' => $label
|
---|
310 | );
|
---|
311 | }
|
---|
312 | }
|
---|
313 |
|
---|
314 | }
|
---|
315 | }
|
---|
316 |
|
---|
317 | return $result;
|
---|
318 | }
|
---|
319 |
|
---|
320 | case 'followupflagged':
|
---|
321 | {
|
---|
322 | $result = array ( );
|
---|
323 |
|
---|
324 | $map = array(
|
---|
325 | //'id' => array(),
|
---|
326 | 'folderName' => array(),
|
---|
327 | 'messageNumber' => array(),
|
---|
328 | 'messageId' => array()
|
---|
329 | );
|
---|
330 |
|
---|
331 | self::parseFilter($criteria["filter"], &$map);
|
---|
332 |
|
---|
333 | if (empty($map['folderName'])) {
|
---|
334 | $folders = $this->get_folders_list();
|
---|
335 | foreach ($folders as $folder)
|
---|
336 | if (isset($folder['folder_id']))
|
---|
337 | $map['folderName'][] = $folder['folder_id'];
|
---|
338 | }
|
---|
339 |
|
---|
340 | $messagesIds = $map['messageId'];
|
---|
341 |
|
---|
342 | foreach ($map['folderName'] as $folder) {
|
---|
343 | $messages = array();
|
---|
344 |
|
---|
345 | $this->mbox = $this->open_mbox($folder);
|
---|
346 |
|
---|
347 | /**
|
---|
348 | * Se é uma busca por messageId
|
---|
349 | */
|
---|
350 | if (!empty($map['messageId'])) {
|
---|
351 |
|
---|
352 | foreach ($messagesIds as $k => $v) {
|
---|
353 |
|
---|
354 | $r = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged" TEXT "Message-Id: '.$v.'"', SE_UID);
|
---|
355 |
|
---|
356 | if ($r) {
|
---|
357 |
|
---|
358 | $messages = array_merge($messages, $r);
|
---|
359 | unset($messagesIds[$k]);
|
---|
360 |
|
---|
361 | }
|
---|
362 | }
|
---|
363 |
|
---|
364 | /**
|
---|
365 | * Se é uma busca por messageNumber.
|
---|
366 | * Lembrando que, neste caso, só deve ser suportada uma única pasta no filtro.
|
---|
367 | */
|
---|
368 | } else {
|
---|
369 | $messages = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged"', SE_UID);
|
---|
370 | }
|
---|
371 |
|
---|
372 | /**
|
---|
373 | * Se é uma busca por messageId, deve ser comparado com os messageNumbers
|
---|
374 | * passados no filtro, se houverem.
|
---|
375 | */
|
---|
376 | if (!empty($map['messageNumber']) && is_array($messages)) {
|
---|
377 |
|
---|
378 | foreach ($messages as $k => $m)
|
---|
379 | if (!in_array($m, $map['messageNumber']))
|
---|
380 | unset($messages[$k]);
|
---|
381 | }
|
---|
382 |
|
---|
383 | /**
|
---|
384 | * Adicionar demais atributos às mensagens para retorno
|
---|
385 | */
|
---|
386 | if(is_array($messages))
|
---|
387 | foreach ($messages as $k => $m) {
|
---|
388 | $headers = imap_fetch_overview($this->mbox, $m, FT_UID);
|
---|
389 |
|
---|
390 | $result[] = array (
|
---|
391 | 'messageId' => $headers[0]->message_id,
|
---|
392 | 'messageNumber' => $m,
|
---|
393 | 'folderName' => $folder
|
---|
394 | );
|
---|
395 | }
|
---|
396 |
|
---|
397 |
|
---|
398 | /**
|
---|
399 | * Se é uma busca por messageId e todos os messageIds foram econstrados:
|
---|
400 | * Stop searching in all folders
|
---|
401 | */
|
---|
402 | if (!empty($map['messageId']) && empty($messagesIds))
|
---|
403 | break;
|
---|
404 | }
|
---|
405 |
|
---|
406 |
|
---|
407 | return $result;
|
---|
408 |
|
---|
409 | } //CASE 'followupflag'
|
---|
410 | }
|
---|
411 | }
|
---|
412 |
|
---|
413 | public function read( $URI, $justthese = false )
|
---|
414 | {
|
---|
415 |
|
---|
416 | switch( $URI['concept'] )
|
---|
417 | {
|
---|
418 | case 'message':
|
---|
419 | {
|
---|
420 | return $this->to_utf8(
|
---|
421 | $this->get_info_msg( array('msg_number'=>$URI['id'],
|
---|
422 | 'msg_folder'=>str_replace( '.', $this->imap_delimiter, $justthese['context']['folder'] ) ,
|
---|
423 | 'decoded' => true ) )
|
---|
424 | );
|
---|
425 | }
|
---|
426 | case 'labeled':
|
---|
427 | {
|
---|
428 | /**
|
---|
429 | * id looks like 'folder/subfolder/subsubfolder/65#13', meaning messageId#labelId
|
---|
430 | */
|
---|
431 | list($messageId, $labelId) = explode('#', $URI['id']);
|
---|
432 | $folderName = basename($messageId);
|
---|
433 | $messageNumber = dirname($messageId);
|
---|
434 |
|
---|
435 | $result = array();
|
---|
436 |
|
---|
437 | if ($folderName && $messageNumber && $labelId) {
|
---|
438 | $this->mbox = $this->open_mbox($folderName);
|
---|
439 | $messagesLabeleds = imap_search($this->mbox, 'UNDELETED KEYWORD "$Label'.$labelId.'"', SE_UID);
|
---|
440 |
|
---|
441 | if (in_array($messageNumber, $messagesLabeleds)) {
|
---|
442 | $result = array (
|
---|
443 | 'id' => $URI['id'],
|
---|
444 | 'folderName' => $folderName,
|
---|
445 | 'messageNumber' => $messageNumber,
|
---|
446 | 'labelId' => $labelId
|
---|
447 | );
|
---|
448 | }
|
---|
449 |
|
---|
450 | }
|
---|
451 |
|
---|
452 | return $result;
|
---|
453 | }
|
---|
454 |
|
---|
455 | case 'followupflagged':
|
---|
456 | {
|
---|
457 |
|
---|
458 | /**
|
---|
459 | * identifica se o formato de ID é "folder/subfolder/subsubfolder/<messageNumber>" ou "<message-id>"
|
---|
460 | */
|
---|
461 | $folderName = $messageNumber = false;
|
---|
462 | if(!($messageHasId = preg_match('/<.*>/', $URI['id']))) {
|
---|
463 | $folderName = dirname($URI['id']);
|
---|
464 | $messageNumber = basename($URI['id']);
|
---|
465 | }
|
---|
466 |
|
---|
467 | $result = array();
|
---|
468 | if ($folderName && $messageNumber) {
|
---|
469 |
|
---|
470 | $this->mbox = $this->open_mbox($folderName);
|
---|
471 | $r = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged"', SE_UID);
|
---|
472 |
|
---|
473 | if (in_array($messageNumber, $r)) {
|
---|
474 | $headers = imap_fetch_overview($this->mbox, $messageNumber, FT_UID);
|
---|
475 |
|
---|
476 | $result = array (
|
---|
477 | 'messageId' => $headers[0]->message_id,
|
---|
478 | 'messageNumber' => $messageNumber,
|
---|
479 | 'folderName' => $folderName
|
---|
480 | );
|
---|
481 | }
|
---|
482 |
|
---|
483 | } else {
|
---|
484 | /**
|
---|
485 | * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela,
|
---|
486 | * senão busca em todas.
|
---|
487 | */
|
---|
488 |
|
---|
489 | $folders = array ();
|
---|
490 | if ($folderName) {
|
---|
491 | $folders = array ($folderName);
|
---|
492 | } else {
|
---|
493 | $folder_list = $this->get_folders_list();
|
---|
494 | foreach ($folder_list as $folder)
|
---|
495 | if (isset($folder['folder_id']))
|
---|
496 | $folders[] = $folder['folder_id'];
|
---|
497 | }
|
---|
498 |
|
---|
499 | foreach ($folders as $folder) {
|
---|
500 |
|
---|
501 | $this->mbox = $this->open_mbox($folder);
|
---|
502 |
|
---|
503 | if ($messages = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged" TEXT "Message-Id: '.$URI['id'].'"', SE_UID)) {
|
---|
504 |
|
---|
505 | $result = array (
|
---|
506 | 'messageId' => $URI['id'],
|
---|
507 | 'messageNumber' => $messages[0],
|
---|
508 | 'folderName' => $folder
|
---|
509 | );
|
---|
510 |
|
---|
511 | /**
|
---|
512 | * Stop searching in all folders
|
---|
513 | */
|
---|
514 | break;
|
---|
515 | }
|
---|
516 |
|
---|
517 | }
|
---|
518 | }
|
---|
519 |
|
---|
520 |
|
---|
521 | return $result;
|
---|
522 | }
|
---|
523 | }
|
---|
524 | }
|
---|
525 |
|
---|
526 | public function create($URI, &$data)
|
---|
527 | {
|
---|
528 | switch( $URI['concept'] )
|
---|
529 | {
|
---|
530 | case 'labeled':
|
---|
531 | {
|
---|
532 | if (isset($data['folderName']) && isset($data['messageNumber']) && isset($data['labelId'])) {
|
---|
533 | $this->mbox = $this->open_mbox($data['folderName']);
|
---|
534 | imap_setflag_full($this->mbox, $data['messageNumber'], '$Label' . $data['labelId'], ST_UID);
|
---|
535 |
|
---|
536 | return array ('id' => $data['folderName'].'/'.$data['messageNumber'].'#'.$data['labelId']);
|
---|
537 | }
|
---|
538 | return array ();
|
---|
539 | }
|
---|
540 | case 'followupflagged':
|
---|
541 | {
|
---|
542 | //deve ser gravado primeiro no imap, obtido o message-id e, depois gravado no banco
|
---|
543 |
|
---|
544 | if (isset($data['folderName']) && isset($data['messageNumber'])) {
|
---|
545 |
|
---|
546 | $this->mbox = $this->open_mbox($data['folderName']);
|
---|
547 | $s = imap_setflag_full($this->mbox, $data['messageNumber'], '$Followupflagged', ST_UID);
|
---|
548 |
|
---|
549 | $headers = imap_fetch_overview($this->mbox, $data['messageNumber'], FT_UID);
|
---|
550 |
|
---|
551 | $data['messageId'] = $headers[0]->message_id;
|
---|
552 |
|
---|
553 | /*
|
---|
554 | * TODO
|
---|
555 | * Verificar erro ao tentar setar uma flag com o limite de flags atingido
|
---|
556 | * onde o status retornado pelo imap_setflag_full é true mesmo não sendo possível
|
---|
557 | * a inserção da flag.
|
---|
558 | */
|
---|
559 |
|
---|
560 | return (($s) && (imap_last_error() != 'Too many user flags in mailbox')) ? $data : array();
|
---|
561 |
|
---|
562 | } else if (isset($data['messageId'])) {
|
---|
563 | /**
|
---|
564 | * Busca pela mensagem com o messageId dado. Se uma pasta foi passada, busca nela,
|
---|
565 | * senão busca em todas.
|
---|
566 | */
|
---|
567 | $folders = array ();
|
---|
568 | if (isset($data['folderName'])) {
|
---|
569 | $folders = array ($data['folderName']);
|
---|
570 | } else {
|
---|
571 | $folder_list = $this->get_folders_list();
|
---|
572 | foreach ($folder_list as $folder)
|
---|
573 | if (isset($folder['folder_id']))
|
---|
574 | $folders[] = $folder['folder_id'];
|
---|
575 | }
|
---|
576 |
|
---|
577 | foreach ($folders as $folder) {
|
---|
578 |
|
---|
579 | $this->mbox = $this->open_mbox($folder);
|
---|
580 | if ($messages = imap_search($this->mbox, 'ALL TEXT "Message-Id: '.$data['messageId'].'"', SE_UID)) {
|
---|
581 |
|
---|
582 | $s = imap_setflag_full($this->mbox, $messages[0], '$Followupflagged', ST_UID);
|
---|
583 |
|
---|
584 | /**
|
---|
585 | * Stop searching in all folders
|
---|
586 | */
|
---|
587 | return $data;
|
---|
588 | }
|
---|
589 |
|
---|
590 | }
|
---|
591 | }
|
---|
592 | return array ();
|
---|
593 | }
|
---|
594 |
|
---|
595 | case 'message':
|
---|
596 | {
|
---|
597 | require_once ROOTPATH.'/library/uuid/class.uuid.php';
|
---|
598 |
|
---|
599 | $GLOBALS['phpgw_info']['flags'] = array( 'noheader' => true, 'nonavbar' => true,'currentapp' => 'expressoMail1_2','enable_nextmatchs_class' => True );
|
---|
600 | $return = array();
|
---|
601 |
|
---|
602 | require_once dirname(__FILE__) . '/../../services/class.servicelocator.php';
|
---|
603 | $mailService = ServiceLocator::getService('mail');
|
---|
604 |
|
---|
605 | $msg_uid = $data['msg_id'];
|
---|
606 | $body = $data['body'];
|
---|
607 | $body = str_replace("<","&yzwkx;",$body); //Alterar as Entities padrão das tags < > para compatibilizar com o Expresso
|
---|
608 | $body = str_replace(">","&xzwky;",$body);
|
---|
609 | $body = str_replace("%nbsp;"," ",$body);
|
---|
610 | $body = html_entity_decode ( $body, ENT_QUOTES , 'ISO-8859-1' );
|
---|
611 | $body = str_replace("&yzwkx;","<",$body);
|
---|
612 | $body = str_replace("&xzwky;",">",$body);
|
---|
613 |
|
---|
614 | $folder = mb_convert_encoding($data['folder'], "UTF7-IMAP","ISO-8859-1, UTF-8");
|
---|
615 | $folder = @preg_replace('/INBOX[\/.]/i', "INBOX".$this->imap_delimiter, $folder);
|
---|
616 |
|
---|
617 | /**
|
---|
618 | * Gera e preenche o field Message-Id do header
|
---|
619 | */
|
---|
620 | $mailService->addHeaderField('Message-Id', UUID::generate( UUID::UUID_RANDOM, UUID::FMT_STRING ) . '@Draft');
|
---|
621 | $mailService->addHeaderField('Reply-To', mb_convert_encoding(($data['input_reply_to']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
|
---|
622 | $mailService->addHeaderField('Date', date("d-M-Y H:i:s"));
|
---|
623 | $mailService->addTo(mb_convert_encoding(($data['input_to']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
|
---|
624 | $mailService->addCc( mb_convert_encoding(($data['input_cc']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
|
---|
625 | $mailService->addBcc(mb_convert_encoding(($data['input_cco']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
|
---|
626 | $mailService->setSubject(mb_convert_encoding(($data['input_subject']), 'ISO-8859-1', 'UTF-8,ISO-8859-1'));
|
---|
627 |
|
---|
628 | if(isset($data['input_important_message']))
|
---|
629 | $mailService->addHeaderField('Importance','High');
|
---|
630 |
|
---|
631 | if(isset($data['input_return_receipt']))
|
---|
632 | $mailService->addHeaderField('Disposition-Notification-To', Config::me('mail'));
|
---|
633 |
|
---|
634 | $this->rfc2397ToEmbeddedAttachment($mailService , $body);
|
---|
635 |
|
---|
636 | $isHTML = ( isset($data['type']) && $data['type'] == 'html' )? true : false;
|
---|
637 |
|
---|
638 | if (!$body) $body = ' ';
|
---|
639 |
|
---|
640 |
|
---|
641 | $mbox_stream = $this->open_mbox($folder);
|
---|
642 |
|
---|
643 | $attachment = json_decode($data['attachments'],TRUE);
|
---|
644 |
|
---|
645 | if(!empty($attachment))
|
---|
646 | foreach ($attachment as &$value)
|
---|
647 | {
|
---|
648 | if((int)$value > 0) //BD attachment
|
---|
649 | {
|
---|
650 | $att = Controller::read(array('id'=> $value , 'concept' => 'mailAttachment'));
|
---|
651 |
|
---|
652 | if($att['disposition'] == 'embedded' && $isHTML) //Caso mensagem em texto simples converter os embedded para attachments
|
---|
653 | {
|
---|
654 | $body = str_replace('"../prototype/getArchive.php?mailAttachment='.$att['id'].'"', '"'.mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1').'"', $body);
|
---|
655 | $mailService->addStringImage(base64_decode($att['source']), $att['type'], mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1'));
|
---|
656 | }
|
---|
657 | else
|
---|
658 | $mailService->addStringAttachment(base64_decode($att['source']), mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1'), $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
|
---|
659 |
|
---|
660 | unset($att);
|
---|
661 | }
|
---|
662 | else
|
---|
663 | {
|
---|
664 | $value = json_decode($value, true);
|
---|
665 |
|
---|
666 | switch ($value['type']) {
|
---|
667 | case 'imapPart':
|
---|
668 | $att = $this->getForwardingAttachment($value['folder'],$value['uid'], $value['part']);
|
---|
669 | if(strstr($body,'src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"') !== false)//Embeded IMG
|
---|
670 | {
|
---|
671 | $body = str_ireplace('src="./inc/get_archive.php?msgFolder='.$value['folder'].'&msgNumber='.$value['uid'].'&indexPart='.$value['part'].'"' , 'src="'.$att['name'].'"', $body);
|
---|
672 | $mailService->addStringImage($att['source'], $att['type'], mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1'));
|
---|
673 | }
|
---|
674 | else
|
---|
675 | $mailService->addStringAttachment($att['source'], mb_convert_encoding($att['name'], 'ISO-8859-1' , 'UTF-8,ISO-8859-1'), $att['type'], 'base64', isset($att['disposition']) ? $att['disposition'] :'attachment' );
|
---|
676 | unset($att);
|
---|
677 | break;
|
---|
678 | case 'imapMSG':
|
---|
679 | $mbox_stream = $this->open_mbox($value['folder']);
|
---|
680 | $rawmsg = $this->getRawHeader($value['uid']) . "\r\n\r\n" . $this->getRawBody($value['uid']);
|
---|
681 | $mailService->addStringAttachment($rawmsg, mb_convert_encoding(base64_decode($value['name']), 'ISO-8859-1' , 'UTF-8,ISO-8859-1'), 'message/rfc822', '7bit', 'attachment' );
|
---|
682 | unset($rawmsg);
|
---|
683 | break;
|
---|
684 |
|
---|
685 | default:
|
---|
686 | break;
|
---|
687 | }
|
---|
688 | }
|
---|
689 |
|
---|
690 | }
|
---|
691 |
|
---|
692 | if($isHTML) $mailService->setBodyHtml($body); else $mailService->setBodyText(mb_convert_encoding($body, 'ISO-8859-1' , 'UTF-8,ISO-8859-1' ));
|
---|
693 |
|
---|
694 | if(imap_append($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, $mailService->getMessage(), "\\Seen \\Draft"))
|
---|
695 | {
|
---|
696 | $status = imap_status($mbox_stream, "{".$this->imap_server.":".$this->imap_port."}".$folder, SA_UIDNEXT);
|
---|
697 | $return['id'] = $status->uidnext - 1;
|
---|
698 |
|
---|
699 | if($data['uidsSave'] )
|
---|
700 | $this->delete_msgs(array('folder'=> $folder , 'msgs_number' => $data['uidsSave']));
|
---|
701 | }
|
---|
702 |
|
---|
703 | return $return;
|
---|
704 | }
|
---|
705 | }
|
---|
706 | }
|
---|
707 |
|
---|
708 | public function delete( $URI, $justthese = false, $criteria = false )
|
---|
709 | {
|
---|
710 | switch( $URI['concept'] )
|
---|
711 | {
|
---|
712 | case 'labeled':
|
---|
713 | {
|
---|
714 | list($messageId, $labelId) = explode('#', $URI['id']);
|
---|
715 | $folderName = dirname($messageId);
|
---|
716 | $messageNumber = basename($messageId);
|
---|
717 |
|
---|
718 | if ($folderName && $messageNumber && $labelId) {
|
---|
719 | $this->mbox = $this->open_mbox($folderName);
|
---|
720 | imap_clearflag_full($this->mbox, $messageNumber, '$Label' . $labelId, ST_UID);
|
---|
721 |
|
---|
722 | }
|
---|
723 | }
|
---|
724 | case 'followupflagged':
|
---|
725 | {
|
---|
726 | $map = array(
|
---|
727 | 'folderName' => array(),
|
---|
728 | 'messageNumber' => array(),
|
---|
729 | 'messageId' => array()
|
---|
730 | );
|
---|
731 |
|
---|
732 | self::parseFilter($criteria["filter"], &$map);
|
---|
733 |
|
---|
734 | if (!$map['folderName']) {
|
---|
735 | $folders = array ();
|
---|
736 |
|
---|
737 | $folder_list = $this->get_folders_list();
|
---|
738 | foreach ($folder_list as $folder)
|
---|
739 | if (isset($folder['folder_id']))
|
---|
740 | $folders[] = $folder['folder_id'];
|
---|
741 | $map['folderName'] = $folders;
|
---|
742 | }
|
---|
743 |
|
---|
744 | $messagesIds = $map['messageId'];
|
---|
745 |
|
---|
746 | foreach ($map['folderName'] as $folder) {
|
---|
747 | $messages = array();
|
---|
748 |
|
---|
749 | $this->mbox = $this->open_mbox($folder);
|
---|
750 |
|
---|
751 | /**
|
---|
752 | * Se é uma busca por messageId
|
---|
753 | */
|
---|
754 | if (!empty($map['messageId'])) {
|
---|
755 |
|
---|
756 | foreach ($messagesIds as $k => $v) {
|
---|
757 | $r = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged" TEXT "Message-Id: '.$v.'"', SE_UID);
|
---|
758 |
|
---|
759 | if ($r) {
|
---|
760 | $messages = $messages + $r;
|
---|
761 | unset($messagesIds[$k]);
|
---|
762 | }
|
---|
763 | }
|
---|
764 |
|
---|
765 | /**
|
---|
766 | * Se é uma busca por messageNumber.
|
---|
767 | * Lembrando que, neste caso, só deve ser suportada uma única pasta no filtro.
|
---|
768 | */
|
---|
769 | } else {
|
---|
770 | $messages = imap_search($this->mbox, 'ALL KEYWORD "$Followupflagged"', SE_UID);
|
---|
771 | }
|
---|
772 |
|
---|
773 | /**
|
---|
774 | * Se é uma busca por messageId, deve ser comparado com os messageNumbers
|
---|
775 | * passados no filtro, se houverem.
|
---|
776 | */
|
---|
777 | if (!empty($map['messageNumber'])) {
|
---|
778 | foreach ($messages as $k => $m)
|
---|
779 | if (!in_array($m, $map['messageNumber']))
|
---|
780 | unset($messages[$k]);
|
---|
781 | }
|
---|
782 |
|
---|
783 | $s = true;
|
---|
784 | foreach ($messages as $k => $m) {
|
---|
785 | $s = imap_clearflag_full($this->mbox, $m, '$Followupflagged', ST_UID) && $s;
|
---|
786 | }
|
---|
787 |
|
---|
788 | /**
|
---|
789 | * Se é uma busca por messageId e todos os messageIds foram econstrados:
|
---|
790 | * Stop searching in all folders
|
---|
791 | */
|
---|
792 | if (!empty($map['messageId']) && empty($messagesIds))
|
---|
793 | break;
|
---|
794 | }
|
---|
795 |
|
---|
796 | return $s;
|
---|
797 | }
|
---|
798 | }
|
---|
799 |
|
---|
800 | //TODO - return
|
---|
801 | }
|
---|
802 |
|
---|
803 | public function deleteAll( $URI, $justthese = false, $criteria = false )
|
---|
804 | {
|
---|
805 | $op = $criteria['filter'][0];
|
---|
806 | $ids = $criteria['filter'][2];
|
---|
807 | if($op == 'IN'){
|
---|
808 | foreach ($ids as $id){
|
---|
809 | self::delete( array( 'concept' => $URI['concept'], 'id' => $id), false, false);
|
---|
810 | }
|
---|
811 | }
|
---|
812 |
|
---|
813 | /**
|
---|
814 | * TODO - implementar a deleção de todos os followupflaggeds conforme filtro
|
---|
815 | */
|
---|
816 | }
|
---|
817 |
|
---|
818 | public function update( $URI, $data, $criteria = false )
|
---|
819 | {
|
---|
820 | /**
|
---|
821 | * Os únicos atributos da sinalização presentes no IMAP são folderName, messageNumber e messageId,
|
---|
822 | * porém a operação de update desses atributos não faz sentido para o usuário da DataLayer,
|
---|
823 | * pois na prática elas são executadas através das operações de CREATE e DELETE.
|
---|
824 | * Assim, para os conceitos "labeled" e "followupflagged", só faz sentido o update de
|
---|
825 | * atributos gravados no banco de dados e nunca no IMAP.
|
---|
826 | */
|
---|
827 | }
|
---|
828 |
|
---|
829 | // public function retrieve( $concept, $id, $parents, $justthese = false, $criteria = false )
|
---|
830 | // {
|
---|
831 | // return $this->read( array( 'id' => $id,
|
---|
832 | // 'concept' => $concept,
|
---|
833 | // 'context' => $parents ), $justthese );
|
---|
834 | // }
|
---|
835 |
|
---|
836 | public function replace( $URI, $data, $criteria = false )
|
---|
837 | {}
|
---|
838 |
|
---|
839 | public function close()
|
---|
840 | {}
|
---|
841 |
|
---|
842 | public function setup()
|
---|
843 | {}
|
---|
844 |
|
---|
845 | public function commit( $uri )
|
---|
846 | { return( true ); }
|
---|
847 |
|
---|
848 | public function rollback( $uri )
|
---|
849 | {}
|
---|
850 |
|
---|
851 | public function begin( $uri )
|
---|
852 | {}
|
---|
853 |
|
---|
854 |
|
---|
855 | public function teardown()
|
---|
856 | {}
|
---|
857 |
|
---|
858 | function to_utf8($in)
|
---|
859 | {
|
---|
860 | if (is_array($in)) {
|
---|
861 | foreach ($in as $key => $value) {
|
---|
862 | $out[$this->to_utf8($key)] = $this->to_utf8($value);
|
---|
863 | }
|
---|
864 | } elseif(is_string($in)) {
|
---|
865 | return mb_convert_encoding( $in , 'UTF-8' , 'UTF-8 , ISO-8859-1' );
|
---|
866 | } else {
|
---|
867 | return $in;
|
---|
868 | }
|
---|
869 | return $out;
|
---|
870 | }
|
---|
871 |
|
---|
872 |
|
---|
873 | private static function parseFilter($filter ,&$map){
|
---|
874 |
|
---|
875 | if( !is_array( $filter ) || count($filter) <= 0) return null;
|
---|
876 |
|
---|
877 | $op = array_shift( $filter );
|
---|
878 | switch(strtolower($op))
|
---|
879 | {
|
---|
880 | case 'and': {
|
---|
881 | foreach ($filter as $term)
|
---|
882 | self::parseFilter($term ,&$map);
|
---|
883 | return;
|
---|
884 | }
|
---|
885 | case 'in': {
|
---|
886 | if(is_array($map[$filter[0]]) && is_array($filter[1]))
|
---|
887 | $map[$filter[0]] = array_unique(array_merge($map[$filter[0]], $filter[1]));
|
---|
888 | return;
|
---|
889 | }
|
---|
890 | case '=': {
|
---|
891 | $map[$filter[0]][] = $filter[1];
|
---|
892 | }
|
---|
893 | }
|
---|
894 | }
|
---|
895 |
|
---|
896 | }
|
---|