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