From 4eeb9c5b9944368611447530ef17007f9e4a9cce Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Sat, 7 Jul 2012 11:30:48 -0400 Subject: [PATCH 001/330] Fix indentation and lower case the whole url inside handle() instead of calling for each parameter --- lib/ocs.php | 747 ++++++++++++++++++++++++++-------------------------- 1 file changed, 371 insertions(+), 376 deletions(-) diff --git a/lib/ocs.php b/lib/ocs.php index 1be41202d7..25854e9ea3 100644 --- a/lib/ocs.php +++ b/lib/ocs.php @@ -29,429 +29,424 @@ */ class OC_OCS { - /** - * reads input date from get/post/cookies and converts the date to a special data-type - * - * @param variable $key - * @param variable-type $type - * @param priority $getpriority - * @param default $default - * @return data - */ - public static function readData($key,$type='raw',$getpriority=false,$default='') { - if($getpriority) { - if(isset($_GET[$key])) { - $data=$_GET[$key]; - } elseif(isset($_POST[$key])) { - $data=$_POST[$key]; - } else { - if($default=='') { - if(($type=='int') or ($type=='float')) $data=0; else $data=''; - } else { - $data=$default; - } - } - } else { - if(isset($_POST[$key])) { - $data=$_POST[$key]; - } elseif(isset($_GET[$key])) { - $data=$_GET[$key]; - } elseif(isset($_COOKIE[$key])) { - $data=$_COOKIE[$key]; - } else { - if($default=='') { - if(($type=='int') or ($type=='float')) $data=0; else $data=''; - } else { - $data=$default; - } - } - } + /** + * reads input date from get/post/cookies and converts the date to a special data-type + * + * @param variable $key + * @param variable-type $type + * @param priority $getpriority + * @param default $default + * @return data + */ + public static function readData($key,$type='raw',$getpriority=false,$default='') { + if($getpriority) { + if(isset($_GET[$key])) { + $data=$_GET[$key]; + } elseif(isset($_POST[$key])) { + $data=$_POST[$key]; + } else { + if($default=='') { + if(($type=='int') or ($type=='float')) $data=0; else $data=''; + } else { + $data=$default; + } + } + } else { + if(isset($_POST[$key])) { + $data=$_POST[$key]; + } elseif(isset($_GET[$key])) { + $data=$_GET[$key]; + } elseif(isset($_COOKIE[$key])) { + $data=$_COOKIE[$key]; + } else { + if($default=='') { + if(($type=='int') or ($type=='float')) $data=0; else $data=''; + } else { + $data=$default; + } + } + } - if($type=='raw') return($data); - elseif($type=='text') return(addslashes(strip_tags($data))); - elseif($type=='int') { $data = (int) $data; return($data); } - elseif($type=='float') { $data = (float) $data; return($data); } - elseif($type=='array') { $data = $data; return($data); } - } + if($type=='raw') return($data); + elseif($type=='text') return(addslashes(strip_tags($data))); + elseif($type=='int') { $data = (int) $data; return($data); } + elseif($type=='float') { $data = (float) $data; return($data); } + elseif($type=='array') { $data = $data; return($data); } + } /** main function to handle the REST request **/ - public static function handle() { - - // overwrite the 404 error page returncode - header("HTTP/1.0 200 OK"); + public static function handle() { + // overwrite the 404 error page returncode + header("HTTP/1.0 200 OK"); - if($_SERVER['REQUEST_METHOD'] == 'GET') { - $method='get'; - }elseif($_SERVER['REQUEST_METHOD'] == 'PUT') { - $method='put'; - parse_str(file_get_contents("php://input"),$put_vars); - }elseif($_SERVER['REQUEST_METHOD'] == 'POST') { - $method='post'; - }else{ - echo('internal server error: method not supported'); - exit(); - } + if($_SERVER['REQUEST_METHOD'] == 'GET') { + $method='get'; + }elseif($_SERVER['REQUEST_METHOD'] == 'PUT') { + $method='put'; + parse_str(file_get_contents("php://input"),$put_vars); + }elseif($_SERVER['REQUEST_METHOD'] == 'POST') { + $method='post'; + }else{ + echo('internal server error: method not supported'); + exit(); + } - // preprocess url - $url=$_SERVER['REQUEST_URI']; - if(substr($url,(strlen($url)-1))<>'/') $url.='/'; - $ex=explode('/',$url); - $paracount=count($ex); + // preprocess url + $url = strtolower($_SERVER['REQUEST_URI']); + if(substr($url,(strlen($url)-1))<>'/') $url.='/'; + $ex=explode('/',$url); + $paracount=count($ex); - // eventhandler - // CONFIG - // apiconfig - GET - CONFIG - if(($method=='get') and (strtolower($ex[$paracount-3])=='v1.php') and (strtolower($ex[$paracount-2])=='config')){ - $format=OC_OCS::readdata('format','text'); - OC_OCS::apiconfig($format); + // eventhandler + // CONFIG + // apiconfig - GET - CONFIG + if(($method=='get') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'config')){ + $format=OC_OCS::readdata('format','text'); + OC_OCS::apiconfig($format); - // PERSON - // personcheck - POST - PERSON/CHECK - }elseif(($method=='post') and (strtolower($ex[$paracount-4])=='v1.php') and (strtolower($ex[$paracount-3])=='person') and (strtolower($ex[$paracount-2])=='check')){ - $format=OC_OCS::readdata('format','text'); - $login=OC_OCS::readdata('login','text'); - $passwd=OC_OCS::readdata('password','text'); - OC_OCS::personcheck($format,$login,$passwd); + // PERSON + // personcheck - POST - PERSON/CHECK + }elseif(($method=='post') and ($ex[$paracount-4] == 'v1.php') and ($ex[$paracount-3]=='person') and ($ex[$paracount-2] == 'check')){ + $format=OC_OCS::readdata('format','text'); + $login=OC_OCS::readdata('login','text'); + $passwd=OC_OCS::readdata('password','text'); + OC_OCS::personcheck($format,$login,$passwd); - // ACTIVITY - // activityget - GET ACTIVITY page,pagesize als urlparameter - }elseif(($method=='get') and (strtolower($ex[$paracount-3])=='v1.php')and (strtolower($ex[$paracount-2])=='activity')){ - $format=OC_OCS::readdata('format','text'); - $page=OC_OCS::readdata('page','int'); - $pagesize=OC_OCS::readdata('pagesize','int'); - if($pagesize<1 or $pagesize>100) $pagesize=10; - OC_OCS::activityget($format,$page,$pagesize); + // ACTIVITY + // activityget - GET ACTIVITY page,pagesize als urlparameter + }elseif(($method=='get') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'activity')){ + $format=OC_OCS::readdata('format','text'); + $page=OC_OCS::readdata('page','int'); + $pagesize=OC_OCS::readdata('pagesize','int'); + if($pagesize<1 or $pagesize>100) $pagesize=10; + OC_OCS::activityget($format,$page,$pagesize); - // activityput - POST ACTIVITY - }elseif(($method=='post') and (strtolower($ex[$paracount-3])=='v1.php')and (strtolower($ex[$paracount-2])=='activity')){ - $format=OC_OCS::readdata('format','text'); - $message=OC_OCS::readdata('message','text'); - OC_OCS::activityput($format,$message); + // activityput - POST ACTIVITY + }elseif(($method=='post') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'activity')){ + $format=OC_OCS::readdata('format','text'); + $message=OC_OCS::readdata('message','text'); + OC_OCS::activityput($format,$message); - // PRIVATEDATA - // get - GET DATA - }elseif(($method=='get') and (strtolower($ex[$paracount-4])=='v1.php')and (strtolower($ex[$paracount-2])=='getattribute')){ - $format=OC_OCS::readdata('format','text'); - OC_OCS::privateDataGet($format); + // PRIVATEDATA + // get - GET DATA + }elseif(($method=='get') and ($ex[$paracount-4] == 'v1.php') and ($ex[$paracount-2] == 'getattribute')){ + $format=OC_OCS::readdata('format','text'); + OC_OCS::privateDataGet($format); - }elseif(($method=='get') and (strtolower($ex[$paracount-5])=='v1.php')and (strtolower($ex[$paracount-3])=='getattribute')){ - $format=OC_OCS::readdata('format','text'); - $app=$ex[$paracount-2]; - OC_OCS::privateDataGet($format, $app); - }elseif(($method=='get') and (strtolower($ex[$paracount-6])=='v1.php')and (strtolower($ex[$paracount-4])=='getattribute')){ - $format=OC_OCS::readdata('format','text'); - $key=$ex[$paracount-2]; - $app=$ex[$paracount-3]; - OC_OCS::privateDataGet($format, $app,$key); + }elseif(($method=='get') and ($ex[$paracount-5] == 'v1.php') and ($ex[$paracount-3] == 'getattribute')){ + $format=OC_OCS::readdata('format','text'); + $app=$ex[$paracount-2]; + OC_OCS::privateDataGet($format, $app); + }elseif(($method=='get') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-4] == 'getattribute')){ + $format=OC_OCS::readdata('format','text'); + $key=$ex[$paracount-2]; + $app=$ex[$paracount-3]; + OC_OCS::privateDataGet($format, $app,$key); - // set - POST DATA - }elseif(($method=='post') and (strtolower($ex[$paracount-6])=='v1.php')and (strtolower($ex[$paracount-4])=='setattribute')){ - $format=OC_OCS::readdata('format','text'); - $key=$ex[$paracount-2]; - $app=$ex[$paracount-3]; - $value=OC_OCS::readdata('value','text'); - OC_OCS::privatedataset($format, $app, $key, $value); - // delete - POST DATA - }elseif(($method=='post') and (strtolower($ex[$paracount-6])=='v1.php')and (strtolower($ex[$paracount-4])=='deleteattribute')){ - $format=OC_OCS::readdata('format','text'); - $key=$ex[$paracount-2]; - $app=$ex[$paracount-3]; - OC_OCS::privatedatadelete($format, $app, $key); + // set - POST DATA + }elseif(($method=='post') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-4] == 'setattribute')){ + $format=OC_OCS::readdata('format','text'); + $key=$ex[$paracount-2]; + $app=$ex[$paracount-3]; + $value=OC_OCS::readdata('value','text'); + OC_OCS::privatedataset($format, $app, $key, $value); + // delete - POST DATA + }elseif(($method=='post') and ($ex[$paracount-6] =='v1.php') and ($ex[$paracount-4] == 'deleteattribute')){ + $format=OC_OCS::readdata('format','text'); + $key=$ex[$paracount-2]; + $app=$ex[$paracount-3]; + OC_OCS::privatedatadelete($format, $app, $key); - }else{ - $format=OC_OCS::readdata('format','text'); - $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n"; - $txt.=OC_OCS::getdebugoutput(); - echo(OC_OCS::generatexml($format,'failed',999,$txt)); - } - exit(); - } + }else{ + $format=OC_OCS::readdata('format','text'); + $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n"; + $txt.=OC_OCS::getdebugoutput(); + echo(OC_OCS::generatexml($format,'failed',999,$txt)); + } + exit(); + } - /** - * generated some debug information to make it easier to find faild API calls - * @return debug data string - */ - private static function getDebugOutput() { - $txt=''; - $txt.="debug output:\n"; - if(isset($_SERVER['REQUEST_METHOD'])) $txt.='http request method: '.$_SERVER['REQUEST_METHOD']."\n"; - if(isset($_SERVER['REQUEST_URI'])) $txt.='http request uri: '.$_SERVER['REQUEST_URI']."\n"; - if(isset($_GET)) foreach($_GET as $key=>$value) $txt.='get parameter: '.$key.'->'.$value."\n"; - if(isset($_POST)) foreach($_POST as $key=>$value) $txt.='post parameter: '.$key.'->'.$value."\n"; - return($txt); - } + /** + * generated some debug information to make it easier to find faild API calls + * @return debug data string + */ + private static function getDebugOutput() { + $txt=''; + $txt.="debug output:\n"; + if(isset($_SERVER['REQUEST_METHOD'])) $txt.='http request method: '.$_SERVER['REQUEST_METHOD']."\n"; + if(isset($_SERVER['REQUEST_URI'])) $txt.='http request uri: '.$_SERVER['REQUEST_URI']."\n"; + if(isset($_GET)) foreach($_GET as $key=>$value) $txt.='get parameter: '.$key.'->'.$value."\n"; + if(isset($_POST)) foreach($_POST as $key=>$value) $txt.='post parameter: '.$key.'->'.$value."\n"; + return($txt); + } - /** - * checks if the user is authenticated - * checks the IP whitlist, apikeys and login/password combination - * if $forceuser is true and the authentication failed it returns an 401 http response. - * if $forceuser is false and authentification fails it returns an empty username string - * @param bool $forceuser - * @return username string - */ - private static function checkPassword($forceuser=true) { - //valid user account ? - if(isset($_SERVER['PHP_AUTH_USER'])) $authuser=$_SERVER['PHP_AUTH_USER']; else $authuser=''; - if(isset($_SERVER['PHP_AUTH_PW'])) $authpw=$_SERVER['PHP_AUTH_PW']; else $authpw=''; + /** + * checks if the user is authenticated + * checks the IP whitlist, apikeys and login/password combination + * if $forceuser is true and the authentication failed it returns an 401 http response. + * if $forceuser is false and authentification fails it returns an empty username string + * @param bool $forceuser + * @return username string + */ + private static function checkPassword($forceuser=true) { + //valid user account ? + if(isset($_SERVER['PHP_AUTH_USER'])) $authuser=$_SERVER['PHP_AUTH_USER']; else $authuser=''; + if(isset($_SERVER['PHP_AUTH_PW'])) $authpw=$_SERVER['PHP_AUTH_PW']; else $authpw=''; - if(empty($authuser)) { - if($forceuser){ - header('WWW-Authenticate: Basic realm="your valid user account or api key"'); - header('HTTP/1.0 401 Unauthorized'); - exit; - }else{ - $identifieduser=''; - } - }else{ - if(!OC_User::login($authuser,$authpw)){ - if($forceuser){ - header('WWW-Authenticate: Basic realm="your valid user account or api key"'); - header('HTTP/1.0 401 Unauthorized'); - exit; - }else{ - $identifieduser=''; - } - }else{ - $identifieduser=$authuser; - } - } + if(empty($authuser)) { + if($forceuser){ + header('WWW-Authenticate: Basic realm="your valid user account or api key"'); + header('HTTP/1.0 401 Unauthorized'); + exit; + }else{ + $identifieduser=''; + } + }else{ + if(!OC_User::login($authuser,$authpw)){ + if($forceuser){ + header('WWW-Authenticate: Basic realm="your valid user account or api key"'); + header('HTTP/1.0 401 Unauthorized'); + exit; + }else{ + $identifieduser=''; + } + }else{ + $identifieduser=$authuser; + } + } - return($identifieduser); - } + return($identifieduser); + } - /** - * generates the xml or json response for the API call from an multidimenional data array. - * @param string $format - * @param string $status - * @param string $statuscode - * @param string $message - * @param array $data - * @param string $tag - * @param string $tagattribute - * @param int $dimension - * @param int $itemscount - * @param int $itemsperpage - * @return string xml/json - */ - private static function generateXml($format,$status,$statuscode,$message,$data=array(),$tag='',$tagattribute='',$dimension=-1,$itemscount='',$itemsperpage='') { - if($format=='json') { + /** + * generates the xml or json response for the API call from an multidimenional data array. + * @param string $format + * @param string $status + * @param string $statuscode + * @param string $message + * @param array $data + * @param string $tag + * @param string $tagattribute + * @param int $dimension + * @param int $itemscount + * @param int $itemsperpage + * @return string xml/json + */ + private static function generateXml($format,$status,$statuscode,$message,$data=array(),$tag='',$tagattribute='',$dimension=-1,$itemscount='',$itemsperpage='') { + if($format=='json') { + $json=array(); + $json['status']=$status; + $json['statuscode']=$statuscode; + $json['message']=$message; + $json['totalitems']=$itemscount; + $json['itemsperpage']=$itemsperpage; + $json['data']=$data; + return(json_encode($json)); + }else{ + $txt=''; + $writer = xmlwriter_open_memory(); + xmlwriter_set_indent( $writer, 2 ); + xmlwriter_start_document($writer ); + xmlwriter_start_element($writer,'ocs'); + xmlwriter_start_element($writer,'meta'); + xmlwriter_write_element($writer,'status',$status); + xmlwriter_write_element($writer,'statuscode',$statuscode); + xmlwriter_write_element($writer,'message',$message); + if($itemscount<>'') xmlwriter_write_element($writer,'totalitems',$itemscount); + if(!empty($itemsperpage)) xmlwriter_write_element($writer,'itemsperpage',$itemsperpage); + xmlwriter_end_element($writer); + if($dimension=='0') { + // 0 dimensions + xmlwriter_write_element($writer,'data',$data); - $json=array(); - $json['status']=$status; - $json['statuscode']=$statuscode; - $json['message']=$message; - $json['totalitems']=$itemscount; - $json['itemsperpage']=$itemsperpage; - $json['data']=$data; - return(json_encode($json)); + }elseif($dimension=='1') { + xmlwriter_start_element($writer,'data'); + foreach($data as $key=>$entry) { + xmlwriter_write_element($writer,$key,$entry); + } + xmlwriter_end_element($writer); + }elseif($dimension=='2') { + xmlwriter_start_element($writer,'data'); + foreach($data as $entry) { + xmlwriter_start_element($writer,$tag); + if(!empty($tagattribute)) { + xmlwriter_write_attribute($writer,'details',$tagattribute); + } + foreach($entry as $key=>$value) { + if(is_array($value)){ + foreach($value as $k=>$v) { + xmlwriter_write_element($writer,$k,$v); + } + } else { + xmlwriter_write_element($writer,$key,$value); + } + } + xmlwriter_end_element($writer); + } + xmlwriter_end_element($writer); - }else{ - $txt=''; - $writer = xmlwriter_open_memory(); - xmlwriter_set_indent( $writer, 2 ); - xmlwriter_start_document($writer ); - xmlwriter_start_element($writer,'ocs'); - xmlwriter_start_element($writer,'meta'); - xmlwriter_write_element($writer,'status',$status); - xmlwriter_write_element($writer,'statuscode',$statuscode); - xmlwriter_write_element($writer,'message',$message); - if($itemscount<>'') xmlwriter_write_element($writer,'totalitems',$itemscount); - if(!empty($itemsperpage)) xmlwriter_write_element($writer,'itemsperpage',$itemsperpage); - xmlwriter_end_element($writer); - if($dimension=='0') { - // 0 dimensions - xmlwriter_write_element($writer,'data',$data); + }elseif($dimension=='3') { + xmlwriter_start_element($writer,'data'); + foreach($data as $entrykey=>$entry) { + xmlwriter_start_element($writer,$tag); + if(!empty($tagattribute)) { + xmlwriter_write_attribute($writer,'details',$tagattribute); + } + foreach($entry as $key=>$value) { + if(is_array($value)){ + xmlwriter_start_element($writer,$entrykey); + foreach($value as $k=>$v) { + xmlwriter_write_element($writer,$k,$v); + } + xmlwriter_end_element($writer); + } else { + xmlwriter_write_element($writer,$key,$value); + } + } + xmlwriter_end_element($writer); + } + xmlwriter_end_element($writer); + }elseif($dimension=='dynamic') { + xmlwriter_start_element($writer,'data'); + OC_OCS::toxml($writer,$data,'comment'); + xmlwriter_end_element($writer); + } - }elseif($dimension=='1') { - xmlwriter_start_element($writer,'data'); - foreach($data as $key=>$entry) { - xmlwriter_write_element($writer,$key,$entry); - } - xmlwriter_end_element($writer); + xmlwriter_end_element($writer); - }elseif($dimension=='2') { - xmlwriter_start_element($writer,'data'); - foreach($data as $entry) { - xmlwriter_start_element($writer,$tag); - if(!empty($tagattribute)) { - xmlwriter_write_attribute($writer,'details',$tagattribute); - } - foreach($entry as $key=>$value) { - if(is_array($value)){ - foreach($value as $k=>$v) { - xmlwriter_write_element($writer,$k,$v); - } - } else { - xmlwriter_write_element($writer,$key,$value); - } - } - xmlwriter_end_element($writer); - } - xmlwriter_end_element($writer); + xmlwriter_end_document( $writer ); + $txt.=xmlwriter_output_memory( $writer ); + unset($writer); + return($txt); + } + } - }elseif($dimension=='3') { - xmlwriter_start_element($writer,'data'); - foreach($data as $entrykey=>$entry) { - xmlwriter_start_element($writer,$tag); - if(!empty($tagattribute)) { - xmlwriter_write_attribute($writer,'details',$tagattribute); - } - foreach($entry as $key=>$value) { - if(is_array($value)){ - xmlwriter_start_element($writer,$entrykey); - foreach($value as $k=>$v) { - xmlwriter_write_element($writer,$k,$v); - } - xmlwriter_end_element($writer); - } else { - xmlwriter_write_element($writer,$key,$value); - } - } - xmlwriter_end_element($writer); - } - xmlwriter_end_element($writer); - }elseif($dimension=='dynamic') { - xmlwriter_start_element($writer,'data'); - OC_OCS::toxml($writer,$data,'comment'); - xmlwriter_end_element($writer); - } - - xmlwriter_end_element($writer); - - xmlwriter_end_document( $writer ); - $txt.=xmlwriter_output_memory( $writer ); - unset($writer); - return($txt); - } - } - - public static function toXml($writer,$data,$node) { - foreach($data as $key => $value) { - if (is_numeric($key)) { - $key = $node; - } - if (is_array($value)){ - xmlwriter_start_element($writer,$key); - OC_OCS::toxml($writer,$value,$node); - xmlwriter_end_element($writer); - }else{ - xmlwriter_write_element($writer,$key,$value); - } - - } - } + public static function toXml($writer,$data,$node) { + foreach($data as $key => $value) { + if (is_numeric($key)) { + $key = $node; + } + if (is_array($value)){ + xmlwriter_start_element($writer,$key); + OC_OCS::toxml($writer,$value,$node); + xmlwriter_end_element($writer); + }else{ + xmlwriter_write_element($writer,$key,$value); + } + } + } - /** - * return the config data of this server - * @param string $format - * @return string xml/json - */ - private static function apiConfig($format) { - $user=OC_OCS::checkpassword(false); - $url=substr(OCP\Util::getServerHost().$_SERVER['SCRIPT_NAME'],0,-11).''; + /** + * return the config data of this server + * @param string $format + * @return string xml/json + */ + private static function apiConfig($format) { + $user=OC_OCS::checkpassword(false); + $url=substr(OCP\Util::getServerHost().$_SERVER['SCRIPT_NAME'],0,-11).''; - $xml['version']='1.5'; - $xml['website']='ownCloud'; - $xml['host']=OCP\Util::getServerHost(); - $xml['contact']=''; - $xml['ssl']='false'; - echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'config','',1)); - } + $xml['version']='1.5'; + $xml['website']='ownCloud'; + $xml['host']=OCP\Util::getServerHost(); + $xml['contact']=''; + $xml['ssl']='false'; + echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'config','',1)); + } - /** - * check if the provided login/apikey/password is valid - * @param string $format - * @param string $login - * @param string $passwd - * @return string xml/json - */ - private static function personCheck($format,$login,$passwd) { - if($login<>''){ - if(OC_User::login($login,$passwd)){ - $xml['person']['personid']=$login; - echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'person','check',2)); - }else{ - echo(OC_OCS::generatexml($format,'failed',102,'login not valid')); - } - }else{ - echo(OC_OCS::generatexml($format,'failed',101,'please specify all mandatory fields')); - } - } + /** + * check if the provided login/apikey/password is valid + * @param string $format + * @param string $login + * @param string $passwd + * @return string xml/json + */ + private static function personCheck($format,$login,$passwd) { + if($login<>''){ + if(OC_User::login($login,$passwd)){ + $xml['person']['personid']=$login; + echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'person','check',2)); + }else{ + echo(OC_OCS::generatexml($format,'failed',102,'login not valid')); + } + }else{ + echo(OC_OCS::generatexml($format,'failed',101,'please specify all mandatory fields')); + } + } - // ACTIVITY API ############################################# + // ACTIVITY API ############################################# - /** - * get my activities - * @param string $format - * @param string $page - * @param string $pagesize - * @return string xml/json - */ - private static function activityGet($format,$page,$pagesize) { - $user=OC_OCS::checkpassword(); - - //TODO + /** + * get my activities + * @param string $format + * @param string $page + * @param string $pagesize + * @return string xml/json + */ + private static function activityGet($format,$page,$pagesize) { + $user=OC_OCS::checkpassword(); - $txt=OC_OCS::generatexml($format,'ok',100,'',$xml,'activity','full',2,$totalcount,$pagesize); - echo($txt); - } + //TODO - /** - * submit a activity - * @param string $format - * @param string $message - * @return string xml/json - */ - private static function activityPut($format,$message) { - // not implemented in ownCloud - $user=OC_OCS::checkpassword(); - echo(OC_OCS::generatexml($format,'ok',100,'')); - } + $txt=OC_OCS::generatexml($format,'ok',100,'',$xml,'activity','full',2,$totalcount,$pagesize); + echo($txt); + } - // PRIVATEDATA API ############################################# + /** + * submit a activity + * @param string $format + * @param string $message + * @return string xml/json + */ + private static function activityPut($format,$message) { + // not implemented in ownCloud + $user=OC_OCS::checkpassword(); + echo(OC_OCS::generatexml($format,'ok',100,'')); + } - /** - * get private data and create the xml for ocs - * @param string $format - * @param string $app - * @param string $key - * @return string xml/json - */ - private static function privateDataGet($format,$app="",$key="") { - $user=OC_OCS::checkpassword(); - $result=OC_OCS::getData($user,$app,$key); - $xml=array(); - foreach($result as $i=>$log) { - $xml[$i]['key']=$log['key']; - $xml[$i]['app']=$log['app']; - $xml[$i]['value']=$log['value']; - } + // PRIVATEDATA API ############################################# + + /** + * get private data and create the xml for ocs + * @param string $format + * @param string $app + * @param string $key + * @return string xml/json + */ + private static function privateDataGet($format,$app="",$key="") { + $user=OC_OCS::checkpassword(); + $result=OC_OCS::getData($user,$app,$key); + $xml=array(); + foreach($result as $i=>$log) { + $xml[$i]['key']=$log['key']; + $xml[$i]['app']=$log['app']; + $xml[$i]['value']=$log['value']; + } - $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'privatedata', 'full', 2, count($xml), 0);//TODO: replace 'privatedata' with 'attribute' once a new libattice has been released that works with it - echo($txt); - } + $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'privatedata', 'full', 2, count($xml), 0);//TODO: replace 'privatedata' with 'attribute' once a new libattice has been released that works with it + echo($txt); + } - /** - * set private data referenced by $key to $value and generate the xml for ocs - * @param string $format - * @param string $app - * @param string $key - * @param string $value - * @return string xml/json - */ + /** + * set private data referenced by $key to $value and generate the xml for ocs + * @param string $format + * @param string $app + * @param string $key + * @param string $value + * @return string xml/json + */ private static function privateDataSet($format, $app, $key, $value) { $user=OC_OCS::checkpassword(); if(OC_OCS::setData($user,$app,$key,$value)){ From e8657c51ba8499fe0f0f46eaa1a8503bff2d2b2a Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Sat, 7 Jul 2012 14:51:06 -0400 Subject: [PATCH 002/330] Implement PERSON add --- lib/ocs.php | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/lib/ocs.php b/lib/ocs.php index 25854e9ea3..309e3bb064 100644 --- a/lib/ocs.php +++ b/lib/ocs.php @@ -75,9 +75,9 @@ class OC_OCS { } - /** - main function to handle the REST request - **/ + /** + main function to handle the REST request + **/ public static function handle() { // overwrite the 404 error page returncode header("HTTP/1.0 200 OK"); @@ -115,7 +115,20 @@ class OC_OCS { $login=OC_OCS::readdata('login','text'); $passwd=OC_OCS::readdata('password','text'); OC_OCS::personcheck($format,$login,$passwd); - + } else if ($method == 'post' && $ex[$paracount - 4] == 'v1.php' && $ex[$paracount - 3] == 'person' && $ex[$paracount - 2] == 'add') { + $format = self::readData('format', 'text'); + if (OC_Group::inGroup(self::checkPassword(), 'admin')) { + $login = self::readData('login', 'text'); + $password = self::readData('password', 'text'); + try { + OC_User::createUser($login, $password); + echo self::generateXml($format, 'ok', 201, ''); + } catch (Exception $exception) { + echo self::generateXml($format, 'fail', 400, $exception->getMessage()); + } + } else { + echo self::generateXml($format, 'fail', 403, 'Permission denied'); + } // ACTIVITY // activityget - GET ACTIVITY page,pagesize als urlparameter }elseif(($method=='get') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'activity')){ From 7de97ed20003d1f5ab9e2bfde9386bba07d0eff8 Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Sat, 7 Jul 2012 16:54:07 -0400 Subject: [PATCH 003/330] Make readData() exit with a 400 Bad Request for not provided required parameters, and sanitize text --- lib/ocs.php | 97 +++++++++++++++++++++++------------------------------ 1 file changed, 42 insertions(+), 55 deletions(-) diff --git a/lib/ocs.php b/lib/ocs.php index 309e3bb064..5e697b4830 100644 --- a/lib/ocs.php +++ b/lib/ocs.php @@ -4,7 +4,9 @@ * ownCloud * * @author Frank Karlitschek +* @author Michael Gapczynski * @copyright 2012 Frank Karlitschek frank@owncloud.org +* @copyright 2012 Michael Gapczynski mtgap@owncloud.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE @@ -32,49 +34,44 @@ class OC_OCS { /** * reads input date from get/post/cookies and converts the date to a special data-type * - * @param variable $key - * @param variable-type $type - * @param priority $getpriority - * @param default $default - * @return data + * @param string HTTP method to read the key from + * @param string Parameter to read + * @param string Variable type to format data + * @param mixed Default value to return if the key is not found + * @return mixed Data or if the key is not found and no default is set it will exit with a 400 Bad request */ - public static function readData($key,$type='raw',$getpriority=false,$default='') { - if($getpriority) { - if(isset($_GET[$key])) { - $data=$_GET[$key]; - } elseif(isset($_POST[$key])) { - $data=$_POST[$key]; - } else { - if($default=='') { - if(($type=='int') or ($type=='float')) $data=0; else $data=''; + public static function readData($method, $key, $type = 'raw', $default = null) { + if ($method == 'get') { + if (isset($_GET[$key])) { + $data = $_GET[$key]; + } else if (isset($default)) { + return $default; } else { - $data=$default; + $data = false; + } + } else if ($method == 'post') { + if (isset($_POST[$key])) { + $data = $_POST[$key]; + } else if (isset($default)) { + return $default; + } else { + $data = false; } } + if ($data === false) { + echo self::generateXml('', 'fail', 400, 'Bad request. Please provide a valid '.$key); + exit(); } else { - if(isset($_POST[$key])) { - $data=$_POST[$key]; - } elseif(isset($_GET[$key])) { - $data=$_GET[$key]; - } elseif(isset($_COOKIE[$key])) { - $data=$_COOKIE[$key]; - } else { - if($default=='') { - if(($type=='int') or ($type=='float')) $data=0; else $data=''; - } else { - $data=$default; - } + // NOTE: Is the raw type necessary? It might be a little risky without sanitization + if ($type == 'raw') return $data; + elseif ($type == 'text') return OC_Util::sanitizeHTML($data); + elseif ($type == 'int') return (int) $data; + elseif ($type == 'float') return (float) $data; + elseif ($type == 'array') return OC_Util::sanitizeHTML($data); + else return OC_Util::sanitizeHTML($data); } - } - - if($type=='raw') return($data); - elseif($type=='text') return(addslashes(strip_tags($data))); - elseif($type=='int') { $data = (int) $data; return($data); } - elseif($type=='float') { $data = (float) $data; return($data); } - elseif($type=='array') { $data = $data; return($data); } } - /** main function to handle the REST request **/ @@ -100,26 +97,23 @@ class OC_OCS { if(substr($url,(strlen($url)-1))<>'/') $url.='/'; $ex=explode('/',$url); $paracount=count($ex); - + $format = self::readData($method, 'format', 'text', ''); // eventhandler // CONFIG // apiconfig - GET - CONFIG if(($method=='get') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'config')){ - $format=OC_OCS::readdata('format','text'); OC_OCS::apiconfig($format); // PERSON // personcheck - POST - PERSON/CHECK }elseif(($method=='post') and ($ex[$paracount-4] == 'v1.php') and ($ex[$paracount-3]=='person') and ($ex[$paracount-2] == 'check')){ - $format=OC_OCS::readdata('format','text'); - $login=OC_OCS::readdata('login','text'); - $passwd=OC_OCS::readdata('password','text'); + $login = self::readData($method, 'login', 'text'); + $passwd = self::readData($method, 'password', 'text'); OC_OCS::personcheck($format,$login,$passwd); } else if ($method == 'post' && $ex[$paracount - 4] == 'v1.php' && $ex[$paracount - 3] == 'person' && $ex[$paracount - 2] == 'add') { - $format = self::readData('format', 'text'); if (OC_Group::inGroup(self::checkPassword(), 'admin')) { - $login = self::readData('login', 'text'); - $password = self::readData('password', 'text'); + $login = self::readData($method, 'login', 'text'); + $password = self::readData($method, 'password', 'text'); try { OC_User::createUser($login, $password); echo self::generateXml($format, 'ok', 201, ''); @@ -132,50 +126,43 @@ class OC_OCS { // ACTIVITY // activityget - GET ACTIVITY page,pagesize als urlparameter }elseif(($method=='get') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'activity')){ - $format=OC_OCS::readdata('format','text'); - $page=OC_OCS::readdata('page','int'); - $pagesize=OC_OCS::readdata('pagesize','int'); + $page = self::readData($method, 'page', 'int', 0); + $pagesize = self::readData($method, 'pagesize','int', 10); if($pagesize<1 or $pagesize>100) $pagesize=10; OC_OCS::activityget($format,$page,$pagesize); // activityput - POST ACTIVITY }elseif(($method=='post') and ($ex[$paracount-3] == 'v1.php') and ($ex[$paracount-2] == 'activity')){ - $format=OC_OCS::readdata('format','text'); - $message=OC_OCS::readdata('message','text'); + $message = self::readData($method, 'message', 'text'); OC_OCS::activityput($format,$message); // PRIVATEDATA // get - GET DATA }elseif(($method=='get') and ($ex[$paracount-4] == 'v1.php') and ($ex[$paracount-2] == 'getattribute')){ - $format=OC_OCS::readdata('format','text'); OC_OCS::privateDataGet($format); }elseif(($method=='get') and ($ex[$paracount-5] == 'v1.php') and ($ex[$paracount-3] == 'getattribute')){ - $format=OC_OCS::readdata('format','text'); $app=$ex[$paracount-2]; OC_OCS::privateDataGet($format, $app); }elseif(($method=='get') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-4] == 'getattribute')){ - $format=OC_OCS::readdata('format','text'); + $key=$ex[$paracount-2]; $app=$ex[$paracount-3]; OC_OCS::privateDataGet($format, $app,$key); // set - POST DATA }elseif(($method=='post') and ($ex[$paracount-6] == 'v1.php') and ($ex[$paracount-4] == 'setattribute')){ - $format=OC_OCS::readdata('format','text'); $key=$ex[$paracount-2]; $app=$ex[$paracount-3]; - $value=OC_OCS::readdata('value','text'); + $value = self::readData($method, 'value', 'text'); OC_OCS::privatedataset($format, $app, $key, $value); // delete - POST DATA }elseif(($method=='post') and ($ex[$paracount-6] =='v1.php') and ($ex[$paracount-4] == 'deleteattribute')){ - $format=OC_OCS::readdata('format','text'); $key=$ex[$paracount-2]; $app=$ex[$paracount-3]; OC_OCS::privatedatadelete($format, $app, $key); }else{ - $format=OC_OCS::readdata('format','text'); $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n"; $txt.=OC_OCS::getdebugoutput(); echo(OC_OCS::generatexml($format,'failed',999,$txt)); From 20838bb9c2f77bf45cf7e4bccf9f941cbc39bbdb Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sat, 28 Jul 2012 21:40:11 +0000 Subject: [PATCH 004/330] Basic structure and functionality of api class --- lib/api.php | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 lib/api.php diff --git a/lib/api.php b/lib/api.php new file mode 100644 index 0000000000..767f1d30b7 --- /dev/null +++ b/lib/api.php @@ -0,0 +1,91 @@ +. + * + */ + + class OC_API { + + /** + * api actions + */ + protected $actions = array(); + + /** + * registers an api call + * @param string $method the http method + * @param string $url the url to match + * @param callable $action the function to run + */ + public function register($method, $url, $action){ + $name = strtolower($method).$url; + if(!isset(self::$actions[$name])){ + OC_Router::create($name, $url) + ->action('OC_API', 'call'); + self::$actions[$name] = array(); + } + self::$actions[$name][] = $action; + } + + /** + * handles an api call + * @param array $parameters + */ + public function call($parameters){ + // TODO load the routes.php from apps + $name = $parameters['_name']; + $response = array(); + // Loop through registered actions + foreach(self::$actions[$name] as $action){ + if(is_callable($action)){ + $action_response = call_user_func($action, $parameters); + if(is_array($action_response)){ + // Merge with previous + $response = array_merge($response, $action_response); + } else { + // TODO - Something failed, do we return an error code, depends on other action responses + } + } else { + // Action not callable + // log + // TODO - Depending on other action responses, do we return a 501? + } + } + // Send the response + if(isset($parameters['_format'])){ + self::respond($response, $parameters['_format']); + } else { + self::respond($response); + } + } + + /** + * respond to a call + * @param int|array $response the response + * @param string $format the format xml|json + */ + private function respond($response, $format='json'){ + // TODO respond in the correct format + } + + } \ No newline at end of file From c375774fca619ee4bd886a9c675908c4006cc980 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sat, 28 Jul 2012 21:50:40 +0000 Subject: [PATCH 005/330] Fix odd indentation issue --- lib/api.php | 178 ++++++++++++++++++++++++++-------------------------- 1 file changed, 89 insertions(+), 89 deletions(-) diff --git a/lib/api.php b/lib/api.php index 767f1d30b7..eaa2bb42f8 100644 --- a/lib/api.php +++ b/lib/api.php @@ -1,91 +1,91 @@ . - * - */ - - class OC_API { - - /** - * api actions - */ - protected $actions = array(); - - /** - * registers an api call - * @param string $method the http method - * @param string $url the url to match - * @param callable $action the function to run - */ - public function register($method, $url, $action){ - $name = strtolower($method).$url; - if(!isset(self::$actions[$name])){ - OC_Router::create($name, $url) - ->action('OC_API', 'call'); - self::$actions[$name] = array(); - } - self::$actions[$name][] = $action; - } - - /** - * handles an api call - * @param array $parameters - */ - public function call($parameters){ - // TODO load the routes.php from apps - $name = $parameters['_name']; - $response = array(); - // Loop through registered actions - foreach(self::$actions[$name] as $action){ - if(is_callable($action)){ - $action_response = call_user_func($action, $parameters); - if(is_array($action_response)){ - // Merge with previous - $response = array_merge($response, $action_response); - } else { - // TODO - Something failed, do we return an error code, depends on other action responses - } - } else { - // Action not callable - // log - // TODO - Depending on other action responses, do we return a 501? - } - } - // Send the response - if(isset($parameters['_format'])){ - self::respond($response, $parameters['_format']); - } else { - self::respond($response); - } - } - - /** - * respond to a call - * @param int|array $response the response - * @param string $format the format xml|json - */ - private function respond($response, $format='json'){ - // TODO respond in the correct format - } - - } \ No newline at end of file +* ownCloud +* +* @author Tom Needham +* @author Michael Gapczynski +* @author Bart Visscher +* @copyright 2012 Tom Needham tom@owncloud.com +* @copyright 2012 Michael Gapczynski mtgap@owncloud.com +* @copyright 2012 Bart Visscher bartv@thisnet.nl +* +* This library is free software; you can redistribute it and/or +* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE +* License as published by the Free Software Foundation; either +* version 3 of the License, or any later version. +* +* This library is distributed in the hope that it will be useful, +* but WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +* GNU AFFERO GENERAL PUBLIC LICENSE for more details. +* +* You should have received a copy of the GNU Affero General Public +* License along with this library. If not, see . +* +*/ + +class OC_API { + + /** + * api actions + */ + protected $actions = array(); + + /** + * registers an api call + * @param string $method the http method + * @param string $url the url to match + * @param callable $action the function to run + */ + public function register($method, $url, $action){ + $name = strtolower($method).$url; + if(!isset(self::$actions[$name])){ + OC_Router::create($name, $url) + ->action('OC_API', 'call'); + self::$actions[$name] = array(); + } + self::$actions[$name][] = $action; + } + + /** + * handles an api call + * @param array $parameters + */ + public function call($parameters){ + + $name = $parameters['_name']; + $response = array(); + // Loop through registered actions + foreach(self::$actions[$name] as $action){ + if(is_callable($action)){ + $action_response = call_user_func($action, $parameters); + if(is_array($action_response)){ + // Merge with previous + $response = array_merge($response, $action_response); + } else { + // TODO - Something failed, do we return an error code, depends on other action responses + } + } else { + // Action not callable + // log + // TODO - Depending on other action responses, do we return a 501? + } + } + // Send the response + if(isset($parameters['_format'])){ + self::respond($response, $parameters['_format']); + } else { + self::respond($response); + } + } + + /** + * respond to a call + * @param int|array $response the response + * @param string $format the format xml|json + */ + private function respond($response, $format='json'){ + // TODO respond in the correct format + } + + } \ No newline at end of file From 9dbe5f3703afd84c701d0d1347c06f1b07ff7fe6 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sat, 28 Jul 2012 21:57:24 +0000 Subject: [PATCH 006/330] Load routes before calling actions --- lib/api.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/lib/api.php b/lib/api.php index eaa2bb42f8..cf40167b07 100644 --- a/lib/api.php +++ b/lib/api.php @@ -53,6 +53,15 @@ class OC_API { */ public function call($parameters){ + // Get the routes + // TODO cache + foreach(OC_APP::getEnabledApps() as $app){ + $file = OC_App::getAppPath($app).'/appinfo/routes.php'; + if(file_exists($file)){ + require_once($file); + } + } + $name = $parameters['_name']; $response = array(); // Loop through registered actions From 038af7e636ad8a2dc9ac342eaecd176cc5c35256 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sun, 29 Jul 2012 15:29:26 +0000 Subject: [PATCH 007/330] Add method to check if an app is shipped or not --- lib/app.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) mode change 100755 => 100644 lib/app.php diff --git a/lib/app.php b/lib/app.php old mode 100755 new mode 100644 index 56132c0867..60bd0ef476 --- a/lib/app.php +++ b/lib/app.php @@ -139,6 +139,20 @@ class OC_App{ OC_Appconfig::setValue($app,'types',$appTypes); } + + /** + * check if app is shipped + * @param string $appid the id of the app to check + * @return bool + */ + public function isShipped($appid){ + $info = self::getAppInfo($appid); + if(isset($info['shipped']) && $info['shipped']=='true'){ + return true; + } else { + return false; + } + } /** * get all enabled apps From 5933d4390107224071f8265afd81222b69f98de7 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 10:25:41 +0000 Subject: [PATCH 008/330] Basic template for authorising exernal apps with OAuth --- settings/oauth.php | 41 ++++++++++++++++++++++++++++++++++++ settings/templates/oauth.php | 19 +++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 settings/oauth.php create mode 100644 settings/templates/oauth.php diff --git a/settings/oauth.php b/settings/oauth.php new file mode 100644 index 0000000000..bcf34b04af --- /dev/null +++ b/settings/oauth.php @@ -0,0 +1,41 @@ + + * This file is licensed under the Affero General Public License version 3 or later. + * See the COPYING-README file. + */ + +require_once('../lib/base.php'); + +// Logic +$operation = isset($_GET['operation']) ? $_GET['operation'] : ''; +switch($operation){ + + case 'register': + + break; + + case 'request_token': + break; + + case 'authorise'; + // Example + $consumer = array( + 'name' => 'Firefox Bookmark Sync', + 'scopes' => array('bookmarks'), + ); + + $t = new OC_Template('settings', 'oauth', 'guest'); + $t->assign('consumer', $consumer); + $t->printPage(); + break; + + case 'access_token'; + break; + + default: + // Something went wrong + header('Location: /'); + break; + +} diff --git a/settings/templates/oauth.php b/settings/templates/oauth.php new file mode 100644 index 0000000000..ce2584365b --- /dev/null +++ b/settings/templates/oauth.php @@ -0,0 +1,19 @@ + + * This file is licensed under the Affero General Public License version 3 or later. + * See the COPYING-README file. + */ +?> + +

is requesting permission to read, write, modify and delete data from the following apps:

+
    + '.$app.''; + } + ?> +
+ + \ No newline at end of file From 138c66a2ba1fdc7b44297bfe8498c200d6d2f250 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 10:51:00 +0000 Subject: [PATCH 009/330] Improve styling of permission request page --- settings/css/oauth.css | 2 ++ settings/templates/oauth.php | 25 +++++++++++++------------ 2 files changed, 15 insertions(+), 12 deletions(-) create mode 100644 settings/css/oauth.css diff --git a/settings/css/oauth.css b/settings/css/oauth.css new file mode 100644 index 0000000000..8bc8c8d428 --- /dev/null +++ b/settings/css/oauth.css @@ -0,0 +1,2 @@ +.guest-container{ width:35%; margin: 2em auto 0 auto; } +#oauth-request button{ float: right; } \ No newline at end of file diff --git a/settings/templates/oauth.php b/settings/templates/oauth.php index ce2584365b..b9fa67d8a3 100644 --- a/settings/templates/oauth.php +++ b/settings/templates/oauth.php @@ -5,15 +5,16 @@ * See the COPYING-README file. */ ?> - -

is requesting permission to read, write, modify and delete data from the following apps:

-
    - '.$app.''; - } - ?> -
- - \ No newline at end of file +
+

is requesting permission to read, write, modify and delete data from the following apps:

+
    + '.$app.''; + } + ?> +
+ + +
From cbc0f0c1c5c5ad9ecc1b20c0f0aee7b4ea564579 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 10:51:48 +0000 Subject: [PATCH 010/330] Include the css for the OAuth page --- settings/oauth.php | 1 + 1 file changed, 1 insertion(+) diff --git a/settings/oauth.php b/settings/oauth.php index bcf34b04af..fc158afe26 100644 --- a/settings/oauth.php +++ b/settings/oauth.php @@ -26,6 +26,7 @@ switch($operation){ ); $t = new OC_Template('settings', 'oauth', 'guest'); + OC_Util::addStyle('settings', 'oauth'); $t->assign('consumer', $consumer); $t->printPage(); break; From e33174f115d7459afb15131f0bc4a6386a673608 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 10:56:21 +0000 Subject: [PATCH 011/330] Add core routes and include them in OC_API::call() --- core/routes.php | 25 +++++++++++++++++++++++++ lib/api.php | 8 +++++--- 2 files changed, 30 insertions(+), 3 deletions(-) create mode 100644 core/routes.php diff --git a/core/routes.php b/core/routes.php new file mode 100644 index 0000000000..4c5004dcf5 --- /dev/null +++ b/core/routes.php @@ -0,0 +1,25 @@ + + * This file is licensed under the Affero General Public License version 3 or later. + * See the COPYING-README file. + */ + +// Config +OC_API::register('get', '/config.{format}', array('OC_API_Config', 'apiConfig')); +// Person +OC_API::register('post', '/person/check.{format}', array('OC_API_Person', 'check')); +// Activity +OC_API::register('get', '/activity.{format}', array('OC_API_Activity', 'activityGet')); +OC_API::register('post', '/activity.{format}', array('OC_API_Activity', 'activityPut')); +// Privatedata +OC_API::register('get', '/privatedata/getattribute/{app}/{key}.{format}', array('OC_API_Privatedata', 'privatedataGet')); +OC_API::register('post', '/privatedata/setattribute/{app}/{key}.{format}', array('OC_API_Privatedata', 'privatedataPut')); +OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}.{format}', array('OC_API_Privatedata', 'privatedataDelete')); +// Cloud +OC_API::register('get', '/cloud/system/webapps.{format}', array('OC_API_Cloud', 'systemwebapps')); +OC_API::register('get', '/cloud/user/{user}.{format}', array('OC_API_Cloud', 'getQuota')); +OC_API::register('post', '/cloud/user/{user}.{format}', array('OC_API_Cloud', 'setQuota')); +OC_API::register('get', '/cloud/user/{user}/publickey.{format}', array('OC_API_Cloud', 'getPublicKey')); +OC_API::register('get', '/cloud/user/{user}/privatekey.{format}', array('OC_API_Cloud', 'getPrivateKey')); +?> \ No newline at end of file diff --git a/lib/api.php b/lib/api.php index cf40167b07..b1176a0707 100644 --- a/lib/api.php +++ b/lib/api.php @@ -29,7 +29,7 @@ class OC_API { /** * api actions */ - protected $actions = array(); + protected static $actions = array(); /** * registers an api call @@ -37,7 +37,7 @@ class OC_API { * @param string $url the url to match * @param callable $action the function to run */ - public function register($method, $url, $action){ + public static function register($method, $url, $action){ $name = strtolower($method).$url; if(!isset(self::$actions[$name])){ OC_Router::create($name, $url) @@ -51,7 +51,7 @@ class OC_API { * handles an api call * @param array $parameters */ - public function call($parameters){ + public static function call($parameters){ // Get the routes // TODO cache @@ -61,6 +61,8 @@ class OC_API { require_once($file); } } + // include core routes + require_once(OC::$SERVERROOT.'core/routes.php'); $name = $parameters['_name']; $response = array(); From f09ecee63aa6ed3c43dd88b125647460b404a601 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 12:41:26 +0000 Subject: [PATCH 012/330] Move routes to ocs folder --- {core => ocs}/routes.php | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) rename {core => ocs}/routes.php (56%) diff --git a/core/routes.php b/ocs/routes.php similarity index 56% rename from core/routes.php rename to ocs/routes.php index 4c5004dcf5..e2f70342b8 100644 --- a/core/routes.php +++ b/ocs/routes.php @@ -6,20 +6,20 @@ */ // Config -OC_API::register('get', '/config.{format}', array('OC_API_Config', 'apiConfig')); +OC_API::register('get', '/config.{format}', array('OC_OCS_Config', 'apiConfig')); // Person -OC_API::register('post', '/person/check.{format}', array('OC_API_Person', 'check')); +OC_API::register('post', '/person/check.{format}', array('OC_OCS_Person', 'check')); // Activity -OC_API::register('get', '/activity.{format}', array('OC_API_Activity', 'activityGet')); -OC_API::register('post', '/activity.{format}', array('OC_API_Activity', 'activityPut')); +OC_API::register('get', '/activity.{format}', array('OC_OCS_Activity', 'activityGet')); // Privatedata -OC_API::register('get', '/privatedata/getattribute/{app}/{key}.{format}', array('OC_API_Privatedata', 'privatedataGet')); -OC_API::register('post', '/privatedata/setattribute/{app}/{key}.{format}', array('OC_API_Privatedata', 'privatedataPut')); -OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}.{format}', array('OC_API_Privatedata', 'privatedataDelete')); +OC_API::register('get', '/privatedata/getattribute/{app}/{key}.{format}', array('OC_OCS_Privatedata', 'privatedataGet')); +OC_API::register('post', '/privatedata/setattribute/{app}/{key}.{format}', array('OC_OCS_Privatedata', 'privatedataPut')); +OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}.{format}', array('OC_OCS_Privatedata', 'privatedataDelete')); // Cloud -OC_API::register('get', '/cloud/system/webapps.{format}', array('OC_API_Cloud', 'systemwebapps')); -OC_API::register('get', '/cloud/user/{user}.{format}', array('OC_API_Cloud', 'getQuota')); -OC_API::register('post', '/cloud/user/{user}.{format}', array('OC_API_Cloud', 'setQuota')); -OC_API::register('get', '/cloud/user/{user}/publickey.{format}', array('OC_API_Cloud', 'getPublicKey')); -OC_API::register('get', '/cloud/user/{user}/privatekey.{format}', array('OC_API_Cloud', 'getPrivateKey')); +OC_API::register('get', '/cloud/system/webapps.{format}', array('OC_OCS_Cloud', 'systemwebapps')); +OC_API::register('get', '/cloud/user/{user}.{format}', array('OC_OCS_Cloud', 'getQuota')); +OC_API::register('post', '/cloud/user/{user}.{format}', array('OC_OCS_Cloud', 'setQuota')); +OC_API::register('get', '/cloud/user/{user}/publickey.{format}', array('OC_OCS_Cloud', 'getPublicKey')); +OC_API::register('get', '/cloud/user/{user}/privatekey.{format}', array('OC_OCS_Cloud', 'getPrivateKey')); + ?> \ No newline at end of file From 9072106048265ce144227605c8919104acf6d746 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 12:42:18 +0000 Subject: [PATCH 013/330] Move OCS methods to lib/ocs/.php --- lib/api.php | 2 +- lib/ocs/activity.php | 11 +++++ lib/ocs/cloud.php | 97 +++++++++++++++++++++++++++++++++++++++++ lib/ocs/config.php | 16 +++++++ lib/ocs/person.php | 22 ++++++++++ lib/ocs/privatedata.php | 37 ++++++++++++++++ 6 files changed, 184 insertions(+), 1 deletion(-) create mode 100644 lib/ocs/activity.php create mode 100644 lib/ocs/cloud.php create mode 100644 lib/ocs/config.php create mode 100644 lib/ocs/person.php create mode 100644 lib/ocs/privatedata.php diff --git a/lib/api.php b/lib/api.php index b1176a0707..2203d86ac9 100644 --- a/lib/api.php +++ b/lib/api.php @@ -62,7 +62,7 @@ class OC_API { } } // include core routes - require_once(OC::$SERVERROOT.'core/routes.php'); + require_once(OC::$SERVERROOT.'ocs/routes.php'); $name = $parameters['_name']; $response = array(); diff --git a/lib/ocs/activity.php b/lib/ocs/activity.php new file mode 100644 index 0000000000..3b090376e7 --- /dev/null +++ b/lib/ocs/activity.php @@ -0,0 +1,11 @@ + \ No newline at end of file diff --git a/lib/ocs/cloud.php b/lib/ocs/cloud.php new file mode 100644 index 0000000000..d0cd72e98c --- /dev/null +++ b/lib/ocs/cloud.php @@ -0,0 +1,97 @@ +$info['name'],'url'=>OC_Helper::linkToAbsolute($app,''),'icon'=>''); + $values[] = $newvalue; + } + } + return $values; + } + + public static function getQuota($parameters){ + $login=OC_OCS::checkpassword(); + if(OC_Group::inGroup($login, 'admin') or ($login==$parameters['user'])) { + + if(OC_User::userExists($parameters['user'])){ + // calculate the disc space + $user_dir = '/'.$parameters['user'].'/files'; + OC_Filesystem::init($user_dir); + $rootInfo=OC_FileCache::get(''); + $sharedInfo=OC_FileCache::get('/Shared'); + $used=$rootInfo['size']-$sharedInfo['size']; + $free=OC_Filesystem::free_space(); + $total=$free+$used; + if($total==0) $total=1; // prevent division by zero + $relative=round(($used/$total)*10000)/100; + + $xml=array(); + $xml['quota']=$total; + $xml['free']=$free; + $xml['used']=$used; + $xml['relative']=$relative; + + return $xml; + }else{ + return 300; + } + }else{ + return 300; + } + } + + public static function setQuota($parameters){ + $login=OC_OCS::checkpassword(); + if(OC_Group::inGroup($login, 'admin')) { + + // todo + // not yet implemented + // add logic here + error_log('OCS call: user:'.$parameters['user'].' quota:'.$parameters['quota']); + + $xml=array(); + return $xml; + }else{ + return 300; + } + } + + public static function getPublickey($parameters){ + $login=OC_OCS::checkpassword(); + + if(OC_User::userExists($parameters['user'])){ + // calculate the disc space + // TODO + return array(); + }else{ + return 300; + } + } + + public static function getPrivatekey($parameters){ + $login=OC_OCS::checkpassword(); + if(OC_Group::inGroup($login, 'admin') or ($login==$parameters['user'])) { + + if(OC_User::userExists($user)){ + // calculate the disc space + $txt='this is the private key of '.$parameters['user']; + echo($txt); + }else{ + echo self::generateXml('', 'fail', 300, 'User does not exist'); + } + }else{ + echo self::generateXml('', 'fail', 300, 'You don´t have permission to access this ressource.'); + } + } + + +} + +?> \ No newline at end of file diff --git a/lib/ocs/config.php b/lib/ocs/config.php new file mode 100644 index 0000000000..b736abe3b9 --- /dev/null +++ b/lib/ocs/config.php @@ -0,0 +1,16 @@ + \ No newline at end of file diff --git a/lib/ocs/person.php b/lib/ocs/person.php new file mode 100644 index 0000000000..f4e4be5ee0 --- /dev/null +++ b/lib/ocs/person.php @@ -0,0 +1,22 @@ +''){ + if(OC_User::login($parameters['login'],$parameters['password'])){ + $xml['person']['personid'] = $parameters['login']; + return $xml; + }else{ + return 102; + } + }else{ + return 101; + } + + } + +} + +?> \ No newline at end of file diff --git a/lib/ocs/privatedata.php b/lib/ocs/privatedata.php new file mode 100644 index 0000000000..cb62d60a8d --- /dev/null +++ b/lib/ocs/privatedata.php @@ -0,0 +1,37 @@ +$log) { + $xml[$i]['key']=$log['key']; + $xml[$i]['app']=$log['app']; + $xml[$i]['value']=$log['value']; + } + return $xml; + //TODO: replace 'privatedata' with 'attribute' once a new libattice has been released that works with it + } + + public static function privatedataSet($parameters){ + $user = OC_OCS::checkpassword(); + if(OC_OCS::setData($user,$app,$key,$value)){ + return 100; + } + } + + public static function privatedataDelete($parameteres){ + $user = OC_OCS::checkpassword(); + if($key=="" or $app==""){ + return; //key and app are NOT optional here + } + if(OC_OCS::deleteData($user,$app,$key)){ + return 100; + } + } + +} + +?> \ No newline at end of file From 9ffaea480fc77514ac1804ad3ca72487c7ba40e4 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 12:44:34 +0000 Subject: [PATCH 014/330] Add the format parameter inside OC_API --- lib/api.php | 2 +- ocs/routes.php | 22 +++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/lib/api.php b/lib/api.php index 2203d86ac9..c61f50c1bc 100644 --- a/lib/api.php +++ b/lib/api.php @@ -40,7 +40,7 @@ class OC_API { public static function register($method, $url, $action){ $name = strtolower($method).$url; if(!isset(self::$actions[$name])){ - OC_Router::create($name, $url) + OC_Router::create($name, $url.'.{format}') ->action('OC_API', 'call'); self::$actions[$name] = array(); } diff --git a/ocs/routes.php b/ocs/routes.php index e2f70342b8..2f8ab2a8f6 100644 --- a/ocs/routes.php +++ b/ocs/routes.php @@ -6,20 +6,20 @@ */ // Config -OC_API::register('get', '/config.{format}', array('OC_OCS_Config', 'apiConfig')); +OC_API::register('get', '/config', array('OC_OCS_Config', 'apiConfig')); // Person -OC_API::register('post', '/person/check.{format}', array('OC_OCS_Person', 'check')); +OC_API::register('post', '/person/check', array('OC_OCS_Person', 'check')); // Activity -OC_API::register('get', '/activity.{format}', array('OC_OCS_Activity', 'activityGet')); +OC_API::register('get', '/activity', array('OC_OCS_Activity', 'activityGet')); // Privatedata -OC_API::register('get', '/privatedata/getattribute/{app}/{key}.{format}', array('OC_OCS_Privatedata', 'privatedataGet')); -OC_API::register('post', '/privatedata/setattribute/{app}/{key}.{format}', array('OC_OCS_Privatedata', 'privatedataPut')); -OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}.{format}', array('OC_OCS_Privatedata', 'privatedataDelete')); +OC_API::register('get', '/privatedata/getattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataGet')); +OC_API::register('post', '/privatedata/setattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataPut')); +OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataDelete')); // Cloud -OC_API::register('get', '/cloud/system/webapps.{format}', array('OC_OCS_Cloud', 'systemwebapps')); -OC_API::register('get', '/cloud/user/{user}.{format}', array('OC_OCS_Cloud', 'getQuota')); -OC_API::register('post', '/cloud/user/{user}.{format}', array('OC_OCS_Cloud', 'setQuota')); -OC_API::register('get', '/cloud/user/{user}/publickey.{format}', array('OC_OCS_Cloud', 'getPublicKey')); -OC_API::register('get', '/cloud/user/{user}/privatekey.{format}', array('OC_OCS_Cloud', 'getPrivateKey')); +OC_API::register('get', '/cloud/system/webapps', array('OC_OCS_Cloud', 'systemwebapps')); +OC_API::register('get', '/cloud/user/{user}', array('OC_OCS_Cloud', 'getQuota')); +OC_API::register('post', '/cloud/user/{user}', array('OC_OCS_Cloud', 'setQuota')); +OC_API::register('get', '/cloud/user/{user}/publickey', array('OC_OCS_Cloud', 'getPublicKey')); +OC_API::register('get', '/cloud/user/{user}/privatekey', array('OC_OCS_Cloud', 'getPrivateKey')); ?> \ No newline at end of file From b563dff10a60e08ad270dc78404102f082abf184 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 12:56:01 +0000 Subject: [PATCH 015/330] Record the app that is registering a call to use later with OAuth --- lib/api.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/api.php b/lib/api.php index c61f50c1bc..46f58debdc 100644 --- a/lib/api.php +++ b/lib/api.php @@ -36,15 +36,16 @@ class OC_API { * @param string $method the http method * @param string $url the url to match * @param callable $action the function to run + * @param string $app the id of the app registering the call */ - public static function register($method, $url, $action){ + public static function register($method, $url, $action, $app){ $name = strtolower($method).$url; if(!isset(self::$actions[$name])){ OC_Router::create($name, $url.'.{format}') ->action('OC_API', 'call'); self::$actions[$name] = array(); } - self::$actions[$name][] = $action; + self::$actions[$name][] = array('app' => $app, 'action' => $action); } /** @@ -68,8 +69,8 @@ class OC_API { $response = array(); // Loop through registered actions foreach(self::$actions[$name] as $action){ - if(is_callable($action)){ - $action_response = call_user_func($action, $parameters); + if(is_callable($action['action'])){ + $action_response = call_user_func($action['action'], $parameters); if(is_array($action_response)){ // Merge with previous $response = array_merge($response, $action_response); From b0dc4383e14713a79c67f71e8e3f3c1c09d8958c Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 12:57:35 +0000 Subject: [PATCH 016/330] Clean code slightly --- lib/api.php | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/lib/api.php b/lib/api.php index 46f58debdc..17663b53b8 100644 --- a/lib/api.php +++ b/lib/api.php @@ -55,15 +55,7 @@ class OC_API { public static function call($parameters){ // Get the routes - // TODO cache - foreach(OC_APP::getEnabledApps() as $app){ - $file = OC_App::getAppPath($app).'/appinfo/routes.php'; - if(file_exists($file)){ - require_once($file); - } - } - // include core routes - require_once(OC::$SERVERROOT.'ocs/routes.php'); + self::loadRoutes(); $name = $parameters['_name']; $response = array(); @@ -91,6 +83,21 @@ class OC_API { } } + /** + * loads the api routes + */ + private static function loadRoutes(){ + // TODO cache + foreach(OC_APP::getEnabledApps() as $app){ + $file = OC_App::getAppPath($app).'/appinfo/routes.php'; + if(file_exists($file)){ + require_once($file); + } + } + // include core routes + require_once(OC::$SERVERROOT.'ocs/routes.php'); + } + /** * respond to a call * @param int|array $response the response From e47a8a9f0937051c17d5f95652098b53610f8cb6 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 13:14:29 +0000 Subject: [PATCH 017/330] Authorisation requires you to be logged in --- settings/oauth.php | 1 + 1 file changed, 1 insertion(+) diff --git a/settings/oauth.php b/settings/oauth.php index fc158afe26..5fe21940b0 100644 --- a/settings/oauth.php +++ b/settings/oauth.php @@ -19,6 +19,7 @@ switch($operation){ break; case 'authorise'; + OC_Util::checkLoggedIn(); // Example $consumer = array( 'name' => 'Firefox Bookmark Sync', From c7c16ac49b661d5087cd64612bce1da5630424b0 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 13:39:06 +0000 Subject: [PATCH 018/330] Improve merging of api responses --- lib/api.php | 47 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/lib/api.php b/lib/api.php index 17663b53b8..02c3f77e5c 100644 --- a/lib/api.php +++ b/lib/api.php @@ -58,23 +58,17 @@ class OC_API { self::loadRoutes(); $name = $parameters['_name']; - $response = array(); // Loop through registered actions foreach(self::$actions[$name] as $action){ + $app = $action['app']; if(is_callable($action['action'])){ - $action_response = call_user_func($action['action'], $parameters); - if(is_array($action_response)){ - // Merge with previous - $response = array_merge($response, $action_response); - } else { - // TODO - Something failed, do we return an error code, depends on other action responses - } + $responses[] = array('app' => $app, 'response' => call_user_func($action['action'], $parameters)); } else { - // Action not callable - // log - // TODO - Depending on other action responses, do we return a 501? + $responses[] = array('app' => $app, 'response' => 501); } } + // Merge the responses + $response = self::mergeResponses($responses); // Send the response if(isset($parameters['_format'])){ self::respond($response, $parameters['_format']); @@ -83,6 +77,35 @@ class OC_API { } } + /** + * intelligently merges the different responses + * @param array $responses + * @return array the final merged response + */ + private static function mergeResponses($responses){ + $finalresponse = array(); + $numresponses = count($responses); + + // TODO - This is only a temporary merge. If keys match and value is another array we want to compare deeper in the array + foreach($responses as $response){ + if(is_int($response) && empty($finalresponse)){ + $finalresponse = $response; + continue; + } + if(is_array($response)){ + // Shipped apps win + if(OC_App::isShipped($response['app'])){ + $finalresponse = array_merge($finalresponse, $response); + } else { + $finalresponse = array_merge($response, $finalresponse); + } + } + } + // END TODO + + return $finalresponse; + } + /** * loads the api routes */ @@ -107,4 +130,4 @@ class OC_API { // TODO respond in the correct format } - } \ No newline at end of file +} \ No newline at end of file From 3a0e3708a50a0672c94c79e165aa834dfe8f4e9a Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 14:26:15 +0000 Subject: [PATCH 019/330] Add public class for registering api calls --- lib/public/api.php | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 lib/public/api.php diff --git a/lib/public/api.php b/lib/public/api.php new file mode 100644 index 0000000000..270aa89329 --- /dev/null +++ b/lib/public/api.php @@ -0,0 +1,41 @@ +. +* +*/ + +namespace OCP; + +/** + * This class provides functions to manage apps in ownCloud + */ +class API { + + /** + * registers an api call + * @param string $method the http method + * @param string $url the url to match + * @param callable $action the function to run + * @param string $app the id of the app registering the call + */ + public function register($method, $url, $action, $app){ + OC_API::register($method, $url, $action, $app); + } + +} From 8161b04c336763297738b348b0695cecd0bc0c78 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 15:08:58 +0000 Subject: [PATCH 020/330] Add Provisioning_API app and routes --- apps/provisioning_api/appinfo/app.php | 27 +++++++++ apps/provisioning_api/appinfo/info.xml | 11 ++++ apps/provisioning_api/appinfo/routes.php | 46 ++++++++++++++++ apps/provisioning_api/appinfo/version | 1 + apps/provisioning_api/lib/apps.php | 42 ++++++++++++++ apps/provisioning_api/lib/groups.php | 29 ++++++++++ apps/provisioning_api/lib/users.php | 70 ++++++++++++++++++++++++ 7 files changed, 226 insertions(+) create mode 100644 apps/provisioning_api/appinfo/app.php create mode 100644 apps/provisioning_api/appinfo/info.xml create mode 100644 apps/provisioning_api/appinfo/routes.php create mode 100644 apps/provisioning_api/appinfo/version create mode 100644 apps/provisioning_api/lib/apps.php create mode 100644 apps/provisioning_api/lib/groups.php create mode 100644 apps/provisioning_api/lib/users.php diff --git a/apps/provisioning_api/appinfo/app.php b/apps/provisioning_api/appinfo/app.php new file mode 100644 index 0000000000..992ee23b5c --- /dev/null +++ b/apps/provisioning_api/appinfo/app.php @@ -0,0 +1,27 @@ +. +* +*/ + +OC::$CLASSPATH['OC_Provisioning_API_Users'] = 'apps/provisioning_api/lib/users.php'; +OC::$CLASSPATH['OC_Provisioning_API_Groups'] = 'apps/provisioning_api/lib/groups.php'; +OC::$CLASSPATH['OC_Provisioning_API_Apps'] = 'apps/provisioning_api/lib/apps.php'; +?> \ No newline at end of file diff --git a/apps/provisioning_api/appinfo/info.xml b/apps/provisioning_api/appinfo/info.xml new file mode 100644 index 0000000000..eb96115507 --- /dev/null +++ b/apps/provisioning_api/appinfo/info.xml @@ -0,0 +1,11 @@ + + + provisioning_api + Provisioning API + AGPL + Tom Needham + 5 + true + Provides API methods to manage an ownCloud Instance + + diff --git a/apps/provisioning_api/appinfo/routes.php b/apps/provisioning_api/appinfo/routes.php new file mode 100644 index 0000000000..dcfaf7b78b --- /dev/null +++ b/apps/provisioning_api/appinfo/routes.php @@ -0,0 +1,46 @@ +. +* +*/ + +// users +OCP\API::register('get', '/users', array('OC_Provisioning_API_Users', 'getUsers'), 'provisioning_api'); +OCP\API::register('post', '/users', array('OC_Provisioning_API_Users', 'addUser'), 'provisioning_api'); +OCP\API::register('get', '/users/{userid}', array('OC_Provisioning_API_Users', 'getUser'), 'provisioning_api'); +OCP\API::register('put', '/users/{userid}', array('OC_Provisioning_API_Users', 'editUser'), 'provisioning_api'); +OCP\API::register('delete', '/users/{userid}', array('OC_Provisioning_API_Users', 'getUsers'), 'provisioning_api'); +OCP\API::register('get', '/users/{userid}/sharedwith', array('OC_Provisioning_API_Users', 'getSharedWithUser'), 'provisioning_api'); +OCP\API::register('get', '/users/{userid}/sharedby', array('OC_Provisioning_API_Users', 'getSharedByUser'), 'provisioning_api'); +OCP\API::register('delete', '/users/{userid}/sharedby', array('OC_Provisioning_API_Users', 'deleteSharedByUser'), 'provisioning_api'); +OCP\API::register('get', '/users/{userid}/groups', array('OC_Provisioning_API_Users', 'getUsersGroups'), 'provisioning_api'); +OCP\API::register('post', '/users/{userid}/groups', array('OC_Provisioning_API_Users', 'addToGroup'), 'provisioning_api'); +OCP\API::register('delete', '/users/{userid}/groups', array('OC_Provisioning_API_Users', 'removeFromGroup'), 'provisioning_api'); +// groups +OCP\API::register('get', '/groups', array('OC_Provisioning_API_Groups', 'getGroups'), 'provisioning_api'); +OCP\API::register('post', '/groups', array('OC_Provisioning_API_Groups', 'addGroup'), 'provisioning_api'); +OCP\API::register('get', '/groups/{groupid}', array('OC_Provisioning_API_Groups', 'getGroup'), 'provisioning_api'); +OCP\API::register('delete', '/groups/{groupid}', array('OC_Provisioning_API_Groups', 'deleteGroup'), 'provisioning_api'); +// apps +OCP\API::register('get', '/apps', array('OC_Provisioning_API_Apps', 'getApps'), 'provisioning_api'); +OCP\API::register('get', '/apps/{appid}', array('OC_Provisioning_API_Apps', 'getApp'), 'provisioning_api'); +OCP\API::register('post', '/apps/{appid}', array('OC_Provisioning_API_Apps', 'enable'), 'provisioning_api'); +OCP\API::register('delete', '/apps/{appid}', array('OC_Provisioning_API_Apps', 'disable'), 'provisioning_api'); +?> \ No newline at end of file diff --git a/apps/provisioning_api/appinfo/version b/apps/provisioning_api/appinfo/version new file mode 100644 index 0000000000..49d59571fb --- /dev/null +++ b/apps/provisioning_api/appinfo/version @@ -0,0 +1 @@ +0.1 diff --git a/apps/provisioning_api/lib/apps.php b/apps/provisioning_api/lib/apps.php new file mode 100644 index 0000000000..fcb1e5ba8f --- /dev/null +++ b/apps/provisioning_api/lib/apps.php @@ -0,0 +1,42 @@ +. +* +*/ + +class OC_Provisioning_API_Apps { + + public static function getApps($parameters){ + + } + + public static function getAppInfo($parameters){ + + } + + public static function enable($parameters){ + + } + + public static function diable($parameters){ + + } + +} \ No newline at end of file diff --git a/apps/provisioning_api/lib/groups.php b/apps/provisioning_api/lib/groups.php new file mode 100644 index 0000000000..7e27eeafb0 --- /dev/null +++ b/apps/provisioning_api/lib/groups.php @@ -0,0 +1,29 @@ +. +* +*/ + +class OC_Provisioning_API_Groups{ + + public static function getGroups($parameters){ + + } +} \ No newline at end of file diff --git a/apps/provisioning_api/lib/users.php b/apps/provisioning_api/lib/users.php new file mode 100644 index 0000000000..77f84f4bb1 --- /dev/null +++ b/apps/provisioning_api/lib/users.php @@ -0,0 +1,70 @@ +. +* +*/ + +class OC_Provisioning_API_Users { + + public static function getUsers($parameters){ + + } + + public static function addUser($parameters){ + + } + + public static function getUser($parameters){ + + } + + public static function editUser($parameters){ + + } + + public static function deleteUser($parameters){ + + } + + public static function getSharedWithUser($parameters){ + + } + + public static function getSharedByUser($parameters){ + + } + + public static function deleteSharedByUser($parameters){ + + } + + public static function getUsersGroups($parameters){ + + } + + public static function addToGroup($parameters){ + + } + + public static function removeFromGroup($parameters){ + + } + +} \ No newline at end of file From caa9182eed93b07d6f47bc1bc629f811172b0a02 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 15:25:53 +0000 Subject: [PATCH 021/330] Updated group methods for provisioning api --- apps/provisioning_api/lib/groups.php | 53 +++++++++++++++++++++++++++- 1 file changed, 52 insertions(+), 1 deletion(-) diff --git a/apps/provisioning_api/lib/groups.php b/apps/provisioning_api/lib/groups.php index 7e27eeafb0..6a18e6b37f 100644 --- a/apps/provisioning_api/lib/groups.php +++ b/apps/provisioning_api/lib/groups.php @@ -23,7 +23,58 @@ class OC_Provisioning_API_Groups{ + /** + * returns a list of groups + */ public static function getGroups($parameters){ - + $groups = OC_Group::getGroups(); + return empty($groups) ? 404 : $groups; } + + /** + * returns an array of users in the group specified + */ + public static function getGroup($parameters){ + // Check the group exists + if(!OC_Group::groupExists($parameters['groupid'])){ + return 404; + } + return OC_Group::usersInGroup($parameters['groupid']); + } + + /** + * creates a new group + */ + public static function addGroup($parameters){ + // Validate name + if( preg_match( '/[^a-zA-Z0-9 _\.@\-]/', $parameters['groupid'] ) || empty($parameters['groupid'])){ + return 401; + } + // Check if it exists + if(OC_Group::groupExists($parameters['groupid'])){ + return 409; + } + if(OC_Group::createGroup($parameters['groupid'])){ + return 200; + } else { + return 500; + } + } + + public static function deleteGroup($parameters){ + // Check it exists + if(!OC_Group::groupExists($parameters['groupid'])){ + return 404; + } else if($parameters['groupid'] == 'admin'){ + // Cannot delete admin group + return 403; + } else { + if(OC_Group::deleteGroup($parameters['groupid'])){ + return 200; + } else { + return 500; + } + } + } + } \ No newline at end of file From c4d87c1aff470d77a90b9969160ef0237d93e68b Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 15:34:47 +0000 Subject: [PATCH 022/330] Add methods for getting users and creating users to provisioning api --- apps/provisioning_api/lib/users.php | 27 +++++++++++++++++++++++++-- 1 file changed, 25 insertions(+), 2 deletions(-) diff --git a/apps/provisioning_api/lib/users.php b/apps/provisioning_api/lib/users.php index 77f84f4bb1..2bc0434d87 100644 --- a/apps/provisioning_api/lib/users.php +++ b/apps/provisioning_api/lib/users.php @@ -23,14 +23,37 @@ class OC_Provisioning_API_Users { + /** + * returns a list of users + */ public static function getUsers($parameters){ - + return OC_User::getUsers(); } public static function addUser($parameters){ - + try { + OC_User::createUser($parameters['userid'], $parameters['password']); + return 200; + } catch (Exception $e) { + switch($e->getMessage()){ + case 'Only the following characters are allowed in a username: "a-z", "A-Z", "0-9", and "_.@-"': + case 'A valid username must be provided': + case 'A valid password must be provided': + return 400; + break; + case 'The username is already being used'; + return 409; + break; + default: + return 500; + break; + } + } } + /** + * gets user info + */ public static function getUser($parameters){ } From 2f84a8d74627cb20cfae1ac4c004af393b8b07de Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 16:04:09 +0000 Subject: [PATCH 023/330] Merge the responses recursively --- lib/api.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/api.php b/lib/api.php index 02c3f77e5c..757e53226b 100644 --- a/lib/api.php +++ b/lib/api.php @@ -86,7 +86,6 @@ class OC_API { $finalresponse = array(); $numresponses = count($responses); - // TODO - This is only a temporary merge. If keys match and value is another array we want to compare deeper in the array foreach($responses as $response){ if(is_int($response) && empty($finalresponse)){ $finalresponse = $response; @@ -95,13 +94,12 @@ class OC_API { if(is_array($response)){ // Shipped apps win if(OC_App::isShipped($response['app'])){ - $finalresponse = array_merge($finalresponse, $response); + $finalresponse = array_merge_recursive($finalresponse, $response); } else { - $finalresponse = array_merge($response, $finalresponse); + $finalresponse = array_merge_recursive($response, $finalresponse); } } } - // END TODO return $finalresponse; } From 91daf54d7c1ad009843d28a7791e67f4dc37f56d Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 16:41:07 +0000 Subject: [PATCH 024/330] Check if required apps are installed --- settings/css/oauth.css | 4 ++- settings/oauth.php | 33 ++++++++++++++++++---- settings/templates/oauth-required-apps.php | 19 +++++++++++++ settings/templates/oauth.php | 6 ++-- 4 files changed, 53 insertions(+), 9 deletions(-) create mode 100644 settings/templates/oauth-required-apps.php diff --git a/settings/css/oauth.css b/settings/css/oauth.css index 8bc8c8d428..ccdb98cfa3 100644 --- a/settings/css/oauth.css +++ b/settings/css/oauth.css @@ -1,2 +1,4 @@ .guest-container{ width:35%; margin: 2em auto 0 auto; } -#oauth-request button{ float: right; } \ No newline at end of file +#oauth-request a.button{ float: right; } +#oauth-request ul li{ list-style: disc; } +#oauth-request ul { margin-left: 2em; margin-top: 1em; } diff --git a/settings/oauth.php b/settings/oauth.php index 5fe21940b0..2592b926d1 100644 --- a/settings/oauth.php +++ b/settings/oauth.php @@ -23,13 +23,36 @@ switch($operation){ // Example $consumer = array( 'name' => 'Firefox Bookmark Sync', - 'scopes' => array('bookmarks'), + 'scopes' => array('ookmarks'), ); - $t = new OC_Template('settings', 'oauth', 'guest'); - OC_Util::addStyle('settings', 'oauth'); - $t->assign('consumer', $consumer); - $t->printPage(); + // Check that the scopes are real and installed + $apps = OC_App::getEnabledApps(); + $notfound = array(); + foreach($consumer['scopes'] as $requiredapp){ + if(!in_array($requiredapp, $apps)){ + $notfound[] = $requiredapp; + } + } + if(!empty($notfound)){ + // We need more apps :( Show error + if(count($notfound)==1){ + $message = 'requires that you have an extra app installed on your ownCloud. Please contact your ownCloud administrator and ask them to install the app below.'; + } else { + $message = 'requires that you have some extra apps installed on your ownCloud. Please contract your ownCloud administrator and ask them to install the apps below.'; + } + $t = new OC_Template('settings', 'oauth-required-apps', 'guest'); + OC_Util::addStyle('settings', 'oauth'); + $t->assign('requiredapps', $notfound); + $t->assign('consumer', $consumer); + $t->assign('message', $message); + $t->printPage(); + } else { + $t = new OC_Template('settings', 'oauth', 'guest'); + OC_Util::addStyle('settings', 'oauth'); + $t->assign('consumer', $consumer); + $t->printPage(); + } break; case 'access_token'; diff --git a/settings/templates/oauth-required-apps.php b/settings/templates/oauth-required-apps.php new file mode 100644 index 0000000000..d4fce54c59 --- /dev/null +++ b/settings/templates/oauth-required-apps.php @@ -0,0 +1,19 @@ + + * This file is licensed under the Affero General Public License version 3 or later. + * See the COPYING-README file. + */ +?> +
+

'.$_['message']; ?>

+
    + '.$requiredapp.''; + } + ?> +
+ Back to ownCloud +
diff --git a/settings/templates/oauth.php b/settings/templates/oauth.php index b9fa67d8a3..053a8aee6d 100644 --- a/settings/templates/oauth.php +++ b/settings/templates/oauth.php @@ -6,7 +6,7 @@ */ ?>
-

is requesting permission to read, write, modify and delete data from the following apps:

+

is requesting your permission to read, write, modify and delete data from the following apps:

- - + Allow + Disallow
From 372fdf8077634d1b82db326db61a204ef6512892 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 20:37:35 +0200 Subject: [PATCH 025/330] Add 'ocs' as app name to API registration --- ocs/routes.php | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/ocs/routes.php b/ocs/routes.php index 2f8ab2a8f6..a913254ebe 100644 --- a/ocs/routes.php +++ b/ocs/routes.php @@ -6,20 +6,20 @@ */ // Config -OC_API::register('get', '/config', array('OC_OCS_Config', 'apiConfig')); +OC_API::register('get', '/config', array('OC_OCS_Config', 'apiConfig'), 'ocs'); // Person -OC_API::register('post', '/person/check', array('OC_OCS_Person', 'check')); +OC_API::register('post', '/person/check', array('OC_OCS_Person', 'check'), 'ocs'); // Activity -OC_API::register('get', '/activity', array('OC_OCS_Activity', 'activityGet')); +OC_API::register('get', '/activity', array('OC_OCS_Activity', 'activityGet'), 'ocs'); // Privatedata -OC_API::register('get', '/privatedata/getattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataGet')); -OC_API::register('post', '/privatedata/setattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataPut')); -OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataDelete')); +OC_API::register('get', '/privatedata/getattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataGet'), 'ocs'); +OC_API::register('post', '/privatedata/setattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataPut'), 'ocs'); +OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataDelete'), 'ocs'); // Cloud -OC_API::register('get', '/cloud/system/webapps', array('OC_OCS_Cloud', 'systemwebapps')); -OC_API::register('get', '/cloud/user/{user}', array('OC_OCS_Cloud', 'getQuota')); -OC_API::register('post', '/cloud/user/{user}', array('OC_OCS_Cloud', 'setQuota')); -OC_API::register('get', '/cloud/user/{user}/publickey', array('OC_OCS_Cloud', 'getPublicKey')); -OC_API::register('get', '/cloud/user/{user}/privatekey', array('OC_OCS_Cloud', 'getPrivateKey')); +OC_API::register('get', '/cloud/system/webapps', array('OC_OCS_Cloud', 'systemwebapps'), 'ocs'); +OC_API::register('get', '/cloud/user/{user}', array('OC_OCS_Cloud', 'getQuota'), 'ocs'); +OC_API::register('post', '/cloud/user/{user}', array('OC_OCS_Cloud', 'setQuota'), 'ocs'); +OC_API::register('get', '/cloud/user/{user}/publickey', array('OC_OCS_Cloud', 'getPublicKey'), 'ocs'); +OC_API::register('get', '/cloud/user/{user}/privatekey', array('OC_OCS_Cloud', 'getPrivateKey'), 'ocs'); -?> \ No newline at end of file +?> From 0271bfa3b7849de64bfbb9dd96313fc35da14e29 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 20:48:03 +0200 Subject: [PATCH 026/330] Move loading of routes to OC_Router --- lib/api.php | 19 ------------------- lib/router.php | 15 +++++++++++++++ 2 files changed, 15 insertions(+), 19 deletions(-) diff --git a/lib/api.php b/lib/api.php index 757e53226b..00a3dc108e 100644 --- a/lib/api.php +++ b/lib/api.php @@ -53,10 +53,6 @@ class OC_API { * @param array $parameters */ public static function call($parameters){ - - // Get the routes - self::loadRoutes(); - $name = $parameters['_name']; // Loop through registered actions foreach(self::$actions[$name] as $action){ @@ -104,21 +100,6 @@ class OC_API { return $finalresponse; } - /** - * loads the api routes - */ - private static function loadRoutes(){ - // TODO cache - foreach(OC_APP::getEnabledApps() as $app){ - $file = OC_App::getAppPath($app).'/appinfo/routes.php'; - if(file_exists($file)){ - require_once($file); - } - } - // include core routes - require_once(OC::$SERVERROOT.'ocs/routes.php'); - } - /** * respond to a call * @param int|array $response the response diff --git a/lib/router.php b/lib/router.php index f037ecdfef..f76f64ac82 100644 --- a/lib/router.php +++ b/lib/router.php @@ -16,6 +16,21 @@ class OC_Router { protected $collections = array(); protected $collection = null; + /** + * loads the api routes + */ + public function loadRoutes(){ + // TODO cache + foreach(OC_APP::getEnabledApps() as $app){ + $file = OC_App::getAppPath($app).'/appinfo/routes.php'; + if(file_exists($file)){ + require_once($file); + } + } + // include ocs routes + require_once(OC::$SERVERROOT.'/ocs/routes.php'); + } + public function useCollection($name) { if (!isset($this->collections[$name])) { $this->collections[$name] = new RouteCollection(); From 95d3b83a77f189569bbf38a54f771af1b85a9406 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 20:50:32 +0200 Subject: [PATCH 027/330] Create OC_Router in OC::init --- lib/base.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/base.php b/lib/base.php index 5041f43648..29a3502e35 100644 --- a/lib/base.php +++ b/lib/base.php @@ -62,6 +62,10 @@ class OC{ * requested file of app */ public static $REQUESTEDFILE = ''; + /* + * OC router + */ + public static $router = null; /** * check if owncloud runs in cli mode */ @@ -354,6 +358,8 @@ class OC{ OC_User::useBackend(new OC_User_Database()); OC_Group::useBackend(new OC_Group_Database()); + OC::$router = new OC_Router(); + // Load Apps // This includes plugins for users and filesystems as well global $RUNTIME_NOAPPS; From 180bd69dbb21dc6e53533a7d93972445b2ff922e Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 20:52:47 +0200 Subject: [PATCH 028/330] Fix OC_API::register --- lib/api.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/api.php b/lib/api.php index 00a3dc108e..fd2c621f38 100644 --- a/lib/api.php +++ b/lib/api.php @@ -40,8 +40,10 @@ class OC_API { */ public static function register($method, $url, $action, $app){ $name = strtolower($method).$url; + $name = str_replace(array('/', '{', '}'), '_', $name); if(!isset(self::$actions[$name])){ - OC_Router::create($name, $url.'.{format}') + OC::$router->create($name, $url.'.{_format}') + ->defaults(array('_format'=>'xml')) ->action('OC_API', 'call'); self::$actions[$name] = array(); } From 7a24f0cd8d28e60360127da19e40bff4b2e04168 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 21:03:41 +0200 Subject: [PATCH 029/330] Make calling ocs/v1.php/config work --- lib/api.php | 17 ++++++++++++----- lib/app.php | 2 +- lib/ocs.php | 18 ++++++++++++++++++ ocs/v1.php | 12 ++++++++++-- 4 files changed, 41 insertions(+), 8 deletions(-) diff --git a/lib/api.php b/lib/api.php index fd2c621f38..515bab6714 100644 --- a/lib/api.php +++ b/lib/api.php @@ -43,7 +43,8 @@ class OC_API { $name = str_replace(array('/', '{', '}'), '_', $name); if(!isset(self::$actions[$name])){ OC::$router->create($name, $url.'.{_format}') - ->defaults(array('_format'=>'xml')) + ->defaults(array('_format' => 'xml')) + ->requirements(array('_format' => 'xml|json')) ->action('OC_API', 'call'); self::$actions[$name] = array(); } @@ -55,7 +56,7 @@ class OC_API { * @param array $parameters */ public static function call($parameters){ - $name = $parameters['_name']; + $name = $parameters['_route']; // Loop through registered actions foreach(self::$actions[$name] as $action){ $app = $action['app']; @@ -107,8 +108,14 @@ class OC_API { * @param int|array $response the response * @param string $format the format xml|json */ - private function respond($response, $format='json'){ - // TODO respond in the correct format + private static function respond($response, $format='json'){ + if ($format == 'json') { + echo json_encode($response); + } else if ($format == 'xml') { + // TODO array to xml + } else { + var_dump($format, $response); + } } -} \ No newline at end of file +} diff --git a/lib/app.php b/lib/app.php index 60bd0ef476..7863153d9b 100644 --- a/lib/app.php +++ b/lib/app.php @@ -145,7 +145,7 @@ class OC_App{ * @param string $appid the id of the app to check * @return bool */ - public function isShipped($appid){ + public static function isShipped($appid){ $info = self::getAppInfo($appid); if(isset($info['shipped']) && $info['shipped']=='true'){ return true; diff --git a/lib/ocs.php b/lib/ocs.php index d7a7951fab..780fd4a658 100644 --- a/lib/ocs.php +++ b/lib/ocs.php @@ -251,6 +251,24 @@ class OC_OCS { exit(); } + public static function notFound() { + if($_SERVER['REQUEST_METHOD'] == 'GET') { + $method='get'; + }elseif($_SERVER['REQUEST_METHOD'] == 'PUT') { + $method='put'; + parse_str(file_get_contents("php://input"),$put_vars); + }elseif($_SERVER['REQUEST_METHOD'] == 'POST') { + $method='post'; + }else{ + echo('internal server error: method not supported'); + exit(); + } + $format = self::readData($method, 'format', 'text', ''); + $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n"; + $txt.=OC_OCS::getDebugOutput(); + echo(OC_OCS::generateXml($format,'failed',999,$txt)); + } + /** * generated some debug information to make it easier to find faild API calls * @return debug data string diff --git a/ocs/v1.php b/ocs/v1.php index ab0dc80f4b..4580221e60 100644 --- a/ocs/v1.php +++ b/ocs/v1.php @@ -22,5 +22,13 @@ */ require_once('../lib/base.php'); -@ob_clean(); -OC_OCS::handle(); +use Symfony\Component\Routing\Exception\ResourceNotFoundException; + +OC::$router->useCollection('ocs'); +OC::$router->loadRoutes(); + +try { + OC::$router->match($_SERVER['PATH_INFO']); +} catch (ResourceNotFoundException $e) { + OC_OCS::notFound(); +} From 0a9ca42c3479e1ebd0efee2bfae10958677bb657 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 21:13:29 +0200 Subject: [PATCH 030/330] Fix OC_OCS_Privatedata::privateDataGet --- lib/ocs/privatedata.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/lib/ocs/privatedata.php b/lib/ocs/privatedata.php index cb62d60a8d..7721404691 100644 --- a/lib/ocs/privatedata.php +++ b/lib/ocs/privatedata.php @@ -3,7 +3,10 @@ class OC_OCS_Privatedata { public static function privatedataGet($parameters){ - $user = OC_OCS::checkpassword(); + // TODO check user auth + $user = OC_User::getUser(); + $app = addslashes(strip_tags($parameters['app'])); + $key = addslashes(strip_tags($parameters['key'])); $result = OC_OCS::getData($user,$app,$key); $xml= array(); foreach($result as $i=>$log) { @@ -34,4 +37,4 @@ class OC_OCS_Privatedata { } -?> \ No newline at end of file +?> From cc6911e1f709edc42ea5558e19fcdeea75cdcf39 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 09:28:12 +0000 Subject: [PATCH 031/330] Make method static --- lib/public/api.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/public/api.php b/lib/public/api.php index 270aa89329..518e6f0097 100644 --- a/lib/public/api.php +++ b/lib/public/api.php @@ -34,7 +34,7 @@ class API { * @param callable $action the function to run * @param string $app the id of the app registering the call */ - public function register($method, $url, $action, $app){ + public static function register($method, $url, $action, $app){ OC_API::register($method, $url, $action, $app); } From b05639e745cabf8d11785f673593680448d844a2 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 10:10:15 +0000 Subject: [PATCH 032/330] Fix error with namespacing --- lib/public/api.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/public/api.php b/lib/public/api.php index 518e6f0097..ed1f6ef237 100644 --- a/lib/public/api.php +++ b/lib/public/api.php @@ -35,7 +35,7 @@ class API { * @param string $app the id of the app registering the call */ public static function register($method, $url, $action, $app){ - OC_API::register($method, $url, $action, $app); + \OC_API::register($method, $url, $action, $app); } } From 5922599f48b8eb2403265f4e4a5dad3899d3ebc6 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 12:10:42 +0100 Subject: [PATCH 033/330] Handle function not needed in lib/ocs.php --- lib/ocs.php | 181 ---------------------------------------------------- 1 file changed, 181 deletions(-) diff --git a/lib/ocs.php b/lib/ocs.php index 780fd4a658..d0b835b522 100644 --- a/lib/ocs.php +++ b/lib/ocs.php @@ -70,187 +70,6 @@ class OC_OCS { } } - /** - main function to handle the REST request - **/ - public static function handle() { - // overwrite the 404 error page returncode - header("HTTP/1.0 200 OK"); - - - if($_SERVER['REQUEST_METHOD'] == 'GET') { - $method='get'; - }elseif($_SERVER['REQUEST_METHOD'] == 'PUT') { - $method='put'; - parse_str(file_get_contents("php://input"),$put_vars); - }elseif($_SERVER['REQUEST_METHOD'] == 'POST') { - $method='post'; - }else{ - echo('internal server error: method not supported'); - exit(); - } - - $format = self::readData($method, 'format', 'text', ''); - - $router = new OC_Router(); - $router->useCollection('ocs'); - // CONFIG - $router->create('config', '/config.{format}') - ->defaults(array('format' => $format)) - ->action('OC_OCS', 'apiConfig') - ->requirements(array('format'=>'xml|json')); - - // PERSON - $router->create('person_check', '/person/check.{format}') - ->post() - ->defaults(array('format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - $login = OC_OCS::readData('post', 'login', 'text'); - $passwd = OC_OCS::readData('post', 'password', 'text'); - OC_OCS::personCheck($format,$login,$passwd); - }) - ->requirements(array('format'=>'xml|json')); - - // ACTIVITY - // activityget - GET ACTIVITY page,pagesize als urlparameter - $router->create('activity_get', '/activity.{format}') - ->defaults(array('format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - $page = OC_OCS::readData('get', 'page', 'int', 0); - $pagesize = OC_OCS::readData('get', 'pagesize', 'int', 10); - if($pagesize<1 or $pagesize>100) $pagesize=10; - OC_OCS::activityGet($format, $page, $pagesize); - }) - ->requirements(array('format'=>'xml|json')); - // activityput - POST ACTIVITY - $router->create('activity_put', '/activity.{format}') - ->post() - ->defaults(array('format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - $message = OC_OCS::readData('post', 'message', 'text'); - OC_OCS::activityPut($format,$message); - }) - ->requirements(array('format'=>'xml|json')); - - // PRIVATEDATA - // get - GET DATA - $router->create('privatedata_get', - '/privatedata/getattribute/{app}/{key}.{format}') - ->defaults(array('app' => '', 'key' => '', 'format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - $app = addslashes(strip_tags($parameters['app'])); - $key = addslashes(strip_tags($parameters['key'])); - OC_OCS::privateDataGet($format, $app, $key); - }) - ->requirements(array('format'=>'xml|json')); - // set - POST DATA - $router->create('privatedata_set', - '/privatedata/setattribute/{app}/{key}.{format}') - ->post() - ->defaults(array('format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - $app = addslashes(strip_tags($parameters['app'])); - $key = addslashes(strip_tags($parameters['key'])); - $value=OC_OCS::readData('post', 'value', 'text'); - OC_OCS::privateDataSet($format, $app, $key, $value); - }) - ->requirements(array('format'=>'xml|json')); - // delete - POST DATA - $router->create('privatedata_delete', - '/privatedata/deleteattribute/{app}/{key}.{format}') - ->post() - ->defaults(array('format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - $app = addslashes(strip_tags($parameters['app'])); - $key = addslashes(strip_tags($parameters['key'])); - OC_OCS::privateDataDelete($format, $app, $key); - }) - ->requirements(array('format'=>'xml|json')); - - // CLOUD - // systemWebApps - $router->create('system_webapps', - '/cloud/system/webapps.{format}') - ->defaults(array('format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - OC_OCS::systemwebapps($format); - }) - ->requirements(array('format'=>'xml|json')); - - // quotaget - $router->create('quota_get', - '/cloud/user/{user}.{format}') - ->defaults(array('format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - $user = $parameters['user']; - OC_OCS::quotaGet($format, $user); - }) - ->requirements(array('format'=>'xml|json')); - // quotaset - $router->create('quota_set', - '/cloud/user/{user}.{format}') - ->post() - ->defaults(array('format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - $user = $parameters['user']; - $quota = self::readData('post', 'quota', 'int'); - OC_OCS::quotaSet($format, $user, $quota); - }) - ->requirements(array('format'=>'xml|json')); - - // keygetpublic - $router->create('keygetpublic', - '/cloud/user/{user}/publickey.{format}') - ->defaults(array('format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - $user = $parameters['user']; - OC_OCS::publicKeyGet($format,$user); - }) - ->requirements(array('format'=>'xml|json')); - - // keygetprivate - $router->create('keygetpublic', - '/cloud/user/{user}/privatekey.{format}') - ->defaults(array('format' => $format)) - ->action(function ($parameters) { - $format = $parameters['format']; - $user = $parameters['user']; - OC_OCS::privateKeyGet($format,$user); - }) - ->requirements(array('format'=>'xml|json')); - - -// add more calls here -// please document all the call in the draft spec -// http://www.freedesktop.org/wiki/Specifications/open-collaboration-services-1.7#CLOUD - -// TODO: -// users -// groups -// bookmarks -// sharing -// versioning -// news (rss) - try { - $router->match($_SERVER['PATH_INFO']); - } catch (ResourceNotFoundException $e) { - $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n"; - $txt.=OC_OCS::getdebugoutput(); - echo(OC_OCS::generatexml($format,'failed',999,$txt)); - } - exit(); - } - public static function notFound() { if($_SERVER['REQUEST_METHOD'] == 'GET') { $method='get'; From 78bbcc8aeac5585a11dca0c1dc77cdd420182744 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 14:34:45 +0100 Subject: [PATCH 034/330] Basic OAuth class based on oauth-php. WIP --- lib/oauth.php | 128 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 lib/oauth.php diff --git a/lib/oauth.php b/lib/oauth.php new file mode 100644 index 0000000000..0eade6ab90 --- /dev/null +++ b/lib/oauth.php @@ -0,0 +1,128 @@ +. +* +*/ + +class OC_OAuth { + + /** + * the oauth-php server object + */ + private static $server; + + /** + * the oauth-php oauthstore object + */ + private static $store; + + /** + * initialises the OAuth store and server + */ + private static function init(){ + // Include the libraries + require_once(OC::$SERVERROOT.'3rdparty/oauth-php/library/OAuthServer.php'); + require_once(OC::$SERVERROOT.'3rdparty/oauth-php/library/OAuthStore.php'); + // Create the server object + self::$server = new OAuthServer(); + // Initialise the OAuth store + self::$store = OAuthStore::instance('owncloud'); + } + + /** + * gets a request token + * TODO save the scopes in the database with this token + */ + public static function getRequestToken(){ + self::init(); + self::$server->requestToken(); + } + + /** + * get the scopes requested by this token + * @param string $requesttoken + * @return array scopes + */ + public static function getScopes($requesttoken){ + // TODO + } + + /** + * exchanges authorised request token for access token + */ + public static function getAccessToken(){ + self::init(); + self::$server->accessToken(); + } + + /** + * registers a new consumer + * @param array $details consumer details, keys requester_name and requester_email required + * @param string $user the owncloud user adding the consumer + * @return array the consumers details including secret and key + */ + public static function registerConsumer($details, $user=null){ + self::init(); + $user = is_null($user) ? OC_User::getUser() : $user; + $consumer = self::$store->updateConsumer($details, $user, OC_Group::inGroup($user, 'admin')); + return $consumer; + } + + /** + * gets a list of consumers + * @param string $user + */ + public static function getConsumers($user=null){ + $user = is_null($user) ? OC_User::getUser() : $user; + return self::$store->listConsumers($user); + } + + /** + * authorises a request token - redirects to callback + * @param string $user + * @param bool $authorised + */ + public static function authoriseToken($user=null){ + $user = is_null($user) ? OC_User::getUser() : $user; + self::$server->authorizeVerify(); + self::$server->authorize($authorised, $user); + } + + /** + * checks if request is authorised + * TODO distinguish between failures as one is a 400 error and other is 401 + * @return string|int + */ + public static function isAuthorised(){ + if(OAuthRequestVerifier::requestIsSigned()){ + try{ + $req = new OAuthRequestVerifier(); + $user = $req->verify(); + return $user; + } catch(OAuthException $e) { + // 401 Unauthorised + return false; + } + } else { + // Bad request + return false; + } + } + +} \ No newline at end of file From ce41f3801eecc47f578ce8698cc69de16a16330b Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 14:59:07 +0100 Subject: [PATCH 035/330] Actually login the user when using OAuth --- lib/oauth.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/lib/oauth.php b/lib/oauth.php index 0eade6ab90..f0341b4b0d 100644 --- a/lib/oauth.php +++ b/lib/oauth.php @@ -114,6 +114,13 @@ class OC_OAuth { try{ $req = new OAuthRequestVerifier(); $user = $req->verify(); + $run = true; + OC_Hook::emit( "OC_User", "pre_login", array( "run" => &$run, "uid" => $user )); + if(!$run){ + return false; + } + OC_User::setUserId($user); + OC_Hook::emit( "OC_User", "post_login", array( "uid" => $user )); return $user; } catch(OAuthException $e) { // 401 Unauthorised From fcf3dbcfc13888a795a85f54179dfd548b34d4aa Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 15:02:51 +0100 Subject: [PATCH 036/330] Require a username for OC_OAuth::registerConsumer() --- lib/oauth.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/lib/oauth.php b/lib/oauth.php index f0341b4b0d..98678d2911 100644 --- a/lib/oauth.php +++ b/lib/oauth.php @@ -77,9 +77,8 @@ class OC_OAuth { * @param string $user the owncloud user adding the consumer * @return array the consumers details including secret and key */ - public static function registerConsumer($details, $user=null){ + public static function registerConsumer($details, $user){ self::init(); - $user = is_null($user) ? OC_User::getUser() : $user; $consumer = self::$store->updateConsumer($details, $user, OC_Group::inGroup($user, 'admin')); return $consumer; } From c2bdb5c71640567e0be3c2fc7e4d32af1469a55e Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 22:18:16 +0200 Subject: [PATCH 037/330] Fix require 3rdpartypath --- lib/oauth.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/oauth.php b/lib/oauth.php index 98678d2911..09dbe4cc75 100644 --- a/lib/oauth.php +++ b/lib/oauth.php @@ -37,8 +37,8 @@ class OC_OAuth { */ private static function init(){ // Include the libraries - require_once(OC::$SERVERROOT.'3rdparty/oauth-php/library/OAuthServer.php'); - require_once(OC::$SERVERROOT.'3rdparty/oauth-php/library/OAuthStore.php'); + require_once(OC::$THIRDPARTYROOT.'3rdparty/oauth-php/library/OAuthServer.php'); + require_once(OC::$THIRDPARTYROOT.'3rdparty/oauth-php/library/OAuthStore.php'); // Create the server object self::$server = new OAuthServer(); // Initialise the OAuth store From 28537037ae27a8e766d3c4ef129422dc02b45d5f Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 22:19:11 +0200 Subject: [PATCH 038/330] Fixup OCS modules --- lib/ocs/activity.php | 3 --- lib/ocs/cloud.php | 53 ++++++++++++++++++++--------------------- lib/ocs/config.php | 3 --- lib/ocs/person.php | 4 ---- lib/ocs/privatedata.php | 22 ++++++++++------- ocs/routes.php | 16 ++++++------- 6 files changed, 47 insertions(+), 54 deletions(-) diff --git a/lib/ocs/activity.php b/lib/ocs/activity.php index 3b090376e7..07b571665e 100644 --- a/lib/ocs/activity.php +++ b/lib/ocs/activity.php @@ -5,7 +5,4 @@ class OC_OCS_Activity { public static function activityGet($parameters){ // TODO } - } - -?> \ No newline at end of file diff --git a/lib/ocs/cloud.php b/lib/ocs/cloud.php index d0cd72e98c..2f2aad714a 100644 --- a/lib/ocs/cloud.php +++ b/lib/ocs/cloud.php @@ -2,8 +2,8 @@ class OC_OCS_Cloud { - public static function systemwebapps($parameters){ - $login = OC_OCS::checkpassword(); + public static function getSystemWebApps($parameters){ + OC_Util::checkLoggedIn(); $apps = OC_App::getEnabledApps(); $values = array(); foreach($apps as $app) { @@ -16,9 +16,10 @@ class OC_OCS_Cloud { return $values; } - public static function getQuota($parameters){ - $login=OC_OCS::checkpassword(); - if(OC_Group::inGroup($login, 'admin') or ($login==$parameters['user'])) { + public static function getUserQuota($parameters){ + OC_Util::checkLoggedIn(); + $user = OC_User::getUser(); + if(OC_Group::inGroup($user, 'admin') or ($user==$parameters['user'])) { if(OC_User::userExists($parameters['user'])){ // calculate the disc space @@ -47,9 +48,10 @@ class OC_OCS_Cloud { } } - public static function setQuota($parameters){ - $login=OC_OCS::checkpassword(); - if(OC_Group::inGroup($login, 'admin')) { + public static function setUserQuota($parameters){ + OC_Util::checkLoggedIn(); + $user = OC_User::getUser(); + if(OC_Group::inGroup($user, 'admin')) { // todo // not yet implemented @@ -63,8 +65,8 @@ class OC_OCS_Cloud { } } - public static function getPublickey($parameters){ - $login=OC_OCS::checkpassword(); + public static function getUserPublickey($parameters){ + OC_Util::checkLoggedIn(); if(OC_User::userExists($parameters['user'])){ // calculate the disc space @@ -75,23 +77,20 @@ class OC_OCS_Cloud { } } - public static function getPrivatekey($parameters){ - $login=OC_OCS::checkpassword(); - if(OC_Group::inGroup($login, 'admin') or ($login==$parameters['user'])) { + public static function getUserPrivatekey($parameters){ + OC_Util::checkLoggedIn(); + $user = OC_User::getUser(); + if(OC_Group::inGroup($user, 'admin') or ($user==$parameters['user'])) { - if(OC_User::userExists($user)){ - // calculate the disc space - $txt='this is the private key of '.$parameters['user']; - echo($txt); - }else{ - echo self::generateXml('', 'fail', 300, 'User does not exist'); - } - }else{ - echo self::generateXml('', 'fail', 300, 'You don´t have permission to access this ressource.'); - } + if(OC_User::userExists($user)){ + // calculate the disc space + $txt='this is the private key of '.$parameters['user']; + echo($txt); + }else{ + echo self::generateXml('', 'fail', 300, 'User does not exist'); + } + }else{ + echo self::generateXml('', 'fail', 300, 'You don´t have permission to access this ressource.'); + } } - - } - -?> \ No newline at end of file diff --git a/lib/ocs/config.php b/lib/ocs/config.php index b736abe3b9..06103cbeb4 100644 --- a/lib/ocs/config.php +++ b/lib/ocs/config.php @@ -10,7 +10,4 @@ class OC_OCS_Config { $xml['ssl'] = 'false'; return $xml; } - } - -?> \ No newline at end of file diff --git a/lib/ocs/person.php b/lib/ocs/person.php index f4e4be5ee0..629a7c2e6c 100644 --- a/lib/ocs/person.php +++ b/lib/ocs/person.php @@ -14,9 +14,5 @@ class OC_OCS_Person { }else{ return 101; } - } - } - -?> \ No newline at end of file diff --git a/lib/ocs/privatedata.php b/lib/ocs/privatedata.php index 7721404691..1c781dece8 100644 --- a/lib/ocs/privatedata.php +++ b/lib/ocs/privatedata.php @@ -2,8 +2,8 @@ class OC_OCS_Privatedata { - public static function privatedataGet($parameters){ - // TODO check user auth + public static function get($parameters){ + OC_Util::checkLoggedIn(); $user = OC_User::getUser(); $app = addslashes(strip_tags($parameters['app'])); $key = addslashes(strip_tags($parameters['key'])); @@ -18,15 +18,22 @@ class OC_OCS_Privatedata { //TODO: replace 'privatedata' with 'attribute' once a new libattice has been released that works with it } - public static function privatedataSet($parameters){ - $user = OC_OCS::checkpassword(); + public static function set($parameters){ + OC_Util::checkLoggedIn(); + $user = OC_User::getUser(); + $app = addslashes(strip_tags($parameters['app'])); + $key = addslashes(strip_tags($parameters['key'])); + $value = OC_OCS::readData('post', 'value', 'text'); if(OC_OCS::setData($user,$app,$key,$value)){ return 100; } } - public static function privatedataDelete($parameteres){ - $user = OC_OCS::checkpassword(); + public static function delete($parameters){ + OC_Util::checkLoggedIn(); + $user = OC_User::getUser(); + $app = addslashes(strip_tags($parameters['app'])); + $key = addslashes(strip_tags($parameters['key'])); if($key=="" or $app==""){ return; //key and app are NOT optional here } @@ -34,7 +41,4 @@ class OC_OCS_Privatedata { return 100; } } - } - -?> diff --git a/ocs/routes.php b/ocs/routes.php index a913254ebe..95df0c7ec9 100644 --- a/ocs/routes.php +++ b/ocs/routes.php @@ -12,14 +12,14 @@ OC_API::register('post', '/person/check', array('OC_OCS_Person', 'check'), 'ocs' // Activity OC_API::register('get', '/activity', array('OC_OCS_Activity', 'activityGet'), 'ocs'); // Privatedata -OC_API::register('get', '/privatedata/getattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataGet'), 'ocs'); -OC_API::register('post', '/privatedata/setattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataPut'), 'ocs'); -OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}', array('OC_OCS_Privatedata', 'privatedataDelete'), 'ocs'); +OC_API::register('get', '/privatedata/getattribute/{app}/{key}', array('OC_OCS_Privatedata', 'get'), 'ocs'); +OC_API::register('post', '/privatedata/setattribute/{app}/{key}', array('OC_OCS_Privatedata', 'set'), 'ocs'); +OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}', array('OC_OCS_Privatedata', 'delete'), 'ocs'); // Cloud -OC_API::register('get', '/cloud/system/webapps', array('OC_OCS_Cloud', 'systemwebapps'), 'ocs'); -OC_API::register('get', '/cloud/user/{user}', array('OC_OCS_Cloud', 'getQuota'), 'ocs'); -OC_API::register('post', '/cloud/user/{user}', array('OC_OCS_Cloud', 'setQuota'), 'ocs'); -OC_API::register('get', '/cloud/user/{user}/publickey', array('OC_OCS_Cloud', 'getPublicKey'), 'ocs'); -OC_API::register('get', '/cloud/user/{user}/privatekey', array('OC_OCS_Cloud', 'getPrivateKey'), 'ocs'); +OC_API::register('get', '/cloud/system/webapps', array('OC_OCS_Cloud', 'getSystemWebApps'), 'ocs'); +OC_API::register('get', '/cloud/user/{user}', array('OC_OCS_Cloud', 'getUserQuota'), 'ocs'); +OC_API::register('post', '/cloud/user/{user}', array('OC_OCS_Cloud', 'setUserQuota'), 'ocs'); +OC_API::register('get', '/cloud/user/{user}/publickey', array('OC_OCS_Cloud', 'getUserPublicKey'), 'ocs'); +OC_API::register('get', '/cloud/user/{user}/privatekey', array('OC_OCS_Cloud', 'getUserPrivateKey'), 'ocs'); ?> From 9d6a09f58946c8d4e7903d5b25a5fb00f6bcb5e8 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 22:33:11 +0200 Subject: [PATCH 039/330] Routing: Method needs to be uppercase --- lib/route.php | 10 +++++----- lib/router.php | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/route.php b/lib/route.php index 0d3339add6..df3a18e844 100644 --- a/lib/route.php +++ b/lib/route.php @@ -10,27 +10,27 @@ use Symfony\Component\Routing\Route; class OC_Route extends Route { public function method($method) { - $this->setRequirement('_method', $method); + $this->setRequirement('_method', strtoupper($method)); return $this; } public function post() { - $this->method('post'); + $this->method('POST'); return $this; } public function get() { - $this->method('get'); + $this->method('GET'); return $this; } public function put() { - $this->method('put'); + $this->method('PUT'); return $this; } public function delete() { - $this->method('delete'); + $this->method('DELETE'); return $this; } diff --git a/lib/router.php b/lib/router.php index f76f64ac82..c3864cfc91 100644 --- a/lib/router.php +++ b/lib/router.php @@ -51,7 +51,7 @@ class OC_Router { if (isset($parameters['action'])) { $action = $parameters['action']; if (!is_callable($action)) { - var_dump($action); + var_dump($action); throw new Exception('not a callable action'); } unset($parameters['action']); From 006b127da44b8cf0771000ed6fbf2228dfe734f6 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 22:33:53 +0200 Subject: [PATCH 040/330] Routing: Handle MethodNotAllowedException --- ocs/v1.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ocs/v1.php b/ocs/v1.php index 4580221e60..7cd61035e7 100644 --- a/ocs/v1.php +++ b/ocs/v1.php @@ -23,6 +23,7 @@ require_once('../lib/base.php'); use Symfony\Component\Routing\Exception\ResourceNotFoundException; +use Symfony\Component\Routing\Exception\MethodNotAllowedException; OC::$router->useCollection('ocs'); OC::$router->loadRoutes(); @@ -31,4 +32,6 @@ try { OC::$router->match($_SERVER['PATH_INFO']); } catch (ResourceNotFoundException $e) { OC_OCS::notFound(); +} catch (MethodNotAllowedException $e) { + OC_Response::setStatus(405); } From 71918a820f0e5b7e9479711107db059cd3a3b194 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 22:34:35 +0200 Subject: [PATCH 041/330] API: set request method for registered urls --- lib/api.php | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/api.php b/lib/api.php index 515bab6714..203b07880f 100644 --- a/lib/api.php +++ b/lib/api.php @@ -43,6 +43,7 @@ class OC_API { $name = str_replace(array('/', '{', '}'), '_', $name); if(!isset(self::$actions[$name])){ OC::$router->create($name, $url.'.{_format}') + ->method($method) ->defaults(array('_format' => 'xml')) ->requirements(array('_format' => 'xml|json')) ->action('OC_API', 'call'); From 7426217e760601f684c402bf363a51bb8c79947c Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 23:26:15 +0200 Subject: [PATCH 042/330] Fix /privatedata/getattribute route --- lib/api.php | 10 ++++++---- ocs/routes.php | 2 ++ 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/api.php b/lib/api.php index 203b07880f..cf699f547f 100644 --- a/lib/api.php +++ b/lib/api.php @@ -38,14 +38,16 @@ class OC_API { * @param callable $action the function to run * @param string $app the id of the app registering the call */ - public static function register($method, $url, $action, $app){ + public static function register($method, $url, $action, $app, + $defaults = array(), + $requirements = array()){ $name = strtolower($method).$url; $name = str_replace(array('/', '{', '}'), '_', $name); if(!isset(self::$actions[$name])){ OC::$router->create($name, $url.'.{_format}') ->method($method) - ->defaults(array('_format' => 'xml')) - ->requirements(array('_format' => 'xml|json')) + ->defaults(array('_format' => 'xml') + $defaults) + ->requirements(array('_format' => 'xml|json') + $requirements) ->action('OC_API', 'call'); self::$actions[$name] = array(); } @@ -112,7 +114,7 @@ class OC_API { private static function respond($response, $format='json'){ if ($format == 'json') { echo json_encode($response); - } else if ($format == 'xml') { + //} else if ($format == 'xml') { // TODO array to xml } else { var_dump($format, $response); diff --git a/ocs/routes.php b/ocs/routes.php index 95df0c7ec9..ac23e29af8 100644 --- a/ocs/routes.php +++ b/ocs/routes.php @@ -12,6 +12,8 @@ OC_API::register('post', '/person/check', array('OC_OCS_Person', 'check'), 'ocs' // Activity OC_API::register('get', '/activity', array('OC_OCS_Activity', 'activityGet'), 'ocs'); // Privatedata +OC_API::register('get', '/privatedata/getattribute', array('OC_OCS_Privatedata', 'get'), 'ocs', array('app' => '', 'key' => '')); +OC_API::register('get', '/privatedata/getattribute/{app}', array('OC_OCS_Privatedata', 'get'), 'ocs', array('key' => '')); OC_API::register('get', '/privatedata/getattribute/{app}/{key}', array('OC_OCS_Privatedata', 'get'), 'ocs'); OC_API::register('post', '/privatedata/setattribute/{app}/{key}', array('OC_OCS_Privatedata', 'set'), 'ocs'); OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}', array('OC_OCS_Privatedata', 'delete'), 'ocs'); From 9ec035e3d372634c633b2a3617566299788797f1 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 1 Aug 2012 10:20:17 +0100 Subject: [PATCH 043/330] Add oauth-php library --- 3rdparty/oauth-php/LICENSE | 22 + 3rdparty/oauth-php/README | 1 + 3rdparty/oauth-php/library/OAuthDiscovery.php | 227 ++ .../oauth-php/library/OAuthException2.php | 50 + 3rdparty/oauth-php/library/OAuthRequest.php | 846 +++++++ .../oauth-php/library/OAuthRequestLogger.php | 316 +++ .../oauth-php/library/OAuthRequestSigner.php | 215 ++ .../library/OAuthRequestVerifier.php | 306 +++ 3rdparty/oauth-php/library/OAuthRequester.php | 521 +++++ 3rdparty/oauth-php/library/OAuthServer.php | 333 +++ 3rdparty/oauth-php/library/OAuthSession.php | 86 + 3rdparty/oauth-php/library/OAuthStore.php | 86 + .../body/OAuthBodyContentDisposition.php | 129 ++ .../body/OAuthBodyMultipartFormdata.php | 143 ++ .../library/discovery/xrds_parse.php | 304 +++ .../library/discovery/xrds_parse.txt | 101 + .../session/OAuthSessionAbstract.class.php | 44 + .../library/session/OAuthSessionSESSION.php | 63 + .../OAuthSignatureMethod.class.php | 69 + .../OAuthSignatureMethod_HMAC_SHA1.php | 115 + .../OAuthSignatureMethod_MD5.php | 95 + .../OAuthSignatureMethod_PLAINTEXT.php | 80 + .../OAuthSignatureMethod_RSA_SHA1.php | 139 ++ .../library/store/OAuthStore2Leg.php | 113 + .../store/OAuthStoreAbstract.class.php | 150 ++ .../library/store/OAuthStoreAnyMeta.php | 264 +++ .../library/store/OAuthStoreMySQL.php | 245 +++ .../library/store/OAuthStoreMySQLi.php | 306 +++ .../library/store/OAuthStoreOracle.php | 1536 +++++++++++++ .../oauth-php/library/store/OAuthStorePDO.php | 274 +++ .../library/store/OAuthStorePostgreSQL.php | 1957 +++++++++++++++++ .../oauth-php/library/store/OAuthStoreSQL.php | 1827 +++++++++++++++ .../library/store/OAuthStoreSession.php | 157 ++ .../oauth-php/library/store/mysql/install.php | 32 + .../oauth-php/library/store/mysql/mysql.sql | 236 ++ .../store/oracle/OracleDB/1_Tables/TABLES.sql | 114 + .../oracle/OracleDB/2_Sequences/SEQUENCES.sql | 9 + .../SP_ADD_CONSUMER_REQUEST_TOKEN.prc | 71 + .../OracleDB/3_Procedures/SP_ADD_LOG.prc | 31 + .../3_Procedures/SP_ADD_SERVER_TOKEN.prc | 55 + .../SP_AUTH_CONSUMER_REQ_TOKEN.prc | 32 + .../3_Procedures/SP_CHECK_SERVER_NONCE.prc | 81 + .../3_Procedures/SP_CONSUMER_STATIC_SAVE.prc | 28 + .../SP_COUNT_CONSUMER_ACCESS_TOKEN.prc | 27 + .../3_Procedures/SP_COUNT_SERVICE_TOKENS.prc | 28 + .../3_Procedures/SP_DELETE_CONSUMER.prc | 35 + .../3_Procedures/SP_DELETE_SERVER.prc | 35 + .../3_Procedures/SP_DELETE_SERVER_TOKEN.prc | 37 + .../SP_DEL_CONSUMER_ACCESS_TOKEN.prc | 33 + .../SP_DEL_CONSUMER_REQUEST_TOKEN.prc | 25 + .../SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc | 96 + .../OracleDB/3_Procedures/SP_GET_CONSUMER.prc | 41 + .../SP_GET_CONSUMER_ACCESS_TOKEN.prc | 43 + .../SP_GET_CONSUMER_REQUEST_TOKEN.prc | 41 + .../SP_GET_CONSUMER_STATIC_SELECT.prc | 25 + .../SP_GET_SECRETS_FOR_SIGNATURE.prc | 43 + .../SP_GET_SECRETS_FOR_VERIFY.prc | 52 + .../OracleDB/3_Procedures/SP_GET_SERVER.prc | 35 + .../3_Procedures/SP_GET_SERVER_FOR_URI.prc | 41 + .../3_Procedures/SP_GET_SERVER_TOKEN.prc | 45 + .../SP_GET_SERVER_TOKEN_SECRETS.prc | 47 + .../3_Procedures/SP_LIST_CONSUMERS.prc | 41 + .../3_Procedures/SP_LIST_CONSUMER_TOKENS.prc | 43 + .../OracleDB/3_Procedures/SP_LIST_LOG.prc | 75 + .../OracleDB/3_Procedures/SP_LIST_SERVERS.prc | 66 + .../3_Procedures/SP_LIST_SERVER_TOKENS.prc | 45 + .../SP_SET_CONSUMER_ACC_TOKEN_TTL.prc | 28 + .../3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc | 29 + .../3_Procedures/SP_UPDATE_CONSUMER.prc | 40 + .../3_Procedures/SP_UPDATE_SERVER.prc | 139 ++ .../library/store/oracle/install.php | 28 + .../library/store/postgresql/pgsql.sql | 166 ++ 72 files changed, 13238 insertions(+) create mode 100644 3rdparty/oauth-php/LICENSE create mode 100644 3rdparty/oauth-php/README create mode 100644 3rdparty/oauth-php/library/OAuthDiscovery.php create mode 100644 3rdparty/oauth-php/library/OAuthException2.php create mode 100644 3rdparty/oauth-php/library/OAuthRequest.php create mode 100644 3rdparty/oauth-php/library/OAuthRequestLogger.php create mode 100644 3rdparty/oauth-php/library/OAuthRequestSigner.php create mode 100644 3rdparty/oauth-php/library/OAuthRequestVerifier.php create mode 100644 3rdparty/oauth-php/library/OAuthRequester.php create mode 100644 3rdparty/oauth-php/library/OAuthServer.php create mode 100644 3rdparty/oauth-php/library/OAuthSession.php create mode 100644 3rdparty/oauth-php/library/OAuthStore.php create mode 100644 3rdparty/oauth-php/library/body/OAuthBodyContentDisposition.php create mode 100644 3rdparty/oauth-php/library/body/OAuthBodyMultipartFormdata.php create mode 100644 3rdparty/oauth-php/library/discovery/xrds_parse.php create mode 100644 3rdparty/oauth-php/library/discovery/xrds_parse.txt create mode 100644 3rdparty/oauth-php/library/session/OAuthSessionAbstract.class.php create mode 100644 3rdparty/oauth-php/library/session/OAuthSessionSESSION.php create mode 100644 3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod.class.php create mode 100644 3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php create mode 100644 3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php create mode 100644 3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php create mode 100644 3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php create mode 100644 3rdparty/oauth-php/library/store/OAuthStore2Leg.php create mode 100644 3rdparty/oauth-php/library/store/OAuthStoreAbstract.class.php create mode 100644 3rdparty/oauth-php/library/store/OAuthStoreAnyMeta.php create mode 100644 3rdparty/oauth-php/library/store/OAuthStoreMySQL.php create mode 100644 3rdparty/oauth-php/library/store/OAuthStoreMySQLi.php create mode 100644 3rdparty/oauth-php/library/store/OAuthStoreOracle.php create mode 100644 3rdparty/oauth-php/library/store/OAuthStorePDO.php create mode 100644 3rdparty/oauth-php/library/store/OAuthStorePostgreSQL.php create mode 100644 3rdparty/oauth-php/library/store/OAuthStoreSQL.php create mode 100644 3rdparty/oauth-php/library/store/OAuthStoreSession.php create mode 100644 3rdparty/oauth-php/library/store/mysql/install.php create mode 100644 3rdparty/oauth-php/library/store/mysql/mysql.sql create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc create mode 100644 3rdparty/oauth-php/library/store/oracle/install.php create mode 100644 3rdparty/oauth-php/library/store/postgresql/pgsql.sql diff --git a/3rdparty/oauth-php/LICENSE b/3rdparty/oauth-php/LICENSE new file mode 100644 index 0000000000..fbdcc373b2 --- /dev/null +++ b/3rdparty/oauth-php/LICENSE @@ -0,0 +1,22 @@ +The MIT License + +Copyright (c) 2007-2009 Mediamatic Lab +Copyright (c) 2010 Corollarium Technologies + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/3rdparty/oauth-php/README b/3rdparty/oauth-php/README new file mode 100644 index 0000000000..ecd6815638 --- /dev/null +++ b/3rdparty/oauth-php/README @@ -0,0 +1 @@ +Please see http://code.google.com/p/oauth-php/ for documentation and help. diff --git a/3rdparty/oauth-php/library/OAuthDiscovery.php b/3rdparty/oauth-php/library/OAuthDiscovery.php new file mode 100644 index 0000000000..8eee11877b --- /dev/null +++ b/3rdparty/oauth-php/library/OAuthDiscovery.php @@ -0,0 +1,227 @@ + + * @date Sep 4, 2008 5:05:19 PM + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__).'/discovery/xrds_parse.php'; + +require_once dirname(__FILE__).'/OAuthException2.php'; +require_once dirname(__FILE__).'/OAuthRequestLogger.php'; + + +class OAuthDiscovery +{ + /** + * Return a description how we can do a consumer allocation. Prefers static allocation if + * possible. If static allocation is possible + * + * See also: http://oauth.net/discovery/#consumer_identity_types + * + * @param string uri + * @return array provider description + */ + static function discover ( $uri ) + { + // See what kind of consumer allocations are available + $xrds_file = self::discoverXRDS($uri); + if (!empty($xrds_file)) + { + $xrds = xrds_parse($xrds_file); + if (empty($xrds)) + { + throw new OAuthException2('Could not discover OAuth information for '.$uri); + } + } + else + { + throw new OAuthException2('Could not discover XRDS file at '.$uri); + } + + // Fill an OAuthServer record for the uri found + $ps = parse_url($uri); + $host = isset($ps['host']) ? $ps['host'] : 'localhost'; + $server_uri = $ps['scheme'].'://'.$host.'/'; + + $p = array( + 'user_id' => null, + 'consumer_key' => '', + 'consumer_secret' => '', + 'signature_methods' => '', + 'server_uri' => $server_uri, + 'request_token_uri' => '', + 'authorize_uri' => '', + 'access_token_uri' => '' + ); + + + // Consumer identity (out of bounds or static) + if (isset($xrds['consumer_identity'])) + { + // Try to find a static consumer allocation, we like those :) + foreach ($xrds['consumer_identity'] as $ci) + { + if ($ci['method'] == 'static' && !empty($ci['consumer_key'])) + { + $p['consumer_key'] = $ci['consumer_key']; + $p['consumer_secret'] = ''; + } + else if ($ci['method'] == 'oob' && !empty($ci['uri'])) + { + // TODO: Keep this uri somewhere for the user? + $p['consumer_oob_uri'] = $ci['uri']; + } + } + } + + // The token uris + if (isset($xrds['request'][0]['uri'])) + { + $p['request_token_uri'] = $xrds['request'][0]['uri']; + if (!empty($xrds['request'][0]['signature_method'])) + { + $p['signature_methods'] = $xrds['request'][0]['signature_method']; + } + } + if (isset($xrds['authorize'][0]['uri'])) + { + $p['authorize_uri'] = $xrds['authorize'][0]['uri']; + if (!empty($xrds['authorize'][0]['signature_method'])) + { + $p['signature_methods'] = $xrds['authorize'][0]['signature_method']; + } + } + if (isset($xrds['access'][0]['uri'])) + { + $p['access_token_uri'] = $xrds['access'][0]['uri']; + if (!empty($xrds['access'][0]['signature_method'])) + { + $p['signature_methods'] = $xrds['access'][0]['signature_method']; + } + } + return $p; + } + + + /** + * Discover the XRDS file at the uri. This is a bit primitive, you should overrule + * this function so that the XRDS file can be cached for later referral. + * + * @param string uri + * @return string false when no XRDS file found + */ + static protected function discoverXRDS ( $uri, $recur = 0 ) + { + // Bail out when we are following redirects + if ($recur > 10) + { + return false; + } + + $data = self::curl($uri); + + // Check what we got back, could be: + // 1. The XRDS discovery file itself (check content-type) + // 2. The X-XRDS-Location header + + if (is_string($data) && !empty($data)) + { + list($head,$body) = explode("\r\n\r\n", $data); + $body = trim($body); + $m = false; + + // See if we got the XRDS file itself or we have to follow a location header + if ( preg_match('/^Content-Type:\s*application\/xrds+xml/im', $head) + || preg_match('/^<\?xml[^>]*\?>\s* \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthException2.php b/3rdparty/oauth-php/library/OAuthException2.php new file mode 100644 index 0000000000..30fc80e8fb --- /dev/null +++ b/3rdparty/oauth-php/library/OAuthException2.php @@ -0,0 +1,50 @@ + + * @date Nov 29, 2007 5:33:54 PM + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +// TODO: something with the HTTP return code matching to the problem + +require_once dirname(__FILE__) . '/OAuthRequestLogger.php'; + +class OAuthException2 extends Exception +{ + function __construct ( $message ) + { + Exception::__construct($message); + OAuthRequestLogger::addNote('OAuthException2: '.$message); + } + +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthRequest.php b/3rdparty/oauth-php/library/OAuthRequest.php new file mode 100644 index 0000000000..e37e8369a1 --- /dev/null +++ b/3rdparty/oauth-php/library/OAuthRequest.php @@ -0,0 +1,846 @@ + + * @date Nov 16, 2007 12:20:31 PM + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + +require_once dirname(__FILE__) . '/OAuthException2.php'; + +/** + * Object to parse an incoming OAuth request or prepare an outgoing OAuth request + */ +class OAuthRequest +{ + /* the realm for this request */ + protected $realm; + + /* all the parameters, RFC3986 encoded name/value pairs */ + protected $param = array(); + + /* the parsed request uri */ + protected $uri_parts; + + /* the raw request uri */ + protected $uri; + + /* the request headers */ + protected $headers; + + /* the request method */ + protected $method; + + /* the body of the OAuth request */ + protected $body; + + + /** + * Construct from the current request. Useful for checking the signature of a request. + * When not supplied with any parameters this will use the current request. + * + * @param string uri might include parameters + * @param string method GET, PUT, POST etc. + * @param string parameters additional post parameters, urlencoded (RFC1738) + * @param array headers headers for request + * @param string body optional body of the OAuth request (POST or PUT) + */ + function __construct ( $uri = null, $method = null, $parameters = '', $headers = array(), $body = null ) + { + if (is_object($_SERVER)) + { + // Tainted arrays - the normal stuff in anyMeta + if (!$method) { + $method = $_SERVER->REQUEST_METHOD->getRawUnsafe(); + } + if (empty($uri)) { + $uri = $_SERVER->REQUEST_URI->getRawUnsafe(); + } + } + else + { + // non anyMeta systems + if (!$method) { + if (isset($_SERVER['REQUEST_METHOD'])) { + $method = $_SERVER['REQUEST_METHOD']; + } + else { + $method = 'GET'; + } + } + $proto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http'; + if (empty($uri)) { + if (strpos($_SERVER['REQUEST_URI'], "://") !== false) { + $uri = $_SERVER['REQUEST_URI']; + } + else { + $uri = sprintf('%s://%s%s', $proto, $_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI']); + } + } + } + $headers = OAuthRequestLogger::getAllHeaders(); + $this->method = strtoupper($method); + + // If this is a post then also check the posted variables + if (strcasecmp($method, 'POST') == 0) + { + // TODO: what to do with 'multipart/form-data'? + if ($this->getRequestContentType() == 'multipart/form-data') + { + // Get the posted body (when available) + if (!isset($headers['X-OAuth-Test'])) + { + $parameters .= $this->getRequestBodyOfMultipart(); + } + } + if ($this->getRequestContentType() == 'application/x-www-form-urlencoded') + { + // Get the posted body (when available) + if (!isset($headers['X-OAuth-Test'])) + { + $parameters .= $this->getRequestBody(); + } + } + else + { + $body = $this->getRequestBody(); + } + } + else if (strcasecmp($method, 'PUT') == 0) + { + $body = $this->getRequestBody(); + } + + $this->method = strtoupper($method); + $this->headers = $headers; + // Store the values, prepare for oauth + $this->uri = $uri; + $this->body = $body; + $this->parseUri($parameters); + $this->parseHeaders(); + $this->transcodeParams(); + } + + + /** + * Return the signature base string. + * Note that we can't use rawurlencode due to specified use of RFC3986. + * + * @return string + */ + function signatureBaseString () + { + $sig = array(); + $sig[] = $this->method; + $sig[] = $this->getRequestUrl(); + $sig[] = $this->getNormalizedParams(); + + return implode('&', array_map(array($this, 'urlencode'), $sig)); + } + + + /** + * Calculate the signature of the request, using the method in oauth_signature_method. + * The signature is returned encoded in the form as used in the url. So the base64 and + * urlencoding has been done. + * + * @param string consumer_secret + * @param string token_secret + * @param string token_type + * @exception when not all parts available + * @return string + */ + function calculateSignature ( $consumer_secret, $token_secret, $token_type = 'access' ) + { + $required = array( + 'oauth_consumer_key', + 'oauth_signature_method', + 'oauth_timestamp', + 'oauth_nonce' + ); + + if ($token_type != 'requestToken') + { + $required[] = 'oauth_token'; + } + + foreach ($required as $req) + { + if (!isset($this->param[$req])) + { + throw new OAuthException2('Can\'t sign request, missing parameter "'.$req.'"'); + } + } + + $this->checks(); + + $base = $this->signatureBaseString(); + $signature = $this->calculateDataSignature($base, $consumer_secret, $token_secret, $this->param['oauth_signature_method']); + return $signature; + } + + + /** + * Calculate the signature of a string. + * Uses the signature method from the current parameters. + * + * @param string data + * @param string consumer_secret + * @param string token_secret + * @param string signature_method + * @exception OAuthException2 thrown when the signature method is unknown + * @return string signature + */ + function calculateDataSignature ( $data, $consumer_secret, $token_secret, $signature_method ) + { + if (is_null($data)) + { + $data = ''; + } + + $sig = $this->getSignatureMethod($signature_method); + return $sig->signature($this, $data, $consumer_secret, $token_secret); + } + + + /** + * Select a signature method from the list of available methods. + * We try to check the most secure methods first. + * + * @todo Let the signature method tell us how secure it is + * @param array methods + * @exception OAuthException2 when we don't support any method in the list + * @return string + */ + public function selectSignatureMethod ( $methods ) + { + if (in_array('HMAC-SHA1', $methods)) + { + $method = 'HMAC-SHA1'; + } + else if (in_array('MD5', $methods)) + { + $method = 'MD5'; + } + else + { + $method = false; + foreach ($methods as $m) + { + $m = strtoupper($m); + $m2 = preg_replace('/[^A-Z0-9]/', '_', $m); + if (file_exists(dirname(__FILE__).'/signature_method/OAuthSignatureMethod_'.$m2.'.php')) + { + $method = $m; + break; + } + } + + if (empty($method)) + { + throw new OAuthException2('None of the signing methods is supported.'); + } + } + return $method; + } + + + /** + * Fetch the signature object used for calculating and checking the signature base string + * + * @param string method + * @return OAuthSignatureMethod object + */ + function getSignatureMethod ( $method ) + { + $m = strtoupper($method); + $m = preg_replace('/[^A-Z0-9]/', '_', $m); + $class = 'OAuthSignatureMethod_'.$m; + + if (file_exists(dirname(__FILE__).'/signature_method/'.$class.'.php')) + { + require_once dirname(__FILE__).'/signature_method/'.$class.'.php'; + $sig = new $class(); + } + else + { + throw new OAuthException2('Unsupported signature method "'.$m.'".'); + } + return $sig; + } + + + /** + * Perform some sanity checks. + * + * @exception OAuthException2 thrown when sanity checks failed + */ + function checks () + { + if (isset($this->param['oauth_version'])) + { + $version = $this->urldecode($this->param['oauth_version']); + if ($version != '1.0') + { + throw new OAuthException2('Expected OAuth version 1.0, got "'.$this->param['oauth_version'].'"'); + } + } + } + + + /** + * Return the request method + * + * @return string + */ + function getMethod () + { + return $this->method; + } + + /** + * Return the complete parameter string for the signature check. + * All parameters are correctly urlencoded and sorted on name and value + * + * @return string + */ + function getNormalizedParams () + { + /* + // sort by name, then by value + // (needed when we start allowing multiple values with the same name) + $keys = array_keys($this->param); + $values = array_values($this->param); + array_multisort($keys, SORT_ASC, $values, SORT_ASC); + */ + $params = $this->param; + $normalized = array(); + + ksort($params); + foreach ($params as $key => $value) + { + // all names and values are already urlencoded, exclude the oauth signature + if ($key != 'oauth_signature') + { + if (is_array($value)) + { + $value_sort = $value; + sort($value_sort); + foreach ($value_sort as $v) + { + $normalized[] = $key.'='.$v; + } + } + else + { + $normalized[] = $key.'='.$value; + } + } + } + return implode('&', $normalized); + } + + + /** + * Return the normalised url for signature checks + */ + function getRequestUrl () + { + $url = $this->uri_parts['scheme'] . '://' + . $this->uri_parts['user'] . (!empty($this->uri_parts['pass']) ? ':' : '') + . $this->uri_parts['pass'] . (!empty($this->uri_parts['user']) ? '@' : '') + . $this->uri_parts['host']; + + if ( $this->uri_parts['port'] + && $this->uri_parts['port'] != $this->defaultPortForScheme($this->uri_parts['scheme'])) + { + $url .= ':'.$this->uri_parts['port']; + } + if (!empty($this->uri_parts['path'])) + { + $url .= $this->uri_parts['path']; + } + return $url; + } + + + /** + * Get a parameter, value is always urlencoded + * + * @param string name + * @param boolean urldecode set to true to decode the value upon return + * @return string value false when not found + */ + function getParam ( $name, $urldecode = false ) + { + if (isset($this->param[$name])) + { + $s = $this->param[$name]; + } + else if (isset($this->param[$this->urlencode($name)])) + { + $s = $this->param[$this->urlencode($name)]; + } + else + { + $s = false; + } + if (!empty($s) && $urldecode) + { + if (is_array($s)) + { + $s = array_map(array($this,'urldecode'), $s); + } + else + { + $s = $this->urldecode($s); + } + } + return $s; + } + + /** + * Set a parameter + * + * @param string name + * @param string value + * @param boolean encoded set to true when the values are already encoded + */ + function setParam ( $name, $value, $encoded = false ) + { + if (!$encoded) + { + $name_encoded = $this->urlencode($name); + if (is_array($value)) + { + foreach ($value as $v) + { + $this->param[$name_encoded][] = $this->urlencode($v); + } + } + else + { + $this->param[$name_encoded] = $this->urlencode($value); + } + } + else + { + $this->param[$name] = $value; + } + } + + + /** + * Re-encode all parameters so that they are encoded using RFC3986. + * Updates the $this->param attribute. + */ + protected function transcodeParams () + { + $params = $this->param; + $this->param = array(); + + foreach ($params as $name=>$value) + { + if (is_array($value)) + { + $this->param[$this->urltranscode($name)] = array_map(array($this,'urltranscode'), $value); + } + else + { + $this->param[$this->urltranscode($name)] = $this->urltranscode($value); + } + } + } + + + + /** + * Return the body of the OAuth request. + * + * @return string null when no body + */ + function getBody () + { + return $this->body; + } + + + /** + * Return the body of the OAuth request. + * + * @return string null when no body + */ + function setBody ( $body ) + { + $this->body = $body; + } + + + /** + * Parse the uri into its parts. Fill in the missing parts. + * + * @param string $parameters optional extra parameters (from eg the http post) + */ + protected function parseUri ( $parameters ) + { + $ps = @parse_url($this->uri); + + // Get the current/requested method + $ps['scheme'] = strtolower($ps['scheme']); + + // Get the current/requested host + if (function_exists('mb_strtolower')) + $ps['host'] = mb_strtolower($ps['host']); + else + $ps['host'] = strtolower($ps['host']); + + if (!preg_match('/^[a-z0-9\.\-]+$/', $ps['host'])) + { + throw new OAuthException2('Unsupported characters in host name'); + } + + // Get the port we are talking on + if (empty($ps['port'])) + { + $ps['port'] = $this->defaultPortForScheme($ps['scheme']); + } + + if (empty($ps['user'])) + { + $ps['user'] = ''; + } + if (empty($ps['pass'])) + { + $ps['pass'] = ''; + } + if (empty($ps['path'])) + { + $ps['path'] = '/'; + } + if (empty($ps['query'])) + { + $ps['query'] = ''; + } + if (empty($ps['fragment'])) + { + $ps['fragment'] = ''; + } + + // Now all is complete - parse all parameters + foreach (array($ps['query'], $parameters) as $params) + { + if (strlen($params) > 0) + { + $params = explode('&', $params); + foreach ($params as $p) + { + @list($name, $value) = explode('=', $p, 2); + if (!strlen($name)) + { + continue; + } + + if (array_key_exists($name, $this->param)) + { + if (is_array($this->param[$name])) + $this->param[$name][] = $value; + else + $this->param[$name] = array($this->param[$name], $value); + } + else + { + $this->param[$name] = $value; + } + } + } + } + $this->uri_parts = $ps; + } + + + /** + * Return the default port for a scheme + * + * @param string scheme + * @return int + */ + protected function defaultPortForScheme ( $scheme ) + { + switch ($scheme) + { + case 'http': return 80; + case 'https': return 443; + default: + throw new OAuthException2('Unsupported scheme type, expected http or https, got "'.$scheme.'"'); + break; + } + } + + + /** + * Encode a string according to the RFC3986 + * + * @param string s + * @return string + */ + function urlencode ( $s ) + { + if ($s === false) + { + return $s; + } + else + { + return str_replace('%7E', '~', rawurlencode($s)); + } + } + + /** + * Decode a string according to RFC3986. + * Also correctly decodes RFC1738 urls. + * + * @param string s + * @return string + */ + function urldecode ( $s ) + { + if ($s === false) + { + return $s; + } + else + { + return rawurldecode($s); + } + } + + /** + * urltranscode - make sure that a value is encoded using RFC3986. + * We use a basic urldecode() function so that any use of '+' as the + * encoding of the space character is correctly handled. + * + * @param string s + * @return string + */ + function urltranscode ( $s ) + { + if ($s === false) + { + return $s; + } + else + { + return $this->urlencode(rawurldecode($s)); + // return $this->urlencode(urldecode($s)); + } + } + + + /** + * Parse the oauth parameters from the request headers + * Looks for something like: + * + * Authorization: OAuth realm="http://photos.example.net/authorize", + * oauth_consumer_key="dpf43f3p2l4k3l03", + * oauth_token="nnch734d00sl2jdk", + * oauth_signature_method="HMAC-SHA1", + * oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D", + * oauth_timestamp="1191242096", + * oauth_nonce="kllo9940pd9333jh", + * oauth_version="1.0" + */ + private function parseHeaders () + { +/* + $this->headers['Authorization'] = 'OAuth realm="http://photos.example.net/authorize", + oauth_consumer_key="dpf43f3p2l4k3l03", + oauth_token="nnch734d00sl2jdk", + oauth_signature_method="HMAC-SHA1", + oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D", + oauth_timestamp="1191242096", + oauth_nonce="kllo9940pd9333jh", + oauth_version="1.0"'; +*/ + if (isset($this->headers['Authorization'])) + { + $auth = trim($this->headers['Authorization']); + if (strncasecmp($auth, 'OAuth', 4) == 0) + { + $vs = explode(',', substr($auth, 6)); + foreach ($vs as $v) + { + if (strpos($v, '=')) + { + $v = trim($v); + list($name,$value) = explode('=', $v, 2); + if (!empty($value) && $value{0} == '"' && substr($value, -1) == '"') + { + $value = substr(substr($value, 1), 0, -1); + } + + if (strcasecmp($name, 'realm') == 0) + { + $this->realm = $value; + } + else + { + $this->param[$name] = $value; + } + } + } + } + } + } + + + /** + * Fetch the content type of the current request + * + * @return string + */ + private function getRequestContentType () + { + $content_type = 'application/octet-stream'; + if (!empty($_SERVER) && array_key_exists('CONTENT_TYPE', $_SERVER)) + { + list($content_type) = explode(';', $_SERVER['CONTENT_TYPE']); + } + return trim($content_type); + } + + + /** + * Get the body of a POST or PUT. + * + * Used for fetching the post parameters and to calculate the body signature. + * + * @return string null when no body present (or wrong content type for body) + */ + private function getRequestBody () + { + $body = null; + if ($this->method == 'POST' || $this->method == 'PUT') + { + $body = ''; + $fh = @fopen('php://input', 'r'); + if ($fh) + { + while (!feof($fh)) + { + $s = fread($fh, 1024); + if (is_string($s)) + { + $body .= $s; + } + } + fclose($fh); + } + } + return $body; + } + + /** + * Get the body of a POST with multipart/form-data by Edison tsai on 16:52 2010/09/16 + * + * Used for fetching the post parameters and to calculate the body signature. + * + * @return string null when no body present (or wrong content type for body) + */ + private function getRequestBodyOfMultipart() + { + $body = null; + if ($this->method == 'POST') + { + $body = ''; + if (is_array($_POST) && count($_POST) > 1) + { + foreach ($_POST AS $k => $v) { + $body .= $k . '=' . $this->urlencode($v) . '&'; + } #end foreach + if(substr($body,-1) == '&') + { + $body = substr($body, 0, strlen($body)-1); + } #end if + } #end if + } #end if + + return $body; + } + + + /** + * Simple function to perform a redirect (GET). + * Redirects the User-Agent, does not return. + * + * @param string uri + * @param array params parameters, urlencoded + * @exception OAuthException2 when redirect uri is illegal + */ + public function redirect ( $uri, $params ) + { + if (!empty($params)) + { + $q = array(); + foreach ($params as $name=>$value) + { + $q[] = $name.'='.$value; + } + $q_s = implode('&', $q); + + if (strpos($uri, '?')) + { + $uri .= '&'.$q_s; + } + else + { + $uri .= '?'.$q_s; + } + } + + // simple security - multiline location headers can inject all kinds of extras + $uri = preg_replace('/\s/', '%20', $uri); + if (strncasecmp($uri, 'http://', 7) && strncasecmp($uri, 'https://', 8)) + { + if (strpos($uri, '://')) + { + throw new OAuthException2('Illegal protocol in redirect uri '.$uri); + } + $uri = 'http://'.$uri; + } + + header('HTTP/1.1 302 Found'); + header('Location: '.$uri); + echo ''; + exit(); + } +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthRequestLogger.php b/3rdparty/oauth-php/library/OAuthRequestLogger.php new file mode 100644 index 0000000000..7307600041 --- /dev/null +++ b/3rdparty/oauth-php/library/OAuthRequestLogger.php @@ -0,0 +1,316 @@ + + * @date Dec 7, 2007 12:22:43 PM + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +class OAuthRequestLogger +{ + static private $logging = 0; + static private $enable_logging = null; + static private $store_log = null; + static private $note = ''; + static private $user_id = null; + static private $request_object = null; + static private $sent = null; + static private $received = null; + static private $log = array(); + + /** + * Start any logging, checks the system configuration if logging is needed. + * + * @param OAuthRequest $request_object + */ + static function start ( $request_object = null ) + { + if (defined('OAUTH_LOG_REQUEST')) + { + if (is_null(OAuthRequestLogger::$enable_logging)) + { + OAuthRequestLogger::$enable_logging = true; + } + if (is_null(OAuthRequestLogger::$store_log)) + { + OAuthRequestLogger::$store_log = true; + } + } + + if (OAuthRequestLogger::$enable_logging && !OAuthRequestLogger::$logging) + { + OAuthRequestLogger::$logging = true; + OAuthRequestLogger::$request_object = $request_object; + ob_start(); + + // Make sure we flush our log entry when we stop the request (eg on an exception) + register_shutdown_function(array('OAuthRequestLogger','flush')); + } + } + + + /** + * Force logging, needed for performing test connects independent from the debugging setting. + * + * @param boolean store_log (optional) true to store the log in the db + */ + static function enableLogging ( $store_log = null ) + { + OAuthRequestLogger::$enable_logging = true; + if (!is_null($store_log)) + { + OAuthRequestLogger::$store_log = $store_log; + } + } + + + /** + * Logs the request to the database, sends any cached output. + * Also called on shutdown, to make sure we always log the request being handled. + */ + static function flush () + { + if (OAuthRequestLogger::$logging) + { + OAuthRequestLogger::$logging = false; + + if (is_null(OAuthRequestLogger::$sent)) + { + // What has been sent to the user-agent? + $data = ob_get_contents(); + if (strlen($data) > 0) + { + ob_end_flush(); + } + elseif (ob_get_level()) + { + ob_end_clean(); + } + $hs = headers_list(); + $sent = implode("\n", $hs) . "\n\n" . $data; + } + else + { + // The request we sent + $sent = OAuthRequestLogger::$sent; + } + + if (is_null(OAuthRequestLogger::$received)) + { + // Build the request we received + $hs0 = self::getAllHeaders(); + $hs = array(); + foreach ($hs0 as $h => $v) + { + $hs[] = "$h: $v"; + } + + $data = ''; + $fh = @fopen('php://input', 'r'); + if ($fh) + { + while (!feof($fh)) + { + $s = fread($fh, 1024); + if (is_string($s)) + { + $data .= $s; + } + } + fclose($fh); + } + $received = implode("\n", $hs) . "\n\n" . $data; + } + else + { + // The answer we received + $received = OAuthRequestLogger::$received; + } + + // The request base string + if (OAuthRequestLogger::$request_object) + { + $base_string = OAuthRequestLogger::$request_object->signatureBaseString(); + } + else + { + $base_string = ''; + } + + // Figure out to what keys we want to log this request + $keys = array(); + if (OAuthRequestLogger::$request_object) + { + $consumer_key = OAuthRequestLogger::$request_object->getParam('oauth_consumer_key', true); + $token = OAuthRequestLogger::$request_object->getParam('oauth_token', true); + + switch (get_class(OAuthRequestLogger::$request_object)) + { + // tokens are access/request tokens by a consumer + case 'OAuthServer': + case 'OAuthRequestVerifier': + $keys['ocr_consumer_key'] = $consumer_key; + $keys['oct_token'] = $token; + break; + + // tokens are access/request tokens to a server + case 'OAuthRequester': + case 'OAuthRequestSigner': + $keys['osr_consumer_key'] = $consumer_key; + $keys['ost_token'] = $token; + break; + } + } + + // Log the request + if (OAuthRequestLogger::$store_log) + { + $store = OAuthStore::instance(); + $store->addLog($keys, $received, $sent, $base_string, OAuthRequestLogger::$note, OAuthRequestLogger::$user_id); + } + + OAuthRequestLogger::$log[] = array( + 'keys' => $keys, + 'received' => $received, + 'sent' => $sent, + 'base_string' => $base_string, + 'note' => OAuthRequestLogger::$note + ); + } + } + + + /** + * Add a note, used by the OAuthException2 to log all exceptions. + * + * @param string note + */ + static function addNote ( $note ) + { + OAuthRequestLogger::$note .= $note . "\n\n"; + } + + /** + * Set the OAuth request object being used + * + * @param OAuthRequest request_object + */ + static function setRequestObject ( $request_object ) + { + OAuthRequestLogger::$request_object = $request_object; + } + + + /** + * Set the relevant user (defaults to the current user) + * + * @param int user_id + */ + static function setUser ( $user_id ) + { + OAuthRequestLogger::$user_id = $user_id; + } + + + /** + * Set the request we sent + * + * @param string request + */ + static function setSent ( $request ) + { + OAuthRequestLogger::$sent = $request; + } + + /** + * Set the reply we received + * + * @param string request + */ + static function setReceived ( $reply ) + { + OAuthRequestLogger::$received = $reply; + } + + + /** + * Get the the log till now + * + * @return array + */ + static function getLog () + { + return OAuthRequestLogger::$log; + } + + + /** + * helper to try to sort out headers for people who aren't running apache, + * or people who are running PHP as FastCGI. + * + * @return array of request headers as associative array. + */ + public static function getAllHeaders() { + $retarr = array(); + $headers = array(); + + if (function_exists('apache_request_headers')) { + $headers = apache_request_headers(); + ksort($headers); + return $headers; + } else { + $headers = array_merge($_ENV, $_SERVER); + + foreach ($headers as $key => $val) { + //we need this header + if (strpos(strtolower($key), 'content-type') !== FALSE) + continue; + if (strtoupper(substr($key, 0, 5)) != "HTTP_") + unset($headers[$key]); + } + } + + //Normalize this array to Cased-Like-This structure. + foreach ($headers AS $key => $value) { + $key = preg_replace('/^HTTP_/i', '', $key); + $key = str_replace( + " ", + "-", + ucwords(strtolower(str_replace(array("-", "_"), " ", $key))) + ); + $retarr[$key] = $value; + } + ksort($retarr); + + return $retarr; + } +} + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthRequestSigner.php b/3rdparty/oauth-php/library/OAuthRequestSigner.php new file mode 100644 index 0000000000..15c0fd88cc --- /dev/null +++ b/3rdparty/oauth-php/library/OAuthRequestSigner.php @@ -0,0 +1,215 @@ + + * @date Nov 16, 2007 4:02:49 PM + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + +require_once dirname(__FILE__) . '/OAuthStore.php'; +require_once dirname(__FILE__) . '/OAuthRequest.php'; + + +class OAuthRequestSigner extends OAuthRequest +{ + protected $request; + protected $store; + protected $usr_id = 0; + private $signed = false; + + + /** + * Construct the request to be signed. Parses or appends the parameters in the params url. + * When you supply an params array, then the params should not be urlencoded. + * When you supply a string, then it is assumed it is of the type application/x-www-form-urlencoded + * + * @param string request url + * @param string method PUT, GET, POST etc. + * @param mixed params string (for urlencoded data, or array with name/value pairs) + * @param string body optional body for PUT and/or POST requests + */ + function __construct ( $request, $method = null, $params = null, $body = null ) + { + $this->store = OAuthStore::instance(); + + if (is_string($params)) + { + parent::__construct($request, $method, $params); + } + else + { + parent::__construct($request, $method); + if (is_array($params)) + { + foreach ($params as $name => $value) + { + $this->setParam($name, $value); + } + } + } + + // With put/ post we might have a body (not for application/x-www-form-urlencoded requests) + if (strcasecmp($method, 'PUT') == 0 || strcasecmp($method, 'POST') == 0) + { + $this->setBody($body); + } + } + + + /** + * Reset the 'signed' flag, so that any changes in the parameters force a recalculation + * of the signature. + */ + function setUnsigned () + { + $this->signed = false; + } + + + /** + * Sign our message in the way the server understands. + * Set the needed oauth_xxxx parameters. + * + * @param int usr_id (optional) user that wants to sign this request + * @param array secrets secrets used for signing, when empty then secrets will be fetched from the token registry + * @param string name name of the token to be used for signing + * @exception OAuthException2 when there is no oauth relation with the server + * @exception OAuthException2 when we don't support the signing methods of the server + */ + function sign ( $usr_id = 0, $secrets = null, $name = '', $token_type = null) + { + $url = $this->getRequestUrl(); + if (empty($secrets)) + { + // get the access tokens for the site (on an user by user basis) + $secrets = $this->store->getSecretsForSignature($url, $usr_id, $name); + } + if (empty($secrets)) + { + throw new OAuthException2('No OAuth relation with the server for at "'.$url.'"'); + } + + $signature_method = $this->selectSignatureMethod($secrets['signature_methods']); + + $token = isset($secrets['token']) ? $secrets['token'] : ''; + $token_secret = isset($secrets['token_secret']) ? $secrets['token_secret'] : ''; + + if (!$token) { + $token = $this->getParam('oauth_token'); + } + + $this->setParam('oauth_signature_method',$signature_method); + $this->setParam('oauth_signature', ''); + $this->setParam('oauth_nonce', !empty($secrets['nonce']) ? $secrets['nonce'] : uniqid('')); + $this->setParam('oauth_timestamp', !empty($secrets['timestamp']) ? $secrets['timestamp'] : time()); + if ($token_type != 'requestToken') + $this->setParam('oauth_token', $token); + $this->setParam('oauth_consumer_key', $secrets['consumer_key']); + $this->setParam('oauth_version', '1.0'); + + $body = $this->getBody(); + if (!is_null($body)) + { + // We also need to sign the body, use the default signature method + $body_signature = $this->calculateDataSignature($body, $secrets['consumer_secret'], $token_secret, $signature_method); + $this->setParam('xoauth_body_signature', $body_signature, true); + } + + $signature = $this->calculateSignature($secrets['consumer_secret'], $token_secret, $token_type); + $this->setParam('oauth_signature', $signature, true); + // $this->setParam('oauth_signature', urldecode($signature), true); + + $this->signed = true; + $this->usr_id = $usr_id; + } + + + /** + * Builds the Authorization header for the request. + * Adds all oauth_ and xoauth_ parameters to the Authorization header. + * + * @return string + */ + function getAuthorizationHeader () + { + if (!$this->signed) + { + $this->sign($this->usr_id); + } + $h = array(); + $h[] = 'Authorization: OAuth realm=""'; + foreach ($this->param as $name => $value) + { + if (strncmp($name, 'oauth_', 6) == 0 || strncmp($name, 'xoauth_', 7) == 0) + { + $h[] = $name.'="'.$value.'"'; + } + } + $hs = implode(', ', $h); + return $hs; + } + + + /** + * Builds the application/x-www-form-urlencoded parameter string. Can be appended as + * the query part to a GET or inside the request body for a POST. + * + * @param boolean oauth_as_header (optional) set to false to include oauth parameters + * @return string + */ + function getQueryString ( $oauth_as_header = true ) + { + $parms = array(); + foreach ($this->param as $name => $value) + { + if ( !$oauth_as_header + || (strncmp($name, 'oauth_', 6) != 0 && strncmp($name, 'xoauth_', 7) != 0)) + { + if (is_array($value)) + { + foreach ($value as $v) + { + $parms[] = $name.'='.$v; + } + } + else + { + $parms[] = $name.'='.$value; + } + } + } + return implode('&', $parms); + } + +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthRequestVerifier.php b/3rdparty/oauth-php/library/OAuthRequestVerifier.php new file mode 100644 index 0000000000..a5def757c6 --- /dev/null +++ b/3rdparty/oauth-php/library/OAuthRequestVerifier.php @@ -0,0 +1,306 @@ + + * @date Nov 16, 2007 4:35:03 PM + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__) . '/OAuthStore.php'; +require_once dirname(__FILE__) . '/OAuthRequest.php'; + + +class OAuthRequestVerifier extends OAuthRequest +{ + private $request; + private $store; + private $accepted_signatures = null; + + /** + * Construct the request to be verified + * + * @param string request + * @param string method + * @param array params The request parameters + */ + function __construct ( $uri = null, $method = null, $params = null ) + { + if ($params) { + $encodedParams = array(); + foreach ($params as $key => $value) { + if (preg_match("/^oauth_/", $key)) { + continue; + } + $encodedParams[rawurlencode($key)] = rawurlencode($value); + } + $this->param = array_merge($this->param, $encodedParams); + } + + $this->store = OAuthStore::instance(); + parent::__construct($uri, $method); + + OAuthRequestLogger::start($this); + } + + + /** + * See if the current request is signed with OAuth + * + * @return boolean + */ + static public function requestIsSigned () + { + if (isset($_REQUEST['oauth_signature'])) + { + $signed = true; + } + else + { + $hs = OAuthRequestLogger::getAllHeaders(); + if (isset($hs['Authorization']) && strpos($hs['Authorization'], 'oauth_signature') !== false) + { + $signed = true; + } + else + { + $signed = false; + } + } + return $signed; + } + + + /** + * Verify the request if it seemed to be signed. + * + * @param string token_type the kind of token needed, defaults to 'access' + * @exception OAuthException2 thrown when the request did not verify + * @return boolean true when signed, false when not signed + */ + public function verifyIfSigned ( $token_type = 'access' ) + { + if ($this->getParam('oauth_consumer_key')) + { + OAuthRequestLogger::start($this); + $this->verify($token_type); + $signed = true; + OAuthRequestLogger::flush(); + } + else + { + $signed = false; + } + return $signed; + } + + + + /** + * Verify the request + * + * @param string token_type the kind of token needed, defaults to 'access' (false, 'access', 'request') + * @exception OAuthException2 thrown when the request did not verify + * @return int user_id associated with token (false when no user associated) + */ + public function verify ( $token_type = 'access' ) + { + $retval = $this->verifyExtended($token_type); + return $retval['user_id']; + } + + + /** + * Verify the request + * + * @param string token_type the kind of token needed, defaults to 'access' (false, 'access', 'request') + * @exception OAuthException2 thrown when the request did not verify + * @return array ('user_id' => associated with token (false when no user associated), + * 'consumer_key' => the associated consumer_key) + * + */ + public function verifyExtended ( $token_type = 'access' ) + { + $consumer_key = $this->getParam('oauth_consumer_key'); + $token = $this->getParam('oauth_token'); + $user_id = false; + $secrets = array(); + + if ($consumer_key && ($token_type === false || $token)) + { + $secrets = $this->store->getSecretsForVerify( $this->urldecode($consumer_key), + $this->urldecode($token), + $token_type); + + $this->store->checkServerNonce( $this->urldecode($consumer_key), + $this->urldecode($token), + $this->getParam('oauth_timestamp', true), + $this->getParam('oauth_nonce', true)); + + $oauth_sig = $this->getParam('oauth_signature'); + if (empty($oauth_sig)) + { + throw new OAuthException2('Verification of signature failed (no oauth_signature in request).'); + } + + try + { + $this->verifySignature($secrets['consumer_secret'], $secrets['token_secret'], $token_type); + } + catch (OAuthException2 $e) + { + throw new OAuthException2('Verification of signature failed (signature base string was "'.$this->signatureBaseString().'").' + . " with " . print_r(array($secrets['consumer_secret'], $secrets['token_secret'], $token_type), true)); + } + + // Check the optional body signature + if ($this->getParam('xoauth_body_signature')) + { + $method = $this->getParam('xoauth_body_signature_method'); + if (empty($method)) + { + $method = $this->getParam('oauth_signature_method'); + } + + try + { + $this->verifyDataSignature($this->getBody(), $secrets['consumer_secret'], $secrets['token_secret'], $method, $this->getParam('xoauth_body_signature')); + } + catch (OAuthException2 $e) + { + throw new OAuthException2('Verification of body signature failed.'); + } + } + + // All ok - fetch the user associated with this request + if (isset($secrets['user_id'])) + { + $user_id = $secrets['user_id']; + } + + // Check if the consumer wants us to reset the ttl of this token + $ttl = $this->getParam('xoauth_token_ttl', true); + if (is_numeric($ttl)) + { + $this->store->setConsumerAccessTokenTtl($this->urldecode($token), $ttl); + } + } + else + { + throw new OAuthException2('Can\'t verify request, missing oauth_consumer_key or oauth_token'); + } + return array('user_id' => $user_id, 'consumer_key' => $consumer_key, 'osr_id' => $secrets['osr_id']); + } + + + + /** + * Verify the signature of the request, using the method in oauth_signature_method. + * The signature is returned encoded in the form as used in the url. So the base64 and + * urlencoding has been done. + * + * @param string consumer_secret + * @param string token_secret + * @exception OAuthException2 thrown when the signature method is unknown + * @exception OAuthException2 when not all parts available + * @exception OAuthException2 when signature does not match + */ + public function verifySignature ( $consumer_secret, $token_secret, $token_type = 'access' ) + { + $required = array( + 'oauth_consumer_key', + 'oauth_signature_method', + 'oauth_timestamp', + 'oauth_nonce', + 'oauth_signature' + ); + + if ($token_type !== false) + { + $required[] = 'oauth_token'; + } + + foreach ($required as $req) + { + if (!isset($this->param[$req])) + { + throw new OAuthException2('Can\'t verify request signature, missing parameter "'.$req.'"'); + } + } + + $this->checks(); + + $base = $this->signatureBaseString(); + $this->verifyDataSignature($base, $consumer_secret, $token_secret, $this->param['oauth_signature_method'], $this->param['oauth_signature']); + } + + + + /** + * Verify the signature of a string. + * + * @param string data + * @param string consumer_secret + * @param string token_secret + * @param string signature_method + * @param string signature + * @exception OAuthException2 thrown when the signature method is unknown + * @exception OAuthException2 when signature does not match + */ + public function verifyDataSignature ( $data, $consumer_secret, $token_secret, $signature_method, $signature ) + { + if (is_null($data)) + { + $data = ''; + } + + $sig = $this->getSignatureMethod($signature_method); + if (!$sig->verify($this, $data, $consumer_secret, $token_secret, $signature)) + { + throw new OAuthException2('Signature verification failed ('.$signature_method.')'); + } + } + + /** + * + * @param array $accepted The array of accepted signature methods, or if null is passed + * all supported methods are accepted and there is no filtering. + * + */ + public function setAcceptedSignatureMethods($accepted = null) { + if (is_array($accepted)) + $this->accepted_signatures = $accepted; + else if ($accepted == null) + $this->accepted_signatures = null; + } +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthRequester.php b/3rdparty/oauth-php/library/OAuthRequester.php new file mode 100644 index 0000000000..98f720d220 --- /dev/null +++ b/3rdparty/oauth-php/library/OAuthRequester.php @@ -0,0 +1,521 @@ + + * @date Nov 20, 2007 1:41:38 PM + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__) . '/OAuthRequestSigner.php'; +require_once dirname(__FILE__) . '/body/OAuthBodyContentDisposition.php'; + + +class OAuthRequester extends OAuthRequestSigner +{ + protected $files; + + /** + * Construct a new request signer. Perform the request with the doRequest() method below. + * + * A request can have either one file or a body, not both. + * + * The files array consists of arrays: + * - file the filename/path containing the data for the POST/PUT + * - data data for the file, omit when you have a file + * - mime content-type of the file + * - filename filename for content disposition header + * + * When OAuth (and PHP) can support multipart/form-data then we can handle more than one file. + * For now max one file, with all the params encoded in the query string. + * + * @param string request + * @param string method http method. GET, PUT, POST etc. + * @param array params name=>value array with request parameters + * @param string body optional body to send + * @param array files optional files to send (max 1 till OAuth support multipart/form-data posts) + */ + function __construct ( $request, $method = null, $params = null, $body = null, $files = null ) + { + parent::__construct($request, $method, $params, $body); + + // When there are files, then we can construct a POST with a single file + if (!empty($files)) + { + $empty = true; + foreach ($files as $f) + { + $empty = $empty && empty($f['file']) && !isset($f['data']); + } + + if (!$empty) + { + if (!is_null($body)) + { + throw new OAuthException2('When sending files, you can\'t send a body as well.'); + } + $this->files = $files; + } + } + } + + + /** + * Perform the request, returns the response code, headers and body. + * + * @param int usr_id optional user id for which we make the request + * @param array curl_options optional extra options for curl request + * @param array options options like name and token_ttl + * @exception OAuthException2 when authentication not accepted + * @exception OAuthException2 when signing was not possible + * @return array (code=>int, headers=>array(), body=>string) + */ + function doRequest ( $usr_id = 0, $curl_options = array(), $options = array() ) + { + $name = isset($options['name']) ? $options['name'] : ''; + if (isset($options['token_ttl'])) + { + $this->setParam('xoauth_token_ttl', intval($options['token_ttl'])); + } + + if (!empty($this->files)) + { + // At the moment OAuth does not support multipart/form-data, so try to encode + // the supplied file (or data) as the request body and add a content-disposition header. + list($extra_headers, $body) = OAuthBodyContentDisposition::encodeBody($this->files); + $this->setBody($body); + $curl_options = $this->prepareCurlOptions($curl_options, $extra_headers); + } + $this->sign($usr_id, null, $name); + $text = $this->curl_raw($curl_options); + $result = $this->curl_parse($text); + if ($result['code'] >= 400) + { + throw new OAuthException2('Request failed with code ' . $result['code'] . ': ' . $result['body']); + } + + // Record the token time to live for this server access token, immediate delete iff ttl <= 0 + // Only done on a succesful request. + $token_ttl = $this->getParam('xoauth_token_ttl', false); + if (is_numeric($token_ttl)) + { + $this->store->setServerTokenTtl($this->getParam('oauth_consumer_key',true), $this->getParam('oauth_token',true), $token_ttl); + } + + return $result; + } + + + /** + * Request a request token from the site belonging to consumer_key + * + * @param string consumer_key + * @param int usr_id + * @param array params (optional) extra arguments for when requesting the request token + * @param string method (optional) change the method of the request, defaults to POST (as it should be) + * @param array options (optional) options like name and token_ttl + * @param array curl_options optional extra options for curl request + * @exception OAuthException2 when no key could be fetched + * @exception OAuthException2 when no server with consumer_key registered + * @return array (authorize_uri, token) + */ + static function requestRequestToken ( $consumer_key, $usr_id, $params = null, $method = 'POST', $options = array(), $curl_options = array()) + { + OAuthRequestLogger::start(); + + if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) + { + $params['xoauth_token_ttl'] = intval($options['token_ttl']); + } + + $store = OAuthStore::instance(); + $r = $store->getServer($consumer_key, $usr_id); + $uri = $r['request_token_uri']; + + $oauth = new OAuthRequester($uri, $method, $params); + $oauth->sign($usr_id, $r, '', 'requestToken'); + $text = $oauth->curl_raw($curl_options); + + if (empty($text)) + { + throw new OAuthException2('No answer from the server "'.$uri.'" while requesting a request token'); + } + $data = $oauth->curl_parse($text); + if ($data['code'] != 200) + { + throw new OAuthException2('Unexpected result from the server "'.$uri.'" ('.$data['code'].') while requesting a request token'); + } + $token = array(); + $params = explode('&', $data['body']); + foreach ($params as $p) + { + @list($name, $value) = explode('=', $p, 2); + $token[$name] = $oauth->urldecode($value); + } + + if (!empty($token['oauth_token']) && !empty($token['oauth_token_secret'])) + { + $opts = array(); + if (isset($options['name'])) + { + $opts['name'] = $options['name']; + } + if (isset($token['xoauth_token_ttl'])) + { + $opts['token_ttl'] = $token['xoauth_token_ttl']; + } + $store->addServerToken($consumer_key, 'request', $token['oauth_token'], $token['oauth_token_secret'], $usr_id, $opts); + } + else + { + throw new OAuthException2('The server "'.$uri.'" did not return the oauth_token or the oauth_token_secret'); + } + + OAuthRequestLogger::flush(); + + // Now we can direct a browser to the authorize_uri + return array( + 'authorize_uri' => $r['authorize_uri'], + 'token' => $token['oauth_token'] + ); + } + + + /** + * Request an access token from the site belonging to consumer_key. + * Before this we got an request token, now we want to exchange it for + * an access token. + * + * @param string consumer_key + * @param string token + * @param int usr_id user requesting the access token + * @param string method (optional) change the method of the request, defaults to POST (as it should be) + * @param array options (optional) extra options for request, eg token_ttl + * @param array curl_options optional extra options for curl request + * + * @exception OAuthException2 when no key could be fetched + * @exception OAuthException2 when no server with consumer_key registered + */ + static function requestAccessToken ( $consumer_key, $token, $usr_id, $method = 'POST', $options = array(), $curl_options = array() ) + { + OAuthRequestLogger::start(); + + $store = OAuthStore::instance(); + $r = $store->getServerTokenSecrets($consumer_key, $token, 'request', $usr_id); + $uri = $r['access_token_uri']; + $token_name = $r['token_name']; + + // Delete the server request token, this one was for one use only + $store->deleteServerToken($consumer_key, $r['token'], 0, true); + + // Try to exchange our request token for an access token + $oauth = new OAuthRequester($uri, $method); + + if (isset($options['oauth_verifier'])) + { + $oauth->setParam('oauth_verifier', $options['oauth_verifier']); + } + if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) + { + $oauth->setParam('xoauth_token_ttl', intval($options['token_ttl'])); + } + + OAuthRequestLogger::setRequestObject($oauth); + + $oauth->sign($usr_id, $r, '', 'accessToken'); + $text = $oauth->curl_raw($curl_options); + if (empty($text)) + { + throw new OAuthException2('No answer from the server "'.$uri.'" while requesting an access token'); + } + $data = $oauth->curl_parse($text); + + if ($data['code'] != 200) + { + throw new OAuthException2('Unexpected result from the server "'.$uri.'" ('.$data['code'].') while requesting an access token'); + } + + $token = array(); + $params = explode('&', $data['body']); + foreach ($params as $p) + { + @list($name, $value) = explode('=', $p, 2); + $token[$oauth->urldecode($name)] = $oauth->urldecode($value); + } + + if (!empty($token['oauth_token']) && !empty($token['oauth_token_secret'])) + { + $opts = array(); + $opts['name'] = $token_name; + if (isset($token['xoauth_token_ttl'])) + { + $opts['token_ttl'] = $token['xoauth_token_ttl']; + } + $store->addServerToken($consumer_key, 'access', $token['oauth_token'], $token['oauth_token_secret'], $usr_id, $opts); + } + else + { + throw new OAuthException2('The server "'.$uri.'" did not return the oauth_token or the oauth_token_secret'); + } + + OAuthRequestLogger::flush(); + } + + + + /** + * Open and close a curl session passing all the options to the curl libs + * + * @param array opts the curl options. + * @exception OAuthException2 when temporary file for PUT operation could not be created + * @return string the result of the curl action + */ + protected function curl_raw ( $opts = array() ) + { + if (isset($opts[CURLOPT_HTTPHEADER])) + { + $header = $opts[CURLOPT_HTTPHEADER]; + } + else + { + $header = array(); + } + + $ch = curl_init(); + $method = $this->getMethod(); + $url = $this->getRequestUrl(); + $header[] = $this->getAuthorizationHeader(); + $query = $this->getQueryString(); + $body = $this->getBody(); + + $has_content_type = false; + foreach ($header as $h) + { + if (strncasecmp($h, 'Content-Type:', 13) == 0) + { + $has_content_type = true; + } + } + + if (!is_null($body)) + { + if ($method == 'TRACE') + { + throw new OAuthException2('A body can not be sent with a TRACE operation'); + } + + // PUT and POST allow a request body + if (!empty($query)) + { + $url .= '?'.$query; + } + + // Make sure that the content type of the request is ok + if (!$has_content_type) + { + $header[] = 'Content-Type: application/octet-stream'; + $has_content_type = true; + } + + // When PUTting, we need to use an intermediate file (because of the curl implementation) + if ($method == 'PUT') + { + /* + if (version_compare(phpversion(), '5.2.0') >= 0) + { + // Use the data wrapper to create the file expected by the put method + $put_file = fopen('data://application/octet-stream;base64,'.base64_encode($body)); + } + */ + + $put_file = @tmpfile(); + if (!$put_file) + { + throw new OAuthException2('Could not create tmpfile for PUT operation'); + } + fwrite($put_file, $body); + fseek($put_file, 0); + + curl_setopt($ch, CURLOPT_PUT, true); + curl_setopt($ch, CURLOPT_INFILE, $put_file); + curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body)); + } + else + { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $body); + } + } + else + { + // a 'normal' request, no body to be send + if ($method == 'POST') + { + if (!$has_content_type) + { + $header[] = 'Content-Type: application/x-www-form-urlencoded'; + $has_content_type = true; + } + + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $query); + } + else + { + if (!empty($query)) + { + $url .= '?'.$query; + } + if ($method != 'GET') + { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); + } + } + } + + curl_setopt($ch, CURLOPT_HTTPHEADER, $header); + curl_setopt($ch, CURLOPT_USERAGENT, 'anyMeta/OAuth 1.0 - ($LastChangedRevision: 174 $)'); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_HEADER, true); + curl_setopt($ch, CURLOPT_TIMEOUT, 30); + + foreach ($opts as $k => $v) + { + if ($k != CURLOPT_HTTPHEADER) + { + curl_setopt($ch, $k, $v); + } + } + + $txt = curl_exec($ch); + if ($txt === false) { + $error = curl_error($ch); + curl_close($ch); + throw new OAuthException2('CURL error: ' . $error); + } + curl_close($ch); + + if (!empty($put_file)) + { + fclose($put_file); + } + + // Tell the logger what we requested and what we received back + $data = $method . " $url\n".implode("\n",$header); + if (is_string($body)) + { + $data .= "\n\n".$body; + } + else if ($method == 'POST') + { + $data .= "\n\n".$query; + } + + OAuthRequestLogger::setSent($data, $body); + OAuthRequestLogger::setReceived($txt); + + return $txt; + } + + + /** + * Parse an http response + * + * @param string response the http text to parse + * @return array (code=>http-code, headers=>http-headers, body=>body) + */ + protected function curl_parse ( $response ) + { + if (empty($response)) + { + return array(); + } + + @list($headers,$body) = explode("\r\n\r\n",$response,2); + $lines = explode("\r\n",$headers); + + if (preg_match('@^HTTP/[0-9]\.[0-9] +100@', $lines[0])) + { + /* HTTP/1.x 100 Continue + * the real data is on the next line + */ + @list($headers,$body) = explode("\r\n\r\n",$body,2); + $lines = explode("\r\n",$headers); + } + + // first line of headers is the HTTP response code + $http_line = array_shift($lines); + if (preg_match('@^HTTP/[0-9]\.[0-9] +([0-9]{3})@', $http_line, $matches)) + { + $code = $matches[1]; + } + + // put the rest of the headers in an array + $headers = array(); + foreach ($lines as $l) + { + list($k, $v) = explode(': ', $l, 2); + $headers[strtolower($k)] = $v; + } + + return array( 'code' => $code, 'headers' => $headers, 'body' => $body); + } + + + /** + * Mix the given headers into the headers that were given to curl + * + * @param array curl_options + * @param array extra_headers + * @return array new curl options + */ + protected function prepareCurlOptions ( $curl_options, $extra_headers ) + { + $hs = array(); + if (!empty($curl_options[CURLOPT_HTTPHEADER]) && is_array($curl_options[CURLOPT_HTTPHEADER])) + { + foreach ($curl_options[CURLOPT_HTTPHEADER] as $h) + { + list($opt, $val) = explode(':', $h, 2); + $opt = str_replace(' ', '-', ucwords(str_replace('-', ' ', $opt))); + $hs[$opt] = $val; + } + } + + $curl_options[CURLOPT_HTTPHEADER] = array(); + $hs = array_merge($hs, $extra_headers); + foreach ($hs as $h => $v) + { + $curl_options[CURLOPT_HTTPHEADER][] = "$h: $v"; + } + return $curl_options; + } +} + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthServer.php b/3rdparty/oauth-php/library/OAuthServer.php new file mode 100644 index 0000000000..995ebc5ca0 --- /dev/null +++ b/3rdparty/oauth-php/library/OAuthServer.php @@ -0,0 +1,333 @@ + + * @date Nov 27, 2007 12:36:38 PM + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once 'OAuthRequestVerifier.php'; +require_once 'OAuthSession.php'; + +class OAuthServer extends OAuthRequestVerifier +{ + protected $session; + + protected $allowed_uri_schemes = array( + 'http', + 'https' + ); + + protected $disallowed_uri_schemes = array( + 'file', + 'callto', + 'mailto' + ); + + /** + * Construct the request to be verified + * + * @param string request + * @param string method + * @param array params The request parameters + * @param string store The session storage class. + * @param array store_options The session storage class parameters. + * @param array options Extra options: + * - allowed_uri_schemes: list of allowed uri schemes. + * - disallowed_uri_schemes: list of unallowed uri schemes. + * + * e.g. Allow only http and https + * $options = array( + * 'allowed_uri_schemes' => array('http', 'https'), + * 'disallowed_uri_schemes' => array() + * ); + * + * e.g. Disallow callto, mailto and file, allow everything else + * $options = array( + * 'allowed_uri_schemes' => array(), + * 'disallowed_uri_schemes' => array('callto', 'mailto', 'file') + * ); + * + * e.g. Allow everything + * $options = array( + * 'allowed_uri_schemes' => array(), + * 'disallowed_uri_schemes' => array() + * ); + * + */ + function __construct ( $uri = null, $method = null, $params = null, $store = 'SESSION', + $store_options = array(), $options = array() ) + { + parent::__construct($uri, $method, $params); + $this->session = OAuthSession::instance($store, $store_options); + + if (array_key_exists('allowed_uri_schemes', $options) && is_array($options['allowed_uri_schemes'])) { + $this->allowed_uri_schemes = $options['allowed_uri_schemes']; + } + if (array_key_exists('disallowed_uri_schemes', $options) && is_array($options['disallowed_uri_schemes'])) { + $this->disallowed_uri_schemes = $options['disallowed_uri_schemes']; + } + } + + /** + * Handle the request_token request. + * Returns the new request token and request token secret. + * + * TODO: add correct result code to exception + * + * @return string returned request token, false on an error + */ + public function requestToken () + { + OAuthRequestLogger::start($this); + try + { + $this->verify(false); + + $options = array(); + $ttl = $this->getParam('xoauth_token_ttl', false); + if ($ttl) + { + $options['token_ttl'] = $ttl; + } + + // 1.0a Compatibility : associate callback url to the request token + $cbUrl = $this->getParam('oauth_callback', true); + if ($cbUrl) { + $options['oauth_callback'] = $cbUrl; + } + + // Create a request token + $store = OAuthStore::instance(); + $token = $store->addConsumerRequestToken($this->getParam('oauth_consumer_key', true), $options); + $result = 'oauth_callback_confirmed=1&oauth_token='.$this->urlencode($token['token']) + .'&oauth_token_secret='.$this->urlencode($token['token_secret']); + + if (!empty($token['token_ttl'])) + { + $result .= '&xoauth_token_ttl='.$this->urlencode($token['token_ttl']); + } + + $request_token = $token['token']; + + header('HTTP/1.1 200 OK'); + header('Content-Length: '.strlen($result)); + header('Content-Type: application/x-www-form-urlencoded'); + + echo $result; + } + catch (OAuthException2 $e) + { + $request_token = false; + + header('HTTP/1.1 401 Unauthorized'); + header('Content-Type: text/plain'); + + echo "OAuth Verification Failed: " . $e->getMessage(); + } + + OAuthRequestLogger::flush(); + return $request_token; + } + + + /** + * Verify the start of an authorization request. Verifies if the request token is valid. + * Next step is the method authorizeFinish() + * + * Nota bene: this stores the current token, consumer key and callback in the _SESSION + * + * @exception OAuthException2 thrown when not a valid request + * @return array token description + */ + public function authorizeVerify () + { + OAuthRequestLogger::start($this); + + $store = OAuthStore::instance(); + $token = $this->getParam('oauth_token', true); + $rs = $store->getConsumerRequestToken($token); + if (empty($rs)) + { + throw new OAuthException2('Unknown request token "'.$token.'"'); + } + + // We need to remember the callback + $verify_oauth_token = $this->session->get('verify_oauth_token'); + if ( empty($verify_oauth_token) + || strcmp($verify_oauth_token, $rs['token'])) + { + $this->session->set('verify_oauth_token', $rs['token']); + $this->session->set('verify_oauth_consumer_key', $rs['consumer_key']); + $cb = $this->getParam('oauth_callback', true); + if ($cb) + $this->session->set('verify_oauth_callback', $cb); + else + $this->session->set('verify_oauth_callback', $rs['callback_url']); + } + OAuthRequestLogger::flush(); + return $rs; + } + + + /** + * Overrule this method when you want to display a nice page when + * the authorization is finished. This function does not know if the authorization was + * succesfull, you need to check the token in the database. + * + * @param boolean authorized if the current token (oauth_token param) is authorized or not + * @param int user_id user for which the token was authorized (or denied) + * @return string verifier For 1.0a Compatibility + */ + public function authorizeFinish ( $authorized, $user_id ) + { + OAuthRequestLogger::start($this); + + $token = $this->getParam('oauth_token', true); + $verifier = null; + if ($this->session->get('verify_oauth_token') == $token) + { + // Flag the token as authorized, or remove the token when not authorized + $store = OAuthStore::instance(); + + // Fetch the referrer host from the oauth callback parameter + $referrer_host = ''; + $oauth_callback = false; + $verify_oauth_callback = $this->session->get('verify_oauth_callback'); + if (!empty($verify_oauth_callback) && $verify_oauth_callback != 'oob') // OUT OF BAND + { + $oauth_callback = $this->session->get('verify_oauth_callback'); + $ps = parse_url($oauth_callback); + if (isset($ps['host'])) + { + $referrer_host = $ps['host']; + } + } + + if ($authorized) + { + OAuthRequestLogger::addNote('Authorized token "'.$token.'" for user '.$user_id.' with referrer "'.$referrer_host.'"'); + // 1.0a Compatibility : create a verifier code + $verifier = $store->authorizeConsumerRequestToken($token, $user_id, $referrer_host); + } + else + { + OAuthRequestLogger::addNote('Authorization rejected for token "'.$token.'" for user '.$user_id."\nToken has been deleted"); + $store->deleteConsumerRequestToken($token); + } + + if (!empty($oauth_callback)) + { + $params = array('oauth_token' => rawurlencode($token)); + // 1.0a Compatibility : if verifier code has been generated, add it to the URL + if ($verifier) { + $params['oauth_verifier'] = $verifier; + } + + $uri = preg_replace('/\s/', '%20', $oauth_callback); + if (!empty($this->allowed_uri_schemes)) + { + if (!in_array(substr($uri, 0, strpos($uri, '://')), $this->allowed_uri_schemes)) + { + throw new OAuthException2('Illegal protocol in redirect uri '.$uri); + } + } + else if (!empty($this->disallowed_uri_schemes)) + { + if (in_array(substr($uri, 0, strpos($uri, '://')), $this->disallowed_uri_schemes)) + { + throw new OAuthException2('Illegal protocol in redirect uri '.$uri); + } + } + + $this->redirect($oauth_callback, $params); + } + } + OAuthRequestLogger::flush(); + return $verifier; + } + + + /** + * Exchange a request token for an access token. + * The exchange is only succesful iff the request token has been authorized. + * + * Never returns, calls exit() when token is exchanged or when error is returned. + */ + public function accessToken () + { + OAuthRequestLogger::start($this); + + try + { + $this->verify('request'); + + $options = array(); + $ttl = $this->getParam('xoauth_token_ttl', false); + if ($ttl) + { + $options['token_ttl'] = $ttl; + } + + $verifier = $this->getParam('oauth_verifier', false); + if ($verifier) { + $options['verifier'] = $verifier; + } + + $store = OAuthStore::instance(); + $token = $store->exchangeConsumerRequestForAccessToken($this->getParam('oauth_token', true), $options); + $result = 'oauth_token='.$this->urlencode($token['token']) + .'&oauth_token_secret='.$this->urlencode($token['token_secret']); + + if (!empty($token['token_ttl'])) + { + $result .= '&xoauth_token_ttl='.$this->urlencode($token['token_ttl']); + } + + header('HTTP/1.1 200 OK'); + header('Content-Length: '.strlen($result)); + header('Content-Type: application/x-www-form-urlencoded'); + + echo $result; + } + catch (OAuthException2 $e) + { + header('HTTP/1.1 401 Access Denied'); + header('Content-Type: text/plain'); + + echo "OAuth Verification Failed: " . $e->getMessage(); + } + + OAuthRequestLogger::flush(); + exit(); + } +} + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthSession.php b/3rdparty/oauth-php/library/OAuthSession.php new file mode 100644 index 0000000000..80ceeb7346 --- /dev/null +++ b/3rdparty/oauth-php/library/OAuthSession.php @@ -0,0 +1,86 @@ + \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthStore.php b/3rdparty/oauth-php/library/OAuthStore.php new file mode 100644 index 0000000000..d3df3a0ae0 --- /dev/null +++ b/3rdparty/oauth-php/library/OAuthStore.php @@ -0,0 +1,86 @@ + + * @date Nov 16, 2007 4:03:30 PM + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__) . '/OAuthException2.php'; + +class OAuthStore +{ + static private $instance = false; + + /** + * Request an instance of the OAuthStore + */ + public static function instance ( $store = 'MySQL', $options = array() ) + { + if (!OAuthStore::$instance) + { + // Select the store you want to use + if (strpos($store, '/') === false) + { + $class = 'OAuthStore'.$store; + $file = dirname(__FILE__) . '/store/'.$class.'.php'; + } + else + { + $file = $store; + $store = basename($file, '.php'); + $class = $store; + } + + if (is_file($file)) + { + require_once $file; + + if (class_exists($class)) + { + OAuthStore::$instance = new $class($options); + } + else + { + throw new OAuthException2('Could not find class '.$class.' in file '.$file); + } + } + else + { + throw new OAuthException2('No OAuthStore for '.$store.' (file '.$file.')'); + } + } + return OAuthStore::$instance; + } +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/body/OAuthBodyContentDisposition.php b/3rdparty/oauth-php/library/body/OAuthBodyContentDisposition.php new file mode 100644 index 0000000000..02b1e42779 --- /dev/null +++ b/3rdparty/oauth-php/library/body/OAuthBodyContentDisposition.php @@ -0,0 +1,129 @@ + + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +class OAuthBodyContentDisposition +{ + /** + * Builds the request string. + * + * The files array can be a combination of the following (either data or file): + * + * file => "path/to/file", filename=, mime=, data= + * + * @param array files (name => filedesc) (not urlencoded) + * @return array (headers, body) + */ + static function encodeBody ( $files ) + { + $headers = array(); + $body = null; + + // 1. Add all the files to the post + if (!empty($files)) + { + foreach ($files as $name => $f) + { + $data = false; + $filename = false; + + if (isset($f['filename'])) + { + $filename = $f['filename']; + } + + if (!empty($f['file'])) + { + $data = @file_get_contents($f['file']); + if ($data === false) + { + throw new OAuthException2(sprintf('Could not read the file "%s" for request body', $f['file'])); + } + if (empty($filename)) + { + $filename = basename($f['file']); + } + } + else if (isset($f['data'])) + { + $data = $f['data']; + } + + // When there is data, add it as a request body, otherwise silently skip the upload + if ($data !== false) + { + if (isset($headers['Content-Disposition'])) + { + throw new OAuthException2('Only a single file (or data) allowed in a signed PUT/POST request body.'); + } + + if (empty($filename)) + { + $filename = 'untitled'; + } + $mime = !empty($f['mime']) ? $f['mime'] : 'application/octet-stream'; + + $headers['Content-Disposition'] = 'attachment; filename="'.OAuthBodyContentDisposition::encodeParameterName($filename).'"'; + $headers['Content-Type'] = $mime; + + $body = $data; + } + + } + + // When we have a body, add the content-length + if (!is_null($body)) + { + $headers['Content-Length'] = strlen($body); + } + } + return array($headers, $body); + } + + + /** + * Encode a parameter's name for use in a multipart header. + * For now we do a simple filter that removes some unwanted characters. + * We might want to implement RFC1522 here. See http://tools.ietf.org/html/rfc1522 + * + * @param string name + * @return string + */ + static function encodeParameterName ( $name ) + { + return preg_replace('/[^\x20-\x7f]|"/', '-', $name); + } +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/body/OAuthBodyMultipartFormdata.php b/3rdparty/oauth-php/library/body/OAuthBodyMultipartFormdata.php new file mode 100644 index 0000000000..a869e1e6d7 --- /dev/null +++ b/3rdparty/oauth-php/library/body/OAuthBodyMultipartFormdata.php @@ -0,0 +1,143 @@ + + * @date Jan 31, 2008 12:50:05 PM + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + +class OAuthBodyMultipartFormdata +{ + /** + * Builds the request string. + * + * The files array can be a combination of the following (either data or file): + * + * file => "path/to/file", filename=, mime=, data= + * + * @param array params (name => value) (all names and values should be urlencoded) + * @param array files (name => filedesc) (not urlencoded) + * @return array (headers, body) + */ + static function encodeBody ( $params, $files ) + { + $headers = array(); + $body = ''; + $boundary = 'OAuthRequester_'.md5(uniqid('multipart') . microtime()); + $headers['Content-Type'] = 'multipart/form-data; boundary=' . $boundary; + + + // 1. Add the parameters to the post + if (!empty($params)) + { + foreach ($params as $name => $value) + { + $body .= '--'.$boundary."\r\n"; + $body .= 'Content-Disposition: form-data; name="'.OAuthBodyMultipartFormdata::encodeParameterName(rawurldecode($name)).'"'; + $body .= "\r\n\r\n"; + $body .= urldecode($value); + $body .= "\r\n"; + } + } + + // 2. Add all the files to the post + if (!empty($files)) + { + $untitled = 1; + + foreach ($files as $name => $f) + { + $data = false; + $filename = false; + + if (isset($f['filename'])) + { + $filename = $f['filename']; + } + + if (!empty($f['file'])) + { + $data = @file_get_contents($f['file']); + if ($data === false) + { + throw new OAuthException2(sprintf('Could not read the file "%s" for form-data part', $f['file'])); + } + if (empty($filename)) + { + $filename = basename($f['file']); + } + } + else if (isset($f['data'])) + { + $data = $f['data']; + } + + // When there is data, add it as a form-data part, otherwise silently skip the upload + if ($data !== false) + { + if (empty($filename)) + { + $filename = sprintf('untitled-%d', $untitled++); + } + $mime = !empty($f['mime']) ? $f['mime'] : 'application/octet-stream'; + $body .= '--'.$boundary."\r\n"; + $body .= 'Content-Disposition: form-data; name="'.OAuthBodyMultipartFormdata::encodeParameterName($name).'"; filename="'.OAuthBodyMultipartFormdata::encodeParameterName($filename).'"'."\r\n"; + $body .= 'Content-Type: '.$mime; + $body .= "\r\n\r\n"; + $body .= $data; + $body .= "\r\n"; + } + + } + } + $body .= '--'.$boundary."--\r\n"; + + $headers['Content-Length'] = strlen($body); + return array($headers, $body); + } + + + /** + * Encode a parameter's name for use in a multipart header. + * For now we do a simple filter that removes some unwanted characters. + * We might want to implement RFC1522 here. See http://tools.ietf.org/html/rfc1522 + * + * @param string name + * @return string + */ + static function encodeParameterName ( $name ) + { + return preg_replace('/[^\x20-\x7f]|"/', '-', $name); + } +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/discovery/xrds_parse.php b/3rdparty/oauth-php/library/discovery/xrds_parse.php new file mode 100644 index 0000000000..c9cf94997d --- /dev/null +++ b/3rdparty/oauth-php/library/discovery/xrds_parse.php @@ -0,0 +1,304 @@ + + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/* example of use: + +header('content-type: text/plain'); +$file = file_get_contents('../../test/discovery/xrds-magnolia.xrds'); +$xrds = xrds_parse($file); +print_r($xrds); + + */ + +/** + * Parse the xrds file in the argument. The xrds description must have been + * fetched via curl or something else. + * + * TODO: more robust checking, support for more service documents + * TODO: support for URIs to definition instead of local xml:id + * + * @param string data contents of xrds file + * @exception Exception when the file is in an unknown format + * @return array + */ +function xrds_parse ( $data ) +{ + $oauth = array(); + $doc = @DOMDocument::loadXML($data); + if ($doc === false) + { + throw new Exception('Error in XML, can\'t load XRDS document'); + } + + $xpath = new DOMXPath($doc); + $xpath->registerNamespace('xrds', 'xri://$xrds'); + $xpath->registerNamespace('xrd', 'xri://$XRD*($v*2.0)'); + $xpath->registerNamespace('simple', 'http://xrds-simple.net/core/1.0'); + + // Yahoo! uses this namespace, with lowercase xrd in it + $xpath->registerNamespace('xrd2', 'xri://$xrd*($v*2.0)'); + + $uris = xrds_oauth_service_uris($xpath); + + foreach ($uris as $uri) + { + // TODO: support uris referring to service documents outside this one + if ($uri{0} == '#') + { + $id = substr($uri, 1); + $oauth = xrds_xrd_oauth($xpath, $id); + if (is_array($oauth) && !empty($oauth)) + { + return $oauth; + } + } + } + + return false; +} + + +/** + * Parse a XRD definition for OAuth and return the uris etc. + * + * @param XPath xpath + * @param string id + * @return array + */ +function xrds_xrd_oauth ( $xpath, $id ) +{ + $oauth = array(); + $xrd = $xpath->query('//xrds:XRDS/xrd:XRD[@xml:id="'.$id.'"]'); + if ($xrd->length == 0) + { + // Yahoo! uses another namespace + $xrd = $xpath->query('//xrds:XRDS/xrd2:XRD[@xml:id="'.$id.'"]'); + } + + if ($xrd->length >= 1) + { + $x = $xrd->item(0); + $services = array(); + foreach ($x->childNodes as $n) + { + switch ($n->nodeName) + { + case 'Type': + if ($n->nodeValue != 'xri://$xrds*simple') + { + // Not a simple XRDS document + return false; + } + break; + case 'Expires': + $oauth['expires'] = $n->nodeValue; + break; + case 'Service': + list($type,$service) = xrds_xrd_oauth_service($n); + if ($type) + { + $services[$type][xrds_priority($n)][] = $service; + } + break; + } + } + + // Flatten the services on priority + foreach ($services as $type => $service) + { + $oauth[$type] = xrds_priority_flatten($service); + } + } + else + { + $oauth = false; + } + return $oauth; +} + + +/** + * Parse a service definition for OAuth in a simple xrd element + * + * @param DOMElement n + * @return array (type, service desc) + */ +function xrds_xrd_oauth_service ( $n ) +{ + $service = array( + 'uri' => '', + 'signature_method' => array(), + 'parameters' => array() + ); + + $type = false; + foreach ($n->childNodes as $c) + { + $name = $c->nodeName; + $value = $c->nodeValue; + + if ($name == 'URI') + { + $service['uri'] = $value; + } + else if ($name == 'Type') + { + if (strncmp($value, 'http://oauth.net/core/1.0/endpoint/', 35) == 0) + { + $type = basename($value); + } + else if (strncmp($value, 'http://oauth.net/core/1.0/signature/', 36) == 0) + { + $service['signature_method'][] = basename($value); + } + else if (strncmp($value, 'http://oauth.net/core/1.0/parameters/', 37) == 0) + { + $service['parameters'][] = basename($value); + } + else if (strncmp($value, 'http://oauth.net/discovery/1.0/consumer-identity/', 49) == 0) + { + $type = 'consumer_identity'; + $service['method'] = basename($value); + unset($service['signature_method']); + unset($service['parameters']); + } + else + { + $service['unknown'][] = $value; + } + } + else if ($name == 'LocalID') + { + $service['consumer_key'] = $value; + } + else if ($name{0} != '#') + { + $service[strtolower($name)] = $value; + } + } + return array($type, $service); +} + + +/** + * Return the OAuth service uris in order of the priority. + * + * @param XPath xpath + * @return array + */ +function xrds_oauth_service_uris ( $xpath ) +{ + $uris = array(); + $xrd_oauth = $xpath->query('//xrds:XRDS/xrd:XRD/xrd:Service/xrd:Type[.=\'http://oauth.net/discovery/1.0\']'); + if ($xrd_oauth->length > 0) + { + $service = array(); + foreach ($xrd_oauth as $xo) + { + // Find the URI of the service definition + $cs = $xo->parentNode->childNodes; + foreach ($cs as $c) + { + if ($c->nodeName == 'URI') + { + $prio = xrds_priority($xo); + $service[$prio][] = $c->nodeValue; + } + } + } + $uris = xrds_priority_flatten($service); + } + return $uris; +} + + + +/** + * Flatten an array according to the priority + * + * @param array ps buckets per prio + * @return array one dimensional array + */ +function xrds_priority_flatten ( $ps ) +{ + $prio = array(); + $null = array(); + ksort($ps); + foreach ($ps as $idx => $bucket) + { + if (!empty($bucket)) + { + if ($idx == 'null') + { + $null = $bucket; + } + else + { + $prio = array_merge($prio, $bucket); + } + } + } + $prio = array_merge($prio, $bucket); + return $prio; +} + + +/** + * Fetch the priority of a element + * + * @param DOMElement elt + * @return mixed 'null' or int + */ +function xrds_priority ( $elt ) +{ + if ($elt->hasAttribute('priority')) + { + $prio = $elt->getAttribute('priority'); + if (is_numeric($prio)) + { + $prio = intval($prio); + } + } + else + { + $prio = 'null'; + } + return $prio; +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/discovery/xrds_parse.txt b/3rdparty/oauth-php/library/discovery/xrds_parse.txt new file mode 100644 index 0000000000..fd867ea9fb --- /dev/null +++ b/3rdparty/oauth-php/library/discovery/xrds_parse.txt @@ -0,0 +1,101 @@ +The xrds_parse.php script contains the function: + + function xrds_parse ( $data. ) + +$data Contains the contents of a XRDS XML file. +When the data is invalid XML then this will throw an exception. + +After parsing a XRDS definition it will return a datastructure much like the one below. + +Array +( + [expires] => 2008-04-13T07:34:58Z + [request] => Array + ( + [0] => Array + ( + [uri] => https://ma.gnolia.com/oauth/get_request_token + [signature_method] => Array + ( + [0] => HMAC-SHA1 + [1] => RSA-SHA1 + [2] => PLAINTEXT + ) + + [parameters] => Array + ( + [0] => auth-header + [1] => post-body + [2] => uri-query + ) + ) + ) + + [authorize] => Array + ( + [0] => Array + ( + [uri] => http://ma.gnolia.com/oauth/authorize + [signature_method] => Array + ( + ) + + [parameters] => Array + ( + [0] => auth-header + [1] => uri-query + ) + ) + ) + + [access] => Array + ( + [0] => Array + ( + [uri] => https://ma.gnolia.com/oauth/get_access_token + [signature_method] => Array + ( + [0] => HMAC-SHA1 + [1] => RSA-SHA1 + [2] => PLAINTEXT + ) + + [parameters] => Array + ( + [0] => auth-header + [1] => post-body + [2] => uri-query + ) + ) + ) + + [resource] => Array + ( + [0] => Array + ( + [uri] => + [signature_method] => Array + ( + [0] => HMAC-SHA1 + [1] => RSA-SHA1 + ) + + [parameters] => Array + ( + [0] => auth-header + [1] => post-body + [2] => uri-query + ) + ) + ) + + [consumer_identity] => Array + ( + [0] => Array + ( + [uri] => http://ma.gnolia.com/applications/new + [method] => oob + ) + ) +) + diff --git a/3rdparty/oauth-php/library/session/OAuthSessionAbstract.class.php b/3rdparty/oauth-php/library/session/OAuthSessionAbstract.class.php new file mode 100644 index 0000000000..dcc80c1d81 --- /dev/null +++ b/3rdparty/oauth-php/library/session/OAuthSessionAbstract.class.php @@ -0,0 +1,44 @@ + + * + * The MIT License + * + * Copyright (c) 2010 Corollarium Technologies + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * This class is used to store Session information on the server. Most + * people will use the $_SESSION based implementation, but you may prefer + * a SQL, Memcache or other implementation. + * + */ +abstract class OAuthSessionAbstract +{ + abstract public function get ( $key ); + abstract public function set ( $key, $data ); +} + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/session/OAuthSessionSESSION.php b/3rdparty/oauth-php/library/session/OAuthSessionSESSION.php new file mode 100644 index 0000000000..3201ecbe06 --- /dev/null +++ b/3rdparty/oauth-php/library/session/OAuthSessionSESSION.php @@ -0,0 +1,63 @@ + + * + * The MIT License + * + * Copyright (c) 2010 Corollarium Technologies + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__) . '/OAuthSessionAbstract.class.php'; + +class OAuthSessionSESSION extends OAuthSessionAbstract +{ + public function __construct( $options = array() ) + { + } + + /** + * Gets a variable value + * + * @param string $key + * @return The value or null if not set. + */ + public function get ( $key ) + { + return @$_SESSION[$key]; + } + + /** + * Sets a variable value + * + * @param string $key The key + * @param any $data The data + */ + public function set ( $key, $data ) + { + $_SESSION[$key] = $data; + } +} + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod.class.php b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod.class.php new file mode 100644 index 0000000000..34ccb428cc --- /dev/null +++ b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod.class.php @@ -0,0 +1,69 @@ + + * @date Sep 8, 2008 12:04:35 PM + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +abstract class OAuthSignatureMethod +{ + /** + * Return the name of this signature + * + * @return string + */ + abstract public function name(); + + /** + * Return the signature for the given request + * + * @param OAuthRequest request + * @param string base_string + * @param string consumer_secret + * @param string token_secret + * @return string + */ + abstract public function signature ( $request, $base_string, $consumer_secret, $token_secret ); + + /** + * Check if the request signature corresponds to the one calculated for the request. + * + * @param OAuthRequest request + * @param string base_string data to be signed, usually the base string, can be a request body + * @param string consumer_secret + * @param string token_secret + * @param string signature from the request, still urlencoded + * @return string + */ + abstract public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature ); +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php new file mode 100644 index 0000000000..e189c93815 --- /dev/null +++ b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php @@ -0,0 +1,115 @@ + + * @date Sep 8, 2008 12:21:19 PM + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + +require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php'; + + +class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod +{ + public function name () + { + return 'HMAC-SHA1'; + } + + + /** + * Calculate the signature using HMAC-SHA1 + * This function is copyright Andy Smith, 2007. + * + * @param OAuthRequest request + * @param string base_string + * @param string consumer_secret + * @param string token_secret + * @return string + */ + function signature ( $request, $base_string, $consumer_secret, $token_secret ) + { + $key = $request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret); + if (function_exists('hash_hmac')) + { + $signature = base64_encode(hash_hmac("sha1", $base_string, $key, true)); + } + else + { + $blocksize = 64; + $hashfunc = 'sha1'; + if (strlen($key) > $blocksize) + { + $key = pack('H*', $hashfunc($key)); + } + $key = str_pad($key,$blocksize,chr(0x00)); + $ipad = str_repeat(chr(0x36),$blocksize); + $opad = str_repeat(chr(0x5c),$blocksize); + $hmac = pack( + 'H*',$hashfunc( + ($key^$opad).pack( + 'H*',$hashfunc( + ($key^$ipad).$base_string + ) + ) + ) + ); + $signature = base64_encode($hmac); + } + return $request->urlencode($signature); + } + + + /** + * Check if the request signature corresponds to the one calculated for the request. + * + * @param OAuthRequest request + * @param string base_string data to be signed, usually the base string, can be a request body + * @param string consumer_secret + * @param string token_secret + * @param string signature from the request, still urlencoded + * @return string + */ + public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature ) + { + $a = $request->urldecode($signature); + $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret)); + + // We have to compare the decoded values + $valA = base64_decode($a); + $valB = base64_decode($b); + + // Crude binary comparison + return rawurlencode($valA) == rawurlencode($valB); + } +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php new file mode 100644 index 0000000000..a016709802 --- /dev/null +++ b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php @@ -0,0 +1,95 @@ + + * @date Sep 8, 2008 12:09:43 PM + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php'; + + +class OAuthSignatureMethod_MD5 extends OAuthSignatureMethod +{ + public function name () + { + return 'MD5'; + } + + + /** + * Calculate the signature using MD5 + * Binary md5 digest, as distinct from PHP's built-in hexdigest. + * This function is copyright Andy Smith, 2007. + * + * @param OAuthRequest request + * @param string base_string + * @param string consumer_secret + * @param string token_secret + * @return string + */ + function signature ( $request, $base_string, $consumer_secret, $token_secret ) + { + $s .= '&'.$request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret); + $md5 = md5($base_string); + $bin = ''; + + for ($i = 0; $i < strlen($md5); $i += 2) + { + $bin .= chr(hexdec($md5{$i+1}) + hexdec($md5{$i}) * 16); + } + return $request->urlencode(base64_encode($bin)); + } + + + /** + * Check if the request signature corresponds to the one calculated for the request. + * + * @param OAuthRequest request + * @param string base_string data to be signed, usually the base string, can be a request body + * @param string consumer_secret + * @param string token_secret + * @param string signature from the request, still urlencoded + * @return string + */ + public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature ) + { + $a = $request->urldecode($signature); + $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret)); + + // We have to compare the decoded values + $valA = base64_decode($a); + $valB = base64_decode($b); + + // Crude binary comparison + return rawurlencode($valA) == rawurlencode($valB); + } +} + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php new file mode 100644 index 0000000000..92ef308673 --- /dev/null +++ b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php @@ -0,0 +1,80 @@ + + * @date Sep 8, 2008 12:09:43 PM + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php'; + + +class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod +{ + public function name () + { + return 'PLAINTEXT'; + } + + + /** + * Calculate the signature using PLAINTEXT + * + * @param OAuthRequest request + * @param string base_string + * @param string consumer_secret + * @param string token_secret + * @return string + */ + function signature ( $request, $base_string, $consumer_secret, $token_secret ) + { + return $request->urlencode($request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret)); + } + + + /** + * Check if the request signature corresponds to the one calculated for the request. + * + * @param OAuthRequest request + * @param string base_string data to be signed, usually the base string, can be a request body + * @param string consumer_secret + * @param string token_secret + * @param string signature from the request, still urlencoded + * @return string + */ + public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature ) + { + $a = $request->urldecode($signature); + $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret)); + + return $request->urldecode($a) == $request->urldecode($b); + } +} + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php new file mode 100644 index 0000000000..864dbfbebb --- /dev/null +++ b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php @@ -0,0 +1,139 @@ + + * @date Sep 8, 2008 12:00:14 PM + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + +require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php'; + +class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod +{ + public function name() + { + return 'RSA-SHA1'; + } + + + /** + * Fetch the public CERT key for the signature + * + * @param OAuthRequest request + * @return string public key + */ + protected function fetch_public_cert ( $request ) + { + // not implemented yet, ideas are: + // (1) do a lookup in a table of trusted certs keyed off of consumer + // (2) fetch via http using a url provided by the requester + // (3) some sort of specific discovery code based on request + // + // either way should return a string representation of the certificate + throw OAuthException2("OAuthSignatureMethod_RSA_SHA1::fetch_public_cert not implemented"); + } + + + /** + * Fetch the private CERT key for the signature + * + * @param OAuthRequest request + * @return string private key + */ + protected function fetch_private_cert ( $request ) + { + // not implemented yet, ideas are: + // (1) do a lookup in a table of trusted certs keyed off of consumer + // + // either way should return a string representation of the certificate + throw OAuthException2("OAuthSignatureMethod_RSA_SHA1::fetch_private_cert not implemented"); + } + + + /** + * Calculate the signature using RSA-SHA1 + * This function is copyright Andy Smith, 2008. + * + * @param OAuthRequest request + * @param string base_string + * @param string consumer_secret + * @param string token_secret + * @return string + */ + public function signature ( $request, $base_string, $consumer_secret, $token_secret ) + { + // Fetch the private key cert based on the request + $cert = $this->fetch_private_cert($request); + + // Pull the private key ID from the certificate + $privatekeyid = openssl_get_privatekey($cert); + + // Sign using the key + $sig = false; + $ok = openssl_sign($base_string, $sig, $privatekeyid); + + // Release the key resource + openssl_free_key($privatekeyid); + + return $request->urlencode(base64_encode($sig)); + } + + + /** + * Check if the request signature is the same as the one calculated for the request. + * + * @param OAuthRequest request + * @param string base_string + * @param string consumer_secret + * @param string token_secret + * @param string signature + * @return string + */ + public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature ) + { + $decoded_sig = base64_decode($request->urldecode($signature)); + + // Fetch the public key cert based on the request + $cert = $this->fetch_public_cert($request); + + // Pull the public key ID from the certificate + $publickeyid = openssl_get_publickey($cert); + + // Check the computed signature against the one passed in the query + $ok = openssl_verify($base_string, $decoded_sig, $publickeyid); + + // Release the key resource + openssl_free_key($publickeyid); + return $ok == 1; + } + +} + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStore2Leg.php b/3rdparty/oauth-php/library/store/OAuthStore2Leg.php new file mode 100644 index 0000000000..faab95b04b --- /dev/null +++ b/3rdparty/oauth-php/library/store/OAuthStore2Leg.php @@ -0,0 +1,113 @@ + + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php'; + +class OAuthStore2Leg extends OAuthStoreAbstract +{ + protected $consumer_key; + protected $consumer_secret; + protected $signature_method = array('HMAC-SHA1'); + protected $token_type = false; + + /* + * Takes two options: consumer_key and consumer_secret + */ + public function __construct( $options = array() ) + { + if(isset($options['consumer_key']) && isset($options['consumer_secret'])) + { + $this->consumer_key = $options['consumer_key']; + $this->consumer_secret = $options['consumer_secret']; + } + else + { + throw new OAuthException2("OAuthStore2Leg needs consumer_token and consumer_secret"); + } + } + + public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function getSecretsForSignature ( $uri, $user_id ) + { + return array( + 'consumer_key' => $this->consumer_key, + 'consumer_secret' => $this->consumer_secret, + 'signature_methods' => $this->signature_method, + 'token' => $this->token_type + ); + } + public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + + public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function getServer( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function getServerForUri ( $uri, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function listServerTokens ( $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function countServerTokens ( $consumer_key ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function getServerToken ( $consumer_key, $token, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function setServerTokenTtl ( $consumer_key, $token, $token_ttl ) + { + //This method just needs to exist. It doesn't have to do anything! + } + + public function listServers ( $q = '', $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function updateServer ( $server, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + + public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function getConsumerStatic () { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + + public function addConsumerRequestToken ( $consumer_key, $options = array() ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function getConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function deleteConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function countConsumerAccessTokens ( $consumer_key ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function getConsumerAccessToken ( $token, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function setConsumerAccessTokenTtl ( $token, $ttl ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + + public function listConsumers ( $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function listConsumerApplications( $begin = 0, $total = 25 ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function listConsumerTokens ( $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + + public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + + public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + public function listLog ( $options, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } + + public function install () { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } +} + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreAbstract.class.php b/3rdparty/oauth-php/library/store/OAuthStoreAbstract.class.php new file mode 100644 index 0000000000..3bfa2b2b0d --- /dev/null +++ b/3rdparty/oauth-php/library/store/OAuthStoreAbstract.class.php @@ -0,0 +1,150 @@ + + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +abstract class OAuthStoreAbstract +{ + abstract public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ); + abstract public function getSecretsForSignature ( $uri, $user_id ); + abstract public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' ); + abstract public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ); + + abstract public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ); + abstract public function getServer( $consumer_key, $user_id, $user_is_admin = false ); + abstract public function getServerForUri ( $uri, $user_id ); + abstract public function listServerTokens ( $user_id ); + abstract public function countServerTokens ( $consumer_key ); + abstract public function getServerToken ( $consumer_key, $token, $user_id ); + abstract public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ); + abstract public function listServers ( $q = '', $user_id ); + abstract public function updateServer ( $server, $user_id, $user_is_admin = false ); + + abstract public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ); + abstract public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ); + abstract public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ); + abstract public function getConsumerStatic (); + + abstract public function addConsumerRequestToken ( $consumer_key, $options = array() ); + abstract public function getConsumerRequestToken ( $token ); + abstract public function deleteConsumerRequestToken ( $token ); + abstract public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ); + abstract public function countConsumerAccessTokens ( $consumer_key ); + abstract public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ); + abstract public function getConsumerAccessToken ( $token, $user_id ); + abstract public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ); + abstract public function setConsumerAccessTokenTtl ( $token, $ttl ); + + abstract public function listConsumers ( $user_id ); + abstract public function listConsumerApplications( $begin = 0, $total = 25 ); + abstract public function listConsumerTokens ( $user_id ); + + abstract public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ); + + abstract public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ); + abstract public function listLog ( $options, $user_id ); + + abstract public function install (); + + /** + * Fetch the current static consumer key for this site, create it when it was not found. + * The consumer secret for the consumer key is always empty. + * + * @return string consumer key + */ + + + /* ** Some handy utility functions ** */ + + /** + * Generate a unique key + * + * @param boolean unique force the key to be unique + * @return string + */ + public function generateKey ( $unique = false ) + { + $key = md5(uniqid(rand(), true)); + if ($unique) + { + list($usec,$sec) = explode(' ',microtime()); + $key .= dechex($usec).dechex($sec); + } + return $key; + } + + /** + * Check to see if a string is valid utf8 + * + * @param string $s + * @return boolean + */ + protected function isUTF8 ( $s ) + { + return preg_match('%(?: + [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte + |\xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs + |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte + |\xED[\x80-\x9F][\x80-\xBF] # excluding surrogates + |\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 + |[\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 + |\xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 + )+%xs', $s); + } + + + /** + * Make a string utf8, replacing all non-utf8 chars with a '.' + * + * @param string + * @return string + */ + protected function makeUTF8 ( $s ) + { + if (function_exists('iconv')) + { + do + { + $ok = true; + $text = @iconv('UTF-8', 'UTF-8//TRANSLIT', $s); + if (strlen($text) != strlen($s)) + { + // Remove the offending character... + $s = $text . '.' . substr($s, strlen($text) + 1); + $ok = false; + } + } + while (!$ok); + } + return $s; + } + +} + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreAnyMeta.php b/3rdparty/oauth-php/library/store/OAuthStoreAnyMeta.php new file mode 100644 index 0000000000..b619ec0367 --- /dev/null +++ b/3rdparty/oauth-php/library/store/OAuthStoreAnyMeta.php @@ -0,0 +1,264 @@ + + * @date Nov 16, 2007 4:03:30 PM + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__) . '/OAuthStoreMySQL.php'; + + +class OAuthStoreAnymeta extends OAuthStoreMySQL +{ + /** + * Construct the OAuthStoreAnymeta + * + * @param array options + */ + function __construct ( $options = array() ) + { + parent::__construct(array('conn' => any_db_conn())); + } + + + /** + * Add an entry to the log table + * + * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token) + * @param string received + * @param string sent + * @param string base_string + * @param string notes + * @param int (optional) user_id + */ + public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) + { + if (is_null($user_id) && isset($GLOBALS['any_auth'])) + { + $user_id = $GLOBALS['any_auth']->getUserId(); + } + parent::addLog($keys, $received, $sent, $base_string, $notes, $user_id); + } + + + /** + * Get a page of entries from the log. Returns the last 100 records + * matching the options given. + * + * @param array options + * @param int user_id current user + * @return array log records + */ + public function listLog ( $options, $user_id ) + { + $where = array(); + $args = array(); + if (empty($options)) + { + $where[] = 'olg_usa_id_ref = %d'; + $args[] = $user_id; + } + else + { + foreach ($options as $option => $value) + { + if (strlen($value) > 0) + { + switch ($option) + { + case 'osr_consumer_key': + case 'ocr_consumer_key': + case 'ost_token': + case 'oct_token': + $where[] = 'olg_'.$option.' = \'%s\''; + $args[] = $value; + break; + } + } + } + + $where[] = '(olg_usa_id_ref IS NULL OR olg_usa_id_ref = %d)'; + $args[] = $user_id; + } + + $rs = any_db_query_all_assoc(' + SELECT olg_id, + olg_osr_consumer_key AS osr_consumer_key, + olg_ost_token AS ost_token, + olg_ocr_consumer_key AS ocr_consumer_key, + olg_oct_token AS oct_token, + olg_usa_id_ref AS user_id, + olg_received AS received, + olg_sent AS sent, + olg_base_string AS base_string, + olg_notes AS notes, + olg_timestamp AS timestamp, + INET_NTOA(olg_remote_ip) AS remote_ip + FROM oauth_log + WHERE '.implode(' AND ', $where).' + ORDER BY olg_id DESC + LIMIT 0,100', $args); + + return $rs; + } + + + + /** + * Initialise the database + */ + public function install () + { + parent::install(); + + any_db_query("ALTER TABLE oauth_consumer_registry MODIFY ocr_usa_id_ref int(11) unsigned"); + any_db_query("ALTER TABLE oauth_consumer_token MODIFY oct_usa_id_ref int(11) unsigned not null"); + any_db_query("ALTER TABLE oauth_server_registry MODIFY osr_usa_id_ref int(11) unsigned"); + any_db_query("ALTER TABLE oauth_server_token MODIFY ost_usa_id_ref int(11) unsigned not null"); + any_db_query("ALTER TABLE oauth_log MODIFY olg_usa_id_ref int(11) unsigned"); + + any_db_alter_add_fk('oauth_consumer_registry', 'ocr_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete set null'); + any_db_alter_add_fk('oauth_consumer_token', 'oct_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete cascade'); + any_db_alter_add_fk('oauth_server_registry', 'osr_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete set null'); + any_db_alter_add_fk('oauth_server_token', 'ost_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete cascade'); + any_db_alter_add_fk('oauth_log', 'olg_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete cascade'); + } + + + + /** Some simple helper functions for querying the mysql db **/ + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + */ + protected function query ( $sql ) + { + list($sql, $args) = $this->sql_args(func_get_args()); + any_db_query($sql, $args); + } + + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_all_assoc ( $sql ) + { + list($sql, $args) = $this->sql_args(func_get_args()); + return any_db_query_all_assoc($sql, $args); + } + + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_row_assoc ( $sql ) + { + list($sql, $args) = $this->sql_args(func_get_args()); + return any_db_query_row_assoc($sql, $args); + } + + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_row ( $sql ) + { + list($sql, $args) = $this->sql_args(func_get_args()); + return any_db_query_row($sql, $args); + } + + + /** + * Perform a query, return the first column of the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return mixed + */ + protected function query_one ( $sql ) + { + list($sql, $args) = $this->sql_args(func_get_args()); + return any_db_query_one($sql, $args); + } + + + /** + * Return the number of rows affected in the last query + * + * @return int + */ + protected function query_affected_rows () + { + return any_db_affected_rows(); + } + + + /** + * Return the id of the last inserted row + * + * @return int + */ + protected function query_insert_id () + { + return any_db_insert_id(); + } + + + private function sql_args ( $args ) + { + $sql = array_shift($args); + if (count($args) == 1 && is_array($args[0])) + { + $args = $args[0]; + } + return array($sql, $args); + } + +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreMySQL.php b/3rdparty/oauth-php/library/store/OAuthStoreMySQL.php new file mode 100644 index 0000000000..c568359ace --- /dev/null +++ b/3rdparty/oauth-php/library/store/OAuthStoreMySQL.php @@ -0,0 +1,245 @@ + + * @date Nov 16, 2007 4:03:30 PM + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + +require_once dirname(__FILE__) . '/OAuthStoreSQL.php'; + + +class OAuthStoreMySQL extends OAuthStoreSQL +{ + /** + * The MySQL connection + */ + protected $conn; + + /** + * Initialise the database + */ + public function install () + { + require_once dirname(__FILE__) . '/mysql/install.php'; + } + + + /* ** Some simple helper functions for querying the mysql db ** */ + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + */ + protected function query ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = mysql_query($sql, $this->conn))) + { + $this->sql_errcheck($sql); + } + if (is_resource($res)) + { + mysql_free_result($res); + } + } + + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_all_assoc ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = mysql_query($sql, $this->conn))) + { + $this->sql_errcheck($sql); + } + $rs = array(); + while ($row = mysql_fetch_assoc($res)) + { + $rs[] = $row; + } + mysql_free_result($res); + return $rs; + } + + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_row_assoc ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = mysql_query($sql, $this->conn))) + { + $this->sql_errcheck($sql); + } + if ($row = mysql_fetch_assoc($res)) + { + $rs = $row; + } + else + { + $rs = false; + } + mysql_free_result($res); + return $rs; + } + + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_row ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = mysql_query($sql, $this->conn))) + { + $this->sql_errcheck($sql); + } + if ($row = mysql_fetch_array($res)) + { + $rs = $row; + } + else + { + $rs = false; + } + mysql_free_result($res); + return $rs; + } + + + /** + * Perform a query, return the first column of the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return mixed + */ + protected function query_one ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = mysql_query($sql, $this->conn))) + { + $this->sql_errcheck($sql); + } + $val = @mysql_result($res, 0, 0); + mysql_free_result($res); + return $val; + } + + + /** + * Return the number of rows affected in the last query + */ + protected function query_affected_rows () + { + return mysql_affected_rows($this->conn); + } + + + /** + * Return the id of the last inserted row + * + * @return int + */ + protected function query_insert_id () + { + return mysql_insert_id($this->conn); + } + + + protected function sql_printf ( $args ) + { + $sql = array_shift($args); + if (count($args) == 1 && is_array($args[0])) + { + $args = $args[0]; + } + $args = array_map(array($this, 'sql_escape_string'), $args); + return vsprintf($sql, $args); + } + + + protected function sql_escape_string ( $s ) + { + if (is_string($s)) + { + return mysql_real_escape_string($s, $this->conn); + } + else if (is_null($s)) + { + return NULL; + } + else if (is_bool($s)) + { + return intval($s); + } + else if (is_int($s) || is_float($s)) + { + return $s; + } + else + { + return mysql_real_escape_string(strval($s), $this->conn); + } + } + + + protected function sql_errcheck ( $sql ) + { + if (mysql_errno($this->conn)) + { + $msg = "SQL Error in OAuthStoreMySQL: ".mysql_error($this->conn)."\n\n" . $sql; + throw new OAuthException2($msg); + } + } +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreMySQLi.php b/3rdparty/oauth-php/library/store/OAuthStoreMySQLi.php new file mode 100644 index 0000000000..09d71bfba5 --- /dev/null +++ b/3rdparty/oauth-php/library/store/OAuthStoreMySQLi.php @@ -0,0 +1,306 @@ + Based on code by Marc Worrell + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/* + * Modified from OAuthStoreMySQL to support MySQLi + */ + +require_once dirname(__FILE__) . '/OAuthStoreMySQL.php'; + + +class OAuthStoreMySQLi extends OAuthStoreMySQL +{ + + public function install() { + $sql = file_get_contents(dirname(__FILE__) . '/mysql/mysql.sql'); + $ps = explode('#--SPLIT--', $sql); + + foreach ($ps as $p) + { + $p = preg_replace('/^\s*#.*$/m', '', $p); + + $this->query($p); + $this->sql_errcheck($p); + } + } + + /** + * Construct the OAuthStoreMySQLi. + * In the options you have to supply either: + * - server, username, password and database (for a mysqli_connect) + * - conn (for the connection to be used) + * + * @param array options + */ + function __construct ( $options = array() ) + { + if (isset($options['conn'])) + { + $this->conn = $options['conn']; + } + else + { + if (isset($options['server'])) + { + $server = $options['server']; + $username = $options['username']; + + if (isset($options['password'])) + { + $this->conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username, $options['password'])); + } + else + { + $this->conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username)); + } + } + else + { + // Try the default mysql connect + $this->conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect()); + } + + if ($this->conn === false) + { + throw new OAuthException2('Could not connect to MySQL database: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))); + } + + if (isset($options['database'])) + { + /* TODO: security. mysqli_ doesn't seem to have an escape identifier function. + $escapeddb = mysqli_real_escape_string($options['database']); + if (!((bool)mysqli_query( $this->conn, "USE `$escapeddb`" ))) + { + $this->sql_errcheck(); + }*/ + } + $this->query('set character set utf8'); + } + } + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + */ + protected function query ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = mysqli_query( $this->conn, $sql))) + { + $this->sql_errcheck($sql); + } + if (!is_bool($res)) + { + ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false); + } + } + + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_all_assoc ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = mysqli_query( $this->conn, $sql))) + { + $this->sql_errcheck($sql); + } + $rs = array(); + while ($row = mysqli_fetch_assoc($res)) + { + $rs[] = $row; + } + ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false); + return $rs; + } + + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_row_assoc ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = mysqli_query( $this->conn, $sql))) + { + $this->sql_errcheck($sql); + } + if ($row = mysqli_fetch_assoc($res)) + { + $rs = $row; + } + else + { + $rs = false; + } + ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false); + return $rs; + } + + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_row ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = mysqli_query( $this->conn, $sql))) + { + $this->sql_errcheck($sql); + } + if ($row = mysqli_fetch_array($res)) + { + $rs = $row; + } + else + { + $rs = false; + } + ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false); + return $rs; + } + + + /** + * Perform a query, return the first column of the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return mixed + */ + protected function query_one ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = mysqli_query( $this->conn, $sql))) + { + $this->sql_errcheck($sql); + } + if ($row = mysqli_fetch_assoc($res)) + { + $val = array_pop($row); + } + else + { + $val = false; + } + ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false); + return $val; + } + + + /** + * Return the number of rows affected in the last query + */ + protected function query_affected_rows () + { + return mysqli_affected_rows($this->conn); + } + + + /** + * Return the id of the last inserted row + * + * @return int + */ + protected function query_insert_id () + { + return ((is_null($___mysqli_res = mysqli_insert_id($this->conn))) ? false : $___mysqli_res); + } + + + protected function sql_printf ( $args ) + { + $sql = array_shift($args); + if (count($args) == 1 && is_array($args[0])) + { + $args = $args[0]; + } + $args = array_map(array($this, 'sql_escape_string'), $args); + return vsprintf($sql, $args); + } + + + protected function sql_escape_string ( $s ) + { + if (is_string($s)) + { + return mysqli_real_escape_string( $this->conn, $s); + } + else if (is_null($s)) + { + return NULL; + } + else if (is_bool($s)) + { + return intval($s); + } + else if (is_int($s) || is_float($s)) + { + return $s; + } + else + { + return mysqli_real_escape_string( $this->conn, strval($s)); + } + } + + + protected function sql_errcheck ( $sql ) + { + if (((is_object($this->conn)) ? mysqli_errno($this->conn) : (($___mysqli_res = mysqli_connect_errno()) ? $___mysqli_res : false))) + { + $msg = "SQL Error in OAuthStoreMySQL: ".((is_object($this->conn)) ? mysqli_error($this->conn) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))."\n\n" . $sql; + throw new OAuthException2($msg); + } + } +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreOracle.php b/3rdparty/oauth-php/library/store/OAuthStoreOracle.php new file mode 100644 index 0000000000..554792faa6 --- /dev/null +++ b/3rdparty/oauth-php/library/store/OAuthStoreOracle.php @@ -0,0 +1,1536 @@ + + * @date Aug 6, 2010 + * + * The MIT License + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php'; + +abstract class OAuthStoreOracle extends OAuthStoreAbstract { + /** + * Maximum delta a timestamp may be off from a previous timestamp. + * Allows multiple consumers with some clock skew to work with the same token. + * Unit is seconds, default max skew is 10 minutes. + */ + protected $max_timestamp_skew = MAX_TIMESTAMP_SKEW; + + /** + * Default ttl for request tokens + */ + protected $max_request_token_ttl = MAX_REQUEST_TOKEN_TIME; + + + /** + * Construct the OAuthStoreMySQL. + * In the options you have to supply either: + * - server, username, password and database (for a mysql_connect) + * - conn (for the connection to be used) + * + * @param array options + */ + function __construct ( $options = array() ) { + if (isset($options['conn'])) { + $this->conn = $options['conn']; + } + else { + $this->conn=oci_connect(DBUSER,DBPASSWORD,DBHOST); + + if ($this->conn === false) { + throw new OAuthException2('Could not connect to database'); + } + + // $this->query('set character set utf8'); + } + } + + /** + * Find stored credentials for the consumer key and token. Used by an OAuth server + * when verifying an OAuth request. + * + * @param string consumer_key + * @param string token + * @param string token_type false, 'request' or 'access' + * @exception OAuthException2 when no secrets where found + * @return array assoc (consumer_secret, token_secret, osr_id, ost_id, user_id) + */ + public function getSecretsForVerify ($consumer_key, $token, $token_type = 'access' ) { + $sql = "BEGIN SP_GET_SECRETS_FOR_VERIFY(:P_CONSUMER_KEY, :P_TOKEN, :P_TOKEN_TYPE, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_TOKEN_TYPE', $token_type, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $getSecretsForVerifyList, null, null, OCI_FETCHSTATEMENT_BY_ROW); + + $rs =$getSecretsForVerifyList; + if (empty($rs)) { + throw new OAuthException2('The consumer_key "'.$consumer_key.'" token "'.$token.'" combination does not exist or is not enabled.'); + } + + return $rs[0]; + } + + + /** + * Find the server details for signing a request, always looks for an access token. + * The returned credentials depend on which local user is making the request. + * + * The consumer_key must belong to the user or be public (user id is null) + * + * For signing we need all of the following: + * + * consumer_key consumer key associated with the server + * consumer_secret consumer secret associated with this server + * token access token associated with this server + * token_secret secret for the access token + * signature_methods signing methods supported by the server (array) + * + * @todo filter on token type (we should know how and with what to sign this request, and there might be old access tokens) + * @param string uri uri of the server + * @param int user_id id of the logged on user + * @param string name (optional) name of the token (case sensitive) + * @exception OAuthException2 when no credentials found + * @return array + */ + public function getSecretsForSignature ( $uri, $user_id, $name = '' ) { + // Find a consumer key and token for the given uri + $ps = parse_url($uri); + $host = isset($ps['host']) ? $ps['host'] : 'localhost'; + $path = isset($ps['path']) ? $ps['path'] : ''; + + if (empty($path) || substr($path, -1) != '/') { + $path .= '/'; + } + // + $sql = "BEGIN SP_GET_SECRETS_FOR_SIGNATURE(:P_HOST, :P_PATH, :P_USER_ID, :P_NAME, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_HOST', $host, 255); + oci_bind_by_name($stmt, ':P_PATH', $path, 255); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 20); + oci_bind_by_name($stmt, ':P_NAME', $name, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $getSecretsForSignatureList, null, null, OCI_FETCHSTATEMENT_BY_ROW); + $secrets = $getSecretsForSignatureList[0]; + // + // The owner of the consumer_key is either the user or nobody (public consumer key) + /*$secrets = $this->query_row_assoc(' + SELECT ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + oct_token as token, + oct_token_secret as token_secret, + ocr_signature_methods as signature_methods + FROM oauth_consumer_registry + JOIN oauth_consumer_token ON oct_ocr_id_ref = ocr_id + WHERE ocr_server_uri_host = \'%s\' + AND ocr_server_uri_path = LEFT(\'%s\', LENGTH(ocr_server_uri_path)) + AND (ocr_usa_id_ref = %s OR ocr_usa_id_ref IS NULL) + AND oct_usa_id_ref = %d + AND oct_token_type = \'access\' + AND oct_name = \'%s\' + AND oct_token_ttl >= NOW() + ORDER BY ocr_usa_id_ref DESC, ocr_consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC + LIMIT 0,1 + ', $host, $path, $user_id, $user_id, $name + ); + */ + if (empty($secrets)) { + throw new OAuthException2('No server tokens available for '.$uri); + } + $secrets['signature_methods'] = explode(',', $secrets['signature_methods']); + return $secrets; + } + + + /** + * Get the token and token secret we obtained from a server. + * + * @param string consumer_key + * @param string token + * @param string token_type + * @param int user_id the user owning the token + * @param string name optional name for a named token + * @exception OAuthException2 when no credentials found + * @return array + */ + public function getServerTokenSecrets ($consumer_key,$token,$token_type,$user_id,$name = '') + { + if ($token_type != 'request' && $token_type != 'access') + { + throw new OAuthException2('Unkown token type "'.$token_type.'", must be either "request" or "access"'); + } + // + $sql = "BEGIN SP_GET_SERVER_TOKEN_SECRETS(:P_CONSUMER_KEY, :P_TOKEN, :P_TOKEN_TYPE, :P_USER_ID, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_TOKEN_TYPE', $token_type, 20); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $getServerTokenSecretsList, null, null, OCI_FETCHSTATEMENT_BY_ROW); + $r=$getServerTokenSecretsList[0]; + // + // Take the most recent token of the given type + /*$r = $this->query_row_assoc(' + SELECT ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + oct_token as token, + oct_token_secret as token_secret, + oct_name as token_name, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri, + IF(oct_token_ttl >= \'9999-12-31\', NULL, UNIX_TIMESTAMP(oct_token_ttl) - UNIX_TIMESTAMP(NOW())) as token_ttl + FROM oauth_consumer_registry + JOIN oauth_consumer_token + ON oct_ocr_id_ref = ocr_id + WHERE ocr_consumer_key = \'%s\' + AND oct_token_type = \'%s\' + AND oct_token = \'%s\' + AND oct_usa_id_ref = %d + AND oct_token_ttl >= NOW() + ', $consumer_key, $token_type, $token, $user_id + );*/ + + if (empty($r)) + { + throw new OAuthException2('Could not find a "'.$token_type.'" token for consumer "'.$consumer_key.'" and user '.$user_id); + } + if (isset($r['signature_methods']) && !empty($r['signature_methods'])) + { + $r['signature_methods'] = explode(',',$r['signature_methods']); + } + else + { + $r['signature_methods'] = array(); + } + return $r; + } + + + /** + * Add a request token we obtained from a server. + * + * @todo remove old tokens for this user and this ocr_id + * @param string consumer_key key of the server in the consumer registry + * @param string token_type one of 'request' or 'access' + * @param string token + * @param string token_secret + * @param int user_id the user owning the token + * @param array options extra options, name and token_ttl + * @exception OAuthException2 when server is not known + * @exception OAuthException2 when we received a duplicate token + */ + public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) + { + if ($token_type != 'request' && $token_type != 'access') + { + throw new OAuthException2('Unknown token type "'.$token_type.'", must be either "request" or "access"'); + } + + // Maximum time to live for this token + if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) + { + $ttl = intval($options['token_ttl']); + } + else if ($token_type == 'request') + { + $ttl =intval($this->max_request_token_ttl); + } + else + { + $ttl = NULL; + } + + + + // Named tokens, unique per user/consumer key + if (isset($options['name']) && $options['name'] != '') + { + $name = $options['name']; + } + else + { + $name = ''; + } + // + $sql = "BEGIN SP_ADD_SERVER_TOKEN(:P_CONSUMER_KEY, :P_USER_ID, :P_NAME, :P_TOKEN_TYPE, :P_TOKEN, :P_TOKEN_SECRET, :P_TOKEN_INTERVAL_IN_SEC, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_NAME', $name, 255); + oci_bind_by_name($stmt, ':P_TOKEN_TYPE', $token_type, 20); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_TOKEN_SECRET', $token_secret, 255); + oci_bind_by_name($stmt, ':P_TOKEN_INTERVAL_IN_SEC', $ttl, 40); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + // + + + + if (!$result) + { + throw new OAuthException2('Received duplicate token "'.$token.'" for the same consumer_key "'.$consumer_key.'"'); + } + } + + + /** + * Delete a server key. This removes access to that site. + * + * @param string consumer_key + * @param int user_id user registering this server + * @param boolean user_is_admin + */ + public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) + { + + $sql = "BEGIN SP_DELETE_SERVER(:P_CONSUMER_KEY, :P_USER_ID, :P_USER_IS_ADMIN, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + } + + + /** + * Get a server from the consumer registry using the consumer key + * + * @param string consumer_key + * @param int user_id + * @param boolean user_is_admin (optional) + * @exception OAuthException2 when server is not found + * @return array + */ + public function getServer ( $consumer_key, $user_id, $user_is_admin = false ) + { + + // + $sql = "BEGIN SP_GET_SERVER(:P_CONSUMER_KEY, :P_USER_ID, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $getServerList, null, null, OCI_FETCHSTATEMENT_BY_ROW); + $r = $getServerList; + // + if (empty($r)) + { + throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" has been registered (for this user)'); + } + + if (isset($r['signature_methods']) && !empty($r['signature_methods'])) + { + $r['signature_methods'] = explode(',',$r['signature_methods']); + } + else + { + $r['signature_methods'] = array(); + } + return $r; + } + + + + /** + * Find the server details that might be used for a request + * + * The consumer_key must belong to the user or be public (user id is null) + * + * @param string uri uri of the server + * @param int user_id id of the logged on user + * @exception OAuthException2 when no credentials found + * @return array + */ + public function getServerForUri ( $uri, $user_id ) + { + // Find a consumer key and token for the given uri + $ps = parse_url($uri); + $host = isset($ps['host']) ? $ps['host'] : 'localhost'; + $path = isset($ps['path']) ? $ps['path'] : ''; + + if (empty($path) || substr($path, -1) != '/') + { + $path .= '/'; + } + + + // + $sql = "BEGIN SP_GET_SERVER_FOR_URI(:P_HOST, :P_PATH,:P_USER_ID, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_HOST', $host, 255); + oci_bind_by_name($stmt, ':P_PATH', $path, 255); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $getServerForUriList, null, null, OCI_FETCHSTATEMENT_BY_ROW); + $server = $getServerForUriList; + // + if (empty($server)) + { + throw new OAuthException2('No server available for '.$uri); + } + $server['signature_methods'] = explode(',', $server['signature_methods']); + return $server; + } + + + /** + * Get a list of all server token this user has access to. + * + * @param int usr_id + * @return array + */ + public function listServerTokens ( $user_id ) + { + + $sql = "BEGIN SP_LIST_SERVER_TOKENS(:P_USER_ID, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $listServerTokensList, null, null, OCI_FETCHSTATEMENT_BY_ROW); + $ts = $listServerTokensList; + return $ts; + } + + + /** + * Count how many tokens we have for the given server + * + * @param string consumer_key + * @return int + */ + public function countServerTokens ( $consumer_key ) + { + + // + $count =0; + $sql = "BEGIN SP_COUNT_SERVICE_TOKENS(:P_CONSUMER_KEY, :P_COUNT, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_COUNT', $count, 40); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + // + return $count; + } + + + /** + * Get a specific server token for the given user + * + * @param string consumer_key + * @param string token + * @param int user_id + * @exception OAuthException2 when no such token found + * @return array + */ + public function getServerToken ( $consumer_key, $token, $user_id ) + { + + $sql = "BEGIN SP_GET_SERVER_TOKEN(:P_CONSUMER_KEY, :P_USER_ID,:P_TOKEN, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $getServerTokenList, null, null, OCI_FETCHSTATEMENT_BY_ROW); + $ts = $getServerTokenList; + // + + if (empty($ts)) + { + throw new OAuthException2('No such consumer key ('.$consumer_key.') and token ('.$token.') combination for user "'.$user_id.'"'); + } + return $ts; + } + + + /** + * Delete a token we obtained from a server. + * + * @param string consumer_key + * @param string token + * @param int user_id + * @param boolean user_is_admin + */ + public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) + { + + // + $sql = "BEGIN SP_DELETE_SERVER_TOKEN(:P_CONSUMER_KEY, :P_USER_ID,:P_TOKEN, :P_USER_IS_ADMIN, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 40); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + // + + } + + + /** + * Set the ttl of a server access token. This is done when the + * server receives a valid request with a xoauth_token_ttl parameter in it. + * + * @param string consumer_key + * @param string token + * @param int token_ttl + */ + public function setServerTokenTtl ( $consumer_key, $token, $token_ttl ) + { + if ($token_ttl <= 0) + { + // Immediate delete when the token is past its ttl + $this->deleteServerToken($consumer_key, $token, 0, true); + } + else + { + // Set maximum time to live for this token + + // + $sql = "BEGIN SP_SET_SERVER_TOKEN_TTL(:P_TOKEN_TTL, :P_CONSUMER_KEY, :P_TOKEN, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_TOKEN_TTL', $token_ttl, 40); + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + // + } + } + + + /** + * Get a list of all consumers from the consumer registry. + * The consumer keys belong to the user or are public (user id is null) + * + * @param string q query term + * @param int user_id + * @return array + */ + public function listServers ( $q = '', $user_id ) + { + $q = trim(str_replace('%', '', $q)); + $args = array(); + + + // + $sql = "BEGIN SP_LIST_SERVERS(:P_Q, :P_USER_ID, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_Q', $q, 255); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $listServersList, null, null, OCI_FETCHSTATEMENT_BY_ROW); + $servers = $listServersList; + // + + return $servers; + } + + + /** + * Register or update a server for our site (we will be the consumer) + * + * (This is the registry at the consumers, registering servers ;-) ) + * + * @param array server + * @param int user_id user registering this server + * @param boolean user_is_admin + * @exception OAuthException2 when fields are missing or on duplicate consumer_key + * @return consumer_key + */ + public function updateServer ( $server, $user_id, $user_is_admin = false ) { + foreach (array('consumer_key', 'server_uri') as $f) { + if (empty($server[$f])) { + throw new OAuthException2('The field "'.$f.'" must be set and non empty'); + } + } + $parts = parse_url($server['server_uri']); + $host = (isset($parts['host']) ? $parts['host'] : 'localhost'); + $path = (isset($parts['path']) ? $parts['path'] : '/'); + + if (isset($server['signature_methods'])) { + if (is_array($server['signature_methods'])) { + $server['signature_methods'] = strtoupper(implode(',', $server['signature_methods'])); + } + } + else { + $server['signature_methods'] = ''; + } + // When the user is an admin, then the user can update the user_id of this record + if ($user_is_admin && array_key_exists('user_id', $server)) { + $flag=1; + } + if($flag) { + if (is_null($server['user_id'])) { + $ocr_usa_id_ref= NULL; + } + else { + $ocr_usa_id_ref = $server['user_id']; + } + } + else { + $flag=0; + $ocr_usa_id_ref=$user_id; + } + //sp + $sql = "BEGIN SP_UPDATE_SERVER(:P_CONSUMER_KEY, :P_USER_ID, :P_OCR_ID, :P_USER_IS_ADMIN, + :P_OCR_CONSUMER_SECRET, :P_OCR_SERVER_URI, :P_OCR_SERVER_URI_HOST, :P_OCR_SERVER_URI_PATH, + :P_OCR_REQUEST_TOKEN_URI, :P_OCR_AUTHORIZE_URI, :P_OCR_ACCESS_TOKEN_URI, :P_OCR_SIGNATURE_METHODS, + :P_OCR_USA_ID_REF, :P_UPDATE_P_OCR_USA_ID_REF_FLAG, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + $server['request_token_uri'] = isset($server['request_token_uri']) ? $server['request_token_uri'] : ''; + $server['authorize_uri'] = isset($server['authorize_uri']) ? $server['authorize_uri'] : ''; + $server['access_token_uri'] = isset($server['access_token_uri']) ? $server['access_token_uri'] : ''; + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $server['consumer_key'], 255); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_OCR_ID', $server['id'], 40); + oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 40); + oci_bind_by_name($stmt, ':P_OCR_CONSUMER_SECRET', $server['consumer_secret'], 255); + oci_bind_by_name($stmt, ':P_OCR_SERVER_URI', $server['server_uri'], 255); + oci_bind_by_name($stmt, ':P_OCR_SERVER_URI_HOST', strtolower($host), 255); + oci_bind_by_name($stmt, ':P_OCR_SERVER_URI_PATH', $path, 255); + oci_bind_by_name($stmt, ':P_OCR_REQUEST_TOKEN_URI', $server['request_token_uri'], 255); + oci_bind_by_name($stmt, ':P_OCR_AUTHORIZE_URI', $server['authorize_uri'], 255); + oci_bind_by_name($stmt, ':P_OCR_ACCESS_TOKEN_URI', $server['access_token_uri'], 255); + oci_bind_by_name($stmt, ':P_OCR_SIGNATURE_METHODS', $server['signature_methods'], 255); + oci_bind_by_name($stmt, ':P_OCR_USA_ID_REF', $ocr_usa_id_ref, 40); + oci_bind_by_name($stmt, ':P_UPDATE_P_OCR_USA_ID_REF_FLAG', $flag, 40); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + + return $server['consumer_key']; + } + + /** + * Insert/update a new consumer with this server (we will be the server) + * When this is a new consumer, then also generate the consumer key and secret. + * Never updates the consumer key and secret. + * When the id is set, then the key and secret must correspond to the entry + * being updated. + * + * (This is the registry at the server, registering consumers ;-) ) + * + * @param array consumer + * @param int user_id user registering this consumer + * @param boolean user_is_admin + * @return string consumer key + */ + public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) { + $consumer_key = $this->generateKey(true); + $consumer_secret = $this->generateKey(); + + $consumer['callback_uri'] = isset($consumer['callback_uri'])? $consumer['callback_uri']: ''; + $consumer['application_uri'] = isset($consumer['application_uri'])? $consumer['application_uri']: ''; + $consumer['application_title'] = isset($consumer['application_title'])? $consumer['application_title']: ''; + $consumer['application_descr'] = isset($consumer['application_descr'])? $consumer['application_descr']: ''; + $consumer['application_notes'] = isset($consumer['application_notes'])? $consumer['application_notes']: ''; + $consumer['application_type'] = isset($consumer['application_type'])? $consumer['application_type']: ''; + $consumer['application_commercial'] = isset($consumer['application_commercial'])?$consumer['application_commercial']:0; + + //sp + $sql = "BEGIN SP_UPDATE_CONSUMER(:P_OSR_USA_ID_REF, :P_OSR_CONSUMER_KEY, :P_OSR_CONSUMER_SECRET, :P_OSR_REQUESTER_NAME, :P_OSR_REQUESTER_EMAIL, :P_OSR_CALLBACK_URI, :P_OSR_APPLICATION_URI, :P_OSR_APPLICATION_TITLE , :P_OSR_APPLICATION_DESCR, :P_OSR_APPLICATION_NOTES, :P_OSR_APPLICATION_TYPE, :P_OSR_APPLICATION_COMMERCIAL, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_OSR_USA_ID_REF', $user_id, 40); + oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_OSR_CONSUMER_SECRET', $consumer_secret, 255); + oci_bind_by_name($stmt, ':P_OSR_REQUESTER_NAME', $consumer['requester_name'], 255); + oci_bind_by_name($stmt, ':P_OSR_REQUESTER_EMAIL', $consumer['requester_email'], 255); + oci_bind_by_name($stmt, ':P_OSR_CALLBACK_URI', $consumer['callback_uri'], 255); + oci_bind_by_name($stmt, ':P_OSR_APPLICATION_URI', $consumer['application_uri'], 255); + oci_bind_by_name($stmt, ':P_OSR_APPLICATION_TITLE', $consumer['application_title'], 255); + oci_bind_by_name($stmt, ':P_OSR_APPLICATION_DESCR', $consumer['application_descr'], 255); + oci_bind_by_name($stmt, ':P_OSR_APPLICATION_NOTES', $consumer['application_notes'], 255); + oci_bind_by_name($stmt, ':P_OSR_APPLICATION_TYPE', $consumer['application_type'], 255); + oci_bind_by_name($stmt, ':P_OSR_APPLICATION_COMMERCIAL', $consumer['application_commercial'], 40); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + echo $result; + return $consumer_key; + } + + + + /** + * Delete a consumer key. This removes access to our site for all applications using this key. + * + * @param string consumer_key + * @param int user_id user registering this server + * @param boolean user_is_admin + */ + public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) + { + + // + $sql = "BEGIN SP_DELETE_CONSUMER(:P_CONSUMER_KEY, :P_USER_ID, :P_USER_IS_ADMIN, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 40); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + // + } + + + + /** + * Fetch a consumer of this server, by consumer_key. + * + * @param string consumer_key + * @param int user_id + * @param boolean user_is_admin (optional) + * @exception OAuthException2 when consumer not found + * @return array + */ + public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { + + $sql = "BEGIN SP_GET_CONSUMER(:P_CONSUMER_KEY, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $getConsumerList, null, null, OCI_FETCHSTATEMENT_BY_ROW); + + $consumer = $getConsumerList; + + if (!is_array($consumer)) { + throw new OAuthException2('No consumer with consumer_key "'.$consumer_key.'"'); + } + + $c = array(); + foreach ($consumer as $key => $value) { + $c[substr($key, 4)] = $value; + } + $c['user_id'] = $c['usa_id_ref']; + + if (!$user_is_admin && !empty($c['user_id']) && $c['user_id'] != $user_id) { + throw new OAuthException2('No access to the consumer information for consumer_key "'.$consumer_key.'"'); + } + return $c; + } + + + /** + * Fetch the static consumer key for this provider. The user for the static consumer + * key is NULL (no user, shared key). If the key did not exist then the key is created. + * + * @return string + */ + public function getConsumerStatic () + { + + // + $sql = "BEGIN SP_GET_CONSUMER_STATIC_SELECT(:P_OSR_CONSUMER_KEY, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $consumer, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + + if (empty($consumer)) + { + $consumer_key = 'sc-'.$this->generateKey(true); + + $sql = "BEGIN SP_CONSUMER_STATIC_SAVE(:P_OSR_CONSUMER_KEY, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + + + // Just make sure that if the consumer key is truncated that we get the truncated string + $consumer = $consumer_key; + } + return $consumer; + } + + + /** + * Add an unautorized request token to our server. + * + * @param string consumer_key + * @param array options (eg. token_ttl) + * @return array (token, token_secret) + */ + public function addConsumerRequestToken ( $consumer_key, $options = array() ) + { + $token = $this->generateKey(true); + $secret = $this->generateKey(); + + + if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) + { + $ttl = intval($options['token_ttl']); + } + else + { + $ttl = $this->max_request_token_ttl; + } + + if (!isset($options['oauth_callback'])) { + // 1.0a Compatibility : store callback url associated with request token + $options['oauth_callback']='oob'; + } + $options_oauth_callback =$options['oauth_callback']; + $sql = "BEGIN SP_ADD_CONSUMER_REQUEST_TOKEN(:P_TOKEN_TTL, :P_CONSUMER_KEY, :P_TOKEN, :P_TOKEN_SECRET, :P_CALLBACK_URL, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_TOKEN_TTL', $ttl, 20); + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_TOKEN_SECRET', $secret, 255); + oci_bind_by_name($stmt, ':P_CALLBACK_URL', $options_oauth_callback, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + + + $returnArray= array('token'=>$token, 'token_secret'=>$secret, 'token_ttl'=>$ttl); + return $returnArray; + } + + + /** + * Fetch the consumer request token, by request token. + * + * @param string token + * @return array token and consumer details + */ + public function getConsumerRequestToken ( $token ) + { + + $sql = "BEGIN SP_GET_CONSUMER_REQUEST_TOKEN(:P_TOKEN, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + + oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW); + + return $rs[0]; + } + + + /** + * Delete a consumer token. The token must be a request or authorized token. + * + * @param string token + */ + public function deleteConsumerRequestToken ( $token ) + { + + $sql = "BEGIN SP_DEL_CONSUMER_REQUEST_TOKEN(:P_TOKEN, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Execute the statement + oci_execute($stmt); + } + + + /** + * Upgrade a request token to be an authorized request token. + * + * @param string token + * @param int user_id user authorizing the token + * @param string referrer_host used to set the referrer host for this token, for user feedback + */ + public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) + { + // 1.0a Compatibility : create a token verifier + $verifier = substr(md5(rand()),0,10); + + $sql = "BEGIN SP_AUTH_CONSUMER_REQ_TOKEN(:P_USER_ID, :P_REFERRER_HOST, :P_VERIFIER, :P_TOKEN, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255); + oci_bind_by_name($stmt, ':P_REFERRER_HOST', $referrer_host, 255); + oci_bind_by_name($stmt, ':P_VERIFIER', $verifier, 255); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + + //Execute the statement + oci_execute($stmt); + + return $verifier; + } + + + /** + * Count the consumer access tokens for the given consumer. + * + * @param string consumer_key + * @return int + */ + public function countConsumerAccessTokens ( $consumer_key ) + { + /*$count = $this->query_one(' + SELECT COUNT(ost_id) + FROM oauth_server_token + JOIN oauth_server_registry + ON ost_osr_id_ref = osr_id + WHERE ost_token_type = \'access\' + AND osr_consumer_key = \'%s\' + AND ost_token_ttl >= NOW() + ', $consumer_key); + */ + $sql = "BEGIN SP_COUNT_CONSUMER_ACCESS_TOKEN(:P_CONSUMER_KEY, :P_COUNT, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_COUNT', $count, 20); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + + //Execute the statement + oci_execute($stmt); + + return $count; + } + + + /** + * Exchange an authorized request token for new access token. + * + * @param string token + * @param array options options for the token, token_ttl + * @exception OAuthException2 when token could not be exchanged + * @return array (token, token_secret) + */ + public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) + { + $new_token = $this->generateKey(true); + $new_secret = $this->generateKey(); + + $sql = "BEGIN SP_EXCH_CONS_REQ_FOR_ACC_TOKEN(:P_TOKEN_TTL, :P_NEW_TOKEN, :P_TOKEN, :P_TOKEN_SECRET, :P_VERIFIER, :P_OUT_TOKEN_TTL, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_TOKEN_TTL', $options['token_ttl'], 255); + oci_bind_by_name($stmt, ':P_NEW_TOKEN', $new_token, 255); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_TOKEN_SECRET', $new_secret, 255); + oci_bind_by_name($stmt, ':P_VERIFIER', $options['verifier'], 255); + oci_bind_by_name($stmt, ':P_OUT_TOKEN_TTL', $ttl, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + + //Execute the statement + oci_execute($stmt); + + $ret = array('token' => $new_token, 'token_secret' => $new_secret); + if (is_numeric($ttl)) + { + $ret['token_ttl'] = intval($ttl); + } + return $ret; + } + + + /** + * Fetch the consumer access token, by access token. + * + * @param string token + * @param int user_id + * @exception OAuthException2 when token is not found + * @return array token and consumer details + */ + public function getConsumerAccessToken ( $token, $user_id ) + { + + $sql = "BEGIN SP_GET_CONSUMER_ACCESS_TOKEN(:P_USER_ID, :P_TOKEN, :P_ROWS :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_USER_ID',$user_id, 255); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW); + if (empty($rs)) + { + throw new OAuthException2('No server_token "'.$token.'" for user "'.$user_id.'"'); + } + return $rs; + } + + + /** + * Delete a consumer access token. + * + * @param string token + * @param int user_id + * @param boolean user_is_admin + */ + public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) + { + /*if ($user_is_admin) + { + $this->query(' + DELETE FROM oauth_server_token + WHERE ost_token = \'%s\' + AND ost_token_type = \'access\' + ', $token); + } + else + { + $this->query(' + DELETE FROM oauth_server_token + WHERE ost_token = \'%s\' + AND ost_token_type = \'access\' + AND ost_usa_id_ref = %d + ', $token, $user_id); + }*/ + $sql = "BEGIN SP_DEL_CONSUMER_ACCESS_TOKEN(:P_USER_ID, :P_TOKEN, :P_USER_IS_ADMIN, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 20); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + + //Execute the statement + oci_execute($stmt); + } + + + /** + * Set the ttl of a consumer access token. This is done when the + * server receives a valid request with a xoauth_token_ttl parameter in it. + * + * @param string token + * @param int ttl + */ + public function setConsumerAccessTokenTtl ( $token, $token_ttl ) + { + if ($token_ttl <= 0) + { + // Immediate delete when the token is past its ttl + $this->deleteConsumerAccessToken($token, 0, true); + } + else + { + // Set maximum time to live for this token + + + $sql = "BEGIN SP_SET_CONSUMER_ACC_TOKEN_TTL(:P_TOKEN, :P_TOKEN_TTL, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_TOKEN_TTL', $token_ttl, 20); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + + //Execute the statement + oci_execute($stmt); + } + } + + + /** + * Fetch a list of all consumer keys, secrets etc. + * Returns the public (user_id is null) and the keys owned by the user + * + * @param int user_id + * @return array + */ + public function listConsumers ( $user_id ) + { + + $sql = "BEGIN SP_LIST_CONSUMERS(:P_USER_ID, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW); + + return $rs; + } + + /** + * List of all registered applications. Data returned has not sensitive + * information and therefore is suitable for public displaying. + * + * @param int $begin + * @param int $total + * @return array + */ + public function listConsumerApplications($begin = 0, $total = 25) + { + // TODO + return array(); + } + + /** + * Fetch a list of all consumer tokens accessing the account of the given user. + * + * @param int user_id + * @return array + */ + public function listConsumerTokens ( $user_id ) + { + + $sql = "BEGIN SP_LIST_CONSUMER_TOKENS(:P_USER_ID, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW); + + return $rs; + } + + + /** + * Check an nonce/timestamp combination. Clears any nonce combinations + * that are older than the one received. + * + * @param string consumer_key + * @param string token + * @param int timestamp + * @param string nonce + * @exception OAuthException2 thrown when the timestamp is not in sequence or nonce is not unique + */ + public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) + { + + $sql = "BEGIN SP_CHECK_SERVER_NONCE(:P_CONSUMER_KEY, :P_TOKEN, :P_TIMESTAMP, :P_MAX_TIMESTAMP_SKEW, :P_NONCE, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); + oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); + oci_bind_by_name($stmt, ':P_TIMESTAMP', $timestamp, 255); + oci_bind_by_name($stmt, ':P_MAX_TIMESTAMP_SKEW', $this->max_timestamp_skew, 20); + oci_bind_by_name($stmt, ':P_NONCE', $nonce, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + + //Execute the statement + oci_execute($stmt); + + } + + + /** + * Add an entry to the log table + * + * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token) + * @param string received + * @param string sent + * @param string base_string + * @param string notes + * @param int (optional) user_id + */ + public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) + { + $args = array(); + $ps = array(); + foreach ($keys as $key => $value) + { + $args[] = $value; + $ps[] = "olg_$key = '%s'"; + } + + if (!empty($_SERVER['REMOTE_ADDR'])) + { + $remote_ip = $_SERVER['REMOTE_ADDR']; + } + else if (!empty($_SERVER['REMOTE_IP'])) + { + $remote_ip = $_SERVER['REMOTE_IP']; + } + else + { + $remote_ip = '0.0.0.0'; + } + + // Build the SQL + $olg_received = $this->makeUTF8($received); + $olg_sent = $this->makeUTF8($sent); + $olg_base_string = $base_string; + $olg_notes = $this->makeUTF8($notes); + $olg_usa_id_ref = $user_id; + $olg_remote_ip = $remote_ip; + + + + $sql = "BEGIN SP_ADD_LOG(:P_RECEIVED, :P_SENT, :P_BASE_STRING, :P_NOTES, :P_USA_ID_REF, :P_REMOTE_IP, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_RECEIVED', $olg_received, 255); + oci_bind_by_name($stmt, ':P_SENT', $olg_sent, 255); + oci_bind_by_name($stmt, ':P_BASE_STRING', $olg_base_string, 255); + oci_bind_by_name($stmt, ':P_NOTES', $olg_notes, 255); + oci_bind_by_name($stmt, ':P_USA_ID_REF', $olg_usa_id_ref, 255); + oci_bind_by_name($stmt, ':P_REMOTE_IP', $olg_remote_ip, 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + + //Execute the statement + oci_execute($stmt); + } + + + /** + * Get a page of entries from the log. Returns the last 100 records + * matching the options given. + * + * @param array options + * @param int user_id current user + * @return array log records + */ + public function listLog ( $options, $user_id ) + { + + if (empty($options)) + { + $optionsFlag=NULL; + + } + else + { + $optionsFlag=1; + + } + + $sql = "BEGIN SP_LIST_LOG(:P_OPTION_FLAG, :P_USA_ID, :P_OSR_CONSUMER_KEY, :P_OCR_CONSUMER_KEY, :P_OST_TOKEN, :P_OCT_TOKEN, :P_ROWS, :P_RESULT); END;"; + + // parse sql + $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); + + // Bind In and Out Variables + oci_bind_by_name($stmt, ':P_OPTION_FLAG', $optionsFlag, 255); + oci_bind_by_name($stmt, ':P_USA_ID', $user_id, 40); + oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $options['osr_consumer_key'], 255); + oci_bind_by_name($stmt, ':P_OCR_CONSUMER_KEY', $options['ocr_consumer_key'], 255); + oci_bind_by_name($stmt, ':P_OST_TOKEN', $options['ost_token'], 255); + oci_bind_by_name($stmt, ':P_OCT_TOKEN', $options['oct_token'], 255); + oci_bind_by_name($stmt, ':P_RESULT', $result, 20); + + //Bind the ref cursor + $p_row = oci_new_cursor($this->conn); + oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); + + //Execute the statement + oci_execute($stmt); + + // treat the ref cursor as a statement resource + oci_execute($p_row, OCI_DEFAULT); + oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW); + + return $rs; + } + + /** + * Initialise the database + */ + public function install () + { + require_once dirname(__FILE__) . '/oracle/install.php'; + } +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStorePDO.php b/3rdparty/oauth-php/library/store/OAuthStorePDO.php new file mode 100644 index 0000000000..821d79b994 --- /dev/null +++ b/3rdparty/oauth-php/library/store/OAuthStorePDO.php @@ -0,0 +1,274 @@ + Based on code by Marc Worrell + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +require_once dirname(__FILE__) . '/OAuthStoreSQL.php'; + + +class OAuthStorePDO extends OAuthStoreSQL +{ + private $conn; // PDO connection + private $lastaffectedrows; + + /** + * Construct the OAuthStorePDO. + * In the options you have to supply either: + * - dsn, username, password and database (for a new PDO connection) + * - conn (for the connection to be used) + * + * @param array options + */ + function __construct ( $options = array() ) + { + if (isset($options['conn'])) + { + $this->conn = $options['conn']; + } + else if (isset($options['dsn'])) + { + try + { + $this->conn = new PDO($options['dsn'], $options['username'], @$options['password']); + } + catch (PDOException $e) + { + throw new OAuthException2('Could not connect to PDO database: ' . $e->getMessage()); + } + + $this->query('set character set utf8'); + } + } + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + */ + protected function query ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + try + { + $this->lastaffectedrows = $this->conn->exec($sql); + if ($this->lastaffectedrows === FALSE) { + $this->sql_errcheck($sql); + } + } + catch (PDOException $e) + { + $this->sql_errcheck($sql); + } + } + + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_all_assoc ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + $result = array(); + + try + { + $stmt = $this->conn->query($sql); + + $result = $stmt->fetchAll(PDO::FETCH_ASSOC); + } + catch (PDOException $e) + { + $this->sql_errcheck($sql); + } + return $result; + } + + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_row_assoc ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + $result = $this->query_all_assoc($sql); + $val = array_pop($result); + return $val; + } + + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_row ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + try + { + $all = $this->conn->query($sql, PDO::FETCH_NUM); + $row = array(); + foreach ($all as $r) { + $row = $r; + break; + } + } + catch (PDOException $e) + { + $this->sql_errcheck($sql); + } + return $row; + } + + + /** + * Perform a query, return the first column of the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return mixed + */ + protected function query_one ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + $row = $this->query_row($sql); + $val = array_pop($row); + return $val; + } + + + /** + * Return the number of rows affected in the last query + */ + protected function query_affected_rows () + { + return $this->lastaffectedrows; + } + + + /** + * Return the id of the last inserted row + * + * @return int + */ + protected function query_insert_id () + { + return $this->conn->lastInsertId(); + } + + + protected function sql_printf ( $args ) + { + $sql = array_shift($args); + if (count($args) == 1 && is_array($args[0])) + { + $args = $args[0]; + } + $args = array_map(array($this, 'sql_escape_string'), $args); + return vsprintf($sql, $args); + } + + + protected function sql_escape_string ( $s ) + { + if (is_string($s)) + { + $s = $this->conn->quote($s); + // kludge. Quote already adds quotes, and this conflicts with OAuthStoreSQL. + // so remove the quotes + $len = mb_strlen($s); + if ($len == 0) + return $s; + + $startcut = 0; + while (isset($s[$startcut]) && $s[$startcut] == '\'') + $startcut++; + + $endcut = $len-1; + while (isset($s[$endcut]) && $s[$endcut] == '\'') + $endcut--; + + $s = mb_substr($s, $startcut, $endcut-$startcut+1); + return $s; + } + else if (is_null($s)) + { + return NULL; + } + else if (is_bool($s)) + { + return intval($s); + } + else if (is_int($s) || is_float($s)) + { + return $s; + } + else + { + return $this->conn->quote(strval($s)); + } + } + + + protected function sql_errcheck ( $sql ) + { + $msg = "SQL Error in OAuthStoreMySQL: ". print_r($this->conn->errorInfo(), true) ."\n\n" . $sql; + $backtrace = debug_backtrace(); + $msg .= "\n\nAt file " . $backtrace[1]['file'] . ", line " . $backtrace[1]['line']; + throw new OAuthException2($msg); + } + + /** + * Initialise the database + */ + public function install () + { + // TODO: this depends on mysql extension + require_once dirname(__FILE__) . '/mysql/install.php'; + } + +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStorePostgreSQL.php b/3rdparty/oauth-php/library/store/OAuthStorePostgreSQL.php new file mode 100644 index 0000000000..04b9f04662 --- /dev/null +++ b/3rdparty/oauth-php/library/store/OAuthStorePostgreSQL.php @@ -0,0 +1,1957 @@ + + * @link http://elma.fr + * + * @Id 2010-10-22 10:07:18 ndelanoe $ + * @version $Id: OAuthStorePostgreSQL.php 175 2010-11-24 19:52:24Z brunobg@corollarium.com $ + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + **/ + +require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php'; + + +class OAuthStorePostgreSQL extends OAuthStoreAbstract +{ + /** + * Maximum delta a timestamp may be off from a previous timestamp. + * Allows multiple consumers with some clock skew to work with the same token. + * Unit is seconds, default max skew is 10 minutes. + */ + protected $max_timestamp_skew = 600; + + /** + * Default ttl for request tokens + */ + protected $max_request_token_ttl = 3600; + + /** + * Number of affected rowsby the last queries + */ + private $_lastAffectedRows = 0; + + public function install() + { + throw new OAuthException2('Not yet implemented, see postgresql/pgsql.sql'); + } + + /** + * Construct the OAuthStorePostgrSQL. + * In the options you have to supply either: + * - server, username, password and database (for a pg_connect) + * - connectionString (for a pg_connect) + * - conn (for the connection to be used) + * + * @param array options + */ + function __construct ( $options = array() ) + { + if (isset($options['conn'])) + { + $this->conn = $options['conn']; + } + else + { + if (isset($options['server'])) + { + $host = $options['server']; + $user = $options['username']; + $dbname = $options['database']; + + $connectionString = sprintf('host=%s dbname=%s user=%s', $host, $dbname, $user); + + if (isset($options['password'])) + { + $connectionString .= ' password=' . $options['password']; + } + + $this->conn = pg_connect($connectionString); + } + elseif (isset($options['connectionString'])) + { + $this->conn = pg_connect($options['connectionString']); + } + else { + + // Try the default pg connect + $this->conn = pg_connect(); + } + + if ($this->conn === false) + { + throw new OAuthException2('Could not connect to PostgresSQL database'); + } + } + } + + /** + * Find stored credentials for the consumer key and token. Used by an OAuth server + * when verifying an OAuth request. + * + * @param string consumer_key + * @param string token + * @param string token_type false, 'request' or 'access' + * @exception OAuthException2 when no secrets where found + * @return array assoc (consumer_secret, token_secret, osr_id, ost_id, user_id) + */ + public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ) + { + if ($token_type === false) + { + $rs = $this->query_row_assoc(' + SELECT osr_id, + osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret + FROM oauth_server_registry + WHERE osr_consumer_key = \'%s\' + AND osr_enabled = \'1\' + ', + $consumer_key); + + if ($rs) + { + $rs['token'] = false; + $rs['token_secret'] = false; + $rs['user_id'] = false; + $rs['ost_id'] = false; + } + } + else + { + $rs = $this->query_row_assoc(' + SELECT osr_id, + ost_id, + ost_usa_id_ref as user_id, + osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret, + ost_token as token, + ost_token_secret as token_secret + FROM oauth_server_registry + JOIN oauth_server_token + ON ost_osr_id_ref = osr_id + WHERE ost_token_type = \'%s\' + AND osr_consumer_key = \'%s\' + AND ost_token = \'%s\' + AND osr_enabled = \'1\' + AND ost_token_ttl >= NOW() + ', + $token_type, $consumer_key, $token); + } + + if (empty($rs)) + { + throw new OAuthException2('The consumer_key "'.$consumer_key.'" token "'.$token.'" combination does not exist or is not enabled.'); + } + return $rs; + } + + /** + * Find the server details for signing a request, always looks for an access token. + * The returned credentials depend on which local user is making the request. + * + * The consumer_key must belong to the user or be public (user id is null) + * + * For signing we need all of the following: + * + * consumer_key consumer key associated with the server + * consumer_secret consumer secret associated with this server + * token access token associated with this server + * token_secret secret for the access token + * signature_methods signing methods supported by the server (array) + * + * @todo filter on token type (we should know how and with what to sign this request, and there might be old access tokens) + * @param string uri uri of the server + * @param int user_id id of the logged on user + * @param string name (optional) name of the token (case sensitive) + * @exception OAuthException2 when no credentials found + * @return array + */ + public function getSecretsForSignature ( $uri, $user_id, $name = '' ) + { + // Find a consumer key and token for the given uri + $ps = parse_url($uri); + $host = isset($ps['host']) ? $ps['host'] : 'localhost'; + $path = isset($ps['path']) ? $ps['path'] : ''; + + if (empty($path) || substr($path, -1) != '/') + { + $path .= '/'; + } + + // The owner of the consumer_key is either the user or nobody (public consumer key) + $secrets = $this->query_row_assoc(' + SELECT ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + oct_token as token, + oct_token_secret as token_secret, + ocr_signature_methods as signature_methods + FROM oauth_consumer_registry + JOIN oauth_consumer_token ON oct_ocr_id_ref = ocr_id + WHERE ocr_server_uri_host = \'%s\' + AND ocr_server_uri_path = SUBSTR(\'%s\', 1, LENGTH(ocr_server_uri_path)) + AND (ocr_usa_id_ref = \'%s\' OR ocr_usa_id_ref IS NULL) + AND oct_usa_id_ref = \'%d\' + AND oct_token_type = \'access\' + AND oct_name = \'%s\' + AND oct_token_ttl >= NOW() + ORDER BY ocr_usa_id_ref DESC, ocr_consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC + LIMIT 1 + ', $host, $path, $user_id, $user_id, $name + ); + + if (empty($secrets)) + { + throw new OAuthException2('No server tokens available for '.$uri); + } + $secrets['signature_methods'] = explode(',', $secrets['signature_methods']); + return $secrets; + } + + /** + * Get the token and token secret we obtained from a server. + * + * @param string consumer_key + * @param string token + * @param string token_type + * @param int user_id the user owning the token + * @param string name optional name for a named token + * @exception OAuthException2 when no credentials found + * @return array + */ + public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' ) + { + if ($token_type != 'request' && $token_type != 'access') + { + throw new OAuthException2('Unkown token type "'.$token_type.'", must be either "request" or "access"'); + } + + // Take the most recent token of the given type + $r = $this->query_row_assoc(' + SELECT ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + oct_token as token, + oct_token_secret as token_secret, + oct_name as token_name, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri, + CASE WHEN oct_token_ttl >= \'9999-12-31\' THEN NULL ELSE oct_token_ttl - NOW() END as token_ttl + FROM oauth_consumer_registry + JOIN oauth_consumer_token + ON oct_ocr_id_ref = ocr_id + WHERE ocr_consumer_key = \'%s\' + AND oct_token_type = \'%s\' + AND oct_token = \'%s\' + AND oct_usa_id_ref = \'%d\' + AND oct_token_ttl >= NOW() + ', $consumer_key, $token_type, $token, $user_id + ); + + if (empty($r)) + { + throw new OAuthException2('Could not find a "'.$token_type.'" token for consumer "'.$consumer_key.'" and user '.$user_id); + } + if (isset($r['signature_methods']) && !empty($r['signature_methods'])) + { + $r['signature_methods'] = explode(',',$r['signature_methods']); + } + else + { + $r['signature_methods'] = array(); + } + return $r; + } + + + /** + * Add a request token we obtained from a server. + * + * @todo remove old tokens for this user and this ocr_id + * @param string consumer_key key of the server in the consumer registry + * @param string token_type one of 'request' or 'access' + * @param string token + * @param string token_secret + * @param int user_id the user owning the token + * @param array options extra options, name and token_ttl + * @exception OAuthException2 when server is not known + * @exception OAuthException2 when we received a duplicate token + */ + public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) + { + if ($token_type != 'request' && $token_type != 'access') + { + throw new OAuthException2('Unknown token type "'.$token_type.'", must be either "request" or "access"'); + } + + // Maximum time to live for this token + if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) + { + $ttl = 'NOW() + INTERVAL \''.intval($options['token_ttl']).' SECOND\''; + } + else if ($token_type == 'request') + { + $ttl = 'NOW() + INTERVAL \''.$this->max_request_token_ttl.' SECOND\''; + } + else + { + $ttl = "'9999-12-31'"; + } + + if (isset($options['server_uri'])) + { + $ocr_id = $this->query_one(' + SELECT ocr_id + FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND ocr_usa_id_ref = \'%d\' + AND ocr_server_uri = \'%s\' + ', $consumer_key, $user_id, $options['server_uri']); + } + else + { + $ocr_id = $this->query_one(' + SELECT ocr_id + FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND ocr_usa_id_ref = \'%d\' + ', $consumer_key, $user_id); + } + + if (empty($ocr_id)) + { + throw new OAuthException2('No server associated with consumer_key "'.$consumer_key.'"'); + } + + // Named tokens, unique per user/consumer key + if (isset($options['name']) && $options['name'] != '') + { + $name = $options['name']; + } + else + { + $name = ''; + } + + // Delete any old tokens with the same type and name for this user/server combination + $this->query(' + DELETE FROM oauth_consumer_token + WHERE oct_ocr_id_ref = %d + AND oct_usa_id_ref = \'%d\' + AND oct_token_type::text = LOWER(\'%s\')::text + AND oct_name = \'%s\' + ', + $ocr_id, + $user_id, + $token_type, + $name); + + // Insert the new token + $this->query(' + INSERT INTO + oauth_consumer_token( + oct_ocr_id_ref, + oct_usa_id_ref, + oct_name, + oct_token, + oct_token_secret, + oct_token_type, + oct_timestamp, + oct_token_ttl + ) + VALUES (%d,%d,\'%s\',\'%s\',\'%s\',\'%s\',NOW(),'.$ttl.')', + $ocr_id, + $user_id, + $name, + $token, + $token_secret, + $token_type); + + if (!$this->query_affected_rows()) + { + throw new OAuthException2('Received duplicate token "'.$token.'" for the same consumer_key "'.$consumer_key.'"'); + } + } + + /** + * Delete a server key. This removes access to that site. + * + * @param string consumer_key + * @param int user_id user registering this server + * @param boolean user_is_admin + */ + public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) + { + if ($user_is_admin) + { + $this->query(' + DELETE FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) + ', $consumer_key, $user_id); + } + else + { + $this->query(' + DELETE FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND ocr_usa_id_ref = \'%d\' + ', $consumer_key, $user_id); + } + } + + + /** + * Get a server from the consumer registry using the consumer key + * + * @param string consumer_key + * @param int user_id + * @param boolean user_is_admin (optional) + * @exception OAuthException2 when server is not found + * @return array + */ + public function getServer ( $consumer_key, $user_id, $user_is_admin = false ) + { + $r = $this->query_row_assoc(' + SELECT ocr_id as id, + ocr_usa_id_ref as user_id, + ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri + FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) + ', $consumer_key, $user_id); + + if (empty($r)) + { + throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" has been registered (for this user)'); + } + + if (isset($r['signature_methods']) && !empty($r['signature_methods'])) + { + $r['signature_methods'] = explode(',',$r['signature_methods']); + } + else + { + $r['signature_methods'] = array(); + } + return $r; + } + + + /** + * Find the server details that might be used for a request + * + * The consumer_key must belong to the user or be public (user id is null) + * + * @param string uri uri of the server + * @param int user_id id of the logged on user + * @exception OAuthException2 when no credentials found + * @return array + */ + public function getServerForUri ( $uri, $user_id ) + { + // Find a consumer key and token for the given uri + $ps = parse_url($uri); + $host = isset($ps['host']) ? $ps['host'] : 'localhost'; + $path = isset($ps['path']) ? $ps['path'] : ''; + + if (empty($path) || substr($path, -1) != '/') + { + $path .= '/'; + } + + // The owner of the consumer_key is either the user or nobody (public consumer key) + $server = $this->query_row_assoc(' + SELECT ocr_id as id, + ocr_usa_id_ref as user_id, + ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri + FROM oauth_consumer_registry + WHERE ocr_server_uri_host = \'%s\' + AND ocr_server_uri_path = SUBSTR(\'%s\', 1, LENGTH(ocr_server_uri_path)) + AND (ocr_usa_id_ref = \'%s\' OR ocr_usa_id_ref IS NULL) + ORDER BY ocr_usa_id_ref DESC, consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC + LIMIT 1 + ', $host, $path, $user_id + ); + + if (empty($server)) + { + throw new OAuthException2('No server available for '.$uri); + } + $server['signature_methods'] = explode(',', $server['signature_methods']); + return $server; + } + + /** + * Get a list of all server token this user has access to. + * + * @param int usr_id + * @return array + */ + public function listServerTokens ( $user_id ) + { + $ts = $this->query_all_assoc(' + SELECT ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + oct_id as token_id, + oct_token as token, + oct_token_secret as token_secret, + oct_usa_id_ref as user_id, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_server_uri_host as server_uri_host, + ocr_server_uri_path as server_uri_path, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri, + oct_timestamp as timestamp + FROM oauth_consumer_registry + JOIN oauth_consumer_token + ON oct_ocr_id_ref = ocr_id + WHERE oct_usa_id_ref = \'%d\' + AND oct_token_type = \'access\' + AND oct_token_ttl >= NOW() + ORDER BY ocr_server_uri_host, ocr_server_uri_path + ', $user_id); + return $ts; + } + + /** + * Count how many tokens we have for the given server + * + * @param string consumer_key + * @return int + */ + public function countServerTokens ( $consumer_key ) + { + $count = $this->query_one(' + SELECT COUNT(oct_id) + FROM oauth_consumer_token + JOIN oauth_consumer_registry + ON oct_ocr_id_ref = ocr_id + WHERE oct_token_type = \'access\' + AND ocr_consumer_key = \'%s\' + AND oct_token_ttl >= NOW() + ', $consumer_key); + + return $count; + } + + /** + * Get a specific server token for the given user + * + * @param string consumer_key + * @param string token + * @param int user_id + * @exception OAuthException2 when no such token found + * @return array + */ + public function getServerToken ( $consumer_key, $token, $user_id ) + { + $ts = $this->query_row_assoc(' + SELECT ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + oct_token as token, + oct_token_secret as token_secret, + oct_usa_id_ref as usr_id, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_server_uri_host as server_uri_host, + ocr_server_uri_path as server_uri_path, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri, + oct_timestamp as timestamp + FROM oauth_consumer_registry + JOIN oauth_consumer_token + ON oct_ocr_id_ref = ocr_id + WHERE ocr_consumer_key = \'%s\' + AND oct_usa_id_ref = \'%d\' + AND oct_token_type = \'access\' + AND oct_token = \'%s\' + AND oct_token_ttl >= NOW() + ', $consumer_key, $user_id, $token); + + if (empty($ts)) + { + throw new OAuthException2('No such consumer key ('.$consumer_key.') and token ('.$token.') combination for user "'.$user_id.'"'); + } + return $ts; + } + + + /** + * Delete a token we obtained from a server. + * + * @param string consumer_key + * @param string token + * @param int user_id + * @param boolean user_is_admin + */ + public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) + { + if ($user_is_admin) + { + $this->query(' + DELETE FROM oauth_consumer_token + USING oauth_consumer_registry + WHERE + oct_ocr_id_ref = ocr_id + AND ocr_consumer_key = \'%s\' + AND oct_token = \'%s\' + ', $consumer_key, $token); + } + else + { + $this->query(' + DELETE FROM oauth_consumer_token + USING oauth_consumer_registry + WHERE + oct_ocr_id_ref = ocr_id + AND ocr_consumer_key = \'%s\' + AND oct_token = \'%s\' + AND oct_usa_id_ref = \'%d\' + ', $consumer_key, $token, $user_id); + } + } + + /** + * Set the ttl of a server access token. This is done when the + * server receives a valid request with a xoauth_token_ttl parameter in it. + * + * @param string consumer_key + * @param string token + * @param int token_ttl + */ + public function setServerTokenTtl ( $consumer_key, $token, $token_ttl ) + { + if ($token_ttl <= 0) + { + // Immediate delete when the token is past its ttl + $this->deleteServerToken($consumer_key, $token, 0, true); + } + else + { + // Set maximum time to live for this token + $this->query(' + UPDATE oauth_consumer_token + SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\') + WHERE ocr_consumer_key = \'%s\' + AND oct_ocr_id_ref = ocr_id + AND oct_token = \'%s\' + ', $token_ttl, $consumer_key, $token); + + // Set maximum time to live for this token + $this->query(' + UPDATE oauth_consumer_registry + SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\') + WHERE ocr_consumer_key = \'%s\' + AND oct_ocr_id_ref = ocr_id + AND oct_token = \'%s\' + ', $token_ttl, $consumer_key, $token); + } + } + + /** + * Get a list of all consumers from the consumer registry. + * The consumer keys belong to the user or are public (user id is null) + * + * @param string q query term + * @param int user_id + * @return array + */ + public function listServers ( $q = '', $user_id ) + { + $q = trim(str_replace('%', '', $q)); + $args = array(); + + if (!empty($q)) + { + $where = ' WHERE ( ocr_consumer_key like \'%%%s%%\' + OR ocr_server_uri like \'%%%s%%\' + OR ocr_server_uri_host like \'%%%s%%\' + OR ocr_server_uri_path like \'%%%s%%\') + AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) + '; + + $args[] = $q; + $args[] = $q; + $args[] = $q; + $args[] = $q; + $args[] = $user_id; + } + else + { + $where = ' WHERE ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL'; + $args[] = $user_id; + } + + $servers = $this->query_all_assoc(' + SELECT ocr_id as id, + ocr_usa_id_ref as user_id, + ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_server_uri_host as server_uri_host, + ocr_server_uri_path as server_uri_path, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri + FROM oauth_consumer_registry + '.$where.' + ORDER BY ocr_server_uri_host, ocr_server_uri_path + ', $args); + return $servers; + } + + /** + * Register or update a server for our site (we will be the consumer) + * + * (This is the registry at the consumers, registering servers ;-) ) + * + * @param array server + * @param int user_id user registering this server + * @param boolean user_is_admin + * @exception OAuthException2 when fields are missing or on duplicate consumer_key + * @return consumer_key + */ + public function updateServer ( $server, $user_id, $user_is_admin = false ) + { + foreach (array('consumer_key', 'server_uri') as $f) + { + if (empty($server[$f])) + { + throw new OAuthException2('The field "'.$f.'" must be set and non empty'); + } + } + + if (!empty($server['id'])) + { + $exists = $this->query_one(' + SELECT ocr_id + FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND ocr_id <> %d + AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) + ', $server['consumer_key'], $server['id'], $user_id); + } + else + { + $exists = $this->query_one(' + SELECT ocr_id + FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) + ', $server['consumer_key'], $user_id); + } + + if ($exists) + { + throw new OAuthException2('The server with key "'.$server['consumer_key'].'" has already been registered'); + } + + $parts = parse_url($server['server_uri']); + $host = (isset($parts['host']) ? $parts['host'] : 'localhost'); + $path = (isset($parts['path']) ? $parts['path'] : '/'); + + if (isset($server['signature_methods'])) + { + if (is_array($server['signature_methods'])) + { + $server['signature_methods'] = strtoupper(implode(',', $server['signature_methods'])); + } + } + else + { + $server['signature_methods'] = ''; + } + + // When the user is an admin, then the user can update the user_id of this record + if ($user_is_admin && array_key_exists('user_id', $server)) + { + if (is_null($server['user_id'])) + { + $update_user = ', ocr_usa_id_ref = NULL'; + } + else + { + $update_user = ', ocr_usa_id_ref = \''. intval($server['user_id']) . '\''; + } + } + else + { + $update_user = ''; + } + + if (!empty($server['id'])) + { + // Check if the current user can update this server definition + if (!$user_is_admin) + { + $ocr_usa_id_ref = $this->query_one(' + SELECT ocr_usa_id_ref + FROM oauth_consumer_registry + WHERE ocr_id = %d + ', $server['id']); + + if ($ocr_usa_id_ref != $user_id) + { + throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this server'); + } + } + + // Update the consumer registration + $this->query(' + UPDATE oauth_consumer_registry + SET ocr_consumer_key = \'%s\', + ocr_consumer_secret = \'%s\', + ocr_server_uri = \'%s\', + ocr_server_uri_host = \'%s\', + ocr_server_uri_path = \'%s\', + ocr_timestamp = NOW(), + ocr_request_token_uri = \'%s\', + ocr_authorize_uri = \'%s\', + ocr_access_token_uri = \'%s\', + ocr_signature_methods = \'%s\' + '.$update_user.' + WHERE ocr_id = %d + ', + $server['consumer_key'], + $server['consumer_secret'], + $server['server_uri'], + strtolower($host), + $path, + isset($server['request_token_uri']) ? $server['request_token_uri'] : '', + isset($server['authorize_uri']) ? $server['authorize_uri'] : '', + isset($server['access_token_uri']) ? $server['access_token_uri'] : '', + $server['signature_methods'], + $server['id'] + ); + } + else + { + $update_user_field = ''; + $update_user_value = ''; + if (empty($update_user)) + { + // Per default the user owning the key is the user registering the key + $update_user_field = ', ocr_usa_id_ref'; + $update_user_value = ', ' . intval($user_id); + } + + $this->query(' + INSERT INTO oauth_consumer_registry ( + ocr_consumer_key , + ocr_consumer_secret , + ocr_server_uri , + ocr_server_uri_host , + ocr_server_uri_path , + ocr_timestamp , + ocr_request_token_uri, + ocr_authorize_uri , + ocr_access_token_uri , + ocr_signature_methods' . $update_user_field . ' + ) + VALUES (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', NOW(), \'%s\', \'%s\', \'%s\', \'%s\''. $update_user_value . ')', + $server['consumer_key'], + $server['consumer_secret'], + $server['server_uri'], + strtolower($host), + $path, + isset($server['request_token_uri']) ? $server['request_token_uri'] : '', + isset($server['authorize_uri']) ? $server['authorize_uri'] : '', + isset($server['access_token_uri']) ? $server['access_token_uri'] : '', + $server['signature_methods'] + ); + + $ocr_id = $this->query_insert_id('oauth_consumer_registry', 'ocr_id'); + } + return $server['consumer_key']; + } + + + /** + * Insert/update a new consumer with this server (we will be the server) + * When this is a new consumer, then also generate the consumer key and secret. + * Never updates the consumer key and secret. + * When the id is set, then the key and secret must correspond to the entry + * being updated. + * + * (This is the registry at the server, registering consumers ;-) ) + * + * @param array consumer + * @param int user_id user registering this consumer + * @param boolean user_is_admin + * @return string consumer key + */ + public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) + { + if (!$user_is_admin) + { + foreach (array('requester_name', 'requester_email') as $f) + { + if (empty($consumer[$f])) + { + throw new OAuthException2('The field "'.$f.'" must be set and non empty'); + } + } + } + + if (!empty($consumer['id'])) + { + if (empty($consumer['consumer_key'])) + { + throw new OAuthException2('The field "consumer_key" must be set and non empty'); + } + if (!$user_is_admin && empty($consumer['consumer_secret'])) + { + throw new OAuthException2('The field "consumer_secret" must be set and non empty'); + } + + // Check if the current user can update this server definition + if (!$user_is_admin) + { + $osr_usa_id_ref = $this->query_one(' + SELECT osr_usa_id_ref + FROM oauth_server_registry + WHERE osr_id = %d + ', $consumer['id']); + + if ($osr_usa_id_ref != $user_id) + { + throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this consumer'); + } + } + else + { + // User is an admin, allow a key owner to be changed or key to be shared + if (array_key_exists('user_id',$consumer)) + { + if (is_null($consumer['user_id'])) + { + $this->query(' + UPDATE oauth_server_registry + SET osr_usa_id_ref = NULL + WHERE osr_id = %d + ', $consumer['id']); + } + else + { + $this->query(' + UPDATE oauth_server_registry + SET osr_usa_id_ref = \'%d\' + WHERE osr_id = %d + ', $consumer['user_id'], $consumer['id']); + } + } + } + + $this->query(' + UPDATE oauth_server_registry + SET osr_requester_name = \'%s\', + osr_requester_email = \'%s\', + osr_callback_uri = \'%s\', + osr_application_uri = \'%s\', + osr_application_title = \'%s\', + osr_application_descr = \'%s\', + osr_application_notes = \'%s\', + osr_application_type = \'%s\', + osr_application_commercial = IF(%d,\'1\',\'0\'), + osr_timestamp = NOW() + WHERE osr_id = %d + AND osr_consumer_key = \'%s\' + AND osr_consumer_secret = \'%s\' + ', + $consumer['requester_name'], + $consumer['requester_email'], + isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '', + isset($consumer['application_uri']) ? $consumer['application_uri'] : '', + isset($consumer['application_title']) ? $consumer['application_title'] : '', + isset($consumer['application_descr']) ? $consumer['application_descr'] : '', + isset($consumer['application_notes']) ? $consumer['application_notes'] : '', + isset($consumer['application_type']) ? $consumer['application_type'] : '', + isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0, + $consumer['id'], + $consumer['consumer_key'], + $consumer['consumer_secret'] + ); + + + $consumer_key = $consumer['consumer_key']; + } + else + { + $consumer_key = $this->generateKey(true); + $consumer_secret= $this->generateKey(); + + // When the user is an admin, then the user can be forced to something else that the user + if ($user_is_admin && array_key_exists('user_id',$consumer)) + { + if (is_null($consumer['user_id'])) + { + $owner_id = 'NULL'; + } + else + { + $owner_id = intval($consumer['user_id']); + } + } + else + { + // No admin, take the user id as the owner id. + $owner_id = intval($user_id); + } + + $this->query(' + INSERT INTO oauth_server_registry ( + osr_enabled, + osr_status, + osr_usa_id_ref, + osr_consumer_key, + osr_consumer_secret, + osr_requester_name, + osr_requester_email, + osr_callback_uri, + osr_application_uri, + osr_application_title, + osr_application_descr, + osr_application_notes, + osr_application_type, + osr_application_commercial, + osr_timestamp, + osr_issue_date + ) + VALUES (\'1\', \'active\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%d\', NOW(), NOW()) + ', + $owner_id, + $consumer_key, + $consumer_secret, + $consumer['requester_name'], + $consumer['requester_email'], + isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '', + isset($consumer['application_uri']) ? $consumer['application_uri'] : '', + isset($consumer['application_title']) ? $consumer['application_title'] : '', + isset($consumer['application_descr']) ? $consumer['application_descr'] : '', + isset($consumer['application_notes']) ? $consumer['application_notes'] : '', + isset($consumer['application_type']) ? $consumer['application_type'] : '', + isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0 + ); + } + return $consumer_key; + + } + + /** + * Delete a consumer key. This removes access to our site for all applications using this key. + * + * @param string consumer_key + * @param int user_id user registering this server + * @param boolean user_is_admin + */ + public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) + { + if ($user_is_admin) + { + $this->query(' + DELETE FROM oauth_server_registry + WHERE osr_consumer_key = \'%s\' + AND (osr_usa_id_ref = \'%d\' OR osr_usa_id_ref IS NULL) + ', $consumer_key, $user_id); + } + else + { + $this->query(' + DELETE FROM oauth_server_registry + WHERE osr_consumer_key = \'%s\' + AND osr_usa_id_ref = \'%d\' + ', $consumer_key, $user_id); + } + } + + /** + * Fetch a consumer of this server, by consumer_key. + * + * @param string consumer_key + * @param int user_id + * @param boolean user_is_admin (optional) + * @exception OAuthException2 when consumer not found + * @return array + */ + public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) + { + $consumer = $this->query_row_assoc(' + SELECT * + FROM oauth_server_registry + WHERE osr_consumer_key = \'%s\' + ', $consumer_key); + + if (!is_array($consumer)) + { + throw new OAuthException2('No consumer with consumer_key "'.$consumer_key.'"'); + } + + $c = array(); + foreach ($consumer as $key => $value) + { + $c[substr($key, 4)] = $value; + } + $c['user_id'] = $c['usa_id_ref']; + + if (!$user_is_admin && !empty($c['user_id']) && $c['user_id'] != $user_id) + { + throw new OAuthException2('No access to the consumer information for consumer_key "'.$consumer_key.'"'); + } + return $c; + } + + + /** + * Fetch the static consumer key for this provider. The user for the static consumer + * key is NULL (no user, shared key). If the key did not exist then the key is created. + * + * @return string + */ + public function getConsumerStatic () + { + $consumer = $this->query_one(' + SELECT osr_consumer_key + FROM oauth_server_registry + WHERE osr_consumer_key LIKE \'sc-%%\' + AND osr_usa_id_ref IS NULL + '); + + if (empty($consumer)) + { + $consumer_key = 'sc-'.$this->generateKey(true); + $this->query(' + INSERT INTO oauth_server_registry ( + osr_enabled, + osr_status, + osr_usa_id_ref, + osr_consumer_key, + osr_consumer_secret, + osr_requester_name, + osr_requester_email, + osr_callback_uri, + osr_application_uri, + osr_application_title, + osr_application_descr, + osr_application_notes, + osr_application_type, + osr_application_commercial, + osr_timestamp, + osr_issue_date + ) + VALUES (\'1\',\'active\', NULL, \'%s\', \'\', \'\', \'\', \'\', \'\', \'Static shared consumer key\', \'\', \'Static shared consumer key\', \'\', 0, NOW(), NOW()) + ', + $consumer_key + ); + + // Just make sure that if the consumer key is truncated that we get the truncated string + $consumer = $this->getConsumerStatic(); + } + return $consumer; + } + + /** + * Add an unautorized request token to our server. + * + * @param string consumer_key + * @param array options (eg. token_ttl) + * @return array (token, token_secret) + */ + public function addConsumerRequestToken ( $consumer_key, $options = array() ) + { + $token = $this->generateKey(true); + $secret = $this->generateKey(); + $osr_id = $this->query_one(' + SELECT osr_id + FROM oauth_server_registry + WHERE osr_consumer_key = \'%s\' + AND osr_enabled = \'1\' + ', $consumer_key); + + if (!$osr_id) + { + throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" or consumer_key is disabled'); + } + + if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) + { + $ttl = intval($options['token_ttl']); + } + else + { + $ttl = $this->max_request_token_ttl; + } + + if (!isset($options['oauth_callback'])) { + // 1.0a Compatibility : store callback url associated with request token + $options['oauth_callback']='oob'; + } + + $this->query(' + INSERT INTO oauth_server_token ( + ost_osr_id_ref, + ost_usa_id_ref, + ost_token, + ost_token_secret, + ost_token_type, + ost_token_ttl, + ost_callback_url + ) + VALUES (%d, \'1\', \'%s\', \'%s\', \'request\', NOW() + INTERVAL \'%d SECOND\', \'%s\')', + $osr_id, $token, $secret, $ttl, $options['oauth_callback']); + + return array('token'=>$token, 'token_secret'=>$secret, 'token_ttl'=>$ttl); + } + + /** + * Fetch the consumer request token, by request token. + * + * @param string token + * @return array token and consumer details + */ + public function getConsumerRequestToken ( $token ) + { + $rs = $this->query_row_assoc(' + SELECT ost_token as token, + ost_token_secret as token_secret, + osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret, + ost_token_type as token_type, + ost_callback_url as callback_url, + osr_application_title as application_title, + osr_application_descr as application_descr, + osr_application_uri as application_uri + FROM oauth_server_token + JOIN oauth_server_registry + ON ost_osr_id_ref = osr_id + WHERE ost_token_type = \'request\' + AND ost_token = \'%s\' + AND ost_token_ttl >= NOW() + ', $token); + + return $rs; + } + + /** + * Delete a consumer token. The token must be a request or authorized token. + * + * @param string token + */ + public function deleteConsumerRequestToken ( $token ) + { + $this->query(' + DELETE FROM oauth_server_token + WHERE ost_token = \'%s\' + AND ost_token_type = \'request\' + ', $token); + } + + /** + * Upgrade a request token to be an authorized request token. + * + * @param string token + * @param int user_id user authorizing the token + * @param string referrer_host used to set the referrer host for this token, for user feedback + */ + public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) + { + // 1.0a Compatibility : create a token verifier + $verifier = substr(md5(rand()),0,10); + + $this->query(' + UPDATE oauth_server_token + SET ost_authorized = \'1\', + ost_usa_id_ref = \'%d\', + ost_timestamp = NOW(), + ost_referrer_host = \'%s\', + ost_verifier = \'%s\' + WHERE ost_token = \'%s\' + AND ost_token_type = \'request\' + ', $user_id, $referrer_host, $verifier, $token); + return $verifier; + } + + /** + * Count the consumer access tokens for the given consumer. + * + * @param string consumer_key + * @return int + */ + public function countConsumerAccessTokens ( $consumer_key ) + { + $count = $this->query_one(' + SELECT COUNT(ost_id) + FROM oauth_server_token + JOIN oauth_server_registry + ON ost_osr_id_ref = osr_id + WHERE ost_token_type = \'access\' + AND osr_consumer_key = \'%s\' + AND ost_token_ttl >= NOW() + ', $consumer_key); + + return $count; + } + + /** + * Exchange an authorized request token for new access token. + * + * @param string token + * @param array options options for the token, token_ttl + * @exception OAuthException2 when token could not be exchanged + * @return array (token, token_secret) + */ + public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) + { + $new_token = $this->generateKey(true); + $new_secret = $this->generateKey(); + + // Maximum time to live for this token + if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) + { + $ttl_sql = '(NOW() + INTERVAL \''.intval($options['token_ttl']).' SECOND\')'; + } + else + { + $ttl_sql = "'9999-12-31'"; + } + + if (isset($options['verifier'])) { + $verifier = $options['verifier']; + + // 1.0a Compatibility : check token against oauth_verifier + $this->query(' + UPDATE oauth_server_token + SET ost_token = \'%s\', + ost_token_secret = \'%s\', + ost_token_type = \'access\', + ost_timestamp = NOW(), + ost_token_ttl = '.$ttl_sql.' + WHERE ost_token = \'%s\' + AND ost_token_type = \'request\' + AND ost_authorized = \'1\' + AND ost_token_ttl >= NOW() + AND ost_verifier = \'%s\' + ', $new_token, $new_secret, $token, $verifier); + } else { + + // 1.0 + $this->query(' + UPDATE oauth_server_token + SET ost_token = \'%s\', + ost_token_secret = \'%s\', + ost_token_type = \'access\', + ost_timestamp = NOW(), + ost_token_ttl = '.$ttl_sql.' + WHERE ost_token = \'%s\' + AND ost_token_type = \'request\' + AND ost_authorized = \'1\' + AND ost_token_ttl >= NOW() + ', $new_token, $new_secret, $token); + } + + if ($this->query_affected_rows() != 1) + { + throw new OAuthException2('Can\'t exchange request token "'.$token.'" for access token. No such token or not authorized'); + } + + $ret = array('token' => $new_token, 'token_secret' => $new_secret); + $ttl = $this->query_one(' + SELECT (CASE WHEN ost_token_ttl >= \'9999-12-31\' THEN NULL ELSE ost_token_ttl - NOW() END) as token_ttl + FROM oauth_server_token + WHERE ost_token = \'%s\'', $new_token); + + if (is_numeric($ttl)) + { + $ret['token_ttl'] = intval($ttl); + } + return $ret; + } + + /** + * Fetch the consumer access token, by access token. + * + * @param string token + * @param int user_id + * @exception OAuthException2 when token is not found + * @return array token and consumer details + */ + public function getConsumerAccessToken ( $token, $user_id ) + { + $rs = $this->query_row_assoc(' + SELECT ost_token as token, + ost_token_secret as token_secret, + ost_referrer_host as token_referrer_host, + osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret, + osr_application_uri as application_uri, + osr_application_title as application_title, + osr_application_descr as application_descr, + osr_callback_uri as callback_uri + FROM oauth_server_token + JOIN oauth_server_registry + ON ost_osr_id_ref = osr_id + WHERE ost_token_type = \'access\' + AND ost_token = \'%s\' + AND ost_usa_id_ref = \'%d\' + AND ost_token_ttl >= NOW() + ', $token, $user_id); + + if (empty($rs)) + { + throw new OAuthException2('No server_token "'.$token.'" for user "'.$user_id.'"'); + } + return $rs; + } + + /** + * Delete a consumer access token. + * + * @param string token + * @param int user_id + * @param boolean user_is_admin + */ + public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) + { + if ($user_is_admin) + { + $this->query(' + DELETE FROM oauth_server_token + WHERE ost_token = \'%s\' + AND ost_token_type = \'access\' + ', $token); + } + else + { + $this->query(' + DELETE FROM oauth_server_token + WHERE ost_token = \'%s\' + AND ost_token_type = \'access\' + AND ost_usa_id_ref = \'%d\' + ', $token, $user_id); + } + } + + /** + * Set the ttl of a consumer access token. This is done when the + * server receives a valid request with a xoauth_token_ttl parameter in it. + * + * @param string token + * @param int ttl + */ + public function setConsumerAccessTokenTtl ( $token, $token_ttl ) + { + if ($token_ttl <= 0) + { + // Immediate delete when the token is past its ttl + $this->deleteConsumerAccessToken($token, 0, true); + } + else + { + // Set maximum time to live for this token + $this->query(' + UPDATE oauth_server_token + SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\') + WHERE ost_token = \'%s\' + AND ost_token_type = \'access\' + ', $token_ttl, $token); + } + } + + /** + * Fetch a list of all consumer keys, secrets etc. + * Returns the public (user_id is null) and the keys owned by the user + * + * @param int user_id + * @return array + */ + public function listConsumers ( $user_id ) + { + $rs = $this->query_all_assoc(' + SELECT osr_id as id, + osr_usa_id_ref as user_id, + osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret, + osr_enabled as enabled, + osr_status as status, + osr_issue_date as issue_date, + osr_application_uri as application_uri, + osr_application_title as application_title, + osr_application_descr as application_descr, + osr_requester_name as requester_name, + osr_requester_email as requester_email, + osr_callback_uri as callback_uri + FROM oauth_server_registry + WHERE (osr_usa_id_ref = \'%d\' OR osr_usa_id_ref IS NULL) + ORDER BY osr_application_title + ', $user_id); + return $rs; + } + + /** + * List of all registered applications. Data returned has not sensitive + * information and therefore is suitable for public displaying. + * + * @param int $begin + * @param int $total + * @return array + */ + public function listConsumerApplications($begin = 0, $total = 25) + { + $rs = $this->query_all_assoc(' + SELECT osr_id as id, + osr_enabled as enabled, + osr_status as status, + osr_issue_date as issue_date, + osr_application_uri as application_uri, + osr_application_title as application_title, + osr_application_descr as application_descr + FROM oauth_server_registry + ORDER BY osr_application_title + '); + // TODO: pagination + return $rs; + } + + + /** + * Fetch a list of all consumer tokens accessing the account of the given user. + * + * @param int user_id + * @return array + */ + public function listConsumerTokens ( $user_id ) + { + $rs = $this->query_all_assoc(' + SELECT osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret, + osr_enabled as enabled, + osr_status as status, + osr_application_uri as application_uri, + osr_application_title as application_title, + osr_application_descr as application_descr, + ost_timestamp as timestamp, + ost_token as token, + ost_token_secret as token_secret, + ost_referrer_host as token_referrer_host, + osr_callback_uri as callback_uri + FROM oauth_server_registry + JOIN oauth_server_token + ON ost_osr_id_ref = osr_id + WHERE ost_usa_id_ref = \'%d\' + AND ost_token_type = \'access\' + AND ost_token_ttl >= NOW() + ORDER BY osr_application_title + ', $user_id); + return $rs; + } + + + /** + * Check an nonce/timestamp combination. Clears any nonce combinations + * that are older than the one received. + * + * @param string consumer_key + * @param string token + * @param int timestamp + * @param string nonce + * @exception OAuthException2 thrown when the timestamp is not in sequence or nonce is not unique + */ + public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) + { + $r = $this->query_row(' + SELECT MAX(osn_timestamp), MAX(osn_timestamp) > %d + %d + FROM oauth_server_nonce + WHERE osn_consumer_key = \'%s\' + AND osn_token = \'%s\' + ', $timestamp, $this->max_timestamp_skew, $consumer_key, $token); + + if (!empty($r) && $r[1] === 't') + { + throw new OAuthException2('Timestamp is out of sequence. Request rejected. Got '.$timestamp.' last max is '.$r[0].' allowed skew is '.$this->max_timestamp_skew); + } + + // Insert the new combination + $this->query(' + INSERT INTO oauth_server_nonce ( + osn_consumer_key, + osn_token, + osn_timestamp, + osn_nonce + ) + VALUES (\'%s\', \'%s\', %d, \'%s\')', + $consumer_key, $token, $timestamp, $nonce); + + if ($this->query_affected_rows() == 0) + { + throw new OAuthException2('Duplicate timestamp/nonce combination, possible replay attack. Request rejected.'); + } + + // Clean up all timestamps older than the one we just received + $this->query(' + DELETE FROM oauth_server_nonce + WHERE osn_consumer_key = \'%s\' + AND osn_token = \'%s\' + AND osn_timestamp < %d - %d + ', $consumer_key, $token, $timestamp, $this->max_timestamp_skew); + } + + /** + * Add an entry to the log table + * + * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token) + * @param string received + * @param string sent + * @param string base_string + * @param string notes + * @param int (optional) user_id + */ + public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) + { + $args = array(); + $ps = array(); + foreach ($keys as $key => $value) + { + $args[] = $value; + $ps[] = "olg_$key = '%s'"; + } + + if (!empty($_SERVER['REMOTE_ADDR'])) + { + $remote_ip = $_SERVER['REMOTE_ADDR']; + } + else if (!empty($_SERVER['REMOTE_IP'])) + { + $remote_ip = $_SERVER['REMOTE_IP']; + } + else + { + $remote_ip = '0.0.0.0'; + } + + // Build the SQL + $ps['olg_received'] = "'%s'"; $args[] = $this->makeUTF8($received); + $ps['olg_sent'] = "'%s'"; $args[] = $this->makeUTF8($sent); + $ps['olg_base_string'] = "'%s'"; $args[] = $base_string; + $ps['olg_notes'] = "'%s'"; $args[] = $this->makeUTF8($notes); + $ps['olg_usa_id_ref'] = "NULLIF('%d', '0')"; $args[] = $user_id; + $ps['olg_remote_ip'] = "NULLIF('%s','0.0.0.0')"; $args[] = $remote_ip; + + $this->query(' + INSERT INTO oauth_log ('.implode(',', array_keys($ps)) . ') + VALUES(' . implode(',', $ps) . ')', + $args + ); + } + + /** + * Get a page of entries from the log. Returns the last 100 records + * matching the options given. + * + * @param array options + * @param int user_id current user + * @return array log records + */ + public function listLog ( $options, $user_id ) + { + $where = array(); + $args = array(); + if (empty($options)) + { + $where[] = 'olg_usa_id_ref = \'%d\''; + $args[] = $user_id; + } + else + { + foreach ($options as $option => $value) + { + if (strlen($value) > 0) + { + switch ($option) + { + case 'osr_consumer_key': + case 'ocr_consumer_key': + case 'ost_token': + case 'oct_token': + $where[] = 'olg_'.$option.' = \'%s\''; + $args[] = $value; + break; + } + } + } + + $where[] = '(olg_usa_id_ref IS NULL OR olg_usa_id_ref = \'%d\')'; + $args[] = $user_id; + } + + $rs = $this->query_all_assoc(' + SELECT olg_id, + olg_osr_consumer_key AS osr_consumer_key, + olg_ost_token AS ost_token, + olg_ocr_consumer_key AS ocr_consumer_key, + olg_oct_token AS oct_token, + olg_usa_id_ref AS user_id, + olg_received AS received, + olg_sent AS sent, + olg_base_string AS base_string, + olg_notes AS notes, + olg_timestamp AS timestamp, + olg_remote_ip AS remote_ip + FROM oauth_log + WHERE '.implode(' AND ', $where).' + ORDER BY olg_id DESC + LIMIT 0,100', $args); + + return $rs; + } + + + /* ** Some simple helper functions for querying the pgsql db ** */ + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + */ + protected function query ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = pg_query($this->conn, $sql))) + { + $this->sql_errcheck($sql); + } + $this->_lastAffectedRows = pg_affected_rows($res); + if (is_resource($res)) + { + pg_free_result($res); + } + } + + + /** + * Perform a query, return all rows + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_all_assoc ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = pg_query($this->conn, $sql))) + { + $this->sql_errcheck($sql); + } + $rs = array(); + while ($row = pg_fetch_assoc($res)) + { + $rs[] = $row; + } + pg_free_result($res); + return $rs; + } + + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_row_assoc ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + + if (!($res = pg_query($this->conn, $sql))) + { + $this->sql_errcheck($sql); + } + if ($row = pg_fetch_assoc($res)) + { + $rs = $row; + } + else + { + $rs = false; + } + pg_free_result($res); + return $rs; + } + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + protected function query_row ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = pg_query($this->conn, $sql))) + { + $this->sql_errcheck($sql); + } + if ($row = pg_fetch_array($res)) + { + $rs = $row; + } + else + { + $rs = false; + } + pg_free_result($res); + return $rs; + } + + + /** + * Perform a query, return the first column of the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return mixed + */ + protected function query_one ( $sql ) + { + $sql = $this->sql_printf(func_get_args()); + if (!($res = pg_query($this->conn, $sql))) + { + $this->sql_errcheck($sql); + } + $val = pg_fetch_row($res); + if ($val && isset($val[0])) { + $val = $val[0]; + } + pg_free_result($res); + return $val; + } + + + /** + * Return the number of rows affected in the last query + */ + protected function query_affected_rows () + { + return $this->_lastAffectedRows; + } + + + /** + * Return the id of the last inserted row + * + * @return int + */ + protected function query_insert_id ( $tableName, $primaryKey = null ) + { + $sequenceName = $tableName; + if ($primaryKey) { + $sequenceName .= "_$primaryKey"; + } + $sequenceName .= '_seq'; + + $sql = " + SELECT + CURRVAL('%s') + "; + $args = array($sql, $sequenceName); + $sql = $this->sql_printf($args); + if (!($res = pg_query($this->conn, $sql))) { + return 0; + } + $val = pg_fetch_row($res, 0); + if ($val && isset($val[0])) { + $val = $val[0]; + } + + pg_free_result($res); + return $val; + } + + + protected function sql_printf ( $args ) + { + $sql = array_shift($args); + if (count($args) == 1 && is_array($args[0])) + { + $args = $args[0]; + } + $args = array_map(array($this, 'sql_escape_string'), $args); + return vsprintf($sql, $args); + } + + + protected function sql_escape_string ( $s ) + { + if (is_string($s)) + { + return pg_escape_string($this->conn, $s); + } + else if (is_null($s)) + { + return NULL; + } + else if (is_bool($s)) + { + return intval($s); + } + else if (is_int($s) || is_float($s)) + { + return $s; + } + else + { + return pg_escape_string($this->conn, strval($s)); + } + } + + + protected function sql_errcheck ( $sql ) + { + $msg = "SQL Error in OAuthStorePostgreSQL: ".pg_last_error($this->conn)."\n\n" . $sql; + throw new OAuthException2($msg); + } +} diff --git a/3rdparty/oauth-php/library/store/OAuthStoreSQL.php b/3rdparty/oauth-php/library/store/OAuthStoreSQL.php new file mode 100644 index 0000000000..95e0720a31 --- /dev/null +++ b/3rdparty/oauth-php/library/store/OAuthStoreSQL.php @@ -0,0 +1,1827 @@ + + * @date Nov 16, 2007 4:03:30 PM + * + * + * The MIT License + * + * Copyright (c) 2007-2008 Mediamatic Lab + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + + +require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php'; + + +abstract class OAuthStoreSQL extends OAuthStoreAbstract +{ + /** + * Maximum delta a timestamp may be off from a previous timestamp. + * Allows multiple consumers with some clock skew to work with the same token. + * Unit is seconds, default max skew is 10 minutes. + */ + protected $max_timestamp_skew = 600; + + /** + * Default ttl for request tokens + */ + protected $max_request_token_ttl = 3600; + + + /** + * Construct the OAuthStoreMySQL. + * In the options you have to supply either: + * - server, username, password and database (for a mysql_connect) + * - conn (for the connection to be used) + * + * @param array options + */ + function __construct ( $options = array() ) + { + if (isset($options['conn'])) + { + $this->conn = $options['conn']; + } + else + { + if (isset($options['server'])) + { + $server = $options['server']; + $username = $options['username']; + + if (isset($options['password'])) + { + $this->conn = mysql_connect($server, $username, $options['password']); + } + else + { + $this->conn = mysql_connect($server, $username); + } + } + else + { + // Try the default mysql connect + $this->conn = mysql_connect(); + } + + if ($this->conn === false) + { + throw new OAuthException2('Could not connect to MySQL database: ' . mysql_error()); + } + + if (isset($options['database'])) + { + if (!mysql_select_db($options['database'], $this->conn)) + { + $this->sql_errcheck(); + } + } + $this->query('set character set utf8'); + } + } + + + /** + * Find stored credentials for the consumer key and token. Used by an OAuth server + * when verifying an OAuth request. + * + * @param string consumer_key + * @param string token + * @param string token_type false, 'request' or 'access' + * @exception OAuthException2 when no secrets where found + * @return array assoc (consumer_secret, token_secret, osr_id, ost_id, user_id) + */ + public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ) + { + if ($token_type === false) + { + $rs = $this->query_row_assoc(' + SELECT osr_id, + osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret + FROM oauth_server_registry + WHERE osr_consumer_key = \'%s\' + AND osr_enabled = 1 + ', + $consumer_key); + + if ($rs) + { + $rs['token'] = false; + $rs['token_secret'] = false; + $rs['user_id'] = false; + $rs['ost_id'] = false; + } + } + else + { + $rs = $this->query_row_assoc(' + SELECT osr_id, + ost_id, + ost_usa_id_ref as user_id, + osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret, + ost_token as token, + ost_token_secret as token_secret + FROM oauth_server_registry + JOIN oauth_server_token + ON ost_osr_id_ref = osr_id + WHERE ost_token_type = \'%s\' + AND osr_consumer_key = \'%s\' + AND ost_token = \'%s\' + AND osr_enabled = 1 + AND ost_token_ttl >= NOW() + ', + $token_type, $consumer_key, $token); + } + + if (empty($rs)) + { + throw new OAuthException2('The consumer_key "'.$consumer_key.'" token "'.$token.'" combination does not exist or is not enabled.'); + } + return $rs; + } + + + /** + * Find the server details for signing a request, always looks for an access token. + * The returned credentials depend on which local user is making the request. + * + * The consumer_key must belong to the user or be public (user id is null) + * + * For signing we need all of the following: + * + * consumer_key consumer key associated with the server + * consumer_secret consumer secret associated with this server + * token access token associated with this server + * token_secret secret for the access token + * signature_methods signing methods supported by the server (array) + * + * @todo filter on token type (we should know how and with what to sign this request, and there might be old access tokens) + * @param string uri uri of the server + * @param int user_id id of the logged on user + * @param string name (optional) name of the token (case sensitive) + * @exception OAuthException2 when no credentials found + * @return array + */ + public function getSecretsForSignature ( $uri, $user_id, $name = '' ) + { + // Find a consumer key and token for the given uri + $ps = parse_url($uri); + $host = isset($ps['host']) ? $ps['host'] : 'localhost'; + $path = isset($ps['path']) ? $ps['path'] : ''; + + if (empty($path) || substr($path, -1) != '/') + { + $path .= '/'; + } + + // The owner of the consumer_key is either the user or nobody (public consumer key) + $secrets = $this->query_row_assoc(' + SELECT ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + oct_token as token, + oct_token_secret as token_secret, + ocr_signature_methods as signature_methods + FROM oauth_consumer_registry + JOIN oauth_consumer_token ON oct_ocr_id_ref = ocr_id + WHERE ocr_server_uri_host = \'%s\' + AND ocr_server_uri_path = LEFT(\'%s\', LENGTH(ocr_server_uri_path)) + AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) + AND oct_token_type = \'access\' + AND oct_name = \'%s\' + AND oct_token_ttl >= NOW() + ORDER BY ocr_usa_id_ref DESC, ocr_consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC + LIMIT 0,1 + ', $host, $path, $user_id, $name + ); + + if (empty($secrets)) + { + throw new OAuthException2('No server tokens available for '.$uri); + } + $secrets['signature_methods'] = explode(',', $secrets['signature_methods']); + return $secrets; + } + + + /** + * Get the token and token secret we obtained from a server. + * + * @param string consumer_key + * @param string token + * @param string token_type + * @param int user_id the user owning the token + * @param string name optional name for a named token + * @exception OAuthException2 when no credentials found + * @return array + */ + public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' ) + { + if ($token_type != 'request' && $token_type != 'access') + { + throw new OAuthException2('Unkown token type "'.$token_type.'", must be either "request" or "access"'); + } + + // Take the most recent token of the given type + $r = $this->query_row_assoc(' + SELECT ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + oct_token as token, + oct_token_secret as token_secret, + oct_name as token_name, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri, + IF(oct_token_ttl >= \'9999-12-31\', NULL, UNIX_TIMESTAMP(oct_token_ttl) - UNIX_TIMESTAMP(NOW())) as token_ttl + FROM oauth_consumer_registry + JOIN oauth_consumer_token + ON oct_ocr_id_ref = ocr_id + WHERE ocr_consumer_key = \'%s\' + AND oct_token_type = \'%s\' + AND oct_token = \'%s\' + AND oct_usa_id_ref = %d + AND oct_token_ttl >= NOW() + ', $consumer_key, $token_type, $token, $user_id + ); + + if (empty($r)) + { + throw new OAuthException2('Could not find a "'.$token_type.'" token for consumer "'.$consumer_key.'" and user '.$user_id); + } + if (isset($r['signature_methods']) && !empty($r['signature_methods'])) + { + $r['signature_methods'] = explode(',',$r['signature_methods']); + } + else + { + $r['signature_methods'] = array(); + } + return $r; + } + + + /** + * Add a request token we obtained from a server. + * + * @todo remove old tokens for this user and this ocr_id + * @param string consumer_key key of the server in the consumer registry + * @param string token_type one of 'request' or 'access' + * @param string token + * @param string token_secret + * @param int user_id the user owning the token + * @param array options extra options, name and token_ttl + * @exception OAuthException2 when server is not known + * @exception OAuthException2 when we received a duplicate token + */ + public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) + { + if ($token_type != 'request' && $token_type != 'access') + { + throw new OAuthException2('Unknown token type "'.$token_type.'", must be either "request" or "access"'); + } + + // Maximum time to live for this token + if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) + { + $ttl = 'DATE_ADD(NOW(), INTERVAL '.intval($options['token_ttl']).' SECOND)'; + } + else if ($token_type == 'request') + { + $ttl = 'DATE_ADD(NOW(), INTERVAL '.$this->max_request_token_ttl.' SECOND)'; + } + else + { + $ttl = "'9999-12-31'"; + } + + if (isset($options['server_uri'])) + { + $ocr_id = $this->query_one(' + SELECT ocr_id + FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND ocr_usa_id_ref = %d + AND ocr_server_uri = \'%s\' + ', $consumer_key, $user_id, $options['server_uri']); + } + else + { + $ocr_id = $this->query_one(' + SELECT ocr_id + FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND ocr_usa_id_ref = %d + ', $consumer_key, $user_id); + } + + if (empty($ocr_id)) + { + throw new OAuthException2('No server associated with consumer_key "'.$consumer_key.'"'); + } + + // Named tokens, unique per user/consumer key + if (isset($options['name']) && $options['name'] != '') + { + $name = $options['name']; + } + else + { + $name = ''; + } + + // Delete any old tokens with the same type and name for this user/server combination + $this->query(' + DELETE FROM oauth_consumer_token + WHERE oct_ocr_id_ref = %d + AND oct_usa_id_ref = %d + AND oct_token_type = LOWER(\'%s\') + AND oct_name = \'%s\' + ', + $ocr_id, + $user_id, + $token_type, + $name); + + // Insert the new token + $this->query(' + INSERT IGNORE INTO oauth_consumer_token + SET oct_ocr_id_ref = %d, + oct_usa_id_ref = %d, + oct_name = \'%s\', + oct_token = \'%s\', + oct_token_secret= \'%s\', + oct_token_type = LOWER(\'%s\'), + oct_timestamp = NOW(), + oct_token_ttl = '.$ttl.' + ', + $ocr_id, + $user_id, + $name, + $token, + $token_secret, + $token_type); + + if (!$this->query_affected_rows()) + { + throw new OAuthException2('Received duplicate token "'.$token.'" for the same consumer_key "'.$consumer_key.'"'); + } + } + + + /** + * Delete a server key. This removes access to that site. + * + * @param string consumer_key + * @param int user_id user registering this server + * @param boolean user_is_admin + */ + public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) + { + if ($user_is_admin) + { + $this->query(' + DELETE FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL) + ', $consumer_key, $user_id); + } + else + { + $this->query(' + DELETE FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND ocr_usa_id_ref = %d + ', $consumer_key, $user_id); + } + } + + + /** + * Get a server from the consumer registry using the consumer key + * + * @param string consumer_key + * @param int user_id + * @param boolean user_is_admin (optional) + * @exception OAuthException2 when server is not found + * @return array + */ + public function getServer ( $consumer_key, $user_id, $user_is_admin = false ) + { + $r = $this->query_row_assoc(' + SELECT ocr_id as id, + ocr_usa_id_ref as user_id, + ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri + FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL) + ', $consumer_key, $user_id); + + if (empty($r)) + { + throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" has been registered (for this user)'); + } + + if (isset($r['signature_methods']) && !empty($r['signature_methods'])) + { + $r['signature_methods'] = explode(',',$r['signature_methods']); + } + else + { + $r['signature_methods'] = array(); + } + return $r; + } + + + + /** + * Find the server details that might be used for a request + * + * The consumer_key must belong to the user or be public (user id is null) + * + * @param string uri uri of the server + * @param int user_id id of the logged on user + * @exception OAuthException2 when no credentials found + * @return array + */ + public function getServerForUri ( $uri, $user_id ) + { + // Find a consumer key and token for the given uri + $ps = parse_url($uri); + $host = isset($ps['host']) ? $ps['host'] : 'localhost'; + $path = isset($ps['path']) ? $ps['path'] : ''; + + if (empty($path) || substr($path, -1) != '/') + { + $path .= '/'; + } + + // The owner of the consumer_key is either the user or nobody (public consumer key) + $server = $this->query_row_assoc(' + SELECT ocr_id as id, + ocr_usa_id_ref as user_id, + ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri + FROM oauth_consumer_registry + WHERE ocr_server_uri_host = \'%s\' + AND ocr_server_uri_path = LEFT(\'%s\', LENGTH(ocr_server_uri_path)) + AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) + ORDER BY ocr_usa_id_ref DESC, consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC + LIMIT 0,1 + ', $host, $path, $user_id + ); + + if (empty($server)) + { + throw new OAuthException2('No server available for '.$uri); + } + $server['signature_methods'] = explode(',', $server['signature_methods']); + return $server; + } + + + /** + * Get a list of all server token this user has access to. + * + * @param int usr_id + * @return array + */ + public function listServerTokens ( $user_id ) + { + $ts = $this->query_all_assoc(' + SELECT ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + oct_id as token_id, + oct_token as token, + oct_token_secret as token_secret, + oct_usa_id_ref as user_id, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_server_uri_host as server_uri_host, + ocr_server_uri_path as server_uri_path, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri, + oct_timestamp as timestamp + FROM oauth_consumer_registry + JOIN oauth_consumer_token + ON oct_ocr_id_ref = ocr_id + WHERE oct_usa_id_ref = %d + AND oct_token_type = \'access\' + AND oct_token_ttl >= NOW() + ORDER BY ocr_server_uri_host, ocr_server_uri_path + ', $user_id); + return $ts; + } + + + /** + * Count how many tokens we have for the given server + * + * @param string consumer_key + * @return int + */ + public function countServerTokens ( $consumer_key ) + { + $count = $this->query_one(' + SELECT COUNT(oct_id) + FROM oauth_consumer_token + JOIN oauth_consumer_registry + ON oct_ocr_id_ref = ocr_id + WHERE oct_token_type = \'access\' + AND ocr_consumer_key = \'%s\' + AND oct_token_ttl >= NOW() + ', $consumer_key); + + return $count; + } + + + /** + * Get a specific server token for the given user + * + * @param string consumer_key + * @param string token + * @param int user_id + * @exception OAuthException2 when no such token found + * @return array + */ + public function getServerToken ( $consumer_key, $token, $user_id ) + { + $ts = $this->query_row_assoc(' + SELECT ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + oct_token as token, + oct_token_secret as token_secret, + oct_usa_id_ref as usr_id, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_server_uri_host as server_uri_host, + ocr_server_uri_path as server_uri_path, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri, + oct_timestamp as timestamp + FROM oauth_consumer_registry + JOIN oauth_consumer_token + ON oct_ocr_id_ref = ocr_id + WHERE ocr_consumer_key = \'%s\' + AND oct_usa_id_ref = %d + AND oct_token_type = \'access\' + AND oct_token = \'%s\' + AND oct_token_ttl >= NOW() + ', $consumer_key, $user_id, $token); + + if (empty($ts)) + { + throw new OAuthException2('No such consumer key ('.$consumer_key.') and token ('.$token.') combination for user "'.$user_id.'"'); + } + return $ts; + } + + + /** + * Delete a token we obtained from a server. + * + * @param string consumer_key + * @param string token + * @param int user_id + * @param boolean user_is_admin + */ + public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) + { + if ($user_is_admin) + { + $this->query(' + DELETE oauth_consumer_token + FROM oauth_consumer_token + JOIN oauth_consumer_registry + ON oct_ocr_id_ref = ocr_id + WHERE ocr_consumer_key = \'%s\' + AND oct_token = \'%s\' + ', $consumer_key, $token); + } + else + { + $this->query(' + DELETE oauth_consumer_token + FROM oauth_consumer_token + JOIN oauth_consumer_registry + ON oct_ocr_id_ref = ocr_id + WHERE ocr_consumer_key = \'%s\' + AND oct_token = \'%s\' + AND oct_usa_id_ref = %d + ', $consumer_key, $token, $user_id); + } + } + + + /** + * Set the ttl of a server access token. This is done when the + * server receives a valid request with a xoauth_token_ttl parameter in it. + * + * @param string consumer_key + * @param string token + * @param int token_ttl + */ + public function setServerTokenTtl ( $consumer_key, $token, $token_ttl ) + { + if ($token_ttl <= 0) + { + // Immediate delete when the token is past its ttl + $this->deleteServerToken($consumer_key, $token, 0, true); + } + else + { + // Set maximum time to live for this token + $this->query(' + UPDATE oauth_consumer_token, oauth_consumer_registry + SET ost_token_ttl = DATE_ADD(NOW(), INTERVAL %d SECOND) + WHERE ocr_consumer_key = \'%s\' + AND oct_ocr_id_ref = ocr_id + AND oct_token = \'%s\' + ', $token_ttl, $consumer_key, $token); + } + } + + + /** + * Get a list of all consumers from the consumer registry. + * The consumer keys belong to the user or are public (user id is null) + * + * @param string q query term + * @param int user_id + * @return array + */ + public function listServers ( $q = '', $user_id ) + { + $q = trim(str_replace('%', '', $q)); + $args = array(); + + if (!empty($q)) + { + $where = ' WHERE ( ocr_consumer_key like \'%%%s%%\' + OR ocr_server_uri like \'%%%s%%\' + OR ocr_server_uri_host like \'%%%s%%\' + OR ocr_server_uri_path like \'%%%s%%\') + AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL) + '; + + $args[] = $q; + $args[] = $q; + $args[] = $q; + $args[] = $q; + $args[] = $user_id; + } + else + { + $where = ' WHERE ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL'; + $args[] = $user_id; + } + + $servers = $this->query_all_assoc(' + SELECT ocr_id as id, + ocr_usa_id_ref as user_id, + ocr_consumer_key as consumer_key, + ocr_consumer_secret as consumer_secret, + ocr_signature_methods as signature_methods, + ocr_server_uri as server_uri, + ocr_server_uri_host as server_uri_host, + ocr_server_uri_path as server_uri_path, + ocr_request_token_uri as request_token_uri, + ocr_authorize_uri as authorize_uri, + ocr_access_token_uri as access_token_uri + FROM oauth_consumer_registry + '.$where.' + ORDER BY ocr_server_uri_host, ocr_server_uri_path + ', $args); + return $servers; + } + + + /** + * Register or update a server for our site (we will be the consumer) + * + * (This is the registry at the consumers, registering servers ;-) ) + * + * @param array server + * @param int user_id user registering this server + * @param boolean user_is_admin + * @exception OAuthException2 when fields are missing or on duplicate consumer_key + * @return consumer_key + */ + public function updateServer ( $server, $user_id, $user_is_admin = false ) + { + foreach (array('consumer_key', 'server_uri') as $f) + { + if (empty($server[$f])) + { + throw new OAuthException2('The field "'.$f.'" must be set and non empty'); + } + } + + if (!empty($server['id'])) + { + $exists = $this->query_one(' + SELECT ocr_id + FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND ocr_id <> %d + AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL) + ', $server['consumer_key'], $server['id'], $user_id); + } + else + { + $exists = $this->query_one(' + SELECT ocr_id + FROM oauth_consumer_registry + WHERE ocr_consumer_key = \'%s\' + AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL) + ', $server['consumer_key'], $user_id); + } + + if ($exists) + { + throw new OAuthException2('The server with key "'.$server['consumer_key'].'" has already been registered'); + } + + $parts = parse_url($server['server_uri']); + $host = (isset($parts['host']) ? $parts['host'] : 'localhost'); + $path = (isset($parts['path']) ? $parts['path'] : '/'); + + if (isset($server['signature_methods'])) + { + if (is_array($server['signature_methods'])) + { + $server['signature_methods'] = strtoupper(implode(',', $server['signature_methods'])); + } + } + else + { + $server['signature_methods'] = ''; + } + + // When the user is an admin, then the user can update the user_id of this record + if ($user_is_admin && array_key_exists('user_id', $server)) + { + if (is_null($server['user_id'])) + { + $update_user = ', ocr_usa_id_ref = NULL'; + } + else + { + $update_user = ', ocr_usa_id_ref = '.intval($server['user_id']); + } + } + else + { + $update_user = ''; + } + + if (!empty($server['id'])) + { + // Check if the current user can update this server definition + if (!$user_is_admin) + { + $ocr_usa_id_ref = $this->query_one(' + SELECT ocr_usa_id_ref + FROM oauth_consumer_registry + WHERE ocr_id = %d + ', $server['id']); + + if ($ocr_usa_id_ref != $user_id) + { + throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this server'); + } + } + + // Update the consumer registration + $this->query(' + UPDATE oauth_consumer_registry + SET ocr_consumer_key = \'%s\', + ocr_consumer_secret = \'%s\', + ocr_server_uri = \'%s\', + ocr_server_uri_host = \'%s\', + ocr_server_uri_path = \'%s\', + ocr_timestamp = NOW(), + ocr_request_token_uri = \'%s\', + ocr_authorize_uri = \'%s\', + ocr_access_token_uri = \'%s\', + ocr_signature_methods = \'%s\' + '.$update_user.' + WHERE ocr_id = %d + ', + $server['consumer_key'], + $server['consumer_secret'], + $server['server_uri'], + strtolower($host), + $path, + isset($server['request_token_uri']) ? $server['request_token_uri'] : '', + isset($server['authorize_uri']) ? $server['authorize_uri'] : '', + isset($server['access_token_uri']) ? $server['access_token_uri'] : '', + $server['signature_methods'], + $server['id'] + ); + } + else + { + if (empty($update_user)) + { + // Per default the user owning the key is the user registering the key + $update_user = ', ocr_usa_id_ref = '.intval($user_id); + } + + $this->query(' + INSERT INTO oauth_consumer_registry + SET ocr_consumer_key = \'%s\', + ocr_consumer_secret = \'%s\', + ocr_server_uri = \'%s\', + ocr_server_uri_host = \'%s\', + ocr_server_uri_path = \'%s\', + ocr_timestamp = NOW(), + ocr_request_token_uri = \'%s\', + ocr_authorize_uri = \'%s\', + ocr_access_token_uri = \'%s\', + ocr_signature_methods = \'%s\' + '.$update_user, + $server['consumer_key'], + $server['consumer_secret'], + $server['server_uri'], + strtolower($host), + $path, + isset($server['request_token_uri']) ? $server['request_token_uri'] : '', + isset($server['authorize_uri']) ? $server['authorize_uri'] : '', + isset($server['access_token_uri']) ? $server['access_token_uri'] : '', + $server['signature_methods'] + ); + + $ocr_id = $this->query_insert_id(); + } + return $server['consumer_key']; + } + + + /** + * Insert/update a new consumer with this server (we will be the server) + * When this is a new consumer, then also generate the consumer key and secret. + * Never updates the consumer key and secret. + * When the id is set, then the key and secret must correspond to the entry + * being updated. + * + * (This is the registry at the server, registering consumers ;-) ) + * + * @param array consumer + * @param int user_id user registering this consumer + * @param boolean user_is_admin + * @return string consumer key + */ + public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) + { + if (!$user_is_admin) + { + foreach (array('requester_name', 'requester_email') as $f) + { + if (empty($consumer[$f])) + { + throw new OAuthException2('The field "'.$f.'" must be set and non empty'); + } + } + } + + if (!empty($consumer['id'])) + { + if (empty($consumer['consumer_key'])) + { + throw new OAuthException2('The field "consumer_key" must be set and non empty'); + } + if (!$user_is_admin && empty($consumer['consumer_secret'])) + { + throw new OAuthException2('The field "consumer_secret" must be set and non empty'); + } + + // Check if the current user can update this server definition + if (!$user_is_admin) + { + $osr_usa_id_ref = $this->query_one(' + SELECT osr_usa_id_ref + FROM oauth_server_registry + WHERE osr_id = %d + ', $consumer['id']); + + if ($osr_usa_id_ref != $user_id) + { + throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this consumer'); + } + } + else + { + // User is an admin, allow a key owner to be changed or key to be shared + if (array_key_exists('user_id',$consumer)) + { + if (is_null($consumer['user_id'])) + { + $this->query(' + UPDATE oauth_server_registry + SET osr_usa_id_ref = NULL + WHERE osr_id = %d + ', $consumer['id']); + } + else + { + $this->query(' + UPDATE oauth_server_registry + SET osr_usa_id_ref = %d + WHERE osr_id = %d + ', $consumer['user_id'], $consumer['id']); + } + } + } + + $this->query(' + UPDATE oauth_server_registry + SET osr_requester_name = \'%s\', + osr_requester_email = \'%s\', + osr_callback_uri = \'%s\', + osr_application_uri = \'%s\', + osr_application_title = \'%s\', + osr_application_descr = \'%s\', + osr_application_notes = \'%s\', + osr_application_type = \'%s\', + osr_application_commercial = IF(%d,1,0), + osr_timestamp = NOW() + WHERE osr_id = %d + AND osr_consumer_key = \'%s\' + AND osr_consumer_secret = \'%s\' + ', + $consumer['requester_name'], + $consumer['requester_email'], + isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '', + isset($consumer['application_uri']) ? $consumer['application_uri'] : '', + isset($consumer['application_title']) ? $consumer['application_title'] : '', + isset($consumer['application_descr']) ? $consumer['application_descr'] : '', + isset($consumer['application_notes']) ? $consumer['application_notes'] : '', + isset($consumer['application_type']) ? $consumer['application_type'] : '', + isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0, + $consumer['id'], + $consumer['consumer_key'], + $consumer['consumer_secret'] + ); + + + $consumer_key = $consumer['consumer_key']; + } + else + { + $consumer_key = $this->generateKey(true); + $consumer_secret= $this->generateKey(); + + // When the user is an admin, then the user can be forced to something else that the user + if ($user_is_admin && array_key_exists('user_id',$consumer)) + { + if (is_null($consumer['user_id'])) + { + $owner_id = 'NULL'; + } + else + { + $owner_id = intval($consumer['user_id']); + } + } + else + { + // No admin, take the user id as the owner id. + $owner_id = intval($user_id); + } + + $this->query(' + INSERT INTO oauth_server_registry + SET osr_enabled = 1, + osr_status = \'active\', + osr_usa_id_ref = \'%s\', + osr_consumer_key = \'%s\', + osr_consumer_secret = \'%s\', + osr_requester_name = \'%s\', + osr_requester_email = \'%s\', + osr_callback_uri = \'%s\', + osr_application_uri = \'%s\', + osr_application_title = \'%s\', + osr_application_descr = \'%s\', + osr_application_notes = \'%s\', + osr_application_type = \'%s\', + osr_application_commercial = IF(%d,1,0), + osr_timestamp = NOW(), + osr_issue_date = NOW() + ', + $owner_id, + $consumer_key, + $consumer_secret, + $consumer['requester_name'], + $consumer['requester_email'], + isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '', + isset($consumer['application_uri']) ? $consumer['application_uri'] : '', + isset($consumer['application_title']) ? $consumer['application_title'] : '', + isset($consumer['application_descr']) ? $consumer['application_descr'] : '', + isset($consumer['application_notes']) ? $consumer['application_notes'] : '', + isset($consumer['application_type']) ? $consumer['application_type'] : '', + isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0 + ); + } + return $consumer_key; + + } + + + + /** + * Delete a consumer key. This removes access to our site for all applications using this key. + * + * @param string consumer_key + * @param int user_id user registering this server + * @param boolean user_is_admin + */ + public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) + { + if ($user_is_admin) + { + $this->query(' + DELETE FROM oauth_server_registry + WHERE osr_consumer_key = \'%s\' + AND (osr_usa_id_ref = %d OR osr_usa_id_ref IS NULL) + ', $consumer_key, $user_id); + } + else + { + $this->query(' + DELETE FROM oauth_server_registry + WHERE osr_consumer_key = \'%s\' + AND osr_usa_id_ref = %d + ', $consumer_key, $user_id); + } + } + + + + /** + * Fetch a consumer of this server, by consumer_key. + * + * @param string consumer_key + * @param int user_id + * @param boolean user_is_admin (optional) + * @exception OAuthException2 when consumer not found + * @return array + */ + public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) + { + $consumer = $this->query_row_assoc(' + SELECT * + FROM oauth_server_registry + WHERE osr_consumer_key = \'%s\' + ', $consumer_key); + + if (!is_array($consumer)) + { + throw new OAuthException2('No consumer with consumer_key "'.$consumer_key.'"'); + } + + $c = array(); + foreach ($consumer as $key => $value) + { + $c[substr($key, 4)] = $value; + } + $c['user_id'] = $c['usa_id_ref']; + + if (!$user_is_admin && !empty($c['user_id']) && $c['user_id'] != $user_id) + { + throw new OAuthException2('No access to the consumer information for consumer_key "'.$consumer_key.'"'); + } + return $c; + } + + + /** + * Fetch the static consumer key for this provider. The user for the static consumer + * key is NULL (no user, shared key). If the key did not exist then the key is created. + * + * @return string + */ + public function getConsumerStatic () + { + $consumer = $this->query_one(' + SELECT osr_consumer_key + FROM oauth_server_registry + WHERE osr_consumer_key LIKE \'sc-%%\' + AND osr_usa_id_ref IS NULL + '); + + if (empty($consumer)) + { + $consumer_key = 'sc-'.$this->generateKey(true); + $this->query(' + INSERT INTO oauth_server_registry + SET osr_enabled = 1, + osr_status = \'active\', + osr_usa_id_ref = NULL, + osr_consumer_key = \'%s\', + osr_consumer_secret = \'\', + osr_requester_name = \'\', + osr_requester_email = \'\', + osr_callback_uri = \'\', + osr_application_uri = \'\', + osr_application_title = \'Static shared consumer key\', + osr_application_descr = \'\', + osr_application_notes = \'Static shared consumer key\', + osr_application_type = \'\', + osr_application_commercial = 0, + osr_timestamp = NOW(), + osr_issue_date = NOW() + ', + $consumer_key + ); + + // Just make sure that if the consumer key is truncated that we get the truncated string + $consumer = $this->getConsumerStatic(); + } + return $consumer; + } + + + /** + * Add an unautorized request token to our server. + * + * @param string consumer_key + * @param array options (eg. token_ttl) + * @return array (token, token_secret) + */ + public function addConsumerRequestToken ( $consumer_key, $options = array() ) + { + $token = $this->generateKey(true); + $secret = $this->generateKey(); + $osr_id = $this->query_one(' + SELECT osr_id + FROM oauth_server_registry + WHERE osr_consumer_key = \'%s\' + AND osr_enabled = 1 + ', $consumer_key); + + if (!$osr_id) + { + throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" or consumer_key is disabled'); + } + + if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) + { + $ttl = intval($options['token_ttl']); + } + else + { + $ttl = $this->max_request_token_ttl; + } + + if (!isset($options['oauth_callback'])) { + // 1.0a Compatibility : store callback url associated with request token + $options['oauth_callback']='oob'; + } + + $this->query(' + INSERT INTO oauth_server_token + SET ost_osr_id_ref = %d, + ost_usa_id_ref = 1, + ost_token = \'%s\', + ost_token_secret = \'%s\', + ost_token_type = \'request\', + ost_token_ttl = DATE_ADD(NOW(), INTERVAL %d SECOND), + ost_callback_url = \'%s\' + ON DUPLICATE KEY UPDATE + ost_osr_id_ref = VALUES(ost_osr_id_ref), + ost_usa_id_ref = VALUES(ost_usa_id_ref), + ost_token = VALUES(ost_token), + ost_token_secret = VALUES(ost_token_secret), + ost_token_type = VALUES(ost_token_type), + ost_token_ttl = VALUES(ost_token_ttl), + ost_callback_url = VALUES(ost_callback_url), + ost_timestamp = NOW() + ', $osr_id, $token, $secret, $ttl, $options['oauth_callback']); + + return array('token'=>$token, 'token_secret'=>$secret, 'token_ttl'=>$ttl); + } + + + /** + * Fetch the consumer request token, by request token. + * + * @param string token + * @return array token and consumer details + */ + public function getConsumerRequestToken ( $token ) + { + $rs = $this->query_row_assoc(' + SELECT ost_token as token, + ost_token_secret as token_secret, + osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret, + ost_token_type as token_type, + ost_callback_url as callback_url, + osr_application_title as application_title, + osr_application_descr as application_descr, + osr_application_uri as application_uri + FROM oauth_server_token + JOIN oauth_server_registry + ON ost_osr_id_ref = osr_id + WHERE ost_token_type = \'request\' + AND ost_token = \'%s\' + AND ost_token_ttl >= NOW() + ', $token); + + return $rs; + } + + + /** + * Delete a consumer token. The token must be a request or authorized token. + * + * @param string token + */ + public function deleteConsumerRequestToken ( $token ) + { + $this->query(' + DELETE FROM oauth_server_token + WHERE ost_token = \'%s\' + AND ost_token_type = \'request\' + ', $token); + } + + + /** + * Upgrade a request token to be an authorized request token. + * + * @param string token + * @param int user_id user authorizing the token + * @param string referrer_host used to set the referrer host for this token, for user feedback + */ + public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) + { + // 1.0a Compatibility : create a token verifier + $verifier = substr(md5(rand()),0,10); + + $this->query(' + UPDATE oauth_server_token + SET ost_authorized = 1, + ost_usa_id_ref = %d, + ost_timestamp = NOW(), + ost_referrer_host = \'%s\', + ost_verifier = \'%s\' + WHERE ost_token = \'%s\' + AND ost_token_type = \'request\' + ', $user_id, $referrer_host, $verifier, $token); + return $verifier; + } + + + /** + * Count the consumer access tokens for the given consumer. + * + * @param string consumer_key + * @return int + */ + public function countConsumerAccessTokens ( $consumer_key ) + { + $count = $this->query_one(' + SELECT COUNT(ost_id) + FROM oauth_server_token + JOIN oauth_server_registry + ON ost_osr_id_ref = osr_id + WHERE ost_token_type = \'access\' + AND osr_consumer_key = \'%s\' + AND ost_token_ttl >= NOW() + ', $consumer_key); + + return $count; + } + + + /** + * Exchange an authorized request token for new access token. + * + * @param string token + * @param array options options for the token, token_ttl + * @exception OAuthException2 when token could not be exchanged + * @return array (token, token_secret) + */ + public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) + { + $new_token = $this->generateKey(true); + $new_secret = $this->generateKey(); + + // Maximum time to live for this token + if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) + { + $ttl_sql = 'DATE_ADD(NOW(), INTERVAL '.intval($options['token_ttl']).' SECOND)'; + } + else + { + $ttl_sql = "'9999-12-31'"; + } + + if (isset($options['verifier'])) { + $verifier = $options['verifier']; + + // 1.0a Compatibility : check token against oauth_verifier + $this->query(' + UPDATE oauth_server_token + SET ost_token = \'%s\', + ost_token_secret = \'%s\', + ost_token_type = \'access\', + ost_timestamp = NOW(), + ost_token_ttl = '.$ttl_sql.' + WHERE ost_token = \'%s\' + AND ost_token_type = \'request\' + AND ost_authorized = 1 + AND ost_token_ttl >= NOW() + AND ost_verifier = \'%s\' + ', $new_token, $new_secret, $token, $verifier); + } else { + + // 1.0 + $this->query(' + UPDATE oauth_server_token + SET ost_token = \'%s\', + ost_token_secret = \'%s\', + ost_token_type = \'access\', + ost_timestamp = NOW(), + ost_token_ttl = '.$ttl_sql.' + WHERE ost_token = \'%s\' + AND ost_token_type = \'request\' + AND ost_authorized = 1 + AND ost_token_ttl >= NOW() + ', $new_token, $new_secret, $token); + } + + if ($this->query_affected_rows() != 1) + { + throw new OAuthException2('Can\'t exchange request token "'.$token.'" for access token. No such token or not authorized'); + } + + $ret = array('token' => $new_token, 'token_secret' => $new_secret); + $ttl = $this->query_one(' + SELECT IF(ost_token_ttl >= \'9999-12-31\', NULL, UNIX_TIMESTAMP(ost_token_ttl) - UNIX_TIMESTAMP(NOW())) as token_ttl + FROM oauth_server_token + WHERE ost_token = \'%s\'', $new_token); + + if (is_numeric($ttl)) + { + $ret['token_ttl'] = intval($ttl); + } + return $ret; + } + + + /** + * Fetch the consumer access token, by access token. + * + * @param string token + * @param int user_id + * @exception OAuthException2 when token is not found + * @return array token and consumer details + */ + public function getConsumerAccessToken ( $token, $user_id ) + { + $rs = $this->query_row_assoc(' + SELECT ost_token as token, + ost_token_secret as token_secret, + ost_referrer_host as token_referrer_host, + osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret, + osr_application_uri as application_uri, + osr_application_title as application_title, + osr_application_descr as application_descr, + osr_callback_uri as callback_uri + FROM oauth_server_token + JOIN oauth_server_registry + ON ost_osr_id_ref = osr_id + WHERE ost_token_type = \'access\' + AND ost_token = \'%s\' + AND ost_usa_id_ref = %d + AND ost_token_ttl >= NOW() + ', $token, $user_id); + + if (empty($rs)) + { + throw new OAuthException2('No server_token "'.$token.'" for user "'.$user_id.'"'); + } + return $rs; + } + + + /** + * Delete a consumer access token. + * + * @param string token + * @param int user_id + * @param boolean user_is_admin + */ + public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) + { + if ($user_is_admin) + { + $this->query(' + DELETE FROM oauth_server_token + WHERE ost_token = \'%s\' + AND ost_token_type = \'access\' + ', $token); + } + else + { + $this->query(' + DELETE FROM oauth_server_token + WHERE ost_token = \'%s\' + AND ost_token_type = \'access\' + AND ost_usa_id_ref = %d + ', $token, $user_id); + } + } + + + /** + * Set the ttl of a consumer access token. This is done when the + * server receives a valid request with a xoauth_token_ttl parameter in it. + * + * @param string token + * @param int ttl + */ + public function setConsumerAccessTokenTtl ( $token, $token_ttl ) + { + if ($token_ttl <= 0) + { + // Immediate delete when the token is past its ttl + $this->deleteConsumerAccessToken($token, 0, true); + } + else + { + // Set maximum time to live for this token + $this->query(' + UPDATE oauth_server_token + SET ost_token_ttl = DATE_ADD(NOW(), INTERVAL %d SECOND) + WHERE ost_token = \'%s\' + AND ost_token_type = \'access\' + ', $token_ttl, $token); + } + } + + + /** + * Fetch a list of all consumer keys, secrets etc. + * Returns the public (user_id is null) and the keys owned by the user + * + * @param int user_id + * @return array + */ + public function listConsumers ( $user_id ) + { + $rs = $this->query_all_assoc(' + SELECT osr_id as id, + osr_usa_id_ref as user_id, + osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret, + osr_enabled as enabled, + osr_status as status, + osr_issue_date as issue_date, + osr_application_uri as application_uri, + osr_application_title as application_title, + osr_application_descr as application_descr, + osr_requester_name as requester_name, + osr_requester_email as requester_email, + osr_callback_uri as callback_uri + FROM oauth_server_registry + WHERE (osr_usa_id_ref = %d OR osr_usa_id_ref IS NULL) + ORDER BY osr_application_title + ', $user_id); + return $rs; + } + + /** + * List of all registered applications. Data returned has not sensitive + * information and therefore is suitable for public displaying. + * + * @param int $begin + * @param int $total + * @return array + */ + public function listConsumerApplications($begin = 0, $total = 25) + { + $rs = $this->query_all_assoc(' + SELECT osr_id as id, + osr_enabled as enabled, + osr_status as status, + osr_issue_date as issue_date, + osr_application_uri as application_uri, + osr_application_title as application_title, + osr_application_descr as application_descr + FROM oauth_server_registry + ORDER BY osr_application_title + '); + // TODO: pagination + return $rs; + } + + /** + * Fetch a list of all consumer tokens accessing the account of the given user. + * + * @param int user_id + * @return array + */ + public function listConsumerTokens ( $user_id ) + { + $rs = $this->query_all_assoc(' + SELECT osr_consumer_key as consumer_key, + osr_consumer_secret as consumer_secret, + osr_enabled as enabled, + osr_status as status, + osr_application_uri as application_uri, + osr_application_title as application_title, + osr_application_descr as application_descr, + ost_timestamp as timestamp, + ost_token as token, + ost_token_secret as token_secret, + ost_referrer_host as token_referrer_host, + osr_callback_uri as callback_uri + FROM oauth_server_registry + JOIN oauth_server_token + ON ost_osr_id_ref = osr_id + WHERE ost_usa_id_ref = %d + AND ost_token_type = \'access\' + AND ost_token_ttl >= NOW() + ORDER BY osr_application_title + ', $user_id); + return $rs; + } + + + /** + * Check an nonce/timestamp combination. Clears any nonce combinations + * that are older than the one received. + * + * @param string consumer_key + * @param string token + * @param int timestamp + * @param string nonce + * @exception OAuthException2 thrown when the timestamp is not in sequence or nonce is not unique + */ + public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) + { + $r = $this->query_row(' + SELECT MAX(osn_timestamp), MAX(osn_timestamp) > %d + %d + FROM oauth_server_nonce + WHERE osn_consumer_key = \'%s\' + AND osn_token = \'%s\' + ', $timestamp, $this->max_timestamp_skew, $consumer_key, $token); + + if (!empty($r) && $r[1]) + { + throw new OAuthException2('Timestamp is out of sequence. Request rejected. Got '.$timestamp.' last max is '.$r[0].' allowed skew is '.$this->max_timestamp_skew); + } + + // Insert the new combination + $this->query(' + INSERT IGNORE INTO oauth_server_nonce + SET osn_consumer_key = \'%s\', + osn_token = \'%s\', + osn_timestamp = %d, + osn_nonce = \'%s\' + ', $consumer_key, $token, $timestamp, $nonce); + + if ($this->query_affected_rows() == 0) + { + throw new OAuthException2('Duplicate timestamp/nonce combination, possible replay attack. Request rejected.'); + } + + // Clean up all timestamps older than the one we just received + $this->query(' + DELETE FROM oauth_server_nonce + WHERE osn_consumer_key = \'%s\' + AND osn_token = \'%s\' + AND osn_timestamp < %d - %d + ', $consumer_key, $token, $timestamp, $this->max_timestamp_skew); + } + + + /** + * Add an entry to the log table + * + * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token) + * @param string received + * @param string sent + * @param string base_string + * @param string notes + * @param int (optional) user_id + */ + public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) + { + $args = array(); + $ps = array(); + foreach ($keys as $key => $value) + { + $args[] = $value; + $ps[] = "olg_$key = '%s'"; + } + + if (!empty($_SERVER['REMOTE_ADDR'])) + { + $remote_ip = $_SERVER['REMOTE_ADDR']; + } + else if (!empty($_SERVER['REMOTE_IP'])) + { + $remote_ip = $_SERVER['REMOTE_IP']; + } + else + { + $remote_ip = '0.0.0.0'; + } + + // Build the SQL + $ps[] = "olg_received = '%s'"; $args[] = $this->makeUTF8($received); + $ps[] = "olg_sent = '%s'"; $args[] = $this->makeUTF8($sent); + $ps[] = "olg_base_string= '%s'"; $args[] = $base_string; + $ps[] = "olg_notes = '%s'"; $args[] = $this->makeUTF8($notes); + $ps[] = "olg_usa_id_ref = NULLIF(%d,0)"; $args[] = $user_id; + $ps[] = "olg_remote_ip = IFNULL(INET_ATON('%s'),0)"; $args[] = $remote_ip; + + $this->query('INSERT INTO oauth_log SET '.implode(',', $ps), $args); + } + + + /** + * Get a page of entries from the log. Returns the last 100 records + * matching the options given. + * + * @param array options + * @param int user_id current user + * @return array log records + */ + public function listLog ( $options, $user_id ) + { + $where = array(); + $args = array(); + if (empty($options)) + { + $where[] = 'olg_usa_id_ref = %d'; + $args[] = $user_id; + } + else + { + foreach ($options as $option => $value) + { + if (strlen($value) > 0) + { + switch ($option) + { + case 'osr_consumer_key': + case 'ocr_consumer_key': + case 'ost_token': + case 'oct_token': + $where[] = 'olg_'.$option.' = \'%s\''; + $args[] = $value; + break; + } + } + } + + $where[] = '(olg_usa_id_ref IS NULL OR olg_usa_id_ref = %d)'; + $args[] = $user_id; + } + + $rs = $this->query_all_assoc(' + SELECT olg_id, + olg_osr_consumer_key AS osr_consumer_key, + olg_ost_token AS ost_token, + olg_ocr_consumer_key AS ocr_consumer_key, + olg_oct_token AS oct_token, + olg_usa_id_ref AS user_id, + olg_received AS received, + olg_sent AS sent, + olg_base_string AS base_string, + olg_notes AS notes, + olg_timestamp AS timestamp, + INET_NTOA(olg_remote_ip) AS remote_ip + FROM oauth_log + WHERE '.implode(' AND ', $where).' + ORDER BY olg_id DESC + LIMIT 0,100', $args); + + return $rs; + } + + + /* ** Some simple helper functions for querying the mysql db ** */ + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + */ + abstract protected function query ( $sql ); + + + /** + * Perform a query, ignore the results + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + abstract protected function query_all_assoc ( $sql ); + + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + abstract protected function query_row_assoc ( $sql ); + + /** + * Perform a query, return the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return array + */ + abstract protected function query_row ( $sql ); + + + /** + * Perform a query, return the first column of the first row + * + * @param string sql + * @param vararg arguments (for sprintf) + * @return mixed + */ + abstract protected function query_one ( $sql ); + + + /** + * Return the number of rows affected in the last query + */ + abstract protected function query_affected_rows (); + + + /** + * Return the id of the last inserted row + * + * @return int + */ + abstract protected function query_insert_id (); + + + abstract protected function sql_printf ( $args ); + + + abstract protected function sql_escape_string ( $s ); + + + abstract protected function sql_errcheck ( $sql ); +} + + +/* vi:set ts=4 sts=4 sw=4 binary noeol: */ + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreSession.php b/3rdparty/oauth-php/library/store/OAuthStoreSession.php new file mode 100644 index 0000000000..4202514aca --- /dev/null +++ b/3rdparty/oauth-php/library/store/OAuthStoreSession.php @@ -0,0 +1,157 @@ +session = &$_SESSION['oauth_' . $options['consumer_key']]; + $this->session['consumer_key'] = $options['consumer_key']; + $this->session['consumer_secret'] = $options['consumer_secret']; + $this->session['signature_methods'] = array('HMAC-SHA1'); + $this->session['server_uri'] = $options['server_uri']; + $this->session['request_token_uri'] = $options['request_token_uri']; + $this->session['authorize_uri'] = $options['authorize_uri']; + $this->session['access_token_uri'] = $options['access_token_uri']; + + } + else + { + throw new OAuthException2("OAuthStoreSession needs consumer_token and consumer_secret"); + } + } + + public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function getSecretsForSignature ( $uri, $user_id ) + { + return $this->session; + } + + public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '') + { + if ($consumer_key != $this->session['consumer_key']) { + return array(); + } + return array( + 'consumer_key' => $consumer_key, + 'consumer_secret' => $this->session['consumer_secret'], + 'token' => $token, + 'token_secret' => $this->session['token_secret'], + 'token_name' => $name, + 'signature_methods' => $this->session['signature_methods'], + 'server_uri' => $this->session['server_uri'], + 'request_token_uri' => $this->session['request_token_uri'], + 'authorize_uri' => $this->session['authorize_uri'], + 'access_token_uri' => $this->session['access_token_uri'], + 'token_ttl' => 3600, + ); + } + + public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) + { + $this->session['token_type'] = $token_type; + $this->session['token'] = $token; + $this->session['token_secret'] = $token_secret; + } + + public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function getServer( $consumer_key, $user_id, $user_is_admin = false ) { + return array( + 'id' => 0, + 'user_id' => $user_id, + 'consumer_key' => $this->session['consumer_key'], + 'consumer_secret' => $this->session['consumer_secret'], + 'signature_methods' => $this->session['signature_methods'], + 'server_uri' => $this->session['server_uri'], + 'request_token_uri' => $this->session['request_token_uri'], + 'authorize_uri' => $this->session['authorize_uri'], + 'access_token_uri' => $this->session['access_token_uri'], + ); + } + + public function getServerForUri ( $uri, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function listServerTokens ( $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function countServerTokens ( $consumer_key ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function getServerToken ( $consumer_key, $token, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) { + // TODO + } + + public function setServerTokenTtl ( $consumer_key, $token, $token_ttl ) + { + //This method just needs to exist. It doesn't have to do anything! + } + + public function listServers ( $q = '', $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function updateServer ( $server, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + + public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function getConsumerStatic () { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + + public function addConsumerRequestToken ( $consumer_key, $options = array() ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function getConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function deleteConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function countConsumerAccessTokens ( $consumer_key ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function getConsumerAccessToken ( $token, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function setConsumerAccessTokenTtl ( $token, $ttl ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + + public function listConsumers ( $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function listConsumerApplications( $begin = 0, $total = 25 ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function listConsumerTokens ( $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + + public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + + public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + public function listLog ( $options, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } + + public function install () { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } +} + +?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/mysql/install.php b/3rdparty/oauth-php/library/store/mysql/install.php new file mode 100644 index 0000000000..0015da5e32 --- /dev/null +++ b/3rdparty/oauth-php/library/store/mysql/install.php @@ -0,0 +1,32 @@ + \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/mysql/mysql.sql b/3rdparty/oauth-php/library/store/mysql/mysql.sql new file mode 100644 index 0000000000..db7f237fdf --- /dev/null +++ b/3rdparty/oauth-php/library/store/mysql/mysql.sql @@ -0,0 +1,236 @@ +# Datamodel for OAuthStoreMySQL +# +# You need to add the foreign key constraints for the user ids your are using. +# I have commented the constraints out, just look for 'usa_id_ref' to enable them. +# +# The --SPLIT-- markers are used by the install.php script +# +# @version $Id: mysql.sql 156 2010-09-16 15:46:49Z brunobg@corollarium.com $ +# @author Marc Worrell +# + +# Changes: +# +# 2010-09-15 +# ALTER TABLE oauth_server_token MODIFY ost_referrer_host varchar(128) not null default ''; +# +# 2010-07-22 +# ALTER TABLE oauth_consumer_registry DROP INDEX ocr_consumer_key; +# ALTER TABLE oauth_consumer_registry ADD UNIQUE ocr_consumer_key(ocr_consumer_key,ocr_usa_id_ref,ocr_server_uri) +# +# 2010-04-20 (on 103 and 110) +# ALTER TABLE oauth_consumer_registry MODIFY ocr_consumer_key varchar(128) binary not null; +# ALTER TABLE oauth_consumer_registry MODIFY ocr_consumer_secret varchar(128) binary not null; +# +# 2010-04-20 (on 103 and 110) +# ALTER TABLE oauth_server_token ADD ost_verifier char(10); +# ALTER TABLE oauth_server_token ADD ost_callback_url varchar(512); +# +# 2008-10-15 (on r48) Added ttl to consumer and server tokens, added named server tokens +# +# ALTER TABLE oauth_server_token +# ADD ost_token_ttl datetime not null default '9999-12-31', +# ADD KEY (ost_token_ttl); +# +# ALTER TABLE oauth_consumer_token +# ADD oct_name varchar(64) binary not null default '', +# ADD oct_token_ttl datetime not null default '9999-12-31', +# DROP KEY oct_usa_id_ref, +# ADD UNIQUE KEY (oct_usa_id_ref, oct_ocr_id_ref, oct_token_type, oct_name), +# ADD KEY (oct_token_ttl); +# +# 2008-09-09 (on r5) Added referrer host to server access token +# +# ALTER TABLE oauth_server_token ADD ost_referrer_host VARCHAR(128) NOT NULL; +# + + +# +# Log table to hold all OAuth request when you enabled logging +# + +CREATE TABLE IF NOT EXISTS oauth_log ( + olg_id int(11) not null auto_increment, + olg_osr_consumer_key varchar(64) binary, + olg_ost_token varchar(64) binary, + olg_ocr_consumer_key varchar(64) binary, + olg_oct_token varchar(64) binary, + olg_usa_id_ref int(11), + olg_received text not null, + olg_sent text not null, + olg_base_string text not null, + olg_notes text not null, + olg_timestamp timestamp not null default current_timestamp, + olg_remote_ip bigint not null, + + primary key (olg_id), + key (olg_osr_consumer_key, olg_id), + key (olg_ost_token, olg_id), + key (olg_ocr_consumer_key, olg_id), + key (olg_oct_token, olg_id), + key (olg_usa_id_ref, olg_id) + +# , foreign key (olg_usa_id_ref) references any_user_auth (usa_id_ref) +# on update cascade +# on delete cascade +) engine=InnoDB default charset=utf8; + +#--SPLIT-- + +# +# /////////////////// CONSUMER SIDE /////////////////// +# + +# This is a registry of all consumer codes we got from other servers +# The consumer_key/secret is obtained from the server +# We also register the server uri, so that we can find the consumer key and secret +# for a certain server. From that server we can check if we have a token for a +# particular user. + +CREATE TABLE IF NOT EXISTS oauth_consumer_registry ( + ocr_id int(11) not null auto_increment, + ocr_usa_id_ref int(11), + ocr_consumer_key varchar(128) binary not null, + ocr_consumer_secret varchar(128) binary not null, + ocr_signature_methods varchar(255) not null default 'HMAC-SHA1,PLAINTEXT', + ocr_server_uri varchar(255) not null, + ocr_server_uri_host varchar(128) not null, + ocr_server_uri_path varchar(128) binary not null, + + ocr_request_token_uri varchar(255) not null, + ocr_authorize_uri varchar(255) not null, + ocr_access_token_uri varchar(255) not null, + ocr_timestamp timestamp not null default current_timestamp, + + primary key (ocr_id), + unique key (ocr_consumer_key, ocr_usa_id_ref, ocr_server_uri), + key (ocr_server_uri), + key (ocr_server_uri_host, ocr_server_uri_path), + key (ocr_usa_id_ref) + +# , foreign key (ocr_usa_id_ref) references any_user_auth(usa_id_ref) +# on update cascade +# on delete set null +) engine=InnoDB default charset=utf8; + +#--SPLIT-- + +# Table used to sign requests for sending to a server by the consumer +# The key is defined for a particular user. Only one single named +# key is allowed per user/server combination + +CREATE TABLE IF NOT EXISTS oauth_consumer_token ( + oct_id int(11) not null auto_increment, + oct_ocr_id_ref int(11) not null, + oct_usa_id_ref int(11) not null, + oct_name varchar(64) binary not null default '', + oct_token varchar(64) binary not null, + oct_token_secret varchar(64) binary not null, + oct_token_type enum('request','authorized','access'), + oct_token_ttl datetime not null default '9999-12-31', + oct_timestamp timestamp not null default current_timestamp, + + primary key (oct_id), + unique key (oct_ocr_id_ref, oct_token), + unique key (oct_usa_id_ref, oct_ocr_id_ref, oct_token_type, oct_name), + key (oct_token_ttl), + + foreign key (oct_ocr_id_ref) references oauth_consumer_registry (ocr_id) + on update cascade + on delete cascade + +# , foreign key (oct_usa_id_ref) references any_user_auth (usa_id_ref) +# on update cascade +# on delete cascade +) engine=InnoDB default charset=utf8; + +#--SPLIT-- + + +# +# ////////////////// SERVER SIDE ///////////////// +# + +# Table holding consumer key/secret combos an user issued to consumers. +# Used for verification of incoming requests. + +CREATE TABLE IF NOT EXISTS oauth_server_registry ( + osr_id int(11) not null auto_increment, + osr_usa_id_ref int(11), + osr_consumer_key varchar(64) binary not null, + osr_consumer_secret varchar(64) binary not null, + osr_enabled tinyint(1) not null default '1', + osr_status varchar(16) not null, + osr_requester_name varchar(64) not null, + osr_requester_email varchar(64) not null, + osr_callback_uri varchar(255) not null, + osr_application_uri varchar(255) not null, + osr_application_title varchar(80) not null, + osr_application_descr text not null, + osr_application_notes text not null, + osr_application_type varchar(20) not null, + osr_application_commercial tinyint(1) not null default '0', + osr_issue_date datetime not null, + osr_timestamp timestamp not null default current_timestamp, + + primary key (osr_id), + unique key (osr_consumer_key), + key (osr_usa_id_ref) + +# , foreign key (osr_usa_id_ref) references any_user_auth(usa_id_ref) +# on update cascade +# on delete set null +) engine=InnoDB default charset=utf8; + +#--SPLIT-- + +# Nonce used by a certain consumer, every used nonce should be unique, this prevents +# replaying attacks. We need to store all timestamp/nonce combinations for the +# maximum timestamp received. + +CREATE TABLE IF NOT EXISTS oauth_server_nonce ( + osn_id int(11) not null auto_increment, + osn_consumer_key varchar(64) binary not null, + osn_token varchar(64) binary not null, + osn_timestamp bigint not null, + osn_nonce varchar(80) binary not null, + + primary key (osn_id), + unique key (osn_consumer_key, osn_token, osn_timestamp, osn_nonce) +) engine=InnoDB default charset=utf8; + +#--SPLIT-- + +# Table used to verify signed requests sent to a server by the consumer +# When the verification is succesful then the associated user id is returned. + +CREATE TABLE IF NOT EXISTS oauth_server_token ( + ost_id int(11) not null auto_increment, + ost_osr_id_ref int(11) not null, + ost_usa_id_ref int(11) not null, + ost_token varchar(64) binary not null, + ost_token_secret varchar(64) binary not null, + ost_token_type enum('request','access'), + ost_authorized tinyint(1) not null default '0', + ost_referrer_host varchar(128) not null default '', + ost_token_ttl datetime not null default '9999-12-31', + ost_timestamp timestamp not null default current_timestamp, + ost_verifier char(10), + ost_callback_url varchar(512), + + primary key (ost_id), + unique key (ost_token), + key (ost_osr_id_ref), + key (ost_token_ttl), + + foreign key (ost_osr_id_ref) references oauth_server_registry (osr_id) + on update cascade + on delete cascade + +# , foreign key (ost_usa_id_ref) references any_user_auth (usa_id_ref) +# on update cascade +# on delete cascade +) engine=InnoDB default charset=utf8; + + + diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql b/3rdparty/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql new file mode 100644 index 0000000000..3d4fa22d6f --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql @@ -0,0 +1,114 @@ +CREATE TABLE oauth_log +( + olg_id number, + olg_osr_consumer_key varchar2(64), + olg_ost_token varchar2(64), + olg_ocr_consumer_key varchar2(64), + olg_oct_token varchar2(64), + olg_usa_id_ref number, + olg_received varchar2(500), + olg_sent varchar2(500), + olg_base_string varchar2(500), + olg_notes varchar2(500), + olg_timestamp date default sysdate, + olg_remote_ip varchar2(50) +); + +alter table oauth_log + add constraint oauth_log_pk primary key (olg_id); + + +CREATE TABLE oauth_consumer_registry +( + ocr_id number, + ocr_usa_id_ref number, + ocr_consumer_key varchar2(64), + ocr_consumer_secret varchar2(64), + ocr_signature_methods varchar2(255)default 'HMAC-SHA1,PLAINTEXT', + ocr_server_uri varchar2(255), + ocr_server_uri_host varchar2(128), + ocr_server_uri_path varchar2(128), + ocr_request_token_uri varchar2(255), + ocr_authorize_uri varchar2(255), + ocr_access_token_uri varchar2(255), + ocr_timestamp date default sysdate +) + +alter table oauth_consumer_registry + add constraint oauth_consumer_registry_pk primary key (ocr_id); + + +CREATE TABLE oauth_consumer_token +( + oct_id number, + oct_ocr_id_ref number, + oct_usa_id_ref number, + oct_name varchar2(64) default '', + oct_token varchar2(64), + oct_token_secret varchar2(64), + oct_token_type varchar2(20), -- enum('request','authorized','access'), + oct_token_ttl date default TO_DATE('9999.12.31', 'yyyy.mm.dd'), + oct_timestamp date default sysdate +); + +alter table oauth_consumer_token + add constraint oauth_consumer_token_pk primary key (oct_id); + + +CREATE TABLE oauth_server_registry +( + osr_id number, + osr_usa_id_ref number, + osr_consumer_key varchar2(64), + osr_consumer_secret varchar2(64), + osr_enabled integer default '1', + osr_status varchar2(16), + osr_requester_name varchar2(64), + osr_requester_email varchar2(64), + osr_callback_uri varchar2(255), + osr_application_uri varchar2(255), + osr_application_title varchar2(80), + osr_application_descr varchar2(500), + osr_application_notes varchar2(500), + osr_application_type varchar2(20), + osr_application_commercial integer default '0', + osr_issue_date date, + osr_timestamp date default sysdate +); + + +alter table oauth_server_registry + add constraint oauth_server_registry_pk primary key (osr_id); + + +CREATE TABLE oauth_server_nonce +( + osn_id number, + osn_consumer_key varchar2(64), + osn_token varchar2(64), + osn_timestamp number, + osn_nonce varchar2(80) +); + +alter table oauth_server_nonce + add constraint oauth_server_nonce_pk primary key (osn_id); + + +CREATE TABLE oauth_server_token +( + ost_id number, + ost_osr_id_ref number, + ost_usa_id_ref number, + ost_token varchar2(64), + ost_token_secret varchar2(64), + ost_token_type varchar2(20), -- enum('request','access'), + ost_authorized integer default '0', + ost_referrer_host varchar2(128), + ost_token_ttl date default TO_DATE('9999.12.31', 'yyyy.mm.dd'), + ost_timestamp date default sysdate, + ost_verifier varchar2(10), + ost_callback_url varchar2(512) +); + +alter table oauth_server_token + add constraint oauth_server_token_pk primary key (ost_id); \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql b/3rdparty/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql new file mode 100644 index 0000000000..53e4227888 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql @@ -0,0 +1,9 @@ +CREATE SEQUENCE SEQ_OCT_ID NOCACHE; + +CREATE SEQUENCE SEQ_OCR_ID NOCACHE; + +CREATE SEQUENCE SEQ_OSR_ID NOCACHE; + +CREATE SEQUENCE SEQ_OSN_ID NOCACHE; + +CREATE SEQUENCE SEQ_OLG_ID NOCACHE; diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc new file mode 100644 index 0000000000..efb9536502 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc @@ -0,0 +1,71 @@ +CREATE OR REPLACE PROCEDURE SP_ADD_CONSUMER_REQUEST_TOKEN +( +P_TOKEN_TTL IN NUMBER, -- IN SECOND +P_CONSUMER_KEY IN VARCHAR2, +P_TOKEN IN VARCHAR2, +P_TOKEN_SECRET IN VARCHAR2, +P_CALLBACK_URL IN VARCHAR2, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Add an unautorized request token to our server. + +V_OSR_ID NUMBER; +V_OSR_ID_REF NUMBER; + +V_EXC_NO_SERVER_EXIST EXCEPTION; +BEGIN + + P_RESULT := 0; + + BEGIN + SELECT OSR_ID INTO V_OSR_ID + FROM OAUTH_SERVER_REGISTRY + WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY + AND OSR_ENABLED = 1; + EXCEPTION + WHEN NO_DATA_FOUND THEN + RAISE V_EXC_NO_SERVER_EXIST; + END; + + +BEGIN + SELECT OST_OSR_ID_REF INTO V_OSR_ID_REF + FROM OAUTH_SERVER_TOKEN + WHERE OST_OSR_ID_REF = V_OSR_ID; + + UPDATE OAUTH_SERVER_TOKEN + SET OST_OSR_ID_REF = V_OSR_ID, + OST_USA_ID_REF = 1, + OST_TOKEN = P_TOKEN, + OST_TOKEN_SECRET = P_TOKEN_SECRET, + OST_TOKEN_TYPE = 'REQUEST', + OST_TOKEN_TTL = SYSDATE + (P_TOKEN_TTL/(24*60*60)), + OST_CALLBACK_URL = P_CALLBACK_URL, + OST_TIMESTAMP = SYSDATE + WHERE OST_OSR_ID_REF = V_OSR_ID_REF; + + + EXCEPTION + WHEN NO_DATA_FOUND THEN + + INSERT INTO OAUTH_SERVER_TOKEN + (OST_ID, OST_OSR_ID_REF, OST_USA_ID_REF, OST_TOKEN, OST_TOKEN_SECRET, OST_TOKEN_TYPE, + OST_TOKEN_TTL, OST_CALLBACK_URL) + VALUES + (SEQ_OCT_ID.NEXTVAL, V_OSR_ID, 1, P_TOKEN, P_TOKEN_SECRET, 'REQUEST', SYSDATE + (P_TOKEN_TTL/(24*60*60)), + P_CALLBACK_URL); + + END; + + +EXCEPTION +WHEN V_EXC_NO_SERVER_EXIST THEN +P_RESULT := 2; -- NO_SERVER_EXIST +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc new file mode 100644 index 0000000000..329499d9c9 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc @@ -0,0 +1,31 @@ +CREATE OR REPLACE PROCEDURE SP_ADD_LOG +( +P_RECEIVED IN VARCHAR2, +P_SENT IN VARCHAR2, +P_BASE_STRING IN VARCHAR2, +P_NOTES IN VARCHAR2, +P_USA_ID_REF IN NUMBER, +P_REMOTE_IP IN VARCHAR2, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Add an entry to the log table + +BEGIN + + P_RESULT := 0; + + INSERT INTO oauth_log + (OLG_ID, olg_received, olg_sent, olg_base_string, olg_notes, olg_usa_id_ref, olg_remote_ip) + VALUES + (SEQ_OLG_ID.NEXTVAL, P_RECEIVED, P_SENT, P_BASE_STRING, P_NOTES, NVL(P_USA_ID_REF, 0), P_REMOTE_IP); + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc new file mode 100644 index 0000000000..371134c9b6 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc @@ -0,0 +1,55 @@ +CREATE OR REPLACE PROCEDURE SP_ADD_SERVER_TOKEN +( +P_CONSUMER_KEY IN VARCHAR2, +P_USER_ID IN NUMBER, +P_NAME IN VARCHAR2, +P_TOKEN_TYPE IN VARCHAR2, +P_TOKEN IN VARCHAR2, +P_TOKEN_SECRET IN VARCHAR2, +P_TOKEN_INTERVAL_IN_SEC IN NUMBER, +P_RESULT OUT NUMBER +) +AS + + -- Add a request token we obtained from a server. +V_OCR_ID NUMBER; +V_TOKEN_TTL DATE; + +V_EXC_INVALID_CONSUMER_KEY EXCEPTION; +BEGIN +P_RESULT := 0; + + BEGIN + SELECT OCR_ID INTO V_OCR_ID FROM OAUTH_CONSUMER_REGISTRY + WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY AND OCR_USA_ID_REF = P_USER_ID; + EXCEPTION + WHEN NO_DATA_FOUND THEN + RAISE V_EXC_INVALID_CONSUMER_KEY; + END; + + DELETE FROM OAUTH_CONSUMER_TOKEN + WHERE OCT_OCR_ID_REF = V_OCR_ID + AND OCT_USA_ID_REF = P_USER_ID + AND UPPER(OCT_TOKEN_TYPE) = UPPER(P_TOKEN_TYPE) + AND OCT_NAME = P_NAME; + + IF P_TOKEN_INTERVAL_IN_SEC IS NOT NULL THEN + V_TOKEN_TTL := SYSDATE + (P_TOKEN_INTERVAL_IN_SEC/(24*60*60)); + ELSE + V_TOKEN_TTL := TO_DATE('9999.12.31', 'yyyy.mm.dd'); + END IF; + + INSERT INTO OAUTH_CONSUMER_TOKEN + (OCT_ID, OCT_OCR_ID_REF,OCT_USA_ID_REF, OCT_NAME, OCT_TOKEN, OCT_TOKEN_SECRET, OCT_TOKEN_TYPE, OCT_TIMESTAMP, OCT_TOKEN_TTL) + VALUES + (SEQ_OCT_ID.NEXTVAL, V_OCR_ID, P_USER_ID, P_NAME, P_TOKEN, P_TOKEN_SECRET, UPPER(P_TOKEN_TYPE), SYSDATE, V_TOKEN_TTL); + +EXCEPTION +WHEN V_EXC_INVALID_CONSUMER_KEY THEN +P_RESULT := 2; -- INVALID_CONSUMER_KEY +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc new file mode 100644 index 0000000000..c3693491d5 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc @@ -0,0 +1,32 @@ +CREATE OR REPLACE PROCEDURE SP_AUTH_CONSUMER_REQ_TOKEN +( +P_USER_ID IN NUMBER, +P_REFERRER_HOST IN VARCHAR2, +P_VERIFIER IN VARCHAR2, +P_TOKEN IN VARCHAR2, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Fetch the consumer request token, by request token. +BEGIN +P_RESULT := 0; + + +UPDATE OAUTH_SERVER_TOKEN + SET OST_AUTHORIZED = 1, + OST_USA_ID_REF = P_USER_ID, + OST_TIMESTAMP = SYSDATE, + OST_REFERRER_HOST = P_REFERRER_HOST, + OST_VERIFIER = P_VERIFIER + WHERE OST_TOKEN = P_TOKEN + AND OST_TOKEN_TYPE = 'REQUEST'; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc new file mode 100644 index 0000000000..444a70fcc8 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc @@ -0,0 +1,81 @@ +CREATE OR REPLACE PROCEDURE SP_CHECK_SERVER_NONCE +( +P_CONSUMER_KEY IN VARCHAR2, +P_TOKEN IN VARCHAR2, +P_TIMESTAMP IN NUMBER, +P_MAX_TIMESTAMP_SKEW IN NUMBER, +P_NONCE IN VARCHAR2, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Check an nonce/timestamp combination. Clears any nonce combinations + -- that are older than the one received. +V_IS_MAX NUMBER; +V_MAX_TIMESTAMP NUMBER; +V_IS_DUPLICATE_TIMESTAMP NUMBER; + +V_EXC_INVALID_TIMESTAMP EXCEPTION; +V_EXC_DUPLICATE_TIMESTAMP EXCEPTION; +BEGIN + + P_RESULT := 0; + + BEGIN + SELECT MAX(OSN_TIMESTAMP), + CASE + WHEN MAX(OSN_TIMESTAMP) > (P_TIMESTAMP + P_MAX_TIMESTAMP_SKEW) THEN 1 ELSE 0 + END "IS_MAX" INTO V_MAX_TIMESTAMP, V_IS_MAX + FROM OAUTH_SERVER_NONCE + WHERE OSN_CONSUMER_KEY = P_CONSUMER_KEY + AND OSN_TOKEN = P_TOKEN; + + IF V_IS_MAX = 1 THEN + RAISE V_EXC_INVALID_TIMESTAMP; + END IF; + + EXCEPTION + WHEN NO_DATA_FOUND THEN + NULL; + END; + + BEGIN + SELECT 1 INTO V_IS_DUPLICATE_TIMESTAMP FROM DUAL WHERE EXISTS + (SELECT OSN_ID FROM OAUTH_SERVER_NONCE + WHERE OSN_CONSUMER_KEY = P_CONSUMER_KEY + AND OSN_TOKEN = P_TOKEN + AND OSN_TIMESTAMP = P_TIMESTAMP + AND OSN_NONCE = P_NONCE); + + IF V_IS_DUPLICATE_TIMESTAMP = 1 THEN + RAISE V_EXC_DUPLICATE_TIMESTAMP; + END IF; + EXCEPTION + WHEN NO_DATA_FOUND THEN + NULL; + END; + + -- Insert the new combination + INSERT INTO OAUTH_SERVER_NONCE + (OSN_ID, OSN_CONSUMER_KEY, OSN_TOKEN, OSN_TIMESTAMP, OSN_NONCE) + VALUES + (SEQ_OSN_ID.NEXTVAL, P_CONSUMER_KEY, P_TOKEN, P_TIMESTAMP, P_NONCE); + + -- Clean up all timestamps older than the one we just received + DELETE FROM OAUTH_SERVER_NONCE + WHERE OSN_CONSUMER_KEY = P_CONSUMER_KEY + AND OSN_TOKEN = P_TOKEN + AND OSN_TIMESTAMP < (P_TIMESTAMP - P_MAX_TIMESTAMP_SKEW); + + +EXCEPTION +WHEN V_EXC_INVALID_TIMESTAMP THEN +P_RESULT := 2; -- INVALID_TIMESTAMP +WHEN V_EXC_DUPLICATE_TIMESTAMP THEN +P_RESULT := 3; -- DUPLICATE_TIMESTAMP +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc new file mode 100644 index 0000000000..047c77bf2d --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc @@ -0,0 +1,28 @@ +CREATE OR REPLACE PROCEDURE SP_CONSUMER_STATIC_SAVE +( +P_OSR_CONSUMER_KEY IN VARCHAR2, +P_RESULT OUT NUMBER +) +AS + +-- PROCEDURE TO Fetch the static consumer key for this provider. +BEGIN +P_RESULT := 0; + + + INSERT INTO OAUTH_SERVER_REGISTRY + (OSR_ID, OSR_ENABLED, OSR_STATUS, OSR_USA_ID_REF, OSR_CONSUMER_KEY, OSR_CONSUMER_SECRET, OSR_REQUESTER_NAME, OSR_REQUESTER_EMAIL, OSR_CALLBACK_URI, + OSR_APPLICATION_URI, OSR_APPLICATION_TITLE, OSR_APPLICATION_DESCR, OSR_APPLICATION_NOTES, + OSR_APPLICATION_TYPE, OSR_APPLICATION_COMMERCIAL, OSR_TIMESTAMP,OSR_ISSUE_DATE) + VALUES + (SEQ_OSR_ID.NEXTVAL, 1, 'ACTIVE', NULL, P_OSR_CONSUMER_KEY, '\', '\', '\', '\', '\', + 'STATIC SHARED CONSUMER KEY', '\', 'STATIC SHARED CONSUMER KEY', '\', 0, SYSDATE, SYSDATE); + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc new file mode 100644 index 0000000000..f7099b9795 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc @@ -0,0 +1,27 @@ +CREATE OR REPLACE PROCEDURE SP_COUNT_CONSUMER_ACCESS_TOKEN +( +P_CONSUMER_KEY IN VARCHAR2, +P_COUNT OUT NUMBER, +P_RESULT OUT NUMBER +) +AS +-- PROCEDURE TO Count the consumer access tokens for the given consumer. +BEGIN +P_RESULT := 0; + +SELECT COUNT(OST_ID) INTO P_COUNT + FROM OAUTH_SERVER_TOKEN + JOIN OAUTH_SERVER_REGISTRY + ON OST_OSR_ID_REF = OSR_ID + WHERE OST_TOKEN_TYPE = 'ACCESS' + AND OSR_CONSUMER_KEY = P_CONSUMER_KEY + AND OST_TOKEN_TTL >= SYSDATE; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc new file mode 100644 index 0000000000..c73b366822 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc @@ -0,0 +1,28 @@ +CREATE OR REPLACE PROCEDURE SP_COUNT_SERVICE_TOKENS +( +P_CONSUMER_KEY IN VARCHAR2, +P_COUNT OUT NUMBER, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Count how many tokens we have for the given server +BEGIN +P_RESULT := 0; + + SELECT COUNT(OCT_ID) INTO P_COUNT + FROM OAUTH_CONSUMER_TOKEN + JOIN OAUTH_CONSUMER_REGISTRY + ON OCT_OCR_ID_REF = OCR_ID + WHERE OCT_TOKEN_TYPE = 'ACCESS' + AND OCR_CONSUMER_KEY = P_CONSUMER_KEY + AND OCT_TOKEN_TTL >= SYSDATE; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc new file mode 100644 index 0000000000..3f18562ef7 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc @@ -0,0 +1,35 @@ +CREATE OR REPLACE PROCEDURE SP_DELETE_CONSUMER +( +P_CONSUMER_KEY IN VARCHAR2, +P_USER_ID IN NUMBER, +P_USER_IS_ADMIN IN NUMBER, --0:NO; 1:YES +P_RESULT OUT NUMBER +) +AS + + -- Delete a consumer key. This removes access to our site for all applications using this key. + +BEGIN +P_RESULT := 0; + +IF P_USER_IS_ADMIN = 1 THEN + + DELETE FROM OAUTH_SERVER_REGISTRY + WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY + AND (OSR_USA_ID_REF = P_USER_ID OR OSR_USA_ID_REF IS NULL); + +ELSIF P_USER_IS_ADMIN = 0 THEN + + DELETE FROM OAUTH_SERVER_REGISTRY + WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY + AND OSR_USA_ID_REF = P_USER_ID; + +END IF; + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc new file mode 100644 index 0000000000..ba259dee98 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc @@ -0,0 +1,35 @@ +CREATE OR REPLACE PROCEDURE SP_DELETE_SERVER +( +P_CONSUMER_KEY IN VARCHAR2, +P_USER_ID IN NUMBER, +P_USER_IS_ADMIN IN NUMBER, --0:NO; 1:YES +P_RESULT OUT NUMBER +) +AS + + -- Delete a server key. This removes access to that site. + +BEGIN +P_RESULT := 0; + +IF P_USER_IS_ADMIN = 1 THEN + + DELETE FROM OAUTH_CONSUMER_REGISTRY + WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY + AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL); + +ELSIF P_USER_IS_ADMIN = 0 THEN + + DELETE FROM OAUTH_CONSUMER_REGISTRY + WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY + AND OCR_USA_ID_REF = P_USER_ID; + +END IF; + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc new file mode 100644 index 0000000000..de9d45007b --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc @@ -0,0 +1,37 @@ +CREATE OR REPLACE PROCEDURE SP_DELETE_SERVER_TOKEN +( +P_CONSUMER_KEY IN VARCHAR2, +P_USER_ID IN NUMBER, +P_TOKEN IN VARCHAR2, +P_USER_IS_ADMIN IN NUMBER, --0:NO; 1:YES +P_RESULT OUT NUMBER +) +AS + + -- Delete a token we obtained from a server. + +BEGIN +P_RESULT := 0; + +IF P_USER_IS_ADMIN = 1 THEN + + DELETE FROM OAUTH_CONSUMER_TOKEN + WHERE OCT_TOKEN = P_TOKEN + AND OCT_OCR_ID_REF IN (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY); + +ELSIF P_USER_IS_ADMIN = 0 THEN + + DELETE FROM OAUTH_CONSUMER_TOKEN + WHERE OCT_TOKEN = P_TOKEN + AND OCT_USA_ID_REF = P_USER_ID + AND OCT_OCR_ID_REF IN (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY); + +END IF; + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc new file mode 100644 index 0000000000..4281bdb9de --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc @@ -0,0 +1,33 @@ +CREATE OR REPLACE PROCEDURE SP_DEL_CONSUMER_ACCESS_TOKEN +( +P_USER_ID IN NUMBER, +P_TOKEN IN VARCHAR2, +P_USER_IS_ADMIN IN NUMBER, -- 1:YES; 0:NO +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Delete a consumer access token. + +BEGIN + + P_RESULT := 0; + + IF P_USER_IS_ADMIN = 1 THEN + DELETE FROM OAUTH_SERVER_TOKEN + WHERE OST_TOKEN = P_TOKEN + AND OST_TOKEN_TYPE = 'ACCESS'; + ELSE + DELETE FROM OAUTH_SERVER_TOKEN + WHERE OST_TOKEN = P_TOKEN + AND OST_TOKEN_TYPE = 'ACCESS' + AND OST_USA_ID_REF = P_USER_ID; + END IF; + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc new file mode 100644 index 0000000000..01678d6bd4 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc @@ -0,0 +1,25 @@ +CREATE OR REPLACE PROCEDURE SP_DEL_CONSUMER_REQUEST_TOKEN +( +P_TOKEN IN VARCHAR2, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Delete a consumer token. The token must be a request or authorized token. + +BEGIN + + P_RESULT := 0; + + DELETE FROM OAUTH_SERVER_TOKEN + WHERE OST_TOKEN = P_TOKEN + AND OST_TOKEN_TYPE = 'REQUEST'; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc new file mode 100644 index 0000000000..66a53ed836 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc @@ -0,0 +1,96 @@ +CREATE OR REPLACE PROCEDURE SP_EXCH_CONS_REQ_FOR_ACC_TOKEN +( +P_TOKEN_TTL IN NUMBER, -- IN SECOND +P_NEW_TOKEN IN VARCHAR2, +P_TOKEN IN VARCHAR2, +P_TOKEN_SECRET IN VARCHAR2, +P_VERIFIER IN VARCHAR2, +P_OUT_TOKEN_TTL OUT NUMBER, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Add an unautorized request token to our server. + +V_TOKEN_EXIST NUMBER; + + +V_EXC_NO_TOKEN_EXIST EXCEPTION; +BEGIN + + P_RESULT := 0; + + IF P_VERIFIER IS NOT NULL THEN + + BEGIN + SELECT 1 INTO V_TOKEN_EXIST FROM DUAL WHERE EXISTS + (SELECT OST_TOKEN FROM OAUTH_SERVER_TOKEN + WHERE OST_TOKEN = P_TOKEN + AND OST_TOKEN_TYPE = 'REQUEST' + AND OST_AUTHORIZED = 1 + AND OST_TOKEN_TTL >= SYSDATE + AND OST_VERIFIER = P_VERIFIER); + EXCEPTION + WHEN NO_DATA_FOUND THEN + RAISE V_EXC_NO_TOKEN_EXIST; + END; + + UPDATE OAUTH_SERVER_TOKEN + SET OST_TOKEN = P_NEW_TOKEN, + OST_TOKEN_SECRET = P_TOKEN_SECRET, + OST_TOKEN_TYPE = 'ACCESS', + OST_TIMESTAMP = SYSDATE, + OST_TOKEN_TTL = NVL(SYSDATE + (P_TOKEN_TTL/(24*60*60)), TO_DATE('9999.12.31', 'yyyy.mm.dd')) + WHERE OST_TOKEN = P_TOKEN + AND OST_TOKEN_TYPE = 'REQUEST' + AND OST_AUTHORIZED = 1 + AND OST_TOKEN_TTL >= SYSDATE + AND OST_VERIFIER = P_VERIFIER; + + ELSE + BEGIN + SELECT 1 INTO V_TOKEN_EXIST FROM DUAL WHERE EXISTS + (SELECT OST_TOKEN FROM OAUTH_SERVER_TOKEN + WHERE OST_TOKEN = P_TOKEN + AND OST_TOKEN_TYPE = 'REQUEST' + AND OST_AUTHORIZED = 1 + AND OST_TOKEN_TTL >= SYSDATE); + EXCEPTION + WHEN NO_DATA_FOUND THEN + RAISE V_EXC_NO_TOKEN_EXIST; + END; + + UPDATE OAUTH_SERVER_TOKEN + SET OST_TOKEN = P_NEW_TOKEN, + OST_TOKEN_SECRET = P_TOKEN_SECRET, + OST_TOKEN_TYPE = 'ACCESS', + OST_TIMESTAMP = SYSDATE, + OST_TOKEN_TTL = NVL(SYSDATE + (P_TOKEN_TTL/(24*60*60)), TO_DATE('9999.12.31', 'yyyy.mm.dd')) + WHERE OST_TOKEN = P_TOKEN + AND OST_TOKEN_TYPE = 'REQUEST' + AND OST_AUTHORIZED = 1 + AND OST_TOKEN_TTL >= SYSDATE; + + + END IF; + + SELECT CASE + WHEN OST_TOKEN_TTL >= TO_DATE('9999.12.31', 'yyyy.mm.dd') THEN NULL ELSE (OST_TOKEN_TTL - SYSDATE)*24*60*60 + END "TOKEN_TTL" INTO P_OUT_TOKEN_TTL + FROM OAUTH_SERVER_TOKEN + WHERE OST_TOKEN = P_NEW_TOKEN; + + + + + + +EXCEPTION +WHEN V_EXC_NO_TOKEN_EXIST THEN +P_RESULT := 2; -- NO_TOKEN_EXIST +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc new file mode 100644 index 0000000000..4225ff212f --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc @@ -0,0 +1,41 @@ +CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER +( +P_CONSUMER_KEY IN STRING, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Fetch a consumer of this server, by consumer_key. +BEGIN +P_RESULT := 0; + +OPEN P_ROWS FOR + SELECT OSR_ID "osr_id", + OSR_USA_ID_REF "osr_usa_id_ref", + OSR_CONSUMER_KEY "osr_consumer_key", + OSR_CONSUMER_SECRET "osr_consumer_secret", + OSR_ENABLED "osr_enabled", + OSR_STATUS "osr_status", + OSR_REQUESTER_NAME "osr_requester_name", + OSR_REQUESTER_EMAIL "osr_requester_email", + OSR_CALLBACK_URI "osr_callback_uri", + OSR_APPLICATION_URI "osr_application_uri", + OSR_APPLICATION_TITLE "osr_application_title", + OSR_APPLICATION_DESCR "osr_application_descr", + OSR_APPLICATION_NOTES "osr_application_notes", + OSR_APPLICATION_TYPE "osr_application_type", + OSR_APPLICATION_COMMERCIAL "osr_application_commercial", + OSR_ISSUE_DATE "osr_issue_date", + OSR_TIMESTAMP "osr_timestamp" + FROM OAUTH_SERVER_REGISTRY + WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc new file mode 100644 index 0000000000..0db2ea9caa --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc @@ -0,0 +1,43 @@ +CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER_ACCESS_TOKEN +( +P_USER_ID IN NUMBER, +P_TOKEN IN VARCHAR2, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Fetch the consumer access token, by access token. + +BEGIN + + P_RESULT := 0; + + + OPEN P_ROWS FOR + SELECT OST_TOKEN "token", + OST_TOKEN_SECRET "token_secret", + OST_REFERRER_HOST "token_referrer_host", + OSR_CONSUMER_KEY "consumer_key", + OSR_CONSUMER_SECRET "consumer_secret", + OSR_APPLICATION_URI "application_uri", + OSR_APPLICATION_TITLE "application_title", + OSR_APPLICATION_DESCR "application_descr", + OSR_CALLBACK_URI "callback_uri" + FROM OAUTH_SERVER_TOKEN + JOIN OAUTH_SERVER_REGISTRY + ON OST_OSR_ID_REF = OSR_ID + WHERE OST_TOKEN_TYPE = 'ACCESS' + AND OST_TOKEN = P_TOKEN + AND OST_USA_ID_REF = P_USER_ID + AND OST_TOKEN_TTL >= SYSDATE; + + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc new file mode 100644 index 0000000000..6d3b590613 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc @@ -0,0 +1,41 @@ +CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER_REQUEST_TOKEN +( +P_TOKEN IN VARCHAR2, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Fetch the consumer request token, by request token. +BEGIN +P_RESULT := 0; + +OPEN P_ROWS FOR + +SELECT OST_TOKEN "token", + OST_TOKEN_SECRET "token_secret", + OSR_CONSUMER_KEY "consumer_key", + OSR_CONSUMER_SECRET "consumer_secret", + OST_TOKEN_TYPE "token_type", + OST_CALLBACK_URL "callback_url", + OSR_APPLICATION_TITLE "application_title", + OSR_APPLICATION_DESCR "application_descr", + OSR_APPLICATION_URI "application_uri" + FROM OAUTH_SERVER_TOKEN + JOIN OAUTH_SERVER_REGISTRY + ON OST_OSR_ID_REF = OSR_ID + WHERE OST_TOKEN_TYPE = 'REQUEST' + AND OST_TOKEN = P_TOKEN + AND OST_TOKEN_TTL >= SYSDATE; + + + + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc new file mode 100644 index 0000000000..1126ef6aea --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc @@ -0,0 +1,25 @@ +CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER_STATIC_SELECT +( +P_OSR_CONSUMER_KEY OUT VARCHAR2, +P_RESULT OUT NUMBER +) +AS + +-- PROCEDURE TO Fetch the static consumer key for this provider. +BEGIN +P_RESULT := 0; + + + SELECT OSR_CONSUMER_KEY INTO P_OSR_CONSUMER_KEY + FROM OAUTH_SERVER_REGISTRY + WHERE OSR_CONSUMER_KEY LIKE 'sc-%%' + AND OSR_USA_ID_REF IS NULL; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc new file mode 100644 index 0000000000..2af7847531 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc @@ -0,0 +1,43 @@ +CREATE OR REPLACE PROCEDURE SP_GET_SECRETS_FOR_SIGNATURE +( +P_HOST IN VARCHAR2, +P_PATH IN VARCHAR2, +P_USER_ID IN NUMBER, +P_NAME IN VARCHAR2, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Find the server details for signing a request, always looks for an access token. + -- The returned credentials depend on which local user is making the request. +BEGIN +P_RESULT := 0; + + OPEN P_ROWS FOR + SELECT * FROM ( + SELECT OCR_CONSUMER_KEY "consumer_key", + OCR_CONSUMER_SECRET "consumer_secret", + OCT_TOKEN "token", + OCT_TOKEN_SECRET "token_secret", + OCR_SIGNATURE_METHODS "signature_methods" + FROM OAUTH_CONSUMER_REGISTRY + JOIN OAUTH_CONSUMER_TOKEN ON OCT_OCR_ID_REF = OCR_ID + WHERE OCR_SERVER_URI_HOST = P_HOST + AND OCR_SERVER_URI_PATH = SUBSTR(P_PATH, 1, LENGTH(OCR_SERVER_URI_PATH)) + AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL) + AND OCT_USA_ID_REF = P_USER_ID + AND OCT_TOKEN_TYPE = 'ACCESS' + AND OCT_NAME = P_NAME + AND OCT_TOKEN_TTL >= SYSDATE + ORDER BY OCR_USA_ID_REF DESC, OCR_CONSUMER_SECRET DESC, LENGTH(OCR_SERVER_URI_PATH) DESC + ) WHERE ROWNUM<=1; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc new file mode 100644 index 0000000000..4fbb435c85 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc @@ -0,0 +1,52 @@ +CREATE OR REPLACE PROCEDURE SP_GET_SECRETS_FOR_VERIFY +( +P_CONSUMER_KEY IN VARCHAR2, +P_TOKEN IN VARCHAR2, +P_TOKEN_TYPE IN VARCHAR2, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE to Find stored credentials for the consumer key and token. Used by an OAuth server + -- when verifying an OAuth request. + +BEGIN +P_RESULT := 0; + +IF P_TOKEN_TYPE IS NULL THEN + OPEN P_ROWS FOR + SELECT OSR.OSR_ID "osr_id", + OSR.OSR_CONSUMER_KEY "consumer_key", + OSR.OSR_CONSUMER_SECRET "consumer_secret" + FROM OAUTH_SERVER_REGISTRY OSR + WHERE OSR.OSR_CONSUMER_KEY = P_CONSUMER_KEY + AND OSR.OSR_ENABLED = 1; +ELSE + OPEN P_ROWS FOR + SELECT OSR.OSR_ID "osr_id", + OST.OST_ID "ost_id", + OST.OST_USA_ID_REF "user_id", + OSR.OSR_CONSUMER_KEY "consumer_key", + OSR.OSR_CONSUMER_SECRET "consumer_secret", + OST.OST_TOKEN "token", + OST.OST_TOKEN_SECRET "token_secret" + FROM OAUTH_SERVER_REGISTRY OSR, OAUTH_SERVER_TOKEN OST + WHERE OST.OST_OSR_ID_REF = OSR.OSR_ID + AND upper(OST.OST_TOKEN_TYPE) = upper(P_TOKEN_TYPE) + AND OSR.OSR_CONSUMER_KEY = P_CONSUMER_KEY + AND OST.OST_TOKEN = P_TOKEN + AND OSR.OSR_ENABLED = 1 + AND OST.OST_TOKEN_TTL >= SYSDATE; + +END IF; + + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc new file mode 100644 index 0000000000..af7d2755b7 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc @@ -0,0 +1,35 @@ +CREATE OR REPLACE PROCEDURE SP_GET_SERVER +( +P_CONSUMER_KEY IN VARCHAR2, +P_USER_ID IN NUMBER, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Get a server from the consumer registry using the consumer key +BEGIN +P_RESULT := 0; + +OPEN P_ROWS FOR + SELECT OCR_ID "id", + OCR_USA_ID_REF "user_id", + OCR_CONSUMER_KEY "consumer_key", + OCR_CONSUMER_SECRET "consumer_secret", + OCR_SIGNATURE_METHODS "signature_methods", + OCR_SERVER_URI "server_uri", + OCR_REQUEST_TOKEN_URI "request_token_uri", + OCR_AUTHORIZE_URI "authorize_uri", + OCR_ACCESS_TOKEN_URI "access_token_uri" + FROM OAUTH_CONSUMER_REGISTRY + WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY + AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL); + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc new file mode 100644 index 0000000000..d838b511bc --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc @@ -0,0 +1,41 @@ +CREATE OR REPLACE PROCEDURE SP_GET_SERVER_FOR_URI +( +P_HOST IN VARCHAR2, +P_PATH IN VARCHAR2, +P_USER_ID IN NUMBER, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Find the server details that might be used for a request +BEGIN +P_RESULT := 0; + +OPEN P_ROWS FOR +SELECT * FROM ( + SELECT OCR_ID "id", + OCR_USA_ID_REF "user_id", + OCR_CONSUMER_KEY "consumer_key", + OCR_CONSUMER_SECRET "consumer_secret", + OCR_SIGNATURE_METHODS "signature_methods", + OCR_SERVER_URI "server_uri", + OCR_REQUEST_TOKEN_URI "request_token_uri", + OCR_AUTHORIZE_URI "authorize_uri", + OCR_ACCESS_TOKEN_URI "access_token_uri" + FROM OAUTH_CONSUMER_REGISTRY + WHERE OCR_SERVER_URI_HOST = P_HOST + AND OCR_SERVER_URI_PATH = SUBSTR(P_PATH, 1, LENGTH(OCR_SERVER_URI_PATH)) + AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL) + ORDER BY ocr_usa_id_ref DESC, OCR_CONSUMER_KEY DESC, LENGTH(ocr_server_uri_path) DESC +) WHERE ROWNUM<=1; + + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc new file mode 100644 index 0000000000..fefbe8acaf --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc @@ -0,0 +1,45 @@ +CREATE OR REPLACE PROCEDURE SP_GET_SERVER_TOKEN +( +P_CONSUMER_KEY IN VARCHAR2, +P_USER_ID IN NUMBER, +P_TOKEN IN VARCHAR2, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Get a specific server token for the given user +BEGIN +P_RESULT := 0; + +OPEN P_ROWS FOR + SELECT OCR_CONSUMER_KEY "consumer_key", + OCR_CONSUMER_SECRET "consumer_secret", + OCT_TOKEN "token", + OCT_TOKEN_SECRET "token_secret", + OCT_USA_ID_REF "usr_id", + OCR_SIGNATURE_METHODS "signature_methods", + OCR_SERVER_URI "server_uri", + OCR_SERVER_URI_HOST "server_uri_host", + OCR_SERVER_URI_PATH "server_uri_path", + OCR_REQUEST_TOKEN_URI "request_token_uri", + OCR_AUTHORIZE_URI "authorize_uri", + OCR_ACCESS_TOKEN_URI "access_token_uri", + OCT_TIMESTAMP "timestamp" + FROM OAUTH_CONSUMER_REGISTRY + JOIN OAUTH_CONSUMER_TOKEN + ON OCT_OCR_ID_REF = OCR_ID + WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY + AND OCT_USA_ID_REF = P_USER_ID + AND OCT_TOKEN_TYPE = 'ACCESS' + AND OCT_TOKEN = P_TOKEN + AND OCT_TOKEN_TTL >= SYSDATE; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc new file mode 100644 index 0000000000..95eec885a6 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc @@ -0,0 +1,47 @@ +CREATE OR REPLACE PROCEDURE SP_GET_SERVER_TOKEN_SECRETS +( +P_CONSUMER_KEY IN VARCHAR2, +P_TOKEN IN VARCHAR2, +P_TOKEN_TYPE IN VARCHAR2, +P_USER_ID IN NUMBER, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- Get the token and token secret we obtained from a server. + +BEGIN +P_RESULT := 0; + + + OPEN P_ROWS FOR + SELECT OCR.OCR_CONSUMER_KEY "consumer_key", + OCR.OCR_CONSUMER_SECRET "consumer_secret", + OCT.OCT_TOKEN "token", + OCT.OCT_TOKEN_SECRET "token_secret", + OCT.OCT_NAME "token_name", + OCR.OCR_SIGNATURE_METHODS "signature_methods", + OCR.OCR_SERVER_URI "server_uri", + OCR.OCR_REQUEST_TOKEN_URI "request_token_uri", + OCR.OCR_AUTHORIZE_URI "authorize_uri", + OCR.OCR_ACCESS_TOKEN_URI "access_token_uri", + CASE WHEN OCT.OCT_TOKEN_TTL >= TO_DATE('9999.12.31', 'yyyy.mm.dd') THEN NULL + ELSE OCT.OCT_TOKEN_TTL - SYSDATE + END "token_ttl" + FROM OAUTH_CONSUMER_REGISTRY OCR, OAUTH_CONSUMER_TOKEN OCT + WHERE OCT.OCT_OCR_ID_REF = OCR_ID + AND OCR.OCR_CONSUMER_KEY = P_CONSUMER_KEY + AND upper(OCT.OCT_TOKEN_TYPE) = upper(P_TOKEN_TYPE) + AND OCT.OCT_TOKEN = P_TOKEN + AND OCT.OCT_USA_ID_REF = P_USER_ID + AND OCT.OCT_TOKEN_TTL >= SYSDATE; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc new file mode 100644 index 0000000000..bb4246557c --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc @@ -0,0 +1,41 @@ +CREATE OR REPLACE PROCEDURE SP_LIST_CONSUMERS +( +P_USER_ID IN NUMBER, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Fetch a list of all consumer keys, secrets etc. + -- Returns the public (user_id is null) and the keys owned by the user + +BEGIN + + P_RESULT := 0; + + OPEN P_ROWS FOR + SELECT OSR_ID "id", + OSR_USA_ID_REF "user_id", + OSR_CONSUMER_KEY "consumer_key", + OSR_CONSUMER_SECRET "consumer_secret", + OSR_ENABLED "enabled", + OSR_STATUS "status", + OSR_ISSUE_DATE "issue_date", + OSR_APPLICATION_URI "application_uri", + OSR_APPLICATION_TITLE "application_title", + OSR_APPLICATION_DESCR "application_descr", + OSR_REQUESTER_NAME "requester_name", + OSR_REQUESTER_EMAIL "requester_email", + OSR_CALLBACK_URI "callback_uri" + FROM OAUTH_SERVER_REGISTRY + WHERE (OSR_USA_ID_REF = P_USER_ID OR OSR_USA_ID_REF IS NULL) + ORDER BY OSR_APPLICATION_TITLE; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc new file mode 100644 index 0000000000..dae9c72cc0 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc @@ -0,0 +1,43 @@ +CREATE OR REPLACE PROCEDURE SP_LIST_CONSUMER_TOKENS +( +P_USER_ID IN NUMBER, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Fetch a list of all consumer tokens accessing the account of the given user. + +BEGIN + + P_RESULT := 0; + + OPEN P_ROWS FOR + SELECT OSR_CONSUMER_KEY "consumer_key", + OSR_CONSUMER_SECRET "consumer_secret", + OSR_ENABLED "enabled", + OSR_STATUS "status", + OSR_APPLICATION_URI "application_uri", + OSR_APPLICATION_TITLE "application_title", + OSR_APPLICATION_DESCR "application_descr", + OST_TIMESTAMP "timestamp", + OST_TOKEN "token", + OST_TOKEN_SECRET "token_secret", + OST_REFERRER_HOST "token_referrer_host", + OSR_CALLBACK_URI "callback_uri" + FROM OAUTH_SERVER_REGISTRY + JOIN OAUTH_SERVER_TOKEN + ON OST_OSR_ID_REF = OSR_ID + WHERE OST_USA_ID_REF = P_USER_ID + AND OST_TOKEN_TYPE = 'ACCESS' + AND OST_TOKEN_TTL >= SYSDATE + ORDER BY OSR_APPLICATION_TITLE; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc new file mode 100644 index 0000000000..275950e419 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc @@ -0,0 +1,75 @@ +CREATE OR REPLACE PROCEDURE SP_LIST_LOG +( +P_OPTION_FLAG IN NUMBER, -- 0:NULL; 1:OTHERWISE +P_USA_ID IN NUMBER, +P_OSR_CONSUMER_KEY IN VARCHAR2, +P_OCR_CONSUMER_KEY IN VARCHAR2, +P_OST_TOKEN IN VARCHAR2, +P_OCT_TOKEN IN VARCHAR2, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Get a page of entries from the log. Returns the last 100 records + -- matching the options given. + +BEGIN + + P_RESULT := 0; + + IF P_OPTION_FLAG IS NULL OR P_OPTION_FLAG = 0 THEN + OPEN P_ROWS FOR + SELECT * FROM ( + SELECT OLG_ID "olg_id", + OLG_OSR_CONSUMER_KEY "osr_consumer_key", + OLG_OST_TOKEN "ost_token", + OLG_OCR_CONSUMER_KEY "ocr_consumer_key", + OLG_OCT_TOKEN "oct_token", + OLG_USA_ID_REF "user_id", + OLG_RECEIVED "received", + OLG_SENT "sent", + OLG_BASE_STRING "base_string", + OLG_NOTES "notes", + OLG_TIMESTAMP "timestamp", + -- INET_NTOA(OLG_REMOTE_IP) "remote_ip" + OLG_REMOTE_IP "remote_ip" + FROM OAUTH_LOG + WHERE OLG_USA_ID_REF = P_USA_ID + ORDER BY OLG_ID DESC + ) WHERE ROWNUM<=100; + ELSE + OPEN P_ROWS FOR + SELECT * FROM ( + SELECT OLG_ID "olg_id", + OLG_OSR_CONSUMER_KEY "osr_consumer_key", + OLG_OST_TOKEN "ost_token", + OLG_OCR_CONSUMER_KEY "ocr_consumer_key", + OLG_OCT_TOKEN "oct_token", + OLG_USA_ID_REF "user_id", + OLG_RECEIVED "received", + OLG_SENT "sent", + OLG_BASE_STRING "base_string", + OLG_NOTES "notes", + OLG_TIMESTAMP "timestamp", + -- INET_NTOA(OLG_REMOTE_IP) "remote_ip" + OLG_REMOTE_IP "remote_ip" + FROM OAUTH_LOG + WHERE OLG_OSR_CONSUMER_KEY = P_OSR_CONSUMER_KEY + AND OLG_OCR_CONSUMER_KEY = P_OCR_CONSUMER_KEY + AND OLG_OST_TOKEN = P_OST_TOKEN + AND OLG_OCT_TOKEN = P_OCT_TOKEN + AND (OLG_USA_ID_REF IS NULL OR OLG_USA_ID_REF = P_USA_ID) + ORDER BY OLG_ID DESC + ) WHERE ROWNUM<=100; + + END IF; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc new file mode 100644 index 0000000000..51dd39a06c --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc @@ -0,0 +1,66 @@ +CREATE OR REPLACE PROCEDURE SP_LIST_SERVERS +( +P_Q IN VARCHAR2, +P_USER_ID IN NUMBER, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Get a list of all consumers from the consumer registry. +BEGIN +P_RESULT := 0; + +IF P_Q IS NOT NULL THEN + + OPEN P_ROWS FOR + SELECT OCR_ID "id", + OCR_USA_ID_REF "user_id", + OCR_CONSUMER_KEY "consumer_key", + OCR_CONSUMER_SECRET "consumer_secret", + OCR_SIGNATURE_METHODS "signature_methods", + OCR_SERVER_URI "server_uri", + OCR_SERVER_URI_HOST "server_uri_host", + OCR_SERVER_URI_PATH "server_uri_path", + OCR_REQUEST_TOKEN_URI "request_token_uri", + OCR_AUTHORIZE_URI "authorize_uri", + OCR_ACCESS_TOKEN_URI "access_token_uri" + FROM OAUTH_CONSUMER_REGISTRY + WHERE ( OCR_CONSUMER_KEY LIKE '%'|| P_Q ||'%' + OR OCR_SERVER_URI LIKE '%'|| P_Q ||'%' + OR OCR_SERVER_URI_HOST LIKE '%'|| P_Q ||'%' + OR OCR_SERVER_URI_PATH LIKE '%'|| P_Q ||'%') + AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL) + ORDER BY OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH; + +ELSE + + OPEN P_ROWS FOR + SELECT OCR_ID "id", + OCR_USA_ID_REF "user_id", + OCR_CONSUMER_KEY "consumer_key", + OCR_CONSUMER_SECRET "consumer_secret", + OCR_SIGNATURE_METHODS "signature_methods", + OCR_SERVER_URI "server_uri", + OCR_SERVER_URI_HOST "server_uri_host", + OCR_SERVER_URI_PATH "server_uri_path", + OCR_REQUEST_TOKEN_URI "request_token_uri", + OCR_AUTHORIZE_URI "authorize_uri", + OCR_ACCESS_TOKEN_URI "access_token_uri" + FROM OAUTH_CONSUMER_REGISTRY + WHERE OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL + ORDER BY OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH; + +END IF; + + + + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc new file mode 100644 index 0000000000..baa62c02e5 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc @@ -0,0 +1,45 @@ +CREATE OR REPLACE PROCEDURE SP_LIST_SERVER_TOKENS +( +P_USER_ID IN NUMBER, +P_ROWS OUT TYPES.REF_CURSOR, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Find the server details that might be used for a request +BEGIN +P_RESULT := 0; + +OPEN P_ROWS FOR + SELECT OCR_CONSUMER_KEY "consumer_key", + OCR_CONSUMER_SECRET "consumer_secret", + OCT_ID "token_id", + OCT_TOKEN "token", + OCT_TOKEN_SECRET "token_secret", + OCT_USA_ID_REF "user_id", + OCR_SIGNATURE_METHODS "signature_methods", + OCR_SERVER_URI "server_uri", + OCR_SERVER_URI_HOST "server_uri_host", + OCR_SERVER_URI_PATH "server_uri_path", + OCR_REQUEST_TOKEN_URI "request_token_uri", + OCR_AUTHORIZE_URI "authorize_uri", + OCR_ACCESS_TOKEN_URI "access_token_uri", + OCT_TIMESTAMP "timestamp" + FROM OAUTH_CONSUMER_REGISTRY + JOIN OAUTH_CONSUMER_TOKEN + ON OCT_OCR_ID_REF = OCR_ID + WHERE OCT_USA_ID_REF = P_USER_ID + AND OCT_TOKEN_TYPE = 'ACCESS' + AND OCT_TOKEN_TTL >= SYSDATE + ORDER BY OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH; + + + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc new file mode 100644 index 0000000000..e5a96c966a --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc @@ -0,0 +1,28 @@ +CREATE OR REPLACE PROCEDURE SP_SET_CONSUMER_ACC_TOKEN_TTL +( +P_TOKEN IN VARCHAR2, +P_TOKEN_TTL IN NUMBER, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Set the ttl of a consumer access token. This is done when the + -- server receives a valid request with a xoauth_token_ttl parameter in it. + +BEGIN + + P_RESULT := 0; + + UPDATE OAUTH_SERVER_TOKEN + SET OST_TOKEN_TTL = SYSDATE + (P_TOKEN_TTL/(24*60*60)) + WHERE OST_TOKEN = P_TOKEN + AND OST_TOKEN_TYPE = 'ACCESS'; + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc new file mode 100644 index 0000000000..34a99de067 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc @@ -0,0 +1,29 @@ +CREATE OR REPLACE PROCEDURE SP_SET_SERVER_TOKEN_TTL +( +P_TOKEN_TTL IN NUMBER, -- IN SECOND +P_CONSUMER_KEY IN VARCHAR2, +P_TOKEN IN VARCHAR2, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Set the ttl of a server access token. + +BEGIN + + P_RESULT := 0; + + +UPDATE OAUTH_CONSUMER_TOKEN +SET OCT_TOKEN_TTL = SYSDATE + (P_TOKEN_TTL/(24*60*60)) -- DATE_ADD(NOW(), INTERVAL %D SECOND) +WHERE OCT_TOKEN = P_TOKEN +AND OCT_OCR_ID_REF IN (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY); + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc new file mode 100644 index 0000000000..a79e64c3be --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc @@ -0,0 +1,40 @@ +CREATE OR REPLACE PROCEDURE SP_UPDATE_CONSUMER +( +P_OSR_USA_ID_REF IN NUMBER, +P_OSR_CONSUMER_KEY IN VARCHAR2, +P_OSR_CONSUMER_SECRET IN VARCHAR2, +P_OSR_REQUESTER_NAME IN VARCHAR2, +P_OSR_REQUESTER_EMAIL IN VARCHAR2, +P_OSR_CALLBACK_URI IN VARCHAR2, +P_OSR_APPLICATION_URI IN VARCHAR2, +P_OSR_APPLICATION_TITLE IN VARCHAR2, +P_OSR_APPLICATION_DESCR IN VARCHAR2, +P_OSR_APPLICATION_NOTES IN VARCHAR2, +P_OSR_APPLICATION_TYPE IN VARCHAR2, +P_OSR_APPLICATION_COMMERCIAL IN INTEGER, +P_RESULT OUT NUMBER +) +AS + + -- PROCEDURE TO Insert a new consumer with this server (we will be the server) +BEGIN +P_RESULT := 0; + + + INSERT INTO OAUTH_SERVER_REGISTRY + ( OSR_ID, OSR_ENABLED, OSR_STATUS,OSR_USA_ID_REF,OSR_CONSUMER_KEY, OSR_CONSUMER_SECRET,OSR_REQUESTER_NAME, + OSR_REQUESTER_EMAIL, OSR_CALLBACK_URI, OSR_APPLICATION_URI, OSR_APPLICATION_TITLE, OSR_APPLICATION_DESCR, + OSR_APPLICATION_NOTES, OSR_APPLICATION_TYPE, OSR_APPLICATION_COMMERCIAL, OSR_TIMESTAMP, OSR_ISSUE_DATE) + VALUES + ( SEQ_OSR_ID.NEXTVAL, 1, 'ACTIVE', P_OSR_USA_ID_REF, P_OSR_CONSUMER_KEY, P_OSR_CONSUMER_SECRET,P_OSR_REQUESTER_NAME, + P_OSR_REQUESTER_EMAIL, P_OSR_CALLBACK_URI, P_OSR_APPLICATION_URI, P_OSR_APPLICATION_TITLE, P_OSR_APPLICATION_DESCR, + P_OSR_APPLICATION_NOTES, P_OSR_APPLICATION_TYPE, P_OSR_APPLICATION_COMMERCIAL, SYSDATE, SYSDATE); + + +EXCEPTION +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc new file mode 100644 index 0000000000..7826eb6249 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc @@ -0,0 +1,139 @@ +CREATE OR REPLACE PROCEDURE SP_UPDATE_SERVER +( +P_CONSUMER_KEY IN VARCHAR2, +P_USER_ID IN NUMBER, +P_OCR_ID IN NUMBER, +P_USER_IS_ADMIN IN NUMBER, -- 0:NO; 1:YES; +P_OCR_CONSUMER_SECRET IN VARCHAR2, +P_OCR_SERVER_URI IN VARCHAR2, +P_OCR_SERVER_URI_HOST IN VARCHAR2, +P_OCR_SERVER_URI_PATH IN VARCHAR2, +P_OCR_REQUEST_TOKEN_URI IN VARCHAR2, +P_OCR_AUTHORIZE_URI IN VARCHAR2, +P_OCR_ACCESS_TOKEN_URI IN VARCHAR2, +P_OCR_SIGNATURE_METHODS IN VARCHAR2, +P_OCR_USA_ID_REF IN NUMBER, +P_UPDATE_P_OCR_USA_ID_REF_FLAG IN NUMBER, -- 1:TRUE; 0:FALSE +P_RESULT OUT NUMBER +) +AS + + -- Add a request token we obtained from a server. +V_OCR_ID_EXIST NUMBER; +V_OCR_USA_ID_REF NUMBER; + +V_EXC_DUPLICATE_CONSUMER_KEY EXCEPTION; +V_EXC_UNAUTHORISED_USER_ID EXCEPTION; +BEGIN +P_RESULT := 0; + +V_OCR_USA_ID_REF := P_OCR_USA_ID_REF; + + IF P_OCR_ID IS NOT NULL THEN + BEGIN + SELECT 1 INTO V_OCR_ID_EXIST FROM DUAL WHERE EXISTS + (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY + WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY + AND OCR_ID != P_OCR_ID + AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL)); + + EXCEPTION + WHEN NO_DATA_FOUND THEN + V_OCR_ID_EXIST :=0; + END; + ELSE + BEGIN + SELECT 1 INTO V_OCR_ID_EXIST FROM DUAL WHERE EXISTS + (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY + WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY + AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL)); + + EXCEPTION + WHEN NO_DATA_FOUND THEN + V_OCR_ID_EXIST :=0; + END; + END IF; + + IF V_OCR_ID_EXIST = 1 THEN + RAISE V_EXC_DUPLICATE_CONSUMER_KEY; + END IF; + + + IF P_OCR_ID IS NOT NULL THEN + IF P_USER_IS_ADMIN != 1 THEN + BEGIN + SELECT OCR_USA_ID_REF INTO V_OCR_USA_ID_REF + FROM OAUTH_CONSUMER_REGISTRY + WHERE OCR_ID = P_OCR_ID; + + EXCEPTION + WHEN NO_DATA_FOUND THEN + NULL; + END; + + IF V_OCR_USA_ID_REF != P_USER_ID THEN + RAISE V_EXC_UNAUTHORISED_USER_ID; + END IF; + END IF; + + IF P_UPDATE_P_OCR_USA_ID_REF_FLAG = 0 THEN + + UPDATE OAUTH_CONSUMER_REGISTRY + SET OCR_CONSUMER_KEY = P_CONSUMER_KEY, + OCR_CONSUMER_SECRET = P_OCR_CONSUMER_SECRET, + OCR_SERVER_URI = P_OCR_SERVER_URI, + OCR_SERVER_URI_HOST = P_OCR_SERVER_URI_HOST, + OCR_SERVER_URI_PATH = P_OCR_SERVER_URI_PATH, + OCR_TIMESTAMP = SYSDATE, + OCR_REQUEST_TOKEN_URI = P_OCR_REQUEST_TOKEN_URI, + OCR_AUTHORIZE_URI = P_OCR_AUTHORIZE_URI, + OCR_ACCESS_TOKEN_URI = P_OCR_ACCESS_TOKEN_URI, + OCR_SIGNATURE_METHODS = P_OCR_SIGNATURE_METHODS + WHERE OCR_ID = P_OCR_ID; + + ELSIF P_UPDATE_P_OCR_USA_ID_REF_FLAG = 1 THEN + UPDATE OAUTH_CONSUMER_REGISTRY + SET OCR_CONSUMER_KEY = P_CONSUMER_KEY, + OCR_CONSUMER_SECRET = P_OCR_CONSUMER_SECRET, + OCR_SERVER_URI = P_OCR_SERVER_URI, + OCR_SERVER_URI_HOST = P_OCR_SERVER_URI_HOST, + OCR_SERVER_URI_PATH = P_OCR_SERVER_URI_PATH, + OCR_TIMESTAMP = SYSDATE, + OCR_REQUEST_TOKEN_URI = P_OCR_REQUEST_TOKEN_URI, + OCR_AUTHORIZE_URI = P_OCR_AUTHORIZE_URI, + OCR_ACCESS_TOKEN_URI = P_OCR_ACCESS_TOKEN_URI, + OCR_SIGNATURE_METHODS = P_OCR_SIGNATURE_METHODS, + OCR_USA_ID_REF = P_OCR_USA_ID_REF + WHERE OCR_ID = P_OCR_ID; + + END IF; + + ELSE + IF P_UPDATE_P_OCR_USA_ID_REF_FLAG = 0 THEN + V_OCR_USA_ID_REF := P_USER_ID; + END IF; + + INSERT INTO OAUTH_CONSUMER_REGISTRY + (OCR_ID, OCR_CONSUMER_KEY ,OCR_CONSUMER_SECRET, OCR_SERVER_URI, OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH, + OCR_TIMESTAMP, OCR_REQUEST_TOKEN_URI, OCR_AUTHORIZE_URI, OCR_ACCESS_TOKEN_URI, OCR_SIGNATURE_METHODS, + OCR_USA_ID_REF) + VALUES + (SEQ_OCR_ID.NEXTVAL, P_CONSUMER_KEY, P_OCR_CONSUMER_SECRET, P_OCR_SERVER_URI, P_OCR_SERVER_URI_HOST, P_OCR_SERVER_URI_PATH, + SYSDATE, P_OCR_REQUEST_TOKEN_URI, P_OCR_AUTHORIZE_URI, P_OCR_ACCESS_TOKEN_URI, P_OCR_SIGNATURE_METHODS, + V_OCR_USA_ID_REF); + + END IF; + + +EXCEPTION +WHEN V_EXC_DUPLICATE_CONSUMER_KEY THEN +P_RESULT := 2; -- DUPLICATE_CONSUMER_KEY +WHEN V_EXC_UNAUTHORISED_USER_ID THEN +P_RESULT := 3; -- UNAUTHORISED_USER_ID + +WHEN OTHERS THEN +-- CALL THE FUNCTION TO LOG ERRORS +ROLLBACK; +P_RESULT := 1; -- ERROR +END; +/ diff --git a/3rdparty/oauth-php/library/store/oracle/install.php b/3rdparty/oauth-php/library/store/oracle/install.php new file mode 100644 index 0000000000..5a80f04023 --- /dev/null +++ b/3rdparty/oauth-php/library/store/oracle/install.php @@ -0,0 +1,28 @@ + \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/postgresql/pgsql.sql b/3rdparty/oauth-php/library/store/postgresql/pgsql.sql new file mode 100644 index 0000000000..8f0e4d3e2c --- /dev/null +++ b/3rdparty/oauth-php/library/store/postgresql/pgsql.sql @@ -0,0 +1,166 @@ +# +# Log table to hold all OAuth request when you enabled logging +# + +CREATE TABLE oauth_log ( + olg_id serial primary key, + olg_osr_consumer_key varchar(64), + olg_ost_token varchar(64), + olg_ocr_consumer_key varchar(64), + olg_oct_token varchar(64), + olg_usa_id_ref text, + olg_received text not null, + olg_sent text not null, + olg_base_string text not null, + olg_notes text not null, + olg_timestamp timestamp not null default current_timestamp, + olg_remote_ip inet not null +); + +COMMENT ON TABLE oauth_log IS 'Log table to hold all OAuth request when you enabled logging'; + + +# +# /////////////////// CONSUMER SIDE /////////////////// +# + +# This is a registry of all consumer codes we got from other servers +# The consumer_key/secret is obtained from the server +# We also register the server uri, so that we can find the consumer key and secret +# for a certain server. From that server we can check if we have a token for a +# particular user. + +CREATE TABLE oauth_consumer_registry ( + ocr_id serial primary key, + ocr_usa_id_ref text, + ocr_consumer_key varchar(128) not null, + ocr_consumer_secret varchar(128) not null, + ocr_signature_methods varchar(255) not null default 'HMAC-SHA1,PLAINTEXT', + ocr_server_uri varchar(255) not null, + ocr_server_uri_host varchar(128) not null, + ocr_server_uri_path varchar(128) not null, + + ocr_request_token_uri varchar(255) not null, + ocr_authorize_uri varchar(255) not null, + ocr_access_token_uri varchar(255) not null, + ocr_timestamp timestamp not null default current_timestamp, + + unique (ocr_consumer_key, ocr_usa_id_ref, ocr_server_uri) +); + +COMMENT ON TABLE oauth_consumer_registry IS 'This is a registry of all consumer codes we got from other servers'; + +# Table used to sign requests for sending to a server by the consumer +# The key is defined for a particular user. Only one single named +# key is allowed per user/server combination + +-- Create enum type token_type +CREATE TYPE consumer_token_type AS ENUM ( + 'request', + 'authorized', + 'access' +); + +CREATE TABLE oauth_consumer_token ( + oct_id serial primary key, + oct_ocr_id_ref integer not null, + oct_usa_id_ref text not null, + oct_name varchar(64) not null default '', + oct_token varchar(64) not null, + oct_token_secret varchar(64) not null, + oct_token_type consumer_token_type, + oct_token_ttl timestamp not null default timestamp '9999-12-31', + oct_timestamp timestamp not null default current_timestamp, + + unique (oct_ocr_id_ref, oct_token), + unique (oct_usa_id_ref, oct_ocr_id_ref, oct_token_type, oct_name), + + foreign key (oct_ocr_id_ref) references oauth_consumer_registry (ocr_id) + on update cascade + on delete cascade +); + + +COMMENT ON TABLE oauth_consumer_token IS 'Table used to sign requests for sending to a server by the consumer'; + +# +# ////////////////// SERVER SIDE ///////////////// +# + +# Table holding consumer key/secret combos an user issued to consumers. +# Used for verification of incoming requests. + +CREATE TABLE oauth_server_registry ( + osr_id serial primary key, + osr_usa_id_ref text, + osr_consumer_key varchar(64) not null, + osr_consumer_secret varchar(64) not null, + osr_enabled boolean not null default true, + osr_status varchar(16) not null, + osr_requester_name varchar(64) not null, + osr_requester_email varchar(64) not null, + osr_callback_uri varchar(255) not null, + osr_application_uri varchar(255) not null, + osr_application_title varchar(80) not null, + osr_application_descr text not null, + osr_application_notes text not null, + osr_application_type varchar(20) not null, + osr_application_commercial boolean not null default false, + osr_issue_date timestamp not null, + osr_timestamp timestamp not null default current_timestamp, + + unique (osr_consumer_key) +); + + +COMMENT ON TABLE oauth_server_registry IS 'Table holding consumer key/secret combos an user issued to consumers'; + +# Nonce used by a certain consumer, every used nonce should be unique, this prevents +# replaying attacks. We need to store all timestamp/nonce combinations for the +# maximum timestamp received. + +CREATE TABLE oauth_server_nonce ( + osn_id serial primary key, + osn_consumer_key varchar(64) not null, + osn_token varchar(64) not null, + osn_timestamp bigint not null, + osn_nonce varchar(80) not null, + + unique (osn_consumer_key, osn_token, osn_timestamp, osn_nonce) +); + + +COMMENT ON TABLE oauth_server_nonce IS 'Nonce used by a certain consumer, every used nonce should be unique, this prevents replaying attacks'; + +# Table used to verify signed requests sent to a server by the consumer +# When the verification is succesful then the associated user id is returned. + +-- Create enum type token_type +CREATE TYPE server_token_type AS ENUM ( + 'request', + 'access' +); + +CREATE TABLE oauth_server_token ( + ost_id serial primary key, + ost_osr_id_ref integer not null, + ost_usa_id_ref text not null, + ost_token varchar(64) not null, + ost_token_secret varchar(64) not null, + ost_token_type server_token_type, + ost_authorized boolean not null default false, + ost_referrer_host varchar(128) not null default '', + ost_token_ttl timestamp not null default timestamp '9999-12-31', + ost_timestamp timestamp not null default current_timestamp, + ost_verifier char(10), + ost_callback_url varchar(512), + + unique (ost_token), + + foreign key (ost_osr_id_ref) references oauth_server_registry (osr_id) + on update cascade + on delete cascade +); + + +COMMENT ON TABLE oauth_server_token IS 'Table used to verify signed requests sent to a server by the consumer'; From e7f7693b2f28ad87c232db51f1101e720fb29623 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 1 Aug 2012 10:21:33 +0100 Subject: [PATCH 044/330] Fix 3rdparty paths, initialise OAuth in correct order --- lib/oauth.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lib/oauth.php b/lib/oauth.php index 09dbe4cc75..0c6e9af725 100644 --- a/lib/oauth.php +++ b/lib/oauth.php @@ -37,12 +37,13 @@ class OC_OAuth { */ private static function init(){ // Include the libraries - require_once(OC::$THIRDPARTYROOT.'3rdparty/oauth-php/library/OAuthServer.php'); - require_once(OC::$THIRDPARTYROOT.'3rdparty/oauth-php/library/OAuthStore.php'); + require_once(OC::$THIRDPARTYROOT.'/3rdparty/oauth-php/library/OAuthServer.php'); + require_once(OC::$THIRDPARTYROOT.'/3rdparty/oauth-php/library/OAuthStore.php'); + require_once(OC::$THIRDPARTYROOT.'/3rdparty/oauth-php/library/OAuthRequestVerifier.php'); + // Initialise the OAuth store + self::$store = OAuthStore::instance('Session'); // Create the server object self::$server = new OAuthServer(); - // Initialise the OAuth store - self::$store = OAuthStore::instance('owncloud'); } /** @@ -109,6 +110,7 @@ class OC_OAuth { * @return string|int */ public static function isAuthorised(){ + self::init(); if(OAuthRequestVerifier::requestIsSigned()){ try{ $req = new OAuthRequestVerifier(); From e315384b4ddc207c1b3f142df4a57e8004a88966 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 1 Aug 2012 10:40:09 +0100 Subject: [PATCH 045/330] Remove unnecessary include --- lib/oauth.php | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/oauth.php b/lib/oauth.php index 0c6e9af725..0621a72a72 100644 --- a/lib/oauth.php +++ b/lib/oauth.php @@ -39,7 +39,6 @@ class OC_OAuth { // Include the libraries require_once(OC::$THIRDPARTYROOT.'/3rdparty/oauth-php/library/OAuthServer.php'); require_once(OC::$THIRDPARTYROOT.'/3rdparty/oauth-php/library/OAuthStore.php'); - require_once(OC::$THIRDPARTYROOT.'/3rdparty/oauth-php/library/OAuthRequestVerifier.php'); // Initialise the OAuth store self::$store = OAuthStore::instance('Session'); // Create the server object From 75dbed22080850b850e2e4befafc6ced557bdba9 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 1 Aug 2012 14:12:59 +0100 Subject: [PATCH 046/330] Fix the api routes --- apps/provisioning_api/appinfo/routes.php | 38 ++++++++++++------------ ocs/routes.php | 4 +-- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/apps/provisioning_api/appinfo/routes.php b/apps/provisioning_api/appinfo/routes.php index dcfaf7b78b..c942dea537 100644 --- a/apps/provisioning_api/appinfo/routes.php +++ b/apps/provisioning_api/appinfo/routes.php @@ -22,25 +22,25 @@ */ // users -OCP\API::register('get', '/users', array('OC_Provisioning_API_Users', 'getUsers'), 'provisioning_api'); -OCP\API::register('post', '/users', array('OC_Provisioning_API_Users', 'addUser'), 'provisioning_api'); -OCP\API::register('get', '/users/{userid}', array('OC_Provisioning_API_Users', 'getUser'), 'provisioning_api'); -OCP\API::register('put', '/users/{userid}', array('OC_Provisioning_API_Users', 'editUser'), 'provisioning_api'); -OCP\API::register('delete', '/users/{userid}', array('OC_Provisioning_API_Users', 'getUsers'), 'provisioning_api'); -OCP\API::register('get', '/users/{userid}/sharedwith', array('OC_Provisioning_API_Users', 'getSharedWithUser'), 'provisioning_api'); -OCP\API::register('get', '/users/{userid}/sharedby', array('OC_Provisioning_API_Users', 'getSharedByUser'), 'provisioning_api'); -OCP\API::register('delete', '/users/{userid}/sharedby', array('OC_Provisioning_API_Users', 'deleteSharedByUser'), 'provisioning_api'); -OCP\API::register('get', '/users/{userid}/groups', array('OC_Provisioning_API_Users', 'getUsersGroups'), 'provisioning_api'); -OCP\API::register('post', '/users/{userid}/groups', array('OC_Provisioning_API_Users', 'addToGroup'), 'provisioning_api'); -OCP\API::register('delete', '/users/{userid}/groups', array('OC_Provisioning_API_Users', 'removeFromGroup'), 'provisioning_api'); +OCP\API::register('get', '/cloud/users', array('OC_Provisioning_API_Users', 'getUsers'), 'provisioning_api'); +OCP\API::register('post', '/cloud/users', array('OC_Provisioning_API_Users', 'addUser'), 'provisioning_api'); +OCP\API::register('get', '/cloud/users/{userid}', array('OC_Provisioning_API_Users', 'getUser'), 'provisioning_api'); +OCP\API::register('put', '/cloud/users/{userid}', array('OC_Provisioning_API_Users', 'editUser'), 'provisioning_api'); +OCP\API::register('delete', '/cloud/users/{userid}', array('OC_Provisioning_API_Users', 'getUsers'), 'provisioning_api'); +OCP\API::register('get', '/cloud/users/{userid}/sharedwith', array('OC_Provisioning_API_Users', 'getSharedWithUser'), 'provisioning_api'); +OCP\API::register('get', '/cloud/users/{userid}/sharedby', array('OC_Provisioning_API_Users', 'getSharedByUser'), 'provisioning_api'); +OCP\API::register('delete', '/cloud/users/{userid}/sharedby', array('OC_Provisioning_API_Users', 'deleteSharedByUser'), 'provisioning_api'); +OCP\API::register('get', '/cloud/users/{userid}/groups', array('OC_Provisioning_API_Users', 'getUsersGroups'), 'provisioning_api'); +OCP\API::register('post', '/cloud/users/{userid}/groups', array('OC_Provisioning_API_Users', 'addToGroup'), 'provisioning_api'); +OCP\API::register('delete', '/cloud/users/{userid}/groups', array('OC_Provisioning_API_Users', 'removeFromGroup'), 'provisioning_api'); // groups -OCP\API::register('get', '/groups', array('OC_Provisioning_API_Groups', 'getGroups'), 'provisioning_api'); -OCP\API::register('post', '/groups', array('OC_Provisioning_API_Groups', 'addGroup'), 'provisioning_api'); -OCP\API::register('get', '/groups/{groupid}', array('OC_Provisioning_API_Groups', 'getGroup'), 'provisioning_api'); -OCP\API::register('delete', '/groups/{groupid}', array('OC_Provisioning_API_Groups', 'deleteGroup'), 'provisioning_api'); +OCP\API::register('get', '/cloud/groups', array('OC_Provisioning_API_Groups', 'getGroups'), 'provisioning_api'); +OCP\API::register('post', '/cloud/groups', array('OC_Provisioning_API_Groups', 'addGroup'), 'provisioning_api'); +OCP\API::register('get', '/cloud/groups/{groupid}', array('OC_Provisioning_API_Groups', 'getGroup'), 'provisioning_api'); +OCP\API::register('delete', '/cloud/groups/{groupid}', array('OC_Provisioning_API_Groups', 'deleteGroup'), 'provisioning_api'); // apps -OCP\API::register('get', '/apps', array('OC_Provisioning_API_Apps', 'getApps'), 'provisioning_api'); -OCP\API::register('get', '/apps/{appid}', array('OC_Provisioning_API_Apps', 'getApp'), 'provisioning_api'); -OCP\API::register('post', '/apps/{appid}', array('OC_Provisioning_API_Apps', 'enable'), 'provisioning_api'); -OCP\API::register('delete', '/apps/{appid}', array('OC_Provisioning_API_Apps', 'disable'), 'provisioning_api'); +OCP\API::register('get', '/cloud/apps', array('OC_Provisioning_API_Apps', 'getApps'), 'provisioning_api'); +OCP\API::register('get', '/cloud/apps/{appid}', array('OC_Provisioning_API_Apps', 'getApp'), 'provisioning_api'); +OCP\API::register('post', '/cloud/apps/{appid}', array('OC_Provisioning_API_Apps', 'enable'), 'provisioning_api'); +OCP\API::register('delete', '/cloud/apps/{appid}', array('OC_Provisioning_API_Apps', 'disable'), 'provisioning_api'); ?> \ No newline at end of file diff --git a/ocs/routes.php b/ocs/routes.php index ac23e29af8..696b17ca23 100644 --- a/ocs/routes.php +++ b/ocs/routes.php @@ -19,8 +19,8 @@ OC_API::register('post', '/privatedata/setattribute/{app}/{key}', array('OC_OCS_ OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}', array('OC_OCS_Privatedata', 'delete'), 'ocs'); // Cloud OC_API::register('get', '/cloud/system/webapps', array('OC_OCS_Cloud', 'getSystemWebApps'), 'ocs'); -OC_API::register('get', '/cloud/user/{user}', array('OC_OCS_Cloud', 'getUserQuota'), 'ocs'); -OC_API::register('post', '/cloud/user/{user}', array('OC_OCS_Cloud', 'setUserQuota'), 'ocs'); +OC_API::register('get', '/cloud/user/{user}/quota', array('OC_OCS_Cloud', 'getUserQuota'), 'ocs'); +OC_API::register('post', '/cloud/user/{user}/quota', array('OC_OCS_Cloud', 'setUserQuota'), 'ocs'); OC_API::register('get', '/cloud/user/{user}/publickey', array('OC_OCS_Cloud', 'getUserPublicKey'), 'ocs'); OC_API::register('get', '/cloud/user/{user}/privatekey', array('OC_OCS_Cloud', 'getUserPrivateKey'), 'ocs'); From 2afe5f9b2b59094b632e79e0a0fec0cd70509273 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 1 Aug 2012 13:37:00 +0000 Subject: [PATCH 047/330] API: add OC_API::checkLoggedIn() --- lib/api.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/lib/api.php b/lib/api.php index cf699f547f..a11dde1c6b 100644 --- a/lib/api.php +++ b/lib/api.php @@ -121,4 +121,15 @@ class OC_API { } } + /** + * check if the user is authenticated + */ + public static function checkLoggedIn(){ + // Check OAuth + if(!OC_OAuth::isAuthorised()){ + OC_Response::setStatus(401); + die(); + } + } + } From c11c2d0fd46fbe2e74ff7fe2ff7205c5cb38ea9f Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 1 Aug 2012 13:39:05 +0000 Subject: [PATCH 048/330] Logout the user at the end of a call to be stateless --- lib/api.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/api.php b/lib/api.php index a11dde1c6b..454a6fd26d 100644 --- a/lib/api.php +++ b/lib/api.php @@ -77,6 +77,8 @@ class OC_API { } else { self::respond($response); } + // logout the user to be stateles + OC_User::logout(); } /** From 93daa9e247e9c423a6d4bb10af1106fdde37b800 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Wed, 1 Aug 2012 19:48:51 +0200 Subject: [PATCH 049/330] API: Complete respond function --- lib/api.php | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/lib/api.php b/lib/api.php index 454a6fd26d..6ee570d60e 100644 --- a/lib/api.php +++ b/lib/api.php @@ -115,13 +115,32 @@ class OC_API { */ private static function respond($response, $format='json'){ if ($format == 'json') { - echo json_encode($response); - //} else if ($format == 'xml') { - // TODO array to xml + OC_JSON::encodedPrint($response); + } else if ($format == 'xml') { + header('Content-type: text/xml; charset=UTF-8'); + $writer = new XMLWriter(); + $writer->openMemory(); + $writer->setIndent( true ); + $writer->startDocument(); + self::toXML($response, $writer); + $writer->endDocument(); + echo $writer->outputMemory(true); } else { var_dump($format, $response); } } + + private static function toXML($array, $writer){ + foreach($array as $k => $v) { + if (is_array($v)) { + $writer->startElement($k); + self::toXML($v, $writer); + $writer->endElement(); + } else { + $writer->writeElement($k, $v); + } + } + } /** * check if the user is authenticated From 7952c6a31c27718428fddbca71c587506eb071d8 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 2 Aug 2012 17:47:38 +0200 Subject: [PATCH 050/330] Change access to router object to getter function --- lib/api.php | 2 +- lib/base.php | 18 ++++++++++++------ ocs/v1.php | 6 +++--- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/lib/api.php b/lib/api.php index 6ee570d60e..155082fa0d 100644 --- a/lib/api.php +++ b/lib/api.php @@ -44,7 +44,7 @@ class OC_API { $name = strtolower($method).$url; $name = str_replace(array('/', '{', '}'), '_', $name); if(!isset(self::$actions[$name])){ - OC::$router->create($name, $url.'.{_format}') + OC::getRouter()->create($name, $url.'.{_format}') ->method($method) ->defaults(array('_format' => 'xml') + $defaults) ->requirements(array('_format' => 'xml|json') + $requirements) diff --git a/lib/base.php b/lib/base.php index 29a3502e35..43588944d0 100644 --- a/lib/base.php +++ b/lib/base.php @@ -62,14 +62,14 @@ class OC{ * requested file of app */ public static $REQUESTEDFILE = ''; - /* - * OC router - */ - public static $router = null; /** * check if owncloud runs in cli mode */ public static $CLI = false; + /* + * OC router + */ + protected static $router = null; /** * SPL autoload */ @@ -275,6 +275,14 @@ class OC{ } } + public static function getRouter() { + if (!isset(OC::$router)) { + OC::$router = new OC_Router(); + } + + return OC::$router; + } + public static function init(){ // register autoloader spl_autoload_register(array('OC','autoload')); @@ -358,8 +366,6 @@ class OC{ OC_User::useBackend(new OC_User_Database()); OC_Group::useBackend(new OC_Group_Database()); - OC::$router = new OC_Router(); - // Load Apps // This includes plugins for users and filesystems as well global $RUNTIME_NOAPPS; diff --git a/ocs/v1.php b/ocs/v1.php index 7cd61035e7..cb8a1faf87 100644 --- a/ocs/v1.php +++ b/ocs/v1.php @@ -25,11 +25,11 @@ require_once('../lib/base.php'); use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Exception\MethodNotAllowedException; -OC::$router->useCollection('ocs'); -OC::$router->loadRoutes(); +OC::getRouter()->useCollection('ocs'); +OC::getRouter()->loadRoutes(); try { - OC::$router->match($_SERVER['PATH_INFO']); + OC::getRouter()->match($_SERVER['PATH_INFO']); } catch (ResourceNotFoundException $e) { OC_OCS::notFound(); } catch (MethodNotAllowedException $e) { From 37ef522b057caf0a0058f6be87db39f7a4f1e174 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 2 Aug 2012 17:48:09 +0200 Subject: [PATCH 051/330] Quick fix for xml encoding arrays --- lib/api.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/api.php b/lib/api.php index 155082fa0d..1ef4e090e3 100644 --- a/lib/api.php +++ b/lib/api.php @@ -132,6 +132,9 @@ class OC_API { private static function toXML($array, $writer){ foreach($array as $k => $v) { + if (is_numeric($k)) { + $k = 'element'; + } if (is_array($v)) { $writer->startElement($k); self::toXML($v, $writer); From 6ba2623485655460440a972e34a8a2a2fda02821 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 2 Aug 2012 17:59:18 +0200 Subject: [PATCH 052/330] Move loading of routes to OC::getRouter function --- lib/base.php | 1 + lib/router.php | 7 ++++++- ocs/v1.php | 1 - 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/lib/base.php b/lib/base.php index 43588944d0..0d9ececc0c 100644 --- a/lib/base.php +++ b/lib/base.php @@ -278,6 +278,7 @@ class OC{ public static function getRouter() { if (!isset(OC::$router)) { OC::$router = new OC_Router(); + OC::$router->loadRoutes(); } return OC::$router; diff --git a/lib/router.php b/lib/router.php index c3864cfc91..5c5171cf82 100644 --- a/lib/router.php +++ b/lib/router.php @@ -16,10 +16,15 @@ class OC_Router { protected $collections = array(); protected $collection = null; + public function __construct() { + // TODO cache + $this->loadRoutes(); + } + /** * loads the api routes */ - public function loadRoutes(){ + public function loadRoutes() { // TODO cache foreach(OC_APP::getEnabledApps() as $app){ $file = OC_App::getAppPath($app).'/appinfo/routes.php'; diff --git a/ocs/v1.php b/ocs/v1.php index cb8a1faf87..938a57009f 100644 --- a/ocs/v1.php +++ b/ocs/v1.php @@ -26,7 +26,6 @@ use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Exception\MethodNotAllowedException; OC::getRouter()->useCollection('ocs'); -OC::getRouter()->loadRoutes(); try { OC::getRouter()->match($_SERVER['PATH_INFO']); From 4b9200f6f7a571c251ef89599e1af9e25e2e75f4 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 2 Aug 2012 21:51:31 +0200 Subject: [PATCH 053/330] Routing: combine all routes into one set --- lib/api.php | 1 + lib/router.php | 22 ++++++++++++++-------- ocs/v1.php | 4 +--- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/lib/api.php b/lib/api.php index 1ef4e090e3..05d34ffe87 100644 --- a/lib/api.php +++ b/lib/api.php @@ -44,6 +44,7 @@ class OC_API { $name = strtolower($method).$url; $name = str_replace(array('/', '{', '}'), '_', $name); if(!isset(self::$actions[$name])){ + OC::getRouter()->useCollection('ocs'); OC::getRouter()->create($name, $url.'.{_format}') ->method($method) ->defaults(array('_format' => 'xml') + $defaults) diff --git a/lib/router.php b/lib/router.php index 5c5171cf82..12cd55df41 100644 --- a/lib/router.php +++ b/lib/router.php @@ -15,32 +15,38 @@ use Symfony\Component\Routing\Exception\ResourceNotFoundException; class OC_Router { protected $collections = array(); protected $collection = null; - - public function __construct() { - // TODO cache - $this->loadRoutes(); - } + protected $root = null; /** * loads the api routes */ public function loadRoutes() { // TODO cache + $this->root = $this->getCollection('root'); foreach(OC_APP::getEnabledApps() as $app){ $file = OC_App::getAppPath($app).'/appinfo/routes.php'; if(file_exists($file)){ + $this->useCollection($app); require_once($file); + $collection = $this->getCollection($app); + $this->root->addCollection($collection, '/apps/'.$app); } } // include ocs routes require_once(OC::$SERVERROOT.'/ocs/routes.php'); + $collection = $this->getCollection('ocs'); + $this->root->addCollection($collection, '/ocs'); } - public function useCollection($name) { + protected function getCollection($name) { if (!isset($this->collections[$name])) { $this->collections[$name] = new RouteCollection(); } - $this->collection = $this->collections[$name]; + return $this->collections[$name]; + } + + public function useCollection($name) { + $this->collection = $this->getCollection($name); } public function create($name, $pattern, array $defaults = array(), array $requirements = array()) { @@ -51,7 +57,7 @@ class OC_Router { public function match($url) { $context = new RequestContext($_SERVER['REQUEST_URI'], $_SERVER['REQUEST_METHOD']); - $matcher = new UrlMatcher($this->collection, $context); + $matcher = new UrlMatcher($this->root, $context); $parameters = $matcher->match($url); if (isset($parameters['action'])) { $action = $parameters['action']; diff --git a/ocs/v1.php b/ocs/v1.php index 938a57009f..ce6bad3d45 100644 --- a/ocs/v1.php +++ b/ocs/v1.php @@ -25,10 +25,8 @@ require_once('../lib/base.php'); use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\Exception\MethodNotAllowedException; -OC::getRouter()->useCollection('ocs'); - try { - OC::getRouter()->match($_SERVER['PATH_INFO']); + OC::getRouter()->match('/ocs'.$_SERVER['PATH_INFO']); } catch (ResourceNotFoundException $e) { OC_OCS::notFound(); } catch (MethodNotAllowedException $e) { From e3d88270cc0fcdfc667f0a120040864818b3b2a1 Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Thu, 2 Aug 2012 20:02:31 -0400 Subject: [PATCH 054/330] OAuth server implementation using oauth library --- 3rdparty/OAuth/LICENSE.TXT | 21 + 3rdparty/OAuth/OAuth.php | 895 +++++++++++++++++++++++++++++++++++++ lib/api.php | 11 +- lib/oauth.php | 136 ++---- settings/oauth.php | 23 +- 5 files changed, 980 insertions(+), 106 deletions(-) create mode 100644 3rdparty/OAuth/LICENSE.TXT create mode 100644 3rdparty/OAuth/OAuth.php diff --git a/3rdparty/OAuth/LICENSE.TXT b/3rdparty/OAuth/LICENSE.TXT new file mode 100644 index 0000000000..8891c7ddc9 --- /dev/null +++ b/3rdparty/OAuth/LICENSE.TXT @@ -0,0 +1,21 @@ +The MIT License + +Copyright (c) 2007 Andy Smith + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/3rdparty/OAuth/OAuth.php b/3rdparty/OAuth/OAuth.php new file mode 100644 index 0000000000..64b7007ab9 --- /dev/null +++ b/3rdparty/OAuth/OAuth.php @@ -0,0 +1,895 @@ +key = $key; + $this->secret = $secret; + $this->callback_url = $callback_url; + } + + function __toString() { + return "OAuthConsumer[key=$this->key,secret=$this->secret]"; + } +} + +class OAuthToken { + // access tokens and request tokens + public $key; + public $secret; + + /** + * key = the token + * secret = the token secret + */ + function __construct($key, $secret) { + $this->key = $key; + $this->secret = $secret; + } + + /** + * generates the basic string serialization of a token that a server + * would respond to request_token and access_token calls with + */ + function to_string() { + return "oauth_token=" . + OAuthUtil::urlencode_rfc3986($this->key) . + "&oauth_token_secret=" . + OAuthUtil::urlencode_rfc3986($this->secret); + } + + function __toString() { + return $this->to_string(); + } +} + +/** + * A class for implementing a Signature Method + * See section 9 ("Signing Requests") in the spec + */ +abstract class OAuthSignatureMethod { + /** + * Needs to return the name of the Signature Method (ie HMAC-SHA1) + * @return string + */ + abstract public function get_name(); + + /** + * Build up the signature + * NOTE: The output of this function MUST NOT be urlencoded. + * the encoding is handled in OAuthRequest when the final + * request is serialized + * @param OAuthRequest $request + * @param OAuthConsumer $consumer + * @param OAuthToken $token + * @return string + */ + abstract public function build_signature($request, $consumer, $token); + + /** + * Verifies that a given signature is correct + * @param OAuthRequest $request + * @param OAuthConsumer $consumer + * @param OAuthToken $token + * @param string $signature + * @return bool + */ + public function check_signature($request, $consumer, $token, $signature) { + $built = $this->build_signature($request, $consumer, $token); + + // Check for zero length, although unlikely here + if (strlen($built) == 0 || strlen($signature) == 0) { + return false; + } + + if (strlen($built) != strlen($signature)) { + return false; + } + + // Avoid a timing leak with a (hopefully) time insensitive compare + $result = 0; + for ($i = 0; $i < strlen($signature); $i++) { + $result |= ord($built{$i}) ^ ord($signature{$i}); + } + + return $result == 0; + } +} + +/** + * The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104] + * where the Signature Base String is the text and the key is the concatenated values (each first + * encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&' + * character (ASCII code 38) even if empty. + * - Chapter 9.2 ("HMAC-SHA1") + */ +class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod { + function get_name() { + return "HMAC-SHA1"; + } + + public function build_signature($request, $consumer, $token) { + $base_string = $request->get_signature_base_string(); + $request->base_string = $base_string; + + $key_parts = array( + $consumer->secret, + ($token) ? $token->secret : "" + ); + + $key_parts = OAuthUtil::urlencode_rfc3986($key_parts); + $key = implode('&', $key_parts); + + return base64_encode(hash_hmac('sha1', $base_string, $key, true)); + } +} + +/** + * The PLAINTEXT method does not provide any security protection and SHOULD only be used + * over a secure channel such as HTTPS. It does not use the Signature Base String. + * - Chapter 9.4 ("PLAINTEXT") + */ +class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod { + public function get_name() { + return "PLAINTEXT"; + } + + /** + * oauth_signature is set to the concatenated encoded values of the Consumer Secret and + * Token Secret, separated by a '&' character (ASCII code 38), even if either secret is + * empty. The result MUST be encoded again. + * - Chapter 9.4.1 ("Generating Signatures") + * + * Please note that the second encoding MUST NOT happen in the SignatureMethod, as + * OAuthRequest handles this! + */ + public function build_signature($request, $consumer, $token) { + $key_parts = array( + $consumer->secret, + ($token) ? $token->secret : "" + ); + + $key_parts = OAuthUtil::urlencode_rfc3986($key_parts); + $key = implode('&', $key_parts); + $request->base_string = $key; + + return $key; + } +} + +/** + * The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in + * [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for + * EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a + * verified way to the Service Provider, in a manner which is beyond the scope of this + * specification. + * - Chapter 9.3 ("RSA-SHA1") + */ +abstract class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod { + public function get_name() { + return "RSA-SHA1"; + } + + // Up to the SP to implement this lookup of keys. Possible ideas are: + // (1) do a lookup in a table of trusted certs keyed off of consumer + // (2) fetch via http using a url provided by the requester + // (3) some sort of specific discovery code based on request + // + // Either way should return a string representation of the certificate + protected abstract function fetch_public_cert(&$request); + + // Up to the SP to implement this lookup of keys. Possible ideas are: + // (1) do a lookup in a table of trusted certs keyed off of consumer + // + // Either way should return a string representation of the certificate + protected abstract function fetch_private_cert(&$request); + + public function build_signature($request, $consumer, $token) { + $base_string = $request->get_signature_base_string(); + $request->base_string = $base_string; + + // Fetch the private key cert based on the request + $cert = $this->fetch_private_cert($request); + + // Pull the private key ID from the certificate + $privatekeyid = openssl_get_privatekey($cert); + + // Sign using the key + $ok = openssl_sign($base_string, $signature, $privatekeyid); + + // Release the key resource + openssl_free_key($privatekeyid); + + return base64_encode($signature); + } + + public function check_signature($request, $consumer, $token, $signature) { + $decoded_sig = base64_decode($signature); + + $base_string = $request->get_signature_base_string(); + + // Fetch the public key cert based on the request + $cert = $this->fetch_public_cert($request); + + // Pull the public key ID from the certificate + $publickeyid = openssl_get_publickey($cert); + + // Check the computed signature against the one passed in the query + $ok = openssl_verify($base_string, $decoded_sig, $publickeyid); + + // Release the key resource + openssl_free_key($publickeyid); + + return $ok == 1; + } +} + +class OAuthRequest { + protected $parameters; + protected $http_method; + protected $http_url; + // for debug purposes + public $base_string; + public static $version = '1.0'; + public static $POST_INPUT = 'php://input'; + + function __construct($http_method, $http_url, $parameters=NULL) { + $parameters = ($parameters) ? $parameters : array(); + $parameters = array_merge( OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters); + $this->parameters = $parameters; + $this->http_method = $http_method; + $this->http_url = $http_url; + } + + + /** + * attempt to build up a request from what was passed to the server + */ + public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) { + $scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on") + ? 'http' + : 'https'; + $http_url = ($http_url) ? $http_url : $scheme . + '://' . $_SERVER['SERVER_NAME'] . + ':' . + $_SERVER['SERVER_PORT'] . + $_SERVER['REQUEST_URI']; + $http_method = ($http_method) ? $http_method : $_SERVER['REQUEST_METHOD']; + + // We weren't handed any parameters, so let's find the ones relevant to + // this request. + // If you run XML-RPC or similar you should use this to provide your own + // parsed parameter-list + if (!$parameters) { + // Find request headers + $request_headers = OAuthUtil::get_headers(); + + // Parse the query-string to find GET parameters + $parameters = OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']); + + // It's a POST request of the proper content-type, so parse POST + // parameters and add those overriding any duplicates from GET + if ($http_method == "POST" + && isset($request_headers['Content-Type']) + && strstr($request_headers['Content-Type'], + 'application/x-www-form-urlencoded') + ) { + $post_data = OAuthUtil::parse_parameters( + file_get_contents(self::$POST_INPUT) + ); + $parameters = array_merge($parameters, $post_data); + } + + // We have a Authorization-header with OAuth data. Parse the header + // and add those overriding any duplicates from GET or POST + if (isset($request_headers['Authorization']) && substr($request_headers['Authorization'], 0, 6) == 'OAuth ') { + $header_parameters = OAuthUtil::split_header( + $request_headers['Authorization'] + ); + $parameters = array_merge($parameters, $header_parameters); + } + + } + + return new OAuthRequest($http_method, $http_url, $parameters); + } + + /** + * pretty much a helper function to set up the request + */ + public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) { + $parameters = ($parameters) ? $parameters : array(); + $defaults = array("oauth_version" => OAuthRequest::$version, + "oauth_nonce" => OAuthRequest::generate_nonce(), + "oauth_timestamp" => OAuthRequest::generate_timestamp(), + "oauth_consumer_key" => $consumer->key); + if ($token) + $defaults['oauth_token'] = $token->key; + + $parameters = array_merge($defaults, $parameters); + + return new OAuthRequest($http_method, $http_url, $parameters); + } + + public function set_parameter($name, $value, $allow_duplicates = true) { + if ($allow_duplicates && isset($this->parameters[$name])) { + // We have already added parameter(s) with this name, so add to the list + if (is_scalar($this->parameters[$name])) { + // This is the first duplicate, so transform scalar (string) + // into an array so we can add the duplicates + $this->parameters[$name] = array($this->parameters[$name]); + } + + $this->parameters[$name][] = $value; + } else { + $this->parameters[$name] = $value; + } + } + + public function get_parameter($name) { + return isset($this->parameters[$name]) ? $this->parameters[$name] : null; + } + + public function get_parameters() { + return $this->parameters; + } + + public function unset_parameter($name) { + unset($this->parameters[$name]); + } + + /** + * The request parameters, sorted and concatenated into a normalized string. + * @return string + */ + public function get_signable_parameters() { + // Grab all parameters + $params = $this->parameters; + + // Remove oauth_signature if present + // Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.") + if (isset($params['oauth_signature'])) { + unset($params['oauth_signature']); + } + + return OAuthUtil::build_http_query($params); + } + + /** + * Returns the base string of this request + * + * The base string defined as the method, the url + * and the parameters (normalized), each urlencoded + * and the concated with &. + */ + public function get_signature_base_string() { + $parts = array( + $this->get_normalized_http_method(), + $this->get_normalized_http_url(), + $this->get_signable_parameters() + ); + + $parts = OAuthUtil::urlencode_rfc3986($parts); + + return implode('&', $parts); + } + + /** + * just uppercases the http method + */ + public function get_normalized_http_method() { + return strtoupper($this->http_method); + } + + /** + * parses the url and rebuilds it to be + * scheme://host/path + */ + public function get_normalized_http_url() { + $parts = parse_url($this->http_url); + + $scheme = (isset($parts['scheme'])) ? $parts['scheme'] : 'http'; + $port = (isset($parts['port'])) ? $parts['port'] : (($scheme == 'https') ? '443' : '80'); + $host = (isset($parts['host'])) ? strtolower($parts['host']) : ''; + $path = (isset($parts['path'])) ? $parts['path'] : ''; + + if (($scheme == 'https' && $port != '443') + || ($scheme == 'http' && $port != '80')) { + $host = "$host:$port"; + } + return "$scheme://$host$path"; + } + + /** + * builds a url usable for a GET request + */ + public function to_url() { + $post_data = $this->to_postdata(); + $out = $this->get_normalized_http_url(); + if ($post_data) { + $out .= '?'.$post_data; + } + return $out; + } + + /** + * builds the data one would send in a POST request + */ + public function to_postdata() { + return OAuthUtil::build_http_query($this->parameters); + } + + /** + * builds the Authorization: header + */ + public function to_header($realm=null) { + $first = true; + if($realm) { + $out = 'Authorization: OAuth realm="' . OAuthUtil::urlencode_rfc3986($realm) . '"'; + $first = false; + } else + $out = 'Authorization: OAuth'; + + $total = array(); + foreach ($this->parameters as $k => $v) { + if (substr($k, 0, 5) != "oauth") continue; + if (is_array($v)) { + throw new OAuthException('Arrays not supported in headers'); + } + $out .= ($first) ? ' ' : ','; + $out .= OAuthUtil::urlencode_rfc3986($k) . + '="' . + OAuthUtil::urlencode_rfc3986($v) . + '"'; + $first = false; + } + return $out; + } + + public function __toString() { + return $this->to_url(); + } + + + public function sign_request($signature_method, $consumer, $token) { + $this->set_parameter( + "oauth_signature_method", + $signature_method->get_name(), + false + ); + $signature = $this->build_signature($signature_method, $consumer, $token); + $this->set_parameter("oauth_signature", $signature, false); + } + + public function build_signature($signature_method, $consumer, $token) { + $signature = $signature_method->build_signature($this, $consumer, $token); + return $signature; + } + + /** + * util function: current timestamp + */ + private static function generate_timestamp() { + return time(); + } + + /** + * util function: current nonce + */ + private static function generate_nonce() { + $mt = microtime(); + $rand = mt_rand(); + + return md5($mt . $rand); // md5s look nicer than numbers + } +} + +class OAuthServer { + protected $timestamp_threshold = 300; // in seconds, five minutes + protected $version = '1.0'; // hi blaine + protected $signature_methods = array(); + + protected $data_store; + + function __construct($data_store) { + $this->data_store = $data_store; + } + + public function add_signature_method($signature_method) { + $this->signature_methods[$signature_method->get_name()] = + $signature_method; + } + + // high level functions + + /** + * process a request_token request + * returns the request token on success + */ + public function fetch_request_token(&$request) { + $this->get_version($request); + + $consumer = $this->get_consumer($request); + + // no token required for the initial token request + $token = NULL; + + $this->check_signature($request, $consumer, $token); + + // Rev A change + $callback = $request->get_parameter('oauth_callback'); + $new_token = $this->data_store->new_request_token($consumer, $callback); + + return $new_token; + } + + /** + * process an access_token request + * returns the access token on success + */ + public function fetch_access_token(&$request) { + $this->get_version($request); + + $consumer = $this->get_consumer($request); + + // requires authorized request token + $token = $this->get_token($request, $consumer, "request"); + + $this->check_signature($request, $consumer, $token); + + // Rev A change + $verifier = $request->get_parameter('oauth_verifier'); + $new_token = $this->data_store->new_access_token($token, $consumer, $verifier); + + return $new_token; + } + + /** + * verify an api call, checks all the parameters + */ + public function verify_request(&$request) { + $this->get_version($request); + $consumer = $this->get_consumer($request); + $token = $this->get_token($request, $consumer, "access"); + $this->check_signature($request, $consumer, $token); + return array($consumer, $token); + } + + // Internals from here + /** + * version 1 + */ + private function get_version(&$request) { + $version = $request->get_parameter("oauth_version"); + if (!$version) { + // Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present. + // Chapter 7.0 ("Accessing Protected Ressources") + $version = '1.0'; + } + if ($version !== $this->version) { + throw new OAuthException("OAuth version '$version' not supported"); + } + return $version; + } + + /** + * figure out the signature with some defaults + */ + private function get_signature_method($request) { + $signature_method = $request instanceof OAuthRequest + ? $request->get_parameter("oauth_signature_method") + : NULL; + + if (!$signature_method) { + // According to chapter 7 ("Accessing Protected Ressources") the signature-method + // parameter is required, and we can't just fallback to PLAINTEXT + throw new OAuthException('No signature method parameter. This parameter is required'); + } + + if (!in_array($signature_method, + array_keys($this->signature_methods))) { + throw new OAuthException( + "Signature method '$signature_method' not supported " . + "try one of the following: " . + implode(", ", array_keys($this->signature_methods)) + ); + } + return $this->signature_methods[$signature_method]; + } + + /** + * try to find the consumer for the provided request's consumer key + */ + private function get_consumer($request) { + $consumer_key = $request instanceof OAuthRequest + ? $request->get_parameter("oauth_consumer_key") + : NULL; + + if (!$consumer_key) { + throw new OAuthException("Invalid consumer key"); + } + + $consumer = $this->data_store->lookup_consumer($consumer_key); + if (!$consumer) { + throw new OAuthException("Invalid consumer"); + } + + return $consumer; + } + + /** + * try to find the token for the provided request's token key + */ + private function get_token($request, $consumer, $token_type="access") { + $token_field = $request instanceof OAuthRequest + ? $request->get_parameter('oauth_token') + : NULL; + + $token = $this->data_store->lookup_token( + $consumer, $token_type, $token_field + ); + if (!$token) { + throw new OAuthException("Invalid $token_type token: $token_field"); + } + return $token; + } + + /** + * all-in-one function to check the signature on a request + * should guess the signature method appropriately + */ + private function check_signature($request, $consumer, $token) { + // this should probably be in a different method + $timestamp = $request instanceof OAuthRequest + ? $request->get_parameter('oauth_timestamp') + : NULL; + $nonce = $request instanceof OAuthRequest + ? $request->get_parameter('oauth_nonce') + : NULL; + + $this->check_timestamp($timestamp); + $this->check_nonce($consumer, $token, $nonce, $timestamp); + + $signature_method = $this->get_signature_method($request); + + $signature = $request->get_parameter('oauth_signature'); + $valid_sig = $signature_method->check_signature( + $request, + $consumer, + $token, + $signature + ); + + if (!$valid_sig) { + throw new OAuthException("Invalid signature"); + } + } + + /** + * check that the timestamp is new enough + */ + private function check_timestamp($timestamp) { + if( ! $timestamp ) + throw new OAuthException( + 'Missing timestamp parameter. The parameter is required' + ); + + // verify that timestamp is recentish + $now = time(); + if (abs($now - $timestamp) > $this->timestamp_threshold) { + throw new OAuthException( + "Expired timestamp, yours $timestamp, ours $now" + ); + } + } + + /** + * check that the nonce is not repeated + */ + private function check_nonce($consumer, $token, $nonce, $timestamp) { + if( ! $nonce ) + throw new OAuthException( + 'Missing nonce parameter. The parameter is required' + ); + + // verify that the nonce is uniqueish + $found = $this->data_store->lookup_nonce( + $consumer, + $token, + $nonce, + $timestamp + ); + if ($found) { + throw new OAuthException("Nonce already used: $nonce"); + } + } + +} + +class OAuthDataStore { + function lookup_consumer($consumer_key) { + // implement me + } + + function lookup_token($consumer, $token_type, $token) { + // implement me + } + + function lookup_nonce($consumer, $token, $nonce, $timestamp) { + // implement me + } + + function new_request_token($consumer, $callback = null) { + // return a new token attached to this consumer + } + + function new_access_token($token, $consumer, $verifier = null) { + // return a new access token attached to this consumer + // for the user associated with this token if the request token + // is authorized + // should also invalidate the request token + } + +} + +class OAuthUtil { + public static function urlencode_rfc3986($input) { + if (is_array($input)) { + return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input); + } else if (is_scalar($input)) { + return str_replace( + '+', + ' ', + str_replace('%7E', '~', rawurlencode($input)) + ); + } else { + return ''; + } +} + + + // This decode function isn't taking into consideration the above + // modifications to the encoding process. However, this method doesn't + // seem to be used anywhere so leaving it as is. + public static function urldecode_rfc3986($string) { + return urldecode($string); + } + + // Utility function for turning the Authorization: header into + // parameters, has to do some unescaping + // Can filter out any non-oauth parameters if needed (default behaviour) + // May 28th, 2010 - method updated to tjerk.meesters for a speed improvement. + // see http://code.google.com/p/oauth/issues/detail?id=163 + public static function split_header($header, $only_allow_oauth_parameters = true) { + $params = array(); + if (preg_match_all('/('.($only_allow_oauth_parameters ? 'oauth_' : '').'[a-z_-]*)=(:?"([^"]*)"|([^,]*))/', $header, $matches)) { + foreach ($matches[1] as $i => $h) { + $params[$h] = OAuthUtil::urldecode_rfc3986(empty($matches[3][$i]) ? $matches[4][$i] : $matches[3][$i]); + } + if (isset($params['realm'])) { + unset($params['realm']); + } + } + return $params; + } + + // helper to try to sort out headers for people who aren't running apache + public static function get_headers() { + if (function_exists('apache_request_headers')) { + // we need this to get the actual Authorization: header + // because apache tends to tell us it doesn't exist + $headers = apache_request_headers(); + + // sanitize the output of apache_request_headers because + // we always want the keys to be Cased-Like-This and arh() + // returns the headers in the same case as they are in the + // request + $out = array(); + foreach ($headers AS $key => $value) { + $key = str_replace( + " ", + "-", + ucwords(strtolower(str_replace("-", " ", $key))) + ); + $out[$key] = $value; + } + } else { + // otherwise we don't have apache and are just going to have to hope + // that $_SERVER actually contains what we need + $out = array(); + if( isset($_SERVER['CONTENT_TYPE']) ) + $out['Content-Type'] = $_SERVER['CONTENT_TYPE']; + if( isset($_ENV['CONTENT_TYPE']) ) + $out['Content-Type'] = $_ENV['CONTENT_TYPE']; + + foreach ($_SERVER as $key => $value) { + if (substr($key, 0, 5) == "HTTP_") { + // this is chaos, basically it is just there to capitalize the first + // letter of every word that is not an initial HTTP and strip HTTP + // code from przemek + $key = str_replace( + " ", + "-", + ucwords(strtolower(str_replace("_", " ", substr($key, 5)))) + ); + $out[$key] = $value; + } + } + } + return $out; + } + + // This function takes a input like a=b&a=c&d=e and returns the parsed + // parameters like this + // array('a' => array('b','c'), 'd' => 'e') + public static function parse_parameters( $input ) { + if (!isset($input) || !$input) return array(); + + $pairs = explode('&', $input); + + $parsed_parameters = array(); + foreach ($pairs as $pair) { + $split = explode('=', $pair, 2); + $parameter = OAuthUtil::urldecode_rfc3986($split[0]); + $value = isset($split[1]) ? OAuthUtil::urldecode_rfc3986($split[1]) : ''; + + if (isset($parsed_parameters[$parameter])) { + // We have already recieved parameter(s) with this name, so add to the list + // of parameters with this name + + if (is_scalar($parsed_parameters[$parameter])) { + // This is the first duplicate, so transform scalar (string) into an array + // so we can add the duplicates + $parsed_parameters[$parameter] = array($parsed_parameters[$parameter]); + } + + $parsed_parameters[$parameter][] = $value; + } else { + $parsed_parameters[$parameter] = $value; + } + } + return $parsed_parameters; + } + + public static function build_http_query($params) { + if (!$params) return ''; + + // Urlencode both keys and values + $keys = OAuthUtil::urlencode_rfc3986(array_keys($params)); + $values = OAuthUtil::urlencode_rfc3986(array_values($params)); + $params = array_combine($keys, $values); + + // Parameters are sorted by name, using lexicographical byte value ordering. + // Ref: Spec: 9.1.1 (1) + uksort($params, 'strcmp'); + + $pairs = array(); + foreach ($params as $parameter => $value) { + if (is_array($value)) { + // If two or more parameters share the same name, they are sorted by their value + // Ref: Spec: 9.1.1 (1) + // June 12th, 2010 - changed to sort because of issue 164 by hidetaka + sort($value, SORT_STRING); + foreach ($value as $duplicate_value) { + $pairs[] = $parameter . '=' . $duplicate_value; + } + } else { + $pairs[] = $parameter . '=' . $value; + } + } + // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61) + // Each name-value pair is separated by an '&' character (ASCII code 38) + return implode('&', $pairs); + } +} + +?> \ No newline at end of file diff --git a/lib/api.php b/lib/api.php index 05d34ffe87..c8bd0aec2f 100644 --- a/lib/api.php +++ b/lib/api.php @@ -25,6 +25,15 @@ */ class OC_API { + + private static $server; + + /** + * initialises the OAuth store and server + */ + private static function init() { + self::$server = new OC_OAuthServer(new OC_OAuthStore()); + } /** * api actions @@ -151,7 +160,7 @@ class OC_API { */ public static function checkLoggedIn(){ // Check OAuth - if(!OC_OAuth::isAuthorised()){ + if(!OC_OAuthServer::isAuthorised()){ OC_Response::setStatus(401); die(); } diff --git a/lib/oauth.php b/lib/oauth.php index 0621a72a72..b72d9aab44 100644 --- a/lib/oauth.php +++ b/lib/oauth.php @@ -2,8 +2,10 @@ /** * ownCloud * -* @author Tom Needham -* @copyright 2012 Tom Needham tom@owncloud.com +* @author Tom Needham +* @author Michael Gapczynski +* @copyright 2012 Tom Needham tom@owncloud.com +* @copyright 2012 Michael Gapczynski mtgap@owncloud.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE @@ -20,87 +22,25 @@ * */ -class OC_OAuth { - - /** - * the oauth-php server object - */ - private static $server; - - /** - * the oauth-php oauthstore object - */ - private static $store; - - /** - * initialises the OAuth store and server - */ - private static function init(){ - // Include the libraries - require_once(OC::$THIRDPARTYROOT.'/3rdparty/oauth-php/library/OAuthServer.php'); - require_once(OC::$THIRDPARTYROOT.'/3rdparty/oauth-php/library/OAuthStore.php'); - // Initialise the OAuth store - self::$store = OAuthStore::instance('Session'); - // Create the server object - self::$server = new OAuthServer(); +class OC_OAuthServer extends OAuthServer { + + public function fetch_request_token(&$request) { + $this->get_version($request); + $consumer = $this->get_consumer($request); + $this->check_signature($request, $consumer, null); + $callback = $request->get_parameter('oauth_callback'); + $scope = $request->get_parameter('scope'); + // TODO Validate scopes + return $this->data_store->new_request_token($consumer, $scope, $callback); } - /** - * gets a request token - * TODO save the scopes in the database with this token - */ - public static function getRequestToken(){ - self::init(); - self::$server->requestToken(); - } - - /** - * get the scopes requested by this token - * @param string $requesttoken - * @return array scopes - */ - public static function getScopes($requesttoken){ - // TODO - } - - /** - * exchanges authorised request token for access token - */ - public static function getAccessToken(){ - self::init(); - self::$server->accessToken(); - } - - /** - * registers a new consumer - * @param array $details consumer details, keys requester_name and requester_email required - * @param string $user the owncloud user adding the consumer - * @return array the consumers details including secret and key - */ - public static function registerConsumer($details, $user){ - self::init(); - $consumer = self::$store->updateConsumer($details, $user, OC_Group::inGroup($user, 'admin')); - return $consumer; - } - - /** - * gets a list of consumers - * @param string $user - */ - public static function getConsumers($user=null){ - $user = is_null($user) ? OC_User::getUser() : $user; - return self::$store->listConsumers($user); - } - - /** - * authorises a request token - redirects to callback - * @param string $user - * @param bool $authorised - */ - public static function authoriseToken($user=null){ - $user = is_null($user) ? OC_User::getUser() : $user; - self::$server->authorizeVerify(); - self::$server->authorize($authorised, $user); + public function authoriseRequestToken(&$request) { + $this->get_version($request); + $consumer = $this->get_consumer($request); + $this->check_signature($request, $consumer, null); + $token = $this->get_token($request, $consumer, 'request'); + $this->check_signature($request, $consumer, $token); + return $this->data_store->authorise_request_token($token, $consumer, OC_User::getUser()); } /** @@ -108,28 +48,22 @@ class OC_OAuth { * TODO distinguish between failures as one is a 400 error and other is 401 * @return string|int */ - public static function isAuthorised(){ - self::init(); - if(OAuthRequestVerifier::requestIsSigned()){ - try{ - $req = new OAuthRequestVerifier(); - $user = $req->verify(); - $run = true; - OC_Hook::emit( "OC_User", "pre_login", array( "run" => &$run, "uid" => $user )); - if(!$run){ - return false; - } - OC_User::setUserId($user); - OC_Hook::emit( "OC_User", "post_login", array( "uid" => $user )); - return $user; - } catch(OAuthException $e) { - // 401 Unauthorised - return false; - } - } else { - // Bad request + public static function isAuthorised($scope) { + try { + $request = OAuthRequest::from_request(); + $this->verify_request(); + } catch (OAuthException $exception) { return false; } + // TODO Get user out of token? May have to write own verify_request() +// $run = true; +// OC_Hook::emit( "OC_User", "pre_login", array( "run" => &$run, "uid" => $user )); +// if(!$run){ +// return false; +// } +// OC_User::setUserId($user); +// OC_Hook::emit( "OC_User", "post_login", array( "uid" => $user )); +// return $user; } } \ No newline at end of file diff --git a/settings/oauth.php b/settings/oauth.php index 2592b926d1..9e7a3c0493 100644 --- a/settings/oauth.php +++ b/settings/oauth.php @@ -9,6 +9,7 @@ require_once('../lib/base.php'); // Logic $operation = isset($_GET['operation']) ? $_GET['operation'] : ''; +$server = new OC_OAuthServer(new OC_OAuthStore()); switch($operation){ case 'register': @@ -16,8 +17,15 @@ switch($operation){ break; case 'request_token': - break; - + try { + $request = OAuthRequest::from_request(); + $token = $server->fetch_request_token($request); + echo $token; + } catch (OAuthException $exception) { + OC_Log::write('OC_OAuthServer', $exception->getMessage(), OC_LOG::ERROR); + echo $exception->getMessage(); + } + break; case 'authorise'; OC_Util::checkLoggedIn(); // Example @@ -56,8 +64,15 @@ switch($operation){ break; case 'access_token'; - break; - + try { + $request = OAuthRequest::from_request(); + $token = $server->fetch_access_token($request); + echo $token; + } catch (OAuthException $exception) { + OC_Log::write('OC_OAuthServer', $exception->getMessage(), OC_LOG::ERROR); + echo $exception->getMessage(); + } + break; default: // Something went wrong header('Location: /'); From 395a056b648ad1513a7445617200db53b784ffb6 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 3 Aug 2012 09:27:16 +0000 Subject: [PATCH 055/330] Remove old oauth-php library --- 3rdparty/oauth-php/LICENSE | 22 - 3rdparty/oauth-php/README | 1 - 3rdparty/oauth-php/library/OAuthDiscovery.php | 227 -- .../oauth-php/library/OAuthException2.php | 50 - 3rdparty/oauth-php/library/OAuthRequest.php | 846 ------- .../oauth-php/library/OAuthRequestLogger.php | 316 --- .../oauth-php/library/OAuthRequestSigner.php | 215 -- .../library/OAuthRequestVerifier.php | 306 --- 3rdparty/oauth-php/library/OAuthRequester.php | 521 ----- 3rdparty/oauth-php/library/OAuthServer.php | 333 --- 3rdparty/oauth-php/library/OAuthSession.php | 86 - 3rdparty/oauth-php/library/OAuthStore.php | 86 - .../body/OAuthBodyContentDisposition.php | 129 -- .../body/OAuthBodyMultipartFormdata.php | 143 -- .../library/discovery/xrds_parse.php | 304 --- .../library/discovery/xrds_parse.txt | 101 - .../session/OAuthSessionAbstract.class.php | 44 - .../library/session/OAuthSessionSESSION.php | 63 - .../OAuthSignatureMethod.class.php | 69 - .../OAuthSignatureMethod_HMAC_SHA1.php | 115 - .../OAuthSignatureMethod_MD5.php | 95 - .../OAuthSignatureMethod_PLAINTEXT.php | 80 - .../OAuthSignatureMethod_RSA_SHA1.php | 139 -- .../library/store/OAuthStore2Leg.php | 113 - .../store/OAuthStoreAbstract.class.php | 150 -- .../library/store/OAuthStoreAnyMeta.php | 264 --- .../library/store/OAuthStoreMySQL.php | 245 --- .../library/store/OAuthStoreMySQLi.php | 306 --- .../library/store/OAuthStoreOracle.php | 1536 ------------- .../oauth-php/library/store/OAuthStorePDO.php | 274 --- .../library/store/OAuthStorePostgreSQL.php | 1957 ----------------- .../oauth-php/library/store/OAuthStoreSQL.php | 1827 --------------- .../library/store/OAuthStoreSession.php | 157 -- .../oauth-php/library/store/mysql/install.php | 32 - .../oauth-php/library/store/mysql/mysql.sql | 236 -- .../store/oracle/OracleDB/1_Tables/TABLES.sql | 114 - .../oracle/OracleDB/2_Sequences/SEQUENCES.sql | 9 - .../SP_ADD_CONSUMER_REQUEST_TOKEN.prc | 71 - .../OracleDB/3_Procedures/SP_ADD_LOG.prc | 31 - .../3_Procedures/SP_ADD_SERVER_TOKEN.prc | 55 - .../SP_AUTH_CONSUMER_REQ_TOKEN.prc | 32 - .../3_Procedures/SP_CHECK_SERVER_NONCE.prc | 81 - .../3_Procedures/SP_CONSUMER_STATIC_SAVE.prc | 28 - .../SP_COUNT_CONSUMER_ACCESS_TOKEN.prc | 27 - .../3_Procedures/SP_COUNT_SERVICE_TOKENS.prc | 28 - .../3_Procedures/SP_DELETE_CONSUMER.prc | 35 - .../3_Procedures/SP_DELETE_SERVER.prc | 35 - .../3_Procedures/SP_DELETE_SERVER_TOKEN.prc | 37 - .../SP_DEL_CONSUMER_ACCESS_TOKEN.prc | 33 - .../SP_DEL_CONSUMER_REQUEST_TOKEN.prc | 25 - .../SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc | 96 - .../OracleDB/3_Procedures/SP_GET_CONSUMER.prc | 41 - .../SP_GET_CONSUMER_ACCESS_TOKEN.prc | 43 - .../SP_GET_CONSUMER_REQUEST_TOKEN.prc | 41 - .../SP_GET_CONSUMER_STATIC_SELECT.prc | 25 - .../SP_GET_SECRETS_FOR_SIGNATURE.prc | 43 - .../SP_GET_SECRETS_FOR_VERIFY.prc | 52 - .../OracleDB/3_Procedures/SP_GET_SERVER.prc | 35 - .../3_Procedures/SP_GET_SERVER_FOR_URI.prc | 41 - .../3_Procedures/SP_GET_SERVER_TOKEN.prc | 45 - .../SP_GET_SERVER_TOKEN_SECRETS.prc | 47 - .../3_Procedures/SP_LIST_CONSUMERS.prc | 41 - .../3_Procedures/SP_LIST_CONSUMER_TOKENS.prc | 43 - .../OracleDB/3_Procedures/SP_LIST_LOG.prc | 75 - .../OracleDB/3_Procedures/SP_LIST_SERVERS.prc | 66 - .../3_Procedures/SP_LIST_SERVER_TOKENS.prc | 45 - .../SP_SET_CONSUMER_ACC_TOKEN_TTL.prc | 28 - .../3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc | 29 - .../3_Procedures/SP_UPDATE_CONSUMER.prc | 40 - .../3_Procedures/SP_UPDATE_SERVER.prc | 139 -- .../library/store/oracle/install.php | 28 - .../library/store/postgresql/pgsql.sql | 166 -- 72 files changed, 13238 deletions(-) delete mode 100644 3rdparty/oauth-php/LICENSE delete mode 100644 3rdparty/oauth-php/README delete mode 100644 3rdparty/oauth-php/library/OAuthDiscovery.php delete mode 100644 3rdparty/oauth-php/library/OAuthException2.php delete mode 100644 3rdparty/oauth-php/library/OAuthRequest.php delete mode 100644 3rdparty/oauth-php/library/OAuthRequestLogger.php delete mode 100644 3rdparty/oauth-php/library/OAuthRequestSigner.php delete mode 100644 3rdparty/oauth-php/library/OAuthRequestVerifier.php delete mode 100644 3rdparty/oauth-php/library/OAuthRequester.php delete mode 100644 3rdparty/oauth-php/library/OAuthServer.php delete mode 100644 3rdparty/oauth-php/library/OAuthSession.php delete mode 100644 3rdparty/oauth-php/library/OAuthStore.php delete mode 100644 3rdparty/oauth-php/library/body/OAuthBodyContentDisposition.php delete mode 100644 3rdparty/oauth-php/library/body/OAuthBodyMultipartFormdata.php delete mode 100644 3rdparty/oauth-php/library/discovery/xrds_parse.php delete mode 100644 3rdparty/oauth-php/library/discovery/xrds_parse.txt delete mode 100644 3rdparty/oauth-php/library/session/OAuthSessionAbstract.class.php delete mode 100644 3rdparty/oauth-php/library/session/OAuthSessionSESSION.php delete mode 100644 3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod.class.php delete mode 100644 3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php delete mode 100644 3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php delete mode 100644 3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php delete mode 100644 3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php delete mode 100644 3rdparty/oauth-php/library/store/OAuthStore2Leg.php delete mode 100644 3rdparty/oauth-php/library/store/OAuthStoreAbstract.class.php delete mode 100644 3rdparty/oauth-php/library/store/OAuthStoreAnyMeta.php delete mode 100644 3rdparty/oauth-php/library/store/OAuthStoreMySQL.php delete mode 100644 3rdparty/oauth-php/library/store/OAuthStoreMySQLi.php delete mode 100644 3rdparty/oauth-php/library/store/OAuthStoreOracle.php delete mode 100644 3rdparty/oauth-php/library/store/OAuthStorePDO.php delete mode 100644 3rdparty/oauth-php/library/store/OAuthStorePostgreSQL.php delete mode 100644 3rdparty/oauth-php/library/store/OAuthStoreSQL.php delete mode 100644 3rdparty/oauth-php/library/store/OAuthStoreSession.php delete mode 100644 3rdparty/oauth-php/library/store/mysql/install.php delete mode 100644 3rdparty/oauth-php/library/store/mysql/mysql.sql delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc delete mode 100644 3rdparty/oauth-php/library/store/oracle/install.php delete mode 100644 3rdparty/oauth-php/library/store/postgresql/pgsql.sql diff --git a/3rdparty/oauth-php/LICENSE b/3rdparty/oauth-php/LICENSE deleted file mode 100644 index fbdcc373b2..0000000000 --- a/3rdparty/oauth-php/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License - -Copyright (c) 2007-2009 Mediamatic Lab -Copyright (c) 2010 Corollarium Technologies - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. \ No newline at end of file diff --git a/3rdparty/oauth-php/README b/3rdparty/oauth-php/README deleted file mode 100644 index ecd6815638..0000000000 --- a/3rdparty/oauth-php/README +++ /dev/null @@ -1 +0,0 @@ -Please see http://code.google.com/p/oauth-php/ for documentation and help. diff --git a/3rdparty/oauth-php/library/OAuthDiscovery.php b/3rdparty/oauth-php/library/OAuthDiscovery.php deleted file mode 100644 index 8eee11877b..0000000000 --- a/3rdparty/oauth-php/library/OAuthDiscovery.php +++ /dev/null @@ -1,227 +0,0 @@ - - * @date Sep 4, 2008 5:05:19 PM - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__).'/discovery/xrds_parse.php'; - -require_once dirname(__FILE__).'/OAuthException2.php'; -require_once dirname(__FILE__).'/OAuthRequestLogger.php'; - - -class OAuthDiscovery -{ - /** - * Return a description how we can do a consumer allocation. Prefers static allocation if - * possible. If static allocation is possible - * - * See also: http://oauth.net/discovery/#consumer_identity_types - * - * @param string uri - * @return array provider description - */ - static function discover ( $uri ) - { - // See what kind of consumer allocations are available - $xrds_file = self::discoverXRDS($uri); - if (!empty($xrds_file)) - { - $xrds = xrds_parse($xrds_file); - if (empty($xrds)) - { - throw new OAuthException2('Could not discover OAuth information for '.$uri); - } - } - else - { - throw new OAuthException2('Could not discover XRDS file at '.$uri); - } - - // Fill an OAuthServer record for the uri found - $ps = parse_url($uri); - $host = isset($ps['host']) ? $ps['host'] : 'localhost'; - $server_uri = $ps['scheme'].'://'.$host.'/'; - - $p = array( - 'user_id' => null, - 'consumer_key' => '', - 'consumer_secret' => '', - 'signature_methods' => '', - 'server_uri' => $server_uri, - 'request_token_uri' => '', - 'authorize_uri' => '', - 'access_token_uri' => '' - ); - - - // Consumer identity (out of bounds or static) - if (isset($xrds['consumer_identity'])) - { - // Try to find a static consumer allocation, we like those :) - foreach ($xrds['consumer_identity'] as $ci) - { - if ($ci['method'] == 'static' && !empty($ci['consumer_key'])) - { - $p['consumer_key'] = $ci['consumer_key']; - $p['consumer_secret'] = ''; - } - else if ($ci['method'] == 'oob' && !empty($ci['uri'])) - { - // TODO: Keep this uri somewhere for the user? - $p['consumer_oob_uri'] = $ci['uri']; - } - } - } - - // The token uris - if (isset($xrds['request'][0]['uri'])) - { - $p['request_token_uri'] = $xrds['request'][0]['uri']; - if (!empty($xrds['request'][0]['signature_method'])) - { - $p['signature_methods'] = $xrds['request'][0]['signature_method']; - } - } - if (isset($xrds['authorize'][0]['uri'])) - { - $p['authorize_uri'] = $xrds['authorize'][0]['uri']; - if (!empty($xrds['authorize'][0]['signature_method'])) - { - $p['signature_methods'] = $xrds['authorize'][0]['signature_method']; - } - } - if (isset($xrds['access'][0]['uri'])) - { - $p['access_token_uri'] = $xrds['access'][0]['uri']; - if (!empty($xrds['access'][0]['signature_method'])) - { - $p['signature_methods'] = $xrds['access'][0]['signature_method']; - } - } - return $p; - } - - - /** - * Discover the XRDS file at the uri. This is a bit primitive, you should overrule - * this function so that the XRDS file can be cached for later referral. - * - * @param string uri - * @return string false when no XRDS file found - */ - static protected function discoverXRDS ( $uri, $recur = 0 ) - { - // Bail out when we are following redirects - if ($recur > 10) - { - return false; - } - - $data = self::curl($uri); - - // Check what we got back, could be: - // 1. The XRDS discovery file itself (check content-type) - // 2. The X-XRDS-Location header - - if (is_string($data) && !empty($data)) - { - list($head,$body) = explode("\r\n\r\n", $data); - $body = trim($body); - $m = false; - - // See if we got the XRDS file itself or we have to follow a location header - if ( preg_match('/^Content-Type:\s*application\/xrds+xml/im', $head) - || preg_match('/^<\?xml[^>]*\?>\s* \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthException2.php b/3rdparty/oauth-php/library/OAuthException2.php deleted file mode 100644 index 30fc80e8fb..0000000000 --- a/3rdparty/oauth-php/library/OAuthException2.php +++ /dev/null @@ -1,50 +0,0 @@ - - * @date Nov 29, 2007 5:33:54 PM - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -// TODO: something with the HTTP return code matching to the problem - -require_once dirname(__FILE__) . '/OAuthRequestLogger.php'; - -class OAuthException2 extends Exception -{ - function __construct ( $message ) - { - Exception::__construct($message); - OAuthRequestLogger::addNote('OAuthException2: '.$message); - } - -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthRequest.php b/3rdparty/oauth-php/library/OAuthRequest.php deleted file mode 100644 index e37e8369a1..0000000000 --- a/3rdparty/oauth-php/library/OAuthRequest.php +++ /dev/null @@ -1,846 +0,0 @@ - - * @date Nov 16, 2007 12:20:31 PM - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -require_once dirname(__FILE__) . '/OAuthException2.php'; - -/** - * Object to parse an incoming OAuth request or prepare an outgoing OAuth request - */ -class OAuthRequest -{ - /* the realm for this request */ - protected $realm; - - /* all the parameters, RFC3986 encoded name/value pairs */ - protected $param = array(); - - /* the parsed request uri */ - protected $uri_parts; - - /* the raw request uri */ - protected $uri; - - /* the request headers */ - protected $headers; - - /* the request method */ - protected $method; - - /* the body of the OAuth request */ - protected $body; - - - /** - * Construct from the current request. Useful for checking the signature of a request. - * When not supplied with any parameters this will use the current request. - * - * @param string uri might include parameters - * @param string method GET, PUT, POST etc. - * @param string parameters additional post parameters, urlencoded (RFC1738) - * @param array headers headers for request - * @param string body optional body of the OAuth request (POST or PUT) - */ - function __construct ( $uri = null, $method = null, $parameters = '', $headers = array(), $body = null ) - { - if (is_object($_SERVER)) - { - // Tainted arrays - the normal stuff in anyMeta - if (!$method) { - $method = $_SERVER->REQUEST_METHOD->getRawUnsafe(); - } - if (empty($uri)) { - $uri = $_SERVER->REQUEST_URI->getRawUnsafe(); - } - } - else - { - // non anyMeta systems - if (!$method) { - if (isset($_SERVER['REQUEST_METHOD'])) { - $method = $_SERVER['REQUEST_METHOD']; - } - else { - $method = 'GET'; - } - } - $proto = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http'; - if (empty($uri)) { - if (strpos($_SERVER['REQUEST_URI'], "://") !== false) { - $uri = $_SERVER['REQUEST_URI']; - } - else { - $uri = sprintf('%s://%s%s', $proto, $_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI']); - } - } - } - $headers = OAuthRequestLogger::getAllHeaders(); - $this->method = strtoupper($method); - - // If this is a post then also check the posted variables - if (strcasecmp($method, 'POST') == 0) - { - // TODO: what to do with 'multipart/form-data'? - if ($this->getRequestContentType() == 'multipart/form-data') - { - // Get the posted body (when available) - if (!isset($headers['X-OAuth-Test'])) - { - $parameters .= $this->getRequestBodyOfMultipart(); - } - } - if ($this->getRequestContentType() == 'application/x-www-form-urlencoded') - { - // Get the posted body (when available) - if (!isset($headers['X-OAuth-Test'])) - { - $parameters .= $this->getRequestBody(); - } - } - else - { - $body = $this->getRequestBody(); - } - } - else if (strcasecmp($method, 'PUT') == 0) - { - $body = $this->getRequestBody(); - } - - $this->method = strtoupper($method); - $this->headers = $headers; - // Store the values, prepare for oauth - $this->uri = $uri; - $this->body = $body; - $this->parseUri($parameters); - $this->parseHeaders(); - $this->transcodeParams(); - } - - - /** - * Return the signature base string. - * Note that we can't use rawurlencode due to specified use of RFC3986. - * - * @return string - */ - function signatureBaseString () - { - $sig = array(); - $sig[] = $this->method; - $sig[] = $this->getRequestUrl(); - $sig[] = $this->getNormalizedParams(); - - return implode('&', array_map(array($this, 'urlencode'), $sig)); - } - - - /** - * Calculate the signature of the request, using the method in oauth_signature_method. - * The signature is returned encoded in the form as used in the url. So the base64 and - * urlencoding has been done. - * - * @param string consumer_secret - * @param string token_secret - * @param string token_type - * @exception when not all parts available - * @return string - */ - function calculateSignature ( $consumer_secret, $token_secret, $token_type = 'access' ) - { - $required = array( - 'oauth_consumer_key', - 'oauth_signature_method', - 'oauth_timestamp', - 'oauth_nonce' - ); - - if ($token_type != 'requestToken') - { - $required[] = 'oauth_token'; - } - - foreach ($required as $req) - { - if (!isset($this->param[$req])) - { - throw new OAuthException2('Can\'t sign request, missing parameter "'.$req.'"'); - } - } - - $this->checks(); - - $base = $this->signatureBaseString(); - $signature = $this->calculateDataSignature($base, $consumer_secret, $token_secret, $this->param['oauth_signature_method']); - return $signature; - } - - - /** - * Calculate the signature of a string. - * Uses the signature method from the current parameters. - * - * @param string data - * @param string consumer_secret - * @param string token_secret - * @param string signature_method - * @exception OAuthException2 thrown when the signature method is unknown - * @return string signature - */ - function calculateDataSignature ( $data, $consumer_secret, $token_secret, $signature_method ) - { - if (is_null($data)) - { - $data = ''; - } - - $sig = $this->getSignatureMethod($signature_method); - return $sig->signature($this, $data, $consumer_secret, $token_secret); - } - - - /** - * Select a signature method from the list of available methods. - * We try to check the most secure methods first. - * - * @todo Let the signature method tell us how secure it is - * @param array methods - * @exception OAuthException2 when we don't support any method in the list - * @return string - */ - public function selectSignatureMethod ( $methods ) - { - if (in_array('HMAC-SHA1', $methods)) - { - $method = 'HMAC-SHA1'; - } - else if (in_array('MD5', $methods)) - { - $method = 'MD5'; - } - else - { - $method = false; - foreach ($methods as $m) - { - $m = strtoupper($m); - $m2 = preg_replace('/[^A-Z0-9]/', '_', $m); - if (file_exists(dirname(__FILE__).'/signature_method/OAuthSignatureMethod_'.$m2.'.php')) - { - $method = $m; - break; - } - } - - if (empty($method)) - { - throw new OAuthException2('None of the signing methods is supported.'); - } - } - return $method; - } - - - /** - * Fetch the signature object used for calculating and checking the signature base string - * - * @param string method - * @return OAuthSignatureMethod object - */ - function getSignatureMethod ( $method ) - { - $m = strtoupper($method); - $m = preg_replace('/[^A-Z0-9]/', '_', $m); - $class = 'OAuthSignatureMethod_'.$m; - - if (file_exists(dirname(__FILE__).'/signature_method/'.$class.'.php')) - { - require_once dirname(__FILE__).'/signature_method/'.$class.'.php'; - $sig = new $class(); - } - else - { - throw new OAuthException2('Unsupported signature method "'.$m.'".'); - } - return $sig; - } - - - /** - * Perform some sanity checks. - * - * @exception OAuthException2 thrown when sanity checks failed - */ - function checks () - { - if (isset($this->param['oauth_version'])) - { - $version = $this->urldecode($this->param['oauth_version']); - if ($version != '1.0') - { - throw new OAuthException2('Expected OAuth version 1.0, got "'.$this->param['oauth_version'].'"'); - } - } - } - - - /** - * Return the request method - * - * @return string - */ - function getMethod () - { - return $this->method; - } - - /** - * Return the complete parameter string for the signature check. - * All parameters are correctly urlencoded and sorted on name and value - * - * @return string - */ - function getNormalizedParams () - { - /* - // sort by name, then by value - // (needed when we start allowing multiple values with the same name) - $keys = array_keys($this->param); - $values = array_values($this->param); - array_multisort($keys, SORT_ASC, $values, SORT_ASC); - */ - $params = $this->param; - $normalized = array(); - - ksort($params); - foreach ($params as $key => $value) - { - // all names and values are already urlencoded, exclude the oauth signature - if ($key != 'oauth_signature') - { - if (is_array($value)) - { - $value_sort = $value; - sort($value_sort); - foreach ($value_sort as $v) - { - $normalized[] = $key.'='.$v; - } - } - else - { - $normalized[] = $key.'='.$value; - } - } - } - return implode('&', $normalized); - } - - - /** - * Return the normalised url for signature checks - */ - function getRequestUrl () - { - $url = $this->uri_parts['scheme'] . '://' - . $this->uri_parts['user'] . (!empty($this->uri_parts['pass']) ? ':' : '') - . $this->uri_parts['pass'] . (!empty($this->uri_parts['user']) ? '@' : '') - . $this->uri_parts['host']; - - if ( $this->uri_parts['port'] - && $this->uri_parts['port'] != $this->defaultPortForScheme($this->uri_parts['scheme'])) - { - $url .= ':'.$this->uri_parts['port']; - } - if (!empty($this->uri_parts['path'])) - { - $url .= $this->uri_parts['path']; - } - return $url; - } - - - /** - * Get a parameter, value is always urlencoded - * - * @param string name - * @param boolean urldecode set to true to decode the value upon return - * @return string value false when not found - */ - function getParam ( $name, $urldecode = false ) - { - if (isset($this->param[$name])) - { - $s = $this->param[$name]; - } - else if (isset($this->param[$this->urlencode($name)])) - { - $s = $this->param[$this->urlencode($name)]; - } - else - { - $s = false; - } - if (!empty($s) && $urldecode) - { - if (is_array($s)) - { - $s = array_map(array($this,'urldecode'), $s); - } - else - { - $s = $this->urldecode($s); - } - } - return $s; - } - - /** - * Set a parameter - * - * @param string name - * @param string value - * @param boolean encoded set to true when the values are already encoded - */ - function setParam ( $name, $value, $encoded = false ) - { - if (!$encoded) - { - $name_encoded = $this->urlencode($name); - if (is_array($value)) - { - foreach ($value as $v) - { - $this->param[$name_encoded][] = $this->urlencode($v); - } - } - else - { - $this->param[$name_encoded] = $this->urlencode($value); - } - } - else - { - $this->param[$name] = $value; - } - } - - - /** - * Re-encode all parameters so that they are encoded using RFC3986. - * Updates the $this->param attribute. - */ - protected function transcodeParams () - { - $params = $this->param; - $this->param = array(); - - foreach ($params as $name=>$value) - { - if (is_array($value)) - { - $this->param[$this->urltranscode($name)] = array_map(array($this,'urltranscode'), $value); - } - else - { - $this->param[$this->urltranscode($name)] = $this->urltranscode($value); - } - } - } - - - - /** - * Return the body of the OAuth request. - * - * @return string null when no body - */ - function getBody () - { - return $this->body; - } - - - /** - * Return the body of the OAuth request. - * - * @return string null when no body - */ - function setBody ( $body ) - { - $this->body = $body; - } - - - /** - * Parse the uri into its parts. Fill in the missing parts. - * - * @param string $parameters optional extra parameters (from eg the http post) - */ - protected function parseUri ( $parameters ) - { - $ps = @parse_url($this->uri); - - // Get the current/requested method - $ps['scheme'] = strtolower($ps['scheme']); - - // Get the current/requested host - if (function_exists('mb_strtolower')) - $ps['host'] = mb_strtolower($ps['host']); - else - $ps['host'] = strtolower($ps['host']); - - if (!preg_match('/^[a-z0-9\.\-]+$/', $ps['host'])) - { - throw new OAuthException2('Unsupported characters in host name'); - } - - // Get the port we are talking on - if (empty($ps['port'])) - { - $ps['port'] = $this->defaultPortForScheme($ps['scheme']); - } - - if (empty($ps['user'])) - { - $ps['user'] = ''; - } - if (empty($ps['pass'])) - { - $ps['pass'] = ''; - } - if (empty($ps['path'])) - { - $ps['path'] = '/'; - } - if (empty($ps['query'])) - { - $ps['query'] = ''; - } - if (empty($ps['fragment'])) - { - $ps['fragment'] = ''; - } - - // Now all is complete - parse all parameters - foreach (array($ps['query'], $parameters) as $params) - { - if (strlen($params) > 0) - { - $params = explode('&', $params); - foreach ($params as $p) - { - @list($name, $value) = explode('=', $p, 2); - if (!strlen($name)) - { - continue; - } - - if (array_key_exists($name, $this->param)) - { - if (is_array($this->param[$name])) - $this->param[$name][] = $value; - else - $this->param[$name] = array($this->param[$name], $value); - } - else - { - $this->param[$name] = $value; - } - } - } - } - $this->uri_parts = $ps; - } - - - /** - * Return the default port for a scheme - * - * @param string scheme - * @return int - */ - protected function defaultPortForScheme ( $scheme ) - { - switch ($scheme) - { - case 'http': return 80; - case 'https': return 443; - default: - throw new OAuthException2('Unsupported scheme type, expected http or https, got "'.$scheme.'"'); - break; - } - } - - - /** - * Encode a string according to the RFC3986 - * - * @param string s - * @return string - */ - function urlencode ( $s ) - { - if ($s === false) - { - return $s; - } - else - { - return str_replace('%7E', '~', rawurlencode($s)); - } - } - - /** - * Decode a string according to RFC3986. - * Also correctly decodes RFC1738 urls. - * - * @param string s - * @return string - */ - function urldecode ( $s ) - { - if ($s === false) - { - return $s; - } - else - { - return rawurldecode($s); - } - } - - /** - * urltranscode - make sure that a value is encoded using RFC3986. - * We use a basic urldecode() function so that any use of '+' as the - * encoding of the space character is correctly handled. - * - * @param string s - * @return string - */ - function urltranscode ( $s ) - { - if ($s === false) - { - return $s; - } - else - { - return $this->urlencode(rawurldecode($s)); - // return $this->urlencode(urldecode($s)); - } - } - - - /** - * Parse the oauth parameters from the request headers - * Looks for something like: - * - * Authorization: OAuth realm="http://photos.example.net/authorize", - * oauth_consumer_key="dpf43f3p2l4k3l03", - * oauth_token="nnch734d00sl2jdk", - * oauth_signature_method="HMAC-SHA1", - * oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D", - * oauth_timestamp="1191242096", - * oauth_nonce="kllo9940pd9333jh", - * oauth_version="1.0" - */ - private function parseHeaders () - { -/* - $this->headers['Authorization'] = 'OAuth realm="http://photos.example.net/authorize", - oauth_consumer_key="dpf43f3p2l4k3l03", - oauth_token="nnch734d00sl2jdk", - oauth_signature_method="HMAC-SHA1", - oauth_signature="tR3%2BTy81lMeYAr%2FFid0kMTYa%2FWM%3D", - oauth_timestamp="1191242096", - oauth_nonce="kllo9940pd9333jh", - oauth_version="1.0"'; -*/ - if (isset($this->headers['Authorization'])) - { - $auth = trim($this->headers['Authorization']); - if (strncasecmp($auth, 'OAuth', 4) == 0) - { - $vs = explode(',', substr($auth, 6)); - foreach ($vs as $v) - { - if (strpos($v, '=')) - { - $v = trim($v); - list($name,$value) = explode('=', $v, 2); - if (!empty($value) && $value{0} == '"' && substr($value, -1) == '"') - { - $value = substr(substr($value, 1), 0, -1); - } - - if (strcasecmp($name, 'realm') == 0) - { - $this->realm = $value; - } - else - { - $this->param[$name] = $value; - } - } - } - } - } - } - - - /** - * Fetch the content type of the current request - * - * @return string - */ - private function getRequestContentType () - { - $content_type = 'application/octet-stream'; - if (!empty($_SERVER) && array_key_exists('CONTENT_TYPE', $_SERVER)) - { - list($content_type) = explode(';', $_SERVER['CONTENT_TYPE']); - } - return trim($content_type); - } - - - /** - * Get the body of a POST or PUT. - * - * Used for fetching the post parameters and to calculate the body signature. - * - * @return string null when no body present (or wrong content type for body) - */ - private function getRequestBody () - { - $body = null; - if ($this->method == 'POST' || $this->method == 'PUT') - { - $body = ''; - $fh = @fopen('php://input', 'r'); - if ($fh) - { - while (!feof($fh)) - { - $s = fread($fh, 1024); - if (is_string($s)) - { - $body .= $s; - } - } - fclose($fh); - } - } - return $body; - } - - /** - * Get the body of a POST with multipart/form-data by Edison tsai on 16:52 2010/09/16 - * - * Used for fetching the post parameters and to calculate the body signature. - * - * @return string null when no body present (or wrong content type for body) - */ - private function getRequestBodyOfMultipart() - { - $body = null; - if ($this->method == 'POST') - { - $body = ''; - if (is_array($_POST) && count($_POST) > 1) - { - foreach ($_POST AS $k => $v) { - $body .= $k . '=' . $this->urlencode($v) . '&'; - } #end foreach - if(substr($body,-1) == '&') - { - $body = substr($body, 0, strlen($body)-1); - } #end if - } #end if - } #end if - - return $body; - } - - - /** - * Simple function to perform a redirect (GET). - * Redirects the User-Agent, does not return. - * - * @param string uri - * @param array params parameters, urlencoded - * @exception OAuthException2 when redirect uri is illegal - */ - public function redirect ( $uri, $params ) - { - if (!empty($params)) - { - $q = array(); - foreach ($params as $name=>$value) - { - $q[] = $name.'='.$value; - } - $q_s = implode('&', $q); - - if (strpos($uri, '?')) - { - $uri .= '&'.$q_s; - } - else - { - $uri .= '?'.$q_s; - } - } - - // simple security - multiline location headers can inject all kinds of extras - $uri = preg_replace('/\s/', '%20', $uri); - if (strncasecmp($uri, 'http://', 7) && strncasecmp($uri, 'https://', 8)) - { - if (strpos($uri, '://')) - { - throw new OAuthException2('Illegal protocol in redirect uri '.$uri); - } - $uri = 'http://'.$uri; - } - - header('HTTP/1.1 302 Found'); - header('Location: '.$uri); - echo ''; - exit(); - } -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthRequestLogger.php b/3rdparty/oauth-php/library/OAuthRequestLogger.php deleted file mode 100644 index 7307600041..0000000000 --- a/3rdparty/oauth-php/library/OAuthRequestLogger.php +++ /dev/null @@ -1,316 +0,0 @@ - - * @date Dec 7, 2007 12:22:43 PM - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -class OAuthRequestLogger -{ - static private $logging = 0; - static private $enable_logging = null; - static private $store_log = null; - static private $note = ''; - static private $user_id = null; - static private $request_object = null; - static private $sent = null; - static private $received = null; - static private $log = array(); - - /** - * Start any logging, checks the system configuration if logging is needed. - * - * @param OAuthRequest $request_object - */ - static function start ( $request_object = null ) - { - if (defined('OAUTH_LOG_REQUEST')) - { - if (is_null(OAuthRequestLogger::$enable_logging)) - { - OAuthRequestLogger::$enable_logging = true; - } - if (is_null(OAuthRequestLogger::$store_log)) - { - OAuthRequestLogger::$store_log = true; - } - } - - if (OAuthRequestLogger::$enable_logging && !OAuthRequestLogger::$logging) - { - OAuthRequestLogger::$logging = true; - OAuthRequestLogger::$request_object = $request_object; - ob_start(); - - // Make sure we flush our log entry when we stop the request (eg on an exception) - register_shutdown_function(array('OAuthRequestLogger','flush')); - } - } - - - /** - * Force logging, needed for performing test connects independent from the debugging setting. - * - * @param boolean store_log (optional) true to store the log in the db - */ - static function enableLogging ( $store_log = null ) - { - OAuthRequestLogger::$enable_logging = true; - if (!is_null($store_log)) - { - OAuthRequestLogger::$store_log = $store_log; - } - } - - - /** - * Logs the request to the database, sends any cached output. - * Also called on shutdown, to make sure we always log the request being handled. - */ - static function flush () - { - if (OAuthRequestLogger::$logging) - { - OAuthRequestLogger::$logging = false; - - if (is_null(OAuthRequestLogger::$sent)) - { - // What has been sent to the user-agent? - $data = ob_get_contents(); - if (strlen($data) > 0) - { - ob_end_flush(); - } - elseif (ob_get_level()) - { - ob_end_clean(); - } - $hs = headers_list(); - $sent = implode("\n", $hs) . "\n\n" . $data; - } - else - { - // The request we sent - $sent = OAuthRequestLogger::$sent; - } - - if (is_null(OAuthRequestLogger::$received)) - { - // Build the request we received - $hs0 = self::getAllHeaders(); - $hs = array(); - foreach ($hs0 as $h => $v) - { - $hs[] = "$h: $v"; - } - - $data = ''; - $fh = @fopen('php://input', 'r'); - if ($fh) - { - while (!feof($fh)) - { - $s = fread($fh, 1024); - if (is_string($s)) - { - $data .= $s; - } - } - fclose($fh); - } - $received = implode("\n", $hs) . "\n\n" . $data; - } - else - { - // The answer we received - $received = OAuthRequestLogger::$received; - } - - // The request base string - if (OAuthRequestLogger::$request_object) - { - $base_string = OAuthRequestLogger::$request_object->signatureBaseString(); - } - else - { - $base_string = ''; - } - - // Figure out to what keys we want to log this request - $keys = array(); - if (OAuthRequestLogger::$request_object) - { - $consumer_key = OAuthRequestLogger::$request_object->getParam('oauth_consumer_key', true); - $token = OAuthRequestLogger::$request_object->getParam('oauth_token', true); - - switch (get_class(OAuthRequestLogger::$request_object)) - { - // tokens are access/request tokens by a consumer - case 'OAuthServer': - case 'OAuthRequestVerifier': - $keys['ocr_consumer_key'] = $consumer_key; - $keys['oct_token'] = $token; - break; - - // tokens are access/request tokens to a server - case 'OAuthRequester': - case 'OAuthRequestSigner': - $keys['osr_consumer_key'] = $consumer_key; - $keys['ost_token'] = $token; - break; - } - } - - // Log the request - if (OAuthRequestLogger::$store_log) - { - $store = OAuthStore::instance(); - $store->addLog($keys, $received, $sent, $base_string, OAuthRequestLogger::$note, OAuthRequestLogger::$user_id); - } - - OAuthRequestLogger::$log[] = array( - 'keys' => $keys, - 'received' => $received, - 'sent' => $sent, - 'base_string' => $base_string, - 'note' => OAuthRequestLogger::$note - ); - } - } - - - /** - * Add a note, used by the OAuthException2 to log all exceptions. - * - * @param string note - */ - static function addNote ( $note ) - { - OAuthRequestLogger::$note .= $note . "\n\n"; - } - - /** - * Set the OAuth request object being used - * - * @param OAuthRequest request_object - */ - static function setRequestObject ( $request_object ) - { - OAuthRequestLogger::$request_object = $request_object; - } - - - /** - * Set the relevant user (defaults to the current user) - * - * @param int user_id - */ - static function setUser ( $user_id ) - { - OAuthRequestLogger::$user_id = $user_id; - } - - - /** - * Set the request we sent - * - * @param string request - */ - static function setSent ( $request ) - { - OAuthRequestLogger::$sent = $request; - } - - /** - * Set the reply we received - * - * @param string request - */ - static function setReceived ( $reply ) - { - OAuthRequestLogger::$received = $reply; - } - - - /** - * Get the the log till now - * - * @return array - */ - static function getLog () - { - return OAuthRequestLogger::$log; - } - - - /** - * helper to try to sort out headers for people who aren't running apache, - * or people who are running PHP as FastCGI. - * - * @return array of request headers as associative array. - */ - public static function getAllHeaders() { - $retarr = array(); - $headers = array(); - - if (function_exists('apache_request_headers')) { - $headers = apache_request_headers(); - ksort($headers); - return $headers; - } else { - $headers = array_merge($_ENV, $_SERVER); - - foreach ($headers as $key => $val) { - //we need this header - if (strpos(strtolower($key), 'content-type') !== FALSE) - continue; - if (strtoupper(substr($key, 0, 5)) != "HTTP_") - unset($headers[$key]); - } - } - - //Normalize this array to Cased-Like-This structure. - foreach ($headers AS $key => $value) { - $key = preg_replace('/^HTTP_/i', '', $key); - $key = str_replace( - " ", - "-", - ucwords(strtolower(str_replace(array("-", "_"), " ", $key))) - ); - $retarr[$key] = $value; - } - ksort($retarr); - - return $retarr; - } -} - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthRequestSigner.php b/3rdparty/oauth-php/library/OAuthRequestSigner.php deleted file mode 100644 index 15c0fd88cc..0000000000 --- a/3rdparty/oauth-php/library/OAuthRequestSigner.php +++ /dev/null @@ -1,215 +0,0 @@ - - * @date Nov 16, 2007 4:02:49 PM - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -require_once dirname(__FILE__) . '/OAuthStore.php'; -require_once dirname(__FILE__) . '/OAuthRequest.php'; - - -class OAuthRequestSigner extends OAuthRequest -{ - protected $request; - protected $store; - protected $usr_id = 0; - private $signed = false; - - - /** - * Construct the request to be signed. Parses or appends the parameters in the params url. - * When you supply an params array, then the params should not be urlencoded. - * When you supply a string, then it is assumed it is of the type application/x-www-form-urlencoded - * - * @param string request url - * @param string method PUT, GET, POST etc. - * @param mixed params string (for urlencoded data, or array with name/value pairs) - * @param string body optional body for PUT and/or POST requests - */ - function __construct ( $request, $method = null, $params = null, $body = null ) - { - $this->store = OAuthStore::instance(); - - if (is_string($params)) - { - parent::__construct($request, $method, $params); - } - else - { - parent::__construct($request, $method); - if (is_array($params)) - { - foreach ($params as $name => $value) - { - $this->setParam($name, $value); - } - } - } - - // With put/ post we might have a body (not for application/x-www-form-urlencoded requests) - if (strcasecmp($method, 'PUT') == 0 || strcasecmp($method, 'POST') == 0) - { - $this->setBody($body); - } - } - - - /** - * Reset the 'signed' flag, so that any changes in the parameters force a recalculation - * of the signature. - */ - function setUnsigned () - { - $this->signed = false; - } - - - /** - * Sign our message in the way the server understands. - * Set the needed oauth_xxxx parameters. - * - * @param int usr_id (optional) user that wants to sign this request - * @param array secrets secrets used for signing, when empty then secrets will be fetched from the token registry - * @param string name name of the token to be used for signing - * @exception OAuthException2 when there is no oauth relation with the server - * @exception OAuthException2 when we don't support the signing methods of the server - */ - function sign ( $usr_id = 0, $secrets = null, $name = '', $token_type = null) - { - $url = $this->getRequestUrl(); - if (empty($secrets)) - { - // get the access tokens for the site (on an user by user basis) - $secrets = $this->store->getSecretsForSignature($url, $usr_id, $name); - } - if (empty($secrets)) - { - throw new OAuthException2('No OAuth relation with the server for at "'.$url.'"'); - } - - $signature_method = $this->selectSignatureMethod($secrets['signature_methods']); - - $token = isset($secrets['token']) ? $secrets['token'] : ''; - $token_secret = isset($secrets['token_secret']) ? $secrets['token_secret'] : ''; - - if (!$token) { - $token = $this->getParam('oauth_token'); - } - - $this->setParam('oauth_signature_method',$signature_method); - $this->setParam('oauth_signature', ''); - $this->setParam('oauth_nonce', !empty($secrets['nonce']) ? $secrets['nonce'] : uniqid('')); - $this->setParam('oauth_timestamp', !empty($secrets['timestamp']) ? $secrets['timestamp'] : time()); - if ($token_type != 'requestToken') - $this->setParam('oauth_token', $token); - $this->setParam('oauth_consumer_key', $secrets['consumer_key']); - $this->setParam('oauth_version', '1.0'); - - $body = $this->getBody(); - if (!is_null($body)) - { - // We also need to sign the body, use the default signature method - $body_signature = $this->calculateDataSignature($body, $secrets['consumer_secret'], $token_secret, $signature_method); - $this->setParam('xoauth_body_signature', $body_signature, true); - } - - $signature = $this->calculateSignature($secrets['consumer_secret'], $token_secret, $token_type); - $this->setParam('oauth_signature', $signature, true); - // $this->setParam('oauth_signature', urldecode($signature), true); - - $this->signed = true; - $this->usr_id = $usr_id; - } - - - /** - * Builds the Authorization header for the request. - * Adds all oauth_ and xoauth_ parameters to the Authorization header. - * - * @return string - */ - function getAuthorizationHeader () - { - if (!$this->signed) - { - $this->sign($this->usr_id); - } - $h = array(); - $h[] = 'Authorization: OAuth realm=""'; - foreach ($this->param as $name => $value) - { - if (strncmp($name, 'oauth_', 6) == 0 || strncmp($name, 'xoauth_', 7) == 0) - { - $h[] = $name.'="'.$value.'"'; - } - } - $hs = implode(', ', $h); - return $hs; - } - - - /** - * Builds the application/x-www-form-urlencoded parameter string. Can be appended as - * the query part to a GET or inside the request body for a POST. - * - * @param boolean oauth_as_header (optional) set to false to include oauth parameters - * @return string - */ - function getQueryString ( $oauth_as_header = true ) - { - $parms = array(); - foreach ($this->param as $name => $value) - { - if ( !$oauth_as_header - || (strncmp($name, 'oauth_', 6) != 0 && strncmp($name, 'xoauth_', 7) != 0)) - { - if (is_array($value)) - { - foreach ($value as $v) - { - $parms[] = $name.'='.$v; - } - } - else - { - $parms[] = $name.'='.$value; - } - } - } - return implode('&', $parms); - } - -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthRequestVerifier.php b/3rdparty/oauth-php/library/OAuthRequestVerifier.php deleted file mode 100644 index a5def757c6..0000000000 --- a/3rdparty/oauth-php/library/OAuthRequestVerifier.php +++ /dev/null @@ -1,306 +0,0 @@ - - * @date Nov 16, 2007 4:35:03 PM - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__) . '/OAuthStore.php'; -require_once dirname(__FILE__) . '/OAuthRequest.php'; - - -class OAuthRequestVerifier extends OAuthRequest -{ - private $request; - private $store; - private $accepted_signatures = null; - - /** - * Construct the request to be verified - * - * @param string request - * @param string method - * @param array params The request parameters - */ - function __construct ( $uri = null, $method = null, $params = null ) - { - if ($params) { - $encodedParams = array(); - foreach ($params as $key => $value) { - if (preg_match("/^oauth_/", $key)) { - continue; - } - $encodedParams[rawurlencode($key)] = rawurlencode($value); - } - $this->param = array_merge($this->param, $encodedParams); - } - - $this->store = OAuthStore::instance(); - parent::__construct($uri, $method); - - OAuthRequestLogger::start($this); - } - - - /** - * See if the current request is signed with OAuth - * - * @return boolean - */ - static public function requestIsSigned () - { - if (isset($_REQUEST['oauth_signature'])) - { - $signed = true; - } - else - { - $hs = OAuthRequestLogger::getAllHeaders(); - if (isset($hs['Authorization']) && strpos($hs['Authorization'], 'oauth_signature') !== false) - { - $signed = true; - } - else - { - $signed = false; - } - } - return $signed; - } - - - /** - * Verify the request if it seemed to be signed. - * - * @param string token_type the kind of token needed, defaults to 'access' - * @exception OAuthException2 thrown when the request did not verify - * @return boolean true when signed, false when not signed - */ - public function verifyIfSigned ( $token_type = 'access' ) - { - if ($this->getParam('oauth_consumer_key')) - { - OAuthRequestLogger::start($this); - $this->verify($token_type); - $signed = true; - OAuthRequestLogger::flush(); - } - else - { - $signed = false; - } - return $signed; - } - - - - /** - * Verify the request - * - * @param string token_type the kind of token needed, defaults to 'access' (false, 'access', 'request') - * @exception OAuthException2 thrown when the request did not verify - * @return int user_id associated with token (false when no user associated) - */ - public function verify ( $token_type = 'access' ) - { - $retval = $this->verifyExtended($token_type); - return $retval['user_id']; - } - - - /** - * Verify the request - * - * @param string token_type the kind of token needed, defaults to 'access' (false, 'access', 'request') - * @exception OAuthException2 thrown when the request did not verify - * @return array ('user_id' => associated with token (false when no user associated), - * 'consumer_key' => the associated consumer_key) - * - */ - public function verifyExtended ( $token_type = 'access' ) - { - $consumer_key = $this->getParam('oauth_consumer_key'); - $token = $this->getParam('oauth_token'); - $user_id = false; - $secrets = array(); - - if ($consumer_key && ($token_type === false || $token)) - { - $secrets = $this->store->getSecretsForVerify( $this->urldecode($consumer_key), - $this->urldecode($token), - $token_type); - - $this->store->checkServerNonce( $this->urldecode($consumer_key), - $this->urldecode($token), - $this->getParam('oauth_timestamp', true), - $this->getParam('oauth_nonce', true)); - - $oauth_sig = $this->getParam('oauth_signature'); - if (empty($oauth_sig)) - { - throw new OAuthException2('Verification of signature failed (no oauth_signature in request).'); - } - - try - { - $this->verifySignature($secrets['consumer_secret'], $secrets['token_secret'], $token_type); - } - catch (OAuthException2 $e) - { - throw new OAuthException2('Verification of signature failed (signature base string was "'.$this->signatureBaseString().'").' - . " with " . print_r(array($secrets['consumer_secret'], $secrets['token_secret'], $token_type), true)); - } - - // Check the optional body signature - if ($this->getParam('xoauth_body_signature')) - { - $method = $this->getParam('xoauth_body_signature_method'); - if (empty($method)) - { - $method = $this->getParam('oauth_signature_method'); - } - - try - { - $this->verifyDataSignature($this->getBody(), $secrets['consumer_secret'], $secrets['token_secret'], $method, $this->getParam('xoauth_body_signature')); - } - catch (OAuthException2 $e) - { - throw new OAuthException2('Verification of body signature failed.'); - } - } - - // All ok - fetch the user associated with this request - if (isset($secrets['user_id'])) - { - $user_id = $secrets['user_id']; - } - - // Check if the consumer wants us to reset the ttl of this token - $ttl = $this->getParam('xoauth_token_ttl', true); - if (is_numeric($ttl)) - { - $this->store->setConsumerAccessTokenTtl($this->urldecode($token), $ttl); - } - } - else - { - throw new OAuthException2('Can\'t verify request, missing oauth_consumer_key or oauth_token'); - } - return array('user_id' => $user_id, 'consumer_key' => $consumer_key, 'osr_id' => $secrets['osr_id']); - } - - - - /** - * Verify the signature of the request, using the method in oauth_signature_method. - * The signature is returned encoded in the form as used in the url. So the base64 and - * urlencoding has been done. - * - * @param string consumer_secret - * @param string token_secret - * @exception OAuthException2 thrown when the signature method is unknown - * @exception OAuthException2 when not all parts available - * @exception OAuthException2 when signature does not match - */ - public function verifySignature ( $consumer_secret, $token_secret, $token_type = 'access' ) - { - $required = array( - 'oauth_consumer_key', - 'oauth_signature_method', - 'oauth_timestamp', - 'oauth_nonce', - 'oauth_signature' - ); - - if ($token_type !== false) - { - $required[] = 'oauth_token'; - } - - foreach ($required as $req) - { - if (!isset($this->param[$req])) - { - throw new OAuthException2('Can\'t verify request signature, missing parameter "'.$req.'"'); - } - } - - $this->checks(); - - $base = $this->signatureBaseString(); - $this->verifyDataSignature($base, $consumer_secret, $token_secret, $this->param['oauth_signature_method'], $this->param['oauth_signature']); - } - - - - /** - * Verify the signature of a string. - * - * @param string data - * @param string consumer_secret - * @param string token_secret - * @param string signature_method - * @param string signature - * @exception OAuthException2 thrown when the signature method is unknown - * @exception OAuthException2 when signature does not match - */ - public function verifyDataSignature ( $data, $consumer_secret, $token_secret, $signature_method, $signature ) - { - if (is_null($data)) - { - $data = ''; - } - - $sig = $this->getSignatureMethod($signature_method); - if (!$sig->verify($this, $data, $consumer_secret, $token_secret, $signature)) - { - throw new OAuthException2('Signature verification failed ('.$signature_method.')'); - } - } - - /** - * - * @param array $accepted The array of accepted signature methods, or if null is passed - * all supported methods are accepted and there is no filtering. - * - */ - public function setAcceptedSignatureMethods($accepted = null) { - if (is_array($accepted)) - $this->accepted_signatures = $accepted; - else if ($accepted == null) - $this->accepted_signatures = null; - } -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthRequester.php b/3rdparty/oauth-php/library/OAuthRequester.php deleted file mode 100644 index 98f720d220..0000000000 --- a/3rdparty/oauth-php/library/OAuthRequester.php +++ /dev/null @@ -1,521 +0,0 @@ - - * @date Nov 20, 2007 1:41:38 PM - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__) . '/OAuthRequestSigner.php'; -require_once dirname(__FILE__) . '/body/OAuthBodyContentDisposition.php'; - - -class OAuthRequester extends OAuthRequestSigner -{ - protected $files; - - /** - * Construct a new request signer. Perform the request with the doRequest() method below. - * - * A request can have either one file or a body, not both. - * - * The files array consists of arrays: - * - file the filename/path containing the data for the POST/PUT - * - data data for the file, omit when you have a file - * - mime content-type of the file - * - filename filename for content disposition header - * - * When OAuth (and PHP) can support multipart/form-data then we can handle more than one file. - * For now max one file, with all the params encoded in the query string. - * - * @param string request - * @param string method http method. GET, PUT, POST etc. - * @param array params name=>value array with request parameters - * @param string body optional body to send - * @param array files optional files to send (max 1 till OAuth support multipart/form-data posts) - */ - function __construct ( $request, $method = null, $params = null, $body = null, $files = null ) - { - parent::__construct($request, $method, $params, $body); - - // When there are files, then we can construct a POST with a single file - if (!empty($files)) - { - $empty = true; - foreach ($files as $f) - { - $empty = $empty && empty($f['file']) && !isset($f['data']); - } - - if (!$empty) - { - if (!is_null($body)) - { - throw new OAuthException2('When sending files, you can\'t send a body as well.'); - } - $this->files = $files; - } - } - } - - - /** - * Perform the request, returns the response code, headers and body. - * - * @param int usr_id optional user id for which we make the request - * @param array curl_options optional extra options for curl request - * @param array options options like name and token_ttl - * @exception OAuthException2 when authentication not accepted - * @exception OAuthException2 when signing was not possible - * @return array (code=>int, headers=>array(), body=>string) - */ - function doRequest ( $usr_id = 0, $curl_options = array(), $options = array() ) - { - $name = isset($options['name']) ? $options['name'] : ''; - if (isset($options['token_ttl'])) - { - $this->setParam('xoauth_token_ttl', intval($options['token_ttl'])); - } - - if (!empty($this->files)) - { - // At the moment OAuth does not support multipart/form-data, so try to encode - // the supplied file (or data) as the request body and add a content-disposition header. - list($extra_headers, $body) = OAuthBodyContentDisposition::encodeBody($this->files); - $this->setBody($body); - $curl_options = $this->prepareCurlOptions($curl_options, $extra_headers); - } - $this->sign($usr_id, null, $name); - $text = $this->curl_raw($curl_options); - $result = $this->curl_parse($text); - if ($result['code'] >= 400) - { - throw new OAuthException2('Request failed with code ' . $result['code'] . ': ' . $result['body']); - } - - // Record the token time to live for this server access token, immediate delete iff ttl <= 0 - // Only done on a succesful request. - $token_ttl = $this->getParam('xoauth_token_ttl', false); - if (is_numeric($token_ttl)) - { - $this->store->setServerTokenTtl($this->getParam('oauth_consumer_key',true), $this->getParam('oauth_token',true), $token_ttl); - } - - return $result; - } - - - /** - * Request a request token from the site belonging to consumer_key - * - * @param string consumer_key - * @param int usr_id - * @param array params (optional) extra arguments for when requesting the request token - * @param string method (optional) change the method of the request, defaults to POST (as it should be) - * @param array options (optional) options like name and token_ttl - * @param array curl_options optional extra options for curl request - * @exception OAuthException2 when no key could be fetched - * @exception OAuthException2 when no server with consumer_key registered - * @return array (authorize_uri, token) - */ - static function requestRequestToken ( $consumer_key, $usr_id, $params = null, $method = 'POST', $options = array(), $curl_options = array()) - { - OAuthRequestLogger::start(); - - if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) - { - $params['xoauth_token_ttl'] = intval($options['token_ttl']); - } - - $store = OAuthStore::instance(); - $r = $store->getServer($consumer_key, $usr_id); - $uri = $r['request_token_uri']; - - $oauth = new OAuthRequester($uri, $method, $params); - $oauth->sign($usr_id, $r, '', 'requestToken'); - $text = $oauth->curl_raw($curl_options); - - if (empty($text)) - { - throw new OAuthException2('No answer from the server "'.$uri.'" while requesting a request token'); - } - $data = $oauth->curl_parse($text); - if ($data['code'] != 200) - { - throw new OAuthException2('Unexpected result from the server "'.$uri.'" ('.$data['code'].') while requesting a request token'); - } - $token = array(); - $params = explode('&', $data['body']); - foreach ($params as $p) - { - @list($name, $value) = explode('=', $p, 2); - $token[$name] = $oauth->urldecode($value); - } - - if (!empty($token['oauth_token']) && !empty($token['oauth_token_secret'])) - { - $opts = array(); - if (isset($options['name'])) - { - $opts['name'] = $options['name']; - } - if (isset($token['xoauth_token_ttl'])) - { - $opts['token_ttl'] = $token['xoauth_token_ttl']; - } - $store->addServerToken($consumer_key, 'request', $token['oauth_token'], $token['oauth_token_secret'], $usr_id, $opts); - } - else - { - throw new OAuthException2('The server "'.$uri.'" did not return the oauth_token or the oauth_token_secret'); - } - - OAuthRequestLogger::flush(); - - // Now we can direct a browser to the authorize_uri - return array( - 'authorize_uri' => $r['authorize_uri'], - 'token' => $token['oauth_token'] - ); - } - - - /** - * Request an access token from the site belonging to consumer_key. - * Before this we got an request token, now we want to exchange it for - * an access token. - * - * @param string consumer_key - * @param string token - * @param int usr_id user requesting the access token - * @param string method (optional) change the method of the request, defaults to POST (as it should be) - * @param array options (optional) extra options for request, eg token_ttl - * @param array curl_options optional extra options for curl request - * - * @exception OAuthException2 when no key could be fetched - * @exception OAuthException2 when no server with consumer_key registered - */ - static function requestAccessToken ( $consumer_key, $token, $usr_id, $method = 'POST', $options = array(), $curl_options = array() ) - { - OAuthRequestLogger::start(); - - $store = OAuthStore::instance(); - $r = $store->getServerTokenSecrets($consumer_key, $token, 'request', $usr_id); - $uri = $r['access_token_uri']; - $token_name = $r['token_name']; - - // Delete the server request token, this one was for one use only - $store->deleteServerToken($consumer_key, $r['token'], 0, true); - - // Try to exchange our request token for an access token - $oauth = new OAuthRequester($uri, $method); - - if (isset($options['oauth_verifier'])) - { - $oauth->setParam('oauth_verifier', $options['oauth_verifier']); - } - if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) - { - $oauth->setParam('xoauth_token_ttl', intval($options['token_ttl'])); - } - - OAuthRequestLogger::setRequestObject($oauth); - - $oauth->sign($usr_id, $r, '', 'accessToken'); - $text = $oauth->curl_raw($curl_options); - if (empty($text)) - { - throw new OAuthException2('No answer from the server "'.$uri.'" while requesting an access token'); - } - $data = $oauth->curl_parse($text); - - if ($data['code'] != 200) - { - throw new OAuthException2('Unexpected result from the server "'.$uri.'" ('.$data['code'].') while requesting an access token'); - } - - $token = array(); - $params = explode('&', $data['body']); - foreach ($params as $p) - { - @list($name, $value) = explode('=', $p, 2); - $token[$oauth->urldecode($name)] = $oauth->urldecode($value); - } - - if (!empty($token['oauth_token']) && !empty($token['oauth_token_secret'])) - { - $opts = array(); - $opts['name'] = $token_name; - if (isset($token['xoauth_token_ttl'])) - { - $opts['token_ttl'] = $token['xoauth_token_ttl']; - } - $store->addServerToken($consumer_key, 'access', $token['oauth_token'], $token['oauth_token_secret'], $usr_id, $opts); - } - else - { - throw new OAuthException2('The server "'.$uri.'" did not return the oauth_token or the oauth_token_secret'); - } - - OAuthRequestLogger::flush(); - } - - - - /** - * Open and close a curl session passing all the options to the curl libs - * - * @param array opts the curl options. - * @exception OAuthException2 when temporary file for PUT operation could not be created - * @return string the result of the curl action - */ - protected function curl_raw ( $opts = array() ) - { - if (isset($opts[CURLOPT_HTTPHEADER])) - { - $header = $opts[CURLOPT_HTTPHEADER]; - } - else - { - $header = array(); - } - - $ch = curl_init(); - $method = $this->getMethod(); - $url = $this->getRequestUrl(); - $header[] = $this->getAuthorizationHeader(); - $query = $this->getQueryString(); - $body = $this->getBody(); - - $has_content_type = false; - foreach ($header as $h) - { - if (strncasecmp($h, 'Content-Type:', 13) == 0) - { - $has_content_type = true; - } - } - - if (!is_null($body)) - { - if ($method == 'TRACE') - { - throw new OAuthException2('A body can not be sent with a TRACE operation'); - } - - // PUT and POST allow a request body - if (!empty($query)) - { - $url .= '?'.$query; - } - - // Make sure that the content type of the request is ok - if (!$has_content_type) - { - $header[] = 'Content-Type: application/octet-stream'; - $has_content_type = true; - } - - // When PUTting, we need to use an intermediate file (because of the curl implementation) - if ($method == 'PUT') - { - /* - if (version_compare(phpversion(), '5.2.0') >= 0) - { - // Use the data wrapper to create the file expected by the put method - $put_file = fopen('data://application/octet-stream;base64,'.base64_encode($body)); - } - */ - - $put_file = @tmpfile(); - if (!$put_file) - { - throw new OAuthException2('Could not create tmpfile for PUT operation'); - } - fwrite($put_file, $body); - fseek($put_file, 0); - - curl_setopt($ch, CURLOPT_PUT, true); - curl_setopt($ch, CURLOPT_INFILE, $put_file); - curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body)); - } - else - { - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $body); - } - } - else - { - // a 'normal' request, no body to be send - if ($method == 'POST') - { - if (!$has_content_type) - { - $header[] = 'Content-Type: application/x-www-form-urlencoded'; - $has_content_type = true; - } - - curl_setopt($ch, CURLOPT_POST, true); - curl_setopt($ch, CURLOPT_POSTFIELDS, $query); - } - else - { - if (!empty($query)) - { - $url .= '?'.$query; - } - if ($method != 'GET') - { - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); - } - } - } - - curl_setopt($ch, CURLOPT_HTTPHEADER, $header); - curl_setopt($ch, CURLOPT_USERAGENT, 'anyMeta/OAuth 1.0 - ($LastChangedRevision: 174 $)'); - curl_setopt($ch, CURLOPT_URL, $url); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLOPT_HEADER, true); - curl_setopt($ch, CURLOPT_TIMEOUT, 30); - - foreach ($opts as $k => $v) - { - if ($k != CURLOPT_HTTPHEADER) - { - curl_setopt($ch, $k, $v); - } - } - - $txt = curl_exec($ch); - if ($txt === false) { - $error = curl_error($ch); - curl_close($ch); - throw new OAuthException2('CURL error: ' . $error); - } - curl_close($ch); - - if (!empty($put_file)) - { - fclose($put_file); - } - - // Tell the logger what we requested and what we received back - $data = $method . " $url\n".implode("\n",$header); - if (is_string($body)) - { - $data .= "\n\n".$body; - } - else if ($method == 'POST') - { - $data .= "\n\n".$query; - } - - OAuthRequestLogger::setSent($data, $body); - OAuthRequestLogger::setReceived($txt); - - return $txt; - } - - - /** - * Parse an http response - * - * @param string response the http text to parse - * @return array (code=>http-code, headers=>http-headers, body=>body) - */ - protected function curl_parse ( $response ) - { - if (empty($response)) - { - return array(); - } - - @list($headers,$body) = explode("\r\n\r\n",$response,2); - $lines = explode("\r\n",$headers); - - if (preg_match('@^HTTP/[0-9]\.[0-9] +100@', $lines[0])) - { - /* HTTP/1.x 100 Continue - * the real data is on the next line - */ - @list($headers,$body) = explode("\r\n\r\n",$body,2); - $lines = explode("\r\n",$headers); - } - - // first line of headers is the HTTP response code - $http_line = array_shift($lines); - if (preg_match('@^HTTP/[0-9]\.[0-9] +([0-9]{3})@', $http_line, $matches)) - { - $code = $matches[1]; - } - - // put the rest of the headers in an array - $headers = array(); - foreach ($lines as $l) - { - list($k, $v) = explode(': ', $l, 2); - $headers[strtolower($k)] = $v; - } - - return array( 'code' => $code, 'headers' => $headers, 'body' => $body); - } - - - /** - * Mix the given headers into the headers that were given to curl - * - * @param array curl_options - * @param array extra_headers - * @return array new curl options - */ - protected function prepareCurlOptions ( $curl_options, $extra_headers ) - { - $hs = array(); - if (!empty($curl_options[CURLOPT_HTTPHEADER]) && is_array($curl_options[CURLOPT_HTTPHEADER])) - { - foreach ($curl_options[CURLOPT_HTTPHEADER] as $h) - { - list($opt, $val) = explode(':', $h, 2); - $opt = str_replace(' ', '-', ucwords(str_replace('-', ' ', $opt))); - $hs[$opt] = $val; - } - } - - $curl_options[CURLOPT_HTTPHEADER] = array(); - $hs = array_merge($hs, $extra_headers); - foreach ($hs as $h => $v) - { - $curl_options[CURLOPT_HTTPHEADER][] = "$h: $v"; - } - return $curl_options; - } -} - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthServer.php b/3rdparty/oauth-php/library/OAuthServer.php deleted file mode 100644 index 995ebc5ca0..0000000000 --- a/3rdparty/oauth-php/library/OAuthServer.php +++ /dev/null @@ -1,333 +0,0 @@ - - * @date Nov 27, 2007 12:36:38 PM - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once 'OAuthRequestVerifier.php'; -require_once 'OAuthSession.php'; - -class OAuthServer extends OAuthRequestVerifier -{ - protected $session; - - protected $allowed_uri_schemes = array( - 'http', - 'https' - ); - - protected $disallowed_uri_schemes = array( - 'file', - 'callto', - 'mailto' - ); - - /** - * Construct the request to be verified - * - * @param string request - * @param string method - * @param array params The request parameters - * @param string store The session storage class. - * @param array store_options The session storage class parameters. - * @param array options Extra options: - * - allowed_uri_schemes: list of allowed uri schemes. - * - disallowed_uri_schemes: list of unallowed uri schemes. - * - * e.g. Allow only http and https - * $options = array( - * 'allowed_uri_schemes' => array('http', 'https'), - * 'disallowed_uri_schemes' => array() - * ); - * - * e.g. Disallow callto, mailto and file, allow everything else - * $options = array( - * 'allowed_uri_schemes' => array(), - * 'disallowed_uri_schemes' => array('callto', 'mailto', 'file') - * ); - * - * e.g. Allow everything - * $options = array( - * 'allowed_uri_schemes' => array(), - * 'disallowed_uri_schemes' => array() - * ); - * - */ - function __construct ( $uri = null, $method = null, $params = null, $store = 'SESSION', - $store_options = array(), $options = array() ) - { - parent::__construct($uri, $method, $params); - $this->session = OAuthSession::instance($store, $store_options); - - if (array_key_exists('allowed_uri_schemes', $options) && is_array($options['allowed_uri_schemes'])) { - $this->allowed_uri_schemes = $options['allowed_uri_schemes']; - } - if (array_key_exists('disallowed_uri_schemes', $options) && is_array($options['disallowed_uri_schemes'])) { - $this->disallowed_uri_schemes = $options['disallowed_uri_schemes']; - } - } - - /** - * Handle the request_token request. - * Returns the new request token and request token secret. - * - * TODO: add correct result code to exception - * - * @return string returned request token, false on an error - */ - public function requestToken () - { - OAuthRequestLogger::start($this); - try - { - $this->verify(false); - - $options = array(); - $ttl = $this->getParam('xoauth_token_ttl', false); - if ($ttl) - { - $options['token_ttl'] = $ttl; - } - - // 1.0a Compatibility : associate callback url to the request token - $cbUrl = $this->getParam('oauth_callback', true); - if ($cbUrl) { - $options['oauth_callback'] = $cbUrl; - } - - // Create a request token - $store = OAuthStore::instance(); - $token = $store->addConsumerRequestToken($this->getParam('oauth_consumer_key', true), $options); - $result = 'oauth_callback_confirmed=1&oauth_token='.$this->urlencode($token['token']) - .'&oauth_token_secret='.$this->urlencode($token['token_secret']); - - if (!empty($token['token_ttl'])) - { - $result .= '&xoauth_token_ttl='.$this->urlencode($token['token_ttl']); - } - - $request_token = $token['token']; - - header('HTTP/1.1 200 OK'); - header('Content-Length: '.strlen($result)); - header('Content-Type: application/x-www-form-urlencoded'); - - echo $result; - } - catch (OAuthException2 $e) - { - $request_token = false; - - header('HTTP/1.1 401 Unauthorized'); - header('Content-Type: text/plain'); - - echo "OAuth Verification Failed: " . $e->getMessage(); - } - - OAuthRequestLogger::flush(); - return $request_token; - } - - - /** - * Verify the start of an authorization request. Verifies if the request token is valid. - * Next step is the method authorizeFinish() - * - * Nota bene: this stores the current token, consumer key and callback in the _SESSION - * - * @exception OAuthException2 thrown when not a valid request - * @return array token description - */ - public function authorizeVerify () - { - OAuthRequestLogger::start($this); - - $store = OAuthStore::instance(); - $token = $this->getParam('oauth_token', true); - $rs = $store->getConsumerRequestToken($token); - if (empty($rs)) - { - throw new OAuthException2('Unknown request token "'.$token.'"'); - } - - // We need to remember the callback - $verify_oauth_token = $this->session->get('verify_oauth_token'); - if ( empty($verify_oauth_token) - || strcmp($verify_oauth_token, $rs['token'])) - { - $this->session->set('verify_oauth_token', $rs['token']); - $this->session->set('verify_oauth_consumer_key', $rs['consumer_key']); - $cb = $this->getParam('oauth_callback', true); - if ($cb) - $this->session->set('verify_oauth_callback', $cb); - else - $this->session->set('verify_oauth_callback', $rs['callback_url']); - } - OAuthRequestLogger::flush(); - return $rs; - } - - - /** - * Overrule this method when you want to display a nice page when - * the authorization is finished. This function does not know if the authorization was - * succesfull, you need to check the token in the database. - * - * @param boolean authorized if the current token (oauth_token param) is authorized or not - * @param int user_id user for which the token was authorized (or denied) - * @return string verifier For 1.0a Compatibility - */ - public function authorizeFinish ( $authorized, $user_id ) - { - OAuthRequestLogger::start($this); - - $token = $this->getParam('oauth_token', true); - $verifier = null; - if ($this->session->get('verify_oauth_token') == $token) - { - // Flag the token as authorized, or remove the token when not authorized - $store = OAuthStore::instance(); - - // Fetch the referrer host from the oauth callback parameter - $referrer_host = ''; - $oauth_callback = false; - $verify_oauth_callback = $this->session->get('verify_oauth_callback'); - if (!empty($verify_oauth_callback) && $verify_oauth_callback != 'oob') // OUT OF BAND - { - $oauth_callback = $this->session->get('verify_oauth_callback'); - $ps = parse_url($oauth_callback); - if (isset($ps['host'])) - { - $referrer_host = $ps['host']; - } - } - - if ($authorized) - { - OAuthRequestLogger::addNote('Authorized token "'.$token.'" for user '.$user_id.' with referrer "'.$referrer_host.'"'); - // 1.0a Compatibility : create a verifier code - $verifier = $store->authorizeConsumerRequestToken($token, $user_id, $referrer_host); - } - else - { - OAuthRequestLogger::addNote('Authorization rejected for token "'.$token.'" for user '.$user_id."\nToken has been deleted"); - $store->deleteConsumerRequestToken($token); - } - - if (!empty($oauth_callback)) - { - $params = array('oauth_token' => rawurlencode($token)); - // 1.0a Compatibility : if verifier code has been generated, add it to the URL - if ($verifier) { - $params['oauth_verifier'] = $verifier; - } - - $uri = preg_replace('/\s/', '%20', $oauth_callback); - if (!empty($this->allowed_uri_schemes)) - { - if (!in_array(substr($uri, 0, strpos($uri, '://')), $this->allowed_uri_schemes)) - { - throw new OAuthException2('Illegal protocol in redirect uri '.$uri); - } - } - else if (!empty($this->disallowed_uri_schemes)) - { - if (in_array(substr($uri, 0, strpos($uri, '://')), $this->disallowed_uri_schemes)) - { - throw new OAuthException2('Illegal protocol in redirect uri '.$uri); - } - } - - $this->redirect($oauth_callback, $params); - } - } - OAuthRequestLogger::flush(); - return $verifier; - } - - - /** - * Exchange a request token for an access token. - * The exchange is only succesful iff the request token has been authorized. - * - * Never returns, calls exit() when token is exchanged or when error is returned. - */ - public function accessToken () - { - OAuthRequestLogger::start($this); - - try - { - $this->verify('request'); - - $options = array(); - $ttl = $this->getParam('xoauth_token_ttl', false); - if ($ttl) - { - $options['token_ttl'] = $ttl; - } - - $verifier = $this->getParam('oauth_verifier', false); - if ($verifier) { - $options['verifier'] = $verifier; - } - - $store = OAuthStore::instance(); - $token = $store->exchangeConsumerRequestForAccessToken($this->getParam('oauth_token', true), $options); - $result = 'oauth_token='.$this->urlencode($token['token']) - .'&oauth_token_secret='.$this->urlencode($token['token_secret']); - - if (!empty($token['token_ttl'])) - { - $result .= '&xoauth_token_ttl='.$this->urlencode($token['token_ttl']); - } - - header('HTTP/1.1 200 OK'); - header('Content-Length: '.strlen($result)); - header('Content-Type: application/x-www-form-urlencoded'); - - echo $result; - } - catch (OAuthException2 $e) - { - header('HTTP/1.1 401 Access Denied'); - header('Content-Type: text/plain'); - - echo "OAuth Verification Failed: " . $e->getMessage(); - } - - OAuthRequestLogger::flush(); - exit(); - } -} - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthSession.php b/3rdparty/oauth-php/library/OAuthSession.php deleted file mode 100644 index 80ceeb7346..0000000000 --- a/3rdparty/oauth-php/library/OAuthSession.php +++ /dev/null @@ -1,86 +0,0 @@ - \ No newline at end of file diff --git a/3rdparty/oauth-php/library/OAuthStore.php b/3rdparty/oauth-php/library/OAuthStore.php deleted file mode 100644 index d3df3a0ae0..0000000000 --- a/3rdparty/oauth-php/library/OAuthStore.php +++ /dev/null @@ -1,86 +0,0 @@ - - * @date Nov 16, 2007 4:03:30 PM - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__) . '/OAuthException2.php'; - -class OAuthStore -{ - static private $instance = false; - - /** - * Request an instance of the OAuthStore - */ - public static function instance ( $store = 'MySQL', $options = array() ) - { - if (!OAuthStore::$instance) - { - // Select the store you want to use - if (strpos($store, '/') === false) - { - $class = 'OAuthStore'.$store; - $file = dirname(__FILE__) . '/store/'.$class.'.php'; - } - else - { - $file = $store; - $store = basename($file, '.php'); - $class = $store; - } - - if (is_file($file)) - { - require_once $file; - - if (class_exists($class)) - { - OAuthStore::$instance = new $class($options); - } - else - { - throw new OAuthException2('Could not find class '.$class.' in file '.$file); - } - } - else - { - throw new OAuthException2('No OAuthStore for '.$store.' (file '.$file.')'); - } - } - return OAuthStore::$instance; - } -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/body/OAuthBodyContentDisposition.php b/3rdparty/oauth-php/library/body/OAuthBodyContentDisposition.php deleted file mode 100644 index 02b1e42779..0000000000 --- a/3rdparty/oauth-php/library/body/OAuthBodyContentDisposition.php +++ /dev/null @@ -1,129 +0,0 @@ - - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -class OAuthBodyContentDisposition -{ - /** - * Builds the request string. - * - * The files array can be a combination of the following (either data or file): - * - * file => "path/to/file", filename=, mime=, data= - * - * @param array files (name => filedesc) (not urlencoded) - * @return array (headers, body) - */ - static function encodeBody ( $files ) - { - $headers = array(); - $body = null; - - // 1. Add all the files to the post - if (!empty($files)) - { - foreach ($files as $name => $f) - { - $data = false; - $filename = false; - - if (isset($f['filename'])) - { - $filename = $f['filename']; - } - - if (!empty($f['file'])) - { - $data = @file_get_contents($f['file']); - if ($data === false) - { - throw new OAuthException2(sprintf('Could not read the file "%s" for request body', $f['file'])); - } - if (empty($filename)) - { - $filename = basename($f['file']); - } - } - else if (isset($f['data'])) - { - $data = $f['data']; - } - - // When there is data, add it as a request body, otherwise silently skip the upload - if ($data !== false) - { - if (isset($headers['Content-Disposition'])) - { - throw new OAuthException2('Only a single file (or data) allowed in a signed PUT/POST request body.'); - } - - if (empty($filename)) - { - $filename = 'untitled'; - } - $mime = !empty($f['mime']) ? $f['mime'] : 'application/octet-stream'; - - $headers['Content-Disposition'] = 'attachment; filename="'.OAuthBodyContentDisposition::encodeParameterName($filename).'"'; - $headers['Content-Type'] = $mime; - - $body = $data; - } - - } - - // When we have a body, add the content-length - if (!is_null($body)) - { - $headers['Content-Length'] = strlen($body); - } - } - return array($headers, $body); - } - - - /** - * Encode a parameter's name for use in a multipart header. - * For now we do a simple filter that removes some unwanted characters. - * We might want to implement RFC1522 here. See http://tools.ietf.org/html/rfc1522 - * - * @param string name - * @return string - */ - static function encodeParameterName ( $name ) - { - return preg_replace('/[^\x20-\x7f]|"/', '-', $name); - } -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/body/OAuthBodyMultipartFormdata.php b/3rdparty/oauth-php/library/body/OAuthBodyMultipartFormdata.php deleted file mode 100644 index a869e1e6d7..0000000000 --- a/3rdparty/oauth-php/library/body/OAuthBodyMultipartFormdata.php +++ /dev/null @@ -1,143 +0,0 @@ - - * @date Jan 31, 2008 12:50:05 PM - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -class OAuthBodyMultipartFormdata -{ - /** - * Builds the request string. - * - * The files array can be a combination of the following (either data or file): - * - * file => "path/to/file", filename=, mime=, data= - * - * @param array params (name => value) (all names and values should be urlencoded) - * @param array files (name => filedesc) (not urlencoded) - * @return array (headers, body) - */ - static function encodeBody ( $params, $files ) - { - $headers = array(); - $body = ''; - $boundary = 'OAuthRequester_'.md5(uniqid('multipart') . microtime()); - $headers['Content-Type'] = 'multipart/form-data; boundary=' . $boundary; - - - // 1. Add the parameters to the post - if (!empty($params)) - { - foreach ($params as $name => $value) - { - $body .= '--'.$boundary."\r\n"; - $body .= 'Content-Disposition: form-data; name="'.OAuthBodyMultipartFormdata::encodeParameterName(rawurldecode($name)).'"'; - $body .= "\r\n\r\n"; - $body .= urldecode($value); - $body .= "\r\n"; - } - } - - // 2. Add all the files to the post - if (!empty($files)) - { - $untitled = 1; - - foreach ($files as $name => $f) - { - $data = false; - $filename = false; - - if (isset($f['filename'])) - { - $filename = $f['filename']; - } - - if (!empty($f['file'])) - { - $data = @file_get_contents($f['file']); - if ($data === false) - { - throw new OAuthException2(sprintf('Could not read the file "%s" for form-data part', $f['file'])); - } - if (empty($filename)) - { - $filename = basename($f['file']); - } - } - else if (isset($f['data'])) - { - $data = $f['data']; - } - - // When there is data, add it as a form-data part, otherwise silently skip the upload - if ($data !== false) - { - if (empty($filename)) - { - $filename = sprintf('untitled-%d', $untitled++); - } - $mime = !empty($f['mime']) ? $f['mime'] : 'application/octet-stream'; - $body .= '--'.$boundary."\r\n"; - $body .= 'Content-Disposition: form-data; name="'.OAuthBodyMultipartFormdata::encodeParameterName($name).'"; filename="'.OAuthBodyMultipartFormdata::encodeParameterName($filename).'"'."\r\n"; - $body .= 'Content-Type: '.$mime; - $body .= "\r\n\r\n"; - $body .= $data; - $body .= "\r\n"; - } - - } - } - $body .= '--'.$boundary."--\r\n"; - - $headers['Content-Length'] = strlen($body); - return array($headers, $body); - } - - - /** - * Encode a parameter's name for use in a multipart header. - * For now we do a simple filter that removes some unwanted characters. - * We might want to implement RFC1522 here. See http://tools.ietf.org/html/rfc1522 - * - * @param string name - * @return string - */ - static function encodeParameterName ( $name ) - { - return preg_replace('/[^\x20-\x7f]|"/', '-', $name); - } -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/discovery/xrds_parse.php b/3rdparty/oauth-php/library/discovery/xrds_parse.php deleted file mode 100644 index c9cf94997d..0000000000 --- a/3rdparty/oauth-php/library/discovery/xrds_parse.php +++ /dev/null @@ -1,304 +0,0 @@ - - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* example of use: - -header('content-type: text/plain'); -$file = file_get_contents('../../test/discovery/xrds-magnolia.xrds'); -$xrds = xrds_parse($file); -print_r($xrds); - - */ - -/** - * Parse the xrds file in the argument. The xrds description must have been - * fetched via curl or something else. - * - * TODO: more robust checking, support for more service documents - * TODO: support for URIs to definition instead of local xml:id - * - * @param string data contents of xrds file - * @exception Exception when the file is in an unknown format - * @return array - */ -function xrds_parse ( $data ) -{ - $oauth = array(); - $doc = @DOMDocument::loadXML($data); - if ($doc === false) - { - throw new Exception('Error in XML, can\'t load XRDS document'); - } - - $xpath = new DOMXPath($doc); - $xpath->registerNamespace('xrds', 'xri://$xrds'); - $xpath->registerNamespace('xrd', 'xri://$XRD*($v*2.0)'); - $xpath->registerNamespace('simple', 'http://xrds-simple.net/core/1.0'); - - // Yahoo! uses this namespace, with lowercase xrd in it - $xpath->registerNamespace('xrd2', 'xri://$xrd*($v*2.0)'); - - $uris = xrds_oauth_service_uris($xpath); - - foreach ($uris as $uri) - { - // TODO: support uris referring to service documents outside this one - if ($uri{0} == '#') - { - $id = substr($uri, 1); - $oauth = xrds_xrd_oauth($xpath, $id); - if (is_array($oauth) && !empty($oauth)) - { - return $oauth; - } - } - } - - return false; -} - - -/** - * Parse a XRD definition for OAuth and return the uris etc. - * - * @param XPath xpath - * @param string id - * @return array - */ -function xrds_xrd_oauth ( $xpath, $id ) -{ - $oauth = array(); - $xrd = $xpath->query('//xrds:XRDS/xrd:XRD[@xml:id="'.$id.'"]'); - if ($xrd->length == 0) - { - // Yahoo! uses another namespace - $xrd = $xpath->query('//xrds:XRDS/xrd2:XRD[@xml:id="'.$id.'"]'); - } - - if ($xrd->length >= 1) - { - $x = $xrd->item(0); - $services = array(); - foreach ($x->childNodes as $n) - { - switch ($n->nodeName) - { - case 'Type': - if ($n->nodeValue != 'xri://$xrds*simple') - { - // Not a simple XRDS document - return false; - } - break; - case 'Expires': - $oauth['expires'] = $n->nodeValue; - break; - case 'Service': - list($type,$service) = xrds_xrd_oauth_service($n); - if ($type) - { - $services[$type][xrds_priority($n)][] = $service; - } - break; - } - } - - // Flatten the services on priority - foreach ($services as $type => $service) - { - $oauth[$type] = xrds_priority_flatten($service); - } - } - else - { - $oauth = false; - } - return $oauth; -} - - -/** - * Parse a service definition for OAuth in a simple xrd element - * - * @param DOMElement n - * @return array (type, service desc) - */ -function xrds_xrd_oauth_service ( $n ) -{ - $service = array( - 'uri' => '', - 'signature_method' => array(), - 'parameters' => array() - ); - - $type = false; - foreach ($n->childNodes as $c) - { - $name = $c->nodeName; - $value = $c->nodeValue; - - if ($name == 'URI') - { - $service['uri'] = $value; - } - else if ($name == 'Type') - { - if (strncmp($value, 'http://oauth.net/core/1.0/endpoint/', 35) == 0) - { - $type = basename($value); - } - else if (strncmp($value, 'http://oauth.net/core/1.0/signature/', 36) == 0) - { - $service['signature_method'][] = basename($value); - } - else if (strncmp($value, 'http://oauth.net/core/1.0/parameters/', 37) == 0) - { - $service['parameters'][] = basename($value); - } - else if (strncmp($value, 'http://oauth.net/discovery/1.0/consumer-identity/', 49) == 0) - { - $type = 'consumer_identity'; - $service['method'] = basename($value); - unset($service['signature_method']); - unset($service['parameters']); - } - else - { - $service['unknown'][] = $value; - } - } - else if ($name == 'LocalID') - { - $service['consumer_key'] = $value; - } - else if ($name{0} != '#') - { - $service[strtolower($name)] = $value; - } - } - return array($type, $service); -} - - -/** - * Return the OAuth service uris in order of the priority. - * - * @param XPath xpath - * @return array - */ -function xrds_oauth_service_uris ( $xpath ) -{ - $uris = array(); - $xrd_oauth = $xpath->query('//xrds:XRDS/xrd:XRD/xrd:Service/xrd:Type[.=\'http://oauth.net/discovery/1.0\']'); - if ($xrd_oauth->length > 0) - { - $service = array(); - foreach ($xrd_oauth as $xo) - { - // Find the URI of the service definition - $cs = $xo->parentNode->childNodes; - foreach ($cs as $c) - { - if ($c->nodeName == 'URI') - { - $prio = xrds_priority($xo); - $service[$prio][] = $c->nodeValue; - } - } - } - $uris = xrds_priority_flatten($service); - } - return $uris; -} - - - -/** - * Flatten an array according to the priority - * - * @param array ps buckets per prio - * @return array one dimensional array - */ -function xrds_priority_flatten ( $ps ) -{ - $prio = array(); - $null = array(); - ksort($ps); - foreach ($ps as $idx => $bucket) - { - if (!empty($bucket)) - { - if ($idx == 'null') - { - $null = $bucket; - } - else - { - $prio = array_merge($prio, $bucket); - } - } - } - $prio = array_merge($prio, $bucket); - return $prio; -} - - -/** - * Fetch the priority of a element - * - * @param DOMElement elt - * @return mixed 'null' or int - */ -function xrds_priority ( $elt ) -{ - if ($elt->hasAttribute('priority')) - { - $prio = $elt->getAttribute('priority'); - if (is_numeric($prio)) - { - $prio = intval($prio); - } - } - else - { - $prio = 'null'; - } - return $prio; -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/discovery/xrds_parse.txt b/3rdparty/oauth-php/library/discovery/xrds_parse.txt deleted file mode 100644 index fd867ea9fb..0000000000 --- a/3rdparty/oauth-php/library/discovery/xrds_parse.txt +++ /dev/null @@ -1,101 +0,0 @@ -The xrds_parse.php script contains the function: - - function xrds_parse ( $data. ) - -$data Contains the contents of a XRDS XML file. -When the data is invalid XML then this will throw an exception. - -After parsing a XRDS definition it will return a datastructure much like the one below. - -Array -( - [expires] => 2008-04-13T07:34:58Z - [request] => Array - ( - [0] => Array - ( - [uri] => https://ma.gnolia.com/oauth/get_request_token - [signature_method] => Array - ( - [0] => HMAC-SHA1 - [1] => RSA-SHA1 - [2] => PLAINTEXT - ) - - [parameters] => Array - ( - [0] => auth-header - [1] => post-body - [2] => uri-query - ) - ) - ) - - [authorize] => Array - ( - [0] => Array - ( - [uri] => http://ma.gnolia.com/oauth/authorize - [signature_method] => Array - ( - ) - - [parameters] => Array - ( - [0] => auth-header - [1] => uri-query - ) - ) - ) - - [access] => Array - ( - [0] => Array - ( - [uri] => https://ma.gnolia.com/oauth/get_access_token - [signature_method] => Array - ( - [0] => HMAC-SHA1 - [1] => RSA-SHA1 - [2] => PLAINTEXT - ) - - [parameters] => Array - ( - [0] => auth-header - [1] => post-body - [2] => uri-query - ) - ) - ) - - [resource] => Array - ( - [0] => Array - ( - [uri] => - [signature_method] => Array - ( - [0] => HMAC-SHA1 - [1] => RSA-SHA1 - ) - - [parameters] => Array - ( - [0] => auth-header - [1] => post-body - [2] => uri-query - ) - ) - ) - - [consumer_identity] => Array - ( - [0] => Array - ( - [uri] => http://ma.gnolia.com/applications/new - [method] => oob - ) - ) -) - diff --git a/3rdparty/oauth-php/library/session/OAuthSessionAbstract.class.php b/3rdparty/oauth-php/library/session/OAuthSessionAbstract.class.php deleted file mode 100644 index dcc80c1d81..0000000000 --- a/3rdparty/oauth-php/library/session/OAuthSessionAbstract.class.php +++ /dev/null @@ -1,44 +0,0 @@ - - * - * The MIT License - * - * Copyright (c) 2010 Corollarium Technologies - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/** - * This class is used to store Session information on the server. Most - * people will use the $_SESSION based implementation, but you may prefer - * a SQL, Memcache or other implementation. - * - */ -abstract class OAuthSessionAbstract -{ - abstract public function get ( $key ); - abstract public function set ( $key, $data ); -} - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/session/OAuthSessionSESSION.php b/3rdparty/oauth-php/library/session/OAuthSessionSESSION.php deleted file mode 100644 index 3201ecbe06..0000000000 --- a/3rdparty/oauth-php/library/session/OAuthSessionSESSION.php +++ /dev/null @@ -1,63 +0,0 @@ - - * - * The MIT License - * - * Copyright (c) 2010 Corollarium Technologies - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__) . '/OAuthSessionAbstract.class.php'; - -class OAuthSessionSESSION extends OAuthSessionAbstract -{ - public function __construct( $options = array() ) - { - } - - /** - * Gets a variable value - * - * @param string $key - * @return The value or null if not set. - */ - public function get ( $key ) - { - return @$_SESSION[$key]; - } - - /** - * Sets a variable value - * - * @param string $key The key - * @param any $data The data - */ - public function set ( $key, $data ) - { - $_SESSION[$key] = $data; - } -} - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod.class.php b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod.class.php deleted file mode 100644 index 34ccb428cc..0000000000 --- a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod.class.php +++ /dev/null @@ -1,69 +0,0 @@ - - * @date Sep 8, 2008 12:04:35 PM - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -abstract class OAuthSignatureMethod -{ - /** - * Return the name of this signature - * - * @return string - */ - abstract public function name(); - - /** - * Return the signature for the given request - * - * @param OAuthRequest request - * @param string base_string - * @param string consumer_secret - * @param string token_secret - * @return string - */ - abstract public function signature ( $request, $base_string, $consumer_secret, $token_secret ); - - /** - * Check if the request signature corresponds to the one calculated for the request. - * - * @param OAuthRequest request - * @param string base_string data to be signed, usually the base string, can be a request body - * @param string consumer_secret - * @param string token_secret - * @param string signature from the request, still urlencoded - * @return string - */ - abstract public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature ); -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php deleted file mode 100644 index e189c93815..0000000000 --- a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_HMAC_SHA1.php +++ /dev/null @@ -1,115 +0,0 @@ - - * @date Sep 8, 2008 12:21:19 PM - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php'; - - -class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod -{ - public function name () - { - return 'HMAC-SHA1'; - } - - - /** - * Calculate the signature using HMAC-SHA1 - * This function is copyright Andy Smith, 2007. - * - * @param OAuthRequest request - * @param string base_string - * @param string consumer_secret - * @param string token_secret - * @return string - */ - function signature ( $request, $base_string, $consumer_secret, $token_secret ) - { - $key = $request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret); - if (function_exists('hash_hmac')) - { - $signature = base64_encode(hash_hmac("sha1", $base_string, $key, true)); - } - else - { - $blocksize = 64; - $hashfunc = 'sha1'; - if (strlen($key) > $blocksize) - { - $key = pack('H*', $hashfunc($key)); - } - $key = str_pad($key,$blocksize,chr(0x00)); - $ipad = str_repeat(chr(0x36),$blocksize); - $opad = str_repeat(chr(0x5c),$blocksize); - $hmac = pack( - 'H*',$hashfunc( - ($key^$opad).pack( - 'H*',$hashfunc( - ($key^$ipad).$base_string - ) - ) - ) - ); - $signature = base64_encode($hmac); - } - return $request->urlencode($signature); - } - - - /** - * Check if the request signature corresponds to the one calculated for the request. - * - * @param OAuthRequest request - * @param string base_string data to be signed, usually the base string, can be a request body - * @param string consumer_secret - * @param string token_secret - * @param string signature from the request, still urlencoded - * @return string - */ - public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature ) - { - $a = $request->urldecode($signature); - $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret)); - - // We have to compare the decoded values - $valA = base64_decode($a); - $valB = base64_decode($b); - - // Crude binary comparison - return rawurlencode($valA) == rawurlencode($valB); - } -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php deleted file mode 100644 index a016709802..0000000000 --- a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_MD5.php +++ /dev/null @@ -1,95 +0,0 @@ - - * @date Sep 8, 2008 12:09:43 PM - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php'; - - -class OAuthSignatureMethod_MD5 extends OAuthSignatureMethod -{ - public function name () - { - return 'MD5'; - } - - - /** - * Calculate the signature using MD5 - * Binary md5 digest, as distinct from PHP's built-in hexdigest. - * This function is copyright Andy Smith, 2007. - * - * @param OAuthRequest request - * @param string base_string - * @param string consumer_secret - * @param string token_secret - * @return string - */ - function signature ( $request, $base_string, $consumer_secret, $token_secret ) - { - $s .= '&'.$request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret); - $md5 = md5($base_string); - $bin = ''; - - for ($i = 0; $i < strlen($md5); $i += 2) - { - $bin .= chr(hexdec($md5{$i+1}) + hexdec($md5{$i}) * 16); - } - return $request->urlencode(base64_encode($bin)); - } - - - /** - * Check if the request signature corresponds to the one calculated for the request. - * - * @param OAuthRequest request - * @param string base_string data to be signed, usually the base string, can be a request body - * @param string consumer_secret - * @param string token_secret - * @param string signature from the request, still urlencoded - * @return string - */ - public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature ) - { - $a = $request->urldecode($signature); - $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret)); - - // We have to compare the decoded values - $valA = base64_decode($a); - $valB = base64_decode($b); - - // Crude binary comparison - return rawurlencode($valA) == rawurlencode($valB); - } -} - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php deleted file mode 100644 index 92ef308673..0000000000 --- a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_PLAINTEXT.php +++ /dev/null @@ -1,80 +0,0 @@ - - * @date Sep 8, 2008 12:09:43 PM - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php'; - - -class OAuthSignatureMethod_PLAINTEXT extends OAuthSignatureMethod -{ - public function name () - { - return 'PLAINTEXT'; - } - - - /** - * Calculate the signature using PLAINTEXT - * - * @param OAuthRequest request - * @param string base_string - * @param string consumer_secret - * @param string token_secret - * @return string - */ - function signature ( $request, $base_string, $consumer_secret, $token_secret ) - { - return $request->urlencode($request->urlencode($consumer_secret).'&'.$request->urlencode($token_secret)); - } - - - /** - * Check if the request signature corresponds to the one calculated for the request. - * - * @param OAuthRequest request - * @param string base_string data to be signed, usually the base string, can be a request body - * @param string consumer_secret - * @param string token_secret - * @param string signature from the request, still urlencoded - * @return string - */ - public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature ) - { - $a = $request->urldecode($signature); - $b = $request->urldecode($this->signature($request, $base_string, $consumer_secret, $token_secret)); - - return $request->urldecode($a) == $request->urldecode($b); - } -} - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php b/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php deleted file mode 100644 index 864dbfbebb..0000000000 --- a/3rdparty/oauth-php/library/signature_method/OAuthSignatureMethod_RSA_SHA1.php +++ /dev/null @@ -1,139 +0,0 @@ - - * @date Sep 8, 2008 12:00:14 PM - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -require_once dirname(__FILE__).'/OAuthSignatureMethod.class.php'; - -class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod -{ - public function name() - { - return 'RSA-SHA1'; - } - - - /** - * Fetch the public CERT key for the signature - * - * @param OAuthRequest request - * @return string public key - */ - protected function fetch_public_cert ( $request ) - { - // not implemented yet, ideas are: - // (1) do a lookup in a table of trusted certs keyed off of consumer - // (2) fetch via http using a url provided by the requester - // (3) some sort of specific discovery code based on request - // - // either way should return a string representation of the certificate - throw OAuthException2("OAuthSignatureMethod_RSA_SHA1::fetch_public_cert not implemented"); - } - - - /** - * Fetch the private CERT key for the signature - * - * @param OAuthRequest request - * @return string private key - */ - protected function fetch_private_cert ( $request ) - { - // not implemented yet, ideas are: - // (1) do a lookup in a table of trusted certs keyed off of consumer - // - // either way should return a string representation of the certificate - throw OAuthException2("OAuthSignatureMethod_RSA_SHA1::fetch_private_cert not implemented"); - } - - - /** - * Calculate the signature using RSA-SHA1 - * This function is copyright Andy Smith, 2008. - * - * @param OAuthRequest request - * @param string base_string - * @param string consumer_secret - * @param string token_secret - * @return string - */ - public function signature ( $request, $base_string, $consumer_secret, $token_secret ) - { - // Fetch the private key cert based on the request - $cert = $this->fetch_private_cert($request); - - // Pull the private key ID from the certificate - $privatekeyid = openssl_get_privatekey($cert); - - // Sign using the key - $sig = false; - $ok = openssl_sign($base_string, $sig, $privatekeyid); - - // Release the key resource - openssl_free_key($privatekeyid); - - return $request->urlencode(base64_encode($sig)); - } - - - /** - * Check if the request signature is the same as the one calculated for the request. - * - * @param OAuthRequest request - * @param string base_string - * @param string consumer_secret - * @param string token_secret - * @param string signature - * @return string - */ - public function verify ( $request, $base_string, $consumer_secret, $token_secret, $signature ) - { - $decoded_sig = base64_decode($request->urldecode($signature)); - - // Fetch the public key cert based on the request - $cert = $this->fetch_public_cert($request); - - // Pull the public key ID from the certificate - $publickeyid = openssl_get_publickey($cert); - - // Check the computed signature against the one passed in the query - $ok = openssl_verify($base_string, $decoded_sig, $publickeyid); - - // Release the key resource - openssl_free_key($publickeyid); - return $ok == 1; - } - -} - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStore2Leg.php b/3rdparty/oauth-php/library/store/OAuthStore2Leg.php deleted file mode 100644 index faab95b04b..0000000000 --- a/3rdparty/oauth-php/library/store/OAuthStore2Leg.php +++ /dev/null @@ -1,113 +0,0 @@ - - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php'; - -class OAuthStore2Leg extends OAuthStoreAbstract -{ - protected $consumer_key; - protected $consumer_secret; - protected $signature_method = array('HMAC-SHA1'); - protected $token_type = false; - - /* - * Takes two options: consumer_key and consumer_secret - */ - public function __construct( $options = array() ) - { - if(isset($options['consumer_key']) && isset($options['consumer_secret'])) - { - $this->consumer_key = $options['consumer_key']; - $this->consumer_secret = $options['consumer_secret']; - } - else - { - throw new OAuthException2("OAuthStore2Leg needs consumer_token and consumer_secret"); - } - } - - public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function getSecretsForSignature ( $uri, $user_id ) - { - return array( - 'consumer_key' => $this->consumer_key, - 'consumer_secret' => $this->consumer_secret, - 'signature_methods' => $this->signature_method, - 'token' => $this->token_type - ); - } - public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - - public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function getServer( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function getServerForUri ( $uri, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function listServerTokens ( $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function countServerTokens ( $consumer_key ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function getServerToken ( $consumer_key, $token, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function setServerTokenTtl ( $consumer_key, $token, $token_ttl ) - { - //This method just needs to exist. It doesn't have to do anything! - } - - public function listServers ( $q = '', $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function updateServer ( $server, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - - public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function getConsumerStatic () { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - - public function addConsumerRequestToken ( $consumer_key, $options = array() ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function getConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function deleteConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function countConsumerAccessTokens ( $consumer_key ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function getConsumerAccessToken ( $token, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function setConsumerAccessTokenTtl ( $token, $ttl ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - - public function listConsumers ( $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function listConsumerApplications( $begin = 0, $total = 25 ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function listConsumerTokens ( $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - - public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - - public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - public function listLog ( $options, $user_id ) { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } - - public function install () { throw new OAuthException2("OAuthStore2Leg doesn't support " . __METHOD__); } -} - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreAbstract.class.php b/3rdparty/oauth-php/library/store/OAuthStoreAbstract.class.php deleted file mode 100644 index 3bfa2b2b0d..0000000000 --- a/3rdparty/oauth-php/library/store/OAuthStoreAbstract.class.php +++ /dev/null @@ -1,150 +0,0 @@ - - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -abstract class OAuthStoreAbstract -{ - abstract public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ); - abstract public function getSecretsForSignature ( $uri, $user_id ); - abstract public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' ); - abstract public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ); - - abstract public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ); - abstract public function getServer( $consumer_key, $user_id, $user_is_admin = false ); - abstract public function getServerForUri ( $uri, $user_id ); - abstract public function listServerTokens ( $user_id ); - abstract public function countServerTokens ( $consumer_key ); - abstract public function getServerToken ( $consumer_key, $token, $user_id ); - abstract public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ); - abstract public function listServers ( $q = '', $user_id ); - abstract public function updateServer ( $server, $user_id, $user_is_admin = false ); - - abstract public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ); - abstract public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ); - abstract public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ); - abstract public function getConsumerStatic (); - - abstract public function addConsumerRequestToken ( $consumer_key, $options = array() ); - abstract public function getConsumerRequestToken ( $token ); - abstract public function deleteConsumerRequestToken ( $token ); - abstract public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ); - abstract public function countConsumerAccessTokens ( $consumer_key ); - abstract public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ); - abstract public function getConsumerAccessToken ( $token, $user_id ); - abstract public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ); - abstract public function setConsumerAccessTokenTtl ( $token, $ttl ); - - abstract public function listConsumers ( $user_id ); - abstract public function listConsumerApplications( $begin = 0, $total = 25 ); - abstract public function listConsumerTokens ( $user_id ); - - abstract public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ); - - abstract public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ); - abstract public function listLog ( $options, $user_id ); - - abstract public function install (); - - /** - * Fetch the current static consumer key for this site, create it when it was not found. - * The consumer secret for the consumer key is always empty. - * - * @return string consumer key - */ - - - /* ** Some handy utility functions ** */ - - /** - * Generate a unique key - * - * @param boolean unique force the key to be unique - * @return string - */ - public function generateKey ( $unique = false ) - { - $key = md5(uniqid(rand(), true)); - if ($unique) - { - list($usec,$sec) = explode(' ',microtime()); - $key .= dechex($usec).dechex($sec); - } - return $key; - } - - /** - * Check to see if a string is valid utf8 - * - * @param string $s - * @return boolean - */ - protected function isUTF8 ( $s ) - { - return preg_match('%(?: - [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte - |\xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs - |[\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte - |\xED[\x80-\x9F][\x80-\xBF] # excluding surrogates - |\xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 - |[\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 - |\xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 - )+%xs', $s); - } - - - /** - * Make a string utf8, replacing all non-utf8 chars with a '.' - * - * @param string - * @return string - */ - protected function makeUTF8 ( $s ) - { - if (function_exists('iconv')) - { - do - { - $ok = true; - $text = @iconv('UTF-8', 'UTF-8//TRANSLIT', $s); - if (strlen($text) != strlen($s)) - { - // Remove the offending character... - $s = $text . '.' . substr($s, strlen($text) + 1); - $ok = false; - } - } - while (!$ok); - } - return $s; - } - -} - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreAnyMeta.php b/3rdparty/oauth-php/library/store/OAuthStoreAnyMeta.php deleted file mode 100644 index b619ec0367..0000000000 --- a/3rdparty/oauth-php/library/store/OAuthStoreAnyMeta.php +++ /dev/null @@ -1,264 +0,0 @@ - - * @date Nov 16, 2007 4:03:30 PM - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__) . '/OAuthStoreMySQL.php'; - - -class OAuthStoreAnymeta extends OAuthStoreMySQL -{ - /** - * Construct the OAuthStoreAnymeta - * - * @param array options - */ - function __construct ( $options = array() ) - { - parent::__construct(array('conn' => any_db_conn())); - } - - - /** - * Add an entry to the log table - * - * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token) - * @param string received - * @param string sent - * @param string base_string - * @param string notes - * @param int (optional) user_id - */ - public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) - { - if (is_null($user_id) && isset($GLOBALS['any_auth'])) - { - $user_id = $GLOBALS['any_auth']->getUserId(); - } - parent::addLog($keys, $received, $sent, $base_string, $notes, $user_id); - } - - - /** - * Get a page of entries from the log. Returns the last 100 records - * matching the options given. - * - * @param array options - * @param int user_id current user - * @return array log records - */ - public function listLog ( $options, $user_id ) - { - $where = array(); - $args = array(); - if (empty($options)) - { - $where[] = 'olg_usa_id_ref = %d'; - $args[] = $user_id; - } - else - { - foreach ($options as $option => $value) - { - if (strlen($value) > 0) - { - switch ($option) - { - case 'osr_consumer_key': - case 'ocr_consumer_key': - case 'ost_token': - case 'oct_token': - $where[] = 'olg_'.$option.' = \'%s\''; - $args[] = $value; - break; - } - } - } - - $where[] = '(olg_usa_id_ref IS NULL OR olg_usa_id_ref = %d)'; - $args[] = $user_id; - } - - $rs = any_db_query_all_assoc(' - SELECT olg_id, - olg_osr_consumer_key AS osr_consumer_key, - olg_ost_token AS ost_token, - olg_ocr_consumer_key AS ocr_consumer_key, - olg_oct_token AS oct_token, - olg_usa_id_ref AS user_id, - olg_received AS received, - olg_sent AS sent, - olg_base_string AS base_string, - olg_notes AS notes, - olg_timestamp AS timestamp, - INET_NTOA(olg_remote_ip) AS remote_ip - FROM oauth_log - WHERE '.implode(' AND ', $where).' - ORDER BY olg_id DESC - LIMIT 0,100', $args); - - return $rs; - } - - - - /** - * Initialise the database - */ - public function install () - { - parent::install(); - - any_db_query("ALTER TABLE oauth_consumer_registry MODIFY ocr_usa_id_ref int(11) unsigned"); - any_db_query("ALTER TABLE oauth_consumer_token MODIFY oct_usa_id_ref int(11) unsigned not null"); - any_db_query("ALTER TABLE oauth_server_registry MODIFY osr_usa_id_ref int(11) unsigned"); - any_db_query("ALTER TABLE oauth_server_token MODIFY ost_usa_id_ref int(11) unsigned not null"); - any_db_query("ALTER TABLE oauth_log MODIFY olg_usa_id_ref int(11) unsigned"); - - any_db_alter_add_fk('oauth_consumer_registry', 'ocr_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete set null'); - any_db_alter_add_fk('oauth_consumer_token', 'oct_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete cascade'); - any_db_alter_add_fk('oauth_server_registry', 'osr_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete set null'); - any_db_alter_add_fk('oauth_server_token', 'ost_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete cascade'); - any_db_alter_add_fk('oauth_log', 'olg_usa_id_ref', 'any_user_auth(usa_id_ref)', 'on update cascade on delete cascade'); - } - - - - /** Some simple helper functions for querying the mysql db **/ - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - */ - protected function query ( $sql ) - { - list($sql, $args) = $this->sql_args(func_get_args()); - any_db_query($sql, $args); - } - - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_all_assoc ( $sql ) - { - list($sql, $args) = $this->sql_args(func_get_args()); - return any_db_query_all_assoc($sql, $args); - } - - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_row_assoc ( $sql ) - { - list($sql, $args) = $this->sql_args(func_get_args()); - return any_db_query_row_assoc($sql, $args); - } - - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_row ( $sql ) - { - list($sql, $args) = $this->sql_args(func_get_args()); - return any_db_query_row($sql, $args); - } - - - /** - * Perform a query, return the first column of the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return mixed - */ - protected function query_one ( $sql ) - { - list($sql, $args) = $this->sql_args(func_get_args()); - return any_db_query_one($sql, $args); - } - - - /** - * Return the number of rows affected in the last query - * - * @return int - */ - protected function query_affected_rows () - { - return any_db_affected_rows(); - } - - - /** - * Return the id of the last inserted row - * - * @return int - */ - protected function query_insert_id () - { - return any_db_insert_id(); - } - - - private function sql_args ( $args ) - { - $sql = array_shift($args); - if (count($args) == 1 && is_array($args[0])) - { - $args = $args[0]; - } - return array($sql, $args); - } - -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreMySQL.php b/3rdparty/oauth-php/library/store/OAuthStoreMySQL.php deleted file mode 100644 index c568359ace..0000000000 --- a/3rdparty/oauth-php/library/store/OAuthStoreMySQL.php +++ /dev/null @@ -1,245 +0,0 @@ - - * @date Nov 16, 2007 4:03:30 PM - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -require_once dirname(__FILE__) . '/OAuthStoreSQL.php'; - - -class OAuthStoreMySQL extends OAuthStoreSQL -{ - /** - * The MySQL connection - */ - protected $conn; - - /** - * Initialise the database - */ - public function install () - { - require_once dirname(__FILE__) . '/mysql/install.php'; - } - - - /* ** Some simple helper functions for querying the mysql db ** */ - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - */ - protected function query ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = mysql_query($sql, $this->conn))) - { - $this->sql_errcheck($sql); - } - if (is_resource($res)) - { - mysql_free_result($res); - } - } - - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_all_assoc ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = mysql_query($sql, $this->conn))) - { - $this->sql_errcheck($sql); - } - $rs = array(); - while ($row = mysql_fetch_assoc($res)) - { - $rs[] = $row; - } - mysql_free_result($res); - return $rs; - } - - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_row_assoc ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = mysql_query($sql, $this->conn))) - { - $this->sql_errcheck($sql); - } - if ($row = mysql_fetch_assoc($res)) - { - $rs = $row; - } - else - { - $rs = false; - } - mysql_free_result($res); - return $rs; - } - - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_row ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = mysql_query($sql, $this->conn))) - { - $this->sql_errcheck($sql); - } - if ($row = mysql_fetch_array($res)) - { - $rs = $row; - } - else - { - $rs = false; - } - mysql_free_result($res); - return $rs; - } - - - /** - * Perform a query, return the first column of the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return mixed - */ - protected function query_one ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = mysql_query($sql, $this->conn))) - { - $this->sql_errcheck($sql); - } - $val = @mysql_result($res, 0, 0); - mysql_free_result($res); - return $val; - } - - - /** - * Return the number of rows affected in the last query - */ - protected function query_affected_rows () - { - return mysql_affected_rows($this->conn); - } - - - /** - * Return the id of the last inserted row - * - * @return int - */ - protected function query_insert_id () - { - return mysql_insert_id($this->conn); - } - - - protected function sql_printf ( $args ) - { - $sql = array_shift($args); - if (count($args) == 1 && is_array($args[0])) - { - $args = $args[0]; - } - $args = array_map(array($this, 'sql_escape_string'), $args); - return vsprintf($sql, $args); - } - - - protected function sql_escape_string ( $s ) - { - if (is_string($s)) - { - return mysql_real_escape_string($s, $this->conn); - } - else if (is_null($s)) - { - return NULL; - } - else if (is_bool($s)) - { - return intval($s); - } - else if (is_int($s) || is_float($s)) - { - return $s; - } - else - { - return mysql_real_escape_string(strval($s), $this->conn); - } - } - - - protected function sql_errcheck ( $sql ) - { - if (mysql_errno($this->conn)) - { - $msg = "SQL Error in OAuthStoreMySQL: ".mysql_error($this->conn)."\n\n" . $sql; - throw new OAuthException2($msg); - } - } -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreMySQLi.php b/3rdparty/oauth-php/library/store/OAuthStoreMySQLi.php deleted file mode 100644 index 09d71bfba5..0000000000 --- a/3rdparty/oauth-php/library/store/OAuthStoreMySQLi.php +++ /dev/null @@ -1,306 +0,0 @@ - Based on code by Marc Worrell - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/* - * Modified from OAuthStoreMySQL to support MySQLi - */ - -require_once dirname(__FILE__) . '/OAuthStoreMySQL.php'; - - -class OAuthStoreMySQLi extends OAuthStoreMySQL -{ - - public function install() { - $sql = file_get_contents(dirname(__FILE__) . '/mysql/mysql.sql'); - $ps = explode('#--SPLIT--', $sql); - - foreach ($ps as $p) - { - $p = preg_replace('/^\s*#.*$/m', '', $p); - - $this->query($p); - $this->sql_errcheck($p); - } - } - - /** - * Construct the OAuthStoreMySQLi. - * In the options you have to supply either: - * - server, username, password and database (for a mysqli_connect) - * - conn (for the connection to be used) - * - * @param array options - */ - function __construct ( $options = array() ) - { - if (isset($options['conn'])) - { - $this->conn = $options['conn']; - } - else - { - if (isset($options['server'])) - { - $server = $options['server']; - $username = $options['username']; - - if (isset($options['password'])) - { - $this->conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username, $options['password'])); - } - else - { - $this->conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect($server, $username)); - } - } - else - { - // Try the default mysql connect - $this->conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect()); - } - - if ($this->conn === false) - { - throw new OAuthException2('Could not connect to MySQL database: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))); - } - - if (isset($options['database'])) - { - /* TODO: security. mysqli_ doesn't seem to have an escape identifier function. - $escapeddb = mysqli_real_escape_string($options['database']); - if (!((bool)mysqli_query( $this->conn, "USE `$escapeddb`" ))) - { - $this->sql_errcheck(); - }*/ - } - $this->query('set character set utf8'); - } - } - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - */ - protected function query ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = mysqli_query( $this->conn, $sql))) - { - $this->sql_errcheck($sql); - } - if (!is_bool($res)) - { - ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false); - } - } - - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_all_assoc ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = mysqli_query( $this->conn, $sql))) - { - $this->sql_errcheck($sql); - } - $rs = array(); - while ($row = mysqli_fetch_assoc($res)) - { - $rs[] = $row; - } - ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false); - return $rs; - } - - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_row_assoc ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = mysqli_query( $this->conn, $sql))) - { - $this->sql_errcheck($sql); - } - if ($row = mysqli_fetch_assoc($res)) - { - $rs = $row; - } - else - { - $rs = false; - } - ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false); - return $rs; - } - - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_row ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = mysqli_query( $this->conn, $sql))) - { - $this->sql_errcheck($sql); - } - if ($row = mysqli_fetch_array($res)) - { - $rs = $row; - } - else - { - $rs = false; - } - ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false); - return $rs; - } - - - /** - * Perform a query, return the first column of the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return mixed - */ - protected function query_one ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = mysqli_query( $this->conn, $sql))) - { - $this->sql_errcheck($sql); - } - if ($row = mysqli_fetch_assoc($res)) - { - $val = array_pop($row); - } - else - { - $val = false; - } - ((mysqli_free_result($res) || (is_object($res) && (get_class($res) == "mysqli_result"))) ? true : false); - return $val; - } - - - /** - * Return the number of rows affected in the last query - */ - protected function query_affected_rows () - { - return mysqli_affected_rows($this->conn); - } - - - /** - * Return the id of the last inserted row - * - * @return int - */ - protected function query_insert_id () - { - return ((is_null($___mysqli_res = mysqli_insert_id($this->conn))) ? false : $___mysqli_res); - } - - - protected function sql_printf ( $args ) - { - $sql = array_shift($args); - if (count($args) == 1 && is_array($args[0])) - { - $args = $args[0]; - } - $args = array_map(array($this, 'sql_escape_string'), $args); - return vsprintf($sql, $args); - } - - - protected function sql_escape_string ( $s ) - { - if (is_string($s)) - { - return mysqli_real_escape_string( $this->conn, $s); - } - else if (is_null($s)) - { - return NULL; - } - else if (is_bool($s)) - { - return intval($s); - } - else if (is_int($s) || is_float($s)) - { - return $s; - } - else - { - return mysqli_real_escape_string( $this->conn, strval($s)); - } - } - - - protected function sql_errcheck ( $sql ) - { - if (((is_object($this->conn)) ? mysqli_errno($this->conn) : (($___mysqli_res = mysqli_connect_errno()) ? $___mysqli_res : false))) - { - $msg = "SQL Error in OAuthStoreMySQL: ".((is_object($this->conn)) ? mysqli_error($this->conn) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false))."\n\n" . $sql; - throw new OAuthException2($msg); - } - } -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreOracle.php b/3rdparty/oauth-php/library/store/OAuthStoreOracle.php deleted file mode 100644 index 554792faa6..0000000000 --- a/3rdparty/oauth-php/library/store/OAuthStoreOracle.php +++ /dev/null @@ -1,1536 +0,0 @@ - - * @date Aug 6, 2010 - * - * The MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php'; - -abstract class OAuthStoreOracle extends OAuthStoreAbstract { - /** - * Maximum delta a timestamp may be off from a previous timestamp. - * Allows multiple consumers with some clock skew to work with the same token. - * Unit is seconds, default max skew is 10 minutes. - */ - protected $max_timestamp_skew = MAX_TIMESTAMP_SKEW; - - /** - * Default ttl for request tokens - */ - protected $max_request_token_ttl = MAX_REQUEST_TOKEN_TIME; - - - /** - * Construct the OAuthStoreMySQL. - * In the options you have to supply either: - * - server, username, password and database (for a mysql_connect) - * - conn (for the connection to be used) - * - * @param array options - */ - function __construct ( $options = array() ) { - if (isset($options['conn'])) { - $this->conn = $options['conn']; - } - else { - $this->conn=oci_connect(DBUSER,DBPASSWORD,DBHOST); - - if ($this->conn === false) { - throw new OAuthException2('Could not connect to database'); - } - - // $this->query('set character set utf8'); - } - } - - /** - * Find stored credentials for the consumer key and token. Used by an OAuth server - * when verifying an OAuth request. - * - * @param string consumer_key - * @param string token - * @param string token_type false, 'request' or 'access' - * @exception OAuthException2 when no secrets where found - * @return array assoc (consumer_secret, token_secret, osr_id, ost_id, user_id) - */ - public function getSecretsForVerify ($consumer_key, $token, $token_type = 'access' ) { - $sql = "BEGIN SP_GET_SECRETS_FOR_VERIFY(:P_CONSUMER_KEY, :P_TOKEN, :P_TOKEN_TYPE, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_TOKEN_TYPE', $token_type, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $getSecretsForVerifyList, null, null, OCI_FETCHSTATEMENT_BY_ROW); - - $rs =$getSecretsForVerifyList; - if (empty($rs)) { - throw new OAuthException2('The consumer_key "'.$consumer_key.'" token "'.$token.'" combination does not exist or is not enabled.'); - } - - return $rs[0]; - } - - - /** - * Find the server details for signing a request, always looks for an access token. - * The returned credentials depend on which local user is making the request. - * - * The consumer_key must belong to the user or be public (user id is null) - * - * For signing we need all of the following: - * - * consumer_key consumer key associated with the server - * consumer_secret consumer secret associated with this server - * token access token associated with this server - * token_secret secret for the access token - * signature_methods signing methods supported by the server (array) - * - * @todo filter on token type (we should know how and with what to sign this request, and there might be old access tokens) - * @param string uri uri of the server - * @param int user_id id of the logged on user - * @param string name (optional) name of the token (case sensitive) - * @exception OAuthException2 when no credentials found - * @return array - */ - public function getSecretsForSignature ( $uri, $user_id, $name = '' ) { - // Find a consumer key and token for the given uri - $ps = parse_url($uri); - $host = isset($ps['host']) ? $ps['host'] : 'localhost'; - $path = isset($ps['path']) ? $ps['path'] : ''; - - if (empty($path) || substr($path, -1) != '/') { - $path .= '/'; - } - // - $sql = "BEGIN SP_GET_SECRETS_FOR_SIGNATURE(:P_HOST, :P_PATH, :P_USER_ID, :P_NAME, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_HOST', $host, 255); - oci_bind_by_name($stmt, ':P_PATH', $path, 255); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 20); - oci_bind_by_name($stmt, ':P_NAME', $name, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $getSecretsForSignatureList, null, null, OCI_FETCHSTATEMENT_BY_ROW); - $secrets = $getSecretsForSignatureList[0]; - // - // The owner of the consumer_key is either the user or nobody (public consumer key) - /*$secrets = $this->query_row_assoc(' - SELECT ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - oct_token as token, - oct_token_secret as token_secret, - ocr_signature_methods as signature_methods - FROM oauth_consumer_registry - JOIN oauth_consumer_token ON oct_ocr_id_ref = ocr_id - WHERE ocr_server_uri_host = \'%s\' - AND ocr_server_uri_path = LEFT(\'%s\', LENGTH(ocr_server_uri_path)) - AND (ocr_usa_id_ref = %s OR ocr_usa_id_ref IS NULL) - AND oct_usa_id_ref = %d - AND oct_token_type = \'access\' - AND oct_name = \'%s\' - AND oct_token_ttl >= NOW() - ORDER BY ocr_usa_id_ref DESC, ocr_consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC - LIMIT 0,1 - ', $host, $path, $user_id, $user_id, $name - ); - */ - if (empty($secrets)) { - throw new OAuthException2('No server tokens available for '.$uri); - } - $secrets['signature_methods'] = explode(',', $secrets['signature_methods']); - return $secrets; - } - - - /** - * Get the token and token secret we obtained from a server. - * - * @param string consumer_key - * @param string token - * @param string token_type - * @param int user_id the user owning the token - * @param string name optional name for a named token - * @exception OAuthException2 when no credentials found - * @return array - */ - public function getServerTokenSecrets ($consumer_key,$token,$token_type,$user_id,$name = '') - { - if ($token_type != 'request' && $token_type != 'access') - { - throw new OAuthException2('Unkown token type "'.$token_type.'", must be either "request" or "access"'); - } - // - $sql = "BEGIN SP_GET_SERVER_TOKEN_SECRETS(:P_CONSUMER_KEY, :P_TOKEN, :P_TOKEN_TYPE, :P_USER_ID, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_TOKEN_TYPE', $token_type, 20); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $getServerTokenSecretsList, null, null, OCI_FETCHSTATEMENT_BY_ROW); - $r=$getServerTokenSecretsList[0]; - // - // Take the most recent token of the given type - /*$r = $this->query_row_assoc(' - SELECT ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - oct_token as token, - oct_token_secret as token_secret, - oct_name as token_name, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri, - IF(oct_token_ttl >= \'9999-12-31\', NULL, UNIX_TIMESTAMP(oct_token_ttl) - UNIX_TIMESTAMP(NOW())) as token_ttl - FROM oauth_consumer_registry - JOIN oauth_consumer_token - ON oct_ocr_id_ref = ocr_id - WHERE ocr_consumer_key = \'%s\' - AND oct_token_type = \'%s\' - AND oct_token = \'%s\' - AND oct_usa_id_ref = %d - AND oct_token_ttl >= NOW() - ', $consumer_key, $token_type, $token, $user_id - );*/ - - if (empty($r)) - { - throw new OAuthException2('Could not find a "'.$token_type.'" token for consumer "'.$consumer_key.'" and user '.$user_id); - } - if (isset($r['signature_methods']) && !empty($r['signature_methods'])) - { - $r['signature_methods'] = explode(',',$r['signature_methods']); - } - else - { - $r['signature_methods'] = array(); - } - return $r; - } - - - /** - * Add a request token we obtained from a server. - * - * @todo remove old tokens for this user and this ocr_id - * @param string consumer_key key of the server in the consumer registry - * @param string token_type one of 'request' or 'access' - * @param string token - * @param string token_secret - * @param int user_id the user owning the token - * @param array options extra options, name and token_ttl - * @exception OAuthException2 when server is not known - * @exception OAuthException2 when we received a duplicate token - */ - public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) - { - if ($token_type != 'request' && $token_type != 'access') - { - throw new OAuthException2('Unknown token type "'.$token_type.'", must be either "request" or "access"'); - } - - // Maximum time to live for this token - if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) - { - $ttl = intval($options['token_ttl']); - } - else if ($token_type == 'request') - { - $ttl =intval($this->max_request_token_ttl); - } - else - { - $ttl = NULL; - } - - - - // Named tokens, unique per user/consumer key - if (isset($options['name']) && $options['name'] != '') - { - $name = $options['name']; - } - else - { - $name = ''; - } - // - $sql = "BEGIN SP_ADD_SERVER_TOKEN(:P_CONSUMER_KEY, :P_USER_ID, :P_NAME, :P_TOKEN_TYPE, :P_TOKEN, :P_TOKEN_SECRET, :P_TOKEN_INTERVAL_IN_SEC, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_NAME', $name, 255); - oci_bind_by_name($stmt, ':P_TOKEN_TYPE', $token_type, 20); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_TOKEN_SECRET', $token_secret, 255); - oci_bind_by_name($stmt, ':P_TOKEN_INTERVAL_IN_SEC', $ttl, 40); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - // - - - - if (!$result) - { - throw new OAuthException2('Received duplicate token "'.$token.'" for the same consumer_key "'.$consumer_key.'"'); - } - } - - - /** - * Delete a server key. This removes access to that site. - * - * @param string consumer_key - * @param int user_id user registering this server - * @param boolean user_is_admin - */ - public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) - { - - $sql = "BEGIN SP_DELETE_SERVER(:P_CONSUMER_KEY, :P_USER_ID, :P_USER_IS_ADMIN, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - } - - - /** - * Get a server from the consumer registry using the consumer key - * - * @param string consumer_key - * @param int user_id - * @param boolean user_is_admin (optional) - * @exception OAuthException2 when server is not found - * @return array - */ - public function getServer ( $consumer_key, $user_id, $user_is_admin = false ) - { - - // - $sql = "BEGIN SP_GET_SERVER(:P_CONSUMER_KEY, :P_USER_ID, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $getServerList, null, null, OCI_FETCHSTATEMENT_BY_ROW); - $r = $getServerList; - // - if (empty($r)) - { - throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" has been registered (for this user)'); - } - - if (isset($r['signature_methods']) && !empty($r['signature_methods'])) - { - $r['signature_methods'] = explode(',',$r['signature_methods']); - } - else - { - $r['signature_methods'] = array(); - } - return $r; - } - - - - /** - * Find the server details that might be used for a request - * - * The consumer_key must belong to the user or be public (user id is null) - * - * @param string uri uri of the server - * @param int user_id id of the logged on user - * @exception OAuthException2 when no credentials found - * @return array - */ - public function getServerForUri ( $uri, $user_id ) - { - // Find a consumer key and token for the given uri - $ps = parse_url($uri); - $host = isset($ps['host']) ? $ps['host'] : 'localhost'; - $path = isset($ps['path']) ? $ps['path'] : ''; - - if (empty($path) || substr($path, -1) != '/') - { - $path .= '/'; - } - - - // - $sql = "BEGIN SP_GET_SERVER_FOR_URI(:P_HOST, :P_PATH,:P_USER_ID, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_HOST', $host, 255); - oci_bind_by_name($stmt, ':P_PATH', $path, 255); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $getServerForUriList, null, null, OCI_FETCHSTATEMENT_BY_ROW); - $server = $getServerForUriList; - // - if (empty($server)) - { - throw new OAuthException2('No server available for '.$uri); - } - $server['signature_methods'] = explode(',', $server['signature_methods']); - return $server; - } - - - /** - * Get a list of all server token this user has access to. - * - * @param int usr_id - * @return array - */ - public function listServerTokens ( $user_id ) - { - - $sql = "BEGIN SP_LIST_SERVER_TOKENS(:P_USER_ID, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $listServerTokensList, null, null, OCI_FETCHSTATEMENT_BY_ROW); - $ts = $listServerTokensList; - return $ts; - } - - - /** - * Count how many tokens we have for the given server - * - * @param string consumer_key - * @return int - */ - public function countServerTokens ( $consumer_key ) - { - - // - $count =0; - $sql = "BEGIN SP_COUNT_SERVICE_TOKENS(:P_CONSUMER_KEY, :P_COUNT, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_COUNT', $count, 40); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - // - return $count; - } - - - /** - * Get a specific server token for the given user - * - * @param string consumer_key - * @param string token - * @param int user_id - * @exception OAuthException2 when no such token found - * @return array - */ - public function getServerToken ( $consumer_key, $token, $user_id ) - { - - $sql = "BEGIN SP_GET_SERVER_TOKEN(:P_CONSUMER_KEY, :P_USER_ID,:P_TOKEN, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $getServerTokenList, null, null, OCI_FETCHSTATEMENT_BY_ROW); - $ts = $getServerTokenList; - // - - if (empty($ts)) - { - throw new OAuthException2('No such consumer key ('.$consumer_key.') and token ('.$token.') combination for user "'.$user_id.'"'); - } - return $ts; - } - - - /** - * Delete a token we obtained from a server. - * - * @param string consumer_key - * @param string token - * @param int user_id - * @param boolean user_is_admin - */ - public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) - { - - // - $sql = "BEGIN SP_DELETE_SERVER_TOKEN(:P_CONSUMER_KEY, :P_USER_ID,:P_TOKEN, :P_USER_IS_ADMIN, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 40); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - // - - } - - - /** - * Set the ttl of a server access token. This is done when the - * server receives a valid request with a xoauth_token_ttl parameter in it. - * - * @param string consumer_key - * @param string token - * @param int token_ttl - */ - public function setServerTokenTtl ( $consumer_key, $token, $token_ttl ) - { - if ($token_ttl <= 0) - { - // Immediate delete when the token is past its ttl - $this->deleteServerToken($consumer_key, $token, 0, true); - } - else - { - // Set maximum time to live for this token - - // - $sql = "BEGIN SP_SET_SERVER_TOKEN_TTL(:P_TOKEN_TTL, :P_CONSUMER_KEY, :P_TOKEN, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_TOKEN_TTL', $token_ttl, 40); - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - // - } - } - - - /** - * Get a list of all consumers from the consumer registry. - * The consumer keys belong to the user or are public (user id is null) - * - * @param string q query term - * @param int user_id - * @return array - */ - public function listServers ( $q = '', $user_id ) - { - $q = trim(str_replace('%', '', $q)); - $args = array(); - - - // - $sql = "BEGIN SP_LIST_SERVERS(:P_Q, :P_USER_ID, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_Q', $q, 255); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $listServersList, null, null, OCI_FETCHSTATEMENT_BY_ROW); - $servers = $listServersList; - // - - return $servers; - } - - - /** - * Register or update a server for our site (we will be the consumer) - * - * (This is the registry at the consumers, registering servers ;-) ) - * - * @param array server - * @param int user_id user registering this server - * @param boolean user_is_admin - * @exception OAuthException2 when fields are missing or on duplicate consumer_key - * @return consumer_key - */ - public function updateServer ( $server, $user_id, $user_is_admin = false ) { - foreach (array('consumer_key', 'server_uri') as $f) { - if (empty($server[$f])) { - throw new OAuthException2('The field "'.$f.'" must be set and non empty'); - } - } - $parts = parse_url($server['server_uri']); - $host = (isset($parts['host']) ? $parts['host'] : 'localhost'); - $path = (isset($parts['path']) ? $parts['path'] : '/'); - - if (isset($server['signature_methods'])) { - if (is_array($server['signature_methods'])) { - $server['signature_methods'] = strtoupper(implode(',', $server['signature_methods'])); - } - } - else { - $server['signature_methods'] = ''; - } - // When the user is an admin, then the user can update the user_id of this record - if ($user_is_admin && array_key_exists('user_id', $server)) { - $flag=1; - } - if($flag) { - if (is_null($server['user_id'])) { - $ocr_usa_id_ref= NULL; - } - else { - $ocr_usa_id_ref = $server['user_id']; - } - } - else { - $flag=0; - $ocr_usa_id_ref=$user_id; - } - //sp - $sql = "BEGIN SP_UPDATE_SERVER(:P_CONSUMER_KEY, :P_USER_ID, :P_OCR_ID, :P_USER_IS_ADMIN, - :P_OCR_CONSUMER_SECRET, :P_OCR_SERVER_URI, :P_OCR_SERVER_URI_HOST, :P_OCR_SERVER_URI_PATH, - :P_OCR_REQUEST_TOKEN_URI, :P_OCR_AUTHORIZE_URI, :P_OCR_ACCESS_TOKEN_URI, :P_OCR_SIGNATURE_METHODS, - :P_OCR_USA_ID_REF, :P_UPDATE_P_OCR_USA_ID_REF_FLAG, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - $server['request_token_uri'] = isset($server['request_token_uri']) ? $server['request_token_uri'] : ''; - $server['authorize_uri'] = isset($server['authorize_uri']) ? $server['authorize_uri'] : ''; - $server['access_token_uri'] = isset($server['access_token_uri']) ? $server['access_token_uri'] : ''; - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $server['consumer_key'], 255); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_OCR_ID', $server['id'], 40); - oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 40); - oci_bind_by_name($stmt, ':P_OCR_CONSUMER_SECRET', $server['consumer_secret'], 255); - oci_bind_by_name($stmt, ':P_OCR_SERVER_URI', $server['server_uri'], 255); - oci_bind_by_name($stmt, ':P_OCR_SERVER_URI_HOST', strtolower($host), 255); - oci_bind_by_name($stmt, ':P_OCR_SERVER_URI_PATH', $path, 255); - oci_bind_by_name($stmt, ':P_OCR_REQUEST_TOKEN_URI', $server['request_token_uri'], 255); - oci_bind_by_name($stmt, ':P_OCR_AUTHORIZE_URI', $server['authorize_uri'], 255); - oci_bind_by_name($stmt, ':P_OCR_ACCESS_TOKEN_URI', $server['access_token_uri'], 255); - oci_bind_by_name($stmt, ':P_OCR_SIGNATURE_METHODS', $server['signature_methods'], 255); - oci_bind_by_name($stmt, ':P_OCR_USA_ID_REF', $ocr_usa_id_ref, 40); - oci_bind_by_name($stmt, ':P_UPDATE_P_OCR_USA_ID_REF_FLAG', $flag, 40); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - - return $server['consumer_key']; - } - - /** - * Insert/update a new consumer with this server (we will be the server) - * When this is a new consumer, then also generate the consumer key and secret. - * Never updates the consumer key and secret. - * When the id is set, then the key and secret must correspond to the entry - * being updated. - * - * (This is the registry at the server, registering consumers ;-) ) - * - * @param array consumer - * @param int user_id user registering this consumer - * @param boolean user_is_admin - * @return string consumer key - */ - public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) { - $consumer_key = $this->generateKey(true); - $consumer_secret = $this->generateKey(); - - $consumer['callback_uri'] = isset($consumer['callback_uri'])? $consumer['callback_uri']: ''; - $consumer['application_uri'] = isset($consumer['application_uri'])? $consumer['application_uri']: ''; - $consumer['application_title'] = isset($consumer['application_title'])? $consumer['application_title']: ''; - $consumer['application_descr'] = isset($consumer['application_descr'])? $consumer['application_descr']: ''; - $consumer['application_notes'] = isset($consumer['application_notes'])? $consumer['application_notes']: ''; - $consumer['application_type'] = isset($consumer['application_type'])? $consumer['application_type']: ''; - $consumer['application_commercial'] = isset($consumer['application_commercial'])?$consumer['application_commercial']:0; - - //sp - $sql = "BEGIN SP_UPDATE_CONSUMER(:P_OSR_USA_ID_REF, :P_OSR_CONSUMER_KEY, :P_OSR_CONSUMER_SECRET, :P_OSR_REQUESTER_NAME, :P_OSR_REQUESTER_EMAIL, :P_OSR_CALLBACK_URI, :P_OSR_APPLICATION_URI, :P_OSR_APPLICATION_TITLE , :P_OSR_APPLICATION_DESCR, :P_OSR_APPLICATION_NOTES, :P_OSR_APPLICATION_TYPE, :P_OSR_APPLICATION_COMMERCIAL, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_OSR_USA_ID_REF', $user_id, 40); - oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_OSR_CONSUMER_SECRET', $consumer_secret, 255); - oci_bind_by_name($stmt, ':P_OSR_REQUESTER_NAME', $consumer['requester_name'], 255); - oci_bind_by_name($stmt, ':P_OSR_REQUESTER_EMAIL', $consumer['requester_email'], 255); - oci_bind_by_name($stmt, ':P_OSR_CALLBACK_URI', $consumer['callback_uri'], 255); - oci_bind_by_name($stmt, ':P_OSR_APPLICATION_URI', $consumer['application_uri'], 255); - oci_bind_by_name($stmt, ':P_OSR_APPLICATION_TITLE', $consumer['application_title'], 255); - oci_bind_by_name($stmt, ':P_OSR_APPLICATION_DESCR', $consumer['application_descr'], 255); - oci_bind_by_name($stmt, ':P_OSR_APPLICATION_NOTES', $consumer['application_notes'], 255); - oci_bind_by_name($stmt, ':P_OSR_APPLICATION_TYPE', $consumer['application_type'], 255); - oci_bind_by_name($stmt, ':P_OSR_APPLICATION_COMMERCIAL', $consumer['application_commercial'], 40); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - echo $result; - return $consumer_key; - } - - - - /** - * Delete a consumer key. This removes access to our site for all applications using this key. - * - * @param string consumer_key - * @param int user_id user registering this server - * @param boolean user_is_admin - */ - public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) - { - - // - $sql = "BEGIN SP_DELETE_CONSUMER(:P_CONSUMER_KEY, :P_USER_ID, :P_USER_IS_ADMIN, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 40); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - // - } - - - - /** - * Fetch a consumer of this server, by consumer_key. - * - * @param string consumer_key - * @param int user_id - * @param boolean user_is_admin (optional) - * @exception OAuthException2 when consumer not found - * @return array - */ - public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { - - $sql = "BEGIN SP_GET_CONSUMER(:P_CONSUMER_KEY, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $getConsumerList, null, null, OCI_FETCHSTATEMENT_BY_ROW); - - $consumer = $getConsumerList; - - if (!is_array($consumer)) { - throw new OAuthException2('No consumer with consumer_key "'.$consumer_key.'"'); - } - - $c = array(); - foreach ($consumer as $key => $value) { - $c[substr($key, 4)] = $value; - } - $c['user_id'] = $c['usa_id_ref']; - - if (!$user_is_admin && !empty($c['user_id']) && $c['user_id'] != $user_id) { - throw new OAuthException2('No access to the consumer information for consumer_key "'.$consumer_key.'"'); - } - return $c; - } - - - /** - * Fetch the static consumer key for this provider. The user for the static consumer - * key is NULL (no user, shared key). If the key did not exist then the key is created. - * - * @return string - */ - public function getConsumerStatic () - { - - // - $sql = "BEGIN SP_GET_CONSUMER_STATIC_SELECT(:P_OSR_CONSUMER_KEY, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $consumer, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - - if (empty($consumer)) - { - $consumer_key = 'sc-'.$this->generateKey(true); - - $sql = "BEGIN SP_CONSUMER_STATIC_SAVE(:P_OSR_CONSUMER_KEY, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - - - // Just make sure that if the consumer key is truncated that we get the truncated string - $consumer = $consumer_key; - } - return $consumer; - } - - - /** - * Add an unautorized request token to our server. - * - * @param string consumer_key - * @param array options (eg. token_ttl) - * @return array (token, token_secret) - */ - public function addConsumerRequestToken ( $consumer_key, $options = array() ) - { - $token = $this->generateKey(true); - $secret = $this->generateKey(); - - - if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) - { - $ttl = intval($options['token_ttl']); - } - else - { - $ttl = $this->max_request_token_ttl; - } - - if (!isset($options['oauth_callback'])) { - // 1.0a Compatibility : store callback url associated with request token - $options['oauth_callback']='oob'; - } - $options_oauth_callback =$options['oauth_callback']; - $sql = "BEGIN SP_ADD_CONSUMER_REQUEST_TOKEN(:P_TOKEN_TTL, :P_CONSUMER_KEY, :P_TOKEN, :P_TOKEN_SECRET, :P_CALLBACK_URL, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_TOKEN_TTL', $ttl, 20); - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_TOKEN_SECRET', $secret, 255); - oci_bind_by_name($stmt, ':P_CALLBACK_URL', $options_oauth_callback, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - - - $returnArray= array('token'=>$token, 'token_secret'=>$secret, 'token_ttl'=>$ttl); - return $returnArray; - } - - - /** - * Fetch the consumer request token, by request token. - * - * @param string token - * @return array token and consumer details - */ - public function getConsumerRequestToken ( $token ) - { - - $sql = "BEGIN SP_GET_CONSUMER_REQUEST_TOKEN(:P_TOKEN, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - - oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW); - - return $rs[0]; - } - - - /** - * Delete a consumer token. The token must be a request or authorized token. - * - * @param string token - */ - public function deleteConsumerRequestToken ( $token ) - { - - $sql = "BEGIN SP_DEL_CONSUMER_REQUEST_TOKEN(:P_TOKEN, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Execute the statement - oci_execute($stmt); - } - - - /** - * Upgrade a request token to be an authorized request token. - * - * @param string token - * @param int user_id user authorizing the token - * @param string referrer_host used to set the referrer host for this token, for user feedback - */ - public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) - { - // 1.0a Compatibility : create a token verifier - $verifier = substr(md5(rand()),0,10); - - $sql = "BEGIN SP_AUTH_CONSUMER_REQ_TOKEN(:P_USER_ID, :P_REFERRER_HOST, :P_VERIFIER, :P_TOKEN, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255); - oci_bind_by_name($stmt, ':P_REFERRER_HOST', $referrer_host, 255); - oci_bind_by_name($stmt, ':P_VERIFIER', $verifier, 255); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - - //Execute the statement - oci_execute($stmt); - - return $verifier; - } - - - /** - * Count the consumer access tokens for the given consumer. - * - * @param string consumer_key - * @return int - */ - public function countConsumerAccessTokens ( $consumer_key ) - { - /*$count = $this->query_one(' - SELECT COUNT(ost_id) - FROM oauth_server_token - JOIN oauth_server_registry - ON ost_osr_id_ref = osr_id - WHERE ost_token_type = \'access\' - AND osr_consumer_key = \'%s\' - AND ost_token_ttl >= NOW() - ', $consumer_key); - */ - $sql = "BEGIN SP_COUNT_CONSUMER_ACCESS_TOKEN(:P_CONSUMER_KEY, :P_COUNT, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_COUNT', $count, 20); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - - //Execute the statement - oci_execute($stmt); - - return $count; - } - - - /** - * Exchange an authorized request token for new access token. - * - * @param string token - * @param array options options for the token, token_ttl - * @exception OAuthException2 when token could not be exchanged - * @return array (token, token_secret) - */ - public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) - { - $new_token = $this->generateKey(true); - $new_secret = $this->generateKey(); - - $sql = "BEGIN SP_EXCH_CONS_REQ_FOR_ACC_TOKEN(:P_TOKEN_TTL, :P_NEW_TOKEN, :P_TOKEN, :P_TOKEN_SECRET, :P_VERIFIER, :P_OUT_TOKEN_TTL, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_TOKEN_TTL', $options['token_ttl'], 255); - oci_bind_by_name($stmt, ':P_NEW_TOKEN', $new_token, 255); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_TOKEN_SECRET', $new_secret, 255); - oci_bind_by_name($stmt, ':P_VERIFIER', $options['verifier'], 255); - oci_bind_by_name($stmt, ':P_OUT_TOKEN_TTL', $ttl, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - - //Execute the statement - oci_execute($stmt); - - $ret = array('token' => $new_token, 'token_secret' => $new_secret); - if (is_numeric($ttl)) - { - $ret['token_ttl'] = intval($ttl); - } - return $ret; - } - - - /** - * Fetch the consumer access token, by access token. - * - * @param string token - * @param int user_id - * @exception OAuthException2 when token is not found - * @return array token and consumer details - */ - public function getConsumerAccessToken ( $token, $user_id ) - { - - $sql = "BEGIN SP_GET_CONSUMER_ACCESS_TOKEN(:P_USER_ID, :P_TOKEN, :P_ROWS :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_USER_ID',$user_id, 255); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW); - if (empty($rs)) - { - throw new OAuthException2('No server_token "'.$token.'" for user "'.$user_id.'"'); - } - return $rs; - } - - - /** - * Delete a consumer access token. - * - * @param string token - * @param int user_id - * @param boolean user_is_admin - */ - public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) - { - /*if ($user_is_admin) - { - $this->query(' - DELETE FROM oauth_server_token - WHERE ost_token = \'%s\' - AND ost_token_type = \'access\' - ', $token); - } - else - { - $this->query(' - DELETE FROM oauth_server_token - WHERE ost_token = \'%s\' - AND ost_token_type = \'access\' - AND ost_usa_id_ref = %d - ', $token, $user_id); - }*/ - $sql = "BEGIN SP_DEL_CONSUMER_ACCESS_TOKEN(:P_USER_ID, :P_TOKEN, :P_USER_IS_ADMIN, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_USER_IS_ADMIN', $user_is_admin, 20); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - - //Execute the statement - oci_execute($stmt); - } - - - /** - * Set the ttl of a consumer access token. This is done when the - * server receives a valid request with a xoauth_token_ttl parameter in it. - * - * @param string token - * @param int ttl - */ - public function setConsumerAccessTokenTtl ( $token, $token_ttl ) - { - if ($token_ttl <= 0) - { - // Immediate delete when the token is past its ttl - $this->deleteConsumerAccessToken($token, 0, true); - } - else - { - // Set maximum time to live for this token - - - $sql = "BEGIN SP_SET_CONSUMER_ACC_TOKEN_TTL(:P_TOKEN, :P_TOKEN_TTL, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_TOKEN_TTL', $token_ttl, 20); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - - //Execute the statement - oci_execute($stmt); - } - } - - - /** - * Fetch a list of all consumer keys, secrets etc. - * Returns the public (user_id is null) and the keys owned by the user - * - * @param int user_id - * @return array - */ - public function listConsumers ( $user_id ) - { - - $sql = "BEGIN SP_LIST_CONSUMERS(:P_USER_ID, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW); - - return $rs; - } - - /** - * List of all registered applications. Data returned has not sensitive - * information and therefore is suitable for public displaying. - * - * @param int $begin - * @param int $total - * @return array - */ - public function listConsumerApplications($begin = 0, $total = 25) - { - // TODO - return array(); - } - - /** - * Fetch a list of all consumer tokens accessing the account of the given user. - * - * @param int user_id - * @return array - */ - public function listConsumerTokens ( $user_id ) - { - - $sql = "BEGIN SP_LIST_CONSUMER_TOKENS(:P_USER_ID, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_USER_ID', $user_id, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW); - - return $rs; - } - - - /** - * Check an nonce/timestamp combination. Clears any nonce combinations - * that are older than the one received. - * - * @param string consumer_key - * @param string token - * @param int timestamp - * @param string nonce - * @exception OAuthException2 thrown when the timestamp is not in sequence or nonce is not unique - */ - public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) - { - - $sql = "BEGIN SP_CHECK_SERVER_NONCE(:P_CONSUMER_KEY, :P_TOKEN, :P_TIMESTAMP, :P_MAX_TIMESTAMP_SKEW, :P_NONCE, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_CONSUMER_KEY', $consumer_key, 255); - oci_bind_by_name($stmt, ':P_TOKEN', $token, 255); - oci_bind_by_name($stmt, ':P_TIMESTAMP', $timestamp, 255); - oci_bind_by_name($stmt, ':P_MAX_TIMESTAMP_SKEW', $this->max_timestamp_skew, 20); - oci_bind_by_name($stmt, ':P_NONCE', $nonce, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - - //Execute the statement - oci_execute($stmt); - - } - - - /** - * Add an entry to the log table - * - * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token) - * @param string received - * @param string sent - * @param string base_string - * @param string notes - * @param int (optional) user_id - */ - public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) - { - $args = array(); - $ps = array(); - foreach ($keys as $key => $value) - { - $args[] = $value; - $ps[] = "olg_$key = '%s'"; - } - - if (!empty($_SERVER['REMOTE_ADDR'])) - { - $remote_ip = $_SERVER['REMOTE_ADDR']; - } - else if (!empty($_SERVER['REMOTE_IP'])) - { - $remote_ip = $_SERVER['REMOTE_IP']; - } - else - { - $remote_ip = '0.0.0.0'; - } - - // Build the SQL - $olg_received = $this->makeUTF8($received); - $olg_sent = $this->makeUTF8($sent); - $olg_base_string = $base_string; - $olg_notes = $this->makeUTF8($notes); - $olg_usa_id_ref = $user_id; - $olg_remote_ip = $remote_ip; - - - - $sql = "BEGIN SP_ADD_LOG(:P_RECEIVED, :P_SENT, :P_BASE_STRING, :P_NOTES, :P_USA_ID_REF, :P_REMOTE_IP, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_RECEIVED', $olg_received, 255); - oci_bind_by_name($stmt, ':P_SENT', $olg_sent, 255); - oci_bind_by_name($stmt, ':P_BASE_STRING', $olg_base_string, 255); - oci_bind_by_name($stmt, ':P_NOTES', $olg_notes, 255); - oci_bind_by_name($stmt, ':P_USA_ID_REF', $olg_usa_id_ref, 255); - oci_bind_by_name($stmt, ':P_REMOTE_IP', $olg_remote_ip, 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - - //Execute the statement - oci_execute($stmt); - } - - - /** - * Get a page of entries from the log. Returns the last 100 records - * matching the options given. - * - * @param array options - * @param int user_id current user - * @return array log records - */ - public function listLog ( $options, $user_id ) - { - - if (empty($options)) - { - $optionsFlag=NULL; - - } - else - { - $optionsFlag=1; - - } - - $sql = "BEGIN SP_LIST_LOG(:P_OPTION_FLAG, :P_USA_ID, :P_OSR_CONSUMER_KEY, :P_OCR_CONSUMER_KEY, :P_OST_TOKEN, :P_OCT_TOKEN, :P_ROWS, :P_RESULT); END;"; - - // parse sql - $stmt = oci_parse($this->conn, $sql) or die ('Can not parse query'); - - // Bind In and Out Variables - oci_bind_by_name($stmt, ':P_OPTION_FLAG', $optionsFlag, 255); - oci_bind_by_name($stmt, ':P_USA_ID', $user_id, 40); - oci_bind_by_name($stmt, ':P_OSR_CONSUMER_KEY', $options['osr_consumer_key'], 255); - oci_bind_by_name($stmt, ':P_OCR_CONSUMER_KEY', $options['ocr_consumer_key'], 255); - oci_bind_by_name($stmt, ':P_OST_TOKEN', $options['ost_token'], 255); - oci_bind_by_name($stmt, ':P_OCT_TOKEN', $options['oct_token'], 255); - oci_bind_by_name($stmt, ':P_RESULT', $result, 20); - - //Bind the ref cursor - $p_row = oci_new_cursor($this->conn); - oci_bind_by_name($stmt, ':P_ROWS', $p_row, -1, OCI_B_CURSOR); - - //Execute the statement - oci_execute($stmt); - - // treat the ref cursor as a statement resource - oci_execute($p_row, OCI_DEFAULT); - oci_fetch_all($p_row, $rs, null, null, OCI_FETCHSTATEMENT_BY_ROW); - - return $rs; - } - - /** - * Initialise the database - */ - public function install () - { - require_once dirname(__FILE__) . '/oracle/install.php'; - } -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStorePDO.php b/3rdparty/oauth-php/library/store/OAuthStorePDO.php deleted file mode 100644 index 821d79b994..0000000000 --- a/3rdparty/oauth-php/library/store/OAuthStorePDO.php +++ /dev/null @@ -1,274 +0,0 @@ - Based on code by Marc Worrell - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -require_once dirname(__FILE__) . '/OAuthStoreSQL.php'; - - -class OAuthStorePDO extends OAuthStoreSQL -{ - private $conn; // PDO connection - private $lastaffectedrows; - - /** - * Construct the OAuthStorePDO. - * In the options you have to supply either: - * - dsn, username, password and database (for a new PDO connection) - * - conn (for the connection to be used) - * - * @param array options - */ - function __construct ( $options = array() ) - { - if (isset($options['conn'])) - { - $this->conn = $options['conn']; - } - else if (isset($options['dsn'])) - { - try - { - $this->conn = new PDO($options['dsn'], $options['username'], @$options['password']); - } - catch (PDOException $e) - { - throw new OAuthException2('Could not connect to PDO database: ' . $e->getMessage()); - } - - $this->query('set character set utf8'); - } - } - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - */ - protected function query ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - try - { - $this->lastaffectedrows = $this->conn->exec($sql); - if ($this->lastaffectedrows === FALSE) { - $this->sql_errcheck($sql); - } - } - catch (PDOException $e) - { - $this->sql_errcheck($sql); - } - } - - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_all_assoc ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - $result = array(); - - try - { - $stmt = $this->conn->query($sql); - - $result = $stmt->fetchAll(PDO::FETCH_ASSOC); - } - catch (PDOException $e) - { - $this->sql_errcheck($sql); - } - return $result; - } - - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_row_assoc ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - $result = $this->query_all_assoc($sql); - $val = array_pop($result); - return $val; - } - - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_row ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - try - { - $all = $this->conn->query($sql, PDO::FETCH_NUM); - $row = array(); - foreach ($all as $r) { - $row = $r; - break; - } - } - catch (PDOException $e) - { - $this->sql_errcheck($sql); - } - return $row; - } - - - /** - * Perform a query, return the first column of the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return mixed - */ - protected function query_one ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - $row = $this->query_row($sql); - $val = array_pop($row); - return $val; - } - - - /** - * Return the number of rows affected in the last query - */ - protected function query_affected_rows () - { - return $this->lastaffectedrows; - } - - - /** - * Return the id of the last inserted row - * - * @return int - */ - protected function query_insert_id () - { - return $this->conn->lastInsertId(); - } - - - protected function sql_printf ( $args ) - { - $sql = array_shift($args); - if (count($args) == 1 && is_array($args[0])) - { - $args = $args[0]; - } - $args = array_map(array($this, 'sql_escape_string'), $args); - return vsprintf($sql, $args); - } - - - protected function sql_escape_string ( $s ) - { - if (is_string($s)) - { - $s = $this->conn->quote($s); - // kludge. Quote already adds quotes, and this conflicts with OAuthStoreSQL. - // so remove the quotes - $len = mb_strlen($s); - if ($len == 0) - return $s; - - $startcut = 0; - while (isset($s[$startcut]) && $s[$startcut] == '\'') - $startcut++; - - $endcut = $len-1; - while (isset($s[$endcut]) && $s[$endcut] == '\'') - $endcut--; - - $s = mb_substr($s, $startcut, $endcut-$startcut+1); - return $s; - } - else if (is_null($s)) - { - return NULL; - } - else if (is_bool($s)) - { - return intval($s); - } - else if (is_int($s) || is_float($s)) - { - return $s; - } - else - { - return $this->conn->quote(strval($s)); - } - } - - - protected function sql_errcheck ( $sql ) - { - $msg = "SQL Error in OAuthStoreMySQL: ". print_r($this->conn->errorInfo(), true) ."\n\n" . $sql; - $backtrace = debug_backtrace(); - $msg .= "\n\nAt file " . $backtrace[1]['file'] . ", line " . $backtrace[1]['line']; - throw new OAuthException2($msg); - } - - /** - * Initialise the database - */ - public function install () - { - // TODO: this depends on mysql extension - require_once dirname(__FILE__) . '/mysql/install.php'; - } - -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStorePostgreSQL.php b/3rdparty/oauth-php/library/store/OAuthStorePostgreSQL.php deleted file mode 100644 index 04b9f04662..0000000000 --- a/3rdparty/oauth-php/library/store/OAuthStorePostgreSQL.php +++ /dev/null @@ -1,1957 +0,0 @@ - - * @link http://elma.fr - * - * @Id 2010-10-22 10:07:18 ndelanoe $ - * @version $Id: OAuthStorePostgreSQL.php 175 2010-11-24 19:52:24Z brunobg@corollarium.com $ - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - **/ - -require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php'; - - -class OAuthStorePostgreSQL extends OAuthStoreAbstract -{ - /** - * Maximum delta a timestamp may be off from a previous timestamp. - * Allows multiple consumers with some clock skew to work with the same token. - * Unit is seconds, default max skew is 10 minutes. - */ - protected $max_timestamp_skew = 600; - - /** - * Default ttl for request tokens - */ - protected $max_request_token_ttl = 3600; - - /** - * Number of affected rowsby the last queries - */ - private $_lastAffectedRows = 0; - - public function install() - { - throw new OAuthException2('Not yet implemented, see postgresql/pgsql.sql'); - } - - /** - * Construct the OAuthStorePostgrSQL. - * In the options you have to supply either: - * - server, username, password and database (for a pg_connect) - * - connectionString (for a pg_connect) - * - conn (for the connection to be used) - * - * @param array options - */ - function __construct ( $options = array() ) - { - if (isset($options['conn'])) - { - $this->conn = $options['conn']; - } - else - { - if (isset($options['server'])) - { - $host = $options['server']; - $user = $options['username']; - $dbname = $options['database']; - - $connectionString = sprintf('host=%s dbname=%s user=%s', $host, $dbname, $user); - - if (isset($options['password'])) - { - $connectionString .= ' password=' . $options['password']; - } - - $this->conn = pg_connect($connectionString); - } - elseif (isset($options['connectionString'])) - { - $this->conn = pg_connect($options['connectionString']); - } - else { - - // Try the default pg connect - $this->conn = pg_connect(); - } - - if ($this->conn === false) - { - throw new OAuthException2('Could not connect to PostgresSQL database'); - } - } - } - - /** - * Find stored credentials for the consumer key and token. Used by an OAuth server - * when verifying an OAuth request. - * - * @param string consumer_key - * @param string token - * @param string token_type false, 'request' or 'access' - * @exception OAuthException2 when no secrets where found - * @return array assoc (consumer_secret, token_secret, osr_id, ost_id, user_id) - */ - public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ) - { - if ($token_type === false) - { - $rs = $this->query_row_assoc(' - SELECT osr_id, - osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret - FROM oauth_server_registry - WHERE osr_consumer_key = \'%s\' - AND osr_enabled = \'1\' - ', - $consumer_key); - - if ($rs) - { - $rs['token'] = false; - $rs['token_secret'] = false; - $rs['user_id'] = false; - $rs['ost_id'] = false; - } - } - else - { - $rs = $this->query_row_assoc(' - SELECT osr_id, - ost_id, - ost_usa_id_ref as user_id, - osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret, - ost_token as token, - ost_token_secret as token_secret - FROM oauth_server_registry - JOIN oauth_server_token - ON ost_osr_id_ref = osr_id - WHERE ost_token_type = \'%s\' - AND osr_consumer_key = \'%s\' - AND ost_token = \'%s\' - AND osr_enabled = \'1\' - AND ost_token_ttl >= NOW() - ', - $token_type, $consumer_key, $token); - } - - if (empty($rs)) - { - throw new OAuthException2('The consumer_key "'.$consumer_key.'" token "'.$token.'" combination does not exist or is not enabled.'); - } - return $rs; - } - - /** - * Find the server details for signing a request, always looks for an access token. - * The returned credentials depend on which local user is making the request. - * - * The consumer_key must belong to the user or be public (user id is null) - * - * For signing we need all of the following: - * - * consumer_key consumer key associated with the server - * consumer_secret consumer secret associated with this server - * token access token associated with this server - * token_secret secret for the access token - * signature_methods signing methods supported by the server (array) - * - * @todo filter on token type (we should know how and with what to sign this request, and there might be old access tokens) - * @param string uri uri of the server - * @param int user_id id of the logged on user - * @param string name (optional) name of the token (case sensitive) - * @exception OAuthException2 when no credentials found - * @return array - */ - public function getSecretsForSignature ( $uri, $user_id, $name = '' ) - { - // Find a consumer key and token for the given uri - $ps = parse_url($uri); - $host = isset($ps['host']) ? $ps['host'] : 'localhost'; - $path = isset($ps['path']) ? $ps['path'] : ''; - - if (empty($path) || substr($path, -1) != '/') - { - $path .= '/'; - } - - // The owner of the consumer_key is either the user or nobody (public consumer key) - $secrets = $this->query_row_assoc(' - SELECT ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - oct_token as token, - oct_token_secret as token_secret, - ocr_signature_methods as signature_methods - FROM oauth_consumer_registry - JOIN oauth_consumer_token ON oct_ocr_id_ref = ocr_id - WHERE ocr_server_uri_host = \'%s\' - AND ocr_server_uri_path = SUBSTR(\'%s\', 1, LENGTH(ocr_server_uri_path)) - AND (ocr_usa_id_ref = \'%s\' OR ocr_usa_id_ref IS NULL) - AND oct_usa_id_ref = \'%d\' - AND oct_token_type = \'access\' - AND oct_name = \'%s\' - AND oct_token_ttl >= NOW() - ORDER BY ocr_usa_id_ref DESC, ocr_consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC - LIMIT 1 - ', $host, $path, $user_id, $user_id, $name - ); - - if (empty($secrets)) - { - throw new OAuthException2('No server tokens available for '.$uri); - } - $secrets['signature_methods'] = explode(',', $secrets['signature_methods']); - return $secrets; - } - - /** - * Get the token and token secret we obtained from a server. - * - * @param string consumer_key - * @param string token - * @param string token_type - * @param int user_id the user owning the token - * @param string name optional name for a named token - * @exception OAuthException2 when no credentials found - * @return array - */ - public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' ) - { - if ($token_type != 'request' && $token_type != 'access') - { - throw new OAuthException2('Unkown token type "'.$token_type.'", must be either "request" or "access"'); - } - - // Take the most recent token of the given type - $r = $this->query_row_assoc(' - SELECT ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - oct_token as token, - oct_token_secret as token_secret, - oct_name as token_name, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri, - CASE WHEN oct_token_ttl >= \'9999-12-31\' THEN NULL ELSE oct_token_ttl - NOW() END as token_ttl - FROM oauth_consumer_registry - JOIN oauth_consumer_token - ON oct_ocr_id_ref = ocr_id - WHERE ocr_consumer_key = \'%s\' - AND oct_token_type = \'%s\' - AND oct_token = \'%s\' - AND oct_usa_id_ref = \'%d\' - AND oct_token_ttl >= NOW() - ', $consumer_key, $token_type, $token, $user_id - ); - - if (empty($r)) - { - throw new OAuthException2('Could not find a "'.$token_type.'" token for consumer "'.$consumer_key.'" and user '.$user_id); - } - if (isset($r['signature_methods']) && !empty($r['signature_methods'])) - { - $r['signature_methods'] = explode(',',$r['signature_methods']); - } - else - { - $r['signature_methods'] = array(); - } - return $r; - } - - - /** - * Add a request token we obtained from a server. - * - * @todo remove old tokens for this user and this ocr_id - * @param string consumer_key key of the server in the consumer registry - * @param string token_type one of 'request' or 'access' - * @param string token - * @param string token_secret - * @param int user_id the user owning the token - * @param array options extra options, name and token_ttl - * @exception OAuthException2 when server is not known - * @exception OAuthException2 when we received a duplicate token - */ - public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) - { - if ($token_type != 'request' && $token_type != 'access') - { - throw new OAuthException2('Unknown token type "'.$token_type.'", must be either "request" or "access"'); - } - - // Maximum time to live for this token - if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) - { - $ttl = 'NOW() + INTERVAL \''.intval($options['token_ttl']).' SECOND\''; - } - else if ($token_type == 'request') - { - $ttl = 'NOW() + INTERVAL \''.$this->max_request_token_ttl.' SECOND\''; - } - else - { - $ttl = "'9999-12-31'"; - } - - if (isset($options['server_uri'])) - { - $ocr_id = $this->query_one(' - SELECT ocr_id - FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND ocr_usa_id_ref = \'%d\' - AND ocr_server_uri = \'%s\' - ', $consumer_key, $user_id, $options['server_uri']); - } - else - { - $ocr_id = $this->query_one(' - SELECT ocr_id - FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND ocr_usa_id_ref = \'%d\' - ', $consumer_key, $user_id); - } - - if (empty($ocr_id)) - { - throw new OAuthException2('No server associated with consumer_key "'.$consumer_key.'"'); - } - - // Named tokens, unique per user/consumer key - if (isset($options['name']) && $options['name'] != '') - { - $name = $options['name']; - } - else - { - $name = ''; - } - - // Delete any old tokens with the same type and name for this user/server combination - $this->query(' - DELETE FROM oauth_consumer_token - WHERE oct_ocr_id_ref = %d - AND oct_usa_id_ref = \'%d\' - AND oct_token_type::text = LOWER(\'%s\')::text - AND oct_name = \'%s\' - ', - $ocr_id, - $user_id, - $token_type, - $name); - - // Insert the new token - $this->query(' - INSERT INTO - oauth_consumer_token( - oct_ocr_id_ref, - oct_usa_id_ref, - oct_name, - oct_token, - oct_token_secret, - oct_token_type, - oct_timestamp, - oct_token_ttl - ) - VALUES (%d,%d,\'%s\',\'%s\',\'%s\',\'%s\',NOW(),'.$ttl.')', - $ocr_id, - $user_id, - $name, - $token, - $token_secret, - $token_type); - - if (!$this->query_affected_rows()) - { - throw new OAuthException2('Received duplicate token "'.$token.'" for the same consumer_key "'.$consumer_key.'"'); - } - } - - /** - * Delete a server key. This removes access to that site. - * - * @param string consumer_key - * @param int user_id user registering this server - * @param boolean user_is_admin - */ - public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) - { - if ($user_is_admin) - { - $this->query(' - DELETE FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) - ', $consumer_key, $user_id); - } - else - { - $this->query(' - DELETE FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND ocr_usa_id_ref = \'%d\' - ', $consumer_key, $user_id); - } - } - - - /** - * Get a server from the consumer registry using the consumer key - * - * @param string consumer_key - * @param int user_id - * @param boolean user_is_admin (optional) - * @exception OAuthException2 when server is not found - * @return array - */ - public function getServer ( $consumer_key, $user_id, $user_is_admin = false ) - { - $r = $this->query_row_assoc(' - SELECT ocr_id as id, - ocr_usa_id_ref as user_id, - ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri - FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) - ', $consumer_key, $user_id); - - if (empty($r)) - { - throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" has been registered (for this user)'); - } - - if (isset($r['signature_methods']) && !empty($r['signature_methods'])) - { - $r['signature_methods'] = explode(',',$r['signature_methods']); - } - else - { - $r['signature_methods'] = array(); - } - return $r; - } - - - /** - * Find the server details that might be used for a request - * - * The consumer_key must belong to the user or be public (user id is null) - * - * @param string uri uri of the server - * @param int user_id id of the logged on user - * @exception OAuthException2 when no credentials found - * @return array - */ - public function getServerForUri ( $uri, $user_id ) - { - // Find a consumer key and token for the given uri - $ps = parse_url($uri); - $host = isset($ps['host']) ? $ps['host'] : 'localhost'; - $path = isset($ps['path']) ? $ps['path'] : ''; - - if (empty($path) || substr($path, -1) != '/') - { - $path .= '/'; - } - - // The owner of the consumer_key is either the user or nobody (public consumer key) - $server = $this->query_row_assoc(' - SELECT ocr_id as id, - ocr_usa_id_ref as user_id, - ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri - FROM oauth_consumer_registry - WHERE ocr_server_uri_host = \'%s\' - AND ocr_server_uri_path = SUBSTR(\'%s\', 1, LENGTH(ocr_server_uri_path)) - AND (ocr_usa_id_ref = \'%s\' OR ocr_usa_id_ref IS NULL) - ORDER BY ocr_usa_id_ref DESC, consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC - LIMIT 1 - ', $host, $path, $user_id - ); - - if (empty($server)) - { - throw new OAuthException2('No server available for '.$uri); - } - $server['signature_methods'] = explode(',', $server['signature_methods']); - return $server; - } - - /** - * Get a list of all server token this user has access to. - * - * @param int usr_id - * @return array - */ - public function listServerTokens ( $user_id ) - { - $ts = $this->query_all_assoc(' - SELECT ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - oct_id as token_id, - oct_token as token, - oct_token_secret as token_secret, - oct_usa_id_ref as user_id, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_server_uri_host as server_uri_host, - ocr_server_uri_path as server_uri_path, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri, - oct_timestamp as timestamp - FROM oauth_consumer_registry - JOIN oauth_consumer_token - ON oct_ocr_id_ref = ocr_id - WHERE oct_usa_id_ref = \'%d\' - AND oct_token_type = \'access\' - AND oct_token_ttl >= NOW() - ORDER BY ocr_server_uri_host, ocr_server_uri_path - ', $user_id); - return $ts; - } - - /** - * Count how many tokens we have for the given server - * - * @param string consumer_key - * @return int - */ - public function countServerTokens ( $consumer_key ) - { - $count = $this->query_one(' - SELECT COUNT(oct_id) - FROM oauth_consumer_token - JOIN oauth_consumer_registry - ON oct_ocr_id_ref = ocr_id - WHERE oct_token_type = \'access\' - AND ocr_consumer_key = \'%s\' - AND oct_token_ttl >= NOW() - ', $consumer_key); - - return $count; - } - - /** - * Get a specific server token for the given user - * - * @param string consumer_key - * @param string token - * @param int user_id - * @exception OAuthException2 when no such token found - * @return array - */ - public function getServerToken ( $consumer_key, $token, $user_id ) - { - $ts = $this->query_row_assoc(' - SELECT ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - oct_token as token, - oct_token_secret as token_secret, - oct_usa_id_ref as usr_id, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_server_uri_host as server_uri_host, - ocr_server_uri_path as server_uri_path, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri, - oct_timestamp as timestamp - FROM oauth_consumer_registry - JOIN oauth_consumer_token - ON oct_ocr_id_ref = ocr_id - WHERE ocr_consumer_key = \'%s\' - AND oct_usa_id_ref = \'%d\' - AND oct_token_type = \'access\' - AND oct_token = \'%s\' - AND oct_token_ttl >= NOW() - ', $consumer_key, $user_id, $token); - - if (empty($ts)) - { - throw new OAuthException2('No such consumer key ('.$consumer_key.') and token ('.$token.') combination for user "'.$user_id.'"'); - } - return $ts; - } - - - /** - * Delete a token we obtained from a server. - * - * @param string consumer_key - * @param string token - * @param int user_id - * @param boolean user_is_admin - */ - public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) - { - if ($user_is_admin) - { - $this->query(' - DELETE FROM oauth_consumer_token - USING oauth_consumer_registry - WHERE - oct_ocr_id_ref = ocr_id - AND ocr_consumer_key = \'%s\' - AND oct_token = \'%s\' - ', $consumer_key, $token); - } - else - { - $this->query(' - DELETE FROM oauth_consumer_token - USING oauth_consumer_registry - WHERE - oct_ocr_id_ref = ocr_id - AND ocr_consumer_key = \'%s\' - AND oct_token = \'%s\' - AND oct_usa_id_ref = \'%d\' - ', $consumer_key, $token, $user_id); - } - } - - /** - * Set the ttl of a server access token. This is done when the - * server receives a valid request with a xoauth_token_ttl parameter in it. - * - * @param string consumer_key - * @param string token - * @param int token_ttl - */ - public function setServerTokenTtl ( $consumer_key, $token, $token_ttl ) - { - if ($token_ttl <= 0) - { - // Immediate delete when the token is past its ttl - $this->deleteServerToken($consumer_key, $token, 0, true); - } - else - { - // Set maximum time to live for this token - $this->query(' - UPDATE oauth_consumer_token - SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\') - WHERE ocr_consumer_key = \'%s\' - AND oct_ocr_id_ref = ocr_id - AND oct_token = \'%s\' - ', $token_ttl, $consumer_key, $token); - - // Set maximum time to live for this token - $this->query(' - UPDATE oauth_consumer_registry - SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\') - WHERE ocr_consumer_key = \'%s\' - AND oct_ocr_id_ref = ocr_id - AND oct_token = \'%s\' - ', $token_ttl, $consumer_key, $token); - } - } - - /** - * Get a list of all consumers from the consumer registry. - * The consumer keys belong to the user or are public (user id is null) - * - * @param string q query term - * @param int user_id - * @return array - */ - public function listServers ( $q = '', $user_id ) - { - $q = trim(str_replace('%', '', $q)); - $args = array(); - - if (!empty($q)) - { - $where = ' WHERE ( ocr_consumer_key like \'%%%s%%\' - OR ocr_server_uri like \'%%%s%%\' - OR ocr_server_uri_host like \'%%%s%%\' - OR ocr_server_uri_path like \'%%%s%%\') - AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) - '; - - $args[] = $q; - $args[] = $q; - $args[] = $q; - $args[] = $q; - $args[] = $user_id; - } - else - { - $where = ' WHERE ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL'; - $args[] = $user_id; - } - - $servers = $this->query_all_assoc(' - SELECT ocr_id as id, - ocr_usa_id_ref as user_id, - ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_server_uri_host as server_uri_host, - ocr_server_uri_path as server_uri_path, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri - FROM oauth_consumer_registry - '.$where.' - ORDER BY ocr_server_uri_host, ocr_server_uri_path - ', $args); - return $servers; - } - - /** - * Register or update a server for our site (we will be the consumer) - * - * (This is the registry at the consumers, registering servers ;-) ) - * - * @param array server - * @param int user_id user registering this server - * @param boolean user_is_admin - * @exception OAuthException2 when fields are missing or on duplicate consumer_key - * @return consumer_key - */ - public function updateServer ( $server, $user_id, $user_is_admin = false ) - { - foreach (array('consumer_key', 'server_uri') as $f) - { - if (empty($server[$f])) - { - throw new OAuthException2('The field "'.$f.'" must be set and non empty'); - } - } - - if (!empty($server['id'])) - { - $exists = $this->query_one(' - SELECT ocr_id - FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND ocr_id <> %d - AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) - ', $server['consumer_key'], $server['id'], $user_id); - } - else - { - $exists = $this->query_one(' - SELECT ocr_id - FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) - ', $server['consumer_key'], $user_id); - } - - if ($exists) - { - throw new OAuthException2('The server with key "'.$server['consumer_key'].'" has already been registered'); - } - - $parts = parse_url($server['server_uri']); - $host = (isset($parts['host']) ? $parts['host'] : 'localhost'); - $path = (isset($parts['path']) ? $parts['path'] : '/'); - - if (isset($server['signature_methods'])) - { - if (is_array($server['signature_methods'])) - { - $server['signature_methods'] = strtoupper(implode(',', $server['signature_methods'])); - } - } - else - { - $server['signature_methods'] = ''; - } - - // When the user is an admin, then the user can update the user_id of this record - if ($user_is_admin && array_key_exists('user_id', $server)) - { - if (is_null($server['user_id'])) - { - $update_user = ', ocr_usa_id_ref = NULL'; - } - else - { - $update_user = ', ocr_usa_id_ref = \''. intval($server['user_id']) . '\''; - } - } - else - { - $update_user = ''; - } - - if (!empty($server['id'])) - { - // Check if the current user can update this server definition - if (!$user_is_admin) - { - $ocr_usa_id_ref = $this->query_one(' - SELECT ocr_usa_id_ref - FROM oauth_consumer_registry - WHERE ocr_id = %d - ', $server['id']); - - if ($ocr_usa_id_ref != $user_id) - { - throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this server'); - } - } - - // Update the consumer registration - $this->query(' - UPDATE oauth_consumer_registry - SET ocr_consumer_key = \'%s\', - ocr_consumer_secret = \'%s\', - ocr_server_uri = \'%s\', - ocr_server_uri_host = \'%s\', - ocr_server_uri_path = \'%s\', - ocr_timestamp = NOW(), - ocr_request_token_uri = \'%s\', - ocr_authorize_uri = \'%s\', - ocr_access_token_uri = \'%s\', - ocr_signature_methods = \'%s\' - '.$update_user.' - WHERE ocr_id = %d - ', - $server['consumer_key'], - $server['consumer_secret'], - $server['server_uri'], - strtolower($host), - $path, - isset($server['request_token_uri']) ? $server['request_token_uri'] : '', - isset($server['authorize_uri']) ? $server['authorize_uri'] : '', - isset($server['access_token_uri']) ? $server['access_token_uri'] : '', - $server['signature_methods'], - $server['id'] - ); - } - else - { - $update_user_field = ''; - $update_user_value = ''; - if (empty($update_user)) - { - // Per default the user owning the key is the user registering the key - $update_user_field = ', ocr_usa_id_ref'; - $update_user_value = ', ' . intval($user_id); - } - - $this->query(' - INSERT INTO oauth_consumer_registry ( - ocr_consumer_key , - ocr_consumer_secret , - ocr_server_uri , - ocr_server_uri_host , - ocr_server_uri_path , - ocr_timestamp , - ocr_request_token_uri, - ocr_authorize_uri , - ocr_access_token_uri , - ocr_signature_methods' . $update_user_field . ' - ) - VALUES (\'%s\', \'%s\', \'%s\', \'%s\', \'%s\', NOW(), \'%s\', \'%s\', \'%s\', \'%s\''. $update_user_value . ')', - $server['consumer_key'], - $server['consumer_secret'], - $server['server_uri'], - strtolower($host), - $path, - isset($server['request_token_uri']) ? $server['request_token_uri'] : '', - isset($server['authorize_uri']) ? $server['authorize_uri'] : '', - isset($server['access_token_uri']) ? $server['access_token_uri'] : '', - $server['signature_methods'] - ); - - $ocr_id = $this->query_insert_id('oauth_consumer_registry', 'ocr_id'); - } - return $server['consumer_key']; - } - - - /** - * Insert/update a new consumer with this server (we will be the server) - * When this is a new consumer, then also generate the consumer key and secret. - * Never updates the consumer key and secret. - * When the id is set, then the key and secret must correspond to the entry - * being updated. - * - * (This is the registry at the server, registering consumers ;-) ) - * - * @param array consumer - * @param int user_id user registering this consumer - * @param boolean user_is_admin - * @return string consumer key - */ - public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) - { - if (!$user_is_admin) - { - foreach (array('requester_name', 'requester_email') as $f) - { - if (empty($consumer[$f])) - { - throw new OAuthException2('The field "'.$f.'" must be set and non empty'); - } - } - } - - if (!empty($consumer['id'])) - { - if (empty($consumer['consumer_key'])) - { - throw new OAuthException2('The field "consumer_key" must be set and non empty'); - } - if (!$user_is_admin && empty($consumer['consumer_secret'])) - { - throw new OAuthException2('The field "consumer_secret" must be set and non empty'); - } - - // Check if the current user can update this server definition - if (!$user_is_admin) - { - $osr_usa_id_ref = $this->query_one(' - SELECT osr_usa_id_ref - FROM oauth_server_registry - WHERE osr_id = %d - ', $consumer['id']); - - if ($osr_usa_id_ref != $user_id) - { - throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this consumer'); - } - } - else - { - // User is an admin, allow a key owner to be changed or key to be shared - if (array_key_exists('user_id',$consumer)) - { - if (is_null($consumer['user_id'])) - { - $this->query(' - UPDATE oauth_server_registry - SET osr_usa_id_ref = NULL - WHERE osr_id = %d - ', $consumer['id']); - } - else - { - $this->query(' - UPDATE oauth_server_registry - SET osr_usa_id_ref = \'%d\' - WHERE osr_id = %d - ', $consumer['user_id'], $consumer['id']); - } - } - } - - $this->query(' - UPDATE oauth_server_registry - SET osr_requester_name = \'%s\', - osr_requester_email = \'%s\', - osr_callback_uri = \'%s\', - osr_application_uri = \'%s\', - osr_application_title = \'%s\', - osr_application_descr = \'%s\', - osr_application_notes = \'%s\', - osr_application_type = \'%s\', - osr_application_commercial = IF(%d,\'1\',\'0\'), - osr_timestamp = NOW() - WHERE osr_id = %d - AND osr_consumer_key = \'%s\' - AND osr_consumer_secret = \'%s\' - ', - $consumer['requester_name'], - $consumer['requester_email'], - isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '', - isset($consumer['application_uri']) ? $consumer['application_uri'] : '', - isset($consumer['application_title']) ? $consumer['application_title'] : '', - isset($consumer['application_descr']) ? $consumer['application_descr'] : '', - isset($consumer['application_notes']) ? $consumer['application_notes'] : '', - isset($consumer['application_type']) ? $consumer['application_type'] : '', - isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0, - $consumer['id'], - $consumer['consumer_key'], - $consumer['consumer_secret'] - ); - - - $consumer_key = $consumer['consumer_key']; - } - else - { - $consumer_key = $this->generateKey(true); - $consumer_secret= $this->generateKey(); - - // When the user is an admin, then the user can be forced to something else that the user - if ($user_is_admin && array_key_exists('user_id',$consumer)) - { - if (is_null($consumer['user_id'])) - { - $owner_id = 'NULL'; - } - else - { - $owner_id = intval($consumer['user_id']); - } - } - else - { - // No admin, take the user id as the owner id. - $owner_id = intval($user_id); - } - - $this->query(' - INSERT INTO oauth_server_registry ( - osr_enabled, - osr_status, - osr_usa_id_ref, - osr_consumer_key, - osr_consumer_secret, - osr_requester_name, - osr_requester_email, - osr_callback_uri, - osr_application_uri, - osr_application_title, - osr_application_descr, - osr_application_notes, - osr_application_type, - osr_application_commercial, - osr_timestamp, - osr_issue_date - ) - VALUES (\'1\', \'active\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%s\', \'%d\', NOW(), NOW()) - ', - $owner_id, - $consumer_key, - $consumer_secret, - $consumer['requester_name'], - $consumer['requester_email'], - isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '', - isset($consumer['application_uri']) ? $consumer['application_uri'] : '', - isset($consumer['application_title']) ? $consumer['application_title'] : '', - isset($consumer['application_descr']) ? $consumer['application_descr'] : '', - isset($consumer['application_notes']) ? $consumer['application_notes'] : '', - isset($consumer['application_type']) ? $consumer['application_type'] : '', - isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0 - ); - } - return $consumer_key; - - } - - /** - * Delete a consumer key. This removes access to our site for all applications using this key. - * - * @param string consumer_key - * @param int user_id user registering this server - * @param boolean user_is_admin - */ - public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) - { - if ($user_is_admin) - { - $this->query(' - DELETE FROM oauth_server_registry - WHERE osr_consumer_key = \'%s\' - AND (osr_usa_id_ref = \'%d\' OR osr_usa_id_ref IS NULL) - ', $consumer_key, $user_id); - } - else - { - $this->query(' - DELETE FROM oauth_server_registry - WHERE osr_consumer_key = \'%s\' - AND osr_usa_id_ref = \'%d\' - ', $consumer_key, $user_id); - } - } - - /** - * Fetch a consumer of this server, by consumer_key. - * - * @param string consumer_key - * @param int user_id - * @param boolean user_is_admin (optional) - * @exception OAuthException2 when consumer not found - * @return array - */ - public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) - { - $consumer = $this->query_row_assoc(' - SELECT * - FROM oauth_server_registry - WHERE osr_consumer_key = \'%s\' - ', $consumer_key); - - if (!is_array($consumer)) - { - throw new OAuthException2('No consumer with consumer_key "'.$consumer_key.'"'); - } - - $c = array(); - foreach ($consumer as $key => $value) - { - $c[substr($key, 4)] = $value; - } - $c['user_id'] = $c['usa_id_ref']; - - if (!$user_is_admin && !empty($c['user_id']) && $c['user_id'] != $user_id) - { - throw new OAuthException2('No access to the consumer information for consumer_key "'.$consumer_key.'"'); - } - return $c; - } - - - /** - * Fetch the static consumer key for this provider. The user for the static consumer - * key is NULL (no user, shared key). If the key did not exist then the key is created. - * - * @return string - */ - public function getConsumerStatic () - { - $consumer = $this->query_one(' - SELECT osr_consumer_key - FROM oauth_server_registry - WHERE osr_consumer_key LIKE \'sc-%%\' - AND osr_usa_id_ref IS NULL - '); - - if (empty($consumer)) - { - $consumer_key = 'sc-'.$this->generateKey(true); - $this->query(' - INSERT INTO oauth_server_registry ( - osr_enabled, - osr_status, - osr_usa_id_ref, - osr_consumer_key, - osr_consumer_secret, - osr_requester_name, - osr_requester_email, - osr_callback_uri, - osr_application_uri, - osr_application_title, - osr_application_descr, - osr_application_notes, - osr_application_type, - osr_application_commercial, - osr_timestamp, - osr_issue_date - ) - VALUES (\'1\',\'active\', NULL, \'%s\', \'\', \'\', \'\', \'\', \'\', \'Static shared consumer key\', \'\', \'Static shared consumer key\', \'\', 0, NOW(), NOW()) - ', - $consumer_key - ); - - // Just make sure that if the consumer key is truncated that we get the truncated string - $consumer = $this->getConsumerStatic(); - } - return $consumer; - } - - /** - * Add an unautorized request token to our server. - * - * @param string consumer_key - * @param array options (eg. token_ttl) - * @return array (token, token_secret) - */ - public function addConsumerRequestToken ( $consumer_key, $options = array() ) - { - $token = $this->generateKey(true); - $secret = $this->generateKey(); - $osr_id = $this->query_one(' - SELECT osr_id - FROM oauth_server_registry - WHERE osr_consumer_key = \'%s\' - AND osr_enabled = \'1\' - ', $consumer_key); - - if (!$osr_id) - { - throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" or consumer_key is disabled'); - } - - if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) - { - $ttl = intval($options['token_ttl']); - } - else - { - $ttl = $this->max_request_token_ttl; - } - - if (!isset($options['oauth_callback'])) { - // 1.0a Compatibility : store callback url associated with request token - $options['oauth_callback']='oob'; - } - - $this->query(' - INSERT INTO oauth_server_token ( - ost_osr_id_ref, - ost_usa_id_ref, - ost_token, - ost_token_secret, - ost_token_type, - ost_token_ttl, - ost_callback_url - ) - VALUES (%d, \'1\', \'%s\', \'%s\', \'request\', NOW() + INTERVAL \'%d SECOND\', \'%s\')', - $osr_id, $token, $secret, $ttl, $options['oauth_callback']); - - return array('token'=>$token, 'token_secret'=>$secret, 'token_ttl'=>$ttl); - } - - /** - * Fetch the consumer request token, by request token. - * - * @param string token - * @return array token and consumer details - */ - public function getConsumerRequestToken ( $token ) - { - $rs = $this->query_row_assoc(' - SELECT ost_token as token, - ost_token_secret as token_secret, - osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret, - ost_token_type as token_type, - ost_callback_url as callback_url, - osr_application_title as application_title, - osr_application_descr as application_descr, - osr_application_uri as application_uri - FROM oauth_server_token - JOIN oauth_server_registry - ON ost_osr_id_ref = osr_id - WHERE ost_token_type = \'request\' - AND ost_token = \'%s\' - AND ost_token_ttl >= NOW() - ', $token); - - return $rs; - } - - /** - * Delete a consumer token. The token must be a request or authorized token. - * - * @param string token - */ - public function deleteConsumerRequestToken ( $token ) - { - $this->query(' - DELETE FROM oauth_server_token - WHERE ost_token = \'%s\' - AND ost_token_type = \'request\' - ', $token); - } - - /** - * Upgrade a request token to be an authorized request token. - * - * @param string token - * @param int user_id user authorizing the token - * @param string referrer_host used to set the referrer host for this token, for user feedback - */ - public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) - { - // 1.0a Compatibility : create a token verifier - $verifier = substr(md5(rand()),0,10); - - $this->query(' - UPDATE oauth_server_token - SET ost_authorized = \'1\', - ost_usa_id_ref = \'%d\', - ost_timestamp = NOW(), - ost_referrer_host = \'%s\', - ost_verifier = \'%s\' - WHERE ost_token = \'%s\' - AND ost_token_type = \'request\' - ', $user_id, $referrer_host, $verifier, $token); - return $verifier; - } - - /** - * Count the consumer access tokens for the given consumer. - * - * @param string consumer_key - * @return int - */ - public function countConsumerAccessTokens ( $consumer_key ) - { - $count = $this->query_one(' - SELECT COUNT(ost_id) - FROM oauth_server_token - JOIN oauth_server_registry - ON ost_osr_id_ref = osr_id - WHERE ost_token_type = \'access\' - AND osr_consumer_key = \'%s\' - AND ost_token_ttl >= NOW() - ', $consumer_key); - - return $count; - } - - /** - * Exchange an authorized request token for new access token. - * - * @param string token - * @param array options options for the token, token_ttl - * @exception OAuthException2 when token could not be exchanged - * @return array (token, token_secret) - */ - public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) - { - $new_token = $this->generateKey(true); - $new_secret = $this->generateKey(); - - // Maximum time to live for this token - if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) - { - $ttl_sql = '(NOW() + INTERVAL \''.intval($options['token_ttl']).' SECOND\')'; - } - else - { - $ttl_sql = "'9999-12-31'"; - } - - if (isset($options['verifier'])) { - $verifier = $options['verifier']; - - // 1.0a Compatibility : check token against oauth_verifier - $this->query(' - UPDATE oauth_server_token - SET ost_token = \'%s\', - ost_token_secret = \'%s\', - ost_token_type = \'access\', - ost_timestamp = NOW(), - ost_token_ttl = '.$ttl_sql.' - WHERE ost_token = \'%s\' - AND ost_token_type = \'request\' - AND ost_authorized = \'1\' - AND ost_token_ttl >= NOW() - AND ost_verifier = \'%s\' - ', $new_token, $new_secret, $token, $verifier); - } else { - - // 1.0 - $this->query(' - UPDATE oauth_server_token - SET ost_token = \'%s\', - ost_token_secret = \'%s\', - ost_token_type = \'access\', - ost_timestamp = NOW(), - ost_token_ttl = '.$ttl_sql.' - WHERE ost_token = \'%s\' - AND ost_token_type = \'request\' - AND ost_authorized = \'1\' - AND ost_token_ttl >= NOW() - ', $new_token, $new_secret, $token); - } - - if ($this->query_affected_rows() != 1) - { - throw new OAuthException2('Can\'t exchange request token "'.$token.'" for access token. No such token or not authorized'); - } - - $ret = array('token' => $new_token, 'token_secret' => $new_secret); - $ttl = $this->query_one(' - SELECT (CASE WHEN ost_token_ttl >= \'9999-12-31\' THEN NULL ELSE ost_token_ttl - NOW() END) as token_ttl - FROM oauth_server_token - WHERE ost_token = \'%s\'', $new_token); - - if (is_numeric($ttl)) - { - $ret['token_ttl'] = intval($ttl); - } - return $ret; - } - - /** - * Fetch the consumer access token, by access token. - * - * @param string token - * @param int user_id - * @exception OAuthException2 when token is not found - * @return array token and consumer details - */ - public function getConsumerAccessToken ( $token, $user_id ) - { - $rs = $this->query_row_assoc(' - SELECT ost_token as token, - ost_token_secret as token_secret, - ost_referrer_host as token_referrer_host, - osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret, - osr_application_uri as application_uri, - osr_application_title as application_title, - osr_application_descr as application_descr, - osr_callback_uri as callback_uri - FROM oauth_server_token - JOIN oauth_server_registry - ON ost_osr_id_ref = osr_id - WHERE ost_token_type = \'access\' - AND ost_token = \'%s\' - AND ost_usa_id_ref = \'%d\' - AND ost_token_ttl >= NOW() - ', $token, $user_id); - - if (empty($rs)) - { - throw new OAuthException2('No server_token "'.$token.'" for user "'.$user_id.'"'); - } - return $rs; - } - - /** - * Delete a consumer access token. - * - * @param string token - * @param int user_id - * @param boolean user_is_admin - */ - public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) - { - if ($user_is_admin) - { - $this->query(' - DELETE FROM oauth_server_token - WHERE ost_token = \'%s\' - AND ost_token_type = \'access\' - ', $token); - } - else - { - $this->query(' - DELETE FROM oauth_server_token - WHERE ost_token = \'%s\' - AND ost_token_type = \'access\' - AND ost_usa_id_ref = \'%d\' - ', $token, $user_id); - } - } - - /** - * Set the ttl of a consumer access token. This is done when the - * server receives a valid request with a xoauth_token_ttl parameter in it. - * - * @param string token - * @param int ttl - */ - public function setConsumerAccessTokenTtl ( $token, $token_ttl ) - { - if ($token_ttl <= 0) - { - // Immediate delete when the token is past its ttl - $this->deleteConsumerAccessToken($token, 0, true); - } - else - { - // Set maximum time to live for this token - $this->query(' - UPDATE oauth_server_token - SET ost_token_ttl = (NOW() + INTERVAL \'%d SECOND\') - WHERE ost_token = \'%s\' - AND ost_token_type = \'access\' - ', $token_ttl, $token); - } - } - - /** - * Fetch a list of all consumer keys, secrets etc. - * Returns the public (user_id is null) and the keys owned by the user - * - * @param int user_id - * @return array - */ - public function listConsumers ( $user_id ) - { - $rs = $this->query_all_assoc(' - SELECT osr_id as id, - osr_usa_id_ref as user_id, - osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret, - osr_enabled as enabled, - osr_status as status, - osr_issue_date as issue_date, - osr_application_uri as application_uri, - osr_application_title as application_title, - osr_application_descr as application_descr, - osr_requester_name as requester_name, - osr_requester_email as requester_email, - osr_callback_uri as callback_uri - FROM oauth_server_registry - WHERE (osr_usa_id_ref = \'%d\' OR osr_usa_id_ref IS NULL) - ORDER BY osr_application_title - ', $user_id); - return $rs; - } - - /** - * List of all registered applications. Data returned has not sensitive - * information and therefore is suitable for public displaying. - * - * @param int $begin - * @param int $total - * @return array - */ - public function listConsumerApplications($begin = 0, $total = 25) - { - $rs = $this->query_all_assoc(' - SELECT osr_id as id, - osr_enabled as enabled, - osr_status as status, - osr_issue_date as issue_date, - osr_application_uri as application_uri, - osr_application_title as application_title, - osr_application_descr as application_descr - FROM oauth_server_registry - ORDER BY osr_application_title - '); - // TODO: pagination - return $rs; - } - - - /** - * Fetch a list of all consumer tokens accessing the account of the given user. - * - * @param int user_id - * @return array - */ - public function listConsumerTokens ( $user_id ) - { - $rs = $this->query_all_assoc(' - SELECT osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret, - osr_enabled as enabled, - osr_status as status, - osr_application_uri as application_uri, - osr_application_title as application_title, - osr_application_descr as application_descr, - ost_timestamp as timestamp, - ost_token as token, - ost_token_secret as token_secret, - ost_referrer_host as token_referrer_host, - osr_callback_uri as callback_uri - FROM oauth_server_registry - JOIN oauth_server_token - ON ost_osr_id_ref = osr_id - WHERE ost_usa_id_ref = \'%d\' - AND ost_token_type = \'access\' - AND ost_token_ttl >= NOW() - ORDER BY osr_application_title - ', $user_id); - return $rs; - } - - - /** - * Check an nonce/timestamp combination. Clears any nonce combinations - * that are older than the one received. - * - * @param string consumer_key - * @param string token - * @param int timestamp - * @param string nonce - * @exception OAuthException2 thrown when the timestamp is not in sequence or nonce is not unique - */ - public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) - { - $r = $this->query_row(' - SELECT MAX(osn_timestamp), MAX(osn_timestamp) > %d + %d - FROM oauth_server_nonce - WHERE osn_consumer_key = \'%s\' - AND osn_token = \'%s\' - ', $timestamp, $this->max_timestamp_skew, $consumer_key, $token); - - if (!empty($r) && $r[1] === 't') - { - throw new OAuthException2('Timestamp is out of sequence. Request rejected. Got '.$timestamp.' last max is '.$r[0].' allowed skew is '.$this->max_timestamp_skew); - } - - // Insert the new combination - $this->query(' - INSERT INTO oauth_server_nonce ( - osn_consumer_key, - osn_token, - osn_timestamp, - osn_nonce - ) - VALUES (\'%s\', \'%s\', %d, \'%s\')', - $consumer_key, $token, $timestamp, $nonce); - - if ($this->query_affected_rows() == 0) - { - throw new OAuthException2('Duplicate timestamp/nonce combination, possible replay attack. Request rejected.'); - } - - // Clean up all timestamps older than the one we just received - $this->query(' - DELETE FROM oauth_server_nonce - WHERE osn_consumer_key = \'%s\' - AND osn_token = \'%s\' - AND osn_timestamp < %d - %d - ', $consumer_key, $token, $timestamp, $this->max_timestamp_skew); - } - - /** - * Add an entry to the log table - * - * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token) - * @param string received - * @param string sent - * @param string base_string - * @param string notes - * @param int (optional) user_id - */ - public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) - { - $args = array(); - $ps = array(); - foreach ($keys as $key => $value) - { - $args[] = $value; - $ps[] = "olg_$key = '%s'"; - } - - if (!empty($_SERVER['REMOTE_ADDR'])) - { - $remote_ip = $_SERVER['REMOTE_ADDR']; - } - else if (!empty($_SERVER['REMOTE_IP'])) - { - $remote_ip = $_SERVER['REMOTE_IP']; - } - else - { - $remote_ip = '0.0.0.0'; - } - - // Build the SQL - $ps['olg_received'] = "'%s'"; $args[] = $this->makeUTF8($received); - $ps['olg_sent'] = "'%s'"; $args[] = $this->makeUTF8($sent); - $ps['olg_base_string'] = "'%s'"; $args[] = $base_string; - $ps['olg_notes'] = "'%s'"; $args[] = $this->makeUTF8($notes); - $ps['olg_usa_id_ref'] = "NULLIF('%d', '0')"; $args[] = $user_id; - $ps['olg_remote_ip'] = "NULLIF('%s','0.0.0.0')"; $args[] = $remote_ip; - - $this->query(' - INSERT INTO oauth_log ('.implode(',', array_keys($ps)) . ') - VALUES(' . implode(',', $ps) . ')', - $args - ); - } - - /** - * Get a page of entries from the log. Returns the last 100 records - * matching the options given. - * - * @param array options - * @param int user_id current user - * @return array log records - */ - public function listLog ( $options, $user_id ) - { - $where = array(); - $args = array(); - if (empty($options)) - { - $where[] = 'olg_usa_id_ref = \'%d\''; - $args[] = $user_id; - } - else - { - foreach ($options as $option => $value) - { - if (strlen($value) > 0) - { - switch ($option) - { - case 'osr_consumer_key': - case 'ocr_consumer_key': - case 'ost_token': - case 'oct_token': - $where[] = 'olg_'.$option.' = \'%s\''; - $args[] = $value; - break; - } - } - } - - $where[] = '(olg_usa_id_ref IS NULL OR olg_usa_id_ref = \'%d\')'; - $args[] = $user_id; - } - - $rs = $this->query_all_assoc(' - SELECT olg_id, - olg_osr_consumer_key AS osr_consumer_key, - olg_ost_token AS ost_token, - olg_ocr_consumer_key AS ocr_consumer_key, - olg_oct_token AS oct_token, - olg_usa_id_ref AS user_id, - olg_received AS received, - olg_sent AS sent, - olg_base_string AS base_string, - olg_notes AS notes, - olg_timestamp AS timestamp, - olg_remote_ip AS remote_ip - FROM oauth_log - WHERE '.implode(' AND ', $where).' - ORDER BY olg_id DESC - LIMIT 0,100', $args); - - return $rs; - } - - - /* ** Some simple helper functions for querying the pgsql db ** */ - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - */ - protected function query ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = pg_query($this->conn, $sql))) - { - $this->sql_errcheck($sql); - } - $this->_lastAffectedRows = pg_affected_rows($res); - if (is_resource($res)) - { - pg_free_result($res); - } - } - - - /** - * Perform a query, return all rows - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_all_assoc ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = pg_query($this->conn, $sql))) - { - $this->sql_errcheck($sql); - } - $rs = array(); - while ($row = pg_fetch_assoc($res)) - { - $rs[] = $row; - } - pg_free_result($res); - return $rs; - } - - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_row_assoc ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - - if (!($res = pg_query($this->conn, $sql))) - { - $this->sql_errcheck($sql); - } - if ($row = pg_fetch_assoc($res)) - { - $rs = $row; - } - else - { - $rs = false; - } - pg_free_result($res); - return $rs; - } - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - protected function query_row ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = pg_query($this->conn, $sql))) - { - $this->sql_errcheck($sql); - } - if ($row = pg_fetch_array($res)) - { - $rs = $row; - } - else - { - $rs = false; - } - pg_free_result($res); - return $rs; - } - - - /** - * Perform a query, return the first column of the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return mixed - */ - protected function query_one ( $sql ) - { - $sql = $this->sql_printf(func_get_args()); - if (!($res = pg_query($this->conn, $sql))) - { - $this->sql_errcheck($sql); - } - $val = pg_fetch_row($res); - if ($val && isset($val[0])) { - $val = $val[0]; - } - pg_free_result($res); - return $val; - } - - - /** - * Return the number of rows affected in the last query - */ - protected function query_affected_rows () - { - return $this->_lastAffectedRows; - } - - - /** - * Return the id of the last inserted row - * - * @return int - */ - protected function query_insert_id ( $tableName, $primaryKey = null ) - { - $sequenceName = $tableName; - if ($primaryKey) { - $sequenceName .= "_$primaryKey"; - } - $sequenceName .= '_seq'; - - $sql = " - SELECT - CURRVAL('%s') - "; - $args = array($sql, $sequenceName); - $sql = $this->sql_printf($args); - if (!($res = pg_query($this->conn, $sql))) { - return 0; - } - $val = pg_fetch_row($res, 0); - if ($val && isset($val[0])) { - $val = $val[0]; - } - - pg_free_result($res); - return $val; - } - - - protected function sql_printf ( $args ) - { - $sql = array_shift($args); - if (count($args) == 1 && is_array($args[0])) - { - $args = $args[0]; - } - $args = array_map(array($this, 'sql_escape_string'), $args); - return vsprintf($sql, $args); - } - - - protected function sql_escape_string ( $s ) - { - if (is_string($s)) - { - return pg_escape_string($this->conn, $s); - } - else if (is_null($s)) - { - return NULL; - } - else if (is_bool($s)) - { - return intval($s); - } - else if (is_int($s) || is_float($s)) - { - return $s; - } - else - { - return pg_escape_string($this->conn, strval($s)); - } - } - - - protected function sql_errcheck ( $sql ) - { - $msg = "SQL Error in OAuthStorePostgreSQL: ".pg_last_error($this->conn)."\n\n" . $sql; - throw new OAuthException2($msg); - } -} diff --git a/3rdparty/oauth-php/library/store/OAuthStoreSQL.php b/3rdparty/oauth-php/library/store/OAuthStoreSQL.php deleted file mode 100644 index 95e0720a31..0000000000 --- a/3rdparty/oauth-php/library/store/OAuthStoreSQL.php +++ /dev/null @@ -1,1827 +0,0 @@ - - * @date Nov 16, 2007 4:03:30 PM - * - * - * The MIT License - * - * Copyright (c) 2007-2008 Mediamatic Lab - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - - -require_once dirname(__FILE__) . '/OAuthStoreAbstract.class.php'; - - -abstract class OAuthStoreSQL extends OAuthStoreAbstract -{ - /** - * Maximum delta a timestamp may be off from a previous timestamp. - * Allows multiple consumers with some clock skew to work with the same token. - * Unit is seconds, default max skew is 10 minutes. - */ - protected $max_timestamp_skew = 600; - - /** - * Default ttl for request tokens - */ - protected $max_request_token_ttl = 3600; - - - /** - * Construct the OAuthStoreMySQL. - * In the options you have to supply either: - * - server, username, password and database (for a mysql_connect) - * - conn (for the connection to be used) - * - * @param array options - */ - function __construct ( $options = array() ) - { - if (isset($options['conn'])) - { - $this->conn = $options['conn']; - } - else - { - if (isset($options['server'])) - { - $server = $options['server']; - $username = $options['username']; - - if (isset($options['password'])) - { - $this->conn = mysql_connect($server, $username, $options['password']); - } - else - { - $this->conn = mysql_connect($server, $username); - } - } - else - { - // Try the default mysql connect - $this->conn = mysql_connect(); - } - - if ($this->conn === false) - { - throw new OAuthException2('Could not connect to MySQL database: ' . mysql_error()); - } - - if (isset($options['database'])) - { - if (!mysql_select_db($options['database'], $this->conn)) - { - $this->sql_errcheck(); - } - } - $this->query('set character set utf8'); - } - } - - - /** - * Find stored credentials for the consumer key and token. Used by an OAuth server - * when verifying an OAuth request. - * - * @param string consumer_key - * @param string token - * @param string token_type false, 'request' or 'access' - * @exception OAuthException2 when no secrets where found - * @return array assoc (consumer_secret, token_secret, osr_id, ost_id, user_id) - */ - public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ) - { - if ($token_type === false) - { - $rs = $this->query_row_assoc(' - SELECT osr_id, - osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret - FROM oauth_server_registry - WHERE osr_consumer_key = \'%s\' - AND osr_enabled = 1 - ', - $consumer_key); - - if ($rs) - { - $rs['token'] = false; - $rs['token_secret'] = false; - $rs['user_id'] = false; - $rs['ost_id'] = false; - } - } - else - { - $rs = $this->query_row_assoc(' - SELECT osr_id, - ost_id, - ost_usa_id_ref as user_id, - osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret, - ost_token as token, - ost_token_secret as token_secret - FROM oauth_server_registry - JOIN oauth_server_token - ON ost_osr_id_ref = osr_id - WHERE ost_token_type = \'%s\' - AND osr_consumer_key = \'%s\' - AND ost_token = \'%s\' - AND osr_enabled = 1 - AND ost_token_ttl >= NOW() - ', - $token_type, $consumer_key, $token); - } - - if (empty($rs)) - { - throw new OAuthException2('The consumer_key "'.$consumer_key.'" token "'.$token.'" combination does not exist or is not enabled.'); - } - return $rs; - } - - - /** - * Find the server details for signing a request, always looks for an access token. - * The returned credentials depend on which local user is making the request. - * - * The consumer_key must belong to the user or be public (user id is null) - * - * For signing we need all of the following: - * - * consumer_key consumer key associated with the server - * consumer_secret consumer secret associated with this server - * token access token associated with this server - * token_secret secret for the access token - * signature_methods signing methods supported by the server (array) - * - * @todo filter on token type (we should know how and with what to sign this request, and there might be old access tokens) - * @param string uri uri of the server - * @param int user_id id of the logged on user - * @param string name (optional) name of the token (case sensitive) - * @exception OAuthException2 when no credentials found - * @return array - */ - public function getSecretsForSignature ( $uri, $user_id, $name = '' ) - { - // Find a consumer key and token for the given uri - $ps = parse_url($uri); - $host = isset($ps['host']) ? $ps['host'] : 'localhost'; - $path = isset($ps['path']) ? $ps['path'] : ''; - - if (empty($path) || substr($path, -1) != '/') - { - $path .= '/'; - } - - // The owner of the consumer_key is either the user or nobody (public consumer key) - $secrets = $this->query_row_assoc(' - SELECT ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - oct_token as token, - oct_token_secret as token_secret, - ocr_signature_methods as signature_methods - FROM oauth_consumer_registry - JOIN oauth_consumer_token ON oct_ocr_id_ref = ocr_id - WHERE ocr_server_uri_host = \'%s\' - AND ocr_server_uri_path = LEFT(\'%s\', LENGTH(ocr_server_uri_path)) - AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) - AND oct_token_type = \'access\' - AND oct_name = \'%s\' - AND oct_token_ttl >= NOW() - ORDER BY ocr_usa_id_ref DESC, ocr_consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC - LIMIT 0,1 - ', $host, $path, $user_id, $name - ); - - if (empty($secrets)) - { - throw new OAuthException2('No server tokens available for '.$uri); - } - $secrets['signature_methods'] = explode(',', $secrets['signature_methods']); - return $secrets; - } - - - /** - * Get the token and token secret we obtained from a server. - * - * @param string consumer_key - * @param string token - * @param string token_type - * @param int user_id the user owning the token - * @param string name optional name for a named token - * @exception OAuthException2 when no credentials found - * @return array - */ - public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '' ) - { - if ($token_type != 'request' && $token_type != 'access') - { - throw new OAuthException2('Unkown token type "'.$token_type.'", must be either "request" or "access"'); - } - - // Take the most recent token of the given type - $r = $this->query_row_assoc(' - SELECT ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - oct_token as token, - oct_token_secret as token_secret, - oct_name as token_name, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri, - IF(oct_token_ttl >= \'9999-12-31\', NULL, UNIX_TIMESTAMP(oct_token_ttl) - UNIX_TIMESTAMP(NOW())) as token_ttl - FROM oauth_consumer_registry - JOIN oauth_consumer_token - ON oct_ocr_id_ref = ocr_id - WHERE ocr_consumer_key = \'%s\' - AND oct_token_type = \'%s\' - AND oct_token = \'%s\' - AND oct_usa_id_ref = %d - AND oct_token_ttl >= NOW() - ', $consumer_key, $token_type, $token, $user_id - ); - - if (empty($r)) - { - throw new OAuthException2('Could not find a "'.$token_type.'" token for consumer "'.$consumer_key.'" and user '.$user_id); - } - if (isset($r['signature_methods']) && !empty($r['signature_methods'])) - { - $r['signature_methods'] = explode(',',$r['signature_methods']); - } - else - { - $r['signature_methods'] = array(); - } - return $r; - } - - - /** - * Add a request token we obtained from a server. - * - * @todo remove old tokens for this user and this ocr_id - * @param string consumer_key key of the server in the consumer registry - * @param string token_type one of 'request' or 'access' - * @param string token - * @param string token_secret - * @param int user_id the user owning the token - * @param array options extra options, name and token_ttl - * @exception OAuthException2 when server is not known - * @exception OAuthException2 when we received a duplicate token - */ - public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) - { - if ($token_type != 'request' && $token_type != 'access') - { - throw new OAuthException2('Unknown token type "'.$token_type.'", must be either "request" or "access"'); - } - - // Maximum time to live for this token - if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) - { - $ttl = 'DATE_ADD(NOW(), INTERVAL '.intval($options['token_ttl']).' SECOND)'; - } - else if ($token_type == 'request') - { - $ttl = 'DATE_ADD(NOW(), INTERVAL '.$this->max_request_token_ttl.' SECOND)'; - } - else - { - $ttl = "'9999-12-31'"; - } - - if (isset($options['server_uri'])) - { - $ocr_id = $this->query_one(' - SELECT ocr_id - FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND ocr_usa_id_ref = %d - AND ocr_server_uri = \'%s\' - ', $consumer_key, $user_id, $options['server_uri']); - } - else - { - $ocr_id = $this->query_one(' - SELECT ocr_id - FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND ocr_usa_id_ref = %d - ', $consumer_key, $user_id); - } - - if (empty($ocr_id)) - { - throw new OAuthException2('No server associated with consumer_key "'.$consumer_key.'"'); - } - - // Named tokens, unique per user/consumer key - if (isset($options['name']) && $options['name'] != '') - { - $name = $options['name']; - } - else - { - $name = ''; - } - - // Delete any old tokens with the same type and name for this user/server combination - $this->query(' - DELETE FROM oauth_consumer_token - WHERE oct_ocr_id_ref = %d - AND oct_usa_id_ref = %d - AND oct_token_type = LOWER(\'%s\') - AND oct_name = \'%s\' - ', - $ocr_id, - $user_id, - $token_type, - $name); - - // Insert the new token - $this->query(' - INSERT IGNORE INTO oauth_consumer_token - SET oct_ocr_id_ref = %d, - oct_usa_id_ref = %d, - oct_name = \'%s\', - oct_token = \'%s\', - oct_token_secret= \'%s\', - oct_token_type = LOWER(\'%s\'), - oct_timestamp = NOW(), - oct_token_ttl = '.$ttl.' - ', - $ocr_id, - $user_id, - $name, - $token, - $token_secret, - $token_type); - - if (!$this->query_affected_rows()) - { - throw new OAuthException2('Received duplicate token "'.$token.'" for the same consumer_key "'.$consumer_key.'"'); - } - } - - - /** - * Delete a server key. This removes access to that site. - * - * @param string consumer_key - * @param int user_id user registering this server - * @param boolean user_is_admin - */ - public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) - { - if ($user_is_admin) - { - $this->query(' - DELETE FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL) - ', $consumer_key, $user_id); - } - else - { - $this->query(' - DELETE FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND ocr_usa_id_ref = %d - ', $consumer_key, $user_id); - } - } - - - /** - * Get a server from the consumer registry using the consumer key - * - * @param string consumer_key - * @param int user_id - * @param boolean user_is_admin (optional) - * @exception OAuthException2 when server is not found - * @return array - */ - public function getServer ( $consumer_key, $user_id, $user_is_admin = false ) - { - $r = $this->query_row_assoc(' - SELECT ocr_id as id, - ocr_usa_id_ref as user_id, - ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri - FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL) - ', $consumer_key, $user_id); - - if (empty($r)) - { - throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" has been registered (for this user)'); - } - - if (isset($r['signature_methods']) && !empty($r['signature_methods'])) - { - $r['signature_methods'] = explode(',',$r['signature_methods']); - } - else - { - $r['signature_methods'] = array(); - } - return $r; - } - - - - /** - * Find the server details that might be used for a request - * - * The consumer_key must belong to the user or be public (user id is null) - * - * @param string uri uri of the server - * @param int user_id id of the logged on user - * @exception OAuthException2 when no credentials found - * @return array - */ - public function getServerForUri ( $uri, $user_id ) - { - // Find a consumer key and token for the given uri - $ps = parse_url($uri); - $host = isset($ps['host']) ? $ps['host'] : 'localhost'; - $path = isset($ps['path']) ? $ps['path'] : ''; - - if (empty($path) || substr($path, -1) != '/') - { - $path .= '/'; - } - - // The owner of the consumer_key is either the user or nobody (public consumer key) - $server = $this->query_row_assoc(' - SELECT ocr_id as id, - ocr_usa_id_ref as user_id, - ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri - FROM oauth_consumer_registry - WHERE ocr_server_uri_host = \'%s\' - AND ocr_server_uri_path = LEFT(\'%s\', LENGTH(ocr_server_uri_path)) - AND (ocr_usa_id_ref = \'%d\' OR ocr_usa_id_ref IS NULL) - ORDER BY ocr_usa_id_ref DESC, consumer_secret DESC, LENGTH(ocr_server_uri_path) DESC - LIMIT 0,1 - ', $host, $path, $user_id - ); - - if (empty($server)) - { - throw new OAuthException2('No server available for '.$uri); - } - $server['signature_methods'] = explode(',', $server['signature_methods']); - return $server; - } - - - /** - * Get a list of all server token this user has access to. - * - * @param int usr_id - * @return array - */ - public function listServerTokens ( $user_id ) - { - $ts = $this->query_all_assoc(' - SELECT ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - oct_id as token_id, - oct_token as token, - oct_token_secret as token_secret, - oct_usa_id_ref as user_id, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_server_uri_host as server_uri_host, - ocr_server_uri_path as server_uri_path, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri, - oct_timestamp as timestamp - FROM oauth_consumer_registry - JOIN oauth_consumer_token - ON oct_ocr_id_ref = ocr_id - WHERE oct_usa_id_ref = %d - AND oct_token_type = \'access\' - AND oct_token_ttl >= NOW() - ORDER BY ocr_server_uri_host, ocr_server_uri_path - ', $user_id); - return $ts; - } - - - /** - * Count how many tokens we have for the given server - * - * @param string consumer_key - * @return int - */ - public function countServerTokens ( $consumer_key ) - { - $count = $this->query_one(' - SELECT COUNT(oct_id) - FROM oauth_consumer_token - JOIN oauth_consumer_registry - ON oct_ocr_id_ref = ocr_id - WHERE oct_token_type = \'access\' - AND ocr_consumer_key = \'%s\' - AND oct_token_ttl >= NOW() - ', $consumer_key); - - return $count; - } - - - /** - * Get a specific server token for the given user - * - * @param string consumer_key - * @param string token - * @param int user_id - * @exception OAuthException2 when no such token found - * @return array - */ - public function getServerToken ( $consumer_key, $token, $user_id ) - { - $ts = $this->query_row_assoc(' - SELECT ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - oct_token as token, - oct_token_secret as token_secret, - oct_usa_id_ref as usr_id, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_server_uri_host as server_uri_host, - ocr_server_uri_path as server_uri_path, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri, - oct_timestamp as timestamp - FROM oauth_consumer_registry - JOIN oauth_consumer_token - ON oct_ocr_id_ref = ocr_id - WHERE ocr_consumer_key = \'%s\' - AND oct_usa_id_ref = %d - AND oct_token_type = \'access\' - AND oct_token = \'%s\' - AND oct_token_ttl >= NOW() - ', $consumer_key, $user_id, $token); - - if (empty($ts)) - { - throw new OAuthException2('No such consumer key ('.$consumer_key.') and token ('.$token.') combination for user "'.$user_id.'"'); - } - return $ts; - } - - - /** - * Delete a token we obtained from a server. - * - * @param string consumer_key - * @param string token - * @param int user_id - * @param boolean user_is_admin - */ - public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) - { - if ($user_is_admin) - { - $this->query(' - DELETE oauth_consumer_token - FROM oauth_consumer_token - JOIN oauth_consumer_registry - ON oct_ocr_id_ref = ocr_id - WHERE ocr_consumer_key = \'%s\' - AND oct_token = \'%s\' - ', $consumer_key, $token); - } - else - { - $this->query(' - DELETE oauth_consumer_token - FROM oauth_consumer_token - JOIN oauth_consumer_registry - ON oct_ocr_id_ref = ocr_id - WHERE ocr_consumer_key = \'%s\' - AND oct_token = \'%s\' - AND oct_usa_id_ref = %d - ', $consumer_key, $token, $user_id); - } - } - - - /** - * Set the ttl of a server access token. This is done when the - * server receives a valid request with a xoauth_token_ttl parameter in it. - * - * @param string consumer_key - * @param string token - * @param int token_ttl - */ - public function setServerTokenTtl ( $consumer_key, $token, $token_ttl ) - { - if ($token_ttl <= 0) - { - // Immediate delete when the token is past its ttl - $this->deleteServerToken($consumer_key, $token, 0, true); - } - else - { - // Set maximum time to live for this token - $this->query(' - UPDATE oauth_consumer_token, oauth_consumer_registry - SET ost_token_ttl = DATE_ADD(NOW(), INTERVAL %d SECOND) - WHERE ocr_consumer_key = \'%s\' - AND oct_ocr_id_ref = ocr_id - AND oct_token = \'%s\' - ', $token_ttl, $consumer_key, $token); - } - } - - - /** - * Get a list of all consumers from the consumer registry. - * The consumer keys belong to the user or are public (user id is null) - * - * @param string q query term - * @param int user_id - * @return array - */ - public function listServers ( $q = '', $user_id ) - { - $q = trim(str_replace('%', '', $q)); - $args = array(); - - if (!empty($q)) - { - $where = ' WHERE ( ocr_consumer_key like \'%%%s%%\' - OR ocr_server_uri like \'%%%s%%\' - OR ocr_server_uri_host like \'%%%s%%\' - OR ocr_server_uri_path like \'%%%s%%\') - AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL) - '; - - $args[] = $q; - $args[] = $q; - $args[] = $q; - $args[] = $q; - $args[] = $user_id; - } - else - { - $where = ' WHERE ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL'; - $args[] = $user_id; - } - - $servers = $this->query_all_assoc(' - SELECT ocr_id as id, - ocr_usa_id_ref as user_id, - ocr_consumer_key as consumer_key, - ocr_consumer_secret as consumer_secret, - ocr_signature_methods as signature_methods, - ocr_server_uri as server_uri, - ocr_server_uri_host as server_uri_host, - ocr_server_uri_path as server_uri_path, - ocr_request_token_uri as request_token_uri, - ocr_authorize_uri as authorize_uri, - ocr_access_token_uri as access_token_uri - FROM oauth_consumer_registry - '.$where.' - ORDER BY ocr_server_uri_host, ocr_server_uri_path - ', $args); - return $servers; - } - - - /** - * Register or update a server for our site (we will be the consumer) - * - * (This is the registry at the consumers, registering servers ;-) ) - * - * @param array server - * @param int user_id user registering this server - * @param boolean user_is_admin - * @exception OAuthException2 when fields are missing or on duplicate consumer_key - * @return consumer_key - */ - public function updateServer ( $server, $user_id, $user_is_admin = false ) - { - foreach (array('consumer_key', 'server_uri') as $f) - { - if (empty($server[$f])) - { - throw new OAuthException2('The field "'.$f.'" must be set and non empty'); - } - } - - if (!empty($server['id'])) - { - $exists = $this->query_one(' - SELECT ocr_id - FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND ocr_id <> %d - AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL) - ', $server['consumer_key'], $server['id'], $user_id); - } - else - { - $exists = $this->query_one(' - SELECT ocr_id - FROM oauth_consumer_registry - WHERE ocr_consumer_key = \'%s\' - AND (ocr_usa_id_ref = %d OR ocr_usa_id_ref IS NULL) - ', $server['consumer_key'], $user_id); - } - - if ($exists) - { - throw new OAuthException2('The server with key "'.$server['consumer_key'].'" has already been registered'); - } - - $parts = parse_url($server['server_uri']); - $host = (isset($parts['host']) ? $parts['host'] : 'localhost'); - $path = (isset($parts['path']) ? $parts['path'] : '/'); - - if (isset($server['signature_methods'])) - { - if (is_array($server['signature_methods'])) - { - $server['signature_methods'] = strtoupper(implode(',', $server['signature_methods'])); - } - } - else - { - $server['signature_methods'] = ''; - } - - // When the user is an admin, then the user can update the user_id of this record - if ($user_is_admin && array_key_exists('user_id', $server)) - { - if (is_null($server['user_id'])) - { - $update_user = ', ocr_usa_id_ref = NULL'; - } - else - { - $update_user = ', ocr_usa_id_ref = '.intval($server['user_id']); - } - } - else - { - $update_user = ''; - } - - if (!empty($server['id'])) - { - // Check if the current user can update this server definition - if (!$user_is_admin) - { - $ocr_usa_id_ref = $this->query_one(' - SELECT ocr_usa_id_ref - FROM oauth_consumer_registry - WHERE ocr_id = %d - ', $server['id']); - - if ($ocr_usa_id_ref != $user_id) - { - throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this server'); - } - } - - // Update the consumer registration - $this->query(' - UPDATE oauth_consumer_registry - SET ocr_consumer_key = \'%s\', - ocr_consumer_secret = \'%s\', - ocr_server_uri = \'%s\', - ocr_server_uri_host = \'%s\', - ocr_server_uri_path = \'%s\', - ocr_timestamp = NOW(), - ocr_request_token_uri = \'%s\', - ocr_authorize_uri = \'%s\', - ocr_access_token_uri = \'%s\', - ocr_signature_methods = \'%s\' - '.$update_user.' - WHERE ocr_id = %d - ', - $server['consumer_key'], - $server['consumer_secret'], - $server['server_uri'], - strtolower($host), - $path, - isset($server['request_token_uri']) ? $server['request_token_uri'] : '', - isset($server['authorize_uri']) ? $server['authorize_uri'] : '', - isset($server['access_token_uri']) ? $server['access_token_uri'] : '', - $server['signature_methods'], - $server['id'] - ); - } - else - { - if (empty($update_user)) - { - // Per default the user owning the key is the user registering the key - $update_user = ', ocr_usa_id_ref = '.intval($user_id); - } - - $this->query(' - INSERT INTO oauth_consumer_registry - SET ocr_consumer_key = \'%s\', - ocr_consumer_secret = \'%s\', - ocr_server_uri = \'%s\', - ocr_server_uri_host = \'%s\', - ocr_server_uri_path = \'%s\', - ocr_timestamp = NOW(), - ocr_request_token_uri = \'%s\', - ocr_authorize_uri = \'%s\', - ocr_access_token_uri = \'%s\', - ocr_signature_methods = \'%s\' - '.$update_user, - $server['consumer_key'], - $server['consumer_secret'], - $server['server_uri'], - strtolower($host), - $path, - isset($server['request_token_uri']) ? $server['request_token_uri'] : '', - isset($server['authorize_uri']) ? $server['authorize_uri'] : '', - isset($server['access_token_uri']) ? $server['access_token_uri'] : '', - $server['signature_methods'] - ); - - $ocr_id = $this->query_insert_id(); - } - return $server['consumer_key']; - } - - - /** - * Insert/update a new consumer with this server (we will be the server) - * When this is a new consumer, then also generate the consumer key and secret. - * Never updates the consumer key and secret. - * When the id is set, then the key and secret must correspond to the entry - * being updated. - * - * (This is the registry at the server, registering consumers ;-) ) - * - * @param array consumer - * @param int user_id user registering this consumer - * @param boolean user_is_admin - * @return string consumer key - */ - public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) - { - if (!$user_is_admin) - { - foreach (array('requester_name', 'requester_email') as $f) - { - if (empty($consumer[$f])) - { - throw new OAuthException2('The field "'.$f.'" must be set and non empty'); - } - } - } - - if (!empty($consumer['id'])) - { - if (empty($consumer['consumer_key'])) - { - throw new OAuthException2('The field "consumer_key" must be set and non empty'); - } - if (!$user_is_admin && empty($consumer['consumer_secret'])) - { - throw new OAuthException2('The field "consumer_secret" must be set and non empty'); - } - - // Check if the current user can update this server definition - if (!$user_is_admin) - { - $osr_usa_id_ref = $this->query_one(' - SELECT osr_usa_id_ref - FROM oauth_server_registry - WHERE osr_id = %d - ', $consumer['id']); - - if ($osr_usa_id_ref != $user_id) - { - throw new OAuthException2('The user "'.$user_id.'" is not allowed to update this consumer'); - } - } - else - { - // User is an admin, allow a key owner to be changed or key to be shared - if (array_key_exists('user_id',$consumer)) - { - if (is_null($consumer['user_id'])) - { - $this->query(' - UPDATE oauth_server_registry - SET osr_usa_id_ref = NULL - WHERE osr_id = %d - ', $consumer['id']); - } - else - { - $this->query(' - UPDATE oauth_server_registry - SET osr_usa_id_ref = %d - WHERE osr_id = %d - ', $consumer['user_id'], $consumer['id']); - } - } - } - - $this->query(' - UPDATE oauth_server_registry - SET osr_requester_name = \'%s\', - osr_requester_email = \'%s\', - osr_callback_uri = \'%s\', - osr_application_uri = \'%s\', - osr_application_title = \'%s\', - osr_application_descr = \'%s\', - osr_application_notes = \'%s\', - osr_application_type = \'%s\', - osr_application_commercial = IF(%d,1,0), - osr_timestamp = NOW() - WHERE osr_id = %d - AND osr_consumer_key = \'%s\' - AND osr_consumer_secret = \'%s\' - ', - $consumer['requester_name'], - $consumer['requester_email'], - isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '', - isset($consumer['application_uri']) ? $consumer['application_uri'] : '', - isset($consumer['application_title']) ? $consumer['application_title'] : '', - isset($consumer['application_descr']) ? $consumer['application_descr'] : '', - isset($consumer['application_notes']) ? $consumer['application_notes'] : '', - isset($consumer['application_type']) ? $consumer['application_type'] : '', - isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0, - $consumer['id'], - $consumer['consumer_key'], - $consumer['consumer_secret'] - ); - - - $consumer_key = $consumer['consumer_key']; - } - else - { - $consumer_key = $this->generateKey(true); - $consumer_secret= $this->generateKey(); - - // When the user is an admin, then the user can be forced to something else that the user - if ($user_is_admin && array_key_exists('user_id',$consumer)) - { - if (is_null($consumer['user_id'])) - { - $owner_id = 'NULL'; - } - else - { - $owner_id = intval($consumer['user_id']); - } - } - else - { - // No admin, take the user id as the owner id. - $owner_id = intval($user_id); - } - - $this->query(' - INSERT INTO oauth_server_registry - SET osr_enabled = 1, - osr_status = \'active\', - osr_usa_id_ref = \'%s\', - osr_consumer_key = \'%s\', - osr_consumer_secret = \'%s\', - osr_requester_name = \'%s\', - osr_requester_email = \'%s\', - osr_callback_uri = \'%s\', - osr_application_uri = \'%s\', - osr_application_title = \'%s\', - osr_application_descr = \'%s\', - osr_application_notes = \'%s\', - osr_application_type = \'%s\', - osr_application_commercial = IF(%d,1,0), - osr_timestamp = NOW(), - osr_issue_date = NOW() - ', - $owner_id, - $consumer_key, - $consumer_secret, - $consumer['requester_name'], - $consumer['requester_email'], - isset($consumer['callback_uri']) ? $consumer['callback_uri'] : '', - isset($consumer['application_uri']) ? $consumer['application_uri'] : '', - isset($consumer['application_title']) ? $consumer['application_title'] : '', - isset($consumer['application_descr']) ? $consumer['application_descr'] : '', - isset($consumer['application_notes']) ? $consumer['application_notes'] : '', - isset($consumer['application_type']) ? $consumer['application_type'] : '', - isset($consumer['application_commercial']) ? $consumer['application_commercial'] : 0 - ); - } - return $consumer_key; - - } - - - - /** - * Delete a consumer key. This removes access to our site for all applications using this key. - * - * @param string consumer_key - * @param int user_id user registering this server - * @param boolean user_is_admin - */ - public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) - { - if ($user_is_admin) - { - $this->query(' - DELETE FROM oauth_server_registry - WHERE osr_consumer_key = \'%s\' - AND (osr_usa_id_ref = %d OR osr_usa_id_ref IS NULL) - ', $consumer_key, $user_id); - } - else - { - $this->query(' - DELETE FROM oauth_server_registry - WHERE osr_consumer_key = \'%s\' - AND osr_usa_id_ref = %d - ', $consumer_key, $user_id); - } - } - - - - /** - * Fetch a consumer of this server, by consumer_key. - * - * @param string consumer_key - * @param int user_id - * @param boolean user_is_admin (optional) - * @exception OAuthException2 when consumer not found - * @return array - */ - public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) - { - $consumer = $this->query_row_assoc(' - SELECT * - FROM oauth_server_registry - WHERE osr_consumer_key = \'%s\' - ', $consumer_key); - - if (!is_array($consumer)) - { - throw new OAuthException2('No consumer with consumer_key "'.$consumer_key.'"'); - } - - $c = array(); - foreach ($consumer as $key => $value) - { - $c[substr($key, 4)] = $value; - } - $c['user_id'] = $c['usa_id_ref']; - - if (!$user_is_admin && !empty($c['user_id']) && $c['user_id'] != $user_id) - { - throw new OAuthException2('No access to the consumer information for consumer_key "'.$consumer_key.'"'); - } - return $c; - } - - - /** - * Fetch the static consumer key for this provider. The user for the static consumer - * key is NULL (no user, shared key). If the key did not exist then the key is created. - * - * @return string - */ - public function getConsumerStatic () - { - $consumer = $this->query_one(' - SELECT osr_consumer_key - FROM oauth_server_registry - WHERE osr_consumer_key LIKE \'sc-%%\' - AND osr_usa_id_ref IS NULL - '); - - if (empty($consumer)) - { - $consumer_key = 'sc-'.$this->generateKey(true); - $this->query(' - INSERT INTO oauth_server_registry - SET osr_enabled = 1, - osr_status = \'active\', - osr_usa_id_ref = NULL, - osr_consumer_key = \'%s\', - osr_consumer_secret = \'\', - osr_requester_name = \'\', - osr_requester_email = \'\', - osr_callback_uri = \'\', - osr_application_uri = \'\', - osr_application_title = \'Static shared consumer key\', - osr_application_descr = \'\', - osr_application_notes = \'Static shared consumer key\', - osr_application_type = \'\', - osr_application_commercial = 0, - osr_timestamp = NOW(), - osr_issue_date = NOW() - ', - $consumer_key - ); - - // Just make sure that if the consumer key is truncated that we get the truncated string - $consumer = $this->getConsumerStatic(); - } - return $consumer; - } - - - /** - * Add an unautorized request token to our server. - * - * @param string consumer_key - * @param array options (eg. token_ttl) - * @return array (token, token_secret) - */ - public function addConsumerRequestToken ( $consumer_key, $options = array() ) - { - $token = $this->generateKey(true); - $secret = $this->generateKey(); - $osr_id = $this->query_one(' - SELECT osr_id - FROM oauth_server_registry - WHERE osr_consumer_key = \'%s\' - AND osr_enabled = 1 - ', $consumer_key); - - if (!$osr_id) - { - throw new OAuthException2('No server with consumer_key "'.$consumer_key.'" or consumer_key is disabled'); - } - - if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) - { - $ttl = intval($options['token_ttl']); - } - else - { - $ttl = $this->max_request_token_ttl; - } - - if (!isset($options['oauth_callback'])) { - // 1.0a Compatibility : store callback url associated with request token - $options['oauth_callback']='oob'; - } - - $this->query(' - INSERT INTO oauth_server_token - SET ost_osr_id_ref = %d, - ost_usa_id_ref = 1, - ost_token = \'%s\', - ost_token_secret = \'%s\', - ost_token_type = \'request\', - ost_token_ttl = DATE_ADD(NOW(), INTERVAL %d SECOND), - ost_callback_url = \'%s\' - ON DUPLICATE KEY UPDATE - ost_osr_id_ref = VALUES(ost_osr_id_ref), - ost_usa_id_ref = VALUES(ost_usa_id_ref), - ost_token = VALUES(ost_token), - ost_token_secret = VALUES(ost_token_secret), - ost_token_type = VALUES(ost_token_type), - ost_token_ttl = VALUES(ost_token_ttl), - ost_callback_url = VALUES(ost_callback_url), - ost_timestamp = NOW() - ', $osr_id, $token, $secret, $ttl, $options['oauth_callback']); - - return array('token'=>$token, 'token_secret'=>$secret, 'token_ttl'=>$ttl); - } - - - /** - * Fetch the consumer request token, by request token. - * - * @param string token - * @return array token and consumer details - */ - public function getConsumerRequestToken ( $token ) - { - $rs = $this->query_row_assoc(' - SELECT ost_token as token, - ost_token_secret as token_secret, - osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret, - ost_token_type as token_type, - ost_callback_url as callback_url, - osr_application_title as application_title, - osr_application_descr as application_descr, - osr_application_uri as application_uri - FROM oauth_server_token - JOIN oauth_server_registry - ON ost_osr_id_ref = osr_id - WHERE ost_token_type = \'request\' - AND ost_token = \'%s\' - AND ost_token_ttl >= NOW() - ', $token); - - return $rs; - } - - - /** - * Delete a consumer token. The token must be a request or authorized token. - * - * @param string token - */ - public function deleteConsumerRequestToken ( $token ) - { - $this->query(' - DELETE FROM oauth_server_token - WHERE ost_token = \'%s\' - AND ost_token_type = \'request\' - ', $token); - } - - - /** - * Upgrade a request token to be an authorized request token. - * - * @param string token - * @param int user_id user authorizing the token - * @param string referrer_host used to set the referrer host for this token, for user feedback - */ - public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) - { - // 1.0a Compatibility : create a token verifier - $verifier = substr(md5(rand()),0,10); - - $this->query(' - UPDATE oauth_server_token - SET ost_authorized = 1, - ost_usa_id_ref = %d, - ost_timestamp = NOW(), - ost_referrer_host = \'%s\', - ost_verifier = \'%s\' - WHERE ost_token = \'%s\' - AND ost_token_type = \'request\' - ', $user_id, $referrer_host, $verifier, $token); - return $verifier; - } - - - /** - * Count the consumer access tokens for the given consumer. - * - * @param string consumer_key - * @return int - */ - public function countConsumerAccessTokens ( $consumer_key ) - { - $count = $this->query_one(' - SELECT COUNT(ost_id) - FROM oauth_server_token - JOIN oauth_server_registry - ON ost_osr_id_ref = osr_id - WHERE ost_token_type = \'access\' - AND osr_consumer_key = \'%s\' - AND ost_token_ttl >= NOW() - ', $consumer_key); - - return $count; - } - - - /** - * Exchange an authorized request token for new access token. - * - * @param string token - * @param array options options for the token, token_ttl - * @exception OAuthException2 when token could not be exchanged - * @return array (token, token_secret) - */ - public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) - { - $new_token = $this->generateKey(true); - $new_secret = $this->generateKey(); - - // Maximum time to live for this token - if (isset($options['token_ttl']) && is_numeric($options['token_ttl'])) - { - $ttl_sql = 'DATE_ADD(NOW(), INTERVAL '.intval($options['token_ttl']).' SECOND)'; - } - else - { - $ttl_sql = "'9999-12-31'"; - } - - if (isset($options['verifier'])) { - $verifier = $options['verifier']; - - // 1.0a Compatibility : check token against oauth_verifier - $this->query(' - UPDATE oauth_server_token - SET ost_token = \'%s\', - ost_token_secret = \'%s\', - ost_token_type = \'access\', - ost_timestamp = NOW(), - ost_token_ttl = '.$ttl_sql.' - WHERE ost_token = \'%s\' - AND ost_token_type = \'request\' - AND ost_authorized = 1 - AND ost_token_ttl >= NOW() - AND ost_verifier = \'%s\' - ', $new_token, $new_secret, $token, $verifier); - } else { - - // 1.0 - $this->query(' - UPDATE oauth_server_token - SET ost_token = \'%s\', - ost_token_secret = \'%s\', - ost_token_type = \'access\', - ost_timestamp = NOW(), - ost_token_ttl = '.$ttl_sql.' - WHERE ost_token = \'%s\' - AND ost_token_type = \'request\' - AND ost_authorized = 1 - AND ost_token_ttl >= NOW() - ', $new_token, $new_secret, $token); - } - - if ($this->query_affected_rows() != 1) - { - throw new OAuthException2('Can\'t exchange request token "'.$token.'" for access token. No such token or not authorized'); - } - - $ret = array('token' => $new_token, 'token_secret' => $new_secret); - $ttl = $this->query_one(' - SELECT IF(ost_token_ttl >= \'9999-12-31\', NULL, UNIX_TIMESTAMP(ost_token_ttl) - UNIX_TIMESTAMP(NOW())) as token_ttl - FROM oauth_server_token - WHERE ost_token = \'%s\'', $new_token); - - if (is_numeric($ttl)) - { - $ret['token_ttl'] = intval($ttl); - } - return $ret; - } - - - /** - * Fetch the consumer access token, by access token. - * - * @param string token - * @param int user_id - * @exception OAuthException2 when token is not found - * @return array token and consumer details - */ - public function getConsumerAccessToken ( $token, $user_id ) - { - $rs = $this->query_row_assoc(' - SELECT ost_token as token, - ost_token_secret as token_secret, - ost_referrer_host as token_referrer_host, - osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret, - osr_application_uri as application_uri, - osr_application_title as application_title, - osr_application_descr as application_descr, - osr_callback_uri as callback_uri - FROM oauth_server_token - JOIN oauth_server_registry - ON ost_osr_id_ref = osr_id - WHERE ost_token_type = \'access\' - AND ost_token = \'%s\' - AND ost_usa_id_ref = %d - AND ost_token_ttl >= NOW() - ', $token, $user_id); - - if (empty($rs)) - { - throw new OAuthException2('No server_token "'.$token.'" for user "'.$user_id.'"'); - } - return $rs; - } - - - /** - * Delete a consumer access token. - * - * @param string token - * @param int user_id - * @param boolean user_is_admin - */ - public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) - { - if ($user_is_admin) - { - $this->query(' - DELETE FROM oauth_server_token - WHERE ost_token = \'%s\' - AND ost_token_type = \'access\' - ', $token); - } - else - { - $this->query(' - DELETE FROM oauth_server_token - WHERE ost_token = \'%s\' - AND ost_token_type = \'access\' - AND ost_usa_id_ref = %d - ', $token, $user_id); - } - } - - - /** - * Set the ttl of a consumer access token. This is done when the - * server receives a valid request with a xoauth_token_ttl parameter in it. - * - * @param string token - * @param int ttl - */ - public function setConsumerAccessTokenTtl ( $token, $token_ttl ) - { - if ($token_ttl <= 0) - { - // Immediate delete when the token is past its ttl - $this->deleteConsumerAccessToken($token, 0, true); - } - else - { - // Set maximum time to live for this token - $this->query(' - UPDATE oauth_server_token - SET ost_token_ttl = DATE_ADD(NOW(), INTERVAL %d SECOND) - WHERE ost_token = \'%s\' - AND ost_token_type = \'access\' - ', $token_ttl, $token); - } - } - - - /** - * Fetch a list of all consumer keys, secrets etc. - * Returns the public (user_id is null) and the keys owned by the user - * - * @param int user_id - * @return array - */ - public function listConsumers ( $user_id ) - { - $rs = $this->query_all_assoc(' - SELECT osr_id as id, - osr_usa_id_ref as user_id, - osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret, - osr_enabled as enabled, - osr_status as status, - osr_issue_date as issue_date, - osr_application_uri as application_uri, - osr_application_title as application_title, - osr_application_descr as application_descr, - osr_requester_name as requester_name, - osr_requester_email as requester_email, - osr_callback_uri as callback_uri - FROM oauth_server_registry - WHERE (osr_usa_id_ref = %d OR osr_usa_id_ref IS NULL) - ORDER BY osr_application_title - ', $user_id); - return $rs; - } - - /** - * List of all registered applications. Data returned has not sensitive - * information and therefore is suitable for public displaying. - * - * @param int $begin - * @param int $total - * @return array - */ - public function listConsumerApplications($begin = 0, $total = 25) - { - $rs = $this->query_all_assoc(' - SELECT osr_id as id, - osr_enabled as enabled, - osr_status as status, - osr_issue_date as issue_date, - osr_application_uri as application_uri, - osr_application_title as application_title, - osr_application_descr as application_descr - FROM oauth_server_registry - ORDER BY osr_application_title - '); - // TODO: pagination - return $rs; - } - - /** - * Fetch a list of all consumer tokens accessing the account of the given user. - * - * @param int user_id - * @return array - */ - public function listConsumerTokens ( $user_id ) - { - $rs = $this->query_all_assoc(' - SELECT osr_consumer_key as consumer_key, - osr_consumer_secret as consumer_secret, - osr_enabled as enabled, - osr_status as status, - osr_application_uri as application_uri, - osr_application_title as application_title, - osr_application_descr as application_descr, - ost_timestamp as timestamp, - ost_token as token, - ost_token_secret as token_secret, - ost_referrer_host as token_referrer_host, - osr_callback_uri as callback_uri - FROM oauth_server_registry - JOIN oauth_server_token - ON ost_osr_id_ref = osr_id - WHERE ost_usa_id_ref = %d - AND ost_token_type = \'access\' - AND ost_token_ttl >= NOW() - ORDER BY osr_application_title - ', $user_id); - return $rs; - } - - - /** - * Check an nonce/timestamp combination. Clears any nonce combinations - * that are older than the one received. - * - * @param string consumer_key - * @param string token - * @param int timestamp - * @param string nonce - * @exception OAuthException2 thrown when the timestamp is not in sequence or nonce is not unique - */ - public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) - { - $r = $this->query_row(' - SELECT MAX(osn_timestamp), MAX(osn_timestamp) > %d + %d - FROM oauth_server_nonce - WHERE osn_consumer_key = \'%s\' - AND osn_token = \'%s\' - ', $timestamp, $this->max_timestamp_skew, $consumer_key, $token); - - if (!empty($r) && $r[1]) - { - throw new OAuthException2('Timestamp is out of sequence. Request rejected. Got '.$timestamp.' last max is '.$r[0].' allowed skew is '.$this->max_timestamp_skew); - } - - // Insert the new combination - $this->query(' - INSERT IGNORE INTO oauth_server_nonce - SET osn_consumer_key = \'%s\', - osn_token = \'%s\', - osn_timestamp = %d, - osn_nonce = \'%s\' - ', $consumer_key, $token, $timestamp, $nonce); - - if ($this->query_affected_rows() == 0) - { - throw new OAuthException2('Duplicate timestamp/nonce combination, possible replay attack. Request rejected.'); - } - - // Clean up all timestamps older than the one we just received - $this->query(' - DELETE FROM oauth_server_nonce - WHERE osn_consumer_key = \'%s\' - AND osn_token = \'%s\' - AND osn_timestamp < %d - %d - ', $consumer_key, $token, $timestamp, $this->max_timestamp_skew); - } - - - /** - * Add an entry to the log table - * - * @param array keys (osr_consumer_key, ost_token, ocr_consumer_key, oct_token) - * @param string received - * @param string sent - * @param string base_string - * @param string notes - * @param int (optional) user_id - */ - public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) - { - $args = array(); - $ps = array(); - foreach ($keys as $key => $value) - { - $args[] = $value; - $ps[] = "olg_$key = '%s'"; - } - - if (!empty($_SERVER['REMOTE_ADDR'])) - { - $remote_ip = $_SERVER['REMOTE_ADDR']; - } - else if (!empty($_SERVER['REMOTE_IP'])) - { - $remote_ip = $_SERVER['REMOTE_IP']; - } - else - { - $remote_ip = '0.0.0.0'; - } - - // Build the SQL - $ps[] = "olg_received = '%s'"; $args[] = $this->makeUTF8($received); - $ps[] = "olg_sent = '%s'"; $args[] = $this->makeUTF8($sent); - $ps[] = "olg_base_string= '%s'"; $args[] = $base_string; - $ps[] = "olg_notes = '%s'"; $args[] = $this->makeUTF8($notes); - $ps[] = "olg_usa_id_ref = NULLIF(%d,0)"; $args[] = $user_id; - $ps[] = "olg_remote_ip = IFNULL(INET_ATON('%s'),0)"; $args[] = $remote_ip; - - $this->query('INSERT INTO oauth_log SET '.implode(',', $ps), $args); - } - - - /** - * Get a page of entries from the log. Returns the last 100 records - * matching the options given. - * - * @param array options - * @param int user_id current user - * @return array log records - */ - public function listLog ( $options, $user_id ) - { - $where = array(); - $args = array(); - if (empty($options)) - { - $where[] = 'olg_usa_id_ref = %d'; - $args[] = $user_id; - } - else - { - foreach ($options as $option => $value) - { - if (strlen($value) > 0) - { - switch ($option) - { - case 'osr_consumer_key': - case 'ocr_consumer_key': - case 'ost_token': - case 'oct_token': - $where[] = 'olg_'.$option.' = \'%s\''; - $args[] = $value; - break; - } - } - } - - $where[] = '(olg_usa_id_ref IS NULL OR olg_usa_id_ref = %d)'; - $args[] = $user_id; - } - - $rs = $this->query_all_assoc(' - SELECT olg_id, - olg_osr_consumer_key AS osr_consumer_key, - olg_ost_token AS ost_token, - olg_ocr_consumer_key AS ocr_consumer_key, - olg_oct_token AS oct_token, - olg_usa_id_ref AS user_id, - olg_received AS received, - olg_sent AS sent, - olg_base_string AS base_string, - olg_notes AS notes, - olg_timestamp AS timestamp, - INET_NTOA(olg_remote_ip) AS remote_ip - FROM oauth_log - WHERE '.implode(' AND ', $where).' - ORDER BY olg_id DESC - LIMIT 0,100', $args); - - return $rs; - } - - - /* ** Some simple helper functions for querying the mysql db ** */ - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - */ - abstract protected function query ( $sql ); - - - /** - * Perform a query, ignore the results - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - abstract protected function query_all_assoc ( $sql ); - - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - abstract protected function query_row_assoc ( $sql ); - - /** - * Perform a query, return the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return array - */ - abstract protected function query_row ( $sql ); - - - /** - * Perform a query, return the first column of the first row - * - * @param string sql - * @param vararg arguments (for sprintf) - * @return mixed - */ - abstract protected function query_one ( $sql ); - - - /** - * Return the number of rows affected in the last query - */ - abstract protected function query_affected_rows (); - - - /** - * Return the id of the last inserted row - * - * @return int - */ - abstract protected function query_insert_id (); - - - abstract protected function sql_printf ( $args ); - - - abstract protected function sql_escape_string ( $s ); - - - abstract protected function sql_errcheck ( $sql ); -} - - -/* vi:set ts=4 sts=4 sw=4 binary noeol: */ - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/OAuthStoreSession.php b/3rdparty/oauth-php/library/store/OAuthStoreSession.php deleted file mode 100644 index 4202514aca..0000000000 --- a/3rdparty/oauth-php/library/store/OAuthStoreSession.php +++ /dev/null @@ -1,157 +0,0 @@ -session = &$_SESSION['oauth_' . $options['consumer_key']]; - $this->session['consumer_key'] = $options['consumer_key']; - $this->session['consumer_secret'] = $options['consumer_secret']; - $this->session['signature_methods'] = array('HMAC-SHA1'); - $this->session['server_uri'] = $options['server_uri']; - $this->session['request_token_uri'] = $options['request_token_uri']; - $this->session['authorize_uri'] = $options['authorize_uri']; - $this->session['access_token_uri'] = $options['access_token_uri']; - - } - else - { - throw new OAuthException2("OAuthStoreSession needs consumer_token and consumer_secret"); - } - } - - public function getSecretsForVerify ( $consumer_key, $token, $token_type = 'access' ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function getSecretsForSignature ( $uri, $user_id ) - { - return $this->session; - } - - public function getServerTokenSecrets ( $consumer_key, $token, $token_type, $user_id, $name = '') - { - if ($consumer_key != $this->session['consumer_key']) { - return array(); - } - return array( - 'consumer_key' => $consumer_key, - 'consumer_secret' => $this->session['consumer_secret'], - 'token' => $token, - 'token_secret' => $this->session['token_secret'], - 'token_name' => $name, - 'signature_methods' => $this->session['signature_methods'], - 'server_uri' => $this->session['server_uri'], - 'request_token_uri' => $this->session['request_token_uri'], - 'authorize_uri' => $this->session['authorize_uri'], - 'access_token_uri' => $this->session['access_token_uri'], - 'token_ttl' => 3600, - ); - } - - public function addServerToken ( $consumer_key, $token_type, $token, $token_secret, $user_id, $options = array() ) - { - $this->session['token_type'] = $token_type; - $this->session['token'] = $token; - $this->session['token_secret'] = $token_secret; - } - - public function deleteServer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function getServer( $consumer_key, $user_id, $user_is_admin = false ) { - return array( - 'id' => 0, - 'user_id' => $user_id, - 'consumer_key' => $this->session['consumer_key'], - 'consumer_secret' => $this->session['consumer_secret'], - 'signature_methods' => $this->session['signature_methods'], - 'server_uri' => $this->session['server_uri'], - 'request_token_uri' => $this->session['request_token_uri'], - 'authorize_uri' => $this->session['authorize_uri'], - 'access_token_uri' => $this->session['access_token_uri'], - ); - } - - public function getServerForUri ( $uri, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function listServerTokens ( $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function countServerTokens ( $consumer_key ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function getServerToken ( $consumer_key, $token, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function deleteServerToken ( $consumer_key, $token, $user_id, $user_is_admin = false ) { - // TODO - } - - public function setServerTokenTtl ( $consumer_key, $token, $token_ttl ) - { - //This method just needs to exist. It doesn't have to do anything! - } - - public function listServers ( $q = '', $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function updateServer ( $server, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - - public function updateConsumer ( $consumer, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function deleteConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function getConsumer ( $consumer_key, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function getConsumerStatic () { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - - public function addConsumerRequestToken ( $consumer_key, $options = array() ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function getConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function deleteConsumerRequestToken ( $token ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function authorizeConsumerRequestToken ( $token, $user_id, $referrer_host = '' ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function countConsumerAccessTokens ( $consumer_key ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function exchangeConsumerRequestForAccessToken ( $token, $options = array() ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function getConsumerAccessToken ( $token, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function deleteConsumerAccessToken ( $token, $user_id, $user_is_admin = false ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function setConsumerAccessTokenTtl ( $token, $ttl ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - - public function listConsumers ( $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function listConsumerApplications( $begin = 0, $total = 25 ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function listConsumerTokens ( $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - - public function checkServerNonce ( $consumer_key, $token, $timestamp, $nonce ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - - public function addLog ( $keys, $received, $sent, $base_string, $notes, $user_id = null ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - public function listLog ( $options, $user_id ) { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } - - public function install () { throw new OAuthException2("OAuthStoreSession doesn't support " . __METHOD__); } -} - -?> \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/mysql/install.php b/3rdparty/oauth-php/library/store/mysql/install.php deleted file mode 100644 index 0015da5e32..0000000000 --- a/3rdparty/oauth-php/library/store/mysql/install.php +++ /dev/null @@ -1,32 +0,0 @@ - \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/mysql/mysql.sql b/3rdparty/oauth-php/library/store/mysql/mysql.sql deleted file mode 100644 index db7f237fdf..0000000000 --- a/3rdparty/oauth-php/library/store/mysql/mysql.sql +++ /dev/null @@ -1,236 +0,0 @@ -# Datamodel for OAuthStoreMySQL -# -# You need to add the foreign key constraints for the user ids your are using. -# I have commented the constraints out, just look for 'usa_id_ref' to enable them. -# -# The --SPLIT-- markers are used by the install.php script -# -# @version $Id: mysql.sql 156 2010-09-16 15:46:49Z brunobg@corollarium.com $ -# @author Marc Worrell -# - -# Changes: -# -# 2010-09-15 -# ALTER TABLE oauth_server_token MODIFY ost_referrer_host varchar(128) not null default ''; -# -# 2010-07-22 -# ALTER TABLE oauth_consumer_registry DROP INDEX ocr_consumer_key; -# ALTER TABLE oauth_consumer_registry ADD UNIQUE ocr_consumer_key(ocr_consumer_key,ocr_usa_id_ref,ocr_server_uri) -# -# 2010-04-20 (on 103 and 110) -# ALTER TABLE oauth_consumer_registry MODIFY ocr_consumer_key varchar(128) binary not null; -# ALTER TABLE oauth_consumer_registry MODIFY ocr_consumer_secret varchar(128) binary not null; -# -# 2010-04-20 (on 103 and 110) -# ALTER TABLE oauth_server_token ADD ost_verifier char(10); -# ALTER TABLE oauth_server_token ADD ost_callback_url varchar(512); -# -# 2008-10-15 (on r48) Added ttl to consumer and server tokens, added named server tokens -# -# ALTER TABLE oauth_server_token -# ADD ost_token_ttl datetime not null default '9999-12-31', -# ADD KEY (ost_token_ttl); -# -# ALTER TABLE oauth_consumer_token -# ADD oct_name varchar(64) binary not null default '', -# ADD oct_token_ttl datetime not null default '9999-12-31', -# DROP KEY oct_usa_id_ref, -# ADD UNIQUE KEY (oct_usa_id_ref, oct_ocr_id_ref, oct_token_type, oct_name), -# ADD KEY (oct_token_ttl); -# -# 2008-09-09 (on r5) Added referrer host to server access token -# -# ALTER TABLE oauth_server_token ADD ost_referrer_host VARCHAR(128) NOT NULL; -# - - -# -# Log table to hold all OAuth request when you enabled logging -# - -CREATE TABLE IF NOT EXISTS oauth_log ( - olg_id int(11) not null auto_increment, - olg_osr_consumer_key varchar(64) binary, - olg_ost_token varchar(64) binary, - olg_ocr_consumer_key varchar(64) binary, - olg_oct_token varchar(64) binary, - olg_usa_id_ref int(11), - olg_received text not null, - olg_sent text not null, - olg_base_string text not null, - olg_notes text not null, - olg_timestamp timestamp not null default current_timestamp, - olg_remote_ip bigint not null, - - primary key (olg_id), - key (olg_osr_consumer_key, olg_id), - key (olg_ost_token, olg_id), - key (olg_ocr_consumer_key, olg_id), - key (olg_oct_token, olg_id), - key (olg_usa_id_ref, olg_id) - -# , foreign key (olg_usa_id_ref) references any_user_auth (usa_id_ref) -# on update cascade -# on delete cascade -) engine=InnoDB default charset=utf8; - -#--SPLIT-- - -# -# /////////////////// CONSUMER SIDE /////////////////// -# - -# This is a registry of all consumer codes we got from other servers -# The consumer_key/secret is obtained from the server -# We also register the server uri, so that we can find the consumer key and secret -# for a certain server. From that server we can check if we have a token for a -# particular user. - -CREATE TABLE IF NOT EXISTS oauth_consumer_registry ( - ocr_id int(11) not null auto_increment, - ocr_usa_id_ref int(11), - ocr_consumer_key varchar(128) binary not null, - ocr_consumer_secret varchar(128) binary not null, - ocr_signature_methods varchar(255) not null default 'HMAC-SHA1,PLAINTEXT', - ocr_server_uri varchar(255) not null, - ocr_server_uri_host varchar(128) not null, - ocr_server_uri_path varchar(128) binary not null, - - ocr_request_token_uri varchar(255) not null, - ocr_authorize_uri varchar(255) not null, - ocr_access_token_uri varchar(255) not null, - ocr_timestamp timestamp not null default current_timestamp, - - primary key (ocr_id), - unique key (ocr_consumer_key, ocr_usa_id_ref, ocr_server_uri), - key (ocr_server_uri), - key (ocr_server_uri_host, ocr_server_uri_path), - key (ocr_usa_id_ref) - -# , foreign key (ocr_usa_id_ref) references any_user_auth(usa_id_ref) -# on update cascade -# on delete set null -) engine=InnoDB default charset=utf8; - -#--SPLIT-- - -# Table used to sign requests for sending to a server by the consumer -# The key is defined for a particular user. Only one single named -# key is allowed per user/server combination - -CREATE TABLE IF NOT EXISTS oauth_consumer_token ( - oct_id int(11) not null auto_increment, - oct_ocr_id_ref int(11) not null, - oct_usa_id_ref int(11) not null, - oct_name varchar(64) binary not null default '', - oct_token varchar(64) binary not null, - oct_token_secret varchar(64) binary not null, - oct_token_type enum('request','authorized','access'), - oct_token_ttl datetime not null default '9999-12-31', - oct_timestamp timestamp not null default current_timestamp, - - primary key (oct_id), - unique key (oct_ocr_id_ref, oct_token), - unique key (oct_usa_id_ref, oct_ocr_id_ref, oct_token_type, oct_name), - key (oct_token_ttl), - - foreign key (oct_ocr_id_ref) references oauth_consumer_registry (ocr_id) - on update cascade - on delete cascade - -# , foreign key (oct_usa_id_ref) references any_user_auth (usa_id_ref) -# on update cascade -# on delete cascade -) engine=InnoDB default charset=utf8; - -#--SPLIT-- - - -# -# ////////////////// SERVER SIDE ///////////////// -# - -# Table holding consumer key/secret combos an user issued to consumers. -# Used for verification of incoming requests. - -CREATE TABLE IF NOT EXISTS oauth_server_registry ( - osr_id int(11) not null auto_increment, - osr_usa_id_ref int(11), - osr_consumer_key varchar(64) binary not null, - osr_consumer_secret varchar(64) binary not null, - osr_enabled tinyint(1) not null default '1', - osr_status varchar(16) not null, - osr_requester_name varchar(64) not null, - osr_requester_email varchar(64) not null, - osr_callback_uri varchar(255) not null, - osr_application_uri varchar(255) not null, - osr_application_title varchar(80) not null, - osr_application_descr text not null, - osr_application_notes text not null, - osr_application_type varchar(20) not null, - osr_application_commercial tinyint(1) not null default '0', - osr_issue_date datetime not null, - osr_timestamp timestamp not null default current_timestamp, - - primary key (osr_id), - unique key (osr_consumer_key), - key (osr_usa_id_ref) - -# , foreign key (osr_usa_id_ref) references any_user_auth(usa_id_ref) -# on update cascade -# on delete set null -) engine=InnoDB default charset=utf8; - -#--SPLIT-- - -# Nonce used by a certain consumer, every used nonce should be unique, this prevents -# replaying attacks. We need to store all timestamp/nonce combinations for the -# maximum timestamp received. - -CREATE TABLE IF NOT EXISTS oauth_server_nonce ( - osn_id int(11) not null auto_increment, - osn_consumer_key varchar(64) binary not null, - osn_token varchar(64) binary not null, - osn_timestamp bigint not null, - osn_nonce varchar(80) binary not null, - - primary key (osn_id), - unique key (osn_consumer_key, osn_token, osn_timestamp, osn_nonce) -) engine=InnoDB default charset=utf8; - -#--SPLIT-- - -# Table used to verify signed requests sent to a server by the consumer -# When the verification is succesful then the associated user id is returned. - -CREATE TABLE IF NOT EXISTS oauth_server_token ( - ost_id int(11) not null auto_increment, - ost_osr_id_ref int(11) not null, - ost_usa_id_ref int(11) not null, - ost_token varchar(64) binary not null, - ost_token_secret varchar(64) binary not null, - ost_token_type enum('request','access'), - ost_authorized tinyint(1) not null default '0', - ost_referrer_host varchar(128) not null default '', - ost_token_ttl datetime not null default '9999-12-31', - ost_timestamp timestamp not null default current_timestamp, - ost_verifier char(10), - ost_callback_url varchar(512), - - primary key (ost_id), - unique key (ost_token), - key (ost_osr_id_ref), - key (ost_token_ttl), - - foreign key (ost_osr_id_ref) references oauth_server_registry (osr_id) - on update cascade - on delete cascade - -# , foreign key (ost_usa_id_ref) references any_user_auth (usa_id_ref) -# on update cascade -# on delete cascade -) engine=InnoDB default charset=utf8; - - - diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql b/3rdparty/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql deleted file mode 100644 index 3d4fa22d6f..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/1_Tables/TABLES.sql +++ /dev/null @@ -1,114 +0,0 @@ -CREATE TABLE oauth_log -( - olg_id number, - olg_osr_consumer_key varchar2(64), - olg_ost_token varchar2(64), - olg_ocr_consumer_key varchar2(64), - olg_oct_token varchar2(64), - olg_usa_id_ref number, - olg_received varchar2(500), - olg_sent varchar2(500), - olg_base_string varchar2(500), - olg_notes varchar2(500), - olg_timestamp date default sysdate, - olg_remote_ip varchar2(50) -); - -alter table oauth_log - add constraint oauth_log_pk primary key (olg_id); - - -CREATE TABLE oauth_consumer_registry -( - ocr_id number, - ocr_usa_id_ref number, - ocr_consumer_key varchar2(64), - ocr_consumer_secret varchar2(64), - ocr_signature_methods varchar2(255)default 'HMAC-SHA1,PLAINTEXT', - ocr_server_uri varchar2(255), - ocr_server_uri_host varchar2(128), - ocr_server_uri_path varchar2(128), - ocr_request_token_uri varchar2(255), - ocr_authorize_uri varchar2(255), - ocr_access_token_uri varchar2(255), - ocr_timestamp date default sysdate -) - -alter table oauth_consumer_registry - add constraint oauth_consumer_registry_pk primary key (ocr_id); - - -CREATE TABLE oauth_consumer_token -( - oct_id number, - oct_ocr_id_ref number, - oct_usa_id_ref number, - oct_name varchar2(64) default '', - oct_token varchar2(64), - oct_token_secret varchar2(64), - oct_token_type varchar2(20), -- enum('request','authorized','access'), - oct_token_ttl date default TO_DATE('9999.12.31', 'yyyy.mm.dd'), - oct_timestamp date default sysdate -); - -alter table oauth_consumer_token - add constraint oauth_consumer_token_pk primary key (oct_id); - - -CREATE TABLE oauth_server_registry -( - osr_id number, - osr_usa_id_ref number, - osr_consumer_key varchar2(64), - osr_consumer_secret varchar2(64), - osr_enabled integer default '1', - osr_status varchar2(16), - osr_requester_name varchar2(64), - osr_requester_email varchar2(64), - osr_callback_uri varchar2(255), - osr_application_uri varchar2(255), - osr_application_title varchar2(80), - osr_application_descr varchar2(500), - osr_application_notes varchar2(500), - osr_application_type varchar2(20), - osr_application_commercial integer default '0', - osr_issue_date date, - osr_timestamp date default sysdate -); - - -alter table oauth_server_registry - add constraint oauth_server_registry_pk primary key (osr_id); - - -CREATE TABLE oauth_server_nonce -( - osn_id number, - osn_consumer_key varchar2(64), - osn_token varchar2(64), - osn_timestamp number, - osn_nonce varchar2(80) -); - -alter table oauth_server_nonce - add constraint oauth_server_nonce_pk primary key (osn_id); - - -CREATE TABLE oauth_server_token -( - ost_id number, - ost_osr_id_ref number, - ost_usa_id_ref number, - ost_token varchar2(64), - ost_token_secret varchar2(64), - ost_token_type varchar2(20), -- enum('request','access'), - ost_authorized integer default '0', - ost_referrer_host varchar2(128), - ost_token_ttl date default TO_DATE('9999.12.31', 'yyyy.mm.dd'), - ost_timestamp date default sysdate, - ost_verifier varchar2(10), - ost_callback_url varchar2(512) -); - -alter table oauth_server_token - add constraint oauth_server_token_pk primary key (ost_id); \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql b/3rdparty/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql deleted file mode 100644 index 53e4227888..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/2_Sequences/SEQUENCES.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE SEQUENCE SEQ_OCT_ID NOCACHE; - -CREATE SEQUENCE SEQ_OCR_ID NOCACHE; - -CREATE SEQUENCE SEQ_OSR_ID NOCACHE; - -CREATE SEQUENCE SEQ_OSN_ID NOCACHE; - -CREATE SEQUENCE SEQ_OLG_ID NOCACHE; diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc deleted file mode 100644 index efb9536502..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_CONSUMER_REQUEST_TOKEN.prc +++ /dev/null @@ -1,71 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_ADD_CONSUMER_REQUEST_TOKEN -( -P_TOKEN_TTL IN NUMBER, -- IN SECOND -P_CONSUMER_KEY IN VARCHAR2, -P_TOKEN IN VARCHAR2, -P_TOKEN_SECRET IN VARCHAR2, -P_CALLBACK_URL IN VARCHAR2, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Add an unautorized request token to our server. - -V_OSR_ID NUMBER; -V_OSR_ID_REF NUMBER; - -V_EXC_NO_SERVER_EXIST EXCEPTION; -BEGIN - - P_RESULT := 0; - - BEGIN - SELECT OSR_ID INTO V_OSR_ID - FROM OAUTH_SERVER_REGISTRY - WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY - AND OSR_ENABLED = 1; - EXCEPTION - WHEN NO_DATA_FOUND THEN - RAISE V_EXC_NO_SERVER_EXIST; - END; - - -BEGIN - SELECT OST_OSR_ID_REF INTO V_OSR_ID_REF - FROM OAUTH_SERVER_TOKEN - WHERE OST_OSR_ID_REF = V_OSR_ID; - - UPDATE OAUTH_SERVER_TOKEN - SET OST_OSR_ID_REF = V_OSR_ID, - OST_USA_ID_REF = 1, - OST_TOKEN = P_TOKEN, - OST_TOKEN_SECRET = P_TOKEN_SECRET, - OST_TOKEN_TYPE = 'REQUEST', - OST_TOKEN_TTL = SYSDATE + (P_TOKEN_TTL/(24*60*60)), - OST_CALLBACK_URL = P_CALLBACK_URL, - OST_TIMESTAMP = SYSDATE - WHERE OST_OSR_ID_REF = V_OSR_ID_REF; - - - EXCEPTION - WHEN NO_DATA_FOUND THEN - - INSERT INTO OAUTH_SERVER_TOKEN - (OST_ID, OST_OSR_ID_REF, OST_USA_ID_REF, OST_TOKEN, OST_TOKEN_SECRET, OST_TOKEN_TYPE, - OST_TOKEN_TTL, OST_CALLBACK_URL) - VALUES - (SEQ_OCT_ID.NEXTVAL, V_OSR_ID, 1, P_TOKEN, P_TOKEN_SECRET, 'REQUEST', SYSDATE + (P_TOKEN_TTL/(24*60*60)), - P_CALLBACK_URL); - - END; - - -EXCEPTION -WHEN V_EXC_NO_SERVER_EXIST THEN -P_RESULT := 2; -- NO_SERVER_EXIST -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc deleted file mode 100644 index 329499d9c9..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_LOG.prc +++ /dev/null @@ -1,31 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_ADD_LOG -( -P_RECEIVED IN VARCHAR2, -P_SENT IN VARCHAR2, -P_BASE_STRING IN VARCHAR2, -P_NOTES IN VARCHAR2, -P_USA_ID_REF IN NUMBER, -P_REMOTE_IP IN VARCHAR2, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Add an entry to the log table - -BEGIN - - P_RESULT := 0; - - INSERT INTO oauth_log - (OLG_ID, olg_received, olg_sent, olg_base_string, olg_notes, olg_usa_id_ref, olg_remote_ip) - VALUES - (SEQ_OLG_ID.NEXTVAL, P_RECEIVED, P_SENT, P_BASE_STRING, P_NOTES, NVL(P_USA_ID_REF, 0), P_REMOTE_IP); - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc deleted file mode 100644 index 371134c9b6..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_ADD_SERVER_TOKEN.prc +++ /dev/null @@ -1,55 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_ADD_SERVER_TOKEN -( -P_CONSUMER_KEY IN VARCHAR2, -P_USER_ID IN NUMBER, -P_NAME IN VARCHAR2, -P_TOKEN_TYPE IN VARCHAR2, -P_TOKEN IN VARCHAR2, -P_TOKEN_SECRET IN VARCHAR2, -P_TOKEN_INTERVAL_IN_SEC IN NUMBER, -P_RESULT OUT NUMBER -) -AS - - -- Add a request token we obtained from a server. -V_OCR_ID NUMBER; -V_TOKEN_TTL DATE; - -V_EXC_INVALID_CONSUMER_KEY EXCEPTION; -BEGIN -P_RESULT := 0; - - BEGIN - SELECT OCR_ID INTO V_OCR_ID FROM OAUTH_CONSUMER_REGISTRY - WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY AND OCR_USA_ID_REF = P_USER_ID; - EXCEPTION - WHEN NO_DATA_FOUND THEN - RAISE V_EXC_INVALID_CONSUMER_KEY; - END; - - DELETE FROM OAUTH_CONSUMER_TOKEN - WHERE OCT_OCR_ID_REF = V_OCR_ID - AND OCT_USA_ID_REF = P_USER_ID - AND UPPER(OCT_TOKEN_TYPE) = UPPER(P_TOKEN_TYPE) - AND OCT_NAME = P_NAME; - - IF P_TOKEN_INTERVAL_IN_SEC IS NOT NULL THEN - V_TOKEN_TTL := SYSDATE + (P_TOKEN_INTERVAL_IN_SEC/(24*60*60)); - ELSE - V_TOKEN_TTL := TO_DATE('9999.12.31', 'yyyy.mm.dd'); - END IF; - - INSERT INTO OAUTH_CONSUMER_TOKEN - (OCT_ID, OCT_OCR_ID_REF,OCT_USA_ID_REF, OCT_NAME, OCT_TOKEN, OCT_TOKEN_SECRET, OCT_TOKEN_TYPE, OCT_TIMESTAMP, OCT_TOKEN_TTL) - VALUES - (SEQ_OCT_ID.NEXTVAL, V_OCR_ID, P_USER_ID, P_NAME, P_TOKEN, P_TOKEN_SECRET, UPPER(P_TOKEN_TYPE), SYSDATE, V_TOKEN_TTL); - -EXCEPTION -WHEN V_EXC_INVALID_CONSUMER_KEY THEN -P_RESULT := 2; -- INVALID_CONSUMER_KEY -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc deleted file mode 100644 index c3693491d5..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_AUTH_CONSUMER_REQ_TOKEN.prc +++ /dev/null @@ -1,32 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_AUTH_CONSUMER_REQ_TOKEN -( -P_USER_ID IN NUMBER, -P_REFERRER_HOST IN VARCHAR2, -P_VERIFIER IN VARCHAR2, -P_TOKEN IN VARCHAR2, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Fetch the consumer request token, by request token. -BEGIN -P_RESULT := 0; - - -UPDATE OAUTH_SERVER_TOKEN - SET OST_AUTHORIZED = 1, - OST_USA_ID_REF = P_USER_ID, - OST_TIMESTAMP = SYSDATE, - OST_REFERRER_HOST = P_REFERRER_HOST, - OST_VERIFIER = P_VERIFIER - WHERE OST_TOKEN = P_TOKEN - AND OST_TOKEN_TYPE = 'REQUEST'; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc deleted file mode 100644 index 444a70fcc8..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CHECK_SERVER_NONCE.prc +++ /dev/null @@ -1,81 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_CHECK_SERVER_NONCE -( -P_CONSUMER_KEY IN VARCHAR2, -P_TOKEN IN VARCHAR2, -P_TIMESTAMP IN NUMBER, -P_MAX_TIMESTAMP_SKEW IN NUMBER, -P_NONCE IN VARCHAR2, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Check an nonce/timestamp combination. Clears any nonce combinations - -- that are older than the one received. -V_IS_MAX NUMBER; -V_MAX_TIMESTAMP NUMBER; -V_IS_DUPLICATE_TIMESTAMP NUMBER; - -V_EXC_INVALID_TIMESTAMP EXCEPTION; -V_EXC_DUPLICATE_TIMESTAMP EXCEPTION; -BEGIN - - P_RESULT := 0; - - BEGIN - SELECT MAX(OSN_TIMESTAMP), - CASE - WHEN MAX(OSN_TIMESTAMP) > (P_TIMESTAMP + P_MAX_TIMESTAMP_SKEW) THEN 1 ELSE 0 - END "IS_MAX" INTO V_MAX_TIMESTAMP, V_IS_MAX - FROM OAUTH_SERVER_NONCE - WHERE OSN_CONSUMER_KEY = P_CONSUMER_KEY - AND OSN_TOKEN = P_TOKEN; - - IF V_IS_MAX = 1 THEN - RAISE V_EXC_INVALID_TIMESTAMP; - END IF; - - EXCEPTION - WHEN NO_DATA_FOUND THEN - NULL; - END; - - BEGIN - SELECT 1 INTO V_IS_DUPLICATE_TIMESTAMP FROM DUAL WHERE EXISTS - (SELECT OSN_ID FROM OAUTH_SERVER_NONCE - WHERE OSN_CONSUMER_KEY = P_CONSUMER_KEY - AND OSN_TOKEN = P_TOKEN - AND OSN_TIMESTAMP = P_TIMESTAMP - AND OSN_NONCE = P_NONCE); - - IF V_IS_DUPLICATE_TIMESTAMP = 1 THEN - RAISE V_EXC_DUPLICATE_TIMESTAMP; - END IF; - EXCEPTION - WHEN NO_DATA_FOUND THEN - NULL; - END; - - -- Insert the new combination - INSERT INTO OAUTH_SERVER_NONCE - (OSN_ID, OSN_CONSUMER_KEY, OSN_TOKEN, OSN_TIMESTAMP, OSN_NONCE) - VALUES - (SEQ_OSN_ID.NEXTVAL, P_CONSUMER_KEY, P_TOKEN, P_TIMESTAMP, P_NONCE); - - -- Clean up all timestamps older than the one we just received - DELETE FROM OAUTH_SERVER_NONCE - WHERE OSN_CONSUMER_KEY = P_CONSUMER_KEY - AND OSN_TOKEN = P_TOKEN - AND OSN_TIMESTAMP < (P_TIMESTAMP - P_MAX_TIMESTAMP_SKEW); - - -EXCEPTION -WHEN V_EXC_INVALID_TIMESTAMP THEN -P_RESULT := 2; -- INVALID_TIMESTAMP -WHEN V_EXC_DUPLICATE_TIMESTAMP THEN -P_RESULT := 3; -- DUPLICATE_TIMESTAMP -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc deleted file mode 100644 index 047c77bf2d..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_CONSUMER_STATIC_SAVE.prc +++ /dev/null @@ -1,28 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_CONSUMER_STATIC_SAVE -( -P_OSR_CONSUMER_KEY IN VARCHAR2, -P_RESULT OUT NUMBER -) -AS - --- PROCEDURE TO Fetch the static consumer key for this provider. -BEGIN -P_RESULT := 0; - - - INSERT INTO OAUTH_SERVER_REGISTRY - (OSR_ID, OSR_ENABLED, OSR_STATUS, OSR_USA_ID_REF, OSR_CONSUMER_KEY, OSR_CONSUMER_SECRET, OSR_REQUESTER_NAME, OSR_REQUESTER_EMAIL, OSR_CALLBACK_URI, - OSR_APPLICATION_URI, OSR_APPLICATION_TITLE, OSR_APPLICATION_DESCR, OSR_APPLICATION_NOTES, - OSR_APPLICATION_TYPE, OSR_APPLICATION_COMMERCIAL, OSR_TIMESTAMP,OSR_ISSUE_DATE) - VALUES - (SEQ_OSR_ID.NEXTVAL, 1, 'ACTIVE', NULL, P_OSR_CONSUMER_KEY, '\', '\', '\', '\', '\', - 'STATIC SHARED CONSUMER KEY', '\', 'STATIC SHARED CONSUMER KEY', '\', 0, SYSDATE, SYSDATE); - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc deleted file mode 100644 index f7099b9795..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_CONSUMER_ACCESS_TOKEN.prc +++ /dev/null @@ -1,27 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_COUNT_CONSUMER_ACCESS_TOKEN -( -P_CONSUMER_KEY IN VARCHAR2, -P_COUNT OUT NUMBER, -P_RESULT OUT NUMBER -) -AS --- PROCEDURE TO Count the consumer access tokens for the given consumer. -BEGIN -P_RESULT := 0; - -SELECT COUNT(OST_ID) INTO P_COUNT - FROM OAUTH_SERVER_TOKEN - JOIN OAUTH_SERVER_REGISTRY - ON OST_OSR_ID_REF = OSR_ID - WHERE OST_TOKEN_TYPE = 'ACCESS' - AND OSR_CONSUMER_KEY = P_CONSUMER_KEY - AND OST_TOKEN_TTL >= SYSDATE; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc deleted file mode 100644 index c73b366822..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_COUNT_SERVICE_TOKENS.prc +++ /dev/null @@ -1,28 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_COUNT_SERVICE_TOKENS -( -P_CONSUMER_KEY IN VARCHAR2, -P_COUNT OUT NUMBER, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Count how many tokens we have for the given server -BEGIN -P_RESULT := 0; - - SELECT COUNT(OCT_ID) INTO P_COUNT - FROM OAUTH_CONSUMER_TOKEN - JOIN OAUTH_CONSUMER_REGISTRY - ON OCT_OCR_ID_REF = OCR_ID - WHERE OCT_TOKEN_TYPE = 'ACCESS' - AND OCR_CONSUMER_KEY = P_CONSUMER_KEY - AND OCT_TOKEN_TTL >= SYSDATE; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc deleted file mode 100644 index 3f18562ef7..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_CONSUMER.prc +++ /dev/null @@ -1,35 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_DELETE_CONSUMER -( -P_CONSUMER_KEY IN VARCHAR2, -P_USER_ID IN NUMBER, -P_USER_IS_ADMIN IN NUMBER, --0:NO; 1:YES -P_RESULT OUT NUMBER -) -AS - - -- Delete a consumer key. This removes access to our site for all applications using this key. - -BEGIN -P_RESULT := 0; - -IF P_USER_IS_ADMIN = 1 THEN - - DELETE FROM OAUTH_SERVER_REGISTRY - WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY - AND (OSR_USA_ID_REF = P_USER_ID OR OSR_USA_ID_REF IS NULL); - -ELSIF P_USER_IS_ADMIN = 0 THEN - - DELETE FROM OAUTH_SERVER_REGISTRY - WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY - AND OSR_USA_ID_REF = P_USER_ID; - -END IF; - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc deleted file mode 100644 index ba259dee98..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER.prc +++ /dev/null @@ -1,35 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_DELETE_SERVER -( -P_CONSUMER_KEY IN VARCHAR2, -P_USER_ID IN NUMBER, -P_USER_IS_ADMIN IN NUMBER, --0:NO; 1:YES -P_RESULT OUT NUMBER -) -AS - - -- Delete a server key. This removes access to that site. - -BEGIN -P_RESULT := 0; - -IF P_USER_IS_ADMIN = 1 THEN - - DELETE FROM OAUTH_CONSUMER_REGISTRY - WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY - AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL); - -ELSIF P_USER_IS_ADMIN = 0 THEN - - DELETE FROM OAUTH_CONSUMER_REGISTRY - WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY - AND OCR_USA_ID_REF = P_USER_ID; - -END IF; - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc deleted file mode 100644 index de9d45007b..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DELETE_SERVER_TOKEN.prc +++ /dev/null @@ -1,37 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_DELETE_SERVER_TOKEN -( -P_CONSUMER_KEY IN VARCHAR2, -P_USER_ID IN NUMBER, -P_TOKEN IN VARCHAR2, -P_USER_IS_ADMIN IN NUMBER, --0:NO; 1:YES -P_RESULT OUT NUMBER -) -AS - - -- Delete a token we obtained from a server. - -BEGIN -P_RESULT := 0; - -IF P_USER_IS_ADMIN = 1 THEN - - DELETE FROM OAUTH_CONSUMER_TOKEN - WHERE OCT_TOKEN = P_TOKEN - AND OCT_OCR_ID_REF IN (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY); - -ELSIF P_USER_IS_ADMIN = 0 THEN - - DELETE FROM OAUTH_CONSUMER_TOKEN - WHERE OCT_TOKEN = P_TOKEN - AND OCT_USA_ID_REF = P_USER_ID - AND OCT_OCR_ID_REF IN (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY); - -END IF; - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc deleted file mode 100644 index 4281bdb9de..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_ACCESS_TOKEN.prc +++ /dev/null @@ -1,33 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_DEL_CONSUMER_ACCESS_TOKEN -( -P_USER_ID IN NUMBER, -P_TOKEN IN VARCHAR2, -P_USER_IS_ADMIN IN NUMBER, -- 1:YES; 0:NO -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Delete a consumer access token. - -BEGIN - - P_RESULT := 0; - - IF P_USER_IS_ADMIN = 1 THEN - DELETE FROM OAUTH_SERVER_TOKEN - WHERE OST_TOKEN = P_TOKEN - AND OST_TOKEN_TYPE = 'ACCESS'; - ELSE - DELETE FROM OAUTH_SERVER_TOKEN - WHERE OST_TOKEN = P_TOKEN - AND OST_TOKEN_TYPE = 'ACCESS' - AND OST_USA_ID_REF = P_USER_ID; - END IF; - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc deleted file mode 100644 index 01678d6bd4..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_DEL_CONSUMER_REQUEST_TOKEN.prc +++ /dev/null @@ -1,25 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_DEL_CONSUMER_REQUEST_TOKEN -( -P_TOKEN IN VARCHAR2, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Delete a consumer token. The token must be a request or authorized token. - -BEGIN - - P_RESULT := 0; - - DELETE FROM OAUTH_SERVER_TOKEN - WHERE OST_TOKEN = P_TOKEN - AND OST_TOKEN_TYPE = 'REQUEST'; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc deleted file mode 100644 index 66a53ed836..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_EXCH_CONS_REQ_FOR_ACC_TOKEN.prc +++ /dev/null @@ -1,96 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_EXCH_CONS_REQ_FOR_ACC_TOKEN -( -P_TOKEN_TTL IN NUMBER, -- IN SECOND -P_NEW_TOKEN IN VARCHAR2, -P_TOKEN IN VARCHAR2, -P_TOKEN_SECRET IN VARCHAR2, -P_VERIFIER IN VARCHAR2, -P_OUT_TOKEN_TTL OUT NUMBER, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Add an unautorized request token to our server. - -V_TOKEN_EXIST NUMBER; - - -V_EXC_NO_TOKEN_EXIST EXCEPTION; -BEGIN - - P_RESULT := 0; - - IF P_VERIFIER IS NOT NULL THEN - - BEGIN - SELECT 1 INTO V_TOKEN_EXIST FROM DUAL WHERE EXISTS - (SELECT OST_TOKEN FROM OAUTH_SERVER_TOKEN - WHERE OST_TOKEN = P_TOKEN - AND OST_TOKEN_TYPE = 'REQUEST' - AND OST_AUTHORIZED = 1 - AND OST_TOKEN_TTL >= SYSDATE - AND OST_VERIFIER = P_VERIFIER); - EXCEPTION - WHEN NO_DATA_FOUND THEN - RAISE V_EXC_NO_TOKEN_EXIST; - END; - - UPDATE OAUTH_SERVER_TOKEN - SET OST_TOKEN = P_NEW_TOKEN, - OST_TOKEN_SECRET = P_TOKEN_SECRET, - OST_TOKEN_TYPE = 'ACCESS', - OST_TIMESTAMP = SYSDATE, - OST_TOKEN_TTL = NVL(SYSDATE + (P_TOKEN_TTL/(24*60*60)), TO_DATE('9999.12.31', 'yyyy.mm.dd')) - WHERE OST_TOKEN = P_TOKEN - AND OST_TOKEN_TYPE = 'REQUEST' - AND OST_AUTHORIZED = 1 - AND OST_TOKEN_TTL >= SYSDATE - AND OST_VERIFIER = P_VERIFIER; - - ELSE - BEGIN - SELECT 1 INTO V_TOKEN_EXIST FROM DUAL WHERE EXISTS - (SELECT OST_TOKEN FROM OAUTH_SERVER_TOKEN - WHERE OST_TOKEN = P_TOKEN - AND OST_TOKEN_TYPE = 'REQUEST' - AND OST_AUTHORIZED = 1 - AND OST_TOKEN_TTL >= SYSDATE); - EXCEPTION - WHEN NO_DATA_FOUND THEN - RAISE V_EXC_NO_TOKEN_EXIST; - END; - - UPDATE OAUTH_SERVER_TOKEN - SET OST_TOKEN = P_NEW_TOKEN, - OST_TOKEN_SECRET = P_TOKEN_SECRET, - OST_TOKEN_TYPE = 'ACCESS', - OST_TIMESTAMP = SYSDATE, - OST_TOKEN_TTL = NVL(SYSDATE + (P_TOKEN_TTL/(24*60*60)), TO_DATE('9999.12.31', 'yyyy.mm.dd')) - WHERE OST_TOKEN = P_TOKEN - AND OST_TOKEN_TYPE = 'REQUEST' - AND OST_AUTHORIZED = 1 - AND OST_TOKEN_TTL >= SYSDATE; - - - END IF; - - SELECT CASE - WHEN OST_TOKEN_TTL >= TO_DATE('9999.12.31', 'yyyy.mm.dd') THEN NULL ELSE (OST_TOKEN_TTL - SYSDATE)*24*60*60 - END "TOKEN_TTL" INTO P_OUT_TOKEN_TTL - FROM OAUTH_SERVER_TOKEN - WHERE OST_TOKEN = P_NEW_TOKEN; - - - - - - -EXCEPTION -WHEN V_EXC_NO_TOKEN_EXIST THEN -P_RESULT := 2; -- NO_TOKEN_EXIST -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc deleted file mode 100644 index 4225ff212f..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER.prc +++ /dev/null @@ -1,41 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER -( -P_CONSUMER_KEY IN STRING, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Fetch a consumer of this server, by consumer_key. -BEGIN -P_RESULT := 0; - -OPEN P_ROWS FOR - SELECT OSR_ID "osr_id", - OSR_USA_ID_REF "osr_usa_id_ref", - OSR_CONSUMER_KEY "osr_consumer_key", - OSR_CONSUMER_SECRET "osr_consumer_secret", - OSR_ENABLED "osr_enabled", - OSR_STATUS "osr_status", - OSR_REQUESTER_NAME "osr_requester_name", - OSR_REQUESTER_EMAIL "osr_requester_email", - OSR_CALLBACK_URI "osr_callback_uri", - OSR_APPLICATION_URI "osr_application_uri", - OSR_APPLICATION_TITLE "osr_application_title", - OSR_APPLICATION_DESCR "osr_application_descr", - OSR_APPLICATION_NOTES "osr_application_notes", - OSR_APPLICATION_TYPE "osr_application_type", - OSR_APPLICATION_COMMERCIAL "osr_application_commercial", - OSR_ISSUE_DATE "osr_issue_date", - OSR_TIMESTAMP "osr_timestamp" - FROM OAUTH_SERVER_REGISTRY - WHERE OSR_CONSUMER_KEY = P_CONSUMER_KEY; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc deleted file mode 100644 index 0db2ea9caa..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_ACCESS_TOKEN.prc +++ /dev/null @@ -1,43 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER_ACCESS_TOKEN -( -P_USER_ID IN NUMBER, -P_TOKEN IN VARCHAR2, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Fetch the consumer access token, by access token. - -BEGIN - - P_RESULT := 0; - - - OPEN P_ROWS FOR - SELECT OST_TOKEN "token", - OST_TOKEN_SECRET "token_secret", - OST_REFERRER_HOST "token_referrer_host", - OSR_CONSUMER_KEY "consumer_key", - OSR_CONSUMER_SECRET "consumer_secret", - OSR_APPLICATION_URI "application_uri", - OSR_APPLICATION_TITLE "application_title", - OSR_APPLICATION_DESCR "application_descr", - OSR_CALLBACK_URI "callback_uri" - FROM OAUTH_SERVER_TOKEN - JOIN OAUTH_SERVER_REGISTRY - ON OST_OSR_ID_REF = OSR_ID - WHERE OST_TOKEN_TYPE = 'ACCESS' - AND OST_TOKEN = P_TOKEN - AND OST_USA_ID_REF = P_USER_ID - AND OST_TOKEN_TTL >= SYSDATE; - - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc deleted file mode 100644 index 6d3b590613..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_REQUEST_TOKEN.prc +++ /dev/null @@ -1,41 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER_REQUEST_TOKEN -( -P_TOKEN IN VARCHAR2, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Fetch the consumer request token, by request token. -BEGIN -P_RESULT := 0; - -OPEN P_ROWS FOR - -SELECT OST_TOKEN "token", - OST_TOKEN_SECRET "token_secret", - OSR_CONSUMER_KEY "consumer_key", - OSR_CONSUMER_SECRET "consumer_secret", - OST_TOKEN_TYPE "token_type", - OST_CALLBACK_URL "callback_url", - OSR_APPLICATION_TITLE "application_title", - OSR_APPLICATION_DESCR "application_descr", - OSR_APPLICATION_URI "application_uri" - FROM OAUTH_SERVER_TOKEN - JOIN OAUTH_SERVER_REGISTRY - ON OST_OSR_ID_REF = OSR_ID - WHERE OST_TOKEN_TYPE = 'REQUEST' - AND OST_TOKEN = P_TOKEN - AND OST_TOKEN_TTL >= SYSDATE; - - - - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc deleted file mode 100644 index 1126ef6aea..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_CONSUMER_STATIC_SELECT.prc +++ /dev/null @@ -1,25 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_GET_CONSUMER_STATIC_SELECT -( -P_OSR_CONSUMER_KEY OUT VARCHAR2, -P_RESULT OUT NUMBER -) -AS - --- PROCEDURE TO Fetch the static consumer key for this provider. -BEGIN -P_RESULT := 0; - - - SELECT OSR_CONSUMER_KEY INTO P_OSR_CONSUMER_KEY - FROM OAUTH_SERVER_REGISTRY - WHERE OSR_CONSUMER_KEY LIKE 'sc-%%' - AND OSR_USA_ID_REF IS NULL; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc deleted file mode 100644 index 2af7847531..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_SIGNATURE.prc +++ /dev/null @@ -1,43 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_GET_SECRETS_FOR_SIGNATURE -( -P_HOST IN VARCHAR2, -P_PATH IN VARCHAR2, -P_USER_ID IN NUMBER, -P_NAME IN VARCHAR2, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Find the server details for signing a request, always looks for an access token. - -- The returned credentials depend on which local user is making the request. -BEGIN -P_RESULT := 0; - - OPEN P_ROWS FOR - SELECT * FROM ( - SELECT OCR_CONSUMER_KEY "consumer_key", - OCR_CONSUMER_SECRET "consumer_secret", - OCT_TOKEN "token", - OCT_TOKEN_SECRET "token_secret", - OCR_SIGNATURE_METHODS "signature_methods" - FROM OAUTH_CONSUMER_REGISTRY - JOIN OAUTH_CONSUMER_TOKEN ON OCT_OCR_ID_REF = OCR_ID - WHERE OCR_SERVER_URI_HOST = P_HOST - AND OCR_SERVER_URI_PATH = SUBSTR(P_PATH, 1, LENGTH(OCR_SERVER_URI_PATH)) - AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL) - AND OCT_USA_ID_REF = P_USER_ID - AND OCT_TOKEN_TYPE = 'ACCESS' - AND OCT_NAME = P_NAME - AND OCT_TOKEN_TTL >= SYSDATE - ORDER BY OCR_USA_ID_REF DESC, OCR_CONSUMER_SECRET DESC, LENGTH(OCR_SERVER_URI_PATH) DESC - ) WHERE ROWNUM<=1; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc deleted file mode 100644 index 4fbb435c85..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SECRETS_FOR_VERIFY.prc +++ /dev/null @@ -1,52 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_GET_SECRETS_FOR_VERIFY -( -P_CONSUMER_KEY IN VARCHAR2, -P_TOKEN IN VARCHAR2, -P_TOKEN_TYPE IN VARCHAR2, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE to Find stored credentials for the consumer key and token. Used by an OAuth server - -- when verifying an OAuth request. - -BEGIN -P_RESULT := 0; - -IF P_TOKEN_TYPE IS NULL THEN - OPEN P_ROWS FOR - SELECT OSR.OSR_ID "osr_id", - OSR.OSR_CONSUMER_KEY "consumer_key", - OSR.OSR_CONSUMER_SECRET "consumer_secret" - FROM OAUTH_SERVER_REGISTRY OSR - WHERE OSR.OSR_CONSUMER_KEY = P_CONSUMER_KEY - AND OSR.OSR_ENABLED = 1; -ELSE - OPEN P_ROWS FOR - SELECT OSR.OSR_ID "osr_id", - OST.OST_ID "ost_id", - OST.OST_USA_ID_REF "user_id", - OSR.OSR_CONSUMER_KEY "consumer_key", - OSR.OSR_CONSUMER_SECRET "consumer_secret", - OST.OST_TOKEN "token", - OST.OST_TOKEN_SECRET "token_secret" - FROM OAUTH_SERVER_REGISTRY OSR, OAUTH_SERVER_TOKEN OST - WHERE OST.OST_OSR_ID_REF = OSR.OSR_ID - AND upper(OST.OST_TOKEN_TYPE) = upper(P_TOKEN_TYPE) - AND OSR.OSR_CONSUMER_KEY = P_CONSUMER_KEY - AND OST.OST_TOKEN = P_TOKEN - AND OSR.OSR_ENABLED = 1 - AND OST.OST_TOKEN_TTL >= SYSDATE; - -END IF; - - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc deleted file mode 100644 index af7d2755b7..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER.prc +++ /dev/null @@ -1,35 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_GET_SERVER -( -P_CONSUMER_KEY IN VARCHAR2, -P_USER_ID IN NUMBER, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Get a server from the consumer registry using the consumer key -BEGIN -P_RESULT := 0; - -OPEN P_ROWS FOR - SELECT OCR_ID "id", - OCR_USA_ID_REF "user_id", - OCR_CONSUMER_KEY "consumer_key", - OCR_CONSUMER_SECRET "consumer_secret", - OCR_SIGNATURE_METHODS "signature_methods", - OCR_SERVER_URI "server_uri", - OCR_REQUEST_TOKEN_URI "request_token_uri", - OCR_AUTHORIZE_URI "authorize_uri", - OCR_ACCESS_TOKEN_URI "access_token_uri" - FROM OAUTH_CONSUMER_REGISTRY - WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY - AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL); - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc deleted file mode 100644 index d838b511bc..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_FOR_URI.prc +++ /dev/null @@ -1,41 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_GET_SERVER_FOR_URI -( -P_HOST IN VARCHAR2, -P_PATH IN VARCHAR2, -P_USER_ID IN NUMBER, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Find the server details that might be used for a request -BEGIN -P_RESULT := 0; - -OPEN P_ROWS FOR -SELECT * FROM ( - SELECT OCR_ID "id", - OCR_USA_ID_REF "user_id", - OCR_CONSUMER_KEY "consumer_key", - OCR_CONSUMER_SECRET "consumer_secret", - OCR_SIGNATURE_METHODS "signature_methods", - OCR_SERVER_URI "server_uri", - OCR_REQUEST_TOKEN_URI "request_token_uri", - OCR_AUTHORIZE_URI "authorize_uri", - OCR_ACCESS_TOKEN_URI "access_token_uri" - FROM OAUTH_CONSUMER_REGISTRY - WHERE OCR_SERVER_URI_HOST = P_HOST - AND OCR_SERVER_URI_PATH = SUBSTR(P_PATH, 1, LENGTH(OCR_SERVER_URI_PATH)) - AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL) - ORDER BY ocr_usa_id_ref DESC, OCR_CONSUMER_KEY DESC, LENGTH(ocr_server_uri_path) DESC -) WHERE ROWNUM<=1; - - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc deleted file mode 100644 index fefbe8acaf..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN.prc +++ /dev/null @@ -1,45 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_GET_SERVER_TOKEN -( -P_CONSUMER_KEY IN VARCHAR2, -P_USER_ID IN NUMBER, -P_TOKEN IN VARCHAR2, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Get a specific server token for the given user -BEGIN -P_RESULT := 0; - -OPEN P_ROWS FOR - SELECT OCR_CONSUMER_KEY "consumer_key", - OCR_CONSUMER_SECRET "consumer_secret", - OCT_TOKEN "token", - OCT_TOKEN_SECRET "token_secret", - OCT_USA_ID_REF "usr_id", - OCR_SIGNATURE_METHODS "signature_methods", - OCR_SERVER_URI "server_uri", - OCR_SERVER_URI_HOST "server_uri_host", - OCR_SERVER_URI_PATH "server_uri_path", - OCR_REQUEST_TOKEN_URI "request_token_uri", - OCR_AUTHORIZE_URI "authorize_uri", - OCR_ACCESS_TOKEN_URI "access_token_uri", - OCT_TIMESTAMP "timestamp" - FROM OAUTH_CONSUMER_REGISTRY - JOIN OAUTH_CONSUMER_TOKEN - ON OCT_OCR_ID_REF = OCR_ID - WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY - AND OCT_USA_ID_REF = P_USER_ID - AND OCT_TOKEN_TYPE = 'ACCESS' - AND OCT_TOKEN = P_TOKEN - AND OCT_TOKEN_TTL >= SYSDATE; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc deleted file mode 100644 index 95eec885a6..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_GET_SERVER_TOKEN_SECRETS.prc +++ /dev/null @@ -1,47 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_GET_SERVER_TOKEN_SECRETS -( -P_CONSUMER_KEY IN VARCHAR2, -P_TOKEN IN VARCHAR2, -P_TOKEN_TYPE IN VARCHAR2, -P_USER_ID IN NUMBER, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- Get the token and token secret we obtained from a server. - -BEGIN -P_RESULT := 0; - - - OPEN P_ROWS FOR - SELECT OCR.OCR_CONSUMER_KEY "consumer_key", - OCR.OCR_CONSUMER_SECRET "consumer_secret", - OCT.OCT_TOKEN "token", - OCT.OCT_TOKEN_SECRET "token_secret", - OCT.OCT_NAME "token_name", - OCR.OCR_SIGNATURE_METHODS "signature_methods", - OCR.OCR_SERVER_URI "server_uri", - OCR.OCR_REQUEST_TOKEN_URI "request_token_uri", - OCR.OCR_AUTHORIZE_URI "authorize_uri", - OCR.OCR_ACCESS_TOKEN_URI "access_token_uri", - CASE WHEN OCT.OCT_TOKEN_TTL >= TO_DATE('9999.12.31', 'yyyy.mm.dd') THEN NULL - ELSE OCT.OCT_TOKEN_TTL - SYSDATE - END "token_ttl" - FROM OAUTH_CONSUMER_REGISTRY OCR, OAUTH_CONSUMER_TOKEN OCT - WHERE OCT.OCT_OCR_ID_REF = OCR_ID - AND OCR.OCR_CONSUMER_KEY = P_CONSUMER_KEY - AND upper(OCT.OCT_TOKEN_TYPE) = upper(P_TOKEN_TYPE) - AND OCT.OCT_TOKEN = P_TOKEN - AND OCT.OCT_USA_ID_REF = P_USER_ID - AND OCT.OCT_TOKEN_TTL >= SYSDATE; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc deleted file mode 100644 index bb4246557c..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMERS.prc +++ /dev/null @@ -1,41 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_LIST_CONSUMERS -( -P_USER_ID IN NUMBER, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Fetch a list of all consumer keys, secrets etc. - -- Returns the public (user_id is null) and the keys owned by the user - -BEGIN - - P_RESULT := 0; - - OPEN P_ROWS FOR - SELECT OSR_ID "id", - OSR_USA_ID_REF "user_id", - OSR_CONSUMER_KEY "consumer_key", - OSR_CONSUMER_SECRET "consumer_secret", - OSR_ENABLED "enabled", - OSR_STATUS "status", - OSR_ISSUE_DATE "issue_date", - OSR_APPLICATION_URI "application_uri", - OSR_APPLICATION_TITLE "application_title", - OSR_APPLICATION_DESCR "application_descr", - OSR_REQUESTER_NAME "requester_name", - OSR_REQUESTER_EMAIL "requester_email", - OSR_CALLBACK_URI "callback_uri" - FROM OAUTH_SERVER_REGISTRY - WHERE (OSR_USA_ID_REF = P_USER_ID OR OSR_USA_ID_REF IS NULL) - ORDER BY OSR_APPLICATION_TITLE; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc deleted file mode 100644 index dae9c72cc0..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_CONSUMER_TOKENS.prc +++ /dev/null @@ -1,43 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_LIST_CONSUMER_TOKENS -( -P_USER_ID IN NUMBER, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Fetch a list of all consumer tokens accessing the account of the given user. - -BEGIN - - P_RESULT := 0; - - OPEN P_ROWS FOR - SELECT OSR_CONSUMER_KEY "consumer_key", - OSR_CONSUMER_SECRET "consumer_secret", - OSR_ENABLED "enabled", - OSR_STATUS "status", - OSR_APPLICATION_URI "application_uri", - OSR_APPLICATION_TITLE "application_title", - OSR_APPLICATION_DESCR "application_descr", - OST_TIMESTAMP "timestamp", - OST_TOKEN "token", - OST_TOKEN_SECRET "token_secret", - OST_REFERRER_HOST "token_referrer_host", - OSR_CALLBACK_URI "callback_uri" - FROM OAUTH_SERVER_REGISTRY - JOIN OAUTH_SERVER_TOKEN - ON OST_OSR_ID_REF = OSR_ID - WHERE OST_USA_ID_REF = P_USER_ID - AND OST_TOKEN_TYPE = 'ACCESS' - AND OST_TOKEN_TTL >= SYSDATE - ORDER BY OSR_APPLICATION_TITLE; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc deleted file mode 100644 index 275950e419..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_LOG.prc +++ /dev/null @@ -1,75 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_LIST_LOG -( -P_OPTION_FLAG IN NUMBER, -- 0:NULL; 1:OTHERWISE -P_USA_ID IN NUMBER, -P_OSR_CONSUMER_KEY IN VARCHAR2, -P_OCR_CONSUMER_KEY IN VARCHAR2, -P_OST_TOKEN IN VARCHAR2, -P_OCT_TOKEN IN VARCHAR2, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Get a page of entries from the log. Returns the last 100 records - -- matching the options given. - -BEGIN - - P_RESULT := 0; - - IF P_OPTION_FLAG IS NULL OR P_OPTION_FLAG = 0 THEN - OPEN P_ROWS FOR - SELECT * FROM ( - SELECT OLG_ID "olg_id", - OLG_OSR_CONSUMER_KEY "osr_consumer_key", - OLG_OST_TOKEN "ost_token", - OLG_OCR_CONSUMER_KEY "ocr_consumer_key", - OLG_OCT_TOKEN "oct_token", - OLG_USA_ID_REF "user_id", - OLG_RECEIVED "received", - OLG_SENT "sent", - OLG_BASE_STRING "base_string", - OLG_NOTES "notes", - OLG_TIMESTAMP "timestamp", - -- INET_NTOA(OLG_REMOTE_IP) "remote_ip" - OLG_REMOTE_IP "remote_ip" - FROM OAUTH_LOG - WHERE OLG_USA_ID_REF = P_USA_ID - ORDER BY OLG_ID DESC - ) WHERE ROWNUM<=100; - ELSE - OPEN P_ROWS FOR - SELECT * FROM ( - SELECT OLG_ID "olg_id", - OLG_OSR_CONSUMER_KEY "osr_consumer_key", - OLG_OST_TOKEN "ost_token", - OLG_OCR_CONSUMER_KEY "ocr_consumer_key", - OLG_OCT_TOKEN "oct_token", - OLG_USA_ID_REF "user_id", - OLG_RECEIVED "received", - OLG_SENT "sent", - OLG_BASE_STRING "base_string", - OLG_NOTES "notes", - OLG_TIMESTAMP "timestamp", - -- INET_NTOA(OLG_REMOTE_IP) "remote_ip" - OLG_REMOTE_IP "remote_ip" - FROM OAUTH_LOG - WHERE OLG_OSR_CONSUMER_KEY = P_OSR_CONSUMER_KEY - AND OLG_OCR_CONSUMER_KEY = P_OCR_CONSUMER_KEY - AND OLG_OST_TOKEN = P_OST_TOKEN - AND OLG_OCT_TOKEN = P_OCT_TOKEN - AND (OLG_USA_ID_REF IS NULL OR OLG_USA_ID_REF = P_USA_ID) - ORDER BY OLG_ID DESC - ) WHERE ROWNUM<=100; - - END IF; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc deleted file mode 100644 index 51dd39a06c..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVERS.prc +++ /dev/null @@ -1,66 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_LIST_SERVERS -( -P_Q IN VARCHAR2, -P_USER_ID IN NUMBER, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Get a list of all consumers from the consumer registry. -BEGIN -P_RESULT := 0; - -IF P_Q IS NOT NULL THEN - - OPEN P_ROWS FOR - SELECT OCR_ID "id", - OCR_USA_ID_REF "user_id", - OCR_CONSUMER_KEY "consumer_key", - OCR_CONSUMER_SECRET "consumer_secret", - OCR_SIGNATURE_METHODS "signature_methods", - OCR_SERVER_URI "server_uri", - OCR_SERVER_URI_HOST "server_uri_host", - OCR_SERVER_URI_PATH "server_uri_path", - OCR_REQUEST_TOKEN_URI "request_token_uri", - OCR_AUTHORIZE_URI "authorize_uri", - OCR_ACCESS_TOKEN_URI "access_token_uri" - FROM OAUTH_CONSUMER_REGISTRY - WHERE ( OCR_CONSUMER_KEY LIKE '%'|| P_Q ||'%' - OR OCR_SERVER_URI LIKE '%'|| P_Q ||'%' - OR OCR_SERVER_URI_HOST LIKE '%'|| P_Q ||'%' - OR OCR_SERVER_URI_PATH LIKE '%'|| P_Q ||'%') - AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL) - ORDER BY OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH; - -ELSE - - OPEN P_ROWS FOR - SELECT OCR_ID "id", - OCR_USA_ID_REF "user_id", - OCR_CONSUMER_KEY "consumer_key", - OCR_CONSUMER_SECRET "consumer_secret", - OCR_SIGNATURE_METHODS "signature_methods", - OCR_SERVER_URI "server_uri", - OCR_SERVER_URI_HOST "server_uri_host", - OCR_SERVER_URI_PATH "server_uri_path", - OCR_REQUEST_TOKEN_URI "request_token_uri", - OCR_AUTHORIZE_URI "authorize_uri", - OCR_ACCESS_TOKEN_URI "access_token_uri" - FROM OAUTH_CONSUMER_REGISTRY - WHERE OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL - ORDER BY OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH; - -END IF; - - - - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc deleted file mode 100644 index baa62c02e5..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_LIST_SERVER_TOKENS.prc +++ /dev/null @@ -1,45 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_LIST_SERVER_TOKENS -( -P_USER_ID IN NUMBER, -P_ROWS OUT TYPES.REF_CURSOR, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Find the server details that might be used for a request -BEGIN -P_RESULT := 0; - -OPEN P_ROWS FOR - SELECT OCR_CONSUMER_KEY "consumer_key", - OCR_CONSUMER_SECRET "consumer_secret", - OCT_ID "token_id", - OCT_TOKEN "token", - OCT_TOKEN_SECRET "token_secret", - OCT_USA_ID_REF "user_id", - OCR_SIGNATURE_METHODS "signature_methods", - OCR_SERVER_URI "server_uri", - OCR_SERVER_URI_HOST "server_uri_host", - OCR_SERVER_URI_PATH "server_uri_path", - OCR_REQUEST_TOKEN_URI "request_token_uri", - OCR_AUTHORIZE_URI "authorize_uri", - OCR_ACCESS_TOKEN_URI "access_token_uri", - OCT_TIMESTAMP "timestamp" - FROM OAUTH_CONSUMER_REGISTRY - JOIN OAUTH_CONSUMER_TOKEN - ON OCT_OCR_ID_REF = OCR_ID - WHERE OCT_USA_ID_REF = P_USER_ID - AND OCT_TOKEN_TYPE = 'ACCESS' - AND OCT_TOKEN_TTL >= SYSDATE - ORDER BY OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH; - - - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc deleted file mode 100644 index e5a96c966a..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_CONSUMER_ACC_TOKEN_TTL.prc +++ /dev/null @@ -1,28 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_SET_CONSUMER_ACC_TOKEN_TTL -( -P_TOKEN IN VARCHAR2, -P_TOKEN_TTL IN NUMBER, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Set the ttl of a consumer access token. This is done when the - -- server receives a valid request with a xoauth_token_ttl parameter in it. - -BEGIN - - P_RESULT := 0; - - UPDATE OAUTH_SERVER_TOKEN - SET OST_TOKEN_TTL = SYSDATE + (P_TOKEN_TTL/(24*60*60)) - WHERE OST_TOKEN = P_TOKEN - AND OST_TOKEN_TYPE = 'ACCESS'; - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc deleted file mode 100644 index 34a99de067..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_SET_SERVER_TOKEN_TTL.prc +++ /dev/null @@ -1,29 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_SET_SERVER_TOKEN_TTL -( -P_TOKEN_TTL IN NUMBER, -- IN SECOND -P_CONSUMER_KEY IN VARCHAR2, -P_TOKEN IN VARCHAR2, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Set the ttl of a server access token. - -BEGIN - - P_RESULT := 0; - - -UPDATE OAUTH_CONSUMER_TOKEN -SET OCT_TOKEN_TTL = SYSDATE + (P_TOKEN_TTL/(24*60*60)) -- DATE_ADD(NOW(), INTERVAL %D SECOND) -WHERE OCT_TOKEN = P_TOKEN -AND OCT_OCR_ID_REF IN (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY); - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc deleted file mode 100644 index a79e64c3be..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_CONSUMER.prc +++ /dev/null @@ -1,40 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_UPDATE_CONSUMER -( -P_OSR_USA_ID_REF IN NUMBER, -P_OSR_CONSUMER_KEY IN VARCHAR2, -P_OSR_CONSUMER_SECRET IN VARCHAR2, -P_OSR_REQUESTER_NAME IN VARCHAR2, -P_OSR_REQUESTER_EMAIL IN VARCHAR2, -P_OSR_CALLBACK_URI IN VARCHAR2, -P_OSR_APPLICATION_URI IN VARCHAR2, -P_OSR_APPLICATION_TITLE IN VARCHAR2, -P_OSR_APPLICATION_DESCR IN VARCHAR2, -P_OSR_APPLICATION_NOTES IN VARCHAR2, -P_OSR_APPLICATION_TYPE IN VARCHAR2, -P_OSR_APPLICATION_COMMERCIAL IN INTEGER, -P_RESULT OUT NUMBER -) -AS - - -- PROCEDURE TO Insert a new consumer with this server (we will be the server) -BEGIN -P_RESULT := 0; - - - INSERT INTO OAUTH_SERVER_REGISTRY - ( OSR_ID, OSR_ENABLED, OSR_STATUS,OSR_USA_ID_REF,OSR_CONSUMER_KEY, OSR_CONSUMER_SECRET,OSR_REQUESTER_NAME, - OSR_REQUESTER_EMAIL, OSR_CALLBACK_URI, OSR_APPLICATION_URI, OSR_APPLICATION_TITLE, OSR_APPLICATION_DESCR, - OSR_APPLICATION_NOTES, OSR_APPLICATION_TYPE, OSR_APPLICATION_COMMERCIAL, OSR_TIMESTAMP, OSR_ISSUE_DATE) - VALUES - ( SEQ_OSR_ID.NEXTVAL, 1, 'ACTIVE', P_OSR_USA_ID_REF, P_OSR_CONSUMER_KEY, P_OSR_CONSUMER_SECRET,P_OSR_REQUESTER_NAME, - P_OSR_REQUESTER_EMAIL, P_OSR_CALLBACK_URI, P_OSR_APPLICATION_URI, P_OSR_APPLICATION_TITLE, P_OSR_APPLICATION_DESCR, - P_OSR_APPLICATION_NOTES, P_OSR_APPLICATION_TYPE, P_OSR_APPLICATION_COMMERCIAL, SYSDATE, SYSDATE); - - -EXCEPTION -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc b/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc deleted file mode 100644 index 7826eb6249..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/OracleDB/3_Procedures/SP_UPDATE_SERVER.prc +++ /dev/null @@ -1,139 +0,0 @@ -CREATE OR REPLACE PROCEDURE SP_UPDATE_SERVER -( -P_CONSUMER_KEY IN VARCHAR2, -P_USER_ID IN NUMBER, -P_OCR_ID IN NUMBER, -P_USER_IS_ADMIN IN NUMBER, -- 0:NO; 1:YES; -P_OCR_CONSUMER_SECRET IN VARCHAR2, -P_OCR_SERVER_URI IN VARCHAR2, -P_OCR_SERVER_URI_HOST IN VARCHAR2, -P_OCR_SERVER_URI_PATH IN VARCHAR2, -P_OCR_REQUEST_TOKEN_URI IN VARCHAR2, -P_OCR_AUTHORIZE_URI IN VARCHAR2, -P_OCR_ACCESS_TOKEN_URI IN VARCHAR2, -P_OCR_SIGNATURE_METHODS IN VARCHAR2, -P_OCR_USA_ID_REF IN NUMBER, -P_UPDATE_P_OCR_USA_ID_REF_FLAG IN NUMBER, -- 1:TRUE; 0:FALSE -P_RESULT OUT NUMBER -) -AS - - -- Add a request token we obtained from a server. -V_OCR_ID_EXIST NUMBER; -V_OCR_USA_ID_REF NUMBER; - -V_EXC_DUPLICATE_CONSUMER_KEY EXCEPTION; -V_EXC_UNAUTHORISED_USER_ID EXCEPTION; -BEGIN -P_RESULT := 0; - -V_OCR_USA_ID_REF := P_OCR_USA_ID_REF; - - IF P_OCR_ID IS NOT NULL THEN - BEGIN - SELECT 1 INTO V_OCR_ID_EXIST FROM DUAL WHERE EXISTS - (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY - WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY - AND OCR_ID != P_OCR_ID - AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL)); - - EXCEPTION - WHEN NO_DATA_FOUND THEN - V_OCR_ID_EXIST :=0; - END; - ELSE - BEGIN - SELECT 1 INTO V_OCR_ID_EXIST FROM DUAL WHERE EXISTS - (SELECT OCR_ID FROM OAUTH_CONSUMER_REGISTRY - WHERE OCR_CONSUMER_KEY = P_CONSUMER_KEY - AND (OCR_USA_ID_REF = P_USER_ID OR OCR_USA_ID_REF IS NULL)); - - EXCEPTION - WHEN NO_DATA_FOUND THEN - V_OCR_ID_EXIST :=0; - END; - END IF; - - IF V_OCR_ID_EXIST = 1 THEN - RAISE V_EXC_DUPLICATE_CONSUMER_KEY; - END IF; - - - IF P_OCR_ID IS NOT NULL THEN - IF P_USER_IS_ADMIN != 1 THEN - BEGIN - SELECT OCR_USA_ID_REF INTO V_OCR_USA_ID_REF - FROM OAUTH_CONSUMER_REGISTRY - WHERE OCR_ID = P_OCR_ID; - - EXCEPTION - WHEN NO_DATA_FOUND THEN - NULL; - END; - - IF V_OCR_USA_ID_REF != P_USER_ID THEN - RAISE V_EXC_UNAUTHORISED_USER_ID; - END IF; - END IF; - - IF P_UPDATE_P_OCR_USA_ID_REF_FLAG = 0 THEN - - UPDATE OAUTH_CONSUMER_REGISTRY - SET OCR_CONSUMER_KEY = P_CONSUMER_KEY, - OCR_CONSUMER_SECRET = P_OCR_CONSUMER_SECRET, - OCR_SERVER_URI = P_OCR_SERVER_URI, - OCR_SERVER_URI_HOST = P_OCR_SERVER_URI_HOST, - OCR_SERVER_URI_PATH = P_OCR_SERVER_URI_PATH, - OCR_TIMESTAMP = SYSDATE, - OCR_REQUEST_TOKEN_URI = P_OCR_REQUEST_TOKEN_URI, - OCR_AUTHORIZE_URI = P_OCR_AUTHORIZE_URI, - OCR_ACCESS_TOKEN_URI = P_OCR_ACCESS_TOKEN_URI, - OCR_SIGNATURE_METHODS = P_OCR_SIGNATURE_METHODS - WHERE OCR_ID = P_OCR_ID; - - ELSIF P_UPDATE_P_OCR_USA_ID_REF_FLAG = 1 THEN - UPDATE OAUTH_CONSUMER_REGISTRY - SET OCR_CONSUMER_KEY = P_CONSUMER_KEY, - OCR_CONSUMER_SECRET = P_OCR_CONSUMER_SECRET, - OCR_SERVER_URI = P_OCR_SERVER_URI, - OCR_SERVER_URI_HOST = P_OCR_SERVER_URI_HOST, - OCR_SERVER_URI_PATH = P_OCR_SERVER_URI_PATH, - OCR_TIMESTAMP = SYSDATE, - OCR_REQUEST_TOKEN_URI = P_OCR_REQUEST_TOKEN_URI, - OCR_AUTHORIZE_URI = P_OCR_AUTHORIZE_URI, - OCR_ACCESS_TOKEN_URI = P_OCR_ACCESS_TOKEN_URI, - OCR_SIGNATURE_METHODS = P_OCR_SIGNATURE_METHODS, - OCR_USA_ID_REF = P_OCR_USA_ID_REF - WHERE OCR_ID = P_OCR_ID; - - END IF; - - ELSE - IF P_UPDATE_P_OCR_USA_ID_REF_FLAG = 0 THEN - V_OCR_USA_ID_REF := P_USER_ID; - END IF; - - INSERT INTO OAUTH_CONSUMER_REGISTRY - (OCR_ID, OCR_CONSUMER_KEY ,OCR_CONSUMER_SECRET, OCR_SERVER_URI, OCR_SERVER_URI_HOST, OCR_SERVER_URI_PATH, - OCR_TIMESTAMP, OCR_REQUEST_TOKEN_URI, OCR_AUTHORIZE_URI, OCR_ACCESS_TOKEN_URI, OCR_SIGNATURE_METHODS, - OCR_USA_ID_REF) - VALUES - (SEQ_OCR_ID.NEXTVAL, P_CONSUMER_KEY, P_OCR_CONSUMER_SECRET, P_OCR_SERVER_URI, P_OCR_SERVER_URI_HOST, P_OCR_SERVER_URI_PATH, - SYSDATE, P_OCR_REQUEST_TOKEN_URI, P_OCR_AUTHORIZE_URI, P_OCR_ACCESS_TOKEN_URI, P_OCR_SIGNATURE_METHODS, - V_OCR_USA_ID_REF); - - END IF; - - -EXCEPTION -WHEN V_EXC_DUPLICATE_CONSUMER_KEY THEN -P_RESULT := 2; -- DUPLICATE_CONSUMER_KEY -WHEN V_EXC_UNAUTHORISED_USER_ID THEN -P_RESULT := 3; -- UNAUTHORISED_USER_ID - -WHEN OTHERS THEN --- CALL THE FUNCTION TO LOG ERRORS -ROLLBACK; -P_RESULT := 1; -- ERROR -END; -/ diff --git a/3rdparty/oauth-php/library/store/oracle/install.php b/3rdparty/oauth-php/library/store/oracle/install.php deleted file mode 100644 index 5a80f04023..0000000000 --- a/3rdparty/oauth-php/library/store/oracle/install.php +++ /dev/null @@ -1,28 +0,0 @@ - \ No newline at end of file diff --git a/3rdparty/oauth-php/library/store/postgresql/pgsql.sql b/3rdparty/oauth-php/library/store/postgresql/pgsql.sql deleted file mode 100644 index 8f0e4d3e2c..0000000000 --- a/3rdparty/oauth-php/library/store/postgresql/pgsql.sql +++ /dev/null @@ -1,166 +0,0 @@ -# -# Log table to hold all OAuth request when you enabled logging -# - -CREATE TABLE oauth_log ( - olg_id serial primary key, - olg_osr_consumer_key varchar(64), - olg_ost_token varchar(64), - olg_ocr_consumer_key varchar(64), - olg_oct_token varchar(64), - olg_usa_id_ref text, - olg_received text not null, - olg_sent text not null, - olg_base_string text not null, - olg_notes text not null, - olg_timestamp timestamp not null default current_timestamp, - olg_remote_ip inet not null -); - -COMMENT ON TABLE oauth_log IS 'Log table to hold all OAuth request when you enabled logging'; - - -# -# /////////////////// CONSUMER SIDE /////////////////// -# - -# This is a registry of all consumer codes we got from other servers -# The consumer_key/secret is obtained from the server -# We also register the server uri, so that we can find the consumer key and secret -# for a certain server. From that server we can check if we have a token for a -# particular user. - -CREATE TABLE oauth_consumer_registry ( - ocr_id serial primary key, - ocr_usa_id_ref text, - ocr_consumer_key varchar(128) not null, - ocr_consumer_secret varchar(128) not null, - ocr_signature_methods varchar(255) not null default 'HMAC-SHA1,PLAINTEXT', - ocr_server_uri varchar(255) not null, - ocr_server_uri_host varchar(128) not null, - ocr_server_uri_path varchar(128) not null, - - ocr_request_token_uri varchar(255) not null, - ocr_authorize_uri varchar(255) not null, - ocr_access_token_uri varchar(255) not null, - ocr_timestamp timestamp not null default current_timestamp, - - unique (ocr_consumer_key, ocr_usa_id_ref, ocr_server_uri) -); - -COMMENT ON TABLE oauth_consumer_registry IS 'This is a registry of all consumer codes we got from other servers'; - -# Table used to sign requests for sending to a server by the consumer -# The key is defined for a particular user. Only one single named -# key is allowed per user/server combination - --- Create enum type token_type -CREATE TYPE consumer_token_type AS ENUM ( - 'request', - 'authorized', - 'access' -); - -CREATE TABLE oauth_consumer_token ( - oct_id serial primary key, - oct_ocr_id_ref integer not null, - oct_usa_id_ref text not null, - oct_name varchar(64) not null default '', - oct_token varchar(64) not null, - oct_token_secret varchar(64) not null, - oct_token_type consumer_token_type, - oct_token_ttl timestamp not null default timestamp '9999-12-31', - oct_timestamp timestamp not null default current_timestamp, - - unique (oct_ocr_id_ref, oct_token), - unique (oct_usa_id_ref, oct_ocr_id_ref, oct_token_type, oct_name), - - foreign key (oct_ocr_id_ref) references oauth_consumer_registry (ocr_id) - on update cascade - on delete cascade -); - - -COMMENT ON TABLE oauth_consumer_token IS 'Table used to sign requests for sending to a server by the consumer'; - -# -# ////////////////// SERVER SIDE ///////////////// -# - -# Table holding consumer key/secret combos an user issued to consumers. -# Used for verification of incoming requests. - -CREATE TABLE oauth_server_registry ( - osr_id serial primary key, - osr_usa_id_ref text, - osr_consumer_key varchar(64) not null, - osr_consumer_secret varchar(64) not null, - osr_enabled boolean not null default true, - osr_status varchar(16) not null, - osr_requester_name varchar(64) not null, - osr_requester_email varchar(64) not null, - osr_callback_uri varchar(255) not null, - osr_application_uri varchar(255) not null, - osr_application_title varchar(80) not null, - osr_application_descr text not null, - osr_application_notes text not null, - osr_application_type varchar(20) not null, - osr_application_commercial boolean not null default false, - osr_issue_date timestamp not null, - osr_timestamp timestamp not null default current_timestamp, - - unique (osr_consumer_key) -); - - -COMMENT ON TABLE oauth_server_registry IS 'Table holding consumer key/secret combos an user issued to consumers'; - -# Nonce used by a certain consumer, every used nonce should be unique, this prevents -# replaying attacks. We need to store all timestamp/nonce combinations for the -# maximum timestamp received. - -CREATE TABLE oauth_server_nonce ( - osn_id serial primary key, - osn_consumer_key varchar(64) not null, - osn_token varchar(64) not null, - osn_timestamp bigint not null, - osn_nonce varchar(80) not null, - - unique (osn_consumer_key, osn_token, osn_timestamp, osn_nonce) -); - - -COMMENT ON TABLE oauth_server_nonce IS 'Nonce used by a certain consumer, every used nonce should be unique, this prevents replaying attacks'; - -# Table used to verify signed requests sent to a server by the consumer -# When the verification is succesful then the associated user id is returned. - --- Create enum type token_type -CREATE TYPE server_token_type AS ENUM ( - 'request', - 'access' -); - -CREATE TABLE oauth_server_token ( - ost_id serial primary key, - ost_osr_id_ref integer not null, - ost_usa_id_ref text not null, - ost_token varchar(64) not null, - ost_token_secret varchar(64) not null, - ost_token_type server_token_type, - ost_authorized boolean not null default false, - ost_referrer_host varchar(128) not null default '', - ost_token_ttl timestamp not null default timestamp '9999-12-31', - ost_timestamp timestamp not null default current_timestamp, - ost_verifier char(10), - ost_callback_url varchar(512), - - unique (ost_token), - - foreign key (ost_osr_id_ref) references oauth_server_registry (osr_id) - on update cascade - on delete cascade -); - - -COMMENT ON TABLE oauth_server_token IS 'Table used to verify signed requests sent to a server by the consumer'; From 88c6928bade99676ab44dd43519dd40d470515c6 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 3 Aug 2012 11:36:01 +0000 Subject: [PATCH 056/330] API: Use OC_API::checkLoggedIn() and OAuth scopes are app_$appname --- settings/oauth.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/settings/oauth.php b/settings/oauth.php index 9e7a3c0493..b04c798b1b 100644 --- a/settings/oauth.php +++ b/settings/oauth.php @@ -27,7 +27,7 @@ switch($operation){ } break; case 'authorise'; - OC_Util::checkLoggedIn(); + OC_API::checkLoggedIn(); // Example $consumer = array( 'name' => 'Firefox Bookmark Sync', @@ -38,6 +38,8 @@ switch($operation){ $apps = OC_App::getEnabledApps(); $notfound = array(); foreach($consumer['scopes'] as $requiredapp){ + // App scopes are in this format: app_$appname + $requiredapp = end(explode('_', $requiredapp)); if(!in_array($requiredapp, $apps)){ $notfound[] = $requiredapp; } From a7906d813ad342f06d4834c10c1200002f7342d2 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 3 Aug 2012 11:47:05 +0000 Subject: [PATCH 057/330] Move OAuth classes into lib/oauth --- lib/api.php | 4 ++-- lib/{oauth.php => oauth/server.php} | 9 ++++++++- lib/oauth/store.php | 29 +++++++++++++++++++++++++++++ settings/oauth.php | 2 +- 4 files changed, 40 insertions(+), 4 deletions(-) rename lib/{oauth.php => oauth/server.php} (90%) create mode 100644 lib/oauth/store.php diff --git a/lib/api.php b/lib/api.php index c8bd0aec2f..8fdfc63070 100644 --- a/lib/api.php +++ b/lib/api.php @@ -23,7 +23,7 @@ * License along with this library. If not, see . * */ - + class OC_API { private static $server; @@ -32,7 +32,7 @@ class OC_API { * initialises the OAuth store and server */ private static function init() { - self::$server = new OC_OAuthServer(new OC_OAuthStore()); + self::$server = new OC_OAuth_Server(new OC_OAuth_Store()); } /** diff --git a/lib/oauth.php b/lib/oauth/server.php similarity index 90% rename from lib/oauth.php rename to lib/oauth/server.php index b72d9aab44..c563c52760 100644 --- a/lib/oauth.php +++ b/lib/oauth/server.php @@ -22,7 +22,9 @@ * */ -class OC_OAuthServer extends OAuthServer { +require_once(OC::$THIRDPARTYROOT.'/3rdparty/OAuth/OAuth.php'); + +class OC_OAuth_Server extends OAuthServer { public function fetch_request_token(&$request) { $this->get_version($request); @@ -34,6 +36,11 @@ class OC_OAuthServer extends OAuthServer { return $this->data_store->new_request_token($consumer, $scope, $callback); } + /** + * authorises a request token + * @param string $request the request token to authorise + * @return What does it return? + */ public function authoriseRequestToken(&$request) { $this->get_version($request); $consumer = $this->get_consumer($request); diff --git a/lib/oauth/store.php b/lib/oauth/store.php new file mode 100644 index 0000000000..2f58e46b5b --- /dev/null +++ b/lib/oauth/store.php @@ -0,0 +1,29 @@ +. +* +*/ + +class OC_OAuth_Store extends OAuthDataStore { + + // To follow. + +} \ No newline at end of file diff --git a/settings/oauth.php b/settings/oauth.php index b04c798b1b..7f30161d85 100644 --- a/settings/oauth.php +++ b/settings/oauth.php @@ -9,7 +9,7 @@ require_once('../lib/base.php'); // Logic $operation = isset($_GET['operation']) ? $_GET['operation'] : ''; -$server = new OC_OAuthServer(new OC_OAuthStore()); +$server = new OC_OAuth_Server(new OC_OAuth_Store()); switch($operation){ case 'register': From 6047a5fe515091d755e964c24de93fc29a5f9754 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 3 Aug 2012 11:56:11 +0000 Subject: [PATCH 058/330] API: Check if the consumer has permissions to access the requested method --- lib/api.php | 12 +++++++++--- lib/oauth/server.php | 3 ++- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/lib/api.php b/lib/api.php index 8fdfc63070..90f36aefbc 100644 --- a/lib/api.php +++ b/lib/api.php @@ -73,11 +73,17 @@ class OC_API { // Loop through registered actions foreach(self::$actions[$name] as $action){ $app = $action['app']; - if(is_callable($action['action'])){ - $responses[] = array('app' => $app, 'response' => call_user_func($action['action'], $parameters)); + // Check the consumer has permission to call this method. + if(OC_OAuth_Server::isAuthorised('app_'.$app)){ + if(is_callable($action['action'])){ + $responses[] = array('app' => $app, 'response' => call_user_func($action['action'], $parameters)); + } else { + $responses[] = array('app' => $app, 'response' => 501); + } } else { - $responses[] = array('app' => $app, 'response' => 501); + $responses[] = array('app' => $app, 'response' => 401); } + } // Merge the responses $response = self::mergeResponses($responses); diff --git a/lib/oauth/server.php b/lib/oauth/server.php index c563c52760..b14277afea 100644 --- a/lib/oauth/server.php +++ b/lib/oauth/server.php @@ -58,7 +58,8 @@ class OC_OAuth_Server extends OAuthServer { public static function isAuthorised($scope) { try { $request = OAuthRequest::from_request(); - $this->verify_request(); + //$this->verify_request(); // TODO cannot use $this in static context + return true; } catch (OAuthException $exception) { return false; } From 21f8646ffc9057bd15fe8a30b781ee20766b5656 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 3 Aug 2012 15:20:01 +0000 Subject: [PATCH 059/330] API: Fix merging of responses. Return 400 error when no OAuth operation sent. --- lib/api.php | 10 +++++----- settings/oauth.php | 4 ++-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/lib/api.php b/lib/api.php index 90f36aefbc..c91216179e 100644 --- a/lib/api.php +++ b/lib/api.php @@ -107,16 +107,16 @@ class OC_API { $numresponses = count($responses); foreach($responses as $response){ - if(is_int($response) && empty($finalresponse)){ - $finalresponse = $response; + if(is_int($response['response']) && empty($finalresponse)){ + $finalresponse = $response['response']; continue; } - if(is_array($response)){ + if(is_array($response['response'])){ // Shipped apps win if(OC_App::isShipped($response['app'])){ - $finalresponse = array_merge_recursive($finalresponse, $response); + $finalresponse = array_merge_recursive($finalresponse, $response['response']); } else { - $finalresponse = array_merge_recursive($response, $finalresponse); + $finalresponse = array_merge_recursive($response['response'], $finalresponse); } } } diff --git a/settings/oauth.php b/settings/oauth.php index 7f30161d85..f088453a26 100644 --- a/settings/oauth.php +++ b/settings/oauth.php @@ -76,8 +76,8 @@ switch($operation){ } break; default: - // Something went wrong - header('Location: /'); + // Something went wrong, we need an operation! + OC_Response::setStatus(400); break; } From b26ffdc4d676373c0914211d6b2105a0b2e63eac Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 30 Aug 2012 14:00:23 +0000 Subject: [PATCH 060/330] Add basic db structure for oauth --- db_structure.xml | 109 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) diff --git a/db_structure.xml b/db_structure.xml index 94567b4d53..5c14f5dcac 100644 --- a/db_structure.xml +++ b/db_structure.xml @@ -399,6 +399,115 @@ + + + + *dbprefix*oauth_consumers + + + + + key + text + 64 + + + + secret + text + 64 + + + + callback + text + 255 + + + + name + text + 200 + + + + url + text + 255 + + + + + +
+ + + + *dbprefix*oauth_nonce + + + + + consumer_key + text + 64 + + + + token + text + 64 + + + + timestamp + integer + 11 + + + + nonce + text + 64 + + + + +
+ + + + *dbprefix*oauth_tokens + + + + + consumer_key + text + 64 + + + + key + text + 64 + + + + secret + text + 64 + + + + type> + text + 7 + + + + +
From 0d1d2c0b61a4a0bcbc4b08a927fa815f4673d31e Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 30 Aug 2012 14:01:27 +0000 Subject: [PATCH 061/330] Fix class name --- lib/api.php | 2 +- settings/oauth.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/api.php b/lib/api.php index c91216179e..55de438f42 100644 --- a/lib/api.php +++ b/lib/api.php @@ -166,7 +166,7 @@ class OC_API { */ public static function checkLoggedIn(){ // Check OAuth - if(!OC_OAuthServer::isAuthorised()){ + if(!OC_OAuth_Server::isAuthorised()){ OC_Response::setStatus(401); die(); } diff --git a/settings/oauth.php b/settings/oauth.php index f088453a26..c6c9be515b 100644 --- a/settings/oauth.php +++ b/settings/oauth.php @@ -22,7 +22,7 @@ switch($operation){ $token = $server->fetch_request_token($request); echo $token; } catch (OAuthException $exception) { - OC_Log::write('OC_OAuthServer', $exception->getMessage(), OC_LOG::ERROR); + OC_Log::write('OC_OAuth_Server', $exception->getMessage(), OC_LOG::ERROR); echo $exception->getMessage(); } break; @@ -71,7 +71,7 @@ switch($operation){ $token = $server->fetch_access_token($request); echo $token; } catch (OAuthException $exception) { - OC_Log::write('OC_OAuthServer', $exception->getMessage(), OC_LOG::ERROR); + OC_Log::write('OC_OAuth_Server', $exception->getMessage(), OC_LOG::ERROR); echo $exception->getMessage(); } break; From 67c2d56be81a48ba63ce92d5fa0ff339be9ca5a5 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 30 Aug 2012 14:02:31 +0000 Subject: [PATCH 062/330] Add ownCloud OAuth store backend. WIP --- lib/oauth/store.php | 74 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 69 insertions(+), 5 deletions(-) diff --git a/lib/oauth/store.php b/lib/oauth/store.php index 2f58e46b5b..f1df7d49b9 100644 --- a/lib/oauth/store.php +++ b/lib/oauth/store.php @@ -2,10 +2,10 @@ /** * ownCloud * -* @author Tom Needham * @author Michael Gapczynski -* @copyright 2012 Tom Needham tom@owncloud.com +* @author Tom Needham * @copyright 2012 Michael Gapczynski mtgap@owncloud.com +* @copyright 2012 Tom Needham tom@owncloud.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE @@ -22,8 +22,72 @@ * */ -class OC_OAuth_Store extends OAuthDataStore { +class OC_OAuth_Store { + + function lookup_consumer($consumer_key) { + $query = OC_DB::prepare("SELECT `key`, `secret`, `callback` FROM `*PREFIX*oauth_consumers` WHERE `key` = ?"); + $results = $query->execute(array($consumer_key)); + if($results->numRows()==0){ + return NULL; + } else { + $details = $results->fetchRow(); + $callback = !empty($details['callback']) ? $details['callback'] : NULL; + return new OAuthConsumer($details['key'], $details['secret'], $callback); + } + } + + function lookup_token($consumer, $token_type, $token) { + $query = OC_DB::prepare("SELECT `key`, `secret`, `type` FROM `*PREFIX*oauth_tokens` WHERE `consumer_key` = ? AND `key` = ? AND `type` = ?"); + $results = $query->execute(array($consumer->key, $token->key, $token_type)); + if($results->numRows()==0){ + return NULL; + } else { + $token = $results->fetchRow(); + return new OAuthToken($token['key'], $token['secret']); + } + } + + function lookup_nonce($consumer, $token, $nonce, $timestamp) { + $query = OC_DB::prepare("INSERT INTO `*PREFIX*oauth_nonce` (`consumer_key`, `token`, `timestamp`, `nonce`) VALUES (?, ?, ?, ?)"); + $affectedrows = $query->exec(array($consumer->key, $token->key, $timestamp, $nonce)); + // Delete all timestamps older than the one passed + $query = OC_DB::prepare("DELETE FROM `*PREFIX*oauth_nonce` WHERE `consumer_key` = ? AND `token` = ? AND `timestamp` < ?"); + $query->execute(array($consumer->key, $token->key, $timestamp - self::MAX_TIMESTAMP_DIFFERENCE)); + return $result; + } + + function new_token($consumer, $token_type, $scope = null) { + $key = md5(time()); + $secret = time() + time(); + $token = new OAuthToken($key, md5(md5($secret))); + $query = OC_DB::prepare("INSERT INTO `*PREFIX*oauth_tokens` (`consumer_key`, `key`, `secret`, `type`, `scope`, `timestamp`) VALUES (?, ?, ?, ?, ?, ?)"); + $result = $query->execute(array($consumer->key, $key, $secret, $token_type, $scope, time())); + return $token; + } + + function new_request_token($consumer, $scope, $callback = null) { + return $this->new_token($consumer, 'request', $scope); + } + + function authorise_request_token($token, $consumer, $uid) { + $query = OC_DB::prepare("UPDATE `*PREFIX*oauth_tokens` SET uid = ? WHERE `consumer_key` = ? AND `key` = ? AND `type` = ?"); + $query->execute(array($uid, $consumer->key, $token->key, 'request')); + // TODO Return oauth_verifier + } + + function new_access_token($token, $consumer, $verifier = null) { + $query = OC_DB::prepare("SELECT `timestamp`, `scope` FROM `*PREFIX*oauth_tokens` WHERE `consumer_key` = ? AND `key` = ? AND `type` = ?"); + $result = $query->execute(array($consumer->key, $token->key, 'request'))->fetchRow(); + if (isset($result['timestamp'])) { + if ($timestamp + self::MAX_REQUEST_TOKEN_TTL < time()) { + return false; + } + $accessToken = $this->new_token($consumer, 'access', $result['scope']); + } + // Delete request token + $query = OC_DB::prepare("DELETE FROM `*PREFIX*oauth_tokens` WHERE `key` = ? AND `type` = ?"); + $query->execute(array($token->key, 'request')); + return $accessToken; + } - // To follow. - } \ No newline at end of file From b650c7c2a7a13cc5c3b680f8c1863ff196a8ea02 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 31 Aug 2012 12:34:48 +0000 Subject: [PATCH 063/330] Add table to hold OAuth scopes --- db_structure.xml | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/db_structure.xml b/db_structure.xml index 5c14f5dcac..7130c85599 100644 --- a/db_structure.xml +++ b/db_structure.xml @@ -419,7 +419,13 @@ - callback + callback_success + text + 255 + + + + callback_fail text 255 @@ -475,6 +481,34 @@
+ + + *dbprefix*oauth_scopes + + + + + key + text + 40 + + + + type + text + 7 + + + + scopes + text + 255 + + + + +
+ *dbprefix*oauth_tokens From 47eebe5f6c12258cd2536fe2f0d7a9e78ff46ae5 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 31 Aug 2012 13:28:05 +0000 Subject: [PATCH 064/330] Add 'authorised' field to oauth_tokens table --- db_structure.xml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/db_structure.xml b/db_structure.xml index 7130c85599..f0f933a656 100644 --- a/db_structure.xml +++ b/db_structure.xml @@ -539,6 +539,12 @@ 7 + + authorised + boolean + 0 + +
From 37bb16becb11caf80fd2e4f608e16f7642c76137 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 4 Sep 2012 11:10:42 +0000 Subject: [PATCH 065/330] API: Add callback_fail, add OC_OAuth::init and bespoke request token method --- lib/oauth/server.php | 50 +++++++++++++++++++++++++++++++++++++------- lib/oauth/store.php | 22 ++++++++++--------- settings/oauth.php | 27 ++++++++++++++++++------ 3 files changed, 75 insertions(+), 24 deletions(-) diff --git a/lib/oauth/server.php b/lib/oauth/server.php index b14277afea..a82a1e2fb0 100644 --- a/lib/oauth/server.php +++ b/lib/oauth/server.php @@ -26,15 +26,30 @@ require_once(OC::$THIRDPARTYROOT.'/3rdparty/OAuth/OAuth.php'); class OC_OAuth_Server extends OAuthServer { - public function fetch_request_token(&$request) { - $this->get_version($request); - $consumer = $this->get_consumer($request); - $this->check_signature($request, $consumer, null); - $callback = $request->get_parameter('oauth_callback'); - $scope = $request->get_parameter('scope'); - // TODO Validate scopes - return $this->data_store->new_request_token($consumer, $scope, $callback); + /** + * sets up the server object + */ + public static function init(){ + $server = new OC_OAuth_Server(new OC_OAuth_Store()); + $server->add_signature_method(new OAuthSignatureMethod_HMAC_SHA1()); + return $server; } + + public function get_request_token(&$request){ + // Check the signature + $token = $this->fetch_request_token($request); + $scopes = $request->get_parameter('scopes'); + // Add scopes to request token + $this->saveScopes($token, $scopes); + + return $token; + } + + public function saveScopes($token, $scopes){ + $query = OC_DB::prepare("INSERT INTO `*PREFIX*oauth_scopes` (`key`, `scopes`) VALUES (?, ?)"); + $result = $query->execute(array($token->key, $scopes)); + } + /** * authorises a request token @@ -74,4 +89,23 @@ class OC_OAuth_Server extends OAuthServer { // return $user; } + /** + * registers a consumer with the ownCloud Instance + * @param string $name the name of the external app + * @param string $url the url to find out more info on the external app + * @param string $callbacksuccess the url to redirect to after autorisation success + * @param string $callbackfail the url to redirect to if the user does not authorise the application + * @return false|OAuthConsumer object + */ + static function register_consumer($name, $url, $callbacksuccess=null, $callbackfail=null){ + // TODO validation + // Check callback url is outside of ownCloud for security + // Generate key and secret + $key = sha1(md5(uniqid(rand(), true))); + $secret = sha1(md5(uniqid(rand(), true))); + $query = OC_DB::prepare("INSERT INTO `*PREFIX*oauth_consumers` (`key`, `secret`, `name`, `url`, `callback_success`, `callback_fail`) VALUES (?, ?, ?, ?, ?, ?)"); + $result = $query->execute(array($key, $secret, $name, $url, $callbacksuccess, $callbackfail)); + return new OAuthConsumer($key, $secret, $callbacksuccess); + } + } \ No newline at end of file diff --git a/lib/oauth/store.php b/lib/oauth/store.php index f1df7d49b9..aa68d38957 100644 --- a/lib/oauth/store.php +++ b/lib/oauth/store.php @@ -22,16 +22,18 @@ * */ -class OC_OAuth_Store { +class OC_OAuth_Store extends OAuthDataStore { + + static private $MAX_TIMESTAMP_DIFFERENCE = 300; function lookup_consumer($consumer_key) { - $query = OC_DB::prepare("SELECT `key`, `secret`, `callback` FROM `*PREFIX*oauth_consumers` WHERE `key` = ?"); + $query = OC_DB::prepare("SELECT `key`, `secret`, `callback_success` FROM `*PREFIX*oauth_consumers` WHERE `key` = ?"); $results = $query->execute(array($consumer_key)); if($results->numRows()==0){ return NULL; } else { $details = $results->fetchRow(); - $callback = !empty($details['callback']) ? $details['callback'] : NULL; + $callback = !empty($details['callback_success']) ? $details['callback_success'] : NULL; return new OAuthConsumer($details['key'], $details['secret'], $callback); } } @@ -49,24 +51,24 @@ class OC_OAuth_Store { function lookup_nonce($consumer, $token, $nonce, $timestamp) { $query = OC_DB::prepare("INSERT INTO `*PREFIX*oauth_nonce` (`consumer_key`, `token`, `timestamp`, `nonce`) VALUES (?, ?, ?, ?)"); - $affectedrows = $query->exec(array($consumer->key, $token->key, $timestamp, $nonce)); + $affectedrows = $query->execute(array($consumer->key, $token, $timestamp, $nonce)); // Delete all timestamps older than the one passed $query = OC_DB::prepare("DELETE FROM `*PREFIX*oauth_nonce` WHERE `consumer_key` = ? AND `token` = ? AND `timestamp` < ?"); - $query->execute(array($consumer->key, $token->key, $timestamp - self::MAX_TIMESTAMP_DIFFERENCE)); + $result = $query->exec(array($consumer->key, $token, $timestamp - self::$MAX_TIMESTAMP_DIFFERENCE)); return $result; } - function new_token($consumer, $token_type, $scope = null) { + function new_token($consumer, $token_type) { $key = md5(time()); $secret = time() + time(); $token = new OAuthToken($key, md5(md5($secret))); - $query = OC_DB::prepare("INSERT INTO `*PREFIX*oauth_tokens` (`consumer_key`, `key`, `secret`, `type`, `scope`, `timestamp`) VALUES (?, ?, ?, ?, ?, ?)"); - $result = $query->execute(array($consumer->key, $key, $secret, $token_type, $scope, time())); + $query = OC_DB::prepare("INSERT INTO `*PREFIX*oauth_tokens` (`consumer_key`, `key`, `secret`, `type`, `timestamp`) VALUES (?, ?, ?, ?, ?, ?)"); + $result = $query->execute(array($consumer->key, $key, $secret, $token_type, time())); return $token; } - function new_request_token($consumer, $scope, $callback = null) { - return $this->new_token($consumer, 'request', $scope); + function new_request_token($consumer, $callback = null) { + return $this->new_token($consumer, 'request'); } function authorise_request_token($token, $consumer, $uid) { diff --git a/settings/oauth.php b/settings/oauth.php index c6c9be515b..8dba9b33a5 100644 --- a/settings/oauth.php +++ b/settings/oauth.php @@ -6,27 +6,41 @@ */ require_once('../lib/base.php'); - // Logic $operation = isset($_GET['operation']) ? $_GET['operation'] : ''; -$server = new OC_OAuth_Server(new OC_OAuth_Store()); +$server = OC_OAuth_server::init(); + switch($operation){ case 'register': - + + // Here external apps can register with an ownCloud + if(empty($_GET['name']) || empty($_GET['url'])){ + // Invalid request + echo 401; + } else { + $callbacksuccess = empty($_GET['callback_success']) ? null : $_GET['callback_success']; + $callbackfail = empty($_GET['callback_fail']) ? null : $_GET['callback_fail']; + $consumer = OC_OAuth_Server::register_consumer($_GET['name'], $_GET['url'], $callbacksuccess, $callbackfail); + + echo 'Registered consumer successfully!

Key: ' . $consumer->key . '
Secret: ' . $consumer->secret; + } break; case 'request_token': + try { $request = OAuthRequest::from_request(); - $token = $server->fetch_request_token($request); + $token = $server->get_request_token($request); echo $token; } catch (OAuthException $exception) { OC_Log::write('OC_OAuth_Server', $exception->getMessage(), OC_LOG::ERROR); echo $exception->getMessage(); } - break; + + break; case 'authorise'; + OC_API::checkLoggedIn(); // Example $consumer = array( @@ -74,7 +88,8 @@ switch($operation){ OC_Log::write('OC_OAuth_Server', $exception->getMessage(), OC_LOG::ERROR); echo $exception->getMessage(); } - break; + + break; default: // Something went wrong, we need an operation! OC_Response::setStatus(400); From 4224eb88314bdece2a254decf7ebf9ffd7b57678 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 4 Sep 2012 13:50:56 +0000 Subject: [PATCH 066/330] API: remove OAuth auth check, respond in ocs formatted xml/json --- lib/api.php | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/lib/api.php b/lib/api.php index 55de438f42..92fa05bd71 100644 --- a/lib/api.php +++ b/lib/api.php @@ -74,15 +74,15 @@ class OC_API { foreach(self::$actions[$name] as $action){ $app = $action['app']; // Check the consumer has permission to call this method. - if(OC_OAuth_Server::isAuthorised('app_'.$app)){ + //if(OC_OAuth_Server::isAuthorised('app_'.$app)){ if(is_callable($action['action'])){ $responses[] = array('app' => $app, 'response' => call_user_func($action['action'], $parameters)); } else { $responses[] = array('app' => $app, 'response' => 501); } - } else { - $responses[] = array('app' => $app, 'response' => 401); - } + //} else { + // $responses[] = array('app' => $app, 'response' => 401); + //} } // Merge the responses @@ -103,25 +103,39 @@ class OC_API { * @return array the final merged response */ private static function mergeResponses($responses){ - $finalresponse = array(); + $finalresponse = array( + 'meta' => array( + 'statuscode' => '', + ), + 'data' => array(), + ); $numresponses = count($responses); foreach($responses as $response){ - if(is_int($response['response']) && empty($finalresponse)){ - $finalresponse = $response['response']; + if(is_int($response['response']) && empty($finalresponse['meta']['statuscode'])){ + $finalresponse['meta']['statuscode'] = $response['response']; continue; } if(is_array($response['response'])){ // Shipped apps win if(OC_App::isShipped($response['app'])){ - $finalresponse = array_merge_recursive($finalresponse, $response['response']); + $finalresponse['data'] = array_merge_recursive($finalresponse['data'], $response['response']); } else { - $finalresponse = array_merge_recursive($response['response'], $finalresponse); + $finalresponse['data'] = array_merge_recursive($response['response'], $finalresponse['data']); } + $finalresponse['meta']['statuscode'] = 100; } } - - return $finalresponse; + //Some tidying up + if($finalresponse['meta']['statuscode']=='100'){ + $finalresponse['meta']['status'] = 'ok'; + } else { + $finalresponse['meta']['status'] = 'failure'; + } + if(empty($finalresponse['data'])){ + unset($finalresponse['data']); + } + return array('ocs' => $finalresponse); } /** From 470b87f62574f62ce132cd24a9c014aac51ddc91 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 5 Sep 2012 09:07:15 +0000 Subject: [PATCH 067/330] Fix ocs/person/check --- lib/ocs/person.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/lib/ocs/person.php b/lib/ocs/person.php index 629a7c2e6c..c757385dfe 100644 --- a/lib/ocs/person.php +++ b/lib/ocs/person.php @@ -3,10 +3,11 @@ class OC_OCS_Person { public static function check($parameters){ - - if($parameters['login']<>''){ - if(OC_User::login($parameters['login'],$parameters['password'])){ - $xml['person']['personid'] = $parameters['login']; + $login = isset($_POST['login']) ? $_POST['login'] : false; + $password = isset($_POST['password']) ? $_POST['password'] : false; + if($login && $password){ + if(OC_User::checkPassword($login,$password)){ + $xml['person']['personid'] = $login; return $xml; }else{ return 102; From 2c664c60e27df290ba4c1d5de42cf50beac2cfdb Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 5 Sep 2012 12:27:17 +0000 Subject: [PATCH 068/330] API: Fix routes definition --- apps/provisioning_api/appinfo/routes.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/provisioning_api/appinfo/routes.php b/apps/provisioning_api/appinfo/routes.php index c942dea537..6468f814bd 100644 --- a/apps/provisioning_api/appinfo/routes.php +++ b/apps/provisioning_api/appinfo/routes.php @@ -26,7 +26,7 @@ OCP\API::register('get', '/cloud/users', array('OC_Provisioning_API_Users', 'get OCP\API::register('post', '/cloud/users', array('OC_Provisioning_API_Users', 'addUser'), 'provisioning_api'); OCP\API::register('get', '/cloud/users/{userid}', array('OC_Provisioning_API_Users', 'getUser'), 'provisioning_api'); OCP\API::register('put', '/cloud/users/{userid}', array('OC_Provisioning_API_Users', 'editUser'), 'provisioning_api'); -OCP\API::register('delete', '/cloud/users/{userid}', array('OC_Provisioning_API_Users', 'getUsers'), 'provisioning_api'); +OCP\API::register('delete', '/cloud/users/{userid}', array('OC_Provisioning_API_Users', 'deleteUser'), 'provisioning_api'); OCP\API::register('get', '/cloud/users/{userid}/sharedwith', array('OC_Provisioning_API_Users', 'getSharedWithUser'), 'provisioning_api'); OCP\API::register('get', '/cloud/users/{userid}/sharedby', array('OC_Provisioning_API_Users', 'getSharedByUser'), 'provisioning_api'); OCP\API::register('delete', '/cloud/users/{userid}/sharedby', array('OC_Provisioning_API_Users', 'deleteSharedByUser'), 'provisioning_api'); @@ -40,7 +40,7 @@ OCP\API::register('get', '/cloud/groups/{groupid}', array('OC_Provisioning_API_G OCP\API::register('delete', '/cloud/groups/{groupid}', array('OC_Provisioning_API_Groups', 'deleteGroup'), 'provisioning_api'); // apps OCP\API::register('get', '/cloud/apps', array('OC_Provisioning_API_Apps', 'getApps'), 'provisioning_api'); -OCP\API::register('get', '/cloud/apps/{appid}', array('OC_Provisioning_API_Apps', 'getApp'), 'provisioning_api'); +OCP\API::register('get', '/cloud/apps/{appid}', array('OC_Provisioning_API_Apps', 'getAppInfo'), 'provisioning_api'); OCP\API::register('post', '/cloud/apps/{appid}', array('OC_Provisioning_API_Apps', 'enable'), 'provisioning_api'); OCP\API::register('delete', '/cloud/apps/{appid}', array('OC_Provisioning_API_Apps', 'disable'), 'provisioning_api'); ?> \ No newline at end of file From 3717969fb1e92b9f06e5dd693feb91036d19654d Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 5 Sep 2012 12:30:24 +0000 Subject: [PATCH 069/330] API: Add provisioning api methods for apps --- apps/provisioning_api/lib/apps.php | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/apps/provisioning_api/lib/apps.php b/apps/provisioning_api/lib/apps.php index fcb1e5ba8f..ef23d8d5a0 100644 --- a/apps/provisioning_api/lib/apps.php +++ b/apps/provisioning_api/lib/apps.php @@ -24,19 +24,41 @@ class OC_Provisioning_API_Apps { public static function getApps($parameters){ - + $filter = isset($_GET['filter']) ? $_GET['filter'] : false; + if($filter){ + switch($filter){ + case 'enabled': + return array('apps' => OC_App::getEnabledApps()); + break; + case 'disabled': + $apps = OC_App::getAllApps(); + $enabled = OC_App::getEnabledApps(); + return array('apps' => array_diff($apps, $enabled)); + break; + default: + // Invalid filter variable + return 101; + break; + } + + } else { + return array('apps' => OC_App::getAllApps()); + } } public static function getAppInfo($parameters){ - + $app = $parameters['appid']; + return OC_App::getAppInfo($app); } public static function enable($parameters){ - + $app = $parameters['appid']; + OC_App::enable($app); } public static function diable($parameters){ - + $app = $parameters['appid']; + OC_App::disable($app); } } \ No newline at end of file From 6c98a94d3deb5a50fed57c5752999d60601e4af5 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 5 Sep 2012 12:32:29 +0000 Subject: [PATCH 070/330] API: Fix addUser and added getUser methods --- apps/provisioning_api/lib/users.php | 24 ++++++++++++++++-------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/apps/provisioning_api/lib/users.php b/apps/provisioning_api/lib/users.php index 2bc0434d87..93eef495e3 100644 --- a/apps/provisioning_api/lib/users.php +++ b/apps/provisioning_api/lib/users.php @@ -30,22 +30,24 @@ class OC_Provisioning_API_Users { return OC_User::getUsers(); } - public static function addUser($parameters){ + public static function addUser(){ + $userid = isset($_POST['userid']) ? $_POST['userid'] : null; + $password = isset($_POST['password']) ? $_POST['password'] : null; try { - OC_User::createUser($parameters['userid'], $parameters['password']); - return 200; + OC_User::createUser($userid, $password); + return 100; } catch (Exception $e) { switch($e->getMessage()){ case 'Only the following characters are allowed in a username: "a-z", "A-Z", "0-9", and "_.@-"': case 'A valid username must be provided': case 'A valid password must be provided': - return 400; + return 101; break; case 'The username is already being used'; - return 409; + return 102; break; default: - return 500; + return 103; break; } } @@ -55,7 +57,12 @@ class OC_Provisioning_API_Users { * gets user info */ public static function getUser($parameters){ - + $userid = $parameters['userid']; + $return = array(); + $return['email'] = OC_Preferences::getValue($userid, 'settings', 'email', ''); + $default = OC_Appconfig::getValue('files', 'default_quota', 0); + $return['quota'] = OC_Preferences::getValue($userid, 'files', 'quota', $default); + return $return; } public static function editUser($parameters){ @@ -79,7 +86,8 @@ class OC_Provisioning_API_Users { } public static function getUsersGroups($parameters){ - + $userid = $parameters['userid']; + return array('groups' => OC_Group::getUserGroups($userid)); } public static function addToGroup($parameters){ From 28a11959d744fd5e23c4a5543c24863c77160644 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 5 Sep 2012 12:32:54 +0000 Subject: [PATCH 071/330] API: Fix /person/check api method --- lib/ocs/person.php | 1 + 1 file changed, 1 insertion(+) diff --git a/lib/ocs/person.php b/lib/ocs/person.php index c757385dfe..23b8853533 100644 --- a/lib/ocs/person.php +++ b/lib/ocs/person.php @@ -16,4 +16,5 @@ class OC_OCS_Person { return 101; } } + } From 6fbc1d74c4d492485c3a2813839dbda6aa68d8cd Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 5 Sep 2012 12:40:29 +0000 Subject: [PATCH 072/330] API: Fix responses of enable and disable app methods --- apps/provisioning_api/lib/apps.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/provisioning_api/lib/apps.php b/apps/provisioning_api/lib/apps.php index ef23d8d5a0..0cac183e4e 100644 --- a/apps/provisioning_api/lib/apps.php +++ b/apps/provisioning_api/lib/apps.php @@ -54,11 +54,13 @@ class OC_Provisioning_API_Apps { public static function enable($parameters){ $app = $parameters['appid']; OC_App::enable($app); + return 100; } - public static function diable($parameters){ + public static function disable($parameters){ $app = $parameters['appid']; OC_App::disable($app); + return 100; } } \ No newline at end of file From 707f74226f5438e825dbe443dd227fbf41c6a3c9 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 5 Sep 2012 12:49:25 +0000 Subject: [PATCH 073/330] API: /cloud/groups use OCS response codes, fix response of getGroups, fix addGroup --- apps/provisioning_api/lib/groups.php | 30 ++++++++++++++-------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/apps/provisioning_api/lib/groups.php b/apps/provisioning_api/lib/groups.php index 6a18e6b37f..0dc9319782 100644 --- a/apps/provisioning_api/lib/groups.php +++ b/apps/provisioning_api/lib/groups.php @@ -27,8 +27,7 @@ class OC_Provisioning_API_Groups{ * returns a list of groups */ public static function getGroups($parameters){ - $groups = OC_Group::getGroups(); - return empty($groups) ? 404 : $groups; + return array('groups' => OC_Group::getGroups()); } /** @@ -37,9 +36,9 @@ class OC_Provisioning_API_Groups{ public static function getGroup($parameters){ // Check the group exists if(!OC_Group::groupExists($parameters['groupid'])){ - return 404; + return 101; } - return OC_Group::usersInGroup($parameters['groupid']); + return array('users' => OC_Group::usersInGroup($parameters['groupid'])); } /** @@ -47,32 +46,33 @@ class OC_Provisioning_API_Groups{ */ public static function addGroup($parameters){ // Validate name - if( preg_match( '/[^a-zA-Z0-9 _\.@\-]/', $parameters['groupid'] ) || empty($parameters['groupid'])){ - return 401; + $groupid = isset($_POST['groupid']) ? $_POST['groupid'] : ''; + if( preg_match( '/[^a-zA-Z0-9 _\.@\-]/', $groupid ) || empty($groupid)){ + return 101; } // Check if it exists - if(OC_Group::groupExists($parameters['groupid'])){ - return 409; + if(OC_Group::groupExists($groupid)){ + return 102; } - if(OC_Group::createGroup($parameters['groupid'])){ - return 200; + if(OC_Group::createGroup($groupid)){ + return 100; } else { - return 500; + return 103; } } public static function deleteGroup($parameters){ // Check it exists if(!OC_Group::groupExists($parameters['groupid'])){ - return 404; + return 101; } else if($parameters['groupid'] == 'admin'){ // Cannot delete admin group - return 403; + return 102; } else { if(OC_Group::deleteGroup($parameters['groupid'])){ - return 200; + return 100; } else { - return 500; + return 103; } } } From fa5dff22a02aeb5985215454549ab1020382b197 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 09:41:20 +0000 Subject: [PATCH 074/330] API: Require api calls to register the required auth level --- lib/api.php | 63 +++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 56 insertions(+), 7 deletions(-) diff --git a/lib/api.php b/lib/api.php index 92fa05bd71..c278f7672f 100644 --- a/lib/api.php +++ b/lib/api.php @@ -26,6 +26,14 @@ class OC_API { + /** + * API authentication levels + */ + const GUEST_AUTH = 0; + const USER_AUTH = 1; + const SUBADMIN_AUTH = 2; + const ADMIN_AUTH = 3; + private static $server; /** @@ -46,8 +54,12 @@ class OC_API { * @param string $url the url to match * @param callable $action the function to run * @param string $app the id of the app registering the call + * @param int $authlevel the level of authentication required for the call + * @param array $defaults + * @param array $requirements */ - public static function register($method, $url, $action, $app, + public static function register($method, $url, $action, $app, + $authlevel = OC_API::USER_AUTH, $defaults = array(), $requirements = array()){ $name = strtolower($method).$url; @@ -61,7 +73,7 @@ class OC_API { ->action('OC_API', 'call'); self::$actions[$name] = array(); } - self::$actions[$name][] = array('app' => $app, 'action' => $action); + self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authlevel); } /** @@ -73,16 +85,16 @@ class OC_API { // Loop through registered actions foreach(self::$actions[$name] as $action){ $app = $action['app']; - // Check the consumer has permission to call this method. - //if(OC_OAuth_Server::isAuthorised('app_'.$app)){ + // Authorsie this call + if($this->isAuthorised($action)){ if(is_callable($action['action'])){ $responses[] = array('app' => $app, 'response' => call_user_func($action['action'], $parameters)); } else { $responses[] = array('app' => $app, 'response' => 501); } - //} else { - // $responses[] = array('app' => $app, 'response' => 401); - //} + } else { + $responses[] = array('app' => $app, 'response' => 401); + } } // Merge the responses @@ -97,6 +109,43 @@ class OC_API { OC_User::logout(); } + /** + * authenticate the api call + * @param array $action the action details as supplied to OC_API::register() + * @return bool + */ + private function isAuthorised($action){ + $level = $action['authlevel']; + switch($level){ + case OC_API::GUEST_AUTH: + // Anyone can access + return true; + break; + case OC_API::USER_AUTH: + // User required + // Check url for username and password + break; + case OC_API::SUBADMIN_AUTH: + // Check for subadmin + break; + case OC_API::ADMIN_AUTH: + // Check for admin + break; + default: + // oops looks like invalid level supplied + return false; + break; + } + } + + /** + * gets login details from url and logs in the user + * @return bool + */ + public function loginUser(){ + // Todo + } + /** * intelligently merges the different responses * @param array $responses From a0452180b05388b5c31f2cbab9e53c542f3b8cc2 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 10:28:05 +0000 Subject: [PATCH 075/330] Remove provisioning_api apps from core --- apps/provisioning_api/appinfo/app.php | 27 ------ apps/provisioning_api/appinfo/info.xml | 11 --- apps/provisioning_api/appinfo/routes.php | 46 ----------- apps/provisioning_api/appinfo/version | 1 - apps/provisioning_api/lib/apps.php | 66 --------------- apps/provisioning_api/lib/groups.php | 80 ------------------ apps/provisioning_api/lib/users.php | 101 ----------------------- 7 files changed, 332 deletions(-) delete mode 100644 apps/provisioning_api/appinfo/app.php delete mode 100644 apps/provisioning_api/appinfo/info.xml delete mode 100644 apps/provisioning_api/appinfo/routes.php delete mode 100644 apps/provisioning_api/appinfo/version delete mode 100644 apps/provisioning_api/lib/apps.php delete mode 100644 apps/provisioning_api/lib/groups.php delete mode 100644 apps/provisioning_api/lib/users.php diff --git a/apps/provisioning_api/appinfo/app.php b/apps/provisioning_api/appinfo/app.php deleted file mode 100644 index 992ee23b5c..0000000000 --- a/apps/provisioning_api/appinfo/app.php +++ /dev/null @@ -1,27 +0,0 @@ -. -* -*/ - -OC::$CLASSPATH['OC_Provisioning_API_Users'] = 'apps/provisioning_api/lib/users.php'; -OC::$CLASSPATH['OC_Provisioning_API_Groups'] = 'apps/provisioning_api/lib/groups.php'; -OC::$CLASSPATH['OC_Provisioning_API_Apps'] = 'apps/provisioning_api/lib/apps.php'; -?> \ No newline at end of file diff --git a/apps/provisioning_api/appinfo/info.xml b/apps/provisioning_api/appinfo/info.xml deleted file mode 100644 index eb96115507..0000000000 --- a/apps/provisioning_api/appinfo/info.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - provisioning_api - Provisioning API - AGPL - Tom Needham - 5 - true - Provides API methods to manage an ownCloud Instance - - diff --git a/apps/provisioning_api/appinfo/routes.php b/apps/provisioning_api/appinfo/routes.php deleted file mode 100644 index 6468f814bd..0000000000 --- a/apps/provisioning_api/appinfo/routes.php +++ /dev/null @@ -1,46 +0,0 @@ -. -* -*/ - -// users -OCP\API::register('get', '/cloud/users', array('OC_Provisioning_API_Users', 'getUsers'), 'provisioning_api'); -OCP\API::register('post', '/cloud/users', array('OC_Provisioning_API_Users', 'addUser'), 'provisioning_api'); -OCP\API::register('get', '/cloud/users/{userid}', array('OC_Provisioning_API_Users', 'getUser'), 'provisioning_api'); -OCP\API::register('put', '/cloud/users/{userid}', array('OC_Provisioning_API_Users', 'editUser'), 'provisioning_api'); -OCP\API::register('delete', '/cloud/users/{userid}', array('OC_Provisioning_API_Users', 'deleteUser'), 'provisioning_api'); -OCP\API::register('get', '/cloud/users/{userid}/sharedwith', array('OC_Provisioning_API_Users', 'getSharedWithUser'), 'provisioning_api'); -OCP\API::register('get', '/cloud/users/{userid}/sharedby', array('OC_Provisioning_API_Users', 'getSharedByUser'), 'provisioning_api'); -OCP\API::register('delete', '/cloud/users/{userid}/sharedby', array('OC_Provisioning_API_Users', 'deleteSharedByUser'), 'provisioning_api'); -OCP\API::register('get', '/cloud/users/{userid}/groups', array('OC_Provisioning_API_Users', 'getUsersGroups'), 'provisioning_api'); -OCP\API::register('post', '/cloud/users/{userid}/groups', array('OC_Provisioning_API_Users', 'addToGroup'), 'provisioning_api'); -OCP\API::register('delete', '/cloud/users/{userid}/groups', array('OC_Provisioning_API_Users', 'removeFromGroup'), 'provisioning_api'); -// groups -OCP\API::register('get', '/cloud/groups', array('OC_Provisioning_API_Groups', 'getGroups'), 'provisioning_api'); -OCP\API::register('post', '/cloud/groups', array('OC_Provisioning_API_Groups', 'addGroup'), 'provisioning_api'); -OCP\API::register('get', '/cloud/groups/{groupid}', array('OC_Provisioning_API_Groups', 'getGroup'), 'provisioning_api'); -OCP\API::register('delete', '/cloud/groups/{groupid}', array('OC_Provisioning_API_Groups', 'deleteGroup'), 'provisioning_api'); -// apps -OCP\API::register('get', '/cloud/apps', array('OC_Provisioning_API_Apps', 'getApps'), 'provisioning_api'); -OCP\API::register('get', '/cloud/apps/{appid}', array('OC_Provisioning_API_Apps', 'getAppInfo'), 'provisioning_api'); -OCP\API::register('post', '/cloud/apps/{appid}', array('OC_Provisioning_API_Apps', 'enable'), 'provisioning_api'); -OCP\API::register('delete', '/cloud/apps/{appid}', array('OC_Provisioning_API_Apps', 'disable'), 'provisioning_api'); -?> \ No newline at end of file diff --git a/apps/provisioning_api/appinfo/version b/apps/provisioning_api/appinfo/version deleted file mode 100644 index 49d59571fb..0000000000 --- a/apps/provisioning_api/appinfo/version +++ /dev/null @@ -1 +0,0 @@ -0.1 diff --git a/apps/provisioning_api/lib/apps.php b/apps/provisioning_api/lib/apps.php deleted file mode 100644 index 0cac183e4e..0000000000 --- a/apps/provisioning_api/lib/apps.php +++ /dev/null @@ -1,66 +0,0 @@ -. -* -*/ - -class OC_Provisioning_API_Apps { - - public static function getApps($parameters){ - $filter = isset($_GET['filter']) ? $_GET['filter'] : false; - if($filter){ - switch($filter){ - case 'enabled': - return array('apps' => OC_App::getEnabledApps()); - break; - case 'disabled': - $apps = OC_App::getAllApps(); - $enabled = OC_App::getEnabledApps(); - return array('apps' => array_diff($apps, $enabled)); - break; - default: - // Invalid filter variable - return 101; - break; - } - - } else { - return array('apps' => OC_App::getAllApps()); - } - } - - public static function getAppInfo($parameters){ - $app = $parameters['appid']; - return OC_App::getAppInfo($app); - } - - public static function enable($parameters){ - $app = $parameters['appid']; - OC_App::enable($app); - return 100; - } - - public static function disable($parameters){ - $app = $parameters['appid']; - OC_App::disable($app); - return 100; - } - -} \ No newline at end of file diff --git a/apps/provisioning_api/lib/groups.php b/apps/provisioning_api/lib/groups.php deleted file mode 100644 index 0dc9319782..0000000000 --- a/apps/provisioning_api/lib/groups.php +++ /dev/null @@ -1,80 +0,0 @@ -. -* -*/ - -class OC_Provisioning_API_Groups{ - - /** - * returns a list of groups - */ - public static function getGroups($parameters){ - return array('groups' => OC_Group::getGroups()); - } - - /** - * returns an array of users in the group specified - */ - public static function getGroup($parameters){ - // Check the group exists - if(!OC_Group::groupExists($parameters['groupid'])){ - return 101; - } - return array('users' => OC_Group::usersInGroup($parameters['groupid'])); - } - - /** - * creates a new group - */ - public static function addGroup($parameters){ - // Validate name - $groupid = isset($_POST['groupid']) ? $_POST['groupid'] : ''; - if( preg_match( '/[^a-zA-Z0-9 _\.@\-]/', $groupid ) || empty($groupid)){ - return 101; - } - // Check if it exists - if(OC_Group::groupExists($groupid)){ - return 102; - } - if(OC_Group::createGroup($groupid)){ - return 100; - } else { - return 103; - } - } - - public static function deleteGroup($parameters){ - // Check it exists - if(!OC_Group::groupExists($parameters['groupid'])){ - return 101; - } else if($parameters['groupid'] == 'admin'){ - // Cannot delete admin group - return 102; - } else { - if(OC_Group::deleteGroup($parameters['groupid'])){ - return 100; - } else { - return 103; - } - } - } - -} \ No newline at end of file diff --git a/apps/provisioning_api/lib/users.php b/apps/provisioning_api/lib/users.php deleted file mode 100644 index 93eef495e3..0000000000 --- a/apps/provisioning_api/lib/users.php +++ /dev/null @@ -1,101 +0,0 @@ -. -* -*/ - -class OC_Provisioning_API_Users { - - /** - * returns a list of users - */ - public static function getUsers($parameters){ - return OC_User::getUsers(); - } - - public static function addUser(){ - $userid = isset($_POST['userid']) ? $_POST['userid'] : null; - $password = isset($_POST['password']) ? $_POST['password'] : null; - try { - OC_User::createUser($userid, $password); - return 100; - } catch (Exception $e) { - switch($e->getMessage()){ - case 'Only the following characters are allowed in a username: "a-z", "A-Z", "0-9", and "_.@-"': - case 'A valid username must be provided': - case 'A valid password must be provided': - return 101; - break; - case 'The username is already being used'; - return 102; - break; - default: - return 103; - break; - } - } - } - - /** - * gets user info - */ - public static function getUser($parameters){ - $userid = $parameters['userid']; - $return = array(); - $return['email'] = OC_Preferences::getValue($userid, 'settings', 'email', ''); - $default = OC_Appconfig::getValue('files', 'default_quota', 0); - $return['quota'] = OC_Preferences::getValue($userid, 'files', 'quota', $default); - return $return; - } - - public static function editUser($parameters){ - - } - - public static function deleteUser($parameters){ - - } - - public static function getSharedWithUser($parameters){ - - } - - public static function getSharedByUser($parameters){ - - } - - public static function deleteSharedByUser($parameters){ - - } - - public static function getUsersGroups($parameters){ - $userid = $parameters['userid']; - return array('groups' => OC_Group::getUserGroups($userid)); - } - - public static function addToGroup($parameters){ - - } - - public static function removeFromGroup($parameters){ - - } - -} \ No newline at end of file From 182f890110f86ced32177dde2ac2fc2437bb2305 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 10:32:35 +0000 Subject: [PATCH 076/330] Remove a merge conflict --- lib/base.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/lib/base.php b/lib/base.php index c7f6fd8ad8..0da33b4d0f 100644 --- a/lib/base.php +++ b/lib/base.php @@ -268,7 +268,6 @@ class OC{ session_start(); } -<<<<<<< HEAD public static function loadapp(){ if(file_exists(OC_App::getAppPath(OC::$REQUESTEDAPP) . '/index.php')){ require_once(OC_App::getAppPath(OC::$REQUESTEDAPP) . '/index.php'); @@ -304,9 +303,7 @@ class OC{ } public static function init(){ -======= - public static function init() { ->>>>>>> master + // register autoloader spl_autoload_register(array('OC','autoload')); setlocale(LC_ALL, 'en_US.UTF-8'); From b261c980c71112fb74541e4c93901ae12449b0d0 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 10:50:10 +0000 Subject: [PATCH 077/330] Fix autoloader merge conflict --- lib/base.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/base.php b/lib/base.php index 0da33b4d0f..2b05fd7f9e 100644 --- a/lib/base.php +++ b/lib/base.php @@ -95,11 +95,13 @@ class OC{ $path = str_replace('_', '/', $className) . '.php'; } elseif(strpos($className,'Symfony\\')===0){ - require_once str_replace('\\','/',$className) . '.php'; + $path = str_replace('\\','/',$className) . '.php'; } elseif(strpos($className,'Test_')===0){ - require_once 'tests/lib/'.strtolower(str_replace('_','/',substr($className,5)) . '.php'); + $path = 'tests/lib/'.strtolower(str_replace('_','/',substr($className,5)) . '.php'); + } else { + return false; } if($fullPath = stream_resolve_include_path($path)) { From 8b409dfe2ad634b84dcbcc54cdd668488318e79b Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 14:15:04 +0000 Subject: [PATCH 078/330] API: Default to user authentication level --- lib/public/api.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/lib/public/api.php b/lib/public/api.php index ed1f6ef237..2821554229 100644 --- a/lib/public/api.php +++ b/lib/public/api.php @@ -33,9 +33,10 @@ class API { * @param string $url the url to match * @param callable $action the function to run * @param string $app the id of the app registering the call + * @param int $authlevel the level of authentication required for the call (See OC_API constants) */ - public static function register($method, $url, $action, $app){ - \OC_API::register($method, $url, $action, $app); + public static function register($method, $url, $action, $app, $authlevel = OC_API::USER_AUTH){ + \OC_API::register($method, $url, $action, $app, $authlevel); } } From a8c82440d0f4158151b9f28c6bfc0bbc14aea3e1 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 15:18:38 +0000 Subject: [PATCH 079/330] API: Use http authentication, check the auth level required --- lib/api.php | 41 ++++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/lib/api.php b/lib/api.php index c278f7672f..29446e979f 100644 --- a/lib/api.php +++ b/lib/api.php @@ -86,7 +86,7 @@ class OC_API { foreach(self::$actions[$name] as $action){ $app = $action['app']; // Authorsie this call - if($this->isAuthorised($action)){ + if(self::isAuthorised($action)){ if(is_callable($action['action'])){ $responses[] = array('app' => $app, 'response' => call_user_func($action['action'], $parameters)); } else { @@ -105,7 +105,7 @@ class OC_API { } else { self::respond($response); } - // logout the user to be stateles + // logout the user to be stateless OC_User::logout(); } @@ -114,7 +114,7 @@ class OC_API { * @param array $action the action details as supplied to OC_API::register() * @return bool */ - private function isAuthorised($action){ + private static function isAuthorised($action){ $level = $action['authlevel']; switch($level){ case OC_API::GUEST_AUTH: @@ -123,13 +123,25 @@ class OC_API { break; case OC_API::USER_AUTH: // User required - // Check url for username and password + return self::loginUser(); break; case OC_API::SUBADMIN_AUTH: // Check for subadmin + $user = self::loginUser(); + if(!$user){ + return false; + } else { + return OC_SubAdmin::isSubAdmin($user); + } break; case OC_API::ADMIN_AUTH: // Check for admin + $user = self::loginUser(); + if(!$user){ + return false; + } else { + return OC_Group::inGroup($user, 'admin'); + } break; default: // oops looks like invalid level supplied @@ -139,11 +151,13 @@ class OC_API { } /** - * gets login details from url and logs in the user - * @return bool + * http basic auth + * @return string|false (username, or false on failure) */ - public function loginUser(){ - // Todo + private static function loginUser(){ + $authuser = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : ''; + $authpw = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : ''; + return OC_User::login($authuser, $authpw) ? $authuser : false; } /** @@ -222,17 +236,6 @@ class OC_API { $writer->writeElement($k, $v); } } - } - /** - * check if the user is authenticated - */ - public static function checkLoggedIn(){ - // Check OAuth - if(!OC_OAuth_Server::isAuthorised()){ - OC_Response::setStatus(401); - die(); - } - } } From 0c55ca1d0a04a1c4cae2665458cdb7fd1bc3d80e Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 15:27:44 +0000 Subject: [PATCH 080/330] API: Add required auth level to OCS routes, move some routes to provisioning_api app --- ocs/routes.php | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/ocs/routes.php b/ocs/routes.php index 696b17ca23..6b01abe31f 100644 --- a/ocs/routes.php +++ b/ocs/routes.php @@ -6,22 +6,18 @@ */ // Config -OC_API::register('get', '/config', array('OC_OCS_Config', 'apiConfig'), 'ocs'); +OC_API::register('get', '/config', array('OC_OCS_Config', 'apiConfig'), 'ocs', OC_API::GUEST_AUTH); // Person -OC_API::register('post', '/person/check', array('OC_OCS_Person', 'check'), 'ocs'); +OC_API::register('post', '/person/check', array('OC_OCS_Person', 'check'), 'ocs', OC_API::GUEST_AUTH); // Activity -OC_API::register('get', '/activity', array('OC_OCS_Activity', 'activityGet'), 'ocs'); +OC_API::register('get', '/activity', array('OC_OCS_Activity', 'activityGet'), 'ocs', OC_API::USER_AUTH); // Privatedata -OC_API::register('get', '/privatedata/getattribute', array('OC_OCS_Privatedata', 'get'), 'ocs', array('app' => '', 'key' => '')); -OC_API::register('get', '/privatedata/getattribute/{app}', array('OC_OCS_Privatedata', 'get'), 'ocs', array('key' => '')); -OC_API::register('get', '/privatedata/getattribute/{app}/{key}', array('OC_OCS_Privatedata', 'get'), 'ocs'); -OC_API::register('post', '/privatedata/setattribute/{app}/{key}', array('OC_OCS_Privatedata', 'set'), 'ocs'); -OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}', array('OC_OCS_Privatedata', 'delete'), 'ocs'); +OC_API::register('get', '/privatedata/getattribute', array('OC_OCS_Privatedata', 'get'), 'ocs', OC_API::USER_AUTH, array('app' => '', 'key' => '')); +OC_API::register('get', '/privatedata/getattribute/{app}', array('OC_OCS_Privatedata', 'get'), 'ocs', OC_API::USER_AUTH, array('key' => '')); +OC_API::register('get', '/privatedata/getattribute/{app}/{key}', array('OC_OCS_Privatedata', 'get'), 'ocs', OC_API::USER_AUTH); +OC_API::register('post', '/privatedata/setattribute/{app}/{key}', array('OC_OCS_Privatedata', 'set'), 'ocs', OC_API::USER_AUTH); +OC_API::register('post', '/privatedata/deleteattribute/{app}/{key}', array('OC_OCS_Privatedata', 'delete'), 'ocs', OC_API::USER_AUTH); // Cloud -OC_API::register('get', '/cloud/system/webapps', array('OC_OCS_Cloud', 'getSystemWebApps'), 'ocs'); -OC_API::register('get', '/cloud/user/{user}/quota', array('OC_OCS_Cloud', 'getUserQuota'), 'ocs'); -OC_API::register('post', '/cloud/user/{user}/quota', array('OC_OCS_Cloud', 'setUserQuota'), 'ocs'); -OC_API::register('get', '/cloud/user/{user}/publickey', array('OC_OCS_Cloud', 'getUserPublicKey'), 'ocs'); -OC_API::register('get', '/cloud/user/{user}/privatekey', array('OC_OCS_Cloud', 'getUserPrivateKey'), 'ocs'); +OC_API::register('get', '/cloud/system/webapps', array('OC_OCS_Cloud', 'getSystemWebApps'), 'ocs', OC_API::ADMIN_AUTH); ?> From 0f07226270d02ba7b8b1da8247cdbcb206a6c744 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 14 Sep 2012 13:41:06 +0000 Subject: [PATCH 081/330] API: Allow admins to access SUBADMIN api methods --- lib/api.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/api.php b/lib/api.php index 29446e979f..ba6e880261 100644 --- a/lib/api.php +++ b/lib/api.php @@ -131,7 +131,13 @@ class OC_API { if(!$user){ return false; } else { - return OC_SubAdmin::isSubAdmin($user); + $subadmin = OC_SubAdmin::isSubAdmin($user); + $admin = OC_Group::inGroup($user, 'admin'); + if($subadmin || $admin){ + return true; + } else { + return false; + } } break; case OC_API::ADMIN_AUTH: @@ -236,6 +242,6 @@ class OC_API { $writer->writeElement($k, $v); } } - + } } From 8926038591a2c290580f13cbb5d8581d0f7861e5 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 17 Sep 2012 12:07:42 +0000 Subject: [PATCH 082/330] API: Fix merge conflict remnants --- lib/ocs.php | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/ocs.php b/lib/ocs.php index 6cdb248086..1cec3ecc7c 100644 --- a/lib/ocs.php +++ b/lib/ocs.php @@ -82,7 +82,6 @@ class OC_OCS { echo('internal server error: method not supported'); exit(); } -<<<<<<< HEAD $format = self::readData($method, 'format', 'text', ''); $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n"; $txt.=OC_OCS::getDebugOutput(); From 3ea01df1cdc3fe8774bf7e2d5eb93cc0fe809345 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 17 Sep 2012 12:08:17 +0000 Subject: [PATCH 083/330] API: Parse PUT and DELETE variables --- lib/api.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/lib/api.php b/lib/api.php index ba6e880261..2940303023 100644 --- a/lib/api.php +++ b/lib/api.php @@ -81,6 +81,12 @@ class OC_API { * @param array $parameters */ public static function call($parameters){ + // Prepare the request variables + if($_SERVER['REQUEST_METHOD'] == 'PUT'){ + parse_str(file_get_contents("php://input"), $_PUT); + } else if($_SERVER['REQUEST_METHOD'] == 'DELETE'){ + parse_str(file_get_contents("php://input"), $_DELETE); + } $name = $parameters['_route']; // Loop through registered actions foreach(self::$actions[$name] as $action){ From 07111ff672037282a6ca870fc19eab9f36875ea0 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sun, 28 Oct 2012 11:04:23 +0000 Subject: [PATCH 084/330] Allow apps to pass defaults and requirements for their API calls --- lib/public/api.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/public/api.php b/lib/public/api.php index 2821554229..9d6d1153e6 100644 --- a/lib/public/api.php +++ b/lib/public/api.php @@ -34,9 +34,11 @@ class API { * @param callable $action the function to run * @param string $app the id of the app registering the call * @param int $authlevel the level of authentication required for the call (See OC_API constants) + * @param array $defaults + * @param array $requirements */ - public static function register($method, $url, $action, $app, $authlevel = OC_API::USER_AUTH){ - \OC_API::register($method, $url, $action, $app, $authlevel); + public static function register($method, $url, $action, $app, $authlevel = OC_API::USER_AUTH, $defaults = array(), $requirements = array()){ + \OC_API::register($method, $url, $action, $app, $authlevel, $defaults, $requirements); } } From b07944798848bc5196dc75e8d8caea5ca71b0f15 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sun, 28 Oct 2012 11:06:47 +0000 Subject: [PATCH 085/330] Add API method for sharing a file, currently only via a link. --- apps/files_sharing/appinfo/app.php | 3 +- apps/files_sharing/appinfo/routes.php | 24 ++++++++++++++ apps/files_sharing/lib/api.php | 46 +++++++++++++++++++++++++++ lib/api.php | 2 +- 4 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 apps/files_sharing/appinfo/routes.php create mode 100644 apps/files_sharing/lib/api.php diff --git a/apps/files_sharing/appinfo/app.php b/apps/files_sharing/appinfo/app.php index 109f86b2e8..1402a14645 100644 --- a/apps/files_sharing/appinfo/app.php +++ b/apps/files_sharing/appinfo/app.php @@ -3,7 +3,8 @@ OC::$CLASSPATH['OC_Share_Backend_File'] = "apps/files_sharing/lib/share/file.php"; OC::$CLASSPATH['OC_Share_Backend_Folder'] = 'apps/files_sharing/lib/share/folder.php'; OC::$CLASSPATH['OC_Filestorage_Shared'] = "apps/files_sharing/lib/sharedstorage.php"; +OC::$CLASSPATH['OC_Sharing_API'] = "apps/files_sharing/lib/api.php"; OCP\Util::connectHook('OC_Filesystem', 'setup', 'OC_Filestorage_Shared', 'setup'); OCP\Share::registerBackend('file', 'OC_Share_Backend_File'); OCP\Share::registerBackend('folder', 'OC_Share_Backend_Folder', 'file'); -OCP\Util::addScript('files_sharing', 'share'); +OCP\Util::addScript('files_sharing', 'share'); \ No newline at end of file diff --git a/apps/files_sharing/appinfo/routes.php b/apps/files_sharing/appinfo/routes.php new file mode 100644 index 0000000000..d10607aa60 --- /dev/null +++ b/apps/files_sharing/appinfo/routes.php @@ -0,0 +1,24 @@ +. +* +*/ +OCP\API::register('post', '/cloud/files/share/{type}/{path}', array('OC_Sharing_API', 'shareFile'), 'files_sharing', OC_API::USER_AUTH, array(), array('type' => 'user|group|link|email|contact|remote', 'path' => '.*')); + +?> \ No newline at end of file diff --git a/apps/files_sharing/lib/api.php b/apps/files_sharing/lib/api.php new file mode 100644 index 0000000000..b1dc0d9e68 --- /dev/null +++ b/apps/files_sharing/lib/api.php @@ -0,0 +1,46 @@ + OCP\Share::SHARE_TYPE_USER, + 'group' => OCP\Share::SHARE_TYPE_GROUP, + 'link' => OCP\Share::SHARE_TYPE_LINK, + 'email' => OCP\Share::SHARE_TYPE_EMAIL, + 'contact' => OCP\Share::SHARE_TYPE_CONTACT, + 'remote' => OCP\Share::SHARE_TYPE_USER, + ); + $type = $typemap[$parameters['type']]; + $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : ''; + $permissionstring = isset($_POST['permissions']) ? $_POST['permissions'] : ''; + $permissionmap = array( + 'C' => OCP\Share::PERMISSION_CREATE, + 'R' => OCP\Share::PERMISSION_READ, + 'U' => OCP\Share::PERMISSION_UPDATE, + 'D' => OCP\Share::PERMISSION_DELETE, + 'S' => OCP\Share::PERMISSION_SHARE, + ); + $permissions = 0; + foreach($permissionmap as $letter => $permission) { + if(strpos($permissionstring, $letter) !== false) { + $permissions += $permission; + } + } + + try { + OCP\Share::shareItem('file', $fileid, $type, $shareWith, $permissions); + } catch (Exception $e){ + error_log($e->getMessage()); + } + switch($type){ + case OCP\Share::SHARE_TYPE_LINK: + return array('url' => OC_Helper::linkToPublic('files') . '&file=' . OC_User::getUser() . '/files' . $path); + break; + } + + } + +} \ No newline at end of file diff --git a/lib/api.php b/lib/api.php index 2940303023..d11c3799d9 100644 --- a/lib/api.php +++ b/lib/api.php @@ -91,7 +91,7 @@ class OC_API { // Loop through registered actions foreach(self::$actions[$name] as $action){ $app = $action['app']; - // Authorsie this call + // Authorise this call if(self::isAuthorised($action)){ if(is_callable($action['action'])){ $responses[] = array('app' => $app, 'response' => call_user_func($action['action'], $parameters)); From 6675a46679ca85d28b1122e832fd0e85d4eb4d15 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sun, 28 Oct 2012 15:03:21 +0000 Subject: [PATCH 086/330] Fix url generated for public shared files --- apps/files_sharing/lib/api.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/files_sharing/lib/api.php b/apps/files_sharing/lib/api.php index b1dc0d9e68..b450b359a4 100644 --- a/apps/files_sharing/lib/api.php +++ b/apps/files_sharing/lib/api.php @@ -14,7 +14,7 @@ class OC_Sharing_API { 'remote' => OCP\Share::SHARE_TYPE_USER, ); $type = $typemap[$parameters['type']]; - $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : ''; + $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null; $permissionstring = isset($_POST['permissions']) ? $_POST['permissions'] : ''; $permissionmap = array( 'C' => OCP\Share::PERMISSION_CREATE, @@ -37,7 +37,7 @@ class OC_Sharing_API { } switch($type){ case OCP\Share::SHARE_TYPE_LINK: - return array('url' => OC_Helper::linkToPublic('files') . '&file=' . OC_User::getUser() . '/files' . $path); + return array('url' => OC_Helper::linkToPublic('files') . '&file=/' . OC_User::getUser() . '/files' . $path); break; } From b2a1b54e9c24637032ea791da4da6e4d5914b5ba Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sun, 28 Oct 2012 23:59:22 +0000 Subject: [PATCH 087/330] Detect http protocol in providers.php --- ocs/providers.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ocs/providers.php b/ocs/providers.php index 4c68ded914..fa01deb9ad 100644 --- a/ocs/providers.php +++ b/ocs/providers.php @@ -23,7 +23,7 @@ require_once '../lib/base.php'; -$url='http://'.substr(OCP\Util::getServerHost().$_SERVER['REQUEST_URI'], 0, -17).'ocs/v1.php/'; +$url=OCP\Util::getServerProtocol().'://'.substr(OCP\Util::getServerHost().$_SERVER['REQUEST_URI'], 0, -17).'ocs/v1.php/'; echo(' From 43917e187b91d8b235c37fa873de306f83e61b36 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 31 Oct 2012 11:31:19 +0000 Subject: [PATCH 088/330] External Share API: Move url down one level in response --- apps/files_sharing/appinfo/routes.php | 1 - apps/files_sharing/lib/api.php | 3 ++- apps/files_sharing/tests/api.php | 13 +++++++++++++ apps2 | 1 + 4 files changed, 16 insertions(+), 2 deletions(-) create mode 100644 apps/files_sharing/tests/api.php create mode 160000 apps2 diff --git a/apps/files_sharing/appinfo/routes.php b/apps/files_sharing/appinfo/routes.php index d10607aa60..180dde635a 100644 --- a/apps/files_sharing/appinfo/routes.php +++ b/apps/files_sharing/appinfo/routes.php @@ -20,5 +20,4 @@ * */ OCP\API::register('post', '/cloud/files/share/{type}/{path}', array('OC_Sharing_API', 'shareFile'), 'files_sharing', OC_API::USER_AUTH, array(), array('type' => 'user|group|link|email|contact|remote', 'path' => '.*')); - ?> \ No newline at end of file diff --git a/apps/files_sharing/lib/api.php b/apps/files_sharing/lib/api.php index b450b359a4..151e6d6cfd 100644 --- a/apps/files_sharing/lib/api.php +++ b/apps/files_sharing/lib/api.php @@ -37,7 +37,8 @@ class OC_Sharing_API { } switch($type){ case OCP\Share::SHARE_TYPE_LINK: - return array('url' => OC_Helper::linkToPublic('files') . '&file=/' . OC_User::getUser() . '/files' . $path); + $link = OC_Helper::linkToPublic('files') . '&file=/' . OC_User::getUser() . '/files' . $path; + return array('link' => array('url' => $link)); break; } diff --git a/apps/files_sharing/tests/api.php b/apps/files_sharing/tests/api.php new file mode 100644 index 0000000000..65d4b87089 --- /dev/null +++ b/apps/files_sharing/tests/api.php @@ -0,0 +1,13 @@ + + * This file is licensed under the Affero General Public License version 3 or + * later. + * See the COPYING-README file. + */ + +class Test_Share_API extends UnitTestCase { + + function test + +} \ No newline at end of file diff --git a/apps2 b/apps2 new file mode 160000 index 0000000000..5108f1f8c2 --- /dev/null +++ b/apps2 @@ -0,0 +1 @@ +Subproject commit 5108f1f8c21117c164ca0627b22f322a5725154d From a0fe53d09adcb95b2b4edfd001346206f0a1bd8b Mon Sep 17 00:00:00 2001 From: Georg Ehrke Date: Thu, 29 Nov 2012 15:08:05 +0100 Subject: [PATCH 089/330] fix pattern for database names --- core/templates/installation.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/templates/installation.php b/core/templates/installation.php index 1e7983eae5..908e730106 100644 --- a/core/templates/installation.php +++ b/core/templates/installation.php @@ -111,7 +111,7 @@

- +

From b23c03c190b5159688f5da097a9b5eb86e113059 Mon Sep 17 00:00:00 2001 From: Thomas Tanghus Date: Mon, 3 Dec 2012 18:56:15 +0100 Subject: [PATCH 090/330] Enhanced multiSelect jquery plugin. --- core/css/multiselect.css | 25 ++++++-- core/js/multiselect.js | 134 +++++++++++++++++++++++++++++---------- 2 files changed, 122 insertions(+), 37 deletions(-) diff --git a/core/css/multiselect.css b/core/css/multiselect.css index 99f0e03933..8639577f0f 100644 --- a/core/css/multiselect.css +++ b/core/css/multiselect.css @@ -5,8 +5,6 @@ ul.multiselectoptions { background-color:#fff; border:1px solid #ddd; - border-bottom-left-radius:.5em; - border-bottom-right-radius:.5em; border-top:none; box-shadow:0 1px 1px #ddd; padding-top:.5em; @@ -14,6 +12,16 @@ z-index:49; } + ul.multiselectoptions.down { + border-bottom-left-radius:.5em; + border-bottom-right-radius:.5em; + } + + ul.multiselectoptions.up { + border-top-left-radius:.5em; + border-top-right-radius:.5em; + } + ul.multiselectoptions>li { overflow:hidden; white-space:nowrap; @@ -30,11 +38,20 @@ div.multiselect.active { background-color:#fff; + position:relative; + z-index:50; + } + + div.multiselect.up { + border-top:0 none; + border-top-left-radius:0; + border-top-right-radius:0; + } + + div.multiselect.down { border-bottom:none; border-bottom-left-radius:0; border-bottom-right-radius:0; - position:relative; - z-index:50; } div.multiselect>span:first-child { diff --git a/core/js/multiselect.js b/core/js/multiselect.js index c4fd74b047..bec9b5856c 100644 --- a/core/js/multiselect.js +++ b/core/js/multiselect.js @@ -1,3 +1,13 @@ +/** + * @param 'createCallback' A function to be called when a new entry is created. Only argument to the function is the value of the option. + * @param 'createText' The placeholder text for the create action. + * @param 'title' The title to show if no options are selected. + * @param 'checked' An array containing values for options that should be checked. Any options which are already selected will be added to this array. + * @param 'labels' The corresponding labels to show for the checked items. + * @param 'oncheck' Callback function which will be called when a checkbox/radiobutton is selected. If the function returns false the input will be unchecked. + * @param 'onuncheck' @see 'oncheck'. + * @param 'singleSelect' If true radiobuttons will be used instead of checkboxes. + */ (function( $ ){ var multiSelectId=-1; $.fn.multiSelect=function(options){ @@ -5,16 +15,25 @@ var settings = { 'createCallback':false, 'createText':false, + 'singleSelect':false, 'title':this.attr('title'), 'checked':[], + 'labels':[], 'oncheck':false, 'onuncheck':false, 'minWidth': 'default;', }; $.extend(settings,options); $.each(this.children(),function(i,option){ - if($(option).attr('selected') && settings.checked.indexOf($(option).val())==-1){ + // If the option is selected, but not in the checked array, add it. + if($(option).attr('selected') && settings.checked.indexOf($(option).val()) == -1){ settings.checked.push($(option).val()); + settings.labels.push($(option).text().trim()); + } + // If the option is in the checked array but not selected, select it. + else if(settings.checked.indexOf($(option).val()) !== -1 && !$(option).attr('selected')){ + $(option).attr('selected', 'selected'); + settings.labels.push($(option).text().trim()); } }); var button=$('
'+settings.title+'
'); @@ -30,18 +49,31 @@ button.css('min-width',settings.minWidth); settings.minOuterWidth=button.outerWidth()-2; button.data('settings',settings); - if(settings.checked.length>0){ - button.children('span').first().text(settings.checked.join(', ')); + + if(!settings.singleSelect && settings.checked.length>0){ + //button.children('span').first().text(settings.checked.join(', ')); + button.children('span').first().text(settings.labels.join(', ')); + } else if(settings.singleSelect) { + button.children('span').first().text(this.find(':selected').text()); } + var self = this; + self.menuDirection = 'down'; button.click(function(event){ var button=$(this); if(button.parent().children('ul').length>0){ - button.parent().children('ul').slideUp(400,function(){ - button.parent().children('ul').remove(); - button.removeClass('active'); - }); + if(self.menuDirection === 'down') { + button.parent().children('ul').slideUp(400,function(){ + button.parent().children('ul').remove(); + button.removeClass('active'); + }); + } else { + button.parent().children('ul').fadeOut(400,function(){ + button.parent().children('ul').remove(); + button.removeClass('active').removeClass('up'); + }); + } return; } var lists=$('ul.multiselectoptions'); @@ -54,15 +86,19 @@ event.stopPropagation(); var options=$(this).parent().next().children(); var list=$('
    ').hide().appendTo($(this).parent()); + var inputType = settings.singleSelect ? 'radio' : 'checkbox'; function createItem(element,checked){ element=$(element); var item=element.val(); var id='ms'+multiSelectId+'-option-'+item; - var input=$(''); + var input=$(''); input.attr('id',id); + if(settings.singleSelect) { + input.attr('name', 'ms'+multiSelectId+'-option'); + } var label=$('