Dotclear

source: plugins/TaC/inc/class.tac.php @ 2661

Revision 2661, 13.6 KB checked in by JcDenis, 13 years ago (diff)

TaC 0.2

  • Fixed user_id
Line 
1<?php
2# -- BEGIN LICENSE BLOCK ----------------------------------
3# This file is part of TaC, a plugin for Dotclear 2.
4#
5# Copyright (c) 2009-2010 JC Denis and contributors
6# jcdenis@gdwd.com
7#
8# Licensed under the GPL version 2.0 license.
9# A copy of this license is available in LICENSE file or at
10# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
11# -- END LICENSE BLOCK ------------------------------------
12
13
14class tac
15{
16     /* Vars */
17     /* Contains the last HTTP status code returned. */
18     public $http_code;
19     /* Contains the last API call. */
20     public $url;
21     /* Set up the API root URL. */
22     public $host = "https://api.twitter.com/1/";
23     /* Set timeout default. */
24     public $timeout = 30;
25     /* Set connect timeout. */
26     public $connecttimeout = 30; 
27     /* Verify SSL Cert. */
28     public $ssl_verifypeer = false;
29     /* Respons format. */
30     public $format = 'json';
31     /* Decode returned json data. */
32     public $decode_json = true;
33     /* Contains the last HTTP headers returned. */
34     public $http_info;
35     /* Set the useragnet. */
36     public $useragent = 'Dotclear-TaC v0.1-alpha1';
37     
38     
39     /* Core object */
40     private $core;
41     /* DB object */
42     private $con;
43     /* table prefix */
44     private $prefix;
45     /* oAuth method object */
46     private $sha1_method;
47     
48     /* consumer table name */
49     private $table_registry;
50     /* plugin_id */
51     private $plugin_id = null;
52     /* Array of plugin info from DB */
53     private $registry = null;
54     /* Array of user info from DB */
55     private $consumer = null;
56     
57     /* token table name */
58     private $table_access;
59     /* user_id */
60     private $user_id = null;
61     /* oAuth token (user) object */
62     private $access = null;
63     /* oAuth consumer (plugin) object */
64     private $token = null;
65     
66     
67     /* Constructeur
68      *
69      * $core : core object
70      * $cr_id : id du plugin
71      * $user_id : id de l'utilisateur sur le blog ou null pour un blog complet
72      */
73     public function __construct($core,$plugin_id='TaC',$user_id=null)
74     {
75          $this->core = $core;
76          $this->con = $this->core->con;
77          $this->prefix = $this->core->prefix;
78         
79          $this->table_registry = $this->prefix.'tac_registry';
80          $this->table_access = $this->prefix.'tac_access';
81         
82          $this->plugin_id = $plugin_id; //todo: test if plugin exists
83          $this->user_id = !$user_id ? null : $user_id; //todo: test if exists
84         
85          // TIC - Twitter Inline Content
86          // helper to easily acces user twitter account
87          $this->tic = new tacQuick($this);
88     }
89     
90     /* Retourne quelques statistiques sur l'utilisation de TaC */
91     public function stat()
92     {
93          $res = array(
94               'registry'=>array()
95          );
96         
97          $rrs = $this->con->select(
98               'SELECT registry_id, cr_id FROM '.$this->table_registry
99          );
100          while($rrs->fetch()) {
101               
102               $ars = $this->con->select(
103                    'SELECT count(ct_id) FROM '.$this->table_access.' '.
104                    "WHERE registry_id = '".$this->con->escape($rrs->registry_id)."' "
105               );
106               $res['registry'][$rrs->registry_id] = array(
107                    'id' => $rrs->cr_id,
108                    'access' => $ars->f(0)+0
109               );
110          }
111         
112          return $res;
113     }
114     
115     /* Test si un plugin est connu et si oui le charge */
116     public function checkRegistry()
117     {
118          // Il est déjà chargé
119          if ($this->registry) {
120               return true;
121          }
122          // Recherche en base
123          $rs = $this->getRegistry($this->plugin_id);
124         
125          // Il n'existe pas
126          if ($rs->isEmpty()) {
127               return false;
128          }
129         
130          // Il existe
131         
132          // On fait le ménage
133          $this->consumer = 
134          $this->registry = 
135          $this->token = 
136          $this->access = null;
137
138          // On charge la methode oAuth
139          $method = 'OAuthSignatureMethod_'.str_replace('-','_',$rs->cr_sig_method);
140          $this->sha1_method = new $method();
141         
142          // On charge l'object oAuth du consumer
143          $this->consumer = new OAuthConsumer($rs->cr_key,$rs->cr_secret);
144         
145          // On charge les infos dans la classe
146          $this->registry = $rs;
147         
148          return true;
149     }
150     
151     /* Get consumer (plugin) info according to its id (plugin id) */
152     public function getRegistry($cr_id)
153     {
154          return $this->con->select(
155               'SELECT * FROM '.$this->table_registry.' '.
156               "WHERE cr_id = '".$this->con->escape($cr_id)."' ".
157               $this->con->limit(1)
158          );
159     }
160     
161     /* Add a registry (from cursor) */
162     public function addRegistry($cur)
163     {
164          $this->con->writeLock($this->table_registry);
165         
166          try {
167               $rs = $this->con->select(
168                    'SELECT MAX(registry_id) FROM '.$this->table_registry
169               );
170               
171               $cur->registry_id = (integer) $rs->f(0) + 1;
172               $cur->registry_dt = date('Y-m-d H:i:s');
173               
174               //todo: $this->getRegistryCursor($cur);
175               
176               $cur->insert();
177               $this->con->unlock();
178          }
179          catch (Exception $e)
180          {
181               $this->con->unlock();
182               throw $e;
183          }
184         
185          return $cur->registry_id;
186     }
187     
188     /* Test si l'utilisateur est connu et si oui on le charge */
189     public function checkAccess()
190     {
191          if (!$this->registry) {
192               throw new Exception(__('Consumer not loaded'));
193          }
194          // Il est déjà chargé
195          if ($this->access) {
196               return true;
197          }
198          // Recherche en base
199          $rs = $this->getAccess($this->registry->registry_id,$this->user_id);
200         
201          // Il n'existe pas
202          if ($rs->isEmpty()) {
203               return false;
204          }
205         
206          // Il existe
207         
208          // On fait le ménage
209          $this->token = 
210          $this->access = null;
211         
212          // On charge l'objet oAuth de l'utilisateur
213          $this->token = new OAuthConsumer($rs->ct_token,$rs->ct_token_secret);
214         
215          // On charge les infos dans la classe
216          $this->access = $rs;
217         
218          return true;
219     }
220     
221     /* Get user  info according to there user_id, plugin id on current blog */
222     public function getAccess($registry_id,$user_id)
223     {
224          $registry_id = abs((integer) $registry_id);
225         
226          $req = 
227          'SELECT * FROM '.$this->table_access.' '.
228          "WHERE blog_id = '".$this->con->escape($this->core->blog->id)."' ".
229          "AND registry_id = '".$registry_id."' ";
230         
231          if ($user_id) {
232               $req .= "AND user_id = '".$this->con->escape($user_id)."' ";
233          }
234          else {
235               $req .= "AND user_id IS NULL ";
236          }
237         
238          return $this->con->select($req.$this->con->limit(1));
239     }
240     
241     /* Ajoute un utilistaeur en base */
242     public function addAccess($cur)
243     {
244          if (!$cur->registry_id) {
245               throw new Exception (__('No registry'));
246          }
247          if (!$cur->ct_id) {
248               throw new Exception (__('No id'));
249          }
250          if (!$cur->ct_token) {
251               throw new Exception (__('No token'));
252          }
253          if (!$cur->ct_token_secret) {
254               throw new Exception (__('No secret'));
255          }
256         
257          $this->con->writeLock($this->table_access);
258         
259          try {
260               $rs = $this->con->select(
261                    'SELECT MAX(access_id) FROM '.$this->table_access
262               );
263               
264               $cur->access_id = (integer) $rs->f(0) + 1;
265               $cur->access_dt = date('Y-m-d H:i:s');
266               $cur->blog_id = $this->core->blog->id;
267               
268               $cur->insert();
269               $this->con->unlock();
270          }
271          catch (Exception $e)
272          {
273               $this->con->unlock();
274               throw $e;
275          }
276         
277          return $cur->access_id;
278     }
279     
280     /* Efface un utilisteur dans la base */
281     public function delAccess($registry_id,$user_id)
282     {
283          $registry_id = abs((integer) $registry_id);
284         
285          $req = 
286          'DELETE FROM '.$this->table_access.' '.
287          "WHERE blog_id = '".$this->con->escape($this->core->blog->id)."' ".
288          "AND registry_id = '".$registry_id."' ";
289         
290          if ($user_id) {
291               $req .= "AND user_id = '".$this->con->escape($user_id)."' ";
292          }
293          else {
294               $req .= "AND user_id IS NULL ";
295          }
296         
297          $this->con->execute($req);
298     }
299     
300     /* Clean current user and session */
301     public function cleanAccess()
302     {
303          if (!$this->registry || !$this->access) {
304               return null;
305          }
306          $this->delAccess($this->registry->registry_id,$this->access->user_id);
307          unset($_SESSION['oauth_token']);
308          unset($_SESSION['oauth_token_secret']);
309         
310          return true;
311     }
312     
313     /* Get temporary token */
314     public function requestAccess($callback_url='',$sign_in=true)
315     {
316          if (!$this->registry) {
317               throw new Exception(__('Consumer not loaded'));
318          }
319         
320          $params = array();
321          if (!empty($callback_url)) {
322               $params['oauth_callback'] = $callback_url;
323          }
324         
325          // On effectue la requete auprès du server oAuth
326          $request = $this->query($this->registry->cr_url_request,'GET',$params);
327         
328          // Aille probleme de requete
329          if ($this->http_code != 200) {
330               throw new Exception(__('Failed to request access'));
331          }
332         
333          // On transforme la réponse pour la rendre lisible
334          $token = OAuthUtil::parse_parameters($request);
335          $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
336         
337          // On met en session les tokens temporaires
338          $_SESSION['oauth_token'] = $token['oauth_token'];
339          $_SESSION['oauth_token_secret'] = $token['oauth_token_secret'];
340         
341          // On retourne l'url qui permettra d'avoie les tokens définitifs
342          return $sign_in ?
343               $this->registry->cr_url_autorize.'?oauth_token='.$token['oauth_token'] : 
344               $this->registry->cr_url_authenticate.'?oauth_token='.$token['oauth_token'];
345     }
346     
347     /* Get final token */
348     public function grantAccess()
349     {
350          if (!$this->registry) {
351               throw new Exception(__('Consumer not loaded'));
352          }
353         
354          // On récupère les tokens temporaire depuis la session
355          $oauth_token = isset($_SESSION['oauth_token']) ? $_SESSION['oauth_token'] : '';
356          $oauth_token_secret = isset($_SESSION['oauth_token_secret']) ? $_SESSION['oauth_token_secret'] : '';
357          $request_token = isset($_REQUEST['oauth_token']) ? $_REQUEST['oauth_token'] : '';
358         
359          // On nettoye les infos temporaire de la session
360          unset($_SESSION['oauth_token']);
361          unset($_SESSION['oauth_token_secret']);
362         
363          // Si il sont différent de ceux retourné par l'url
364          // la session a expiré et donc on efface tout
365          if (!$oauth_token_secret || !$oauth_token 
366           || $request_token && $oauth_token !== $request_token)
367          {
368               $this->delAccess($this->registry->registry_id,$this->user_id);
369               
370               throw new Exception (__('Expired access'));
371          }
372         
373          // on charge l'objet de l'utilisateur
374          $this->token = new OAuthConsumer($oauth_token, $oauth_token_secret);
375         
376          // on demande un vérification
377          $params = array();
378          if (!empty($_REQUEST['oauth_verifier'])) {
379               $params['oauth_verifier'] = $_REQUEST['oauth_verifier'];
380          }
381          $request = $this->query($this->registry->cr_url_access,'GET',$params);
382         
383          if ($this->http_code != 200) {
384               throw new Exception(__('Failed to grant access'));
385          }
386         
387          // On transforme la réponse pour la rendre lisible
388          $token = OAuthUtil::parse_parameters($request);
389          $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
390         
391          // On sauve les tokens defintif en base
392          $cur = $this->con->openCursor($this->prefix.'tac_access');
393         
394          try {
395               $cur->registry_id = $this->registry->registry_id;
396               $cur->ct_id = $token['user_id'];
397               $cur->ct_token = $token['oauth_token'];
398               $cur->ct_token_secret = $token['oauth_token_secret'];
399               
400               if ($this->user_id) {
401                    $cur->user_id = $this->user_id;
402               }
403               
404               $this->addAccess($cur);
405          }
406          catch (Exception $e) {
407               throw New Exception(__('Failed to add access').$e->getMessage());
408          }
409         
410          return true;
411     }
412     
413     /* GET wrapper for query */
414     public function get($url,$parameters=array())
415     {
416          $response = $this->query($url,'GET',$parameters);
417          if ($this->format === 'json' && $this->decode_json) {
418               return json_decode($response);
419          }
420          return $response;
421     }
422     
423     /* POST wrapper for query */
424     public function post($url,$parameters=array())
425     {
426          $response = $this->query($url,'POST',$parameters);
427          if ($this->format === 'json' && $this->decode_json) {
428               return json_decode($response);
429          }
430          return $response;
431     }
432     
433     /* DELETE wrapper for query */
434     public function delete($url,$parameters=array())
435     {
436          $response = $this->query($url,'DELETE',$parameters);
437          if ($this->format === 'json' && $this->decode_json) {
438               return json_decode($response);
439          }
440          return $response;
441     }
442     
443     /* Query with oAuth signature */
444     private function query($url,$method,$parameters)
445     {
446          if (strrpos($url,'https://') !== 0 && strrpos($url,'http://') !== 0) {
447               $url = $this->host.$url.'.'.$this->format;
448          }
449          $request = OAuthRequest::from_consumer_and_token($this->consumer,$this->token,$method,$url,$parameters);
450          $request->sign_request($this->sha1_method,$this->consumer,$this->token);
451         
452          switch ($method) {
453               case 'GET':
454                    return $this->http($request->to_url(),'GET');
455               default:
456                    return $this->http($request->get_normalized_http_url(),$method,$request->to_postdata());
457          }
458     }
459     
460     //!!! rewrite it with clearbricks net htttp !!!
461     private function http($url, $method, $postfields = NULL)
462     {
463          $this->http_info = array();
464          $ci = curl_init();
465         
466          /* Curl settings */
467          curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
468          curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
469          curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
470          curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
471          curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
472          curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
473          curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this,'getHeader'));
474          curl_setopt($ci, CURLOPT_HEADER, FALSE);
475
476          switch ($method) {
477               case 'POST':
478                    curl_setopt($ci, CURLOPT_POST, TRUE);
479                    if (!empty($postfields)) {
480                         curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
481                    }
482                    break;
483               case 'DELETE':
484                    curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
485                    if (!empty($postfields)) {
486                         $url = "{$url}?{$postfields}";
487                    }
488          }
489
490          curl_setopt($ci,CURLOPT_URL,$url);
491          $response = curl_exec($ci);
492          $this->http_code = curl_getinfo($ci,CURLINFO_HTTP_CODE);
493          $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
494          $this->url = $url;
495          curl_close ($ci);
496         
497          return $response;
498     }
499     
500     private function getHeader($ch, $header)
501     {
502          $i = strpos($header, ':');
503          if (!empty($i)) {
504               $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
505               $value = trim(substr($header, $i + 2));
506               $this->http_header[$key] = $value;
507          }
508          return strlen($header);
509     }
510}
511?>
Note: See TracBrowser for help on using the repository browser.

Sites map