source: trunk/prototype/rest/catalog/DynamicContactResource.php @ 6783

Revision 6783, 11.2 KB checked in by tezza, 12 years ago (diff)

Ticket #2963 - Corrigido verificação da preferência do contato dinâmico.

RevLine 
[6473]1<?php
2
[6523]3if (!defined('ROOTPATH'))
4    define('ROOTPATH', dirname(__FILE__) . '/..');
[6473]5
[6523]6require_once(ROOTPATH . '/rest/hypermedia/hypermedia.php');
[6473]7
8use prototype\api\Config as Config;
9
10class DynamicContactResource extends Resource {
11
12    /**
13     * Retorna um contato recente
14     *
15     * @license    http://www.gnu.org/copyleft/gpl.html GPL
16     * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
17     * @sponsor    Caixa Econômica Federal
18     * @author     José Vicente Tezza Jr.
19     * @return     Retorna um contato recente
20     * @access     public
21     * */
[6523]22    function get($request, $id) {
[6473]23
[6523]24        $this->secured();
[6473]25
[6605]26        //verificar se a preferencia de contatos dinamicos nao esta ativada
27        if(!$this->isEnabledDynamicContacts(Config::me("uidNumber")) ){
28                $response = new Response($request);
29                $this->createException($request, $response, Response::UNAUTHORIZED, 'Resource unauthorized', 'disabled dynamic contacts preference');
30                return $response;
31        }
32
[6523]33        $response = new Response($request);
34        $response->addHeader('Content-type', 'aplication/json');
35        $response->code = Response::OK;
[6473]36
[6523]37        $h = new Hypermedia();
38        $c = new Collection($request->resources, 'DynamicContactResource', $id);
[6473]39
[6523]40        try {
41            $dynamicContact = Controller::read(
42                            array('concept' => 'dynamicContact'), false, array('filter' => array('AND', array('=', 'owner', Config::me("uidNumber")), array('=', 'id', $id)))
43            );
[6473]44
[6523]45            //Se nao foi encontrado contatos na consulta
46            if (!$dynamicContact) {
47                $this->createException($request, $response, Response::NOTFOUND, 'Bad request', 'Dynamic Contact not found.');
48                return $response;
49            }
50           
51            //Normaliza dado
52            if(is_array($dynamicContact))
53                $dynamicContact = $dynamicContact[0];
[6473]54
55
[6523]56            $t = new Template();
57            $d = new Data();
[6473]58
[6523]59            $d->setName('name');
60            $d->setValue(null);
61            $d->setPrompt('Nome do Contato Recente');
62            $d->setDataType('string');
63            $d->setMaxLength(100);
64            $d->setMinLength(null);
65            $d->setRequired(true);
[6473]66
[6523]67            $t->addData($d);
[6473]68
[6523]69            $d = new Data();
70            $d->setName('mail');
71            $d->setValue(null);
72            $d->setPrompt('Email do Contato Recente');
73            $d->setDataType('string');
74            $d->setMaxLength(100);
75            $d->setMinLength(null);
76            $d->setRequired(true);
[6473]77
[6523]78            $t->addData($d);
[6473]79
[6523]80            $d = new Data();
81            $d->setName('number_of_messages');
82            $d->setValue(null);
83            $d->setPrompt('Quantidade de mensagens enviadas');
84            $d->setDataType('integer');
85            $d->setMaxLength(100);
86            $d->setMinLength(null);
87            $d->setRequired(false);
[6473]88
[6523]89            $t->addData($d);
[6473]90
[6523]91            $c->setTemplate($t);
[6473]92
[6523]93            $d = new Data();
94            $d->setName('id');
95            $d->setValue($dynamicContact['id']);
96            $d->setPrompt('Identificador do Contato Recente');
97            $d->setDataType('integer');
98            $d->setMaxLength(null);
99            $d->setMinLength(null);
100            $d->setRequired(true);
[6473]101
[6523]102            $c->addData($d);
[6473]103
[6523]104            $d = new Data();
[6473]105
[6523]106            $d->setName('name');
107            $d->setValue($dynamicContact['name']);
108            $d->setPrompt('Nome do Contato Recente');
109            $d->setDataType('string');
110            $d->setMaxLength('100');
111            $d->setMinLength(null);
112            $d->setRequired(true);
[6473]113
[6523]114            $c->addData($d);
[6473]115
[6523]116            $d = new Data();
117            $d->setName('mail');
118            $d->setValue($dynamicContact['mail']);
119            $d->setPrompt('Email do Contato Recente');
120            $d->setDataType('string');
121            $d->setMaxLength('100');
122            $d->setMinLength(null);
123            $d->setRequired(true);
[6473]124
[6523]125            $c->addData($d);
[6473]126
[6523]127            $d = new Data();
128            $d->setName('number_of_messages');
129            $d->setValue($dynamicContact['number_of_messages']);
130            $d->setPrompt('Quantidade de mensagens enviadas');
131            $d->setDataType('integer');
132            $d->setMaxLength('100');
133            $d->setMinLength(null);
134            $d->setRequired(false);
[6473]135
[6523]136            $c->addData($d);
[6473]137
138
[6523]139            $l = new Link();
[6473]140
[6523]141            $l->setHref('');
142            $l->setRel('delete');
143            $l->setAlt('Remover');
144            $l->setPrompt('Remover');
145            $l->setRender('link');
[6473]146
[6523]147            $c->addLink($l);
[6473]148
[6523]149            $l = new Link();
150            $l->setHref('');
151            $l->setRel('put');
152            $l->setAlt('Atualizar');
153            $l->setPrompt('Atualizar');
154            $l->setRender('link');
[6473]155
[6523]156            $c->addLink($l);
[6473]157
158            $h->setCollection($c);
[6523]159        } catch (Exception $ex) {
160            $this->createException($request, $response, Response::INTERNALSERVERERROR, 'Internal Server Error', 'Internal Server Error');
161            return $response;
162        }
[6473]163
[6523]164        $response->body = $h->getHypermedia($request->accept[10][0]);
165        return $response;
166    }
[6473]167
168    /**
169     * Atualiza um contato recente
170     *
171     * @license    http://www.gnu.org/copyleft/gpl.html GPL
172     * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
173     * @sponsor    Caixa Econômica Federal
174     * @author     José Vicente Tezza Jr.
175     * @return     retorna a uri do contato recente
176     * @access     public
177     * */
[6523]178    function put($request, $id) {
179       
180        $this->secured();
[6473]181
[6605]182        //verificar se a preferencia de contatos dinamicos nao esta ativada
183        if(!$this->isEnabledDynamicContacts(Config::me("uidNumber")) ){
184                $response = new Response($request);
185                $this->createException($request, $response, Response::UNAUTHORIZED, 'Resource unauthorized', 'disabled dynamic contacts preference');
186                return $response;
187        }
188
189
[6523]190        $post = $request->dataDecoded;
191        $response = new Response($request);
[6473]192
[6523]193        if (count($post) == 0){
194            $this->createException($request, $response, Response::BADREQUEST, 'Bad request', 'Invalid template data');
195            return $response;
196        }
[6473]197
[6523]198        //recupera os atributos definidos no conceito 'user'
199        $map = Config::get('dynamicContact', 'PostgreSQL.mapping');
[6473]200
[6523]201        $params = array();
202        foreach ($post as $key => $value) {
[6473]203
[6523]204            if (!isset($map[$key]) || $key == 'id' || $key == 'timestamp' || $key == 'number_of_messages') {
205                continue;
206            }
207            $params[$key] = $value;
208        }
[6473]209
[6523]210        if (count($params) == 0) {
211            $this->createException($request, $response, Response::BADREQUEST, 'Bad request', 'Invalid template data');
212            return $response;
213        }
[6473]214
[6523]215        //completar os atributos
216        $params['owner'] = Config::me("uidNumber");
217        $params['timestamp'] = time();
218        $params['id'] = $id;
[6473]219
[6523]220        $response->addHeader('Content-type', 'aplication/json');
221        $response->code = Response::NOCONTENT;
[6473]222
[6523]223        try {
[6473]224
[6523]225            $dynamicContact = Controller::read(
226                            array('concept' => 'dynamicContact'), false, array('filter' => array(
227                            'AND',
228                            array('=', 'owner', Config::me("uidNumber")),
229                            array('=', 'id', $id)))
230            );
[6473]231
232
[6523]233            //Se existe o recurso
234            if ($dynamicContact) {
235                //Normaliza o recurso
236                if(is_array($dynamicContact))
237                    $dynamicContact = $dynamicContact[0];
[6512]238               
[6523]239                $params['number_of_messages'] = $dynamicContact['number_of_messages'] + 1;
[6473]240
[6523]241                $dynamicContact = Controller::update(array('concept' => 'dynamicContact', 'id' => $id), $params);
[6473]242
[6523]243                if (!$dynamicContact) {
244                    $this->createException($request, $response, Response::INTERNALSERVERERROR, 'Internal Server Error', Controller::service('PostgreSQL')->error);
245                    return $response;
246                }
247            } else {
248                /*
249                $idDynamicContact = Controller::create( array('concept' => 'dynamicContact'), $params);
250                */
251                //if (!$idDynamicContact) {
252                    $this->createException($request, $response, Response::NOTFOUND, 'Bad request', 'Invalid data');
253                    return $response;
254                //}
255            }
256        } catch (Exception $ex) {
257            $this->createException($request, $response, Response::INTERNALSERVERERROR, 'Internal Server Error', 'Internal Server Error');
258            return $response;
259        }
260        $response->body = json_encode(null);
261        return $response;
262    }
[6473]263
264    /**
265     * Remove um contato recente
266     *
267     * @license    http://www.gnu.org/copyleft/gpl.html GPL
268     * @author     Consórcio Expresso Livre - 4Linux (www.4linux.com.br) e Prognus Software Livre (www.prognus.com.br)
269     * @sponsor    Caixa Econômica Federal
270     * @author     José Vicente Tezza Jr.
271     * @access     public
272     * */
[6523]273    function delete($request, $id) {
[6473]274
[6523]275        $this->secured();
276
[6605]277        //verificar se a preferencia de contatos dinamicos nao esta ativada
278        if(!$this->isEnabledDynamicContacts(Config::me("uidNumber")) ){
279                $response = new Response($request);
280                $this->createException($request, $response, Response::UNAUTHORIZED, 'Resource unauthorized', 'disabled dynamic contacts preference');
281                return $response;
282        }
283
[6473]284        $response = new Response($request);
[6523]285        $response->addHeader('Content-type', 'aplication/json');
[6473]286        $response->code = Response::NOCONTENT;
287
[6523]288        try {
289            //Verifica se o recurso existe
290            $dinamicContact = Controller::read(array('concept' => 'dynamicContact', 'id' => $id));
[6473]291
[6523]292            //Se existe o recurso
293            if ($dinamicContact) {
[6473]294
[6523]295                $delete = Controller::delete(array('concept' => 'dynamicContact', 'id' => $id));
[6473]296
[6523]297                if (!$delete) {
298                    $this->createException($request, $response, Response::INTERNALSERVERERROR, 'Internal Server Error', Controller::service('PostgreSQL')->error);
299                    return $response;
[6473]300                }
[6523]301            } else {
302                $this->createException($request, $response, Response::NOTFOUND, 'Bad request', 'Invalid data');
303                return $response;
304            }
305        } catch (Exception $ex) {
306            $this->createException($request, $response, Response::INTERNALSERVERERROR, 'Internal Server Error', 'Internal Server Error');
307            return $response;
[6473]308        }
309
[6523]310        $response->body = json_encode(null);
311        return $response;
312    }
313   
314     private function createException($request, &$response, $code, $title, $description) {
315        $response->code = $code;
316         
317        $h = new Hypermedia();
318        $c = new Collection($request->resources, 'DynamicContactResource');
319        $e = new Error();
[6473]320
[6523]321        $e->setCode($code);
322        $e->setTitle($title);
323        $e->setDescription($description);
324       
325        $c->setError($e);
326        $h->setCollection($c);
[6473]327
[6523]328        $response->body = $h->getHypermedia($request->accept[10][0]);
329    }
330
[6605]331    private function isEnabledDynamicContacts($user){
332
[6783]333                //recuperando as preferencias (suas preferencias, preferencia padrão, preferencia obrigatoria)
334                //dos contatos dinamicos
335        $sql = 'SELECT preference_owner, preference_value '.
[6605]336                'FROM phpgw_preferences '.
337                'WHERE preference_app = \'expressoMail\' AND '.
[6783]338                        'preference_owner in (-1,-2, ' . $user . ')';
[6605]339
[6783]340        $preferences = Controller::service('PostgreSQL')->execResultSql($sql);
[6605]341
[6783]342                $array = array();
343        if(count($preferences) > 0){
344                        foreach($preferences as $preference){
345                                //recupera a preferencia
346                $preference_value = unserialize( $preference['preference_value'] );
347               
348                                //gera um array com o owner e o valor da preferencia:
349                                //true: SIM  (1)
350                                //false: NAO (0)
351                                //null: escolha pelo usuario/ usar padrao / sem padrao
352                                $value = null;
353                                if(isset($preference_value['use_dynamic_contacts'])){
354                                        $value = (isset($preference_value['use_dynamic_contacts'])) ? $preference_value['use_dynamic_contacts'] == '1' : false;
355                                }
356                                $array[ $preference['preference_owner'] ] = $value;
357                        }
358        }
[6605]359
[6783]360                //preferencia obrigatoria (SIM)
361                if(array_key_exists(-1,$array) && $array[-1]){
362                        return true;
363                }
364                //preferencia do user (SIM)
365                else if(array_key_exists($user,$array) && $array[$user] ){
366                        return true;
367                }
368                //preferencia padrao (SIM) escolhida pelo user
369                else if(array_key_exists($user, $array) && $array[$user] === null &&
370                        array_key_exists(-2, $array) && $array[-2]){
371                        return true;
372                }
373                return false;
[6605]374    }
[6473]375}
[6523]376
[6473]377?>
Note: See TracBrowser for help on using the repository browser.