From 4eeb9c5b9944368611447530ef17007f9e4a9cce Mon Sep 17 00:00:00 2001
From: Michael Gapczynski
Date: Sat, 7 Jul 2012 11:30:48 -0400
Subject: [PATCH 001/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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:
+
+Disallow
+Allow
\ 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/183] 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:
-
-Disallow
-Allow
\ No newline at end of file
+
+
is requesting permission to read, write, modify and delete data from the following apps:
+
+
Allow
+
Disallow
+
From cbc0f0c1c5c5ad9ecc1b20c0f0aee7b4ea564579 Mon Sep 17 00:00:00 2001
From: Tom Needham
Date: Mon, 30 Jul 2012 10:51:48 +0000
Subject: [PATCH 010/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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.
+ */
+?>
+
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
+
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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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/183] 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 @@
t( 'Database name' ); ?>
-
+
From 115dbc721d77509274e7a1bacf0239ada565b005 Mon Sep 17 00:00:00 2001
From: Tom Needham
Date: Tue, 11 Dec 2012 22:36:46 +0000
Subject: [PATCH 090/183] API: Specify the response format using a GET
parameter
---
lib/api.php | 14 +++++---------
1 file changed, 5 insertions(+), 9 deletions(-)
diff --git a/lib/api.php b/lib/api.php
index d11c3799d9..cc1d9fccaf 100644
--- a/lib/api.php
+++ b/lib/api.php
@@ -66,10 +66,8 @@ class OC_API {
$name = str_replace(array('/', '{', '}'), '_', $name);
if(!isset(self::$actions[$name])){
OC::getRouter()->useCollection('ocs');
- OC::getRouter()->create($name, $url.'.{_format}')
+ OC::getRouter()->create($name, $url)
->method($method)
- ->defaults(array('_format' => 'xml') + $defaults)
- ->requirements(array('_format' => 'xml|json') + $requirements)
->action('OC_API', 'call');
self::$actions[$name] = array();
}
@@ -106,11 +104,9 @@ class OC_API {
// Merge the responses
$response = self::mergeResponses($responses);
// Send the response
- if(isset($parameters['_format'])){
- self::respond($response, $parameters['_format']);
- } else {
- self::respond($response);
- }
+ $formats = array('json', 'xml');
+ $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
+ self::respond($response, $format);
// logout the user to be stateless
OC_User::logout();
}
@@ -218,7 +214,7 @@ class OC_API {
* @param int|array $response the response
* @param string $format the format xml|json
*/
- private static function respond($response, $format='json'){
+ private static function respond($response, $format='xml'){
if ($format == 'json') {
OC_JSON::encodedPrint($response);
} else if ($format == 'xml') {
From 140141edf2c5d89f083b4d254c0533e0209d517b Mon Sep 17 00:00:00 2001
From: Tom Needham
Date: Wed, 12 Dec 2012 16:50:25 +0000
Subject: [PATCH 091/183] API: Further tidying, implement OC_OCS_Result object
for api results.
---
lib/api.php | 69 ++++++----------------------------------------
lib/ocs/result.php | 65 +++++++++++++++++++++++++++++++++++++++++++
2 files changed, 74 insertions(+), 60 deletions(-)
create mode 100644 lib/ocs/result.php
diff --git a/lib/api.php b/lib/api.php
index cc1d9fccaf..e119b87821 100644
--- a/lib/api.php
+++ b/lib/api.php
@@ -71,7 +71,7 @@ class OC_API {
->action('OC_API', 'call');
self::$actions[$name] = array();
}
- self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authlevel);
+ self::$actions[$name] = array('app' => $app, 'action' => $action, 'authlevel' => $authlevel);
}
/**
@@ -87,22 +87,11 @@ class OC_API {
}
$name = $parameters['_route'];
// Loop through registered actions
- foreach(self::$actions[$name] as $action){
- $app = $action['app'];
- // Authorise this call
- if(self::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);
- }
-
- }
- // Merge the responses
- $response = self::mergeResponses($responses);
+ if(is_callable(self::$actions[$name]['action'])){
+ $response = call_user_func(self::$actions[$name]['action'], $parameters);
+ } else {
+ $response = new OC_OCS_Result(null, 998, 'Internal server error.');
+ }
// Send the response
$formats = array('json', 'xml');
$format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
@@ -168,53 +157,13 @@ class OC_API {
return OC_User::login($authuser, $authpw) ? $authuser : false;
}
- /**
- * intelligently merges the different responses
- * @param array $responses
- * @return array the final merged response
- */
- private static function mergeResponses($responses){
- $finalresponse = array(
- 'meta' => array(
- 'statuscode' => '',
- ),
- 'data' => array(),
- );
- $numresponses = count($responses);
-
- foreach($responses as $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['data'] = array_merge_recursive($finalresponse['data'], $response['response']);
- } else {
- $finalresponse['data'] = array_merge_recursive($response['response'], $finalresponse['data']);
- }
- $finalresponse['meta']['statuscode'] = 100;
- }
- }
- //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);
- }
-
/**
* respond to a call
- * @param int|array $response the response
+ * @param int|array $result the result from the api method
* @param string $format the format xml|json
*/
- private static function respond($response, $format='xml'){
+ private static function respond($result, $format='xml'){
+ $response = array('ocs' => $result->getResult());
if ($format == 'json') {
OC_JSON::encodedPrint($response);
} else if ($format == 'xml') {
diff --git a/lib/ocs/result.php b/lib/ocs/result.php
new file mode 100644
index 0000000000..a7199cb5ac
--- /dev/null
+++ b/lib/ocs/result.php
@@ -0,0 +1,65 @@
+data = $data;
+ $this->statuscode = $code;
+ $this->message = $message;
+ }
+
+ /**
+ * sets the statuscode
+ * @param $code int
+ */
+ public function setCode(int $code){
+ $this->statuscode = $code;
+ }
+
+ /**
+ * optionally set the total number of items available
+ * @param $items int
+ */
+ public function setItems(int $items){
+ $this->items = $items;
+ }
+
+ /**
+ * optionally set the the number of items per page
+ * @param $items int
+ */
+ public function setItemsPerPage(int $items){
+ $this->perpage = $items;
+ }
+
+ /**
+ * set a custom message for the response
+ * @param $message string the message
+ */
+ public function setMessage(string $message){
+ $this->message = $message;
+ }
+
+ /**
+ * returns the data associated with the api result
+ * @return array
+ */
+ public function getResult(){
+ $return = array();
+ $return['meta'] = array();
+ $return['meta']['status'] = ($this->statuscode === 100) ? 'ok' : 'failure';
+ $return['meta']['statuscode'] = $this->statuscode;
+ $return['meta']['message'] = $this->message;
+ $return['data'] = $this->data;
+ // Return the result data.
+ return $return;
+ }
+
+
+}
\ No newline at end of file
From 2a4b554ca67ba55c75bbff75777285e550dca84f Mon Sep 17 00:00:00 2001
From: Tom Needham
Date: Wed, 12 Dec 2012 17:35:58 +0000
Subject: [PATCH 092/183] API: OCS methods now use OC_OCS_Result to return data
---
lib/ocs/cloud.php | 4 ++--
lib/ocs/config.php | 2 +-
lib/ocs/person.php | 6 +++---
lib/ocs/privatedata.php | 8 ++++----
4 files changed, 10 insertions(+), 10 deletions(-)
diff --git a/lib/ocs/cloud.php b/lib/ocs/cloud.php
index 2f2aad714a..720cc0ade3 100644
--- a/lib/ocs/cloud.php
+++ b/lib/ocs/cloud.php
@@ -13,7 +13,7 @@ class OC_OCS_Cloud {
$values[] = $newvalue;
}
}
- return $values;
+ return new OC_OCS_Result($values);
}
public static function getUserQuota($parameters){
@@ -39,7 +39,7 @@ class OC_OCS_Cloud {
$xml['used']=$used;
$xml['relative']=$relative;
- return $xml;
+ return new OC_OCS_Result($xml);
}else{
return 300;
}
diff --git a/lib/ocs/config.php b/lib/ocs/config.php
index 06103cbeb4..eb9e470381 100644
--- a/lib/ocs/config.php
+++ b/lib/ocs/config.php
@@ -8,6 +8,6 @@ class OC_OCS_Config {
$xml['host'] = OCP\Util::getServerHost();
$xml['contact'] = '';
$xml['ssl'] = 'false';
- return $xml;
+ return new OC_OCS_Result($xml);
}
}
diff --git a/lib/ocs/person.php b/lib/ocs/person.php
index 23b8853533..b5f07d88ae 100644
--- a/lib/ocs/person.php
+++ b/lib/ocs/person.php
@@ -8,12 +8,12 @@ class OC_OCS_Person {
if($login && $password){
if(OC_User::checkPassword($login,$password)){
$xml['person']['personid'] = $login;
- return $xml;
+ return new OC_OCS_Result($xml);
}else{
- return 102;
+ return new OC_OCS_Result(null, 102);
}
}else{
- return 101;
+ return new OC_OCS_Result(null, 101);
}
}
diff --git a/lib/ocs/privatedata.php b/lib/ocs/privatedata.php
index 1c781dece8..02ca31f2d2 100644
--- a/lib/ocs/privatedata.php
+++ b/lib/ocs/privatedata.php
@@ -14,7 +14,7 @@ class OC_OCS_Privatedata {
$xml[$i]['app']=$log['app'];
$xml[$i]['value']=$log['value'];
}
- return $xml;
+ return new OC_OCS_Result($xml);
//TODO: replace 'privatedata' with 'attribute' once a new libattice has been released that works with it
}
@@ -25,7 +25,7 @@ class OC_OCS_Privatedata {
$key = addslashes(strip_tags($parameters['key']));
$value = OC_OCS::readData('post', 'value', 'text');
if(OC_OCS::setData($user,$app,$key,$value)){
- return 100;
+ return new OC_OCS_Result(null, 100);
}
}
@@ -35,10 +35,10 @@ class OC_OCS_Privatedata {
$app = addslashes(strip_tags($parameters['app']));
$key = addslashes(strip_tags($parameters['key']));
if($key=="" or $app==""){
- return; //key and app are NOT optional here
+ return new OC_OCS_Result(null, 101); //key and app are NOT optional here
}
if(OC_OCS::deleteData($user,$app,$key)){
- return 100;
+ return new OC_OCS_Result(null, 100);
}
}
}
From 3cc34055368114d81e722adea03a2118e78d2aac Mon Sep 17 00:00:00 2001
From: Tom Needham
Date: Wed, 12 Dec 2012 18:06:07 +0000
Subject: [PATCH 093/183] API: Remove old code. Move remaining methods to
OC_OCS_Result.
---
lib/ocs.php | 290 ----------------------------------------
lib/ocs/cloud.php | 32 +----
lib/ocs/config.php | 1 +
lib/ocs/privatedata.php | 6 +-
ocs/routes.php | 8 +-
5 files changed, 17 insertions(+), 320 deletions(-)
diff --git a/lib/ocs.php b/lib/ocs.php
index 1cec3ecc7c..001965d45e 100644
--- a/lib/ocs.php
+++ b/lib/ocs.php
@@ -103,44 +103,6 @@ class OC_OCS {
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='';
-
- 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);
- }
-
/**
* generates the xml or json response for the API call from an multidimenional data array.
@@ -261,130 +223,6 @@ class OC_OCS {
}
}
- /**
- * return the config data of this server
- * @param string $format
- * @return string xml/json
- */
- public static function apiConfig($parameters) {
- $format = $parameters['format'];
- $user=OC_OCS::checkpassword(false);
- $url=substr(OCP\Util::getServerHost().$_SERVER['SCRIPT_NAME'], 0, -11).'';
-
- $xml['version']='1.7';
- $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'));
- }
- }
-
- // 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
-
- $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'activity', 'full', 2, $totalcount,$pagesize);
- echo($txt);
- }
-
- /**
- * 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, ''));
- }
-
- // 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);
- }
-
- /**
- * 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)) {
- echo(OC_OCS::generatexml($format, 'ok', 100, ''));
- }
- }
-
- /**
- * delete private data referenced by $key and generate the xml for ocs
- * @param string $format
- * @param string $app
- * @param string $key
- * @return string xml/json
- */
- private static function privateDataDelete($format, $app, $key) {
- if($key=="" or $app=="") {
- return; //key and app are NOT optional here
- }
- $user=OC_OCS::checkpassword();
- if(OC_OCS::deleteData($user, $app, $key)) {
- echo(OC_OCS::generatexml($format, 'ok', 100, ''));
- }
- }
-
/**
* get private data
* @param string $user
@@ -416,93 +254,6 @@ class OC_OCS {
return $result;
}
- /**
- * set private data referenced by $key to $value
- * @param string $user
- * @param string $app
- * @param string $key
- * @param string $value
- * @return bool
- */
- public static function setData($user, $app, $key, $value) {
- return OC_Preferences::setValue($user, $app, $key, $value);
- }
-
- /**
- * delete private data referenced by $key
- * @param string $user
- * @param string $app
- * @param string $key
- * @return string xml/json
- */
- public static function deleteData($user, $app, $key) {
- return OC_Preferences::deleteKey($user, $app, $key);
- }
-
-
- // CLOUD API #############################################
-
- /**
- * get a list of installed web apps
- * @param string $format
- * @return string xml/json
- */
- private static function systemWebApps($format) {
- $login=OC_OCS::checkpassword();
- $apps=OC_App::getEnabledApps();
- $values=array();
- foreach($apps as $app) {
- $info=OC_App::getAppInfo($app);
- if(isset($info['standalone'])) {
- $newvalue=array('name'=>$info['name'],'url'=>OC_Helper::linkToAbsolute($app,''),'icon'=>'');
- $values[]=$newvalue;
- }
-
- }
- $txt=OC_OCS::generatexml($format, 'ok', 100, '', $values, 'cloud', '', 2, 0, 0);
- echo($txt);
-
- }
-
-
- /**
- * get the quota of a user
- * @param string $format
- * @param string $user
- * @return string xml/json
- */
- private static function quotaGet($format,$user) {
- $login=OC_OCS::checkpassword();
- if(OC_Group::inGroup($login, 'admin') or ($login==$user)) {
-
- if(OC_User::userExists($user)) {
- // calculate the disc space
- $user_dir = '/'.$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;
-
- $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'cloud', '', 1, 0, 0);
- 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.');
- }
- }
-
/**
* set the quota of a user
* @param string $format
@@ -527,45 +278,4 @@ class OC_OCS {
}
}
- /**
- * get the public key of a user
- * @param string $format
- * @param string $user
- * @return string xml/json
- */
- private static function publicKeyGet($format,$user) {
- $login=OC_OCS::checkpassword();
-
- if(OC_User::userExists($user)) {
- // calculate the disc space
- $txt='this is the public key of '.$user;
- echo($txt);
- }else{
- echo self::generateXml('', 'fail', 300, 'User does not exist');
- }
- }
-
- /**
- * get the private key of a user
- * @param string $format
- * @param string $user
- * @return string xml/json
- */
- private static function privateKeyGet($format,$user) {
- $login=OC_OCS::checkpassword();
- if(OC_Group::inGroup($login, 'admin') or ($login==$user)) {
-
- if(OC_User::userExists($user)) {
- // calculate the disc space
- $txt='this is the private key of '.$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.');
- }
- }
-
-
}
diff --git a/lib/ocs/cloud.php b/lib/ocs/cloud.php
index 720cc0ade3..b5cfbc295e 100644
--- a/lib/ocs/cloud.php
+++ b/lib/ocs/cloud.php
@@ -17,7 +17,6 @@ class OC_OCS_Cloud {
}
public static function getUserQuota($parameters){
- OC_Util::checkLoggedIn();
$user = OC_User::getUser();
if(OC_Group::inGroup($user, 'admin') or ($user==$parameters['user'])) {
@@ -41,44 +40,25 @@ class OC_OCS_Cloud {
return new OC_OCS_Result($xml);
}else{
- return 300;
+ return new OC_OCS_Result(null, 300);
}
}else{
- return 300;
- }
- }
-
- public static function setUserQuota($parameters){
- OC_Util::checkLoggedIn();
- $user = OC_User::getUser();
- if(OC_Group::inGroup($user, '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;
+ return new OC_OCS_Result(null, 300);
}
}
public static function getUserPublickey($parameters){
- OC_Util::checkLoggedIn();
if(OC_User::userExists($parameters['user'])){
// calculate the disc space
// TODO
- return array();
+ return new OC_OCS_Result(array());
}else{
- return 300;
+ return new OC_OCS_Result(null, 300);
}
}
public static function getUserPrivatekey($parameters){
- OC_Util::checkLoggedIn();
$user = OC_User::getUser();
if(OC_Group::inGroup($user, 'admin') or ($user==$parameters['user'])) {
@@ -87,10 +67,10 @@ class OC_OCS_Cloud {
$txt='this is the private key of '.$parameters['user'];
echo($txt);
}else{
- echo self::generateXml('', 'fail', 300, 'User does not exist');
+ return new OC_OCS_Result(null, 300, 'User does not exist');
}
}else{
- echo self::generateXml('', 'fail', 300, 'You don´t have permission to access this ressource.');
+ return new OC_OCS_Result('null', 300, 'You don´t have permission to access this ressource.');
}
}
}
diff --git a/lib/ocs/config.php b/lib/ocs/config.php
index eb9e470381..52affcd65e 100644
--- a/lib/ocs/config.php
+++ b/lib/ocs/config.php
@@ -10,4 +10,5 @@ class OC_OCS_Config {
$xml['ssl'] = 'false';
return new OC_OCS_Result($xml);
}
+
}
diff --git a/lib/ocs/privatedata.php b/lib/ocs/privatedata.php
index 02ca31f2d2..09d636bd73 100644
--- a/lib/ocs/privatedata.php
+++ b/lib/ocs/privatedata.php
@@ -8,7 +8,7 @@ class OC_OCS_Privatedata {
$app = addslashes(strip_tags($parameters['app']));
$key = addslashes(strip_tags($parameters['key']));
$result = OC_OCS::getData($user,$app,$key);
- $xml= array();
+ $xml = array();
foreach($result as $i=>$log) {
$xml[$i]['key']=$log['key'];
$xml[$i]['app']=$log['app'];
@@ -24,7 +24,7 @@ class OC_OCS_Privatedata {
$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)){
+ if(OC_Preferences::setValue($user,$app,$key,$value)){
return new OC_OCS_Result(null, 100);
}
}
@@ -37,7 +37,7 @@ class OC_OCS_Privatedata {
if($key=="" or $app==""){
return new OC_OCS_Result(null, 101); //key and app are NOT optional here
}
- if(OC_OCS::deleteData($user,$app,$key)){
+ if(OC_Preferences::deleteKey($user,$app,$key)){
return new OC_OCS_Result(null, 100);
}
}
diff --git a/ocs/routes.php b/ocs/routes.php
index 6b01abe31f..033d9b79df 100644
--- a/ocs/routes.php
+++ b/ocs/routes.php
@@ -10,7 +10,13 @@ OC_API::register('get', '/config', array('OC_OCS_Config', 'apiConfig'), 'ocs', O
// Person
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::USER_AUTH);
+OC_API::register('get', '/activity', array('OC_OCS_Activity', 'activityGet'), 'ocs', OC_API::USER_AUTH);
+
+
+//activity put, keygetpublic, keygetprivate
+
+
+
// Privatedata
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' => ''));
From 228a75ebaa3a8fd543ea473bc23ba0b11a028511 Mon Sep 17 00:00:00 2001
From: Tom Needham
Date: Wed, 12 Dec 2012 20:58:40 +0000
Subject: [PATCH 094/183] API: Include totalitems and itemsperpage meta data
when needed.
---
lib/ocs/result.php | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/lib/ocs/result.php b/lib/ocs/result.php
index a7199cb5ac..24029051da 100644
--- a/lib/ocs/result.php
+++ b/lib/ocs/result.php
@@ -26,7 +26,7 @@ class OC_OCS_Result{
* optionally set the total number of items available
* @param $items int
*/
- public function setItems(int $items){
+ public function setTotalItems(int $items){
$this->items = $items;
}
@@ -56,6 +56,12 @@ class OC_OCS_Result{
$return['meta']['status'] = ($this->statuscode === 100) ? 'ok' : 'failure';
$return['meta']['statuscode'] = $this->statuscode;
$return['meta']['message'] = $this->message;
+ if(isset($this->items)){
+ $return['meta']['totalitems'] = $this->items;
+ }
+ if(isset($this->perpage)){
+ $return['meta']['itemsperpage'] = $this->perpage;
+ }
$return['data'] = $this->data;
// Return the result data.
return $return;
From 1475ff63ddeb56c277836092d2b02861cb47e4ee Mon Sep 17 00:00:00 2001
From: Tom Needham
Date: Wed, 12 Dec 2012 21:04:23 +0000
Subject: [PATCH 095/183] API: Add check to see if the user is authorised to
run the api method
---
lib/api.php | 14 +++++++++-----
1 file changed, 9 insertions(+), 5 deletions(-)
diff --git a/lib/api.php b/lib/api.php
index e119b87821..84d1155b59 100644
--- a/lib/api.php
+++ b/lib/api.php
@@ -86,12 +86,16 @@ class OC_API {
parse_str(file_get_contents("php://input"), $_DELETE);
}
$name = $parameters['_route'];
- // Loop through registered actions
- if(is_callable(self::$actions[$name]['action'])){
- $response = call_user_func(self::$actions[$name]['action'], $parameters);
+ // Check authentication and availability
+ if(self::isAuthorised(self::$actions[$name])){
+ if(is_callable(self::$actions[$name]['action'])){
+ $response = call_user_func(self::$actions[$name]['action'], $parameters);
+ } else {
+ $response = new OC_OCS_Result(null, 998, 'Internal server error');
+ }
} else {
- $response = new OC_OCS_Result(null, 998, 'Internal server error.');
- }
+ $response = new OC_OCS_Result(null, 997, 'Unauthorised');
+ }
// Send the response
$formats = array('json', 'xml');
$format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
From c7a665a1e460811c76abe4bb69111c72812c4b79 Mon Sep 17 00:00:00 2001
From: Tom Needham
Date: Fri, 14 Dec 2012 14:55:02 +0000
Subject: [PATCH 096/183] API: Tidy up routes.php, remove redundant call
registration
---
ocs/routes.php | 9 ---------
1 file changed, 9 deletions(-)
diff --git a/ocs/routes.php b/ocs/routes.php
index 033d9b79df..d77b96fc14 100644
--- a/ocs/routes.php
+++ b/ocs/routes.php
@@ -11,19 +11,10 @@ OC_API::register('get', '/config', array('OC_OCS_Config', 'apiConfig'), 'ocs', O
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::USER_AUTH);
-
-
-//activity put, keygetpublic, keygetprivate
-
-
-
// Privatedata
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::ADMIN_AUTH);
-
?>
From 4facd766e3712d4c714f2e1bf2ad4be41461a7cc Mon Sep 17 00:00:00 2001
From: Tom Needham
Date: Fri, 14 Dec 2012 14:58:31 +0000
Subject: [PATCH 097/183] Remove 3rdparty repo from ocs_api branch
---
3rdparty/Archive/Tar.php | 1973 -------
3rdparty/Console/Getopt.php | 251 -
3rdparty/Crypt_Blowfish/Blowfish.php | 317 -
.../Crypt_Blowfish/Blowfish/DefaultKey.php | 327 --
3rdparty/Dropbox/API.php | 380 --
3rdparty/Dropbox/Exception.php | 15 -
3rdparty/Dropbox/Exception/Forbidden.php | 18 -
3rdparty/Dropbox/Exception/NotFound.php | 20 -
3rdparty/Dropbox/Exception/OverQuota.php | 20 -
3rdparty/Dropbox/Exception/RequestToken.php | 18 -
3rdparty/Dropbox/LICENSE.txt | 19 -
3rdparty/Dropbox/OAuth.php | 151 -
3rdparty/Dropbox/OAuth/Consumer/Dropbox.php | 37 -
3rdparty/Dropbox/OAuth/Curl.php | 282 -
3rdparty/Dropbox/README.md | 31 -
3rdparty/Dropbox/autoload.php | 29 -
3rdparty/Google/LICENSE.txt | 21 -
3rdparty/Google/OAuth.php | 751 ---
3rdparty/Google/common.inc.php | 185 -
3rdparty/MDB2.php | 4587 ---------------
3rdparty/MDB2/Date.php | 183 -
3rdparty/MDB2/Driver/Datatype/Common.php | 1842 ------
3rdparty/MDB2/Driver/Datatype/mysql.php | 602 --
3rdparty/MDB2/Driver/Datatype/oci8.php | 499 --
3rdparty/MDB2/Driver/Datatype/pgsql.php | 579 --
3rdparty/MDB2/Driver/Datatype/sqlite.php | 418 --
3rdparty/MDB2/Driver/Function/Common.php | 293 -
3rdparty/MDB2/Driver/Function/mysql.php | 136 -
3rdparty/MDB2/Driver/Function/oci8.php | 187 -
3rdparty/MDB2/Driver/Function/pgsql.php | 132 -
3rdparty/MDB2/Driver/Function/sqlite.php | 162 -
3rdparty/MDB2/Driver/Manager/Common.php | 1038 ----
3rdparty/MDB2/Driver/Manager/mysql.php | 1471 -----
3rdparty/MDB2/Driver/Manager/oci8.php | 1340 -----
3rdparty/MDB2/Driver/Manager/pgsql.php | 990 ----
3rdparty/MDB2/Driver/Manager/sqlite.php | 1390 -----
3rdparty/MDB2/Driver/Native/Common.php | 61 -
3rdparty/MDB2/Driver/Native/mysql.php | 60 -
3rdparty/MDB2/Driver/Native/oci8.php | 60 -
3rdparty/MDB2/Driver/Native/pgsql.php | 88 -
3rdparty/MDB2/Driver/Native/sqlite.php | 60 -
3rdparty/MDB2/Driver/Reverse/Common.php | 517 --
3rdparty/MDB2/Driver/Reverse/mysql.php | 546 --
3rdparty/MDB2/Driver/Reverse/oci8.php | 625 --
3rdparty/MDB2/Driver/Reverse/pgsql.php | 574 --
3rdparty/MDB2/Driver/Reverse/sqlite.php | 611 --
3rdparty/MDB2/Driver/mysql.php | 1729 ------
3rdparty/MDB2/Driver/oci8.php | 1700 ------
3rdparty/MDB2/Driver/pgsql.php | 1583 -----
3rdparty/MDB2/Driver/sqlite.php | 1104 ----
3rdparty/MDB2/Extended.php | 723 ---
3rdparty/MDB2/Iterator.php | 262 -
3rdparty/MDB2/LOB.php | 264 -
3rdparty/MDB2/Schema.php | 2797 ---------
3rdparty/MDB2/Schema/Parser.php | 876 ---
3rdparty/MDB2/Schema/Parser2.php | 802 ---
3rdparty/MDB2/Schema/Reserved/ibase.php | 437 --
3rdparty/MDB2/Schema/Reserved/mssql.php | 260 -
3rdparty/MDB2/Schema/Reserved/mysql.php | 285 -
3rdparty/MDB2/Schema/Reserved/oci8.php | 173 -
3rdparty/MDB2/Schema/Reserved/pgsql.php | 148 -
3rdparty/MDB2/Schema/Tool.php | 583 --
.../MDB2/Schema/Tool/ParameterException.php | 61 -
3rdparty/MDB2/Schema/Validate.php | 1004 ----
3rdparty/MDB2/Schema/Writer.php | 586 --
3rdparty/OAuth/LICENSE.TXT | 21 -
3rdparty/OAuth/OAuth.php | 895 ---
3rdparty/OS/Guess.php | 338 --
3rdparty/PEAR-LICENSE | 27 -
3rdparty/PEAR.php | 1063 ----
3rdparty/PEAR/Autoloader.php | 218 -
3rdparty/PEAR/Builder.php | 489 --
3rdparty/PEAR/ChannelFile.php | 1559 -----
3rdparty/PEAR/ChannelFile/Parser.php | 68 -
3rdparty/PEAR/Command.php | 414 --
3rdparty/PEAR/Command/Auth.php | 81 -
3rdparty/PEAR/Command/Auth.xml | 30 -
3rdparty/PEAR/Command/Build.php | 85 -
3rdparty/PEAR/Command/Build.xml | 10 -
3rdparty/PEAR/Command/Channels.php | 883 ---
3rdparty/PEAR/Command/Channels.xml | 123 -
3rdparty/PEAR/Command/Common.php | 273 -
3rdparty/PEAR/Command/Config.php | 414 --
3rdparty/PEAR/Command/Config.xml | 92 -
3rdparty/PEAR/Command/Install.php | 1268 ----
3rdparty/PEAR/Command/Install.xml | 276 -
3rdparty/PEAR/Command/Mirror.php | 139 -
3rdparty/PEAR/Command/Mirror.xml | 18 -
3rdparty/PEAR/Command/Package.php | 1124 ----
3rdparty/PEAR/Command/Package.xml | 237 -
3rdparty/PEAR/Command/Pickle.php | 421 --
3rdparty/PEAR/Command/Pickle.xml | 36 -
3rdparty/PEAR/Command/Registry.php | 1145 ----
3rdparty/PEAR/Command/Registry.xml | 58 -
3rdparty/PEAR/Command/Remote.php | 810 ---
3rdparty/PEAR/Command/Remote.xml | 109 -
3rdparty/PEAR/Command/Test.php | 337 --
3rdparty/PEAR/Command/Test.xml | 54 -
3rdparty/PEAR/Common.php | 837 ---
3rdparty/PEAR/Config.php | 2097 -------
3rdparty/PEAR/Dependency.php | 487 --
3rdparty/PEAR/Dependency2.php | 1358 -----
3rdparty/PEAR/DependencyDB.php | 769 ---
3rdparty/PEAR/Downloader.php | 1766 ------
3rdparty/PEAR/Downloader/Package.php | 1988 -------
3rdparty/PEAR/ErrorStack.php | 985 ----
3rdparty/PEAR/Exception.php | 389 --
3rdparty/PEAR/FixPHP5PEARWarnings.php | 7 -
3rdparty/PEAR/Frontend.php | 228 -
3rdparty/PEAR/Frontend/CLI.php | 751 ---
3rdparty/PEAR/Installer.php | 1823 ------
3rdparty/PEAR/Installer/Role.php | 276 -
3rdparty/PEAR/Installer/Role/Cfg.php | 106 -
3rdparty/PEAR/Installer/Role/Cfg.xml | 15 -
3rdparty/PEAR/Installer/Role/Common.php | 174 -
3rdparty/PEAR/Installer/Role/Data.php | 28 -
3rdparty/PEAR/Installer/Role/Data.xml | 15 -
3rdparty/PEAR/Installer/Role/Doc.php | 28 -
3rdparty/PEAR/Installer/Role/Doc.xml | 15 -
3rdparty/PEAR/Installer/Role/Ext.php | 28 -
3rdparty/PEAR/Installer/Role/Ext.xml | 12 -
3rdparty/PEAR/Installer/Role/Php.php | 28 -
3rdparty/PEAR/Installer/Role/Php.xml | 15 -
3rdparty/PEAR/Installer/Role/Script.php | 28 -
3rdparty/PEAR/Installer/Role/Script.xml | 15 -
3rdparty/PEAR/Installer/Role/Src.php | 34 -
3rdparty/PEAR/Installer/Role/Src.xml | 12 -
3rdparty/PEAR/Installer/Role/Test.php | 28 -
3rdparty/PEAR/Installer/Role/Test.xml | 15 -
3rdparty/PEAR/Installer/Role/Www.php | 28 -
3rdparty/PEAR/Installer/Role/Www.xml | 15 -
3rdparty/PEAR/PackageFile.php | 492 --
3rdparty/PEAR/PackageFile/Generator/v1.php | 1284 ----
3rdparty/PEAR/PackageFile/Generator/v2.php | 893 ---
3rdparty/PEAR/PackageFile/Parser/v1.php | 459 --
3rdparty/PEAR/PackageFile/Parser/v2.php | 113 -
3rdparty/PEAR/PackageFile/v1.php | 1612 -----
3rdparty/PEAR/PackageFile/v2.php | 2049 -------
3rdparty/PEAR/PackageFile/v2/Validator.php | 2154 -------
3rdparty/PEAR/PackageFile/v2/rw.php | 1604 -----
3rdparty/PEAR/Packager.php | 201 -
3rdparty/PEAR/REST.php | 483 --
3rdparty/PEAR/REST/10.php | 871 ---
3rdparty/PEAR/REST/11.php | 341 --
3rdparty/PEAR/REST/13.php | 299 -
3rdparty/PEAR/Registry.php | 2395 --------
3rdparty/PEAR/Remote.php | 394 --
3rdparty/PEAR/RunTest.php | 968 ---
3rdparty/PEAR/Task/Common.php | 202 -
3rdparty/PEAR/Task/Postinstallscript.php | 323 -
3rdparty/PEAR/Task/Postinstallscript/rw.php | 169 -
3rdparty/PEAR/Task/Replace.php | 176 -
3rdparty/PEAR/Task/Replace/rw.php | 61 -
3rdparty/PEAR/Task/Unixeol.php | 77 -
3rdparty/PEAR/Task/Unixeol/rw.php | 56 -
3rdparty/PEAR/Task/Windowseol.php | 77 -
3rdparty/PEAR/Task/Windowseol/rw.php | 56 -
3rdparty/PEAR/Validate.php | 629 --
3rdparty/PEAR/Validator/PECL.php | 63 -
3rdparty/PEAR/XMLParser.php | 253 -
3rdparty/PEAR5.php | 33 -
3rdparty/Sabre.includes.php | 26 -
3rdparty/Sabre/CalDAV/Backend/Abstract.php | 168 -
3rdparty/Sabre/CalDAV/Backend/PDO.php | 396 --
3rdparty/Sabre/CalDAV/Calendar.php | 343 --
3rdparty/Sabre/CalDAV/CalendarObject.php | 273 -
3rdparty/Sabre/CalDAV/CalendarQueryParser.php | 296 -
.../Sabre/CalDAV/CalendarQueryValidator.php | 370 --
3rdparty/Sabre/CalDAV/CalendarRootNode.php | 75 -
3rdparty/Sabre/CalDAV/ICSExportPlugin.php | 139 -
3rdparty/Sabre/CalDAV/ICalendar.php | 18 -
3rdparty/Sabre/CalDAV/ICalendarObject.php | 20 -
3rdparty/Sabre/CalDAV/Plugin.php | 931 ---
.../Sabre/CalDAV/Principal/Collection.php | 31 -
3rdparty/Sabre/CalDAV/Principal/ProxyRead.php | 178 -
.../Sabre/CalDAV/Principal/ProxyWrite.php | 178 -
3rdparty/Sabre/CalDAV/Principal/User.php | 132 -
.../SupportedCalendarComponentSet.php | 85 -
.../CalDAV/Property/SupportedCalendarData.php | 38 -
.../CalDAV/Property/SupportedCollationSet.php | 44 -
3rdparty/Sabre/CalDAV/Schedule/IMip.php | 104 -
3rdparty/Sabre/CalDAV/Schedule/IOutbox.php | 16 -
3rdparty/Sabre/CalDAV/Schedule/Outbox.php | 152 -
3rdparty/Sabre/CalDAV/Server.php | 68 -
3rdparty/Sabre/CalDAV/UserCalendars.php | 298 -
3rdparty/Sabre/CalDAV/Version.php | 24 -
3rdparty/Sabre/CalDAV/includes.php | 43 -
3rdparty/Sabre/CardDAV/AddressBook.php | 312 -
.../Sabre/CardDAV/AddressBookQueryParser.php | 219 -
3rdparty/Sabre/CardDAV/AddressBookRoot.php | 78 -
3rdparty/Sabre/CardDAV/Backend/Abstract.php | 166 -
3rdparty/Sabre/CardDAV/Backend/PDO.php | 330 --
3rdparty/Sabre/CardDAV/Card.php | 250 -
3rdparty/Sabre/CardDAV/IAddressBook.php | 18 -
3rdparty/Sabre/CardDAV/ICard.php | 18 -
3rdparty/Sabre/CardDAV/IDirectory.php | 21 -
3rdparty/Sabre/CardDAV/Plugin.php | 669 ---
.../CardDAV/Property/SupportedAddressData.php | 69 -
3rdparty/Sabre/CardDAV/UserAddressBooks.php | 257 -
3rdparty/Sabre/CardDAV/Version.php | 26 -
3rdparty/Sabre/CardDAV/includes.php | 32 -
.../Sabre/DAV/Auth/Backend/AbstractBasic.php | 83 -
.../Sabre/DAV/Auth/Backend/AbstractDigest.php | 98 -
3rdparty/Sabre/DAV/Auth/Backend/Apache.php | 62 -
3rdparty/Sabre/DAV/Auth/Backend/File.php | 75 -
3rdparty/Sabre/DAV/Auth/Backend/PDO.php | 65 -
3rdparty/Sabre/DAV/Auth/IBackend.php | 36 -
3rdparty/Sabre/DAV/Auth/Plugin.php | 111 -
.../Sabre/DAV/Browser/GuessContentType.php | 97 -
.../Sabre/DAV/Browser/MapGetToPropFind.php | 55 -
3rdparty/Sabre/DAV/Browser/Plugin.php | 489 --
3rdparty/Sabre/DAV/Browser/assets/favicon.ico | Bin 4286 -> 0 bytes
.../DAV/Browser/assets/icons/addressbook.png | Bin 7232 -> 0 bytes
.../DAV/Browser/assets/icons/calendar.png | Bin 4388 -> 0 bytes
.../Sabre/DAV/Browser/assets/icons/card.png | Bin 5695 -> 0 bytes
.../DAV/Browser/assets/icons/collection.png | Bin 3474 -> 0 bytes
.../Sabre/DAV/Browser/assets/icons/file.png | Bin 2837 -> 0 bytes
.../Sabre/DAV/Browser/assets/icons/parent.png | Bin 3474 -> 0 bytes
.../DAV/Browser/assets/icons/principal.png | Bin 5480 -> 0 bytes
3rdparty/Sabre/DAV/Client.php | 492 --
3rdparty/Sabre/DAV/Collection.php | 106 -
3rdparty/Sabre/DAV/Directory.php | 17 -
3rdparty/Sabre/DAV/Exception.php | 64 -
3rdparty/Sabre/DAV/Exception/BadRequest.php | 28 -
3rdparty/Sabre/DAV/Exception/Conflict.php | 28 -
.../Sabre/DAV/Exception/ConflictingLock.php | 35 -
3rdparty/Sabre/DAV/Exception/FileNotFound.php | 19 -
3rdparty/Sabre/DAV/Exception/Forbidden.php | 27 -
.../DAV/Exception/InsufficientStorage.php | 27 -
.../DAV/Exception/InvalidResourceType.php | 33 -
.../Exception/LockTokenMatchesRequestUri.php | 39 -
3rdparty/Sabre/DAV/Exception/Locked.php | 67 -
.../Sabre/DAV/Exception/MethodNotAllowed.php | 45 -
.../Sabre/DAV/Exception/NotAuthenticated.php | 28 -
3rdparty/Sabre/DAV/Exception/NotFound.php | 28 -
.../Sabre/DAV/Exception/NotImplemented.php | 27 -
.../Sabre/DAV/Exception/PaymentRequired.php | 28 -
.../DAV/Exception/PreconditionFailed.php | 69 -
.../DAV/Exception/ReportNotImplemented.php | 30 -
.../RequestedRangeNotSatisfiable.php | 29 -
.../DAV/Exception/UnsupportedMediaType.php | 28 -
3rdparty/Sabre/DAV/FS/Directory.php | 136 -
3rdparty/Sabre/DAV/FS/File.php | 89 -
3rdparty/Sabre/DAV/FS/Node.php | 80 -
3rdparty/Sabre/DAV/FSExt/Directory.php | 154 -
3rdparty/Sabre/DAV/FSExt/File.php | 93 -
3rdparty/Sabre/DAV/FSExt/Node.php | 212 -
3rdparty/Sabre/DAV/File.php | 85 -
3rdparty/Sabre/DAV/ICollection.php | 74 -
3rdparty/Sabre/DAV/IExtendedCollection.php | 28 -
3rdparty/Sabre/DAV/IFile.php | 77 -
3rdparty/Sabre/DAV/INode.php | 46 -
3rdparty/Sabre/DAV/IProperties.php | 67 -
3rdparty/Sabre/DAV/IQuota.php | 27 -
3rdparty/Sabre/DAV/Locks/Backend/Abstract.php | 50 -
3rdparty/Sabre/DAV/Locks/Backend/FS.php | 191 -
3rdparty/Sabre/DAV/Locks/Backend/File.php | 181 -
3rdparty/Sabre/DAV/Locks/Backend/PDO.php | 165 -
3rdparty/Sabre/DAV/Locks/LockInfo.php | 81 -
3rdparty/Sabre/DAV/Locks/Plugin.php | 636 --
3rdparty/Sabre/DAV/Mount/Plugin.php | 80 -
3rdparty/Sabre/DAV/Node.php | 55 -
3rdparty/Sabre/DAV/ObjectTree.php | 153 -
3rdparty/Sabre/DAV/Property.php | 25 -
.../Sabre/DAV/Property/GetLastModified.php | 75 -
3rdparty/Sabre/DAV/Property/Href.php | 91 -
3rdparty/Sabre/DAV/Property/HrefList.php | 96 -
3rdparty/Sabre/DAV/Property/IHref.php | 25 -
3rdparty/Sabre/DAV/Property/LockDiscovery.php | 102 -
3rdparty/Sabre/DAV/Property/ResourceType.php | 125 -
3rdparty/Sabre/DAV/Property/Response.php | 155 -
3rdparty/Sabre/DAV/Property/ResponseList.php | 57 -
3rdparty/Sabre/DAV/Property/SupportedLock.php | 76 -
.../Sabre/DAV/Property/SupportedReportSet.php | 109 -
3rdparty/Sabre/DAV/Server.php | 2006 -------
3rdparty/Sabre/DAV/ServerPlugin.php | 90 -
3rdparty/Sabre/DAV/SimpleCollection.php | 105 -
3rdparty/Sabre/DAV/SimpleDirectory.php | 21 -
3rdparty/Sabre/DAV/SimpleFile.php | 121 -
3rdparty/Sabre/DAV/StringUtil.php | 91 -
.../Sabre/DAV/TemporaryFileFilterPlugin.php | 289 -
3rdparty/Sabre/DAV/Tree.php | 193 -
3rdparty/Sabre/DAV/Tree/Filesystem.php | 123 -
3rdparty/Sabre/DAV/URLUtil.php | 121 -
3rdparty/Sabre/DAV/UUIDUtil.php | 64 -
3rdparty/Sabre/DAV/Version.php | 24 -
3rdparty/Sabre/DAV/XMLUtil.php | 186 -
3rdparty/Sabre/DAV/includes.php | 97 -
.../DAVACL/AbstractPrincipalCollection.php | 154 -
.../Sabre/DAVACL/Exception/AceConflict.php | 32 -
.../Sabre/DAVACL/Exception/NeedPrivileges.php | 81 -
.../Sabre/DAVACL/Exception/NoAbstract.php | 32 -
.../Exception/NotRecognizedPrincipal.php | 32 -
.../Exception/NotSupportedPrivilege.php | 32 -
3rdparty/Sabre/DAVACL/IACL.php | 73 -
3rdparty/Sabre/DAVACL/IPrincipal.php | 75 -
3rdparty/Sabre/DAVACL/IPrincipalBackend.php | 153 -
3rdparty/Sabre/DAVACL/Plugin.php | 1348 -----
3rdparty/Sabre/DAVACL/Principal.php | 279 -
.../Sabre/DAVACL/PrincipalBackend/PDO.php | 427 --
3rdparty/Sabre/DAVACL/PrincipalCollection.php | 35 -
3rdparty/Sabre/DAVACL/Property/Acl.php | 209 -
.../Sabre/DAVACL/Property/AclRestrictions.php | 32 -
.../Property/CurrentUserPrivilegeSet.php | 75 -
3rdparty/Sabre/DAVACL/Property/Principal.php | 160 -
.../DAVACL/Property/SupportedPrivilegeSet.php | 92 -
3rdparty/Sabre/DAVACL/Version.php | 24 -
3rdparty/Sabre/DAVACL/includes.php | 38 -
3rdparty/Sabre/HTTP/AWSAuth.php | 227 -
3rdparty/Sabre/HTTP/AbstractAuth.php | 111 -
3rdparty/Sabre/HTTP/BasicAuth.php | 67 -
3rdparty/Sabre/HTTP/DigestAuth.php | 240 -
3rdparty/Sabre/HTTP/Request.php | 268 -
3rdparty/Sabre/HTTP/Response.php | 157 -
3rdparty/Sabre/HTTP/Util.php | 82 -
3rdparty/Sabre/HTTP/Version.php | 24 -
3rdparty/Sabre/HTTP/includes.php | 27 -
3rdparty/Sabre/VObject/Component.php | 365 --
3rdparty/Sabre/VObject/Component/VAlarm.php | 102 -
.../Sabre/VObject/Component/VCalendar.php | 133 -
3rdparty/Sabre/VObject/Component/VEvent.php | 71 -
3rdparty/Sabre/VObject/Component/VJournal.php | 46 -
3rdparty/Sabre/VObject/Component/VTodo.php | 68 -
3rdparty/Sabre/VObject/DateTimeParser.php | 181 -
3rdparty/Sabre/VObject/Element.php | 16 -
3rdparty/Sabre/VObject/Element/DateTime.php | 37 -
.../Sabre/VObject/Element/MultiDateTime.php | 17 -
3rdparty/Sabre/VObject/ElementList.php | 172 -
3rdparty/Sabre/VObject/FreeBusyGenerator.php | 297 -
3rdparty/Sabre/VObject/Node.php | 149 -
3rdparty/Sabre/VObject/Parameter.php | 84 -
3rdparty/Sabre/VObject/ParseException.php | 12 -
3rdparty/Sabre/VObject/Property.php | 348 --
3rdparty/Sabre/VObject/Property/DateTime.php | 260 -
.../Sabre/VObject/Property/MultiDateTime.php | 166 -
3rdparty/Sabre/VObject/Reader.php | 183 -
3rdparty/Sabre/VObject/RecurrenceIterator.php | 1043 ----
3rdparty/Sabre/VObject/Version.php | 24 -
3rdparty/Sabre/VObject/WindowsTimezoneMap.php | 128 -
3rdparty/Sabre/VObject/includes.php | 41 -
3rdparty/Sabre/autoload.php | 31 -
3rdparty/Symfony/Component/Routing | 1 -
3rdparty/System.php | 629 --
3rdparty/XML/Parser.php | 754 ---
3rdparty/XML/Parser/Simple.php | 326 -
3rdparty/aws-sdk/README.md | 136 -
.../aws-sdk/_compatibility_test/README.md | 37 -
.../sdk_compatibility.inc.php | 75 -
.../sdk_compatibility_test.php | 789 ---
.../sdk_compatibility_test_cli.php | 186 -
3rdparty/aws-sdk/_docs/CHANGELOG.md | 1405 -----
3rdparty/aws-sdk/_docs/CONTRIBUTORS.md | 64 -
.../aws-sdk/_docs/DYNAMODBSESSIONHANDLER.html | 235 -
3rdparty/aws-sdk/_docs/KNOWNISSUES.md | 65 -
3rdparty/aws-sdk/_docs/LICENSE.md | 151 -
3rdparty/aws-sdk/_docs/NOTICE.md | 444 --
.../aws-sdk/_docs/STREAMWRAPPER_README.html | 243 -
.../_docs/WHERE_IS_THE_API_REFERENCE.md | 2 -
.../authentication/signable.interface.php | 48 -
.../signature_v2query.class.php | 163 -
.../authentication/signature_v3json.class.php | 235 -
.../signature_v3query.class.php | 192 -
.../authentication/signature_v4json.class.php | 353 --
.../signature_v4query.class.php | 345 --
.../authentication/signer.abstract.php | 68 -
3rdparty/aws-sdk/lib/cachecore/LICENSE | 25 -
3rdparty/aws-sdk/lib/cachecore/README | 1 -
3rdparty/aws-sdk/lib/cachecore/_sql/README | 5 -
3rdparty/aws-sdk/lib/cachecore/_sql/mysql.sql | 7 -
3rdparty/aws-sdk/lib/cachecore/_sql/pgsql.sql | 6 -
.../aws-sdk/lib/cachecore/_sql/sqlite3.sql | 2 -
.../aws-sdk/lib/cachecore/cacheapc.class.php | 126 -
.../aws-sdk/lib/cachecore/cachecore.class.php | 160 -
.../aws-sdk/lib/cachecore/cachefile.class.php | 189 -
.../aws-sdk/lib/cachecore/cachemc.class.php | 183 -
.../aws-sdk/lib/cachecore/cachepdo.class.php | 297 -
.../lib/cachecore/cachexcache.class.php | 129 -
.../lib/cachecore/icachecore.interface.php | 66 -
.../aws-sdk/lib/dom/ArrayToDOMDocument.php | 181 -
3rdparty/aws-sdk/lib/requestcore/LICENSE | 25 -
3rdparty/aws-sdk/lib/requestcore/README.md | 15 -
3rdparty/aws-sdk/lib/requestcore/cacert.pem | 3390 -----------
.../lib/requestcore/requestcore.class.php | 1028 ----
3rdparty/aws-sdk/lib/yaml/LICENSE | 19 -
3rdparty/aws-sdk/lib/yaml/README.markdown | 15 -
3rdparty/aws-sdk/lib/yaml/lib/sfYaml.php | 135 -
.../aws-sdk/lib/yaml/lib/sfYamlDumper.php | 60 -
.../aws-sdk/lib/yaml/lib/sfYamlInline.php | 442 --
.../aws-sdk/lib/yaml/lib/sfYamlParser.php | 612 --
3rdparty/aws-sdk/sdk.class.php | 1435 -----
3rdparty/aws-sdk/services/s3.class.php | 3979 -------------
3rdparty/aws-sdk/utilities/array.class.php | 312 -
.../aws-sdk/utilities/batchrequest.class.php | 126 -
.../aws-sdk/utilities/complextype.class.php | 123 -
.../aws-sdk/utilities/credential.class.php | 157 -
.../aws-sdk/utilities/credentials.class.php | 125 -
.../aws-sdk/utilities/gzipdecode.class.php | 377 --
.../aws-sdk/utilities/hadoopbase.class.php | 67 -
.../utilities/hadoopbootstrap.class.php | 127 -
.../aws-sdk/utilities/hadoopstep.class.php | 98 -
3rdparty/aws-sdk/utilities/info.class.php | 69 -
3rdparty/aws-sdk/utilities/json.class.php | 89 -
3rdparty/aws-sdk/utilities/manifest.class.php | 54 -
.../aws-sdk/utilities/mimetypes.class.php | 223 -
3rdparty/aws-sdk/utilities/policy.class.php | 134 -
3rdparty/aws-sdk/utilities/request.class.php | 70 -
3rdparty/aws-sdk/utilities/response.class.php | 29 -
.../aws-sdk/utilities/simplexml.class.php | 248 -
.../aws-sdk/utilities/stacktemplate.class.php | 52 -
.../aws-sdk/utilities/stepconfig.class.php | 91 -
.../aws-sdk/utilities/utilities.class.php | 399 --
3rdparty/class.phpmailer.php | 2532 --------
3rdparty/class.smtp.php | 818 ---
3rdparty/css/chosen-sprite.png | Bin 559 -> 0 bytes
3rdparty/css/chosen.css | 392 --
3rdparty/css/chosen/chosen-sprite.png | Bin 3998 -> 0 bytes
3rdparty/css/chosen/chosen.css | 392 --
3rdparty/fullcalendar/GPL-LICENSE.txt | 278 -
3rdparty/fullcalendar/MIT-LICENSE.txt | 20 -
3rdparty/fullcalendar/css/fullcalendar.css | 618 --
.../fullcalendar/css/fullcalendar.print.css | 61 -
3rdparty/fullcalendar/js/fullcalendar.js | 5220 -----------------
3rdparty/fullcalendar/js/fullcalendar.min.js | 114 -
3rdparty/fullcalendar/js/gcal.js | 112 -
3rdparty/getid3/extension.cache.dbm.php | 211 -
3rdparty/getid3/extension.cache.mysql.php | 173 -
3rdparty/getid3/getid3.lib.php | 1317 -----
3rdparty/getid3/getid3.php | 1744 ------
3rdparty/getid3/license.txt | 340 --
3rdparty/getid3/module.archive.gzip.php | 280 -
3rdparty/getid3/module.archive.rar.php | 53 -
3rdparty/getid3/module.archive.szip.php | 96 -
3rdparty/getid3/module.archive.tar.php | 178 -
3rdparty/getid3/module.archive.zip.php | 424 --
3rdparty/getid3/module.audio-video.asf.php | 2021 -------
3rdparty/getid3/module.audio-video.bink.php | 73 -
3rdparty/getid3/module.audio-video.flv.php | 731 ---
.../getid3/module.audio-video.matroska.php | 1706 ------
3rdparty/getid3/module.audio-video.mpeg.php | 299 -
3rdparty/getid3/module.audio-video.nsv.php | 226 -
.../getid3/module.audio-video.quicktime.php | 2134 -------
3rdparty/getid3/module.audio-video.real.php | 530 --
3rdparty/getid3/module.audio-video.riff.php | 2409 --------
3rdparty/getid3/module.audio-video.swf.php | 142 -
3rdparty/getid3/module.audio.aa.php | 59 -
3rdparty/getid3/module.audio.aac.php | 515 --
3rdparty/getid3/module.audio.ac3.php | 473 --
3rdparty/getid3/module.audio.au.php | 165 -
3rdparty/getid3/module.audio.avr.php | 127 -
3rdparty/getid3/module.audio.bonk.php | 230 -
3rdparty/getid3/module.audio.dss.php | 75 -
3rdparty/getid3/module.audio.dts.php | 246 -
3rdparty/getid3/module.audio.flac.php | 480 --
3rdparty/getid3/module.audio.la.php | 229 -
3rdparty/getid3/module.audio.lpac.php | 130 -
3rdparty/getid3/module.audio.midi.php | 526 --
3rdparty/getid3/module.audio.mod.php | 101 -
3rdparty/getid3/module.audio.monkey.php | 205 -
3rdparty/getid3/module.audio.mp3.php | 2011 -------
3rdparty/getid3/module.audio.mpc.php | 509 --
3rdparty/getid3/module.audio.ogg.php | 705 ---
3rdparty/getid3/module.audio.optimfrog.php | 429 --
3rdparty/getid3/module.audio.rkau.php | 94 -
3rdparty/getid3/module.audio.shorten.php | 183 -
3rdparty/getid3/module.audio.tta.php | 109 -
3rdparty/getid3/module.audio.voc.php | 207 -
3rdparty/getid3/module.audio.vqf.php | 162 -
3rdparty/getid3/module.audio.wavpack.php | 400 --
3rdparty/getid3/module.graphic.bmp.php | 690 ---
3rdparty/getid3/module.graphic.efax.php | 53 -
3rdparty/getid3/module.graphic.gif.php | 184 -
3rdparty/getid3/module.graphic.jpg.php | 338 --
3rdparty/getid3/module.graphic.pcd.php | 134 -
3rdparty/getid3/module.graphic.png.php | 520 --
3rdparty/getid3/module.graphic.svg.php | 104 -
3rdparty/getid3/module.graphic.tiff.php | 227 -
3rdparty/getid3/module.misc.cue.php | 312 -
3rdparty/getid3/module.misc.exe.php | 61 -
3rdparty/getid3/module.misc.iso.php | 389 --
3rdparty/getid3/module.misc.msoffice.php | 40 -
3rdparty/getid3/module.misc.par2.php | 33 -
3rdparty/getid3/module.misc.pdf.php | 33 -
3rdparty/getid3/module.tag.apetag.php | 372 --
3rdparty/getid3/module.tag.id3v1.php | 362 --
3rdparty/getid3/module.tag.id3v2.php | 3327 -----------
3rdparty/getid3/module.tag.lyrics3.php | 297 -
3rdparty/getid3/module.tag.xmp.php | 766 ---
3rdparty/getid3/write.apetag.php | 225 -
3rdparty/getid3/write.id3v1.php | 138 -
3rdparty/getid3/write.id3v2.php | 2050 -------
3rdparty/getid3/write.lyrics3.php | 73 -
3rdparty/getid3/write.metaflac.php | 163 -
3rdparty/getid3/write.php | 615 --
3rdparty/getid3/write.real.php | 275 -
3rdparty/getid3/write.vorbiscomment.php | 121 -
3rdparty/js/chosen/LICENSE.md | 24 -
3rdparty/js/chosen/README.md | 46 -
3rdparty/js/chosen/VERSION | 1 -
3rdparty/js/chosen/chosen.jquery.js | 952 ---
3rdparty/js/chosen/chosen.jquery.min.js | 10 -
3rdparty/mediawiki/CSSMin.php | 228 -
3rdparty/mediawiki/JavaScriptMinifier.php | 606 --
3rdparty/miniColors/GPL-LICENSE.txt | 278 -
3rdparty/miniColors/MIT-LICENSE.txt | 20 -
3rdparty/miniColors/css/images/colors.png | Bin 12973 -> 0 bytes
3rdparty/miniColors/css/images/trigger.png | Bin 706 -> 0 bytes
3rdparty/miniColors/css/jquery.miniColors.css | 125 -
3rdparty/miniColors/js/jquery.miniColors.js | 710 ---
.../miniColors/js/jquery.miniColors.min.js | 9 -
3rdparty/openid/class.openid.v3.php | 326 -
3rdparty/openid/phpmyid.php | 1707 ------
3rdparty/php-cloudfiles/.gitignore | 3 -
3rdparty/php-cloudfiles/AUTHORS | 11 -
3rdparty/php-cloudfiles/COPYING | 27 -
3rdparty/php-cloudfiles/Changelog | 93 -
3rdparty/php-cloudfiles/README | 73 -
3rdparty/php-cloudfiles/cloudfiles.php | 2599 --------
.../php-cloudfiles/cloudfiles_exceptions.php | 41 -
3rdparty/php-cloudfiles/cloudfiles_http.php | 1488 -----
3rdparty/phpass/PasswordHash.php | 253 -
3rdparty/phpass/c/Makefile | 21 -
3rdparty/phpass/c/crypt_private.c | 106 -
3rdparty/phpass/test.php | 72 -
3rdparty/smb4php/smb.php | 456 --
3rdparty/timepicker/GPL-LICENSE.txt | 278 -
3rdparty/timepicker/MIT-LICENSE.txt | 20 -
.../ui-bg_diagonals-thick_18_b81900_40x40.png | Bin 260 -> 0 bytes
.../ui-bg_diagonals-thick_20_666666_40x40.png | Bin 251 -> 0 bytes
.../images/ui-bg_flat_10_000000_40x100.png | Bin 178 -> 0 bytes
.../images/ui-bg_glass_100_f6f6f6_1x400.png | Bin 104 -> 0 bytes
.../images/ui-bg_glass_100_fdf5ce_1x400.png | Bin 125 -> 0 bytes
.../images/ui-bg_glass_65_ffffff_1x400.png | Bin 105 -> 0 bytes
.../ui-bg_gloss-wave_35_f6a828_500x100.png | Bin 3762 -> 0 bytes
.../ui-bg_highlight-soft_100_eeeeee_1x100.png | Bin 90 -> 0 bytes
.../ui-bg_highlight-soft_75_ffe45c_1x100.png | Bin 129 -> 0 bytes
.../images/ui-icons_222222_256x240.png | Bin 4369 -> 0 bytes
.../images/ui-icons_228ef1_256x240.png | Bin 4369 -> 0 bytes
.../images/ui-icons_ef8c08_256x240.png | Bin 4369 -> 0 bytes
.../images/ui-icons_ffd27a_256x240.png | Bin 4369 -> 0 bytes
.../images/ui-icons_ffffff_256x240.png | Bin 4369 -> 0 bytes
.../css/include/jquery-1.5.1.min.js | 16 -
.../css/include/jquery-ui-1.8.14.custom.css | 568 --
.../css/include/jquery.ui.core.min.js | 17 -
.../css/include/jquery.ui.position.min.js | 16 -
.../css/include/jquery.ui.tabs.min.js | 35 -
.../css/include/jquery.ui.widget.min.js | 15 -
.../ui-bg_diagonals-thick_18_b81900_40x40.png | Bin 260 -> 0 bytes
.../ui-bg_diagonals-thick_20_666666_40x40.png | Bin 251 -> 0 bytes
.../images/ui-bg_flat_10_000000_40x100.png | Bin 178 -> 0 bytes
.../images/ui-bg_glass_100_f6f6f6_1x400.png | Bin 104 -> 0 bytes
.../images/ui-bg_glass_100_fdf5ce_1x400.png | Bin 125 -> 0 bytes
.../images/ui-bg_glass_65_ffffff_1x400.png | Bin 105 -> 0 bytes
.../ui-bg_gloss-wave_35_f6a828_500x100.png | Bin 3762 -> 0 bytes
.../ui-bg_highlight-soft_100_eeeeee_1x100.png | Bin 90 -> 0 bytes
.../ui-bg_highlight-soft_75_ffe45c_1x100.png | Bin 129 -> 0 bytes
.../images/ui-icons_222222_256x240.png | Bin 4369 -> 0 bytes
.../images/ui-icons_228ef1_256x240.png | Bin 4369 -> 0 bytes
.../images/ui-icons_ef8c08_256x240.png | Bin 4369 -> 0 bytes
.../images/ui-icons_ffd27a_256x240.png | Bin 4369 -> 0 bytes
.../images/ui-icons_ffffff_256x240.png | Bin 4369 -> 0 bytes
.../timepicker/css/jquery.ui.timepicker.css | 69 -
3rdparty/timepicker/js/i18n/i18n.html | 147 -
.../js/i18n/jquery.ui.timepicker-cs.js | 12 -
.../js/i18n/jquery.ui.timepicker-de.js | 12 -
.../js/i18n/jquery.ui.timepicker-es.js | 12 -
.../js/i18n/jquery.ui.timepicker-fr.js | 13 -
.../js/i18n/jquery.ui.timepicker-hr.js | 13 -
.../js/i18n/jquery.ui.timepicker-it.js | 12 -
.../js/i18n/jquery.ui.timepicker-ja.js | 12 -
.../js/i18n/jquery.ui.timepicker-nl.js | 12 -
.../js/i18n/jquery.ui.timepicker-pl.js | 12 -
.../js/i18n/jquery.ui.timepicker-pt-BR.js | 12 -
.../js/i18n/jquery.ui.timepicker-sl.js | 12 -
.../js/i18n/jquery.ui.timepicker-sv.js | 12 -
.../js/i18n/jquery.ui.timepicker-tr.js | 12 -
.../timepicker/js/jquery.ui.timepicker.js | 1406 -----
3rdparty/timepicker/releases.txt | 115 -
577 files changed, 192247 deletions(-)
delete mode 100644 3rdparty/Archive/Tar.php
delete mode 100644 3rdparty/Console/Getopt.php
delete mode 100644 3rdparty/Crypt_Blowfish/Blowfish.php
delete mode 100644 3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php
delete mode 100644 3rdparty/Dropbox/API.php
delete mode 100644 3rdparty/Dropbox/Exception.php
delete mode 100644 3rdparty/Dropbox/Exception/Forbidden.php
delete mode 100644 3rdparty/Dropbox/Exception/NotFound.php
delete mode 100644 3rdparty/Dropbox/Exception/OverQuota.php
delete mode 100644 3rdparty/Dropbox/Exception/RequestToken.php
delete mode 100644 3rdparty/Dropbox/LICENSE.txt
delete mode 100644 3rdparty/Dropbox/OAuth.php
delete mode 100644 3rdparty/Dropbox/OAuth/Consumer/Dropbox.php
delete mode 100644 3rdparty/Dropbox/OAuth/Curl.php
delete mode 100644 3rdparty/Dropbox/README.md
delete mode 100644 3rdparty/Dropbox/autoload.php
delete mode 100644 3rdparty/Google/LICENSE.txt
delete mode 100755 3rdparty/Google/OAuth.php
delete mode 100755 3rdparty/Google/common.inc.php
delete mode 100644 3rdparty/MDB2.php
delete mode 100644 3rdparty/MDB2/Date.php
delete mode 100644 3rdparty/MDB2/Driver/Datatype/Common.php
delete mode 100644 3rdparty/MDB2/Driver/Datatype/mysql.php
delete mode 100644 3rdparty/MDB2/Driver/Datatype/oci8.php
delete mode 100644 3rdparty/MDB2/Driver/Datatype/pgsql.php
delete mode 100644 3rdparty/MDB2/Driver/Datatype/sqlite.php
delete mode 100644 3rdparty/MDB2/Driver/Function/Common.php
delete mode 100644 3rdparty/MDB2/Driver/Function/mysql.php
delete mode 100644 3rdparty/MDB2/Driver/Function/oci8.php
delete mode 100644 3rdparty/MDB2/Driver/Function/pgsql.php
delete mode 100644 3rdparty/MDB2/Driver/Function/sqlite.php
delete mode 100644 3rdparty/MDB2/Driver/Manager/Common.php
delete mode 100644 3rdparty/MDB2/Driver/Manager/mysql.php
delete mode 100644 3rdparty/MDB2/Driver/Manager/oci8.php
delete mode 100644 3rdparty/MDB2/Driver/Manager/pgsql.php
delete mode 100644 3rdparty/MDB2/Driver/Manager/sqlite.php
delete mode 100644 3rdparty/MDB2/Driver/Native/Common.php
delete mode 100644 3rdparty/MDB2/Driver/Native/mysql.php
delete mode 100644 3rdparty/MDB2/Driver/Native/oci8.php
delete mode 100644 3rdparty/MDB2/Driver/Native/pgsql.php
delete mode 100644 3rdparty/MDB2/Driver/Native/sqlite.php
delete mode 100644 3rdparty/MDB2/Driver/Reverse/Common.php
delete mode 100644 3rdparty/MDB2/Driver/Reverse/mysql.php
delete mode 100644 3rdparty/MDB2/Driver/Reverse/oci8.php
delete mode 100644 3rdparty/MDB2/Driver/Reverse/pgsql.php
delete mode 100644 3rdparty/MDB2/Driver/Reverse/sqlite.php
delete mode 100644 3rdparty/MDB2/Driver/mysql.php
delete mode 100644 3rdparty/MDB2/Driver/oci8.php
delete mode 100644 3rdparty/MDB2/Driver/pgsql.php
delete mode 100644 3rdparty/MDB2/Driver/sqlite.php
delete mode 100644 3rdparty/MDB2/Extended.php
delete mode 100644 3rdparty/MDB2/Iterator.php
delete mode 100644 3rdparty/MDB2/LOB.php
delete mode 100644 3rdparty/MDB2/Schema.php
delete mode 100644 3rdparty/MDB2/Schema/Parser.php
delete mode 100644 3rdparty/MDB2/Schema/Parser2.php
delete mode 100644 3rdparty/MDB2/Schema/Reserved/ibase.php
delete mode 100644 3rdparty/MDB2/Schema/Reserved/mssql.php
delete mode 100644 3rdparty/MDB2/Schema/Reserved/mysql.php
delete mode 100644 3rdparty/MDB2/Schema/Reserved/oci8.php
delete mode 100644 3rdparty/MDB2/Schema/Reserved/pgsql.php
delete mode 100644 3rdparty/MDB2/Schema/Tool.php
delete mode 100644 3rdparty/MDB2/Schema/Tool/ParameterException.php
delete mode 100644 3rdparty/MDB2/Schema/Validate.php
delete mode 100644 3rdparty/MDB2/Schema/Writer.php
delete mode 100644 3rdparty/OAuth/LICENSE.TXT
delete mode 100644 3rdparty/OAuth/OAuth.php
delete mode 100644 3rdparty/OS/Guess.php
delete mode 100644 3rdparty/PEAR-LICENSE
delete mode 100644 3rdparty/PEAR.php
delete mode 100644 3rdparty/PEAR/Autoloader.php
delete mode 100644 3rdparty/PEAR/Builder.php
delete mode 100644 3rdparty/PEAR/ChannelFile.php
delete mode 100644 3rdparty/PEAR/ChannelFile/Parser.php
delete mode 100644 3rdparty/PEAR/Command.php
delete mode 100644 3rdparty/PEAR/Command/Auth.php
delete mode 100644 3rdparty/PEAR/Command/Auth.xml
delete mode 100644 3rdparty/PEAR/Command/Build.php
delete mode 100644 3rdparty/PEAR/Command/Build.xml
delete mode 100644 3rdparty/PEAR/Command/Channels.php
delete mode 100644 3rdparty/PEAR/Command/Channels.xml
delete mode 100644 3rdparty/PEAR/Command/Common.php
delete mode 100644 3rdparty/PEAR/Command/Config.php
delete mode 100644 3rdparty/PEAR/Command/Config.xml
delete mode 100644 3rdparty/PEAR/Command/Install.php
delete mode 100644 3rdparty/PEAR/Command/Install.xml
delete mode 100644 3rdparty/PEAR/Command/Mirror.php
delete mode 100644 3rdparty/PEAR/Command/Mirror.xml
delete mode 100644 3rdparty/PEAR/Command/Package.php
delete mode 100644 3rdparty/PEAR/Command/Package.xml
delete mode 100644 3rdparty/PEAR/Command/Pickle.php
delete mode 100644 3rdparty/PEAR/Command/Pickle.xml
delete mode 100644 3rdparty/PEAR/Command/Registry.php
delete mode 100644 3rdparty/PEAR/Command/Registry.xml
delete mode 100644 3rdparty/PEAR/Command/Remote.php
delete mode 100644 3rdparty/PEAR/Command/Remote.xml
delete mode 100644 3rdparty/PEAR/Command/Test.php
delete mode 100644 3rdparty/PEAR/Command/Test.xml
delete mode 100644 3rdparty/PEAR/Common.php
delete mode 100644 3rdparty/PEAR/Config.php
delete mode 100644 3rdparty/PEAR/Dependency.php
delete mode 100644 3rdparty/PEAR/Dependency2.php
delete mode 100644 3rdparty/PEAR/DependencyDB.php
delete mode 100644 3rdparty/PEAR/Downloader.php
delete mode 100644 3rdparty/PEAR/Downloader/Package.php
delete mode 100644 3rdparty/PEAR/ErrorStack.php
delete mode 100644 3rdparty/PEAR/Exception.php
delete mode 100644 3rdparty/PEAR/FixPHP5PEARWarnings.php
delete mode 100644 3rdparty/PEAR/Frontend.php
delete mode 100644 3rdparty/PEAR/Frontend/CLI.php
delete mode 100644 3rdparty/PEAR/Installer.php
delete mode 100644 3rdparty/PEAR/Installer/Role.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Cfg.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Cfg.xml
delete mode 100644 3rdparty/PEAR/Installer/Role/Common.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Data.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Data.xml
delete mode 100644 3rdparty/PEAR/Installer/Role/Doc.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Doc.xml
delete mode 100644 3rdparty/PEAR/Installer/Role/Ext.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Ext.xml
delete mode 100644 3rdparty/PEAR/Installer/Role/Php.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Php.xml
delete mode 100644 3rdparty/PEAR/Installer/Role/Script.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Script.xml
delete mode 100644 3rdparty/PEAR/Installer/Role/Src.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Src.xml
delete mode 100644 3rdparty/PEAR/Installer/Role/Test.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Test.xml
delete mode 100644 3rdparty/PEAR/Installer/Role/Www.php
delete mode 100644 3rdparty/PEAR/Installer/Role/Www.xml
delete mode 100644 3rdparty/PEAR/PackageFile.php
delete mode 100644 3rdparty/PEAR/PackageFile/Generator/v1.php
delete mode 100644 3rdparty/PEAR/PackageFile/Generator/v2.php
delete mode 100644 3rdparty/PEAR/PackageFile/Parser/v1.php
delete mode 100644 3rdparty/PEAR/PackageFile/Parser/v2.php
delete mode 100644 3rdparty/PEAR/PackageFile/v1.php
delete mode 100644 3rdparty/PEAR/PackageFile/v2.php
delete mode 100644 3rdparty/PEAR/PackageFile/v2/Validator.php
delete mode 100644 3rdparty/PEAR/PackageFile/v2/rw.php
delete mode 100644 3rdparty/PEAR/Packager.php
delete mode 100644 3rdparty/PEAR/REST.php
delete mode 100644 3rdparty/PEAR/REST/10.php
delete mode 100644 3rdparty/PEAR/REST/11.php
delete mode 100644 3rdparty/PEAR/REST/13.php
delete mode 100644 3rdparty/PEAR/Registry.php
delete mode 100644 3rdparty/PEAR/Remote.php
delete mode 100644 3rdparty/PEAR/RunTest.php
delete mode 100644 3rdparty/PEAR/Task/Common.php
delete mode 100644 3rdparty/PEAR/Task/Postinstallscript.php
delete mode 100644 3rdparty/PEAR/Task/Postinstallscript/rw.php
delete mode 100644 3rdparty/PEAR/Task/Replace.php
delete mode 100644 3rdparty/PEAR/Task/Replace/rw.php
delete mode 100644 3rdparty/PEAR/Task/Unixeol.php
delete mode 100644 3rdparty/PEAR/Task/Unixeol/rw.php
delete mode 100644 3rdparty/PEAR/Task/Windowseol.php
delete mode 100644 3rdparty/PEAR/Task/Windowseol/rw.php
delete mode 100644 3rdparty/PEAR/Validate.php
delete mode 100644 3rdparty/PEAR/Validator/PECL.php
delete mode 100644 3rdparty/PEAR/XMLParser.php
delete mode 100644 3rdparty/PEAR5.php
delete mode 100755 3rdparty/Sabre.includes.php
delete mode 100755 3rdparty/Sabre/CalDAV/Backend/Abstract.php
delete mode 100755 3rdparty/Sabre/CalDAV/Backend/PDO.php
delete mode 100755 3rdparty/Sabre/CalDAV/Calendar.php
delete mode 100755 3rdparty/Sabre/CalDAV/CalendarObject.php
delete mode 100755 3rdparty/Sabre/CalDAV/CalendarQueryParser.php
delete mode 100755 3rdparty/Sabre/CalDAV/CalendarQueryValidator.php
delete mode 100755 3rdparty/Sabre/CalDAV/CalendarRootNode.php
delete mode 100755 3rdparty/Sabre/CalDAV/ICSExportPlugin.php
delete mode 100755 3rdparty/Sabre/CalDAV/ICalendar.php
delete mode 100755 3rdparty/Sabre/CalDAV/ICalendarObject.php
delete mode 100755 3rdparty/Sabre/CalDAV/Plugin.php
delete mode 100755 3rdparty/Sabre/CalDAV/Principal/Collection.php
delete mode 100755 3rdparty/Sabre/CalDAV/Principal/ProxyRead.php
delete mode 100755 3rdparty/Sabre/CalDAV/Principal/ProxyWrite.php
delete mode 100755 3rdparty/Sabre/CalDAV/Principal/User.php
delete mode 100755 3rdparty/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php
delete mode 100755 3rdparty/Sabre/CalDAV/Property/SupportedCalendarData.php
delete mode 100755 3rdparty/Sabre/CalDAV/Property/SupportedCollationSet.php
delete mode 100755 3rdparty/Sabre/CalDAV/Schedule/IMip.php
delete mode 100755 3rdparty/Sabre/CalDAV/Schedule/IOutbox.php
delete mode 100755 3rdparty/Sabre/CalDAV/Schedule/Outbox.php
delete mode 100755 3rdparty/Sabre/CalDAV/Server.php
delete mode 100755 3rdparty/Sabre/CalDAV/UserCalendars.php
delete mode 100755 3rdparty/Sabre/CalDAV/Version.php
delete mode 100755 3rdparty/Sabre/CalDAV/includes.php
delete mode 100755 3rdparty/Sabre/CardDAV/AddressBook.php
delete mode 100755 3rdparty/Sabre/CardDAV/AddressBookQueryParser.php
delete mode 100755 3rdparty/Sabre/CardDAV/AddressBookRoot.php
delete mode 100755 3rdparty/Sabre/CardDAV/Backend/Abstract.php
delete mode 100755 3rdparty/Sabre/CardDAV/Backend/PDO.php
delete mode 100755 3rdparty/Sabre/CardDAV/Card.php
delete mode 100755 3rdparty/Sabre/CardDAV/IAddressBook.php
delete mode 100755 3rdparty/Sabre/CardDAV/ICard.php
delete mode 100755 3rdparty/Sabre/CardDAV/IDirectory.php
delete mode 100755 3rdparty/Sabre/CardDAV/Plugin.php
delete mode 100755 3rdparty/Sabre/CardDAV/Property/SupportedAddressData.php
delete mode 100755 3rdparty/Sabre/CardDAV/UserAddressBooks.php
delete mode 100755 3rdparty/Sabre/CardDAV/Version.php
delete mode 100755 3rdparty/Sabre/CardDAV/includes.php
delete mode 100755 3rdparty/Sabre/DAV/Auth/Backend/AbstractBasic.php
delete mode 100755 3rdparty/Sabre/DAV/Auth/Backend/AbstractDigest.php
delete mode 100755 3rdparty/Sabre/DAV/Auth/Backend/Apache.php
delete mode 100755 3rdparty/Sabre/DAV/Auth/Backend/File.php
delete mode 100755 3rdparty/Sabre/DAV/Auth/Backend/PDO.php
delete mode 100755 3rdparty/Sabre/DAV/Auth/IBackend.php
delete mode 100755 3rdparty/Sabre/DAV/Auth/Plugin.php
delete mode 100755 3rdparty/Sabre/DAV/Browser/GuessContentType.php
delete mode 100755 3rdparty/Sabre/DAV/Browser/MapGetToPropFind.php
delete mode 100755 3rdparty/Sabre/DAV/Browser/Plugin.php
delete mode 100755 3rdparty/Sabre/DAV/Browser/assets/favicon.ico
delete mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/addressbook.png
delete mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/calendar.png
delete mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/card.png
delete mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/collection.png
delete mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/file.png
delete mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/parent.png
delete mode 100755 3rdparty/Sabre/DAV/Browser/assets/icons/principal.png
delete mode 100755 3rdparty/Sabre/DAV/Client.php
delete mode 100755 3rdparty/Sabre/DAV/Collection.php
delete mode 100755 3rdparty/Sabre/DAV/Directory.php
delete mode 100755 3rdparty/Sabre/DAV/Exception.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/BadRequest.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/Conflict.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/ConflictingLock.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/FileNotFound.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/Forbidden.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/InsufficientStorage.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/InvalidResourceType.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/Locked.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/MethodNotAllowed.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/NotAuthenticated.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/NotFound.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/NotImplemented.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/PaymentRequired.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/PreconditionFailed.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/ReportNotImplemented.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php
delete mode 100755 3rdparty/Sabre/DAV/Exception/UnsupportedMediaType.php
delete mode 100755 3rdparty/Sabre/DAV/FS/Directory.php
delete mode 100755 3rdparty/Sabre/DAV/FS/File.php
delete mode 100755 3rdparty/Sabre/DAV/FS/Node.php
delete mode 100755 3rdparty/Sabre/DAV/FSExt/Directory.php
delete mode 100755 3rdparty/Sabre/DAV/FSExt/File.php
delete mode 100755 3rdparty/Sabre/DAV/FSExt/Node.php
delete mode 100755 3rdparty/Sabre/DAV/File.php
delete mode 100755 3rdparty/Sabre/DAV/ICollection.php
delete mode 100755 3rdparty/Sabre/DAV/IExtendedCollection.php
delete mode 100755 3rdparty/Sabre/DAV/IFile.php
delete mode 100755 3rdparty/Sabre/DAV/INode.php
delete mode 100755 3rdparty/Sabre/DAV/IProperties.php
delete mode 100755 3rdparty/Sabre/DAV/IQuota.php
delete mode 100755 3rdparty/Sabre/DAV/Locks/Backend/Abstract.php
delete mode 100755 3rdparty/Sabre/DAV/Locks/Backend/FS.php
delete mode 100755 3rdparty/Sabre/DAV/Locks/Backend/File.php
delete mode 100755 3rdparty/Sabre/DAV/Locks/Backend/PDO.php
delete mode 100755 3rdparty/Sabre/DAV/Locks/LockInfo.php
delete mode 100755 3rdparty/Sabre/DAV/Locks/Plugin.php
delete mode 100755 3rdparty/Sabre/DAV/Mount/Plugin.php
delete mode 100755 3rdparty/Sabre/DAV/Node.php
delete mode 100755 3rdparty/Sabre/DAV/ObjectTree.php
delete mode 100755 3rdparty/Sabre/DAV/Property.php
delete mode 100755 3rdparty/Sabre/DAV/Property/GetLastModified.php
delete mode 100755 3rdparty/Sabre/DAV/Property/Href.php
delete mode 100755 3rdparty/Sabre/DAV/Property/HrefList.php
delete mode 100755 3rdparty/Sabre/DAV/Property/IHref.php
delete mode 100755 3rdparty/Sabre/DAV/Property/LockDiscovery.php
delete mode 100755 3rdparty/Sabre/DAV/Property/ResourceType.php
delete mode 100755 3rdparty/Sabre/DAV/Property/Response.php
delete mode 100755 3rdparty/Sabre/DAV/Property/ResponseList.php
delete mode 100755 3rdparty/Sabre/DAV/Property/SupportedLock.php
delete mode 100755 3rdparty/Sabre/DAV/Property/SupportedReportSet.php
delete mode 100755 3rdparty/Sabre/DAV/Server.php
delete mode 100755 3rdparty/Sabre/DAV/ServerPlugin.php
delete mode 100755 3rdparty/Sabre/DAV/SimpleCollection.php
delete mode 100755 3rdparty/Sabre/DAV/SimpleDirectory.php
delete mode 100755 3rdparty/Sabre/DAV/SimpleFile.php
delete mode 100755 3rdparty/Sabre/DAV/StringUtil.php
delete mode 100755 3rdparty/Sabre/DAV/TemporaryFileFilterPlugin.php
delete mode 100755 3rdparty/Sabre/DAV/Tree.php
delete mode 100755 3rdparty/Sabre/DAV/Tree/Filesystem.php
delete mode 100755 3rdparty/Sabre/DAV/URLUtil.php
delete mode 100755 3rdparty/Sabre/DAV/UUIDUtil.php
delete mode 100755 3rdparty/Sabre/DAV/Version.php
delete mode 100755 3rdparty/Sabre/DAV/XMLUtil.php
delete mode 100755 3rdparty/Sabre/DAV/includes.php
delete mode 100755 3rdparty/Sabre/DAVACL/AbstractPrincipalCollection.php
delete mode 100755 3rdparty/Sabre/DAVACL/Exception/AceConflict.php
delete mode 100755 3rdparty/Sabre/DAVACL/Exception/NeedPrivileges.php
delete mode 100755 3rdparty/Sabre/DAVACL/Exception/NoAbstract.php
delete mode 100755 3rdparty/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php
delete mode 100755 3rdparty/Sabre/DAVACL/Exception/NotSupportedPrivilege.php
delete mode 100755 3rdparty/Sabre/DAVACL/IACL.php
delete mode 100755 3rdparty/Sabre/DAVACL/IPrincipal.php
delete mode 100755 3rdparty/Sabre/DAVACL/IPrincipalBackend.php
delete mode 100755 3rdparty/Sabre/DAVACL/Plugin.php
delete mode 100755 3rdparty/Sabre/DAVACL/Principal.php
delete mode 100755 3rdparty/Sabre/DAVACL/PrincipalBackend/PDO.php
delete mode 100755 3rdparty/Sabre/DAVACL/PrincipalCollection.php
delete mode 100755 3rdparty/Sabre/DAVACL/Property/Acl.php
delete mode 100755 3rdparty/Sabre/DAVACL/Property/AclRestrictions.php
delete mode 100755 3rdparty/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php
delete mode 100755 3rdparty/Sabre/DAVACL/Property/Principal.php
delete mode 100755 3rdparty/Sabre/DAVACL/Property/SupportedPrivilegeSet.php
delete mode 100755 3rdparty/Sabre/DAVACL/Version.php
delete mode 100755 3rdparty/Sabre/DAVACL/includes.php
delete mode 100755 3rdparty/Sabre/HTTP/AWSAuth.php
delete mode 100755 3rdparty/Sabre/HTTP/AbstractAuth.php
delete mode 100755 3rdparty/Sabre/HTTP/BasicAuth.php
delete mode 100755 3rdparty/Sabre/HTTP/DigestAuth.php
delete mode 100755 3rdparty/Sabre/HTTP/Request.php
delete mode 100755 3rdparty/Sabre/HTTP/Response.php
delete mode 100755 3rdparty/Sabre/HTTP/Util.php
delete mode 100755 3rdparty/Sabre/HTTP/Version.php
delete mode 100755 3rdparty/Sabre/HTTP/includes.php
delete mode 100755 3rdparty/Sabre/VObject/Component.php
delete mode 100755 3rdparty/Sabre/VObject/Component/VAlarm.php
delete mode 100755 3rdparty/Sabre/VObject/Component/VCalendar.php
delete mode 100755 3rdparty/Sabre/VObject/Component/VEvent.php
delete mode 100755 3rdparty/Sabre/VObject/Component/VJournal.php
delete mode 100755 3rdparty/Sabre/VObject/Component/VTodo.php
delete mode 100755 3rdparty/Sabre/VObject/DateTimeParser.php
delete mode 100755 3rdparty/Sabre/VObject/Element.php
delete mode 100755 3rdparty/Sabre/VObject/Element/DateTime.php
delete mode 100755 3rdparty/Sabre/VObject/Element/MultiDateTime.php
delete mode 100755 3rdparty/Sabre/VObject/ElementList.php
delete mode 100755 3rdparty/Sabre/VObject/FreeBusyGenerator.php
delete mode 100755 3rdparty/Sabre/VObject/Node.php
delete mode 100755 3rdparty/Sabre/VObject/Parameter.php
delete mode 100755 3rdparty/Sabre/VObject/ParseException.php
delete mode 100755 3rdparty/Sabre/VObject/Property.php
delete mode 100755 3rdparty/Sabre/VObject/Property/DateTime.php
delete mode 100755 3rdparty/Sabre/VObject/Property/MultiDateTime.php
delete mode 100755 3rdparty/Sabre/VObject/Reader.php
delete mode 100755 3rdparty/Sabre/VObject/RecurrenceIterator.php
delete mode 100755 3rdparty/Sabre/VObject/Version.php
delete mode 100755 3rdparty/Sabre/VObject/WindowsTimezoneMap.php
delete mode 100755 3rdparty/Sabre/VObject/includes.php
delete mode 100755 3rdparty/Sabre/autoload.php
delete mode 160000 3rdparty/Symfony/Component/Routing
delete mode 100644 3rdparty/System.php
delete mode 100644 3rdparty/XML/Parser.php
delete mode 100644 3rdparty/XML/Parser/Simple.php
delete mode 100644 3rdparty/aws-sdk/README.md
delete mode 100644 3rdparty/aws-sdk/_compatibility_test/README.md
delete mode 100644 3rdparty/aws-sdk/_compatibility_test/sdk_compatibility.inc.php
delete mode 100644 3rdparty/aws-sdk/_compatibility_test/sdk_compatibility_test.php
delete mode 100755 3rdparty/aws-sdk/_compatibility_test/sdk_compatibility_test_cli.php
delete mode 100644 3rdparty/aws-sdk/_docs/CHANGELOG.md
delete mode 100644 3rdparty/aws-sdk/_docs/CONTRIBUTORS.md
delete mode 100644 3rdparty/aws-sdk/_docs/DYNAMODBSESSIONHANDLER.html
delete mode 100644 3rdparty/aws-sdk/_docs/KNOWNISSUES.md
delete mode 100644 3rdparty/aws-sdk/_docs/LICENSE.md
delete mode 100644 3rdparty/aws-sdk/_docs/NOTICE.md
delete mode 100644 3rdparty/aws-sdk/_docs/STREAMWRAPPER_README.html
delete mode 100644 3rdparty/aws-sdk/_docs/WHERE_IS_THE_API_REFERENCE.md
delete mode 100644 3rdparty/aws-sdk/authentication/signable.interface.php
delete mode 100644 3rdparty/aws-sdk/authentication/signature_v2query.class.php
delete mode 100644 3rdparty/aws-sdk/authentication/signature_v3json.class.php
delete mode 100644 3rdparty/aws-sdk/authentication/signature_v3query.class.php
delete mode 100644 3rdparty/aws-sdk/authentication/signature_v4json.class.php
delete mode 100644 3rdparty/aws-sdk/authentication/signature_v4query.class.php
delete mode 100644 3rdparty/aws-sdk/authentication/signer.abstract.php
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/LICENSE
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/README
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/_sql/README
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/_sql/mysql.sql
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/_sql/pgsql.sql
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/_sql/sqlite3.sql
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/cacheapc.class.php
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/cachecore.class.php
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/cachefile.class.php
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/cachemc.class.php
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/cachepdo.class.php
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/cachexcache.class.php
delete mode 100755 3rdparty/aws-sdk/lib/cachecore/icachecore.interface.php
delete mode 100644 3rdparty/aws-sdk/lib/dom/ArrayToDOMDocument.php
delete mode 100755 3rdparty/aws-sdk/lib/requestcore/LICENSE
delete mode 100755 3rdparty/aws-sdk/lib/requestcore/README.md
delete mode 100755 3rdparty/aws-sdk/lib/requestcore/cacert.pem
delete mode 100755 3rdparty/aws-sdk/lib/requestcore/requestcore.class.php
delete mode 100644 3rdparty/aws-sdk/lib/yaml/LICENSE
delete mode 100644 3rdparty/aws-sdk/lib/yaml/README.markdown
delete mode 100644 3rdparty/aws-sdk/lib/yaml/lib/sfYaml.php
delete mode 100644 3rdparty/aws-sdk/lib/yaml/lib/sfYamlDumper.php
delete mode 100644 3rdparty/aws-sdk/lib/yaml/lib/sfYamlInline.php
delete mode 100644 3rdparty/aws-sdk/lib/yaml/lib/sfYamlParser.php
delete mode 100755 3rdparty/aws-sdk/sdk.class.php
delete mode 100755 3rdparty/aws-sdk/services/s3.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/array.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/batchrequest.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/complextype.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/credential.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/credentials.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/gzipdecode.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/hadoopbase.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/hadoopbootstrap.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/hadoopstep.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/info.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/json.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/manifest.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/mimetypes.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/policy.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/request.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/response.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/simplexml.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/stacktemplate.class.php
delete mode 100644 3rdparty/aws-sdk/utilities/stepconfig.class.php
delete mode 100755 3rdparty/aws-sdk/utilities/utilities.class.php
delete mode 100644 3rdparty/class.phpmailer.php
delete mode 100644 3rdparty/class.smtp.php
delete mode 100755 3rdparty/css/chosen-sprite.png
delete mode 100755 3rdparty/css/chosen.css
delete mode 100644 3rdparty/css/chosen/chosen-sprite.png
delete mode 100755 3rdparty/css/chosen/chosen.css
delete mode 100644 3rdparty/fullcalendar/GPL-LICENSE.txt
delete mode 100644 3rdparty/fullcalendar/MIT-LICENSE.txt
delete mode 100644 3rdparty/fullcalendar/css/fullcalendar.css
delete mode 100644 3rdparty/fullcalendar/css/fullcalendar.print.css
delete mode 100644 3rdparty/fullcalendar/js/fullcalendar.js
delete mode 100644 3rdparty/fullcalendar/js/fullcalendar.min.js
delete mode 100644 3rdparty/fullcalendar/js/gcal.js
delete mode 100644 3rdparty/getid3/extension.cache.dbm.php
delete mode 100644 3rdparty/getid3/extension.cache.mysql.php
delete mode 100644 3rdparty/getid3/getid3.lib.php
delete mode 100644 3rdparty/getid3/getid3.php
delete mode 100644 3rdparty/getid3/license.txt
delete mode 100644 3rdparty/getid3/module.archive.gzip.php
delete mode 100644 3rdparty/getid3/module.archive.rar.php
delete mode 100644 3rdparty/getid3/module.archive.szip.php
delete mode 100644 3rdparty/getid3/module.archive.tar.php
delete mode 100644 3rdparty/getid3/module.archive.zip.php
delete mode 100644 3rdparty/getid3/module.audio-video.asf.php
delete mode 100644 3rdparty/getid3/module.audio-video.bink.php
delete mode 100644 3rdparty/getid3/module.audio-video.flv.php
delete mode 100644 3rdparty/getid3/module.audio-video.matroska.php
delete mode 100644 3rdparty/getid3/module.audio-video.mpeg.php
delete mode 100644 3rdparty/getid3/module.audio-video.nsv.php
delete mode 100644 3rdparty/getid3/module.audio-video.quicktime.php
delete mode 100644 3rdparty/getid3/module.audio-video.real.php
delete mode 100644 3rdparty/getid3/module.audio-video.riff.php
delete mode 100644 3rdparty/getid3/module.audio-video.swf.php
delete mode 100644 3rdparty/getid3/module.audio.aa.php
delete mode 100644 3rdparty/getid3/module.audio.aac.php
delete mode 100644 3rdparty/getid3/module.audio.ac3.php
delete mode 100644 3rdparty/getid3/module.audio.au.php
delete mode 100644 3rdparty/getid3/module.audio.avr.php
delete mode 100644 3rdparty/getid3/module.audio.bonk.php
delete mode 100644 3rdparty/getid3/module.audio.dss.php
delete mode 100644 3rdparty/getid3/module.audio.dts.php
delete mode 100644 3rdparty/getid3/module.audio.flac.php
delete mode 100644 3rdparty/getid3/module.audio.la.php
delete mode 100644 3rdparty/getid3/module.audio.lpac.php
delete mode 100644 3rdparty/getid3/module.audio.midi.php
delete mode 100644 3rdparty/getid3/module.audio.mod.php
delete mode 100644 3rdparty/getid3/module.audio.monkey.php
delete mode 100644 3rdparty/getid3/module.audio.mp3.php
delete mode 100644 3rdparty/getid3/module.audio.mpc.php
delete mode 100644 3rdparty/getid3/module.audio.ogg.php
delete mode 100644 3rdparty/getid3/module.audio.optimfrog.php
delete mode 100644 3rdparty/getid3/module.audio.rkau.php
delete mode 100644 3rdparty/getid3/module.audio.shorten.php
delete mode 100644 3rdparty/getid3/module.audio.tta.php
delete mode 100644 3rdparty/getid3/module.audio.voc.php
delete mode 100644 3rdparty/getid3/module.audio.vqf.php
delete mode 100644 3rdparty/getid3/module.audio.wavpack.php
delete mode 100644 3rdparty/getid3/module.graphic.bmp.php
delete mode 100644 3rdparty/getid3/module.graphic.efax.php
delete mode 100644 3rdparty/getid3/module.graphic.gif.php
delete mode 100644 3rdparty/getid3/module.graphic.jpg.php
delete mode 100644 3rdparty/getid3/module.graphic.pcd.php
delete mode 100644 3rdparty/getid3/module.graphic.png.php
delete mode 100644 3rdparty/getid3/module.graphic.svg.php
delete mode 100644 3rdparty/getid3/module.graphic.tiff.php
delete mode 100644 3rdparty/getid3/module.misc.cue.php
delete mode 100644 3rdparty/getid3/module.misc.exe.php
delete mode 100644 3rdparty/getid3/module.misc.iso.php
delete mode 100644 3rdparty/getid3/module.misc.msoffice.php
delete mode 100644 3rdparty/getid3/module.misc.par2.php
delete mode 100644 3rdparty/getid3/module.misc.pdf.php
delete mode 100644 3rdparty/getid3/module.tag.apetag.php
delete mode 100644 3rdparty/getid3/module.tag.id3v1.php
delete mode 100644 3rdparty/getid3/module.tag.id3v2.php
delete mode 100644 3rdparty/getid3/module.tag.lyrics3.php
delete mode 100644 3rdparty/getid3/module.tag.xmp.php
delete mode 100644 3rdparty/getid3/write.apetag.php
delete mode 100644 3rdparty/getid3/write.id3v1.php
delete mode 100644 3rdparty/getid3/write.id3v2.php
delete mode 100644 3rdparty/getid3/write.lyrics3.php
delete mode 100644 3rdparty/getid3/write.metaflac.php
delete mode 100644 3rdparty/getid3/write.php
delete mode 100644 3rdparty/getid3/write.real.php
delete mode 100644 3rdparty/getid3/write.vorbiscomment.php
delete mode 100644 3rdparty/js/chosen/LICENSE.md
delete mode 100644 3rdparty/js/chosen/README.md
delete mode 100644 3rdparty/js/chosen/VERSION
delete mode 100755 3rdparty/js/chosen/chosen.jquery.js
delete mode 100755 3rdparty/js/chosen/chosen.jquery.min.js
delete mode 100644 3rdparty/mediawiki/CSSMin.php
delete mode 100644 3rdparty/mediawiki/JavaScriptMinifier.php
delete mode 100644 3rdparty/miniColors/GPL-LICENSE.txt
delete mode 100644 3rdparty/miniColors/MIT-LICENSE.txt
delete mode 100755 3rdparty/miniColors/css/images/colors.png
delete mode 100755 3rdparty/miniColors/css/images/trigger.png
delete mode 100755 3rdparty/miniColors/css/jquery.miniColors.css
delete mode 100755 3rdparty/miniColors/js/jquery.miniColors.js
delete mode 100755 3rdparty/miniColors/js/jquery.miniColors.min.js
delete mode 100644 3rdparty/openid/class.openid.v3.php
delete mode 100644 3rdparty/openid/phpmyid.php
delete mode 100644 3rdparty/php-cloudfiles/.gitignore
delete mode 100644 3rdparty/php-cloudfiles/AUTHORS
delete mode 100644 3rdparty/php-cloudfiles/COPYING
delete mode 100644 3rdparty/php-cloudfiles/Changelog
delete mode 100644 3rdparty/php-cloudfiles/README
delete mode 100644 3rdparty/php-cloudfiles/cloudfiles.php
delete mode 100644 3rdparty/php-cloudfiles/cloudfiles_exceptions.php
delete mode 100644 3rdparty/php-cloudfiles/cloudfiles_http.php
delete mode 100644 3rdparty/phpass/PasswordHash.php
delete mode 100644 3rdparty/phpass/c/Makefile
delete mode 100644 3rdparty/phpass/c/crypt_private.c
delete mode 100644 3rdparty/phpass/test.php
delete mode 100644 3rdparty/smb4php/smb.php
delete mode 100755 3rdparty/timepicker/GPL-LICENSE.txt
delete mode 100755 3rdparty/timepicker/MIT-LICENSE.txt
delete mode 100755 3rdparty/timepicker/css/include/images/ui-bg_diagonals-thick_18_b81900_40x40.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-bg_diagonals-thick_20_666666_40x40.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-bg_flat_10_000000_40x100.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-bg_glass_100_f6f6f6_1x400.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-bg_glass_100_fdf5ce_1x400.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-bg_glass_65_ffffff_1x400.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-bg_gloss-wave_35_f6a828_500x100.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-bg_highlight-soft_100_eeeeee_1x100.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-bg_highlight-soft_75_ffe45c_1x100.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-icons_222222_256x240.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-icons_228ef1_256x240.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-icons_ef8c08_256x240.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-icons_ffd27a_256x240.png
delete mode 100755 3rdparty/timepicker/css/include/images/ui-icons_ffffff_256x240.png
delete mode 100755 3rdparty/timepicker/css/include/jquery-1.5.1.min.js
delete mode 100755 3rdparty/timepicker/css/include/jquery-ui-1.8.14.custom.css
delete mode 100755 3rdparty/timepicker/css/include/jquery.ui.core.min.js
delete mode 100755 3rdparty/timepicker/css/include/jquery.ui.position.min.js
delete mode 100755 3rdparty/timepicker/css/include/jquery.ui.tabs.min.js
delete mode 100755 3rdparty/timepicker/css/include/jquery.ui.widget.min.js
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_diagonals-thick_18_b81900_40x40.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_diagonals-thick_20_666666_40x40.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_flat_10_000000_40x100.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_100_f6f6f6_1x400.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_100_fdf5ce_1x400.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_glass_65_ffffff_1x400.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_gloss-wave_35_f6a828_500x100.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_highlight-soft_100_eeeeee_1x100.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-bg_highlight-soft_75_ffe45c_1x100.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_222222_256x240.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_228ef1_256x240.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ef8c08_256x240.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ffd27a_256x240.png
delete mode 100755 3rdparty/timepicker/css/include/ui-lightness/images/ui-icons_ffffff_256x240.png
delete mode 100755 3rdparty/timepicker/css/jquery.ui.timepicker.css
delete mode 100755 3rdparty/timepicker/js/i18n/i18n.html
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-cs.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-de.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-es.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-fr.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-hr.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-it.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-ja.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-nl.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-pl.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-pt-BR.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-sl.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-sv.js
delete mode 100755 3rdparty/timepicker/js/i18n/jquery.ui.timepicker-tr.js
delete mode 100755 3rdparty/timepicker/js/jquery.ui.timepicker.js
delete mode 100755 3rdparty/timepicker/releases.txt
diff --git a/3rdparty/Archive/Tar.php b/3rdparty/Archive/Tar.php
deleted file mode 100644
index fd2d5d7d9b..0000000000
--- a/3rdparty/Archive/Tar.php
+++ /dev/null
@@ -1,1973 +0,0 @@
-
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * * Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *
- * @category File_Formats
- * @package Archive_Tar
- * @author Vincent Blavet
- * @copyright 1997-2010 The Authors
- * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Tar.php 324840 2012-04-05 08:44:41Z mrook $
- * @link http://pear.php.net/package/Archive_Tar
- */
-
-require_once 'PEAR.php';
-
-define('ARCHIVE_TAR_ATT_SEPARATOR', 90001);
-define('ARCHIVE_TAR_END_BLOCK', pack("a512", ''));
-
-/**
-* Creates a (compressed) Tar archive
-*
-* @package Archive_Tar
-* @author Vincent Blavet
-* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
-* @version $Revision: 324840 $
-*/
-class Archive_Tar extends PEAR
-{
- /**
- * @var string Name of the Tar
- */
- var $_tarname='';
-
- /**
- * @var boolean if true, the Tar file will be gzipped
- */
- var $_compress=false;
-
- /**
- * @var string Type of compression : 'none', 'gz' or 'bz2'
- */
- var $_compress_type='none';
-
- /**
- * @var string Explode separator
- */
- var $_separator=' ';
-
- /**
- * @var file descriptor
- */
- var $_file=0;
-
- /**
- * @var string Local Tar name of a remote Tar (http:// or ftp://)
- */
- var $_temp_tarname='';
-
- /**
- * @var string regular expression for ignoring files or directories
- */
- var $_ignore_regexp='';
-
- /**
- * @var object PEAR_Error object
- */
- var $error_object=null;
-
- // {{{ constructor
- /**
- * Archive_Tar Class constructor. This flavour of the constructor only
- * declare a new Archive_Tar object, identifying it by the name of the
- * tar file.
- * If the compress argument is set the tar will be read or created as a
- * gzip or bz2 compressed TAR file.
- *
- * @param string $p_tarname The name of the tar archive to create
- * @param string $p_compress can be null, 'gz' or 'bz2'. This
- * parameter indicates if gzip or bz2 compression
- * is required. For compatibility reason the
- * boolean value 'true' means 'gz'.
- *
- * @access public
- */
- function Archive_Tar($p_tarname, $p_compress = null)
- {
- $this->PEAR();
- $this->_compress = false;
- $this->_compress_type = 'none';
- if (($p_compress === null) || ($p_compress == '')) {
- if (@file_exists($p_tarname)) {
- if ($fp = @fopen($p_tarname, "rb")) {
- // look for gzip magic cookie
- $data = fread($fp, 2);
- fclose($fp);
- if ($data == "\37\213") {
- $this->_compress = true;
- $this->_compress_type = 'gz';
- // No sure it's enought for a magic code ....
- } elseif ($data == "BZ") {
- $this->_compress = true;
- $this->_compress_type = 'bz2';
- }
- }
- } else {
- // probably a remote file or some file accessible
- // through a stream interface
- if (substr($p_tarname, -2) == 'gz') {
- $this->_compress = true;
- $this->_compress_type = 'gz';
- } elseif ((substr($p_tarname, -3) == 'bz2') ||
- (substr($p_tarname, -2) == 'bz')) {
- $this->_compress = true;
- $this->_compress_type = 'bz2';
- }
- }
- } else {
- if (($p_compress === true) || ($p_compress == 'gz')) {
- $this->_compress = true;
- $this->_compress_type = 'gz';
- } else if ($p_compress == 'bz2') {
- $this->_compress = true;
- $this->_compress_type = 'bz2';
- } else {
- $this->_error("Unsupported compression type '$p_compress'\n".
- "Supported types are 'gz' and 'bz2'.\n");
- return false;
- }
- }
- $this->_tarname = $p_tarname;
- if ($this->_compress) { // assert zlib or bz2 extension support
- if ($this->_compress_type == 'gz')
- $extname = 'zlib';
- else if ($this->_compress_type == 'bz2')
- $extname = 'bz2';
-
- if (!extension_loaded($extname)) {
- PEAR::loadExtension($extname);
- }
- if (!extension_loaded($extname)) {
- $this->_error("The extension '$extname' couldn't be found.\n".
- "Please make sure your version of PHP was built ".
- "with '$extname' support.\n");
- return false;
- }
- }
- }
- // }}}
-
- // {{{ destructor
- function _Archive_Tar()
- {
- $this->_close();
- // ----- Look for a local copy to delete
- if ($this->_temp_tarname != '')
- @unlink($this->_temp_tarname);
- $this->_PEAR();
- }
- // }}}
-
- // {{{ create()
- /**
- * This method creates the archive file and add the files / directories
- * that are listed in $p_filelist.
- * If a file with the same name exist and is writable, it is replaced
- * by the new tar.
- * The method return false and a PEAR error text.
- * The $p_filelist parameter can be an array of string, each string
- * representing a filename or a directory name with their path if
- * needed. It can also be a single string with names separated by a
- * single blank.
- * For each directory added in the archive, the files and
- * sub-directories are also added.
- * See also createModify() method for more details.
- *
- * @param array $p_filelist An array of filenames and directory names, or a
- * single string with names separated by a single
- * blank space.
- *
- * @return true on success, false on error.
- * @see createModify()
- * @access public
- */
- function create($p_filelist)
- {
- return $this->createModify($p_filelist, '', '');
- }
- // }}}
-
- // {{{ add()
- /**
- * This method add the files / directories that are listed in $p_filelist in
- * the archive. If the archive does not exist it is created.
- * The method return false and a PEAR error text.
- * The files and directories listed are only added at the end of the archive,
- * even if a file with the same name is already archived.
- * See also createModify() method for more details.
- *
- * @param array $p_filelist An array of filenames and directory names, or a
- * single string with names separated by a single
- * blank space.
- *
- * @return true on success, false on error.
- * @see createModify()
- * @access public
- */
- function add($p_filelist)
- {
- return $this->addModify($p_filelist, '', '');
- }
- // }}}
-
- // {{{ extract()
- function extract($p_path='', $p_preserve=false)
- {
- return $this->extractModify($p_path, '', $p_preserve);
- }
- // }}}
-
- // {{{ listContent()
- function listContent()
- {
- $v_list_detail = array();
-
- if ($this->_openRead()) {
- if (!$this->_extractList('', $v_list_detail, "list", '', '')) {
- unset($v_list_detail);
- $v_list_detail = 0;
- }
- $this->_close();
- }
-
- return $v_list_detail;
- }
- // }}}
-
- // {{{ createModify()
- /**
- * This method creates the archive file and add the files / directories
- * that are listed in $p_filelist.
- * If the file already exists and is writable, it is replaced by the
- * new tar. It is a create and not an add. If the file exists and is
- * read-only or is a directory it is not replaced. The method return
- * false and a PEAR error text.
- * The $p_filelist parameter can be an array of string, each string
- * representing a filename or a directory name with their path if
- * needed. It can also be a single string with names separated by a
- * single blank.
- * The path indicated in $p_remove_dir will be removed from the
- * memorized path of each file / directory listed when this path
- * exists. By default nothing is removed (empty path '')
- * The path indicated in $p_add_dir will be added at the beginning of
- * the memorized path of each file / directory listed. However it can
- * be set to empty ''. The adding of a path is done after the removing
- * of path.
- * The path add/remove ability enables the user to prepare an archive
- * for extraction in a different path than the origin files are.
- * See also addModify() method for file adding properties.
- *
- * @param array $p_filelist An array of filenames and directory names,
- * or a single string with names separated by
- * a single blank space.
- * @param string $p_add_dir A string which contains a path to be added
- * to the memorized path of each element in
- * the list.
- * @param string $p_remove_dir A string which contains a path to be
- * removed from the memorized path of each
- * element in the list, when relevant.
- *
- * @return boolean true on success, false on error.
- * @access public
- * @see addModify()
- */
- function createModify($p_filelist, $p_add_dir, $p_remove_dir='')
- {
- $v_result = true;
-
- if (!$this->_openWrite())
- return false;
-
- if ($p_filelist != '') {
- if (is_array($p_filelist))
- $v_list = $p_filelist;
- elseif (is_string($p_filelist))
- $v_list = explode($this->_separator, $p_filelist);
- else {
- $this->_cleanFile();
- $this->_error('Invalid file list');
- return false;
- }
-
- $v_result = $this->_addList($v_list, $p_add_dir, $p_remove_dir);
- }
-
- if ($v_result) {
- $this->_writeFooter();
- $this->_close();
- } else
- $this->_cleanFile();
-
- return $v_result;
- }
- // }}}
-
- // {{{ addModify()
- /**
- * This method add the files / directories listed in $p_filelist at the
- * end of the existing archive. If the archive does not yet exists it
- * is created.
- * The $p_filelist parameter can be an array of string, each string
- * representing a filename or a directory name with their path if
- * needed. It can also be a single string with names separated by a
- * single blank.
- * The path indicated in $p_remove_dir will be removed from the
- * memorized path of each file / directory listed when this path
- * exists. By default nothing is removed (empty path '')
- * The path indicated in $p_add_dir will be added at the beginning of
- * the memorized path of each file / directory listed. However it can
- * be set to empty ''. The adding of a path is done after the removing
- * of path.
- * The path add/remove ability enables the user to prepare an archive
- * for extraction in a different path than the origin files are.
- * If a file/dir is already in the archive it will only be added at the
- * end of the archive. There is no update of the existing archived
- * file/dir. However while extracting the archive, the last file will
- * replace the first one. This results in a none optimization of the
- * archive size.
- * If a file/dir does not exist the file/dir is ignored. However an
- * error text is send to PEAR error.
- * If a file/dir is not readable the file/dir is ignored. However an
- * error text is send to PEAR error.
- *
- * @param array $p_filelist An array of filenames and directory
- * names, or a single string with names
- * separated by a single blank space.
- * @param string $p_add_dir A string which contains a path to be
- * added to the memorized path of each
- * element in the list.
- * @param string $p_remove_dir A string which contains a path to be
- * removed from the memorized path of
- * each element in the list, when
- * relevant.
- *
- * @return true on success, false on error.
- * @access public
- */
- function addModify($p_filelist, $p_add_dir, $p_remove_dir='')
- {
- $v_result = true;
-
- if (!$this->_isArchive())
- $v_result = $this->createModify($p_filelist, $p_add_dir,
- $p_remove_dir);
- else {
- if (is_array($p_filelist))
- $v_list = $p_filelist;
- elseif (is_string($p_filelist))
- $v_list = explode($this->_separator, $p_filelist);
- else {
- $this->_error('Invalid file list');
- return false;
- }
-
- $v_result = $this->_append($v_list, $p_add_dir, $p_remove_dir);
- }
-
- return $v_result;
- }
- // }}}
-
- // {{{ addString()
- /**
- * This method add a single string as a file at the
- * end of the existing archive. If the archive does not yet exists it
- * is created.
- *
- * @param string $p_filename A string which contains the full
- * filename path that will be associated
- * with the string.
- * @param string $p_string The content of the file added in
- * the archive.
- *
- * @return true on success, false on error.
- * @access public
- */
- function addString($p_filename, $p_string)
- {
- $v_result = true;
-
- if (!$this->_isArchive()) {
- if (!$this->_openWrite()) {
- return false;
- }
- $this->_close();
- }
-
- if (!$this->_openAppend())
- return false;
-
- // Need to check the get back to the temporary file ? ....
- $v_result = $this->_addString($p_filename, $p_string);
-
- $this->_writeFooter();
-
- $this->_close();
-
- return $v_result;
- }
- // }}}
-
- // {{{ extractModify()
- /**
- * This method extract all the content of the archive in the directory
- * indicated by $p_path. When relevant the memorized path of the
- * files/dir can be modified by removing the $p_remove_path path at the
- * beginning of the file/dir path.
- * While extracting a file, if the directory path does not exists it is
- * created.
- * While extracting a file, if the file already exists it is replaced
- * without looking for last modification date.
- * While extracting a file, if the file already exists and is write
- * protected, the extraction is aborted.
- * While extracting a file, if a directory with the same name already
- * exists, the extraction is aborted.
- * While extracting a directory, if a file with the same name already
- * exists, the extraction is aborted.
- * While extracting a file/directory if the destination directory exist
- * and is write protected, or does not exist but can not be created,
- * the extraction is aborted.
- * If after extraction an extracted file does not show the correct
- * stored file size, the extraction is aborted.
- * When the extraction is aborted, a PEAR error text is set and false
- * is returned. However the result can be a partial extraction that may
- * need to be manually cleaned.
- *
- * @param string $p_path The path of the directory where the
- * files/dir need to by extracted.
- * @param string $p_remove_path Part of the memorized path that can be
- * removed if present at the beginning of
- * the file/dir path.
- * @param boolean $p_preserve Preserve user/group ownership of files
- *
- * @return boolean true on success, false on error.
- * @access public
- * @see extractList()
- */
- function extractModify($p_path, $p_remove_path, $p_preserve=false)
- {
- $v_result = true;
- $v_list_detail = array();
-
- if ($v_result = $this->_openRead()) {
- $v_result = $this->_extractList($p_path, $v_list_detail,
- "complete", 0, $p_remove_path, $p_preserve);
- $this->_close();
- }
-
- return $v_result;
- }
- // }}}
-
- // {{{ extractInString()
- /**
- * This method extract from the archive one file identified by $p_filename.
- * The return value is a string with the file content, or NULL on error.
- *
- * @param string $p_filename The path of the file to extract in a string.
- *
- * @return a string with the file content or NULL.
- * @access public
- */
- function extractInString($p_filename)
- {
- if ($this->_openRead()) {
- $v_result = $this->_extractInString($p_filename);
- $this->_close();
- } else {
- $v_result = null;
- }
-
- return $v_result;
- }
- // }}}
-
- // {{{ extractList()
- /**
- * This method extract from the archive only the files indicated in the
- * $p_filelist. These files are extracted in the current directory or
- * in the directory indicated by the optional $p_path parameter.
- * If indicated the $p_remove_path can be used in the same way as it is
- * used in extractModify() method.
- *
- * @param array $p_filelist An array of filenames and directory names,
- * or a single string with names separated
- * by a single blank space.
- * @param string $p_path The path of the directory where the
- * files/dir need to by extracted.
- * @param string $p_remove_path Part of the memorized path that can be
- * removed if present at the beginning of
- * the file/dir path.
- * @param boolean $p_preserve Preserve user/group ownership of files
- *
- * @return true on success, false on error.
- * @access public
- * @see extractModify()
- */
- function extractList($p_filelist, $p_path='', $p_remove_path='', $p_preserve=false)
- {
- $v_result = true;
- $v_list_detail = array();
-
- if (is_array($p_filelist))
- $v_list = $p_filelist;
- elseif (is_string($p_filelist))
- $v_list = explode($this->_separator, $p_filelist);
- else {
- $this->_error('Invalid string list');
- return false;
- }
-
- if ($v_result = $this->_openRead()) {
- $v_result = $this->_extractList($p_path, $v_list_detail, "partial",
- $v_list, $p_remove_path, $p_preserve);
- $this->_close();
- }
-
- return $v_result;
- }
- // }}}
-
- // {{{ setAttribute()
- /**
- * This method set specific attributes of the archive. It uses a variable
- * list of parameters, in the format attribute code + attribute values :
- * $arch->setAttribute(ARCHIVE_TAR_ATT_SEPARATOR, ',');
- *
- * @param mixed $argv variable list of attributes and values
- *
- * @return true on success, false on error.
- * @access public
- */
- function setAttribute()
- {
- $v_result = true;
-
- // ----- Get the number of variable list of arguments
- if (($v_size = func_num_args()) == 0) {
- return true;
- }
-
- // ----- Get the arguments
- $v_att_list = &func_get_args();
-
- // ----- Read the attributes
- $i=0;
- while ($i<$v_size) {
-
- // ----- Look for next option
- switch ($v_att_list[$i]) {
- // ----- Look for options that request a string value
- case ARCHIVE_TAR_ATT_SEPARATOR :
- // ----- Check the number of parameters
- if (($i+1) >= $v_size) {
- $this->_error('Invalid number of parameters for '
- .'attribute ARCHIVE_TAR_ATT_SEPARATOR');
- return false;
- }
-
- // ----- Get the value
- $this->_separator = $v_att_list[$i+1];
- $i++;
- break;
-
- default :
- $this->_error('Unknow attribute code '.$v_att_list[$i].'');
- return false;
- }
-
- // ----- Next attribute
- $i++;
- }
-
- return $v_result;
- }
- // }}}
-
- // {{{ setIgnoreRegexp()
- /**
- * This method sets the regular expression for ignoring files and directories
- * at import, for example:
- * $arch->setIgnoreRegexp("#CVS|\.svn#");
- *
- * @param string $regexp regular expression defining which files or directories to ignore
- *
- * @access public
- */
- function setIgnoreRegexp($regexp)
- {
- $this->_ignore_regexp = $regexp;
- }
- // }}}
-
- // {{{ setIgnoreList()
- /**
- * This method sets the regular expression for ignoring all files and directories
- * matching the filenames in the array list at import, for example:
- * $arch->setIgnoreList(array('CVS', '.svn', 'bin/tool'));
- *
- * @param array $list a list of file or directory names to ignore
- *
- * @access public
- */
- function setIgnoreList($list)
- {
- $regexp = str_replace(array('#', '.', '^', '$'), array('\#', '\.', '\^', '\$'), $list);
- $regexp = '#/'.join('$|/', $list).'#';
- $this->setIgnoreRegexp($regexp);
- }
- // }}}
-
- // {{{ _error()
- function _error($p_message)
- {
- $this->error_object = &$this->raiseError($p_message);
- }
- // }}}
-
- // {{{ _warning()
- function _warning($p_message)
- {
- $this->error_object = &$this->raiseError($p_message);
- }
- // }}}
-
- // {{{ _isArchive()
- function _isArchive($p_filename=null)
- {
- if ($p_filename == null) {
- $p_filename = $this->_tarname;
- }
- clearstatcache();
- return @is_file($p_filename) && !@is_link($p_filename);
- }
- // }}}
-
- // {{{ _openWrite()
- function _openWrite()
- {
- if ($this->_compress_type == 'gz' && function_exists('gzopen'))
- $this->_file = @gzopen($this->_tarname, "wb9");
- else if ($this->_compress_type == 'bz2' && function_exists('bzopen'))
- $this->_file = @bzopen($this->_tarname, "w");
- else if ($this->_compress_type == 'none')
- $this->_file = @fopen($this->_tarname, "wb");
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
-
- if ($this->_file == 0) {
- $this->_error('Unable to open in write mode \''
- .$this->_tarname.'\'');
- return false;
- }
-
- return true;
- }
- // }}}
-
- // {{{ _openRead()
- function _openRead()
- {
- if (strtolower(substr($this->_tarname, 0, 7)) == 'http://') {
-
- // ----- Look if a local copy need to be done
- if ($this->_temp_tarname == '') {
- $this->_temp_tarname = uniqid('tar').'.tmp';
- if (!$v_file_from = @fopen($this->_tarname, 'rb')) {
- $this->_error('Unable to open in read mode \''
- .$this->_tarname.'\'');
- $this->_temp_tarname = '';
- return false;
- }
- if (!$v_file_to = @fopen($this->_temp_tarname, 'wb')) {
- $this->_error('Unable to open in write mode \''
- .$this->_temp_tarname.'\'');
- $this->_temp_tarname = '';
- return false;
- }
- while ($v_data = @fread($v_file_from, 1024))
- @fwrite($v_file_to, $v_data);
- @fclose($v_file_from);
- @fclose($v_file_to);
- }
-
- // ----- File to open if the local copy
- $v_filename = $this->_temp_tarname;
-
- } else
- // ----- File to open if the normal Tar file
- $v_filename = $this->_tarname;
-
- if ($this->_compress_type == 'gz')
- $this->_file = @gzopen($v_filename, "rb");
- else if ($this->_compress_type == 'bz2')
- $this->_file = @bzopen($v_filename, "r");
- else if ($this->_compress_type == 'none')
- $this->_file = @fopen($v_filename, "rb");
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
-
- if ($this->_file == 0) {
- $this->_error('Unable to open in read mode \''.$v_filename.'\'');
- return false;
- }
-
- return true;
- }
- // }}}
-
- // {{{ _openReadWrite()
- function _openReadWrite()
- {
- if ($this->_compress_type == 'gz')
- $this->_file = @gzopen($this->_tarname, "r+b");
- else if ($this->_compress_type == 'bz2') {
- $this->_error('Unable to open bz2 in read/write mode \''
- .$this->_tarname.'\' (limitation of bz2 extension)');
- return false;
- } else if ($this->_compress_type == 'none')
- $this->_file = @fopen($this->_tarname, "r+b");
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
-
- if ($this->_file == 0) {
- $this->_error('Unable to open in read/write mode \''
- .$this->_tarname.'\'');
- return false;
- }
-
- return true;
- }
- // }}}
-
- // {{{ _close()
- function _close()
- {
- //if (isset($this->_file)) {
- if (is_resource($this->_file)) {
- if ($this->_compress_type == 'gz')
- @gzclose($this->_file);
- else if ($this->_compress_type == 'bz2')
- @bzclose($this->_file);
- else if ($this->_compress_type == 'none')
- @fclose($this->_file);
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
-
- $this->_file = 0;
- }
-
- // ----- Look if a local copy need to be erase
- // Note that it might be interesting to keep the url for a time : ToDo
- if ($this->_temp_tarname != '') {
- @unlink($this->_temp_tarname);
- $this->_temp_tarname = '';
- }
-
- return true;
- }
- // }}}
-
- // {{{ _cleanFile()
- function _cleanFile()
- {
- $this->_close();
-
- // ----- Look for a local copy
- if ($this->_temp_tarname != '') {
- // ----- Remove the local copy but not the remote tarname
- @unlink($this->_temp_tarname);
- $this->_temp_tarname = '';
- } else {
- // ----- Remove the local tarname file
- @unlink($this->_tarname);
- }
- $this->_tarname = '';
-
- return true;
- }
- // }}}
-
- // {{{ _writeBlock()
- function _writeBlock($p_binary_data, $p_len=null)
- {
- if (is_resource($this->_file)) {
- if ($p_len === null) {
- if ($this->_compress_type == 'gz')
- @gzputs($this->_file, $p_binary_data);
- else if ($this->_compress_type == 'bz2')
- @bzwrite($this->_file, $p_binary_data);
- else if ($this->_compress_type == 'none')
- @fputs($this->_file, $p_binary_data);
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
- } else {
- if ($this->_compress_type == 'gz')
- @gzputs($this->_file, $p_binary_data, $p_len);
- else if ($this->_compress_type == 'bz2')
- @bzwrite($this->_file, $p_binary_data, $p_len);
- else if ($this->_compress_type == 'none')
- @fputs($this->_file, $p_binary_data, $p_len);
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
-
- }
- }
- return true;
- }
- // }}}
-
- // {{{ _readBlock()
- function _readBlock()
- {
- $v_block = null;
- if (is_resource($this->_file)) {
- if ($this->_compress_type == 'gz')
- $v_block = @gzread($this->_file, 512);
- else if ($this->_compress_type == 'bz2')
- $v_block = @bzread($this->_file, 512);
- else if ($this->_compress_type == 'none')
- $v_block = @fread($this->_file, 512);
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
- }
- return $v_block;
- }
- // }}}
-
- // {{{ _jumpBlock()
- function _jumpBlock($p_len=null)
- {
- if (is_resource($this->_file)) {
- if ($p_len === null)
- $p_len = 1;
-
- if ($this->_compress_type == 'gz') {
- @gzseek($this->_file, gztell($this->_file)+($p_len*512));
- }
- else if ($this->_compress_type == 'bz2') {
- // ----- Replace missing bztell() and bzseek()
- for ($i=0; $i<$p_len; $i++)
- $this->_readBlock();
- } else if ($this->_compress_type == 'none')
- @fseek($this->_file, $p_len*512, SEEK_CUR);
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
-
- }
- return true;
- }
- // }}}
-
- // {{{ _writeFooter()
- function _writeFooter()
- {
- if (is_resource($this->_file)) {
- // ----- Write the last 0 filled block for end of archive
- $v_binary_data = pack('a1024', '');
- $this->_writeBlock($v_binary_data);
- }
- return true;
- }
- // }}}
-
- // {{{ _addList()
- function _addList($p_list, $p_add_dir, $p_remove_dir)
- {
- $v_result=true;
- $v_header = array();
-
- // ----- Remove potential windows directory separator
- $p_add_dir = $this->_translateWinPath($p_add_dir);
- $p_remove_dir = $this->_translateWinPath($p_remove_dir, false);
-
- if (!$this->_file) {
- $this->_error('Invalid file descriptor');
- return false;
- }
-
- if (sizeof($p_list) == 0)
- return true;
-
- foreach ($p_list as $v_filename) {
- if (!$v_result) {
- break;
- }
-
- // ----- Skip the current tar name
- if ($v_filename == $this->_tarname)
- continue;
-
- if ($v_filename == '')
- continue;
-
- // ----- ignore files and directories matching the ignore regular expression
- if ($this->_ignore_regexp && preg_match($this->_ignore_regexp, '/'.$v_filename)) {
- $this->_warning("File '$v_filename' ignored");
- continue;
- }
-
- if (!file_exists($v_filename) && !is_link($v_filename)) {
- $this->_warning("File '$v_filename' does not exist");
- continue;
- }
-
- // ----- Add the file or directory header
- if (!$this->_addFile($v_filename, $v_header, $p_add_dir, $p_remove_dir))
- return false;
-
- if (@is_dir($v_filename) && !@is_link($v_filename)) {
- if (!($p_hdir = opendir($v_filename))) {
- $this->_warning("Directory '$v_filename' can not be read");
- continue;
- }
- while (false !== ($p_hitem = readdir($p_hdir))) {
- if (($p_hitem != '.') && ($p_hitem != '..')) {
- if ($v_filename != ".")
- $p_temp_list[0] = $v_filename.'/'.$p_hitem;
- else
- $p_temp_list[0] = $p_hitem;
-
- $v_result = $this->_addList($p_temp_list,
- $p_add_dir,
- $p_remove_dir);
- }
- }
-
- unset($p_temp_list);
- unset($p_hdir);
- unset($p_hitem);
- }
- }
-
- return $v_result;
- }
- // }}}
-
- // {{{ _addFile()
- function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir, $v_stored_filename=null)
- {
- if (!$this->_file) {
- $this->_error('Invalid file descriptor');
- return false;
- }
-
- if ($p_filename == '') {
- $this->_error('Invalid file name');
- return false;
- }
-
- // ownCloud change to make it possible to specify the filename to use
- if(is_null($v_stored_filename)) {
- // ----- Calculate the stored filename
- $p_filename = $this->_translateWinPath($p_filename, false);
- $v_stored_filename = $p_filename;
- if (strcmp($p_filename, $p_remove_dir) == 0) {
- return true;
- }
- if ($p_remove_dir != '') {
- if (substr($p_remove_dir, -1) != '/')
- $p_remove_dir .= '/';
-
- if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir)
- $v_stored_filename = substr($p_filename, strlen($p_remove_dir));
- }
- $v_stored_filename = $this->_translateWinPath($v_stored_filename);
- if ($p_add_dir != '') {
- if (substr($p_add_dir, -1) == '/')
- $v_stored_filename = $p_add_dir.$v_stored_filename;
- else
- $v_stored_filename = $p_add_dir.'/'.$v_stored_filename;
- }
-
- $v_stored_filename = $this->_pathReduction($v_stored_filename);
- }
-
- if ($this->_isArchive($p_filename)) {
- if (($v_file = @fopen($p_filename, "rb")) == 0) {
- $this->_warning("Unable to open file '".$p_filename
- ."' in binary read mode");
- return true;
- }
-
- if (!$this->_writeHeader($p_filename, $v_stored_filename))
- return false;
-
- while (($v_buffer = fread($v_file, 512)) != '') {
- $v_binary_data = pack("a512", "$v_buffer");
- $this->_writeBlock($v_binary_data);
- }
-
- fclose($v_file);
-
- } else {
- // ----- Only header for dir
- if (!$this->_writeHeader($p_filename, $v_stored_filename))
- return false;
- }
-
- return true;
- }
- // }}}
-
- // {{{ _addString()
- function _addString($p_filename, $p_string)
- {
- if (!$this->_file) {
- $this->_error('Invalid file descriptor');
- return false;
- }
-
- if ($p_filename == '') {
- $this->_error('Invalid file name');
- return false;
- }
-
- // ----- Calculate the stored filename
- $p_filename = $this->_translateWinPath($p_filename, false);;
-
- if (!$this->_writeHeaderBlock($p_filename, strlen($p_string),
- time(), 384, "", 0, 0))
- return false;
-
- $i=0;
- while (($v_buffer = substr($p_string, (($i++)*512), 512)) != '') {
- $v_binary_data = pack("a512", $v_buffer);
- $this->_writeBlock($v_binary_data);
- }
-
- return true;
- }
- // }}}
-
- // {{{ _writeHeader()
- function _writeHeader($p_filename, $p_stored_filename)
- {
- if ($p_stored_filename == '')
- $p_stored_filename = $p_filename;
- $v_reduce_filename = $this->_pathReduction($p_stored_filename);
-
- if (strlen($v_reduce_filename) > 99) {
- if (!$this->_writeLongHeader($v_reduce_filename))
- return false;
- }
-
- $v_info = lstat($p_filename);
- $v_uid = sprintf("%07s", DecOct($v_info[4]));
- $v_gid = sprintf("%07s", DecOct($v_info[5]));
- $v_perms = sprintf("%07s", DecOct($v_info['mode'] & 000777));
-
- $v_mtime = sprintf("%011s", DecOct($v_info['mtime']));
-
- $v_linkname = '';
-
- if (@is_link($p_filename)) {
- $v_typeflag = '2';
- $v_linkname = readlink($p_filename);
- $v_size = sprintf("%011s", DecOct(0));
- } elseif (@is_dir($p_filename)) {
- $v_typeflag = "5";
- $v_size = sprintf("%011s", DecOct(0));
- } else {
- $v_typeflag = '0';
- clearstatcache();
- $v_size = sprintf("%011s", DecOct($v_info['size']));
- }
-
- $v_magic = 'ustar ';
-
- $v_version = ' ';
-
- if (function_exists('posix_getpwuid'))
- {
- $userinfo = posix_getpwuid($v_info[4]);
- $groupinfo = posix_getgrgid($v_info[5]);
-
- $v_uname = $userinfo['name'];
- $v_gname = $groupinfo['name'];
- }
- else
- {
- $v_uname = '';
- $v_gname = '';
- }
-
- $v_devmajor = '';
-
- $v_devminor = '';
-
- $v_prefix = '';
-
- $v_binary_data_first = pack("a100a8a8a8a12a12",
- $v_reduce_filename, $v_perms, $v_uid,
- $v_gid, $v_size, $v_mtime);
- $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
- $v_typeflag, $v_linkname, $v_magic,
- $v_version, $v_uname, $v_gname,
- $v_devmajor, $v_devminor, $v_prefix, '');
-
- // ----- Calculate the checksum
- $v_checksum = 0;
- // ..... First part of the header
- for ($i=0; $i<148; $i++)
- $v_checksum += ord(substr($v_binary_data_first,$i,1));
- // ..... Ignore the checksum value and replace it by ' ' (space)
- for ($i=148; $i<156; $i++)
- $v_checksum += ord(' ');
- // ..... Last part of the header
- for ($i=156, $j=0; $i<512; $i++, $j++)
- $v_checksum += ord(substr($v_binary_data_last,$j,1));
-
- // ----- Write the first 148 bytes of the header in the archive
- $this->_writeBlock($v_binary_data_first, 148);
-
- // ----- Write the calculated checksum
- $v_checksum = sprintf("%06s ", DecOct($v_checksum));
- $v_binary_data = pack("a8", $v_checksum);
- $this->_writeBlock($v_binary_data, 8);
-
- // ----- Write the last 356 bytes of the header in the archive
- $this->_writeBlock($v_binary_data_last, 356);
-
- return true;
- }
- // }}}
-
- // {{{ _writeHeaderBlock()
- function _writeHeaderBlock($p_filename, $p_size, $p_mtime=0, $p_perms=0,
- $p_type='', $p_uid=0, $p_gid=0)
- {
- $p_filename = $this->_pathReduction($p_filename);
-
- if (strlen($p_filename) > 99) {
- if (!$this->_writeLongHeader($p_filename))
- return false;
- }
-
- if ($p_type == "5") {
- $v_size = sprintf("%011s", DecOct(0));
- } else {
- $v_size = sprintf("%011s", DecOct($p_size));
- }
-
- $v_uid = sprintf("%07s", DecOct($p_uid));
- $v_gid = sprintf("%07s", DecOct($p_gid));
- $v_perms = sprintf("%07s", DecOct($p_perms & 000777));
-
- $v_mtime = sprintf("%11s", DecOct($p_mtime));
-
- $v_linkname = '';
-
- $v_magic = 'ustar ';
-
- $v_version = ' ';
-
- if (function_exists('posix_getpwuid'))
- {
- $userinfo = posix_getpwuid($p_uid);
- $groupinfo = posix_getgrgid($p_gid);
-
- $v_uname = $userinfo['name'];
- $v_gname = $groupinfo['name'];
- }
- else
- {
- $v_uname = '';
- $v_gname = '';
- }
-
- $v_devmajor = '';
-
- $v_devminor = '';
-
- $v_prefix = '';
-
- $v_binary_data_first = pack("a100a8a8a8a12A12",
- $p_filename, $v_perms, $v_uid, $v_gid,
- $v_size, $v_mtime);
- $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
- $p_type, $v_linkname, $v_magic,
- $v_version, $v_uname, $v_gname,
- $v_devmajor, $v_devminor, $v_prefix, '');
-
- // ----- Calculate the checksum
- $v_checksum = 0;
- // ..... First part of the header
- for ($i=0; $i<148; $i++)
- $v_checksum += ord(substr($v_binary_data_first,$i,1));
- // ..... Ignore the checksum value and replace it by ' ' (space)
- for ($i=148; $i<156; $i++)
- $v_checksum += ord(' ');
- // ..... Last part of the header
- for ($i=156, $j=0; $i<512; $i++, $j++)
- $v_checksum += ord(substr($v_binary_data_last,$j,1));
-
- // ----- Write the first 148 bytes of the header in the archive
- $this->_writeBlock($v_binary_data_first, 148);
-
- // ----- Write the calculated checksum
- $v_checksum = sprintf("%06s ", DecOct($v_checksum));
- $v_binary_data = pack("a8", $v_checksum);
- $this->_writeBlock($v_binary_data, 8);
-
- // ----- Write the last 356 bytes of the header in the archive
- $this->_writeBlock($v_binary_data_last, 356);
-
- return true;
- }
- // }}}
-
- // {{{ _writeLongHeader()
- function _writeLongHeader($p_filename)
- {
- $v_size = sprintf("%11s ", DecOct(strlen($p_filename)));
-
- $v_typeflag = 'L';
-
- $v_linkname = '';
-
- $v_magic = '';
-
- $v_version = '';
-
- $v_uname = '';
-
- $v_gname = '';
-
- $v_devmajor = '';
-
- $v_devminor = '';
-
- $v_prefix = '';
-
- $v_binary_data_first = pack("a100a8a8a8a12a12",
- '././@LongLink', 0, 0, 0, $v_size, 0);
- $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12",
- $v_typeflag, $v_linkname, $v_magic,
- $v_version, $v_uname, $v_gname,
- $v_devmajor, $v_devminor, $v_prefix, '');
-
- // ----- Calculate the checksum
- $v_checksum = 0;
- // ..... First part of the header
- for ($i=0; $i<148; $i++)
- $v_checksum += ord(substr($v_binary_data_first,$i,1));
- // ..... Ignore the checksum value and replace it by ' ' (space)
- for ($i=148; $i<156; $i++)
- $v_checksum += ord(' ');
- // ..... Last part of the header
- for ($i=156, $j=0; $i<512; $i++, $j++)
- $v_checksum += ord(substr($v_binary_data_last,$j,1));
-
- // ----- Write the first 148 bytes of the header in the archive
- $this->_writeBlock($v_binary_data_first, 148);
-
- // ----- Write the calculated checksum
- $v_checksum = sprintf("%06s ", DecOct($v_checksum));
- $v_binary_data = pack("a8", $v_checksum);
- $this->_writeBlock($v_binary_data, 8);
-
- // ----- Write the last 356 bytes of the header in the archive
- $this->_writeBlock($v_binary_data_last, 356);
-
- // ----- Write the filename as content of the block
- $i=0;
- while (($v_buffer = substr($p_filename, (($i++)*512), 512)) != '') {
- $v_binary_data = pack("a512", "$v_buffer");
- $this->_writeBlock($v_binary_data);
- }
-
- return true;
- }
- // }}}
-
- // {{{ _readHeader()
- function _readHeader($v_binary_data, &$v_header)
- {
- if (strlen($v_binary_data)==0) {
- $v_header['filename'] = '';
- return true;
- }
-
- if (strlen($v_binary_data) != 512) {
- $v_header['filename'] = '';
- $this->_error('Invalid block size : '.strlen($v_binary_data));
- return false;
- }
-
- if (!is_array($v_header)) {
- $v_header = array();
- }
- // ----- Calculate the checksum
- $v_checksum = 0;
- // ..... First part of the header
- for ($i=0; $i<148; $i++)
- $v_checksum+=ord(substr($v_binary_data,$i,1));
- // ..... Ignore the checksum value and replace it by ' ' (space)
- for ($i=148; $i<156; $i++)
- $v_checksum += ord(' ');
- // ..... Last part of the header
- for ($i=156; $i<512; $i++)
- $v_checksum+=ord(substr($v_binary_data,$i,1));
-
- $v_data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/" .
- "a8checksum/a1typeflag/a100link/a6magic/a2version/" .
- "a32uname/a32gname/a8devmajor/a8devminor/a131prefix",
- $v_binary_data);
-
- if (strlen($v_data["prefix"]) > 0) {
- $v_data["filename"] = "$v_data[prefix]/$v_data[filename]";
- }
-
- // ----- Extract the checksum
- $v_header['checksum'] = OctDec(trim($v_data['checksum']));
- if ($v_header['checksum'] != $v_checksum) {
- $v_header['filename'] = '';
-
- // ----- Look for last block (empty block)
- if (($v_checksum == 256) && ($v_header['checksum'] == 0))
- return true;
-
- $this->_error('Invalid checksum for file "'.$v_data['filename']
- .'" : '.$v_checksum.' calculated, '
- .$v_header['checksum'].' expected');
- return false;
- }
-
- // ----- Extract the properties
- $v_header['filename'] = $v_data['filename'];
- if ($this->_maliciousFilename($v_header['filename'])) {
- $this->_error('Malicious .tar detected, file "' . $v_header['filename'] .
- '" will not install in desired directory tree');
- return false;
- }
- $v_header['mode'] = OctDec(trim($v_data['mode']));
- $v_header['uid'] = OctDec(trim($v_data['uid']));
- $v_header['gid'] = OctDec(trim($v_data['gid']));
- $v_header['size'] = OctDec(trim($v_data['size']));
- $v_header['mtime'] = OctDec(trim($v_data['mtime']));
- if (($v_header['typeflag'] = $v_data['typeflag']) == "5") {
- $v_header['size'] = 0;
- }
- $v_header['link'] = trim($v_data['link']);
- /* ----- All these fields are removed form the header because
- they do not carry interesting info
- $v_header[magic] = trim($v_data[magic]);
- $v_header[version] = trim($v_data[version]);
- $v_header[uname] = trim($v_data[uname]);
- $v_header[gname] = trim($v_data[gname]);
- $v_header[devmajor] = trim($v_data[devmajor]);
- $v_header[devminor] = trim($v_data[devminor]);
- */
-
- return true;
- }
- // }}}
-
- // {{{ _maliciousFilename()
- /**
- * Detect and report a malicious file name
- *
- * @param string $file
- *
- * @return bool
- * @access private
- */
- function _maliciousFilename($file)
- {
- if (strpos($file, '/../') !== false) {
- return true;
- }
- if (strpos($file, '../') === 0) {
- return true;
- }
- return false;
- }
- // }}}
-
- // {{{ _readLongHeader()
- function _readLongHeader(&$v_header)
- {
- $v_filename = '';
- $n = floor($v_header['size']/512);
- for ($i=0; $i<$n; $i++) {
- $v_content = $this->_readBlock();
- $v_filename .= $v_content;
- }
- if (($v_header['size'] % 512) != 0) {
- $v_content = $this->_readBlock();
- $v_filename .= trim($v_content);
- }
-
- // ----- Read the next header
- $v_binary_data = $this->_readBlock();
-
- if (!$this->_readHeader($v_binary_data, $v_header))
- return false;
-
- $v_filename = trim($v_filename);
- $v_header['filename'] = $v_filename;
- if ($this->_maliciousFilename($v_filename)) {
- $this->_error('Malicious .tar detected, file "' . $v_filename .
- '" will not install in desired directory tree');
- return false;
- }
-
- return true;
- }
- // }}}
-
- // {{{ _extractInString()
- /**
- * This method extract from the archive one file identified by $p_filename.
- * The return value is a string with the file content, or null on error.
- *
- * @param string $p_filename The path of the file to extract in a string.
- *
- * @return a string with the file content or null.
- * @access private
- */
- function _extractInString($p_filename)
- {
- $v_result_str = "";
-
- While (strlen($v_binary_data = $this->_readBlock()) != 0)
- {
- if (!$this->_readHeader($v_binary_data, $v_header))
- return null;
-
- if ($v_header['filename'] == '')
- continue;
-
- // ----- Look for long filename
- if ($v_header['typeflag'] == 'L') {
- if (!$this->_readLongHeader($v_header))
- return null;
- }
-
- if ($v_header['filename'] == $p_filename) {
- if ($v_header['typeflag'] == "5") {
- $this->_error('Unable to extract in string a directory '
- .'entry {'.$v_header['filename'].'}');
- return null;
- } else {
- $n = floor($v_header['size']/512);
- for ($i=0; $i<$n; $i++) {
- $v_result_str .= $this->_readBlock();
- }
- if (($v_header['size'] % 512) != 0) {
- $v_content = $this->_readBlock();
- $v_result_str .= substr($v_content, 0,
- ($v_header['size'] % 512));
- }
- return $v_result_str;
- }
- } else {
- $this->_jumpBlock(ceil(($v_header['size']/512)));
- }
- }
-
- return null;
- }
- // }}}
-
- // {{{ _extractList()
- function _extractList($p_path, &$p_list_detail, $p_mode,
- $p_file_list, $p_remove_path, $p_preserve=false)
- {
- $v_result=true;
- $v_nb = 0;
- $v_extract_all = true;
- $v_listing = false;
-
- $p_path = $this->_translateWinPath($p_path, false);
- if ($p_path == '' || (substr($p_path, 0, 1) != '/'
- && substr($p_path, 0, 3) != "../" && !strpos($p_path, ':'))) {
- $p_path = "./".$p_path;
- }
- $p_remove_path = $this->_translateWinPath($p_remove_path);
-
- // ----- Look for path to remove format (should end by /)
- if (($p_remove_path != '') && (substr($p_remove_path, -1) != '/'))
- $p_remove_path .= '/';
- $p_remove_path_size = strlen($p_remove_path);
-
- switch ($p_mode) {
- case "complete" :
- $v_extract_all = true;
- $v_listing = false;
- break;
- case "partial" :
- $v_extract_all = false;
- $v_listing = false;
- break;
- case "list" :
- $v_extract_all = false;
- $v_listing = true;
- break;
- default :
- $this->_error('Invalid extract mode ('.$p_mode.')');
- return false;
- }
-
- clearstatcache();
-
- while (strlen($v_binary_data = $this->_readBlock()) != 0)
- {
- $v_extract_file = FALSE;
- $v_extraction_stopped = 0;
-
- if (!$this->_readHeader($v_binary_data, $v_header))
- return false;
-
- if ($v_header['filename'] == '') {
- continue;
- }
-
- // ----- Look for long filename
- if ($v_header['typeflag'] == 'L') {
- if (!$this->_readLongHeader($v_header))
- return false;
- }
-
- if ((!$v_extract_all) && (is_array($p_file_list))) {
- // ----- By default no unzip if the file is not found
- $v_extract_file = false;
-
- for ($i=0; $i strlen($p_file_list[$i]))
- && (substr($v_header['filename'], 0, strlen($p_file_list[$i]))
- == $p_file_list[$i])) {
- $v_extract_file = true;
- break;
- }
- }
-
- // ----- It is a file, so compare the file names
- elseif ($p_file_list[$i] == $v_header['filename']) {
- $v_extract_file = true;
- break;
- }
- }
- } else {
- $v_extract_file = true;
- }
-
- // ----- Look if this file need to be extracted
- if (($v_extract_file) && (!$v_listing))
- {
- if (($p_remove_path != '')
- && (substr($v_header['filename'], 0, $p_remove_path_size)
- == $p_remove_path))
- $v_header['filename'] = substr($v_header['filename'],
- $p_remove_path_size);
- if (($p_path != './') && ($p_path != '/')) {
- while (substr($p_path, -1) == '/')
- $p_path = substr($p_path, 0, strlen($p_path)-1);
-
- if (substr($v_header['filename'], 0, 1) == '/')
- $v_header['filename'] = $p_path.$v_header['filename'];
- else
- $v_header['filename'] = $p_path.'/'.$v_header['filename'];
- }
- if (file_exists($v_header['filename'])) {
- if ( (@is_dir($v_header['filename']))
- && ($v_header['typeflag'] == '')) {
- $this->_error('File '.$v_header['filename']
- .' already exists as a directory');
- return false;
- }
- if ( ($this->_isArchive($v_header['filename']))
- && ($v_header['typeflag'] == "5")) {
- $this->_error('Directory '.$v_header['filename']
- .' already exists as a file');
- return false;
- }
- if (!is_writeable($v_header['filename'])) {
- $this->_error('File '.$v_header['filename']
- .' already exists and is write protected');
- return false;
- }
- if (filemtime($v_header['filename']) > $v_header['mtime']) {
- // To be completed : An error or silent no replace ?
- }
- }
-
- // ----- Check the directory availability and create it if necessary
- elseif (($v_result
- = $this->_dirCheck(($v_header['typeflag'] == "5"
- ?$v_header['filename']
- :dirname($v_header['filename'])))) != 1) {
- $this->_error('Unable to create path for '.$v_header['filename']);
- return false;
- }
-
- if ($v_extract_file) {
- if ($v_header['typeflag'] == "5") {
- if (!@file_exists($v_header['filename'])) {
- if (!@mkdir($v_header['filename'], 0777)) {
- $this->_error('Unable to create directory {'
- .$v_header['filename'].'}');
- return false;
- }
- }
- } elseif ($v_header['typeflag'] == "2") {
- if (@file_exists($v_header['filename'])) {
- @unlink($v_header['filename']);
- }
- if (!@symlink($v_header['link'], $v_header['filename'])) {
- $this->_error('Unable to extract symbolic link {'
- .$v_header['filename'].'}');
- return false;
- }
- } else {
- if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) {
- $this->_error('Error while opening {'.$v_header['filename']
- .'} in write binary mode');
- return false;
- } else {
- $n = floor($v_header['size']/512);
- for ($i=0; $i<$n; $i++) {
- $v_content = $this->_readBlock();
- fwrite($v_dest_file, $v_content, 512);
- }
- if (($v_header['size'] % 512) != 0) {
- $v_content = $this->_readBlock();
- fwrite($v_dest_file, $v_content, ($v_header['size'] % 512));
- }
-
- @fclose($v_dest_file);
-
- if ($p_preserve) {
- @chown($v_header['filename'], $v_header['uid']);
- @chgrp($v_header['filename'], $v_header['gid']);
- }
-
- // ----- Change the file mode, mtime
- @touch($v_header['filename'], $v_header['mtime']);
- if ($v_header['mode'] & 0111) {
- // make file executable, obey umask
- $mode = fileperms($v_header['filename']) | (~umask() & 0111);
- @chmod($v_header['filename'], $mode);
- }
- }
-
- // ----- Check the file size
- clearstatcache();
- if (!is_file($v_header['filename'])) {
- $this->_error('Extracted file '.$v_header['filename']
- .'does not exist. Archive may be corrupted.');
- return false;
- }
-
- $filesize = filesize($v_header['filename']);
- if ($filesize != $v_header['size']) {
- $this->_error('Extracted file '.$v_header['filename']
- .' does not have the correct file size \''
- .$filesize
- .'\' ('.$v_header['size']
- .' expected). Archive may be corrupted.');
- return false;
- }
- }
- } else {
- $this->_jumpBlock(ceil(($v_header['size']/512)));
- }
- } else {
- $this->_jumpBlock(ceil(($v_header['size']/512)));
- }
-
- /* TBC : Seems to be unused ...
- if ($this->_compress)
- $v_end_of_file = @gzeof($this->_file);
- else
- $v_end_of_file = @feof($this->_file);
- */
-
- if ($v_listing || $v_extract_file || $v_extraction_stopped) {
- // ----- Log extracted files
- if (($v_file_dir = dirname($v_header['filename']))
- == $v_header['filename'])
- $v_file_dir = '';
- if ((substr($v_header['filename'], 0, 1) == '/') && ($v_file_dir == ''))
- $v_file_dir = '/';
-
- $p_list_detail[$v_nb++] = $v_header;
- if (is_array($p_file_list) && (count($p_list_detail) == count($p_file_list))) {
- return true;
- }
- }
- }
-
- return true;
- }
- // }}}
-
- // {{{ _openAppend()
- function _openAppend()
- {
- if (filesize($this->_tarname) == 0)
- return $this->_openWrite();
-
- if ($this->_compress) {
- $this->_close();
-
- if (!@rename($this->_tarname, $this->_tarname.".tmp")) {
- $this->_error('Error while renaming \''.$this->_tarname
- .'\' to temporary file \''.$this->_tarname
- .'.tmp\'');
- return false;
- }
-
- if ($this->_compress_type == 'gz')
- $v_temp_tar = @gzopen($this->_tarname.".tmp", "rb");
- elseif ($this->_compress_type == 'bz2')
- $v_temp_tar = @bzopen($this->_tarname.".tmp", "r");
-
- if ($v_temp_tar == 0) {
- $this->_error('Unable to open file \''.$this->_tarname
- .'.tmp\' in binary read mode');
- @rename($this->_tarname.".tmp", $this->_tarname);
- return false;
- }
-
- if (!$this->_openWrite()) {
- @rename($this->_tarname.".tmp", $this->_tarname);
- return false;
- }
-
- if ($this->_compress_type == 'gz') {
- $end_blocks = 0;
-
- while (!@gzeof($v_temp_tar)) {
- $v_buffer = @gzread($v_temp_tar, 512);
- if ($v_buffer == ARCHIVE_TAR_END_BLOCK || strlen($v_buffer) == 0) {
- $end_blocks++;
- // do not copy end blocks, we will re-make them
- // after appending
- continue;
- } elseif ($end_blocks > 0) {
- for ($i = 0; $i < $end_blocks; $i++) {
- $this->_writeBlock(ARCHIVE_TAR_END_BLOCK);
- }
- $end_blocks = 0;
- }
- $v_binary_data = pack("a512", $v_buffer);
- $this->_writeBlock($v_binary_data);
- }
-
- @gzclose($v_temp_tar);
- }
- elseif ($this->_compress_type == 'bz2') {
- $end_blocks = 0;
-
- while (strlen($v_buffer = @bzread($v_temp_tar, 512)) > 0) {
- if ($v_buffer == ARCHIVE_TAR_END_BLOCK || strlen($v_buffer) == 0) {
- $end_blocks++;
- // do not copy end blocks, we will re-make them
- // after appending
- continue;
- } elseif ($end_blocks > 0) {
- for ($i = 0; $i < $end_blocks; $i++) {
- $this->_writeBlock(ARCHIVE_TAR_END_BLOCK);
- }
- $end_blocks = 0;
- }
- $v_binary_data = pack("a512", $v_buffer);
- $this->_writeBlock($v_binary_data);
- }
-
- @bzclose($v_temp_tar);
- }
-
- if (!@unlink($this->_tarname.".tmp")) {
- $this->_error('Error while deleting temporary file \''
- .$this->_tarname.'.tmp\'');
- }
-
- } else {
- // ----- For not compressed tar, just add files before the last
- // one or two 512 bytes block
- if (!$this->_openReadWrite())
- return false;
-
- clearstatcache();
- $v_size = filesize($this->_tarname);
-
- // We might have zero, one or two end blocks.
- // The standard is two, but we should try to handle
- // other cases.
- fseek($this->_file, $v_size - 1024);
- if (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) {
- fseek($this->_file, $v_size - 1024);
- }
- elseif (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) {
- fseek($this->_file, $v_size - 512);
- }
- }
-
- return true;
- }
- // }}}
-
- // {{{ _append()
- function _append($p_filelist, $p_add_dir='', $p_remove_dir='')
- {
- if (!$this->_openAppend())
- return false;
-
- if ($this->_addList($p_filelist, $p_add_dir, $p_remove_dir))
- $this->_writeFooter();
-
- $this->_close();
-
- return true;
- }
- // }}}
-
- // {{{ _dirCheck()
-
- /**
- * Check if a directory exists and create it (including parent
- * dirs) if not.
- *
- * @param string $p_dir directory to check
- *
- * @return bool true if the directory exists or was created
- */
- function _dirCheck($p_dir)
- {
- clearstatcache();
- if ((@is_dir($p_dir)) || ($p_dir == ''))
- return true;
-
- $p_parent_dir = dirname($p_dir);
-
- if (($p_parent_dir != $p_dir) &&
- ($p_parent_dir != '') &&
- (!$this->_dirCheck($p_parent_dir)))
- return false;
-
- if (!@mkdir($p_dir, 0777)) {
- $this->_error("Unable to create directory '$p_dir'");
- return false;
- }
-
- return true;
- }
-
- // }}}
-
- // {{{ _pathReduction()
-
- /**
- * Compress path by changing for example "/dir/foo/../bar" to "/dir/bar",
- * rand emove double slashes.
- *
- * @param string $p_dir path to reduce
- *
- * @return string reduced path
- *
- * @access private
- *
- */
- function _pathReduction($p_dir)
- {
- $v_result = '';
-
- // ----- Look for not empty path
- if ($p_dir != '') {
- // ----- Explode path by directory names
- $v_list = explode('/', $p_dir);
-
- // ----- Study directories from last to first
- for ($i=sizeof($v_list)-1; $i>=0; $i--) {
- // ----- Look for current path
- if ($v_list[$i] == ".") {
- // ----- Ignore this directory
- // Should be the first $i=0, but no check is done
- }
- else if ($v_list[$i] == "..") {
- // ----- Ignore it and ignore the $i-1
- $i--;
- }
- else if ( ($v_list[$i] == '')
- && ($i!=(sizeof($v_list)-1))
- && ($i!=0)) {
- // ----- Ignore only the double '//' in path,
- // but not the first and last /
- } else {
- $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?'/'
- .$v_result:'');
- }
- }
- }
-
- if (defined('OS_WINDOWS') && OS_WINDOWS) {
- $v_result = strtr($v_result, '\\', '/');
- }
-
- return $v_result;
- }
-
- // }}}
-
- // {{{ _translateWinPath()
- function _translateWinPath($p_path, $p_remove_disk_letter=true)
- {
- if (defined('OS_WINDOWS') && OS_WINDOWS) {
- // ----- Look for potential disk letter
- if ( ($p_remove_disk_letter)
- && (($v_position = strpos($p_path, ':')) != false)) {
- $p_path = substr($p_path, $v_position+1);
- }
- // ----- Change potential windows directory separator
- if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) {
- $p_path = strtr($p_path, '\\', '/');
- }
- }
- return $p_path;
- }
- // }}}
-
-}
-?>
diff --git a/3rdparty/Console/Getopt.php b/3rdparty/Console/Getopt.php
deleted file mode 100644
index aec980b34d..0000000000
--- a/3rdparty/Console/Getopt.php
+++ /dev/null
@@ -1,251 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id: Getopt.php,v 1.21.4.7 2003/12/05 21:57:01 andrei Exp $
-
-require_once( 'PEAR.php');
-
-/**
- * Command-line options parsing class.
- *
- * @author Andrei Zmievski
- *
- */
-class Console_Getopt {
- /**
- * Parses the command-line options.
- *
- * The first parameter to this function should be the list of command-line
- * arguments without the leading reference to the running program.
- *
- * The second parameter is a string of allowed short options. Each of the
- * option letters can be followed by a colon ':' to specify that the option
- * requires an argument, or a double colon '::' to specify that the option
- * takes an optional argument.
- *
- * The third argument is an optional array of allowed long options. The
- * leading '--' should not be included in the option name. Options that
- * require an argument should be followed by '=', and options that take an
- * option argument should be followed by '=='.
- *
- * The return value is an array of two elements: the list of parsed
- * options and the list of non-option command-line arguments. Each entry in
- * the list of parsed options is a pair of elements - the first one
- * specifies the option, and the second one specifies the option argument,
- * if there was one.
- *
- * Long and short options can be mixed.
- *
- * Most of the semantics of this function are based on GNU getopt_long().
- *
- * @param array $args an array of command-line arguments
- * @param string $short_options specifies the list of allowed short options
- * @param array $long_options specifies the list of allowed long options
- *
- * @return array two-element array containing the list of parsed options and
- * the non-option arguments
- *
- * @access public
- *
- */
- function getopt2($args, $short_options, $long_options = null)
- {
- return Console_Getopt::doGetopt(2, $args, $short_options, $long_options);
- }
-
- /**
- * This function expects $args to start with the script name (POSIX-style).
- * Preserved for backwards compatibility.
- * @see getopt2()
- */
- function getopt($args, $short_options, $long_options = null)
- {
- return Console_Getopt::doGetopt(1, $args, $short_options, $long_options);
- }
-
- /**
- * The actual implementation of the argument parsing code.
- */
- function doGetopt($version, $args, $short_options, $long_options = null)
- {
- // in case you pass directly readPHPArgv() as the first arg
- if (PEAR::isError($args)) {
- return $args;
- }
- if (empty($args)) {
- return array(array(), array());
- }
- $opts = array();
- $non_opts = array();
-
- settype($args, 'array');
-
- if ($long_options) {
- sort($long_options);
- }
-
- /*
- * Preserve backwards compatibility with callers that relied on
- * erroneous POSIX fix.
- */
- if ($version < 2) {
- if (isset($args[0]{0}) && $args[0]{0} != '-') {
- array_shift($args);
- }
- }
-
- reset($args);
- while (list($i, $arg) = each($args)) {
-
- /* The special element '--' means explicit end of
- options. Treat the rest of the arguments as non-options
- and end the loop. */
- if ($arg == '--') {
- $non_opts = array_merge($non_opts, array_slice($args, $i + 1));
- break;
- }
-
- if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) {
- $non_opts = array_merge($non_opts, array_slice($args, $i));
- break;
- } elseif (strlen($arg) > 1 && $arg{1} == '-') {
- $error = Console_Getopt::_parseLongOption(substr($arg, 2), $long_options, $opts, $args);
- if (PEAR::isError($error))
- return $error;
- } else {
- $error = Console_Getopt::_parseShortOption(substr($arg, 1), $short_options, $opts, $args);
- if (PEAR::isError($error))
- return $error;
- }
- }
-
- return array($opts, $non_opts);
- }
-
- /**
- * @access private
- *
- */
- function _parseShortOption($arg, $short_options, &$opts, &$args)
- {
- for ($i = 0; $i < strlen($arg); $i++) {
- $opt = $arg{$i};
- $opt_arg = null;
-
- /* Try to find the short option in the specifier string. */
- if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':')
- {
- return PEAR::raiseError("Console_Getopt: unrecognized option -- $opt");
- }
-
- if (strlen($spec) > 1 && $spec{1} == ':') {
- if (strlen($spec) > 2 && $spec{2} == ':') {
- if ($i + 1 < strlen($arg)) {
- /* Option takes an optional argument. Use the remainder of
- the arg string if there is anything left. */
- $opts[] = array($opt, substr($arg, $i + 1));
- break;
- }
- } else {
- /* Option requires an argument. Use the remainder of the arg
- string if there is anything left. */
- if ($i + 1 < strlen($arg)) {
- $opts[] = array($opt, substr($arg, $i + 1));
- break;
- } else if (list(, $opt_arg) = each($args))
- /* Else use the next argument. */;
- else
- return PEAR::raiseError("Console_Getopt: option requires an argument -- $opt");
- }
- }
-
- $opts[] = array($opt, $opt_arg);
- }
- }
-
- /**
- * @access private
- *
- */
- function _parseLongOption($arg, $long_options, &$opts, &$args)
- {
- @list($opt, $opt_arg) = explode('=', $arg);
- $opt_len = strlen($opt);
-
- for ($i = 0; $i < count($long_options); $i++) {
- $long_opt = $long_options[$i];
- $opt_start = substr($long_opt, 0, $opt_len);
-
- /* Option doesn't match. Go on to the next one. */
- if ($opt_start != $opt)
- continue;
-
- $opt_rest = substr($long_opt, $opt_len);
-
- /* Check that the options uniquely matches one of the allowed
- options. */
- if ($opt_rest != '' && $opt{0} != '=' &&
- $i + 1 < count($long_options) &&
- $opt == substr($long_options[$i+1], 0, $opt_len)) {
- return PEAR::raiseError("Console_Getopt: option --$opt is ambiguous");
- }
-
- if (substr($long_opt, -1) == '=') {
- if (substr($long_opt, -2) != '==') {
- /* Long option requires an argument.
- Take the next argument if one wasn't specified. */;
- if (!strlen($opt_arg) && !(list(, $opt_arg) = each($args))) {
- return PEAR::raiseError("Console_Getopt: option --$opt requires an argument");
- }
- }
- } else if ($opt_arg) {
- return PEAR::raiseError("Console_Getopt: option --$opt doesn't allow an argument");
- }
-
- $opts[] = array('--' . $opt, $opt_arg);
- return;
- }
-
- return PEAR::raiseError("Console_Getopt: unrecognized option --$opt");
- }
-
- /**
- * Safely read the $argv PHP array across different PHP configurations.
- * Will take care on register_globals and register_argc_argv ini directives
- *
- * @access public
- * @return mixed the $argv PHP array or PEAR error if not registered
- */
- function readPHPArgv()
- {
- global $argv;
- if (!is_array($argv)) {
- if (!@is_array($_SERVER['argv'])) {
- if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) {
- return PEAR::raiseError("Console_Getopt: Could not read cmd args (register_argc_argv=Off?)");
- }
- return $GLOBALS['HTTP_SERVER_VARS']['argv'];
- }
- return $_SERVER['argv'];
- }
- return $argv;
- }
-
-}
-
-?>
diff --git a/3rdparty/Crypt_Blowfish/Blowfish.php b/3rdparty/Crypt_Blowfish/Blowfish.php
deleted file mode 100644
index 4ccacb963e..0000000000
--- a/3rdparty/Crypt_Blowfish/Blowfish.php
+++ /dev/null
@@ -1,317 +0,0 @@
-
- * @copyright 2005 Matthew Fonda
- * @license http://www.php.net/license/3_0.txt PHP License 3.0
- * @version CVS: $Id: Blowfish.php,v 1.81 2005/05/30 18:40:36 mfonda Exp $
- * @link http://pear.php.net/package/Crypt_Blowfish
- */
-
-
-require_once 'PEAR.php';
-
-
-/**
- *
- * Example usage:
- * $bf = new Crypt_Blowfish('some secret key!');
- * $encrypted = $bf->encrypt('this is some example plain text');
- * $plaintext = $bf->decrypt($encrypted);
- * echo "plain text: $plaintext";
- *
- *
- * @category Encryption
- * @package Crypt_Blowfish
- * @author Matthew Fonda
- * @copyright 2005 Matthew Fonda
- * @license http://www.php.net/license/3_0.txt PHP License 3.0
- * @link http://pear.php.net/package/Crypt_Blowfish
- * @version @package_version@
- * @access public
- */
-class Crypt_Blowfish
-{
- /**
- * P-Array contains 18 32-bit subkeys
- *
- * @var array
- * @access private
- */
- var $_P = array();
-
-
- /**
- * Array of four S-Blocks each containing 256 32-bit entries
- *
- * @var array
- * @access private
- */
- var $_S = array();
-
- /**
- * Mcrypt td resource
- *
- * @var resource
- * @access private
- */
- var $_td = null;
-
- /**
- * Initialization vector
- *
- * @var string
- * @access private
- */
- var $_iv = null;
-
-
- /**
- * Crypt_Blowfish Constructor
- * Initializes the Crypt_Blowfish object, and gives a sets
- * the secret key
- *
- * @param string $key
- * @access public
- */
- function Crypt_Blowfish($key)
- {
- if (extension_loaded('mcrypt')) {
- $this->_td = mcrypt_module_open(MCRYPT_BLOWFISH, '', 'ecb', '');
- $this->_iv = mcrypt_create_iv(8, MCRYPT_RAND);
- }
- $this->setKey($key);
- }
-
- /**
- * Deprecated isReady method
- *
- * @return bool
- * @access public
- * @deprecated
- */
- function isReady()
- {
- return true;
- }
-
- /**
- * Deprecated init method - init is now a private
- * method and has been replaced with _init
- *
- * @return bool
- * @access public
- * @deprecated
- * @see Crypt_Blowfish::_init()
- */
- function init()
- {
- $this->_init();
- }
-
- /**
- * Initializes the Crypt_Blowfish object
- *
- * @access private
- */
- function _init()
- {
- $defaults = new Crypt_Blowfish_DefaultKey();
- $this->_P = $defaults->P;
- $this->_S = $defaults->S;
- }
-
- /**
- * Enciphers a single 64 bit block
- *
- * @param int &$Xl
- * @param int &$Xr
- * @access private
- */
- function _encipher(&$Xl, &$Xr)
- {
- for ($i = 0; $i < 16; $i++) {
- $temp = $Xl ^ $this->_P[$i];
- $Xl = ((($this->_S[0][($temp>>24) & 255] +
- $this->_S[1][($temp>>16) & 255]) ^
- $this->_S[2][($temp>>8) & 255]) +
- $this->_S[3][$temp & 255]) ^ $Xr;
- $Xr = $temp;
- }
- $Xr = $Xl ^ $this->_P[16];
- $Xl = $temp ^ $this->_P[17];
- }
-
-
- /**
- * Deciphers a single 64 bit block
- *
- * @param int &$Xl
- * @param int &$Xr
- * @access private
- */
- function _decipher(&$Xl, &$Xr)
- {
- for ($i = 17; $i > 1; $i--) {
- $temp = $Xl ^ $this->_P[$i];
- $Xl = ((($this->_S[0][($temp>>24) & 255] +
- $this->_S[1][($temp>>16) & 255]) ^
- $this->_S[2][($temp>>8) & 255]) +
- $this->_S[3][$temp & 255]) ^ $Xr;
- $Xr = $temp;
- }
- $Xr = $Xl ^ $this->_P[1];
- $Xl = $temp ^ $this->_P[0];
- }
-
-
- /**
- * Encrypts a string
- *
- * @param string $plainText
- * @return string Returns cipher text on success, PEAR_Error on failure
- * @access public
- */
- function encrypt($plainText)
- {
- if (!is_string($plainText)) {
- PEAR::raiseError('Plain text must be a string', 0, PEAR_ERROR_DIE);
- }
-
- if (extension_loaded('mcrypt')) {
- return mcrypt_generic($this->_td, $plainText);
- }
-
- $cipherText = '';
- $len = strlen($plainText);
- $plainText .= str_repeat(chr(0),(8 - ($len%8))%8);
- for ($i = 0; $i < $len; $i += 8) {
- list(,$Xl,$Xr) = unpack("N2",substr($plainText,$i,8));
- $this->_encipher($Xl, $Xr);
- $cipherText .= pack("N2", $Xl, $Xr);
- }
- return $cipherText;
- }
-
-
- /**
- * Decrypts an encrypted string
- *
- * @param string $cipherText
- * @return string Returns plain text on success, PEAR_Error on failure
- * @access public
- */
- function decrypt($cipherText)
- {
- if (!is_string($cipherText)) {
- PEAR::raiseError('Cipher text must be a string', 1, PEAR_ERROR_DIE);
- }
-
- if (extension_loaded('mcrypt')) {
- return mdecrypt_generic($this->_td, $cipherText);
- }
-
- $plainText = '';
- $len = strlen($cipherText);
- $cipherText .= str_repeat(chr(0),(8 - ($len%8))%8);
- for ($i = 0; $i < $len; $i += 8) {
- list(,$Xl,$Xr) = unpack("N2",substr($cipherText,$i,8));
- $this->_decipher($Xl, $Xr);
- $plainText .= pack("N2", $Xl, $Xr);
- }
- return $plainText;
- }
-
-
- /**
- * Sets the secret key
- * The key must be non-zero, and less than or equal to
- * 56 characters in length.
- *
- * @param string $key
- * @return bool Returns true on success, PEAR_Error on failure
- * @access public
- */
- function setKey($key)
- {
- if (!is_string($key)) {
- PEAR::raiseError('Key must be a string', 2, PEAR_ERROR_DIE);
- }
-
- $len = strlen($key);
-
- if ($len > 56 || $len == 0) {
- PEAR::raiseError('Key must be less than 56 characters and non-zero. Supplied key length: ' . $len, 3, PEAR_ERROR_DIE);
- }
-
- if (extension_loaded('mcrypt')) {
- mcrypt_generic_init($this->_td, $key, $this->_iv);
- return true;
- }
-
- require_once 'Blowfish/DefaultKey.php';
- $this->_init();
-
- $k = 0;
- $data = 0;
- $datal = 0;
- $datar = 0;
-
- for ($i = 0; $i < 18; $i++) {
- $data = 0;
- for ($j = 4; $j > 0; $j--) {
- $data = $data << 8 | ord($key{$k});
- $k = ($k+1) % $len;
- }
- $this->_P[$i] ^= $data;
- }
-
- for ($i = 0; $i <= 16; $i += 2) {
- $this->_encipher($datal, $datar);
- $this->_P[$i] = $datal;
- $this->_P[$i+1] = $datar;
- }
- for ($i = 0; $i < 256; $i += 2) {
- $this->_encipher($datal, $datar);
- $this->_S[0][$i] = $datal;
- $this->_S[0][$i+1] = $datar;
- }
- for ($i = 0; $i < 256; $i += 2) {
- $this->_encipher($datal, $datar);
- $this->_S[1][$i] = $datal;
- $this->_S[1][$i+1] = $datar;
- }
- for ($i = 0; $i < 256; $i += 2) {
- $this->_encipher($datal, $datar);
- $this->_S[2][$i] = $datal;
- $this->_S[2][$i+1] = $datar;
- }
- for ($i = 0; $i < 256; $i += 2) {
- $this->_encipher($datal, $datar);
- $this->_S[3][$i] = $datal;
- $this->_S[3][$i+1] = $datar;
- }
-
- return true;
- }
-
-}
-
-?>
diff --git a/3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php b/3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php
deleted file mode 100644
index 2ff8ac788a..0000000000
--- a/3rdparty/Crypt_Blowfish/Blowfish/DefaultKey.php
+++ /dev/null
@@ -1,327 +0,0 @@
-
- * @copyright 2005 Matthew Fonda
- * @license http://www.php.net/license/3_0.txt PHP License 3.0
- * @version CVS: $Id: DefaultKey.php,v 1.81 2005/05/30 18:40:37 mfonda Exp $
- * @link http://pear.php.net/package/Crypt_Blowfish
- */
-
-
-/**
- * Class containing default key
- *
- * @category Encryption
- * @package Crypt_Blowfish
- * @author Matthew Fonda
- * @copyright 2005 Matthew Fonda
- * @license http://www.php.net/license/3_0.txt PHP License 3.0
- * @link http://pear.php.net/package/Crypt_Blowfish
- * @version @package_version@
- * @access public
- */
-class Crypt_Blowfish_DefaultKey
-{
- var $P = array();
-
- var $S = array();
-
- function Crypt_Blowfish_DefaultKey()
- {
- $this->P = array(
- 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344,
- 0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89,
- 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C,
- 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917,
- 0x9216D5D9, 0x8979FB1B
- );
-
- $this->S = array(
- array(
- 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7,
- 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99,
- 0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16,
- 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E,
- 0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE,
- 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013,
- 0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF,
- 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E,
- 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60,
- 0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440,
- 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE,
- 0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A,
- 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E,
- 0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677,
- 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193,
- 0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032,
- 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88,
- 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239,
- 0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E,
- 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0,
- 0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3,
- 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98,
- 0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88,
- 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE,
- 0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6,
- 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D,
- 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B,
- 0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7,
- 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA,
- 0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463,
- 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F,
- 0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09,
- 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3,
- 0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB,
- 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279,
- 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8,
- 0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB,
- 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82,
- 0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB,
- 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573,
- 0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0,
- 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B,
- 0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790,
- 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8,
- 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4,
- 0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0,
- 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7,
- 0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C,
- 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD,
- 0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1,
- 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299,
- 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9,
- 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477,
- 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF,
- 0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49,
- 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF,
- 0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA,
- 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5,
- 0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41,
- 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915,
- 0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400,
- 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915,
- 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664,
- 0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A
- ),
- array(
- 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623,
- 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266,
- 0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1,
- 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E,
- 0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6,
- 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1,
- 0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E,
- 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1,
- 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737,
- 0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8,
- 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF,
- 0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD,
- 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701,
- 0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7,
- 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41,
- 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331,
- 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF,
- 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF,
- 0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E,
- 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87,
- 0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C,
- 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2,
- 0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16,
- 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD,
- 0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B,
- 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509,
- 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E,
- 0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3,
- 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F,
- 0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A,
- 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4,
- 0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960,
- 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66,
- 0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28,
- 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802,
- 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84,
- 0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510,
- 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF,
- 0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14,
- 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E,
- 0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50,
- 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7,
- 0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8,
- 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281,
- 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99,
- 0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696,
- 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128,
- 0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73,
- 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0,
- 0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0,
- 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105,
- 0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250,
- 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3,
- 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285,
- 0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00,
- 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061,
- 0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB,
- 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E,
- 0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735,
- 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC,
- 0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9,
- 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340,
- 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20,
- 0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7
- ),
- array(
- 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934,
- 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068,
- 0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF,
- 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840,
- 0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45,
- 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504,
- 0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A,
- 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB,
- 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE,
- 0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6,
- 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42,
- 0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B,
- 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2,
- 0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB,
- 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527,
- 0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B,
- 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33,
- 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C,
- 0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3,
- 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC,
- 0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17,
- 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564,
- 0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B,
- 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115,
- 0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922,
- 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728,
- 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0,
- 0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E,
- 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37,
- 0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D,
- 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804,
- 0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B,
- 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3,
- 0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB,
- 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D,
- 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C,
- 0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350,
- 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9,
- 0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A,
- 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE,
- 0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D,
- 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC,
- 0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F,
- 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61,
- 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2,
- 0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9,
- 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2,
- 0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C,
- 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E,
- 0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633,
- 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10,
- 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169,
- 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52,
- 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027,
- 0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5,
- 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62,
- 0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634,
- 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76,
- 0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24,
- 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC,
- 0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4,
- 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C,
- 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837,
- 0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0
- ),
- array(
- 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B,
- 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE,
- 0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B,
- 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4,
- 0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8,
- 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6,
- 0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304,
- 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22,
- 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4,
- 0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6,
- 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9,
- 0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59,
- 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593,
- 0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51,
- 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28,
- 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C,
- 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B,
- 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28,
- 0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C,
- 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD,
- 0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A,
- 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319,
- 0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB,
- 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F,
- 0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991,
- 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32,
- 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680,
- 0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166,
- 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE,
- 0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB,
- 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5,
- 0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47,
- 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370,
- 0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D,
- 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84,
- 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048,
- 0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8,
- 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD,
- 0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9,
- 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7,
- 0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38,
- 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F,
- 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C,
- 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525,
- 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1,
- 0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442,
- 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964,
- 0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E,
- 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8,
- 0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D,
- 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F,
- 0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299,
- 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02,
- 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC,
- 0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614,
- 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A,
- 0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6,
- 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B,
- 0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0,
- 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060,
- 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E,
- 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9,
- 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F,
- 0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6
- )
- );
- }
-
-}
-
-?>
diff --git a/3rdparty/Dropbox/API.php b/3rdparty/Dropbox/API.php
deleted file mode 100644
index 8cdce678e1..0000000000
--- a/3rdparty/Dropbox/API.php
+++ /dev/null
@@ -1,380 +0,0 @@
-oauth = $oauth;
- $this->root = $root;
- $this->useSSL = $useSSL;
- if (!$this->useSSL)
- {
- throw new Dropbox_Exception('Dropbox REST API now requires that all requests use SSL');
- }
-
- }
-
- /**
- * Returns information about the current dropbox account
- *
- * @return stdclass
- */
- public function getAccountInfo() {
-
- $data = $this->oauth->fetch($this->api_url . 'account/info');
- return json_decode($data['body'],true);
-
- }
-
- /**
- * Returns a file's contents
- *
- * @param string $path path
- * @param string $root Use this to override the default root path (sandbox/dropbox)
- * @return string
- */
- public function getFile($path = '', $root = null) {
-
- if (is_null($root)) $root = $this->root;
- $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
- $result = $this->oauth->fetch($this->api_content_url . 'files/' . $root . '/' . ltrim($path,'/'));
- return $result['body'];
-
- }
-
- /**
- * Uploads a new file
- *
- * @param string $path Target path (including filename)
- * @param string $file Either a path to a file or a stream resource
- * @param string $root Use this to override the default root path (sandbox/dropbox)
- * @return bool
- */
- public function putFile($path, $file, $root = null) {
-
- $directory = dirname($path);
- $filename = basename($path);
-
- if($directory==='.') $directory = '';
- $directory = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($directory));
-// $filename = str_replace('~', '%7E', rawurlencode($filename));
- if (is_null($root)) $root = $this->root;
-
- if (is_string($file)) {
-
- $file = fopen($file,'rb');
-
- } elseif (!is_resource($file)) {
- throw new Dropbox_Exception('File must be a file-resource or a string');
- }
- $result=$this->multipartFetch($this->api_content_url . 'files/' .
- $root . '/' . trim($directory,'/'), $file, $filename);
-
- if(!isset($result["httpStatus"]) || $result["httpStatus"] != 200)
- throw new Dropbox_Exception("Uploading file to Dropbox failed");
-
- return true;
- }
-
-
- /**
- * Copies a file or directory from one location to another
- *
- * This method returns the file information of the newly created file.
- *
- * @param string $from source path
- * @param string $to destination path
- * @param string $root Use this to override the default root path (sandbox/dropbox)
- * @return stdclass
- */
- public function copy($from, $to, $root = null) {
-
- if (is_null($root)) $root = $this->root;
- $response = $this->oauth->fetch($this->api_url . 'fileops/copy', array('from_path' => $from, 'to_path' => $to, 'root' => $root), 'POST');
-
- return json_decode($response['body'],true);
-
- }
-
- /**
- * Creates a new folder
- *
- * This method returns the information from the newly created directory
- *
- * @param string $path
- * @param string $root Use this to override the default root path (sandbox/dropbox)
- * @return stdclass
- */
- public function createFolder($path, $root = null) {
-
- if (is_null($root)) $root = $this->root;
-
- // Making sure the path starts with a /
-// $path = '/' . ltrim($path,'/');
-
- $response = $this->oauth->fetch($this->api_url . 'fileops/create_folder', array('path' => $path, 'root' => $root),'POST');
- return json_decode($response['body'],true);
-
- }
-
- /**
- * Deletes a file or folder.
- *
- * This method will return the metadata information from the deleted file or folder, if successful.
- *
- * @param string $path Path to new folder
- * @param string $root Use this to override the default root path (sandbox/dropbox)
- * @return array
- */
- public function delete($path, $root = null) {
-
- if (is_null($root)) $root = $this->root;
- $response = $this->oauth->fetch($this->api_url . 'fileops/delete', array('path' => $path, 'root' => $root), 'POST');
- return json_decode($response['body']);
-
- }
-
- /**
- * Moves a file or directory to a new location
- *
- * This method returns the information from the newly created directory
- *
- * @param mixed $from Source path
- * @param mixed $to destination path
- * @param string $root Use this to override the default root path (sandbox/dropbox)
- * @return stdclass
- */
- public function move($from, $to, $root = null) {
-
- if (is_null($root)) $root = $this->root;
- $response = $this->oauth->fetch($this->api_url . 'fileops/move', array('from_path' => rawurldecode($from), 'to_path' => rawurldecode($to), 'root' => $root), 'POST');
-
- return json_decode($response['body'],true);
-
- }
-
- /**
- * Returns file and directory information
- *
- * @param string $path Path to receive information from
- * @param bool $list When set to true, this method returns information from all files in a directory. When set to false it will only return infromation from the specified directory.
- * @param string $hash If a hash is supplied, this method simply returns true if nothing has changed since the last request. Good for caching.
- * @param int $fileLimit Maximum number of file-information to receive
- * @param string $root Use this to override the default root path (sandbox/dropbox)
- * @return array|true
- */
- public function getMetaData($path, $list = true, $hash = null, $fileLimit = null, $root = null) {
-
- if (is_null($root)) $root = $this->root;
-
- $args = array(
- 'list' => $list,
- );
-
- if (!is_null($hash)) $args['hash'] = $hash;
- if (!is_null($fileLimit)) $args['file_limit'] = $fileLimit;
-
- $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
- $response = $this->oauth->fetch($this->api_url . 'metadata/' . $root . '/' . ltrim($path,'/'), $args);
-
- /* 304 is not modified */
- if ($response['httpStatus']==304) {
- return true;
- } else {
- return json_decode($response['body'],true);
- }
-
- }
-
- /**
- * A way of letting you keep up with changes to files and folders in a user's Dropbox. You can periodically call /delta to get a list of "delta entries", which are instructions on how to update your local state to match the server's state.
- *
- * This method returns the information from the newly created directory
- *
- * @param string $cursor A string that is used to keep track of your current state. On the next call pass in this value to return delta entries that have been recorded since the cursor was returned.
- * @return stdclass
- */
- public function delta($cursor) {
-
- $arg['cursor'] = $cursor;
-
- $response = $this->oauth->fetch($this->api_url . 'delta', $arg, 'POST');
- return json_decode($response['body'],true);
-
- }
-
- /**
- * Returns a thumbnail (as a string) for a file path.
- *
- * @param string $path Path to file
- * @param string $size small, medium or large
- * @param string $root Use this to override the default root path (sandbox/dropbox)
- * @return string
- */
- public function getThumbnail($path, $size = 'small', $root = null) {
-
- if (is_null($root)) $root = $this->root;
- $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
- $response = $this->oauth->fetch($this->api_content_url . 'thumbnails/' . $root . '/' . ltrim($path,'/'),array('size' => $size));
-
- return $response['body'];
-
- }
-
- /**
- * This method is used to generate multipart POST requests for file upload
- *
- * @param string $uri
- * @param array $arguments
- * @return bool
- */
- protected function multipartFetch($uri, $file, $filename) {
-
- /* random string */
- $boundary = 'R50hrfBj5JYyfR3vF3wR96GPCC9Fd2q2pVMERvEaOE3D8LZTgLLbRpNwXek3';
-
- $headers = array(
- 'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
- );
-
- $body="--" . $boundary . "\r\n";
- $body.="Content-Disposition: form-data; name=file; filename=".rawurldecode($filename)."\r\n";
- $body.="Content-type: application/octet-stream\r\n";
- $body.="\r\n";
- $body.=stream_get_contents($file);
- $body.="\r\n";
- $body.="--" . $boundary . "--";
-
- // Dropbox requires the filename to also be part of the regular arguments, so it becomes
- // part of the signature.
- $uri.='?file=' . $filename;
-
- return $this->oauth->fetch($uri, $body, 'POST', $headers);
-
- }
-
-
- /**
- * Search
- *
- * Returns metadata for all files and folders that match the search query.
- *
- * @added by: diszo.sasil
- *
- * @param string $query
- * @param string $root Use this to override the default root path (sandbox/dropbox)
- * @param string $path
- * @return array
- */
- public function search($query = '', $root = null, $path = ''){
- if (is_null($root)) $root = $this->root;
- if(!empty($path)){
- $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
- }
- $response = $this->oauth->fetch($this->api_url . 'search/' . $root . '/' . ltrim($path,'/'),array('query' => $query));
- return json_decode($response['body'],true);
- }
-
- /**
- * Creates and returns a shareable link to files or folders.
- *
- * Note: Links created by the /shares API call expire after thirty days.
- *
- * @param type $path
- * @param type $root
- * @return type
- */
- public function share($path, $root = null) {
- if (is_null($root)) $root = $this->root;
- $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
- $response = $this->oauth->fetch($this->api_url. 'shares/'. $root . '/' . ltrim($path, '/'), array(), 'POST');
- return json_decode($response['body'],true);
-
- }
-
- /**
- * Returns a link directly to a file.
- * Similar to /shares. The difference is that this bypasses the Dropbox webserver, used to provide a preview of the file, so that you can effectively stream the contents of your media.
- *
- * Note: The /media link expires after four hours, allotting enough time to stream files, but not enough to leave a connection open indefinitely.
- *
- * @param type $path
- * @param type $root
- * @return type
- */
- public function media($path, $root = null) {
-
- if (is_null($root)) $root = $this->root;
- $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
- $response = $this->oauth->fetch($this->api_url. 'media/'. $root . '/' . ltrim($path, '/'), array(), 'POST');
- return json_decode($response['body'],true);
-
- }
-
- /**
- * Creates and returns a copy_ref to a file. This reference string can be used to copy that file to another user's Dropbox by passing it in as the from_copy_ref parameter on /fileops/copy.
- *
- * @param type $path
- * @param type $root
- * @return type
- */
- public function copy_ref($path, $root = null) {
-
- if (is_null($root)) $root = $this->root;
- $path = str_replace(array('%2F','~'), array('/','%7E'), rawurlencode($path));
- $response = $this->oauth->fetch($this->api_url. 'copy_ref/'. $root . '/' . ltrim($path, '/'));
- return json_decode($response['body'],true);
-
- }
-
-
-}
diff --git a/3rdparty/Dropbox/Exception.php b/3rdparty/Dropbox/Exception.php
deleted file mode 100644
index 50cbc4c791..0000000000
--- a/3rdparty/Dropbox/Exception.php
+++ /dev/null
@@ -1,15 +0,0 @@
-oauth_token = $token['token'];
- $this->oauth_token_secret = $token['token_secret'];
- } else {
- $this->oauth_token = $token;
- $this->oauth_token_secret = $token_secret;
- }
-
- }
-
- /**
- * Returns the oauth request tokens as an associative array.
- *
- * The array will contain the elements 'token' and 'token_secret'.
- *
- * @return array
- */
- public function getToken() {
-
- return array(
- 'token' => $this->oauth_token,
- 'token_secret' => $this->oauth_token_secret,
- );
-
- }
-
- /**
- * Returns the authorization url
- *
- * @param string $callBack Specify a callback url to automatically redirect the user back
- * @return string
- */
- public function getAuthorizeUrl($callBack = null) {
-
- // Building the redirect uri
- $token = $this->getToken();
- $uri = self::URI_AUTHORIZE . '?oauth_token=' . $token['token'];
- if ($callBack) $uri.='&oauth_callback=' . $callBack;
- return $uri;
- }
-
- /**
- * Fetches a secured oauth url and returns the response body.
- *
- * @param string $uri
- * @param mixed $arguments
- * @param string $method
- * @param array $httpHeaders
- * @return string
- */
- public abstract function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array());
-
- /**
- * Requests the OAuth request token.
- *
- * @return array
- */
- abstract public function getRequestToken();
-
- /**
- * Requests the OAuth access tokens.
- *
- * @return array
- */
- abstract public function getAccessToken();
-
-}
diff --git a/3rdparty/Dropbox/OAuth/Consumer/Dropbox.php b/3rdparty/Dropbox/OAuth/Consumer/Dropbox.php
deleted file mode 100644
index 204a659de0..0000000000
--- a/3rdparty/Dropbox/OAuth/Consumer/Dropbox.php
+++ /dev/null
@@ -1,37 +0,0 @@
-consumerRequest instanceof HTTP_OAuth_Consumer_Request) {
- $this->consumerRequest = new HTTP_OAuth_Consumer_Request;
- }
-
- // TODO: Change this and add in code to validate the SSL cert.
- // see https://github.com/bagder/curl/blob/master/lib/mk-ca-bundle.pl
- $this->consumerRequest->setConfig(array(
- 'ssl_verify_peer' => false,
- 'ssl_verify_host' => false
- ));
-
- return $this->consumerRequest;
- }
-}
diff --git a/3rdparty/Dropbox/OAuth/Curl.php b/3rdparty/Dropbox/OAuth/Curl.php
deleted file mode 100644
index b75b27bb36..0000000000
--- a/3rdparty/Dropbox/OAuth/Curl.php
+++ /dev/null
@@ -1,282 +0,0 @@
-consumerKey = $consumerKey;
- $this->consumerSecret = $consumerSecret;
- }
-
- /**
- * Fetches a secured oauth url and returns the response body.
- *
- * @param string $uri
- * @param mixed $arguments
- * @param string $method
- * @param array $httpHeaders
- * @return string
- */
- public function fetch($uri, $arguments = array(), $method = 'GET', $httpHeaders = array()) {
-
- $uri=str_replace('http://', 'https://', $uri); // all https, upload makes problems if not
- if (is_string($arguments) and strtoupper($method) == 'POST') {
- preg_match("/\?file=(.*)$/i", $uri, $matches);
- if (isset($matches[1])) {
- $uri = str_replace($matches[0], "", $uri);
- $filename = $matches[1];
- $httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, array("file" => $filename), $method));
- }
- } else {
- $httpHeaders=array_merge($httpHeaders,$this->getOAuthHeader($uri, $arguments, $method));
- }
- $ch = curl_init();
- if (strtoupper($method) == 'POST') {
- curl_setopt($ch, CURLOPT_URL, $uri);
- curl_setopt($ch, CURLOPT_POST, true);
-// if (is_array($arguments))
-// $arguments=http_build_query($arguments);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $arguments);
-// $httpHeaders['Content-Length']=strlen($arguments);
- } else {
- curl_setopt($ch, CURLOPT_URL, $uri.'?'.http_build_query($arguments));
- curl_setopt($ch, CURLOPT_POST, false);
- }
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_TIMEOUT, 300);
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
-// curl_setopt($ch, CURLOPT_CAINFO, "rootca");
- curl_setopt($ch, CURLOPT_FRESH_CONNECT, true);
- //Build header
- $headers = array();
- foreach ($httpHeaders as $name => $value) {
- $headers[] = "{$name}: $value";
- }
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- if (!ini_get('safe_mode') && !ini_get('open_basedir'))
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
- if (function_exists($this->ProgressFunction) and defined('CURLOPT_PROGRESSFUNCTION')) {
- curl_setopt($ch, CURLOPT_NOPROGRESS, false);
- curl_setopt($ch, CURLOPT_PROGRESSFUNCTION, $this->ProgressFunction);
- curl_setopt($ch, CURLOPT_BUFFERSIZE, 512);
- }
- $response=curl_exec($ch);
- $errorno=curl_errno($ch);
- $error=curl_error($ch);
- $status=curl_getinfo($ch,CURLINFO_HTTP_CODE);
- curl_close($ch);
-
-
- if (!empty($errorno))
- throw new Dropbox_Exception_NotFound('Curl error: ('.$errorno.') '.$error."\n");
-
- if ($status>=300) {
- $body = json_decode($response,true);
- switch ($status) {
- // Not modified
- case 304 :
- return array(
- 'httpStatus' => 304,
- 'body' => null,
- );
- break;
- case 403 :
- throw new Dropbox_Exception_Forbidden('Forbidden.
- This could mean a bad OAuth request, or a file or folder already existing at the target location.
- ' . $body["error"] . "\n");
- case 404 :
- throw new Dropbox_Exception_NotFound('Resource at uri: ' . $uri . ' could not be found. ' .
- $body["error"] . "\n");
- case 507 :
- throw new Dropbox_Exception_OverQuota('This dropbox is full. ' .
- $body["error"] . "\n");
- }
- if (!empty($body["error"]))
- throw new Dropbox_Exception_RequestToken('Error: ('.$status.') '.$body["error"]."\n");
- }
-
- return array(
- 'body' => $response,
- 'httpStatus' => $status
- );
- }
-
- /**
- * Returns named array with oauth parameters for further use
- * @return array Array with oauth_ parameters
- */
- private function getOAuthBaseParams() {
- $params['oauth_version'] = '1.0';
- $params['oauth_signature_method'] = 'HMAC-SHA1';
-
- $params['oauth_consumer_key'] = $this->consumerKey;
- $tokens = $this->getToken();
- if (isset($tokens['token']) && $tokens['token']) {
- $params['oauth_token'] = $tokens['token'];
- }
- $params['oauth_timestamp'] = time();
- $params['oauth_nonce'] = md5(microtime() . mt_rand());
- return $params;
- }
-
- /**
- * Creates valid Authorization header for OAuth, based on URI and Params
- *
- * @param string $uri
- * @param array $params
- * @param string $method GET or POST, standard is GET
- * @param array $oAuthParams optional, pass your own oauth_params here
- * @return array Array for request's headers section like
- * array('Authorization' => 'OAuth ...');
- */
- private function getOAuthHeader($uri, $params, $method = 'GET', $oAuthParams = null) {
- $oAuthParams = $oAuthParams ? $oAuthParams : $this->getOAuthBaseParams();
-
- // create baseString to encode for the sent parameters
- $baseString = $method . '&';
- $baseString .= $this->oauth_urlencode($uri) . "&";
-
- // OAuth header does not include GET-Parameters
- $signatureParams = array_merge($params, $oAuthParams);
-
- // sorting the parameters
- ksort($signatureParams);
-
- $encodedParams = array();
- foreach ($signatureParams as $key => $value) {
- $encodedParams[] = $this->oauth_urlencode($key) . '=' . $this->oauth_urlencode($value);
- }
-
- $baseString .= $this->oauth_urlencode(implode('&', $encodedParams));
-
- // encode the signature
- $tokens = $this->getToken();
- $hash = $this->hash_hmac_sha1($this->consumerSecret.'&'.$tokens['token_secret'], $baseString);
- $signature = base64_encode($hash);
-
- // add signature to oAuthParams
- $oAuthParams['oauth_signature'] = $signature;
-
- $oAuthEncoded = array();
- foreach ($oAuthParams as $key => $value) {
- $oAuthEncoded[] = $key . '="' . $this->oauth_urlencode($value) . '"';
- }
-
- return array('Authorization' => 'OAuth ' . implode(', ', $oAuthEncoded));
- }
-
- /**
- * Requests the OAuth request token.
- *
- * @return void
- */
- public function getRequestToken() {
- $result = $this->fetch(self::URI_REQUEST_TOKEN, array(), 'POST');
- if ($result['httpStatus'] == "200") {
- $tokens = array();
- parse_str($result['body'], $tokens);
- $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
- return $this->getToken();
- } else {
- throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.');
- }
- }
-
- /**
- * Requests the OAuth access tokens.
- *
- * This method requires the 'unauthorized' request tokens
- * and, if successful will set the authorized request tokens.
- *
- * @return void
- */
- public function getAccessToken() {
- $result = $this->fetch(self::URI_ACCESS_TOKEN, array(), 'POST');
- if ($result['httpStatus'] == "200") {
- $tokens = array();
- parse_str($result['body'], $tokens);
- $this->setToken($tokens['oauth_token'], $tokens['oauth_token_secret']);
- return $this->getToken();
- } else {
- throw new Dropbox_Exception_RequestToken('We were unable to fetch request tokens. This likely means that your consumer key and/or secret are incorrect.');
- }
- }
-
- /**
- * Helper function to properly urlencode parameters.
- * See http://php.net/manual/en/function.oauth-urlencode.php
- *
- * @param string $string
- * @return string
- */
- private function oauth_urlencode($string) {
- return str_replace('%E7', '~', rawurlencode($string));
- }
-
- /**
- * Hash function for hmac_sha1; uses native function if available.
- *
- * @param string $key
- * @param string $data
- * @return string
- */
- private function hash_hmac_sha1($key, $data) {
- if (function_exists('hash_hmac') && in_array('sha1', hash_algos())) {
- return hash_hmac('sha1', $data, $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);
- $hash = pack('H*', $hashfunc(( $key ^ $opad ) . pack('H*', $hashfunc(($key ^ $ipad) . $data))));
-
- return $hash;
- }
- }
-
-
-}
\ No newline at end of file
diff --git a/3rdparty/Dropbox/README.md b/3rdparty/Dropbox/README.md
deleted file mode 100644
index 54e05db762..0000000000
--- a/3rdparty/Dropbox/README.md
+++ /dev/null
@@ -1,31 +0,0 @@
-Dropbox-php
-===========
-
-This PHP library allows you to easily integrate dropbox with PHP.
-
-The following PHP extension is required:
-
-* json
-
-The library makes use of OAuth. At the moment you can use either of these libraries:
-
-[PHP OAuth extension](http://pecl.php.net/package/oauth)
-[PEAR's HTTP_OAUTH package](http://pear.php.net/package/http_oauth)
-
-The extension is recommended, but if you can't install php extensions you should go for the pear package.
-Installing
-----------
-
- pear channel-discover pear.dropbox-php.com
- pear install dropbox-php/Dropbox-alpha
-
-Documentation
--------------
-Check out the [documentation](http://www.dropbox-php.com/docs).
-
-Questions?
-----------
-
-[Dropbox-php Mailing list](http://groups.google.com/group/dropbox-php)
-[Official Dropbox developer forum](http://forums.dropbox.com/forum.php?id=5)
-
diff --git a/3rdparty/Dropbox/autoload.php b/3rdparty/Dropbox/autoload.php
deleted file mode 100644
index 5388ea6334..0000000000
--- a/3rdparty/Dropbox/autoload.php
+++ /dev/null
@@ -1,29 +0,0 @@
-key = $key;
- $this->secret = $secret;
- $this->callback_url = $callback_url;
- }/*}}}*/
-}/*}}}*/
-
-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::urlencodeRFC3986($this->key) .
- "&oauth_token_secret=" . OAuthUtil::urlencodeRFC3986($this->secret);
- }/*}}}*/
-
- function __toString() {/*{{{*/
- return $this->to_string();
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod {/*{{{*/
- public function check_signature(&$request, $consumer, $token, $signature) {
- $built = $this->build_signature($request, $consumer, $token);
- return $built == $signature;
- }
-}/*}}}*/
-
-class OAuthSignatureMethod_HMAC_SHA1 extends OAuthSignatureMethod {/*{{{*/
- function get_name() {/*{{{*/
- return "HMAC-SHA1";
- }/*}}}*/
-
- public function build_signature($request, $consumer, $token, $privKey=NULL) {/*{{{*/
- $base_string = $request->get_signature_base_string();
- $request->base_string = $base_string;
-
- $key_parts = array(
- $consumer->secret,
- ($token) ? $token->secret : ""
- );
-
- $key_parts = array_map(array('OAuthUtil','urlencodeRFC3986'), $key_parts);
- $key = implode('&', $key_parts);
-
- return base64_encode( hash_hmac('sha1', $base_string, $key, true));
- }/*}}}*/
-}/*}}}*/
-
-class OAuthSignatureMethod_RSA_SHA1 extends OAuthSignatureMethod {/*{{{*/
- public function get_name() {/*{{{*/
- return "RSA-SHA1";
- }/*}}}*/
-
- 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 Exception("fetch_public_cert not implemented");
- }/*}}}*/
-
- protected function fetch_private_cert($privKey) {//&$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 Exception("fetch_private_cert not implemented");
- }/*}}}*/
-
- public function build_signature(&$request, $consumer, $token, $privKey) {/*{{{*/
- $base_string = $request->get_signature_base_string();
-
- // Fetch the private key cert based on the request
- //$cert = $this->fetch_private_cert($consumer->privKey);
-
- //Pull the private key ID from the certificate
- //$privatekeyid = openssl_get_privatekey($cert);
-
- // hacked in
- if ($privKey == '') {
- $fp = fopen($GLOBALS['PRIV_KEY_FILE'], "r");
- $privKey = fread($fp, 8192);
- fclose($fp);
- }
- $privatekeyid = openssl_get_privatekey($privKey);
-
- //Check the computer signature against the one passed in the query
- $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 computer 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 {/*{{{*/
- private $parameters;
- private $http_method;
- private $http_url;
- // for debug purposes
- public $base_string;
- public static $version = '1.0';
-
- function __construct($http_method, $http_url, $parameters=NULL) {/*{{{*/
- @$parameters or $parameters = array();
- $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 or $http_url = $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
- @$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
-
- $request_headers = OAuthRequest::get_headers();
-
- // let the library user override things however they'd like, if they know
- // which parameters to use then go for it, for example XMLRPC might want to
- // do this
- if ($parameters) {
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- }
- // next check for the auth header, we need to do some extra stuff
- // if that is the case, namely suck in the parameters from GET or POST
- // so that we can include them in the signature
- else if (@substr($request_headers['Authorization'], 0, 5) == "OAuth") {
- $header_parameters = OAuthRequest::split_header($request_headers['Authorization']);
- if ($http_method == "GET") {
- $req_parameters = $_GET;
- }
- else if ($http_method = "POST") {
- $req_parameters = $_POST;
- }
- $parameters = array_merge($header_parameters, $req_parameters);
- $req = new OAuthRequest($http_method, $http_url, $parameters);
- }
- else if ($http_method == "GET") {
- $req = new OAuthRequest($http_method, $http_url, $_GET);
- }
- else if ($http_method == "POST") {
- $req = new OAuthRequest($http_method, $http_url, $_POST);
- }
- return $req;
- }/*}}}*/
-
- /**
- * 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 or $parameters = array();
- $defaults = array("oauth_version" => OAuthRequest::$version,
- "oauth_nonce" => OAuthRequest::generate_nonce(),
- "oauth_timestamp" => OAuthRequest::generate_timestamp(),
- "oauth_consumer_key" => $consumer->key);
- $parameters = array_merge($defaults, $parameters);
-
- if ($token) {
- $parameters['oauth_token'] = $token->key;
- }
-
- // oauth v1.0a
- /*if (isset($_REQUEST['oauth_verifier'])) {
- $parameters['oauth_verifier'] = $_REQUEST['oauth_verifier'];
- }*/
-
-
- return new OAuthRequest($http_method, $http_url, $parameters);
- }/*}}}*/
-
- public function set_parameter($name, $value) {/*{{{*/
- $this->parameters[$name] = $value;
- }/*}}}*/
-
- public function get_parameter($name) {/*{{{*/
- return $this->parameters[$name];
- }/*}}}*/
-
- public function get_parameters() {/*{{{*/
- return $this->parameters;
- }/*}}}*/
-
- /**
- * Returns the normalized parameters of the request
- *
- * This will be all (except oauth_signature) parameters,
- * sorted first by key, and if duplicate keys, then by
- * value.
- *
- * The returned string will be all the key=value pairs
- * concated by &.
- *
- * @return string
- */
- public function get_signable_parameters() {/*{{{*/
- // Grab all parameters
- $params = $this->parameters;
-
- // Remove oauth_signature if present
- if (isset($params['oauth_signature'])) {
- unset($params['oauth_signature']);
- }
-
- // Urlencode both keys and values
- $keys = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_keys($params));
- $values = array_map(array('OAuthUtil', 'urlencodeRFC3986'), array_values($params));
- $params = array_combine($keys, $values);
-
- // Sort by keys (natsort)
- uksort($params, 'strnatcmp');
-
-if(isset($params['title']) && isset($params['title-exact'])) {
- $temp = $params['title-exact'];
- $title = $params['title'];
-
- unset($params['title']);
- unset($params['title-exact']);
-
- $params['title-exact'] = $temp;
- $params['title'] = $title;
-}
-
- // Generate key=value pairs
- $pairs = array();
- foreach ($params as $key=>$value ) {
- if (is_array($value)) {
- // If the value is an array, it's because there are multiple
- // with the same key, sort them, then add all the pairs
- natsort($value);
- foreach ($value as $v2) {
- $pairs[] = $key . '=' . $v2;
- }
- } else {
- $pairs[] = $key . '=' . $value;
- }
- }
-
- // Return the pairs, concated with &
- return implode('&', $pairs);
- }/*}}}*/
-
- /**
- * 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 = array_map(array('OAuthUtil', 'urlencodeRFC3986'), $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() {/*{{{*/
- $out = $this->get_normalized_http_url() . "?";
- $out .= $this->to_postdata();
- return $out;
- }/*}}}*/
-
- /**
- * builds the data one would send in a POST request
- */
- public function to_postdata() {/*{{{*/
- $total = array();
- foreach ($this->parameters as $k => $v) {
- $total[] = OAuthUtil::urlencodeRFC3986($k) . "=" . OAuthUtil::urlencodeRFC3986($v);
- }
- $out = implode("&", $total);
- return $out;
- }/*}}}*/
-
- /**
- * builds the Authorization: header
- */
- public function to_header() {/*{{{*/
- $out ='Authorization: OAuth ';
- $total = array();
-
- /*
- $sig = $this->parameters['oauth_signature'];
- unset($this->parameters['oauth_signature']);
- uksort($this->parameters, 'strnatcmp');
- $this->parameters['oauth_signature'] = $sig;
- */
-
- foreach ($this->parameters as $k => $v) {
- if (substr($k, 0, 5) != "oauth") continue;
- $out .= OAuthUtil::urlencodeRFC3986($k) . '="' . OAuthUtil::urlencodeRFC3986($v) . '", ';
- }
- $out = substr_replace($out, '', strlen($out) - 2);
-
- return $out;
- }/*}}}*/
-
- public function __toString() {/*{{{*/
- return $this->to_url();
- }/*}}}*/
-
-
- public function sign_request($signature_method, $consumer, $token, $privKey=NULL) {/*{{{*/
- $this->set_parameter("oauth_signature_method", $signature_method->get_name());
- $signature = $this->build_signature($signature_method, $consumer, $token, $privKey);
- $this->set_parameter("oauth_signature", $signature);
- }/*}}}*/
-
- public function build_signature($signature_method, $consumer, $token, $privKey=NULL) {/*{{{*/
- $signature = $signature_method->build_signature($this, $consumer, $token, $privKey);
- 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
- }/*}}}*/
-
- /**
- * util function for turning the Authorization: header into
- * parameters, has to do some unescaping
- */
- private static function split_header($header) {/*{{{*/
- // this should be a regex
- // error cases: commas in parameter values
- $parts = explode(",", $header);
- $out = array();
- foreach ($parts as $param) {
- $param = ltrim($param);
- // skip the "realm" param, nobody ever uses it anyway
- if (substr($param, 0, 5) != "oauth") continue;
-
- $param_parts = explode("=", $param);
-
- // rawurldecode() used because urldecode() will turn a "+" in the
- // value into a space
- $out[$param_parts[0]] = rawurldecode(substr($param_parts[1], 1, -1));
- }
- return $out;
- }/*}}}*/
-
- /**
- * helper to try to sort out headers for people who aren't running apache
- */
- private 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
- return apache_request_headers();
- }
- // otherwise we don't have apache and are just going to have to hope
- // that $_SERVER actually contains what we need
- $out = array();
- 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;
- }/*}}}*/
-}/*}}}*/
-
-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);
-
- $new_token = $this->data_store->new_request_token($consumer);
-
- 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);
-
- $new_token = $this->data_store->new_access_token($token, $consumer);
-
- 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) {
- $version = 1.0;
- }
- if ($version && $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->get_parameter("oauth_signature_method");
- if (!$signature_method) {
- $signature_method = "PLAINTEXT";
- }
- 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->get_parameter("oauth_consumer_key");
- 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->get_parameter('oauth_token');
- $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->get_parameter('oauth_timestamp');
- $nonce = @$request->get_parameter('oauth_nonce');
-
- $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) {/*{{{*/
- // verify that timestamp is recentish
- $now = time();
- if ($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) {/*{{{*/
- // 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 fetch_request_token($consumer) {/*{{{*/
- // return a new token attached to this consumer
- }/*}}}*/
-
- function fetch_access_token($token, $consumer) {/*{{{*/
- // 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
- }/*}}}*/
-
-}/*}}}*/
-
-
-/* A very naive dbm-based oauth storage
- */
-class SimpleOAuthDataStore extends OAuthDataStore {/*{{{*/
- private $dbh;
-
- function __construct($path = "oauth.gdbm") {/*{{{*/
- $this->dbh = dba_popen($path, 'c', 'gdbm');
- }/*}}}*/
-
- function __destruct() {/*{{{*/
- dba_close($this->dbh);
- }/*}}}*/
-
- function lookup_consumer($consumer_key) {/*{{{*/
- $rv = dba_fetch("consumer_$consumer_key", $this->dbh);
- if ($rv === FALSE) {
- return NULL;
- }
- $obj = unserialize($rv);
- if (!($obj instanceof OAuthConsumer)) {
- return NULL;
- }
- return $obj;
- }/*}}}*/
-
- function lookup_token($consumer, $token_type, $token) {/*{{{*/
- $rv = dba_fetch("${token_type}_${token}", $this->dbh);
- if ($rv === FALSE) {
- return NULL;
- }
- $obj = unserialize($rv);
- if (!($obj instanceof OAuthToken)) {
- return NULL;
- }
- return $obj;
- }/*}}}*/
-
- function lookup_nonce($consumer, $token, $nonce, $timestamp) {/*{{{*/
- return dba_exists("nonce_$nonce", $this->dbh);
- }/*}}}*/
-
- function new_token($consumer, $type="request") {/*{{{*/
- $key = md5(time());
- $secret = time() + time();
- $token = new OAuthToken($key, md5(md5($secret)));
- if (!dba_insert("${type}_$key", serialize($token), $this->dbh)) {
- throw new OAuthException("doooom!");
- }
- return $token;
- }/*}}}*/
-
- function new_request_token($consumer) {/*{{{*/
- return $this->new_token($consumer, "request");
- }/*}}}*/
-
- function new_access_token($token, $consumer) {/*{{{*/
-
- $token = $this->new_token($consumer, 'access');
- dba_delete("request_" . $token->key, $this->dbh);
- return $token;
- }/*}}}*/
-}/*}}}*/
-
-class OAuthUtil {/*{{{*/
- public static function urlencodeRFC3986($string) {/*{{{*/
- return str_replace('%7E', '~', rawurlencode($string));
- }/*}}}*/
-
- public static function urldecodeRFC3986($string) {/*{{{*/
- return rawurldecode($string);
- }/*}}}*/
-}/*}}}*/
-
-?>
\ No newline at end of file
diff --git a/3rdparty/Google/common.inc.php b/3rdparty/Google/common.inc.php
deleted file mode 100755
index 57185cdc4d..0000000000
--- a/3rdparty/Google/common.inc.php
+++ /dev/null
@@ -1,185 +0,0 @@
-
- */
-
-$PRIV_KEY_FILE = '/path/to/your/rsa_private_key.pem';
-
-// OAuth library - http://oauth.googlecode.com/svn/code/php/
-require_once('OAuth.php');
-
-// Google's accepted signature methods
-$hmac_method = new OAuthSignatureMethod_HMAC_SHA1();
-$rsa_method = new OAuthSignatureMethod_RSA_SHA1();
-$SIG_METHODS = array($rsa_method->get_name() => $rsa_method,
- $hmac_method->get_name() => $hmac_method);
-
-/**
- * Makes an HTTP request to the specified URL
- *
- * @param string $http_method The HTTP method (GET, POST, PUT, DELETE)
- * @param string $url Full URL of the resource to access
- * @param array $extraHeaders (optional) Additional headers to include in each
- * request. Elements are header/value pair strings ('Host: example.com')
- * @param string $postData (optional) POST/PUT request body
- * @param bool $returnResponseHeaders True if resp. headers should be returned.
- * @return string Response body from the server
- */
-function send_signed_request($http_method, $url, $extraHeaders=null,
- $postData=null, $returnResponseHeaders=true) {
- $curl = curl_init($url);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($curl, CURLOPT_FAILONERROR, false);
- curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
-
- // Return request headers in the reponse
-// curl_setopt($curl, CURLINFO_HEADER_OUT, true);
-
- // Return response headers ni the response?
- if ($returnResponseHeaders) {
- curl_setopt($curl, CURLOPT_HEADER, true);
- }
-
- $headers = array();
- //$headers[] = 'GData-Version: 2.0'; // use GData v2 by default
- if (is_array($extraHeaders)) {
- $headers = array_merge($headers, $extraHeaders);
- }
-
- // Setup default curl options for each type of HTTP request.
- // This is also a great place to add additional headers for each request.
- switch($http_method) {
- case 'GET':
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
- break;
- case 'POST':
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($curl, CURLOPT_POST, 1);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
- break;
- case 'PUT':
- $headers[] = 'If-Match: *';
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method);
- curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
- break;
- case 'DELETE':
- $headers[] = 'If-Match: *';
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $http_method);
- break;
- default:
- curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
- }
-
- // Execute the request. If an error occures, fill the response body with it.
- $response = curl_exec($curl);
- if (!$response) {
- $response = curl_error($curl);
- }
-
- // Add server's response headers to our response body
- $response = curl_getinfo($curl, CURLINFO_HEADER_OUT) . $response;
-
- curl_close($curl);
-
- return $response;
-}
-
-/**
-* Takes XML as a string and returns it nicely indented
-*
-* @param string $xml The xml to beautify
-* @param boolean $html_output True if returned XML should be escaped for HTML.
-* @return string The beautified xml
-*/
-function xml_pretty_printer($xml, $html_output=false) {
- $xml_obj = new SimpleXMLElement($xml);
- $level = 2;
-
- // Get an array containing each XML element
- $xml = explode("\n", preg_replace('/>\s*', ">\n<", $xml_obj->asXML()));
-
- // Hold current indentation level
- $indent = 0;
-
- $pretty = array();
-
- // Shift off opening XML tag if present
- if (count($xml) && preg_match('/^<\?\s*xml/', $xml[0])) {
- $pretty[] = array_shift($xml);
- }
-
- foreach ($xml as $el) {
- if (preg_match('/^<([\w])+[^>\/]*>$/U', $el)) {
- // opening tag, increase indent
- $pretty[] = str_repeat(' ', $indent) . $el;
- $indent += $level;
- } else {
- if (preg_match('/^<\/.+>$/', $el)) {
- $indent -= $level; // closing tag, decrease indent
- }
- if ($indent < 0) {
- $indent += $level;
- }
- $pretty[] = str_repeat(' ', $indent) . $el;
- }
- }
-
- $xml = implode("\n", $pretty);
- return $html_output ? htmlentities($xml) : $xml;
-}
-
-/**
- * Joins key/value pairs by $inner_glue and each pair together by $outer_glue.
- *
- * Example: implode_assoc('=', '&', array('a' => 1, 'b' => 2)) === 'a=1&b=2'
- *
- * @param string $inner_glue What to implode each key/value pair with
- * @param string $outer_glue What to impode each key/value string subset with
- * @param array $array Associative array of query parameters
- * @return string Urlencoded string of query parameters
- */
-function implode_assoc($inner_glue, $outer_glue, $array) {
- $output = array();
- foreach($array as $key => $item) {
- $output[] = $key . $inner_glue . urlencode($item);
- }
- return implode($outer_glue, $output);
-}
-
-/**
- * Explodes a string of key/value url parameters into an associative array.
- * This method performs the compliment operations of implode_assoc().
- *
- * Example: explode_assoc('=', '&', 'a=1&b=2') === array('a' => 1, 'b' => 2)
- *
- * @param string $inner_glue What each key/value pair is joined with
- * @param string $outer_glue What each set of key/value pairs is joined with.
- * @param array $array Associative array of query parameters
- * @return array Urlencoded string of query parameters
- */
-function explode_assoc($inner_glue, $outer_glue, $params) {
- $tempArr = explode($outer_glue, $params);
- foreach($tempArr as $val) {
- $pos = strpos($val, $inner_glue);
- $key = substr($val, 0, $pos);
- $array2[$key] = substr($val, $pos + 1, strlen($val));
- }
- return $array2;
-}
-
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2.php b/3rdparty/MDB2.php
deleted file mode 100644
index a0ead9b9bc..0000000000
--- a/3rdparty/MDB2.php
+++ /dev/null
@@ -1,4587 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-
-require_once 'PEAR.php';
-
-// {{{ Error constants
-
-/**
- * The method mapErrorCode in each MDB2_dbtype implementation maps
- * native error codes to one of these.
- *
- * If you add an error code here, make sure you also add a textual
- * version of it in MDB2::errorMessage().
- */
-
-define('MDB2_OK', true);
-define('MDB2_ERROR', -1);
-define('MDB2_ERROR_SYNTAX', -2);
-define('MDB2_ERROR_CONSTRAINT', -3);
-define('MDB2_ERROR_NOT_FOUND', -4);
-define('MDB2_ERROR_ALREADY_EXISTS', -5);
-define('MDB2_ERROR_UNSUPPORTED', -6);
-define('MDB2_ERROR_MISMATCH', -7);
-define('MDB2_ERROR_INVALID', -8);
-define('MDB2_ERROR_NOT_CAPABLE', -9);
-define('MDB2_ERROR_TRUNCATED', -10);
-define('MDB2_ERROR_INVALID_NUMBER', -11);
-define('MDB2_ERROR_INVALID_DATE', -12);
-define('MDB2_ERROR_DIVZERO', -13);
-define('MDB2_ERROR_NODBSELECTED', -14);
-define('MDB2_ERROR_CANNOT_CREATE', -15);
-define('MDB2_ERROR_CANNOT_DELETE', -16);
-define('MDB2_ERROR_CANNOT_DROP', -17);
-define('MDB2_ERROR_NOSUCHTABLE', -18);
-define('MDB2_ERROR_NOSUCHFIELD', -19);
-define('MDB2_ERROR_NEED_MORE_DATA', -20);
-define('MDB2_ERROR_NOT_LOCKED', -21);
-define('MDB2_ERROR_VALUE_COUNT_ON_ROW', -22);
-define('MDB2_ERROR_INVALID_DSN', -23);
-define('MDB2_ERROR_CONNECT_FAILED', -24);
-define('MDB2_ERROR_EXTENSION_NOT_FOUND',-25);
-define('MDB2_ERROR_NOSUCHDB', -26);
-define('MDB2_ERROR_ACCESS_VIOLATION', -27);
-define('MDB2_ERROR_CANNOT_REPLACE', -28);
-define('MDB2_ERROR_CONSTRAINT_NOT_NULL',-29);
-define('MDB2_ERROR_DEADLOCK', -30);
-define('MDB2_ERROR_CANNOT_ALTER', -31);
-define('MDB2_ERROR_MANAGER', -32);
-define('MDB2_ERROR_MANAGER_PARSE', -33);
-define('MDB2_ERROR_LOADMODULE', -34);
-define('MDB2_ERROR_INSUFFICIENT_DATA', -35);
-define('MDB2_ERROR_NO_PERMISSION', -36);
-define('MDB2_ERROR_DISCONNECT_FAILED', -37);
-
-// }}}
-// {{{ Verbose constants
-/**
- * These are just helper constants to more verbosely express parameters to prepare()
- */
-
-define('MDB2_PREPARE_MANIP', false);
-define('MDB2_PREPARE_RESULT', null);
-
-// }}}
-// {{{ Fetchmode constants
-
-/**
- * This is a special constant that tells MDB2 the user hasn't specified
- * any particular get mode, so the default should be used.
- */
-define('MDB2_FETCHMODE_DEFAULT', 0);
-
-/**
- * Column data indexed by numbers, ordered from 0 and up
- */
-define('MDB2_FETCHMODE_ORDERED', 1);
-
-/**
- * Column data indexed by column names
- */
-define('MDB2_FETCHMODE_ASSOC', 2);
-
-/**
- * Column data as object properties
- */
-define('MDB2_FETCHMODE_OBJECT', 3);
-
-/**
- * For multi-dimensional results: normally the first level of arrays
- * is the row number, and the second level indexed by column number or name.
- * MDB2_FETCHMODE_FLIPPED switches this order, so the first level of arrays
- * is the column name, and the second level the row number.
- */
-define('MDB2_FETCHMODE_FLIPPED', 4);
-
-// }}}
-// {{{ Portability mode constants
-
-/**
- * Portability: turn off all portability features.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_NONE', 0);
-
-/**
- * Portability: convert names of tables and fields to case defined in the
- * "field_case" option when using the query*(), fetch*() and tableInfo() methods.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_FIX_CASE', 1);
-
-/**
- * Portability: right trim the data output by query*() and fetch*().
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_RTRIM', 2);
-
-/**
- * Portability: force reporting the number of rows deleted.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_DELETE_COUNT', 4);
-
-/**
- * Portability: not needed in MDB2 (just left here for compatibility to DB)
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_NUMROWS', 8);
-
-/**
- * Portability: makes certain error messages in certain drivers compatible
- * with those from other DBMS's.
- *
- * + mysql, mysqli: change unique/primary key constraints
- * MDB2_ERROR_ALREADY_EXISTS -> MDB2_ERROR_CONSTRAINT
- *
- * + odbc(access): MS's ODBC driver reports 'no such field' as code
- * 07001, which means 'too few parameters.' When this option is on
- * that code gets mapped to MDB2_ERROR_NOSUCHFIELD.
- *
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_ERRORS', 16);
-
-/**
- * Portability: convert empty values to null strings in data output by
- * query*() and fetch*().
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_EMPTY_TO_NULL', 32);
-
-/**
- * Portability: removes database/table qualifiers from associative indexes
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES', 64);
-
-/**
- * Portability: turn on all portability features.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_ALL', 127);
-
-// }}}
-// {{{ Globals for class instance tracking
-
-/**
- * These are global variables that are used to track the various class instances
- */
-
-$GLOBALS['_MDB2_databases'] = array();
-$GLOBALS['_MDB2_dsninfo_default'] = array(
- 'phptype' => false,
- 'dbsyntax' => false,
- 'username' => false,
- 'password' => false,
- 'protocol' => false,
- 'hostspec' => false,
- 'port' => false,
- 'socket' => false,
- 'database' => false,
- 'mode' => false,
-);
-
-// }}}
-// {{{ class MDB2
-
-/**
- * The main 'MDB2' class is simply a container class with some static
- * methods for creating DB objects as well as some utility functions
- * common to all parts of DB.
- *
- * The object model of MDB2 is as follows (indentation means inheritance):
- *
- * MDB2 The main MDB2 class. This is simply a utility class
- * with some 'static' methods for creating MDB2 objects as
- * well as common utility functions for other MDB2 classes.
- *
- * MDB2_Driver_Common The base for each MDB2 implementation. Provides default
- * | implementations (in OO lingo virtual methods) for
- * | the actual DB implementations as well as a bunch of
- * | query utility functions.
- * |
- * +-MDB2_Driver_mysql The MDB2 implementation for MySQL. Inherits MDB2_Driver_Common.
- * When calling MDB2::factory or MDB2::connect for MySQL
- * connections, the object returned is an instance of this
- * class.
- * +-MDB2_Driver_pgsql The MDB2 implementation for PostGreSQL. Inherits MDB2_Driver_Common.
- * When calling MDB2::factory or MDB2::connect for PostGreSQL
- * connections, the object returned is an instance of this
- * class.
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2
-{
- // {{{ function setOptions($db, $options)
-
- /**
- * set option array in an exiting database object
- *
- * @param MDB2_Driver_Common MDB2 object
- * @param array An associative array of option names and their values.
- *
- * @return mixed MDB2_OK or a PEAR Error object
- *
- * @access public
- */
- static function setOptions($db, $options)
- {
- if (is_array($options)) {
- foreach ($options as $option => $value) {
- $test = $db->setOption($option, $value);
- if (MDB2::isError($test)) {
- return $test;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function classExists($classname)
-
- /**
- * Checks if a class exists without triggering __autoload
- *
- * @param string classname
- *
- * @return bool true success and false on error
- * @static
- * @access public
- */
- static function classExists($classname)
- {
- return class_exists($classname, false);
- }
-
- // }}}
- // {{{ function loadClass($class_name, $debug)
-
- /**
- * Loads a PEAR class.
- *
- * @param string classname to load
- * @param bool if errors should be suppressed
- *
- * @return mixed true success or PEAR_Error on failure
- *
- * @access public
- */
- static function loadClass($class_name, $debug)
- {
- if (!MDB2::classExists($class_name)) {
- $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
- if ($debug) {
- $include = include_once($file_name);
- } else {
- $include = @include_once($file_name);
- }
- if (!$include) {
- if (!MDB2::fileExists($file_name)) {
- $msg = "unable to find package '$class_name' file '$file_name'";
- } else {
- $msg = "unable to load class '$class_name' from file '$file_name'";
- }
- $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
- return $err;
- }
- if (!MDB2::classExists($class_name)) {
- $msg = "unable to load class '$class_name' from file '$file_name'";
- $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
- return $err;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function factory($dsn, $options = false)
-
- /**
- * Create a new MDB2 object for the specified database type
- *
- * @param mixed 'data source name', see the MDB2::parseDSN
- * method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * @param array An associative array of option names and
- * their values.
- *
- * @return mixed a newly created MDB2 object, or false on error
- *
- * @access public
- */
- static function factory($dsn, $options = false)
- {
- $dsninfo = MDB2::parseDSN($dsn);
- if (empty($dsninfo['phptype'])) {
- $err = MDB2::raiseError(MDB2_ERROR_NOT_FOUND,
- null, null, 'no RDBMS driver specified');
- return $err;
- }
- $class_name = 'MDB2_Driver_'.$dsninfo['phptype'];
-
- $debug = (!empty($options['debug']));
- $err = MDB2::loadClass($class_name, $debug);
- if (MDB2::isError($err)) {
- return $err;
- }
-
- $db = new $class_name();
- $db->setDSN($dsninfo);
- $err = MDB2::setOptions($db, $options);
- if (MDB2::isError($err)) {
- return $err;
- }
-
- return $db;
- }
-
- // }}}
- // {{{ function connect($dsn, $options = false)
-
- /**
- * Create a new MDB2_Driver_* connection object and connect to the specified
- * database
- *
- * @param mixed $dsn 'data source name', see the MDB2::parseDSN
- * method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * @param array $options An associative array of option names and
- * their values.
- *
- * @return mixed a newly created MDB2 connection object, or a MDB2
- * error object on error
- *
- * @access public
- * @see MDB2::parseDSN
- */
- static function connect($dsn, $options = false)
- {
- $db = MDB2::factory($dsn, $options);
- if (MDB2::isError($db)) {
- return $db;
- }
-
- $err = $db->connect();
- if (MDB2::isError($err)) {
- $dsn = $db->getDSN('string', 'xxx');
- $db->disconnect();
- $err->addUserInfo($dsn);
- return $err;
- }
-
- return $db;
- }
-
- // }}}
- // {{{ function singleton($dsn = null, $options = false)
-
- /**
- * Returns a MDB2 connection with the requested DSN.
- * A new MDB2 connection object is only created if no object with the
- * requested DSN exists yet.
- *
- * @param mixed 'data source name', see the MDB2::parseDSN
- * method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * @param array An associative array of option names and
- * their values.
- *
- * @return mixed a newly created MDB2 connection object, or a MDB2
- * error object on error
- *
- * @access public
- * @see MDB2::parseDSN
- */
- static function singleton($dsn = null, $options = false)
- {
- if ($dsn) {
- $dsninfo = MDB2::parseDSN($dsn);
- $dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo);
- $keys = array_keys($GLOBALS['_MDB2_databases']);
- for ($i=0, $j=count($keys); $i<$j; ++$i) {
- if (isset($GLOBALS['_MDB2_databases'][$keys[$i]])) {
- $tmp_dsn = $GLOBALS['_MDB2_databases'][$keys[$i]]->getDSN('array');
- if (count(array_diff_assoc($tmp_dsn, $dsninfo)) == 0) {
- MDB2::setOptions($GLOBALS['_MDB2_databases'][$keys[$i]], $options);
- return $GLOBALS['_MDB2_databases'][$keys[$i]];
- }
- }
- }
- } elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) {
- return $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];
- }
- $db = MDB2::factory($dsn, $options);
- return $db;
- }
-
- // }}}
- // {{{ function areEquals()
-
- /**
- * It looks like there's a memory leak in array_diff() in PHP 5.1.x,
- * so use this method instead.
- * @see http://pear.php.net/bugs/bug.php?id=11790
- *
- * @param array $arr1
- * @param array $arr2
- * @return boolean
- */
- static function areEquals($arr1, $arr2)
- {
- if (count($arr1) != count($arr2)) {
- return false;
- }
- foreach (array_keys($arr1) as $k) {
- if (!array_key_exists($k, $arr2) || $arr1[$k] != $arr2[$k]) {
- return false;
- }
- }
- return true;
- }
-
- // }}}
- // {{{ function loadFile($file)
-
- /**
- * load a file (like 'Date')
- *
- * @param string $file name of the file in the MDB2 directory (without '.php')
- *
- * @return string name of the file that was included
- *
- * @access public
- */
- static function loadFile($file)
- {
- $file_name = 'MDB2'.DIRECTORY_SEPARATOR.$file.'.php';
- if (!MDB2::fileExists($file_name)) {
- return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'unable to find: '.$file_name);
- }
- if (!include_once($file_name)) {
- return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'unable to load driver class: '.$file_name);
- }
- return $file_name;
- }
-
- // }}}
- // {{{ function apiVersion()
-
- /**
- * Return the MDB2 API version
- *
- * @return string the MDB2 API version number
- *
- * @access public
- */
- function apiVersion()
- {
- return '@package_version@';
- }
-
- // }}}
- // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
-
- /**
- * This method is used to communicate an error and invoke error
- * callbacks etc. Basically a wrapper for PEAR::raiseError
- * without the message string.
- *
- * @param mixed int error code
- *
- * @param int error mode, see PEAR_Error docs
- *
- * @param mixed If error mode is PEAR_ERROR_TRIGGER, this is the
- * error level (E_USER_NOTICE etc). If error mode is
- * PEAR_ERROR_CALLBACK, this is the callback function,
- * either as a function name, or as an array of an
- * object and method name. For other error modes this
- * parameter is ignored.
- *
- * @param string Extra debug information. Defaults to the last
- * query and native error code.
- *
- * @return PEAR_Error instance of a PEAR Error object
- *
- * @access private
- * @see PEAR_Error
- */
- public static function &raiseError($code = null,
- $mode = null,
- $options = null,
- $userinfo = null,
- $dummy1 = null,
- $dummy2 = null,
- $dummy3 = false)
- {
- $pear = new PEAR;
- $err = $pear->raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
- return $err;
- }
-
- // }}}
- // {{{ function isError($data, $code = null)
-
- /**
- * Tell whether a value is a MDB2 error.
- *
- * @param mixed the value to test
- * @param int if is an error object, return true
- * only if $code is a string and
- * $db->getMessage() == $code or
- * $code is an integer and $db->getCode() == $code
- *
- * @return bool true if parameter is an error
- *
- * @access public
- */
- static function isError($data, $code = null)
- {
- if ($data instanceof MDB2_Error) {
- if (null === $code) {
- return true;
- }
- if (is_string($code)) {
- return $data->getMessage() === $code;
- }
- return in_array($data->getCode(), (array)$code);
- }
- return false;
- }
-
- // }}}
- // {{{ function isConnection($value)
-
- /**
- * Tell whether a value is a MDB2 connection
- *
- * @param mixed value to test
- *
- * @return bool whether $value is a MDB2 connection
- * @access public
- */
- static function isConnection($value)
- {
- return ($value instanceof MDB2_Driver_Common);
- }
-
- // }}}
- // {{{ function isResult($value)
-
- /**
- * Tell whether a value is a MDB2 result
- *
- * @param mixed $value value to test
- *
- * @return bool whether $value is a MDB2 result
- *
- * @access public
- */
- function isResult($value)
- {
- return ($value instanceof MDB2_Result);
- }
-
- // }}}
- // {{{ function isResultCommon($value)
-
- /**
- * Tell whether a value is a MDB2 result implementing the common interface
- *
- * @param mixed $value value to test
- *
- * @return bool whether $value is a MDB2 result implementing the common interface
- *
- * @access public
- */
- static function isResultCommon($value)
- {
- return ($value instanceof MDB2_Result_Common);
- }
-
- // }}}
- // {{{ function isStatement($value)
-
- /**
- * Tell whether a value is a MDB2 statement interface
- *
- * @param mixed value to test
- *
- * @return bool whether $value is a MDB2 statement interface
- *
- * @access public
- */
- function isStatement($value)
- {
- return ($value instanceof MDB2_Statement_Common);
- }
-
- // }}}
- // {{{ function errorMessage($value = null)
-
- /**
- * Return a textual error message for a MDB2 error code
- *
- * @param int|array integer error code,
- null to get the current error code-message map,
- or an array with a new error code-message map
- *
- * @return string error message, or false if the error code was
- * not recognized
- *
- * @access public
- */
- static function errorMessage($value = null)
- {
- static $errorMessages;
-
- if (is_array($value)) {
- $errorMessages = $value;
- return MDB2_OK;
- }
-
- if (!isset($errorMessages)) {
- $errorMessages = array(
- MDB2_OK => 'no error',
- MDB2_ERROR => 'unknown error',
- MDB2_ERROR_ALREADY_EXISTS => 'already exists',
- MDB2_ERROR_CANNOT_CREATE => 'can not create',
- MDB2_ERROR_CANNOT_ALTER => 'can not alter',
- MDB2_ERROR_CANNOT_REPLACE => 'can not replace',
- MDB2_ERROR_CANNOT_DELETE => 'can not delete',
- MDB2_ERROR_CANNOT_DROP => 'can not drop',
- MDB2_ERROR_CONSTRAINT => 'constraint violation',
- MDB2_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
- MDB2_ERROR_DIVZERO => 'division by zero',
- MDB2_ERROR_INVALID => 'invalid',
- MDB2_ERROR_INVALID_DATE => 'invalid date or time',
- MDB2_ERROR_INVALID_NUMBER => 'invalid number',
- MDB2_ERROR_MISMATCH => 'mismatch',
- MDB2_ERROR_NODBSELECTED => 'no database selected',
- MDB2_ERROR_NOSUCHFIELD => 'no such field',
- MDB2_ERROR_NOSUCHTABLE => 'no such table',
- MDB2_ERROR_NOT_CAPABLE => 'MDB2 backend not capable',
- MDB2_ERROR_NOT_FOUND => 'not found',
- MDB2_ERROR_NOT_LOCKED => 'not locked',
- MDB2_ERROR_SYNTAX => 'syntax error',
- MDB2_ERROR_UNSUPPORTED => 'not supported',
- MDB2_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
- MDB2_ERROR_INVALID_DSN => 'invalid DSN',
- MDB2_ERROR_CONNECT_FAILED => 'connect failed',
- MDB2_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
- MDB2_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
- MDB2_ERROR_NOSUCHDB => 'no such database',
- MDB2_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
- MDB2_ERROR_LOADMODULE => 'error while including on demand module',
- MDB2_ERROR_TRUNCATED => 'truncated',
- MDB2_ERROR_DEADLOCK => 'deadlock detected',
- MDB2_ERROR_NO_PERMISSION => 'no permission',
- MDB2_ERROR_DISCONNECT_FAILED => 'disconnect failed',
- );
- }
-
- if (null === $value) {
- return $errorMessages;
- }
-
- if (MDB2::isError($value)) {
- $value = $value->getCode();
- }
-
- return isset($errorMessages[$value]) ?
- $errorMessages[$value] : $errorMessages[MDB2_ERROR];
- }
-
- // }}}
- // {{{ function parseDSN($dsn)
-
- /**
- * Parse a data source name.
- *
- * Additional keys can be added by appending a URI query string to the
- * end of the DSN.
- *
- * The format of the supplied DSN is in its fullest form:
- *
- * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
- *
- *
- * Most variations are allowed:
- *
- * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644
- * phptype://username:password@hostspec/database_name
- * phptype://username:password@hostspec
- * phptype://username@hostspec
- * phptype://hostspec/database
- * phptype://hostspec
- * phptype(dbsyntax)
- * phptype
- *
- *
- * @param string Data Source Name to be parsed
- *
- * @return array an associative array with the following keys:
- * + phptype: Database backend used in PHP (mysql, odbc etc.)
- * + dbsyntax: Database used with regards to SQL syntax etc.
- * + protocol: Communication protocol to use (tcp, unix etc.)
- * + hostspec: Host specification (hostname[:port])
- * + database: Database to use on the DBMS server
- * + username: User name for login
- * + password: Password for login
- *
- * @access public
- * @author Tomas V.V.Cox
- */
- static function parseDSN($dsn)
- {
- $parsed = $GLOBALS['_MDB2_dsninfo_default'];
-
- if (is_array($dsn)) {
- $dsn = array_merge($parsed, $dsn);
- if (!$dsn['dbsyntax']) {
- $dsn['dbsyntax'] = $dsn['phptype'];
- }
- return $dsn;
- }
-
- // Find phptype and dbsyntax
- if (($pos = strpos($dsn, '://')) !== false) {
- $str = substr($dsn, 0, $pos);
- $dsn = substr($dsn, $pos + 3);
- } else {
- $str = $dsn;
- $dsn = null;
- }
-
- // Get phptype and dbsyntax
- // $str => phptype(dbsyntax)
- if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
- $parsed['phptype'] = $arr[1];
- $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2];
- } else {
- $parsed['phptype'] = $str;
- $parsed['dbsyntax'] = $str;
- }
-
- if (!count($dsn)) {
- return $parsed;
- }
-
- // Get (if found): username and password
- // $dsn => username:password@protocol+hostspec/database
- if (($at = strrpos($dsn,'@')) !== false) {
- $str = substr($dsn, 0, $at);
- $dsn = substr($dsn, $at + 1);
- if (($pos = strpos($str, ':')) !== false) {
- $parsed['username'] = rawurldecode(substr($str, 0, $pos));
- $parsed['password'] = rawurldecode(substr($str, $pos + 1));
- } else {
- $parsed['username'] = rawurldecode($str);
- }
- }
-
- // Find protocol and hostspec
-
- // $dsn => proto(proto_opts)/database
- if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) {
- $proto = $match[1];
- $proto_opts = $match[2] ? $match[2] : false;
- $dsn = $match[3];
-
- // $dsn => protocol+hostspec/database (old format)
- } else {
- if (strpos($dsn, '+') !== false) {
- list($proto, $dsn) = explode('+', $dsn, 2);
- }
- if ( strpos($dsn, '//') === 0
- && strpos($dsn, '/', 2) !== false
- && $parsed['phptype'] == 'oci8'
- ) {
- //oracle's "Easy Connect" syntax:
- //"username/password@[//]host[:port][/service_name]"
- //e.g. "scott/tiger@//mymachine:1521/oracle"
- $proto_opts = $dsn;
- $pos = strrpos($proto_opts, '/');
- $dsn = substr($proto_opts, $pos + 1);
- $proto_opts = substr($proto_opts, 0, $pos);
- } elseif (strpos($dsn, '/') !== false) {
- list($proto_opts, $dsn) = explode('/', $dsn, 2);
- } else {
- $proto_opts = $dsn;
- $dsn = null;
- }
- }
-
- // process the different protocol options
- $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp';
- $proto_opts = rawurldecode($proto_opts);
- if (strpos($proto_opts, ':') !== false) {
- list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
- }
- if ($parsed['protocol'] == 'tcp') {
- $parsed['hostspec'] = $proto_opts;
- } elseif ($parsed['protocol'] == 'unix') {
- $parsed['socket'] = $proto_opts;
- }
-
- // Get dabase if any
- // $dsn => database
- if ($dsn) {
- // /database
- if (($pos = strpos($dsn, '?')) === false) {
- $parsed['database'] = rawurldecode($dsn);
- // /database?param1=value1¶m2=value2
- } else {
- $parsed['database'] = rawurldecode(substr($dsn, 0, $pos));
- $dsn = substr($dsn, $pos + 1);
- if (strpos($dsn, '&') !== false) {
- $opts = explode('&', $dsn);
- } else { // database?param1=value1
- $opts = array($dsn);
- }
- foreach ($opts as $opt) {
- list($key, $value) = explode('=', $opt);
- if (!array_key_exists($key, $parsed) || false === $parsed[$key]) {
- // don't allow params overwrite
- $parsed[$key] = rawurldecode($value);
- }
- }
- }
- }
-
- return $parsed;
- }
-
- // }}}
- // {{{ function fileExists($file)
-
- /**
- * Checks if a file exists in the include path
- *
- * @param string filename
- *
- * @return bool true success and false on error
- *
- * @access public
- */
- static function fileExists($file)
- {
- // safe_mode does notwork with is_readable()
- if (!@ini_get('safe_mode')) {
- $dirs = explode(PATH_SEPARATOR, ini_get('include_path'));
- foreach ($dirs as $dir) {
- if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
- return true;
- }
- }
- } else {
- $fp = @fopen($file, 'r', true);
- if (is_resource($fp)) {
- @fclose($fp);
- return true;
- }
- }
- return false;
- }
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Error extends PEAR_Error
-
-/**
- * MDB2_Error implements a class for reporting portable database error
- * messages.
- *
- * @package MDB2
- * @category Database
- * @author Stig Bakken
- */
-class MDB2_Error extends PEAR_Error
-{
- // {{{ constructor: function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null)
-
- /**
- * MDB2_Error constructor.
- *
- * @param mixed MDB2 error code, or string with error message.
- * @param int what 'error mode' to operate in
- * @param int what error level to use for $mode & PEAR_ERROR_TRIGGER
- * @param mixed additional debug info, such as the last query
- */
- function __construct($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN,
- $level = E_USER_NOTICE, $debuginfo = null, $dummy = null)
- {
- if (null === $code) {
- $code = MDB2_ERROR;
- }
- $this->PEAR_Error('MDB2 Error: '.MDB2::errorMessage($code), $code,
- $mode, $level, $debuginfo);
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Driver_Common extends PEAR
-
-/**
- * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Common
-{
- // {{{ Variables (Properties)
-
- /**
- * @var MDB2_Driver_Datatype_Common
- */
- public $datatype;
-
- /**
- * @var MDB2_Extended
- */
- public $extended;
-
- /**
- * @var MDB2_Driver_Function_Common
- */
- public $function;
-
- /**
- * @var MDB2_Driver_Manager_Common
- */
- public $manager;
-
- /**
- * @var MDB2_Driver_Native_Commonn
- */
- public $native;
-
- /**
- * @var MDB2_Driver_Reverse_Common
- */
- public $reverse;
-
- /**
- * index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array
- * @var int
- * @access public
- */
- public $db_index = 0;
-
- /**
- * DSN used for the next query
- * @var array
- * @access protected
- */
- public $dsn = array();
-
- /**
- * DSN that was used to create the current connection
- * @var array
- * @access protected
- */
- public $connected_dsn = array();
-
- /**
- * connection resource
- * @var mixed
- * @access protected
- */
- public $connection = 0;
-
- /**
- * if the current opened connection is a persistent connection
- * @var bool
- * @access protected
- */
- public $opened_persistent;
-
- /**
- * the name of the database for the next query
- * @var string
- * @access public
- */
- public $database_name = '';
-
- /**
- * the name of the database currently selected
- * @var string
- * @access protected
- */
- public $connected_database_name = '';
-
- /**
- * server version information
- * @var string
- * @access protected
- */
- public $connected_server_info = '';
-
- /**
- * list of all supported features of the given driver
- * @var array
- * @access public
- */
- public $supported = array(
- 'sequences' => false,
- 'indexes' => false,
- 'affected_rows' => false,
- 'summary_functions' => false,
- 'order_by_text' => false,
- 'transactions' => false,
- 'savepoints' => false,
- 'current_id' => false,
- 'limit_queries' => false,
- 'LOBs' => false,
- 'replace' => false,
- 'sub_selects' => false,
- 'triggers' => false,
- 'auto_increment' => false,
- 'primary_key' => false,
- 'result_introspection' => false,
- 'prepared_statements' => false,
- 'identifier_quoting' => false,
- 'pattern_escaping' => false,
- 'new_link' => false,
- );
-
- /**
- * Array of supported options that can be passed to the MDB2 instance.
- *
- * The options can be set during object creation, using
- * MDB2::connect(), MDB2::factory() or MDB2::singleton(). The options can
- * also be set after the object is created, using MDB2::setOptions() or
- * MDB2_Driver_Common::setOption().
- * The list of available option includes:
- *
- * $options['ssl'] -> boolean: determines if ssl should be used for connections
- * $options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names
- * $options['disable_query'] -> boolean: determines if queries should be executed
- * $options['result_class'] -> string: class used for result sets
- * $options['buffered_result_class'] -> string: class used for buffered result sets
- * $options['result_wrap_class'] -> string: class used to wrap result sets into
- * $options['result_buffering'] -> boolean should results be buffered or not?
- * $options['fetch_class'] -> string: class to use when fetch mode object is used
- * $options['persistent'] -> boolean: persistent connection?
- * $options['debug'] -> integer: numeric debug level
- * $options['debug_handler'] -> string: function/method that captures debug messages
- * $options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler
- * $options['default_text_field_length'] -> integer: default text field length to use
- * $options['lob_buffer_length'] -> integer: LOB buffer length
- * $options['log_line_break'] -> string: line-break format
- * $options['idxname_format'] -> string: pattern for index name
- * $options['seqname_format'] -> string: pattern for sequence name
- * $options['savepoint_format'] -> string: pattern for auto generated savepoint names
- * $options['statement_format'] -> string: pattern for prepared statement names
- * $options['seqcol_name'] -> string: sequence column name
- * $options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used
- * $options['use_transactions'] -> boolean: if transaction use should be enabled
- * $options['decimal_places'] -> integer: number of decimal places to handle
- * $options['portability'] -> integer: portability constant
- * $options['modules'] -> array: short to long module name mapping for __call()
- * $options['emulate_prepared'] -> boolean: force prepared statements to be emulated
- * $options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes
- * $options['datatype_map_callback'] -> array: callback function/method that should be called
- * $options['bindname_format'] -> string: regular expression pattern for named parameters
- * $options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed
- * $options['max_identifiers_length'] -> integer: max identifier length
- * $options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']
- * $options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']
- *
- *
- * @var array
- * @access public
- * @see MDB2::connect()
- * @see MDB2::factory()
- * @see MDB2::singleton()
- * @see MDB2_Driver_Common::setOption()
- */
- public $options = array(
- 'ssl' => false,
- 'field_case' => CASE_LOWER,
- 'disable_query' => false,
- 'result_class' => 'MDB2_Result_%s',
- 'buffered_result_class' => 'MDB2_BufferedResult_%s',
- 'result_wrap_class' => false,
- 'result_buffering' => true,
- 'fetch_class' => 'stdClass',
- 'persistent' => false,
- 'debug' => 0,
- 'debug_handler' => 'MDB2_defaultDebugOutput',
- 'debug_expanded_output' => false,
- 'default_text_field_length' => 4096,
- 'lob_buffer_length' => 8192,
- 'log_line_break' => "\n",
- 'idxname_format' => '%s_idx',
- 'seqname_format' => '%s_seq',
- 'savepoint_format' => 'MDB2_SAVEPOINT_%s',
- 'statement_format' => 'MDB2_STATEMENT_%1$s_%2$s',
- 'seqcol_name' => 'sequence',
- 'quote_identifier' => false,
- 'use_transactions' => true,
- 'decimal_places' => 2,
- 'portability' => MDB2_PORTABILITY_ALL,
- 'modules' => array(
- 'ex' => 'Extended',
- 'dt' => 'Datatype',
- 'mg' => 'Manager',
- 'rv' => 'Reverse',
- 'na' => 'Native',
- 'fc' => 'Function',
- ),
- 'emulate_prepared' => false,
- 'datatype_map' => array(),
- 'datatype_map_callback' => array(),
- 'nativetype_map_callback' => array(),
- 'lob_allow_url_include' => false,
- 'bindname_format' => '(?:\d+)|(?:[a-zA-Z][a-zA-Z0-9_]*)',
- 'max_identifiers_length' => 30,
- 'default_fk_action_onupdate' => 'RESTRICT',
- 'default_fk_action_ondelete' => 'RESTRICT',
- );
-
- /**
- * string array
- * @var string
- * @access public
- */
- public $string_quoting = array(
- 'start' => "'",
- 'end' => "'",
- 'escape' => false,
- 'escape_pattern' => false,
- );
-
- /**
- * identifier quoting
- * @var array
- * @access public
- */
- public $identifier_quoting = array(
- 'start' => '"',
- 'end' => '"',
- 'escape' => '"',
- );
-
- /**
- * sql comments
- * @var array
- * @access protected
- */
- public $sql_comments = array(
- array('start' => '--', 'end' => "\n", 'escape' => false),
- array('start' => '/*', 'end' => '*/', 'escape' => false),
- );
-
- /**
- * comparision wildcards
- * @var array
- * @access protected
- */
- protected $wildcards = array('%', '_');
-
- /**
- * column alias keyword
- * @var string
- * @access protected
- */
- public $as_keyword = ' AS ';
-
- /**
- * warnings
- * @var array
- * @access protected
- */
- public $warnings = array();
-
- /**
- * string with the debugging information
- * @var string
- * @access public
- */
- public $debug_output = '';
-
- /**
- * determine if there is an open transaction
- * @var bool
- * @access protected
- */
- public $in_transaction = false;
-
- /**
- * the smart transaction nesting depth
- * @var int
- * @access protected
- */
- public $nested_transaction_counter = null;
-
- /**
- * the first error that occured inside a nested transaction
- * @var MDB2_Error|bool
- * @access protected
- */
- protected $has_transaction_error = false;
-
- /**
- * result offset used in the next query
- * @var int
- * @access public
- */
- public $offset = 0;
-
- /**
- * result limit used in the next query
- * @var int
- * @access public
- */
- public $limit = 0;
-
- /**
- * Database backend used in PHP (mysql, odbc etc.)
- * @var string
- * @access public
- */
- public $phptype;
-
- /**
- * Database used with regards to SQL syntax etc.
- * @var string
- * @access public
- */
- public $dbsyntax;
-
- /**
- * the last query sent to the driver
- * @var string
- * @access public
- */
- public $last_query;
-
- /**
- * the default fetchmode used
- * @var int
- * @access public
- */
- public $fetchmode = MDB2_FETCHMODE_ORDERED;
-
- /**
- * array of module instances
- * @var array
- * @access protected
- */
- protected $modules = array();
-
- /**
- * determines of the PHP4 destructor emulation has been enabled yet
- * @var array
- * @access protected
- */
- protected $destructor_registered = true;
-
- /**
- * @var PEAR
- */
- protected $pear;
-
- // }}}
- // {{{ constructor: function __construct()
-
- /**
- * Constructor
- */
- function __construct()
- {
- end($GLOBALS['_MDB2_databases']);
- $db_index = key($GLOBALS['_MDB2_databases']) + 1;
- $GLOBALS['_MDB2_databases'][$db_index] = &$this;
- $this->db_index = $db_index;
- $this->pear = new PEAR;
- }
-
- // }}}
- // {{{ destructor: function __destruct()
-
- /**
- * Destructor
- */
- function __destruct()
- {
- $this->disconnect(false);
- }
-
- // }}}
- // {{{ function free()
-
- /**
- * Free the internal references so that the instance can be destroyed
- *
- * @return bool true on success, false if result is invalid
- *
- * @access public
- */
- function free()
- {
- unset($GLOBALS['_MDB2_databases'][$this->db_index]);
- unset($this->db_index);
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function __toString()
-
- /**
- * String conversation
- *
- * @return string representation of the object
- *
- * @access public
- */
- function __toString()
- {
- $info = get_class($this);
- $info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')';
- if ($this->connection) {
- $info.= ' [connected]';
- }
- return $info;
- }
-
- // }}}
- // {{{ function errorInfo($error = null)
-
- /**
- * This method is used to collect information about an error
- *
- * @param mixed error code or resource
- *
- * @return array with MDB2 errorcode, native error code, native message
- *
- * @access public
- */
- function errorInfo($error = null)
- {
- return array($error, null, null);
- }
-
- // }}}
- // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
-
- /**
- * This method is used to communicate an error and invoke error
- * callbacks etc. Basically a wrapper for PEAR::raiseError
- * without the message string.
- *
- * @param mixed $code integer error code, or a PEAR error object (all
- * other parameters are ignored if this parameter is
- * an object
- * @param int $mode error mode, see PEAR_Error docs
- * @param mixed $options If error mode is PEAR_ERROR_TRIGGER, this is the
- * error level (E_USER_NOTICE etc). If error mode is
- * PEAR_ERROR_CALLBACK, this is the callback function,
- * either as a function name, or as an array of an
- * object and method name. For other error modes this
- * parameter is ignored.
- * @param string $userinfo Extra debug information. Defaults to the last
- * query and native error code.
- * @param string $method name of the method that triggered the error
- * @param string $dummy1 not used
- * @param bool $dummy2 not used
- *
- * @return PEAR_Error instance of a PEAR Error object
- * @access public
- * @see PEAR_Error
- */
- function &raiseError($code = null,
- $mode = null,
- $options = null,
- $userinfo = null,
- $method = null,
- $dummy1 = null,
- $dummy2 = false
- ) {
- $userinfo = "[Error message: $userinfo]\n";
- // The error is yet a MDB2 error object
- if (MDB2::isError($code)) {
- // because we use the static PEAR::raiseError, our global
- // handler should be used if it is set
- if ((null === $mode) && !empty($this->_default_error_mode)) {
- $mode = $this->_default_error_mode;
- $options = $this->_default_error_options;
- }
- if (null === $userinfo) {
- $userinfo = $code->getUserinfo();
- }
- $code = $code->getCode();
- } elseif ($code == MDB2_ERROR_NOT_FOUND) {
- // extension not loaded: don't call $this->errorInfo() or the script
- // will die
- } elseif (isset($this->connection)) {
- if (!empty($this->last_query)) {
- $userinfo.= "[Last executed query: {$this->last_query}]\n";
- }
- $native_errno = $native_msg = null;
- list($code, $native_errno, $native_msg) = $this->errorInfo($code);
- if ((null !== $native_errno) && $native_errno !== '') {
- $userinfo.= "[Native code: $native_errno]\n";
- }
- if ((null !== $native_msg) && $native_msg !== '') {
- $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n";
- }
- if (null !== $method) {
- $userinfo = $method.': '.$userinfo;
- }
- }
-
- $err = $this->pear->raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
- if ($err->getMode() !== PEAR_ERROR_RETURN
- && isset($this->nested_transaction_counter) && !$this->has_transaction_error) {
- $this->has_transaction_error = $err;
- }
- return $err;
- }
-
- // }}}
- // {{{ function resetWarnings()
-
- /**
- * reset the warning array
- *
- * @return void
- *
- * @access public
- */
- function resetWarnings()
- {
- $this->warnings = array();
- }
-
- // }}}
- // {{{ function getWarnings()
-
- /**
- * Get all warnings in reverse order.
- * This means that the last warning is the first element in the array
- *
- * @return array with warnings
- *
- * @access public
- * @see resetWarnings()
- */
- function getWarnings()
- {
- return array_reverse($this->warnings);
- }
-
- // }}}
- // {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')
-
- /**
- * Sets which fetch mode should be used by default on queries
- * on this connection
- *
- * @param int MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC
- * or MDB2_FETCHMODE_OBJECT
- * @param string the class name of the object to be returned
- * by the fetch methods when the
- * MDB2_FETCHMODE_OBJECT mode is selected.
- * If no class is specified by default a cast
- * to object from the assoc array row will be
- * done. There is also the possibility to use
- * and extend the 'MDB2_row' class.
- *
- * @return mixed MDB2_OK or MDB2 Error Object
- *
- * @access public
- * @see MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT
- */
- function setFetchMode($fetchmode, $object_class = 'stdClass')
- {
- switch ($fetchmode) {
- case MDB2_FETCHMODE_OBJECT:
- $this->options['fetch_class'] = $object_class;
- case MDB2_FETCHMODE_ORDERED:
- case MDB2_FETCHMODE_ASSOC:
- $this->fetchmode = $fetchmode;
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'invalid fetchmode mode', __FUNCTION__);
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setOption($option, $value)
-
- /**
- * set the option for the db class
- *
- * @param string option name
- * @param mixed value for the option
- *
- * @return mixed MDB2_OK or MDB2 Error Object
- *
- * @access public
- */
- function setOption($option, $value)
- {
- if (array_key_exists($option, $this->options)) {
- $this->options[$option] = $value;
- return MDB2_OK;
- }
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- "unknown option $option", __FUNCTION__);
- }
-
- // }}}
- // {{{ function getOption($option)
-
- /**
- * Returns the value of an option
- *
- * @param string option name
- *
- * @return mixed the option value or error object
- *
- * @access public
- */
- function getOption($option)
- {
- if (array_key_exists($option, $this->options)) {
- return $this->options[$option];
- }
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- "unknown option $option", __FUNCTION__);
- }
-
- // }}}
- // {{{ function debug($message, $scope = '', $is_manip = null)
-
- /**
- * set a debug message
- *
- * @param string message that should be appended to the debug variable
- * @param string usually the method name that triggered the debug call:
- * for example 'query', 'prepare', 'execute', 'parameters',
- * 'beginTransaction', 'commit', 'rollback'
- * @param array contains context information about the debug() call
- * common keys are: is_manip, time, result etc.
- *
- * @return void
- *
- * @access public
- */
- function debug($message, $scope = '', $context = array())
- {
- if ($this->options['debug'] && $this->options['debug_handler']) {
- if (!$this->options['debug_expanded_output']) {
- if (!empty($context['when']) && $context['when'] !== 'pre') {
- return null;
- }
- $context = empty($context['is_manip']) ? false : $context['is_manip'];
- }
- return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context));
- }
- return null;
- }
-
- // }}}
- // {{{ function getDebugOutput()
-
- /**
- * output debug info
- *
- * @return string content of the debug_output class variable
- *
- * @access public
- */
- function getDebugOutput()
- {
- return $this->debug_output;
- }
-
- // }}}
- // {{{ function escape($text)
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- if ($escape_wildcards) {
- $text = $this->escapePattern($text);
- }
-
- $text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text);
- return $text;
- }
-
- // }}}
- // {{{ function escapePattern($text)
-
- /**
- * Quotes pattern (% and _) characters in a string)
- *
- * @param string the input string to quote
- *
- * @return string quoted string
- *
- * @access public
- */
- function escapePattern($text)
- {
- if ($this->string_quoting['escape_pattern']) {
- $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);
- foreach ($this->wildcards as $wildcard) {
- $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);
- }
- }
- return $text;
- }
-
- // }}}
- // {{{ function quoteIdentifier($str, $check_option = false)
-
- /**
- * Quote a string so it can be safely used as a table or column name
- *
- * Delimiting style depends on which database driver is being used.
- *
- * NOTE: just because you CAN use delimited identifiers doesn't mean
- * you SHOULD use them. In general, they end up causing way more
- * problems than they solve.
- *
- * NOTE: if you have table names containing periods, don't use this method
- * (@see bug #11906)
- *
- * Portability is broken by using the following characters inside
- * delimited identifiers:
- * + backtick (` ) -- due to MySQL
- * + double quote (" ) -- due to Oracle
- * + brackets ([ or ] ) -- due to Access
- *
- * Delimited identifiers are known to generally work correctly under
- * the following drivers:
- * + mssql
- * + mysql
- * + mysqli
- * + oci8
- * + pgsql
- * + sqlite
- *
- * InterBase doesn't seem to be able to use delimited identifiers
- * via PHP 4. They work fine under PHP 5.
- *
- * @param string identifier name to be quoted
- * @param bool check the 'quote_identifier' option
- *
- * @return string quoted identifier string
- *
- * @access public
- */
- function quoteIdentifier($str, $check_option = false)
- {
- if ($check_option && !$this->options['quote_identifier']) {
- return $str;
- }
- $str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str);
- $parts = explode('.', $str);
- foreach (array_keys($parts) as $k) {
- $parts[$k] = $this->identifier_quoting['start'] . $parts[$k] . $this->identifier_quoting['end'];
- }
- return implode('.', $parts);
- }
-
- // }}}
- // {{{ function getAsKeyword()
-
- /**
- * Gets the string to alias column
- *
- * @return string to use when aliasing a column
- */
- function getAsKeyword()
- {
- return $this->as_keyword;
- }
-
- // }}}
- // {{{ function getConnection()
-
- /**
- * Returns a native connection
- *
- * @return mixed a valid MDB2 connection object,
- * or a MDB2 error object on error
- *
- * @access public
- */
- function getConnection()
- {
- $result = $this->connect();
- if (MDB2::isError($result)) {
- return $result;
- }
- return $this->connection;
- }
-
- // }}}
- // {{{ function _fixResultArrayValues(&$row, $mode)
-
- /**
- * Do all necessary conversions on result arrays to fix DBMS quirks
- *
- * @param array the array to be fixed (passed by reference)
- * @param array bit-wise addition of the required portability modes
- *
- * @return void
- *
- * @access protected
- */
- function _fixResultArrayValues(&$row, $mode)
- {
- switch ($mode) {
- case MDB2_PORTABILITY_EMPTY_TO_NULL:
- foreach ($row as $key => $value) {
- if ($value === '') {
- $row[$key] = null;
- }
- }
- break;
- case MDB2_PORTABILITY_RTRIM:
- foreach ($row as $key => $value) {
- if (is_string($value)) {
- $row[$key] = rtrim($value);
- }
- }
- break;
- case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:
- $tmp_row = array();
- foreach ($row as $key => $value) {
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):
- foreach ($row as $key => $value) {
- if ($value === '') {
- $row[$key] = null;
- } elseif (is_string($value)) {
- $row[$key] = rtrim($value);
- }
- }
- break;
- case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
- $tmp_row = array();
- foreach ($row as $key => $value) {
- if (is_string($value)) {
- $value = rtrim($value);
- }
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
- $tmp_row = array();
- foreach ($row as $key => $value) {
- if ($value === '') {
- $value = null;
- }
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
- $tmp_row = array();
- foreach ($row as $key => $value) {
- if ($value === '') {
- $value = null;
- } elseif (is_string($value)) {
- $value = rtrim($value);
- }
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- }
- }
-
- // }}}
- // {{{ function loadModule($module, $property = null, $phptype_specific = null)
-
- /**
- * loads a module
- *
- * @param string name of the module that should be loaded
- * (only used for error messages)
- * @param string name of the property into which the class will be loaded
- * @param bool if the class to load for the module is specific to the
- * phptype
- *
- * @return object on success a reference to the given module is returned
- * and on failure a PEAR error
- *
- * @access public
- */
- function loadModule($module, $property = null, $phptype_specific = null)
- {
- if (!$property) {
- $property = strtolower($module);
- }
-
- if (!isset($this->{$property})) {
- $version = $phptype_specific;
- if ($phptype_specific !== false) {
- $version = true;
- $class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype;
- $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
- }
- if ($phptype_specific === false
- || (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name))
- ) {
- $version = false;
- $class_name = 'MDB2_'.$module;
- $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
- }
-
- $err = MDB2::loadClass($class_name, $this->getOption('debug'));
- if (MDB2::isError($err)) {
- return $err;
- }
-
- // load module in a specific version
- if ($version) {
- if (method_exists($class_name, 'getClassName')) {
- $class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index);
- if ($class_name != $class_name_new) {
- $class_name = $class_name_new;
- $err = MDB2::loadClass($class_name, $this->getOption('debug'));
- if (MDB2::isError($err)) {
- return $err;
- }
- }
- }
- }
-
- if (!MDB2::classExists($class_name)) {
- $err = $this->raiseError(MDB2_ERROR_LOADMODULE, null, null,
- "unable to load module '$module' into property '$property'", __FUNCTION__);
- return $err;
- }
- $this->{$property} = new $class_name($this->db_index);
- $this->modules[$module] = $this->{$property};
- if ($version) {
- // this will be used in the connect method to determine if the module
- // needs to be loaded with a different version if the server
- // version changed in between connects
- $this->loaded_version_modules[] = $property;
- }
- }
-
- return $this->{$property};
- }
-
- // }}}
- // {{{ function __call($method, $params)
-
- /**
- * Calls a module method using the __call magic method
- *
- * @param string Method name.
- * @param array Arguments.
- *
- * @return mixed Returned value.
- */
- function __call($method, $params)
- {
- $module = null;
- if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)
- && isset($this->options['modules'][$match[1]])
- ) {
- $module = $this->options['modules'][$match[1]];
- $method = strtolower($match[2]).$match[3];
- if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {
- $result = $this->loadModule($module);
- if (MDB2::isError($result)) {
- return $result;
- }
- }
- } else {
- foreach ($this->modules as $key => $foo) {
- if (is_object($this->modules[$key])
- && method_exists($this->modules[$key], $method)
- ) {
- $module = $key;
- break;
- }
- }
- }
- if (null !== $module) {
- return call_user_func_array(array(&$this->modules[$module], $method), $params);
- }
- trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
- }
-
- // }}}
- // {{{ function beginTransaction($savepoint = null)
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'transactions are not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function commit($savepoint = null)
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'commiting transactions is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function rollback($savepoint = null)
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'rolling back transactions is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function inTransaction($ignore_nested = false)
-
- /**
- * If a transaction is currently open.
- *
- * @param bool if the nested transaction count should be ignored
- * @return int|bool - an integer with the nesting depth is returned if a
- * nested transaction is open
- * - true is returned for a normal open transaction
- * - false is returned if no transaction is open
- *
- * @access public
- */
- function inTransaction($ignore_nested = false)
- {
- if (!$ignore_nested && isset($this->nested_transaction_counter)) {
- return $this->nested_transaction_counter;
- }
- return $this->in_transaction;
- }
-
- // }}}
- // {{{ function setTransactionIsolation($isolation)
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @param array some transaction options:
- * 'wait' => 'WAIT' | 'NO WAIT'
- * 'rw' => 'READ WRITE' | 'READ ONLY'
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation, $options = array())
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level setting is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function beginNestedTransaction($savepoint = false)
-
- /**
- * Start a nested transaction.
- *
- * @return mixed MDB2_OK on success/savepoint name, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function beginNestedTransaction()
- {
- if ($this->in_transaction) {
- ++$this->nested_transaction_counter;
- $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
- if ($this->supports('savepoints') && $savepoint) {
- return $this->beginTransaction($savepoint);
- }
- return MDB2_OK;
- }
- $this->has_transaction_error = false;
- $result = $this->beginTransaction();
- $this->nested_transaction_counter = 1;
- return $result;
- }
-
- // }}}
- // {{{ function completeNestedTransaction($force_rollback = false, $release = false)
-
- /**
- * Finish a nested transaction by rolling back if an error occured or
- * committing otherwise.
- *
- * @param bool if the transaction should be rolled back regardless
- * even if no error was set within the nested transaction
- * @return mixed MDB_OK on commit/counter decrementing, false on rollback
- * and a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function completeNestedTransaction($force_rollback = false)
- {
- if ($this->nested_transaction_counter > 1) {
- $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
- if ($this->supports('savepoints') && $savepoint) {
- if ($force_rollback || $this->has_transaction_error) {
- $result = $this->rollback($savepoint);
- if (!MDB2::isError($result)) {
- $result = false;
- $this->has_transaction_error = false;
- }
- } else {
- $result = $this->commit($savepoint);
- }
- } else {
- $result = MDB2_OK;
- }
- --$this->nested_transaction_counter;
- return $result;
- }
-
- $this->nested_transaction_counter = null;
- $result = MDB2_OK;
-
- // transaction has not yet been rolled back
- if ($this->in_transaction) {
- if ($force_rollback || $this->has_transaction_error) {
- $result = $this->rollback();
- if (!MDB2::isError($result)) {
- $result = false;
- }
- } else {
- $result = $this->commit();
- }
- }
- $this->has_transaction_error = false;
- return $result;
- }
-
- // }}}
- // {{{ function failNestedTransaction($error = null, $immediately = false)
-
- /**
- * Force setting nested transaction to failed.
- *
- * @param mixed value to return in getNestededTransactionError()
- * @param bool if the transaction should be rolled back immediately
- * @return bool MDB2_OK
- *
- * @access public
- * @since 2.1.1
- */
- function failNestedTransaction($error = null, $immediately = false)
- {
- if (null !== $error) {
- $error = $this->has_transaction_error ? $this->has_transaction_error : true;
- } elseif (!$error) {
- $error = true;
- }
- $this->has_transaction_error = $error;
- if (!$immediately) {
- return MDB2_OK;
- }
- return $this->rollback();
- }
-
- // }}}
- // {{{ function getNestedTransactionError()
-
- /**
- * The first error that occured since the transaction start.
- *
- * @return MDB2_Error|bool MDB2 error object if an error occured or false.
- *
- * @access public
- * @since 2.1.1
- */
- function getNestedTransactionError()
- {
- return $this->has_transaction_error;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function connect()
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ setCharset($charset, $connection = null)
-
- /**
- * Set the charset on the current connection
- *
- * @param string charset
- * @param resource connection handle
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function setCharset($charset, $connection = null)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function disconnect($force = true)
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force whether the disconnect should be forced even if the
- * connection is opened persistently
- *
- * @return mixed true on success, false if not connected and error object on error
- *
- * @access public
- */
- function disconnect($force = true)
- {
- $this->connection = 0;
- $this->connected_dsn = array();
- $this->connected_database_name = '';
- $this->opened_persistent = null;
- $this->connected_server_info = '';
- $this->in_transaction = null;
- $this->nested_transaction_counter = null;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setDatabase($name)
-
- /**
- * Select a different database
- *
- * @param string name of the database that should be selected
- *
- * @return string name of the database previously connected to
- *
- * @access public
- */
- function setDatabase($name)
- {
- $previous_database_name = (isset($this->database_name)) ? $this->database_name : '';
- $this->database_name = $name;
- if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_name)) {
- $this->disconnect(false);
- }
- return $previous_database_name;
- }
-
- // }}}
- // {{{ function getDatabase()
-
- /**
- * Get the current database
- *
- * @return string name of the database
- *
- * @access public
- */
- function getDatabase()
- {
- return $this->database_name;
- }
-
- // }}}
- // {{{ function setDSN($dsn)
-
- /**
- * set the DSN
- *
- * @param mixed DSN string or array
- *
- * @return MDB2_OK
- *
- * @access public
- */
- function setDSN($dsn)
- {
- $dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
- $dsn = MDB2::parseDSN($dsn);
- if (array_key_exists('database', $dsn)) {
- $this->database_name = $dsn['database'];
- unset($dsn['database']);
- }
- $this->dsn = array_merge($dsn_default, $dsn);
- return $this->disconnect(false);
- }
-
- // }}}
- // {{{ function getDSN($type = 'string', $hidepw = false)
-
- /**
- * return the DSN as a string
- *
- * @param string format to return ("array", "string")
- * @param string string to hide the password with
- *
- * @return mixed DSN in the chosen type
- *
- * @access public
- */
- function getDSN($type = 'string', $hidepw = false)
- {
- $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
- $dsn['phptype'] = $this->phptype;
- $dsn['database'] = $this->database_name;
- if ($hidepw) {
- $dsn['password'] = $hidepw;
- }
- switch ($type) {
- // expand to include all possible options
- case 'string':
- $dsn = $dsn['phptype'].
- ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
- '://'.$dsn['username'].':'.
- $dsn['password'].'@'.$dsn['hostspec'].
- ($dsn['port'] ? (':'.$dsn['port']) : '').
- '/'.$dsn['database'];
- break;
- case 'array':
- default:
- break;
- }
- return $dsn;
- }
-
- // }}}
- // {{{ _isNewLinkSet()
-
- /**
- * Check if the 'new_link' option is set
- *
- * @return boolean
- *
- * @access protected
- */
- function _isNewLinkSet()
- {
- return (isset($this->dsn['new_link'])
- && ($this->dsn['new_link'] === true
- || (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link']))
- || (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link'])
- )
- );
- }
-
- // }}}
- // {{{ function &standaloneQuery($query, $types = null, $is_manip = false)
-
- /**
- * execute a query as database administrator
- *
- * @param string the SQL query
- * @param mixed array that contains the types of the columns in
- * the result set
- * @param bool if the query is a manipulation query
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function standaloneQuery($query, $types = null, $is_manip = false)
- {
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $connection = $this->getConnection();
- if (MDB2::isError($connection)) {
- return $connection;
- }
-
- $result = $this->_doQuery($query, $is_manip, $connection, false);
- if (MDB2::isError($result)) {
- return $result;
- }
-
- if ($is_manip) {
- $affected_rows = $this->_affectedRows($connection, $result);
- return $affected_rows;
- }
- $result = $this->_wrapResult($result, $types, true, true, $limit, $offset);
- return $result;
- }
-
- // }}}
- // {{{ function _modifyQuery($query, $is_manip, $limit, $offset)
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string query to modify
- * @param bool if it is a DML query
- * @param int limit the number of rows
- * @param int start reading from given offset
- *
- * @return string modified query
- *
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- return $query;
- }
-
- // }}}
- // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
-
- /**
- * Execute a query
- * @param string query
- * @param bool if the query is a manipulation query
- * @param resource connection handle
- * @param string database name
- *
- * @return result or error object
- *
- * @access protected
- */
- function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (MDB2::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $err;
- }
-
- // }}}
- // {{{ function _affectedRows($connection, $result = null)
-
- /**
- * Returns the number of rows affected
- *
- * @param resource result handle
- * @param resource connection handle
- *
- * @return mixed MDB2 Error Object or the number of rows affected
- *
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function &exec($query)
-
- /**
- * Execute a manipulation query to the database and return the number of affected rows
- *
- * @param string the SQL query
- *
- * @return mixed number of affected rows on success, a MDB2 error on failure
- *
- * @access public
- */
- function exec($query)
- {
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, true, $limit, $offset);
-
- $connection = $this->getConnection();
- if (MDB2::isError($connection)) {
- return $connection;
- }
-
- $result = $this->_doQuery($query, true, $connection, $this->database_name);
- if (MDB2::isError($result)) {
- return $result;
- }
-
- $affectedRows = $this->_affectedRows($connection, $result);
- return $affectedRows;
- }
-
- // }}}
- // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
-
- /**
- * Send a query to the database and return any results
- *
- * @param string the SQL query
- * @param mixed array that contains the types of the columns in
- * the result set
- * @param mixed string which specifies which result class to use
- * @param mixed string which specifies which class to wrap results in
- *
- * @return mixed an MDB2_Result handle on success, a MDB2 error on failure
- *
- * @access public
- */
- function query($query, $types = null, $result_class = true, $result_wrap_class = true)
- {
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, false, $limit, $offset);
-
- $connection = $this->getConnection();
- if (MDB2::isError($connection)) {
- return $connection;
- }
-
- $result = $this->_doQuery($query, false, $connection, $this->database_name);
- if (MDB2::isError($result)) {
- return $result;
- }
-
- $result = $this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);
- return $result;
- }
-
- // }}}
- // {{{ function _wrapResult($result_resource, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)
-
- /**
- * wrap a result set into the correct class
- *
- * @param resource result handle
- * @param mixed array that contains the types of the columns in
- * the result set
- * @param mixed string which specifies which result class to use
- * @param mixed string which specifies which class to wrap results in
- * @param string number of rows to select
- * @param string first row to select
- *
- * @return mixed an MDB2_Result, a MDB2 error on failure
- *
- * @access protected
- */
- function _wrapResult($result_resource, $types = array(), $result_class = true,
- $result_wrap_class = true, $limit = null, $offset = null)
- {
- if ($types === true) {
- if ($this->supports('result_introspection')) {
- $this->loadModule('Reverse', null, true);
- $tableInfo = $this->reverse->tableInfo($result_resource);
- if (MDB2::isError($tableInfo)) {
- return $tableInfo;
- }
- $types = array();
- $types_assoc = array();
- foreach ($tableInfo as $field) {
- $types[] = $field['mdb2type'];
- $types_assoc[$field['name']] = $field['mdb2type'];
- }
- } else {
- $types = null;
- }
- }
-
- if ($result_class === true) {
- $result_class = $this->options['result_buffering']
- ? $this->options['buffered_result_class'] : $this->options['result_class'];
- }
-
- if ($result_class) {
- $class_name = sprintf($result_class, $this->phptype);
- if (!MDB2::classExists($class_name)) {
- $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'result class does not exist '.$class_name, __FUNCTION__);
- return $err;
- }
- $result = new $class_name($this, $result_resource, $limit, $offset);
- if (!MDB2::isResultCommon($result)) {
- $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'result class is not extended from MDB2_Result_Common', __FUNCTION__);
- return $err;
- }
-
- if (!empty($types)) {
- $err = $result->setResultTypes($types);
- if (MDB2::isError($err)) {
- $result->free();
- return $err;
- }
- }
- if (!empty($types_assoc)) {
- $err = $result->setResultTypes($types_assoc);
- if (MDB2::isError($err)) {
- $result->free();
- return $err;
- }
- }
-
- if ($result_wrap_class === true) {
- $result_wrap_class = $this->options['result_wrap_class'];
- }
- if ($result_wrap_class) {
- if (!MDB2::classExists($result_wrap_class)) {
- $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);
- return $err;
- }
- $result = new $result_wrap_class($result, $this->fetchmode);
- }
-
- return $result;
- }
-
- return $result_resource;
- }
-
- // }}}
- // {{{ function getServerVersion($native = false)
-
- /**
- * return version information about the server
- *
- * @param bool determines if the raw version string should be returned
- *
- * @return mixed array with version information or row string
- *
- * @access public
- */
- function getServerVersion($native = false)
- {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function setLimit($limit, $offset = null)
-
- /**
- * set the range of the next query
- *
- * @param string number of rows to select
- * @param string first row to select
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function setLimit($limit, $offset = null)
- {
- if (!$this->supports('limit_queries')) {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'limit is not supported by this driver', __FUNCTION__);
- }
- $limit = (int)$limit;
- if ($limit < 0) {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'it was not specified a valid selected range row limit', __FUNCTION__);
- }
- $this->limit = $limit;
- if (null !== $offset) {
- $offset = (int)$offset;
- if ($offset < 0) {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'it was not specified a valid first selected range row', __FUNCTION__);
- }
- $this->offset = $offset;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function subSelect($query, $type = false)
-
- /**
- * simple subselect emulation: leaves the query untouched for all RDBMS
- * that support subselects
- *
- * @param string the SQL query for the subselect that may only
- * return a column
- * @param string determines type of the field
- *
- * @return string the query
- *
- * @access public
- */
- function subSelect($query, $type = false)
- {
- if ($this->supports('sub_selects') === true) {
- return $query;
- }
-
- if (!$this->supports('sub_selects')) {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- $col = $this->queryCol($query, $type);
- if (MDB2::isError($col)) {
- return $col;
- }
- if (!is_array($col) || count($col) == 0) {
- return 'NULL';
- }
- if ($type) {
- $this->loadModule('Datatype', null, true);
- return $this->datatype->implodeArray($col, $type);
- }
- return implode(', ', $col);
- }
-
- // }}}
- // {{{ function replace($table, $fields)
-
- /**
- * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
- * query, except that if there is already a row in the table with the same
- * key field values, the old row is deleted before the new row is inserted.
- *
- * The REPLACE type of query does not make part of the SQL standards. Since
- * practically only MySQL and SQLite implement it natively, this type of
- * query isemulated through this method for other DBMS using standard types
- * of queries inside a transaction to assure the atomicity of the operation.
- *
- * @param string name of the table on which the REPLACE query will
- * be executed.
- * @param array associative array that describes the fields and the
- * values that will be inserted or updated in the specified table. The
- * indexes of the array are the names of all the fields of the table.
- * The values of the array are also associative arrays that describe
- * the values and other properties of the table fields.
- *
- * Here follows a list of field properties that need to be specified:
- *
- * value
- * Value to be assigned to the specified field. This value may be
- * of specified in database independent type format as this
- * function can perform the necessary datatype conversions.
- *
- * Default: this property is required unless the Null property is
- * set to 1.
- *
- * type
- * Name of the type of the field. Currently, all types MDB2
- * are supported except for clob and blob.
- *
- * Default: no type conversion
- *
- * null
- * bool property that indicates that the value for this field
- * should be set to null.
- *
- * The default value for fields missing in INSERT queries may be
- * specified the definition of a table. Often, the default value
- * is already null, but since the REPLACE may be emulated using
- * an UPDATE query, make sure that all fields of the table are
- * listed in this function argument array.
- *
- * Default: 0
- *
- * key
- * bool property that indicates that this field should be
- * handled as a primary key or at least as part of the compound
- * unique index of the table that will determine the row that will
- * updated if it exists or inserted a new row otherwise.
- *
- * This function will fail if no key field is specified or if the
- * value of a key field is set to null because fields that are
- * part of unique index they may not be null.
- *
- * Default: 0
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function replace($table, $fields)
- {
- if (!$this->supports('replace')) {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'replace query is not supported', __FUNCTION__);
- }
- $count = count($fields);
- $condition = $values = array();
- for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {
- $name = key($fields);
- if (isset($fields[$name]['null']) && $fields[$name]['null']) {
- $value = 'NULL';
- } else {
- $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
- $value = $this->quote($fields[$name]['value'], $type);
- }
- $values[$name] = $value;
- if (isset($fields[$name]['key']) && $fields[$name]['key']) {
- if ($value === 'NULL') {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'key value '.$name.' may not be NULL', __FUNCTION__);
- }
- $condition[] = $this->quoteIdentifier($name, true) . '=' . $value;
- }
- }
- if (empty($condition)) {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'not specified which fields are keys', __FUNCTION__);
- }
-
- $result = null;
- $in_transaction = $this->in_transaction;
- if (!$in_transaction && MDB2::isError($result = $this->beginTransaction())) {
- return $result;
- }
-
- $connection = $this->getConnection();
- if (MDB2::isError($connection)) {
- return $connection;
- }
-
- $condition = ' WHERE '.implode(' AND ', $condition);
- $query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition;
- $result = $this->_doQuery($query, true, $connection);
- if (!MDB2::isError($result)) {
- $affected_rows = $this->_affectedRows($connection, $result);
- $insert = '';
- foreach ($values as $key => $value) {
- $insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true);
- }
- $values = implode(', ', $values);
- $query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($insert) VALUES ($values)";
- $result = $this->_doQuery($query, true, $connection);
- if (!MDB2::isError($result)) {
- $affected_rows += $this->_affectedRows($connection, $result);;
- }
- }
-
- if (!$in_transaction) {
- if (MDB2::isError($result)) {
- $this->rollback();
- } else {
- $result = $this->commit();
- }
- }
-
- if (MDB2::isError($result)) {
- return $result;
- }
-
- return $affected_rows;
- }
-
- // }}}
- // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string the query to prepare
- * @param mixed array that contains the types of the placeholders
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed key (field) value (parameter) pair for all lob placeholders
- *
- * @return mixed resource handle for the prepared query on success,
- * a MDB2 error on failure
- *
- * @access public
- * @see bindParam, execute
- */
- function prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (MDB2::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = 0;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (null === $placeholder_type) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (MDB2::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (null === $placeholder_type) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- if (!empty($types) && is_array($types)) {
- if ($placeholder_type == ':') {
- if (is_int(key($types))) {
- $types_tmp = $types;
- $types = array();
- $count = -1;
- }
- } else {
- $types = array_values($types);
- }
- }
- }
- if ($placeholder_type == ':') {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $parameter = preg_replace($regexp, '\\1', $query);
- if ($parameter === '') {
- $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- $positions[$p_position] = $parameter;
- $query = substr_replace($query, '?', $position, strlen($parameter)+1);
- // use parameter name in type array
- if (isset($count) && isset($types_tmp[++$count])) {
- $types[$parameter] = $types_tmp[$count];
- }
- } else {
- $positions[$p_position] = count($positions);
- }
- $position = $p_position + 1;
- } else {
- $position = $p_position;
- }
- }
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $statement = null;
- $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ function _skipDelimitedStrings($query, $position, $p_position)
-
- /**
- * Utility method, used by prepare() to avoid replacing placeholders within delimited strings.
- * Check if the placeholder is contained within a delimited string.
- * If so, skip it and advance the position, otherwise return the current position,
- * which is valid
- *
- * @param string $query
- * @param integer $position current string cursor position
- * @param integer $p_position placeholder position
- *
- * @return mixed integer $new_position on success
- * MDB2_Error on failure
- *
- * @access protected
- */
- function _skipDelimitedStrings($query, $position, $p_position)
- {
- $ignores = array();
- $ignores[] = $this->string_quoting;
- $ignores[] = $this->identifier_quoting;
- $ignores = array_merge($ignores, $this->sql_comments);
-
- foreach ($ignores as $ignore) {
- if (!empty($ignore['start'])) {
- if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {
- $end_quote = $start_quote;
- do {
- if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {
- if ($ignore['end'] === "\n") {
- $end_quote = strlen($query) - 1;
- } else {
- $err = MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'query with an unterminated text string specified', __FUNCTION__);
- return $err;
- }
- }
- } while ($ignore['escape']
- && $end_quote-1 != $start_quote
- && $query[($end_quote - 1)] == $ignore['escape']
- && ( $ignore['escape_pattern'] !== $ignore['escape']
- || $query[($end_quote - 2)] != $ignore['escape'])
- );
-
- $position = $end_quote + 1;
- return $position;
- }
- }
- }
- return $position;
- }
-
- // }}}
- // {{{ function quote($value, $type = null, $quote = true)
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string text string value that is intended to be converted.
- * @param string type to which the value should be converted to
- * @param bool quote
- * @param bool escape wildcards
- *
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- *
- * @access public
- */
- function quote($value, $type = null, $quote = true, $escape_wildcards = false)
- {
- $result = $this->loadModule('Datatype', null, true);
- if (MDB2::isError($result)) {
- return $result;
- }
-
- return $this->datatype->quote($value, $type, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ function getDeclaration($type, $name, $field)
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare
- * of the given type
- *
- * @param string type to which the value should be converted to
- * @param string name the field to be declared.
- * @param string definition of the field
- *
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- *
- * @access public
- */
- function getDeclaration($type, $name, $field)
- {
- $result = $this->loadModule('Datatype', null, true);
- if (MDB2::isError($result)) {
- return $result;
- }
- return $this->datatype->getDeclaration($type, $name, $field);
- }
-
- // }}}
- // {{{ function compareDefinition($current, $previous)
-
- /**
- * Obtain an array of changes that may need to applied
- *
- * @param array new definition
- * @param array old definition
- *
- * @return array containing all changes that will need to be applied
- *
- * @access public
- */
- function compareDefinition($current, $previous)
- {
- $result = $this->loadModule('Datatype', null, true);
- if (MDB2::isError($result)) {
- return $result;
- }
- return $this->datatype->compareDefinition($current, $previous);
- }
-
- // }}}
- // {{{ function supports($feature)
-
- /**
- * Tell whether a DB implementation or its backend extension
- * supports a given feature.
- *
- * @param string name of the feature (see the MDB2 class doc)
- *
- * @return bool|string if this DB implementation supports a given feature
- * false means no, true means native,
- * 'emulated' means emulated
- *
- * @access public
- */
- function supports($feature)
- {
- if (array_key_exists($feature, $this->supported)) {
- return $this->supported[$feature];
- }
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- "unknown support feature $feature", __FUNCTION__);
- }
-
- // }}}
- // {{{ function getSequenceName($sqn)
-
- /**
- * adds sequence name formatting to a sequence name
- *
- * @param string name of the sequence
- *
- * @return string formatted sequence name
- *
- * @access public
- */
- function getSequenceName($sqn)
- {
- return sprintf($this->options['seqname_format'],
- preg_replace('/[^a-z0-9_\-\$.]/i', '_', $sqn));
- }
-
- // }}}
- // {{{ function getIndexName($idx)
-
- /**
- * adds index name formatting to a index name
- *
- * @param string name of the index
- *
- * @return string formatted index name
- *
- * @access public
- */
- function getIndexName($idx)
- {
- return sprintf($this->options['idxname_format'],
- preg_replace('/[^a-z0-9_\-\$.]/i', '_', $idx));
- }
-
- // }}}
- // {{{ function nextID($seq_name, $ondemand = true)
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string name of the sequence
- * @param bool when true missing sequences are automatic created
- *
- * @return mixed MDB2 Error Object or id
- *
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function lastInsertID($table = null, $field = null)
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- *
- * @return mixed MDB2 Error Object or id
- *
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- return MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function currID($seq_name)
-
- /**
- * Returns the current id of a sequence
- *
- * @param string name of the sequence
- *
- * @return mixed MDB2 Error Object or id
- *
- * @access public
- */
- function currID($seq_name)
- {
- $this->warnings[] = 'database does not support getting current
- sequence value, the sequence value was incremented';
- return $this->nextID($seq_name);
- }
-
- // }}}
- // {{{ function queryOne($query, $type = null, $colnum = 0)
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * the first row of the result set and then frees
- * the result set.
- *
- * @param string $query the SELECT query statement to be executed.
- * @param string $type optional argument that specifies the expected
- * datatype of the result set field, so that an eventual
- * conversion may be performed. The default datatype is
- * text, meaning that no conversion is performed
- * @param mixed $colnum the column number (or name) to fetch
- *
- * @return mixed MDB2_OK or field value on success, a MDB2 error on failure
- *
- * @access public
- */
- function queryOne($query, $type = null, $colnum = 0)
- {
- $result = $this->query($query, $type);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $one = $result->fetchOne($colnum);
- $result->free();
- return $one;
- }
-
- // }}}
- // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
-
- /**
- * Execute the specified query, fetch the values from the first
- * row of the result set into an array and then frees
- * the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array optional array argument that specifies a list of
- * expected datatypes of the result set columns, so that the eventual
- * conversions may be performed. The default list of datatypes is
- * empty, meaning that no conversion is performed.
- * @param int how the array data should be indexed
- *
- * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $result = $this->query($query, $types);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $row = $result->fetchRow($fetchmode);
- $result->free();
- return $row;
- }
-
- // }}}
- // {{{ function queryCol($query, $type = null, $colnum = 0)
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * each row of the result set into an array and then frees the result set.
- *
- * @param string $query the SELECT query statement to be executed.
- * @param string $type optional argument that specifies the expected
- * datatype of the result set field, so that an eventual
- * conversion may be performed. The default datatype is text,
- * meaning that no conversion is performed
- * @param mixed $colnum the column number (or name) to fetch
- *
- * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
- * @access public
- */
- function queryCol($query, $type = null, $colnum = 0)
- {
- $result = $this->query($query, $type);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $col = $result->fetchCol($colnum);
- $result->free();
- return $col;
- }
-
- // }}}
- // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
-
- /**
- * Execute the specified query, fetch all the rows of the result set into
- * a two dimensional array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array optional array argument that specifies a list of
- * expected datatypes of the result set columns, so that the eventual
- * conversions may be performed. The default list of datatypes is
- * empty, meaning that no conversion is performed.
- * @param int how the array data should be indexed
- * @param bool if set to true, the $all will have the first
- * column as its first dimension
- * @param bool used only when the query returns exactly
- * two columns. If true, the values of the returned array will be
- * one-element arrays instead of scalars.
- * @param bool if true, the values of the returned array is
- * wrapped in another array. If the same key value (in the first
- * column) repeats itself, the values will be appended to this array
- * instead of overwriting the existing values.
- *
- * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
- $rekey = false, $force_array = false, $group = false)
- {
- $result = $this->query($query, $types);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
- $result->free();
- return $all;
- }
-
- // }}}
- // {{{ function delExpect($error_code)
-
- /**
- * This method deletes all occurences of the specified element from
- * the expected error codes stack.
- *
- * @param mixed $error_code error code that should be deleted
- * @return mixed list of error codes that were deleted or error
- *
- * @uses PEAR::delExpect()
- */
- public function delExpect($error_code)
- {
- return $this->pear->delExpect($error_code);
- }
-
- // }}}
- // {{{ function expectError($code)
-
- /**
- * This method is used to tell which errors you expect to get.
- * Expected errors are always returned with error mode
- * PEAR_ERROR_RETURN. Expected error codes are stored in a stack,
- * and this method pushes a new element onto it. The list of
- * expected errors are in effect until they are popped off the
- * stack with the popExpect() method.
- *
- * Note that this method can not be called statically
- *
- * @param mixed $code a single error code or an array of error codes to expect
- *
- * @return int the new depth of the "expected errors" stack
- *
- * @uses PEAR::expectError()
- */
- public function expectError($code = '*')
- {
- return $this->pear->expectError($code);
- }
-
- // }}}
- // {{{ function getStaticProperty($class, $var)
-
- /**
- * If you have a class that's mostly/entirely static, and you need static
- * properties, you can use this method to simulate them. Eg. in your method(s)
- * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar');
- * You MUST use a reference, or they will not persist!
- *
- * @param string $class The calling classname, to prevent clashes
- * @param string $var The variable to retrieve.
- * @return mixed A reference to the variable. If not set it will be
- * auto initialised to NULL.
- *
- * @uses PEAR::getStaticProperty()
- */
- public function &getStaticProperty($class, $var)
- {
- $tmp = $this->pear->getStaticProperty($class, $var);
- return $tmp;
- }
-
- // }}}
- // {{{ function loadExtension($ext)
-
- /**
- * OS independant PHP extension load. Remember to take care
- * on the correct extension name for case sensitive OSes.
- *
- * @param string $ext The extension name
- * @return bool Success or not on the dl() call
- *
- * @uses PEAR::loadExtension()
- */
- public function loadExtension($ext)
- {
- return $this->pear->loadExtension($ext);
- }
-
- // }}}
- // {{{ function popErrorHandling()
-
- /**
- * Pop the last error handler used
- *
- * @return bool Always true
- *
- * @see PEAR::pushErrorHandling
- * @uses PEAR::popErrorHandling()
- */
- public function popErrorHandling()
- {
- return $this->pear->popErrorHandling();
- }
-
- // }}}
- // {{{ function popExpect()
-
- /**
- * This method pops one element off the expected error codes
- * stack.
- *
- * @return array the list of error codes that were popped
- *
- * @uses PEAR::popExpect()
- */
- public function popExpect()
- {
- return $this->pear->popExpect();
- }
-
- // }}}
- // {{{ function pushErrorHandling($mode, $options = null)
-
- /**
- * Push a new error handler on top of the error handler options stack. With this
- * you can easily override the actual error handler for some code and restore
- * it later with popErrorHandling.
- *
- * @param mixed $mode (same as setErrorHandling)
- * @param mixed $options (same as setErrorHandling)
- *
- * @return bool Always true
- *
- * @see PEAR::setErrorHandling
- * @uses PEAR::pushErrorHandling()
- */
- public function pushErrorHandling($mode, $options = null)
- {
- return $this->pear->pushErrorHandling($mode, $options);
- }
-
- // }}}
- // {{{ function registerShutdownFunc($func, $args = array())
-
- /**
- * Use this function to register a shutdown method for static
- * classes.
- *
- * @param mixed $func The function name (or array of class/method) to call
- * @param mixed $args The arguments to pass to the function
- * @return void
- *
- * @uses PEAR::registerShutdownFunc()
- */
- public function registerShutdownFunc($func, $args = array())
- {
- return $this->pear->registerShutdownFunc($func, $args);
- }
-
- // }}}
- // {{{ function setErrorHandling($mode = null, $options = null)
-
- /**
- * Sets how errors generated by this object should be handled.
- * Can be invoked both in objects and statically. If called
- * statically, setErrorHandling sets the default behaviour for all
- * PEAR objects. If called in an object, setErrorHandling sets
- * the default behaviour for that object.
- *
- * @param int $mode
- * One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
- * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
- * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION.
- *
- * @param mixed $options
- * When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
- * of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
- *
- * When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
- * to be the callback function or method. A callback
- * function is a string with the name of the function, a
- * callback method is an array of two elements: the element
- * at index 0 is the object, and the element at index 1 is
- * the name of the method to call in the object.
- *
- * When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
- * a printf format string used when printing the error
- * message.
- *
- * @access public
- * @return void
- * @see PEAR_ERROR_RETURN
- * @see PEAR_ERROR_PRINT
- * @see PEAR_ERROR_TRIGGER
- * @see PEAR_ERROR_DIE
- * @see PEAR_ERROR_CALLBACK
- * @see PEAR_ERROR_EXCEPTION
- *
- * @since PHP 4.0.5
- * @uses PEAR::setErrorHandling($mode, $options)
- */
- public function setErrorHandling($mode = null, $options = null)
- {
- return $this->pear->setErrorHandling($mode, $options);
- }
-
- /**
- * @uses PEAR::staticPopErrorHandling()
- */
- public function staticPopErrorHandling()
- {
- return $this->pear->staticPopErrorHandling();
- }
-
- // }}}
- // {{{ function staticPushErrorHandling($mode, $options = null)
-
- /**
- * @uses PEAR::staticPushErrorHandling($mode, $options)
- */
- public function staticPushErrorHandling($mode, $options = null)
- {
- return $this->pear->staticPushErrorHandling($mode, $options);
- }
-
- // }}}
- // {{{ function &throwError($message = null, $code = null, $userinfo = null)
-
- /**
- * Simpler form of raiseError with fewer options. In most cases
- * message, code and userinfo are enough.
- *
- * @param mixed $message a text error message or a PEAR error object
- *
- * @param int $code a numeric error code (it is up to your class
- * to define these if you want to use codes)
- *
- * @param string $userinfo If you need to pass along for example debug
- * information, this parameter is meant for that.
- *
- * @return object a PEAR error object
- * @see PEAR::raiseError
- * @uses PEAR::&throwError()
- */
- public function &throwError($message = null, $code = null, $userinfo = null)
- {
- $tmp = $this->pear->throwError($message, $code, $userinfo);
- return $tmp;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Result
-
-/**
- * The dummy class that all user space result classes should extend from
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Result
-{
-}
-
-// }}}
-// {{{ class MDB2_Result_Common extends MDB2_Result
-
-/**
- * The common result class for MDB2 result objects
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Result_Common extends MDB2_Result
-{
- // {{{ Variables (Properties)
-
- public $db;
- public $result;
- public $rownum = -1;
- public $types = array();
- public $types_assoc = array();
- public $values = array();
- public $offset;
- public $offset_count = 0;
- public $limit;
- public $column_names;
-
- // }}}
- // {{{ constructor: function __construct($db, &$result, $limit = 0, $offset = 0)
-
- /**
- * Constructor
- */
- function __construct($db, &$result, $limit = 0, $offset = 0)
- {
- $this->db = $db;
- $this->result = $result;
- $this->offset = $offset;
- $this->limit = max(0, $limit - 1);
- }
-
- // }}}
- // {{{ function setResultTypes($types)
-
- /**
- * Define the list of types to be associated with the columns of a given
- * result set.
- *
- * This function may be called before invoking fetchRow(), fetchOne(),
- * fetchCol() and fetchAll() so that the necessary data type
- * conversions are performed on the data to be retrieved by them. If this
- * function is not called, the type of all result set columns is assumed
- * to be text, thus leading to not perform any conversions.
- *
- * @param array variable that lists the
- * data types to be expected in the result set columns. If this array
- * contains less types than the number of columns that are returned
- * in the result set, the remaining columns are assumed to be of the
- * type text. Currently, the types clob and blob are not fully
- * supported.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function setResultTypes($types)
- {
- $load = $this->db->loadModule('Datatype', null, true);
- if (MDB2::isError($load)) {
- return $load;
- }
- $types = $this->db->datatype->checkResultTypes($types);
- if (MDB2::isError($types)) {
- return $types;
- }
- foreach ($types as $key => $value) {
- if (is_numeric($key)) {
- $this->types[$key] = $value;
- } else {
- $this->types_assoc[$key] = $value;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function seek($rownum = 0)
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int number of the row where the data can be found
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function seek($rownum = 0)
- {
- $target_rownum = $rownum - 1;
- if ($this->rownum > $target_rownum) {
- return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'seeking to previous rows not implemented', __FUNCTION__);
- }
- while ($this->rownum < $target_rownum) {
- $this->fetchRow();
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
-
- /**
- * Fetch and return a row of data
- *
- * @param int how the array data should be indexed
- * @param int number of the row where the data can be found
- *
- * @return int data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- $err = MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $err;
- }
-
- // }}}
- // {{{ function fetchOne($colnum = 0)
-
- /**
- * fetch single column from the next row from a result set
- *
- * @param int|string the column number (or name) to fetch
- * @param int number of the row where the data can be found
- *
- * @return string data on success, a MDB2 error on failure
- * @access public
- */
- function fetchOne($colnum = 0, $rownum = null)
- {
- $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
- $row = $this->fetchRow($fetchmode, $rownum);
- if (!is_array($row) || MDB2::isError($row)) {
- return $row;
- }
- if (!array_key_exists($colnum, $row)) {
- return MDB2::raiseError(MDB2_ERROR_TRUNCATED, null, null,
- 'column is not defined in the result set: '.$colnum, __FUNCTION__);
- }
- return $row[$colnum];
- }
-
- // }}}
- // {{{ function fetchCol($colnum = 0)
-
- /**
- * Fetch and return a column from the current row pointer position
- *
- * @param int|string the column number (or name) to fetch
- *
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function fetchCol($colnum = 0)
- {
- $column = array();
- $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
- $row = $this->fetchRow($fetchmode);
- if (is_array($row)) {
- if (!array_key_exists($colnum, $row)) {
- return MDB2::raiseError(MDB2_ERROR_TRUNCATED, null, null,
- 'column is not defined in the result set: '.$colnum, __FUNCTION__);
- }
- do {
- $column[] = $row[$colnum];
- } while (is_array($row = $this->fetchRow($fetchmode)));
- }
- if (MDB2::isError($row)) {
- return $row;
- }
- return $column;
- }
-
- // }}}
- // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
-
- /**
- * Fetch and return all rows from the current row pointer position
- *
- * @param int $fetchmode the fetch mode to use:
- * + MDB2_FETCHMODE_ORDERED
- * + MDB2_FETCHMODE_ASSOC
- * + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED
- * + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED
- * @param bool if set to true, the $all will have the first
- * column as its first dimension
- * @param bool used only when the query returns exactly
- * two columns. If true, the values of the returned array will be
- * one-element arrays instead of scalars.
- * @param bool if true, the values of the returned array is
- * wrapped in another array. If the same key value (in the first
- * column) repeats itself, the values will be appended to this array
- * instead of overwriting the existing values.
- *
- * @return mixed data array on success, a MDB2 error on failure
- *
- * @access public
- * @see getAssoc()
- */
- function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,
- $force_array = false, $group = false)
- {
- $all = array();
- $row = $this->fetchRow($fetchmode);
- if (MDB2::isError($row)) {
- return $row;
- } elseif (!$row) {
- return $all;
- }
-
- $shift_array = $rekey ? false : null;
- if (null !== $shift_array) {
- if (is_object($row)) {
- $colnum = count(get_object_vars($row));
- } else {
- $colnum = count($row);
- }
- if ($colnum < 2) {
- return MDB2::raiseError(MDB2_ERROR_TRUNCATED, null, null,
- 'rekey feature requires atleast 2 column', __FUNCTION__);
- }
- $shift_array = (!$force_array && $colnum == 2);
- }
-
- if ($rekey) {
- do {
- if (is_object($row)) {
- $arr = get_object_vars($row);
- $key = reset($arr);
- unset($row->{$key});
- } else {
- if ( $fetchmode == MDB2_FETCHMODE_ASSOC
- || $fetchmode == MDB2_FETCHMODE_OBJECT
- ) {
- $key = reset($row);
- unset($row[key($row)]);
- } else {
- $key = array_shift($row);
- }
- if ($shift_array) {
- $row = array_shift($row);
- }
- }
- if ($group) {
- $all[$key][] = $row;
- } else {
- $all[$key] = $row;
- }
- } while (($row = $this->fetchRow($fetchmode)));
- } elseif ($fetchmode == MDB2_FETCHMODE_FLIPPED) {
- do {
- foreach ($row as $key => $val) {
- $all[$key][] = $val;
- }
- } while (($row = $this->fetchRow($fetchmode)));
- } else {
- do {
- $all[] = $row;
- } while (($row = $this->fetchRow($fetchmode)));
- }
-
- return $all;
- }
-
- // }}}
- // {{{ function rowCount()
- /**
- * Returns the actual row number that was last fetched (count from 0)
- * @return int
- *
- * @access public
- */
- function rowCount()
- {
- return $this->rownum + 1;
- }
-
- // }}}
- // {{{ function numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- *
- * @access public
- */
- function numRows()
- {
- return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function nextResult()
-
- /**
- * Move the internal result pointer to the next available result
- *
- * @return true on success, false if there is no more result set or an error object on failure
- *
- * @access public
- */
- function nextResult()
- {
- return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result or
- * from the cache.
- *
- * @param bool If set to true the values are the column names,
- * otherwise the names of the columns are the keys.
- * @return mixed Array variable that holds the names of columns or an
- * MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- *
- * @access public
- */
- function getColumnNames($flip = false)
- {
- if (!isset($this->column_names)) {
- $result = $this->_getColumnNames();
- if (MDB2::isError($result)) {
- return $result;
- }
- $this->column_names = $result;
- }
- if ($flip) {
- return array_flip($this->column_names);
- }
- return $this->column_names;
- }
-
- // }}}
- // {{{ function _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- *
- * @access private
- */
- function _getColumnNames()
- {
- return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- *
- * @access public
- */
- function numCols()
- {
- return MDB2::raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function getResource()
-
- /**
- * return the resource associated with the result object
- *
- * @return resource
- *
- * @access public
- */
- function getResource()
- {
- return $this->result;
- }
-
- // }}}
- // {{{ function bindColumn($column, &$value, $type = null)
-
- /**
- * Set bind variable to a column.
- *
- * @param int column number or name
- * @param mixed variable reference
- * @param string specifies the type of the field
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function bindColumn($column, &$value, $type = null)
- {
- if (!is_numeric($column)) {
- $column_names = $this->getColumnNames();
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($this->db->options['field_case'] == CASE_LOWER) {
- $column = strtolower($column);
- } else {
- $column = strtoupper($column);
- }
- }
- $column = $column_names[$column];
- }
- $this->values[$column] =& $value;
- if (null !== $type) {
- $this->types[$column] = $type;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function _assignBindColumns($row)
-
- /**
- * Bind a variable to a value in the result row.
- *
- * @param array row data
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access private
- */
- function _assignBindColumns($row)
- {
- $row = array_values($row);
- foreach ($row as $column => $value) {
- if (array_key_exists($column, $this->values)) {
- $this->values[$column] = $value;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return bool true on success, false if result is invalid
- *
- * @access public
- */
- function free()
- {
- $this->result = false;
- return MDB2_OK;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Row
-
-/**
- * The simple class that accepts row data as an array
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Row
-{
- // {{{ constructor: function __construct(&$row)
-
- /**
- * constructor
- *
- * @param resource row data as array
- */
- function __construct(&$row)
- {
- foreach ($row as $key => $value) {
- $this->$key = &$row[$key];
- }
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Statement_Common
-
-/**
- * The common statement class for MDB2 statement objects
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Statement_Common
-{
- // {{{ Variables (Properties)
-
- var $db;
- var $statement;
- var $query;
- var $result_types;
- var $types;
- var $values = array();
- var $limit;
- var $offset;
- var $is_manip;
-
- // }}}
- // {{{ constructor: function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
-
- /**
- * Constructor
- */
- function __construct($db, $statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
- {
- $this->db = $db;
- $this->statement = $statement;
- $this->positions = $positions;
- $this->query = $query;
- $this->types = (array)$types;
- $this->result_types = (array)$result_types;
- $this->limit = $limit;
- $this->is_manip = $is_manip;
- $this->offset = $offset;
- }
-
- // }}}
- // {{{ function bindValue($parameter, &$value, $type = null)
-
- /**
- * Set the value of a parameter of a prepared query.
- *
- * @param int the order number of the parameter in the query
- * statement. The order number of the first parameter is 1.
- * @param mixed value that is meant to be assigned to specified
- * parameter. The type of the value depends on the $type argument.
- * @param string specifies the type of the field
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function bindValue($parameter, $value, $type = null)
- {
- if (!is_numeric($parameter)) {
- if (strpos($parameter, ':') === 0) {
- $parameter = substr($parameter, 1);
- }
- }
- if (!in_array($parameter, $this->positions)) {
- return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $this->values[$parameter] = $value;
- if (null !== $type) {
- $this->types[$parameter] = $type;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function bindValueArray($values, $types = null)
-
- /**
- * Set the values of multiple a parameter of a prepared query in bulk.
- *
- * @param array specifies all necessary information
- * for bindValue() the array elements must use keys corresponding to
- * the number of the position of the parameter.
- * @param array specifies the types of the fields
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @see bindParam()
- */
- function bindValueArray($values, $types = null)
- {
- $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
- $parameters = array_keys($values);
- $this->db->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- foreach ($parameters as $key => $parameter) {
- $err = $this->bindValue($parameter, $values[$parameter], $types[$key]);
- if (MDB2::isError($err)) {
- if ($err->getCode() == MDB2_ERROR_NOT_FOUND) {
- //ignore (extra value for missing placeholder)
- continue;
- }
- $this->db->popExpect();
- $this->db->popErrorHandling();
- return $err;
- }
- }
- $this->db->popExpect();
- $this->db->popErrorHandling();
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function bindParam($parameter, &$value, $type = null)
-
- /**
- * Bind a variable to a parameter of a prepared query.
- *
- * @param int the order number of the parameter in the query
- * statement. The order number of the first parameter is 1.
- * @param mixed variable that is meant to be bound to specified
- * parameter. The type of the value depends on the $type argument.
- * @param string specifies the type of the field
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function bindParam($parameter, &$value, $type = null)
- {
- if (!is_numeric($parameter)) {
- if (strpos($parameter, ':') === 0) {
- $parameter = substr($parameter, 1);
- }
- }
- if (!in_array($parameter, $this->positions)) {
- return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $this->values[$parameter] =& $value;
- if (null !== $type) {
- $this->types[$parameter] = $type;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function bindParamArray(&$values, $types = null)
-
- /**
- * Bind the variables of multiple a parameter of a prepared query in bulk.
- *
- * @param array specifies all necessary information
- * for bindParam() the array elements must use keys corresponding to
- * the number of the position of the parameter.
- * @param array specifies the types of the fields
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @see bindParam()
- */
- function bindParamArray(&$values, $types = null)
- {
- $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
- $parameters = array_keys($values);
- foreach ($parameters as $key => $parameter) {
- $err = $this->bindParam($parameter, $values[$parameter], $types[$key]);
- if (MDB2::isError($err)) {
- return $err;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)
-
- /**
- * Execute a prepared query statement.
- *
- * @param array specifies all necessary information
- * for bindParam() the array elements must use keys corresponding
- * to the number of the position of the parameter.
- * @param mixed specifies which result class to use
- * @param mixed specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access public
- */
- function execute($values = null, $result_class = true, $result_wrap_class = false)
- {
- if (null === $this->positions) {
- return MDB2::raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
-
- $values = (array)$values;
- if (!empty($values)) {
- $err = $this->bindValueArray($values);
- if (MDB2::isError($err)) {
- return MDB2::raiseError(MDB2_ERROR, null, null,
- 'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);
- }
- }
- $result = $this->_execute($result_class, $result_wrap_class);
- return $result;
- }
-
- // }}}
- // {{{ function _execute($result_class = true, $result_wrap_class = false)
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed specifies which result class to use
- * @param mixed specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access private
- */
- function _execute($result_class = true, $result_wrap_class = false)
- {
- $this->last_query = $this->query;
- $query = '';
- $last_position = 0;
- foreach ($this->positions as $current_position => $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $value = $this->values[$parameter];
- $query.= substr($this->query, $last_position, $current_position - $last_position);
- if (!isset($value)) {
- $value_quoted = 'NULL';
- } else {
- $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
- $value_quoted = $this->db->quote($value, $type);
- if (MDB2::isError($value_quoted)) {
- return $value_quoted;
- }
- }
- $query.= $value_quoted;
- $last_position = $current_position + 1;
- }
- $query.= substr($this->query, $last_position);
-
- $this->db->offset = $this->offset;
- $this->db->limit = $this->limit;
- if ($this->is_manip) {
- $result = $this->db->exec($query);
- } else {
- $result = $this->db->query($query, $this->result_types, $result_class, $result_wrap_class);
- }
- return $result;
- }
-
- // }}}
- // {{{ function free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function free()
- {
- if (null === $this->positions) {
- return MDB2::raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
-
- $this->statement = null;
- $this->positions = null;
- $this->query = null;
- $this->types = null;
- $this->result_types = null;
- $this->limit = null;
- $this->is_manip = null;
- $this->offset = null;
- $this->values = null;
-
- return MDB2_OK;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Module_Common
-
-/**
- * The common modules class for MDB2 module objects
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Module_Common
-{
- // {{{ Variables (Properties)
-
- /**
- * contains the key to the global MDB2 instance array of the associated
- * MDB2 instance
- *
- * @var int
- * @access protected
- */
- protected $db_index;
-
- // }}}
- // {{{ constructor: function __construct($db_index)
-
- /**
- * Constructor
- */
- function __construct($db_index)
- {
- $this->db_index = $db_index;
- }
-
- // }}}
- // {{{ function getDBInstance()
-
- /**
- * Get the instance of MDB2 associated with the module instance
- *
- * @return object MDB2 instance or a MDB2 error on failure
- *
- * @access public
- */
- function getDBInstance()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $result = $GLOBALS['_MDB2_databases'][$this->db_index];
- } else {
- $result = MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'could not find MDB2 instance');
- }
- return $result;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ function MDB2_closeOpenTransactions()
-
-/**
- * Close any open transactions form persistent connections
- *
- * @return void
- *
- * @access public
- */
-
-function MDB2_closeOpenTransactions()
-{
- reset($GLOBALS['_MDB2_databases']);
- while (next($GLOBALS['_MDB2_databases'])) {
- $key = key($GLOBALS['_MDB2_databases']);
- if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent
- && $GLOBALS['_MDB2_databases'][$key]->in_transaction
- ) {
- $GLOBALS['_MDB2_databases'][$key]->rollback();
- }
- }
-}
-
-// }}}
-// {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)
-
-/**
- * default debug output handler
- *
- * @param object reference to an MDB2 database object
- * @param string usually the method name that triggered the debug call:
- * for example 'query', 'prepare', 'execute', 'parameters',
- * 'beginTransaction', 'commit', 'rollback'
- * @param string message that should be appended to the debug variable
- * @param array contains context information about the debug() call
- * common keys are: is_manip, time, result etc.
- *
- * @return void|string optionally return a modified message, this allows
- * rewriting a query before being issued or prepared
- *
- * @access public
- */
-function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())
-{
- $db->debug_output.= $scope.'('.$db->db_index.'): ';
- $db->debug_output.= $message.$db->getOption('log_line_break');
- return $message;
-}
-
-// }}}
-?>
diff --git a/3rdparty/MDB2/Date.php b/3rdparty/MDB2/Date.php
deleted file mode 100644
index ca88eaa347..0000000000
--- a/3rdparty/MDB2/Date.php
+++ /dev/null
@@ -1,183 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-
-/**
- * Several methods to convert the MDB2 native timestamp format (ISO based)
- * to and from data structures that are convenient to worth with in side of php.
- * For more complex date arithmetic please take a look at the Date package in PEAR
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Date
-{
- // {{{ mdbNow()
-
- /**
- * return the current datetime
- *
- * @return string current datetime in the MDB2 format
- * @access public
- */
- function mdbNow()
- {
- return date('Y-m-d H:i:s');
- }
- // }}}
-
- // {{{ mdbToday()
-
- /**
- * return the current date
- *
- * @return string current date in the MDB2 format
- * @access public
- */
- function mdbToday()
- {
- return date('Y-m-d');
- }
- // }}}
-
- // {{{ mdbTime()
-
- /**
- * return the current time
- *
- * @return string current time in the MDB2 format
- * @access public
- */
- function mdbTime()
- {
- return date('H:i:s');
- }
- // }}}
-
- // {{{ date2Mdbstamp()
-
- /**
- * convert a date into a MDB2 timestamp
- *
- * @param int hour of the date
- * @param int minute of the date
- * @param int second of the date
- * @param int month of the date
- * @param int day of the date
- * @param int year of the date
- *
- * @return string a valid MDB2 timestamp
- * @access public
- */
- function date2Mdbstamp($hour = null, $minute = null, $second = null,
- $month = null, $day = null, $year = null)
- {
- return MDB2_Date::unix2Mdbstamp(mktime($hour, $minute, $second, $month, $day, $year, -1));
- }
- // }}}
-
- // {{{ unix2Mdbstamp()
-
- /**
- * convert a unix timestamp into a MDB2 timestamp
- *
- * @param int a valid unix timestamp
- *
- * @return string a valid MDB2 timestamp
- * @access public
- */
- function unix2Mdbstamp($unix_timestamp)
- {
- return date('Y-m-d H:i:s', $unix_timestamp);
- }
- // }}}
-
- // {{{ mdbstamp2Unix()
-
- /**
- * convert a MDB2 timestamp into a unix timestamp
- *
- * @param int a valid MDB2 timestamp
- * @return string unix timestamp with the time stored in the MDB2 format
- *
- * @access public
- */
- function mdbstamp2Unix($mdb_timestamp)
- {
- $arr = MDB2_Date::mdbstamp2Date($mdb_timestamp);
-
- return mktime($arr['hour'], $arr['minute'], $arr['second'], $arr['month'], $arr['day'], $arr['year'], -1);
- }
- // }}}
-
- // {{{ mdbstamp2Date()
-
- /**
- * convert a MDB2 timestamp into an array containing all
- * values necessary to pass to php's date() function
- *
- * @param int a valid MDB2 timestamp
- *
- * @return array with the time split
- * @access public
- */
- function mdbstamp2Date($mdb_timestamp)
- {
- list($arr['year'], $arr['month'], $arr['day'], $arr['hour'], $arr['minute'], $arr['second']) =
- sscanf($mdb_timestamp, "%04u-%02u-%02u %02u:%02u:%02u");
- return $arr;
- }
- // }}}
-}
-
-?>
diff --git a/3rdparty/MDB2/Driver/Datatype/Common.php b/3rdparty/MDB2/Driver/Datatype/Common.php
deleted file mode 100644
index dd7f1c7e0a..0000000000
--- a/3rdparty/MDB2/Driver/Datatype/Common.php
+++ /dev/null
@@ -1,1842 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-
-require_once 'MDB2/LOB.php';
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-
-/**
- * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Datatype');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Datatype_Common extends MDB2_Module_Common
-{
- var $valid_default_values = array(
- 'text' => '',
- 'boolean' => true,
- 'integer' => 0,
- 'decimal' => 0.0,
- 'float' => 0.0,
- 'timestamp' => '1970-01-01 00:00:00',
- 'time' => '00:00:00',
- 'date' => '1970-01-01',
- 'clob' => '',
- 'blob' => '',
- );
-
- /**
- * contains all LOB objects created with this MDB2 instance
- * @var array
- * @access protected
- */
- var $lobs = array();
-
- // }}}
- // {{{ getValidTypes()
-
- /**
- * Get the list of valid types
- *
- * This function returns an array of valid types as keys with the values
- * being possible default values for all native datatypes and mapped types
- * for custom datatypes.
- *
- * @return mixed array on success, a MDB2 error on failure
- * @access public
- */
- function getValidTypes()
- {
- $types = $this->valid_default_values;
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (!empty($db->options['datatype_map'])) {
- foreach ($db->options['datatype_map'] as $type => $mapped_type) {
- if (array_key_exists($mapped_type, $types)) {
- $types[$type] = $types[$mapped_type];
- } elseif (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'mapped_type' => $mapped_type);
- $default = call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- $types[$type] = $default;
- }
- }
- }
- return $types;
- }
-
- // }}}
- // {{{ checkResultTypes()
-
- /**
- * Define the list of types to be associated with the columns of a given
- * result set.
- *
- * This function may be called before invoking fetchRow(), fetchOne()
- * fetchCole() and fetchAll() so that the necessary data type
- * conversions are performed on the data to be retrieved by them. If this
- * function is not called, the type of all result set columns is assumed
- * to be text, thus leading to not perform any conversions.
- *
- * @param array $types array variable that lists the
- * data types to be expected in the result set columns. If this array
- * contains less types than the number of columns that are returned
- * in the result set, the remaining columns are assumed to be of the
- * type text. Currently, the types clob and blob are not fully
- * supported.
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function checkResultTypes($types)
- {
- $types = is_array($types) ? $types : array($types);
- foreach ($types as $key => $type) {
- if (!isset($this->valid_default_values[$type])) {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (empty($db->options['datatype_map'][$type])) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- $type.' for '.$key.' is not a supported column type', __FUNCTION__);
- }
- }
- }
- return $types;
- }
-
- // }}}
- // {{{ _baseConvertResult()
-
- /**
- * General type conversion method
- *
- * @param mixed $value reference to a value to be converted
- * @param string $type specifies which type to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return object an MDB2 error on failure
- * @access protected
- */
- function _baseConvertResult($value, $type, $rtrim = true)
- {
- switch ($type) {
- case 'text':
- if ($rtrim) {
- $value = rtrim($value);
- }
- return $value;
- case 'integer':
- return intval($value);
- case 'boolean':
- return !empty($value);
- case 'decimal':
- return $value;
- case 'float':
- return doubleval($value);
- case 'date':
- return $value;
- case 'time':
- return $value;
- case 'timestamp':
- return $value;
- case 'clob':
- case 'blob':
- $this->lobs[] = array(
- 'buffer' => null,
- 'position' => 0,
- 'lob_index' => null,
- 'endOfLOB' => false,
- 'resource' => $value,
- 'value' => null,
- 'loaded' => false,
- );
- end($this->lobs);
- $lob_index = key($this->lobs);
- $this->lobs[$lob_index]['lob_index'] = $lob_index;
- return fopen('MDB2LOB://'.$lob_index.'@'.$this->db_index, 'r+');
- }
-
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'attempt to convert result value to an unknown type :' . $type, __FUNCTION__);
- }
-
- // }}}
- // {{{ convertResult()
-
- /**
- * Convert a value to a RDBMS indipendent MDB2 type
- *
- * @param mixed $value value to be converted
- * @param string $type specifies which type to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return mixed converted value
- * @access public
- */
- function convertResult($value, $type, $rtrim = true)
- {
- if (null === $value) {
- return null;
- }
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'value' => $value, 'rtrim' => $rtrim);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
- return $this->_baseConvertResult($value, $type, $rtrim);
- }
-
- // }}}
- // {{{ convertResultRow()
-
- /**
- * Convert a result row
- *
- * @param array $types
- * @param array $row specifies the types to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return mixed MDB2_OK on success, an MDB2 error on failure
- * @access public
- */
- function convertResultRow($types, $row, $rtrim = true)
- {
- //$types = $this->_sortResultFieldTypes(array_keys($row), $types);
- $keys = array_keys($row);
- if (is_int($keys[0])) {
- $types = $this->_sortResultFieldTypes($keys, $types);
- }
- foreach ($row as $key => $value) {
- if (empty($types[$key])) {
- continue;
- }
- $value = $this->convertResult($row[$key], $types[$key], $rtrim);
- if (PEAR::isError($value)) {
- return $value;
- }
- $row[$key] = $value;
- }
- return $row;
- }
-
- // }}}
- // {{{ _sortResultFieldTypes()
-
- /**
- * convert a result row
- *
- * @param array $types
- * @param array $row specifies the types to convert to
- * @param bool $rtrim if to rtrim text values or not
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function _sortResultFieldTypes($columns, $types)
- {
- $n_cols = count($columns);
- $n_types = count($types);
- if ($n_cols > $n_types) {
- for ($i= $n_cols - $n_types; $i >= 0; $i--) {
- $types[] = null;
- }
- }
- $sorted_types = array();
- foreach ($columns as $col) {
- $sorted_types[$col] = null;
- }
- foreach ($types as $name => $type) {
- if (array_key_exists($name, $sorted_types)) {
- $sorted_types[$name] = $type;
- unset($types[$name]);
- }
- }
- // if there are left types in the array, fill the null values of the
- // sorted array with them, in order.
- if (count($types)) {
- reset($types);
- foreach (array_keys($sorted_types) as $k) {
- if (null === $sorted_types[$k]) {
- $sorted_types[$k] = current($types);
- next($types);
- }
- }
- }
- return $sorted_types;
- }
-
- // }}}
- // {{{ getDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare
- * of the given type
- *
- * @param string $type type to which the value should be converted to
- * @param string $name name the field to be declared.
- * @param string $field definition of the field
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getDeclaration($type, $name, $field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'name' => $name, 'field' => $field);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- $field['type'] = $type;
- }
-
- if (!method_exists($this, "_get{$type}Declaration")) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'type not defined: '.$type, __FUNCTION__);
- }
- return $this->{"_get{$type}Declaration"}($name, $field);
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- $length = !empty($field['length']) ? $field['length'] : $db->options['default_text_field_length'];
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
- : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
- case 'clob':
- return 'TEXT';
- case 'blob':
- return 'TEXT';
- case 'integer':
- return 'INT';
- case 'boolean':
- return 'INT';
- case 'date':
- return 'CHAR ('.strlen('YYYY-MM-DD').')';
- case 'time':
- return 'CHAR ('.strlen('HH:MM:SS').')';
- case 'timestamp':
- return 'CHAR ('.strlen('YYYY-MM-DD HH:MM:SS').')';
- case 'float':
- return 'TEXT';
- case 'decimal':
- return 'TEXT';
- }
- return '';
- }
-
- // }}}
- // {{{ _getDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a generic type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * charset
- * Text value with the default CHARACTER SET for this field.
- * collation
- * Text value with the default COLLATION for this field.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field, or a MDB2_Error on failure
- * @access protected
- */
- function _getDeclaration($name, $field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $declaration_options = $db->datatype->_getDeclarationOptions($field);
- if (PEAR::isError($declaration_options)) {
- return $declaration_options;
- }
- return $name.' '.$this->getTypeDeclaration($field).$declaration_options;
- }
-
- // }}}
- // {{{ _getDeclarationOptions()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a generic type
- * field to be used in statement like CREATE TABLE, without the field name
- * and type values (ie. just the character set, default value, if the
- * field is permitted to be NULL or not, and the collation options).
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Text value to be used as default for this field.
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * charset
- * Text value with the default CHARACTER SET for this field.
- * collation
- * Text value with the default COLLATION for this field.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field's options.
- * @access protected
- */
- function _getDeclarationOptions($field)
- {
- $charset = empty($field['charset']) ? '' :
- ' '.$this->_getCharsetFieldDeclaration($field['charset']);
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $default = '';
- if (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $valid_default_values = $this->getValidTypes();
- $field['default'] = $valid_default_values[$field['type']];
- if ($field['default'] === '' && ($db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)) {
- $field['default'] = ' ';
- }
- }
- if (null !== $field['default']) {
- $default = ' DEFAULT ' . $this->quote($field['default'], $field['type']);
- }
- }
-
- $collation = empty($field['collation']) ? '' :
- ' '.$this->_getCollationFieldDeclaration($field['collation']);
-
- return $charset.$default.$notnull.$collation;
- }
-
- // }}}
- // {{{ _getCharsetFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $charset name of the charset
- * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
- * of a field declaration.
- */
- function _getCharsetFieldDeclaration($charset)
- {
- return '';
- }
-
- // }}}
- // {{{ _getCollationFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $collation name of the collation
- * @return string DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration.
- */
- function _getCollationFieldDeclaration($collation)
- {
- return '';
- }
-
- // }}}
- // {{{ _getIntegerDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an integer type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field should be
- * declared as unsigned integer if possible.
- *
- * default
- * Integer value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getIntegerDeclaration($name, $field)
- {
- if (!empty($field['unsigned'])) {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";
- }
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getTextDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getTextDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getCLOBDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an character
- * large object type field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the large
- * object field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function _getCLOBDeclaration($name, $field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$notnull;
- }
-
- // }}}
- // {{{ _getBLOBDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an binary large
- * object type field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the large
- * object field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getBLOBDeclaration($name, $field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$notnull;
- }
-
- // }}}
- // {{{ _getBooleanDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a boolean type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Boolean value to be used as default for this field.
- *
- * notnullL
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getBooleanDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getDateDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a date type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Date value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getDateDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getTimestampDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a timestamp
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Timestamp value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getTimestampDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getTimeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a time
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Time value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getTimeDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getFloatDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a float type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Float value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getFloatDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getDecimalDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a decimal type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Decimal value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getDecimalDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ compareDefinition()
-
- /**
- * Obtain an array of changes that may need to applied
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access public
- */
- function compareDefinition($current, $previous)
- {
- $type = !empty($current['type']) ? $current['type'] : null;
-
- if (!method_exists($this, "_compare{$type}Definition")) {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('current' => $current, 'previous' => $previous);
- $change = call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- return $change;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'type "'.$current['type'].'" is not yet supported', __FUNCTION__);
- }
-
- if (empty($previous['type']) || $previous['type'] != $type) {
- return $current;
- }
-
- $change = $this->{"_compare{$type}Definition"}($current, $previous);
-
- if ($previous['type'] != $type) {
- $change['type'] = true;
- }
-
- $previous_notnull = !empty($previous['notnull']) ? $previous['notnull'] : false;
- $notnull = !empty($current['notnull']) ? $current['notnull'] : false;
- if ($previous_notnull != $notnull) {
- $change['notnull'] = true;
- }
-
- $previous_default = array_key_exists('default', $previous) ? $previous['default'] :
- ($previous_notnull ? '' : null);
- $default = array_key_exists('default', $current) ? $current['default'] :
- ($notnull ? '' : null);
- if ($previous_default !== $default) {
- $change['default'] = true;
- }
-
- return $change;
- }
-
- // }}}
- // {{{ _compareIntegerDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an integer field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareIntegerDefinition($current, $previous)
- {
- $change = array();
- $previous_unsigned = !empty($previous['unsigned']) ? $previous['unsigned'] : false;
- $unsigned = !empty($current['unsigned']) ? $current['unsigned'] : false;
- if ($previous_unsigned != $unsigned) {
- $change['unsigned'] = true;
- }
- $previous_autoincrement = !empty($previous['autoincrement']) ? $previous['autoincrement'] : false;
- $autoincrement = !empty($current['autoincrement']) ? $current['autoincrement'] : false;
- if ($previous_autoincrement != $autoincrement) {
- $change['autoincrement'] = true;
- }
- return $change;
- }
-
- // }}}
- // {{{ _compareTextDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an text field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareTextDefinition($current, $previous)
- {
- $change = array();
- $previous_length = !empty($previous['length']) ? $previous['length'] : 0;
- $length = !empty($current['length']) ? $current['length'] : 0;
- if ($previous_length != $length) {
- $change['length'] = true;
- }
- $previous_fixed = !empty($previous['fixed']) ? $previous['fixed'] : 0;
- $fixed = !empty($current['fixed']) ? $current['fixed'] : 0;
- if ($previous_fixed != $fixed) {
- $change['fixed'] = true;
- }
- return $change;
- }
-
- // }}}
- // {{{ _compareCLOBDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an CLOB field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareCLOBDefinition($current, $previous)
- {
- return $this->_compareTextDefinition($current, $previous);
- }
-
- // }}}
- // {{{ _compareBLOBDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an BLOB field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareBLOBDefinition($current, $previous)
- {
- return $this->_compareTextDefinition($current, $previous);
- }
-
- // }}}
- // {{{ _compareDateDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an date field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareDateDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareTimeDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an time field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareTimeDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareTimestampDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an timestamp field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareTimestampDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareBooleanDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an boolean field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareBooleanDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareFloatDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an float field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareFloatDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareDecimalDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an decimal field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareDecimalDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ quote()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param string $type type to which the value should be converted to
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access public
- */
- function quote($value, $type = null, $quote = true, $escape_wildcards = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ((null === $value)
- || ($value === '' && $db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)
- ) {
- if (!$quote) {
- return null;
- }
- return 'NULL';
- }
-
- if (null === $type) {
- switch (gettype($value)) {
- case 'integer':
- $type = 'integer';
- break;
- case 'double':
- // todo: default to decimal as float is quite unusual
- // $type = 'float';
- $type = 'decimal';
- break;
- case 'boolean':
- $type = 'boolean';
- break;
- case 'array':
- $value = serialize($value);
- case 'object':
- $type = 'text';
- break;
- default:
- if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $value)) {
- $type = 'timestamp';
- } elseif (preg_match('/^\d{2}:\d{2}$/', $value)) {
- $type = 'time';
- } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
- $type = 'date';
- } else {
- $type = 'text';
- }
- break;
- }
- } elseif (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'value' => $value, 'quote' => $quote, 'escape_wildcards' => $escape_wildcards);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
-
- if (!method_exists($this, "_quote{$type}")) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'type not defined: '.$type, __FUNCTION__);
- }
- $value = $this->{"_quote{$type}"}($value, $quote, $escape_wildcards);
- if ($quote && $escape_wildcards && $db->string_quoting['escape_pattern']
- && $db->string_quoting['escape'] !== $db->string_quoting['escape_pattern']
- ) {
- $value.= $this->patternEscapeString();
- }
- return $value;
- }
-
- // }}}
- // {{{ _quoteInteger()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteInteger($value, $quote, $escape_wildcards)
- {
- return (int)$value;
- }
-
- // }}}
- // {{{ _quoteText()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that already contains any DBMS specific
- * escaped character sequences.
- * @access protected
- */
- function _quoteText($value, $quote, $escape_wildcards)
- {
- if (!$quote) {
- return $value;
- }
-
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $value = $db->escape($value, $escape_wildcards);
- if (PEAR::isError($value)) {
- return $value;
- }
- return "'".$value."'";
- }
-
- // }}}
- // {{{ _readFile()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _readFile($value)
- {
- $close = false;
- if (preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
- $close = true;
- if (strtolower($match[1]) == 'file://') {
- $value = $match[2];
- }
- $value = @fopen($value, 'r');
- }
-
- if (is_resource($value)) {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $fp = $value;
- $value = '';
- while (!@feof($fp)) {
- $value.= @fread($fp, $db->options['lob_buffer_length']);
- }
- if ($close) {
- @fclose($fp);
- }
- }
-
- return $value;
- }
-
- // }}}
- // {{{ _quoteLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteLOB($value, $quote, $escape_wildcards)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if ($db->options['lob_allow_url_include']) {
- $value = $this->_readFile($value);
- if (PEAR::isError($value)) {
- return $value;
- }
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteCLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteCLOB($value, $quote, $escape_wildcards)
- {
- return $this->_quoteLOB($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteBLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBLOB($value, $quote, $escape_wildcards)
- {
- return $this->_quoteLOB($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteBoolean()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBoolean($value, $quote, $escape_wildcards)
- {
- return ($value ? 1 : 0);
- }
-
- // }}}
- // {{{ _quoteDate()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteDate($value, $quote, $escape_wildcards)
- {
- if ($value === 'CURRENT_DATE') {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (isset($db->function) && is_object($this->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
- return $db->function->now('date');
- }
- return 'CURRENT_DATE';
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteTimestamp()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteTimestamp($value, $quote, $escape_wildcards)
- {
- if ($value === 'CURRENT_TIMESTAMP') {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (isset($db->function) && is_object($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
- return $db->function->now('timestamp');
- }
- return 'CURRENT_TIMESTAMP';
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteTime()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteTime($value, $quote, $escape_wildcards)
- {
- if ($value === 'CURRENT_TIME') {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (isset($db->function) && is_object($this->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
- return $db->function->now('time');
- }
- return 'CURRENT_TIME';
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteFloat()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteFloat($value, $quote, $escape_wildcards)
- {
- if (preg_match('/^(.*)e([-+])(\d+)$/i', $value, $matches)) {
- $decimal = $this->_quoteDecimal($matches[1], $quote, $escape_wildcards);
- $sign = $matches[2];
- $exponent = str_pad($matches[3], 2, '0', STR_PAD_LEFT);
- $value = $decimal.'E'.$sign.$exponent;
- } else {
- $value = $this->_quoteDecimal($value, $quote, $escape_wildcards);
- }
- return $value;
- }
-
- // }}}
- // {{{ _quoteDecimal()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteDecimal($value, $quote, $escape_wildcards)
- {
- $value = (string)$value;
- $value = preg_replace('/[^\d\.,\-+eE]/', '', $value);
- if (preg_match('/[^\.\d]/', $value)) {
- if (strpos($value, ',')) {
- // 1000,00
- if (!strpos($value, '.')) {
- // convert the last "," to a "."
- $value = strrev(str_replace(',', '.', strrev($value)));
- // 1.000,00
- } elseif (strpos($value, '.') && strpos($value, '.') < strpos($value, ',')) {
- $value = str_replace('.', '', $value);
- // convert the last "," to a "."
- $value = strrev(str_replace(',', '.', strrev($value)));
- // 1,000.00
- } else {
- $value = str_replace(',', '', $value);
- }
- }
- }
- return $value;
- }
-
- // }}}
- // {{{ writeLOBToFile()
-
- /**
- * retrieve LOB from the database
- *
- * @param resource $lob stream handle
- * @param string $file name of the file into which the LOb should be fetched
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access protected
- */
- function writeLOBToFile($lob, $file)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (preg_match('/^(\w+:\/\/)(.*)$/', $file, $match)) {
- if ($match[1] == 'file://') {
- $file = $match[2];
- }
- }
-
- $fp = @fopen($file, 'wb');
- while (!@feof($lob)) {
- $result = @fread($lob, $db->options['lob_buffer_length']);
- $read = strlen($result);
- if (@fwrite($fp, $result, $read) != $read) {
- @fclose($fp);
- return $db->raiseError(MDB2_ERROR, null, null,
- 'could not write to the output file', __FUNCTION__);
- }
- }
- @fclose($fp);
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _retrieveLOB()
-
- /**
- * retrieve LOB from the database
- *
- * @param array $lob array
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access protected
- */
- function _retrieveLOB(&$lob)
- {
- if (null === $lob['value']) {
- $lob['value'] = $lob['resource'];
- }
- $lob['loaded'] = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ readLOB()
-
- /**
- * Read data from large object input stream.
- *
- * @param resource $lob stream handle
- * @param string $data reference to a variable that will hold data
- * to be read from the large object input stream
- * @param integer $length value that indicates the largest ammount ofdata
- * to be read from the large object input stream.
- * @return mixed the effective number of bytes read from the large object
- * input stream on sucess or an MDB2 error object.
- * @access public
- * @see endOfLOB()
- */
- function _readLOB($lob, $length)
- {
- return substr($lob['value'], $lob['position'], $length);
- }
-
- // }}}
- // {{{ _endOfLOB()
-
- /**
- * Determine whether it was reached the end of the large object and
- * therefore there is no more data to be read for the its input stream.
- *
- * @param array $lob array
- * @return mixed true or false on success, a MDB2 error on failure
- * @access protected
- */
- function _endOfLOB($lob)
- {
- return $lob['endOfLOB'];
- }
-
- // }}}
- // {{{ destroyLOB()
-
- /**
- * Free any resources allocated during the lifetime of the large object
- * handler object.
- *
- * @param resource $lob stream handle
- * @access public
- */
- function destroyLOB($lob)
- {
- $lob_data = stream_get_meta_data($lob);
- $lob_index = $lob_data['wrapper_data']->lob_index;
- fclose($lob);
- if (isset($this->lobs[$lob_index])) {
- $this->_destroyLOB($this->lobs[$lob_index]);
- unset($this->lobs[$lob_index]);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _destroyLOB()
-
- /**
- * Free any resources allocated during the lifetime of the large object
- * handler object.
- *
- * @param array $lob array
- * @access private
- */
- function _destroyLOB(&$lob)
- {
- return MDB2_OK;
- }
-
- // }}}
- // {{{ implodeArray()
-
- /**
- * apply a type to all values of an array and return as a comma seperated string
- * useful for generating IN statements
- *
- * @access public
- *
- * @param array $array data array
- * @param string $type determines type of the field
- *
- * @return string comma seperated values
- */
- function implodeArray($array, $type = false)
- {
- if (!is_array($array) || empty($array)) {
- return 'NULL';
- }
- if ($type) {
- foreach ($array as $value) {
- $return[] = $this->quote($value, $type);
- }
- } else {
- $return = $array;
- }
- return implode(', ', $return);
- }
-
- // }}}
- // {{{ matchPattern()
-
- /**
- * build a pattern matching string
- *
- * @access public
- *
- * @param array $pattern even keys are strings, odd are patterns (% and _)
- * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
- * @param string $field optional field name that is being matched against
- * (might be required when emulating ILIKE)
- *
- * @return string SQL pattern
- */
- function matchPattern($pattern, $operator = null, $field = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $match = '';
- if (null !== $operator) {
- $operator = strtoupper($operator);
- switch ($operator) {
- // case insensitive
- case 'ILIKE':
- if (null === $field) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'case insensitive LIKE matching requires passing the field name', __FUNCTION__);
- }
- $db->loadModule('Function', null, true);
- $match = $db->function->lower($field).' LIKE ';
- break;
- case 'NOT ILIKE':
- if (null === $field) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'case insensitive NOT ILIKE matching requires passing the field name', __FUNCTION__);
- }
- $db->loadModule('Function', null, true);
- $match = $db->function->lower($field).' NOT LIKE ';
- break;
- // case sensitive
- case 'LIKE':
- $match = (null === $field) ? 'LIKE ' : ($field.' LIKE ');
- break;
- case 'NOT LIKE':
- $match = (null === $field) ? 'NOT LIKE ' : ($field.' NOT LIKE ');
- break;
- default:
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'not a supported operator type:'. $operator, __FUNCTION__);
- }
- }
- $match.= "'";
- foreach ($pattern as $key => $value) {
- if ($key % 2) {
- $match.= $value;
- } else {
- $escaped = $db->escape($value);
- if (PEAR::isError($escaped)) {
- return $escaped;
- }
- $match.= $db->escapePattern($escaped);
- }
- }
- $match.= "'";
- $match.= $this->patternEscapeString();
- return $match;
- }
-
- // }}}
- // {{{ patternEscapeString()
-
- /**
- * build string to define pattern escape character
- *
- * @access public
- *
- * @return string define pattern escape character
- */
- function patternEscapeString()
- {
- return '';
- }
-
- // }}}
- // {{{ mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function mapNativeDatatype($field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- // If the user has specified an option to map the native field
- // type to a custom MDB2 datatype...
- $db_type = strtok($field['type'], '(), ');
- if (!empty($db->options['nativetype_map_callback'][$db_type])) {
- return call_user_func_array($db->options['nativetype_map_callback'][$db_type], array($db, $field));
- }
-
- // Otherwise perform the built-in (i.e. normal) MDB2 native type to
- // MDB2 datatype conversion
- return $this->_mapNativeDatatype($field);
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ mapPrepareDatatype()
-
- /**
- * Maps an mdb2 datatype to mysqli prepare type
- *
- * @param string $type
- * @return string
- * @access public
- */
- function mapPrepareDatatype($type)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
-
- return $type;
- }
-}
-?>
diff --git a/3rdparty/MDB2/Driver/Datatype/mysql.php b/3rdparty/MDB2/Driver/Datatype/mysql.php
deleted file mode 100644
index d23eed23ff..0000000000
--- a/3rdparty/MDB2/Driver/Datatype/mysql.php
+++ /dev/null
@@ -1,602 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-require_once 'MDB2/Driver/Datatype/Common.php';
-
-/**
- * MDB2 MySQL driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Datatype_mysql extends MDB2_Driver_Datatype_Common
-{
- // {{{ _getCharsetFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $charset name of the charset
- * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
- * of a field declaration.
- */
- function _getCharsetFieldDeclaration($charset)
- {
- return 'CHARACTER SET '.$charset;
- }
-
- // }}}
- // {{{ _getCollationFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $collation name of the collation
- * @return string DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration.
- */
- function _getCollationFieldDeclaration($collation)
- {
- return 'COLLATE '.$collation;
- }
-
- // }}}
- // {{{ getDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare
- * of the given type
- *
- * @param string $type type to which the value should be converted to
- * @param string $name name the field to be declared.
- * @param string $field definition of the field
- *
- * @return string DBMS-specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getDeclaration($type, $name, $field)
- {
- // MySQL DDL syntax forbids combining NOT NULL with DEFAULT NULL.
- // To get a default of NULL for NOT NULL columns, omit it.
- if ( isset($field['notnull'])
- && !empty($field['notnull'])
- && array_key_exists('default', $field) // do not use isset() here!
- && null === $field['default']
- ) {
- unset($field['default']);
- }
- return parent::getDeclaration($type, $name, $field);
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- if (empty($field['length']) && array_key_exists('default', $field)) {
- $field['length'] = $db->varchar_max_length;
- }
- $length = !empty($field['length']) ? $field['length'] : false;
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)')
- : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
- case 'clob':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 255) {
- return 'TINYTEXT';
- } elseif ($length <= 65532) {
- return 'TEXT';
- } elseif ($length <= 16777215) {
- return 'MEDIUMTEXT';
- }
- }
- return 'LONGTEXT';
- case 'blob':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 255) {
- return 'TINYBLOB';
- } elseif ($length <= 65532) {
- return 'BLOB';
- } elseif ($length <= 16777215) {
- return 'MEDIUMBLOB';
- }
- }
- return 'LONGBLOB';
- case 'integer':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 1) {
- return 'TINYINT';
- } elseif ($length == 2) {
- return 'SMALLINT';
- } elseif ($length == 3) {
- return 'MEDIUMINT';
- } elseif ($length == 4) {
- return 'INT';
- } elseif ($length > 4) {
- return 'BIGINT';
- }
- }
- return 'INT';
- case 'boolean':
- return 'TINYINT(1)';
- case 'date':
- return 'DATE';
- case 'time':
- return 'TIME';
- case 'timestamp':
- return 'DATETIME';
- case 'float':
- $l = '';
- if (!empty($field['length'])) {
- $l = '(' . $field['length'];
- if (!empty($field['scale'])) {
- $l .= ',' . $field['scale'];
- }
- $l .= ')';
- }
- return 'DOUBLE' . $l;
- case 'decimal':
- $length = !empty($field['length']) ? $field['length'] : 18;
- $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
- return 'DECIMAL('.$length.','.$scale.')';
- }
- return '';
- }
-
- // }}}
- // {{{ _getIntegerDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an integer type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param string $field associative array with the name of the properties
- * of the field being declared as array indexes.
- * Currently, the types of supported field
- * properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field
- * should be declared as unsigned integer if
- * possible.
- *
- * default
- * Integer value to be used as default for this
- * field.
- *
- * notnull
- * Boolean flag that indicates whether this field is
- * constrained to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getIntegerDeclaration($name, $field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $default = $autoinc = '';
- if (!empty($field['autoincrement'])) {
- $autoinc = ' AUTO_INCREMENT PRIMARY KEY';
- } elseif (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $field['default'] = empty($field['notnull']) ? null : 0;
- }
- $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
- if (empty($default) && empty($notnull)) {
- $default = ' DEFAULT NULL';
- }
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;
- }
-
- // }}}
- // {{{ _getFloatDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an float type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param string $field associative array with the name of the properties
- * of the field being declared as array indexes.
- * Currently, the types of supported field
- * properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field
- * should be declared as unsigned float if
- * possible.
- *
- * default
- * float value to be used as default for this
- * field.
- *
- * notnull
- * Boolean flag that indicates whether this field is
- * constrained to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getFloatDeclaration($name, $field)
- {
- // Since AUTO_INCREMENT can be used for integer or floating-point types,
- // reuse the INTEGER declaration
- // @see http://bugs.mysql.com/bug.php?id=31032
- return $this->_getIntegerDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getDecimalDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an decimal type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param string $field associative array with the name of the properties
- * of the field being declared as array indexes.
- * Currently, the types of supported field
- * properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field
- * should be declared as unsigned integer if
- * possible.
- *
- * default
- * Decimal value to be used as default for this
- * field.
- *
- * notnull
- * Boolean flag that indicates whether this field is
- * constrained to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getDecimalDeclaration($name, $field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $default = '';
- if (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $field['default'] = empty($field['notnull']) ? null : 0;
- }
- $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
- } elseif (empty($field['notnull'])) {
- $default = ' DEFAULT NULL';
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull;
- }
-
- // }}}
- // {{{ matchPattern()
-
- /**
- * build a pattern matching string
- *
- * @access public
- *
- * @param array $pattern even keys are strings, odd are patterns (% and _)
- * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
- * @param string $field optional field name that is being matched against
- * (might be required when emulating ILIKE)
- *
- * @return string SQL pattern
- */
- function matchPattern($pattern, $operator = null, $field = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $match = '';
- if (null !== $operator) {
- $field = (null === $field) ? '' : $field.' ';
- $operator = strtoupper($operator);
- switch ($operator) {
- // case insensitive
- case 'ILIKE':
- $match = $field.'LIKE ';
- break;
- case 'NOT ILIKE':
- $match = $field.'NOT LIKE ';
- break;
- // case sensitive
- case 'LIKE':
- $match = $field.'LIKE BINARY ';
- break;
- case 'NOT LIKE':
- $match = $field.'NOT LIKE BINARY ';
- break;
- default:
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'not a supported operator type:'. $operator, __FUNCTION__);
- }
- }
- $match.= "'";
- foreach ($pattern as $key => $value) {
- if ($key % 2) {
- $match.= $value;
- } else {
- $match.= $db->escapePattern($db->escape($value));
- }
- }
- $match.= "'";
- $match.= $this->patternEscapeString();
- return $match;
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db_type = strtolower($field['type']);
- $db_type = strtok($db_type, '(), ');
- if ($db_type == 'national') {
- $db_type = strtok('(), ');
- }
- if (!empty($field['length'])) {
- $length = strtok($field['length'], ', ');
- $decimal = strtok(', ');
- } else {
- $length = strtok('(), ');
- $decimal = strtok('(), ');
- }
- $type = array();
- $unsigned = $fixed = null;
- switch ($db_type) {
- case 'tinyint':
- $type[] = 'integer';
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 1;
- break;
- case 'smallint':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 2;
- break;
- case 'mediumint':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 3;
- break;
- case 'int':
- case 'integer':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 4;
- break;
- case 'bigint':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 8;
- break;
- case 'tinytext':
- case 'mediumtext':
- case 'longtext':
- case 'text':
- case 'varchar':
- $fixed = false;
- case 'string':
- case 'char':
- $type[] = 'text';
- if ($length == '1') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- } elseif (strstr($db_type, 'text')) {
- $type[] = 'clob';
- if ($decimal == 'binary') {
- $type[] = 'blob';
- }
- $type = array_reverse($type);
- }
- if ($fixed !== false) {
- $fixed = true;
- }
- break;
- case 'enum':
- $type[] = 'text';
- preg_match_all('/\'.+\'/U', $field['type'], $matches);
- $length = 0;
- $fixed = false;
- if (is_array($matches)) {
- foreach ($matches[0] as $value) {
- $length = max($length, strlen($value)-2);
- }
- if ($length == '1' && count($matches[0]) == 2) {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- }
- }
- $type[] = 'integer';
- case 'set':
- $fixed = false;
- $type[] = 'text';
- $type[] = 'integer';
- break;
- case 'date':
- $type[] = 'date';
- $length = null;
- break;
- case 'datetime':
- case 'timestamp':
- $type[] = 'timestamp';
- $length = null;
- break;
- case 'time':
- $type[] = 'time';
- $length = null;
- break;
- case 'float':
- case 'double':
- case 'real':
- $type[] = 'float';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- if ($decimal !== false) {
- $length = $length.','.$decimal;
- }
- break;
- case 'unknown':
- case 'decimal':
- case 'numeric':
- $type[] = 'decimal';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- if ($decimal !== false) {
- $length = $length.','.$decimal;
- }
- break;
- case 'tinyblob':
- case 'mediumblob':
- case 'longblob':
- case 'blob':
- $type[] = 'blob';
- $length = null;
- break;
- case 'binary':
- case 'varbinary':
- $type[] = 'blob';
- break;
- case 'year':
- $type[] = 'integer';
- $type[] = 'date';
- $length = null;
- break;
- default:
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unknown database attribute type: '.$db_type, __FUNCTION__);
- }
-
- if ((int)$length <= 0) {
- $length = null;
- }
-
- return array($type, $length, $unsigned, $fixed);
- }
-
- // }}}
-}
-
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Datatype/oci8.php b/3rdparty/MDB2/Driver/Datatype/oci8.php
deleted file mode 100644
index 4d2e792a80..0000000000
--- a/3rdparty/MDB2/Driver/Datatype/oci8.php
+++ /dev/null
@@ -1,499 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-
-// $Id: oci8.php 295587 2010-02-28 17:16:38Z quipo $
-
-require_once 'MDB2/Driver/Datatype/Common.php';
-
-/**
- * MDB2 OCI8 driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Datatype_oci8 extends MDB2_Driver_Datatype_Common
-{
- // {{{ _baseConvertResult()
-
- /**
- * general type conversion method
- *
- * @param mixed $value refernce to a value to be converted
- * @param string $type specifies which type to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return object a MDB2 error on failure
- * @access protected
- */
- function _baseConvertResult($value, $type, $rtrim = true)
- {
- if (null === $value) {
- return null;
- }
- switch ($type) {
- case 'text':
- if (is_object($value) && is_a($value, 'OCI-Lob')) {
- //LOB => fetch into variable
- $clob = $this->_baseConvertResult($value, 'clob', $rtrim);
- if (!PEAR::isError($clob) && is_resource($clob)) {
- $clob_value = '';
- while (!feof($clob)) {
- $clob_value .= fread($clob, 8192);
- }
- $this->destroyLOB($clob);
- }
- $value = $clob_value;
- }
- if ($rtrim) {
- $value = rtrim($value);
- }
- return $value;
- case 'date':
- return substr($value, 0, strlen('YYYY-MM-DD'));
- case 'time':
- return substr($value, strlen('YYYY-MM-DD '), strlen('HH:MI:SS'));
- }
- return parent::_baseConvertResult($value, $type, $rtrim);
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- $length = !empty($field['length'])
- ? $field['length'] : $db->options['default_text_field_length'];
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? 'CHAR('.$length.')' : 'VARCHAR2('.$length.')';
- case 'clob':
- return 'CLOB';
- case 'blob':
- return 'BLOB';
- case 'integer':
- if (!empty($field['length'])) {
- switch((int)$field['length']) {
- case 1: $digit = 3; break;
- case 2: $digit = 5; break;
- case 3: $digit = 8; break;
- case 4: $digit = 10; break;
- case 5: $digit = 13; break;
- case 6: $digit = 15; break;
- case 7: $digit = 17; break;
- case 8: $digit = 20; break;
- default: $digit = 10;
- }
- return 'NUMBER('.$digit.')';
- }
- return 'INT';
- case 'boolean':
- return 'NUMBER(1)';
- case 'date':
- case 'time':
- case 'timestamp':
- return 'DATE';
- case 'float':
- return 'NUMBER';
- case 'decimal':
- $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
- return 'NUMBER(*,'.$scale.')';
- }
- }
-
- // }}}
- // {{{ _quoteCLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteCLOB($value, $quote, $escape_wildcards)
- {
- return 'EMPTY_CLOB()';
- }
-
- // }}}
- // {{{ _quoteBLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBLOB($value, $quote, $escape_wildcards)
- {
- return 'EMPTY_BLOB()';
- }
-
- // }}}
- // {{{ _quoteDate()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteDate($value, $quote, $escape_wildcards)
- {
- return $this->_quoteText("$value 00:00:00", $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteTimestamp()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- //function _quoteTimestamp($value, $quote, $escape_wildcards)
- //{
- // return $this->_quoteText($value, $quote, $escape_wildcards);
- //}
-
- // }}}
- // {{{ _quoteTime()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteTime($value, $quote, $escape_wildcards)
- {
- return $this->_quoteText("0001-01-01 $value", $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ writeLOBToFile()
-
- /**
- * retrieve LOB from the database
- *
- * @param array $lob array
- * @param string $file name of the file into which the LOb should be fetched
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access protected
- */
- function writeLOBToFile($lob, $file)
- {
- if (preg_match('/^(\w+:\/\/)(.*)$/', $file, $match)) {
- if ($match[1] == 'file://') {
- $file = $match[2];
- }
- }
- $lob_data = stream_get_meta_data($lob);
- $lob_index = $lob_data['wrapper_data']->lob_index;
- $result = $this->lobs[$lob_index]['resource']->writetofile($file);
- $this->lobs[$lob_index]['resource']->seek(0);
- if (!$result) {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(null, null, null,
- 'Unable to write LOB to file', __FUNCTION__);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _retrieveLOB()
-
- /**
- * retrieve LOB from the database
- *
- * @param array $lob array
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access protected
- */
- function _retrieveLOB(&$lob)
- {
- if (!is_object($lob['resource'])) {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'attemped to retrieve LOB from non existing or NULL column', __FUNCTION__);
- }
-
- if (!$lob['loaded']
-# && !method_exists($lob['resource'], 'read')
- ) {
- $lob['value'] = $lob['resource']->load();
- $lob['resource']->seek(0);
- }
- $lob['loaded'] = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _readLOB()
-
- /**
- * Read data from large object input stream.
- *
- * @param array $lob array
- * @param blob $data reference to a variable that will hold data to be
- * read from the large object input stream
- * @param int $length integer value that indicates the largest ammount of
- * data to be read from the large object input stream.
- * @return mixed length on success, a MDB2 error on failure
- * @access protected
- */
- function _readLOB($lob, $length)
- {
- if ($lob['loaded']) {
- return parent::_readLOB($lob, $length);
- }
-
- if (!is_object($lob['resource'])) {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'attemped to retrieve LOB from non existing or NULL column', __FUNCTION__);
- }
-
- $data = $lob['resource']->read($length);
- if (!is_string($data)) {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(null, null, null,
- 'Unable to read LOB', __FUNCTION__);
- }
- return $data;
- }
-
- // }}}
- // {{{ patternEscapeString()
-
- /**
- * build string to define escape pattern string
- *
- * @access public
- *
- *
- * @return string define escape pattern
- */
- function patternEscapeString()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- return " ESCAPE '". $db->string_quoting['escape_pattern'] ."'";
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db_type = strtolower($field['type']);
- $type = array();
- $length = $unsigned = $fixed = null;
- if (!empty($field['length'])) {
- $length = $field['length'];
- }
- switch ($db_type) {
- case 'integer':
- case 'pls_integer':
- case 'binary_integer':
- $type[] = 'integer';
- if ($length == '1') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- }
- break;
- case 'varchar':
- case 'varchar2':
- case 'nvarchar2':
- $fixed = false;
- case 'char':
- case 'nchar':
- $type[] = 'text';
- if ($length == '1') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- }
- if ($fixed !== false) {
- $fixed = true;
- }
- break;
- case 'date':
- case 'timestamp':
- $type[] = 'timestamp';
- $length = null;
- break;
- case 'float':
- $type[] = 'float';
- break;
- case 'number':
- if (!empty($field['scale'])) {
- $type[] = 'decimal';
- $length = $length.','.$field['scale'];
- } else {
- $type[] = 'integer';
- if ($length == '1') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- }
- }
- break;
- case 'long':
- $type[] = 'text';
- case 'clob':
- case 'nclob':
- $type[] = 'clob';
- break;
- case 'blob':
- case 'raw':
- case 'long raw':
- case 'bfile':
- $type[] = 'blob';
- $length = null;
- break;
- case 'rowid':
- case 'urowid':
- default:
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unknown database attribute type: '.$db_type, __FUNCTION__);
- }
-
- if ((int)$length <= 0) {
- $length = null;
- }
-
- return array($type, $length, $unsigned, $fixed);
- }
-}
-
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Datatype/pgsql.php b/3rdparty/MDB2/Driver/Datatype/pgsql.php
deleted file mode 100644
index db2fa27902..0000000000
--- a/3rdparty/MDB2/Driver/Datatype/pgsql.php
+++ /dev/null
@@ -1,579 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-
-require_once 'MDB2/Driver/Datatype/Common.php';
-
-/**
- * MDB2 PostGreSQL driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_Driver_Datatype_pgsql extends MDB2_Driver_Datatype_Common
-{
- // {{{ _baseConvertResult()
-
- /**
- * General type conversion method
- *
- * @param mixed $value refernce to a value to be converted
- * @param string $type specifies which type to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return object a MDB2 error on failure
- * @access protected
- */
- function _baseConvertResult($value, $type, $rtrim = true)
- {
- if (null === $value) {
- return null;
- }
- switch ($type) {
- case 'boolean':
- return $value == 't';
- case 'float':
- return doubleval($value);
- case 'date':
- return $value;
- case 'time':
- return substr($value, 0, strlen('HH:MM:SS'));
- case 'timestamp':
- return substr($value, 0, strlen('YYYY-MM-DD HH:MM:SS'));
- case 'blob':
- $value = pg_unescape_bytea($value);
- return parent::_baseConvertResult($value, $type, $rtrim);
- }
- return parent::_baseConvertResult($value, $type, $rtrim);
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- $length = !empty($field['length']) ? $field['length'] : false;
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
- : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
- case 'clob':
- return 'TEXT';
- case 'blob':
- return 'BYTEA';
- case 'integer':
- if (!empty($field['autoincrement'])) {
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length > 4) {
- return 'BIGSERIAL PRIMARY KEY';
- }
- }
- return 'SERIAL PRIMARY KEY';
- }
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 2) {
- return 'SMALLINT';
- } elseif ($length == 3 || $length == 4) {
- return 'INT';
- } elseif ($length > 4) {
- return 'BIGINT';
- }
- }
- return 'INT';
- case 'boolean':
- return 'BOOLEAN';
- case 'date':
- return 'DATE';
- case 'time':
- return 'TIME without time zone';
- case 'timestamp':
- return 'TIMESTAMP without time zone';
- case 'float':
- return 'FLOAT8';
- case 'decimal':
- $length = !empty($field['length']) ? $field['length'] : 18;
- $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
- return 'NUMERIC('.$length.','.$scale.')';
- }
- }
-
- // }}}
- // {{{ _getIntegerDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an integer type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field should be
- * declared as unsigned integer if possible.
- *
- * default
- * Integer value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getIntegerDeclaration($name, $field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($field['unsigned'])) {
- $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";
- }
- if (!empty($field['autoincrement'])) {
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field);
- }
- $default = '';
- if (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $field['default'] = empty($field['notnull']) ? null : 0;
- }
- $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- if (empty($default) && empty($notnull)) {
- $default = ' DEFAULT NULL';
- }
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$default.$notnull;
- }
-
- // }}}
- // {{{ _quoteCLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteCLOB($value, $quote, $escape_wildcards)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if ($db->options['lob_allow_url_include']) {
- $value = $this->_readFile($value);
- if (PEAR::isError($value)) {
- return $value;
- }
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteBLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBLOB($value, $quote, $escape_wildcards)
- {
- if (!$quote) {
- return $value;
- }
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if ($db->options['lob_allow_url_include']) {
- $value = $this->_readFile($value);
- if (PEAR::isError($value)) {
- return $value;
- }
- }
- if (version_compare(PHP_VERSION, '5.2.0RC6', '>=')) {
- $connection = $db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $value = @pg_escape_bytea($connection, $value);
- } else {
- $value = @pg_escape_bytea($value);
- }
- return "'".$value."'";
- }
-
- // }}}
- // {{{ _quoteBoolean()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBoolean($value, $quote, $escape_wildcards)
- {
- $value = $value ? 't' : 'f';
- if (!$quote) {
- return $value;
- }
- return "'".$value."'";
- }
-
- // }}}
- // {{{ matchPattern()
-
- /**
- * build a pattern matching string
- *
- * @access public
- *
- * @param array $pattern even keys are strings, odd are patterns (% and _)
- * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
- * @param string $field optional field name that is being matched against
- * (might be required when emulating ILIKE)
- *
- * @return string SQL pattern
- */
- function matchPattern($pattern, $operator = null, $field = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $match = '';
- if (null !== $operator) {
- $field = (null === $field) ? '' : $field.' ';
- $operator = strtoupper($operator);
- switch ($operator) {
- // case insensitive
- case 'ILIKE':
- $match = $field.'ILIKE ';
- break;
- case 'NOT ILIKE':
- $match = $field.'NOT ILIKE ';
- break;
- // case sensitive
- case 'LIKE':
- $match = $field.'LIKE ';
- break;
- case 'NOT LIKE':
- $match = $field.'NOT LIKE ';
- break;
- default:
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'not a supported operator type:'. $operator, __FUNCTION__);
- }
- }
- $match.= "'";
- foreach ($pattern as $key => $value) {
- if ($key % 2) {
- $match.= $value;
- } else {
- $match.= $db->escapePattern($db->escape($value));
- }
- }
- $match.= "'";
- $match.= $this->patternEscapeString();
- return $match;
- }
-
- // }}}
- // {{{ patternEscapeString()
-
- /**
- * build string to define escape pattern string
- *
- * @access public
- *
- *
- * @return string define escape pattern
- */
- function patternEscapeString()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- return ' ESCAPE '.$this->quote($db->string_quoting['escape_pattern']);
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db_type = strtolower($field['type']);
- $length = $field['length'];
- $type = array();
- $unsigned = $fixed = null;
- switch ($db_type) {
- case 'smallint':
- case 'int2':
- $type[] = 'integer';
- $unsigned = false;
- $length = 2;
- if ($length == '2') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- }
- break;
- case 'int':
- case 'int4':
- case 'integer':
- case 'serial':
- case 'serial4':
- $type[] = 'integer';
- $unsigned = false;
- $length = 4;
- break;
- case 'bigint':
- case 'int8':
- case 'bigserial':
- case 'serial8':
- $type[] = 'integer';
- $unsigned = false;
- $length = 8;
- break;
- case 'bool':
- case 'boolean':
- $type[] = 'boolean';
- $length = null;
- break;
- case 'text':
- case 'varchar':
- $fixed = false;
- case 'unknown':
- case 'char':
- case 'bpchar':
- $type[] = 'text';
- if ($length == '1') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- } elseif (strstr($db_type, 'text')) {
- $type[] = 'clob';
- $type = array_reverse($type);
- }
- if ($fixed !== false) {
- $fixed = true;
- }
- break;
- case 'date':
- $type[] = 'date';
- $length = null;
- break;
- case 'datetime':
- case 'timestamp':
- case 'timestamptz':
- $type[] = 'timestamp';
- $length = null;
- break;
- case 'time':
- $type[] = 'time';
- $length = null;
- break;
- case 'float':
- case 'float4':
- case 'float8':
- case 'double':
- case 'real':
- $type[] = 'float';
- break;
- case 'decimal':
- case 'money':
- case 'numeric':
- $type[] = 'decimal';
- if (isset($field['scale'])) {
- $length = $length.','.$field['scale'];
- }
- break;
- case 'tinyblob':
- case 'mediumblob':
- case 'longblob':
- case 'blob':
- case 'bytea':
- $type[] = 'blob';
- $length = null;
- break;
- case 'oid':
- $type[] = 'blob';
- $type[] = 'clob';
- $length = null;
- break;
- case 'year':
- $type[] = 'integer';
- $type[] = 'date';
- $length = null;
- break;
- default:
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unknown database attribute type: '.$db_type, __FUNCTION__);
- }
-
- if ((int)$length <= 0) {
- $length = null;
- }
-
- return array($type, $length, $unsigned, $fixed);
- }
-
- // }}}
- // {{{ mapPrepareDatatype()
-
- /**
- * Maps an mdb2 datatype to native prepare type
- *
- * @param string $type
- * @return string
- * @access public
- */
- function mapPrepareDatatype($type)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
-
- switch ($type) {
- case 'integer':
- return 'int';
- case 'boolean':
- return 'bool';
- case 'decimal':
- case 'float':
- return 'numeric';
- case 'clob':
- return 'text';
- case 'blob':
- return 'bytea';
- default:
- break;
- }
- return $type;
- }
- // }}}
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Datatype/sqlite.php b/3rdparty/MDB2/Driver/Datatype/sqlite.php
deleted file mode 100644
index 50475a3628..0000000000
--- a/3rdparty/MDB2/Driver/Datatype/sqlite.php
+++ /dev/null
@@ -1,418 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-require_once 'MDB2/Driver/Datatype/Common.php';
-
-/**
- * MDB2 SQLite driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Datatype_sqlite extends MDB2_Driver_Datatype_Common
-{
- // {{{ _getCollationFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $collation name of the collation
- *
- * @return string DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration.
- */
- function _getCollationFieldDeclaration($collation)
- {
- return 'COLLATE '.$collation;
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- $length = !empty($field['length'])
- ? $field['length'] : false;
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
- : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
- case 'clob':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 255) {
- return 'TINYTEXT';
- } elseif ($length <= 65532) {
- return 'TEXT';
- } elseif ($length <= 16777215) {
- return 'MEDIUMTEXT';
- }
- }
- return 'LONGTEXT';
- case 'blob':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 255) {
- return 'TINYBLOB';
- } elseif ($length <= 65532) {
- return 'BLOB';
- } elseif ($length <= 16777215) {
- return 'MEDIUMBLOB';
- }
- }
- return 'LONGBLOB';
- case 'integer':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 2) {
- return 'SMALLINT';
- } elseif ($length == 3 || $length == 4) {
- return 'INTEGER';
- } elseif ($length > 4) {
- return 'BIGINT';
- }
- }
- return 'INTEGER';
- case 'boolean':
- return 'BOOLEAN';
- case 'date':
- return 'DATE';
- case 'time':
- return 'TIME';
- case 'timestamp':
- return 'DATETIME';
- case 'float':
- return 'DOUBLE'.($db->options['fixed_float'] ? '('.
- ($db->options['fixed_float']+2).','.$db->options['fixed_float'].')' : '');
- case 'decimal':
- $length = !empty($field['length']) ? $field['length'] : 18;
- $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
- return 'DECIMAL('.$length.','.$scale.')';
- }
- return '';
- }
-
- // }}}
- // {{{ _getIntegerDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an integer type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param string $field associative array with the name of the properties
- * of the field being declared as array indexes.
- * Currently, the types of supported field
- * properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field
- * should be declared as unsigned integer if
- * possible.
- *
- * default
- * Integer value to be used as default for this
- * field.
- *
- * notnull
- * Boolean flag that indicates whether this field is
- * constrained to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getIntegerDeclaration($name, $field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $default = $autoinc = '';
- if (!empty($field['autoincrement'])) {
- $autoinc = ' PRIMARY KEY';
- } elseif (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $field['default'] = empty($field['notnull']) ? null : 0;
- }
- $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
- if (empty($default) && empty($notnull)) {
- $default = ' DEFAULT NULL';
- }
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;
- }
-
- // }}}
- // {{{ matchPattern()
-
- /**
- * build a pattern matching string
- *
- * @access public
- *
- * @param array $pattern even keys are strings, odd are patterns (% and _)
- * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
- * @param string $field optional field name that is being matched against
- * (might be required when emulating ILIKE)
- *
- * @return string SQL pattern
- */
- function matchPattern($pattern, $operator = null, $field = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $match = '';
- if (null !== $operator) {
- $field = (null === $field) ? '' : $field.' ';
- $operator = strtoupper($operator);
- switch ($operator) {
- // case insensitive
- case 'ILIKE':
- $match = $field.'LIKE ';
- break;
- case 'NOT ILIKE':
- $match = $field.'NOT LIKE ';
- break;
- // case sensitive
- case 'LIKE':
- $match = $field.'LIKE ';
- break;
- case 'NOT LIKE':
- $match = $field.'NOT LIKE ';
- break;
- default:
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'not a supported operator type:'. $operator, __FUNCTION__);
- }
- }
- $match.= "'";
- foreach ($pattern as $key => $value) {
- if ($key % 2) {
- $match.= $value;
- } else {
- $match.= $db->escapePattern($db->escape($value));
- }
- }
- $match.= "'";
- $match.= $this->patternEscapeString();
- return $match;
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db_type = strtolower($field['type']);
- $length = !empty($field['length']) ? $field['length'] : null;
- $unsigned = !empty($field['unsigned']) ? $field['unsigned'] : null;
- $fixed = null;
- $type = array();
- switch ($db_type) {
- case 'boolean':
- $type[] = 'boolean';
- break;
- case 'tinyint':
- $type[] = 'integer';
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 1;
- break;
- case 'smallint':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 2;
- break;
- case 'mediumint':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 3;
- break;
- case 'int':
- case 'integer':
- case 'serial':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 4;
- break;
- case 'bigint':
- case 'bigserial':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 8;
- break;
- case 'clob':
- $type[] = 'clob';
- $fixed = false;
- break;
- case 'tinytext':
- case 'mediumtext':
- case 'longtext':
- case 'text':
- case 'varchar':
- case 'varchar2':
- $fixed = false;
- case 'char':
- $type[] = 'text';
- if ($length == '1') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- } elseif (strstr($db_type, 'text')) {
- $type[] = 'clob';
- $type = array_reverse($type);
- }
- if ($fixed !== false) {
- $fixed = true;
- }
- break;
- case 'date':
- $type[] = 'date';
- $length = null;
- break;
- case 'datetime':
- case 'timestamp':
- $type[] = 'timestamp';
- $length = null;
- break;
- case 'time':
- $type[] = 'time';
- $length = null;
- break;
- case 'float':
- case 'double':
- case 'real':
- $type[] = 'float';
- break;
- case 'decimal':
- case 'numeric':
- $type[] = 'decimal';
- $length = $length.','.$field['decimal'];
- break;
- case 'tinyblob':
- case 'mediumblob':
- case 'longblob':
- case 'blob':
- $type[] = 'blob';
- $length = null;
- break;
- case 'year':
- $type[] = 'integer';
- $type[] = 'date';
- $length = null;
- break;
- default:
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unknown database attribute type: '.$db_type, __FUNCTION__);
- }
-
- if ((int)$length <= 0) {
- $length = null;
- }
-
- return array($type, $length, $unsigned, $fixed);
- }
-
- // }}}
-}
-
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Function/Common.php b/3rdparty/MDB2/Driver/Function/Common.php
deleted file mode 100644
index 5a780fd48e..0000000000
--- a/3rdparty/MDB2/Driver/Function/Common.php
+++ /dev/null
@@ -1,293 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-
-/**
- * Base class for the function modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Function');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Function_Common extends MDB2_Module_Common
-{
- // {{{ executeStoredProc()
-
- /**
- * Execute a stored procedure and return any results
- *
- * @param string $name string that identifies the function to execute
- * @param mixed $params array that contains the paramaters to pass the stored proc
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- *
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $error = $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $error;
- }
-
- // }}}
- // {{{ functionTable()
-
- /**
- * return string for internal table used when calling only a function
- *
- * @return string for internal table used when calling only a function
- * @access public
- */
- function functionTable()
- {
- return '';
- }
-
- // }}}
- // {{{ now()
-
- /**
- * Return string to call a variable with the current timestamp inside an SQL statement
- * There are three special variables for current date and time:
- * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type)
- * - CURRENT_DATE (date, DATE type)
- * - CURRENT_TIME (time, TIME type)
- *
- * @param string $type 'timestamp' | 'time' | 'date'
- *
- * @return string to call a variable with the current timestamp
- * @access public
- */
- function now($type = 'timestamp')
- {
- switch ($type) {
- case 'time':
- return 'CURRENT_TIME';
- case 'date':
- return 'CURRENT_DATE';
- case 'timestamp':
- default:
- return 'CURRENT_TIMESTAMP';
- }
- }
-
- // }}}
- // {{{ unixtimestamp()
-
- /**
- * return string to call a function to get the unix timestamp from a iso timestamp
- *
- * @param string $expression
- *
- * @return string to call a variable with the timestamp
- * @access public
- */
- function unixtimestamp($expression)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $error = $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $error;
- }
-
- // }}}
- // {{{ substring()
-
- /**
- * return string to call a function to get a substring inside an SQL statement
- *
- * @return string to call a function to get a substring
- * @access public
- */
- function substring($value, $position = 1, $length = null)
- {
- if (null !== $length) {
- return "SUBSTRING($value FROM $position FOR $length)";
- }
- return "SUBSTRING($value FROM $position)";
- }
-
- // }}}
- // {{{ replace()
-
- /**
- * return string to call a function to get replace inside an SQL statement.
- *
- * @return string to call a function to get a replace
- * @access public
- */
- function replace($str, $from_str, $to_str)
- {
- return "REPLACE($str, $from_str , $to_str)";
- }
-
- // }}}
- // {{{ concat()
-
- /**
- * Returns string to concatenate two or more string parameters
- *
- * @param string $value1
- * @param string $value2
- * @param string $values...
- *
- * @return string to concatenate two strings
- * @access public
- */
- function concat($value1, $value2)
- {
- $args = func_get_args();
- return "(".implode(' || ', $args).")";
- }
-
- // }}}
- // {{{ random()
-
- /**
- * return string to call a function to get random value inside an SQL statement
- *
- * @return return string to generate float between 0 and 1
- * @access public
- */
- function random()
- {
- return 'RAND()';
- }
-
- // }}}
- // {{{ lower()
-
- /**
- * return string to call a function to lower the case of an expression
- *
- * @param string $expression
- *
- * @return return string to lower case of an expression
- * @access public
- */
- function lower($expression)
- {
- return "LOWER($expression)";
- }
-
- // }}}
- // {{{ upper()
-
- /**
- * return string to call a function to upper the case of an expression
- *
- * @param string $expression
- *
- * @return return string to upper case of an expression
- * @access public
- */
- function upper($expression)
- {
- return "UPPER($expression)";
- }
-
- // }}}
- // {{{ length()
-
- /**
- * return string to call a function to get the length of a string expression
- *
- * @param string $expression
- *
- * @return return string to get the string expression length
- * @access public
- */
- function length($expression)
- {
- return "LENGTH($expression)";
- }
-
- // }}}
- // {{{ guid()
-
- /**
- * Returns global unique identifier
- *
- * @return string to get global unique identifier
- * @access public
- */
- function guid()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $error = $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $error;
- }
-
- // }}}
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Function/mysql.php b/3rdparty/MDB2/Driver/Function/mysql.php
deleted file mode 100644
index 90fdafc973..0000000000
--- a/3rdparty/MDB2/Driver/Function/mysql.php
+++ /dev/null
@@ -1,136 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-require_once 'MDB2/Driver/Function/Common.php';
-
-/**
- * MDB2 MySQL driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Function_mysql extends MDB2_Driver_Function_Common
-{
- // }}}
- // {{{ executeStoredProc()
-
- /**
- * Execute a stored procedure and return any results
- *
- * @param string $name string that identifies the function to execute
- * @param mixed $params array that contains the paramaters to pass the stored proc
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'CALL '.$name;
- $query .= $params ? '('.implode(', ', $params).')' : '()';
- return $db->query($query, $types, $result_class, $result_wrap_class);
- }
-
- // }}}
- // {{{ unixtimestamp()
-
- /**
- * return string to call a function to get the unix timestamp from a iso timestamp
- *
- * @param string $expression
- *
- * @return string to call a variable with the timestamp
- * @access public
- */
- function unixtimestamp($expression)
- {
- return 'UNIX_TIMESTAMP('. $expression.')';
- }
-
- // }}}
- // {{{ concat()
-
- /**
- * Returns string to concatenate two or more string parameters
- *
- * @param string $value1
- * @param string $value2
- * @param string $values...
- * @return string to concatenate two strings
- * @access public
- **/
- function concat($value1, $value2)
- {
- $args = func_get_args();
- return "CONCAT(".implode(', ', $args).")";
- }
-
- // }}}
- // {{{ guid()
-
- /**
- * Returns global unique identifier
- *
- * @return string to get global unique identifier
- * @access public
- */
- function guid()
- {
- return 'UUID()';
- }
-
- // }}}
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Function/oci8.php b/3rdparty/MDB2/Driver/Function/oci8.php
deleted file mode 100644
index 757d17fcb8..0000000000
--- a/3rdparty/MDB2/Driver/Function/oci8.php
+++ /dev/null
@@ -1,187 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-
-// $Id: oci8.php 295587 2010-02-28 17:16:38Z quipo $
-
-require_once 'MDB2/Driver/Function/Common.php';
-
-/**
- * MDB2 oci8 driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Function_oci8 extends MDB2_Driver_Function_Common
-{
- // {{{ executeStoredProc()
-
- /**
- * Execute a stored procedure and return any results
- *
- * @param string $name string that identifies the function to execute
- * @param mixed $params array that contains the paramaters to pass the stored proc
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'EXEC '.$name;
- $query .= $params ? '('.implode(', ', $params).')' : '()';
- return $db->query($query, $types, $result_class, $result_wrap_class);
- }
-
- // }}}
- // {{{ functionTable()
-
- /**
- * return string for internal table used when calling only a function
- *
- * @return string for internal table used when calling only a function
- * @access public
- */
- function functionTable()
- {
- return ' FROM dual';
- }
-
- // }}}
- // {{{ now()
-
- /**
- * Return string to call a variable with the current timestamp inside an SQL statement
- * There are three special variables for current date and time:
- * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type)
- * - CURRENT_DATE (date, DATE type)
- * - CURRENT_TIME (time, TIME type)
- *
- * @return string to call a variable with the current timestamp
- * @access public
- */
- function now($type = 'timestamp')
- {
- switch ($type) {
- case 'date':
- case 'time':
- case 'timestamp':
- default:
- return 'TO_CHAR(CURRENT_TIMESTAMP, \'YYYY-MM-DD HH24:MI:SS\')';
- }
- }
-
- // }}}
- // {{{ unixtimestamp()
-
- /**
- * return string to call a function to get the unix timestamp from a iso timestamp
- *
- * @param string $expression
- *
- * @return string to call a variable with the timestamp
- * @access public
- */
- function unixtimestamp($expression)
- {
- $utc_offset = 'CAST(SYS_EXTRACT_UTC(SYSTIMESTAMP) AS DATE) - CAST(SYSTIMESTAMP AS DATE)';
- $epoch_date = 'to_date(\'19700101\', \'YYYYMMDD\')';
- return '(CAST('.$expression.' AS DATE) - '.$epoch_date.' + '.$utc_offset.') * 86400 seconds';
- }
-
- // }}}
- // {{{ substring()
-
- /**
- * return string to call a function to get a substring inside an SQL statement
- *
- * @return string to call a function to get a substring
- * @access public
- */
- function substring($value, $position = 1, $length = null)
- {
- if (null !== $length) {
- return "SUBSTR($value, $position, $length)";
- }
- return "SUBSTR($value, $position)";
- }
-
- // }}}
- // {{{ random()
-
- /**
- * return string to call a function to get random value inside an SQL statement
- *
- * @return return string to generate float between 0 and 1
- * @access public
- */
- function random()
- {
- return 'dbms_random.value';
- }
-
- // }}}}
- // {{{ guid()
-
- /**
- * Returns global unique identifier
- *
- * @return string to get global unique identifier
- * @access public
- */
- function guid()
- {
- return 'SYS_GUID()';
- }
-
- // }}}}
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Function/pgsql.php b/3rdparty/MDB2/Driver/Function/pgsql.php
deleted file mode 100644
index 7cc34a2d70..0000000000
--- a/3rdparty/MDB2/Driver/Function/pgsql.php
+++ /dev/null
@@ -1,132 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-
-require_once 'MDB2/Driver/Function/Common.php';
-
-/**
- * MDB2 MySQL driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Function_pgsql extends MDB2_Driver_Function_Common
-{
- // {{{ executeStoredProc()
-
- /**
- * Execute a stored procedure and return any results
- *
- * @param string $name string that identifies the function to execute
- * @param mixed $params array that contains the paramaters to pass the stored proc
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT * FROM '.$name;
- $query .= $params ? '('.implode(', ', $params).')' : '()';
- return $db->query($query, $types, $result_class, $result_wrap_class);
- }
- // }}}
- // {{{ unixtimestamp()
-
- /**
- * return string to call a function to get the unix timestamp from a iso timestamp
- *
- * @param string $expression
- *
- * @return string to call a variable with the timestamp
- * @access public
- */
- function unixtimestamp($expression)
- {
- return 'EXTRACT(EPOCH FROM DATE_TRUNC(\'seconds\', CAST ((' . $expression . ') AS TIMESTAMP)))';
- }
-
- // }}}
- // {{{ substring()
-
- /**
- * return string to call a function to get a substring inside an SQL statement
- *
- * @return string to call a function to get a substring
- * @access public
- */
- function substring($value, $position = 1, $length = null)
- {
- if (null !== $length) {
- return "SUBSTRING(CAST($value AS VARCHAR) FROM $position FOR $length)";
- }
- return "SUBSTRING(CAST($value AS VARCHAR) FROM $position)";
- }
-
- // }}}
- // {{{ random()
-
- /**
- * return string to call a function to get random value inside an SQL statement
- *
- * @return return string to generate float between 0 and 1
- * @access public
- */
- function random()
- {
- return 'RANDOM()';
- }
-
- // }}}
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Function/sqlite.php b/3rdparty/MDB2/Driver/Function/sqlite.php
deleted file mode 100644
index 65ade4fec0..0000000000
--- a/3rdparty/MDB2/Driver/Function/sqlite.php
+++ /dev/null
@@ -1,162 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-require_once 'MDB2/Driver/Function/Common.php';
-
-/**
- * MDB2 SQLite driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Function_sqlite extends MDB2_Driver_Function_Common
-{
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct($db_index)
- {
- parent::__construct($db_index);
- // create all sorts of UDFs
- }
-
- // {{{ now()
-
- /**
- * Return string to call a variable with the current timestamp inside an SQL statement
- * There are three special variables for current date and time.
- *
- * @return string to call a variable with the current timestamp
- * @access public
- */
- function now($type = 'timestamp')
- {
- switch ($type) {
- case 'time':
- return 'time(\'now\')';
- case 'date':
- return 'date(\'now\')';
- case 'timestamp':
- default:
- return 'datetime(\'now\')';
- }
- }
-
- // }}}
- // {{{ unixtimestamp()
-
- /**
- * return string to call a function to get the unix timestamp from a iso timestamp
- *
- * @param string $expression
- *
- * @return string to call a variable with the timestamp
- * @access public
- */
- function unixtimestamp($expression)
- {
- return 'strftime("%s",'. $expression.', "utc")';
- }
-
- // }}}
- // {{{ substring()
-
- /**
- * return string to call a function to get a substring inside an SQL statement
- *
- * @return string to call a function to get a substring
- * @access public
- */
- function substring($value, $position = 1, $length = null)
- {
- if (null !== $length) {
- return "substr($value, $position, $length)";
- }
- return "substr($value, $position, length($value))";
- }
-
- // }}}
- // {{{ random()
-
- /**
- * return string to call a function to get random value inside an SQL statement
- *
- * @return return string to generate float between 0 and 1
- * @access public
- */
- function random()
- {
- return '((RANDOM()+2147483648)/4294967296)';
- }
-
- // }}}
- // {{{ replace()
-
- /**
- * return string to call a function to get a replacement inside an SQL statement.
- *
- * @return string to call a function to get a replace
- * @access public
- */
- function replace($str, $from_str, $to_str)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $error = $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $error;
- }
-
- // }}}
-}
-?>
diff --git a/3rdparty/MDB2/Driver/Manager/Common.php b/3rdparty/MDB2/Driver/Manager/Common.php
deleted file mode 100644
index 2e99c332a2..0000000000
--- a/3rdparty/MDB2/Driver/Manager/Common.php
+++ /dev/null
@@ -1,1038 +0,0 @@
- |
-// | Lorenzo Alberton |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- * @author Lorenzo Alberton
- */
-
-/**
- * Base class for the management modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Manager');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Manager_Common extends MDB2_Module_Common
-{
- // {{{ splitTableSchema()
-
- /**
- * Split the "[owner|schema].table" notation into an array
- *
- * @param string $table [schema and] table name
- *
- * @return array array(schema, table)
- * @access private
- */
- function splitTableSchema($table)
- {
- $ret = array();
- if (strpos($table, '.') !== false) {
- return explode('.', $table);
- }
- return array(null, $table);
- }
-
- // }}}
- // {{{ getFieldDeclarationList()
-
- /**
- * Get declaration of a number of field in bulk
- *
- * @param array $fields a multidimensional associative array.
- * The first dimension determines the field name, while the second
- * dimension is keyed with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Boolean value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- *
- * @return mixed string on success, a MDB2 error on failure
- * @access public
- */
- function getFieldDeclarationList($fields)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!is_array($fields) || empty($fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'missing any fields', __FUNCTION__);
- }
- foreach ($fields as $field_name => $field) {
- $query = $db->getDeclaration($field['type'], $field_name, $field);
- if (PEAR::isError($query)) {
- return $query;
- }
- $query_fields[] = $query;
- }
- return implode(', ', $query_fields);
- }
-
- // }}}
- // {{{ _fixSequenceName()
-
- /**
- * Removes any formatting in an sequence name using the 'seqname_format' option
- *
- * @param string $sqn string that containts name of a potential sequence
- * @param bool $check if only formatted sequences should be returned
- * @return string name of the sequence with possible formatting removed
- * @access protected
- */
- function _fixSequenceName($sqn, $check = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $seq_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['seqname_format']).'$/i';
- $seq_name = preg_replace($seq_pattern, '\\1', $sqn);
- if ($seq_name && !strcasecmp($sqn, $db->getSequenceName($seq_name))) {
- return $seq_name;
- }
- if ($check) {
- return false;
- }
- return $sqn;
- }
-
- // }}}
- // {{{ _fixIndexName()
-
- /**
- * Removes any formatting in an index name using the 'idxname_format' option
- *
- * @param string $idx string that containts name of anl index
- * @return string name of the index with eventual formatting removed
- * @access protected
- */
- function _fixIndexName($idx)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $idx_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['idxname_format']).'$/i';
- $idx_name = preg_replace($idx_pattern, '\\1', $idx);
- if ($idx_name && !strcasecmp($idx, $db->getIndexName($idx_name))) {
- return $idx_name;
- }
- return $idx;
- }
-
- // }}}
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset, collation info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($database, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ alterDatabase()
-
- /**
- * alter an existing database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset, collation info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function alterDatabase($database, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($database)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ _getCreateTableQuery()
-
- /**
- * Create a basic SQL query for a new table creation
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * @param array $options An associative array of table options
- *
- * @return mixed string (the SQL query) on success, a MDB2 error on failure
- * @see createTable()
- */
- function _getCreateTableQuery($name, $fields, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!$name) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- 'no valid table name specified', __FUNCTION__);
- }
- if (empty($fields)) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- 'no fields specified for table "'.$name.'"', __FUNCTION__);
- }
- $query_fields = $this->getFieldDeclarationList($fields);
- if (PEAR::isError($query_fields)) {
- return $query_fields;
- }
- if (!empty($options['primary'])) {
- $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')';
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = 'CREATE ';
- if (!empty($options['temporary'])) {
- $result .= $this->_getTemporaryTableQuery();
- }
- $result .= " TABLE $name ($query_fields)";
- return $result;
- }
-
- // }}}
- // {{{ _getTemporaryTableQuery()
-
- /**
- * A method to return the required SQL string that fits between CREATE ... TABLE
- * to create the table as a temporary table.
- *
- * Should be overridden in driver classes to return the correct string for the
- * specific database type.
- *
- * The default is to return the string "TEMPORARY" - this will result in a
- * SQL error for any database that does not support temporary tables, or that
- * requires a different SQL command from "CREATE TEMPORARY TABLE".
- *
- * @return string The string required to be placed between "CREATE" and "TABLE"
- * to generate a temporary table, if possible.
- */
- function _getTemporaryTableQuery()
- {
- return 'TEMPORARY';
- }
-
- // }}}
- // {{{ createTable()
-
- /**
- * create a new table
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * The indexes of the array entries are the names of the fields of the table an
- * the array entry values are associative arrays like those that are meant to be
- * passed with the field definitions to get[Type]Declaration() functions.
- * array(
- * 'id' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * 'notnull' => 1
- * 'default' => 0
- * ),
- * 'name' => array(
- * 'type' => 'text',
- * 'length' => 12
- * ),
- * 'password' => array(
- * 'type' => 'text',
- * 'length' => 12
- * )
- * );
- * @param array $options An associative array of table options:
- * array(
- * 'comment' => 'Foo',
- * 'temporary' => true|false,
- * );
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createTable($name, $fields, $options = array())
- {
- $query = $this->_getCreateTableQuery($name, $fields, $options);
- if (PEAR::isError($query)) {
- return $query;
- }
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $result = $db->exec($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropTable()
-
- /**
- * drop an existing table
- *
- * @param string $name name of the table that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropTable($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = $db->exec("DROP TABLE $name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ truncateTable()
-
- /**
- * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
- * it falls back to a DELETE FROM TABLE query)
- *
- * @param string $name name of the table that should be truncated
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function truncateTable($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = $db->exec("DELETE FROM $name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ vacuum()
-
- /**
- * Optimize (vacuum) all the tables in the db (or only the specified table)
- * and optionally run ANALYZE.
- *
- * @param string $table table name (all the tables if empty)
- * @param array $options an array with driver-specific options:
- * - timeout [int] (in seconds) [mssql-only]
- * - analyze [boolean] [pgsql and mysql]
- * - full [boolean] [pgsql-only]
- * - freeze [boolean] [pgsql-only]
- *
- * @return mixed MDB2_OK success, a MDB2 error on failure
- * @access public
- */
- function vacuum($table = null, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implementedd', __FUNCTION__);
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @param string database, the current is default
- * NB: not all the drivers can get the view names from
- * a database other than the current one
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews($database = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableViews()
-
- /**
- * list the views in the database that reference a given table
- *
- * @param string table for which all referenced views should be found
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listTableViews($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listFunctions()
-
- /**
- * list all functions in the current database
- *
- * @return mixed array of function names on success, a MDB2 error on failure
- * @access public
- */
- function listFunctions()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the current database
- *
- * @param string database, the current is default.
- * NB: not all the drivers can get the table names from
- * a database other than the current one
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables($database = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ createIndex()
-
- /**
- * Get the stucture of a field into an array
- *
- * @param string $table name of the table on which the index is to be created
- * @param string $name name of the index to be created
- * @param array $definition associative array that defines properties of the index to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the index fields as array
- * indexes. Each entry of this array is set to another type of associative
- * array that specifies properties of the index that are specific to
- * each field.
- *
- * Currently, only the sorting property is supported. It should be used
- * to define the sorting direction of the index. It may be set to either
- * ascending or descending.
- *
- * Not all DBMS support index sorting direction configuration. The DBMS
- * drivers of those that do not support it ignore this property. Use the
- * function supports() to determine whether the DBMS driver can manage indexes.
- *
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(
- * 'sorting' => 'ascending'
- * ),
- * 'last_login' => array()
- * )
- * )
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createIndex($table, $name, $definition)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "CREATE INDEX $name ON $table";
- $fields = array();
- foreach (array_keys($definition['fields']) as $field) {
- $fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $fields) . ')';
- $result = $db->exec($query);
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropIndex()
-
- /**
- * drop existing index
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the index to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropIndex($table, $name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $result = $db->exec("DROP INDEX $name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- return '';
- }
-
- // }}}
- // {{{ createConstraint()
-
- /**
- * create a constraint on a table
- *
- * @param string $table name of the table on which the constraint is to be created
- * @param string $name name of the constraint to be created
- * @param array $definition associative array that defines properties of the constraint to be created.
- * The full structure of the array looks like this:
- *
- * array (
- * [primary] => 0
- * [unique] => 0
- * [foreign] => 1
- * [check] => 0
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * [position] => 3
- * )
- * )
- * [references] => array(
- * [table] => name
- * [fields] => array(
- * [field1name] => array( //one entry per each referenced field
- * [position] => 1
- * )
- * )
- * )
- * [deferrable] => 0
- * [initiallydeferred] => 0
- * [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [match] => SIMPLE|PARTIAL|FULL
- * );
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createConstraint($table, $name, $definition)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "ALTER TABLE $table ADD CONSTRAINT $name";
- if (!empty($definition['primary'])) {
- $query.= ' PRIMARY KEY';
- } elseif (!empty($definition['unique'])) {
- $query.= ' UNIQUE';
- } elseif (!empty($definition['foreign'])) {
- $query.= ' FOREIGN KEY';
- }
- $fields = array();
- foreach (array_keys($definition['fields']) as $field) {
- $fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $fields) . ')';
- if (!empty($definition['foreign'])) {
- $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true);
- $referenced_fields = array();
- foreach (array_keys($definition['references']['fields']) as $field) {
- $referenced_fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $referenced_fields) . ')';
- $query .= $this->_getAdvancedFKOptions($definition);
- }
- $result = $db->exec($query);
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropConstraint()
-
- /**
- * drop existing constraint
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the constraint to be dropped
- * @param string $primary hint if the constraint is primary
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropConstraint($table, $name, $primary = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $result = $db->exec("ALTER TABLE $table DROP CONSTRAINT $name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @param string database, the current is default
- * NB: not all the drivers can get the sequence names from
- * a database other than the current one
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences($database = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
-}
-?>
diff --git a/3rdparty/MDB2/Driver/Manager/mysql.php b/3rdparty/MDB2/Driver/Manager/mysql.php
deleted file mode 100644
index c663c0c5d2..0000000000
--- a/3rdparty/MDB2/Driver/Manager/mysql.php
+++ /dev/null
@@ -1,1471 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-require_once 'MDB2/Driver/Manager/Common.php';
-
-/**
- * MDB2 MySQL driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Manager_mysql extends MDB2_Driver_Manager_Common
-{
-
- // }}}
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset, collation info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($name, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $query = 'CREATE DATABASE ' . $name;
- if (!empty($options['charset'])) {
- $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text');
- }
- if (!empty($options['collation'])) {
- $query .= ' COLLATE ' . $db->quote($options['collation'], 'text');
- }
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ alterDatabase()
-
- /**
- * alter an existing database
- *
- * @param string $name name of the database that is intended to be changed
- * @param array $options array with charset, collation info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function alterDatabase($name, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true);
- if (!empty($options['charset'])) {
- $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text');
- }
- if (!empty($options['collation'])) {
- $query .= ' COLLATE ' . $db->quote($options['collation'], 'text');
- }
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $query = "DROP DATABASE $name";
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- $query = '';
- if (!empty($definition['match'])) {
- $query .= ' MATCH '.$definition['match'];
- }
- if (!empty($definition['onupdate'])) {
- $query .= ' ON UPDATE '.$definition['onupdate'];
- }
- if (!empty($definition['ondelete'])) {
- $query .= ' ON DELETE '.$definition['ondelete'];
- }
- return $query;
- }
-
- // }}}
- // {{{ createTable()
-
- /**
- * create a new table
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * The indexes of the array entries are the names of the fields of the table an
- * the array entry values are associative arrays like those that are meant to be
- * passed with the field definitions to get[Type]Declaration() functions.
- * array(
- * 'id' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * 'notnull' => 1
- * 'default' => 0
- * ),
- * 'name' => array(
- * 'type' => 'text',
- * 'length' => 12
- * ),
- * 'password' => array(
- * 'type' => 'text',
- * 'length' => 12
- * )
- * );
- * @param array $options An associative array of table options:
- * array(
- * 'comment' => 'Foo',
- * 'charset' => 'utf8',
- * 'collate' => 'utf8_unicode_ci',
- * 'type' => 'innodb',
- * );
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createTable($name, $fields, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- // if we have an AUTO_INCREMENT column and a PK on more than one field,
- // we have to handle it differently...
- $autoincrement = null;
- if (empty($options['primary'])) {
- $pk_fields = array();
- foreach ($fields as $fieldname => $def) {
- if (!empty($def['primary'])) {
- $pk_fields[$fieldname] = true;
- }
- if (!empty($def['autoincrement'])) {
- $autoincrement = $fieldname;
- }
- }
- if ((null !== $autoincrement) && count($pk_fields) > 1) {
- $options['primary'] = $pk_fields;
- } else {
- // the PK constraint is on max one field => OK
- $autoincrement = null;
- }
- }
-
- $query = $this->_getCreateTableQuery($name, $fields, $options);
- if (PEAR::isError($query)) {
- return $query;
- }
-
- if (null !== $autoincrement) {
- // we have to remove the PK clause added by _getIntegerDeclaration()
- $query = str_replace('AUTO_INCREMENT PRIMARY KEY', 'AUTO_INCREMENT', $query);
- }
-
- $options_strings = array();
-
- if (!empty($options['comment'])) {
- $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text');
- }
-
- if (!empty($options['charset'])) {
- $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset'];
- if (!empty($options['collate'])) {
- $options_strings['charset'].= ' COLLATE '.$options['collate'];
- }
- }
-
- $type = false;
- if (!empty($options['type'])) {
- $type = $options['type'];
- } elseif ($db->options['default_table_type']) {
- $type = $db->options['default_table_type'];
- }
- if ($type) {
- $options_strings[] = "ENGINE = $type";
- }
-
- if (!empty($options_strings)) {
- $query .= ' '.implode(' ', $options_strings);
- }
- $result = $db->exec($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropTable()
-
- /**
- * drop an existing table
- *
- * @param string $name name of the table that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropTable($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- //delete the triggers associated to existing FK constraints
- $constraints = $this->listTableConstraints($name);
- if (!PEAR::isError($constraints) && !empty($constraints)) {
- $db->loadModule('Reverse', null, true);
- foreach ($constraints as $constraint) {
- $definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
- if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
- $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
-
- return parent::dropTable($name);
- }
-
- // }}}
- // {{{ truncateTable()
-
- /**
- * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
- * it falls back to a DELETE FROM TABLE query)
- *
- * @param string $name name of the table that should be truncated
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function truncateTable($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = $db->exec("TRUNCATE TABLE $name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ vacuum()
-
- /**
- * Optimize (vacuum) all the tables in the db (or only the specified table)
- * and optionally run ANALYZE.
- *
- * @param string $table table name (all the tables if empty)
- * @param array $options an array with driver-specific options:
- * - timeout [int] (in seconds) [mssql-only]
- * - analyze [boolean] [pgsql and mysql]
- * - full [boolean] [pgsql-only]
- * - freeze [boolean] [pgsql-only]
- *
- * @return mixed MDB2_OK success, a MDB2 error on failure
- * @access public
- */
- function vacuum($table = null, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (empty($table)) {
- $table = $this->listTables();
- if (PEAR::isError($table)) {
- return $table;
- }
- }
- if (is_array($table)) {
- foreach (array_keys($table) as $k) {
- $table[$k] = $db->quoteIdentifier($table[$k], true);
- }
- $table = implode(', ', $table);
- } else {
- $table = $db->quoteIdentifier($table, true);
- }
-
- $result = $db->exec('OPTIMIZE TABLE '.$table);
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!empty($options['analyze'])) {
- $result = $db->exec('ANALYZE TABLE '.$table);
- if (MDB2::isError($result)) {
- return $result;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- foreach ($changes as $change_name => $change) {
- switch ($change_name) {
- case 'add':
- case 'remove':
- case 'change':
- case 'rename':
- case 'name':
- break;
- default:
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'change type "'.$change_name.'" not yet supported', __FUNCTION__);
- }
- }
-
- if ($check) {
- return MDB2_OK;
- }
-
- $query = '';
- if (!empty($changes['name'])) {
- $change_name = $db->quoteIdentifier($changes['name'], true);
- $query .= 'RENAME TO ' . $change_name;
- }
-
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $field_name => $field) {
- if ($query) {
- $query.= ', ';
- }
- $query.= 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field);
- }
- }
-
- if (!empty($changes['remove']) && is_array($changes['remove'])) {
- foreach ($changes['remove'] as $field_name => $field) {
- if ($query) {
- $query.= ', ';
- }
- $field_name = $db->quoteIdentifier($field_name, true);
- $query.= 'DROP ' . $field_name;
- }
- }
-
- $rename = array();
- if (!empty($changes['rename']) && is_array($changes['rename'])) {
- foreach ($changes['rename'] as $field_name => $field) {
- $rename[$field['name']] = $field_name;
- }
- }
-
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $field_name => $field) {
- if ($query) {
- $query.= ', ';
- }
- if (isset($rename[$field_name])) {
- $old_field_name = $rename[$field_name];
- unset($rename[$field_name]);
- } else {
- $old_field_name = $field_name;
- }
- $old_field_name = $db->quoteIdentifier($old_field_name, true);
- $query.= "CHANGE $old_field_name " . $db->getDeclaration($field['definition']['type'], $field_name, $field['definition']);
- }
- }
-
- if (!empty($rename) && is_array($rename)) {
- foreach ($rename as $rename_name => $renamed_field) {
- if ($query) {
- $query.= ', ';
- }
- $field = $changes['rename'][$renamed_field];
- $renamed_field = $db->quoteIdentifier($renamed_field, true);
- $query.= 'CHANGE ' . $renamed_field . ' ' . $db->getDeclaration($field['definition']['type'], $field['name'], $field['definition']);
- }
- }
-
- if (!$query) {
- return MDB2_OK;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = $db->exec("ALTER TABLE $name $query");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->queryCol('SHOW DATABASES');
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->queryCol('SELECT DISTINCT USER FROM mysql.USER');
- }
-
- // }}}
- // {{{ listFunctions()
-
- /**
- * list all functions in the current database
- *
- * @return mixed array of function names on success, a MDB2 error on failure
- * @access public
- */
- function listFunctions()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name FROM mysql.proc";
- /*
- SELECT ROUTINE_NAME
- FROM INFORMATION_SCHEMA.ROUTINES
- WHERE ROUTINE_TYPE = 'FUNCTION'
- */
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SHOW TRIGGERS';
- if (null !== $table) {
- $table = $db->quote($table, 'text');
- $query .= " LIKE $table";
- }
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the current database
- *
- * @param string database, the current is default
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables($database = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SHOW /*!50002 FULL*/ TABLES";
- if (null !== $database) {
- $query .= " FROM $database";
- }
- $query.= "/*!50002 WHERE Table_type = 'BASE TABLE'*/";
-
- $table_names = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
-
- $result = array();
- foreach ($table_names as $table) {
- if (!$this->_fixSequenceName($table[0], true)) {
- $result[] = $table[0];
- }
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @param string database, the current is default
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews($database = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SHOW FULL TABLES';
- if (null !== $database) {
- $query.= " FROM $database";
- }
- $query.= " WHERE Table_type = 'VIEW'";
-
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $result = $db->queryCol("SHOW COLUMNS FROM $table");
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ createIndex()
-
- /**
- * Get the stucture of a field into an array
- *
- * @author Leoncx
- * @param string $table name of the table on which the index is to be created
- * @param string $name name of the index to be created
- * @param array $definition associative array that defines properties of the index to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the index fields as array
- * indexes. Each entry of this array is set to another type of associative
- * array that specifies properties of the index that are specific to
- * each field.
- *
- * Currently, only the sorting property is supported. It should be used
- * to define the sorting direction of the index. It may be set to either
- * ascending or descending.
- *
- * Not all DBMS support index sorting direction configuration. The DBMS
- * drivers of those that do not support it ignore this property. Use the
- * function supports() to determine whether the DBMS driver can manage indexes.
- *
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(
- * 'sorting' => 'ascending'
- * 'length' => 10
- * ),
- * 'last_login' => array()
- * )
- * )
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createIndex($table, $name, $definition)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "CREATE INDEX $name ON $table";
- $fields = array();
- foreach ($definition['fields'] as $field => $fieldinfo) {
- if (!empty($fieldinfo['length'])) {
- $fields[] = $db->quoteIdentifier($field, true) . '(' . $fieldinfo['length'] . ')';
- } else {
- $fields[] = $db->quoteIdentifier($field, true);
- }
- }
- $query .= ' ('. implode(', ', $fields) . ')';
- $result = $db->exec($query);
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropIndex()
-
- /**
- * drop existing index
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the index to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropIndex($table, $name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $result = $db->exec("DROP INDEX $name ON $table");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $key_name = 'Key_name';
- $non_unique = 'Non_unique';
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $key_name = strtolower($key_name);
- $non_unique = strtolower($non_unique);
- } else {
- $key_name = strtoupper($key_name);
- $non_unique = strtoupper($non_unique);
- }
- }
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW INDEX FROM $table";
- $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $index_data) {
- if ($index_data[$non_unique] && ($index = $this->_fixIndexName($index_data[$key_name]))) {
- $result[$index] = true;
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createConstraint()
-
- /**
- * create a constraint on a table
- *
- * @param string $table name of the table on which the constraint is to be created
- * @param string $name name of the constraint to be created
- * @param array $definition associative array that defines properties of the constraint to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the constraint fields as array
- * constraints. Each entry of this array is set to another type of associative
- * array that specifies properties of the constraint that are specific to
- * each field.
- *
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(),
- * 'last_login' => array()
- * )
- * )
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createConstraint($table, $name, $definition)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $type = '';
- $idx_name = $db->quoteIdentifier($db->getIndexName($name), true);
- if (!empty($definition['primary'])) {
- $type = 'PRIMARY';
- $idx_name = 'KEY';
- } elseif (!empty($definition['unique'])) {
- $type = 'UNIQUE';
- } elseif (!empty($definition['foreign'])) {
- $type = 'CONSTRAINT';
- }
- if (empty($type)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'invalid definition, could not create constraint', __FUNCTION__);
- }
-
- $table_quoted = $db->quoteIdentifier($table, true);
- $query = "ALTER TABLE $table_quoted ADD $type $idx_name";
- if (!empty($definition['foreign'])) {
- $query .= ' FOREIGN KEY';
- }
- $fields = array();
- foreach ($definition['fields'] as $field => $fieldinfo) {
- $quoted = $db->quoteIdentifier($field, true);
- if (!empty($fieldinfo['length'])) {
- $quoted .= '(' . $fieldinfo['length'] . ')';
- }
- $fields[] = $quoted;
- }
- $query .= ' ('. implode(', ', $fields) . ')';
- if (!empty($definition['foreign'])) {
- $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true);
- $referenced_fields = array();
- foreach (array_keys($definition['references']['fields']) as $field) {
- $referenced_fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $referenced_fields) . ')';
- $query .= $this->_getAdvancedFKOptions($definition);
-
- // add index on FK column(s) or we can't add a FK constraint
- // @see http://forums.mysql.com/read.php?22,19755,226009
- $result = $this->createIndex($table, $name.'_fkidx', $definition);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $res = $db->exec($query);
- if (PEAR::isError($res)) {
- return $res;
- }
- if (!empty($definition['foreign'])) {
- return $this->_createFKTriggers($table, array($name => $definition));
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropConstraint()
-
- /**
- * drop existing constraint
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the constraint to be dropped
- * @param string $primary hint if the constraint is primary
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropConstraint($table, $name, $primary = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($primary || strtolower($name) == 'primary') {
- $query = 'ALTER TABLE '. $db->quoteIdentifier($table, true) .' DROP PRIMARY KEY';
- $result = $db->exec($query);
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- //is it a FK constraint? If so, also delete the associated triggers
- $db->loadModule('Reverse', null, true);
- $definition = $db->reverse->getTableConstraintDefinition($table, $name);
- if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
- //first drop the FK enforcing triggers
- $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);
- if (PEAR::isError($result)) {
- return $result;
- }
- //then drop the constraint itself
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "ALTER TABLE $table DROP FOREIGN KEY $name";
- $result = $db->exec($query);
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "ALTER TABLE $table DROP INDEX $name";
- $result = $db->exec($query);
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _createFKTriggers()
-
- /**
- * Create triggers to enforce the FOREIGN KEY constraint on the table
- *
- * NB: since there's no RAISE_APPLICATION_ERROR facility in mysql,
- * we call a non-existent procedure to raise the FK violation message.
- * @see http://forums.mysql.com/read.php?99,55108,71877#msg-71877
- *
- * @param string $table table name
- * @param array $foreign_keys FOREIGN KEY definitions
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function _createFKTriggers($table, $foreign_keys)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- // create triggers to enforce FOREIGN KEY constraints
- if ($db->supports('triggers') && !empty($foreign_keys)) {
- $table_quoted = $db->quoteIdentifier($table, true);
- foreach ($foreign_keys as $fkname => $fkdef) {
- if (empty($fkdef)) {
- continue;
- }
- //set actions to default if not set
- $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);
- $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']);
-
- $trigger_names = array(
- 'insert' => $fkname.'_insert_trg',
- 'update' => $fkname.'_update_trg',
- 'pk_update' => $fkname.'_pk_update_trg',
- 'pk_delete' => $fkname.'_pk_delete_trg',
- );
- $table_fields = array_keys($fkdef['fields']);
- $referenced_fields = array_keys($fkdef['references']['fields']);
-
- //create the ON [UPDATE|DELETE] triggers on the primary table
- $restrict_action = ' IF (SELECT ';
- $aliased_fields = array();
- foreach ($table_fields as $field) {
- $aliased_fields[] = $table_quoted .'.'.$field .' AS '.$field;
- }
- $restrict_action .= implode(',', $aliased_fields)
- .' FROM '.$table_quoted
- .' WHERE ';
- $conditions = array();
- $new_values = array();
- $null_values = array();
- for ($i=0; $i OLD.'.$referenced_fields[$i];
- }
-
- $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL';
- $restrict_action2 = empty($conditions2) ? '' : ' AND (' .implode(' OR ', $conditions2) .')';
- $restrict_action3 = ' THEN CALL %s_ON_TABLE_'.$table.'_VIOLATES_FOREIGN_KEY_CONSTRAINT();'
- .' END IF;';
-
- $restrict_action_update = $restrict_action . $restrict_action2 . $restrict_action3;
- $restrict_action_delete = $restrict_action . $restrict_action3; // There is no NEW row in on DELETE trigger
-
- $cascade_action_update = 'UPDATE '.$table_quoted.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions). ';';
- $cascade_action_delete = 'DELETE FROM '.$table_quoted.' WHERE '.implode(' AND ', $conditions). ';';
- $setnull_action = 'UPDATE '.$table_quoted.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions). ';';
-
- if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) {
- $db->loadModule('Reverse', null, true);
- $default_values = array();
- foreach ($table_fields as $table_field) {
- $field_definition = $db->reverse->getTableFieldDefinition($table, $field);
- if (PEAR::isError($field_definition)) {
- return $field_definition;
- }
- $default_values[] = $table_field .' = '. $field_definition[0]['default'];
- }
- $setdefault_action = 'UPDATE '.$table_quoted.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions). ';';
- }
-
- $query = 'CREATE TRIGGER %s'
- .' %s ON '.$fkdef['references']['table']
- .' FOR EACH ROW BEGIN '
- .' SET FOREIGN_KEY_CHECKS = 0; '; //only really needed for ON UPDATE CASCADE
-
- if ('CASCADE' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $cascade_action_update;
- } elseif ('SET NULL' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action;
- } elseif ('SET DEFAULT' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action;
- } elseif ('NO ACTION' == $fkdef['onupdate']) {
- $sql_update = sprintf($query.$restrict_action_update, $trigger_names['pk_update'], 'AFTER UPDATE', 'update');
- } elseif ('RESTRICT' == $fkdef['onupdate']) {
- $sql_update = sprintf($query.$restrict_action_update, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update');
- }
- if ('CASCADE' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $cascade_action_delete;
- } elseif ('SET NULL' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action;
- } elseif ('SET DEFAULT' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action;
- } elseif ('NO ACTION' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query.$restrict_action_delete, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete');
- } elseif ('RESTRICT' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query.$restrict_action_delete, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete');
- }
- $sql_update .= ' SET FOREIGN_KEY_CHECKS = 1; END;';
- $sql_delete .= ' SET FOREIGN_KEY_CHECKS = 1; END;';
-
- $db->pushErrorHandling(PEAR_ERROR_RETURN);
- $db->expectError(MDB2_ERROR_CANNOT_CREATE);
- $result = $db->exec($sql_delete);
- $expected_errmsg = 'This MySQL version doesn\'t support multiple triggers with the same action time and event for one table';
- $db->popExpect();
- $db->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) {
- return $result;
- }
- $db->warnings[] = $expected_errmsg;
- }
- $db->pushErrorHandling(PEAR_ERROR_RETURN);
- $db->expectError(MDB2_ERROR_CANNOT_CREATE);
- $result = $db->exec($sql_update);
- $db->popExpect();
- $db->popErrorHandling();
- if (PEAR::isError($result) && $result->getCode() != MDB2_ERROR_CANNOT_CREATE) {
- if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) {
- return $result;
- }
- $db->warnings[] = $expected_errmsg;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _dropFKTriggers()
-
- /**
- * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
- *
- * @param string $table table name
- * @param string $fkname FOREIGN KEY constraint name
- * @param string $referenced_table referenced table name
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function _dropFKTriggers($table, $fkname, $referenced_table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $triggers = $this->listTableTriggers($table);
- $triggers2 = $this->listTableTriggers($referenced_table);
- if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) {
- $triggers = array_merge($triggers, $triggers2);
- $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';
- foreach ($triggers as $trigger) {
- if (preg_match($pattern, $trigger)) {
- $result = $db->exec('DROP TRIGGER '.$trigger);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $key_name = 'Key_name';
- $non_unique = 'Non_unique';
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $key_name = strtolower($key_name);
- $non_unique = strtolower($non_unique);
- } else {
- $key_name = strtoupper($key_name);
- $non_unique = strtoupper($non_unique);
- }
- }
-
- $query = 'SHOW INDEX FROM ' . $db->quoteIdentifier($table, true);
- $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $index_data) {
- if (!$index_data[$non_unique]) {
- if ($index_data[$key_name] !== 'PRIMARY') {
- $index = $this->_fixIndexName($index_data[$key_name]);
- } else {
- $index = 'PRIMARY';
- }
- if (!empty($index)) {
- $result[$index] = true;
- }
- }
- }
-
- //list FOREIGN KEY constraints...
- $query = 'SHOW CREATE TABLE '. $db->escape($table);
- $definition = $db->queryOne($query, 'text', 1);
- if (!PEAR::isError($definition) && !empty($definition)) {
- $pattern = '/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN KEY\b/Uims';
- if (preg_match_all($pattern, str_replace('`', '', $definition), $matches) > 0) {
- foreach ($matches[1] as $constraint) {
- $result[$constraint] = true;
- }
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @param array $options An associative array of table options:
- * array(
- * 'comment' => 'Foo',
- * 'charset' => 'utf8',
- * 'collate' => 'utf8_unicode_ci',
- * 'type' => 'innodb',
- * );
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true);
-
- $options_strings = array();
-
- if (!empty($options['comment'])) {
- $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text');
- }
-
- if (!empty($options['charset'])) {
- $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset'];
- if (!empty($options['collate'])) {
- $options_strings['charset'].= ' COLLATE '.$options['collate'];
- }
- }
-
- $type = false;
- if (!empty($options['type'])) {
- $type = $options['type'];
- } elseif ($db->options['default_table_type']) {
- $type = $db->options['default_table_type'];
- }
- if ($type) {
- $options_strings[] = "ENGINE = $type";
- }
-
- $query = "CREATE TABLE $sequence_name ($seqcol_name INT NOT NULL AUTO_INCREMENT, PRIMARY KEY ($seqcol_name))";
- if (!empty($options_strings)) {
- $query .= ' '.implode(' ', $options_strings);
- }
- $res = $db->exec($query);
- if (PEAR::isError($res)) {
- return $res;
- }
-
- if ($start == 1) {
- return MDB2_OK;
- }
-
- $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')';
- $res = $db->exec($query);
- if (!PEAR::isError($res)) {
- return MDB2_OK;
- }
-
- // Handle error
- $result = $db->exec("DROP TABLE $sequence_name");
- if (PEAR::isError($result)) {
- return $db->raiseError($result, null, null,
- 'could not drop inconsistent sequence table', __FUNCTION__);
- }
-
- return $db->raiseError($res, null, null,
- 'could not create sequence table', __FUNCTION__);
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($seq_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- $result = $db->exec("DROP TABLE $sequence_name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @param string database, the current is default
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences($database = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SHOW TABLES";
- if (null !== $database) {
- $query .= " FROM $database";
- }
- $table_names = $db->queryCol($query);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
-
- $result = array();
- foreach ($table_names as $table_name) {
- if ($sqn = $this->_fixSequenceName($table_name, true)) {
- $result[] = $sqn;
- }
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
-}
-?>
diff --git a/3rdparty/MDB2/Driver/Manager/oci8.php b/3rdparty/MDB2/Driver/Manager/oci8.php
deleted file mode 100644
index 90ae8eb230..0000000000
--- a/3rdparty/MDB2/Driver/Manager/oci8.php
+++ /dev/null
@@ -1,1340 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-
-// $Id: oci8.php 295587 2010-02-28 17:16:38Z quipo $
-
-require_once 'MDB2/Driver/Manager/Common.php';
-
-/**
- * MDB2 oci8 driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Manager_oci8 extends MDB2_Driver_Manager_Common
-{
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset, collation info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($name, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $username = $db->options['database_name_prefix'].$name;
- $password = $db->dsn['password'] ? $db->dsn['password'] : $name;
- $tablespace = $db->options['default_tablespace']
- ? ' DEFAULT TABLESPACE '.$db->options['default_tablespace'] : '';
-
- $query = 'CREATE USER '.$username.' IDENTIFIED BY '.$password.$tablespace;
- $result = $db->standaloneQuery($query, null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = 'GRANT CREATE SESSION, CREATE TABLE, UNLIMITED TABLESPACE, CREATE SEQUENCE, CREATE TRIGGER TO '.$username;
- $result = $db->standaloneQuery($query, null, true);
- if (PEAR::isError($result)) {
- $query = 'DROP USER '.$username.' CASCADE';
- $result2 = $db->standaloneQuery($query, null, true);
- if (PEAR::isError($result2)) {
- return $db->raiseError($result2, null, null,
- 'could not setup the database user', __FUNCTION__);
- }
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ alterDatabase()
-
- /**
- * alter an existing database
- *
- * IMPORTANT: the safe way to change the db charset is to do a full import/export!
- * If - and only if - the new character set is a strict superset of the current
- * character set, it is possible to use the ALTER DATABASE CHARACTER SET to
- * expedite the change in the database character set.
- *
- * @param string $name name of the database that is intended to be changed
- * @param array $options array with name, charset info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function alterDatabase($name, $options = array())
- {
- //disabled
- //return parent::alterDatabase($name, $options);
-
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($options['name'])) {
- $query = 'ALTER DATABASE ' . $db->quoteIdentifier($name, true)
- .' RENAME GLOBAL_NAME TO ' . $db->quoteIdentifier($options['name'], true);
- $result = $db->standaloneQuery($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!empty($options['charset'])) {
- $queries = array();
- $queries[] = 'SHUTDOWN IMMEDIATE'; //or NORMAL
- $queries[] = 'STARTUP MOUNT';
- $queries[] = 'ALTER SYSTEM ENABLE RESTRICTED SESSION';
- $queries[] = 'ALTER SYSTEM SET JOB_QUEUE_PROCESSES=0';
- $queries[] = 'ALTER DATABASE OPEN';
- $queries[] = 'ALTER DATABASE CHARACTER SET ' . $options['charset'];
- $queries[] = 'ALTER DATABASE NATIONAL CHARACTER SET ' . $options['charset'];
- $queries[] = 'SHUTDOWN IMMEDIATE'; //or NORMAL
- $queries[] = 'STARTUP';
-
- foreach ($queries as $query) {
- $result = $db->standaloneQuery($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param object $db database object that is extended by this class
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $username = $db->options['database_name_prefix'].$name;
- return $db->standaloneQuery('DROP USER '.$username.' CASCADE', null, true);
- }
-
-
- // }}}
- // {{{ _makeAutoincrement()
-
- /**
- * add an autoincrement sequence + trigger
- *
- * @param string $name name of the PK field
- * @param string $table name of the table
- * @param string $start start value for the sequence
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function _makeAutoincrement($name, $table, $start = 1)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table_uppercase = strtoupper($table);
- $index_name = $table_uppercase . '_AI_PK';
- $definition = array(
- 'primary' => true,
- 'fields' => array($name => true),
- );
- $idxname_format = $db->getOption('idxname_format');
- $db->setOption('idxname_format', '%s');
- $result = $this->createConstraint($table, $index_name, $definition);
- $db->setOption('idxname_format', $idxname_format);
- if (PEAR::isError($result)) {
- return $db->raiseError($result, null, null,
- 'primary key for autoincrement PK could not be created', __FUNCTION__);
- }
-
- if (null === $start) {
- $db->beginTransaction();
- $query = 'SELECT MAX(' . $db->quoteIdentifier($name, true) . ') FROM ' . $db->quoteIdentifier($table, true);
- $start = $this->db->queryOne($query, 'integer');
- if (PEAR::isError($start)) {
- return $start;
- }
- ++$start;
- $result = $this->createSequence($table, $start);
- $db->commit();
- } else {
- $result = $this->createSequence($table, $start);
- }
- if (PEAR::isError($result)) {
- return $db->raiseError($result, null, null,
- 'sequence for autoincrement PK could not be created', __FUNCTION__);
- }
- $seq_name = $db->getSequenceName($table);
- $trigger_name = $db->quoteIdentifier($table_uppercase . '_AI_PK', true);
- $seq_name_quoted = $db->quoteIdentifier($seq_name, true);
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($name, true);
- $trigger_sql = '
-CREATE TRIGGER '.$trigger_name.'
- BEFORE INSERT
- ON '.$table.'
- FOR EACH ROW
-DECLARE
- last_Sequence NUMBER;
- last_InsertID NUMBER;
-BEGIN
- SELECT '.$seq_name_quoted.'.NEXTVAL INTO :NEW.'.$name.' FROM DUAL;
- IF (:NEW.'.$name.' IS NULL OR :NEW.'.$name.' = 0) THEN
- SELECT '.$seq_name_quoted.'.NEXTVAL INTO :NEW.'.$name.' FROM DUAL;
- ELSE
- SELECT NVL(Last_Number, 0) INTO last_Sequence
- FROM User_Sequences
- WHERE UPPER(Sequence_Name) = UPPER(\''.$seq_name.'\');
- SELECT :NEW.'.$name.' INTO last_InsertID FROM DUAL;
- WHILE (last_InsertID > last_Sequence) LOOP
- SELECT '.$seq_name_quoted.'.NEXTVAL INTO last_Sequence FROM DUAL;
- END LOOP;
- END IF;
-END;
-';
- $result = $db->exec($trigger_sql);
- if (PEAR::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _dropAutoincrement()
-
- /**
- * drop an existing autoincrement sequence + trigger
- *
- * @param string $table name of the table
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function _dropAutoincrement($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = strtoupper($table);
- $trigger_name = $table . '_AI_PK';
- $trigger_name_quoted = $db->quote($trigger_name, 'text');
- $query = 'SELECT trigger_name FROM user_triggers';
- $query.= ' WHERE trigger_name='.$trigger_name_quoted.' OR trigger_name='.strtoupper($trigger_name_quoted);
- $trigger = $db->queryOne($query);
- if (PEAR::isError($trigger)) {
- return $trigger;
- }
-
- if ($trigger) {
- $trigger_name = $db->quoteIdentifier($table . '_AI_PK', true);
- $trigger_sql = 'DROP TRIGGER ' . $trigger_name;
- $result = $db->exec($trigger_sql);
- if (PEAR::isError($result)) {
- return $db->raiseError($result, null, null,
- 'trigger for autoincrement PK could not be dropped', __FUNCTION__);
- }
-
- $result = $this->dropSequence($table);
- if (PEAR::isError($result)) {
- return $db->raiseError($result, null, null,
- 'sequence for autoincrement PK could not be dropped', __FUNCTION__);
- }
-
- $index_name = $table . '_AI_PK';
- $idxname_format = $db->getOption('idxname_format');
- $db->setOption('idxname_format', '%s');
- $result1 = $this->dropConstraint($table, $index_name);
- $db->setOption('idxname_format', $idxname_format);
- $result2 = $this->dropConstraint($table, $index_name);
- if (PEAR::isError($result1) && PEAR::isError($result2)) {
- return $db->raiseError($result1, null, null,
- 'primary key for autoincrement PK could not be dropped', __FUNCTION__);
- }
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _getTemporaryTableQuery()
-
- /**
- * A method to return the required SQL string that fits between CREATE ... TABLE
- * to create the table as a temporary table.
- *
- * @return string The string required to be placed between "CREATE" and "TABLE"
- * to generate a temporary table, if possible.
- */
- function _getTemporaryTableQuery()
- {
- return 'GLOBAL TEMPORARY';
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- $query = '';
- if (!empty($definition['ondelete']) && (strtoupper($definition['ondelete']) != 'NO ACTION')) {
- $query .= ' ON DELETE '.$definition['ondelete'];
- }
- if (!empty($definition['deferrable'])) {
- $query .= ' DEFERRABLE';
- } else {
- $query .= ' NOT DEFERRABLE';
- }
- if (!empty($definition['initiallydeferred'])) {
- $query .= ' INITIALLY DEFERRED';
- } else {
- $query .= ' INITIALLY IMMEDIATE';
- }
- return $query;
- }
-
- // }}}
- // {{{ createTable()
-
- /**
- * create a new table
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * The indexes of the array entries are the names of the fields of the table an
- * the array entry values are associative arrays like those that are meant to be
- * passed with the field definitions to get[Type]Declaration() functions.
- *
- * Example
- * array(
- *
- * 'id' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * 'notnull' => 1
- * 'default' => 0
- * ),
- * 'name' => array(
- * 'type' => 'text',
- * 'length' => 12
- * ),
- * 'password' => array(
- * 'type' => 'text',
- * 'length' => 12
- * )
- * );
- * @param array $options An associative array of table options:
- * array(
- * 'comment' => 'Foo',
- * 'temporary' => true|false,
- * );
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createTable($name, $fields, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $db->beginNestedTransaction();
- $result = parent::createTable($name, $fields, $options);
- if (!PEAR::isError($result)) {
- foreach ($fields as $field_name => $field) {
- if (!empty($field['autoincrement'])) {
- $result = $this->_makeAutoincrement($field_name, $name);
- }
- }
- }
- $db->completeNestedTransaction();
- return $result;
- }
-
- // }}}
- // {{{ dropTable()
-
- /**
- * drop an existing table
- *
- * @param string $name name of the table that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropTable($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $db->beginNestedTransaction();
- $result = $this->_dropAutoincrement($name);
- if (!PEAR::isError($result)) {
- $result = parent::dropTable($name);
- }
- $db->completeNestedTransaction();
- return $result;
- }
-
- // }}}
- // {{{ truncateTable()
-
- /**
- * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
- * it falls back to a DELETE FROM TABLE query)
- *
- * @param string $name name of the table that should be truncated
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function truncateTable($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- return $db->exec("TRUNCATE TABLE $name");
- }
-
- // }}}
- // {{{ vacuum()
-
- /**
- * Optimize (vacuum) all the tables in the db (or only the specified table)
- * and optionally run ANALYZE.
- *
- * @param string $table table name (all the tables if empty)
- * @param array $options an array with driver-specific options:
- * - timeout [int] (in seconds) [mssql-only]
- * - analyze [boolean] [pgsql and mysql]
- * - full [boolean] [pgsql-only]
- * - freeze [boolean] [pgsql-only]
- *
- * @return mixed MDB2_OK success, a MDB2 error on failure
- * @access public
- */
- function vacuum($table = null, $options = array())
- {
- // not needed in Oracle
- return MDB2_OK;
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- foreach ($changes as $change_name => $change) {
- switch ($change_name) {
- case 'add':
- case 'remove':
- case 'change':
- case 'name':
- case 'rename':
- break;
- default:
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'change type "'.$change_name.'" not yet supported', __FUNCTION__);
- }
- }
-
- if ($check) {
- return MDB2_OK;
- }
-
- $name = $db->quoteIdentifier($name, true);
-
- if (!empty($changes['add']) && is_array($changes['add'])) {
- $fields = array();
- foreach ($changes['add'] as $field_name => $field) {
- $fields[] = $db->getDeclaration($field['type'], $field_name, $field);
- }
- $result = $db->exec("ALTER TABLE $name ADD (". implode(', ', $fields).')');
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!empty($changes['change']) && is_array($changes['change'])) {
- $fields = array();
- foreach ($changes['change'] as $field_name => $field) {
- //fix error "column to be modified to NOT NULL is already NOT NULL"
- if (!array_key_exists('notnull', $field)) {
- unset($field['definition']['notnull']);
- }
- $fields[] = $db->getDeclaration($field['definition']['type'], $field_name, $field['definition']);
- }
- $result = $db->exec("ALTER TABLE $name MODIFY (". implode(', ', $fields).')');
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!empty($changes['rename']) && is_array($changes['rename'])) {
- foreach ($changes['rename'] as $field_name => $field) {
- $field_name = $db->quoteIdentifier($field_name, true);
- $query = "ALTER TABLE $name RENAME COLUMN $field_name TO ".$db->quoteIdentifier($field['name']);
- $result = $db->exec($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($changes['remove']) && is_array($changes['remove'])) {
- $fields = array();
- foreach ($changes['remove'] as $field_name => $field) {
- $fields[] = $db->quoteIdentifier($field_name, true);
- }
- $result = $db->exec("ALTER TABLE $name DROP COLUMN ". implode(', ', $fields));
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!empty($changes['name'])) {
- $change_name = $db->quoteIdentifier($changes['name'], true);
- $result = $db->exec("ALTER TABLE $name RENAME TO ".$change_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _fetchCol()
-
- /**
- * Utility method to fetch and format a column from a resultset
- *
- * @param resource $result
- * @param boolean $fixname (used when listing indices or constraints)
- * @return mixed array of names on success, a MDB2 error on failure
- * @access private
- */
- function _fetchCol($result, $fixname = false)
- {
- if (PEAR::isError($result)) {
- return $result;
- }
- $col = $result->fetchCol();
- if (PEAR::isError($col)) {
- return $col;
- }
- $result->free();
-
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($fixname) {
- foreach ($col as $k => $v) {
- $col[$k] = $this->_fixIndexName($v);
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- && $db->options['field_case'] == CASE_LOWER
- ) {
- $col = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $col);
- }
- return $col;
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!$db->options['emulate_database']) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'database listing is only supported if the "emulate_database" option is enabled', __FUNCTION__);
- }
-
- if ($db->options['database_name_prefix']) {
- $query = 'SELECT SUBSTR(username, ';
- $query.= (strlen($db->options['database_name_prefix'])+1);
- $query.= ") FROM sys.dba_users WHERE username LIKE '";
- $query.= $db->options['database_name_prefix']."%'";
- } else {
- $query = 'SELECT username FROM sys.dba_users';
- }
- $result = $db->standaloneQuery($query, array('text'), false);
- return $this->_fetchCol($result);
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->options['emulate_database'] && $db->options['database_name_prefix']) {
- $query = 'SELECT SUBSTR(username, ';
- $query.= (strlen($db->options['database_name_prefix'])+1);
- $query.= ") FROM sys.dba_users WHERE username NOT LIKE '";
- $query.= $db->options['database_name_prefix']."%'";
- } else {
- $query = 'SELECT username FROM sys.dba_users';
- }
- return $db->queryCol($query);
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @param string owner, the current is default
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews($owner = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = 'SELECT view_name
- FROM sys.all_views
- WHERE owner=? OR owner=?';
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $result = $stmt->execute(array($owner, strtoupper($owner)));
- return $this->_fetchCol($result);
- }
-
- // }}}
- // {{{ listFunctions()
-
- /**
- * list all functions in the current database
- *
- * @param string owner, the current is default
- * @return mixed array of function names on success, a MDB2 error on failure
- * @access public
- */
- function listFunctions($owner = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = "SELECT name
- FROM sys.all_source
- WHERE line = 1
- AND type = 'FUNCTION'
- AND (owner=? OR owner=?)";
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $result = $stmt->execute(array($owner, strtoupper($owner)));
- return $this->_fetchCol($result);
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = "SELECT trigger_name
- FROM sys.all_triggers
- WHERE (table_name=? OR table_name=?)
- AND (owner=? OR owner=?)";
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $args = array(
- $table,
- strtoupper($table),
- $owner,
- strtoupper($owner),
- );
- $result = $stmt->execute($args);
- return $this->_fetchCol($result);
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the database
- *
- * @param string owner, the current is default
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables($owner = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = 'SELECT table_name
- FROM sys.all_tables
- WHERE owner=? OR owner=?';
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $result = $stmt->execute(array($owner, strtoupper($owner)));
- return $this->_fetchCol($result);
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($owner, $table) = $this->splitTableSchema($table);
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = 'SELECT column_name
- FROM all_tab_columns
- WHERE (table_name=? OR table_name=?)
- AND (owner=? OR owner=?)
- ORDER BY column_id';
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $args = array(
- $table,
- strtoupper($table),
- $owner,
- strtoupper($owner),
- );
- $result = $stmt->execute($args);
- return $this->_fetchCol($result);
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($owner, $table) = $this->splitTableSchema($table);
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = 'SELECT i.index_name name
- FROM all_indexes i
- LEFT JOIN all_constraints c
- ON c.index_name = i.index_name
- AND c.owner = i.owner
- AND c.table_name = i.table_name
- WHERE (i.table_name=? OR i.table_name=?)
- AND (i.owner=? OR i.owner=?)
- AND c.index_name IS NULL
- AND i.generated=' .$db->quote('N', 'text');
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $args = array(
- $table,
- strtoupper($table),
- $owner,
- strtoupper($owner),
- );
- $result = $stmt->execute($args);
- return $this->_fetchCol($result, true);
- }
-
- // }}}
- // {{{ createConstraint()
-
- /**
- * create a constraint on a table
- *
- * @param string $table name of the table on which the constraint is to be created
- * @param string $name name of the constraint to be created
- * @param array $definition associative array that defines properties of the constraint to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the constraint fields as array
- * constraints. Each entry of this array is set to another type of associative
- * array that specifies properties of the constraint that are specific to
- * each field.
- *
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(),
- * 'last_login' => array()
- * )
- * )
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createConstraint($table, $name, $definition)
- {
- $result = parent::createConstraint($table, $name, $definition);
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!empty($definition['foreign'])) {
- return $this->_createFKTriggers($table, array($name => $definition));
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropConstraint()
-
- /**
- * drop existing constraint
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the constraint to be dropped
- * @param string $primary hint if the constraint is primary
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropConstraint($table, $name, $primary = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- //is it a FK constraint? If so, also delete the associated triggers
- $db->loadModule('Reverse', null, true);
- $definition = $db->reverse->getTableConstraintDefinition($table, $name);
- if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
- //first drop the FK enforcing triggers
- $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return parent::dropConstraint($table, $name, $primary);
- }
-
- // }}}
- // {{{ _createFKTriggers()
-
- /**
- * Create triggers to enforce the FOREIGN KEY constraint on the table
- *
- * @param string $table table name
- * @param array $foreign_keys FOREIGN KEY definitions
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function _createFKTriggers($table, $foreign_keys)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- // create triggers to enforce FOREIGN KEY constraints
- if ($db->supports('triggers') && !empty($foreign_keys)) {
- $table = $db->quoteIdentifier($table, true);
- foreach ($foreign_keys as $fkname => $fkdef) {
- if (empty($fkdef)) {
- continue;
- }
- $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);
- if ('RESTRICT' == $fkdef['onupdate'] || 'NO ACTION' == $fkdef['onupdate']) {
- // already handled by default
- continue;
- }
-
- $trigger_name = substr(strtolower($fkname.'_pk_upd_trg'), 0, $db->options['max_identifiers_length']);
- $table_fields = array_keys($fkdef['fields']);
- $referenced_fields = array_keys($fkdef['references']['fields']);
-
- //create the ON UPDATE trigger on the primary table
- $restrict_action = ' IF (SELECT ';
- $aliased_fields = array();
- foreach ($table_fields as $field) {
- $aliased_fields[] = $table .'.'.$field .' AS '.$field;
- }
- $restrict_action .= implode(',', $aliased_fields)
- .' FROM '.$table
- .' WHERE ';
- $conditions = array();
- $new_values = array();
- $null_values = array();
- for ($i=0; $iloadModule('Reverse', null, true);
- $default_values = array();
- foreach ($table_fields as $table_field) {
- $field_definition = $db->reverse->getTableFieldDefinition($table, $field);
- if (PEAR::isError($field_definition)) {
- return $field_definition;
- }
- $default_values[] = $table_field .' = '. $field_definition[0]['default'];
- }
- $setdefault_action = 'UPDATE '.$table.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions). ';';
- }
-
- $query = 'CREATE TRIGGER %s'
- .' %s ON '.$fkdef['references']['table']
- .' FOR EACH ROW '
- .' BEGIN ';
-
- if ('CASCADE' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_name, 'BEFORE UPDATE', 'update') . $cascade_action;
- } elseif ('SET NULL' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_name, 'BEFORE UPDATE', 'update') . $setnull_action;
- } elseif ('SET DEFAULT' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_name, 'BEFORE UPDATE', 'update') . $setdefault_action;
- }
- $sql_update .= ' END;';
- $result = $db->exec($sql_update);
- if (PEAR::isError($result)) {
- if ($result->getCode() === MDB2_ERROR_ALREADY_EXISTS) {
- return MDB2_OK;
- }
- return $result;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _dropFKTriggers()
-
- /**
- * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
- *
- * @param string $table table name
- * @param string $fkname FOREIGN KEY constraint name
- * @param string $referenced_table referenced table name
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function _dropFKTriggers($table, $fkname, $referenced_table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $triggers = $this->listTableTriggers($table);
- $triggers2 = $this->listTableTriggers($referenced_table);
- if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) {
- $triggers = array_merge($triggers, $triggers2);
- $trigger_name = substr(strtolower($fkname.'_pk_upd_trg'), 0, $db->options['max_identifiers_length']);
- $pattern = '/^'.$trigger_name.'$/i';
- foreach ($triggers as $trigger) {
- if (preg_match($pattern, $trigger)) {
- $result = $db->exec('DROP TRIGGER '.$trigger);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($owner, $table) = $this->splitTableSchema($table);
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = 'SELECT constraint_name
- FROM all_constraints
- WHERE (table_name=? OR table_name=?)
- AND (owner=? OR owner=?)';
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $args = array(
- $table,
- strtoupper($table),
- $owner,
- strtoupper($owner),
- );
- $result = $stmt->execute($args);
- return $this->_fetchCol($result, true);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param object $db database object that is extended by this class
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- $query = "CREATE SEQUENCE $sequence_name START WITH $start INCREMENT BY 1 NOCACHE";
- $query.= ($start < 1 ? " MINVALUE $start" : '');
- return $db->exec($query);
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param object $db database object that is extended by this class
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($seq_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- return $db->exec("DROP SEQUENCE $sequence_name");
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @param string owner, the current is default
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences($owner = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = 'SELECT sequence_name
- FROM sys.all_sequences
- WHERE (sequence_owner=? OR sequence_owner=?)';
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $result = $stmt->execute(array($owner, strtoupper($owner)));
- if (PEAR::isError($result)) {
- return $result;
- }
- $col = $result->fetchCol();
- if (PEAR::isError($col)) {
- return $col;
- }
- $result->free();
-
- foreach ($col as $k => $v) {
- $col[$k] = $this->_fixSequenceName($v);
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- && $db->options['field_case'] == CASE_LOWER
- ) {
- $col = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $col);
- }
- return $col;
- }
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Manager/pgsql.php b/3rdparty/MDB2/Driver/Manager/pgsql.php
deleted file mode 100644
index 3e70f3a3b2..0000000000
--- a/3rdparty/MDB2/Driver/Manager/pgsql.php
+++ /dev/null
@@ -1,990 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-
-require_once 'MDB2/Driver/Manager/Common.php';
-
-/**
- * MDB2 MySQL driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_Driver_Manager_pgsql extends MDB2_Driver_Manager_Common
-{
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($name, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $query = 'CREATE DATABASE ' . $name;
- if (!empty($options['charset'])) {
- $query .= ' WITH ENCODING ' . $db->quote($options['charset'], 'text');
- }
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ alterDatabase()
-
- /**
- * alter an existing database
- *
- * @param string $name name of the database that is intended to be changed
- * @param array $options array with name, owner info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function alterDatabase($name, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = '';
- if (!empty($options['name'])) {
- $query .= ' RENAME TO ' . $options['name'];
- }
- if (!empty($options['owner'])) {
- $query .= ' OWNER TO ' . $options['owner'];
- }
-
- if (empty($query)) {
- return MDB2_OK;
- }
-
- $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true) . $query;
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $query = "DROP DATABASE $name";
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- $query = '';
- if (!empty($definition['match'])) {
- $query .= ' MATCH '.$definition['match'];
- }
- if (!empty($definition['onupdate'])) {
- $query .= ' ON UPDATE '.$definition['onupdate'];
- }
- if (!empty($definition['ondelete'])) {
- $query .= ' ON DELETE '.$definition['ondelete'];
- }
- if (!empty($definition['deferrable'])) {
- $query .= ' DEFERRABLE';
- } else {
- $query .= ' NOT DEFERRABLE';
- }
- if (!empty($definition['initiallydeferred'])) {
- $query .= ' INITIALLY DEFERRED';
- } else {
- $query .= ' INITIALLY IMMEDIATE';
- }
- return $query;
- }
-
- // }}}
- // {{{ truncateTable()
-
- /**
- * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
- * it falls back to a DELETE FROM TABLE query)
- *
- * @param string $name name of the table that should be truncated
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function truncateTable($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = $db->exec("TRUNCATE TABLE $name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ vacuum()
-
- /**
- * Optimize (vacuum) all the tables in the db (or only the specified table)
- * and optionally run ANALYZE.
- *
- * @param string $table table name (all the tables if empty)
- * @param array $options an array with driver-specific options:
- * - timeout [int] (in seconds) [mssql-only]
- * - analyze [boolean] [pgsql and mysql]
- * - full [boolean] [pgsql-only]
- * - freeze [boolean] [pgsql-only]
- *
- * @return mixed MDB2_OK success, a MDB2 error on failure
- * @access public
- */
- function vacuum($table = null, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $query = 'VACUUM';
-
- if (!empty($options['full'])) {
- $query .= ' FULL';
- }
- if (!empty($options['freeze'])) {
- $query .= ' FREEZE';
- }
- if (!empty($options['analyze'])) {
- $query .= ' ANALYZE';
- }
-
- if (!empty($table)) {
- $query .= ' '.$db->quoteIdentifier($table, true);
- }
- $result = $db->exec($query);
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- foreach ($changes as $change_name => $change) {
- switch ($change_name) {
- case 'add':
- case 'remove':
- case 'change':
- case 'name':
- case 'rename':
- break;
- default:
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'change type "'.$change_name.'\" not yet supported', __FUNCTION__);
- }
- }
-
- if ($check) {
- return MDB2_OK;
- }
-
- $unquoted_name = $name;
- $name = $db->quoteIdentifier($name, true);
-
- if (!empty($changes['remove']) && is_array($changes['remove'])) {
- foreach ($changes['remove'] as $field_name => $field) {
- $field_name = $db->quoteIdentifier($field_name, true);
- $query = 'DROP ' . $field_name;
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($changes['rename']) && is_array($changes['rename'])) {
- foreach ($changes['rename'] as $field_name => $field) {
- $field_name = $db->quoteIdentifier($field_name, true);
- $result = $db->exec("ALTER TABLE $name RENAME COLUMN $field_name TO ".$db->quoteIdentifier($field['name'], true));
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $field_name => $field) {
- $query = 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field);
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $field_name => $field) {
- $unquoted_field_name = $field_name;
- $field_name = $db->quoteIdentifier($field_name, true);
- if (!empty($field['definition']['type'])) {
- $server_info = $db->getServerVersion();
- if (PEAR::isError($server_info)) {
- return $server_info;
- }
- if (is_array($server_info) && $server_info['major'] < 8) {
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'changing column type for "'.$change_name.'\" requires PostgreSQL 8.0 or above', __FUNCTION__);
- }
- $db->loadModule('Datatype', null, true);
- $type = $db->datatype->getTypeDeclaration($field['definition']);
- if($type=='SERIAL PRIMARY KEY'){//not correct when altering a table, since serials arent a real type
- $type='INTEGER';//use integer instead
- }
- $query = "ALTER $field_name TYPE $type USING CAST($field_name AS $type)";
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- if (array_key_exists('autoincrement', $field['definition'])) {
- $query = "ALTER $field_name SET DEFAULT nextval(".$db->quote($unquoted_name.'_'.$unquoted_field_name.'_seq', 'text').")";
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- elseif (array_key_exists('default', $field['definition'])) {
- $query = "ALTER $field_name SET DEFAULT ".$db->quote($field['definition']['default'], $field['definition']['type']);
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- if (array_key_exists('notnull', $field['definition'])) {
- $query = "ALTER $field_name ".($field['definition']['notnull'] ? 'SET' : 'DROP').' NOT NULL';
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
-
- if (!empty($changes['name'])) {
- $change_name = $db->quoteIdentifier($changes['name'], true);
- $result = $db->exec("ALTER TABLE $name RENAME TO ".$change_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT datname FROM pg_database';
- $result2 = $db->standaloneQuery($query, array('text'), false);
- if (!MDB2::isResultCommon($result2)) {
- return $result2;
- }
-
- $result = $result2->fetchCol();
- $result2->free();
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT usename FROM pg_user';
- $result2 = $db->standaloneQuery($query, array('text'), false);
- if (!MDB2::isResultCommon($result2)) {
- return $result2;
- }
-
- $result = $result2->fetchCol();
- $result2->free();
- return $result;
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews($database = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT viewname
- FROM pg_views
- WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
- AND viewname !~ '^pg_'";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableViews()
-
- /**
- * list the views in the database that reference a given table
- *
- * @param string table for which all referenced views should be found
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listTableViews($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT viewname FROM pg_views NATURAL JOIN pg_tables';
- $query.= ' WHERE tablename ='.$db->quote($table, 'text');
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listFunctions()
-
- /**
- * list all functions in the current database
- *
- * @return mixed array of function names on success, a MDB2 error on failure
- * @access public
- */
- function listFunctions()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "
- SELECT
- proname
- FROM
- pg_proc pr,
- pg_type tp
- WHERE
- tp.oid = pr.prorettype
- AND pr.proisagg = FALSE
- AND tp.typname <> 'trigger'
- AND pr.pronamespace IN
- (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT trg.tgname AS trigger_name
- FROM pg_trigger trg,
- pg_class tbl
- WHERE trg.tgrelid = tbl.oid';
- if (null !== $table) {
- $table = $db->quote(strtoupper($table), 'text');
- $query .= " AND UPPER(tbl.relname) = $table";
- }
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the current database
- *
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables($database = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- // gratuitously stolen from PEAR DB _getSpecialQuery in pgsql.php
- $query = 'SELECT c.relname AS "Name"'
- . ' FROM pg_class c, pg_user u'
- . ' WHERE c.relowner = u.usesysid'
- . " AND c.relkind = 'r'"
- . ' AND NOT EXISTS'
- . ' (SELECT 1 FROM pg_views'
- . ' WHERE viewname = c.relname)'
- . " AND c.relname !~ '^(pg_|sql_)'"
- . ' UNION'
- . ' SELECT c.relname AS "Name"'
- . ' FROM pg_class c'
- . " WHERE c.relkind = 'r'"
- . ' AND NOT EXISTS'
- . ' (SELECT 1 FROM pg_views'
- . ' WHERE viewname = c.relname)'
- . ' AND NOT EXISTS'
- . ' (SELECT 1 FROM pg_user'
- . ' WHERE usesysid = c.relowner)'
- . " AND c.relname !~ '^pg_'";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table);
-
- $table = $db->quoteIdentifier($table, true);
- if (!empty($schema)) {
- $table = $db->quoteIdentifier($schema, true) . '.' .$table;
- }
- $db->setLimit(1);
- $result2 = $db->query("SELECT * FROM $table");
- if (PEAR::isError($result2)) {
- return $result2;
- }
- $result = $result2->getColumnNames();
- $result2->free();
- if (PEAR::isError($result)) {
- return $result;
- }
- return array_flip($result);
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table);
-
- $table = $db->quote($table, 'text');
- $subquery = "SELECT indexrelid
- FROM pg_index
- LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid
- LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
- WHERE pg_class.relname = $table
- AND indisunique != 't'
- AND indisprimary != 't'";
- if (!empty($schema)) {
- $subquery .= ' AND pg_namespace.nspname = '.$db->quote($schema, 'text');
- }
- $query = "SELECT relname FROM pg_class WHERE oid IN ($subquery)";
- $indexes = $db->queryCol($query, 'text');
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $index) {
- $index = $this->_fixIndexName($index);
- if (!empty($index)) {
- $result[$index] = true;
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ dropConstraint()
-
- /**
- * drop existing constraint
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the constraint to be dropped
- * @param string $primary hint if the constraint is primary
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropConstraint($table, $name, $primary = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- // is it an UNIQUE index?
- $query = 'SELECT relname
- FROM pg_class
- WHERE oid IN (
- SELECT indexrelid
- FROM pg_index, pg_class
- WHERE pg_class.relname = '.$db->quote($table, 'text').'
- AND pg_class.oid = pg_index.indrelid
- AND indisunique = \'t\')
- EXCEPT
- SELECT conname
- FROM pg_constraint, pg_class
- WHERE pg_constraint.conrelid = pg_class.oid
- AND relname = '. $db->quote($table, 'text');
- $unique = $db->queryCol($query, 'text');
- if (PEAR::isError($unique) || empty($unique)) {
- // not an UNIQUE index, maybe a CONSTRAINT
- return parent::dropConstraint($table, $name, $primary);
- }
-
- if (in_array($name, $unique)) {
- $result = $db->exec('DROP INDEX '.$db->quoteIdentifier($name, true));
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
- $idxname = $db->getIndexName($name);
- if (in_array($idxname, $unique)) {
- $result = $db->exec('DROP INDEX '.$db->quoteIdentifier($idxname, true));
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $name . ' is not an existing constraint for table ' . $table, __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table);
-
- $table = $db->quote($table, 'text');
- $query = 'SELECT conname
- FROM pg_constraint
- LEFT JOIN pg_class ON pg_constraint.conrelid = pg_class.oid
- LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
- WHERE relname = ' .$table;
- if (!empty($schema)) {
- $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text');
- }
- $query .= '
- UNION DISTINCT
- SELECT relname
- FROM pg_class
- WHERE oid IN (
- SELECT indexrelid
- FROM pg_index
- LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid
- LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
- WHERE pg_class.relname = '.$table.'
- AND indisunique = \'t\'';
- if (!empty($schema)) {
- $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text');
- }
- $query .= ')';
- $constraints = $db->queryCol($query);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- $result = array();
- foreach ($constraints as $constraint) {
- $constraint = $this->_fixIndexName($constraint);
- if (!empty($constraint)) {
- $result[$constraint] = true;
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- && $db->options['field_case'] == CASE_LOWER
- ) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- $result = $db->exec("CREATE SEQUENCE $sequence_name INCREMENT 1".
- ($start < 1 ? " MINVALUE $start" : '')." START $start");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($seq_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- $result = $db->exec("DROP SEQUENCE $sequence_name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences($database = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT relname FROM pg_class WHERE relkind = 'S' AND relnamespace IN";
- $query.= "(SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')";
- $table_names = $db->queryCol($query);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
- $result = array();
- foreach ($table_names as $table_name) {
- $result[] = $this->_fixSequenceName($table_name);
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-}
-?>
diff --git a/3rdparty/MDB2/Driver/Manager/sqlite.php b/3rdparty/MDB2/Driver/Manager/sqlite.php
deleted file mode 100644
index 1e7efe3e74..0000000000
--- a/3rdparty/MDB2/Driver/Manager/sqlite.php
+++ /dev/null
@@ -1,1390 +0,0 @@
- |
-// | Lorenzo Alberton |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-require_once 'MDB2/Driver/Manager/Common.php';
-
-/**
- * MDB2 SQLite driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- * @author Lorenzo Alberton
- */
-class MDB2_Driver_Manager_sqlite extends MDB2_Driver_Manager_Common
-{
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($name, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $database_file = $db->_getDatabaseFile($name);
- if (file_exists($database_file)) {
- return $db->raiseError(MDB2_ERROR_ALREADY_EXISTS, null, null,
- 'database already exists', __FUNCTION__);
- }
- $php_errormsg = '';
- $handle = @sqlite_open($database_file, $db->dsn['mode'], $php_errormsg);
- if (!$handle) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- (isset($php_errormsg) ? $php_errormsg : 'could not create the database file'), __FUNCTION__);
- }
- if (!empty($options['charset'])) {
- $query = 'PRAGMA encoding = ' . $db->quote($options['charset'], 'text');
- @sqlite_query($query, $handle);
- }
- @sqlite_close($handle);
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $database_file = $db->_getDatabaseFile($name);
- if (!@file_exists($database_file)) {
- return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null,
- 'database does not exist', __FUNCTION__);
- }
- $result = @unlink($database_file);
- if (!$result) {
- return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null,
- (isset($php_errormsg) ? $php_errormsg : 'could not remove the database file'), __FUNCTION__);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- $query = '';
- if (!empty($definition['match'])) {
- $query .= ' MATCH '.$definition['match'];
- }
- if (!empty($definition['onupdate']) && (strtoupper($definition['onupdate']) != 'NO ACTION')) {
- $query .= ' ON UPDATE '.$definition['onupdate'];
- }
- if (!empty($definition['ondelete']) && (strtoupper($definition['ondelete']) != 'NO ACTION')) {
- $query .= ' ON DELETE '.$definition['ondelete'];
- }
- if (!empty($definition['deferrable'])) {
- $query .= ' DEFERRABLE';
- } else {
- $query .= ' NOT DEFERRABLE';
- }
- if (!empty($definition['initiallydeferred'])) {
- $query .= ' INITIALLY DEFERRED';
- } else {
- $query .= ' INITIALLY IMMEDIATE';
- }
- return $query;
- }
-
- // }}}
- // {{{ _getCreateTableQuery()
-
- /**
- * Create a basic SQL query for a new table creation
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * @param array $options An associative array of table options
- * @return mixed string (the SQL query) on success, a MDB2 error on failure
- * @see createTable()
- */
- function _getCreateTableQuery($name, $fields, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!$name) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- 'no valid table name specified', __FUNCTION__);
- }
- if (empty($fields)) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- 'no fields specified for table "'.$name.'"', __FUNCTION__);
- }
- $query_fields = $this->getFieldDeclarationList($fields);
- if (PEAR::isError($query_fields)) {
- return $query_fields;
- }
- if (!empty($options['primary'])) {
- $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')';
- }
- if (!empty($options['foreign_keys'])) {
- foreach ($options['foreign_keys'] as $fkname => $fkdef) {
- if (empty($fkdef)) {
- continue;
- }
- $query_fields.= ', CONSTRAINT '.$fkname.' FOREIGN KEY ('.implode(', ', array_keys($fkdef['fields'])).')';
- $query_fields.= ' REFERENCES '.$fkdef['references']['table'].' ('.implode(', ', array_keys($fkdef['references']['fields'])).')';
- $query_fields.= $this->_getAdvancedFKOptions($fkdef);
- }
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = 'CREATE ';
- if (!empty($options['temporary'])) {
- $result .= $this->_getTemporaryTableQuery();
- }
- $result .= " TABLE $name ($query_fields)";
- return $result;
- }
-
- // }}}
- // {{{ createTable()
-
- /**
- * create a new table
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition
- * of each field of the new table
- * @param array $options An associative array of table options
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createTable($name, $fields, $options = array())
- {
- $result = parent::createTable($name, $fields, $options);
- if (PEAR::isError($result)) {
- return $result;
- }
- // create triggers to enforce FOREIGN KEY constraints
- if (!empty($options['foreign_keys'])) {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- foreach ($options['foreign_keys'] as $fkname => $fkdef) {
- if (empty($fkdef)) {
- continue;
- }
- //set actions to default if not set
- $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);
- $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']);
-
- $trigger_names = array(
- 'insert' => $fkname.'_insert_trg',
- 'update' => $fkname.'_update_trg',
- 'pk_update' => $fkname.'_pk_update_trg',
- 'pk_delete' => $fkname.'_pk_delete_trg',
- );
-
- //create the [insert|update] triggers on the FK table
- $table_fields = array_keys($fkdef['fields']);
- $referenced_fields = array_keys($fkdef['references']['fields']);
- $query = 'CREATE TRIGGER %s BEFORE %s ON '.$name
- .' FOR EACH ROW BEGIN'
- .' SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
- .' WHERE (SELECT ';
- $aliased_fields = array();
- foreach ($referenced_fields as $field) {
- $aliased_fields[] = $fkdef['references']['table'] .'.'.$field .' AS '.$field;
- }
- $query .= implode(',', $aliased_fields)
- .' FROM '.$fkdef['references']['table']
- .' WHERE ';
- $conditions = array();
- for ($i=0; $iexec(sprintf($query, $trigger_names['insert'], 'INSERT', 'insert'));
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $result = $db->exec(sprintf($query, $trigger_names['update'], 'UPDATE', 'update'));
- if (PEAR::isError($result)) {
- return $result;
- }
-
- //create the ON [UPDATE|DELETE] triggers on the primary table
- $restrict_action = 'SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
- .' WHERE (SELECT ';
- $aliased_fields = array();
- foreach ($table_fields as $field) {
- $aliased_fields[] = $name .'.'.$field .' AS '.$field;
- }
- $restrict_action .= implode(',', $aliased_fields)
- .' FROM '.$name
- .' WHERE ';
- $conditions = array();
- $new_values = array();
- $null_values = array();
- for ($i=0; $i OLD.'.$referenced_fields[$i];
- }
- $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL'
- .' AND (' .implode(' OR ', $conditions2) .')';
-
- $cascade_action_update = 'UPDATE '.$name.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions);
- $cascade_action_delete = 'DELETE FROM '.$name.' WHERE '.implode(' AND ', $conditions);
- $setnull_action = 'UPDATE '.$name.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions);
-
- if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) {
- $db->loadModule('Reverse', null, true);
- $default_values = array();
- foreach ($table_fields as $table_field) {
- $field_definition = $db->reverse->getTableFieldDefinition($name, $field);
- if (PEAR::isError($field_definition)) {
- return $field_definition;
- }
- $default_values[] = $table_field .' = '. $field_definition[0]['default'];
- }
- $setdefault_action = 'UPDATE '.$name.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions);
- }
-
- $query = 'CREATE TRIGGER %s'
- .' %s ON '.$fkdef['references']['table']
- .' FOR EACH ROW BEGIN ';
-
- if ('CASCADE' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . $cascade_action_update. '; END;';
- } elseif ('SET NULL' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action. '; END;';
- } elseif ('SET DEFAULT' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action. '; END;';
- } elseif ('NO ACTION' == $fkdef['onupdate']) {
- $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . '; END;';
- } elseif ('RESTRICT' == $fkdef['onupdate']) {
- $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . '; END;';
- }
- if ('CASCADE' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete') . $cascade_action_delete. '; END;';
- } elseif ('SET NULL' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action. '; END;';
- } elseif ('SET DEFAULT' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action. '; END;';
- } elseif ('NO ACTION' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete') . '; END;';
- } elseif ('RESTRICT' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . '; END;';
- }
-
- if (PEAR::isError($result)) {
- return $result;
- }
- $result = $db->exec($sql_delete);
- if (PEAR::isError($result)) {
- return $result;
- }
- $result = $db->exec($sql_update);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- if (PEAR::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropTable()
-
- /**
- * drop an existing table
- *
- * @param string $name name of the table that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropTable($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- //delete the triggers associated to existing FK constraints
- $constraints = $this->listTableConstraints($name);
- if (!PEAR::isError($constraints) && !empty($constraints)) {
- $db->loadModule('Reverse', null, true);
- foreach ($constraints as $constraint) {
- $definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
- if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
- $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = $db->exec("DROP TABLE $name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ vacuum()
-
- /**
- * Optimize (vacuum) all the tables in the db (or only the specified table)
- * and optionally run ANALYZE.
- *
- * @param string $table table name (all the tables if empty)
- * @param array $options an array with driver-specific options:
- * - timeout [int] (in seconds) [mssql-only]
- * - analyze [boolean] [pgsql and mysql]
- * - full [boolean] [pgsql-only]
- * - freeze [boolean] [pgsql-only]
- *
- * @return mixed MDB2_OK success, a MDB2 error on failure
- * @access public
- */
- function vacuum($table = null, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'VACUUM';
- if (!empty($table)) {
- $query .= ' '.$db->quoteIdentifier($table, true);
- }
- $result = $db->exec($query);
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check, $options = array())
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- foreach ($changes as $change_name => $change) {
- switch ($change_name) {
- case 'add':
- case 'remove':
- case 'change':
- case 'name':
- case 'rename':
- break;
- default:
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'change type "'.$change_name.'" not yet supported', __FUNCTION__);
- }
- }
-
- if ($check) {
- return MDB2_OK;
- }
-
- $db->loadModule('Reverse', null, true);
-
- // actually sqlite 2.x supports no ALTER TABLE at all .. so we emulate it
- $fields = $db->manager->listTableFields($name);
- if (PEAR::isError($fields)) {
- return $fields;
- }
-
- $fields = array_flip($fields);
- foreach ($fields as $field => $value) {
- $definition = $db->reverse->getTableFieldDefinition($name, $field);
- if (PEAR::isError($definition)) {
- return $definition;
- }
- $fields[$field] = $definition[0];
- }
-
- $indexes = $db->manager->listTableIndexes($name);
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $indexes = array_flip($indexes);
- foreach ($indexes as $index => $value) {
- $definition = $db->reverse->getTableIndexDefinition($name, $index);
- if (PEAR::isError($definition)) {
- return $definition;
- }
- $indexes[$index] = $definition;
- }
-
- $constraints = $db->manager->listTableConstraints($name);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- if (!array_key_exists('foreign_keys', $options)) {
- $options['foreign_keys'] = array();
- }
- $constraints = array_flip($constraints);
- foreach ($constraints as $constraint => $value) {
- if (!empty($definition['primary'])) {
- if (!array_key_exists('primary', $options)) {
- $options['primary'] = $definition['fields'];
- //remove from the $constraint array, it's already handled by createTable()
- unset($constraints[$constraint]);
- }
- } else {
- $c_definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
- if (PEAR::isError($c_definition)) {
- return $c_definition;
- }
- if (!empty($c_definition['foreign'])) {
- if (!array_key_exists($constraint, $options['foreign_keys'])) {
- $options['foreign_keys'][$constraint] = $c_definition;
- }
- //remove from the $constraint array, it's already handled by createTable()
- unset($constraints[$constraint]);
- } else {
- $constraints[$constraint] = $c_definition;
- }
- }
- }
-
- $name_new = $name;
- $create_order = $select_fields = array_keys($fields);
- foreach ($changes as $change_name => $change) {
- switch ($change_name) {
- case 'add':
- foreach ($change as $field_name => $field) {
- $fields[$field_name] = $field;
- $create_order[] = $field_name;
- }
- break;
- case 'remove':
- foreach ($change as $field_name => $field) {
- unset($fields[$field_name]);
- $select_fields = array_diff($select_fields, array($field_name));
- $create_order = array_diff($create_order, array($field_name));
- }
- break;
- case 'change':
- foreach ($change as $field_name => $field) {
- $fields[$field_name] = $field['definition'];
- }
- break;
- case 'name':
- $name_new = $change;
- break;
- case 'rename':
- foreach ($change as $field_name => $field) {
- unset($fields[$field_name]);
- $fields[$field['name']] = $field['definition'];
- $create_order[array_search($field_name, $create_order)] = $field['name'];
- }
- break;
- default:
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'change type "'.$change_name.'" not yet supported', __FUNCTION__);
- }
- }
-
- $data = null;
- if (!empty($select_fields)) {
- $query = 'SELECT '.implode(', ', $select_fields).' FROM '.$db->quoteIdentifier($name, true);
- $data = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED);
- }
-
- $result = $this->dropTable($name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $result = $this->createTable($name_new, $fields, $options);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- foreach ($indexes as $index => $definition) {
- $this->createIndex($name_new, $index, $definition);
- }
-
- foreach ($constraints as $constraint => $definition) {
- $this->createConstraint($name_new, $constraint, $definition);
- }
-
- if (!empty($select_fields) && !empty($data)) {
- $query = 'INSERT INTO '.$db->quoteIdentifier($name_new, true);
- $query.= '('.implode(', ', array_slice(array_keys($fields), 0, count($select_fields))).')';
- $query.=' VALUES (?'.str_repeat(', ?', (count($select_fields) - 1)).')';
- $stmt = $db->prepare($query, null, MDB2_PREPARE_MANIP);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- foreach ($data as $row) {
- $result = $stmt->execute($row);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'list databases is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'list databases is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name FROM sqlite_master WHERE type='view' AND sql NOT NULL";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableViews()
-
- /**
- * list the views in the database that reference a given table
- *
- * @param string table for which all referenced views should be found
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listTableViews($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
- $views = $db->queryAll($query, array('text', 'text'), MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($views)) {
- return $views;
- }
- $result = array();
- foreach ($views as $row) {
- if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i", $row['sql'])) {
- if (!empty($row['name'])) {
- $result[$row['name']] = true;
- }
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the current database
- *
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
- $table_names = $db->queryCol($query);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
- $result = array();
- foreach ($table_names as $table_name) {
- if (!$this->_fixSequenceName($table_name, true)) {
- $result[] = $table_name;
- }
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->loadModule('Reverse', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name='.$db->quote($table, 'text');
- }
- $sql = $db->queryOne($query);
- if (PEAR::isError($sql)) {
- return $sql;
- }
- $columns = $db->reverse->_getTableColumns($sql);
- $fields = array();
- foreach ($columns as $column) {
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column['name'] = strtolower($column['name']);
- } else {
- $column['name'] = strtoupper($column['name']);
- }
- } else {
- $column = array_change_key_case($column, $db->options['field_case']);
- }
- $fields[] = $column['name'];
- }
- return $fields;
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name FROM sqlite_master WHERE type='trigger' AND sql NOT NULL";
- if (null !== $table) {
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= ' AND LOWER(tbl_name)='.$db->quote(strtolower($table), 'text');
- } else {
- $query.= ' AND tbl_name='.$db->quote($table, 'text');
- }
- }
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ createIndex()
-
- /**
- * Get the stucture of a field into an array
- *
- * @param string $table name of the table on which the index is to be created
- * @param string $name name of the index to be created
- * @param array $definition associative array that defines properties of the index to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the index fields as array
- * indexes. Each entry of this array is set to another type of associative
- * array that specifies properties of the index that are specific to
- * each field.
- *
- * Currently, only the sorting property is supported. It should be used
- * to define the sorting direction of the index. It may be set to either
- * ascending or descending.
- *
- * Not all DBMS support index sorting direction configuration. The DBMS
- * drivers of those that do not support it ignore this property. Use the
- * function support() to determine whether the DBMS driver can manage indexes.
-
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(
- * 'sorting' => 'ascending'
- * ),
- * 'last_login' => array()
- * )
- * )
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createIndex($table, $name, $definition)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "CREATE INDEX $name ON $table";
- $fields = array();
- foreach ($definition['fields'] as $field_name => $field) {
- $field_string = $db->quoteIdentifier($field_name, true);
- if (!empty($field['sorting'])) {
- switch ($field['sorting']) {
- case 'ascending':
- $field_string.= ' ASC';
- break;
- case 'descending':
- $field_string.= ' DESC';
- break;
- }
- }
- $fields[] = $field_string;
- }
- $query .= ' ('.implode(', ', $fields) . ')';
- $result = $db->exec($query);
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropIndex()
-
- /**
- * drop existing index
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the index to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropIndex($table, $name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->getIndexName($name);
- $result = $db->exec("DROP INDEX $name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quote($table, 'text');
- $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(tbl_name)='.strtolower($table);
- } else {
- $query.= "tbl_name=$table";
- }
- $query.= " AND sql NOT NULL ORDER BY name";
- $indexes = $db->queryCol($query, 'text');
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $sql) {
- if (preg_match("/^create index ([^ ]+) on /i", $sql, $tmp)) {
- $index = $this->_fixIndexName($tmp[1]);
- if (!empty($index)) {
- $result[$index] = true;
- }
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createConstraint()
-
- /**
- * create a constraint on a table
- *
- * @param string $table name of the table on which the constraint is to be created
- * @param string $name name of the constraint to be created
- * @param array $definition associative array that defines properties of the constraint to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the constraint fields as array
- * constraints. Each entry of this array is set to another type of associative
- * array that specifies properties of the constraint that are specific to
- * each field.
- *
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(),
- * 'last_login' => array()
- * )
- * )
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createConstraint($table, $name, $definition)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($definition['primary'])) {
- return $db->manager->alterTable($table, array(), false, array('primary' => $definition['fields']));
- }
-
- if (!empty($definition['foreign'])) {
- return $db->manager->alterTable($table, array(), false, array('foreign_keys' => array($name => $definition)));
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->getIndexName($name);
- $query = "CREATE UNIQUE INDEX $name ON $table";
- $fields = array();
- foreach ($definition['fields'] as $field_name => $field) {
- $field_string = $field_name;
- if (!empty($field['sorting'])) {
- switch ($field['sorting']) {
- case 'ascending':
- $field_string.= ' ASC';
- break;
- case 'descending':
- $field_string.= ' DESC';
- break;
- }
- }
- $fields[] = $field_string;
- }
- $query .= ' ('.implode(', ', $fields) . ')';
- $result = $db->exec($query);
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropConstraint()
-
- /**
- * drop existing constraint
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the constraint to be dropped
- * @param string $primary hint if the constraint is primary
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropConstraint($table, $name, $primary = false)
- {
- if ($primary || $name == 'PRIMARY') {
- return $this->alterTable($table, array(), false, array('primary' => null));
- }
-
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- //is it a FK constraint? If so, also delete the associated triggers
- $db->loadModule('Reverse', null, true);
- $definition = $db->reverse->getTableConstraintDefinition($table, $name);
- if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
- //first drop the FK enforcing triggers
- $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);
- if (PEAR::isError($result)) {
- return $result;
- }
- //then drop the constraint itself
- return $this->alterTable($table, array(), false, array('foreign_keys' => array($name => null)));
- }
-
- $name = $db->getIndexName($name);
- $result = $db->exec("DROP INDEX $name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _dropFKTriggers()
-
- /**
- * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
- *
- * @param string $table table name
- * @param string $fkname FOREIGN KEY constraint name
- * @param string $referenced_table referenced table name
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function _dropFKTriggers($table, $fkname, $referenced_table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $triggers = $this->listTableTriggers($table);
- $triggers2 = $this->listTableTriggers($referenced_table);
- if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) {
- $triggers = array_merge($triggers, $triggers2);
- $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';
- foreach ($triggers as $trigger) {
- if (preg_match($pattern, $trigger)) {
- $result = $db->exec('DROP TRIGGER '.$trigger);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quote($table, 'text');
- $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(tbl_name)='.strtolower($table);
- } else {
- $query.= "tbl_name=$table";
- }
- $query.= " AND sql NOT NULL ORDER BY name";
- $indexes = $db->queryCol($query, 'text');
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $sql) {
- if (preg_match("/^create unique index ([^ ]+) on /i", $sql, $tmp)) {
- $index = $this->_fixIndexName($tmp[1]);
- if (!empty($index)) {
- $result[$index] = true;
- }
- }
- }
-
- // also search in table definition for PRIMARY KEYs...
- $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)='.strtolower($table);
- } else {
- $query.= "name=$table";
- }
- $query.= " AND sql NOT NULL ORDER BY name";
- $table_def = $db->queryOne($query, 'text');
- if (PEAR::isError($table_def)) {
- return $table_def;
- }
- if (preg_match("/\bPRIMARY\s+KEY\b/i", $table_def, $tmp)) {
- $result['primary'] = true;
- }
-
- // ...and for FOREIGN KEYs
- if (preg_match_all("/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN\s+KEY/imsx", $table_def, $tmp)) {
- foreach ($tmp[1] as $fk) {
- $result[$fk] = true;
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true);
- $query = "CREATE TABLE $sequence_name ($seqcol_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)";
- $res = $db->exec($query);
- if (PEAR::isError($res)) {
- return $res;
- }
- if ($start == 1) {
- return MDB2_OK;
- }
- $res = $db->exec("INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')');
- if (!PEAR::isError($res)) {
- return MDB2_OK;
- }
- // Handle error
- $result = $db->exec("DROP TABLE $sequence_name");
- if (PEAR::isError($result)) {
- return $db->raiseError($result, null, null,
- 'could not drop inconsistent sequence table', __FUNCTION__);
- }
- return $db->raiseError($res, null, null,
- 'could not create sequence table', __FUNCTION__);
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($seq_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- $result = $db->exec("DROP TABLE $sequence_name");
- if (MDB2::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences()
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
- $table_names = $db->queryCol($query);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
- $result = array();
- foreach ($table_names as $table_name) {
- if ($sqn = $this->_fixSequenceName($table_name, true)) {
- $result[] = $sqn;
- }
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
-}
-?>
diff --git a/3rdparty/MDB2/Driver/Native/Common.php b/3rdparty/MDB2/Driver/Native/Common.php
deleted file mode 100644
index 67dc1bddd0..0000000000
--- a/3rdparty/MDB2/Driver/Native/Common.php
+++ /dev/null
@@ -1,61 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-/**
- * Base class for the natuve modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Native');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Native_Common extends MDB2_Module_Common
-{
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Native/mysql.php b/3rdparty/MDB2/Driver/Native/mysql.php
deleted file mode 100644
index 48e65a05fd..0000000000
--- a/3rdparty/MDB2/Driver/Native/mysql.php
+++ /dev/null
@@ -1,60 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 MySQL driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Native_mysql extends MDB2_Driver_Native_Common
-{
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Native/oci8.php b/3rdparty/MDB2/Driver/Native/oci8.php
deleted file mode 100644
index d198f9687a..0000000000
--- a/3rdparty/MDB2/Driver/Native/oci8.php
+++ /dev/null
@@ -1,60 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id: oci8.php 215004 2006-06-18 21:59:05Z lsmith $
-//
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 Oracle driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Native_oci8 extends MDB2_Driver_Native_Common
-{
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Native/pgsql.php b/3rdparty/MDB2/Driver/Native/pgsql.php
deleted file mode 100644
index f4db5eae52..0000000000
--- a/3rdparty/MDB2/Driver/Native/pgsql.php
+++ /dev/null
@@ -1,88 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 PostGreSQL driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_Driver_Native_pgsql extends MDB2_Driver_Native_Common
-{
- // }}}
- // {{{ deleteOID()
-
- /**
- * delete an OID
- *
- * @param integer $OID
- * @return mixed MDB2_OK on success or MDB2 Error Object on failure
- * @access public
- */
- function deleteOID($OID)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $connection = $db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- if (!@pg_lo_unlink($connection, $OID)) {
- return $db->raiseError(null, null, null,
- 'Unable to unlink OID: '.$OID, __FUNCTION__);
- }
- return MDB2_OK;
- }
-
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Native/sqlite.php b/3rdparty/MDB2/Driver/Native/sqlite.php
deleted file mode 100644
index 4eb796dce7..0000000000
--- a/3rdparty/MDB2/Driver/Native/sqlite.php
+++ /dev/null
@@ -1,60 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 SQLite driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common
-{
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Reverse/Common.php b/3rdparty/MDB2/Driver/Reverse/Common.php
deleted file mode 100644
index 2260520835..0000000000
--- a/3rdparty/MDB2/Driver/Reverse/Common.php
+++ /dev/null
@@ -1,517 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-/**
- * @package MDB2
- * @category Database
- */
-
-/**
- * These are constants for the tableInfo-function
- * they are bitwised or'ed. so if there are more constants to be defined
- * in the future, adjust MDB2_TABLEINFO_FULL accordingly
- */
-
-define('MDB2_TABLEINFO_ORDER', 1);
-define('MDB2_TABLEINFO_ORDERTABLE', 2);
-define('MDB2_TABLEINFO_FULL', 3);
-
-/**
- * Base class for the schema reverse engineering module that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Reverse');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Reverse_Common extends MDB2_Module_Common
-{
- // {{{ splitTableSchema()
-
- /**
- * Split the "[owner|schema].table" notation into an array
- *
- * @param string $table [schema and] table name
- *
- * @return array array(schema, table)
- * @access private
- */
- function splitTableSchema($table)
- {
- $ret = array();
- if (strpos($table, '.') !== false) {
- return explode('.', $table);
- }
- return array(null, $table);
- }
-
- // }}}
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $field name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure.
- * The returned array contains an array for each field definition,
- * with all or some of these indices, depending on the field data type:
- * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
- * @access public
- */
- function getTableFieldDefinition($table, $field)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $index name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- *
- * array (
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * )
- * )
- * );
- *
- * @access public
- */
- function getTableIndexDefinition($table, $index)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of an constraints into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $index name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- *
- * array (
- * [primary] => 0
- * [unique] => 0
- * [foreign] => 1
- * [check] => 0
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * [position] => 3
- * )
- * )
- * [references] => array(
- * [table] => name
- * [fields] => array(
- * [field1name] => array( //one entry per each referenced field
- * [position] => 1
- * )
- * )
- * )
- * [deferrable] => 0
- * [initiallydeferred] => 0
- * [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [match] => SIMPLE|PARTIAL|FULL
- * );
- *
- * @access public
- */
- function getTableConstraintDefinition($table, $index)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getSequenceDefinition()
-
- /**
- * Get the structure of a sequence into an array
- *
- * @param string $sequence name of sequence that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- *
- * array (
- * [start] => n
- * );
- *
- * @access public
- */
- function getSequenceDefinition($sequence)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $start = $db->currId($sequence);
- if (PEAR::isError($start)) {
- return $start;
- }
- if ($db->supports('current_id')) {
- $start++;
- } else {
- $db->warnings[] = 'database does not support getting current
- sequence value, the sequence value was incremented';
- }
- $definition = array();
- if ($start != 1) {
- $definition = array('start' => $start);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- *
- * array (
- * [trigger_name] => 'trigger name',
- * [table_name] => 'table name',
- * [trigger_body] => 'trigger body definition',
- * [trigger_type] => 'BEFORE' | 'AFTER',
- * [trigger_event] => 'INSERT' | 'UPDATE' | 'DELETE'
- * //or comma separated list of multiple events, when supported
- * [trigger_enabled] => true|false
- * [trigger_comment] => 'trigger comment',
- * );
- *
- * The oci8 driver also returns a [when_clause] index.
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * The format of the resulting array depends on which $mode
- * you select. The sample output below is based on this query:
- *
- * SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
- * FROM tblFoo
- * JOIN tblBar ON tblFoo.fldId = tblBar.fldId
- *
- *
- *
- *
- *
- * null (default)
- *
- * [0] => Array (
- * [table] => tblFoo
- * [name] => fldId
- * [type] => int
- * [len] => 11
- * [flags] => primary_key not_null
- * )
- * [1] => Array (
- * [table] => tblFoo
- * [name] => fldPhone
- * [type] => string
- * [len] => 20
- * [flags] =>
- * )
- * [2] => Array (
- * [table] => tblBar
- * [name] => fldId
- * [type] => int
- * [len] => 11
- * [flags] => primary_key not_null
- * )
- *
- *
- *
- *
- * MDB2_TABLEINFO_ORDER
- *
- * In addition to the information found in the default output,
- * a notation of the number of columns is provided by the
- * num_fields element while the order
- * element provides an array with the column names as the keys and
- * their location index number (corresponding to the keys in the
- * the default output) as the values.
- *
- * If a result set has identical field names, the last one is
- * used.
- *
- *
- * [num_fields] => 3
- * [order] => Array (
- * [fldId] => 2
- * [fldTrans] => 1
- * )
- *
- *
- *
- *
- * MDB2_TABLEINFO_ORDERTABLE
- *
- * Similar to MDB2_TABLEINFO_ORDER but adds more
- * dimensions to the array in which the table names are keys and
- * the field names are sub-keys. This is helpful for queries that
- * join tables which have identical field names.
- *
- *
- * [num_fields] => 3
- * [ordertable] => Array (
- * [tblFoo] => Array (
- * [fldId] => 0
- * [fldPhone] => 1
- * )
- * [tblBar] => Array (
- * [fldId] => 2
- * )
- * )
- *
- *
- *
- *
- *
- * The flags element contains a space separated list
- * of extra information about the field. This data is inconsistent
- * between DBMS's due to the way each DBMS works.
- * + primary_key
- * + unique_key
- * + multiple_key
- * + not_null
- *
- * Most DBMS's only provide the table and flags
- * elements if $result is a table name. The following DBMS's
- * provide full information from queries:
- * + fbsql
- * + mysql
- *
- * If the 'portability' option has MDB2_PORTABILITY_FIX_CASE
- * turned on, the names of tables and fields will be lower or upper cased.
- *
- * @param object|string $result MDB2_result object from a query or a
- * string containing the name of a table.
- * While this also accepts a query result
- * resource identifier, this behavior is
- * deprecated.
- * @param int $mode either unused or one of the tableInfo modes:
- * MDB2_TABLEINFO_ORDERTABLE ,
- * MDB2_TABLEINFO_ORDER or
- * MDB2_TABLEINFO_FULL (which does both).
- * These are bitwise, so the first two can be
- * combined using | .
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::setOption()
- */
- function tableInfo($result, $mode = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!is_string($result)) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- $db->loadModule('Manager', null, true);
- $fields = $db->manager->listTableFields($result);
- if (PEAR::isError($fields)) {
- return $fields;
- }
-
- $flags = array();
-
- $idxname_format = $db->getOption('idxname_format');
- $db->setOption('idxname_format', '%s');
-
- $indexes = $db->manager->listTableIndexes($result);
- if (PEAR::isError($indexes)) {
- $db->setOption('idxname_format', $idxname_format);
- return $indexes;
- }
-
- foreach ($indexes as $index) {
- $definition = $this->getTableIndexDefinition($result, $index);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- if (count($definition['fields']) > 1) {
- foreach ($definition['fields'] as $field => $sort) {
- $flags[$field] = 'multiple_key';
- }
- }
- }
-
- $constraints = $db->manager->listTableConstraints($result);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- foreach ($constraints as $constraint) {
- $definition = $this->getTableConstraintDefinition($result, $constraint);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- $flag = !empty($definition['primary'])
- ? 'primary_key' : (!empty($definition['unique'])
- ? 'unique_key' : false);
- if ($flag) {
- foreach ($definition['fields'] as $field => $sort) {
- if (empty($flags[$field]) || $flags[$field] != 'primary_key') {
- $flags[$field] = $flag;
- }
- }
- }
- }
-
- $res = array();
-
- if ($mode) {
- $res['num_fields'] = count($fields);
- }
-
- foreach ($fields as $i => $field) {
- $definition = $this->getTableFieldDefinition($result, $field);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- $res[$i] = $definition[0];
- $res[$i]['name'] = $field;
- $res[$i]['table'] = $result;
- $res[$i]['type'] = preg_replace('/^([a-z]+).*$/i', '\\1', trim($definition[0]['nativetype']));
- // 'primary_key', 'unique_key', 'multiple_key'
- $res[$i]['flags'] = empty($flags[$field]) ? '' : $flags[$field];
- // not_null', 'unsigned', 'auto_increment', 'default_[rawencodedvalue]'
- if (!empty($res[$i]['notnull'])) {
- $res[$i]['flags'].= ' not_null';
- }
- if (!empty($res[$i]['unsigned'])) {
- $res[$i]['flags'].= ' unsigned';
- }
- if (!empty($res[$i]['auto_increment'])) {
- $res[$i]['flags'].= ' autoincrement';
- }
- if (!empty($res[$i]['default'])) {
- $res[$i]['flags'].= ' default_'.rawurlencode($res[$i]['default']);
- }
-
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- $db->setOption('idxname_format', $idxname_format);
- return $res;
- }
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Reverse/mysql.php b/3rdparty/MDB2/Driver/Reverse/mysql.php
deleted file mode 100644
index 8ebdc9979b..0000000000
--- a/3rdparty/MDB2/Driver/Reverse/mysql.php
+++ /dev/null
@@ -1,546 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-require_once 'MDB2/Driver/Reverse/Common.php';
-
-/**
- * MDB2 MySQL driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- * @author Lorenzo Alberton
- */
-class MDB2_Driver_Reverse_mysql extends MDB2_Driver_Reverse_Common
-{
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name);
- $columns = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($columns)) {
- return $columns;
- }
- foreach ($columns as $column) {
- $column = array_change_key_case($column, CASE_LOWER);
- $column['name'] = $column['field'];
- unset($column['field']);
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column['name'] = strtolower($column['name']);
- } else {
- $column['name'] = strtoupper($column['name']);
- }
- } else {
- $column = array_change_key_case($column, $db->options['field_case']);
- }
- if ($field_name == $column['name']) {
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (empty($column['null']) || $column['null'] !== 'YES') {
- $notnull = true;
- }
- $default = false;
- if (array_key_exists('default', $column)) {
- $default = $column['default'];
- if ((null === $default) && $notnull) {
- $default = '';
- }
- }
- $definition[0] = array(
- 'notnull' => $notnull,
- 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
- );
- $autoincrement = false;
- if (!empty($column['extra'])) {
- if ($column['extra'] == 'auto_increment') {
- $autoincrement = true;
- } else {
- $definition[0]['extra'] = $column['extra'];
- }
- }
- $collate = null;
- if (!empty($column['collation'])) {
- $collate = $column['collation'];
- $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate);
- }
-
- if (null !== $length) {
- $definition[0]['length'] = $length;
- }
- if (null !== $unsigned) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (null !== $fixed) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- if ($autoincrement !== false) {
- $definition[0]['autoincrement'] = $autoincrement;
- }
- if (null !== $collate) {
- $definition[0]['collate'] = $collate;
- $definition[0]['charset'] = $charset;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- } elseif ($type == 'timestamp' && $notnull && empty($definition[$key]['default'])) {
- $definition[$key]['default'] = '0000-00-00 00:00:00';
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- return $definition;
- }
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table column', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
- $index_name_mdb2 = $db->getIndexName($index_name);
- $result = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2)));
- if (!PEAR::isError($result) && (null !== $result)) {
- // apply 'idxname_format' only if the query succeeded, otherwise
- // fallback to the given $index_name, without transformation
- $index_name = $index_name_mdb2;
- }
- $result = $db->query(sprintf($query, $db->quote($index_name)));
- if (PEAR::isError($result)) {
- return $result;
- }
- $colpos = 1;
- $definition = array();
- while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
- $row = array_change_key_case($row, CASE_LOWER);
- $key_name = $row['key_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $key_name = strtolower($key_name);
- } else {
- $key_name = strtoupper($key_name);
- }
- }
- if ($index_name == $key_name) {
- if (!$row['non_unique']) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $index_name . ' is not an existing table index', __FUNCTION__);
- }
- $column_name = $row['column_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column_name = strtolower($column_name);
- } else {
- $column_name = strtoupper($column_name);
- }
- }
- $definition['fields'][$column_name] = array(
- 'position' => $colpos++
- );
- if (!empty($row['collation'])) {
- $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
- ? 'ascending' : 'descending');
- }
- }
- }
- $result->free();
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $index_name . ' is not an existing table index', __FUNCTION__);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
- $constraint_name_original = $constraint_name;
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
- if (strtolower($constraint_name) != 'primary') {
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $result = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2)));
- if (!PEAR::isError($result) && (null !== $result)) {
- // apply 'idxname_format' only if the query succeeded, otherwise
- // fallback to the given $index_name, without transformation
- $constraint_name = $constraint_name_mdb2;
- }
- }
- $result = $db->query(sprintf($query, $db->quote($constraint_name)));
- if (PEAR::isError($result)) {
- return $result;
- }
- $colpos = 1;
- //default values, eventually overridden
- $definition = array(
- 'primary' => false,
- 'unique' => false,
- 'foreign' => false,
- 'check' => false,
- 'fields' => array(),
- 'references' => array(
- 'table' => '',
- 'fields' => array(),
- ),
- 'onupdate' => '',
- 'ondelete' => '',
- 'match' => '',
- 'deferrable' => false,
- 'initiallydeferred' => false,
- );
- while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
- $row = array_change_key_case($row, CASE_LOWER);
- $key_name = $row['key_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $key_name = strtolower($key_name);
- } else {
- $key_name = strtoupper($key_name);
- }
- }
- if ($constraint_name == $key_name) {
- if ($row['non_unique']) {
- //FOREIGN KEY?
- return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
- }
- if ($row['key_name'] == 'PRIMARY') {
- $definition['primary'] = true;
- } elseif (!$row['non_unique']) {
- $definition['unique'] = true;
- }
- $column_name = $row['column_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column_name = strtolower($column_name);
- } else {
- $column_name = strtoupper($column_name);
- }
- }
- $definition['fields'][$column_name] = array(
- 'position' => $colpos++
- );
- if (!empty($row['collation'])) {
- $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
- ? 'ascending' : 'descending');
- }
- }
- }
- $result->free();
- if (empty($definition['fields'])) {
- return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
- }
- return $definition;
- }
-
- // }}}
- // {{{ _getTableFKConstraintDefinition()
-
- /**
- * Get the FK definition from the CREATE TABLE statement
- *
- * @param string $table table name
- * @param string $constraint_name constraint name
- * @param array $definition default values for constraint definition
- *
- * @return array|PEAR_Error
- * @access private
- */
- function _getTableFKConstraintDefinition($table, $constraint_name, $definition)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- //Use INFORMATION_SCHEMA instead?
- //SELECT *
- // FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS
- // WHERE CONSTRAINT_SCHEMA = '$dbname'
- // AND TABLE_NAME = '$table'
- // AND CONSTRAINT_NAME = '$constraint_name';
- $query = 'SHOW CREATE TABLE '. $db->escape($table);
- $constraint = $db->queryOne($query, 'text', 1);
- if (!PEAR::isError($constraint) && !empty($constraint)) {
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $constraint = strtolower($constraint);
- } else {
- $constraint = strtoupper($constraint);
- }
- }
- $constraint_name_original = $constraint_name;
- $constraint_name = $db->getIndexName($constraint_name);
- $pattern = '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^\s]+) \(([^\)]+)\)(?: ON DELETE ([^\s]+))?(?: ON UPDATE ([^\s]+))?/i';
- if (!preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
- //fallback to original constraint name
- $pattern = '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^\s]+) \(([^\)]+)\)(?: ON DELETE ([^\s]+))?(?: ON UPDATE ([^\s]+))?/i';
- }
- if (preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
- $definition['foreign'] = true;
- $column_names = explode(',', $matches[1]);
- $referenced_cols = explode(',', $matches[3]);
- $definition['references'] = array(
- 'table' => $matches[2],
- 'fields' => array(),
- );
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- $colpos = 1;
- foreach ($referenced_cols as $column_name) {
- $definition['references']['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- $definition['ondelete'] = empty($matches[4]) ? 'RESTRICT' : strtoupper($matches[4]);
- $definition['onupdate'] = empty($matches[5]) ? 'RESTRICT' : strtoupper($matches[5]);
- $definition['match'] = 'SIMPLE';
- return $definition;
- }
- }
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT trigger_name,
- event_object_table AS table_name,
- action_statement AS trigger_body,
- action_timing AS trigger_type,
- event_manipulation AS trigger_event
- FROM information_schema.triggers
- WHERE trigger_name = '. $db->quote($trigger, 'text');
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- );
- $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($def)) {
- return $def;
- }
- $def['trigger_comment'] = '';
- $def['trigger_enabled'] = true;
- return $def;
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * @param object|string $result MDB2_result object from a query or a
- * string containing the name of a table.
- * While this also accepts a query result
- * resource identifier, this behavior is
- * deprecated.
- * @param int $mode a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::setOption()
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
- if (!is_resource($resource)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Could not generate result resource', __FUNCTION__);
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strtoupper';
- }
- } else {
- $case_func = 'strval';
- }
-
- $count = @mysql_num_fields($resource);
- $res = array();
- if ($mode) {
- $res['num_fields'] = $count;
- }
-
- $db->loadModule('Datatype', null, true);
- for ($i = 0; $i < $count; $i++) {
- $res[$i] = array(
- 'table' => $case_func(@mysql_field_table($resource, $i)),
- 'name' => $case_func(@mysql_field_name($resource, $i)),
- 'type' => @mysql_field_type($resource, $i),
- 'length' => @mysql_field_len($resource, $i),
- 'flags' => @mysql_field_flags($resource, $i),
- );
- if ($res[$i]['type'] == 'string') {
- $res[$i]['type'] = 'char';
- } elseif ($res[$i]['type'] == 'unknown') {
- $res[$i]['type'] = 'decimal';
- }
- $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
- if (PEAR::isError($mdb2type_info)) {
- return $mdb2type_info;
- }
- $res[$i]['mdb2type'] = $mdb2type_info[0][0];
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- return $res;
- }
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Reverse/oci8.php b/3rdparty/MDB2/Driver/Reverse/oci8.php
deleted file mode 100644
index d89ad77137..0000000000
--- a/3rdparty/MDB2/Driver/Reverse/oci8.php
+++ /dev/null
@@ -1,625 +0,0 @@
- |
-// | Lorenzo Alberton |
-// +----------------------------------------------------------------------+
-//
-// $Id: oci8.php 295587 2010-02-28 17:16:38Z quipo $
-//
-
-require_once 'MDB2/Driver/Reverse/Common.php';
-
-/**
- * MDB2 Oracle driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Reverse_oci8 extends MDB2_Driver_Reverse_Common
-{
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- list($owner, $table) = $this->splitTableSchema($table_name);
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = 'SELECT column_name AS "name",
- data_type AS "type",
- nullable AS "nullable",
- data_default AS "default",
- COALESCE(data_precision, data_length) AS "length",
- data_scale AS "scale"
- FROM all_tab_columns
- WHERE (table_name=? OR table_name=?)
- AND (owner=? OR owner=?)
- AND (column_name=? OR column_name=?)
- ORDER BY column_id';
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $args = array(
- $table,
- strtoupper($table),
- $owner,
- strtoupper($owner),
- $field_name,
- strtoupper($field_name)
- );
- $result = $stmt->execute($args);
- if (PEAR::isError($result)) {
- return $result;
- }
- $column = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($column)) {
- return $column;
- }
- $stmt->free();
- $result->free();
-
- if (empty($column)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $field_name . ' is not a column in table ' . $table_name, __FUNCTION__);
- }
-
- $column = array_change_key_case($column, CASE_LOWER);
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column['name'] = strtolower($column['name']);
- } else {
- $column['name'] = strtoupper($column['name']);
- }
- }
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (!empty($column['nullable']) && $column['nullable'] == 'N') {
- $notnull = true;
- }
- $default = false;
- if (array_key_exists('default', $column)) {
- $default = $column['default'];
- if ($default === 'NULL') {
- $default = null;
- }
- //ugly hack, but works for the reverse direction
- if ($default == "''") {
- $default = '';
- }
- if ((null === $default) && $notnull) {
- $default = '';
- }
- }
-
- $definition[0] = array('notnull' => $notnull, 'nativetype' => $column['type']);
- if (null !== $length) {
- $definition[0]['length'] = $length;
- }
- if (null !== $unsigned) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (null !== $fixed) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- if ($type == 'integer') {
- $query= "SELECT trigger_body
- FROM all_triggers
- WHERE table_name=?
- AND triggering_event='INSERT'
- AND trigger_type='BEFORE EACH ROW'";
- // ^^ pretty reasonable mimic for "auto_increment" in oracle?
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $result = $stmt->execute(strtoupper($table));
- if (PEAR::isError($result)) {
- return $result;
- }
- while ($triggerstr = $result->fetchOne()) {
- if (preg_match('/.*SELECT\W+(.+)\.nextval +into +\:NEW\.'.$field_name.' +FROM +dual/im', $triggerstr, $matches)) {
- $definition[0]['autoincrement'] = $matches[1];
- }
- }
- $stmt->free();
- $result->free();
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($owner, $table) = $this->splitTableSchema($table_name);
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = 'SELECT aic.column_name AS "column_name",
- aic.column_position AS "column_position",
- aic.descend AS "descend",
- aic.table_owner AS "table_owner",
- alc.constraint_type AS "constraint_type"
- FROM all_ind_columns aic
- LEFT JOIN all_constraints alc
- ON aic.index_name = alc.constraint_name
- AND aic.table_name = alc.table_name
- AND aic.table_owner = alc.owner
- WHERE (aic.table_name=? OR aic.table_name=?)
- AND (aic.index_name=? OR aic.index_name=?)
- AND (aic.table_owner=? OR aic.table_owner=?)
- ORDER BY column_position';
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $indexnames = array_unique(array($db->getIndexName($index_name), $index_name));
- $i = 0;
- $row = null;
- while ((null === $row) && array_key_exists($i, $indexnames)) {
- $args = array(
- $table,
- strtoupper($table),
- $indexnames[$i],
- strtoupper($indexnames[$i]),
- $owner,
- strtoupper($owner)
- );
- $result = $stmt->execute($args);
- if (PEAR::isError($result)) {
- return $result;
- }
- $row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row)) {
- return $row;
- }
- $i++;
- }
- if (null === $row) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $index_name. ' is not an index on table '. $table_name, __FUNCTION__);
- }
- if ($row['constraint_type'] == 'U' || $row['constraint_type'] == 'P') {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $index_name. ' is a constraint, not an index on table '. $table_name, __FUNCTION__);
- }
-
- $definition = array();
- while (null !== $row) {
- $row = array_change_key_case($row, CASE_LOWER);
- $column_name = $row['column_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column_name = strtolower($column_name);
- } else {
- $column_name = strtoupper($column_name);
- }
- }
- $definition['fields'][$column_name] = array(
- 'position' => (int)$row['column_position'],
- );
- if (!empty($row['descend'])) {
- $definition['fields'][$column_name]['sorting'] =
- ($row['descend'] == 'ASC' ? 'ascending' : 'descending');
- }
- $row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
- }
- $result->free();
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $index_name. ' is not an index on table '. $table_name, __FUNCTION__);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($owner, $table) = $this->splitTableSchema($table_name);
- if (empty($owner)) {
- $owner = $db->dsn['username'];
- }
-
- $query = 'SELECT alc.constraint_name,
- CASE alc.constraint_type WHEN \'P\' THEN 1 ELSE 0 END "primary",
- CASE alc.constraint_type WHEN \'R\' THEN 1 ELSE 0 END "foreign",
- CASE alc.constraint_type WHEN \'U\' THEN 1 ELSE 0 END "unique",
- CASE alc.constraint_type WHEN \'C\' THEN 1 ELSE 0 END "check",
- alc.DELETE_RULE "ondelete",
- \'NO ACTION\' "onupdate",
- \'SIMPLE\' "match",
- CASE alc.deferrable WHEN \'NOT DEFERRABLE\' THEN 0 ELSE 1 END "deferrable",
- CASE alc.deferred WHEN \'IMMEDIATE\' THEN 0 ELSE 1 END "initiallydeferred",
- alc.search_condition AS "search_condition",
- alc.table_name,
- cols.column_name AS "column_name",
- cols.position,
- r_alc.table_name "references_table",
- r_cols.column_name "references_field",
- r_cols.position "references_field_position"
- FROM all_cons_columns cols
- LEFT JOIN all_constraints alc
- ON alc.constraint_name = cols.constraint_name
- AND alc.owner = cols.owner
- LEFT JOIN all_constraints r_alc
- ON alc.r_constraint_name = r_alc.constraint_name
- AND alc.r_owner = r_alc.owner
- LEFT JOIN all_cons_columns r_cols
- ON r_alc.constraint_name = r_cols.constraint_name
- AND r_alc.owner = r_cols.owner
- AND cols.position = r_cols.position
- WHERE (alc.constraint_name=? OR alc.constraint_name=?)
- AND alc.constraint_name = cols.constraint_name
- AND (alc.owner=? OR alc.owner=?)';
- $tablenames = array();
- if (!empty($table)) {
- $query.= ' AND (alc.table_name=? OR alc.table_name=?)';
- $tablenames = array($table, strtoupper($table));
- }
- $stmt = $db->prepare($query);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $constraintnames = array_unique(array($db->getIndexName($constraint_name), $constraint_name));
- $c = 0;
- $row = null;
- while ((null === $row) && array_key_exists($c, $constraintnames)) {
- $args = array(
- $constraintnames[$c],
- strtoupper($constraintnames[$c]),
- $owner,
- strtoupper($owner)
- );
- if (!empty($table)) {
- $args = array_merge($args, $tablenames);
- }
- $result = $stmt->execute($args);
- if (PEAR::isError($result)) {
- return $result;
- }
- $row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row)) {
- return $row;
- }
- $c++;
- }
-
- $definition = array(
- 'primary' => (boolean)$row['primary'],
- 'unique' => (boolean)$row['unique'],
- 'foreign' => (boolean)$row['foreign'],
- 'check' => (boolean)$row['check'],
- 'deferrable' => (boolean)$row['deferrable'],
- 'initiallydeferred' => (boolean)$row['initiallydeferred'],
- 'ondelete' => $row['ondelete'],
- 'onupdate' => $row['onupdate'],
- 'match' => $row['match'],
- );
-
- if ($definition['check']) {
- // pattern match constraint for check constraint values into enum-style output:
- $enumregex = '/'.$row['column_name'].' in \((.+?)\)/i';
- if (preg_match($enumregex, $row['search_condition'], $rangestr)) {
- $definition['fields'][$column_name] = array();
- $allowed = explode(',', $rangestr[1]);
- foreach ($allowed as $val) {
- $val = trim($val);
- $val = preg_replace('/^\'/', '', $val);
- $val = preg_replace('/\'$/', '', $val);
- array_push($definition['fields'][$column_name], $val);
- }
- }
- }
-
- while (null !== $row) {
- $row = array_change_key_case($row, CASE_LOWER);
- $column_name = $row['column_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column_name = strtolower($column_name);
- } else {
- $column_name = strtoupper($column_name);
- }
- }
- $definition['fields'][$column_name] = array(
- 'position' => (int)$row['position']
- );
- if ($row['foreign']) {
- $ref_column_name = $row['references_field'];
- $ref_table_name = $row['references_table'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $ref_column_name = strtolower($ref_column_name);
- $ref_table_name = strtolower($ref_table_name);
- } else {
- $ref_column_name = strtoupper($ref_column_name);
- $ref_table_name = strtoupper($ref_table_name);
- }
- }
- $definition['references']['table'] = $ref_table_name;
- $definition['references']['fields'][$ref_column_name] = array(
- 'position' => (int)$row['references_field_position']
- );
- }
- $lastrow = $row;
- $row = $result->fetchRow(MDB2_FETCHMODE_ASSOC);
- }
- $result->free();
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not a constraint on table '. $table_name, __FUNCTION__);
- }
-
- return $definition;
- }
-
- // }}}
- // {{{ getSequenceDefinition()
-
- /**
- * Get the structure of a sequence into an array
- *
- * @param string $sequence name of sequence that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getSequenceDefinition($sequence)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->getSequenceName($sequence);
- $query = 'SELECT last_number FROM user_sequences';
- $query.= ' WHERE sequence_name='.$db->quote($sequence_name, 'text');
- $query.= ' OR sequence_name='.$db->quote(strtoupper($sequence_name), 'text');
- $start = $db->queryOne($query, 'integer');
- if (PEAR::isError($start)) {
- return $start;
- }
- $definition = array();
- if ($start != 1) {
- $definition = array('start' => $start);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT trigger_name AS "trigger_name",
- table_name AS "table_name",
- trigger_body AS "trigger_body",
- trigger_type AS "trigger_type",
- triggering_event AS "trigger_event",
- description AS "trigger_comment",
- 1 AS "trigger_enabled",
- when_clause AS "when_clause"
- FROM user_triggers
- WHERE trigger_name = \''. strtoupper($trigger).'\'';
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- 'trigger_comment' => 'text',
- 'trigger_enabled' => 'boolean',
- 'when_clause' => 'text',
- );
- $result = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!empty($result['trigger_type'])) {
- //$result['trigger_type'] = array_shift(explode(' ', $result['trigger_type']));
- $result['trigger_type'] = preg_replace('/(\S+).*/', '\\1', $result['trigger_type']);
- }
- return $result;
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * NOTE: only supports 'table' and 'flags' if $result
- * is a table name.
- *
- * NOTE: flags won't contain index information.
- *
- * @param object|string $result MDB2_result object from a query or a
- * string containing the name of a table.
- * While this also accepts a query result
- * resource identifier, this behavior is
- * deprecated.
- * @param int $mode a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
- if (!is_resource($resource)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Could not generate result resource', __FUNCTION__);
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strtoupper';
- }
- } else {
- $case_func = 'strval';
- }
-
- $count = @OCINumCols($resource);
- $res = array();
-
- if ($mode) {
- $res['num_fields'] = $count;
- }
-
- $db->loadModule('Datatype', null, true);
- for ($i = 0; $i < $count; $i++) {
- $column = array(
- 'table' => '',
- 'name' => $case_func(@OCIColumnName($resource, $i+1)),
- 'type' => @OCIColumnType($resource, $i+1),
- 'length' => @OCIColumnSize($resource, $i+1),
- 'flags' => '',
- );
- $res[$i] = $column;
- $res[$i]['mdb2type'] = $db->datatype->mapNativeDatatype($res[$i]);
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
- return $res;
- }
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Reverse/pgsql.php b/3rdparty/MDB2/Driver/Reverse/pgsql.php
deleted file mode 100644
index eab02f9b99..0000000000
--- a/3rdparty/MDB2/Driver/Reverse/pgsql.php
+++ /dev/null
@@ -1,574 +0,0 @@
- |
-// | Lorenzo Alberton |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-
-require_once 'MDB2/Driver/Reverse/Common.php';
-
-/**
- * MDB2 PostGreSQL driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- * @author Lorenzo Alberton
- */
-class MDB2_Driver_Reverse_pgsql extends MDB2_Driver_Reverse_Common
-{
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT a.attname AS name,
- t.typname AS type,
- CASE a.attlen
- WHEN -1 THEN
- CASE t.typname
- WHEN 'numeric' THEN (a.atttypmod / 65536)
- WHEN 'decimal' THEN (a.atttypmod / 65536)
- WHEN 'money' THEN (a.atttypmod / 65536)
- ELSE CASE a.atttypmod
- WHEN -1 THEN NULL
- ELSE a.atttypmod - 4
- END
- END
- ELSE a.attlen
- END AS length,
- CASE t.typname
- WHEN 'numeric' THEN (a.atttypmod % 65536) - 4
- WHEN 'decimal' THEN (a.atttypmod % 65536) - 4
- WHEN 'money' THEN (a.atttypmod % 65536) - 4
- ELSE 0
- END AS scale,
- a.attnotnull,
- a.atttypmod,
- a.atthasdef,
- (SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
- FROM pg_attrdef d
- WHERE d.adrelid = a.attrelid
- AND d.adnum = a.attnum
- AND a.atthasdef
- ) as default
- FROM pg_attribute a,
- pg_class c,
- pg_type t
- WHERE c.relname = ".$db->quote($table, 'text')."
- AND a.atttypid = t.oid
- AND c.oid = a.attrelid
- AND NOT a.attisdropped
- AND a.attnum > 0
- AND a.attname = ".$db->quote($field_name, 'text')."
- ORDER BY a.attnum";
- $column = $db->queryRow($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($column)) {
- return $column;
- }
-
- if (empty($column)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table column', __FUNCTION__);
- }
-
- $column = array_change_key_case($column, CASE_LOWER);
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (!empty($column['attnotnull']) && $column['attnotnull'] == 't') {
- $notnull = true;
- }
- $default = null;
- if ($column['atthasdef'] === 't'
- && strpos($column['default'], 'NULL') !== 0
- && !preg_match("/nextval\('([^']+)'/", $column['default'])
- ) {
- $pattern = '/^\'(.*)\'::[\w ]+$/i';
- $default = $column['default'];#substr($column['adsrc'], 1, -1);
- if ((null === $default) && $notnull) {
- $default = '';
- } elseif (!empty($default) && preg_match($pattern, $default)) {
- //remove data type cast
- $default = preg_replace ($pattern, '\\1', $default);
- }
- }
- $autoincrement = false;
- if (preg_match("/nextval\('([^']+)'/", $column['default'], $nextvals)) {
- $autoincrement = true;
- }
- $definition[0] = array('notnull' => $notnull, 'nativetype' => $column['type']);
- if (null !== $length) {
- $definition[0]['length'] = $length;
- }
- if (null !== $unsigned) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (null !== $fixed) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- if ($autoincrement !== false) {
- $definition[0]['autoincrement'] = $autoincrement;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = 'SELECT relname, indkey FROM pg_index, pg_class';
- $query.= ' WHERE pg_class.oid = pg_index.indexrelid';
- $query.= " AND indisunique != 't' AND indisprimary != 't'";
- $query.= ' AND pg_class.relname = %s';
- $index_name_mdb2 = $db->getIndexName($index_name);
- $row = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $row = $db->queryRow(sprintf($query, $db->quote($index_name, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
-
- if (empty($row)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
-
- $row = array_change_key_case($row, CASE_LOWER);
-
- $db->loadModule('Manager', null, true);
- $columns = $db->manager->listTableFields($table_name);
-
- $definition = array();
-
- $index_column_numbers = explode(' ', $row['indkey']);
-
- $colpos = 1;
- foreach ($index_column_numbers as $number) {
- $definition['fields'][$columns[($number - 1)]] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT c.oid,
- c.conname AS constraint_name,
- CASE WHEN c.contype = 'c' THEN 1 ELSE 0 END AS \"check\",
- CASE WHEN c.contype = 'f' THEN 1 ELSE 0 END AS \"foreign\",
- CASE WHEN c.contype = 'p' THEN 1 ELSE 0 END AS \"primary\",
- CASE WHEN c.contype = 'u' THEN 1 ELSE 0 END AS \"unique\",
- CASE WHEN c.condeferrable = 'f' THEN 0 ELSE 1 END AS deferrable,
- CASE WHEN c.condeferred = 'f' THEN 0 ELSE 1 END AS initiallydeferred,
- --array_to_string(c.conkey, ' ') AS constraint_key,
- t.relname AS table_name,
- t2.relname AS references_table,
- CASE confupdtype
- WHEN 'a' THEN 'NO ACTION'
- WHEN 'r' THEN 'RESTRICT'
- WHEN 'c' THEN 'CASCADE'
- WHEN 'n' THEN 'SET NULL'
- WHEN 'd' THEN 'SET DEFAULT'
- END AS onupdate,
- CASE confdeltype
- WHEN 'a' THEN 'NO ACTION'
- WHEN 'r' THEN 'RESTRICT'
- WHEN 'c' THEN 'CASCADE'
- WHEN 'n' THEN 'SET NULL'
- WHEN 'd' THEN 'SET DEFAULT'
- END AS ondelete,
- CASE confmatchtype
- WHEN 'u' THEN 'UNSPECIFIED'
- WHEN 'f' THEN 'FULL'
- WHEN 'p' THEN 'PARTIAL'
- END AS match,
- --array_to_string(c.confkey, ' ') AS fk_constraint_key,
- consrc
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.conrelid = t.oid
- LEFT JOIN pg_class t2 ON c.confrelid = t2.oid
- WHERE c.conname = %s
- AND t.relname = " . $db->quote($table, 'text');
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $constraint_name_mdb2 = $constraint_name;
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
- $uniqueIndex = false;
- if (empty($row)) {
- // We might be looking for a UNIQUE index that was not created
- // as a constraint but should be treated as such.
- $query = 'SELECT relname AS constraint_name,
- indkey,
- 0 AS "check",
- 0 AS "foreign",
- 0 AS "primary",
- 1 AS "unique",
- 0 AS deferrable,
- 0 AS initiallydeferred,
- NULL AS references_table,
- NULL AS onupdate,
- NULL AS ondelete,
- NULL AS match
- FROM pg_index, pg_class
- WHERE pg_class.oid = pg_index.indexrelid
- AND indisunique = \'t\'
- AND pg_class.relname = %s';
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $constraint_name_mdb2 = $constraint_name;
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
- if (empty($row)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
- $uniqueIndex = true;
- }
-
- $row = array_change_key_case($row, CASE_LOWER);
-
- $definition = array(
- 'primary' => (boolean)$row['primary'],
- 'unique' => (boolean)$row['unique'],
- 'foreign' => (boolean)$row['foreign'],
- 'check' => (boolean)$row['check'],
- 'fields' => array(),
- 'references' => array(
- 'table' => $row['references_table'],
- 'fields' => array(),
- ),
- 'deferrable' => (boolean)$row['deferrable'],
- 'initiallydeferred' => (boolean)$row['initiallydeferred'],
- 'onupdate' => $row['onupdate'],
- 'ondelete' => $row['ondelete'],
- 'match' => $row['match'],
- );
-
- if ($uniqueIndex) {
- $db->loadModule('Manager', null, true);
- $columns = $db->manager->listTableFields($table_name);
- $index_column_numbers = explode(' ', $row['indkey']);
- $colpos = 1;
- foreach ($index_column_numbers as $number) {
- $definition['fields'][$columns[($number - 1)]] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
- return $definition;
- }
-
- $query = 'SELECT a.attname
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.conrelid = t.oid
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)
- WHERE c.conname = %s
- AND t.relname = ' . $db->quote($table, 'text');
- $fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
- if (PEAR::isError($fields)) {
- return $fields;
- }
- $colpos = 1;
- foreach ($fields as $field) {
- $definition['fields'][$field] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
-
- if ($definition['foreign']) {
- $query = 'SELECT a.attname
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.confrelid = t.oid
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.confkey)
- WHERE c.conname = %s
- AND t.relname = ' . $db->quote($definition['references']['table'], 'text');
- $foreign_fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
- if (PEAR::isError($foreign_fields)) {
- return $foreign_fields;
- }
- $colpos = 1;
- foreach ($foreign_fields as $foreign_field) {
- $definition['references']['fields'][$foreign_field] = array(
- 'position' => $colpos++,
- );
- }
- }
-
- if ($definition['check']) {
- $check_def = $db->queryOne("SELECT pg_get_constraintdef(" . $row['oid'] . ", 't')");
- // ...
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- *
- * @TODO: add support for plsql functions and functions with args
- */
- function getTriggerDefinition($trigger)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT trg.tgname AS trigger_name,
- tbl.relname AS table_name,
- CASE
- WHEN p.proname IS NOT NULL THEN 'EXECUTE PROCEDURE ' || p.proname || '();'
- ELSE ''
- END AS trigger_body,
- CASE trg.tgtype & cast(2 as int2)
- WHEN 0 THEN 'AFTER'
- ELSE 'BEFORE'
- END AS trigger_type,
- CASE trg.tgtype & cast(28 as int2)
- WHEN 16 THEN 'UPDATE'
- WHEN 8 THEN 'DELETE'
- WHEN 4 THEN 'INSERT'
- WHEN 20 THEN 'INSERT, UPDATE'
- WHEN 28 THEN 'INSERT, UPDATE, DELETE'
- WHEN 24 THEN 'UPDATE, DELETE'
- WHEN 12 THEN 'INSERT, DELETE'
- END AS trigger_event,
- CASE trg.tgenabled
- WHEN 'O' THEN 't'
- ELSE trg.tgenabled
- END AS trigger_enabled,
- obj_description(trg.oid, 'pg_trigger') AS trigger_comment
- FROM pg_trigger trg,
- pg_class tbl,
- pg_proc p
- WHERE trg.tgrelid = tbl.oid
- AND trg.tgfoid = p.oid
- AND trg.tgname = ". $db->quote($trigger, 'text');
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- 'trigger_comment' => 'text',
- 'trigger_enabled' => 'boolean',
- );
- return $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * NOTE: only supports 'table' and 'flags' if $result
- * is a table name.
- *
- * @param object|string $result MDB2_result object from a query or a
- * string containing the name of a table.
- * While this also accepts a query result
- * resource identifier, this behavior is
- * deprecated.
- * @param int $mode a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
- if (!is_resource($resource)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Could not generate result resource', __FUNCTION__);
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strtoupper';
- }
- } else {
- $case_func = 'strval';
- }
-
- $count = @pg_num_fields($resource);
- $res = array();
-
- if ($mode) {
- $res['num_fields'] = $count;
- }
-
- $db->loadModule('Datatype', null, true);
- for ($i = 0; $i < $count; $i++) {
- $res[$i] = array(
- 'table' => function_exists('pg_field_table') ? @pg_field_table($resource, $i) : '',
- 'name' => $case_func(@pg_field_name($resource, $i)),
- 'type' => @pg_field_type($resource, $i),
- 'length' => @pg_field_size($resource, $i),
- 'flags' => '',
- );
- $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
- if (PEAR::isError($mdb2type_info)) {
- return $mdb2type_info;
- }
- $res[$i]['mdb2type'] = $mdb2type_info[0][0];
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- return $res;
- }
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/Reverse/sqlite.php b/3rdparty/MDB2/Driver/Reverse/sqlite.php
deleted file mode 100644
index 811400480f..0000000000
--- a/3rdparty/MDB2/Driver/Reverse/sqlite.php
+++ /dev/null
@@ -1,611 +0,0 @@
- |
-// | Lorenzo Alberton |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-require_once 'MDB2/Driver/Reverse/Common.php';
-
-/**
- * MDB2 SQlite driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common
-{
- /**
- * Remove SQL comments from the field definition
- *
- * @access private
- */
- function _removeComments($sql) {
- $lines = explode("\n", $sql);
- foreach ($lines as $k => $line) {
- $pieces = explode('--', $line);
- if (count($pieces) > 1 && (substr_count($pieces[0], '\'') % 2) == 0) {
- $lines[$k] = substr($line, 0, strpos($line, '--'));
- }
- }
- return implode("\n", $lines);
- }
-
- /**
- *
- */
- function _getTableColumns($sql)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $start_pos = strpos($sql, '(');
- $end_pos = strrpos($sql, ')');
- $column_def = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
- // replace the decimal length-places-separator with a colon
- $column_def = preg_replace('/(\d),(\d)/', '\1:\2', $column_def);
- $column_def = $this->_removeComments($column_def);
- $column_sql = explode(',', $column_def);
- $columns = array();
- $count = count($column_sql);
- if ($count == 0) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unexpected empty table column definition list', __FUNCTION__);
- }
- $regexp = '/^\s*([^\s]+) +(CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|TINYINT|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( NULL| NOT NULL)?( UNSIGNED)?( NULL| NOT NULL)?( PRIMARY KEY)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?(\s*\-\-.*)?$/i';
- $regexp2 = '/^\s*([^ ]+) +(PRIMARY|UNIQUE|CHECK)$/i';
- for ($i=0, $j=0; $i<$count; ++$i) {
- if (!preg_match($regexp, trim($column_sql[$i]), $matches)) {
- if (!preg_match($regexp2, trim($column_sql[$i]))) {
- continue;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unexpected table column SQL definition: "'.$column_sql[$i].'"', __FUNCTION__);
- }
- $columns[$j]['name'] = trim($matches[1], implode('', $db->identifier_quoting));
- $columns[$j]['type'] = strtolower($matches[2]);
- if (isset($matches[4]) && strlen($matches[4])) {
- $columns[$j]['length'] = $matches[4];
- }
- if (isset($matches[6]) && strlen($matches[6])) {
- $columns[$j]['decimal'] = $matches[6];
- }
- if (isset($matches[8]) && strlen($matches[8])) {
- $columns[$j]['unsigned'] = true;
- }
- if (isset($matches[9]) && strlen($matches[9])) {
- $columns[$j]['autoincrement'] = true;
- }
- if (isset($matches[12]) && strlen($matches[12])) {
- $default = $matches[12];
- if (strlen($default) && $default[0]=="'") {
- $default = str_replace("''", "'", substr($default, 1, strlen($default)-2));
- }
- if ($default === 'NULL') {
- $default = null;
- }
- $columns[$j]['default'] = $default;
- } else {
- $columns[$j]['default'] = null;
- }
- if (isset($matches[7]) && strlen($matches[7])) {
- $columns[$j]['notnull'] = ($matches[7] === ' NOT NULL');
- } else if (isset($matches[9]) && strlen($matches[9])) {
- $columns[$j]['notnull'] = ($matches[9] === ' NOT NULL');
- } else if (isset($matches[13]) && strlen($matches[13])) {
- $columns[$j]['notnull'] = ($matches[13] === ' NOT NULL');
- }
- ++$j;
- }
- return $columns;
- }
-
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the stucture of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure.
- * The returned array contains an array for each field definition,
- * with (some of) these indices:
- * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name='.$db->quote($table, 'text');
- }
- $sql = $db->queryOne($query);
- if (PEAR::isError($sql)) {
- return $sql;
- }
- $columns = $this->_getTableColumns($sql);
- foreach ($columns as $column) {
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column['name'] = strtolower($column['name']);
- } else {
- $column['name'] = strtoupper($column['name']);
- }
- } else {
- $column = array_change_key_case($column, $db->options['field_case']);
- }
- if ($field_name == $column['name']) {
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (!empty($column['notnull'])) {
- $notnull = $column['notnull'];
- }
- $default = false;
- if (array_key_exists('default', $column)) {
- $default = $column['default'];
- if ((null === $default) && $notnull) {
- $default = '';
- }
- }
- $autoincrement = false;
- if (!empty($column['autoincrement'])) {
- $autoincrement = true;
- }
-
- $definition[0] = array(
- 'notnull' => $notnull,
- 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
- );
- if (null !== $length) {
- $definition[0]['length'] = $length;
- }
- if (null !== $unsigned) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (null !== $fixed) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- if ($autoincrement !== false) {
- $definition[0]['autoincrement'] = $autoincrement;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- return $definition;
- }
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table column', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the stucture of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
- }
- $query.= ' AND sql NOT NULL ORDER BY name';
- $index_name_mdb2 = $db->getIndexName($index_name);
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($index_name_mdb2), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($index_name_mdb2, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- if (PEAR::isError($sql) || empty($sql)) {
- // fallback to the given $index_name, without transformation
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($index_name), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($index_name, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- }
- if (PEAR::isError($sql)) {
- return $sql;
- }
- if (!$sql) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
-
- $sql = strtolower($sql);
- $start_pos = strpos($sql, '(');
- $end_pos = strrpos($sql, ')');
- $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
- $column_names = explode(',', $column_names);
-
- if (preg_match("/^create unique/", $sql)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
-
- $definition = array();
- $count = count($column_names);
- for ($i=0; $i<$count; ++$i) {
- $column_name = strtok($column_names[$i], ' ');
- $collation = strtok(' ');
- $definition['fields'][$column_name] = array(
- 'position' => $i+1
- );
- if (!empty($collation)) {
- $definition['fields'][$column_name]['sorting'] =
- ($collation=='ASC' ? 'ascending' : 'descending');
- }
- }
-
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the stucture of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
- }
- $query.= ' AND sql NOT NULL ORDER BY name';
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($constraint_name_mdb2), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($constraint_name_mdb2, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- if (PEAR::isError($sql) || empty($sql)) {
- // fallback to the given $index_name, without transformation
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($constraint_name), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($constraint_name, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- }
- if (PEAR::isError($sql)) {
- return $sql;
- }
- //default values, eventually overridden
- $definition = array(
- 'primary' => false,
- 'unique' => false,
- 'foreign' => false,
- 'check' => false,
- 'fields' => array(),
- 'references' => array(
- 'table' => '',
- 'fields' => array(),
- ),
- 'onupdate' => '',
- 'ondelete' => '',
- 'match' => '',
- 'deferrable' => false,
- 'initiallydeferred' => false,
- );
- if (!$sql) {
- $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name='.$db->quote($table, 'text');
- }
- $query.= " AND sql NOT NULL ORDER BY name";
- $sql = $db->queryOne($query, 'text');
- if (PEAR::isError($sql)) {
- return $sql;
- }
- if ($constraint_name == 'primary') {
- // search in table definition for PRIMARY KEYs
- if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i", $sql, $tmp)) {
- $definition['primary'] = true;
- $definition['fields'] = array();
- $column_names = explode(',', $tmp[1]);
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- return $definition;
- }
- if (preg_match("/\"([^\"]+)\"[^\,\"]+\bPRIMARY\s+KEY\b[^\,\)]*/i", $sql, $tmp)) {
- $definition['primary'] = true;
- $definition['fields'] = array();
- $column_names = explode(',', $tmp[1]);
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- return $definition;
- }
- } else {
- // search in table definition for FOREIGN KEYs
- $pattern = "/\bCONSTRAINT\b\s+%s\s+
- \bFOREIGN\s+KEY\b\s*\(([^\)]+)\)\s*
- \bREFERENCES\b\s+([^\s]+)\s*\(([^\)]+)\)\s*
- (?:\bMATCH\s*([^\s]+))?\s*
- (?:\bON\s+UPDATE\s+([^\s,\)]+))?\s*
- (?:\bON\s+DELETE\s+([^\s,\)]+))?\s*
- /imsx";
- $found_fk = false;
- if (preg_match(sprintf($pattern, $constraint_name_mdb2), $sql, $tmp)) {
- $found_fk = true;
- } elseif (preg_match(sprintf($pattern, $constraint_name), $sql, $tmp)) {
- $found_fk = true;
- }
- if ($found_fk) {
- $definition['foreign'] = true;
- $definition['match'] = 'SIMPLE';
- $definition['onupdate'] = 'NO ACTION';
- $definition['ondelete'] = 'NO ACTION';
- $definition['references']['table'] = $tmp[2];
- $column_names = explode(',', $tmp[1]);
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- $referenced_cols = explode(',', $tmp[3]);
- $colpos = 1;
- foreach ($referenced_cols as $column_name) {
- $definition['references']['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- if (isset($tmp[4])) {
- $definition['match'] = $tmp[4];
- }
- if (isset($tmp[5])) {
- $definition['onupdate'] = $tmp[5];
- }
- if (isset($tmp[6])) {
- $definition['ondelete'] = $tmp[6];
- }
- return $definition;
- }
- }
- $sql = false;
- }
- if (!$sql) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
-
- $sql = strtolower($sql);
- $start_pos = strpos($sql, '(');
- $end_pos = strrpos($sql, ')');
- $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
- $column_names = explode(',', $column_names);
-
- if (!preg_match("/^create unique/", $sql)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
-
- $definition['unique'] = true;
- $count = count($column_names);
- for ($i=0; $i<$count; ++$i) {
- $column_name = strtok($column_names[$i]," ");
- $collation = strtok(" ");
- $definition['fields'][$column_name] = array(
- 'position' => $i+1
- );
- if (!empty($collation)) {
- $definition['fields'][$column_name]['sorting'] =
- ($collation=='ASC' ? 'ascending' : 'descending');
- }
- }
-
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name as trigger_name,
- tbl_name AS table_name,
- sql AS trigger_body,
- NULL AS trigger_type,
- NULL AS trigger_event,
- NULL AS trigger_comment,
- 1 AS trigger_enabled
- FROM sqlite_master
- WHERE type='trigger'";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger), 'text');
- } else {
- $query.= ' AND name='.$db->quote($trigger, 'text');
- }
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- 'trigger_comment' => 'text',
- 'trigger_enabled' => 'boolean',
- );
- $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($def)) {
- return $def;
- }
- if (empty($def)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing trigger', __FUNCTION__);
- }
- if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims", $def['trigger_body'], $tmp)) {
- $def['trigger_type'] = strtoupper($tmp[1]);
- $def['trigger_event'] = strtoupper($tmp[2]);
- }
- return $def;
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table
- *
- * @param string $result a string containing the name of a table
- * @param int $mode a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::tableInfo()
- * @since Method available since Release 1.7.0
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_CAPABLE, null, null,
- 'This DBMS can not obtain tableInfo from result sets', __FUNCTION__);
- }
-}
-
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/mysql.php b/3rdparty/MDB2/Driver/mysql.php
deleted file mode 100644
index 1d22e61f46..0000000000
--- a/3rdparty/MDB2/Driver/mysql.php
+++ /dev/null
@@ -1,1729 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-/**
- * MDB2 MySQL driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_mysql extends MDB2_Driver_Common
-{
- // {{{ properties
-
- public $string_quoting = array(
- 'start' => "'",
- 'end' => "'",
- 'escape' => '\\',
- 'escape_pattern' => '\\',
- );
-
- public $identifier_quoting = array(
- 'start' => '`',
- 'end' => '`',
- 'escape' => '`',
- );
-
- public $sql_comments = array(
- array('start' => '-- ', 'end' => "\n", 'escape' => false),
- array('start' => '#', 'end' => "\n", 'escape' => false),
- array('start' => '/*', 'end' => '*/', 'escape' => false),
- );
-
- protected $server_capabilities_checked = false;
-
- protected $start_transaction = false;
-
- public $varchar_max_length = 255;
-
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'mysql';
- $this->dbsyntax = 'mysql';
-
- $this->supported['sequences'] = 'emulated';
- $this->supported['indexes'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['transactions'] = false;
- $this->supported['savepoints'] = false;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['current_id'] = 'emulated';
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = true;
- $this->supported['sub_selects'] = 'emulated';
- $this->supported['triggers'] = false;
- $this->supported['auto_increment'] = true;
- $this->supported['primary_key'] = true;
- $this->supported['result_introspection'] = true;
- $this->supported['prepared_statements'] = 'emulated';
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = true;
- $this->supported['new_link'] = true;
-
- $this->options['DBA_username'] = false;
- $this->options['DBA_password'] = false;
- $this->options['default_table_type'] = '';
- $this->options['max_identifiers_length'] = 64;
-
- $this->_reCheckSupportedOptions();
- }
-
- // }}}
- // {{{ _reCheckSupportedOptions()
-
- /**
- * If the user changes certain options, other capabilities may depend
- * on the new settings, so we need to check them (again).
- *
- * @access private
- */
- function _reCheckSupportedOptions()
- {
- $this->supported['transactions'] = $this->options['use_transactions'];
- $this->supported['savepoints'] = $this->options['use_transactions'];
- if ($this->options['default_table_type']) {
- switch (strtoupper($this->options['default_table_type'])) {
- case 'BLACKHOLE':
- case 'MEMORY':
- case 'ARCHIVE':
- case 'CSV':
- case 'HEAP':
- case 'ISAM':
- case 'MERGE':
- case 'MRG_ISAM':
- case 'ISAM':
- case 'MRG_MYISAM':
- case 'MYISAM':
- $this->supported['savepoints'] = false;
- $this->supported['transactions'] = false;
- $this->warnings[] = $this->options['default_table_type'] .
- ' is not a supported default table type';
- break;
- }
- }
- }
-
- // }}}
- // {{{ function setOption($option, $value)
-
- /**
- * set the option for the db class
- *
- * @param string option name
- * @param mixed value for the option
- *
- * @return mixed MDB2_OK or MDB2 Error Object
- *
- * @access public
- */
- function setOption($option, $value)
- {
- $res = parent::setOption($option, $value);
- $this->_reCheckSupportedOptions();
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- if ($this->connection) {
- $native_code = @mysql_errno($this->connection);
- $native_msg = @mysql_error($this->connection);
- } else {
- $native_code = @mysql_errno();
- $native_msg = @mysql_error();
- }
- if (is_null($error)) {
- static $ecode_map;
- if (empty($ecode_map)) {
- $ecode_map = array(
- 1000 => MDB2_ERROR_INVALID, //hashchk
- 1001 => MDB2_ERROR_INVALID, //isamchk
- 1004 => MDB2_ERROR_CANNOT_CREATE,
- 1005 => MDB2_ERROR_CANNOT_CREATE,
- 1006 => MDB2_ERROR_CANNOT_CREATE,
- 1007 => MDB2_ERROR_ALREADY_EXISTS,
- 1008 => MDB2_ERROR_CANNOT_DROP,
- 1009 => MDB2_ERROR_CANNOT_DROP,
- 1010 => MDB2_ERROR_CANNOT_DROP,
- 1011 => MDB2_ERROR_CANNOT_DELETE,
- 1022 => MDB2_ERROR_ALREADY_EXISTS,
- 1029 => MDB2_ERROR_NOT_FOUND,
- 1032 => MDB2_ERROR_NOT_FOUND,
- 1044 => MDB2_ERROR_ACCESS_VIOLATION,
- 1045 => MDB2_ERROR_ACCESS_VIOLATION,
- 1046 => MDB2_ERROR_NODBSELECTED,
- 1048 => MDB2_ERROR_CONSTRAINT,
- 1049 => MDB2_ERROR_NOSUCHDB,
- 1050 => MDB2_ERROR_ALREADY_EXISTS,
- 1051 => MDB2_ERROR_NOSUCHTABLE,
- 1054 => MDB2_ERROR_NOSUCHFIELD,
- 1060 => MDB2_ERROR_ALREADY_EXISTS,
- 1061 => MDB2_ERROR_ALREADY_EXISTS,
- 1062 => MDB2_ERROR_ALREADY_EXISTS,
- 1064 => MDB2_ERROR_SYNTAX,
- 1067 => MDB2_ERROR_INVALID,
- 1072 => MDB2_ERROR_NOT_FOUND,
- 1086 => MDB2_ERROR_ALREADY_EXISTS,
- 1091 => MDB2_ERROR_NOT_FOUND,
- 1100 => MDB2_ERROR_NOT_LOCKED,
- 1109 => MDB2_ERROR_NOT_FOUND,
- 1125 => MDB2_ERROR_ALREADY_EXISTS,
- 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- 1138 => MDB2_ERROR_INVALID,
- 1142 => MDB2_ERROR_ACCESS_VIOLATION,
- 1143 => MDB2_ERROR_ACCESS_VIOLATION,
- 1146 => MDB2_ERROR_NOSUCHTABLE,
- 1149 => MDB2_ERROR_SYNTAX,
- 1169 => MDB2_ERROR_CONSTRAINT,
- 1176 => MDB2_ERROR_NOT_FOUND,
- 1177 => MDB2_ERROR_NOSUCHTABLE,
- 1213 => MDB2_ERROR_DEADLOCK,
- 1216 => MDB2_ERROR_CONSTRAINT,
- 1217 => MDB2_ERROR_CONSTRAINT,
- 1227 => MDB2_ERROR_ACCESS_VIOLATION,
- 1235 => MDB2_ERROR_CANNOT_CREATE,
- 1299 => MDB2_ERROR_INVALID_DATE,
- 1300 => MDB2_ERROR_INVALID,
- 1304 => MDB2_ERROR_ALREADY_EXISTS,
- 1305 => MDB2_ERROR_NOT_FOUND,
- 1306 => MDB2_ERROR_CANNOT_DROP,
- 1307 => MDB2_ERROR_CANNOT_CREATE,
- 1334 => MDB2_ERROR_CANNOT_ALTER,
- 1339 => MDB2_ERROR_NOT_FOUND,
- 1356 => MDB2_ERROR_INVALID,
- 1359 => MDB2_ERROR_ALREADY_EXISTS,
- 1360 => MDB2_ERROR_NOT_FOUND,
- 1363 => MDB2_ERROR_NOT_FOUND,
- 1365 => MDB2_ERROR_DIVZERO,
- 1451 => MDB2_ERROR_CONSTRAINT,
- 1452 => MDB2_ERROR_CONSTRAINT,
- 1542 => MDB2_ERROR_CANNOT_DROP,
- 1546 => MDB2_ERROR_CONSTRAINT,
- 1582 => MDB2_ERROR_CONSTRAINT,
- 2003 => MDB2_ERROR_CONNECT_FAILED,
- 2019 => MDB2_ERROR_INVALID,
- );
- }
- if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
- $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
- $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
- $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
- } else {
- // Doing this in case mode changes during runtime.
- $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
- $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
- $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
- }
- if (isset($ecode_map[$native_code])) {
- $error = $ecode_map[$native_code];
- }
- }
- return array($error, $native_code, $native_msg);
- }
-
- // }}}
- // {{{ escape()
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- if ($escape_wildcards) {
- $text = $this->escapePattern($text);
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $text = @mysql_real_escape_string($text, $connection);
- return $text;
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- $this->_getServerCapabilities();
- if (!is_null($savepoint)) {
- if (!$this->supports('savepoints')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
- }
- $query = 'SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- } elseif ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0';
- $result = $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- if (!$this->supports('savepoints')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
- $server_info = $this->getServerVersion();
- if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
- return MDB2_OK;
- }
- $query = 'RELEASE SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- if (!$this->supports('transactions')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'transactions are not supported', __FUNCTION__);
- }
-
- $result = $this->_doQuery('COMMIT', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!$this->start_transaction) {
- $query = 'SET AUTOCOMMIT = 1';
- $result = $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- if (!$this->supports('savepoints')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
- $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $query = 'ROLLBACK';
- $result = $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!$this->start_transaction) {
- $query = 'SET AUTOCOMMIT = 1';
- $result = $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @param array some transaction options:
- * 'wait' => 'WAIT' | 'NO WAIT'
- * 'rw' => 'READ WRITE' | 'READ ONLY'
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation, $options = array())
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- if (!$this->supports('transactions')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'transactions are not supported', __FUNCTION__);
- }
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- case 'SERIALIZABLE':
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ _doConnect()
-
- /**
- * do the grunt work of the connect
- *
- * @return connection on success or MDB2 Error Object on failure
- * @access protected
- */
- function _doConnect($username, $password, $persistent = false)
- {
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- $params = array();
- $unix = ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix');
- if (empty($this->dsn['hostspec'])) {
- $this->dsn['hostspec'] = $unix ? '' : 'localhost';
- }
- if ($this->dsn['hostspec']) {
- $params[0] = $this->dsn['hostspec'] . ($this->dsn['port'] ? ':' . $this->dsn['port'] : '');
- } else {
- $params[0] = ':' . $this->dsn['socket'];
- }
- $params[] = $username ? $username : null;
- $params[] = $password ? $password : null;
- if (!$persistent) {
- if ($this->_isNewLinkSet()) {
- $params[] = true;
- } else {
- $params[] = false;
- }
- }
- if (version_compare(phpversion(), '4.3.0', '>=')) {
- $params[] = isset($this->dsn['client_flags'])
- ? $this->dsn['client_flags'] : null;
- }
- $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
-
- $connection = @call_user_func_array($connect_function, $params);
- if (!$connection) {
- if (($err = @mysql_error()) != '') {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- $err, __FUNCTION__);
- } else {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
- }
-
- if (!empty($this->dsn['charset'])) {
- $result = $this->setCharset($this->dsn['charset'], $connection);
- if (PEAR::isError($result)) {
- $this->disconnect(false);
- return $result;
- }
- }
-
- return $connection;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return MDB2_OK on success, MDB2 Error Object on failure
- * @access public
- */
- function connect()
- {
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->opened_persistent == $this->options['persistent']
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- $connection = $this->_doConnect(
- $this->dsn['username'],
- $this->dsn['password'],
- $this->options['persistent']
- );
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = '';
- $this->opened_persistent = $this->options['persistent'];
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
-
- if ($this->database_name) {
- if ($this->database_name != $this->connected_database_name) {
- if (!@mysql_select_db($this->database_name, $connection)) {
- $err = $this->raiseError(null, null, null,
- 'Could not select the database: '.$this->database_name, __FUNCTION__);
- return $err;
- }
- $this->connected_database_name = $this->database_name;
- }
- }
-
- $this->_getServerCapabilities();
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ setCharset()
-
- /**
- * Set the charset on the current connection
- *
- * @param string charset (or array(charset, collation))
- * @param resource connection handle
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function setCharset($charset, $connection = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- $collation = null;
- if (is_array($charset) && 2 == count($charset)) {
- $collation = array_pop($charset);
- $charset = array_pop($charset);
- }
- $client_info = mysql_get_client_info();
- if (function_exists('mysql_set_charset') && version_compare($client_info, '5.0.6')) {
- if (!$result = mysql_set_charset($charset, $connection)) {
- $err = $this->raiseError(null, null, null,
- 'Could not set client character set', __FUNCTION__);
- return $err;
- }
- return $result;
- }
- $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'";
- if (!is_null($collation)) {
- $query .= " COLLATE '".mysql_real_escape_string($collation, $connection)."'";
- }
- return $this->_doQuery($query, true, $connection);
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- $connection = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $result = @mysql_select_db($name, $connection);
- @mysql_close($connection);
-
- return $result;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- $ok = @mysql_close($this->connection);
- if (!$ok) {
- return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
- null, null, null, __FUNCTION__);
- }
- }
- } else {
- return false;
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ standaloneQuery()
-
- /**
- * execute a query as DBA
- *
- * @param string $query the SQL query
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param boolean $is_manip if the query is a manipulation query
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function standaloneQuery($query, $types = null, $is_manip = false)
- {
- $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
- $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
- $connection = $this->_doConnect($user, $pass, $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $result = $this->_doQuery($query, $is_manip, $connection, $this->database_name);
- if (!PEAR::isError($result)) {
- $result = $this->_affectedRows($connection, $result);
- }
-
- @mysql_close($connection);
- return $result;
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->options['disable_query']) {
- $result = $is_manip ? 0 : null;
- return $result;
- }
-
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- if (is_null($database_name)) {
- $database_name = $this->database_name;
- }
-
- if ($database_name) {
- if ($database_name != $this->connected_database_name) {
- if (!@mysql_select_db($database_name, $connection)) {
- $err = $this->raiseError(null, null, null,
- 'Could not select the database: '.$database_name, __FUNCTION__);
- return $err;
- }
- $this->connected_database_name = $database_name;
- }
- }
-
- $function = $this->options['result_buffering']
- ? 'mysql_query' : 'mysql_unbuffered_query';
- $result = @$function($query, $connection);
- if (!$result && 0 !== mysql_errno($connection)) {
- $err = $this->raiseError(null, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @mysql_affected_rows($connection);
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
- // "DELETE FROM table" gives 0 affected rows in MySQL.
- // This little hack lets you know how many rows were deleted.
- if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
- $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
- 'DELETE FROM \1 WHERE 1=1', $query);
- }
- }
- if ($limit > 0
- && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
- ) {
- $query = rtrim($query);
- if (substr($query, -1) == ';') {
- $query = substr($query, 0, -1);
- }
-
- // LIMIT doesn't always come last in the query
- // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
- $after = '';
- if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {
- $after = $matches[0];
- $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
- } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {
- $after = $matches[0];
- $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
- } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {
- $after = $matches[0];
- $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
- }
-
- if ($is_manip) {
- return $query . " LIMIT $limit" . $after;
- } else {
- return $query . " LIMIT $offset, $limit" . $after;
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } else {
- $server_info = @mysql_get_server_info($connection);
- }
- if (!$server_info) {
- return $this->raiseError(null, null, null,
- 'Could not get server information', __FUNCTION__);
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native) {
- $tmp = explode('.', $server_info, 3);
- if (isset($tmp[2]) && strpos($tmp[2], '-')) {
- $tmp2 = explode('-', @$tmp[2], 2);
- } else {
- $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
- $tmp2[1] = null;
- }
- $server_info = array(
- 'major' => isset($tmp[0]) ? $tmp[0] : null,
- 'minor' => isset($tmp[1]) ? $tmp[1] : null,
- 'patch' => $tmp2[0],
- 'extra' => $tmp2[1],
- 'native' => $server_info,
- );
- }
- return $server_info;
- }
-
- // }}}
- // {{{ _getServerCapabilities()
-
- /**
- * Fetch some information about the server capabilities
- * (transactions, subselects, prepared statements, etc).
- *
- * @access private
- */
- function _getServerCapabilities()
- {
- if (!$this->server_capabilities_checked) {
- $this->server_capabilities_checked = true;
-
- //set defaults
- $this->supported['sub_selects'] = 'emulated';
- $this->supported['prepared_statements'] = 'emulated';
- $this->supported['triggers'] = false;
- $this->start_transaction = false;
- $this->varchar_max_length = 255;
-
- $server_info = $this->getServerVersion();
- if (is_array($server_info)) {
- $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'];
-
- if (!version_compare($server_version, '4.1.0', '<')) {
- $this->supported['sub_selects'] = true;
- $this->supported['prepared_statements'] = true;
- }
-
- // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)
- if (version_compare($server_version, '4.1.0', '>=')) {
- if (version_compare($server_version, '4.1.1', '<')) {
- $this->supported['savepoints'] = false;
- }
- } elseif (version_compare($server_version, '4.0.14', '<')) {
- $this->supported['savepoints'] = false;
- }
-
- if (!version_compare($server_version, '4.0.11', '<')) {
- $this->start_transaction = true;
- }
-
- if (!version_compare($server_version, '5.0.3', '<')) {
- $this->varchar_max_length = 65532;
- }
-
- if (!version_compare($server_version, '5.0.2', '<')) {
- $this->supported['triggers'] = true;
- }
- }
- }
- }
-
- // }}}
- // {{{ function _skipUserDefinedVariable($query, $position)
-
- /**
- * Utility method, used by prepare() to avoid misinterpreting MySQL user
- * defined variables (SELECT @x:=5) for placeholders.
- * Check if the placeholder is a false positive, i.e. if it is an user defined
- * variable instead. If so, skip it and advance the position, otherwise
- * return the current position, which is valid
- *
- * @param string $query
- * @param integer $position current string cursor position
- * @return integer $new_position
- * @access protected
- */
- function _skipUserDefinedVariable($query, $position)
- {
- $found = strpos(strrev(substr($query, 0, $position)), '@');
- if ($found === false) {
- return $position;
- }
- $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
- $substring = substr($query, $pos, $position - $pos + 2);
- if (preg_match('/^@\w+\s*:=$/', $substring)) {
- return $position + 1; //found an user defined variable: skip it
- }
- return $position;
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string $query the query to prepare
- * @param mixed $types array that contains the types of the placeholders
- * @param mixed $result_types array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
- * @return mixed resource handle for the prepared query on success, a MDB2
- * error on failure
- * @access public
- * @see bindParam, execute
- */
- function prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- // connect to get server capabilities (http://pear.php.net/bugs/16147)
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- if ($this->options['emulate_prepared']
- || $this->supported['prepared_statements'] !== true
- ) {
- return parent::prepare($query, $types, $result_types, $lobs);
- }
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = 0;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (is_null($placeholder_type)) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (PEAR::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- //make sure this is not part of an user defined variable
- $new_pos = $this->_skipUserDefinedVariable($query, $position);
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (is_null($placeholder_type)) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- }
- if ($placeholder_type == ':') {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $parameter = preg_replace($regexp, '\\1', $query);
- if ($parameter === '') {
- $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- $positions[$p_position] = $parameter;
- $query = substr_replace($query, '?', $position, strlen($parameter)+1);
- } else {
- $positions[$p_position] = count($positions);
- }
- $position = $p_position + 1;
- } else {
- $position = $p_position;
- }
- }
-
- static $prep_statement_counter = 1;
- $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
- $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
- $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
- $statement = $this->_doQuery($query, true, $connection);
- if (PEAR::isError($statement)) {
- return $statement;
- }
-
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ replace()
-
- /**
- * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
- * query, except that if there is already a row in the table with the same
- * key field values, the old row is deleted before the new row is inserted.
- *
- * The REPLACE type of query does not make part of the SQL standards. Since
- * practically only MySQL implements it natively, this type of query is
- * emulated through this method for other DBMS using standard types of
- * queries inside a transaction to assure the atomicity of the operation.
- *
- * @access public
- *
- * @param string $table name of the table on which the REPLACE query will
- * be executed.
- * @param array $fields associative array that describes the fields and the
- * values that will be inserted or updated in the specified table. The
- * indexes of the array are the names of all the fields of the table. The
- * values of the array are also associative arrays that describe the
- * values and other properties of the table fields.
- *
- * Here follows a list of field properties that need to be specified:
- *
- * value:
- * Value to be assigned to the specified field. This value may be
- * of specified in database independent type format as this
- * function can perform the necessary datatype conversions.
- *
- * Default:
- * this property is required unless the Null property
- * is set to 1.
- *
- * type
- * Name of the type of the field. Currently, all types Metabase
- * are supported except for clob and blob.
- *
- * Default: no type conversion
- *
- * null
- * Boolean property that indicates that the value for this field
- * should be set to null.
- *
- * The default value for fields missing in INSERT queries may be
- * specified the definition of a table. Often, the default value
- * is already null, but since the REPLACE may be emulated using
- * an UPDATE query, make sure that all fields of the table are
- * listed in this function argument array.
- *
- * Default: 0
- *
- * key
- * Boolean property that indicates that this field should be
- * handled as a primary key or at least as part of the compound
- * unique index of the table that will determine the row that will
- * updated if it exists or inserted a new row otherwise.
- *
- * This function will fail if no key field is specified or if the
- * value of a key field is set to null because fields that are
- * part of unique index they may not be null.
- *
- * Default: 0
- *
- * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function replace($table, $fields)
- {
- $count = count($fields);
- $query = $values = '';
- $keys = $colnum = 0;
- for (reset($fields); $colnum < $count; next($fields), $colnum++) {
- $name = key($fields);
- if ($colnum > 0) {
- $query .= ',';
- $values.= ',';
- }
- $query.= $this->quoteIdentifier($name, true);
- if (isset($fields[$name]['null']) && $fields[$name]['null']) {
- $value = 'NULL';
- } else {
- $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
- $value = $this->quote($fields[$name]['value'], $type);
- if (PEAR::isError($value)) {
- return $value;
- }
- }
- $values.= $value;
- if (isset($fields[$name]['key']) && $fields[$name]['key']) {
- if ($value === 'NULL') {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'key value '.$name.' may not be NULL', __FUNCTION__);
- }
- $keys++;
- }
- }
- if ($keys == 0) {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'not specified which fields are keys', __FUNCTION__);
- }
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $table = $this->quoteIdentifier($table, true);
- $query = "REPLACE INTO $table ($query) VALUES ($values)";
- $result = $this->_doQuery($query, true, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->_affectedRows($connection, $result);
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- *
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
- $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result = $this->_doQuery($query, true);
- $this->popExpect();
- $this->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result, null, null,
- 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
- } else {
- return $this->nextID($seq_name, false);
- }
- }
- return $result;
- }
- $value = $this->lastInsertID();
- if (is_numeric($value)) {
- $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
- $result = $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
- }
- }
- return $value;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
- // not casting to integer to handle BIGINT http://pear.php.net/bugs/bug.php?id=17650
- return $this->queryOne('SELECT LAST_INSERT_ID()');
- }
-
- // }}}
- // {{{ currID()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function currID($seq_name)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
- $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
- return $this->queryOne($query, 'integer');
- }
-}
-
-/**
- * MDB2 MySQL result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Result_mysql extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (!is_null($rownum)) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ( $fetchmode == MDB2_FETCHMODE_ASSOC
- || $fetchmode == MDB2_FETCHMODE_OBJECT
- ) {
- $row = @mysql_fetch_assoc($this->result);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- $row = @mysql_fetch_row($this->result);
- }
-
- if (!$row) {
- if ($this->result === false) {
- $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- return null;
- }
- $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if ( ( $fetchmode != MDB2_FETCHMODE_ASSOC
- && $fetchmode != MDB2_FETCHMODE_OBJECT)
- && !empty($this->types)
- ) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC
- || $fetchmode == MDB2_FETCHMODE_OBJECT)
- && !empty($this->types_assoc)
- ) {
- $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $rowObj = new $object_class($row);
- $row = $rowObj;
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @mysql_field_name($this->result, $column);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- * @access public
- */
- function numCols()
- {
- $cols = @mysql_num_fields($this->result);
- if (is_null($cols)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- return $cols;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return boolean true on success, false if result is invalid
- * @access public
- */
- function free()
- {
- if (is_resource($this->result) && $this->db->connection) {
- $free = @mysql_free_result($this->result);
- if ($free === false) {
- return $this->db->raiseError(null, null, null,
- 'Could not free result', __FUNCTION__);
- }
- }
- $this->result = false;
- return MDB2_OK;
- }
-}
-
-/**
- * MDB2 MySQL buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_BufferedResult_mysql extends MDB2_Result_mysql
-{
- // }}}
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return MDB2_OK;
- }
- return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- $numrows = $this->numRows();
- if (PEAR::isError($numrows)) {
- return $numrows;
- }
- return $this->rownum < ($numrows - 1);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- $rows = @mysql_num_rows($this->result);
- if (false === $rows) {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return 0;
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get row count', __FUNCTION__);
- }
- return $rows;
- }
-
- // }}}
-}
-
-/**
- * MDB2 MySQL statement driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Statement_mysql extends MDB2_Statement_Common
-{
- // {{{ _execute()
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access private
- */
- function _execute($result_class = true, $result_wrap_class = true)
- {
- if (is_null($this->statement)) {
- $result = parent::_execute($result_class, $result_wrap_class);
- return $result;
- }
- $this->db->last_query = $this->query;
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
- if ($this->db->getOption('disable_query')) {
- $result = $this->is_manip ? 0 : null;
- return $result;
- }
-
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $query = 'EXECUTE '.$this->statement;
- if (!empty($this->positions)) {
- $parameters = array();
- foreach ($this->positions as $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $close = false;
- $value = $this->values[$parameter];
- $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
- if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']) {
- if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
- if ($match[1] == 'file://') {
- $value = $match[2];
- }
- $value = @fopen($value, 'r');
- $close = true;
- }
- if (is_resource($value)) {
- $data = '';
- while (!@feof($value)) {
- $data.= @fread($value, $this->db->options['lob_buffer_length']);
- }
- if ($close) {
- @fclose($value);
- }
- $value = $data;
- }
- }
- $quoted = $this->db->quote($value, $type);
- if (PEAR::isError($quoted)) {
- return $quoted;
- }
- $param_query = 'SET @'.$parameter.' = '.$quoted;
- $result = $this->db->_doQuery($param_query, true, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $query.= ' USING @'.implode(', @', array_values($this->positions));
- }
-
- $result = $this->db->_doQuery($query, $this->is_manip, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($this->is_manip) {
- $affected_rows = $this->db->_affectedRows($connection, $result);
- return $affected_rows;
- }
-
- $result = $this->db->_wrapResult($result, $this->result_types,
- $result_class, $result_wrap_class, $this->limit, $this->offset);
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function free()
- {
- if (is_null($this->positions)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
- $result = MDB2_OK;
-
- if (!is_null($this->statement)) {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $query = 'DEALLOCATE PREPARE '.$this->statement;
- $result = $this->db->_doQuery($query, true, $connection);
- }
-
- parent::free();
- return $result;
- }
-}
-?>
diff --git a/3rdparty/MDB2/Driver/oci8.php b/3rdparty/MDB2/Driver/oci8.php
deleted file mode 100644
index a1eefc94d1..0000000000
--- a/3rdparty/MDB2/Driver/oci8.php
+++ /dev/null
@@ -1,1700 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-
-// $Id: oci8.php 295587 2010-02-28 17:16:38Z quipo $
-
-/**
- * MDB2 OCI8 driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_oci8 extends MDB2_Driver_Common
-{
- // {{{ properties
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '@');
-
- var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
-
- var $uncommitedqueries = 0;
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'oci8';
- $this->dbsyntax = 'oci8';
-
- $this->supported['sequences'] = true;
- $this->supported['indexes'] = true;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['current_id'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['transactions'] = true;
- $this->supported['savepoints'] = true;
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = 'emulated';
- $this->supported['sub_selects'] = true;
- $this->supported['triggers'] = true;
- $this->supported['auto_increment'] = false; // implementation is broken
- $this->supported['primary_key'] = true;
- $this->supported['result_introspection'] = true;
- $this->supported['prepared_statements'] = true;
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = true;
- $this->supported['new_link'] = true;
-
- $this->options['DBA_username'] = false;
- $this->options['DBA_password'] = false;
- $this->options['database_name_prefix'] = false;
- $this->options['emulate_database'] = true;
- $this->options['default_tablespace'] = false;
- $this->options['default_text_field_length'] = 2000;
- $this->options['lob_allow_url_include'] = false;
- $this->options['result_prefetching'] = false;
- $this->options['max_identifiers_length'] = 30;
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- if (is_resource($error)) {
- $error_data = @OCIError($error);
- $error = null;
- } elseif ($this->connection) {
- $error_data = @OCIError($this->connection);
- } else {
- $error_data = @OCIError();
- }
- $native_code = $error_data['code'];
- $native_msg = $error_data['message'];
- if (null === $error) {
- static $ecode_map;
- if (empty($ecode_map)) {
- $ecode_map = array(
- 1 => MDB2_ERROR_CONSTRAINT,
- 900 => MDB2_ERROR_SYNTAX,
- 904 => MDB2_ERROR_NOSUCHFIELD,
- 911 => MDB2_ERROR_SYNTAX, //invalid character
- 913 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- 921 => MDB2_ERROR_SYNTAX,
- 923 => MDB2_ERROR_SYNTAX,
- 942 => MDB2_ERROR_NOSUCHTABLE,
- 955 => MDB2_ERROR_ALREADY_EXISTS,
- 1400 => MDB2_ERROR_CONSTRAINT_NOT_NULL,
- 1401 => MDB2_ERROR_INVALID,
- 1407 => MDB2_ERROR_CONSTRAINT_NOT_NULL,
- 1418 => MDB2_ERROR_NOT_FOUND,
- 1435 => MDB2_ERROR_NOT_FOUND,
- 1476 => MDB2_ERROR_DIVZERO,
- 1722 => MDB2_ERROR_INVALID_NUMBER,
- 2289 => MDB2_ERROR_NOSUCHTABLE,
- 2291 => MDB2_ERROR_CONSTRAINT,
- 2292 => MDB2_ERROR_CONSTRAINT,
- 2449 => MDB2_ERROR_CONSTRAINT,
- 4081 => MDB2_ERROR_ALREADY_EXISTS, //trigger already exists
- 24344 => MDB2_ERROR_SYNTAX, //success with compilation error
- );
- }
- if (isset($ecode_map[$native_code])) {
- $error = $ecode_map[$native_code];
- }
- }
- return array($error, $native_code, $native_msg);
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (null !== $savepoint) {
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
- }
- $query = 'SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
- if ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $this->in_transaction = true;
- ++$this->uncommitedqueries;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (null !== $savepoint) {
- return MDB2_OK;
- }
-
- if ($this->uncommitedqueries) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- if (!@OCICommit($connection)) {
- return $this->raiseError(null, null, null,
- 'Unable to commit transaction', __FUNCTION__);
- }
- $this->uncommitedqueries = 0;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (null !== $savepoint) {
- $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- if ($this->uncommitedqueries) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- if (!@OCIRollback($connection)) {
- return $this->raiseError(null, null, null,
- 'Unable to rollback transaction', __FUNCTION__);
- }
- $this->uncommitedqueries = 0;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @param array some transaction options:
- * 'wait' => 'WAIT' | 'NO WAIT'
- * 'rw' => 'READ WRITE' | 'READ ONLY'
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation, $options = array())
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- $isolation = 'READ COMMITTED';
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- $isolation = 'SERIALIZABLE';
- case 'SERIALIZABLE':
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "ALTER SESSION ISOLATION LEVEL $isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ _doConnect()
-
- /**
- * do the grunt work of the connect
- *
- * @return connection on success or MDB2 Error Object on failure
- * @access protected
- */
- function _doConnect($username, $password, $persistent = false)
- {
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- $sid = '';
-
- if (!empty($this->dsn['service']) && $this->dsn['hostspec']) {
- //oci8://username:password@foo.example.com[:port]/?service=service
- // service name is given, it is assumed that hostspec is really a
- // hostname, we try to construct an oracle connection string from this
- $port = $this->dsn['port'] ? $this->dsn['port'] : 1521;
- $sid = sprintf("(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)
- (HOST=%s) (PORT=%s)))
- (CONNECT_DATA=(SERVICE_NAME=%s)))",
- $this->dsn['hostspec'],
- $port,
- $this->dsn['service']
- );
- } elseif ($this->dsn['hostspec']) {
- // we are given something like 'oci8://username:password@foo/'
- // we have hostspec but not a service name, now we assume that
- // hostspec is a tnsname defined in tnsnames.ora
- $sid = $this->dsn['hostspec'];
- if (isset($this->dsn['port']) && $this->dsn['port']) {
- $sid = $sid.':'.$this->dsn['port'];
- }
- } else {
- // oci://username:password@
- // if everything fails, we have to rely on environment variables
- // not before a check to 'emulate_database'
- if (!$this->options['emulate_database'] && $this->database_name) {
- $sid = $this->database_name;
- } elseif (getenv('ORACLE_SID')) {
- $sid = getenv('ORACLE_SID');
- } elseif ($sid = getenv('TWO_TASK')) {
- $sid = getenv('TWO_TASK');
- } else {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'not a valid connection string or environment variable [ORACLE_SID|TWO_TASK] not set',
- __FUNCTION__);
- }
- }
-
- if (function_exists('oci_connect')) {
- if ($this->_isNewLinkSet()) {
- $connect_function = 'oci_new_connect';
- } else {
- $connect_function = $persistent ? 'oci_pconnect' : 'oci_connect';
- }
-
- $charset = empty($this->dsn['charset']) ? null : $this->dsn['charset'];
- $session_mode = empty($this->dsn['session_mode']) ? null : $this->dsn['session_mode'];
- $connection = @$connect_function($username, $password, $sid, $charset, $session_mode);
- $error = @OCIError();
- if (isset($error['code']) && $error['code'] == 12541) {
- // Couldn't find TNS listener. Try direct connection.
- $connection = @$connect_function($username, $password, null, $charset);
- }
- } else {
- $connect_function = $persistent ? 'OCIPLogon' : 'OCILogon';
- $connection = @$connect_function($username, $password, $sid);
-
- if (!empty($this->dsn['charset'])) {
- $result = $this->setCharset($this->dsn['charset'], $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!$connection) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if (empty($this->dsn['disable_iso_date'])) {
- $query = "ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'";
- $err = $this->_doQuery($query, true, $connection);
- if (PEAR::isError($err)) {
- $this->disconnect(false);
- return $err;
- }
- }
-
- $query = "ALTER SESSION SET NLS_NUMERIC_CHARACTERS='. '";
- $err = $this->_doQuery($query, true, $connection);
- if (PEAR::isError($err)) {
- $this->disconnect(false);
- return $err;
- }
-
- return $connection;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return MDB2_OK on success, MDB2 Error Object on failure
- * @access public
- */
- function connect()
- {
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->opened_persistent == $this->options['persistent']
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- if ($this->database_name && $this->options['emulate_database']) {
- $this->dsn['username'] = $this->options['database_name_prefix'].$this->database_name;
- }
-
- $connection = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = '';
- $this->opened_persistent = $this->options['persistent'];
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
-
- if ($this->database_name) {
- if ($this->database_name != $this->connected_database_name) {
- $query = 'ALTER SESSION SET CURRENT_SCHEMA = "' .strtoupper($this->database_name) .'"';
- $result = $this->_doQuery($query);
- if (PEAR::isError($result)) {
- $err = $this->raiseError($result, null, null,
- 'Could not select the database: '.$this->database_name, __FUNCTION__);
- return $err;
- }
- $this->connected_database_name = $this->database_name;
- }
- }
-
- $this->as_keyword = ' ';
- $server_info = $this->getServerVersion();
- if (is_array($server_info)) {
- if ($server_info['major'] >= '10') {
- $this->as_keyword = ' AS ';
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- $connection = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $query = 'ALTER SESSION SET CURRENT_SCHEMA = "' .strtoupper($name) .'"';
- $result = $this->_doQuery($query, true, $connection, false);
- if (PEAR::isError($result)) {
- if (!MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) {
- return $result;
- }
- return false;
- }
- return true;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- $ok = false;
- if (function_exists('oci_close')) {
- $ok = @oci_close($this->connection);
- } else {
- $ok = @OCILogOff($this->connection);
- }
- if (!$ok) {
- return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
- null, null, null, __FUNCTION__);
- }
- }
- $this->uncommitedqueries = 0;
- } else {
- return false;
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ standaloneQuery()
-
- /**
- * execute a query as DBA
- *
- * @param string $query the SQL query
- * @param mixed $types array containing the types of the columns in
- * the result set
- * @param boolean $is_manip if the query is a manipulation query
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function standaloneQuery($query, $types = null, $is_manip = false)
- {
- $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
- $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
- $connection = $this->_doConnect($user, $pass, $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $result = $this->_doQuery($query, $is_manip, $connection, false);
- if (!PEAR::isError($result)) {
- if ($is_manip) {
- $result = $this->_affectedRows($connection, $result);
- } else {
- $result = $this->_wrapResult($result, $types, true, false, $limit, $offset);
- }
- }
-
- @OCILogOff($connection);
- return $result;
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if (preg_match('/^\s*SELECT/i', $query)) {
- if (!preg_match('/\sFROM\s/i', $query)) {
- $query.= " FROM dual";
- }
- if ($limit > 0) {
- // taken from http://svn.ez.no/svn/ezcomponents/packages/Database
- $max = $offset + $limit;
- if ($offset > 0) {
- $min = $offset + 1;
- $query = "SELECT * FROM (SELECT a.*, ROWNUM mdb2rn FROM ($query) a WHERE ROWNUM <= $max) WHERE mdb2rn >= $min";
- } else {
- $query = "SELECT a.* FROM ($query) a WHERE ROWNUM <= $max";
- }
- }
- }
- return $query;
- }
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a generic type
- * field to be used in statement like CREATE TABLE, without the field name
- * and type values (ie. just the character set, default value, if the
- * field is permitted to be NULL or not, and the collation options).
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Text value to be used as default for this field.
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * charset
- * Text value with the default CHARACTER SET for this field.
- * collation
- * Text value with the default COLLATION for this field.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field's options.
- * @access protected
- */
- function _getDeclarationOptions($field)
- {
- $charset = empty($field['charset']) ? '' :
- ' '.$this->_getCharsetFieldDeclaration($field['charset']);
-
- $notnull = empty($field['notnull']) ? ' NULL' : ' NOT NULL';
- $default = '';
- if (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $valid_default_values = $this->getValidTypes();
- $field['default'] = $valid_default_values[$field['type']];
- if ($field['default'] === '' && ($db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)) {
- $field['default'] = ' ';
- }
- }
- if (null !== $field['default']) {
- $default = ' DEFAULT ' . $this->quote($field['default'], $field['type']);
- }
- }
-
- $collation = empty($field['collation']) ? '' :
- ' '.$this->_getCollationFieldDeclaration($field['collation']);
-
- return $charset.$default.$notnull.$collation;
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->getOption('disable_query')) {
- if ($is_manip) {
- return 0;
- }
- return null;
- }
-
- if (null === $connection) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
-
- $query = str_replace("\r\n", "\n", $query); //for fixing end-of-line character in the PL/SQL in windows
- $result = @OCIParse($connection, $query);
- if (!$result) {
- $err = $this->raiseError(null, null, null,
- 'Could not create statement', __FUNCTION__);
- return $err;
- }
-
- $mode = $this->in_transaction ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
- if (!@OCIExecute($result, $mode)) {
- $err = $this->raiseError($result, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- }
-
- if (is_numeric($this->options['result_prefetching'])) {
- @ocisetprefetch($result, $this->options['result_prefetching']);
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (null === $connection) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @OCIRowCount($result);
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } else {
- $server_info = @ociserverversion($connection);
- }
- if (!$server_info) {
- return $this->raiseError(null, null, null,
- 'Could not get server information', __FUNCTION__);
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native) {
- if (!preg_match('/ (\d+)\.(\d+)\.(\d+)\.([\d\.]+) /', $server_info, $tmp)) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'Could not parse version information:'.$server_info, __FUNCTION__);
- }
- $server_info = array(
- 'major' => $tmp[1],
- 'minor' => $tmp[2],
- 'patch' => $tmp[3],
- 'extra' => $tmp[4],
- 'native' => $server_info,
- );
- }
- return $server_info;
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string $query the query to prepare
- * @param mixed $types array that contains the types of the placeholders
- * @param mixed $result_types array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
- * @return mixed resource handle for the prepared query on success, a MDB2
- * error on failure
- * @access public
- * @see bindParam, execute
- */
- function prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- if ($this->options['emulate_prepared']) {
- return parent::prepare($query, $types, $result_types, $lobs);
- }
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = 0;
- $parameter = -1;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (null === $placeholder_type) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (PEAR::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (null === $placeholder_type) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- if (!empty($types) && is_array($types)) {
- if ($placeholder_type == ':') {
- if (is_int(key($types))) {
- $types_tmp = $types;
- $types = array();
- $count = -1;
- }
- } else {
- $types = array_values($types);
- }
- }
- }
- if ($placeholder_type == ':') {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $parameter = preg_replace($regexp, '\\1', $query);
- if ($parameter === '') {
- $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- // use parameter name in type array
- if (isset($count) && isset($types_tmp[++$count])) {
- $types[$parameter] = $types_tmp[$count];
- }
- $length = strlen($parameter) + 1;
- } else {
- ++$parameter;
- //$length = strlen($parameter);
- $length = 1; // strlen('?')
- }
- if (!in_array($parameter, $positions)) {
- $positions[] = $parameter;
- }
- if (isset($types[$parameter])
- && ($types[$parameter] == 'clob' || $types[$parameter] == 'blob')
- ) {
- if (!isset($lobs[$parameter])) {
- $lobs[$parameter] = $parameter;
- }
- $value = $this->quote(true, $types[$parameter]);
- if (PEAR::isError($value)) {
- return $value;
- }
- $query = substr_replace($query, $value, $p_position, $length);
- $position = $p_position + strlen($value) - 1;
- } elseif ($placeholder_type == '?') {
- $query = substr_replace($query, ':'.$parameter, $p_position, 1);
- $position = $p_position + $length;
- } else {
- $position = $p_position + 1;
- }
- } else {
- $position = $p_position;
- }
- }
- if (is_array($lobs)) {
- $columns = $variables = '';
- foreach ($lobs as $parameter => $field) {
- $columns.= ($columns ? ', ' : ' RETURNING ').$field;
- $variables.= ($variables ? ', ' : ' INTO ').':'.$parameter;
- }
- $query.= $columns.$variables;
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $statement = @OCIParse($connection, $query);
- if (!$statement) {
- $err = $this->raiseError(null, null, null,
- 'Could not create statement', __FUNCTION__);
- return $err;
- }
-
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $query = "SELECT $sequence_name.nextval FROM DUAL";
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result = $this->queryOne($query, 'integer');
- $this->popExpect();
- $this->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->nextId($seq_name, false);
- }
- }
- return $result;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- $old_seq = $table.(empty($field) ? '' : '_'.$field);
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($table), true);
- $result = $this->queryOne("SELECT $sequence_name.currval", 'integer');
- if (PEAR::isError($result)) {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($old_seq), true);
- $result = $this->queryOne("SELECT $sequence_name.currval", 'integer');
- }
-
- return $result;
- }
-
- // }}}
- // {{{ currId()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2_Error or id
- * @access public
- */
- function currId($seq_name)
- {
- $sequence_name = $this->getSequenceName($seq_name);
- $query = 'SELECT (last_number-1) FROM all_sequences';
- $query.= ' WHERE sequence_name='.$this->quote($sequence_name, 'text');
- $query.= ' OR sequence_name='.$this->quote(strtoupper($sequence_name), 'text');
- return $this->queryOne($query, 'integer');
- }
-}
-
-/**
- * MDB2 OCI8 result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Result_oci8 extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (null !== $rownum) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- @OCIFetchInto($this->result, $row, OCI_ASSOC+OCI_RETURN_NULLS);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- @OCIFetchInto($this->result, $row, OCI_RETURN_NULLS);
- }
- if (!$row) {
- if (false === $this->result) {
- $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- return null;
- }
- // remove additional column at the end
- if ($this->offset > 0) {
- array_pop($row);
- }
- $mode = 0;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if (!empty($this->types)) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $rowObj = new $object_class($row);
- $row = $rowObj;
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @OCIColumnName($this->result, $column + 1);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- * @access public
- */
- function numCols()
- {
- $cols = @OCINumCols($this->result);
- if (null === $cols) {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- }
- if (null === $this->result) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- if ($this->offset > 0) {
- --$cols;
- }
- return $cols;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Free the internal resources associated with $result.
- *
- * @return boolean true on success, false if $result is invalid
- * @access public
- */
- function free()
- {
- if (is_resource($this->result) && $this->db->connection) {
- $free = @OCIFreeCursor($this->result);
- if (false === $free) {
- return $this->db->raiseError(null, null, null,
- 'Could not free result', __FUNCTION__);
- }
- }
- $this->result = false;
- return MDB2_OK;
-
- }
-}
-
-/**
- * MDB2 OCI8 buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_BufferedResult_oci8 extends MDB2_Result_oci8
-{
- var $buffer;
- var $buffer_rownum = - 1;
-
- // {{{ _fillBuffer()
-
- /**
- * Fill the row buffer
- *
- * @param int $rownum row number upto which the buffer should be filled
- if the row number is null all rows are ready into the buffer
- * @return boolean true on success, false on failure
- * @access protected
- */
- function _fillBuffer($rownum = null)
- {
- if (isset($this->buffer) && is_array($this->buffer)) {
- if (null === $rownum) {
- if (!end($this->buffer)) {
- return false;
- }
- } elseif (isset($this->buffer[$rownum])) {
- return (bool)$this->buffer[$rownum];
- }
- }
-
- $row = true;
- while (((null === $rownum) || $this->buffer_rownum < $rownum)
- && ($row = @OCIFetchInto($this->result, $buffer, OCI_RETURN_NULLS))
- ) {
- ++$this->buffer_rownum;
- // remove additional column at the end
- if ($this->offset > 0) {
- array_pop($buffer);
- }
- if (empty($this->types)) {
- foreach (array_keys($buffer) as $key) {
- if (is_a($buffer[$key], 'oci-lob')) {
- $buffer[$key] = $buffer[$key]->load();
- }
- }
- }
- $this->buffer[$this->buffer_rownum] = $buffer;
- }
-
- if (!$row) {
- ++$this->buffer_rownum;
- $this->buffer[$this->buffer_rownum] = false;
- return false;
- }
- return true;
- }
-
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (false === $this->result) {
- $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- if (null === $this->result) {
- return null;
- }
- if (null !== $rownum) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- $target_rownum = $this->rownum + 1;
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if (!$this->_fillBuffer($target_rownum)) {
- return null;
- }
- $row = $this->buffer[$target_rownum];
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- $column_names = $this->getColumnNames();
- foreach ($column_names as $name => $i) {
- $column_names[$name] = $row[$i];
- }
- $row = $column_names;
- }
- $mode = 0;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if (!empty($this->types)) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $rowObj = new $object_class($row);
- $row = $rowObj;
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- }
- if (null === $this->result) {
- return true;
- }
- if ($this->_fillBuffer($this->rownum + 1)) {
- return true;
- }
- return false;
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- }
- if (null === $this->result) {
- return 0;
- }
- $this->_fillBuffer();
- return $this->buffer_rownum;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Free the internal resources associated with $result.
- *
- * @return boolean true on success, false if $result is invalid
- * @access public
- */
- function free()
- {
- $this->buffer = null;
- $this->buffer_rownum = null;
- return parent::free();
- }
-}
-
-/**
- * MDB2 OCI8 statement driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Statement_oci8 extends MDB2_Statement_Common
-{
- // {{{ Variables (Properties)
-
- var $type_maxlengths = array();
-
- // }}}
- // {{{ bindParam()
-
- /**
- * Bind a variable to a parameter of a prepared query.
- *
- * @param int $parameter the order number of the parameter in the query
- * statement. The order number of the first parameter is 1.
- * @param mixed &$value variable that is meant to be bound to specified
- * parameter. The type of the value depends on the $type argument.
- * @param string $type specifies the type of the field
- * @param int $maxlength specifies the maximum length of the field; if set to -1, the
- * current length of $value is used
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function bindParam($parameter, &$value, $type = null, $maxlength = -1)
- {
- if (!is_numeric($parameter)) {
- $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
- }
- if (MDB2_OK === ($ret = parent::bindParam($parameter, $value, $type))) {
- $this->type_maxlengths[$parameter] = $maxlength;
- }
-
- return $ret;
- }
-
- // }}}
- // {{{ _execute()
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access private
- */
- function _execute($result_class = true, $result_wrap_class = false)
- {
- if (null === $this->statement) {
- return parent::_execute($result_class, $result_wrap_class);
- }
- $this->db->last_query = $this->query;
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
- if ($this->db->getOption('disable_query')) {
- $result = $this->is_manip ? 0 : null;
- return $result;
- }
-
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $result = MDB2_OK;
- $lobs = $quoted_values = array();
- $i = 0;
- foreach ($this->positions as $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
- if ($type == 'clob' || $type == 'blob') {
- $lobs[$i]['file'] = false;
- if (is_resource($this->values[$parameter])) {
- $fp = $this->values[$parameter];
- $this->values[$parameter] = '';
- while (!feof($fp)) {
- $this->values[$parameter] .= fread($fp, 8192);
- }
- } elseif (is_a($this->values[$parameter], 'OCI-Lob')) {
- //do nothing
- } elseif ($this->db->getOption('lob_allow_url_include')
- && preg_match('/^(\w+:\/\/)(.*)$/', $this->values[$parameter], $match)
- ) {
- $lobs[$i]['file'] = true;
- if ($match[1] == 'file://') {
- $this->values[$parameter] = $match[2];
- }
- }
- $lobs[$i]['value'] = $this->values[$parameter];
- $lobs[$i]['descriptor'] =& $this->values[$parameter];
- // Test to see if descriptor has already been created for this
- // variable (i.e. if it has been bound more than once):
- if (!is_a($this->values[$parameter], 'OCI-Lob')) {
- $this->values[$parameter] = @OCINewDescriptor($connection, OCI_D_LOB);
- if (false === $this->values[$parameter]) {
- $result = $this->db->raiseError(null, null, null,
- 'Unable to create descriptor for LOB in parameter: '.$parameter, __FUNCTION__);
- break;
- }
- }
- $lob_type = ($type == 'blob' ? OCI_B_BLOB : OCI_B_CLOB);
- if (!@OCIBindByName($this->statement, ':'.$parameter, $lobs[$i]['descriptor'], -1, $lob_type)) {
- $result = $this->db->raiseError($this->statement, null, null,
- 'could not bind LOB parameter', __FUNCTION__);
- break;
- }
- } else if ($type == OCI_B_BFILE) {
- // Test to see if descriptor has already been created for this
- // variable (i.e. if it has been bound more than once):
- if (!is_a($this->values[$parameter], "OCI-Lob")) {
- $this->values[$parameter] = @OCINewDescriptor($connection, OCI_D_FILE);
- if (false === $this->values[$parameter]) {
- $result = $this->db->raiseError(null, null, null,
- 'Unable to create descriptor for BFILE in parameter: '.$parameter, __FUNCTION__);
- break;
- }
- }
- if (!@OCIBindByName($this->statement, ':'.$parameter, $this->values[$parameter], -1, $type)) {
- $result = $this->db->raiseError($this->statement, null, null,
- 'Could not bind BFILE parameter', __FUNCTION__);
- break;
- }
- } else if ($type == OCI_B_ROWID) {
- // Test to see if descriptor has already been created for this
- // variable (i.e. if it has been bound more than once):
- if (!is_a($this->values[$parameter], "OCI-Lob")) {
- $this->values[$parameter] = @OCINewDescriptor($connection, OCI_D_ROWID);
- if (false === $this->values[$parameter]) {
- $result = $this->db->raiseError(null, null, null,
- 'Unable to create descriptor for ROWID in parameter: '.$parameter, __FUNCTION__);
- break;
- }
- }
- if (!@OCIBindByName($this->statement, ':'.$parameter, $this->values[$parameter], -1, $type)) {
- $result = $this->db->raiseError($this->statement, null, null,
- 'Could not bind ROWID parameter', __FUNCTION__);
- break;
- }
- } else if ($type == OCI_B_CURSOR) {
- // Test to see if cursor has already been allocated for this
- // variable (i.e. if it has been bound more than once):
- if (!is_resource($this->values[$parameter]) || !get_resource_type($this->values[$parameter]) == "oci8 statement") {
- $this->values[$parameter] = @OCINewCursor($connection);
- if (false === $this->values[$parameter]) {
- $result = $this->db->raiseError(null, null, null,
- 'Unable to allocate cursor for parameter: '.$parameter, __FUNCTION__);
- break;
- }
- }
- if (!@OCIBindByName($this->statement, ':'.$parameter, $this->values[$parameter], -1, $type)) {
- $result = $this->db->raiseError($this->statement, null, null,
- 'Could not bind CURSOR parameter', __FUNCTION__);
- break;
- }
- } else {
- $maxlength = array_key_exists($parameter, $this->type_maxlengths) ? $this->type_maxlengths[$parameter] : -1;
- $this->values[$parameter] = $this->db->quote($this->values[$parameter], $type, false);
- $quoted_values[$i] =& $this->values[$parameter];
- if (PEAR::isError($quoted_values[$i])) {
- return $quoted_values[$i];
- }
- if (!@OCIBindByName($this->statement, ':'.$parameter, $quoted_values[$i], $maxlength)) {
- $result = $this->db->raiseError($this->statement, null, null,
- 'could not bind non-abstract parameter', __FUNCTION__);
- break;
- }
- }
- ++$i;
- }
-
- $lob_keys = array_keys($lobs);
- if (!PEAR::isError($result)) {
- $mode = (!empty($lobs) || $this->db->in_transaction) ? OCI_DEFAULT : OCI_COMMIT_ON_SUCCESS;
- if (!@OCIExecute($this->statement, $mode)) {
- $err = $this->db->raiseError($this->statement, null, null,
- 'could not execute statement', __FUNCTION__);
- return $err;
- }
-
- if (!empty($lobs)) {
- foreach ($lob_keys as $i) {
- if ((null !== $lobs[$i]['value']) && $lobs[$i]['value'] !== '') {
- if (is_object($lobs[$i]['value'])) {
- // Probably a NULL LOB
- // @see http://bugs.php.net/bug.php?id=27485
- continue;
- }
- if ($lobs[$i]['file']) {
- $result = $lobs[$i]['descriptor']->savefile($lobs[$i]['value']);
- } else {
- $result = $lobs[$i]['descriptor']->save($lobs[$i]['value']);
- }
- if (!$result) {
- $result = $this->db->raiseError(null, null, null,
- 'Unable to save descriptor contents', __FUNCTION__);
- break;
- }
- }
- }
-
- if (!PEAR::isError($result)) {
- if (!$this->db->in_transaction) {
- if (!@OCICommit($connection)) {
- $result = $this->db->raiseError(null, null, null,
- 'Unable to commit transaction', __FUNCTION__);
- }
- } else {
- ++$this->db->uncommitedqueries;
- }
- }
- }
- }
-
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($this->is_manip) {
- $affected_rows = $this->db->_affectedRows($connection, $this->statement);
- return $affected_rows;
- }
-
- $result = $this->db->_wrapResult($this->statement, $this->result_types,
- $result_class, $result_wrap_class, $this->limit, $this->offset);
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function free()
- {
- if (null === $this->positions) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
- $result = MDB2_OK;
-
- if ((null !== $this->statement) && !@OCIFreeStatement($this->statement)) {
- $result = $this->db->raiseError(null, null, null,
- 'Could not free statement', __FUNCTION__);
- }
-
- parent::free();
- return $result;
- }
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Driver/pgsql.php b/3rdparty/MDB2/Driver/pgsql.php
deleted file mode 100644
index 8a8b3f7c91..0000000000
--- a/3rdparty/MDB2/Driver/pgsql.php
+++ /dev/null
@@ -1,1583 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-
-/**
- * MDB2 PostGreSQL driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_Driver_pgsql extends MDB2_Driver_Common
-{
- // {{{ properties
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');
-
- var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'pgsql';
- $this->dbsyntax = 'pgsql';
-
- $this->supported['sequences'] = true;
- $this->supported['indexes'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['transactions'] = true;
- $this->supported['savepoints'] = true;
- $this->supported['current_id'] = true;
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = 'emulated';
- $this->supported['sub_selects'] = true;
- $this->supported['triggers'] = true;
- $this->supported['auto_increment'] = 'emulated';
- $this->supported['primary_key'] = true;
- $this->supported['result_introspection'] = true;
- $this->supported['prepared_statements'] = true;
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = true;
- $this->supported['new_link'] = true;
-
- $this->options['DBA_username'] = false;
- $this->options['DBA_password'] = false;
- $this->options['multi_query'] = false;
- $this->options['disable_smart_seqname'] = true;
- $this->options['max_identifiers_length'] = 63;
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- // Fall back to MDB2_ERROR if there was no mapping.
- $error_code = MDB2_ERROR;
-
- $native_msg = '';
- if (is_resource($error)) {
- $native_msg = @pg_result_error($error);
- } elseif ($this->connection) {
- $native_msg = @pg_last_error($this->connection);
- if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {
- $native_msg = 'Database connection has been lost.';
- $error_code = MDB2_ERROR_CONNECT_FAILED;
- }
- } else {
- $native_msg = @pg_last_error();
- }
-
- static $error_regexps;
- if (empty($error_regexps)) {
- $error_regexps = array(
- '/column .* (of relation .*)?does not exist/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/(relation|sequence|table).*does not exist|class .* not found/i'
- => MDB2_ERROR_NOSUCHTABLE,
- '/database .* does not exist/'
- => MDB2_ERROR_NOT_FOUND,
- '/constraint .* does not exist/'
- => MDB2_ERROR_NOT_FOUND,
- '/index .* does not exist/'
- => MDB2_ERROR_NOT_FOUND,
- '/database .* already exists/i'
- => MDB2_ERROR_ALREADY_EXISTS,
- '/relation .* already exists/i'
- => MDB2_ERROR_ALREADY_EXISTS,
- '/(divide|division) by zero$/i'
- => MDB2_ERROR_DIVZERO,
- '/pg_atoi: error in .*: can\'t parse /i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/invalid input syntax for( type)? (integer|numeric)/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/value .* is out of range for type \w*int/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/integer out of range/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/value too long for type character/i'
- => MDB2_ERROR_INVALID,
- '/attribute .* not found|relation .* does not have attribute/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/column .* specified in USING clause does not exist in (left|right) table/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/parser: parse error at or near/i'
- => MDB2_ERROR_SYNTAX,
- '/syntax error at/'
- => MDB2_ERROR_SYNTAX,
- '/column reference .* is ambiguous/i'
- => MDB2_ERROR_SYNTAX,
- '/permission denied/'
- => MDB2_ERROR_ACCESS_VIOLATION,
- '/violates not-null constraint/'
- => MDB2_ERROR_CONSTRAINT_NOT_NULL,
- '/violates [\w ]+ constraint/'
- => MDB2_ERROR_CONSTRAINT,
- '/referential integrity violation/'
- => MDB2_ERROR_CONSTRAINT,
- '/more expressions than target columns/i'
- => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- );
- }
- if (is_numeric($error) && $error < 0) {
- $error_code = $error;
- } else {
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $native_msg)) {
- $error_code = $code;
- break;
- }
- }
- }
- return array($error_code, null, $native_msg);
- }
-
- // }}}
- // {{{ escape()
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- if ($escape_wildcards) {
- $text = $this->escapePattern($text);
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- if (is_resource($connection) && version_compare(PHP_VERSION, '5.2.0RC5', '>=')) {
- $text = @pg_escape_string($connection, $text);
- } else {
- $text = @pg_escape_string($text);
- }
- return $text;
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (null !== $savepoint) {
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
- }
- $query = 'SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
- if ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $result = $this->_doQuery('BEGIN', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (null !== $savepoint) {
- $query = 'RELEASE SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $result = $this->_doQuery('COMMIT', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (null !== $savepoint) {
- $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $query = 'ROLLBACK';
- $result = $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @param array some transaction options:
- * 'wait' => 'WAIT' | 'NO WAIT'
- * 'rw' => 'READ WRITE' | 'READ ONLY'
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation, $options = array())
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- case 'SERIALIZABLE':
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ _doConnect()
-
- /**
- * Do the grunt work of connecting to the database
- *
- * @return mixed connection resource on success, MDB2 Error Object on failure
- * @access protected
- */
- function _doConnect($username, $password, $database_name, $persistent = false)
- {
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- if ($database_name == '') {
- $database_name = 'template1';
- }
-
- $protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp';
-
- $params = array('');
- if ($protocol == 'tcp') {
- if ($this->dsn['hostspec']) {
- $params[0].= 'host=' . $this->dsn['hostspec'];
- }
- if ($this->dsn['port']) {
- $params[0].= ' port=' . $this->dsn['port'];
- }
- } elseif ($protocol == 'unix') {
- // Allow for pg socket in non-standard locations.
- if ($this->dsn['socket']) {
- $params[0].= 'host=' . $this->dsn['socket'];
- }
- if ($this->dsn['port']) {
- $params[0].= ' port=' . $this->dsn['port'];
- }
- }
- if ($database_name) {
- $params[0].= ' dbname=\'' . addslashes($database_name) . '\'';
- }
- if ($username) {
- $params[0].= ' user=\'' . addslashes($username) . '\'';
- }
- if ($password) {
- $params[0].= ' password=\'' . addslashes($password) . '\'';
- }
- if (!empty($this->dsn['options'])) {
- $params[0].= ' options=' . $this->dsn['options'];
- }
- if (!empty($this->dsn['tty'])) {
- $params[0].= ' tty=' . $this->dsn['tty'];
- }
- if (!empty($this->dsn['connect_timeout'])) {
- $params[0].= ' connect_timeout=' . $this->dsn['connect_timeout'];
- }
- if (!empty($this->dsn['sslmode'])) {
- $params[0].= ' sslmode=' . $this->dsn['sslmode'];
- }
- if (!empty($this->dsn['service'])) {
- $params[0].= ' service=' . $this->dsn['service'];
- }
-
- if ($this->_isNewLinkSet()) {
- if (version_compare(phpversion(), '4.3.0', '>=')) {
- $params[] = PGSQL_CONNECT_FORCE_NEW;
- }
- }
-
- $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
- $connection = @call_user_func_array($connect_function, $params);
- if (!$connection) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if (empty($this->dsn['disable_iso_date'])) {
- if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) {
- return $this->raiseError(null, null, null,
- 'Unable to set date style to iso', __FUNCTION__);
- }
- }
-
- if (!empty($this->dsn['charset'])) {
- $result = $this->setCharset($this->dsn['charset'], $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- // Enable extra compatibility settings on 8.2 and later
- if (function_exists('pg_parameter_status')) {
- $version = pg_parameter_status($connection, 'server_version');
- if ($version == false) {
- return $this->raiseError(null, null, null,
- 'Unable to retrieve server version', __FUNCTION__);
- }
- $version = explode ('.', $version);
- if ( $version['0'] > 8
- || ($version['0'] == 8 && $version['1'] >= 2)
- ) {
- if (!@pg_query($connection, "SET SESSION STANDARD_CONFORMING_STRINGS = OFF")) {
- return $this->raiseError(null, null, null,
- 'Unable to set standard_conforming_strings to off', __FUNCTION__);
- }
-
- if (!@pg_query($connection, "SET SESSION ESCAPE_STRING_WARNING = OFF")) {
- return $this->raiseError(null, null, null,
- 'Unable to set escape_string_warning to off', __FUNCTION__);
- }
- }
- }
-
- return $connection;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return true on success, MDB2 Error Object on failure
- * @access public
- */
- function connect()
- {
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->connected_database_name == $this->database_name
- && ($this->opened_persistent == $this->options['persistent'])
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- if ($this->database_name) {
- $connection = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->database_name,
- $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = $this->database_name;
- $this->opened_persistent = $this->options['persistent'];
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ setCharset()
-
- /**
- * Set the charset on the current connection
- *
- * @param string charset
- * @param resource connection handle
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function setCharset($charset, $connection = null)
- {
- if (null === $connection) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- if (is_array($charset)) {
- $charset = array_shift($charset);
- $this->warnings[] = 'postgresql does not support setting client collation';
- }
- $result = @pg_set_client_encoding($connection, $charset);
- if ($result == -1) {
- return $this->raiseError(null, null, null,
- 'Unable to set client charset: '.$charset, __FUNCTION__);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- $res = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->escape($name),
- $this->options['persistent']);
- if (!PEAR::isError($res)) {
- return true;
- }
-
- return false;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- $ok = @pg_close($this->connection);
- if (!$ok) {
- return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
- null, null, null, __FUNCTION__);
- }
- }
- } else {
- return false;
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ standaloneQuery()
-
- /**
- * execute a query as DBA
- *
- * @param string $query the SQL query
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param boolean $is_manip if the query is a manipulation query
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function standaloneQuery($query, $types = null, $is_manip = false)
- {
- $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
- $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
- $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $result = $this->_doQuery($query, $is_manip, $connection, $this->database_name);
- if (!PEAR::isError($result)) {
- if ($is_manip) {
- $result = $this->_affectedRows($connection, $result);
- } else {
- $result = $this->_wrapResult($result, $types, true, true, $limit, $offset);
- }
- }
-
- @pg_close($connection);
- return $result;
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->options['disable_query']) {
- $result = $is_manip ? 0 : null;
- return $result;
- }
-
- if (null === $connection) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
-
- $function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query';
- $result = @$function($connection, $query);
- if (!$result) {
- $err = $this->raiseError(null, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- } elseif ($this->options['multi_query']) {
- if (!($result = @pg_get_result($connection))) {
- $err = $this->raiseError(null, null, null,
- 'Could not get the first result from a multi query', __FUNCTION__);
- return $err;
- }
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (null === $connection) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @pg_affected_rows($result);
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if ($limit > 0
- && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
- ) {
- $query = rtrim($query);
- if (substr($query, -1) == ';') {
- $query = substr($query, 0, -1);
- }
- if ($is_manip) {
- $query = $this->_modifyManipQuery($query, $limit);
- } else {
- $query.= " LIMIT $limit OFFSET $offset";
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ _modifyManipQuery()
-
- /**
- * Changes a manip query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param integer $limit limit the number of rows
- * @return string modified query
- * @access protected
- */
- function _modifyManipQuery($query, $limit)
- {
- $pos = strpos(strtolower($query), 'where');
- $where = $pos ? substr($query, $pos) : '';
-
- $manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)';
- $from_clause = '([\w\.]+)';
- $where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)';
- $pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i';
- $matches = preg_match($pattern, $query, $match);
- if ($matches) {
- $manip = $match[1];
- $from = $match[2];
- $what = (count($matches) == 6) ? $match[5] : $match[3];
- return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
- }
- //return error?
- return $query;
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $query = 'SHOW SERVER_VERSION';
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } else {
- $server_info = $this->queryOne($query, 'text');
- if (PEAR::isError($server_info)) {
- return $server_info;
- }
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native && !PEAR::isError($server_info)) {
- $tmp = explode('.', $server_info, 3);
- if (empty($tmp[2])
- && isset($tmp[1])
- && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)
- ) {
- $server_info = array(
- 'major' => $tmp[0],
- 'minor' => $tmp2[1],
- 'patch' => null,
- 'extra' => $tmp2[2],
- 'native' => $server_info,
- );
- } else {
- $server_info = array(
- 'major' => isset($tmp[0]) ? $tmp[0] : null,
- 'minor' => isset($tmp[1]) ? $tmp[1] : null,
- 'patch' => isset($tmp[2]) ? $tmp[2] : null,
- 'extra' => null,
- 'native' => $server_info,
- );
- }
- }
- return $server_info;
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string $query the query to prepare
- * @param mixed $types array that contains the types of the placeholders
- * @param mixed $result_types array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
- * @return mixed resource handle for the prepared query on success, a MDB2
- * error on failure
- * @access public
- * @see bindParam, execute
- */
- function prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- if ($this->options['emulate_prepared']) {
- return parent::prepare($query, $types, $result_types, $lobs);
- }
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $pgtypes = function_exists('pg_prepare') ? false : array();
- if ($pgtypes !== false && !empty($types)) {
- $this->loadModule('Datatype', null, true);
- }
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = $parameter = 0;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- //skip "::type" cast ("select id::varchar(20) from sometable where name=?")
- $doublecolon_position = strpos($query, '::', $position);
- if ($doublecolon_position !== false && $doublecolon_position == $c_position) {
- $c_position = strpos($query, $colon, $position+2);
- }
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (null === $placeholder_type) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (PEAR::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (null === $placeholder_type) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- if (!empty($types) && is_array($types)) {
- if ($placeholder_type == ':') {
- } else {
- $types = array_values($types);
- }
- }
- }
- if ($placeholder_type_guess == '?') {
- $length = 1;
- $name = $parameter;
- } else {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $param = preg_replace($regexp, '\\1', $query);
- if ($param === '') {
- $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- $length = strlen($param) + 1;
- $name = $param;
- }
- if ($pgtypes !== false) {
- if (is_array($types) && array_key_exists($name, $types)) {
- $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]);
- } elseif (is_array($types) && array_key_exists($parameter, $types)) {
- $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]);
- } else {
- $pgtypes[] = 'text';
- }
- }
- if (($key_parameter = array_search($name, $positions)) !== false) {
- //$next_parameter = 1;
- $parameter = $key_parameter + 1;
- //foreach ($positions as $key => $value) {
- // if ($key_parameter == $key) {
- // break;
- // }
- // ++$next_parameter;
- //}
- } else {
- ++$parameter;
- //$next_parameter = $parameter;
- $positions[] = $name;
- }
- $query = substr_replace($query, '$'.$parameter, $position, $length);
- $position = $p_position + strlen($parameter);
- } else {
- $position = $p_position;
- }
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- static $prep_statement_counter = 1;
- $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
- $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
- if (false === $pgtypes) {
- $result = @pg_prepare($connection, $statement_name, $query);
- if (!$result) {
- $err = $this->raiseError(null, null, null,
- 'Unable to create prepared statement handle', __FUNCTION__);
- return $err;
- }
- } else {
- $types_string = '';
- if ($pgtypes) {
- $types_string = ' ('.implode(', ', $pgtypes).') ';
- }
- $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;
- $statement = $this->_doQuery($query, true, $connection);
- if (PEAR::isError($statement)) {
- return $statement;
- }
- }
-
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ function getSequenceName($sqn)
-
- /**
- * adds sequence name formatting to a sequence name
- *
- * @param string name of the sequence
- *
- * @return string formatted sequence name
- *
- * @access public
- */
- function getSequenceName($sqn)
- {
- if (false === $this->options['disable_smart_seqname']) {
- if (strpos($sqn, '_') !== false) {
- list($table, $field) = explode('_', $sqn, 2);
- }
- $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')");
- if (PEAR::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) {
- $order_by = ' a.attnum';
- $schema_clause = ' AND n.nspname=current_schema()';
- } else {
- $schemas = explode(',', $schema_list);
- $schema_clause = ' AND n.nspname IN ('.$schema_list.')';
- $counter = 1;
- $order_by = ' CASE ';
- foreach ($schemas as $schema) {
- $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++;
- }
- $order_by .= ' ELSE '.$counter.' END, a.attnum';
- }
-
- $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
- FROM pg_attrdef d
- WHERE d.adrelid = a.attrelid
- AND d.adnum = a.attnum
- AND a.atthasdef
- ) FROM 'nextval[^'']*''([^'']*)')
- FROM pg_attribute a
- LEFT JOIN pg_class c ON c.oid = a.attrelid
- LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef
- LEFT JOIN pg_namespace n ON c.relnamespace = n.oid
- WHERE (c.relname = ".$this->quote($sqn, 'text');
- if (!empty($field)) {
- $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";
- }
- $query .= " )"
- .$schema_clause."
- AND NOT a.attisdropped
- AND a.attnum > 0
- AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
- ORDER BY ".$order_by;
- $seqname = $this->queryOne($query);
- if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) {
- return $seqname;
- }
- }
-
- return parent::getSequenceName($sqn);
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $query = "SELECT NEXTVAL('$sequence_name')";
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result = $this->queryOne($query, 'integer');
- $this->popExpect();
- $this->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result, null, null,
- 'on demand sequence could not be created', __FUNCTION__);
- }
- return $this->nextId($seq_name, false);
- }
- }
- return $result;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- if (empty($table) && empty($field)) {
- return $this->queryOne('SELECT lastval()', 'integer');
- }
- $seq = $table.(empty($field) ? '' : '_'.$field);
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq), true);
- return $this->queryOne("SELECT currval('$sequence_name')", 'integer');
- }
-
- // }}}
- // {{{ currID()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function currID($seq_name)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');
- }
-}
-
-/**
- * MDB2 PostGreSQL result driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_Result_pgsql extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (null !== $rownum) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ( $fetchmode == MDB2_FETCHMODE_ASSOC
- || $fetchmode == MDB2_FETCHMODE_OBJECT
- ) {
- $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- $row = @pg_fetch_row($this->result);
- }
- if (!$row) {
- if (false === $this->result) {
- $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- return null;
- }
- $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if ( ( $fetchmode != MDB2_FETCHMODE_ASSOC
- && $fetchmode != MDB2_FETCHMODE_OBJECT)
- && !empty($this->types)
- ) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC
- || $fetchmode == MDB2_FETCHMODE_OBJECT)
- && !empty($this->types_assoc)
- ) {
- $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $rowObj = new $object_class($row);
- $row = $rowObj;
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @pg_field_name($this->result, $column);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @access public
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- */
- function numCols()
- {
- $cols = @pg_num_fields($this->result);
- if (null === $cols) {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- }
- if (null === $this->result) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- return $cols;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal result pointer to the next available result
- *
- * @return true on success, false if there is no more result set or an error object on failure
- * @access public
- */
- function nextResult()
- {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- if (!($this->result = @pg_get_result($connection))) {
- return false;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return boolean true on success, false if result is invalid
- * @access public
- */
- function free()
- {
- if (is_resource($this->result) && $this->db->connection) {
- $free = @pg_free_result($this->result);
- if (false === $free) {
- return $this->db->raiseError(null, null, null,
- 'Could not free result', __FUNCTION__);
- }
- }
- $this->result = false;
- return MDB2_OK;
- }
-}
-
-/**
- * MDB2 PostGreSQL buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
-{
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- }
- if (null === $this->result) {
- return MDB2_OK;
- }
- return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- $numrows = $this->numRows();
- if (PEAR::isError($numrows)) {
- return $numrows;
- }
- return $this->rownum < ($numrows - 1);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- $rows = @pg_num_rows($this->result);
- if (null === $rows) {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- }
- if (null === $this->result) {
- return 0;
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get row count', __FUNCTION__);
- }
- return $rows;
- }
-}
-
-/**
- * MDB2 PostGreSQL statement driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper
- */
-class MDB2_Statement_pgsql extends MDB2_Statement_Common
-{
- // {{{ _execute()
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access private
- */
- function _execute($result_class = true, $result_wrap_class = true)
- {
- if (null === $this->statement) {
- return parent::_execute($result_class, $result_wrap_class);
- }
- $this->db->last_query = $this->query;
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
- if ($this->db->getOption('disable_query')) {
- $result = $this->is_manip ? 0 : null;
- return $result;
- }
-
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $query = false;
- $parameters = array();
- // todo: disabled until pg_execute() bytea issues are cleared up
- if (true || !function_exists('pg_execute')) {
- $query = 'EXECUTE '.$this->statement;
- }
- if (!empty($this->positions)) {
- foreach ($this->positions as $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $value = $this->values[$parameter];
- $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
- if (is_resource($value) || $type == 'clob' || $type == 'blob' || $this->db->options['lob_allow_url_include']) {
- if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
- if ($match[1] == 'file://') {
- $value = $match[2];
- }
- $value = @fopen($value, 'r');
- $close = true;
- }
- if (is_resource($value)) {
- $data = '';
- while (!@feof($value)) {
- $data.= @fread($value, $this->db->options['lob_buffer_length']);
- }
- if ($close) {
- @fclose($value);
- }
- $value = $data;
- }
- }
- $quoted = $this->db->quote($value, $type, $query);
- if (PEAR::isError($quoted)) {
- return $quoted;
- }
- $parameters[] = $quoted;
- }
- if ($query) {
- $query.= ' ('.implode(', ', $parameters).')';
- }
- }
-
- if (!$query) {
- $result = @pg_execute($connection, $this->statement, $parameters);
- if (!$result) {
- $err = $this->db->raiseError(null, null, null,
- 'Unable to execute statement', __FUNCTION__);
- return $err;
- }
- } else {
- $result = $this->db->_doQuery($query, $this->is_manip, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if ($this->is_manip) {
- $affected_rows = $this->db->_affectedRows($connection, $result);
- return $affected_rows;
- }
-
- $result = $this->db->_wrapResult($result, $this->result_types,
- $result_class, $result_wrap_class, $this->limit, $this->offset);
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function free()
- {
- if (null === $this->positions) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
- $result = MDB2_OK;
-
- if (null !== $this->statement) {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $query = 'DEALLOCATE PREPARE '.$this->statement;
- $result = $this->db->_doQuery($query, true, $connection);
- }
-
- parent::free();
- return $result;
- }
-
- /**
- * drop an existing table
- *
- * @param string $name name of the table that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropTable($name)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = $db->exec("DROP TABLE $name");
-
- if (PEAR::isError($result)) {
- $result = $db->exec("DROP TABLE $name CASCADE");
- }
-
- return $result;
- }
-}
-?>
diff --git a/3rdparty/MDB2/Driver/sqlite.php b/3rdparty/MDB2/Driver/sqlite.php
deleted file mode 100644
index 42363bb8c5..0000000000
--- a/3rdparty/MDB2/Driver/sqlite.php
+++ /dev/null
@@ -1,1104 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-//
-
-/**
- * MDB2 SQLite driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Driver_sqlite extends MDB2_Driver_Common
-{
- // {{{ properties
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false);
-
- var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
-
- var $_lasterror = '';
-
- var $fix_assoc_fields_names = false;
-
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'sqlite';
- $this->dbsyntax = 'sqlite';
-
- $this->supported['sequences'] = 'emulated';
- $this->supported['indexes'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['current_id'] = 'emulated';
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = true;
- $this->supported['transactions'] = true;
- $this->supported['savepoints'] = false;
- $this->supported['sub_selects'] = true;
- $this->supported['triggers'] = true;
- $this->supported['auto_increment'] = true;
- $this->supported['primary_key'] = false; // requires alter table implementation
- $this->supported['result_introspection'] = false; // not implemented
- $this->supported['prepared_statements'] = 'emulated';
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = false;
- $this->supported['new_link'] = false;
-
- $this->options['DBA_username'] = false;
- $this->options['DBA_password'] = false;
- $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off';
- $this->options['fixed_float'] = 0;
- $this->options['database_path'] = '';
- $this->options['database_extension'] = '';
- $this->options['server_version'] = '';
- $this->options['max_identifiers_length'] = 128; //no real limit
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- $native_code = null;
- if ($this->connection) {
- $native_code = @sqlite_last_error($this->connection);
- }
- $native_msg = $this->_lasterror
- ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code);
-
- // PHP 5.2+ prepends the function name to $php_errormsg, so we need
- // this hack to work around it, per bug #9599.
- $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg);
-
- if (null === $error) {
- static $error_regexps;
- if (empty($error_regexps)) {
- $error_regexps = array(
- '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE,
- '/^no such index:/' => MDB2_ERROR_NOT_FOUND,
- '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS,
- '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT,
- '/is not unique/' => MDB2_ERROR_CONSTRAINT,
- '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT,
- '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT,
- '/violates .*constraint/' => MDB2_ERROR_CONSTRAINT,
- '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL,
- '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD,
- '/no column named/' => MDB2_ERROR_NOSUCHFIELD,
- '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD,
- '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX,
- '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- );
- }
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $native_msg)) {
- $error = $code;
- break;
- }
- }
- }
- return array($error, $native_code, $native_msg);
- }
-
- // }}}
- // {{{ escape()
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- $text = @sqlite_escape_string($text);
- return $text;
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (null !== $savepoint) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
- if ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $query = 'BEGIN TRANSACTION '.$this->options['base_transaction_name'];
- $result = $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (null !== $savepoint) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
-
- $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name'];
- $result = $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (null !== $savepoint) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
-
- $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name'];
- $result = $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @param array some transaction options:
- * 'wait' => 'WAIT' | 'NO WAIT'
- * 'rw' => 'READ WRITE' | 'READ ONLY'
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation, $options = array())
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- $isolation = 0;
- break;
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- case 'SERIALIZABLE':
- $isolation = 1;
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "PRAGMA read_uncommitted=$isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ getDatabaseFile()
-
- /**
- * Builds the string with path+dbname+extension
- *
- * @return string full database path+file
- * @access protected
- */
- function _getDatabaseFile($database_name)
- {
- if ($database_name === '' || $database_name === ':memory:') {
- return $database_name;
- }
- return $this->options['database_path'].$database_name.$this->options['database_extension'];
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return true on success, MDB2 Error Object on failure
- **/
- function connect()
- {
- $database_file = $this->_getDatabaseFile($this->database_name);
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->connected_database_name == $database_file
- && $this->opened_persistent == $this->options['persistent']
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- if (empty($this->database_name)) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if ($database_file !== ':memory:') {
- if (!file_exists($database_file)) {
- if (!touch($database_file)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Could not create database file', __FUNCTION__);
- }
- if (!isset($this->dsn['mode'])
- || !is_numeric($this->dsn['mode'])
- ) {
- $mode = 0644;
- } else {
- $mode = octdec($this->dsn['mode']);
- }
- if (!chmod($database_file, $mode)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Could not be chmodded database file', __FUNCTION__);
- }
- if (!file_exists($database_file)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Could not be found database file', __FUNCTION__);
- }
- }
- if (!is_file($database_file)) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'Database is a directory name', __FUNCTION__);
- }
- if (!is_readable($database_file)) {
- return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null,
- 'Could not read database file', __FUNCTION__);
- }
- }
-
- $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open');
- $php_errormsg = '';
- if (version_compare('5.1.0', PHP_VERSION, '>')) {
- @ini_set('track_errors', true);
- $connection = @$connect_function($database_file);
- @ini_restore('track_errors');
- } else {
- $connection = @$connect_function($database_file, 0666, $php_errormsg);
- }
- $this->_lasterror = $php_errormsg;
- if (!$connection) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if ($this->fix_assoc_fields_names ||
- $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES)
- {
- @sqlite_query("PRAGMA short_column_names = 1", $connection);
- $this->fix_assoc_fields_names = true;
- }
-
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = $database_file;
- $this->opened_persistent = $this->getoption('persistent');
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- $database_file = $this->_getDatabaseFile($name);
- $result = file_exists($database_file);
- return $result;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- @sqlite_close($this->connection);
- }
- } else {
- return false;
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->options['disable_query']) {
- $result = $is_manip ? 0 : null;
- return $result;
- }
-
- if (null === $connection) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
-
- $function = $this->options['result_buffering']
- ? 'sqlite_query' : 'sqlite_unbuffered_query';
- $php_errormsg = '';
- if (version_compare('5.1.0', PHP_VERSION, '>')) {
- @ini_set('track_errors', true);
- do {
- $result = @$function($query.';', $connection);
- } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
- @ini_restore('track_errors');
- } else {
- do {
- $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg);
- } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
- }
- $this->_lasterror = $php_errormsg;
-
- if (!$result) {
- $code = null;
- if (0 === strpos($this->_lasterror, 'no such table')) {
- $code = MDB2_ERROR_NOSUCHTABLE;
- }
- $err = $this->raiseError($code, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (null === $connection) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @sqlite_changes($connection);
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
- if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
- $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
- 'DELETE FROM \1 WHERE 1=1', $query);
- }
- }
- if ($limit > 0
- && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
- ) {
- $query = rtrim($query);
- if (substr($query, -1) == ';') {
- $query = substr($query, 0, -1);
- }
- if ($is_manip) {
- $query.= " LIMIT $limit";
- } else {
- $query.= " LIMIT $offset,$limit";
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $server_info = false;
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } elseif ($this->options['server_version']) {
- $server_info = $this->options['server_version'];
- } elseif (function_exists('sqlite_libversion')) {
- $server_info = @sqlite_libversion();
- }
- if (!$server_info) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__);
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native) {
- $tmp = explode('.', $server_info, 3);
- $server_info = array(
- 'major' => isset($tmp[0]) ? $tmp[0] : null,
- 'minor' => isset($tmp[1]) ? $tmp[1] : null,
- 'patch' => isset($tmp[2]) ? $tmp[2] : null,
- 'extra' => null,
- 'native' => $server_info,
- );
- }
- return $server_info;
- }
-
- // }}}
- // {{{ replace()
-
- /**
- * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
- * query, except that if there is already a row in the table with the same
- * key field values, the old row is deleted before the new row is inserted.
- *
- * The REPLACE type of query does not make part of the SQL standards. Since
- * practically only SQLite implements it natively, this type of query is
- * emulated through this method for other DBMS using standard types of
- * queries inside a transaction to assure the atomicity of the operation.
- *
- * @access public
- *
- * @param string $table name of the table on which the REPLACE query will
- * be executed.
- * @param array $fields associative array that describes the fields and the
- * values that will be inserted or updated in the specified table. The
- * indexes of the array are the names of all the fields of the table. The
- * values of the array are also associative arrays that describe the
- * values and other properties of the table fields.
- *
- * Here follows a list of field properties that need to be specified:
- *
- * value:
- * Value to be assigned to the specified field. This value may be
- * of specified in database independent type format as this
- * function can perform the necessary datatype conversions.
- *
- * Default:
- * this property is required unless the Null property
- * is set to 1.
- *
- * type
- * Name of the type of the field. Currently, all types Metabase
- * are supported except for clob and blob.
- *
- * Default: no type conversion
- *
- * null
- * Boolean property that indicates that the value for this field
- * should be set to null.
- *
- * The default value for fields missing in INSERT queries may be
- * specified the definition of a table. Often, the default value
- * is already null, but since the REPLACE may be emulated using
- * an UPDATE query, make sure that all fields of the table are
- * listed in this function argument array.
- *
- * Default: 0
- *
- * key
- * Boolean property that indicates that this field should be
- * handled as a primary key or at least as part of the compound
- * unique index of the table that will determine the row that will
- * updated if it exists or inserted a new row otherwise.
- *
- * This function will fail if no key field is specified or if the
- * value of a key field is set to null because fields that are
- * part of unique index they may not be null.
- *
- * Default: 0
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function replace($table, $fields)
- {
- $count = count($fields);
- $query = $values = '';
- $keys = $colnum = 0;
- for (reset($fields); $colnum < $count; next($fields), $colnum++) {
- $name = key($fields);
- if ($colnum > 0) {
- $query .= ',';
- $values.= ',';
- }
- $query.= $this->quoteIdentifier($name, true);
- if (isset($fields[$name]['null']) && $fields[$name]['null']) {
- $value = 'NULL';
- } else {
- $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
- $value = $this->quote($fields[$name]['value'], $type);
- if (PEAR::isError($value)) {
- return $value;
- }
- }
- $values.= $value;
- if (isset($fields[$name]['key']) && $fields[$name]['key']) {
- if ($value === 'NULL') {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'key value '.$name.' may not be NULL', __FUNCTION__);
- }
- $keys++;
- }
- }
- if ($keys == 0) {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'not specified which fields are keys', __FUNCTION__);
- }
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $table = $this->quoteIdentifier($table, true);
- $query = "REPLACE INTO $table ($query) VALUES ($values)";
- $result = $this->_doQuery($query, true, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->_affectedRows($connection, $result);
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- *
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->options['seqcol_name'];
- $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result = $this->_doQuery($query, true);
- $this->popExpect();
- $this->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result, null, null,
- 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
- } else {
- return $this->nextID($seq_name, false);
- }
- }
- return $result;
- }
- $value = $this->lastInsertID();
- if (is_numeric($value)) {
- $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
- $result = $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
- }
- }
- return $value;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $value = @sqlite_last_insert_rowid($connection);
- if (!$value) {
- return $this->raiseError(null, null, null,
- 'Could not get last insert ID', __FUNCTION__);
- }
- return $value;
- }
-
- // }}}
- // {{{ currID()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function currID($seq_name)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
- $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
- return $this->queryOne($query, 'integer');
- }
-}
-
-/**
- * MDB2 SQLite result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Result_sqlite extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (null !== $rownum) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ( $fetchmode == MDB2_FETCHMODE_ASSOC
- || $fetchmode == MDB2_FETCHMODE_OBJECT
- ) {
- $row = @sqlite_fetch_array($this->result, SQLITE_ASSOC);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- $row = @sqlite_fetch_array($this->result, SQLITE_NUM);
- }
- if (!$row) {
- if (false === $this->result) {
- $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- return null;
- }
- $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if ( ( $fetchmode != MDB2_FETCHMODE_ASSOC
- && $fetchmode != MDB2_FETCHMODE_OBJECT)
- && !empty($this->types)
- ) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC
- || $fetchmode == MDB2_FETCHMODE_OBJECT)
- && !empty($this->types_assoc)
- ) {
- $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $rowObj = new $object_class($row);
- $row = $rowObj;
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @sqlite_field_name($this->result, $column);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @access public
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- */
- function numCols()
- {
- $cols = @sqlite_num_fields($this->result);
- if (null === $cols) {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- }
- if (null === $this->result) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- return $cols;
- }
-}
-
-/**
- * MDB2 SQLite buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite
-{
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if (!@sqlite_seek($this->result, $rownum)) {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- }
- if (null === $this->result) {
- return MDB2_OK;
- }
- return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- $numrows = $this->numRows();
- if (PEAR::isError($numrows)) {
- return $numrows;
- }
- return $this->rownum < ($numrows - 1);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- $rows = @sqlite_num_rows($this->result);
- if (null === $rows) {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- }
- if (null === $this->result) {
- return 0;
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get row count', __FUNCTION__);
- }
- return $rows;
- }
-}
-
-/**
- * MDB2 SQLite statement driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Statement_sqlite extends MDB2_Statement_Common
-{
-
-}
-?>
diff --git a/3rdparty/MDB2/Extended.php b/3rdparty/MDB2/Extended.php
deleted file mode 100644
index 5b0a5be34a..0000000000
--- a/3rdparty/MDB2/Extended.php
+++ /dev/null
@@ -1,723 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-
-/**
- * Used by autoPrepare()
- */
-define('MDB2_AUTOQUERY_INSERT', 1);
-define('MDB2_AUTOQUERY_UPDATE', 2);
-define('MDB2_AUTOQUERY_DELETE', 3);
-define('MDB2_AUTOQUERY_SELECT', 4);
-
-/**
- * MDB2_Extended: class which adds several high level methods to MDB2
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Extended extends MDB2_Module_Common
-{
- // {{{ autoPrepare()
-
- /**
- * Generate an insert, update or delete query and call prepare() on it
- *
- * @param string table
- * @param array the fields names
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- * @param array that contains the types of the placeholders
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- *
- * @return resource handle for the query
- * @see buildManipSQL
- * @access public
- */
- function autoPrepare($table, $table_fields, $mode = MDB2_AUTOQUERY_INSERT,
- $where = false, $types = null, $result_types = MDB2_PREPARE_MANIP)
- {
- $query = $this->buildManipSQL($table, $table_fields, $mode, $where);
- if (PEAR::isError($query)) {
- return $query;
- }
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $lobs = array();
- foreach ((array)$types as $param => $type) {
- if (($type == 'clob') || ($type == 'blob')) {
- $lobs[$param] = $table_fields[$param];
- }
- }
- return $db->prepare($query, $types, $result_types, $lobs);
- }
-
- // }}}
- // {{{ autoExecute()
-
- /**
- * Generate an insert, update or delete query and call prepare() and execute() on it
- *
- * @param string name of the table
- * @param array assoc ($key=>$value) where $key is a field name and $value its value
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- * @param array that contains the types of the placeholders
- * @param string which specifies which result class to use
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- *
- * @return bool|MDB2_Error true on success, a MDB2 error on failure
- * @see buildManipSQL
- * @see autoPrepare
- * @access public
- */
- function autoExecute($table, $fields_values, $mode = MDB2_AUTOQUERY_INSERT,
- $where = false, $types = null, $result_class = true, $result_types = MDB2_PREPARE_MANIP)
- {
- $fields_values = (array)$fields_values;
- if ($mode == MDB2_AUTOQUERY_SELECT) {
- if (is_array($result_types)) {
- $keys = array_keys($result_types);
- } elseif (!empty($fields_values)) {
- $keys = $fields_values;
- } else {
- $keys = array();
- }
- } else {
- $keys = array_keys($fields_values);
- }
- $params = array_values($fields_values);
- if (empty($params)) {
- $query = $this->buildManipSQL($table, $keys, $mode, $where);
-
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if ($mode == MDB2_AUTOQUERY_SELECT) {
- $result = $db->query($query, $result_types, $result_class);
- } else {
- $result = $db->exec($query);
- }
- } else {
- $stmt = $this->autoPrepare($table, $keys, $mode, $where, $types, $result_types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $result = $stmt->execute($params, $result_class);
- $stmt->free();
- }
- return $result;
- }
-
- // }}}
- // {{{ buildManipSQL()
-
- /**
- * Make automaticaly an sql query for prepare()
- *
- * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), MDB2_AUTOQUERY_INSERT)
- * will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)
- * NB : - This belongs more to a SQL Builder class, but this is a simple facility
- * - Be carefull ! If you don't give a $where param with an UPDATE/DELETE query, all
- * the records of the table will be updated/deleted !
- *
- * @param string name of the table
- * @param ordered array containing the fields names
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- *
- * @return string sql query for prepare()
- * @access public
- */
- function buildManipSQL($table, $table_fields, $mode, $where = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->options['quote_identifier']) {
- $table = $db->quoteIdentifier($table);
- }
-
- if (!empty($table_fields) && $db->options['quote_identifier']) {
- foreach ($table_fields as $key => $field) {
- $table_fields[$key] = $db->quoteIdentifier($field);
- }
- }
-
- if ((false !== $where) && (null !== $where)) {
- if (is_array($where)) {
- $where = implode(' AND ', $where);
- }
- $where = ' WHERE '.$where;
- }
-
- switch ($mode) {
- case MDB2_AUTOQUERY_INSERT:
- if (empty($table_fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Insert requires table fields', __FUNCTION__);
- }
- $cols = implode(', ', $table_fields);
- $values = '?'.str_repeat(', ?', (count($table_fields) - 1));
- return 'INSERT INTO '.$table.' ('.$cols.') VALUES ('.$values.')';
- break;
- case MDB2_AUTOQUERY_UPDATE:
- if (empty($table_fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Update requires table fields', __FUNCTION__);
- }
- $set = implode(' = ?, ', $table_fields).' = ?';
- $sql = 'UPDATE '.$table.' SET '.$set.$where;
- return $sql;
- break;
- case MDB2_AUTOQUERY_DELETE:
- $sql = 'DELETE FROM '.$table.$where;
- return $sql;
- break;
- case MDB2_AUTOQUERY_SELECT:
- $cols = !empty($table_fields) ? implode(', ', $table_fields) : '*';
- $sql = 'SELECT '.$cols.' FROM '.$table.$where;
- return $sql;
- break;
- }
- return $db->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'Non existant mode', __FUNCTION__);
- }
-
- // }}}
- // {{{ limitQuery()
-
- /**
- * Generates a limited query
- *
- * @param string query
- * @param array that contains the types of the columns in the result set
- * @param integer the numbers of rows to fetch
- * @param integer the row to start to fetching
- * @param string which specifies which result class to use
- * @param mixed string which specifies which class to wrap results in
- *
- * @return MDB2_Result|MDB2_Error result set on success, a MDB2 error on failure
- * @access public
- */
- function limitQuery($query, $types, $limit, $offset = 0, $result_class = true,
- $result_wrap_class = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->setLimit($limit, $offset);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $db->query($query, $types, $result_class, $result_wrap_class);
- }
-
- // }}}
- // {{{ execParam()
-
- /**
- * Execute a parameterized DML statement.
- *
- * @param string the SQL query
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- *
- * @return int|MDB2_Error affected rows on success, a MDB2 error on failure
- * @access public
- */
- function execParam($query, $params = array(), $param_types = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->exec($query);
- }
-
- $stmt = $db->prepare($query, $param_types, MDB2_PREPARE_MANIP);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $stmt->free();
- return $result;
- }
-
- // }}}
- // {{{ getOne()
-
- /**
- * Fetch the first column of the first row of data returned from a query.
- * Takes care of doing the query and freeing the results when finished.
- *
- * @param string the SQL query
- * @param string that contains the type of the column in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int|string which column to return
- *
- * @return scalar|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getOne($query, $type = null, $params = array(),
- $param_types = null, $colnum = 0)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- settype($type, 'array');
- if (empty($params)) {
- return $db->queryOne($query, $type, $colnum);
- }
-
- $stmt = $db->prepare($query, $param_types, $type);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $one = $result->fetchOne($colnum);
- $stmt->free();
- $result->free();
- return $one;
- }
-
- // }}}
- // {{{ getRow()
-
- /**
- * Fetch the first row of data returned from a query. Takes care
- * of doing the query and freeing the results when finished.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int the fetch mode to use
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getRow($query, $types = null, $params = array(),
- $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryRow($query, $types, $fetchmode);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $row = $result->fetchRow($fetchmode);
- $stmt->free();
- $result->free();
- return $row;
- }
-
- // }}}
- // {{{ getCol()
-
- /**
- * Fetch a single column from a result set and return it as an
- * indexed array.
- *
- * @param string the SQL query
- * @param string that contains the type of the column in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int|string which column to return
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getCol($query, $type = null, $params = array(),
- $param_types = null, $colnum = 0)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- settype($type, 'array');
- if (empty($params)) {
- return $db->queryCol($query, $type, $colnum);
- }
-
- $stmt = $db->prepare($query, $param_types, $type);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $col = $result->fetchCol($colnum);
- $stmt->free();
- $result->free();
- return $col;
- }
-
- // }}}
- // {{{ getAll()
-
- /**
- * Fetch all the rows returned from a query.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int the fetch mode to use
- * @param bool if set to true, the $all will have the first
- * column as its first dimension
- * @param bool $force_array used only when the query returns exactly
- * two columns. If true, the values of the returned array will be
- * one-element arrays instead of scalars.
- * @param bool $group if true, the values of the returned array is
- * wrapped in another array. If the same key value (in the first
- * column) repeats itself, the values will be appended to this array
- * instead of overwriting the existing values.
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getAll($query, $types = null, $params = array(),
- $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
- $rekey = false, $force_array = false, $group = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryAll($query, $types, $fetchmode, $rekey, $force_array, $group);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
- $stmt->free();
- $result->free();
- return $all;
- }
-
- // }}}
- // {{{ getAssoc()
-
- /**
- * Fetch the entire result set of a query and return it as an
- * associative array using the first column as the key.
- *
- * If the result set contains more than two columns, the value
- * will be an array of the values from column 2-n. If the result
- * set contains only two columns, the returned value will be a
- * scalar with the value of the second column (unless forced to an
- * array with the $force_array parameter). A MDB2 error code is
- * returned on errors. If the result set contains fewer than two
- * columns, a MDB2_ERROR_TRUNCATED error is returned.
- *
- * For example, if the table 'mytable' contains:
- *
- * ID TEXT DATE
- * --------------------------------
- * 1 'one' 944679408
- * 2 'two' 944679408
- * 3 'three' 944679408
- *
- * Then the call getAssoc('SELECT id,text FROM mytable') returns:
- *
- * array(
- * '1' => 'one',
- * '2' => 'two',
- * '3' => 'three',
- * )
- *
- * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
- *
- * array(
- * '1' => array('one', '944679408'),
- * '2' => array('two', '944679408'),
- * '3' => array('three', '944679408')
- * )
- *
- *
- * If the more than one row occurs with the same value in the
- * first column, the last row overwrites all previous ones by
- * default. Use the $group parameter if you don't want to
- * overwrite like this. Example:
- *
- * getAssoc('SELECT category,id,name FROM mytable', null, null
- * MDB2_FETCHMODE_ASSOC, false, true) returns:
- * array(
- * '1' => array(array('id' => '4', 'name' => 'number four'),
- * array('id' => '6', 'name' => 'number six')
- * ),
- * '9' => array(array('id' => '4', 'name' => 'number four'),
- * array('id' => '6', 'name' => 'number six')
- * )
- * )
- *
- *
- * Keep in mind that database functions in PHP usually return string
- * values for results regardless of the database's internal type.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param bool $force_array used only when the query returns
- * exactly two columns. If TRUE, the values of the returned array
- * will be one-element arrays instead of scalars.
- * @param bool $group if TRUE, the values of the returned array
- * is wrapped in another array. If the same key value (in the first
- * column) repeats itself, the values will be appended to this array
- * instead of overwriting the existing values.
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getAssoc($query, $types = null, $params = array(), $param_types = null,
- $fetchmode = MDB2_FETCHMODE_DEFAULT, $force_array = false, $group = false)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryAll($query, $types, $fetchmode, true, $force_array, $group);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, true, $force_array, $group);
- $stmt->free();
- $result->free();
- return $all;
- }
-
- // }}}
- // {{{ executeMultiple()
-
- /**
- * This function does several execute() calls on the same statement handle.
- * $params must be an array indexed numerically from 0, one execute call is
- * done for every 'row' in the array.
- *
- * If an error occurs during execute(), executeMultiple() does not execute
- * the unfinished rows, but rather returns that error.
- *
- * @param resource query handle from prepare()
- * @param array numeric array containing the data to insert into the query
- *
- * @return bool|MDB2_Error true on success, a MDB2 error on failure
- * @access public
- * @see prepare(), execute()
- */
- function executeMultiple($stmt, $params = null)
- {
- if (MDB2::isError($stmt)) {
- return $stmt;
- }
- for ($i = 0, $j = count($params); $i < $j; $i++) {
- $result = $stmt->execute($params[$i]);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ getBeforeID()
-
- /**
- * Returns the next free id of a sequence if the RDBMS
- * does not support auto increment
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @param bool when true the sequence is automatic created, if it not exists
- * @param bool if the returned value should be quoted
- *
- * @return int|MDB2_Error id on success, a MDB2 error on failure
- * @access public
- */
- function getBeforeID($table, $field = null, $ondemand = true, $quote = true)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->supports('auto_increment') !== true) {
- $seq = $table.(empty($field) ? '' : '_'.$field);
- $id = $db->nextID($seq, $ondemand);
- if (!$quote || PEAR::isError($id)) {
- return $id;
- }
- return $db->quote($id, 'integer');
- } elseif (!$quote) {
- return null;
- }
- return 'NULL';
- }
-
- // }}}
- // {{{ getAfterID()
-
- /**
- * Returns the autoincrement ID if supported or $id
- *
- * @param mixed value as returned by getBeforeId()
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- *
- * @return int|MDB2_Error id on success, a MDB2 error on failure
- * @access public
- */
- function getAfterID($id, $table, $field = null)
- {
- $db = $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->supports('auto_increment') !== true) {
- return $id;
- }
- return $db->lastInsertID($table, $field);
- }
-
- // }}}
-}
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/Iterator.php b/3rdparty/MDB2/Iterator.php
deleted file mode 100644
index 46feade321..0000000000
--- a/3rdparty/MDB2/Iterator.php
+++ /dev/null
@@ -1,262 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-
-/**
- * PHP5 Iterator
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_Iterator implements Iterator
-{
- protected $fetchmode;
- /**
- * @var MDB2_Result_Common
- */
- protected $result;
- protected $row;
-
- // {{{ constructor
-
- /**
- * Constructor
- */
- public function __construct(MDB2_Result_Common $result, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $this->result = $result;
- $this->fetchmode = $fetchmode;
- }
- // }}}
-
- // {{{ seek()
-
- /**
- * Seek forward to a specific row in a result set
- *
- * @param int number of the row where the data can be found
- *
- * @return void
- * @access public
- */
- public function seek($rownum)
- {
- $this->row = null;
- if ($this->result) {
- $this->result->seek($rownum);
- }
- }
- // }}}
-
- // {{{ next()
-
- /**
- * Fetch next row of data
- *
- * @return void
- * @access public
- */
- public function next()
- {
- $this->row = null;
- }
- // }}}
-
- // {{{ current()
-
- /**
- * return a row of data
- *
- * @return void
- * @access public
- */
- public function current()
- {
- if (null === $this->row) {
- $row = $this->result->fetchRow($this->fetchmode);
- if (PEAR::isError($row)) {
- $row = false;
- }
- $this->row = $row;
- }
- return $this->row;
- }
- // }}}
-
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return bool true/false, false is also returned on failure
- * @access public
- */
- public function valid()
- {
- return (bool)$this->current();
- }
- // }}}
-
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function free()
- {
- if ($this->result) {
- return $this->result->free();
- }
- $this->result = false;
- $this->row = null;
- return false;
- }
- // }}}
-
- // {{{ key()
-
- /**
- * Returns the row number
- *
- * @return int|bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function key()
- {
- if ($this->result) {
- return $this->result->rowCount();
- }
- return false;
- }
- // }}}
-
- // {{{ rewind()
-
- /**
- * Seek to the first row in a result set
- *
- * @return void
- * @access public
- */
- public function rewind()
- {
- }
- // }}}
-
- // {{{ destructor
-
- /**
- * Destructor
- */
- public function __destruct()
- {
- $this->free();
- }
- // }}}
-}
-
-/**
- * PHP5 buffered Iterator
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_BufferedIterator extends MDB2_Iterator implements SeekableIterator
-{
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function valid()
- {
- if ($this->result) {
- return $this->result->valid();
- }
- return false;
- }
- // }}}
-
- // {{{count()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return int|MDB2_Error number of rows, false|MDB2_Error if result is invalid
- * @access public
- */
- public function count()
- {
- if ($this->result) {
- return $this->result->numRows();
- }
- return false;
- }
- // }}}
-
- // {{{ rewind()
-
- /**
- * Seek to the first row in a result set
- *
- * @return void
- * @access public
- */
- public function rewind()
- {
- $this->seek(0);
- }
- // }}}
-}
-
-?>
\ No newline at end of file
diff --git a/3rdparty/MDB2/LOB.php b/3rdparty/MDB2/LOB.php
deleted file mode 100644
index 537a77e546..0000000000
--- a/3rdparty/MDB2/LOB.php
+++ /dev/null
@@ -1,264 +0,0 @@
- |
-// +----------------------------------------------------------------------+
-//
-// $Id$
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-
-require_once 'MDB2.php';
-
-/**
- * MDB2_LOB: user land stream wrapper implementation for LOB support
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith
- */
-class MDB2_LOB
-{
- /**
- * contains the key to the global MDB2 instance array of the associated
- * MDB2 instance
- *
- * @var integer
- * @access protected
- */
- var $db_index;
-
- /**
- * contains the key to the global MDB2_LOB instance array of the associated
- * MDB2_LOB instance
- *
- * @var integer
- * @access protected
- */
- var $lob_index;
-
- // {{{ stream_open()
-
- /**
- * open stream
- *
- * @param string specifies the URL that was passed to fopen()
- * @param string the mode used to open the file
- * @param int holds additional flags set by the streams API
- * @param string not used
- *
- * @return bool
- * @access public
- */
- function stream_open($path, $mode, $options, &$opened_path)
- {
- if (!preg_match('/^rb?\+?$/', $mode)) {
- return false;
- }
- $url = parse_url($path);
- if (empty($url['host'])) {
- return false;
- }
- $this->db_index = (int)$url['host'];
- if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- return false;
- }
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $this->lob_index = (int)$url['user'];
- if (!isset($db->datatype->lobs[$this->lob_index])) {
- return false;
- }
- return true;
- }
- // }}}
-
- // {{{ stream_read()
-
- /**
- * read stream
- *
- * @param int number of bytes to read
- *
- * @return string
- * @access public
- */
- function stream_read($count)
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $db->datatype->_retrieveLOB($db->datatype->lobs[$this->lob_index]);
-
- $data = $db->datatype->_readLOB($db->datatype->lobs[$this->lob_index], $count);
- $length = strlen($data);
- if ($length == 0) {
- $db->datatype->lobs[$this->lob_index]['endOfLOB'] = true;
- }
- $db->datatype->lobs[$this->lob_index]['position'] += $length;
- return $data;
- }
- }
- // }}}
-
- // {{{ stream_write()
-
- /**
- * write stream, note implemented
- *
- * @param string data
- *
- * @return int
- * @access public
- */
- function stream_write($data)
- {
- return 0;
- }
- // }}}
-
- // {{{ stream_tell()
-
- /**
- * return the current position
- *
- * @return int current position
- * @access public
- */
- function stream_tell()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- return $db->datatype->lobs[$this->lob_index]['position'];
- }
- }
- // }}}
-
- // {{{ stream_eof()
-
- /**
- * Check if stream reaches EOF
- *
- * @return bool
- * @access public
- */
- function stream_eof()
- {
- if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- return true;
- }
-
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $result = $db->datatype->_endOfLOB($db->datatype->lobs[$this->lob_index]);
- if (version_compare(phpversion(), "5.0", ">=")
- && version_compare(phpversion(), "5.1", "<")
- ) {
- return !$result;
- }
- return $result;
- }
- // }}}
-
- // {{{ stream_seek()
-
- /**
- * Seek stream, not implemented
- *
- * @param int offset
- * @param int whence
- *
- * @return bool
- * @access public
- */
- function stream_seek($offset, $whence)
- {
- return false;
- }
- // }}}
-
- // {{{ stream_stat()
-
- /**
- * return information about stream
- *
- * @access public
- */
- function stream_stat()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- return array(
- 'db_index' => $this->db_index,
- 'lob_index' => $this->lob_index,
- );
- }
- }
- // }}}
-
- // {{{ stream_close()
-
- /**
- * close stream
- *
- * @access public
- */
- function stream_close()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- if (isset($db->datatype->lobs[$this->lob_index])) {
- $db->datatype->_destroyLOB($db->datatype->lobs[$this->lob_index]);
- unset($db->datatype->lobs[$this->lob_index]);
- }
- }
- }
- // }}}
-}
-
-// register streams wrapper
-if (!stream_wrapper_register("MDB2LOB", "MDB2_LOB")) {
- MDB2::raiseError();
- return false;
-}
-
-?>
diff --git a/3rdparty/MDB2/Schema.php b/3rdparty/MDB2/Schema.php
deleted file mode 100644
index 5eeb97b055..0000000000
--- a/3rdparty/MDB2/Schema.php
+++ /dev/null
@@ -1,2797 +0,0 @@
-
- * @author Igor Feghali
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-require_once 'MDB2.php';
-
-define('MDB2_SCHEMA_DUMP_ALL', 0);
-define('MDB2_SCHEMA_DUMP_STRUCTURE', 1);
-define('MDB2_SCHEMA_DUMP_CONTENT', 2);
-
-/**
- * If you add an error code here, make sure you also add a textual
- * version of it in MDB2_Schema::errorMessage().
- */
-
-define('MDB2_SCHEMA_ERROR', -1);
-define('MDB2_SCHEMA_ERROR_PARSE', -2);
-define('MDB2_SCHEMA_ERROR_VALIDATE', -3);
-define('MDB2_SCHEMA_ERROR_UNSUPPORTED', -4); // Driver does not support this function
-define('MDB2_SCHEMA_ERROR_INVALID', -5); // Invalid attribute value
-define('MDB2_SCHEMA_ERROR_WRITER', -6);
-
-/**
- * The database manager is a class that provides a set of database
- * management services like installing, altering and dumping the data
- * structures of databases.
- *
- * @category Database
- * @package MDB2_Schema
- * @author Lukas Smith
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema extends PEAR
-{
- // {{{ properties
-
- var $db;
-
- var $warnings = array();
-
- var $options = array(
- 'fail_on_invalid_names' => true,
- 'dtd_file' => false,
- 'valid_types' => array(),
- 'force_defaults' => true,
- 'parser' => 'MDB2_Schema_Parser',
- 'writer' => 'MDB2_Schema_Writer',
- 'validate' => 'MDB2_Schema_Validate',
- 'drop_obsolete_objects' => false
- );
-
- // }}}
- // {{{ apiVersion()
-
- /**
- * Return the MDB2 API version
- *
- * @return string the MDB2 API version number
- * @access public
- */
- function apiVersion()
- {
- return '0.4.3';
- }
-
- // }}}
- // {{{ arrayMergeClobber()
-
- /**
- * Clobbers two arrays together
- *
- * @param array $a1 array that should be clobbered
- * @param array $a2 array that should be clobbered
- *
- * @return array|false array on success and false on error
- *
- * @access public
- * @author kc@hireability.com
- */
- function arrayMergeClobber($a1, $a2)
- {
- if (!is_array($a1) || !is_array($a2)) {
- return false;
- }
- foreach ($a2 as $key => $val) {
- if (is_array($val) && array_key_exists($key, $a1) && is_array($a1[$key])) {
- $a1[$key] = MDB2_Schema::arrayMergeClobber($a1[$key], $val);
- } else {
- $a1[$key] = $val;
- }
- }
- return $a1;
- }
-
- // }}}
- // {{{ resetWarnings()
-
- /**
- * reset the warning array
- *
- * @access public
- * @return void
- */
- function resetWarnings()
- {
- $this->warnings = array();
- }
-
- // }}}
- // {{{ getWarnings()
-
- /**
- * Get all warnings in reverse order
- *
- * This means that the last warning is the first element in the array
- *
- * @return array with warnings
- * @access public
- * @see resetWarnings()
- */
- function getWarnings()
- {
- return array_reverse($this->warnings);
- }
-
- // }}}
- // {{{ setOption()
-
- /**
- * Sets the option for the db class
- *
- * @param string $option option name
- * @param mixed $value value for the option
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function setOption($option, $value)
- {
- if (isset($this->options[$option])) {
- if (is_null($value)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'may not set an option to value null');
- }
- $this->options[$option] = $value;
- return MDB2_OK;
- }
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- "unknown option $option");
- }
-
- // }}}
- // {{{ getOption()
-
- /**
- * returns the value of an option
- *
- * @param string $option option name
- *
- * @return mixed the option value or error object
- * @access public
- */
- function getOption($option)
- {
- if (isset($this->options[$option])) {
- return $this->options[$option];
- }
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED,
- null, null, "unknown option $option");
- }
-
- // }}}
- // {{{ factory()
-
- /**
- * Create a new MDB2 object for the specified database type
- * type
- *
- * @param string|array|MDB2_Driver_Common &$db 'data source name', see the
- * MDB2::parseDSN method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by @see MDB2::parseDSN.
- * Finally you can also pass an existing db object to be used.
- * @param array $options An associative array of option names and their values.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- * @see MDB2::parseDSN
- */
- static function &factory(&$db, $options = array())
- {
- $obj = new MDB2_Schema();
-
- $result = $obj->connect($db, $options);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $obj;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Create a new MDB2 connection object and connect to the specified
- * database
- *
- * @param string|array|MDB2_Driver_Common &$db 'data source name', see the
- * MDB2::parseDSN method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * Finally you can also pass an existing db object to be used.
- * @param array $options An associative array of option names and their values.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- * @see MDB2::parseDSN
- */
- function connect(&$db, $options = array())
- {
- $db_options = array();
- if (is_array($options)) {
- foreach ($options as $option => $value) {
- if (array_key_exists($option, $this->options)) {
- $result = $this->setOption($option, $value);
- if (PEAR::isError($result)) {
- return $result;
- }
- } else {
- $db_options[$option] = $value;
- }
- }
- }
-
- $this->disconnect();
- if (!MDB2::isConnection($db)) {
- $db = MDB2::factory($db, $db_options);
- }
-
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $this->db = $db;
- $this->db->loadModule('Datatype');
- $this->db->loadModule('Manager');
- $this->db->loadModule('Reverse');
- $this->db->loadModule('Function');
- if (empty($this->options['valid_types'])) {
- $this->options['valid_types'] = $this->db->datatype->getValidTypes();
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @access public
- * @return void
- */
- function disconnect()
- {
- if (MDB2::isConnection($this->db)) {
- $this->db->disconnect();
- unset($this->db);
- }
- }
-
- // }}}
- // {{{ parseDatabaseDefinition()
-
- /**
- * Parse a database definition from a file or an array
- *
- * @param string|array $schema the database schema array or file name
- * @param bool $skip_unreadable if non readable files should be skipped
- * @param array $variables associative array that the defines the text string values
- * that are meant to be used to replace the variables that are
- * used in the schema description.
- * @param bool $fail_on_invalid_names make function fail on invalid names
- * @param array $structure database structure definition
- *
- * @access public
- * @return array
- */
- function parseDatabaseDefinition($schema, $skip_unreadable = false, $variables = array(),
- $fail_on_invalid_names = true, $structure = false)
- {
- $database_definition = false;
- if (is_string($schema)) {
- // if $schema is not readable then we just skip it
- // and simply copy the $current_schema file to that file name
- if (is_readable($schema)) {
- $database_definition = $this->parseDatabaseDefinitionFile($schema, $variables, $fail_on_invalid_names, $structure);
- }
- } elseif (is_array($schema)) {
- $database_definition = $schema;
- }
- if (!$database_definition && !$skip_unreadable) {
- $database_definition = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'invalid data type of schema or unreadable data source');
- }
- return $database_definition;
- }
-
- // }}}
- // {{{ parseDatabaseDefinitionFile()
-
- /**
- * Parse a database definition file by creating a schema format
- * parser object and passing the file contents as parser input data stream.
- *
- * @param string $input_file the database schema file.
- * @param array $variables associative array that the defines the text string values
- * that are meant to be used to replace the variables that are
- * used in the schema description.
- * @param bool $fail_on_invalid_names make function fail on invalid names
- * @param array $structure database structure definition
- *
- * @access public
- * @return array
- */
- function parseDatabaseDefinitionFile($input_file, $variables = array(),
- $fail_on_invalid_names = true, $structure = false)
- {
- $dtd_file = $this->options['dtd_file'];
- if ($dtd_file) {
- include_once 'XML/DTD/XmlValidator.php';
- $dtd = new XML_DTD_XmlValidator;
- if (!$dtd->isValid($dtd_file, $input_file)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_PARSE, null, null, $dtd->getMessage());
- }
- }
-
- $class_name = $this->options['parser'];
-
- $result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $max_identifiers_length = null;
- if (isset($this->db->options['max_identifiers_length'])) {
- $max_identifiers_length = $this->db->options['max_identifiers_length'];
- }
-
- $parser = new $class_name($variables, $fail_on_invalid_names, $structure,
- $this->options['valid_types'], $this->options['force_defaults'],
- $max_identifiers_length
- );
-
- $result = $parser->setInputFile($input_file);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $result = $parser->parse();
- if (PEAR::isError($result)) {
- return $result;
- }
- if (PEAR::isError($parser->error)) {
- return $parser->error;
- }
-
- return $parser->database_definition;
- }
-
- // }}}
- // {{{ getDefinitionFromDatabase()
-
- /**
- * Attempt to reverse engineer a schema structure from an existing MDB2
- * This method can be used if no xml schema file exists yet.
- * The resulting xml schema file may need some manual adjustments.
- *
- * @return array|MDB2_Error array with definition or error object
- * @access public
- */
- function getDefinitionFromDatabase()
- {
- $database = $this->db->database_name;
- if (empty($database)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'it was not specified a valid database name');
- }
-
- $class_name = $this->options['validate'];
-
- $result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $max_identifiers_length = null;
- if (isset($this->db->options['max_identifiers_length'])) {
- $max_identifiers_length = $this->db->options['max_identifiers_length'];
- }
-
- $val = new $class_name(
- $this->options['fail_on_invalid_names'],
- $this->options['valid_types'],
- $this->options['force_defaults'],
- $max_identifiers_length
- );
-
- $database_definition = array(
- 'name' => $database,
- 'create' => true,
- 'overwrite' => false,
- 'charset' => 'utf8',
- 'description' => '',
- 'comments' => '',
- 'tables' => array(),
- 'sequences' => array(),
- );
-
- $tables = $this->db->manager->listTables();
- if (PEAR::isError($tables)) {
- return $tables;
- }
-
- foreach ($tables as $table_name) {
- $fields = $this->db->manager->listTableFields($table_name);
- if (PEAR::isError($fields)) {
- return $fields;
- }
-
- $database_definition['tables'][$table_name] = array(
- 'was' => '',
- 'description' => '',
- 'comments' => '',
- 'fields' => array(),
- 'indexes' => array(),
- 'constraints' => array(),
- 'initialization' => array()
- );
-
- $table_definition = $database_definition['tables'][$table_name];
- foreach ($fields as $field_name) {
- $definition = $this->db->reverse->getTableFieldDefinition($table_name, $field_name);
- if (PEAR::isError($definition)) {
- return $definition;
- }
-
- if (!empty($definition[0]['autoincrement'])) {
- $definition[0]['default'] = '0';
- }
-
- $table_definition['fields'][$field_name] = $definition[0];
-
- $field_choices = count($definition);
- if ($field_choices > 1) {
- $warning = "There are $field_choices type choices in the table $table_name field $field_name (#1 is the default): ";
-
- $field_choice_cnt = 1;
-
- $table_definition['fields'][$field_name]['choices'] = array();
- foreach ($definition as $field_choice) {
- $table_definition['fields'][$field_name]['choices'][] = $field_choice;
-
- $warning .= 'choice #'.($field_choice_cnt).': '.serialize($field_choice);
- $field_choice_cnt++;
- }
- $this->warnings[] = $warning;
- }
-
- /**
- * The first parameter is used to verify if there are duplicated
- * fields which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateField(array(), $table_definition['fields'][$field_name], $field_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- $keys = array();
-
- $indexes = $this->db->manager->listTableIndexes($table_name);
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- if (is_array($indexes)) {
- foreach ($indexes as $index_name) {
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- $definition = $this->db->reverse->getTableIndexDefinition($table_name, $index_name);
- $this->db->popExpect();
- if (PEAR::isError($definition)) {
- if (PEAR::isError($definition, MDB2_ERROR_NOT_FOUND)) {
- continue;
- }
- return $definition;
- }
-
- $keys[$index_name] = $definition;
- }
- }
-
- $constraints = $this->db->manager->listTableConstraints($table_name);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- if (is_array($constraints)) {
- foreach ($constraints as $constraint_name) {
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- $definition = $this->db->reverse->getTableConstraintDefinition($table_name, $constraint_name);
- $this->db->popExpect();
- if (PEAR::isError($definition)) {
- if (PEAR::isError($definition, MDB2_ERROR_NOT_FOUND)) {
- continue;
- }
- return $definition;
- }
-
- $keys[$constraint_name] = $definition;
- }
- }
-
- foreach ($keys as $key_name => $definition) {
- if (array_key_exists('foreign', $definition)
- && $definition['foreign']
- ) {
- /**
- * The first parameter is used to verify if there are duplicated
- * foreign keys which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateConstraint(array(), $definition, $key_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- foreach ($definition['fields'] as $field_name => $field) {
- /**
- * The first parameter is used to verify if there are duplicated
- * referencing fields which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateConstraintField(array(), $field_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $definition['fields'][$field_name] = '';
- }
-
- foreach ($definition['references']['fields'] as $field_name => $field) {
- /**
- * The first parameter is used to verify if there are duplicated
- * referenced fields which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateConstraintReferencedField(array(), $field_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $definition['references']['fields'][$field_name] = '';
- }
-
- $table_definition['constraints'][$key_name] = $definition;
- } else {
- /**
- * The first parameter is used to verify if there are duplicated
- * indices which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateIndex(array(), $definition, $key_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- foreach ($definition['fields'] as $field_name => $field) {
- /**
- * The first parameter is used to verify if there are duplicated
- * index fields which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateIndexField(array(), $field, $field_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $definition['fields'][$field_name] = $field;
- }
-
- $table_definition['indexes'][$key_name] = $definition;
- }
- }
-
- /**
- * The first parameter is used to verify if there are duplicated
- * tables which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateTable(array(), $table_definition, $table_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- $database_definition['tables'][$table_name]=$table_definition;
-
- }
-
- $sequences = $this->db->manager->listSequences();
- if (PEAR::isError($sequences)) {
- return $sequences;
- }
-
- if (is_array($sequences)) {
- foreach ($sequences as $sequence_name) {
- $definition = $this->db->reverse->getSequenceDefinition($sequence_name);
- if (PEAR::isError($definition)) {
- return $definition;
- }
- if (isset($database_definition['tables'][$sequence_name])
- && isset($database_definition['tables'][$sequence_name]['indexes'])
- ) {
- foreach ($database_definition['tables'][$sequence_name]['indexes'] as $index) {
- if (isset($index['primary']) && $index['primary']
- && count($index['fields'] == 1)
- ) {
- $definition['on'] = array(
- 'table' => $sequence_name,
- 'field' => key($index['fields']),
- );
- break;
- }
- }
- }
-
- /**
- * The first parameter is used to verify if there are duplicated
- * sequences which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateSequence(array(), $definition, $sequence_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $database_definition['sequences'][$sequence_name] = $definition;
- }
- }
-
- $result = $val->validateDatabase($database_definition);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- return $database_definition;
- }
-
- // }}}
- // {{{ createTableIndexes()
-
- /**
- * A method to create indexes for an existing table
- *
- * @param string $table_name Name of the table
- * @param array $indexes An array of indexes to be created
- * @param boolean $overwrite If the table/index should be overwritten if it already exists
- *
- * @return mixed MDB2_Error if there is an error creating an index, MDB2_OK otherwise
- * @access public
- */
- function createTableIndexes($table_name, $indexes, $overwrite = false)
- {
- if (!$this->db->supports('indexes')) {
- $this->db->debug('Indexes are not supported', __FUNCTION__);
- return MDB2_OK;
- }
-
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
- foreach ($indexes as $index_name => $index) {
-
- // Does the index already exist, and if so, should it be overwritten?
- $create_index = true;
- $this->db->expectError($errorcodes);
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $current_indexes = $this->db->manager->listTableConstraints($table_name);
- } else {
- $current_indexes = $this->db->manager->listTableIndexes($table_name);
- }
-
- $this->db->popExpect();
- if (PEAR::isError($current_indexes)) {
- if (!MDB2::isError($current_indexes, $errorcodes)) {
- return $current_indexes;
- }
- } elseif (is_array($current_indexes) && in_array($index_name, $current_indexes)) {
- if (!$overwrite) {
- $this->db->debug('Index already exists: '.$index_name, __FUNCTION__);
- $create_index = false;
- } else {
- $this->db->debug('Preparing to overwrite index: '.$index_name, __FUNCTION__);
-
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $result = $this->db->manager->dropConstraint($table_name, $index_name);
- } else {
- $result = $this->db->manager->dropIndex($table_name, $index_name);
- }
- $this->db->popExpect();
- if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) {
- return $result;
- }
- }
- }
-
- // Check if primary is being used and if it's supported
- if (!empty($index['primary']) && !$this->db->supports('primary_key')) {
-
- // Primary not supported so we fallback to UNIQUE and making the field NOT NULL
- $index['unique'] = true;
-
- $changes = array();
-
- foreach ($index['fields'] as $field => $empty) {
- $field_info = $this->db->reverse->getTableFieldDefinition($table_name, $field);
- if (PEAR::isError($field_info)) {
- return $field_info;
- }
- if (!$field_info[0]['notnull']) {
- $changes['change'][$field] = $field_info[0];
-
- $changes['change'][$field]['notnull'] = true;
- }
- }
- if (!empty($changes)) {
- $this->db->manager->alterTable($table_name, $changes, false);
- }
- }
-
- // Should the index be created?
- if ($create_index) {
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $result = $this->db->manager->createConstraint($table_name, $index_name, $index);
- } else {
- $result = $this->db->manager->createIndex($table_name, $index_name, $index);
- }
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ createTableConstraints()
-
- /**
- * A method to create foreign keys for an existing table
- *
- * @param string $table_name Name of the table
- * @param array $constraints An array of foreign keys to be created
- * @param boolean $overwrite If the foreign key should be overwritten if it already exists
- *
- * @return mixed MDB2_Error if there is an error creating a foreign key, MDB2_OK otherwise
- * @access public
- */
- function createTableConstraints($table_name, $constraints, $overwrite = false)
- {
- if (!$this->db->supports('indexes')) {
- $this->db->debug('Indexes are not supported', __FUNCTION__);
- return MDB2_OK;
- }
-
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
- foreach ($constraints as $constraint_name => $constraint) {
-
- // Does the foreign key already exist, and if so, should it be overwritten?
- $create_constraint = true;
- $this->db->expectError($errorcodes);
- $current_constraints = $this->db->manager->listTableConstraints($table_name);
- $this->db->popExpect();
- if (PEAR::isError($current_constraints)) {
- if (!MDB2::isError($current_constraints, $errorcodes)) {
- return $current_constraints;
- }
- } elseif (is_array($current_constraints) && in_array($constraint_name, $current_constraints)) {
- if (!$overwrite) {
- $this->db->debug('Foreign key already exists: '.$constraint_name, __FUNCTION__);
- $create_constraint = false;
- } else {
- $this->db->debug('Preparing to overwrite foreign key: '.$constraint_name, __FUNCTION__);
- $result = $this->db->manager->dropConstraint($table_name, $constraint_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- // Should the foreign key be created?
- if ($create_constraint) {
- $result = $this->db->manager->createConstraint($table_name, $constraint_name, $constraint);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ createTable()
-
- /**
- * Create a table and inititialize the table if data is available
- *
- * @param string $table_name name of the table to be created
- * @param array $table multi dimensional array that contains the
- * structure and optional data of the table
- * @param bool $overwrite if the table/index should be overwritten if it already exists
- * @param array $options an array of options to be passed to the database specific driver
- * version of MDB2_Driver_Manager_Common::createTable().
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function createTable($table_name, $table, $overwrite = false, $options = array())
- {
- $create = true;
-
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
-
- $this->db->expectError($errorcodes);
-
- $tables = $this->db->manager->listTables();
-
- $this->db->popExpect();
- if (PEAR::isError($tables)) {
- if (!MDB2::isError($tables, $errorcodes)) {
- return $tables;
- }
- } elseif (is_array($tables) && in_array($table_name, $tables)) {
- if (!$overwrite) {
- $create = false;
- $this->db->debug('Table already exists: '.$table_name, __FUNCTION__);
- } else {
- $result = $this->db->manager->dropTable($table_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->db->debug('Overwritting table: '.$table_name, __FUNCTION__);
- }
- }
-
- if ($create) {
- $result = $this->db->manager->createTable($table_name, $table['fields'], $options);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!empty($table['initialization']) && is_array($table['initialization'])) {
- $result = $this->initializeTable($table_name, $table);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!empty($table['indexes']) && is_array($table['indexes'])) {
- $result = $this->createTableIndexes($table_name, $table['indexes'], $overwrite);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!empty($table['constraints']) && is_array($table['constraints'])) {
- $result = $this->createTableConstraints($table_name, $table['constraints'], $overwrite);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ initializeTable()
-
- /**
- * Inititialize the table with data
- *
- * @param string $table_name name of the table
- * @param array $table multi dimensional array that contains the
- * structure and optional data of the table
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function initializeTable($table_name, $table)
- {
- $query_insertselect = 'INSERT INTO %s (%s) (SELECT %s FROM %s %s)';
-
- $query_insert = 'INSERT INTO %s (%s) VALUES (%s)';
- $query_update = 'UPDATE %s SET %s %s';
- $query_delete = 'DELETE FROM %s %s';
-
- $table_name = $this->db->quoteIdentifier($table_name, true);
-
- $result = MDB2_OK;
-
- $support_transactions = $this->db->supports('transactions');
-
- foreach ($table['initialization'] as $instruction) {
- $query = '';
- switch ($instruction['type']) {
- case 'insert':
- if (!isset($instruction['data']['select'])) {
- $data = $this->getInstructionFields($instruction['data'], $table['fields']);
- if (!empty($data)) {
- $fields = implode(', ', array_keys($data));
- $values = implode(', ', array_values($data));
-
- $query = sprintf($query_insert, $table_name, $fields, $values);
- }
- } else {
- $data = $this->getInstructionFields($instruction['data']['select'], $table['fields']);
- $where = $this->getInstructionWhere($instruction['data']['select'], $table['fields']);
-
- $select_table_name = $this->db->quoteIdentifier($instruction['data']['select']['table'], true);
- if (!empty($data)) {
- $fields = implode(', ', array_keys($data));
- $values = implode(', ', array_values($data));
-
- $query = sprintf($query_insertselect, $table_name, $fields, $values, $select_table_name, $where);
- }
- }
- break;
- case 'update':
- $data = $this->getInstructionFields($instruction['data'], $table['fields']);
- $where = $this->getInstructionWhere($instruction['data'], $table['fields']);
- if (!empty($data)) {
- array_walk($data, array($this, 'buildFieldValue'));
- $fields_values = implode(', ', $data);
-
- $query = sprintf($query_update, $table_name, $fields_values, $where);
- }
- break;
- case 'delete':
- $where = $this->getInstructionWhere($instruction['data'], $table['fields']);
- $query = sprintf($query_delete, $table_name, $where);
- break;
- }
- if ($query) {
- if ($support_transactions && PEAR::isError($res = $this->db->beginNestedTransaction())) {
- return $res;
- }
-
- $result = $this->db->exec($query);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($support_transactions && PEAR::isError($res = $this->db->completeNestedTransaction())) {
- return $res;
- }
- }
- }
- return $result;
- }
-
- // }}}
- // {{{ buildFieldValue()
-
- /**
- * Appends the contents of second argument + '=' to the beginning of first
- * argument.
- *
- * Used with array_walk() in initializeTable() for UPDATEs.
- *
- * @param string &$element value of array's element
- * @param string $key key of array's element
- *
- * @return void
- *
- * @access public
- * @see MDB2_Schema::initializeTable()
- */
- function buildFieldValue(&$element, $key)
- {
- $element = $key."=$element";
- }
-
- // }}}
- // {{{ getExpression()
-
- /**
- * Generates a string that represents a value that would be associated
- * with a column in a DML instruction.
- *
- * @param array $element multi dimensional array that contains the
- * structure of the current DML instruction.
- * @param array $fields_definition multi dimensional array that contains the
- * definition for current table's fields
- * @param string $type type of given field
- *
- * @return string
- *
- * @access public
- * @see MDB2_Schema::getInstructionFields(), MDB2_Schema::getInstructionWhere()
- */
- function getExpression($element, $fields_definition = array(), $type = null)
- {
- $str = '';
- switch ($element['type']) {
- case 'null':
- $str .= 'NULL';
- break;
- case 'value':
- $str .= $this->db->quote($element['data'], $type);
- break;
- case 'column':
- $str .= $this->db->quoteIdentifier($element['data'], true);
- break;
- case 'function':
- $arguments = array();
- if (!empty($element['data']['arguments'])
- && is_array($element['data']['arguments'])
- ) {
- foreach ($element['data']['arguments'] as $v) {
- $arguments[] = $this->getExpression($v, $fields_definition);
- }
- }
- if (method_exists($this->db->function, $element['data']['name'])) {
- $user_func = array(&$this->db->function, $element['data']['name']);
-
- $str .= call_user_func_array($user_func, $arguments);
- } else {
- $str .= $element['data']['name'].'(';
- $str .= implode(', ', $arguments);
- $str .= ')';
- }
- break;
- case 'expression':
- $type0 = $type1 = null;
- if ($element['data']['operants'][0]['type'] == 'column'
- && array_key_exists($element['data']['operants'][0]['data'], $fields_definition)
- ) {
- $type0 = $fields_definition[$element['data']['operants'][0]['data']]['type'];
- }
-
- if ($element['data']['operants'][1]['type'] == 'column'
- && array_key_exists($element['data']['operants'][1]['data'], $fields_definition)
- ) {
- $type1 = $fields_definition[$element['data']['operants'][1]['data']]['type'];
- }
-
- $str .= '(';
- $str .= $this->getExpression($element['data']['operants'][0], $fields_definition, $type1);
- $str .= $this->getOperator($element['data']['operator']);
- $str .= $this->getExpression($element['data']['operants'][1], $fields_definition, $type0);
- $str .= ')';
- break;
- }
-
- return $str;
- }
-
- // }}}
- // {{{ getOperator()
-
- /**
- * Returns the matching SQL operator
- *
- * @param string $op parsed descriptive operator
- *
- * @return string matching SQL operator
- *
- * @access public
- * @static
- * @see MDB2_Schema::getExpression()
- */
- function getOperator($op)
- {
- switch ($op) {
- case 'PLUS':
- return ' + ';
- case 'MINUS':
- return ' - ';
- case 'TIMES':
- return ' * ';
- case 'DIVIDED':
- return ' / ';
- case 'EQUAL':
- return ' = ';
- case 'NOT EQUAL':
- return ' != ';
- case 'LESS THAN':
- return ' < ';
- case 'GREATER THAN':
- return ' > ';
- case 'LESS THAN OR EQUAL':
- return ' <= ';
- case 'GREATER THAN OR EQUAL':
- return ' >= ';
- default:
- return ' '.$op.' ';
- }
- }
-
- // }}}
- // {{{ getInstructionFields()
-
- /**
- * Walks the parsed DML instruction array, field by field,
- * storing them and their processed values inside a new array.
- *
- * @param array $instruction multi dimensional array that contains the
- * structure of the current DML instruction.
- * @param array $fields_definition multi dimensional array that contains the
- * definition for current table's fields
- *
- * @return array array of strings in the form 'field_name' => 'value'
- *
- * @access public
- * @static
- * @see MDB2_Schema::initializeTable()
- */
- function getInstructionFields($instruction, $fields_definition = array())
- {
- $fields = array();
- if (!empty($instruction['field']) && is_array($instruction['field'])) {
- foreach ($instruction['field'] as $field) {
- $field_name = $this->db->quoteIdentifier($field['name'], true);
-
- $fields[$field_name] = $this->getExpression($field['group'], $fields_definition);
- }
- }
- return $fields;
- }
-
- // }}}
- // {{{ getInstructionWhere()
-
- /**
- * Translates the parsed WHERE expression of a DML instruction
- * (array structure) to a SQL WHERE clause (string).
- *
- * @param array $instruction multi dimensional array that contains the
- * structure of the current DML instruction.
- * @param array $fields_definition multi dimensional array that contains the
- * definition for current table's fields.
- *
- * @return string SQL WHERE clause
- *
- * @access public
- * @static
- * @see MDB2_Schema::initializeTable()
- */
- function getInstructionWhere($instruction, $fields_definition = array())
- {
- $where = '';
- if (!empty($instruction['where'])) {
- $where = 'WHERE '.$this->getExpression($instruction['where'], $fields_definition);
- }
- return $where;
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * Create a sequence
- *
- * @param string $sequence_name name of the sequence to be created
- * @param array $sequence multi dimensional array that contains the
- * structure and optional data of the table
- * @param bool $overwrite if the sequence should be overwritten if it already exists
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function createSequence($sequence_name, $sequence, $overwrite = false)
- {
- if (!$this->db->supports('sequences')) {
- $this->db->debug('Sequences are not supported', __FUNCTION__);
- return MDB2_OK;
- }
-
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
- $this->db->expectError($errorcodes);
- $sequences = $this->db->manager->listSequences();
- $this->db->popExpect();
- if (PEAR::isError($sequences)) {
- if (!MDB2::isError($sequences, $errorcodes)) {
- return $sequences;
- }
- } elseif (is_array($sequence) && in_array($sequence_name, $sequences)) {
- if (!$overwrite) {
- $this->db->debug('Sequence already exists: '.$sequence_name, __FUNCTION__);
- return MDB2_OK;
- }
-
- $result = $this->db->manager->dropSequence($sequence_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->db->debug('Overwritting sequence: '.$sequence_name, __FUNCTION__);
- }
-
- $start = 1;
- $field = '';
- if (!empty($sequence['on'])) {
- $table = $sequence['on']['table'];
- $field = $sequence['on']['field'];
-
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
- $this->db->expectError($errorcodes);
- $tables = $this->db->manager->listTables();
- $this->db->popExpect();
- if (PEAR::isError($tables) && !MDB2::isError($tables, $errorcodes)) {
- return $tables;
- }
-
- if (!PEAR::isError($tables) && is_array($tables) && in_array($table, $tables)) {
- if ($this->db->supports('summary_functions')) {
- $query = "SELECT MAX($field) FROM ".$this->db->quoteIdentifier($table, true);
- } else {
- $query = "SELECT $field FROM ".$this->db->quoteIdentifier($table, true)." ORDER BY $field DESC";
- }
- $start = $this->db->queryOne($query, 'integer');
- if (PEAR::isError($start)) {
- return $start;
- }
- ++$start;
- } else {
- $this->warnings[] = 'Could not sync sequence: '.$sequence_name;
- }
- } elseif (!empty($sequence['start']) && is_numeric($sequence['start'])) {
- $start = $sequence['start'];
- $table = '';
- }
-
- $result = $this->db->manager->createSequence($sequence_name, $start);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ createDatabase()
-
- /**
- * Create a database space within which may be created database objects
- * like tables, indexes and sequences. The implementation of this function
- * is highly DBMS specific and may require special permissions to run
- * successfully. Consult the documentation or the DBMS drivers that you
- * use to be aware of eventual configuration requirements.
- *
- * @param array $database_definition multi dimensional array that contains the current definition
- * @param array $options an array of options to be passed to the
- * database specific driver version of
- * MDB2_Driver_Manager_Common::createTable().
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function createDatabase($database_definition, $options = array())
- {
- if (!isset($database_definition['name']) || !$database_definition['name']) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'no valid database name specified');
- }
-
- $create = (isset($database_definition['create']) && $database_definition['create']);
- $overwrite = (isset($database_definition['overwrite']) && $database_definition['overwrite']);
-
- /**
- *
- * We need to clean up database name before any query to prevent
- * database driver from using a inexistent database
- *
- */
- $previous_database_name = $this->db->setDatabase('');
-
- // Lower / Upper case the db name if the portability deems so.
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $func = $this->db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper';
-
- $db_name = $func($database_definition['name']);
- } else {
- $db_name = $database_definition['name'];
- }
-
- if ($create) {
-
- $dbExists = $this->db->databaseExists($db_name);
- if (PEAR::isError($dbExists)) {
- return $dbExists;
- }
-
- if ($dbExists && $overwrite) {
- $this->db->expectError(MDB2_ERROR_CANNOT_DROP);
- $result = $this->db->manager->dropDatabase($db_name);
- $this->db->popExpect();
- if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_CANNOT_DROP)) {
- return $result;
- }
- $dbExists = false;
- $this->db->debug('Overwritting database: ' . $db_name, __FUNCTION__);
- }
-
- $dbOptions = array();
- if (array_key_exists('charset', $database_definition)
- && !empty($database_definition['charset'])) {
- $dbOptions['charset'] = $database_definition['charset'];
- }
-
- if ($dbExists) {
- $this->db->debug('Database already exists: ' . $db_name, __FUNCTION__);
- if (!empty($dbOptions)) {
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NO_PERMISSION);
- $this->db->expectError($errorcodes);
- $result = $this->db->manager->alterDatabase($db_name, $dbOptions);
- $this->db->popExpect();
- if (PEAR::isError($result) && !MDB2::isError($result, $errorcodes)) {
- return $result;
- }
- }
- $create = false;
- } else {
- $this->db->expectError(MDB2_ERROR_UNSUPPORTED);
- $result = $this->db->manager->createDatabase($db_name, $dbOptions);
- $this->db->popExpect();
- if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_UNSUPPORTED)) {
- return $result;
- }
- $this->db->debug('Creating database: ' . $db_name, __FUNCTION__);
- }
- }
-
- $this->db->setDatabase($db_name);
- if (($support_transactions = $this->db->supports('transactions'))
- && PEAR::isError($result = $this->db->beginNestedTransaction())
- ) {
- return $result;
- }
-
- $created_objects = 0;
- if (isset($database_definition['tables'])
- && is_array($database_definition['tables'])
- ) {
- foreach ($database_definition['tables'] as $table_name => $table) {
- $result = $this->createTable($table_name, $table, $overwrite, $options);
- if (PEAR::isError($result)) {
- break;
- }
- $created_objects++;
- }
- }
- if (!PEAR::isError($result)
- && isset($database_definition['sequences'])
- && is_array($database_definition['sequences'])
- ) {
- foreach ($database_definition['sequences'] as $sequence_name => $sequence) {
- $result = $this->createSequence($sequence_name, $sequence, false, $overwrite);
-
- if (PEAR::isError($result)) {
- break;
- }
- $created_objects++;
- }
- }
-
- if ($support_transactions) {
- $res = $this->db->completeNestedTransaction();
- if (PEAR::isError($res)) {
- $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'Could not end transaction ('.
- $res->getMessage().' ('.$res->getUserinfo().'))');
- }
- } elseif (PEAR::isError($result) && $created_objects) {
- $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'the database was only partially created ('.
- $result->getMessage().' ('.$result->getUserinfo().'))');
- }
-
- $this->db->setDatabase($previous_database_name);
-
- if (PEAR::isError($result) && $create
- && PEAR::isError($result2 = $this->db->manager->dropDatabase($db_name))
- ) {
- if (!MDB2::isError($result2, MDB2_ERROR_UNSUPPORTED)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'Could not drop the created database after unsuccessful creation attempt ('.
- $result2->getMessage().' ('.$result2->getUserinfo().'))');
- }
- }
-
- return $result;
- }
-
- // }}}
- // {{{ compareDefinitions()
-
- /**
- * Compare a previous definition with the currently parsed definition
- *
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- *
- * @return array|MDB2_Error array of changes on success, or a error object
- * @access public
- */
- function compareDefinitions($current_definition, $previous_definition)
- {
- $changes = array();
-
- if (!empty($current_definition['tables']) && is_array($current_definition['tables'])) {
- $changes['tables'] = $defined_tables = array();
- foreach ($current_definition['tables'] as $table_name => $table) {
- $previous_tables = array();
- if (!empty($previous_definition) && is_array($previous_definition)) {
- $previous_tables = $previous_definition['tables'];
- }
- $change = $this->compareTableDefinitions($table_name, $table, $previous_tables, $defined_tables);
- if (PEAR::isError($change)) {
- return $change;
- }
- if (!empty($change)) {
- $changes['tables'] = MDB2_Schema::arrayMergeClobber($changes['tables'], $change);
- }
- }
- }
- if (!empty($previous_definition['tables'])
- && is_array($previous_definition['tables'])
- ) {
- foreach ($previous_definition['tables'] as $table_name => $table) {
- if (empty($defined_tables[$table_name])) {
- $changes['tables']['remove'][$table_name] = true;
- }
- }
- }
-
- if (!empty($current_definition['sequences']) && is_array($current_definition['sequences'])) {
- $changes['sequences'] = $defined_sequences = array();
- foreach ($current_definition['sequences'] as $sequence_name => $sequence) {
- $previous_sequences = array();
- if (!empty($previous_definition) && is_array($previous_definition)) {
- $previous_sequences = $previous_definition['sequences'];
- }
-
- $change = $this->compareSequenceDefinitions($sequence_name,
- $sequence,
- $previous_sequences,
- $defined_sequences);
- if (PEAR::isError($change)) {
- return $change;
- }
- if (!empty($change)) {
- $changes['sequences'] = MDB2_Schema::arrayMergeClobber($changes['sequences'], $change);
- }
- }
- }
- if (!empty($previous_definition['sequences'])
- && is_array($previous_definition['sequences'])
- ) {
- foreach ($previous_definition['sequences'] as $sequence_name => $sequence) {
- if (empty($defined_sequences[$sequence_name])) {
- $changes['sequences']['remove'][$sequence_name] = true;
- }
- }
- }
-
- return $changes;
- }
-
- // }}}
- // {{{ compareTableFieldsDefinitions()
-
- /**
- * Compare a previous definition with the currently parsed definition
- *
- * @param string $table_name name of the table
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- *
- * @return array|MDB2_Error array of changes on success, or a error object
- * @access public
- */
- function compareTableFieldsDefinitions($table_name, $current_definition,
- $previous_definition)
- {
- $changes = $defined_fields = array();
-
- if (is_array($current_definition)) {
- foreach ($current_definition as $field_name => $field) {
- $was_field_name = $field['was'];
- if (!empty($previous_definition[$field_name])
- && (
- (isset($previous_definition[$field_name]['was'])
- && $previous_definition[$field_name]['was'] == $was_field_name)
- || !isset($previous_definition[$was_field_name])
- )) {
- $was_field_name = $field_name;
- }
-
- if (!empty($previous_definition[$was_field_name])) {
- if ($was_field_name != $field_name) {
- $changes['rename'][$was_field_name] = array('name' => $field_name, 'definition' => $field);
- }
-
- if (!empty($defined_fields[$was_field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'the field "'.$was_field_name.
- '" was specified for more than one field of table');
- }
-
- $defined_fields[$was_field_name] = true;
-
- $change = $this->db->compareDefinition($field, $previous_definition[$was_field_name]);
- if (PEAR::isError($change)) {
- return $change;
- }
-
- if (!empty($change)) {
- if (array_key_exists('default', $change)
- && $change['default']
- && !array_key_exists('default', $field)) {
- $field['default'] = null;
- }
-
- $change['definition'] = $field;
-
- $changes['change'][$field_name] = $change;
- }
- } else {
- if ($field_name != $was_field_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'it was specified a previous field name ("'.
- $was_field_name.'") for field "'.$field_name.'" of table "'.
- $table_name.'" that does not exist');
- }
-
- $changes['add'][$field_name] = $field;
- }
- }
- }
-
- if (isset($previous_definition) && is_array($previous_definition)) {
- foreach ($previous_definition as $field_previous_name => $field_previous) {
- if (empty($defined_fields[$field_previous_name])) {
- $changes['remove'][$field_previous_name] = true;
- }
- }
- }
-
- return $changes;
- }
-
- // }}}
- // {{{ compareTableIndexesDefinitions()
-
- /**
- * Compare a previous definition with the currently parsed definition
- *
- * @param string $table_name name of the table
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- *
- * @return array|MDB2_Error array of changes on success, or a error object
- * @access public
- */
- function compareTableIndexesDefinitions($table_name, $current_definition,
- $previous_definition)
- {
- $changes = $defined_indexes = array();
-
- if (is_array($current_definition)) {
- foreach ($current_definition as $index_name => $index) {
- $was_index_name = $index['was'];
- if (!empty($previous_definition[$index_name])
- && isset($previous_definition[$index_name]['was'])
- && $previous_definition[$index_name]['was'] == $was_index_name
- ) {
- $was_index_name = $index_name;
- }
- if (!empty($previous_definition[$was_index_name])) {
- $change = array();
- if ($was_index_name != $index_name) {
- $change['name'] = $was_index_name;
- }
-
- if (!empty($defined_indexes[$was_index_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'the index "'.$was_index_name.'" was specified for'.
- ' more than one index of table "'.$table_name.'"');
- }
- $defined_indexes[$was_index_name] = true;
-
- $previous_unique = array_key_exists('unique', $previous_definition[$was_index_name])
- ? $previous_definition[$was_index_name]['unique'] : false;
-
- $unique = array_key_exists('unique', $index) ? $index['unique'] : false;
- if ($previous_unique != $unique) {
- $change['unique'] = $unique;
- }
-
- $previous_primary = array_key_exists('primary', $previous_definition[$was_index_name])
- ? $previous_definition[$was_index_name]['primary'] : false;
-
- $primary = array_key_exists('primary', $index) ? $index['primary'] : false;
- if ($previous_primary != $primary) {
- $change['primary'] = $primary;
- }
-
- $defined_fields = array();
- $previous_fields = $previous_definition[$was_index_name]['fields'];
- if (!empty($index['fields']) && is_array($index['fields'])) {
- foreach ($index['fields'] as $field_name => $field) {
- if (!empty($previous_fields[$field_name])) {
- $defined_fields[$field_name] = true;
-
- $previous_sorting = array_key_exists('sorting', $previous_fields[$field_name])
- ? $previous_fields[$field_name]['sorting'] : '';
-
- $sorting = array_key_exists('sorting', $field) ? $field['sorting'] : '';
- if ($previous_sorting != $sorting) {
- $change['change'] = true;
- }
- } else {
- $change['change'] = true;
- }
- }
- }
- if (isset($previous_fields) && is_array($previous_fields)) {
- foreach ($previous_fields as $field_name => $field) {
- if (empty($defined_fields[$field_name])) {
- $change['change'] = true;
- }
- }
- }
- if (!empty($change)) {
- $changes['change'][$index_name] = $current_definition[$index_name];
- }
- } else {
- if ($index_name != $was_index_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'it was specified a previous index name ("'.$was_index_name.
- ') for index "'.$index_name.'" of table "'.$table_name.'" that does not exist');
- }
- $changes['add'][$index_name] = $current_definition[$index_name];
- }
- }
- }
- foreach ($previous_definition as $index_previous_name => $index_previous) {
- if (empty($defined_indexes[$index_previous_name])) {
- $changes['remove'][$index_previous_name] = $index_previous;
- }
- }
- return $changes;
- }
-
- // }}}
- // {{{ compareTableDefinitions()
-
- /**
- * Compare a previous definition with the currently parsed definition
- *
- * @param string $table_name name of the table
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- * @param array &$defined_tables table names in the schema
- *
- * @return array|MDB2_Error array of changes on success, or a error object
- * @access public
- */
- function compareTableDefinitions($table_name, $current_definition,
- $previous_definition, &$defined_tables)
- {
- $changes = array();
-
- if (is_array($current_definition)) {
- $was_table_name = $table_name;
- if (!empty($current_definition['was'])) {
- $was_table_name = $current_definition['was'];
- }
- if (!empty($previous_definition[$was_table_name])) {
- $changes['change'][$was_table_name] = array();
- if ($was_table_name != $table_name) {
- $changes['change'][$was_table_name] = array('name' => $table_name);
- }
- if (!empty($defined_tables[$was_table_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'the table "'.$was_table_name.
- '" was specified for more than one table of the database');
- }
- $defined_tables[$was_table_name] = true;
- if (!empty($current_definition['fields']) && is_array($current_definition['fields'])) {
- $previous_fields = array();
- if (isset($previous_definition[$was_table_name]['fields'])
- && is_array($previous_definition[$was_table_name]['fields'])) {
- $previous_fields = $previous_definition[$was_table_name]['fields'];
- }
-
- $change = $this->compareTableFieldsDefinitions($table_name,
- $current_definition['fields'],
- $previous_fields);
-
- if (PEAR::isError($change)) {
- return $change;
- }
- if (!empty($change)) {
- $changes['change'][$was_table_name] =
- MDB2_Schema::arrayMergeClobber($changes['change'][$was_table_name], $change);
- }
- }
- if (!empty($current_definition['indexes']) && is_array($current_definition['indexes'])) {
- $previous_indexes = array();
- if (isset($previous_definition[$was_table_name]['indexes'])
- && is_array($previous_definition[$was_table_name]['indexes'])) {
- $previous_indexes = $previous_definition[$was_table_name]['indexes'];
- }
- $change = $this->compareTableIndexesDefinitions($table_name,
- $current_definition['indexes'],
- $previous_indexes);
-
- if (PEAR::isError($change)) {
- return $change;
- }
- if (!empty($change)) {
- $changes['change'][$was_table_name]['indexes'] = $change;
- }
- }
- if (empty($changes['change'][$was_table_name])) {
- unset($changes['change'][$was_table_name]);
- }
- if (empty($changes['change'])) {
- unset($changes['change']);
- }
- } else {
- if ($table_name != $was_table_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'it was specified a previous table name ("'.$was_table_name.
- '") for table "'.$table_name.'" that does not exist');
- }
- $changes['add'][$table_name] = true;
- }
- }
-
- return $changes;
- }
-
- // }}}
- // {{{ compareSequenceDefinitions()
-
- /**
- * Compare a previous definition with the currently parsed definition
- *
- * @param string $sequence_name name of the sequence
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- * @param array &$defined_sequences names in the schema
- *
- * @return array|MDB2_Error array of changes on success, or a error object
- * @access public
- */
- function compareSequenceDefinitions($sequence_name, $current_definition,
- $previous_definition, &$defined_sequences)
- {
- $changes = array();
-
- if (is_array($current_definition)) {
- $was_sequence_name = $sequence_name;
- if (!empty($previous_definition[$sequence_name])
- && isset($previous_definition[$sequence_name]['was'])
- && $previous_definition[$sequence_name]['was'] == $was_sequence_name
- ) {
- $was_sequence_name = $sequence_name;
- } elseif (!empty($current_definition['was'])) {
- $was_sequence_name = $current_definition['was'];
- }
- if (!empty($previous_definition[$was_sequence_name])) {
- if ($was_sequence_name != $sequence_name) {
- $changes['change'][$was_sequence_name]['name'] = $sequence_name;
- }
-
- if (!empty($defined_sequences[$was_sequence_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'the sequence "'.$was_sequence_name.'" was specified as base'.
- ' of more than of sequence of the database');
- }
-
- $defined_sequences[$was_sequence_name] = true;
-
- $change = array();
- if (!empty($current_definition['start'])
- && isset($previous_definition[$was_sequence_name]['start'])
- && $current_definition['start'] != $previous_definition[$was_sequence_name]['start']
- ) {
- $change['start'] = $previous_definition[$sequence_name]['start'];
- }
- if (isset($current_definition['on']['table'])
- && isset($previous_definition[$was_sequence_name]['on']['table'])
- && $current_definition['on']['table'] != $previous_definition[$was_sequence_name]['on']['table']
- && isset($current_definition['on']['field'])
- && isset($previous_definition[$was_sequence_name]['on']['field'])
- && $current_definition['on']['field'] != $previous_definition[$was_sequence_name]['on']['field']
- ) {
- $change['on'] = $current_definition['on'];
- }
- if (!empty($change)) {
- $changes['change'][$was_sequence_name][$sequence_name] = $change;
- }
- } else {
- if ($sequence_name != $was_sequence_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'it was specified a previous sequence name ("'.$was_sequence_name.
- '") for sequence "'.$sequence_name.'" that does not exist');
- }
- $changes['add'][$sequence_name] = true;
- }
- }
- return $changes;
- }
- // }}}
- // {{{ verifyAlterDatabase()
-
- /**
- * Verify that the changes requested are supported
- *
- * @param array $changes associative array that contains the definition of the changes
- * that are meant to be applied to the database structure.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function verifyAlterDatabase($changes)
- {
- if (!empty($changes['tables']['change']) && is_array($changes['tables']['change'])) {
- foreach ($changes['tables']['change'] as $table_name => $table) {
- if (!empty($table['indexes']) && is_array($table['indexes'])) {
- if (!$this->db->supports('indexes')) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- 'indexes are not supported');
- }
- $table_changes = count($table['indexes']);
- if (!empty($table['indexes']['add'])) {
- $table_changes--;
- }
- if (!empty($table['indexes']['remove'])) {
- $table_changes--;
- }
- if (!empty($table['indexes']['change'])) {
- $table_changes--;
- }
- if ($table_changes) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- 'index alteration not yet supported: '.implode(', ', array_keys($table['indexes'])));
- }
- }
- unset($table['indexes']);
- $result = $this->db->manager->alterTable($table_name, $table, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- if (!empty($changes['sequences']) && is_array($changes['sequences'])) {
- if (!$this->db->supports('sequences')) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- 'sequences are not supported');
- }
- $sequence_changes = count($changes['sequences']);
- if (!empty($changes['sequences']['add'])) {
- $sequence_changes--;
- }
- if (!empty($changes['sequences']['remove'])) {
- $sequence_changes--;
- }
- if (!empty($changes['sequences']['change'])) {
- $sequence_changes--;
- }
- if ($sequence_changes) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- 'sequence alteration not yet supported: '.implode(', ', array_keys($changes['sequences'])));
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ alterDatabaseIndexes()
-
- /**
- * Execute the necessary actions to implement the requested changes
- * in the indexes inside a database structure.
- *
- * @param string $table_name name of the table
- * @param array $changes associative array that contains the definition of the changes
- * that are meant to be applied to the database structure.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function alterDatabaseIndexes($table_name, $changes)
- {
- $alterations = 0;
- if (empty($changes)) {
- return $alterations;
- }
-
- if (!empty($changes['remove']) && is_array($changes['remove'])) {
- foreach ($changes['remove'] as $index_name => $index) {
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $result = $this->db->manager->dropConstraint($table_name, $index_name, !empty($index['primary']));
- } else {
- $result = $this->db->manager->dropIndex($table_name, $index_name);
- }
- $this->db->popExpect();
- if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) {
- return $result;
- }
- $alterations++;
- }
- }
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $index_name => $index) {
- /**
- * Drop existing index/constraint first.
- * Since $changes doesn't tell us whether it's an index or a constraint before the change,
- * we have to find out and call the appropriate method.
- */
- if (in_array($index_name, $this->db->manager->listTableIndexes($table_name))) {
- $result = $this->db->manager->dropIndex($table_name, $index_name);
- } elseif (in_array($index_name, $this->db->manager->listTableConstraints($table_name))) {
- $result = $this->db->manager->dropConstraint($table_name, $index_name);
- }
- if (!empty($result) && PEAR::isError($result)) {
- return $result;
- }
-
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $result = $this->db->manager->createConstraint($table_name, $index_name, $index);
- } else {
- $result = $this->db->manager->createIndex($table_name, $index_name, $index);
- }
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $index_name => $index) {
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $result = $this->db->manager->createConstraint($table_name, $index_name, $index);
- } else {
- $result = $this->db->manager->createIndex($table_name, $index_name, $index);
- }
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- return $alterations;
- }
-
- // }}}
- // {{{ alterDatabaseTables()
-
- /**
- * Execute the necessary actions to implement the requested changes
- * in the tables inside a database structure.
- *
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- * @param array $changes associative array that contains the definition of the changes
- * that are meant to be applied to the database structure.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function alterDatabaseTables($current_definition, $previous_definition, $changes)
- {
- /* FIXME: tables marked to be added are initialized by createTable(), others don't */
- $alterations = 0;
- if (empty($changes)) {
- return $alterations;
- }
-
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $table_name => $table) {
- $result = $this->createTable($table_name, $current_definition[$table_name]);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- if ($this->options['drop_obsolete_objects']
- && !empty($changes['remove'])
- && is_array($changes['remove'])
- ) {
- foreach ($changes['remove'] as $table_name => $table) {
- $result = $this->db->manager->dropTable($table_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $table_name => $table) {
- $indexes = array();
- if (!empty($table['indexes'])) {
- $indexes = $table['indexes'];
- unset($table['indexes']);
- }
- if (!empty($indexes['remove'])) {
- $result = $this->alterDatabaseIndexes($table_name, array('remove' => $indexes['remove']));
- if (PEAR::isError($result)) {
- return $result;
- }
- unset($indexes['remove']);
- $alterations += $result;
- }
- $result = $this->db->manager->alterTable($table_name, $table, false);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
-
- // table may be renamed at this point
- if (!empty($table['name'])) {
- $table_name = $table['name'];
- }
-
- if (!empty($indexes)) {
- $result = $this->alterDatabaseIndexes($table_name, $indexes);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations += $result;
- }
- }
- }
-
- return $alterations;
- }
-
- // }}}
- // {{{ alterDatabaseSequences()
-
- /**
- * Execute the necessary actions to implement the requested changes
- * in the sequences inside a database structure.
- *
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- * @param array $changes associative array that contains the definition of the changes
- * that are meant to be applied to the database structure.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function alterDatabaseSequences($current_definition, $previous_definition, $changes)
- {
- $alterations = 0;
- if (empty($changes)) {
- return $alterations;
- }
-
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $sequence_name => $sequence) {
- $result = $this->createSequence($sequence_name, $current_definition[$sequence_name]);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- if ($this->options['drop_obsolete_objects']
- && !empty($changes['remove'])
- && is_array($changes['remove'])
- ) {
- foreach ($changes['remove'] as $sequence_name => $sequence) {
- $result = $this->db->manager->dropSequence($sequence_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $sequence_name => $sequence) {
- $result = $this->db->manager->dropSequence($previous_definition[$sequence_name]['was']);
- if (PEAR::isError($result)) {
- return $result;
- }
- $result = $this->createSequence($sequence_name, $sequence);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- return $alterations;
- }
-
- // }}}
- // {{{ alterDatabase()
-
- /**
- * Execute the necessary actions to implement the requested changes
- * in a database structure.
- *
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- * @param array $changes associative array that contains the definition of the changes
- * that are meant to be applied to the database structure.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function alterDatabase($current_definition, $previous_definition, $changes)
- {
- $alterations = 0;
- if (empty($changes)) {
- return $alterations;
- }
-
- $result = $this->verifyAlterDatabase($changes);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if (!empty($current_definition['name'])) {
- $previous_database_name = $this->db->setDatabase($current_definition['name']);
- }
-
- if (($support_transactions = $this->db->supports('transactions'))
- && PEAR::isError($result = $this->db->beginNestedTransaction())
- ) {
- return $result;
- }
-
- if (!empty($changes['tables']) && !empty($current_definition['tables'])) {
- $current_tables = isset($current_definition['tables']) ? $current_definition['tables'] : array();
- $previous_tables = isset($previous_definition['tables']) ? $previous_definition['tables'] : array();
-
- $result = $this->alterDatabaseTables($current_tables, $previous_tables, $changes['tables']);
- if (is_numeric($result)) {
- $alterations += $result;
- }
- }
-
- if (!PEAR::isError($result) && !empty($changes['sequences'])) {
- $current_sequences = isset($current_definition['sequences']) ? $current_definition['sequences'] : array();
- $previous_sequences = isset($previous_definition['sequences']) ? $previous_definition['sequences'] : array();
-
- $result = $this->alterDatabaseSequences($current_sequences, $previous_sequences, $changes['sequences']);
- if (is_numeric($result)) {
- $alterations += $result;
- }
- }
-
- if ($support_transactions) {
- $res = $this->db->completeNestedTransaction();
- if (PEAR::isError($res)) {
- $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'Could not end transaction ('.
- $res->getMessage().' ('.$res->getUserinfo().'))');
- }
- } elseif (PEAR::isError($result) && $alterations) {
- $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'the requested database alterations were only partially implemented ('.
- $result->getMessage().' ('.$result->getUserinfo().'))');
- }
-
- if (isset($previous_database_name)) {
- $this->db->setDatabase($previous_database_name);
- }
- return $result;
- }
-
- // }}}
- // {{{ dumpDatabaseChanges()
-
- /**
- * Dump the changes between two database definitions.
- *
- * @param array $changes associative array that specifies the list of database
- * definitions changes as returned by the _compareDefinitions
- * manager class function.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function dumpDatabaseChanges($changes)
- {
- if (!empty($changes['tables'])) {
- if (!empty($changes['tables']['add']) && is_array($changes['tables']['add'])) {
- foreach ($changes['tables']['add'] as $table_name => $table) {
- $this->db->debug("$table_name:", __FUNCTION__);
- $this->db->debug("\tAdded table '$table_name'", __FUNCTION__);
- }
- }
-
- if (!empty($changes['tables']['remove']) && is_array($changes['tables']['remove'])) {
- if ($this->options['drop_obsolete_objects']) {
- foreach ($changes['tables']['remove'] as $table_name => $table) {
- $this->db->debug("$table_name:", __FUNCTION__);
- $this->db->debug("\tRemoved table '$table_name'", __FUNCTION__);
- }
- } else {
- foreach ($changes['tables']['remove'] as $table_name => $table) {
- $this->db->debug("\tObsolete table '$table_name' left as is", __FUNCTION__);
- }
- }
- }
-
- if (!empty($changes['tables']['change']) && is_array($changes['tables']['change'])) {
- foreach ($changes['tables']['change'] as $table_name => $table) {
- if (array_key_exists('name', $table)) {
- $this->db->debug("\tRenamed table '$table_name' to '".$table['name']."'", __FUNCTION__);
- }
- if (!empty($table['add']) && is_array($table['add'])) {
- foreach ($table['add'] as $field_name => $field) {
- $this->db->debug("\tAdded field '".$field_name."'", __FUNCTION__);
- }
- }
- if (!empty($table['remove']) && is_array($table['remove'])) {
- foreach ($table['remove'] as $field_name => $field) {
- $this->db->debug("\tRemoved field '".$field_name."'", __FUNCTION__);
- }
- }
- if (!empty($table['rename']) && is_array($table['rename'])) {
- foreach ($table['rename'] as $field_name => $field) {
- $this->db->debug("\tRenamed field '".$field_name."' to '".$field['name']."'", __FUNCTION__);
- }
- }
- if (!empty($table['change']) && is_array($table['change'])) {
- foreach ($table['change'] as $field_name => $field) {
- $field = $field['definition'];
- if (array_key_exists('type', $field)) {
- $this->db->debug("\tChanged field '$field_name' type to '".$field['type']."'", __FUNCTION__);
- }
-
- if (array_key_exists('unsigned', $field)) {
- $this->db->debug("\tChanged field '$field_name' type to '".
- (!empty($field['unsigned']) && $field['unsigned'] ? '' : 'not ')."unsigned'",
- __FUNCTION__);
- }
-
- if (array_key_exists('length', $field)) {
- $this->db->debug("\tChanged field '$field_name' length to '".
- (!empty($field['length']) ? $field['length']: 'no length')."'", __FUNCTION__);
- }
- if (array_key_exists('default', $field)) {
- $this->db->debug("\tChanged field '$field_name' default to ".
- (isset($field['default']) ? "'".$field['default']."'" : 'NULL'), __FUNCTION__);
- }
-
- if (array_key_exists('notnull', $field)) {
- $this->db->debug("\tChanged field '$field_name' notnull to ".
- (!empty($field['notnull']) && $field['notnull'] ? 'true' : 'false'),
- __FUNCTION__);
- }
- }
- }
- if (!empty($table['indexes']) && is_array($table['indexes'])) {
- if (!empty($table['indexes']['add']) && is_array($table['indexes']['add'])) {
- foreach ($table['indexes']['add'] as $index_name => $index) {
- $this->db->debug("\tAdded index '".$index_name.
- "' of table '$table_name'", __FUNCTION__);
- }
- }
- if (!empty($table['indexes']['remove']) && is_array($table['indexes']['remove'])) {
- foreach ($table['indexes']['remove'] as $index_name => $index) {
- $this->db->debug("\tRemoved index '".$index_name.
- "' of table '$table_name'", __FUNCTION__);
- }
- }
- if (!empty($table['indexes']['change']) && is_array($table['indexes']['change'])) {
- foreach ($table['indexes']['change'] as $index_name => $index) {
- if (array_key_exists('name', $index)) {
- $this->db->debug("\tRenamed index '".$index_name."' to '".$index['name'].
- "' on table '$table_name'", __FUNCTION__);
- }
- if (array_key_exists('unique', $index)) {
- $this->db->debug("\tChanged index '".$index_name."' unique to '".
- !empty($index['unique'])."' on table '$table_name'", __FUNCTION__);
- }
- if (array_key_exists('primary', $index)) {
- $this->db->debug("\tChanged index '".$index_name."' primary to '".
- !empty($index['primary'])."' on table '$table_name'", __FUNCTION__);
- }
- if (array_key_exists('change', $index)) {
- $this->db->debug("\tChanged index '".$index_name.
- "' on table '$table_name'", __FUNCTION__);
- }
- }
- }
- }
- }
- }
- }
- if (!empty($changes['sequences'])) {
- if (!empty($changes['sequences']['add']) && is_array($changes['sequences']['add'])) {
- foreach ($changes['sequences']['add'] as $sequence_name => $sequence) {
- $this->db->debug("$sequence_name:", __FUNCTION__);
- $this->db->debug("\tAdded sequence '$sequence_name'", __FUNCTION__);
- }
- }
- if (!empty($changes['sequences']['remove']) && is_array($changes['sequences']['remove'])) {
- if ($this->options['drop_obsolete_objects']) {
- foreach ($changes['sequences']['remove'] as $sequence_name => $sequence) {
- $this->db->debug("$sequence_name:", __FUNCTION__);
- $this->db->debug("\tRemoved sequence '$sequence_name'", __FUNCTION__);
- }
- } else {
- foreach ($changes['sequences']['remove'] as $sequence_name => $sequence) {
- $this->db->debug("\tObsolete sequence '$sequence_name' left as is", __FUNCTION__);
- }
- }
- }
- if (!empty($changes['sequences']['change']) && is_array($changes['sequences']['change'])) {
- foreach ($changes['sequences']['change'] as $sequence_name => $sequence) {
- if (array_key_exists('name', $sequence)) {
- $this->db->debug("\tRenamed sequence '$sequence_name' to '".
- $sequence['name']."'", __FUNCTION__);
- }
- if (!empty($sequence['change']) && is_array($sequence['change'])) {
- foreach ($sequence['change'] as $sequence_name => $sequence) {
- if (array_key_exists('start', $sequence)) {
- $this->db->debug("\tChanged sequence '$sequence_name' start to '".
- $sequence['start']."'", __FUNCTION__);
- }
- }
- }
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dumpDatabase()
-
- /**
- * Dump a previously parsed database structure in the Metabase schema
- * XML based format suitable for the Metabase parser. This function
- * may optionally dump the database definition with initialization
- * commands that specify the data that is currently present in the tables.
- *
- * @param array $database_definition multi dimensional array that contains the current definition
- * @param array $arguments associative array that takes pairs of tag
- * names and values that define dump options.
- * array (
- * 'output_mode' => String
- * 'file' : dump into a file
- * default: dump using a function
- * 'output' => String
- * depending on the 'Output_Mode'
- * name of the file
- * name of the function
- * 'end_of_line' => String
- * end of line delimiter that should be used
- * default: "\n"
- * );
- * @param int $dump Int that determines what data to dump
- * + MDB2_SCHEMA_DUMP_ALL : the entire db
- * + MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
- * + MDB2_SCHEMA_DUMP_CONTENT : only the content of the db
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function dumpDatabase($database_definition, $arguments, $dump = MDB2_SCHEMA_DUMP_ALL)
- {
- $class_name = $this->options['writer'];
-
- $result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
- if (PEAR::isError($result)) {
- return $result;
- }
-
- // get initialization data
- if (isset($database_definition['tables']) && is_array($database_definition['tables'])
- && $dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT
- ) {
- foreach ($database_definition['tables'] as $table_name => $table) {
- $fields = array();
- $fieldsq = array();
- foreach ($table['fields'] as $field_name => $field) {
- $fields[$field_name] = $field['type'];
-
- $fieldsq[] = $this->db->quoteIdentifier($field_name, true);
- }
-
- $query = 'SELECT '.implode(', ', $fieldsq).' FROM ';
- $query .= $this->db->quoteIdentifier($table_name, true);
-
- $data = $this->db->queryAll($query, $fields, MDB2_FETCHMODE_ASSOC);
-
- if (PEAR::isError($data)) {
- return $data;
- }
-
- if (!empty($data)) {
- $initialization = array();
- $lob_buffer_length = $this->db->getOption('lob_buffer_length');
- foreach ($data as $row) {
- $rows = array();
- foreach ($row as $key => $lob) {
- if (is_resource($lob)) {
- $value = '';
- while (!feof($lob)) {
- $value .= fread($lob, $lob_buffer_length);
- }
- $row[$key] = $value;
- }
- $rows[] = array('name' => $key, 'group' => array('type' => 'value', 'data' => $row[$key]));
- }
- $initialization[] = array('type' => 'insert', 'data' => array('field' => $rows));
- }
- $database_definition['tables'][$table_name]['initialization'] = $initialization;
- }
- }
- }
-
- $writer = new $class_name($this->options['valid_types']);
- return $writer->dumpDatabase($database_definition, $arguments, $dump);
- }
-
- // }}}
- // {{{ writeInitialization()
-
- /**
- * Write initialization and sequences
- *
- * @param string|array $data data file or data array
- * @param string|array $structure structure file or array
- * @param array $variables associative array that is passed to the argument
- * of the same name to the parseDatabaseDefinitionFile function. (there third
- * param)
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function writeInitialization($data, $structure = false, $variables = array())
- {
- if ($structure) {
- $structure = $this->parseDatabaseDefinition($structure, false, $variables);
- if (PEAR::isError($structure)) {
- return $structure;
- }
- }
-
- $data = $this->parseDatabaseDefinition($data, false, $variables, false, $structure);
- if (PEAR::isError($data)) {
- return $data;
- }
-
- $previous_database_name = null;
- if (!empty($data['name'])) {
- $previous_database_name = $this->db->setDatabase($data['name']);
- } elseif (!empty($structure['name'])) {
- $previous_database_name = $this->db->setDatabase($structure['name']);
- }
-
- if (!empty($data['tables']) && is_array($data['tables'])) {
- foreach ($data['tables'] as $table_name => $table) {
- if (empty($table['initialization'])) {
- continue;
- }
- $result = $this->initializeTable($table_name, $table);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($structure['sequences']) && is_array($structure['sequences'])) {
- foreach ($structure['sequences'] as $sequence_name => $sequence) {
- if (isset($data['sequences'][$sequence_name])
- || !isset($sequence['on']['table'])
- || !isset($data['tables'][$sequence['on']['table']])
- ) {
- continue;
- }
- $result = $this->createSequence($sequence_name, $sequence, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- if (!empty($data['sequences']) && is_array($data['sequences'])) {
- foreach ($data['sequences'] as $sequence_name => $sequence) {
- $result = $this->createSequence($sequence_name, $sequence, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (isset($previous_database_name)) {
- $this->db->setDatabase($previous_database_name);
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ updateDatabase()
-
- /**
- * Compare the correspondent files of two versions of a database schema
- * definition: the previously installed and the one that defines the schema
- * that is meant to update the database.
- * If the specified previous definition file does not exist, this function
- * will create the database from the definition specified in the current
- * schema file.
- * If both files exist, the function assumes that the database was previously
- * installed based on the previous schema file and will update it by just
- * applying the changes.
- * If this function succeeds, the contents of the current schema file are
- * copied to replace the previous schema file contents. Any subsequent schema
- * changes should only be done on the file specified by the $current_schema_file
- * to let this function make a consistent evaluation of the exact changes that
- * need to be applied.
- *
- * @param string|array $current_schema filename or array of the updated database schema definition.
- * @param string|array $previous_schema filename or array of the previously installed database schema definition.
- * @param array $variables associative array that is passed to the argument of the same
- * name to the parseDatabaseDefinitionFile function. (there third param)
- * @param bool $disable_query determines if the disable_query option should be set to true
- * for the alterDatabase() or createDatabase() call
- * @param bool $overwrite_old_schema_file Overwrite?
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function updateDatabase($current_schema, $previous_schema = false,
- $variables = array(), $disable_query = false,
- $overwrite_old_schema_file = false)
- {
- $current_definition = $this->parseDatabaseDefinition($current_schema, false, $variables,
- $this->options['fail_on_invalid_names']);
-
- if (PEAR::isError($current_definition)) {
- return $current_definition;
- }
-
- $previous_definition = false;
- if ($previous_schema) {
- $previous_definition = $this->parseDatabaseDefinition($previous_schema, true, $variables,
- $this->options['fail_on_invalid_names']);
- if (PEAR::isError($previous_definition)) {
- return $previous_definition;
- }
- }
-
- if ($previous_definition) {
- $dbExists = $this->db->databaseExists($current_definition['name']);
- if (PEAR::isError($dbExists)) {
- return $dbExists;
- }
-
- if (!$dbExists) {
- return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'database to update does not exist: '.$current_definition['name']);
- }
-
- $changes = $this->compareDefinitions($current_definition, $previous_definition);
- if (PEAR::isError($changes)) {
- return $changes;
- }
-
- if (is_array($changes)) {
- $this->db->setOption('disable_query', $disable_query);
- $result = $this->alterDatabase($current_definition, $previous_definition, $changes);
- $this->db->setOption('disable_query', false);
- if (PEAR::isError($result)) {
- return $result;
- }
- $copy = true;
- if ($this->db->options['debug']) {
- $result = $this->dumpDatabaseChanges($changes);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- } else {
- $this->db->setOption('disable_query', $disable_query);
- $result = $this->createDatabase($current_definition);
- $this->db->setOption('disable_query', false);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if ($overwrite_old_schema_file
- && !$disable_query
- && is_string($previous_schema) && is_string($current_schema)
- && !copy($current_schema, $previous_schema)) {
-
- return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'Could not copy the new database definition file to the current file');
- }
-
- return MDB2_OK;
- }
- // }}}
- // {{{ errorMessage()
-
- /**
- * Return a textual error message for a MDB2 error code
- *
- * @param int|array $value integer error code, null
to get the
- * current error code-message map,
- * or an array with a new error code-message map
- *
- * @return string error message, or false if the error code was not recognized
- * @access public
- */
- function errorMessage($value = null)
- {
- static $errorMessages;
- if (is_array($value)) {
- $errorMessages = $value;
- return MDB2_OK;
- } elseif (!isset($errorMessages)) {
- $errorMessages = array(
- MDB2_SCHEMA_ERROR => 'unknown error',
- MDB2_SCHEMA_ERROR_PARSE => 'schema parse error',
- MDB2_SCHEMA_ERROR_VALIDATE => 'schema validation error',
- MDB2_SCHEMA_ERROR_INVALID => 'invalid',
- MDB2_SCHEMA_ERROR_UNSUPPORTED => 'not supported',
- MDB2_SCHEMA_ERROR_WRITER => 'schema writer error',
- );
- }
-
- if (is_null($value)) {
- return $errorMessages;
- }
-
- if (PEAR::isError($value)) {
- $value = $value->getCode();
- }
-
- return !empty($errorMessages[$value]) ?
- $errorMessages[$value] : $errorMessages[MDB2_SCHEMA_ERROR];
- }
-
- // }}}
- // {{{ raiseError()
-
- /**
- * This method is used to communicate an error and invoke error
- * callbacks etc. Basically a wrapper for PEAR::raiseError
- * without the message string.
- *
- * @param int|PEAR_Error $code integer error code or and PEAR_Error instance
- * @param int $mode error mode, see PEAR_Error docs
- * error level (E_USER_NOTICE etc). If error mode is
- * PEAR_ERROR_CALLBACK, this is the callback function,
- * either as a function name, or as an array of an
- * object and method name. For other error modes this
- * parameter is ignored.
- * @param array $options Options, depending on the mode, @see PEAR::setErrorHandling
- * @param string $userinfo Extra debug information. Defaults to the last
- * query and native error code.
- *
- * @return object a PEAR error object
- * @access public
- * @see PEAR_Error
- */
- static function &raiseError($code = null, $mode = null, $options = null, $userinfo = null, $dummy1 = null, $dummy2 = null, $dummy3 = false)
- {
- $err = PEAR::raiseError(null, $code, $mode, $options,
- $userinfo, 'MDB2_Schema_Error', true);
- return $err;
- }
-
- // }}}
- // {{{ isError()
-
- /**
- * Tell whether a value is an MDB2_Schema error.
- *
- * @param mixed $data the value to test
- * @param int $code if $data is an error object, return true only if $code is
- * a string and $db->getMessage() == $code or
- * $code is an integer and $db->getCode() == $code
- *
- * @return bool true if parameter is an error
- * @access public
- */
- static function isError($data, $code = null)
- {
- if (is_a($data, 'MDB2_Schema_Error')) {
- if (is_null($code)) {
- return true;
- } elseif (is_string($code)) {
- return $data->getMessage() === $code;
- } else {
- $code = (array)$code;
- return in_array($data->getCode(), $code);
- }
- }
- return false;
- }
-
- // }}}
-}
-
-/**
- * MDB2_Schema_Error implements a class for reporting portable database error
- * messages.
- *
- * @category Database
- * @package MDB2_Schema
- * @author Stig Bakken
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Error extends PEAR_Error
-{
- /**
- * MDB2_Schema_Error constructor.
- *
- * @param mixed $code error code, or string with error message.
- * @param int $mode what 'error mode' to operate in
- * @param int $level what error level to use for $mode & PEAR_ERROR_TRIGGER
- * @param mixed $debuginfo additional debug info, such as the last query
- *
- * @access public
- */
- function MDB2_Schema_Error($code = MDB2_SCHEMA_ERROR, $mode = PEAR_ERROR_RETURN,
- $level = E_USER_NOTICE, $debuginfo = null)
- {
- $this->PEAR_Error('MDB2_Schema Error: ' . MDB2_Schema::errorMessage($code), $code,
- $mode, $level, $debuginfo);
- }
-}
diff --git a/3rdparty/MDB2/Schema/Parser.php b/3rdparty/MDB2/Schema/Parser.php
deleted file mode 100644
index 3c4345661b..0000000000
--- a/3rdparty/MDB2/Schema/Parser.php
+++ /dev/null
@@ -1,876 +0,0 @@
-
- * @author Igor Feghali
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-require_once 'XML/Parser.php';
-require_once 'MDB2/Schema/Validate.php';
-
-/**
- * Parses an XML schema file
- *
- * @category Database
- * @package MDB2_Schema
- * @author Christian Dickmann
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Parser extends XML_Parser
-{
- var $database_definition = array();
-
- var $elements = array();
-
- var $element = '';
-
- var $count = 0;
-
- var $table = array();
-
- var $table_name = '';
-
- var $field = array();
-
- var $field_name = '';
-
- var $init = array();
-
- var $init_function = array();
-
- var $init_expression = array();
-
- var $init_field = array();
-
- var $index = array();
-
- var $index_name = '';
-
- var $constraint = array();
-
- var $constraint_name = '';
-
- var $var_mode = false;
-
- var $variables = array();
-
- var $sequence = array();
-
- var $sequence_name = '';
-
- var $error;
-
- var $structure = false;
-
- var $val;
-
- /**
- * PHP 5 constructor
- *
- * @param array $variables mixed array with user defined schema
- * variables
- * @param bool $fail_on_invalid_names array with reserved words per RDBMS
- * @param array $structure multi dimensional array with
- * database schema and data
- * @param array $valid_types information of all valid fields
- * types
- * @param bool $force_defaults if true sets a default value to
- * field when not explicit
- * @param int $max_identifiers_length maximum allowed size for entities
- * name
- *
- * @return void
- *
- * @access public
- * @static
- */
- function __construct($variables, $fail_on_invalid_names = true,
- $structure = false, $valid_types = array(), $force_defaults = true,
- $max_identifiers_length = null
- ) {
- // force ISO-8859-1 due to different defaults for PHP4 and PHP5
- // todo: this probably needs to be investigated some more andcleaned up
- parent::__construct('ISO-8859-1');
-
- $this->variables = $variables;
- $this->structure = $structure;
- $this->val = new MDB2_Schema_Validate(
- $fail_on_invalid_names,
- $valid_types,
- $force_defaults,
- $max_identifiers_length
- );
- }
-
- /**
- * Triggered when reading a XML open tag
- *
- * @param resource $xp xml parser resource
- * @param string $element element name
- * @param array $attribs attributes
- *
- * @return void
- * @access private
- * @static
- */
- function startHandler($xp, $element, &$attribs)
- {
- if (strtolower($element) == 'variable') {
- $this->var_mode = true;
- return;
- }
-
- $this->elements[$this->count++] = strtolower($element);
-
- $this->element = implode('-', $this->elements);
-
- switch ($this->element) {
- /* Initialization */
- case 'database-table-initialization':
- $this->table['initialization'] = array();
- break;
-
- /* Insert */
- /* insert: field+ */
- case 'database-table-initialization-insert':
- $this->init = array('type' => 'insert', 'data' => array('field' => array()));
- break;
- /* insert-select: field+, table, where? */
- case 'database-table-initialization-insert-select':
- $this->init['data']['table'] = '';
- break;
-
- /* Update */
- /* update: field+, where? */
- case 'database-table-initialization-update':
- $this->init = array('type' => 'update', 'data' => array('field' => array()));
- break;
-
- /* Delete */
- /* delete: where */
- case 'database-table-initialization-delete':
- $this->init = array('type' => 'delete', 'data' => array('where' => array()));
- break;
-
- /* Insert and Update */
- case 'database-table-initialization-insert-field':
- case 'database-table-initialization-insert-select-field':
- case 'database-table-initialization-update-field':
- $this->init_field = array('name' => '', 'group' => array());
- break;
- case 'database-table-initialization-insert-field-value':
- case 'database-table-initialization-insert-select-field-value':
- case 'database-table-initialization-update-field-value':
- /* if value tag is empty cdataHandler is not called so we must force value element creation here */
- $this->init_field['group'] = array('type' => 'value', 'data' => '');
- break;
- case 'database-table-initialization-insert-field-null':
- case 'database-table-initialization-insert-select-field-null':
- case 'database-table-initialization-update-field-null':
- $this->init_field['group'] = array('type' => 'null');
- break;
- case 'database-table-initialization-insert-field-function':
- case 'database-table-initialization-insert-select-field-function':
- case 'database-table-initialization-update-field-function':
- $this->init_function = array('name' => '');
- break;
- case 'database-table-initialization-insert-field-expression':
- case 'database-table-initialization-insert-select-field-expression':
- case 'database-table-initialization-update-field-expression':
- $this->init_expression = array();
- break;
-
- /* All */
- case 'database-table-initialization-insert-select-where':
- case 'database-table-initialization-update-where':
- case 'database-table-initialization-delete-where':
- $this->init['data']['where'] = array('type' => '', 'data' => array());
- break;
- case 'database-table-initialization-insert-select-where-expression':
- case 'database-table-initialization-update-where-expression':
- case 'database-table-initialization-delete-where-expression':
- $this->init_expression = array();
- break;
-
- /* One level simulation of expression-function recursion */
- case 'database-table-initialization-insert-field-expression-function':
- case 'database-table-initialization-insert-select-field-expression-function':
- case 'database-table-initialization-insert-select-where-expression-function':
- case 'database-table-initialization-update-field-expression-function':
- case 'database-table-initialization-update-where-expression-function':
- case 'database-table-initialization-delete-where-expression-function':
- $this->init_function = array('name' => '');
- break;
-
- /* One level simulation of function-expression recursion */
- case 'database-table-initialization-insert-field-function-expression':
- case 'database-table-initialization-insert-select-field-function-expression':
- case 'database-table-initialization-insert-select-where-function-expression':
- case 'database-table-initialization-update-field-function-expression':
- case 'database-table-initialization-update-where-function-expression':
- case 'database-table-initialization-delete-where-function-expression':
- $this->init_expression = array();
- break;
-
- /* Definition */
- case 'database':
- $this->database_definition = array(
- 'name' => '',
- 'create' => '',
- 'overwrite' => '',
- 'charset' => '',
- 'description' => '',
- 'comments' => '',
- 'tables' => array(),
- 'sequences' => array()
- );
- break;
- case 'database-table':
- $this->table_name = '';
-
- $this->table = array(
- 'was' => '',
- 'description' => '',
- 'comments' => '',
- 'fields' => array(),
- 'indexes' => array(),
- 'constraints' => array(),
- 'initialization' => array()
- );
- break;
- case 'database-table-declaration-field':
- case 'database-table-declaration-foreign-field':
- case 'database-table-declaration-foreign-references-field':
- $this->field_name = '';
-
- $this->field = array();
- break;
- case 'database-table-declaration-index-field':
- $this->field_name = '';
-
- $this->field = array('sorting' => '', 'length' => '');
- break;
- /* force field attributes to be initialized when the tag is empty in the XML */
- case 'database-table-declaration-field-was':
- $this->field['was'] = '';
- break;
- case 'database-table-declaration-field-type':
- $this->field['type'] = '';
- break;
- case 'database-table-declaration-field-fixed':
- $this->field['fixed'] = '';
- break;
- case 'database-table-declaration-field-default':
- $this->field['default'] = '';
- break;
- case 'database-table-declaration-field-notnull':
- $this->field['notnull'] = '';
- break;
- case 'database-table-declaration-field-autoincrement':
- $this->field['autoincrement'] = '';
- break;
- case 'database-table-declaration-field-unsigned':
- $this->field['unsigned'] = '';
- break;
- case 'database-table-declaration-field-length':
- $this->field['length'] = '';
- break;
- case 'database-table-declaration-field-description':
- $this->field['description'] = '';
- break;
- case 'database-table-declaration-field-comments':
- $this->field['comments'] = '';
- break;
- case 'database-table-declaration-index':
- $this->index_name = '';
-
- $this->index = array(
- 'was' => '',
- 'unique' =>'',
- 'primary' => '',
- 'fields' => array()
- );
- break;
- case 'database-table-declaration-foreign':
- $this->constraint_name = '';
-
- $this->constraint = array(
- 'was' => '',
- 'match' => '',
- 'ondelete' => '',
- 'onupdate' => '',
- 'deferrable' => '',
- 'initiallydeferred' => '',
- 'foreign' => true,
- 'fields' => array(),
- 'references' => array('table' => '', 'fields' => array())
- );
- break;
- case 'database-sequence':
- $this->sequence_name = '';
-
- $this->sequence = array(
- 'was' => '',
- 'start' => '',
- 'description' => '',
- 'comments' => '',
- );
- break;
- }
- }
-
- /**
- * Triggered when reading a XML close tag
- *
- * @param resource $xp xml parser resource
- * @param string $element element name
- *
- * @return void
- * @access private
- * @static
- */
- function endHandler($xp, $element)
- {
- if (strtolower($element) == 'variable') {
- $this->var_mode = false;
- return;
- }
-
- switch ($this->element) {
- /* Initialization */
-
- /* Insert */
- case 'database-table-initialization-insert-select':
- $this->init['data'] = array('select' => $this->init['data']);
- break;
-
- /* Insert and Delete */
- case 'database-table-initialization-insert-field':
- case 'database-table-initialization-insert-select-field':
- case 'database-table-initialization-update-field':
- $result = $this->val->validateDataField($this->table['fields'], $this->init['data']['field'], $this->init_field);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->init['data']['field'][] = $this->init_field;
- }
- break;
- case 'database-table-initialization-insert-field-function':
- case 'database-table-initialization-insert-select-field-function':
- case 'database-table-initialization-update-field-function':
- $this->init_field['group'] = array('type' => 'function', 'data' => $this->init_function);
- break;
- case 'database-table-initialization-insert-field-expression':
- case 'database-table-initialization-insert-select-field-expression':
- case 'database-table-initialization-update-field-expression':
- $this->init_field['group'] = array('type' => 'expression', 'data' => $this->init_expression);
- break;
-
- /* All */
- case 'database-table-initialization-insert-select-where-expression':
- case 'database-table-initialization-update-where-expression':
- case 'database-table-initialization-delete-where-expression':
- $this->init['data']['where']['type'] = 'expression';
- $this->init['data']['where']['data'] = $this->init_expression;
- break;
- case 'database-table-initialization-insert':
- case 'database-table-initialization-delete':
- case 'database-table-initialization-update':
- $this->table['initialization'][] = $this->init;
- break;
-
- /* One level simulation of expression-function recursion */
- case 'database-table-initialization-insert-field-expression-function':
- case 'database-table-initialization-insert-select-field-expression-function':
- case 'database-table-initialization-insert-select-where-expression-function':
- case 'database-table-initialization-update-field-expression-function':
- case 'database-table-initialization-update-where-expression-function':
- case 'database-table-initialization-delete-where-expression-function':
- $this->init_expression['operants'][] = array('type' => 'function', 'data' => $this->init_function);
- break;
-
- /* One level simulation of function-expression recursion */
- case 'database-table-initialization-insert-field-function-expression':
- case 'database-table-initialization-insert-select-field-function-expression':
- case 'database-table-initialization-insert-select-where-function-expression':
- case 'database-table-initialization-update-field-function-expression':
- case 'database-table-initialization-update-where-function-expression':
- case 'database-table-initialization-delete-where-function-expression':
- $this->init_function['arguments'][] = array('type' => 'expression', 'data' => $this->init_expression);
- break;
-
- /* Table definition */
- case 'database-table':
- $result = $this->val->validateTable($this->database_definition['tables'], $this->table, $this->table_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->database_definition['tables'][$this->table_name] = $this->table;
- }
- break;
- case 'database-table-name':
- if (isset($this->structure['tables'][$this->table_name])) {
- $this->table = $this->structure['tables'][$this->table_name];
- }
- break;
-
- /* Field declaration */
- case 'database-table-declaration-field':
- $result = $this->val->validateField($this->table['fields'], $this->field, $this->field_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->table['fields'][$this->field_name] = $this->field;
- }
- break;
-
- /* Index declaration */
- case 'database-table-declaration-index':
- $result = $this->val->validateIndex($this->table['indexes'], $this->index, $this->index_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->table['indexes'][$this->index_name] = $this->index;
- }
- break;
- case 'database-table-declaration-index-field':
- $result = $this->val->validateIndexField($this->index['fields'], $this->field, $this->field_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->index['fields'][$this->field_name] = $this->field;
- }
- break;
-
- /* Foreign Key declaration */
- case 'database-table-declaration-foreign':
- $result = $this->val->validateConstraint($this->table['constraints'], $this->constraint, $this->constraint_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->table['constraints'][$this->constraint_name] = $this->constraint;
- }
- break;
- case 'database-table-declaration-foreign-field':
- $result = $this->val->validateConstraintField($this->constraint['fields'], $this->field_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->constraint['fields'][$this->field_name] = '';
- }
- break;
- case 'database-table-declaration-foreign-references-field':
- $result = $this->val->validateConstraintReferencedField($this->constraint['references']['fields'], $this->field_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->constraint['references']['fields'][$this->field_name] = '';
- }
- break;
-
- /* Sequence declaration */
- case 'database-sequence':
- $result = $this->val->validateSequence($this->database_definition['sequences'], $this->sequence, $this->sequence_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->database_definition['sequences'][$this->sequence_name] = $this->sequence;
- }
- break;
-
- /* End of File */
- case 'database':
- $result = $this->val->validateDatabase($this->database_definition);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- }
- break;
- }
-
- unset($this->elements[--$this->count]);
- $this->element = implode('-', $this->elements);
- }
-
- /**
- * Pushes a MDB2_Schema_Error into stack and returns it
- *
- * @param string $msg textual message
- * @param int $xmlecode PHP's XML parser error code
- * @param resource $xp xml parser resource
- * @param int $ecode MDB2_Schema's error code
- *
- * @return object
- * @access private
- * @static
- */
- static function &raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE, $userinfo = null,
- $error_class = null,
- $skipmsg = false)
- {
- if (is_null($this->error)) {
- $error = '';
- if (is_resource($msg)) {
- $error .= 'Parser error: '.xml_error_string(xml_get_error_code($msg));
- $xp = $msg;
- } else {
- $error .= 'Parser error: '.$msg;
- if (!is_resource($xp)) {
- $xp = $this->parser;
- }
- }
-
- if ($error_string = xml_error_string($xmlecode)) {
- $error .= ' - '.$error_string;
- }
-
- if (is_resource($xp)) {
- $byte = @xml_get_current_byte_index($xp);
- $line = @xml_get_current_line_number($xp);
- $column = @xml_get_current_column_number($xp);
- $error .= " - Byte: $byte; Line: $line; Col: $column";
- }
-
- $error .= "\n";
-
- $this->error = MDB2_Schema::raiseError($ecode, null, null, $error);
- }
- return $this->error;
- }
-
- /**
- * Triggered when reading data in a XML element (text between tags)
- *
- * @param resource $xp xml parser resource
- * @param string $data text
- *
- * @return void
- * @access private
- * @static
- */
- function cdataHandler($xp, $data)
- {
- if ($this->var_mode == true) {
- if (!isset($this->variables[$data])) {
- $this->raiseError('variable "'.$data.'" not found', null, $xp);
- return;
- }
- $data = $this->variables[$data];
- }
-
- switch ($this->element) {
- /* Initialization */
-
- /* Insert */
- case 'database-table-initialization-insert-select-table':
- $this->init['data']['table'] = $data;
- break;
-
- /* Insert and Update */
- case 'database-table-initialization-insert-field-name':
- case 'database-table-initialization-insert-select-field-name':
- case 'database-table-initialization-update-field-name':
- $this->init_field['name'] .= $data;
- break;
- case 'database-table-initialization-insert-field-value':
- case 'database-table-initialization-insert-select-field-value':
- case 'database-table-initialization-update-field-value':
- $this->init_field['group']['data'] .= $data;
- break;
- case 'database-table-initialization-insert-field-function-name':
- case 'database-table-initialization-insert-select-field-function-name':
- case 'database-table-initialization-update-field-function-name':
- $this->init_function['name'] .= $data;
- break;
- case 'database-table-initialization-insert-field-function-value':
- case 'database-table-initialization-insert-select-field-function-value':
- case 'database-table-initialization-update-field-function-value':
- $this->init_function['arguments'][] = array('type' => 'value', 'data' => $data);
- break;
- case 'database-table-initialization-insert-field-function-column':
- case 'database-table-initialization-insert-select-field-function-column':
- case 'database-table-initialization-update-field-function-column':
- $this->init_function['arguments'][] = array('type' => 'column', 'data' => $data);
- break;
- case 'database-table-initialization-insert-field-column':
- case 'database-table-initialization-insert-select-field-column':
- case 'database-table-initialization-update-field-column':
- $this->init_field['group'] = array('type' => 'column', 'data' => $data);
- break;
-
- /* All */
- case 'database-table-initialization-insert-field-expression-operator':
- case 'database-table-initialization-insert-select-field-expression-operator':
- case 'database-table-initialization-insert-select-where-expression-operator':
- case 'database-table-initialization-update-field-expression-operator':
- case 'database-table-initialization-update-where-expression-operator':
- case 'database-table-initialization-delete-where-expression-operator':
- $this->init_expression['operator'] = $data;
- break;
- case 'database-table-initialization-insert-field-expression-value':
- case 'database-table-initialization-insert-select-field-expression-value':
- case 'database-table-initialization-insert-select-where-expression-value':
- case 'database-table-initialization-update-field-expression-value':
- case 'database-table-initialization-update-where-expression-value':
- case 'database-table-initialization-delete-where-expression-value':
- $this->init_expression['operants'][] = array('type' => 'value', 'data' => $data);
- break;
- case 'database-table-initialization-insert-field-expression-column':
- case 'database-table-initialization-insert-select-field-expression-column':
- case 'database-table-initialization-insert-select-where-expression-column':
- case 'database-table-initialization-update-field-expression-column':
- case 'database-table-initialization-update-where-expression-column':
- case 'database-table-initialization-delete-where-expression-column':
- $this->init_expression['operants'][] = array('type' => 'column', 'data' => $data);
- break;
-
- case 'database-table-initialization-insert-field-function-function':
- case 'database-table-initialization-insert-field-function-expression':
- case 'database-table-initialization-insert-field-expression-expression':
- case 'database-table-initialization-update-field-function-function':
- case 'database-table-initialization-update-field-function-expression':
- case 'database-table-initialization-update-field-expression-expression':
- case 'database-table-initialization-update-where-expression-expression':
- case 'database-table-initialization-delete-where-expression-expression':
- /* Recursion to be implemented yet */
- break;
-
- /* One level simulation of expression-function recursion */
- case 'database-table-initialization-insert-field-expression-function-name':
- case 'database-table-initialization-insert-select-field-expression-function-name':
- case 'database-table-initialization-insert-select-where-expression-function-name':
- case 'database-table-initialization-update-field-expression-function-name':
- case 'database-table-initialization-update-where-expression-function-name':
- case 'database-table-initialization-delete-where-expression-function-name':
- $this->init_function['name'] .= $data;
- break;
- case 'database-table-initialization-insert-field-expression-function-value':
- case 'database-table-initialization-insert-select-field-expression-function-value':
- case 'database-table-initialization-insert-select-where-expression-function-value':
- case 'database-table-initialization-update-field-expression-function-value':
- case 'database-table-initialization-update-where-expression-function-value':
- case 'database-table-initialization-delete-where-expression-function-value':
- $this->init_function['arguments'][] = array('type' => 'value', 'data' => $data);
- break;
- case 'database-table-initialization-insert-field-expression-function-column':
- case 'database-table-initialization-insert-select-field-expression-function-column':
- case 'database-table-initialization-insert-select-where-expression-function-column':
- case 'database-table-initialization-update-field-expression-function-column':
- case 'database-table-initialization-update-where-expression-function-column':
- case 'database-table-initialization-delete-where-expression-function-column':
- $this->init_function['arguments'][] = array('type' => 'column', 'data' => $data);
- break;
-
- /* One level simulation of function-expression recursion */
- case 'database-table-initialization-insert-field-function-expression-operator':
- case 'database-table-initialization-insert-select-field-function-expression-operator':
- case 'database-table-initialization-update-field-function-expression-operator':
- $this->init_expression['operator'] = $data;
- break;
- case 'database-table-initialization-insert-field-function-expression-value':
- case 'database-table-initialization-insert-select-field-function-expression-value':
- case 'database-table-initialization-update-field-function-expression-value':
- $this->init_expression['operants'][] = array('type' => 'value', 'data' => $data);
- break;
- case 'database-table-initialization-insert-field-function-expression-column':
- case 'database-table-initialization-insert-select-field-function-expression-column':
- case 'database-table-initialization-update-field-function-expression-column':
- $this->init_expression['operants'][] = array('type' => 'column', 'data' => $data);
- break;
-
- /* Database */
- case 'database-name':
- $this->database_definition['name'] .= $data;
- break;
- case 'database-create':
- $this->database_definition['create'] .= $data;
- break;
- case 'database-overwrite':
- $this->database_definition['overwrite'] .= $data;
- break;
- case 'database-charset':
- $this->database_definition['charset'] .= $data;
- break;
- case 'database-description':
- $this->database_definition['description'] .= $data;
- break;
- case 'database-comments':
- $this->database_definition['comments'] .= $data;
- break;
-
- /* Table declaration */
- case 'database-table-name':
- $this->table_name .= $data;
- break;
- case 'database-table-was':
- $this->table['was'] .= $data;
- break;
- case 'database-table-description':
- $this->table['description'] .= $data;
- break;
- case 'database-table-comments':
- $this->table['comments'] .= $data;
- break;
-
- /* Field declaration */
- case 'database-table-declaration-field-name':
- $this->field_name .= $data;
- break;
- case 'database-table-declaration-field-was':
- $this->field['was'] .= $data;
- break;
- case 'database-table-declaration-field-type':
- $this->field['type'] .= $data;
- break;
- case 'database-table-declaration-field-fixed':
- $this->field['fixed'] .= $data;
- break;
- case 'database-table-declaration-field-default':
- $this->field['default'] .= $data;
- break;
- case 'database-table-declaration-field-notnull':
- $this->field['notnull'] .= $data;
- break;
- case 'database-table-declaration-field-autoincrement':
- $this->field['autoincrement'] .= $data;
- break;
- case 'database-table-declaration-field-unsigned':
- $this->field['unsigned'] .= $data;
- break;
- case 'database-table-declaration-field-length':
- $this->field['length'] .= $data;
- break;
- case 'database-table-declaration-field-description':
- $this->field['description'] .= $data;
- break;
- case 'database-table-declaration-field-comments':
- $this->field['comments'] .= $data;
- break;
-
- /* Index declaration */
- case 'database-table-declaration-index-name':
- $this->index_name .= $data;
- break;
- case 'database-table-declaration-index-was':
- $this->index['was'] .= $data;
- break;
- case 'database-table-declaration-index-unique':
- $this->index['unique'] .= $data;
- break;
- case 'database-table-declaration-index-primary':
- $this->index['primary'] .= $data;
- break;
- case 'database-table-declaration-index-field-name':
- $this->field_name .= $data;
- break;
- case 'database-table-declaration-index-field-sorting':
- $this->field['sorting'] .= $data;
- break;
- /* Add by Leoncx */
- case 'database-table-declaration-index-field-length':
- $this->field['length'] .= $data;
- break;
-
- /* Foreign Key declaration */
- case 'database-table-declaration-foreign-name':
- $this->constraint_name .= $data;
- break;
- case 'database-table-declaration-foreign-was':
- $this->constraint['was'] .= $data;
- break;
- case 'database-table-declaration-foreign-match':
- $this->constraint['match'] .= $data;
- break;
- case 'database-table-declaration-foreign-ondelete':
- $this->constraint['ondelete'] .= $data;
- break;
- case 'database-table-declaration-foreign-onupdate':
- $this->constraint['onupdate'] .= $data;
- break;
- case 'database-table-declaration-foreign-deferrable':
- $this->constraint['deferrable'] .= $data;
- break;
- case 'database-table-declaration-foreign-initiallydeferred':
- $this->constraint['initiallydeferred'] .= $data;
- break;
- case 'database-table-declaration-foreign-field':
- $this->field_name .= $data;
- break;
- case 'database-table-declaration-foreign-references-table':
- $this->constraint['references']['table'] .= $data;
- break;
- case 'database-table-declaration-foreign-references-field':
- $this->field_name .= $data;
- break;
-
- /* Sequence declaration */
- case 'database-sequence-name':
- $this->sequence_name .= $data;
- break;
- case 'database-sequence-was':
- $this->sequence['was'] .= $data;
- break;
- case 'database-sequence-start':
- $this->sequence['start'] .= $data;
- break;
- case 'database-sequence-description':
- $this->sequence['description'] .= $data;
- break;
- case 'database-sequence-comments':
- $this->sequence['comments'] .= $data;
- break;
- case 'database-sequence-on':
- $this->sequence['on'] = array('table' => '', 'field' => '');
- break;
- case 'database-sequence-on-table':
- $this->sequence['on']['table'] .= $data;
- break;
- case 'database-sequence-on-field':
- $this->sequence['on']['field'] .= $data;
- break;
- }
- }
-}
diff --git a/3rdparty/MDB2/Schema/Parser2.php b/3rdparty/MDB2/Schema/Parser2.php
deleted file mode 100644
index f27dffbabf..0000000000
--- a/3rdparty/MDB2/Schema/Parser2.php
+++ /dev/null
@@ -1,802 +0,0 @@
-
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-require_once 'XML/Unserializer.php';
-require_once 'MDB2/Schema/Validate.php';
-
-/**
- * Parses an XML schema file
- *
- * @category Database
- * @package MDB2_Schema
- * @author Lukas Smith
- * @author Igor Feghali
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Parser2 extends XML_Unserializer
-{
- var $database_definition = array();
-
- var $database_loaded = array();
-
- var $variables = array();
-
- var $error;
-
- var $structure = false;
-
- var $val;
-
- var $options = array();
-
- var $table = array();
-
- var $table_name = '';
-
- var $field = array();
-
- var $field_name = '';
-
- var $index = array();
-
- var $index_name = '';
-
- var $constraint = array();
-
- var $constraint_name = '';
-
- var $sequence = array();
-
- var $sequence_name = '';
-
- var $init = array();
-
- /**
- * PHP 5 constructor
- *
- * @param array $variables mixed array with user defined schema
- * variables
- * @param bool $fail_on_invalid_names array with reserved words per RDBMS
- * @param array $structure multi dimensional array with
- * database schema and data
- * @param array $valid_types information of all valid fields
- * types
- * @param bool $force_defaults if true sets a default value to
- * field when not explicit
- * @param int $max_identifiers_length maximum allowed size for entities
- * name
- *
- * @return void
- *
- * @access public
- * @static
- */
- function __construct($variables, $fail_on_invalid_names = true,
- $structure = false, $valid_types = array(), $force_defaults = true,
- $max_identifiers_length = null
- ) {
- // force ISO-8859-1 due to different defaults for PHP4 and PHP5
- // todo: this probably needs to be investigated some more and cleaned up
- $this->options['encoding'] = 'ISO-8859-1';
-
- $this->options['XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE'] = true;
- $this->options['XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY'] = false;
-
- $this->options['forceEnum'] = array('table', 'field', 'index', 'foreign', 'insert', 'update', 'delete', 'sequence');
-
- /*
- * todo: find a way to force the following items not to be parsed as arrays
- * as it cause problems in functions with multiple arguments
- */
- //$this->options['forceNEnum'] = array('value', 'column');
- $this->variables = $variables;
- $this->structure = $structure;
-
- $this->val = new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults);
- parent::XML_Unserializer($this->options);
- }
-
- /**
- * Main method. Parses XML Schema File.
- *
- * @return bool|error object
- *
- * @access public
- */
- function parse()
- {
- $result = $this->unserialize($this->filename, true);
-
- if (PEAR::isError($result)) {
- return $result;
- } else {
- $this->database_loaded = $this->getUnserializedData();
- return $this->fixDatabaseKeys($this->database_loaded);
- }
- }
-
- /**
- * Do the necessary stuff to set the input XML schema file
- *
- * @param string $filename full path to schema file
- *
- * @return boolean MDB2_OK on success
- *
- * @access public
- */
- function setInputFile($filename)
- {
- $this->filename = $filename;
- return MDB2_OK;
- }
-
- /**
- * Enforce the default values for mandatory keys and ensure everything goes
- * always in the same order (simulates the behaviour of the original
- * parser). Works at database level.
- *
- * @param array $database multi dimensional array with database definition
- * and data.
- *
- * @return bool|error MDB2_OK on success or error object
- *
- * @access private
- */
- function fixDatabaseKeys($database)
- {
- $this->database_definition = array(
- 'name' => '',
- 'create' => '',
- 'overwrite' => '',
- 'charset' => '',
- 'description' => '',
- 'comments' => '',
- 'tables' => array(),
- 'sequences' => array()
- );
-
- if (!empty($database['name'])) {
- $this->database_definition['name'] = $database['name'];
- }
- if (!empty($database['create'])) {
- $this->database_definition['create'] = $database['create'];
- }
- if (!empty($database['overwrite'])) {
- $this->database_definition['overwrite'] = $database['overwrite'];
- }
- if (!empty($database['charset'])) {
- $this->database_definition['charset'] = $database['charset'];
- }
- if (!empty($database['description'])) {
- $this->database_definition['description'] = $database['description'];
- }
- if (!empty($database['comments'])) {
- $this->database_definition['comments'] = $database['comments'];
- }
-
- if (!empty($database['table']) && is_array($database['table'])) {
- foreach ($database['table'] as $table) {
- $this->fixTableKeys($table);
- }
- }
-
- if (!empty($database['sequence']) && is_array($database['sequence'])) {
- foreach ($database['sequence'] as $sequence) {
- $this->fixSequenceKeys($sequence);
- }
- }
-
- $result = $this->val->validateDatabase($this->database_definition);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- }
-
- return MDB2_OK;
- }
-
- /**
- * Enforce the default values for mandatory keys and ensure everything goes
- * always in the same order (simulates the behaviour of the original
- * parser). Works at table level.
- *
- * @param array $table multi dimensional array with table definition
- * and data.
- *
- * @return bool|error MDB2_OK on success or error object
- *
- * @access private
- */
- function fixTableKeys($table)
- {
- $this->table = array(
- 'was' => '',
- 'description' => '',
- 'comments' => '',
- 'fields' => array(),
- 'indexes' => array(),
- 'constraints' => array(),
- 'initialization' => array()
- );
-
- if (!empty($table['name'])) {
- $this->table_name = $table['name'];
- } else {
- $this->table_name = '';
- }
- if (!empty($table['was'])) {
- $this->table['was'] = $table['was'];
- }
- if (!empty($table['description'])) {
- $this->table['description'] = $table['description'];
- }
- if (!empty($table['comments'])) {
- $this->table['comments'] = $table['comments'];
- }
-
- if (!empty($table['declaration']) && is_array($table['declaration'])) {
- if (!empty($table['declaration']['field']) && is_array($table['declaration']['field'])) {
- foreach ($table['declaration']['field'] as $field) {
- $this->fixTableFieldKeys($field);
- }
- }
-
- if (!empty($table['declaration']['index']) && is_array($table['declaration']['index'])) {
- foreach ($table['declaration']['index'] as $index) {
- $this->fixTableIndexKeys($index);
- }
- }
-
- if (!empty($table['declaration']['foreign']) && is_array($table['declaration']['foreign'])) {
- foreach ($table['declaration']['foreign'] as $constraint) {
- $this->fixTableConstraintKeys($constraint);
- }
- }
- }
-
- if (!empty($table['initialization']) && is_array($table['initialization'])) {
- if (!empty($table['initialization']['insert']) && is_array($table['initialization']['insert'])) {
- foreach ($table['initialization']['insert'] as $init) {
- $this->fixTableInitializationKeys($init, 'insert');
- }
- }
- if (!empty($table['initialization']['update']) && is_array($table['initialization']['update'])) {
- foreach ($table['initialization']['update'] as $init) {
- $this->fixTableInitializationKeys($init, 'update');
- }
- }
- if (!empty($table['initialization']['delete']) && is_array($table['initialization']['delete'])) {
- foreach ($table['initialization']['delete'] as $init) {
- $this->fixTableInitializationKeys($init, 'delete');
- }
- }
- }
-
- $result = $this->val->validateTable($this->database_definition['tables'], $this->table, $this->table_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- } else {
- $this->database_definition['tables'][$this->table_name] = $this->table;
- }
-
- return MDB2_OK;
- }
-
- /**
- * Enforce the default values for mandatory keys and ensure everything goes
- * always in the same order (simulates the behaviour of the original
- * parser). Works at table field level.
- *
- * @param array $field array with table field definition
- *
- * @return bool|error MDB2_OK on success or error object
- *
- * @access private
- */
- function fixTableFieldKeys($field)
- {
- $this->field = array();
- if (!empty($field['name'])) {
- $this->field_name = $field['name'];
- } else {
- $this->field_name = '';
- }
- if (!empty($field['was'])) {
- $this->field['was'] = $field['was'];
- }
- if (!empty($field['type'])) {
- $this->field['type'] = $field['type'];
- }
- if (!empty($field['fixed'])) {
- $this->field['fixed'] = $field['fixed'];
- }
- if (isset($field['default'])) {
- $this->field['default'] = $field['default'];
- }
- if (!empty($field['notnull'])) {
- $this->field['notnull'] = $field['notnull'];
- }
- if (!empty($field['autoincrement'])) {
- $this->field['autoincrement'] = $field['autoincrement'];
- }
- if (!empty($field['unsigned'])) {
- $this->field['unsigned'] = $field['unsigned'];
- }
- if (!empty($field['length'])) {
- $this->field['length'] = $field['length'];
- }
- if (!empty($field['description'])) {
- $this->field['description'] = $field['description'];
- }
- if (!empty($field['comments'])) {
- $this->field['comments'] = $field['comments'];
- }
-
- $result = $this->val->validateField($this->table['fields'], $this->field, $this->field_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- } else {
- $this->table['fields'][$this->field_name] = $this->field;
- }
-
- return MDB2_OK;
- }
-
- /**
- * Enforce the default values for mandatory keys and ensure everything goes
- * always in the same order (simulates the behaviour of the original
- * parser). Works at table index level.
- *
- * @param array $index array with table index definition
- *
- * @return bool|error MDB2_OK on success or error object
- *
- * @access private
- */
- function fixTableIndexKeys($index)
- {
- $this->index = array(
- 'was' => '',
- 'unique' =>'',
- 'primary' => '',
- 'fields' => array()
- );
-
- if (!empty($index['name'])) {
- $this->index_name = $index['name'];
- } else {
- $this->index_name = '';
- }
- if (!empty($index['was'])) {
- $this->index['was'] = $index['was'];
- }
- if (!empty($index['unique'])) {
- $this->index['unique'] = $index['unique'];
- }
- if (!empty($index['primary'])) {
- $this->index['primary'] = $index['primary'];
- }
- if (!empty($index['field'])) {
- foreach ($index['field'] as $field) {
- if (!empty($field['name'])) {
- $this->field_name = $field['name'];
- } else {
- $this->field_name = '';
- }
- $this->field = array(
- 'sorting' => '',
- 'length' => ''
- );
-
- if (!empty($field['sorting'])) {
- $this->field['sorting'] = $field['sorting'];
- }
- if (!empty($field['length'])) {
- $this->field['length'] = $field['length'];
- }
-
- $result = $this->val->validateIndexField($this->index['fields'], $this->field, $this->field_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- }
-
- $this->index['fields'][$this->field_name] = $this->field;
- }
- }
-
- $result = $this->val->validateIndex($this->table['indexes'], $this->index, $this->index_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- } else {
- $this->table['indexes'][$this->index_name] = $this->index;
- }
-
- return MDB2_OK;
- }
-
- /**
- * Enforce the default values for mandatory keys and ensure everything goes
- * always in the same order (simulates the behaviour of the original
- * parser). Works at table constraint level.
- *
- * @param array $constraint array with table index definition
- *
- * @return bool|error MDB2_OK on success or error object
- *
- * @access private
- */
- function fixTableConstraintKeys($constraint)
- {
- $this->constraint = array(
- 'was' => '',
- 'match' => '',
- 'ondelete' => '',
- 'onupdate' => '',
- 'deferrable' => '',
- 'initiallydeferred' => '',
- 'foreign' => true,
- 'fields' => array(),
- 'references' => array('table' => '', 'fields' => array())
- );
-
- if (!empty($constraint['name'])) {
- $this->constraint_name = $constraint['name'];
- } else {
- $this->constraint_name = '';
- }
- if (!empty($constraint['was'])) {
- $this->constraint['was'] = $constraint['was'];
- }
- if (!empty($constraint['match'])) {
- $this->constraint['match'] = $constraint['match'];
- }
- if (!empty($constraint['ondelete'])) {
- $this->constraint['ondelete'] = $constraint['ondelete'];
- }
- if (!empty($constraint['onupdate'])) {
- $this->constraint['onupdate'] = $constraint['onupdate'];
- }
- if (!empty($constraint['deferrable'])) {
- $this->constraint['deferrable'] = $constraint['deferrable'];
- }
- if (!empty($constraint['initiallydeferred'])) {
- $this->constraint['initiallydeferred'] = $constraint['initiallydeferred'];
- }
- if (!empty($constraint['field']) && is_array($constraint['field'])) {
- foreach ($constraint['field'] as $field) {
- $result = $this->val->validateConstraintField($this->constraint['fields'], $field);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- }
-
- $this->constraint['fields'][$field] = '';
- }
- }
-
- if (!empty($constraint['references']) && is_array($constraint['references'])) {
- /**
- * As we forced 'table' to be enumerated
- * we have to fix it on the foreign-references-table context
- */
- if (!empty($constraint['references']['table']) && is_array($constraint['references']['table'])) {
- $this->constraint['references']['table'] = $constraint['references']['table'][0];
- }
-
- if (!empty($constraint['references']['field']) && is_array($constraint['references']['field'])) {
- foreach ($constraint['references']['field'] as $field) {
- $result = $this->val->validateConstraintReferencedField($this->constraint['references']['fields'], $field);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- }
-
- $this->constraint['references']['fields'][$field] = '';
- }
- }
- }
-
- $result = $this->val->validateConstraint($this->table['constraints'], $this->constraint, $this->constraint_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- } else {
- $this->table['constraints'][$this->constraint_name] = $this->constraint;
- }
-
- return MDB2_OK;
- }
-
- /**
- * Enforce the default values for mandatory keys and ensure everything goes
- * always in the same order (simulates the behaviour of the original
- * parser). Works at table data level.
- *
- * @param array $element multi dimensional array with query definition
- * @param string $type whether its a insert|update|delete query
- *
- * @return bool|error MDB2_OK on success or error object
- *
- * @access private
- */
- function fixTableInitializationKeys($element, $type = '')
- {
- if (!empty($element['select']) && is_array($element['select'])) {
- $this->fixTableInitializationDataKeys($element['select']);
- $this->init = array( 'select' => $this->init );
- } else {
- $this->fixTableInitializationDataKeys($element);
- }
-
- $this->table['initialization'][] = array( 'type' => $type, 'data' => $this->init );
- }
-
- /**
- * Enforce the default values for mandatory keys and ensure everything goes
- * always in the same order (simulates the behaviour of the original
- * parser). Works deeper at the table initialization level (data). At this
- * point we are look at one of the below:
- *
- *
- * {field}+
- *
- *
- * (this is a select extracted off a insert-select query)
- *
- * {field}+
- *
- * {expression}
- * ?
- *
- *
- *
- * {field}+
- *
- * {expression}
- * ?
- *
- *
- *
- *
- * {expression}
- *
- *
- *
- * @param array $element multi dimensional array with query definition
- *
- * @return bool|error MDB2_OK on success or error object
- *
- * @access private
- */
- function fixTableInitializationDataKeys($element)
- {
- $this->init = array();
- if (!empty($element['field']) && is_array($element['field'])) {
- foreach ($element['field'] as $field) {
- $name = $field['name'];
- unset($field['name']);
-
- $this->setExpression($field);
- $this->init['field'][] = array( 'name' => $name, 'group' => $field );
- }
- }
- /**
- * As we forced 'table' to be enumerated
- * we have to fix it on the insert-select context
- */
- if (!empty($element['table']) && is_array($element['table'])) {
- $this->init['table'] = $element['table'][0];
- }
- if (!empty($element['where']) && is_array($element['where'])) {
- $this->init['where'] = $element['where'];
- $this->setExpression($this->init['where']);
- }
- }
-
- /**
- * Recursively diggs into an "expression" element. According to our
- * documentation an "expression" element is of the kind:
- *
- *
- * or or or {function} or {expression}
- *
- * or or or {function} or {expression}
- *
- *
- * @param array &$arr reference to current element definition
- *
- * @return void
- *
- * @access private
- */
- function setExpression(&$arr)
- {
- $element = each($arr);
-
- $arr = array( 'type' => $element['key'] );
-
- $element = $element['value'];
-
- switch ($arr['type']) {
- case 'null':
- break;
- case 'value':
- case 'column':
- $arr['data'] = $element;
- break;
- case 'function':
- if (!empty($element)
- && is_array($element)
- ) {
- $arr['data'] = array( 'name' => $element['name'] );
- unset($element['name']);
-
- foreach ($element as $type => $value) {
- if (!empty($value)) {
- if (is_array($value)) {
- foreach ($value as $argument) {
- $argument = array( $type => $argument );
- $this->setExpression($argument);
- $arr['data']['arguments'][] = $argument;
- }
- } else {
- $arr['data']['arguments'][] = array( 'type' => $type, 'data' => $value );
- }
- }
- }
- }
- break;
- case 'expression':
- $arr['data'] = array( 'operants' => array(), 'operator' => $element['operator'] );
- unset($element['operator']);
-
- foreach ($element as $k => $v) {
- $argument = array( $k => $v );
- $this->setExpression($argument);
- $arr['data']['operants'][] = $argument;
- }
- break;
- }
- }
-
- /**
- * Enforce the default values for mandatory keys and ensure everything goes
- * always in the same order (simulates the behaviour of the original
- * parser). Works at database sequences level. A "sequence" element looks
- * like:
- *
- *
- *
- * ?
- * ?
- * ?
- * ?
- *
- *
- *
- * ?
- *
- *
- * @param array $sequence multi dimensional array with sequence definition
- *
- * @return bool|error MDB2_OK on success or error object
- *
- * @access private
- */
- function fixSequenceKeys($sequence)
- {
- $this->sequence = array(
- 'was' => '',
- 'start' => '',
- 'description' => '',
- 'comments' => '',
- );
-
- if (!empty($sequence['name'])) {
- $this->sequence_name = $sequence['name'];
- } else {
- $this->sequence_name = '';
- }
- if (!empty($sequence['was'])) {
- $this->sequence['was'] = $sequence['was'];
- }
- if (!empty($sequence['start'])) {
- $this->sequence['start'] = $sequence['start'];
- }
- if (!empty($sequence['description'])) {
- $this->sequence['description'] = $sequence['description'];
- }
- if (!empty($sequence['comments'])) {
- $this->sequence['comments'] = $sequence['comments'];
- }
- if (!empty($sequence['on']) && is_array($sequence['on'])) {
- /**
- * As we forced 'table' to be enumerated
- * we have to fix it on the sequence-on-table context
- */
- if (!empty($sequence['on']['table']) && is_array($sequence['on']['table'])) {
- $this->sequence['on']['table'] = $sequence['on']['table'][0];
- }
-
- /**
- * As we forced 'field' to be enumerated
- * we have to fix it on the sequence-on-field context
- */
- if (!empty($sequence['on']['field']) && is_array($sequence['on']['field'])) {
- $this->sequence['on']['field'] = $sequence['on']['field'][0];
- }
- }
-
- $result = $this->val->validateSequence($this->database_definition['sequences'], $this->sequence, $this->sequence_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- } else {
- $this->database_definition['sequences'][$this->sequence_name] = $this->sequence;
- }
-
- return MDB2_OK;
- }
-
- /**
- * Pushes a MDB2_Schema_Error into stack and returns it
- *
- * @param string $msg textual message
- * @param int $ecode MDB2_Schema's error code
- *
- * @return object
- * @access private
- * @static
- */
- function &raiseError($msg = null, $ecode = MDB2_SCHEMA_ERROR_PARSE)
- {
- if (is_null($this->error)) {
- $error = 'Parser error: '.$msg."\n";
-
- $this->error = MDB2_Schema::raiseError($ecode, null, null, $error);
- }
- return $this->error;
- }
-}
diff --git a/3rdparty/MDB2/Schema/Reserved/ibase.php b/3rdparty/MDB2/Schema/Reserved/ibase.php
deleted file mode 100644
index d797822a4b..0000000000
--- a/3rdparty/MDB2/Schema/Reserved/ibase.php
+++ /dev/null
@@ -1,437 +0,0 @@
-
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-// {{{ $GLOBALS['_MDB2_Schema_Reserved']['ibase']
-/**
- * Has a list of reserved words of Interbase/Firebird
- *
- * @package MDB2_Schema
- * @category Database
- * @access protected
- * @author Lorenzo Alberton
- */
-$GLOBALS['_MDB2_Schema_Reserved']['ibase'] = array(
- 'ABS',
- 'ABSOLUTE',
- 'ACTION',
- 'ACTIVE',
- 'ADD',
- 'ADMIN',
- 'AFTER',
- 'ALL',
- 'ALLOCATE',
- 'ALTER',
- 'AND',
- 'ANY',
- 'ARE',
- 'AS',
- 'ASC',
- 'ASCENDING',
- 'ASSERTION',
- 'AT',
- 'AUTHORIZATION',
- 'AUTO',
- 'AUTODDL',
- 'AVG',
- 'BACKUP',
- 'BASE_NAME',
- 'BASED',
- 'BASENAME',
- 'BEFORE',
- 'BEGIN',
- 'BETWEEN',
- 'BIGINT',
- 'BIT',
- 'BIT_LENGTH',
- 'BLOB',
- 'BLOCK',
- 'BLOBEDIT',
- 'BOOLEAN',
- 'BOTH',
- 'BOTH',
- 'BREAK',
- 'BUFFER',
- 'BY',
- 'CACHE',
- 'CASCADE',
- 'CASCADED',
- 'CASE',
- 'CASE',
- 'CAST',
- 'CATALOG',
- 'CHAR',
- 'CHAR_LENGTH',
- 'CHARACTER',
- 'CHARACTER_LENGTH',
- 'CHECK',
- 'CHECK_POINT_LEN',
- 'CHECK_POINT_LENGTH',
- 'CLOSE',
- 'COALESCE',
- 'COLLATE',
- 'COLLATION',
- 'COLUMN',
- 'COMMENT',
- 'COMMIT',
- 'COMMITTED',
- 'COMPILETIME',
- 'COMPUTED',
- 'CONDITIONAL',
- 'CONNECT',
- 'CONNECTION',
- 'CONSTRAINT',
- 'CONSTRAINTS',
- 'CONTAINING',
- 'CONTINUE',
- 'CONVERT',
- 'CORRESPONDING',
- 'COUNT',
- 'CREATE',
- 'CROSS',
- 'CSTRING',
- 'CURRENT',
- 'CURRENT_CONNECTION',
- 'CURRENT_DATE',
- 'CURRENT_ROLE',
- 'CURRENT_TIME',
- 'CURRENT_TIMESTAMP',
- 'CURRENT_TRANSACTION',
- 'CURRENT_USER',
- 'DATABASE',
- 'DATE',
- 'DAY',
- 'DB_KEY',
- 'DEALLOCATE',
- 'DEBUG',
- 'DEC',
- 'DECIMAL',
- 'DECLARE',
- 'DEFAULT',
- 'DEFERRABLE',
- 'DEFERRED',
- 'DELETE',
- 'DELETING',
- 'DESC',
- 'DESCENDING',
- 'DESCRIBE',
- 'DESCRIPTOR',
- 'DIAGNOSTICS',
- 'DIFFERENCE',
- 'DISCONNECT',
- 'DISPLAY',
- 'DISTINCT',
- 'DO',
- 'DOMAIN',
- 'DOUBLE',
- 'DROP',
- 'ECHO',
- 'EDIT',
- 'ELSE',
- 'END',
- 'END-EXEC',
- 'ENTRY_POINT',
- 'ESCAPE',
- 'EVENT',
- 'EXCEPT',
- 'EXCEPTION',
- 'EXEC',
- 'EXECUTE',
- 'EXISTS',
- 'EXIT',
- 'EXTERN',
- 'EXTERNAL',
- 'EXTRACT',
- 'FALSE',
- 'FETCH',
- 'FILE',
- 'FILTER',
- 'FIRST',
- 'FLOAT',
- 'FOR',
- 'FOREIGN',
- 'FOUND',
- 'FREE_IT',
- 'FROM',
- 'FULL',
- 'FUNCTION',
- 'GDSCODE',
- 'GEN_ID',
- 'GENERATOR',
- 'GET',
- 'GLOBAL',
- 'GO',
- 'GOTO',
- 'GRANT',
- 'GROUP',
- 'GROUP_COMMIT_WAIT',
- 'GROUP_COMMIT_WAIT_TIME',
- 'HAVING',
- 'HELP',
- 'HOUR',
- 'IDENTITY',
- 'IF',
- 'IIF',
- 'IMMEDIATE',
- 'IN',
- 'INACTIVE',
- 'INDEX',
- 'INDICATOR',
- 'INIT',
- 'INITIALLY',
- 'INNER',
- 'INPUT',
- 'INPUT_TYPE',
- 'INSENSITIVE',
- 'INSERT',
- 'INSERTING',
- 'INT',
- 'INTEGER',
- 'INTERSECT',
- 'INTERVAL',
- 'INTO',
- 'IS',
- 'ISOLATION',
- 'ISQL',
- 'JOIN',
- 'KEY',
- 'LANGUAGE',
- 'LAST',
- 'LC_MESSAGES',
- 'LC_TYPE',
- 'LEADING',
- 'LEADING',
- 'LEADING',
- 'LEAVE',
- 'LEFT',
- 'LENGTH',
- 'LEV',
- 'LEVEL',
- 'LIKE',
- 'LOCAL',
- 'LOCK',
- 'LOG_BUF_SIZE',
- 'LOG_BUFFER_SIZE',
- 'LOGFILE',
- 'LONG',
- 'LOWER',
- 'MANUAL',
- 'MATCH',
- 'MAX',
- 'MAX_SEGMENT',
- 'MAXIMUM',
- 'MAXIMUM_SEGMENT',
- 'MERGE',
- 'MESSAGE',
- 'MIN',
- 'MINIMUM',
- 'MINUTE',
- 'MODULE',
- 'MODULE_NAME',
- 'MONTH',
- 'NAMES',
- 'NATIONAL',
- 'NATURAL',
- 'NCHAR',
- 'NEXT',
- 'NO',
- 'NOAUTO',
- 'NOT',
- 'NULL',
- 'NULLIF',
- 'NULLS',
- 'NUM_LOG_BUFFERS',
- 'NUM_LOG_BUFS',
- 'NUMERIC',
- 'OCTET_LENGTH',
- 'OF',
- 'ON',
- 'ONLY',
- 'OPEN',
- 'OPTION',
- 'OR',
- 'ORDER',
- 'OUTER',
- 'OUTPUT',
- 'OUTPUT_TYPE',
- 'OVERFLOW',
- 'OVERLAPS',
- 'PAD',
- 'PAGE',
- 'PAGE_SIZE',
- 'PAGELENGTH',
- 'PAGES',
- 'PARAMETER',
- 'PARTIAL',
- 'PASSWORD',
- 'PERCENT',
- 'PLAN',
- 'POSITION',
- 'POST_EVENT',
- 'PRECISION',
- 'PREPARE',
- 'PRESERVE',
- 'PRIMARY',
- 'PRIOR',
- 'PRIVILEGES',
- 'PROCEDURE',
- 'PUBLIC',
- 'QUIT',
- 'RAW_PARTITIONS',
- 'RDB$DB_KEY',
- 'READ',
- 'REAL',
- 'RECORD_VERSION',
- 'RECREATE',
- 'RECREATE ROW_COUNT',
- 'REFERENCES',
- 'RELATIVE',
- 'RELEASE',
- 'RESERV',
- 'RESERVING',
- 'RESTART',
- 'RESTRICT',
- 'RETAIN',
- 'RETURN',
- 'RETURNING',
- 'RETURNING_VALUES',
- 'RETURNS',
- 'REVOKE',
- 'RIGHT',
- 'ROLE',
- 'ROLLBACK',
- 'ROW_COUNT',
- 'ROWS',
- 'RUNTIME',
- 'SAVEPOINT',
- 'SCALAR_ARRAY',
- 'SCHEMA',
- 'SCROLL',
- 'SECOND',
- 'SECTION',
- 'SELECT',
- 'SEQUENCE',
- 'SESSION',
- 'SESSION_USER',
- 'SET',
- 'SHADOW',
- 'SHARED',
- 'SHELL',
- 'SHOW',
- 'SINGULAR',
- 'SIZE',
- 'SKIP',
- 'SMALLINT',
- 'SNAPSHOT',
- 'SOME',
- 'SORT',
- 'SPACE',
- 'SQL',
- 'SQLCODE',
- 'SQLERROR',
- 'SQLSTATE',
- 'SQLWARNING',
- 'STABILITY',
- 'STARTING',
- 'STARTS',
- 'STATEMENT',
- 'STATIC',
- 'STATISTICS',
- 'SUB_TYPE',
- 'SUBSTRING',
- 'SUM',
- 'SUSPEND',
- 'SYSTEM_USER',
- 'TABLE',
- 'TEMPORARY',
- 'TERMINATOR',
- 'THEN',
- 'TIES',
- 'TIME',
- 'TIMESTAMP',
- 'TIMEZONE_HOUR',
- 'TIMEZONE_MINUTE',
- 'TO',
- 'TRAILING',
- 'TRANSACTION',
- 'TRANSLATE',
- 'TRANSLATION',
- 'TRIGGER',
- 'TRIM',
- 'TRUE',
- 'TYPE',
- 'UNCOMMITTED',
- 'UNION',
- 'UNIQUE',
- 'UNKNOWN',
- 'UPDATE',
- 'UPDATING',
- 'UPPER',
- 'USAGE',
- 'USER',
- 'USING',
- 'VALUE',
- 'VALUES',
- 'VARCHAR',
- 'VARIABLE',
- 'VARYING',
- 'VERSION',
- 'VIEW',
- 'WAIT',
- 'WEEKDAY',
- 'WHEN',
- 'WHENEVER',
- 'WHERE',
- 'WHILE',
- 'WITH',
- 'WORK',
- 'WRITE',
- 'YEAR',
- 'YEARDAY',
- 'ZONE',
-);
-// }}}
diff --git a/3rdparty/MDB2/Schema/Reserved/mssql.php b/3rdparty/MDB2/Schema/Reserved/mssql.php
deleted file mode 100644
index 7aa65f426f..0000000000
--- a/3rdparty/MDB2/Schema/Reserved/mssql.php
+++ /dev/null
@@ -1,260 +0,0 @@
-
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-// {{{ $GLOBALS['_MDB2_Schema_Reserved']['mssql']
-/**
- * Has a list of all the reserved words for mssql.
- *
- * @package MDB2_Schema
- * @category Database
- * @access protected
- * @author David Coallier
- */
-$GLOBALS['_MDB2_Schema_Reserved']['mssql'] = array(
- 'ADD',
- 'CURRENT_TIMESTAMP',
- 'GROUP',
- 'OPENQUERY',
- 'SERIALIZABLE',
- 'ALL',
- 'CURRENT_USER',
- 'HAVING',
- 'OPENROWSET',
- 'SESSION_USER',
- 'ALTER',
- 'CURSOR',
- 'HOLDLOCK',
- 'OPTION',
- 'SET',
- 'AND',
- 'DATABASE',
- 'IDENTITY',
- 'OR',
- 'SETUSER',
- 'ANY',
- 'DBCC',
- 'IDENTITYCOL',
- 'ORDER',
- 'SHUTDOWN',
- 'AS',
- 'DEALLOCATE',
- 'IDENTITY_INSERT',
- 'OUTER',
- 'SOME',
- 'ASC',
- 'DECLARE',
- 'IF',
- 'OVER',
- 'STATISTICS',
- 'AUTHORIZATION',
- 'DEFAULT',
- 'IN',
- 'PERCENT',
- 'SUM',
- 'AVG',
- 'DELETE',
- 'INDEX',
- 'PERM',
- 'SYSTEM_USER',
- 'BACKUP',
- 'DENY',
- 'INNER',
- 'PERMANENT',
- 'TABLE',
- 'BEGIN',
- 'DESC',
- 'INSERT',
- 'PIPE',
- 'TAPE',
- 'BETWEEN',
- 'DISK',
- 'INTERSECT',
- 'PLAN',
- 'TEMP',
- 'BREAK',
- 'DISTINCT',
- 'INTO',
- 'PRECISION',
- 'TEMPORARY',
- 'BROWSE',
- 'DISTRIBUTED',
- 'IS',
- 'PREPARE',
- 'TEXTSIZE',
- 'BULK',
- 'DOUBLE',
- 'ISOLATION',
- 'PRIMARY',
- 'THEN',
- 'BY',
- 'DROP',
- 'JOIN',
- 'PRINT',
- 'TO',
- 'CASCADE',
- 'DUMMY',
- 'KEY',
- 'PRIVILEGES',
- 'TOP',
- 'CASE',
- 'DUMP',
- 'KILL',
- 'PROC',
- 'TRAN',
- 'CHECK',
- 'ELSE',
- 'LEFT',
- 'PROCEDURE',
- 'TRANSACTION',
- 'CHECKPOINT',
- 'END',
- 'LEVEL',
- 'PROCESSEXIT',
- 'TRIGGER',
- 'CLOSE',
- 'ERRLVL',
- 'LIKE',
- 'PUBLIC',
- 'TRUNCATE',
- 'CLUSTERED',
- 'ERROREXIT',
- 'LINENO',
- 'RAISERROR',
- 'TSEQUAL',
- 'COALESCE',
- 'ESCAPE',
- 'LOAD',
- 'READ',
- 'UNCOMMITTED',
- 'COLUMN',
- 'EXCEPT',
- 'MAX',
- 'READTEXT',
- 'UNION',
- 'COMMIT',
- 'EXEC',
- 'MIN',
- 'RECONFIGURE',
- 'UNIQUE',
- 'COMMITTED',
- 'EXECUTE',
- 'MIRROREXIT',
- 'REFERENCES',
- 'UPDATE',
- 'COMPUTE',
- 'EXISTS',
- 'NATIONAL',
- 'REPEATABLE',
- 'UPDATETEXT',
- 'CONFIRM',
- 'EXIT',
- 'NOCHECK',
- 'REPLICATION',
- 'USE',
- 'CONSTRAINT',
- 'FETCH',
- 'NONCLUSTERED',
- 'RESTORE',
- 'USER',
- 'CONTAINS',
- 'FILE',
- 'NOT',
- 'RESTRICT',
- 'VALUES',
- 'CONTAINSTABLE',
- 'FILLFACTOR',
- 'NULL',
- 'RETURN',
- 'VARYING',
- 'CONTINUE',
- 'FLOPPY',
- 'NULLIF',
- 'REVOKE',
- 'VIEW',
- 'CONTROLROW',
- 'FOR',
- 'OF',
- 'RIGHT',
- 'WAITFOR',
- 'CONVERT',
- 'FOREIGN',
- 'OFF',
- 'ROLLBACK',
- 'WHEN',
- 'COUNT',
- 'FREETEXT',
- 'OFFSETS',
- 'ROWCOUNT',
- 'WHERE',
- 'CREATE',
- 'FREETEXTTABLE',
- 'ON',
- 'ROWGUIDCOL',
- 'WHILE',
- 'CROSS',
- 'FROM',
- 'ONCE',
- 'RULE',
- 'WITH',
- 'CURRENT',
- 'FULL',
- 'ONLY',
- 'SAVE',
- 'WORK',
- 'CURRENT_DATE',
- 'GOTO',
- 'OPEN',
- 'SCHEMA',
- 'WRITETEXT',
- 'CURRENT_TIME',
- 'GRANT',
- 'OPENDATASOURCE',
- 'SELECT',
-);
-//}}}
diff --git a/3rdparty/MDB2/Schema/Reserved/mysql.php b/3rdparty/MDB2/Schema/Reserved/mysql.php
deleted file mode 100644
index 6a4338b261..0000000000
--- a/3rdparty/MDB2/Schema/Reserved/mysql.php
+++ /dev/null
@@ -1,285 +0,0 @@
-
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-// {{{ $GLOBALS['_MDB2_Schema_Reserved']['mysql']
-/**
- * Has a list of reserved words of mysql
- *
- * @package MDB2_Schema
- * @category Database
- * @access protected
- * @author David Coalier
- */
-$GLOBALS['_MDB2_Schema_Reserved']['mysql'] = array(
- 'ADD',
- 'ALL',
- 'ALTER',
- 'ANALYZE',
- 'AND',
- 'AS',
- 'ASC',
- 'ASENSITIVE',
- 'BEFORE',
- 'BETWEEN',
- 'BIGINT',
- 'BINARY',
- 'BLOB',
- 'BOTH',
- 'BY',
- 'CALL',
- 'CASCADE',
- 'CASE',
- 'CHANGE',
- 'CHAR',
- 'CHARACTER',
- 'CHECK',
- 'COLLATE',
- 'COLUMN',
- 'CONDITION',
- 'CONNECTION',
- 'CONSTRAINT',
- 'CONTINUE',
- 'CONVERT',
- 'CREATE',
- 'CROSS',
- 'CURRENT_DATE',
- 'CURRENT_TIME',
- 'CURRENT_TIMESTAMP',
- 'CURRENT_USER',
- 'CURSOR',
- 'DATABASE',
- 'DATABASES',
- 'DAY_HOUR',
- 'DAY_MICROSECOND',
- 'DAY_MINUTE',
- 'DAY_SECOND',
- 'DEC',
- 'DECIMAL',
- 'DECLARE',
- 'DEFAULT',
- 'DELAYED',
- 'DELETE',
- 'DESC',
- 'DESCRIBE',
- 'DETERMINISTIC',
- 'DISTINCT',
- 'DISTINCTROW',
- 'DIV',
- 'DOUBLE',
- 'DROP',
- 'DUAL',
- 'EACH',
- 'ELSE',
- 'ELSEIF',
- 'ENCLOSED',
- 'ESCAPED',
- 'EXISTS',
- 'EXIT',
- 'EXPLAIN',
- 'FALSE',
- 'FETCH',
- 'FLOAT',
- 'FLOAT4',
- 'FLOAT8',
- 'FOR',
- 'FORCE',
- 'FOREIGN',
- 'FROM',
- 'FULLTEXT',
- 'GOTO',
- 'GRANT',
- 'GROUP',
- 'HAVING',
- 'HIGH_PRIORITY',
- 'HOUR_MICROSECOND',
- 'HOUR_MINUTE',
- 'HOUR_SECOND',
- 'IF',
- 'IGNORE',
- 'IN',
- 'INDEX',
- 'INFILE',
- 'INNER',
- 'INOUT',
- 'INSENSITIVE',
- 'INSERT',
- 'INT',
- 'INT1',
- 'INT2',
- 'INT3',
- 'INT4',
- 'INT8',
- 'INTEGER',
- 'INTERVAL',
- 'INTO',
- 'IS',
- 'ITERATE',
- 'JOIN',
- 'KEY',
- 'KEYS',
- 'KILL',
- 'LABEL',
- 'LEADING',
- 'LEAVE',
- 'LEFT',
- 'LIKE',
- 'LIMIT',
- 'LINES',
- 'LOAD',
- 'LOCALTIME',
- 'LOCALTIMESTAMP',
- 'LOCK',
- 'LONG',
- 'LONGBLOB',
- 'LONGTEXT',
- 'LOOP',
- 'LOW_PRIORITY',
- 'MATCH',
- 'MEDIUMBLOB',
- 'MEDIUMINT',
- 'MEDIUMTEXT',
- 'MIDDLEINT',
- 'MINUTE_MICROSECOND',
- 'MINUTE_SECOND',
- 'MOD',
- 'MODIFIES',
- 'NATURAL',
- 'NOT',
- 'NO_WRITE_TO_BINLOG',
- 'NULL',
- 'NUMERIC',
- 'ON',
- 'OPTIMIZE',
- 'OPTION',
- 'OPTIONALLY',
- 'OR',
- 'ORDER',
- 'OUT',
- 'OUTER',
- 'OUTFILE',
- 'PRECISION',
- 'PRIMARY',
- 'PROCEDURE',
- 'PURGE',
- 'RAID0',
- 'READ',
- 'READS',
- 'REAL',
- 'REFERENCES',
- 'REGEXP',
- 'RELEASE',
- 'RENAME',
- 'REPEAT',
- 'REPLACE',
- 'REQUIRE',
- 'RESTRICT',
- 'RETURN',
- 'REVOKE',
- 'RIGHT',
- 'RLIKE',
- 'SCHEMA',
- 'SCHEMAS',
- 'SECOND_MICROSECOND',
- 'SELECT',
- 'SENSITIVE',
- 'SEPARATOR',
- 'SET',
- 'SHOW',
- 'SMALLINT',
- 'SONAME',
- 'SPATIAL',
- 'SPECIFIC',
- 'SQL',
- 'SQLEXCEPTION',
- 'SQLSTATE',
- 'SQLWARNING',
- 'SQL_BIG_RESULT',
- 'SQL_CALC_FOUND_ROWS',
- 'SQL_SMALL_RESULT',
- 'SSL',
- 'STARTING',
- 'STRAIGHT_JOIN',
- 'TABLE',
- 'TERMINATED',
- 'THEN',
- 'TINYBLOB',
- 'TINYINT',
- 'TINYTEXT',
- 'TO',
- 'TRAILING',
- 'TRIGGER',
- 'TRUE',
- 'UNDO',
- 'UNION',
- 'UNIQUE',
- 'UNLOCK',
- 'UNSIGNED',
- 'UPDATE',
- 'USAGE',
- 'USE',
- 'USING',
- 'UTC_DATE',
- 'UTC_TIME',
- 'UTC_TIMESTAMP',
- 'VALUES',
- 'VARBINARY',
- 'VARCHAR',
- 'VARCHARACTER',
- 'VARYING',
- 'WHEN',
- 'WHERE',
- 'WHILE',
- 'WITH',
- 'WRITE',
- 'X509',
- 'XOR',
- 'YEAR_MONTH',
- 'ZEROFILL',
- );
- // }}}
diff --git a/3rdparty/MDB2/Schema/Reserved/oci8.php b/3rdparty/MDB2/Schema/Reserved/oci8.php
deleted file mode 100644
index 3cc898e1d6..0000000000
--- a/3rdparty/MDB2/Schema/Reserved/oci8.php
+++ /dev/null
@@ -1,173 +0,0 @@
-
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-// {{{ $GLOBALS['_MDB2_Schema_Reserved']['oci8']
-/**
- * Has a list of all the reserved words for oracle.
- *
- * @package MDB2_Schema
- * @category Database
- * @access protected
- * @author David Coallier
- */
-$GLOBALS['_MDB2_Schema_Reserved']['oci8'] = array(
- 'ACCESS',
- 'ELSE',
- 'MODIFY',
- 'START',
- 'ADD',
- 'EXCLUSIVE',
- 'NOAUDIT',
- 'SELECT',
- 'ALL',
- 'EXISTS',
- 'NOCOMPRESS',
- 'SESSION',
- 'ALTER',
- 'FILE',
- 'NOT',
- 'SET',
- 'AND',
- 'FLOAT',
- 'NOTFOUND ',
- 'SHARE',
- 'ANY',
- 'FOR',
- 'NOWAIT',
- 'SIZE',
- 'ARRAYLEN',
- 'FROM',
- 'NULL',
- 'SMALLINT',
- 'AS',
- 'GRANT',
- 'NUMBER',
- 'SQLBUF',
- 'ASC',
- 'GROUP',
- 'OF',
- 'SUCCESSFUL',
- 'AUDIT',
- 'HAVING',
- 'OFFLINE ',
- 'SYNONYM',
- 'BETWEEN',
- 'IDENTIFIED',
- 'ON',
- 'SYSDATE',
- 'BY',
- 'IMMEDIATE',
- 'ONLINE',
- 'TABLE',
- 'CHAR',
- 'IN',
- 'OPTION',
- 'THEN',
- 'CHECK',
- 'INCREMENT',
- 'OR',
- 'TO',
- 'CLUSTER',
- 'INDEX',
- 'ORDER',
- 'TRIGGER',
- 'COLUMN',
- 'INITIAL',
- 'PCTFREE',
- 'UID',
- 'COMMENT',
- 'INSERT',
- 'PRIOR',
- 'UNION',
- 'COMPRESS',
- 'INTEGER',
- 'PRIVILEGES',
- 'UNIQUE',
- 'CONNECT',
- 'INTERSECT',
- 'PUBLIC',
- 'UPDATE',
- 'CREATE',
- 'INTO',
- 'RAW',
- 'USER',
- 'CURRENT',
- 'IS',
- 'RENAME',
- 'VALIDATE',
- 'DATE',
- 'LEVEL',
- 'RESOURCE',
- 'VALUES',
- 'DECIMAL',
- 'LIKE',
- 'REVOKE',
- 'VARCHAR',
- 'DEFAULT',
- 'LOCK',
- 'ROW',
- 'VARCHAR2',
- 'DELETE',
- 'LONG',
- 'ROWID',
- 'VIEW',
- 'DESC',
- 'MAXEXTENTS',
- 'ROWLABEL',
- 'WHENEVER',
- 'DISTINCT',
- 'MINUS',
- 'ROWNUM',
- 'WHERE',
- 'DROP',
- 'MODE',
- 'ROWS',
- 'WITH',
-);
-// }}}
diff --git a/3rdparty/MDB2/Schema/Reserved/pgsql.php b/3rdparty/MDB2/Schema/Reserved/pgsql.php
deleted file mode 100644
index 84537685e0..0000000000
--- a/3rdparty/MDB2/Schema/Reserved/pgsql.php
+++ /dev/null
@@ -1,148 +0,0 @@
-
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-// {{{ $GLOBALS['_MDB2_Schema_Reserved']['pgsql']
-/**
- * Has a list of reserved words of pgsql
- *
- * @package MDB2_Schema
- * @category Database
- * @access protected
- * @author Marcelo Santos Araujo
- */
-$GLOBALS['_MDB2_Schema_Reserved']['pgsql'] = array(
- 'ALL',
- 'ANALYSE',
- 'ANALYZE',
- 'AND',
- 'ANY',
- 'AS',
- 'ASC',
- 'AUTHORIZATION',
- 'BETWEEN',
- 'BINARY',
- 'BOTH',
- 'CASE',
- 'CAST',
- 'CHECK',
- 'COLLATE',
- 'COLUMN',
- 'CONSTRAINT',
- 'CREATE',
- 'CURRENT_DATE',
- 'CURRENT_TIME',
- 'CURRENT_TIMESTAMP',
- 'CURRENT_USER',
- 'DEFAULT',
- 'DEFERRABLE',
- 'DESC',
- 'DISTINCT',
- 'DO',
- 'ELSE',
- 'END',
- 'EXCEPT',
- 'FALSE',
- 'FOR',
- 'FOREIGN',
- 'FREEZE',
- 'FROM',
- 'FULL',
- 'GRANT',
- 'GROUP',
- 'HAVING',
- 'ILIKE',
- 'IN',
- 'INITIALLY',
- 'INNER',
- 'INTERSECT',
- 'INTO',
- 'IS',
- 'ISNULL',
- 'JOIN',
- 'LEADING',
- 'LEFT',
- 'LIKE',
- 'LIMIT',
- 'LOCALTIME',
- 'LOCALTIMESTAMP',
- 'NATURAL',
- 'NEW',
- 'NOT',
- 'NOTNULL',
- 'NULL',
- 'OFF',
- 'OFFSET',
- 'OLD',
- 'ON',
- 'ONLY',
- 'OR',
- 'ORDER',
- 'OUTER',
- 'OVERLAPS',
- 'PLACING',
- 'PRIMARY',
- 'REFERENCES',
- 'SELECT',
- 'SESSION_USER',
- 'SIMILAR',
- 'SOME',
- 'TABLE',
- 'THEN',
- 'TO',
- 'TRAILING',
- 'TRUE',
- 'UNION',
- 'UNIQUE',
- 'USER',
- 'USING',
- 'VERBOSE',
- 'WHEN',
- 'WHERE'
-);
-// }}}
diff --git a/3rdparty/MDB2/Schema/Tool.php b/3rdparty/MDB2/Schema/Tool.php
deleted file mode 100644
index 3210c9173e..0000000000
--- a/3rdparty/MDB2/Schema/Tool.php
+++ /dev/null
@@ -1,583 +0,0 @@
-
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-require_once 'MDB2/Schema.php';
-require_once 'MDB2/Schema/Tool/ParameterException.php';
-
-/**
-* Command line tool to work with database schemas
-*
-* Functionality:
-* - dump a database schema to stdout
-* - import schema into database
-* - create a diff between two schemas
-* - apply diff to database
-*
- * @category Database
- * @package MDB2_Schema
- * @author Christian Weiske
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Tool
-{
- /**
- * Run the schema tool
- *
- * @param array $args Array of command line arguments
- */
- public function __construct($args)
- {
- $strAction = $this->getAction($args);
- try {
- $this->{'do' . ucfirst($strAction)}($args);
- } catch (MDB2_Schema_Tool_ParameterException $e) {
- $this->{'doHelp' . ucfirst($strAction)}($e->getMessage());
- }
- }//public function __construct($args)
-
-
-
- /**
- * Runs the tool with command line arguments
- *
- * @return void
- */
- public static function run()
- {
- $args = $GLOBALS['argv'];
- array_shift($args);
-
- try {
- $tool = new MDB2_Schema_Tool($args);
- } catch (Exception $e) {
- self::toStdErr($e->getMessage() . "\n");
- }
- }//public static function run()
-
-
-
- /**
- * Reads the first parameter from the argument array and
- * returns the action.
- *
- * @param array &$args Command line parameters
- *
- * @return string Action to execute
- */
- protected function getAction(&$args)
- {
- if (count($args) == 0) {
- return 'help';
- }
- $arg = array_shift($args);
- switch ($arg) {
- case 'h':
- case 'help':
- case '-h':
- case '--help':
- return 'help';
- case 'd':
- case 'dump':
- case '-d':
- case '--dump':
- return 'dump';
- case 'l':
- case 'load':
- case '-l':
- case '--load':
- return 'load';
- case 'i':
- case 'diff':
- case '-i':
- case '--diff':
- return 'diff';
- case 'a':
- case 'apply':
- case '-a':
- case '--apply':
- return 'apply';
- case 'n':
- case 'init':
- case '-i':
- case '--init':
- return 'init';
- default:
- throw new MDB2_Schema_Tool_ParameterException(
- "Unknown mode \"$arg\""
- );
- }
- }//protected function getAction(&$args)
-
-
-
- /**
- * Writes the message to stderr
- *
- * @param string $msg Message to print
- *
- * @return void
- */
- protected static function toStdErr($msg)
- {
- file_put_contents('php://stderr', $msg);
- }//protected static function toStdErr($msg)
-
-
-
- /**
- * Displays generic help to stdout
- *
- * @return void
- */
- protected function doHelp()
- {
- self::toStdErr(
-<< ' ',
- 'idxname_format' => '%s',
- 'debug' => true,
- 'quote_identifier' => true,
- 'force_defaults' => false,
- 'portability' => true,
- 'use_transactions' => false,
- );
- return $options;
- }//protected function getSchemaOptions()
-
-
-
- /**
- * Checks if the passed parameter is a PEAR_Error object
- * and throws an exception in that case.
- *
- * @param mixed $object Some variable to check
- * @param string $location Where the error occured
- *
- * @return void
- */
- protected function throwExceptionOnError($object, $location = '')
- {
- if (PEAR::isError($object)) {
- //FIXME: exception class
- //debug_print_backtrace();
- throw new Exception('Error ' . $location
- . "\n" . $object->getMessage()
- . "\n" . $object->getUserInfo()
- );
- }
- }//protected function throwExceptionOnError($object, $location = '')
-
-
-
- /**
- * Loads a file or a dsn from the arguments
- *
- * @param array &$args Array of arguments to the program
- *
- * @return array Array of ('file'|'dsn', $value)
- */
- protected function getFileOrDsn(&$args)
- {
- if (count($args) == 0) {
- throw new MDB2_Schema_Tool_ParameterException(
- 'File or DSN expected'
- );
- }
-
- $arg = array_shift($args);
- if ($arg == '-p') {
- $bAskPassword = true;
- $arg = array_shift($args);
- } else {
- $bAskPassword = false;
- }
-
- if (strpos($arg, '://') === false) {
- if (file_exists($arg)) {
- //File
- return array('file', $arg);
- } else {
- throw new Exception('Schema file does not exist');
- }
- }
-
- //read password if necessary
- if ($bAskPassword) {
- $password = $this->readPasswordFromStdin($arg);
- $arg = self::setPasswordIntoDsn($arg, $password);
- self::toStdErr($arg);
- }
- return array('dsn', $arg);
- }//protected function getFileOrDsn(&$args)
-
-
-
- /**
- * Takes a DSN data source name and integrates the given
- * password into it.
- *
- * @param string $dsn Data source name
- * @param string $password Password
- *
- * @return string DSN with password
- */
- protected function setPasswordIntoDsn($dsn, $password)
- {
- //simple try to integrate password
- if (strpos($dsn, '@') === false) {
- //no @ -> no user and no password
- return str_replace('://', '://:' . $password . '@', $dsn);
- } else if (preg_match('|://[^:]+@|', $dsn)) {
- //user only, no password
- return str_replace('@', ':' . $password . '@', $dsn);
- } else if (strpos($dsn, ':@') !== false) {
- //abstract version
- return str_replace(':@', ':' . $password . '@', $dsn);
- }
-
- return $dsn;
- }//protected function setPasswordIntoDsn($dsn, $password)
-
-
-
- /**
- * Reads a password from stdin
- *
- * @param string $dsn DSN name to put into the message
- *
- * @return string Password
- */
- protected function readPasswordFromStdin($dsn)
- {
- $stdin = fopen('php://stdin', 'r');
- self::toStdErr('Please insert password for ' . $dsn . "\n");
- $password = '';
- $breakme = false;
- while (false !== ($char = fgetc($stdin))) {
- if (ord($char) == 10 || $char == "\n" || $char == "\r") {
- break;
- }
- $password .= $char;
- }
- fclose($stdin);
-
- return trim($password);
- }//protected function readPasswordFromStdin()
-
-
-
- /**
- * Creates a database schema dump and sends it to stdout
- *
- * @param array $args Command line arguments
- *
- * @return void
- */
- protected function doDump($args)
- {
- $dump_what = MDB2_SCHEMA_DUMP_STRUCTURE;
- $arg = '';
- if (count($args)) {
- $arg = $args[0];
- }
-
- switch (strtolower($arg)) {
- case 'all':
- $dump_what = MDB2_SCHEMA_DUMP_ALL;
- array_shift($args);
- break;
- case 'data':
- $dump_what = MDB2_SCHEMA_DUMP_CONTENT;
- array_shift($args);
- break;
- case 'schema':
- array_shift($args);
- }
-
- list($type, $dsn) = $this->getFileOrDsn($args);
- if ($type == 'file') {
- throw new MDB2_Schema_Tool_ParameterException(
- 'Dumping a schema file as a schema file does not make much ' .
- 'sense'
- );
- }
-
- $schema = MDB2_Schema::factory($dsn, $this->getSchemaOptions());
- $this->throwExceptionOnError($schema);
-
- $definition = $schema->getDefinitionFromDatabase();
- $this->throwExceptionOnError($definition);
-
-
- $dump_options = array(
- 'output_mode' => 'file',
- 'output' => 'php://stdout',
- 'end_of_line' => "\r\n"
- );
- $op = $schema->dumpDatabase(
- $definition, $dump_options, $dump_what
- );
- $this->throwExceptionOnError($op);
-
- $schema->disconnect();
- }//protected function doDump($args)
-
-
-
- /**
- * Loads a database schema
- *
- * @param array $args Command line arguments
- *
- * @return void
- */
- protected function doLoad($args)
- {
- list($typeSource, $dsnSource) = $this->getFileOrDsn($args);
- list($typeDest, $dsnDest) = $this->getFileOrDsn($args);
-
- if ($typeDest == 'file') {
- throw new MDB2_Schema_Tool_ParameterException(
- 'A schema can only be loaded into a database, not a file'
- );
- }
-
-
- $schemaDest = MDB2_Schema::factory($dsnDest, $this->getSchemaOptions());
- $this->throwExceptionOnError($schemaDest);
-
- //load definition
- if ($typeSource == 'file') {
- $definition = $schemaDest->parseDatabaseDefinitionFile($dsnSource);
- $where = 'loading schema file';
- } else {
- $schemaSource = MDB2_Schema::factory(
- $dsnSource,
- $this->getSchemaOptions()
- );
- $this->throwExceptionOnError(
- $schemaSource,
- 'connecting to source database'
- );
-
- $definition = $schemaSource->getDefinitionFromDatabase();
- $where = 'loading definition from database';
- }
- $this->throwExceptionOnError($definition, $where);
-
-
- //create destination database from definition
- $simulate = false;
- $op = $schemaDest->createDatabase(
- $definition,
- array(),
- $simulate
- );
- $this->throwExceptionOnError($op, 'creating the database');
- }//protected function doLoad($args)
-
-
-
- /**
- * Initializes a database with data
- *
- * @param array $args Command line arguments
- *
- * @return void
- */
- protected function doInit($args)
- {
- list($typeSource, $dsnSource) = $this->getFileOrDsn($args);
- list($typeDest, $dsnDest) = $this->getFileOrDsn($args);
-
- if ($typeSource != 'file') {
- throw new MDB2_Schema_Tool_ParameterException(
- 'Data must come from a source file'
- );
- }
-
- if ($typeDest != 'dsn') {
- throw new MDB2_Schema_Tool_ParameterException(
- 'A schema can only be loaded into a database, not a file'
- );
- }
-
- $schemaDest = MDB2_Schema::factory($dsnDest, $this->getSchemaOptions());
- $this->throwExceptionOnError(
- $schemaDest,
- 'connecting to destination database'
- );
-
- $definition = $schemaDest->getDefinitionFromDatabase();
- $this->throwExceptionOnError(
- $definition,
- 'loading definition from database'
- );
-
- $op = $schemaDest->writeInitialization($dsnSource, $definition);
- $this->throwExceptionOnError($op, 'initializing database');
- }//protected function doInit($args)
-
-
-}//class MDB2_Schema_Tool
diff --git a/3rdparty/MDB2/Schema/Tool/ParameterException.php b/3rdparty/MDB2/Schema/Tool/ParameterException.php
deleted file mode 100644
index 92bea69391..0000000000
--- a/3rdparty/MDB2/Schema/Tool/ParameterException.php
+++ /dev/null
@@ -1,61 +0,0 @@
-
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-/**
- * To be implemented yet
- *
- * @category Database
- * @package MDB2_Schema
- * @author Christian Weiske
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Tool_ParameterException extends Exception
-{
-}
diff --git a/3rdparty/MDB2/Schema/Validate.php b/3rdparty/MDB2/Schema/Validate.php
deleted file mode 100644
index 4a8e0d27ba..0000000000
--- a/3rdparty/MDB2/Schema/Validate.php
+++ /dev/null
@@ -1,1004 +0,0 @@
-
- * @author Igor Feghali
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-/**
- * Validates an XML schema file
- *
- * @category Database
- * @package MDB2_Schema
- * @author Igor Feghali
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Validate
-{
- // {{{ properties
-
- var $fail_on_invalid_names = true;
-
- var $valid_types = array();
-
- var $force_defaults = true;
-
- var $max_identifiers_length = null;
-
- // }}}
- // {{{ constructor
-
- /**
- * PHP 5 constructor
- *
- * @param bool $fail_on_invalid_names array with reserved words per RDBMS
- * @param array $valid_types information of all valid fields
- * types
- * @param bool $force_defaults if true sets a default value to
- * field when not explicit
- * @param int $max_identifiers_length maximum allowed size for entities
- * name
- *
- * @return void
- *
- * @access public
- * @static
- */
- function __construct($fail_on_invalid_names = true, $valid_types = array(),
- $force_defaults = true, $max_identifiers_length = null
- ) {
- if (empty($GLOBALS['_MDB2_Schema_Reserved'])) {
- $GLOBALS['_MDB2_Schema_Reserved'] = array();
- }
-
- if (is_array($fail_on_invalid_names)) {
- $this->fail_on_invalid_names = array_intersect($fail_on_invalid_names,
- array_keys($GLOBALS['_MDB2_Schema_Reserved']));
- } elseif ($fail_on_invalid_names === true) {
- $this->fail_on_invalid_names = array_keys($GLOBALS['_MDB2_Schema_Reserved']);
- } else {
- $this->fail_on_invalid_names = array();
- }
- $this->valid_types = $valid_types;
- $this->force_defaults = $force_defaults;
- $this->max_identifiers_length = $max_identifiers_length;
- }
-
- // }}}
- // {{{ raiseError()
-
- /**
- * Pushes a MDB2_Schema_Error into stack and returns it
- *
- * @param int $ecode MDB2_Schema's error code
- * @param string $msg textual message
- *
- * @return object
- * @access private
- * @static
- */
- function &raiseError($ecode, $msg = null)
- {
- $error = MDB2_Schema::raiseError($ecode, null, null, $msg);
- return $error;
- }
-
- // }}}
- // {{{ isBoolean()
-
- /**
- * Verifies if a given value can be considered boolean. If yes, set value
- * to true or false according to its actual contents and return true. If
- * not, keep its contents untouched and return false.
- *
- * @param mixed &$value value to be checked
- *
- * @return bool
- *
- * @access public
- * @static
- */
- function isBoolean(&$value)
- {
- if (is_bool($value)) {
- return true;
- }
-
- if ($value === 0 || $value === 1 || $value === '') {
- $value = (bool)$value;
- return true;
- }
-
- if (!is_string($value)) {
- return false;
- }
-
- switch ($value) {
- case '0':
- case 'N':
- case 'n':
- case 'no':
- case 'false':
- $value = false;
- break;
- case '1':
- case 'Y':
- case 'y':
- case 'yes':
- case 'true':
- $value = true;
- break;
- default:
- return false;
- }
- return true;
- }
-
- // }}}
- // {{{ validateTable()
-
- /* Definition */
- /**
- * Checks whether the definition of a parsed table is valid. Modify table
- * definition when necessary.
- *
- * @param array $tables multi dimensional array that contains the
- * tables of current database.
- * @param array &$table multi dimensional array that contains the
- * structure and optional data of the table.
- * @param string $table_name name of the parsed table
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateTable($tables, &$table, $table_name)
- {
- /* Table name duplicated? */
- if (is_array($tables) && isset($tables[$table_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'table "'.$table_name.'" already exists');
- }
-
- /**
- * Valid name ?
- */
- $result = $this->validateIdentifier($table_name, 'table');
- if (PEAR::isError($result)) {
- return $result;
- }
-
- /* Was */
- if (empty($table['was'])) {
- $table['was'] = $table_name;
- }
-
- /* Have we got fields? */
- if (empty($table['fields']) || !is_array($table['fields'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'tables need one or more fields');
- }
-
- /* Autoincrement */
- $autoinc = $primary = false;
- foreach ($table['fields'] as $field_name => $field) {
- if (!empty($field['autoincrement'])) {
- if ($autoinc) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'there was already an autoincrement field in "'.$table_name.'" before "'.$field_name.'"');
- }
- $autoinc = $field_name;
- }
- }
-
- /*
- * Checking Indexes
- * this have to be done here otherwise we can't
- * guarantee that all table fields were already
- * defined in the moment we are parsing indexes
- */
- if (!empty($table['indexes']) && is_array($table['indexes'])) {
- foreach ($table['indexes'] as $name => $index) {
- $skip_index = false;
- if (!empty($index['primary'])) {
- /*
- * Lets see if we should skip this index since there is
- * already an auto increment on this field this implying
- * a primary key index.
- */
- if (count($index['fields']) == '1'
- && $autoinc
- && array_key_exists($autoinc, $index['fields'])) {
- $skip_index = true;
- } elseif ($autoinc || $primary) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'there was already an primary index or autoincrement field in "'.$table_name.'" before "'.$name.'"');
- } else {
- $primary = true;
- }
- }
-
- if (!$skip_index && is_array($index['fields'])) {
- foreach ($index['fields'] as $field_name => $field) {
- if (!isset($table['fields'][$field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'index field "'.$field_name.'" does not exist');
- }
- if (!empty($index['primary'])
- && !$table['fields'][$field_name]['notnull']
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'all primary key fields must be defined notnull in "'.$table_name.'"');
- }
- }
- } else {
- unset($table['indexes'][$name]);
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateField()
-
- /**
- * Checks whether the definition of a parsed field is valid. Modify field
- * definition when necessary.
- *
- * @param array $fields multi dimensional array that contains the
- * fields of current table.
- * @param array &$field multi dimensional array that contains the
- * structure of the parsed field.
- * @param string $field_name name of the parsed field
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateField($fields, &$field, $field_name)
- {
- /**
- * Valid name ?
- */
- $result = $this->validateIdentifier($field_name, 'field');
- if (PEAR::isError($result)) {
- return $result;
- }
-
- /* Field name duplicated? */
- if (is_array($fields) && isset($fields[$field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "'.$field_name.'" already exists');
- }
-
- /* Type check */
- if (empty($field['type'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'no field type specified');
- }
- if (!empty($this->valid_types) && !array_key_exists($field['type'], $this->valid_types)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'no valid field type ("'.$field['type'].'") specified');
- }
-
- /* Unsigned */
- if (array_key_exists('unsigned', $field) && !$this->isBoolean($field['unsigned'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'unsigned has to be a boolean value');
- }
-
- /* Fixed */
- if (array_key_exists('fixed', $field) && !$this->isBoolean($field['fixed'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'fixed has to be a boolean value');
- }
-
- /* Length */
- if (array_key_exists('length', $field) && $field['length'] <= 0) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'length has to be an integer greater 0');
- }
-
- // if it's a DECIMAL datatype, check if a 'scale' value is provided:
- // 8,4 should be translated to DECIMAL(8,4)
- if (is_float($this->valid_types[$field['type']])
- && !empty($field['length'])
- && strpos($field['length'], ',') !== false
- ) {
- list($field['length'], $field['scale']) = explode(',', $field['length']);
- }
-
- /* Was */
- if (empty($field['was'])) {
- $field['was'] = $field_name;
- }
-
- /* Notnull */
- if (empty($field['notnull'])) {
- $field['notnull'] = false;
- }
- if (!$this->isBoolean($field['notnull'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "notnull" has to be a boolean value');
- }
-
- /* Default */
- if ($this->force_defaults
- && !array_key_exists('default', $field)
- && $field['type'] != 'clob' && $field['type'] != 'blob'
- ) {
- $field['default'] = $this->valid_types[$field['type']];
- }
- if (array_key_exists('default', $field)) {
- if ($field['type'] == 'clob' || $field['type'] == 'blob') {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field['type'].'"-fields are not allowed to have a default value');
- }
- if ($field['default'] === '' && !$field['notnull']) {
- $field['default'] = null;
- }
- }
- if (isset($field['default'])
- && PEAR::isError($result = $this->validateDataFieldValue($field, $field['default'], $field_name))
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'default value of "'.$field_name.'" is incorrect: '.$result->getUserinfo());
- }
-
- /* Autoincrement */
- if (!empty($field['autoincrement'])) {
- if (!$field['notnull']) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'all autoincrement fields must be defined notnull');
- }
-
- if (empty($field['default'])) {
- $field['default'] = '0';
- } elseif ($field['default'] !== '0' && $field['default'] !== 0) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'all autoincrement fields must be defined default "0"');
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateIndex()
-
- /**
- * Checks whether a parsed index is valid. Modify index definition when
- * necessary.
- *
- * @param array $table_indexes multi dimensional array that contains the
- * indexes of current table.
- * @param array &$index multi dimensional array that contains the
- * structure of the parsed index.
- * @param string $index_name name of the parsed index
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateIndex($table_indexes, &$index, $index_name)
- {
- /**
- * Valid name ?
- */
- $result = $this->validateIdentifier($index_name, 'index');
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if (is_array($table_indexes) && isset($table_indexes[$index_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'index "'.$index_name.'" already exists');
- }
- if (array_key_exists('unique', $index) && !$this->isBoolean($index['unique'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "unique" has to be a boolean value');
- }
- if (array_key_exists('primary', $index) && !$this->isBoolean($index['primary'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "primary" has to be a boolean value');
- }
-
- /* Have we got fields? */
- if (empty($index['fields']) || !is_array($index['fields'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'indexes need one or more fields');
- }
-
- if (empty($index['was'])) {
- $index['was'] = $index_name;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateIndexField()
-
- /**
- * Checks whether a parsed index-field is valid. Modify its definition when
- * necessary.
- *
- * @param array $index_fields multi dimensional array that contains the
- * fields of current index.
- * @param array &$field multi dimensional array that contains the
- * structure of the parsed index-field.
- * @param string $field_name name of the parsed index-field
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateIndexField($index_fields, &$field, $field_name)
- {
- /**
- * Valid name ?
- */
- $result = $this->validateIdentifier($field_name, 'index field');
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if (is_array($index_fields) && isset($index_fields[$field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'index field "'.$field_name.'" already exists');
- }
- if (empty($field['sorting'])) {
- $field['sorting'] = 'ascending';
- } elseif ($field['sorting'] !== 'ascending' && $field['sorting'] !== 'descending') {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'sorting type unknown');
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateConstraint()
-
- /**
- * Checks whether a parsed foreign key is valid. Modify its definition when
- * necessary.
- *
- * @param array $table_constraints multi dimensional array that contains the
- * constraints of current table.
- * @param array &$constraint multi dimensional array that contains the
- * structure of the parsed foreign key.
- * @param string $constraint_name name of the parsed foreign key
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateConstraint($table_constraints, &$constraint, $constraint_name)
- {
- /**
- * Valid name ?
- */
- $result = $this->validateIdentifier($constraint_name, 'foreign key');
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if (is_array($table_constraints) && isset($table_constraints[$constraint_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign key "'.$constraint_name.'" already exists');
- }
-
- /* Have we got fields? */
- if (empty($constraint['fields']) || !is_array($constraint['fields'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign key "'.$constraint_name.'" need one or more fields');
- }
-
- /* Have we got referenced fields? */
- if (empty($constraint['references']) || !is_array($constraint['references'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign key "'.$constraint_name.'" need to reference one or more fields');
- }
-
- /* Have we got referenced table? */
- if (empty($constraint['references']['table'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign key "'.$constraint_name.'" need to reference a table');
- }
-
- if (empty($constraint['was'])) {
- $constraint['was'] = $constraint_name;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateConstraintField()
-
- /**
- * Checks whether a foreign-field is valid.
- *
- * @param array $constraint_fields multi dimensional array that contains the
- * fields of current foreign key.
- * @param string $field_name name of the parsed foreign-field
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateConstraintField($constraint_fields, $field_name)
- {
- /**
- * Valid name ?
- */
- $result = $this->validateIdentifier($field_name, 'foreign key field');
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if (is_array($constraint_fields) && isset($constraint_fields[$field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign field "'.$field_name.'" already exists');
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateConstraintReferencedField()
-
- /**
- * Checks whether a foreign-referenced field is valid.
- *
- * @param array $referenced_fields multi dimensional array that contains the
- * fields of current foreign key.
- * @param string $field_name name of the parsed foreign-field
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateConstraintReferencedField($referenced_fields, $field_name)
- {
- /**
- * Valid name ?
- */
- $result = $this->validateIdentifier($field_name, 'referenced foreign field');
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if (is_array($referenced_fields) && isset($referenced_fields[$field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign field "'.$field_name.'" already referenced');
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateSequence()
-
- /**
- * Checks whether the definition of a parsed sequence is valid. Modify
- * sequence definition when necessary.
- *
- * @param array $sequences multi dimensional array that contains the
- * sequences of current database.
- * @param array &$sequence multi dimensional array that contains the
- * structure of the parsed sequence.
- * @param string $sequence_name name of the parsed sequence
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateSequence($sequences, &$sequence, $sequence_name)
- {
- /**
- * Valid name ?
- */
- $result = $this->validateIdentifier($sequence_name, 'sequence');
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if (is_array($sequences) && isset($sequences[$sequence_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'sequence "'.$sequence_name.'" already exists');
- }
-
- if (is_array($this->fail_on_invalid_names)) {
- $name = strtoupper($sequence_name);
- foreach ($this->fail_on_invalid_names as $rdbms) {
- if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'sequence name "'.$sequence_name.'" is a reserved word in: '.$rdbms);
- }
- }
- }
-
- if (empty($sequence['was'])) {
- $sequence['was'] = $sequence_name;
- }
-
- if (!empty($sequence['on'])
- && (empty($sequence['on']['table']) || empty($sequence['on']['field']))
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'sequence "'.$sequence_name.'" on a table was not properly defined');
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateDatabase()
-
- /**
- * Checks whether a parsed database is valid. Modify its structure and
- * data when necessary.
- *
- * @param array &$database multi dimensional array that contains the
- * structure and optional data of the database.
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateDatabase(&$database)
- {
- if (!is_array($database)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'something wrong went with database definition');
- }
-
- /**
- * Valid name ?
- */
- $result = $this->validateIdentifier($database['name'], 'database');
- if (PEAR::isError($result)) {
- return $result;
- }
-
- /* Create */
- if (isset($database['create'])
- && !$this->isBoolean($database['create'])
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "create" has to be a boolean value');
- }
-
- /* Overwrite */
- if (isset($database['overwrite'])
- && $database['overwrite'] !== ''
- && !$this->isBoolean($database['overwrite'])
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "overwrite" has to be a boolean value');
- }
-
- /*
- * This have to be done here otherwise we can't guarantee that all
- * tables were already defined in the moment we are parsing constraints
- */
- if (isset($database['tables'])) {
- foreach ($database['tables'] as $table_name => $table) {
- if (!empty($table['constraints'])) {
- foreach ($table['constraints'] as $constraint_name => $constraint) {
- $referenced_table_name = $constraint['references']['table'];
-
- if (!isset($database['tables'][$referenced_table_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'referenced table "'.$referenced_table_name.'" of foreign key "'.$constraint_name.'" of table "'.$table_name.'" does not exist');
- }
-
- if (empty($constraint['references']['fields'])) {
- $referenced_table = $database['tables'][$referenced_table_name];
-
- $primary = false;
-
- if (!empty($referenced_table['indexes'])) {
- foreach ($referenced_table['indexes'] as $index_name => $index) {
- if (array_key_exists('primary', $index)
- && $index['primary']
- ) {
- $primary = array();
- foreach ($index['fields'] as $field_name => $field) {
- $primary[$field_name] = '';
- }
- break;
- }
- }
- }
-
- if (!$primary) {
- foreach ($referenced_table['fields'] as $field_name => $field) {
- if (array_key_exists('autoincrement', $field)
- && $field['autoincrement']
- ) {
- $primary = array( $field_name => '' );
- break;
- }
- }
- }
-
- if (!$primary) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'referenced table "'.$referenced_table_name.'" has no primary key and no referenced field was specified for foreign key "'.$constraint_name.'" of table "'.$table_name.'"');
- }
-
- $constraint['references']['fields'] = $primary;
- }
-
- /* the same number of referencing and referenced fields ? */
- if (count($constraint['fields']) != count($constraint['references']['fields'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'The number of fields in the referenced key must match those of the foreign key "'.$constraint_name.'"');
- }
-
- $database['tables'][$table_name]['constraints'][$constraint_name]['references']['fields'] = $constraint['references']['fields'];
- }
- }
- }
- }
-
- /*
- * This have to be done here otherwise we can't guarantee that all
- * tables were already defined in the moment we are parsing sequences
- */
- if (isset($database['sequences'])) {
- foreach ($database['sequences'] as $seq_name => $seq) {
- if (!empty($seq['on'])
- && empty($database['tables'][$seq['on']['table']]['fields'][$seq['on']['field']])
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'sequence "'.$seq_name.'" was assigned on unexisting field/table');
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateDataField()
-
- /* Data Manipulation */
- /**
- * Checks whether a parsed DML-field is valid. Modify its structure when
- * necessary. This is called when validating INSERT and
- * UPDATE.
- *
- * @param array $table_fields multi dimensional array that contains the
- * definition for current table's fields.
- * @param array $instruction_fields multi dimensional array that contains the
- * parsed fields of the current DML instruction.
- * @param string &$field array that contains the parsed instruction field
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateDataField($table_fields, $instruction_fields, &$field)
- {
- /**
- * Valid name ?
- */
- $result = $this->validateIdentifier($field['name'], 'field');
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if (is_array($instruction_fields) && isset($instruction_fields[$field['name']])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "'.$field['name'].'" already initialized');
- }
-
- if (is_array($table_fields) && !isset($table_fields[$field['name']])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field['name'].'" is not defined');
- }
-
- if (!isset($field['group']['type'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field['name'].'" has no initial value');
- }
-
- if (isset($field['group']['data'])
- && $field['group']['type'] == 'value'
- && $field['group']['data'] !== ''
- && PEAR::isError($result = $this->validateDataFieldValue($table_fields[$field['name']], $field['group']['data'], $field['name']))
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'value of "'.$field['name'].'" is incorrect: '.$result->getUserinfo());
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateDataFieldValue()
-
- /**
- * Checks whether a given value is compatible with a table field. This is
- * done when parsing a field for a INSERT or UPDATE instruction.
- *
- * @param array $field_def multi dimensional array that contains the
- * definition for current table's fields.
- * @param string &$field_value value to fill the parsed field
- * @param string $field_name name of the parsed field
- *
- * @return bool|error object
- *
- * @access public
- * @see MDB2_Schema_Validate::validateInsertField()
- */
- function validateDataFieldValue($field_def, &$field_value, $field_name)
- {
- switch ($field_def['type']) {
- case 'text':
- case 'clob':
- if (!empty($field_def['length']) && strlen($field_value) > $field_def['length']) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is larger than "'.$field_def['length'].'"');
- }
- break;
- case 'blob':
- $field_value = pack('H*', $field_value);
- if (!empty($field_def['length']) && strlen($field_value) > $field_def['length']) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is larger than "'.$field_def['type'].'"');
- }
- break;
- case 'integer':
- if ($field_value != ((int)$field_value)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- //$field_value = (int)$field_value;
- if (!empty($field_def['unsigned']) && $field_def['unsigned'] && $field_value < 0) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" signed instead of unsigned');
- }
- break;
- case 'boolean':
- if (!$this->isBoolean($field_value)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- break;
- case 'date':
- if (!preg_match('/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/', $field_value)
- && $field_value !== 'CURRENT_DATE'
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- break;
- case 'timestamp':
- if (!preg_match('/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $field_value)
- && strcasecmp($field_value, 'now()') != 0
- && $field_value !== 'CURRENT_TIMESTAMP'
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- break;
- case 'time':
- if (!preg_match("/([0-9]{2}):([0-9]{2}):([0-9]{2})/", $field_value)
- && $field_value !== 'CURRENT_TIME'
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- break;
- case 'float':
- case 'double':
- if ($field_value != (double)$field_value) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- //$field_value = (double)$field_value;
- break;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateIdentifier()
-
- /**
- * Checks whether a given identifier is valid for current driver.
- *
- * @param string $id identifier to check
- * @param string $type whether identifier represents a table name, index, etc.
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateIdentifier($id, $type)
- {
- $max_length = $this->max_identifiers_length;
- $cur_length = strlen($id);
-
- /**
- * Have we got a name?
- */
- if (!$id) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- "a $type has to have a name");
- }
-
- /**
- * Supported length ?
- */
- if ($max_length !== null
- && $cur_length > $max_length
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- "$type name '$id' is too long for current driver");
- } elseif ($cur_length > 30) {
- // FIXME: find a way to issue a warning in MDB2_Schema object
- /* $this->warnings[] = "$type name '$id' might not be
- portable to other drivers"; */
- }
-
- /**
- * Reserved ?
- */
- if (is_array($this->fail_on_invalid_names)) {
- $name = strtoupper($id);
- foreach ($this->fail_on_invalid_names as $rdbms) {
- if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- "$type name '$id' is a reserved word in: $rdbms");
- }
- }
- }
-
- return MDB2_OK;
- }
-
- // }}}
-}
diff --git a/3rdparty/MDB2/Schema/Writer.php b/3rdparty/MDB2/Schema/Writer.php
deleted file mode 100644
index 3eaa39a207..0000000000
--- a/3rdparty/MDB2/Schema/Writer.php
+++ /dev/null
@@ -1,586 +0,0 @@
-
- * @author Igor Feghali
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version SVN: $Id$
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-/**
- * Writes an XML schema file
- *
- * @category Database
- * @package MDB2_Schema
- * @author Lukas Smith
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Writer
-{
- // {{{ properties
-
- var $valid_types = array();
-
- // }}}
- // {{{ constructor
-
- /**
- * PHP 5 constructor
- *
- * @param array $valid_types information of all valid fields
- * types
- *
- * @return void
- *
- * @access public
- * @static
- */
- function __construct($valid_types = array())
- {
- $this->valid_types = $valid_types;
- }
-
- // }}}
- // {{{ raiseError()
-
- /**
- * This method is used to communicate an error and invoke error
- * callbacks etc. Basically a wrapper for PEAR::raiseError
- * without the message string.
- *
- * @param int|PEAR_Error $code integer error code or and PEAR_Error
- * instance
- * @param int $mode error mode, see PEAR_Error docs error
- * level (E_USER_NOTICE etc). If error mode
- * is PEAR_ERROR_CALLBACK, this is the
- * callback function, either as a function
- * name, or as an array of an object and
- * method name. For other error modes this
- * parameter is ignored.
- * @param string $options Extra debug information. Defaults to the
- * last query and native error code.
- * @param string $userinfo User-friendly error message
- *
- * @return object a PEAR error object
- * @access public
- * @see PEAR_Error
- */
- function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
- {
- $error = MDB2_Schema::raiseError($code, $mode, $options, $userinfo);
- return $error;
- }
-
- // }}}
- // {{{ _escapeSpecialChars()
-
- /**
- * add escapecharacters to all special characters in a string
- *
- * @param string $string string that should be escaped
- *
- * @return string escaped string
- * @access protected
- */
- function _escapeSpecialChars($string)
- {
- if (!is_string($string)) {
- $string = strval($string);
- }
-
- $escaped = '';
- for ($char = 0, $count = strlen($string); $char < $count; $char++) {
- switch ($string[$char]) {
- case '&':
- $escaped .= '&';
- break;
- case '>':
- $escaped .= '>';
- break;
- case '<':
- $escaped .= '<';
- break;
- case '"':
- $escaped .= '"';
- break;
- case '\'':
- $escaped .= ''';
- break;
- default:
- $code = ord($string[$char]);
- if ($code < 32 || $code > 127) {
- $escaped .= "$code;";
- } else {
- $escaped .= $string[$char];
- }
- break;
- }
- }
- return $escaped;
- }
-
- // }}}
- // {{{ _dumpBoolean()
-
- /**
- * dump the structure of a sequence
- *
- * @param string $boolean boolean value or variable definition
- *
- * @return string with xml boolea definition
- * @access private
- */
- function _dumpBoolean($boolean)
- {
- if (is_string($boolean)) {
- if ($boolean !== 'true' || $boolean !== 'false'
- || preg_match('/.* /', $boolean)
- ) {
- return $boolean;
- }
- }
- return $boolean ? 'true' : 'false';
- }
-
- // }}}
- // {{{ dumpSequence()
-
- /**
- * dump the structure of a sequence
- *
- * @param string $sequence_definition sequence definition
- * @param string $sequence_name sequence name
- * @param string $eol end of line characters
- * @param integer $dump determines what data to dump
- * MDB2_SCHEMA_DUMP_ALL : the entire db
- * MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
- * MDB2_SCHEMA_DUMP_CONTENT : only the content of the db
- *
- * @return mixed string xml sequence definition on success, or a error object
- * @access public
- */
- function dumpSequence($sequence_definition, $sequence_name, $eol, $dump = MDB2_SCHEMA_DUMP_ALL)
- {
- $buffer = "$eol $eol $sequence_name $eol";
- if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT) {
- if (!empty($sequence_definition['start'])) {
- $start = $sequence_definition['start'];
- $buffer .= " $start $eol";
- }
- }
-
- if (!empty($sequence_definition['on'])) {
- $buffer .= " $eol";
- $buffer .= " ".$sequence_definition['on']['table'];
- $buffer .= "
$eol ".$sequence_definition['on']['field'];
- $buffer .= " $eol $eol";
- }
- $buffer .= " $eol";
-
- return $buffer;
- }
-
- // }}}
- // {{{ dumpDatabase()
-
- /**
- * Dump a previously parsed database structure in the Metabase schema
- * XML based format suitable for the Metabase parser. This function
- * may optionally dump the database definition with initialization
- * commands that specify the data that is currently present in the tables.
- *
- * @param array $database_definition unknown
- * @param array $arguments associative array that takes pairs of tag
- * names and values that define dump options.
- * array (
- * 'output_mode' => String
- * 'file' : dump into a file
- * default: dump using a function
- * 'output' => String
- * depending on the 'Output_Mode'
- * name of the file
- * name of the function
- * 'end_of_line' => String
- * end of line delimiter that should be used
- * default: "\n"
- * );
- * @param integer $dump determines what data to dump
- * MDB2_SCHEMA_DUMP_ALL : the entire db
- * MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
- * MDB2_SCHEMA_DUMP_CONTENT : only the content of the db
- *
- * @return mixed MDB2_OK on success, or a error object
- * @access public
- */
- function dumpDatabase($database_definition, $arguments, $dump = MDB2_SCHEMA_DUMP_ALL)
- {
- if (!empty($arguments['output'])) {
- if (!empty($arguments['output_mode']) && $arguments['output_mode'] == 'file') {
- $fp = fopen($arguments['output'], 'w');
- if ($fp === false) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null,
- 'it was not possible to open output file');
- }
-
- $output = false;
- } elseif (is_callable($arguments['output'])) {
- $output = $arguments['output'];
- } else {
- return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null,
- 'no valid output function specified');
- }
- } else {
- return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null,
- 'no output method specified');
- }
-
- $eol = isset($arguments['end_of_line']) ? $arguments['end_of_line'] : "\n";
-
- $sequences = array();
- if (!empty($database_definition['sequences'])
- && is_array($database_definition['sequences'])
- ) {
- foreach ($database_definition['sequences'] as $sequence_name => $sequence) {
- $table = !empty($sequence['on']) ? $sequence['on']['table'] :'';
-
- $sequences[$table][] = $sequence_name;
- }
- }
-
- $buffer = ''.$eol;
- $buffer .= "$eol$eol ".$database_definition['name']." ";
- $buffer .= "$eol ".$this->_dumpBoolean($database_definition['create'])." ";
- $buffer .= "$eol ".$this->_dumpBoolean($database_definition['overwrite'])." $eol";
- $buffer .= "$eol ".$database_definition['charset']." $eol";
-
- if ($output) {
- call_user_func($output, $buffer);
- } else {
- fwrite($fp, $buffer);
- }
-
- if (!empty($database_definition['tables']) && is_array($database_definition['tables'])) {
- foreach ($database_definition['tables'] as $table_name => $table) {
- $buffer = "$eol $eol$eol $table_name $eol";
- if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_STRUCTURE) {
- $buffer .= "$eol $eol";
- if (!empty($table['fields']) && is_array($table['fields'])) {
- foreach ($table['fields'] as $field_name => $field) {
- if (empty($field['type'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null,
- 'it was not specified the type of the field "'.
- $field_name.'" of the table "'.$table_name.'"');
- }
- if (!empty($this->valid_types) && !array_key_exists($field['type'], $this->valid_types)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- 'type "'.$field['type'].'" is not yet supported');
- }
- $buffer .= "$eol $eol $field_name $eol ";
- $buffer .= $field['type']." $eol";
- if (!empty($field['fixed']) && $field['type'] === 'text') {
- $buffer .= " ".$this->_dumpBoolean($field['fixed'])." $eol";
- }
- if (array_key_exists('default', $field)
- && $field['type'] !== 'clob' && $field['type'] !== 'blob'
- ) {
- $buffer .= ' '.$this->_escapeSpecialChars($field['default'])." $eol";
- }
- if (!empty($field['notnull'])) {
- $buffer .= " ".$this->_dumpBoolean($field['notnull'])." $eol";
- } else {
- $buffer .= " false $eol";
- }
- if (!empty($field['autoincrement'])) {
- $buffer .= " " . $field['autoincrement'] ." $eol";
- }
- if (!empty($field['unsigned'])) {
- $buffer .= " ".$this->_dumpBoolean($field['unsigned'])." $eol";
- }
- if (!empty($field['length'])) {
- $buffer .= ' '.$field['length']." $eol";
- }
- $buffer .= " $eol";
- }
- }
-
- if (!empty($table['indexes']) && is_array($table['indexes'])) {
- foreach ($table['indexes'] as $index_name => $index) {
- if (strtolower($index_name) === 'primary') {
- $index_name = $table_name . '_pKey';
- }
- $buffer .= "$eol $eol $index_name $eol";
- if (!empty($index['unique'])) {
- $buffer .= " ".$this->_dumpBoolean($index['unique'])." $eol";
- }
-
- if (!empty($index['primary'])) {
- $buffer .= " ".$this->_dumpBoolean($index['primary'])." $eol";
- }
-
- foreach ($index['fields'] as $field_name => $field) {
- $buffer .= " $eol $field_name $eol";
- if (!empty($field) && is_array($field)) {
- $buffer .= ' '.$field['sorting']." $eol";
- }
- $buffer .= " $eol";
- }
- $buffer .= " $eol";
- }
- }
-
- if (!empty($table['constraints']) && is_array($table['constraints'])) {
- foreach ($table['constraints'] as $constraint_name => $constraint) {
- $buffer .= "$eol $eol $constraint_name $eol";
- if (empty($constraint['fields']) || !is_array($constraint['fields'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null,
- 'it was not specified a field for the foreign key "'.
- $constraint_name.'" of the table "'.$table_name.'"');
- }
- if (!is_array($constraint['references']) || empty($constraint['references']['table'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null,
- 'it was not specified the referenced table of the foreign key "'.
- $constraint_name.'" of the table "'.$table_name.'"');
- }
- if (!empty($constraint['match'])) {
- $buffer .= " ".$constraint['match']." $eol";
- }
- if (!empty($constraint['ondelete'])) {
- $buffer .= " ".$constraint['ondelete']." $eol";
- }
- if (!empty($constraint['onupdate'])) {
- $buffer .= " ".$constraint['onupdate']." $eol";
- }
- if (!empty($constraint['deferrable'])) {
- $buffer .= " ".$constraint['deferrable']." $eol";
- }
- if (!empty($constraint['initiallydeferred'])) {
- $buffer .= " ".$constraint['initiallydeferred']." $eol";
- }
- foreach ($constraint['fields'] as $field_name => $field) {
- $buffer .= " $field_name $eol";
- }
- $buffer .= " $eol ".$constraint['references']['table']."
$eol";
- foreach ($constraint['references']['fields'] as $field_name => $field) {
- $buffer .= " $field_name $eol";
- }
- $buffer .= " $eol";
-
- $buffer .= " $eol";
- }
- }
-
- $buffer .= "$eol $eol";
- }
-
- if ($output) {
- call_user_func($output, $buffer);
- } else {
- fwrite($fp, $buffer);
- }
-
- $buffer = '';
- if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT) {
- if (!empty($table['initialization']) && is_array($table['initialization'])) {
- $buffer = "$eol $eol";
- foreach ($table['initialization'] as $instruction) {
- switch ($instruction['type']) {
- case 'insert':
- $buffer .= "$eol $eol";
- foreach ($instruction['data']['field'] as $field) {
- $field_name = $field['name'];
-
- $buffer .= "$eol $eol $field_name $eol";
- $buffer .= $this->writeExpression($field['group'], 5, $arguments);
- $buffer .= " $eol";
- }
- $buffer .= "$eol $eol";
- break;
- case 'update':
- $buffer .= "$eol $eol";
- foreach ($instruction['data']['field'] as $field) {
- $field_name = $field['name'];
-
- $buffer .= "$eol $eol $field_name $eol";
- $buffer .= $this->writeExpression($field['group'], 5, $arguments);
- $buffer .= " $eol";
- }
-
- if (!empty($instruction['data']['where'])
- && is_array($instruction['data']['where'])
- ) {
- $buffer .= " $eol";
- $buffer .= $this->writeExpression($instruction['data']['where'], 5, $arguments);
- $buffer .= " $eol";
- }
-
- $buffer .= "$eol $eol";
- break;
- case 'delete':
- $buffer .= "$eol $eol$eol";
- if (!empty($instruction['data']['where'])
- && is_array($instruction['data']['where'])
- ) {
- $buffer .= " $eol";
- $buffer .= $this->writeExpression($instruction['data']['where'], 5, $arguments);
- $buffer .= " $eol";
- }
- $buffer .= "$eol $eol";
- break;
- }
- }
- $buffer .= "$eol $eol";
- }
- }
- $buffer .= "$eol
$eol";
- if ($output) {
- call_user_func($output, $buffer);
- } else {
- fwrite($fp, $buffer);
- }
-
- if (isset($sequences[$table_name])) {
- foreach ($sequences[$table_name] as $sequence) {
- $result = $this->dumpSequence($database_definition['sequences'][$sequence],
- $sequence, $eol, $dump);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($output) {
- call_user_func($output, $result);
- } else {
- fwrite($fp, $result);
- }
- }
- }
- }
- }
-
- if (isset($sequences[''])) {
- foreach ($sequences[''] as $sequence) {
- $result = $this->dumpSequence($database_definition['sequences'][$sequence],
- $sequence, $eol, $dump);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($output) {
- call_user_func($output, $result);
- } else {
- fwrite($fp, $result);
- }
- }
- }
-
- $buffer = "$eol $eol";
- if ($output) {
- call_user_func($output, $buffer);
- } else {
- fwrite($fp, $buffer);
- fclose($fp);
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ writeExpression()
-
- /**
- * Dumps the structure of an element. Elements can be value, column,
- * function or expression.
- *
- * @param array $element multi dimensional array that represents the parsed element
- * of a DML instruction.
- * @param integer $offset base indentation width
- * @param array $arguments associative array that takes pairs of tag
- * names and values that define dump options.
- *
- * @return string
- *
- * @access public
- * @see MDB2_Schema_Writer::dumpDatabase()
- */
- function writeExpression($element, $offset = 0, $arguments = null)
- {
- $eol = isset($arguments['end_of_line']) ? $arguments['end_of_line'] : "\n";
- $str = '';
-
- $indent = str_repeat(' ', $offset);
- $noffset = $offset + 1;
-
- switch ($element['type']) {
- case 'value':
- $str .= "$indent".$this->_escapeSpecialChars($element['data'])." $eol";
- break;
- case 'column':
- $str .= "$indent".$this->_escapeSpecialChars($element['data'])." $eol";
- break;
- case 'function':
- $str .= "$indent$eol$indent ".$this->_escapeSpecialChars($element['data']['name'])." $eol";
-
- if (!empty($element['data']['arguments'])
- && is_array($element['data']['arguments'])
- ) {
- foreach ($element['data']['arguments'] as $v) {
- $str .= $this->writeExpression($v, $noffset, $arguments);
- }
- }
-
- $str .= "$indent $eol";
- break;
- case 'expression':
- $str .= "$indent$eol";
- $str .= $this->writeExpression($element['data']['operants'][0], $noffset, $arguments);
- $str .= "$indent ".$element['data']['operator']." $eol";
- $str .= $this->writeExpression($element['data']['operants'][1], $noffset, $arguments);
- $str .= "$indent $eol";
- break;
- }
- return $str;
- }
-
- // }}}
-}
diff --git a/3rdparty/OAuth/LICENSE.TXT b/3rdparty/OAuth/LICENSE.TXT
deleted file mode 100644
index 8891c7ddc9..0000000000
--- a/3rdparty/OAuth/LICENSE.TXT
+++ /dev/null
@@ -1,21 +0,0 @@
-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
deleted file mode 100644
index 64b7007ab9..0000000000
--- a/3rdparty/OAuth/OAuth.php
+++ /dev/null
@@ -1,895 +0,0 @@
-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/3rdparty/OS/Guess.php b/3rdparty/OS/Guess.php
deleted file mode 100644
index d3f2cc764e..0000000000
--- a/3rdparty/OS/Guess.php
+++ /dev/null
@@ -1,338 +0,0 @@
-
- * @author Gregory Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Guess.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since PEAR 0.1
- */
-
-// {{{ uname examples
-
-// php_uname() without args returns the same as 'uname -a', or a PHP-custom
-// string for Windows.
-// PHP versions prior to 4.3 return the uname of the host where PHP was built,
-// as of 4.3 it returns the uname of the host running the PHP code.
-//
-// PC RedHat Linux 7.1:
-// Linux host.example.com 2.4.2-2 #1 Sun Apr 8 20:41:30 EDT 2001 i686 unknown
-//
-// PC Debian Potato:
-// Linux host 2.4.17 #2 SMP Tue Feb 12 15:10:04 CET 2002 i686 unknown
-//
-// PC FreeBSD 3.3:
-// FreeBSD host.example.com 3.3-STABLE FreeBSD 3.3-STABLE #0: Mon Feb 21 00:42:31 CET 2000 root@example.com:/usr/src/sys/compile/CONFIG i386
-//
-// PC FreeBSD 4.3:
-// FreeBSD host.example.com 4.3-RELEASE FreeBSD 4.3-RELEASE #1: Mon Jun 25 11:19:43 EDT 2001 root@example.com:/usr/src/sys/compile/CONFIG i386
-//
-// PC FreeBSD 4.5:
-// FreeBSD host.example.com 4.5-STABLE FreeBSD 4.5-STABLE #0: Wed Feb 6 23:59:23 CET 2002 root@example.com:/usr/src/sys/compile/CONFIG i386
-//
-// PC FreeBSD 4.5 w/uname from GNU shellutils:
-// FreeBSD host.example.com 4.5-STABLE FreeBSD 4.5-STABLE #0: Wed Feb i386 unknown
-//
-// HP 9000/712 HP-UX 10:
-// HP-UX iq B.10.10 A 9000/712 2008429113 two-user license
-//
-// HP 9000/712 HP-UX 10 w/uname from GNU shellutils:
-// HP-UX host B.10.10 A 9000/712 unknown
-//
-// IBM RS6000/550 AIX 4.3:
-// AIX host 3 4 000003531C00
-//
-// AIX 4.3 w/uname from GNU shellutils:
-// AIX host 3 4 000003531C00 unknown
-//
-// SGI Onyx IRIX 6.5 w/uname from GNU shellutils:
-// IRIX64 host 6.5 01091820 IP19 mips
-//
-// SGI Onyx IRIX 6.5:
-// IRIX64 host 6.5 01091820 IP19
-//
-// SparcStation 20 Solaris 8 w/uname from GNU shellutils:
-// SunOS host.example.com 5.8 Generic_108528-12 sun4m sparc
-//
-// SparcStation 20 Solaris 8:
-// SunOS host.example.com 5.8 Generic_108528-12 sun4m sparc SUNW,SPARCstation-20
-//
-// Mac OS X (Darwin)
-// Darwin home-eden.local 7.5.0 Darwin Kernel Version 7.5.0: Thu Aug 5 19:26:16 PDT 2004; root:xnu/xnu-517.7.21.obj~3/RELEASE_PPC Power Macintosh
-//
-// Mac OS X early versions
-//
-
-// }}}
-
-/* TODO:
- * - define endianness, to allow matchSignature("bigend") etc.
- */
-
-/**
- * Retrieves information about the current operating system
- *
- * This class uses php_uname() to grok information about the current OS
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Gregory Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- */
-class OS_Guess
-{
- var $sysname;
- var $nodename;
- var $cpu;
- var $release;
- var $extra;
-
- function OS_Guess($uname = null)
- {
- list($this->sysname,
- $this->release,
- $this->cpu,
- $this->extra,
- $this->nodename) = $this->parseSignature($uname);
- }
-
- function parseSignature($uname = null)
- {
- static $sysmap = array(
- 'HP-UX' => 'hpux',
- 'IRIX64' => 'irix',
- );
- static $cpumap = array(
- 'i586' => 'i386',
- 'i686' => 'i386',
- 'ppc' => 'powerpc',
- );
- if ($uname === null) {
- $uname = php_uname();
- }
- $parts = preg_split('/\s+/', trim($uname));
- $n = count($parts);
-
- $release = $machine = $cpu = '';
- $sysname = $parts[0];
- $nodename = $parts[1];
- $cpu = $parts[$n-1];
- $extra = '';
- if ($cpu == 'unknown') {
- $cpu = $parts[$n - 2];
- }
-
- switch ($sysname) {
- case 'AIX' :
- $release = "$parts[3].$parts[2]";
- break;
- case 'Windows' :
- switch ($parts[1]) {
- case '95/98':
- $release = '9x';
- break;
- default:
- $release = $parts[1];
- break;
- }
- $cpu = 'i386';
- break;
- case 'Linux' :
- $extra = $this->_detectGlibcVersion();
- // use only the first two digits from the kernel version
- $release = preg_replace('/^([0-9]+\.[0-9]+).*/', '\1', $parts[2]);
- break;
- case 'Mac' :
- $sysname = 'darwin';
- $nodename = $parts[2];
- $release = $parts[3];
- if ($cpu == 'Macintosh') {
- if ($parts[$n - 2] == 'Power') {
- $cpu = 'powerpc';
- }
- }
- break;
- case 'Darwin' :
- if ($cpu == 'Macintosh') {
- if ($parts[$n - 2] == 'Power') {
- $cpu = 'powerpc';
- }
- }
- $release = preg_replace('/^([0-9]+\.[0-9]+).*/', '\1', $parts[2]);
- break;
- default:
- $release = preg_replace('/-.*/', '', $parts[2]);
- break;
- }
-
- if (isset($sysmap[$sysname])) {
- $sysname = $sysmap[$sysname];
- } else {
- $sysname = strtolower($sysname);
- }
- if (isset($cpumap[$cpu])) {
- $cpu = $cpumap[$cpu];
- }
- return array($sysname, $release, $cpu, $extra, $nodename);
- }
-
- function _detectGlibcVersion()
- {
- static $glibc = false;
- if ($glibc !== false) {
- return $glibc; // no need to run this multiple times
- }
- $major = $minor = 0;
- include_once "System.php";
- // Use glibc's header file to
- // get major and minor version number:
- if (@file_exists('/usr/include/features.h') &&
- @is_readable('/usr/include/features.h')) {
- if (!@file_exists('/usr/bin/cpp') || !@is_executable('/usr/bin/cpp')) {
- $features_file = fopen('/usr/include/features.h', 'rb');
- while (!feof($features_file)) {
- $line = fgets($features_file, 8192);
- if (!$line || (strpos($line, '#define') === false)) {
- continue;
- }
- if (strpos($line, '__GLIBC__')) {
- // major version number #define __GLIBC__ version
- $line = preg_split('/\s+/', $line);
- $glibc_major = trim($line[2]);
- if (isset($glibc_minor)) {
- break;
- }
- continue;
- }
-
- if (strpos($line, '__GLIBC_MINOR__')) {
- // got the minor version number
- // #define __GLIBC_MINOR__ version
- $line = preg_split('/\s+/', $line);
- $glibc_minor = trim($line[2]);
- if (isset($glibc_major)) {
- break;
- }
- continue;
- }
- }
- fclose($features_file);
- if (!isset($glibc_major) || !isset($glibc_minor)) {
- return $glibc = '';
- }
- return $glibc = 'glibc' . trim($glibc_major) . "." . trim($glibc_minor) ;
- } // no cpp
-
- $tmpfile = System::mktemp("glibctest");
- $fp = fopen($tmpfile, "w");
- fwrite($fp, "#include \n__GLIBC__ __GLIBC_MINOR__\n");
- fclose($fp);
- $cpp = popen("/usr/bin/cpp $tmpfile", "r");
- while ($line = fgets($cpp, 1024)) {
- if ($line{0} == '#' || trim($line) == '') {
- continue;
- }
-
- if (list($major, $minor) = explode(' ', trim($line))) {
- break;
- }
- }
- pclose($cpp);
- unlink($tmpfile);
- } // features.h
-
- if (!($major && $minor) && @is_link('/lib/libc.so.6')) {
- // Let's try reading the libc.so.6 symlink
- if (preg_match('/^libc-(.*)\.so$/', basename(readlink('/lib/libc.so.6')), $matches)) {
- list($major, $minor) = explode('.', $matches[1]);
- }
- }
-
- if (!($major && $minor)) {
- return $glibc = '';
- }
-
- return $glibc = "glibc{$major}.{$minor}";
- }
-
- function getSignature()
- {
- if (empty($this->extra)) {
- return "{$this->sysname}-{$this->release}-{$this->cpu}";
- }
- return "{$this->sysname}-{$this->release}-{$this->cpu}-{$this->extra}";
- }
-
- function getSysname()
- {
- return $this->sysname;
- }
-
- function getNodename()
- {
- return $this->nodename;
- }
-
- function getCpu()
- {
- return $this->cpu;
- }
-
- function getRelease()
- {
- return $this->release;
- }
-
- function getExtra()
- {
- return $this->extra;
- }
-
- function matchSignature($match)
- {
- $fragments = is_array($match) ? $match : explode('-', $match);
- $n = count($fragments);
- $matches = 0;
- if ($n > 0) {
- $matches += $this->_matchFragment($fragments[0], $this->sysname);
- }
- if ($n > 1) {
- $matches += $this->_matchFragment($fragments[1], $this->release);
- }
- if ($n > 2) {
- $matches += $this->_matchFragment($fragments[2], $this->cpu);
- }
- if ($n > 3) {
- $matches += $this->_matchFragment($fragments[3], $this->extra);
- }
- return ($matches == $n);
- }
-
- function _matchFragment($fragment, $value)
- {
- if (strcspn($fragment, '*?') < strlen($fragment)) {
- $reg = '/^' . str_replace(array('*', '?', '/'), array('.*', '.', '\\/'), $fragment) . '\\z/';
- return preg_match($reg, $value);
- }
- return ($fragment == '*' || !strcasecmp($fragment, $value));
- }
-
-}
-/*
- * Local Variables:
- * indent-tabs-mode: nil
- * c-basic-offset: 4
- * End:
- */
\ No newline at end of file
diff --git a/3rdparty/PEAR-LICENSE b/3rdparty/PEAR-LICENSE
deleted file mode 100644
index a00a2421fd..0000000000
--- a/3rdparty/PEAR-LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 1997-2009,
- Stig Bakken ,
- Gregory Beaver ,
- Helgi Þormar Þorbjörnsson ,
- Tomas V.V.Cox ,
- Martin Jansen .
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
- * Redistributions of source code must retain the above copyright notice,
- this list of conditions and the following disclaimer.
- * Redistributions in binary form must reproduce the above copyright
- notice, this list of conditions and the following disclaimer in the
- documentation and/or other materials provided with the distribution.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/3rdparty/PEAR.php b/3rdparty/PEAR.php
deleted file mode 100644
index 501f6a653d..0000000000
--- a/3rdparty/PEAR.php
+++ /dev/null
@@ -1,1063 +0,0 @@
-
- * @author Stig Bakken
- * @author Tomas V.V.Cox
- * @author Greg Beaver
- * @copyright 1997-2010 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: PEAR.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- */
-
-/**#@+
- * ERROR constants
- */
-define('PEAR_ERROR_RETURN', 1);
-define('PEAR_ERROR_PRINT', 2);
-define('PEAR_ERROR_TRIGGER', 4);
-define('PEAR_ERROR_DIE', 8);
-define('PEAR_ERROR_CALLBACK', 16);
-/**
- * WARNING: obsolete
- * @deprecated
- */
-define('PEAR_ERROR_EXCEPTION', 32);
-/**#@-*/
-define('PEAR_ZE2', (function_exists('version_compare') &&
- version_compare(zend_version(), "2-dev", "ge")));
-
-if (substr(PHP_OS, 0, 3) == 'WIN') {
- define('OS_WINDOWS', true);
- define('OS_UNIX', false);
- define('PEAR_OS', 'Windows');
-} else {
- define('OS_WINDOWS', false);
- define('OS_UNIX', true);
- define('PEAR_OS', 'Unix'); // blatant assumption
-}
-
-$GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_RETURN;
-$GLOBALS['_PEAR_default_error_options'] = E_USER_NOTICE;
-$GLOBALS['_PEAR_destructor_object_list'] = array();
-$GLOBALS['_PEAR_shutdown_funcs'] = array();
-$GLOBALS['_PEAR_error_handler_stack'] = array();
-
-@ini_set('track_errors', true);
-
-/**
- * Base class for other PEAR classes. Provides rudimentary
- * emulation of destructors.
- *
- * If you want a destructor in your class, inherit PEAR and make a
- * destructor method called _yourclassname (same name as the
- * constructor, but with a "_" prefix). Also, in your constructor you
- * have to call the PEAR constructor: $this->PEAR();.
- * The destructor method will be called without parameters. Note that
- * at in some SAPI implementations (such as Apache), any output during
- * the request shutdown (in which destructors are called) seems to be
- * discarded. If you need to get any debug information from your
- * destructor, use error_log(), syslog() or something similar.
- *
- * IMPORTANT! To use the emulated destructors you need to create the
- * objects by reference: $obj =& new PEAR_child;
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Tomas V.V. Cox
- * @author Greg Beaver
- * @copyright 1997-2006 The PHP Group
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @see PEAR_Error
- * @since Class available since PHP 4.0.2
- * @link http://pear.php.net/manual/en/core.pear.php#core.pear.pear
- */
-class PEAR
-{
- /**
- * Whether to enable internal debug messages.
- *
- * @var bool
- * @access private
- */
- var $_debug = false;
-
- /**
- * Default error mode for this object.
- *
- * @var int
- * @access private
- */
- var $_default_error_mode = null;
-
- /**
- * Default error options used for this object when error mode
- * is PEAR_ERROR_TRIGGER.
- *
- * @var int
- * @access private
- */
- var $_default_error_options = null;
-
- /**
- * Default error handler (callback) for this object, if error mode is
- * PEAR_ERROR_CALLBACK.
- *
- * @var string
- * @access private
- */
- var $_default_error_handler = '';
-
- /**
- * Which class to use for error objects.
- *
- * @var string
- * @access private
- */
- var $_error_class = 'PEAR_Error';
-
- /**
- * An array of expected errors.
- *
- * @var array
- * @access private
- */
- var $_expected_errors = array();
-
- /**
- * Constructor. Registers this object in
- * $_PEAR_destructor_object_list for destructor emulation if a
- * destructor object exists.
- *
- * @param string $error_class (optional) which class to use for
- * error objects, defaults to PEAR_Error.
- * @access public
- * @return void
- */
- function PEAR($error_class = null)
- {
- $classname = strtolower(get_class($this));
- if ($this->_debug) {
- print "PEAR constructor called, class=$classname\n";
- }
-
- if ($error_class !== null) {
- $this->_error_class = $error_class;
- }
-
- while ($classname && strcasecmp($classname, "pear")) {
- $destructor = "_$classname";
- if (method_exists($this, $destructor)) {
- global $_PEAR_destructor_object_list;
- $_PEAR_destructor_object_list[] = &$this;
- if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
- register_shutdown_function("_PEAR_call_destructors");
- $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
- }
- break;
- } else {
- $classname = get_parent_class($classname);
- }
- }
- }
-
- /**
- * Destructor (the emulated type of...). Does nothing right now,
- * but is included for forward compatibility, so subclass
- * destructors should always call it.
- *
- * See the note in the class desciption about output from
- * destructors.
- *
- * @access public
- * @return void
- */
- function _PEAR() {
- if ($this->_debug) {
- printf("PEAR destructor called, class=%s\n", strtolower(get_class($this)));
- }
- }
-
- /**
- * If you have a class that's mostly/entirely static, and you need static
- * properties, you can use this method to simulate them. Eg. in your method(s)
- * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar');
- * You MUST use a reference, or they will not persist!
- *
- * @access public
- * @param string $class The calling classname, to prevent clashes
- * @param string $var The variable to retrieve.
- * @return mixed A reference to the variable. If not set it will be
- * auto initialised to NULL.
- */
- function &getStaticProperty($class, $var)
- {
- static $properties;
- if (!isset($properties[$class])) {
- $properties[$class] = array();
- }
-
- if (!array_key_exists($var, $properties[$class])) {
- $properties[$class][$var] = null;
- }
-
- return $properties[$class][$var];
- }
-
- /**
- * Use this function to register a shutdown method for static
- * classes.
- *
- * @access public
- * @param mixed $func The function name (or array of class/method) to call
- * @param mixed $args The arguments to pass to the function
- * @return void
- */
- function registerShutdownFunc($func, $args = array())
- {
- // if we are called statically, there is a potential
- // that no shutdown func is registered. Bug #6445
- if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
- register_shutdown_function("_PEAR_call_destructors");
- $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
- }
- $GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args);
- }
-
- /**
- * Tell whether a value is a PEAR error.
- *
- * @param mixed $data the value to test
- * @param int $code if $data is an error object, return true
- * only if $code is a string and
- * $obj->getMessage() == $code or
- * $code is an integer and $obj->getCode() == $code
- * @access public
- * @return bool true if parameter is an error
- */
- static function isError($data, $code = null)
- {
- if (!is_a($data, 'PEAR_Error')) {
- return false;
- }
-
- if (is_null($code)) {
- return true;
- } elseif (is_string($code)) {
- return $data->getMessage() == $code;
- }
-
- return $data->getCode() == $code;
- }
-
- /**
- * Sets how errors generated by this object should be handled.
- * Can be invoked both in objects and statically. If called
- * statically, setErrorHandling sets the default behaviour for all
- * PEAR objects. If called in an object, setErrorHandling sets
- * the default behaviour for that object.
- *
- * @param int $mode
- * One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
- * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
- * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION.
- *
- * @param mixed $options
- * When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
- * of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
- *
- * When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
- * to be the callback function or method. A callback
- * function is a string with the name of the function, a
- * callback method is an array of two elements: the element
- * at index 0 is the object, and the element at index 1 is
- * the name of the method to call in the object.
- *
- * When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
- * a printf format string used when printing the error
- * message.
- *
- * @access public
- * @return void
- * @see PEAR_ERROR_RETURN
- * @see PEAR_ERROR_PRINT
- * @see PEAR_ERROR_TRIGGER
- * @see PEAR_ERROR_DIE
- * @see PEAR_ERROR_CALLBACK
- * @see PEAR_ERROR_EXCEPTION
- *
- * @since PHP 4.0.5
- */
- function setErrorHandling($mode = null, $options = null)
- {
- if (isset($this) && is_a($this, 'PEAR')) {
- $setmode = &$this->_default_error_mode;
- $setoptions = &$this->_default_error_options;
- } else {
- $setmode = &$GLOBALS['_PEAR_default_error_mode'];
- $setoptions = &$GLOBALS['_PEAR_default_error_options'];
- }
-
- switch ($mode) {
- case PEAR_ERROR_EXCEPTION:
- case PEAR_ERROR_RETURN:
- case PEAR_ERROR_PRINT:
- case PEAR_ERROR_TRIGGER:
- case PEAR_ERROR_DIE:
- case null:
- $setmode = $mode;
- $setoptions = $options;
- break;
-
- case PEAR_ERROR_CALLBACK:
- $setmode = $mode;
- // class/object method callback
- if (is_callable($options)) {
- $setoptions = $options;
- } else {
- trigger_error("invalid error callback", E_USER_WARNING);
- }
- break;
-
- default:
- trigger_error("invalid error mode", E_USER_WARNING);
- break;
- }
- }
-
- /**
- * This method is used to tell which errors you expect to get.
- * Expected errors are always returned with error mode
- * PEAR_ERROR_RETURN. Expected error codes are stored in a stack,
- * and this method pushes a new element onto it. The list of
- * expected errors are in effect until they are popped off the
- * stack with the popExpect() method.
- *
- * Note that this method can not be called statically
- *
- * @param mixed $code a single error code or an array of error codes to expect
- *
- * @return int the new depth of the "expected errors" stack
- * @access public
- */
- function expectError($code = '*')
- {
- if (is_array($code)) {
- array_push($this->_expected_errors, $code);
- } else {
- array_push($this->_expected_errors, array($code));
- }
- return count($this->_expected_errors);
- }
-
- /**
- * This method pops one element off the expected error codes
- * stack.
- *
- * @return array the list of error codes that were popped
- */
- function popExpect()
- {
- return array_pop($this->_expected_errors);
- }
-
- /**
- * This method checks unsets an error code if available
- *
- * @param mixed error code
- * @return bool true if the error code was unset, false otherwise
- * @access private
- * @since PHP 4.3.0
- */
- function _checkDelExpect($error_code)
- {
- $deleted = false;
- foreach ($this->_expected_errors as $key => $error_array) {
- if (in_array($error_code, $error_array)) {
- unset($this->_expected_errors[$key][array_search($error_code, $error_array)]);
- $deleted = true;
- }
-
- // clean up empty arrays
- if (0 == count($this->_expected_errors[$key])) {
- unset($this->_expected_errors[$key]);
- }
- }
-
- return $deleted;
- }
-
- /**
- * This method deletes all occurences of the specified element from
- * the expected error codes stack.
- *
- * @param mixed $error_code error code that should be deleted
- * @return mixed list of error codes that were deleted or error
- * @access public
- * @since PHP 4.3.0
- */
- function delExpect($error_code)
- {
- $deleted = false;
- if ((is_array($error_code) && (0 != count($error_code)))) {
- // $error_code is a non-empty array here; we walk through it trying
- // to unset all values
- foreach ($error_code as $key => $error) {
- $deleted = $this->_checkDelExpect($error) ? true : false;
- }
-
- return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
- } elseif (!empty($error_code)) {
- // $error_code comes alone, trying to unset it
- if ($this->_checkDelExpect($error_code)) {
- return true;
- }
-
- return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
- }
-
- // $error_code is empty
- return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME
- }
-
- /**
- * This method is a wrapper that returns an instance of the
- * configured error class with this object's default error
- * handling applied. If the $mode and $options parameters are not
- * specified, the object's defaults are used.
- *
- * @param mixed $message a text error message or a PEAR error object
- *
- * @param int $code a numeric error code (it is up to your class
- * to define these if you want to use codes)
- *
- * @param int $mode One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
- * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
- * PEAR_ERROR_CALLBACK, PEAR_ERROR_EXCEPTION.
- *
- * @param mixed $options If $mode is PEAR_ERROR_TRIGGER, this parameter
- * specifies the PHP-internal error level (one of
- * E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
- * If $mode is PEAR_ERROR_CALLBACK, this
- * parameter specifies the callback function or
- * method. In other error modes this parameter
- * is ignored.
- *
- * @param string $userinfo If you need to pass along for example debug
- * information, this parameter is meant for that.
- *
- * @param string $error_class The returned error object will be
- * instantiated from this class, if specified.
- *
- * @param bool $skipmsg If true, raiseError will only pass error codes,
- * the error message parameter will be dropped.
- *
- * @access public
- * @return object a PEAR error object
- * @see PEAR::setErrorHandling
- * @since PHP 4.0.5
- */
- static function &raiseError($message = null,
- $code = null,
- $mode = null,
- $options = null,
- $userinfo = null,
- $error_class = null,
- $skipmsg = false)
- {
- // The error is yet a PEAR error object
- if (is_object($message)) {
- $code = $message->getCode();
- $userinfo = $message->getUserInfo();
- $error_class = $message->getType();
- $message->error_message_prefix = '';
- $message = $message->getMessage();
- }
-
- if (
- isset($this) &&
- isset($this->_expected_errors) &&
- count($this->_expected_errors) > 0 &&
- count($exp = end($this->_expected_errors))
- ) {
- if ($exp[0] == "*" ||
- (is_int(reset($exp)) && in_array($code, $exp)) ||
- (is_string(reset($exp)) && in_array($message, $exp))
- ) {
- $mode = PEAR_ERROR_RETURN;
- }
- }
-
- // No mode given, try global ones
- if ($mode === null) {
- // Class error handler
- if (isset($this) && isset($this->_default_error_mode)) {
- $mode = $this->_default_error_mode;
- $options = $this->_default_error_options;
- // Global error handler
- } elseif (isset($GLOBALS['_PEAR_default_error_mode'])) {
- $mode = $GLOBALS['_PEAR_default_error_mode'];
- $options = $GLOBALS['_PEAR_default_error_options'];
- }
- }
-
- if ($error_class !== null) {
- $ec = $error_class;
- } elseif (isset($this) && isset($this->_error_class)) {
- $ec = $this->_error_class;
- } else {
- $ec = 'PEAR_Error';
- }
-
- if (intval(PHP_VERSION) < 5) {
- // little non-eval hack to fix bug #12147
- include 'PEAR/FixPHP5PEARWarnings.php';
- return $a;
- }
-
- if ($skipmsg) {
- $a = new $ec($code, $mode, $options, $userinfo);
- } else {
- $a = new $ec($message, $code, $mode, $options, $userinfo);
- }
-
- return $a;
- }
-
- /**
- * Simpler form of raiseError with fewer options. In most cases
- * message, code and userinfo are enough.
- *
- * @param mixed $message a text error message or a PEAR error object
- *
- * @param int $code a numeric error code (it is up to your class
- * to define these if you want to use codes)
- *
- * @param string $userinfo If you need to pass along for example debug
- * information, this parameter is meant for that.
- *
- * @access public
- * @return object a PEAR error object
- * @see PEAR::raiseError
- */
- function &throwError($message = null, $code = null, $userinfo = null)
- {
- if (isset($this) && is_a($this, 'PEAR')) {
- $a = $this->raiseError($message, $code, null, null, $userinfo);
- return $a;
- }
-
- $a = PEAR::raiseError($message, $code, null, null, $userinfo);
- return $a;
- }
-
- function staticPushErrorHandling($mode, $options = null)
- {
- $stack = &$GLOBALS['_PEAR_error_handler_stack'];
- $def_mode = &$GLOBALS['_PEAR_default_error_mode'];
- $def_options = &$GLOBALS['_PEAR_default_error_options'];
- $stack[] = array($def_mode, $def_options);
- switch ($mode) {
- case PEAR_ERROR_EXCEPTION:
- case PEAR_ERROR_RETURN:
- case PEAR_ERROR_PRINT:
- case PEAR_ERROR_TRIGGER:
- case PEAR_ERROR_DIE:
- case null:
- $def_mode = $mode;
- $def_options = $options;
- break;
-
- case PEAR_ERROR_CALLBACK:
- $def_mode = $mode;
- // class/object method callback
- if (is_callable($options)) {
- $def_options = $options;
- } else {
- trigger_error("invalid error callback", E_USER_WARNING);
- }
- break;
-
- default:
- trigger_error("invalid error mode", E_USER_WARNING);
- break;
- }
- $stack[] = array($mode, $options);
- return true;
- }
-
- function staticPopErrorHandling()
- {
- $stack = &$GLOBALS['_PEAR_error_handler_stack'];
- $setmode = &$GLOBALS['_PEAR_default_error_mode'];
- $setoptions = &$GLOBALS['_PEAR_default_error_options'];
- array_pop($stack);
- list($mode, $options) = $stack[sizeof($stack) - 1];
- array_pop($stack);
- switch ($mode) {
- case PEAR_ERROR_EXCEPTION:
- case PEAR_ERROR_RETURN:
- case PEAR_ERROR_PRINT:
- case PEAR_ERROR_TRIGGER:
- case PEAR_ERROR_DIE:
- case null:
- $setmode = $mode;
- $setoptions = $options;
- break;
-
- case PEAR_ERROR_CALLBACK:
- $setmode = $mode;
- // class/object method callback
- if (is_callable($options)) {
- $setoptions = $options;
- } else {
- trigger_error("invalid error callback", E_USER_WARNING);
- }
- break;
-
- default:
- trigger_error("invalid error mode", E_USER_WARNING);
- break;
- }
- return true;
- }
-
- /**
- * Push a new error handler on top of the error handler options stack. With this
- * you can easily override the actual error handler for some code and restore
- * it later with popErrorHandling.
- *
- * @param mixed $mode (same as setErrorHandling)
- * @param mixed $options (same as setErrorHandling)
- *
- * @return bool Always true
- *
- * @see PEAR::setErrorHandling
- */
- function pushErrorHandling($mode, $options = null)
- {
- $stack = &$GLOBALS['_PEAR_error_handler_stack'];
- if (isset($this) && is_a($this, 'PEAR')) {
- $def_mode = &$this->_default_error_mode;
- $def_options = &$this->_default_error_options;
- } else {
- $def_mode = &$GLOBALS['_PEAR_default_error_mode'];
- $def_options = &$GLOBALS['_PEAR_default_error_options'];
- }
- $stack[] = array($def_mode, $def_options);
-
- if (isset($this) && is_a($this, 'PEAR')) {
- $this->setErrorHandling($mode, $options);
- } else {
- PEAR::setErrorHandling($mode, $options);
- }
- $stack[] = array($mode, $options);
- return true;
- }
-
- /**
- * Pop the last error handler used
- *
- * @return bool Always true
- *
- * @see PEAR::pushErrorHandling
- */
- function popErrorHandling()
- {
- $stack = &$GLOBALS['_PEAR_error_handler_stack'];
- array_pop($stack);
- list($mode, $options) = $stack[sizeof($stack) - 1];
- array_pop($stack);
- if (isset($this) && is_a($this, 'PEAR')) {
- $this->setErrorHandling($mode, $options);
- } else {
- PEAR::setErrorHandling($mode, $options);
- }
- return true;
- }
-
- /**
- * OS independant PHP extension load. Remember to take care
- * on the correct extension name for case sensitive OSes.
- *
- * @param string $ext The extension name
- * @return bool Success or not on the dl() call
- */
- static function loadExtension($ext)
- {
- if (extension_loaded($ext)) {
- return true;
- }
-
- // if either returns true dl() will produce a FATAL error, stop that
- if (
- function_exists('dl') === false ||
- ini_get('enable_dl') != 1 ||
- ini_get('safe_mode') == 1
- ) {
- return false;
- }
-
- if (OS_WINDOWS) {
- $suffix = '.dll';
- } elseif (PHP_OS == 'HP-UX') {
- $suffix = '.sl';
- } elseif (PHP_OS == 'AIX') {
- $suffix = '.a';
- } elseif (PHP_OS == 'OSX') {
- $suffix = '.bundle';
- } else {
- $suffix = '.so';
- }
-
- return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
- }
-}
-
-if (PEAR_ZE2) {
- include_once 'PEAR5.php';
-}
-
-function _PEAR_call_destructors()
-{
- global $_PEAR_destructor_object_list;
- if (is_array($_PEAR_destructor_object_list) &&
- sizeof($_PEAR_destructor_object_list))
- {
- reset($_PEAR_destructor_object_list);
- if (PEAR_ZE2) {
- $destructLifoExists = PEAR5::getStaticProperty('PEAR', 'destructlifo');
- } else {
- $destructLifoExists = PEAR::getStaticProperty('PEAR', 'destructlifo');
- }
-
- if ($destructLifoExists) {
- $_PEAR_destructor_object_list = array_reverse($_PEAR_destructor_object_list);
- }
-
- while (list($k, $objref) = each($_PEAR_destructor_object_list)) {
- $classname = get_class($objref);
- while ($classname) {
- $destructor = "_$classname";
- if (method_exists($objref, $destructor)) {
- $objref->$destructor();
- break;
- } else {
- $classname = get_parent_class($classname);
- }
- }
- }
- // Empty the object list to ensure that destructors are
- // not called more than once.
- $_PEAR_destructor_object_list = array();
- }
-
- // Now call the shutdown functions
- if (
- isset($GLOBALS['_PEAR_shutdown_funcs']) &&
- is_array($GLOBALS['_PEAR_shutdown_funcs']) &&
- !empty($GLOBALS['_PEAR_shutdown_funcs'])
- ) {
- foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) {
- call_user_func_array($value[0], $value[1]);
- }
- }
-}
-
-/**
- * Standard PEAR error class for PHP 4
- *
- * This class is supserseded by {@link PEAR_Exception} in PHP 5
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Tomas V.V. Cox
- * @author Gregory Beaver
- * @copyright 1997-2006 The PHP Group
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/manual/en/core.pear.pear-error.php
- * @see PEAR::raiseError(), PEAR::throwError()
- * @since Class available since PHP 4.0.2
- */
-class PEAR_Error
-{
- var $error_message_prefix = '';
- var $mode = PEAR_ERROR_RETURN;
- var $level = E_USER_NOTICE;
- var $code = -1;
- var $message = '';
- var $userinfo = '';
- var $backtrace = null;
-
- /**
- * PEAR_Error constructor
- *
- * @param string $message message
- *
- * @param int $code (optional) error code
- *
- * @param int $mode (optional) error mode, one of: PEAR_ERROR_RETURN,
- * PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER,
- * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION
- *
- * @param mixed $options (optional) error level, _OR_ in the case of
- * PEAR_ERROR_CALLBACK, the callback function or object/method
- * tuple.
- *
- * @param string $userinfo (optional) additional user/debug info
- *
- * @access public
- *
- */
- function PEAR_Error($message = 'unknown error', $code = null,
- $mode = null, $options = null, $userinfo = null)
- {
- if ($mode === null) {
- $mode = PEAR_ERROR_RETURN;
- }
- $this->message = $message;
- $this->code = $code;
- $this->mode = $mode;
- $this->userinfo = $userinfo;
-
- if (PEAR_ZE2) {
- $skiptrace = PEAR5::getStaticProperty('PEAR_Error', 'skiptrace');
- } else {
- $skiptrace = PEAR::getStaticProperty('PEAR_Error', 'skiptrace');
- }
-
- if (!$skiptrace) {
- $this->backtrace = debug_backtrace();
- if (isset($this->backtrace[0]) && isset($this->backtrace[0]['object'])) {
- unset($this->backtrace[0]['object']);
- }
- }
-
- if ($mode & PEAR_ERROR_CALLBACK) {
- $this->level = E_USER_NOTICE;
- $this->callback = $options;
- } else {
- if ($options === null) {
- $options = E_USER_NOTICE;
- }
-
- $this->level = $options;
- $this->callback = null;
- }
-
- if ($this->mode & PEAR_ERROR_PRINT) {
- if (is_null($options) || is_int($options)) {
- $format = "%s";
- } else {
- $format = $options;
- }
-
- printf($format, $this->getMessage());
- }
-
- if ($this->mode & PEAR_ERROR_TRIGGER) {
- trigger_error($this->getMessage(), $this->level);
- }
-
- if ($this->mode & PEAR_ERROR_DIE) {
- $msg = $this->getMessage();
- if (is_null($options) || is_int($options)) {
- $format = "%s";
- if (substr($msg, -1) != "\n") {
- $msg .= "\n";
- }
- } else {
- $format = $options;
- }
- die(sprintf($format, $msg));
- }
-
- if ($this->mode & PEAR_ERROR_CALLBACK && is_callable($this->callback)) {
- call_user_func($this->callback, $this);
- }
-
- if ($this->mode & PEAR_ERROR_EXCEPTION) {
- trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_Exception for exceptions", E_USER_WARNING);
- eval('$e = new Exception($this->message, $this->code);throw($e);');
- }
- }
-
- /**
- * Get the error mode from an error object.
- *
- * @return int error mode
- * @access public
- */
- function getMode()
- {
- return $this->mode;
- }
-
- /**
- * Get the callback function/method from an error object.
- *
- * @return mixed callback function or object/method array
- * @access public
- */
- function getCallback()
- {
- return $this->callback;
- }
-
- /**
- * Get the error message from an error object.
- *
- * @return string full error message
- * @access public
- */
- function getMessage()
- {
- return ($this->error_message_prefix . $this->message);
- }
-
- /**
- * Get error code from an error object
- *
- * @return int error code
- * @access public
- */
- function getCode()
- {
- return $this->code;
- }
-
- /**
- * Get the name of this error/exception.
- *
- * @return string error/exception name (type)
- * @access public
- */
- function getType()
- {
- return get_class($this);
- }
-
- /**
- * Get additional user-supplied information.
- *
- * @return string user-supplied information
- * @access public
- */
- function getUserInfo()
- {
- return $this->userinfo;
- }
-
- /**
- * Get additional debug information supplied by the application.
- *
- * @return string debug information
- * @access public
- */
- function getDebugInfo()
- {
- return $this->getUserInfo();
- }
-
- /**
- * Get the call backtrace from where the error was generated.
- * Supported with PHP 4.3.0 or newer.
- *
- * @param int $frame (optional) what frame to fetch
- * @return array Backtrace, or NULL if not available.
- * @access public
- */
- function getBacktrace($frame = null)
- {
- if (defined('PEAR_IGNORE_BACKTRACE')) {
- return null;
- }
- if ($frame === null) {
- return $this->backtrace;
- }
- return $this->backtrace[$frame];
- }
-
- function addUserInfo($info)
- {
- if (empty($this->userinfo)) {
- $this->userinfo = $info;
- } else {
- $this->userinfo .= " ** $info";
- }
- }
-
- function __toString()
- {
- return $this->getMessage();
- }
-
- /**
- * Make a string representation of this object.
- *
- * @return string a string with an object summary
- * @access public
- */
- function toString()
- {
- $modes = array();
- $levels = array(E_USER_NOTICE => 'notice',
- E_USER_WARNING => 'warning',
- E_USER_ERROR => 'error');
- if ($this->mode & PEAR_ERROR_CALLBACK) {
- if (is_array($this->callback)) {
- $callback = (is_object($this->callback[0]) ?
- strtolower(get_class($this->callback[0])) :
- $this->callback[0]) . '::' .
- $this->callback[1];
- } else {
- $callback = $this->callback;
- }
- return sprintf('[%s: message="%s" code=%d mode=callback '.
- 'callback=%s prefix="%s" info="%s"]',
- strtolower(get_class($this)), $this->message, $this->code,
- $callback, $this->error_message_prefix,
- $this->userinfo);
- }
- if ($this->mode & PEAR_ERROR_PRINT) {
- $modes[] = 'print';
- }
- if ($this->mode & PEAR_ERROR_TRIGGER) {
- $modes[] = 'trigger';
- }
- if ($this->mode & PEAR_ERROR_DIE) {
- $modes[] = 'die';
- }
- if ($this->mode & PEAR_ERROR_RETURN) {
- $modes[] = 'return';
- }
- return sprintf('[%s: message="%s" code=%d mode=%s level=%s '.
- 'prefix="%s" info="%s"]',
- strtolower(get_class($this)), $this->message, $this->code,
- implode("|", $modes), $levels[$this->level],
- $this->error_message_prefix,
- $this->userinfo);
- }
-}
-
-/*
- * Local Variables:
- * mode: php
- * tab-width: 4
- * c-basic-offset: 4
- * End:
- */
diff --git a/3rdparty/PEAR/Autoloader.php b/3rdparty/PEAR/Autoloader.php
deleted file mode 100644
index 51620c7085..0000000000
--- a/3rdparty/PEAR/Autoloader.php
+++ /dev/null
@@ -1,218 +0,0 @@
-
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Autoloader.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/manual/en/core.ppm.php#core.ppm.pear-autoloader
- * @since File available since Release 0.1
- * @deprecated File deprecated in Release 1.4.0a1
- */
-
-// /* vim: set expandtab tabstop=4 shiftwidth=4: */
-
-if (!extension_loaded("overload")) {
- // die hard without ext/overload
- die("Rebuild PHP with the `overload' extension to use PEAR_Autoloader");
-}
-
-/**
- * Include for PEAR_Error and PEAR classes
- */
-require_once "PEAR.php";
-
-/**
- * This class is for objects where you want to separate the code for
- * some methods into separate classes. This is useful if you have a
- * class with not-frequently-used methods that contain lots of code
- * that you would like to avoid always parsing.
- *
- * The PEAR_Autoloader class provides autoloading and aggregation.
- * The autoloading lets you set up in which classes the separated
- * methods are found. Aggregation is the technique used to import new
- * methods, an instance of each class providing separated methods is
- * stored and called every time the aggregated method is called.
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/manual/en/core.ppm.php#core.ppm.pear-autoloader
- * @since File available since Release 0.1
- * @deprecated File deprecated in Release 1.4.0a1
- */
-class PEAR_Autoloader extends PEAR
-{
- // {{{ properties
-
- /**
- * Map of methods and classes where they are defined
- *
- * @var array
- *
- * @access private
- */
- var $_autoload_map = array();
-
- /**
- * Map of methods and aggregate objects
- *
- * @var array
- *
- * @access private
- */
- var $_method_map = array();
-
- // }}}
- // {{{ addAutoload()
-
- /**
- * Add one or more autoload entries.
- *
- * @param string $method which method to autoload
- *
- * @param string $classname (optional) which class to find the method in.
- * If the $method parameter is an array, this
- * parameter may be omitted (and will be ignored
- * if not), and the $method parameter will be
- * treated as an associative array with method
- * names as keys and class names as values.
- *
- * @return void
- *
- * @access public
- */
- function addAutoload($method, $classname = null)
- {
- if (is_array($method)) {
- array_walk($method, create_function('$a,&$b', '$b = strtolower($b);'));
- $this->_autoload_map = array_merge($this->_autoload_map, $method);
- } else {
- $this->_autoload_map[strtolower($method)] = $classname;
- }
- }
-
- // }}}
- // {{{ removeAutoload()
-
- /**
- * Remove an autoload entry.
- *
- * @param string $method which method to remove the autoload entry for
- *
- * @return bool TRUE if an entry was removed, FALSE if not
- *
- * @access public
- */
- function removeAutoload($method)
- {
- $method = strtolower($method);
- $ok = isset($this->_autoload_map[$method]);
- unset($this->_autoload_map[$method]);
- return $ok;
- }
-
- // }}}
- // {{{ addAggregateObject()
-
- /**
- * Add an aggregate object to this object. If the specified class
- * is not defined, loading it will be attempted following PEAR's
- * file naming scheme. All the methods in the class will be
- * aggregated, except private ones (name starting with an
- * underscore) and constructors.
- *
- * @param string $classname what class to instantiate for the object.
- *
- * @return void
- *
- * @access public
- */
- function addAggregateObject($classname)
- {
- $classname = strtolower($classname);
- if (!class_exists($classname)) {
- $include_file = preg_replace('/[^a-z0-9]/i', '_', $classname);
- include_once $include_file;
- }
- $obj = new $classname;
- $methods = get_class_methods($classname);
- foreach ($methods as $method) {
- // don't import priviate methods and constructors
- if ($method{0} != '_' && $method != $classname) {
- $this->_method_map[$method] = $obj;
- }
- }
- }
-
- // }}}
- // {{{ removeAggregateObject()
-
- /**
- * Remove an aggregate object.
- *
- * @param string $classname the class of the object to remove
- *
- * @return bool TRUE if an object was removed, FALSE if not
- *
- * @access public
- */
- function removeAggregateObject($classname)
- {
- $ok = false;
- $classname = strtolower($classname);
- reset($this->_method_map);
- while (list($method, $obj) = each($this->_method_map)) {
- if (is_a($obj, $classname)) {
- unset($this->_method_map[$method]);
- $ok = true;
- }
- }
- return $ok;
- }
-
- // }}}
- // {{{ __call()
-
- /**
- * Overloaded object call handler, called each time an
- * undefined/aggregated method is invoked. This method repeats
- * the call in the right aggregate object and passes on the return
- * value.
- *
- * @param string $method which method that was called
- *
- * @param string $args An array of the parameters passed in the
- * original call
- *
- * @return mixed The return value from the aggregated method, or a PEAR
- * error if the called method was unknown.
- */
- function __call($method, $args, &$retval)
- {
- $method = strtolower($method);
- if (empty($this->_method_map[$method]) && isset($this->_autoload_map[$method])) {
- $this->addAggregateObject($this->_autoload_map[$method]);
- }
- if (isset($this->_method_map[$method])) {
- $retval = call_user_func_array(array($this->_method_map[$method], $method), $args);
- return true;
- }
- return false;
- }
-
- // }}}
-}
-
-overload("PEAR_Autoloader");
-
-?>
diff --git a/3rdparty/PEAR/Builder.php b/3rdparty/PEAR/Builder.php
deleted file mode 100644
index 90f3a14555..0000000000
--- a/3rdparty/PEAR/Builder.php
+++ /dev/null
@@ -1,489 +0,0 @@
-
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Builder.php 313024 2011-07-06 19:51:24Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- *
- * TODO: log output parameters in PECL command line
- * TODO: msdev path in configuration
- */
-
-/**
- * Needed for extending PEAR_Builder
- */
-require_once 'PEAR/Common.php';
-require_once 'PEAR/PackageFile.php';
-
-/**
- * Class to handle building (compiling) extensions.
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since PHP 4.0.2
- * @see http://pear.php.net/manual/en/core.ppm.pear-builder.php
- */
-class PEAR_Builder extends PEAR_Common
-{
- var $php_api_version = 0;
- var $zend_module_api_no = 0;
- var $zend_extension_api_no = 0;
-
- var $extensions_built = array();
-
- /**
- * @var string Used for reporting when it is not possible to pass function
- * via extra parameter, e.g. log, msdevCallback
- */
- var $current_callback = null;
-
- // used for msdev builds
- var $_lastline = null;
- var $_firstline = null;
-
- /**
- * PEAR_Builder constructor.
- *
- * @param object $ui user interface object (instance of PEAR_Frontend_*)
- *
- * @access public
- */
- function PEAR_Builder(&$ui)
- {
- parent::PEAR_Common();
- $this->setFrontendObject($ui);
- }
-
- /**
- * Build an extension from source on windows.
- * requires msdev
- */
- function _build_win32($descfile, $callback = null)
- {
- if (is_object($descfile)) {
- $pkg = $descfile;
- $descfile = $pkg->getPackageFile();
- } else {
- $pf = &new PEAR_PackageFile($this->config, $this->debug);
- $pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
- if (PEAR::isError($pkg)) {
- return $pkg;
- }
- }
- $dir = dirname($descfile);
- $old_cwd = getcwd();
-
- if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) {
- return $this->raiseError("could not chdir to $dir");
- }
-
- // packages that were in a .tar have the packagefile in this directory
- $vdir = $pkg->getPackage() . '-' . $pkg->getVersion();
- if (file_exists($dir) && is_dir($vdir)) {
- if (!chdir($vdir)) {
- return $this->raiseError("could not chdir to " . realpath($vdir));
- }
-
- $dir = getcwd();
- }
-
- $this->log(2, "building in $dir");
-
- $dsp = $pkg->getPackage().'.dsp';
- if (!file_exists("$dir/$dsp")) {
- return $this->raiseError("The DSP $dsp does not exist.");
- }
- // XXX TODO: make release build type configurable
- $command = 'msdev '.$dsp.' /MAKE "'.$pkg->getPackage(). ' - Release"';
-
- $err = $this->_runCommand($command, array(&$this, 'msdevCallback'));
- if (PEAR::isError($err)) {
- return $err;
- }
-
- // figure out the build platform and type
- $platform = 'Win32';
- $buildtype = 'Release';
- if (preg_match('/.*?'.$pkg->getPackage().'\s-\s(\w+)\s(.*?)-+/i',$this->_firstline,$matches)) {
- $platform = $matches[1];
- $buildtype = $matches[2];
- }
-
- if (preg_match('/(.*)?\s-\s(\d+).*?(\d+)/', $this->_lastline, $matches)) {
- if ($matches[2]) {
- // there were errors in the build
- return $this->raiseError("There were errors during compilation.");
- }
- $out = $matches[1];
- } else {
- return $this->raiseError("Did not understand the completion status returned from msdev.exe.");
- }
-
- // msdev doesn't tell us the output directory :/
- // open the dsp, find /out and use that directory
- $dsptext = join(file($dsp),'');
-
- // this regex depends on the build platform and type having been
- // correctly identified above.
- $regex ='/.*?!IF\s+"\$\(CFG\)"\s+==\s+("'.
- $pkg->getPackage().'\s-\s'.
- $platform.'\s'.
- $buildtype.'").*?'.
- '\/out:"(.*?)"/is';
-
- if ($dsptext && preg_match($regex, $dsptext, $matches)) {
- // what we get back is a relative path to the output file itself.
- $outfile = realpath($matches[2]);
- } else {
- return $this->raiseError("Could not retrieve output information from $dsp.");
- }
- // realpath returns false if the file doesn't exist
- if ($outfile && copy($outfile, "$dir/$out")) {
- $outfile = "$dir/$out";
- }
-
- $built_files[] = array(
- 'file' => "$outfile",
- 'php_api' => $this->php_api_version,
- 'zend_mod_api' => $this->zend_module_api_no,
- 'zend_ext_api' => $this->zend_extension_api_no,
- );
-
- return $built_files;
- }
- // }}}
-
- // {{{ msdevCallback()
- function msdevCallback($what, $data)
- {
- if (!$this->_firstline)
- $this->_firstline = $data;
- $this->_lastline = $data;
- call_user_func($this->current_callback, $what, $data);
- }
-
- /**
- * @param string
- * @param string
- * @param array
- * @access private
- */
- function _harvestInstDir($dest_prefix, $dirname, &$built_files)
- {
- $d = opendir($dirname);
- if (!$d)
- return false;
-
- $ret = true;
- while (($ent = readdir($d)) !== false) {
- if ($ent{0} == '.')
- continue;
-
- $full = $dirname . DIRECTORY_SEPARATOR . $ent;
- if (is_dir($full)) {
- if (!$this->_harvestInstDir(
- $dest_prefix . DIRECTORY_SEPARATOR . $ent,
- $full, $built_files)) {
- $ret = false;
- break;
- }
- } else {
- $dest = $dest_prefix . DIRECTORY_SEPARATOR . $ent;
- $built_files[] = array(
- 'file' => $full,
- 'dest' => $dest,
- 'php_api' => $this->php_api_version,
- 'zend_mod_api' => $this->zend_module_api_no,
- 'zend_ext_api' => $this->zend_extension_api_no,
- );
- }
- }
- closedir($d);
- return $ret;
- }
-
- /**
- * Build an extension from source. Runs "phpize" in the source
- * directory, but compiles in a temporary directory
- * (TMPDIR/pear-build-USER/PACKAGE-VERSION).
- *
- * @param string|PEAR_PackageFile_v* $descfile path to XML package description file, or
- * a PEAR_PackageFile object
- *
- * @param mixed $callback callback function used to report output,
- * see PEAR_Builder::_runCommand for details
- *
- * @return array an array of associative arrays with built files,
- * format:
- * array( array( 'file' => '/path/to/ext.so',
- * 'php_api' => YYYYMMDD,
- * 'zend_mod_api' => YYYYMMDD,
- * 'zend_ext_api' => YYYYMMDD ),
- * ... )
- *
- * @access public
- *
- * @see PEAR_Builder::_runCommand
- */
- function build($descfile, $callback = null)
- {
- if (preg_match('/(\\/|\\\\|^)([^\\/\\\\]+)?php(.+)?$/',
- $this->config->get('php_bin'), $matches)) {
- if (isset($matches[2]) && strlen($matches[2]) &&
- trim($matches[2]) != trim($this->config->get('php_prefix'))) {
- $this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') .
- ' appears to have a prefix ' . $matches[2] . ', but' .
- ' config variable php_prefix does not match');
- }
-
- if (isset($matches[3]) && strlen($matches[3]) &&
- trim($matches[3]) != trim($this->config->get('php_suffix'))) {
- $this->log(0, 'WARNING: php_bin ' . $this->config->get('php_bin') .
- ' appears to have a suffix ' . $matches[3] . ', but' .
- ' config variable php_suffix does not match');
- }
- }
-
- $this->current_callback = $callback;
- if (PEAR_OS == "Windows") {
- return $this->_build_win32($descfile, $callback);
- }
-
- if (PEAR_OS != 'Unix') {
- return $this->raiseError("building extensions not supported on this platform");
- }
-
- if (is_object($descfile)) {
- $pkg = $descfile;
- $descfile = $pkg->getPackageFile();
- if (is_a($pkg, 'PEAR_PackageFile_v1')) {
- $dir = dirname($descfile);
- } else {
- $dir = $pkg->_config->get('temp_dir') . '/' . $pkg->getName();
- // automatically delete at session end
- $this->addTempFile($dir);
- }
- } else {
- $pf = &new PEAR_PackageFile($this->config);
- $pkg = &$pf->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
- if (PEAR::isError($pkg)) {
- return $pkg;
- }
- $dir = dirname($descfile);
- }
-
- // Find config. outside of normal path - e.g. config.m4
- foreach (array_keys($pkg->getInstallationFileList()) as $item) {
- if (stristr(basename($item), 'config.m4') && dirname($item) != '.') {
- $dir .= DIRECTORY_SEPARATOR . dirname($item);
- break;
- }
- }
-
- $old_cwd = getcwd();
- if (!file_exists($dir) || !is_dir($dir) || !chdir($dir)) {
- return $this->raiseError("could not chdir to $dir");
- }
-
- $vdir = $pkg->getPackage() . '-' . $pkg->getVersion();
- if (is_dir($vdir)) {
- chdir($vdir);
- }
-
- $dir = getcwd();
- $this->log(2, "building in $dir");
- putenv('PATH=' . $this->config->get('bin_dir') . ':' . getenv('PATH'));
- $err = $this->_runCommand($this->config->get('php_prefix')
- . "phpize" .
- $this->config->get('php_suffix'),
- array(&$this, 'phpizeCallback'));
- if (PEAR::isError($err)) {
- return $err;
- }
-
- if (!$err) {
- return $this->raiseError("`phpize' failed");
- }
-
- // {{{ start of interactive part
- $configure_command = "$dir/configure";
- $configure_options = $pkg->getConfigureOptions();
- if ($configure_options) {
- foreach ($configure_options as $o) {
- $default = array_key_exists('default', $o) ? $o['default'] : null;
- list($r) = $this->ui->userDialog('build',
- array($o['prompt']),
- array('text'),
- array($default));
- if (substr($o['name'], 0, 5) == 'with-' &&
- ($r == 'yes' || $r == 'autodetect')) {
- $configure_command .= " --$o[name]";
- } else {
- $configure_command .= " --$o[name]=".trim($r);
- }
- }
- }
- // }}} end of interactive part
-
- // FIXME make configurable
- if (!$user=getenv('USER')) {
- $user='defaultuser';
- }
-
- $tmpdir = $this->config->get('temp_dir');
- $build_basedir = System::mktemp(' -t "' . $tmpdir . '" -d "pear-build-' . $user . '"');
- $build_dir = "$build_basedir/$vdir";
- $inst_dir = "$build_basedir/install-$vdir";
- $this->log(1, "building in $build_dir");
- if (is_dir($build_dir)) {
- System::rm(array('-rf', $build_dir));
- }
-
- if (!System::mkDir(array('-p', $build_dir))) {
- return $this->raiseError("could not create build dir: $build_dir");
- }
-
- $this->addTempFile($build_dir);
- if (!System::mkDir(array('-p', $inst_dir))) {
- return $this->raiseError("could not create temporary install dir: $inst_dir");
- }
- $this->addTempFile($inst_dir);
-
- $make_command = getenv('MAKE') ? getenv('MAKE') : 'make';
-
- $to_run = array(
- $configure_command,
- $make_command,
- "$make_command INSTALL_ROOT=\"$inst_dir\" install",
- "find \"$inst_dir\" | xargs ls -dils"
- );
- if (!file_exists($build_dir) || !is_dir($build_dir) || !chdir($build_dir)) {
- return $this->raiseError("could not chdir to $build_dir");
- }
- putenv('PHP_PEAR_VERSION=1.9.4');
- foreach ($to_run as $cmd) {
- $err = $this->_runCommand($cmd, $callback);
- if (PEAR::isError($err)) {
- chdir($old_cwd);
- return $err;
- }
- if (!$err) {
- chdir($old_cwd);
- return $this->raiseError("`$cmd' failed");
- }
- }
- if (!($dp = opendir("modules"))) {
- chdir($old_cwd);
- return $this->raiseError("no `modules' directory found");
- }
- $built_files = array();
- $prefix = exec($this->config->get('php_prefix')
- . "php-config" .
- $this->config->get('php_suffix') . " --prefix");
- $this->_harvestInstDir($prefix, $inst_dir . DIRECTORY_SEPARATOR . $prefix, $built_files);
- chdir($old_cwd);
- return $built_files;
- }
-
- /**
- * Message callback function used when running the "phpize"
- * program. Extracts the API numbers used. Ignores other message
- * types than "cmdoutput".
- *
- * @param string $what the type of message
- * @param mixed $data the message
- *
- * @return void
- *
- * @access public
- */
- function phpizeCallback($what, $data)
- {
- if ($what != 'cmdoutput') {
- return;
- }
- $this->log(1, rtrim($data));
- if (preg_match('/You should update your .aclocal.m4/', $data)) {
- return;
- }
- $matches = array();
- if (preg_match('/^\s+(\S[^:]+):\s+(\d{8})/', $data, $matches)) {
- $member = preg_replace('/[^a-z]/', '_', strtolower($matches[1]));
- $apino = (int)$matches[2];
- if (isset($this->$member)) {
- $this->$member = $apino;
- //$msg = sprintf("%-22s : %d", $matches[1], $apino);
- //$this->log(1, $msg);
- }
- }
- }
-
- /**
- * Run an external command, using a message callback to report
- * output. The command will be run through popen and output is
- * reported for every line with a "cmdoutput" message with the
- * line string, including newlines, as payload.
- *
- * @param string $command the command to run
- *
- * @param mixed $callback (optional) function to use as message
- * callback
- *
- * @return bool whether the command was successful (exit code 0
- * means success, any other means failure)
- *
- * @access private
- */
- function _runCommand($command, $callback = null)
- {
- $this->log(1, "running: $command");
- $pp = popen("$command 2>&1", "r");
- if (!$pp) {
- return $this->raiseError("failed to run `$command'");
- }
- if ($callback && $callback[0]->debug == 1) {
- $olddbg = $callback[0]->debug;
- $callback[0]->debug = 2;
- }
-
- while ($line = fgets($pp, 1024)) {
- if ($callback) {
- call_user_func($callback, 'cmdoutput', $line);
- } else {
- $this->log(2, rtrim($line));
- }
- }
- if ($callback && isset($olddbg)) {
- $callback[0]->debug = $olddbg;
- }
-
- $exitcode = is_resource($pp) ? pclose($pp) : -1;
- return ($exitcode == 0);
- }
-
- function log($level, $msg)
- {
- if ($this->current_callback) {
- if ($this->debug >= $level) {
- call_user_func($this->current_callback, 'output', $msg);
- }
- return;
- }
- return PEAR_Common::log($level, $msg);
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/ChannelFile.php b/3rdparty/PEAR/ChannelFile.php
deleted file mode 100644
index f2c02ab42b..0000000000
--- a/3rdparty/PEAR/ChannelFile.php
+++ /dev/null
@@ -1,1559 +0,0 @@
-
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: ChannelFile.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 1.4.0a1
- */
-
-/**
- * Needed for error handling
- */
-require_once 'PEAR/ErrorStack.php';
-require_once 'PEAR/XMLParser.php';
-require_once 'PEAR/Common.php';
-
-/**
- * Error code if the channel.xml tag does not contain a valid version
- */
-define('PEAR_CHANNELFILE_ERROR_NO_VERSION', 1);
-/**
- * Error code if the channel.xml tag version is not supported (version 1.0 is the only supported version,
- * currently
- */
-define('PEAR_CHANNELFILE_ERROR_INVALID_VERSION', 2);
-
-/**
- * Error code if parsing is attempted with no xml extension
- */
-define('PEAR_CHANNELFILE_ERROR_NO_XML_EXT', 3);
-
-/**
- * Error code if creating the xml parser resource fails
- */
-define('PEAR_CHANNELFILE_ERROR_CANT_MAKE_PARSER', 4);
-
-/**
- * Error code used for all sax xml parsing errors
- */
-define('PEAR_CHANNELFILE_ERROR_PARSER_ERROR', 5);
-
-/**#@+
- * Validation errors
- */
-/**
- * Error code when channel name is missing
- */
-define('PEAR_CHANNELFILE_ERROR_NO_NAME', 6);
-/**
- * Error code when channel name is invalid
- */
-define('PEAR_CHANNELFILE_ERROR_INVALID_NAME', 7);
-/**
- * Error code when channel summary is missing
- */
-define('PEAR_CHANNELFILE_ERROR_NO_SUMMARY', 8);
-/**
- * Error code when channel summary is multi-line
- */
-define('PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY', 9);
-/**
- * Error code when channel server is missing for protocol
- */
-define('PEAR_CHANNELFILE_ERROR_NO_HOST', 10);
-/**
- * Error code when channel server is invalid for protocol
- */
-define('PEAR_CHANNELFILE_ERROR_INVALID_HOST', 11);
-/**
- * Error code when a mirror name is invalid
- */
-define('PEAR_CHANNELFILE_ERROR_INVALID_MIRROR', 21);
-/**
- * Error code when a mirror type is invalid
- */
-define('PEAR_CHANNELFILE_ERROR_INVALID_MIRRORTYPE', 22);
-/**
- * Error code when an attempt is made to generate xml, but the parsed content is invalid
- */
-define('PEAR_CHANNELFILE_ERROR_INVALID', 23);
-/**
- * Error code when an empty package name validate regex is passed in
- */
-define('PEAR_CHANNELFILE_ERROR_EMPTY_REGEX', 24);
-/**
- * Error code when a tag has no version
- */
-define('PEAR_CHANNELFILE_ERROR_NO_FUNCTIONVERSION', 25);
-/**
- * Error code when a tag has no name
- */
-define('PEAR_CHANNELFILE_ERROR_NO_FUNCTIONNAME', 26);
-/**
- * Error code when a tag has no name
- */
-define('PEAR_CHANNELFILE_ERROR_NOVALIDATE_NAME', 27);
-/**
- * Error code when a tag has no version attribute
- */
-define('PEAR_CHANNELFILE_ERROR_NOVALIDATE_VERSION', 28);
-/**
- * Error code when a mirror does not exist but is called for in one of the set*
- * methods.
- */
-define('PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND', 32);
-/**
- * Error code when a server port is not numeric
- */
-define('PEAR_CHANNELFILE_ERROR_INVALID_PORT', 33);
-/**
- * Error code when contains no version attribute
- */
-define('PEAR_CHANNELFILE_ERROR_NO_STATICVERSION', 34);
-/**
- * Error code when contains no type attribute in a protocol definition
- */
-define('PEAR_CHANNELFILE_ERROR_NOBASEURLTYPE', 35);
-/**
- * Error code when a mirror is defined and the channel.xml represents the __uri pseudo-channel
- */
-define('PEAR_CHANNELFILE_URI_CANT_MIRROR', 36);
-/**
- * Error code when ssl attribute is present and is not "yes"
- */
-define('PEAR_CHANNELFILE_ERROR_INVALID_SSL', 37);
-/**#@-*/
-
-/**
- * Mirror types allowed. Currently only internet servers are recognized.
- */
-$GLOBALS['_PEAR_CHANNELS_MIRROR_TYPES'] = array('server');
-
-
-/**
- * The Channel handling class
- *
- * @category pear
- * @package PEAR
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 1.4.0a1
- */
-class PEAR_ChannelFile
-{
- /**
- * @access private
- * @var PEAR_ErrorStack
- * @access private
- */
- var $_stack;
-
- /**
- * Supported channel.xml versions, for parsing
- * @var array
- * @access private
- */
- var $_supportedVersions = array('1.0');
-
- /**
- * Parsed channel information
- * @var array
- * @access private
- */
- var $_channelInfo;
-
- /**
- * index into the subchannels array, used for parsing xml
- * @var int
- * @access private
- */
- var $_subchannelIndex;
-
- /**
- * index into the mirrors array, used for parsing xml
- * @var int
- * @access private
- */
- var $_mirrorIndex;
-
- /**
- * Flag used to determine the validity of parsed content
- * @var boolean
- * @access private
- */
- var $_isValid = false;
-
- function PEAR_ChannelFile()
- {
- $this->_stack = &new PEAR_ErrorStack('PEAR_ChannelFile');
- $this->_stack->setErrorMessageTemplate($this->_getErrorMessage());
- $this->_isValid = false;
- }
-
- /**
- * @return array
- * @access protected
- */
- function _getErrorMessage()
- {
- return
- array(
- PEAR_CHANNELFILE_ERROR_INVALID_VERSION =>
- 'While parsing channel.xml, an invalid version number "%version% was passed in, expecting one of %versions%',
- PEAR_CHANNELFILE_ERROR_NO_VERSION =>
- 'No version number found in tag',
- PEAR_CHANNELFILE_ERROR_NO_XML_EXT =>
- '%error%',
- PEAR_CHANNELFILE_ERROR_CANT_MAKE_PARSER =>
- 'Unable to create XML parser',
- PEAR_CHANNELFILE_ERROR_PARSER_ERROR =>
- '%error%',
- PEAR_CHANNELFILE_ERROR_NO_NAME =>
- 'Missing channel name',
- PEAR_CHANNELFILE_ERROR_INVALID_NAME =>
- 'Invalid channel %tag% "%name%"',
- PEAR_CHANNELFILE_ERROR_NO_SUMMARY =>
- 'Missing channel summary',
- PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY =>
- 'Channel summary should be on one line, but is multi-line',
- PEAR_CHANNELFILE_ERROR_NO_HOST =>
- 'Missing channel server for %type% server',
- PEAR_CHANNELFILE_ERROR_INVALID_HOST =>
- 'Server name "%server%" is invalid for %type% server',
- PEAR_CHANNELFILE_ERROR_INVALID_MIRROR =>
- 'Invalid mirror name "%name%", mirror type %type%',
- PEAR_CHANNELFILE_ERROR_INVALID_MIRRORTYPE =>
- 'Invalid mirror type "%type%"',
- PEAR_CHANNELFILE_ERROR_INVALID =>
- 'Cannot generate xml, contents are invalid',
- PEAR_CHANNELFILE_ERROR_EMPTY_REGEX =>
- 'packagenameregex cannot be empty',
- PEAR_CHANNELFILE_ERROR_NO_FUNCTIONVERSION =>
- '%parent% %protocol% function has no version',
- PEAR_CHANNELFILE_ERROR_NO_FUNCTIONNAME =>
- '%parent% %protocol% function has no name',
- PEAR_CHANNELFILE_ERROR_NOBASEURLTYPE =>
- '%parent% rest baseurl has no type',
- PEAR_CHANNELFILE_ERROR_NOVALIDATE_NAME =>
- 'Validation package has no name in tag',
- PEAR_CHANNELFILE_ERROR_NOVALIDATE_VERSION =>
- 'Validation package "%package%" has no version',
- PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND =>
- 'Mirror "%mirror%" does not exist',
- PEAR_CHANNELFILE_ERROR_INVALID_PORT =>
- 'Port "%port%" must be numeric',
- PEAR_CHANNELFILE_ERROR_NO_STATICVERSION =>
- ' tag must contain version attribute',
- PEAR_CHANNELFILE_URI_CANT_MIRROR =>
- 'The __uri pseudo-channel cannot have mirrors',
- PEAR_CHANNELFILE_ERROR_INVALID_SSL =>
- '%server% has invalid ssl attribute "%ssl%" can only be yes or not present',
- );
- }
-
- /**
- * @param string contents of package.xml file
- * @return bool success of parsing
- */
- function fromXmlString($data)
- {
- if (preg_match('/_supportedVersions)) {
- $this->_stack->push(PEAR_CHANNELFILE_ERROR_INVALID_VERSION, 'error',
- array('version' => $channelversion[1]));
- return false;
- }
- $parser = new PEAR_XMLParser;
- $result = $parser->parse($data);
- if ($result !== true) {
- if ($result->getCode() == 1) {
- $this->_stack->push(PEAR_CHANNELFILE_ERROR_NO_XML_EXT, 'error',
- array('error' => $result->getMessage()));
- } else {
- $this->_stack->push(PEAR_CHANNELFILE_ERROR_CANT_MAKE_PARSER, 'error');
- }
- return false;
- }
- $this->_channelInfo = $parser->getData();
- return true;
- } else {
- $this->_stack->push(PEAR_CHANNELFILE_ERROR_NO_VERSION, 'error', array('xml' => $data));
- return false;
- }
- }
-
- /**
- * @return array
- */
- function toArray()
- {
- if (!$this->_isValid && !$this->validate()) {
- return false;
- }
- return $this->_channelInfo;
- }
-
- /**
- * @param array
- * @static
- * @return PEAR_ChannelFile|false false if invalid
- */
- function &fromArray($data, $compatibility = false, $stackClass = 'PEAR_ErrorStack')
- {
- $a = new PEAR_ChannelFile($compatibility, $stackClass);
- $a->_fromArray($data);
- if (!$a->validate()) {
- $a = false;
- return $a;
- }
- return $a;
- }
-
- /**
- * Unlike {@link fromArray()} this does not do any validation
- * @param array
- * @static
- * @return PEAR_ChannelFile
- */
- function &fromArrayWithErrors($data, $compatibility = false,
- $stackClass = 'PEAR_ErrorStack')
- {
- $a = new PEAR_ChannelFile($compatibility, $stackClass);
- $a->_fromArray($data);
- return $a;
- }
-
- /**
- * @param array
- * @access private
- */
- function _fromArray($data)
- {
- $this->_channelInfo = $data;
- }
-
- /**
- * Wrapper to {@link PEAR_ErrorStack::getErrors()}
- * @param boolean determines whether to purge the error stack after retrieving
- * @return array
- */
- function getErrors($purge = false)
- {
- return $this->_stack->getErrors($purge);
- }
-
- /**
- * Unindent given string (?)
- *
- * @param string $str The string that has to be unindented.
- * @return string
- * @access private
- */
- function _unIndent($str)
- {
- // remove leading newlines
- $str = preg_replace('/^[\r\n]+/', '', $str);
- // find whitespace at the beginning of the first line
- $indent_len = strspn($str, " \t");
- $indent = substr($str, 0, $indent_len);
- $data = '';
- // remove the same amount of whitespace from following lines
- foreach (explode("\n", $str) as $line) {
- if (substr($line, 0, $indent_len) == $indent) {
- $data .= substr($line, $indent_len) . "\n";
- }
- }
- return $data;
- }
-
- /**
- * Parse a channel.xml file. Expects the name of
- * a channel xml file as input.
- *
- * @param string $descfile name of channel xml file
- * @return bool success of parsing
- */
- function fromXmlFile($descfile)
- {
- if (!file_exists($descfile) || !is_file($descfile) || !is_readable($descfile) ||
- (!$fp = fopen($descfile, 'r'))) {
- require_once 'PEAR.php';
- return PEAR::raiseError("Unable to open $descfile");
- }
-
- // read the whole thing so we only get one cdata callback
- // for each block of cdata
- fclose($fp);
- $data = file_get_contents($descfile);
- return $this->fromXmlString($data);
- }
-
- /**
- * Parse channel information from different sources
- *
- * This method is able to extract information about a channel
- * from an .xml file or a string
- *
- * @access public
- * @param string Filename of the source or the source itself
- * @return bool
- */
- function fromAny($info)
- {
- if (is_string($info) && file_exists($info) && strlen($info) < 255) {
- $tmp = substr($info, -4);
- if ($tmp == '.xml') {
- $info = $this->fromXmlFile($info);
- } else {
- $fp = fopen($info, "r");
- $test = fread($fp, 5);
- fclose($fp);
- if ($test == "fromXmlFile($info);
- }
- }
- if (PEAR::isError($info)) {
- require_once 'PEAR.php';
- return PEAR::raiseError($info);
- }
- }
- if (is_string($info)) {
- $info = $this->fromXmlString($info);
- }
- return $info;
- }
-
- /**
- * Return an XML document based on previous parsing and modifications
- *
- * @return string XML data
- *
- * @access public
- */
- function toXml()
- {
- if (!$this->_isValid && !$this->validate()) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID);
- return false;
- }
- if (!isset($this->_channelInfo['attribs']['version'])) {
- $this->_channelInfo['attribs']['version'] = '1.0';
- }
- $channelInfo = $this->_channelInfo;
- $ret = "\n";
- $ret .= "
- $channelInfo[name]
- " . htmlspecialchars($channelInfo['summary'])."
-";
- if (isset($channelInfo['suggestedalias'])) {
- $ret .= ' ' . $channelInfo['suggestedalias'] . " \n";
- }
- if (isset($channelInfo['validatepackage'])) {
- $ret .= ' ' .
- htmlspecialchars($channelInfo['validatepackage']['_content']) .
- " \n";
- }
- $ret .= " \n";
- $ret .= ' _makeRestXml($channelInfo['servers']['primary']['rest'], ' ');
- }
- $ret .= " \n";
- if (isset($channelInfo['servers']['mirror'])) {
- $ret .= $this->_makeMirrorsXml($channelInfo);
- }
- $ret .= " \n";
- $ret .= " ";
- return str_replace("\r", "\n", str_replace("\r\n", "\n", $ret));
- }
-
- /**
- * Generate the tag
- * @access private
- */
- function _makeRestXml($info, $indent)
- {
- $ret = $indent . "\n";
- if (isset($info['baseurl']) && !isset($info['baseurl'][0])) {
- $info['baseurl'] = array($info['baseurl']);
- }
-
- if (isset($info['baseurl'])) {
- foreach ($info['baseurl'] as $url) {
- $ret .= "$indent \n";
- }
- }
- $ret .= $indent . " \n";
- return $ret;
- }
-
- /**
- * Generate the tag
- * @access private
- */
- function _makeMirrorsXml($channelInfo)
- {
- $ret = "";
- if (!isset($channelInfo['servers']['mirror'][0])) {
- $channelInfo['servers']['mirror'] = array($channelInfo['servers']['mirror']);
- }
- foreach ($channelInfo['servers']['mirror'] as $mirror) {
- $ret .= ' _makeRestXml($mirror['rest'], ' ');
- }
- $ret .= " \n";
- } else {
- $ret .= "/>\n";
- }
- }
- return $ret;
- }
-
- /**
- * Generate the tag
- * @access private
- */
- function _makeFunctionsXml($functions, $indent, $rest = false)
- {
- $ret = '';
- if (!isset($functions[0])) {
- $functions = array($functions);
- }
- foreach ($functions as $function) {
- $ret .= "$indent\n";
- }
- return $ret;
- }
-
- /**
- * Validation error. Also marks the object contents as invalid
- * @param error code
- * @param array error information
- * @access private
- */
- function _validateError($code, $params = array())
- {
- $this->_stack->push($code, 'error', $params);
- $this->_isValid = false;
- }
-
- /**
- * Validation warning. Does not mark the object contents invalid.
- * @param error code
- * @param array error information
- * @access private
- */
- function _validateWarning($code, $params = array())
- {
- $this->_stack->push($code, 'warning', $params);
- }
-
- /**
- * Validate parsed file.
- *
- * @access public
- * @return boolean
- */
- function validate()
- {
- $this->_isValid = true;
- $info = $this->_channelInfo;
- if (empty($info['name'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_NAME);
- } elseif (!$this->validChannelServer($info['name'])) {
- if ($info['name'] != '__uri') {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_NAME, array('tag' => 'name',
- 'name' => $info['name']));
- }
- }
- if (empty($info['summary'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_SUMMARY);
- } elseif (strpos(trim($info['summary']), "\n") !== false) {
- $this->_validateWarning(PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY,
- array('summary' => $info['summary']));
- }
- if (isset($info['suggestedalias'])) {
- if (!$this->validChannelServer($info['suggestedalias'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_NAME,
- array('tag' => 'suggestedalias', 'name' =>$info['suggestedalias']));
- }
- }
- if (isset($info['localalias'])) {
- if (!$this->validChannelServer($info['localalias'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_NAME,
- array('tag' => 'localalias', 'name' =>$info['localalias']));
- }
- }
- if (isset($info['validatepackage'])) {
- if (!isset($info['validatepackage']['_content'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_NOVALIDATE_NAME);
- }
- if (!isset($info['validatepackage']['attribs']['version'])) {
- $content = isset($info['validatepackage']['_content']) ?
- $info['validatepackage']['_content'] :
- null;
- $this->_validateError(PEAR_CHANNELFILE_ERROR_NOVALIDATE_VERSION,
- array('package' => $content));
- }
- }
-
- if (isset($info['servers']['primary']['attribs'], $info['servers']['primary']['attribs']['port']) &&
- !is_numeric($info['servers']['primary']['attribs']['port'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_PORT,
- array('port' => $info['servers']['primary']['attribs']['port']));
- }
-
- if (isset($info['servers']['primary']['attribs'], $info['servers']['primary']['attribs']['ssl']) &&
- $info['servers']['primary']['attribs']['ssl'] != 'yes') {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_SSL,
- array('ssl' => $info['servers']['primary']['attribs']['ssl'],
- 'server' => $info['name']));
- }
-
- if (isset($info['servers']['primary']['rest']) &&
- isset($info['servers']['primary']['rest']['baseurl'])) {
- $this->_validateFunctions('rest', $info['servers']['primary']['rest']['baseurl']);
- }
- if (isset($info['servers']['mirror'])) {
- if ($this->_channelInfo['name'] == '__uri') {
- $this->_validateError(PEAR_CHANNELFILE_URI_CANT_MIRROR);
- }
- if (!isset($info['servers']['mirror'][0])) {
- $info['servers']['mirror'] = array($info['servers']['mirror']);
- }
- foreach ($info['servers']['mirror'] as $mirror) {
- if (!isset($mirror['attribs']['host'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_HOST,
- array('type' => 'mirror'));
- } elseif (!$this->validChannelServer($mirror['attribs']['host'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_HOST,
- array('server' => $mirror['attribs']['host'], 'type' => 'mirror'));
- }
- if (isset($mirror['attribs']['ssl']) && $mirror['attribs']['ssl'] != 'yes') {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_SSL,
- array('ssl' => $info['ssl'], 'server' => $mirror['attribs']['host']));
- }
- if (isset($mirror['rest'])) {
- $this->_validateFunctions('rest', $mirror['rest']['baseurl'],
- $mirror['attribs']['host']);
- }
- }
- }
- return $this->_isValid;
- }
-
- /**
- * @param string rest - protocol name this function applies to
- * @param array the functions
- * @param string the name of the parent element (mirror name, for instance)
- */
- function _validateFunctions($protocol, $functions, $parent = '')
- {
- if (!isset($functions[0])) {
- $functions = array($functions);
- }
-
- foreach ($functions as $function) {
- if (!isset($function['_content']) || empty($function['_content'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_FUNCTIONNAME,
- array('parent' => $parent, 'protocol' => $protocol));
- }
-
- if ($protocol == 'rest') {
- if (!isset($function['attribs']['type']) ||
- empty($function['attribs']['type'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_NOBASEURLTYPE,
- array('parent' => $parent, 'protocol' => $protocol));
- }
- } else {
- if (!isset($function['attribs']['version']) ||
- empty($function['attribs']['version'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_FUNCTIONVERSION,
- array('parent' => $parent, 'protocol' => $protocol));
- }
- }
- }
- }
-
- /**
- * Test whether a string contains a valid channel server.
- * @param string $ver the package version to test
- * @return bool
- */
- function validChannelServer($server)
- {
- if ($server == '__uri') {
- return true;
- }
- return (bool) preg_match(PEAR_CHANNELS_SERVER_PREG, $server);
- }
-
- /**
- * @return string|false
- */
- function getName()
- {
- if (isset($this->_channelInfo['name'])) {
- return $this->_channelInfo['name'];
- }
-
- return false;
- }
-
- /**
- * @return string|false
- */
- function getServer()
- {
- if (isset($this->_channelInfo['name'])) {
- return $this->_channelInfo['name'];
- }
-
- return false;
- }
-
- /**
- * @return int|80 port number to connect to
- */
- function getPort($mirror = false)
- {
- if ($mirror) {
- if ($mir = $this->getMirror($mirror)) {
- if (isset($mir['attribs']['port'])) {
- return $mir['attribs']['port'];
- }
-
- if ($this->getSSL($mirror)) {
- return 443;
- }
-
- return 80;
- }
-
- return false;
- }
-
- if (isset($this->_channelInfo['servers']['primary']['attribs']['port'])) {
- return $this->_channelInfo['servers']['primary']['attribs']['port'];
- }
-
- if ($this->getSSL()) {
- return 443;
- }
-
- return 80;
- }
-
- /**
- * @return bool Determines whether secure sockets layer (SSL) is used to connect to this channel
- */
- function getSSL($mirror = false)
- {
- if ($mirror) {
- if ($mir = $this->getMirror($mirror)) {
- if (isset($mir['attribs']['ssl'])) {
- return true;
- }
-
- return false;
- }
-
- return false;
- }
-
- if (isset($this->_channelInfo['servers']['primary']['attribs']['ssl'])) {
- return true;
- }
-
- return false;
- }
-
- /**
- * @return string|false
- */
- function getSummary()
- {
- if (isset($this->_channelInfo['summary'])) {
- return $this->_channelInfo['summary'];
- }
-
- return false;
- }
-
- /**
- * @param string protocol type
- * @param string Mirror name
- * @return array|false
- */
- function getFunctions($protocol, $mirror = false)
- {
- if ($this->getName() == '__uri') {
- return false;
- }
-
- $function = $protocol == 'rest' ? 'baseurl' : 'function';
- if ($mirror) {
- if ($mir = $this->getMirror($mirror)) {
- if (isset($mir[$protocol][$function])) {
- return $mir[$protocol][$function];
- }
- }
-
- return false;
- }
-
- if (isset($this->_channelInfo['servers']['primary'][$protocol][$function])) {
- return $this->_channelInfo['servers']['primary'][$protocol][$function];
- }
-
- return false;
- }
-
- /**
- * @param string Protocol type
- * @param string Function name (null to return the
- * first protocol of the type requested)
- * @param string Mirror name, if any
- * @return array
- */
- function getFunction($type, $name = null, $mirror = false)
- {
- $protocols = $this->getFunctions($type, $mirror);
- if (!$protocols) {
- return false;
- }
-
- foreach ($protocols as $protocol) {
- if ($name === null) {
- return $protocol;
- }
-
- if ($protocol['_content'] != $name) {
- continue;
- }
-
- return $protocol;
- }
-
- return false;
- }
-
- /**
- * @param string protocol type
- * @param string protocol name
- * @param string version
- * @param string mirror name
- * @return boolean
- */
- function supports($type, $name = null, $mirror = false, $version = '1.0')
- {
- $protocols = $this->getFunctions($type, $mirror);
- if (!$protocols) {
- return false;
- }
-
- foreach ($protocols as $protocol) {
- if ($protocol['attribs']['version'] != $version) {
- continue;
- }
-
- if ($name === null) {
- return true;
- }
-
- if ($protocol['_content'] != $name) {
- continue;
- }
-
- return true;
- }
-
- return false;
- }
-
- /**
- * Determines whether a channel supports Representational State Transfer (REST) protocols
- * for retrieving channel information
- * @param string
- * @return bool
- */
- function supportsREST($mirror = false)
- {
- if ($mirror == $this->_channelInfo['name']) {
- $mirror = false;
- }
-
- if ($mirror) {
- if ($mir = $this->getMirror($mirror)) {
- return isset($mir['rest']);
- }
-
- return false;
- }
-
- return isset($this->_channelInfo['servers']['primary']['rest']);
- }
-
- /**
- * Get the URL to access a base resource.
- *
- * Hyperlinks in the returned xml will be used to retrieve the proper information
- * needed. This allows extreme extensibility and flexibility in implementation
- * @param string Resource Type to retrieve
- */
- function getBaseURL($resourceType, $mirror = false)
- {
- if ($mirror == $this->_channelInfo['name']) {
- $mirror = false;
- }
-
- if ($mirror) {
- $mir = $this->getMirror($mirror);
- if (!$mir) {
- return false;
- }
-
- $rest = $mir['rest'];
- } else {
- $rest = $this->_channelInfo['servers']['primary']['rest'];
- }
-
- if (!isset($rest['baseurl'][0])) {
- $rest['baseurl'] = array($rest['baseurl']);
- }
-
- foreach ($rest['baseurl'] as $baseurl) {
- if (strtolower($baseurl['attribs']['type']) == strtolower($resourceType)) {
- return $baseurl['_content'];
- }
- }
-
- return false;
- }
-
- /**
- * Since REST does not implement RPC, provide this as a logical wrapper around
- * resetFunctions for REST
- * @param string|false mirror name, if any
- */
- function resetREST($mirror = false)
- {
- return $this->resetFunctions('rest', $mirror);
- }
-
- /**
- * Empty all protocol definitions
- * @param string protocol type
- * @param string|false mirror name, if any
- */
- function resetFunctions($type, $mirror = false)
- {
- if ($mirror) {
- if (isset($this->_channelInfo['servers']['mirror'])) {
- $mirrors = $this->_channelInfo['servers']['mirror'];
- if (!isset($mirrors[0])) {
- $mirrors = array($mirrors);
- }
-
- foreach ($mirrors as $i => $mir) {
- if ($mir['attribs']['host'] == $mirror) {
- if (isset($this->_channelInfo['servers']['mirror'][$i][$type])) {
- unset($this->_channelInfo['servers']['mirror'][$i][$type]);
- }
-
- return true;
- }
- }
-
- return false;
- }
-
- return false;
- }
-
- if (isset($this->_channelInfo['servers']['primary'][$type])) {
- unset($this->_channelInfo['servers']['primary'][$type]);
- }
-
- return true;
- }
-
- /**
- * Set a channel's protocols to the protocols supported by pearweb
- */
- function setDefaultPEARProtocols($version = '1.0', $mirror = false)
- {
- switch ($version) {
- case '1.0' :
- $this->resetREST($mirror);
-
- if (!isset($this->_channelInfo['servers'])) {
- $this->_channelInfo['servers'] = array('primary' =>
- array('rest' => array()));
- } elseif (!isset($this->_channelInfo['servers']['primary'])) {
- $this->_channelInfo['servers']['primary'] = array('rest' => array());
- }
-
- return true;
- break;
- default :
- return false;
- break;
- }
- }
-
- /**
- * @return array
- */
- function getMirrors()
- {
- if (isset($this->_channelInfo['servers']['mirror'])) {
- $mirrors = $this->_channelInfo['servers']['mirror'];
- if (!isset($mirrors[0])) {
- $mirrors = array($mirrors);
- }
-
- return $mirrors;
- }
-
- return array();
- }
-
- /**
- * Get the unserialized XML representing a mirror
- * @return array|false
- */
- function getMirror($server)
- {
- foreach ($this->getMirrors() as $mirror) {
- if ($mirror['attribs']['host'] == $server) {
- return $mirror;
- }
- }
-
- return false;
- }
-
- /**
- * @param string
- * @return string|false
- * @error PEAR_CHANNELFILE_ERROR_NO_NAME
- * @error PEAR_CHANNELFILE_ERROR_INVALID_NAME
- */
- function setName($name)
- {
- return $this->setServer($name);
- }
-
- /**
- * Set the socket number (port) that is used to connect to this channel
- * @param integer
- * @param string|false name of the mirror server, or false for the primary
- */
- function setPort($port, $mirror = false)
- {
- if ($mirror) {
- if (!isset($this->_channelInfo['servers']['mirror'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
- array('mirror' => $mirror));
- return false;
- }
-
- if (isset($this->_channelInfo['servers']['mirror'][0])) {
- foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
- if ($mirror == $mir['attribs']['host']) {
- $this->_channelInfo['servers']['mirror'][$i]['attribs']['port'] = $port;
- return true;
- }
- }
-
- return false;
- } elseif ($this->_channelInfo['servers']['mirror']['attribs']['host'] == $mirror) {
- $this->_channelInfo['servers']['mirror']['attribs']['port'] = $port;
- $this->_isValid = false;
- return true;
- }
- }
-
- $this->_channelInfo['servers']['primary']['attribs']['port'] = $port;
- $this->_isValid = false;
- return true;
- }
-
- /**
- * Set the socket number (port) that is used to connect to this channel
- * @param bool Determines whether to turn on SSL support or turn it off
- * @param string|false name of the mirror server, or false for the primary
- */
- function setSSL($ssl = true, $mirror = false)
- {
- if ($mirror) {
- if (!isset($this->_channelInfo['servers']['mirror'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
- array('mirror' => $mirror));
- return false;
- }
-
- if (isset($this->_channelInfo['servers']['mirror'][0])) {
- foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
- if ($mirror == $mir['attribs']['host']) {
- if (!$ssl) {
- if (isset($this->_channelInfo['servers']['mirror'][$i]
- ['attribs']['ssl'])) {
- unset($this->_channelInfo['servers']['mirror'][$i]['attribs']['ssl']);
- }
- } else {
- $this->_channelInfo['servers']['mirror'][$i]['attribs']['ssl'] = 'yes';
- }
-
- return true;
- }
- }
-
- return false;
- } elseif ($this->_channelInfo['servers']['mirror']['attribs']['host'] == $mirror) {
- if (!$ssl) {
- if (isset($this->_channelInfo['servers']['mirror']['attribs']['ssl'])) {
- unset($this->_channelInfo['servers']['mirror']['attribs']['ssl']);
- }
- } else {
- $this->_channelInfo['servers']['mirror']['attribs']['ssl'] = 'yes';
- }
-
- $this->_isValid = false;
- return true;
- }
- }
-
- if ($ssl) {
- $this->_channelInfo['servers']['primary']['attribs']['ssl'] = 'yes';
- } else {
- if (isset($this->_channelInfo['servers']['primary']['attribs']['ssl'])) {
- unset($this->_channelInfo['servers']['primary']['attribs']['ssl']);
- }
- }
-
- $this->_isValid = false;
- return true;
- }
-
- /**
- * @param string
- * @return string|false
- * @error PEAR_CHANNELFILE_ERROR_NO_SERVER
- * @error PEAR_CHANNELFILE_ERROR_INVALID_SERVER
- */
- function setServer($server, $mirror = false)
- {
- if (empty($server)) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_SERVER);
- return false;
- } elseif (!$this->validChannelServer($server)) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_NAME,
- array('tag' => 'name', 'name' => $server));
- return false;
- }
-
- if ($mirror) {
- $found = false;
- foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
- if ($mirror == $mir['attribs']['host']) {
- $found = true;
- break;
- }
- }
-
- if (!$found) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
- array('mirror' => $mirror));
- return false;
- }
-
- $this->_channelInfo['mirror'][$i]['attribs']['host'] = $server;
- return true;
- }
-
- $this->_channelInfo['name'] = $server;
- return true;
- }
-
- /**
- * @param string
- * @return boolean success
- * @error PEAR_CHANNELFILE_ERROR_NO_SUMMARY
- * @warning PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY
- */
- function setSummary($summary)
- {
- if (empty($summary)) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_NO_SUMMARY);
- return false;
- } elseif (strpos(trim($summary), "\n") !== false) {
- $this->_validateWarning(PEAR_CHANNELFILE_ERROR_MULTILINE_SUMMARY,
- array('summary' => $summary));
- }
-
- $this->_channelInfo['summary'] = $summary;
- return true;
- }
-
- /**
- * @param string
- * @param boolean determines whether the alias is in channel.xml or local
- * @return boolean success
- */
- function setAlias($alias, $local = false)
- {
- if (!$this->validChannelServer($alias)) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_INVALID_NAME,
- array('tag' => 'suggestedalias', 'name' => $alias));
- return false;
- }
-
- if ($local) {
- $this->_channelInfo['localalias'] = $alias;
- } else {
- $this->_channelInfo['suggestedalias'] = $alias;
- }
-
- return true;
- }
-
- /**
- * @return string
- */
- function getAlias()
- {
- if (isset($this->_channelInfo['localalias'])) {
- return $this->_channelInfo['localalias'];
- }
- if (isset($this->_channelInfo['suggestedalias'])) {
- return $this->_channelInfo['suggestedalias'];
- }
- if (isset($this->_channelInfo['name'])) {
- return $this->_channelInfo['name'];
- }
- return '';
- }
-
- /**
- * Set the package validation object if it differs from PEAR's default
- * The class must be includeable via changing _ in the classname to path separator,
- * but no checking of this is made.
- * @param string|false pass in false to reset to the default packagename regex
- * @return boolean success
- */
- function setValidationPackage($validateclass, $version)
- {
- if (empty($validateclass)) {
- unset($this->_channelInfo['validatepackage']);
- }
- $this->_channelInfo['validatepackage'] = array('_content' => $validateclass);
- $this->_channelInfo['validatepackage']['attribs'] = array('version' => $version);
- }
-
- /**
- * Add a protocol to the provides section
- * @param string protocol type
- * @param string protocol version
- * @param string protocol name, if any
- * @param string mirror name, if this is a mirror's protocol
- * @return bool
- */
- function addFunction($type, $version, $name = '', $mirror = false)
- {
- if ($mirror) {
- return $this->addMirrorFunction($mirror, $type, $version, $name);
- }
-
- $set = array('attribs' => array('version' => $version), '_content' => $name);
- if (!isset($this->_channelInfo['servers']['primary'][$type]['function'])) {
- if (!isset($this->_channelInfo['servers'])) {
- $this->_channelInfo['servers'] = array('primary' =>
- array($type => array()));
- } elseif (!isset($this->_channelInfo['servers']['primary'])) {
- $this->_channelInfo['servers']['primary'] = array($type => array());
- }
-
- $this->_channelInfo['servers']['primary'][$type]['function'] = $set;
- $this->_isValid = false;
- return true;
- } elseif (!isset($this->_channelInfo['servers']['primary'][$type]['function'][0])) {
- $this->_channelInfo['servers']['primary'][$type]['function'] = array(
- $this->_channelInfo['servers']['primary'][$type]['function']);
- }
-
- $this->_channelInfo['servers']['primary'][$type]['function'][] = $set;
- return true;
- }
- /**
- * Add a protocol to a mirror's provides section
- * @param string mirror name (server)
- * @param string protocol type
- * @param string protocol version
- * @param string protocol name, if any
- */
- function addMirrorFunction($mirror, $type, $version, $name = '')
- {
- if (!isset($this->_channelInfo['servers']['mirror'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
- array('mirror' => $mirror));
- return false;
- }
-
- $setmirror = false;
- if (isset($this->_channelInfo['servers']['mirror'][0])) {
- foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
- if ($mirror == $mir['attribs']['host']) {
- $setmirror = &$this->_channelInfo['servers']['mirror'][$i];
- break;
- }
- }
- } else {
- if ($this->_channelInfo['servers']['mirror']['attribs']['host'] == $mirror) {
- $setmirror = &$this->_channelInfo['servers']['mirror'];
- }
- }
-
- if (!$setmirror) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
- array('mirror' => $mirror));
- return false;
- }
-
- $set = array('attribs' => array('version' => $version), '_content' => $name);
- if (!isset($setmirror[$type]['function'])) {
- $setmirror[$type]['function'] = $set;
- $this->_isValid = false;
- return true;
- } elseif (!isset($setmirror[$type]['function'][0])) {
- $setmirror[$type]['function'] = array($setmirror[$type]['function']);
- }
-
- $setmirror[$type]['function'][] = $set;
- $this->_isValid = false;
- return true;
- }
-
- /**
- * @param string Resource Type this url links to
- * @param string URL
- * @param string|false mirror name, if this is not a primary server REST base URL
- */
- function setBaseURL($resourceType, $url, $mirror = false)
- {
- if ($mirror) {
- if (!isset($this->_channelInfo['servers']['mirror'])) {
- $this->_validateError(PEAR_CHANNELFILE_ERROR_MIRROR_NOT_FOUND,
- array('mirror' => $mirror));
- return false;
- }
-
- $setmirror = false;
- if (isset($this->_channelInfo['servers']['mirror'][0])) {
- foreach ($this->_channelInfo['servers']['mirror'] as $i => $mir) {
- if ($mirror == $mir['attribs']['host']) {
- $setmirror = &$this->_channelInfo['servers']['mirror'][$i];
- break;
- }
- }
- } else {
- if ($this->_channelInfo['servers']['mirror']['attribs']['host'] == $mirror) {
- $setmirror = &$this->_channelInfo['servers']['mirror'];
- }
- }
- } else {
- $setmirror = &$this->_channelInfo['servers']['primary'];
- }
-
- $set = array('attribs' => array('type' => $resourceType), '_content' => $url);
- if (!isset($setmirror['rest'])) {
- $setmirror['rest'] = array();
- }
-
- if (!isset($setmirror['rest']['baseurl'])) {
- $setmirror['rest']['baseurl'] = $set;
- $this->_isValid = false;
- return true;
- } elseif (!isset($setmirror['rest']['baseurl'][0])) {
- $setmirror['rest']['baseurl'] = array($setmirror['rest']['baseurl']);
- }
-
- foreach ($setmirror['rest']['baseurl'] as $i => $url) {
- if ($url['attribs']['type'] == $resourceType) {
- $this->_isValid = false;
- $setmirror['rest']['baseurl'][$i] = $set;
- return true;
- }
- }
-
- $setmirror['rest']['baseurl'][] = $set;
- $this->_isValid = false;
- return true;
- }
-
- /**
- * @param string mirror server
- * @param int mirror http port
- * @return boolean
- */
- function addMirror($server, $port = null)
- {
- if ($this->_channelInfo['name'] == '__uri') {
- return false; // the __uri channel cannot have mirrors by definition
- }
-
- $set = array('attribs' => array('host' => $server));
- if (is_numeric($port)) {
- $set['attribs']['port'] = $port;
- }
-
- if (!isset($this->_channelInfo['servers']['mirror'])) {
- $this->_channelInfo['servers']['mirror'] = $set;
- return true;
- }
-
- if (!isset($this->_channelInfo['servers']['mirror'][0])) {
- $this->_channelInfo['servers']['mirror'] =
- array($this->_channelInfo['servers']['mirror']);
- }
-
- $this->_channelInfo['servers']['mirror'][] = $set;
- return true;
- }
-
- /**
- * Retrieve the name of the validation package for this channel
- * @return string|false
- */
- function getValidationPackage()
- {
- if (!$this->_isValid && !$this->validate()) {
- return false;
- }
-
- if (!isset($this->_channelInfo['validatepackage'])) {
- return array('attribs' => array('version' => 'default'),
- '_content' => 'PEAR_Validate');
- }
-
- return $this->_channelInfo['validatepackage'];
- }
-
- /**
- * Retrieve the object that can be used for custom validation
- * @param string|false the name of the package to validate. If the package is
- * the channel validation package, PEAR_Validate is returned
- * @return PEAR_Validate|false false is returned if the validation package
- * cannot be located
- */
- function &getValidationObject($package = false)
- {
- if (!class_exists('PEAR_Validate')) {
- require_once 'PEAR/Validate.php';
- }
-
- if (!$this->_isValid) {
- if (!$this->validate()) {
- $a = false;
- return $a;
- }
- }
-
- if (isset($this->_channelInfo['validatepackage'])) {
- if ($package == $this->_channelInfo['validatepackage']) {
- // channel validation packages are always validated by PEAR_Validate
- $val = &new PEAR_Validate;
- return $val;
- }
-
- if (!class_exists(str_replace('.', '_',
- $this->_channelInfo['validatepackage']['_content']))) {
- if ($this->isIncludeable(str_replace('_', '/',
- $this->_channelInfo['validatepackage']['_content']) . '.php')) {
- include_once str_replace('_', '/',
- $this->_channelInfo['validatepackage']['_content']) . '.php';
- $vclass = str_replace('.', '_',
- $this->_channelInfo['validatepackage']['_content']);
- $val = &new $vclass;
- } else {
- $a = false;
- return $a;
- }
- } else {
- $vclass = str_replace('.', '_',
- $this->_channelInfo['validatepackage']['_content']);
- $val = &new $vclass;
- }
- } else {
- $val = &new PEAR_Validate;
- }
-
- return $val;
- }
-
- function isIncludeable($path)
- {
- $possibilities = explode(PATH_SEPARATOR, ini_get('include_path'));
- foreach ($possibilities as $dir) {
- if (file_exists($dir . DIRECTORY_SEPARATOR . $path)
- && is_readable($dir . DIRECTORY_SEPARATOR . $path)) {
- return true;
- }
- }
-
- return false;
- }
-
- /**
- * This function is used by the channel updater and retrieves a value set by
- * the registry, or the current time if it has not been set
- * @return string
- */
- function lastModified()
- {
- if (isset($this->_channelInfo['_lastmodified'])) {
- return $this->_channelInfo['_lastmodified'];
- }
-
- return time();
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/ChannelFile/Parser.php b/3rdparty/PEAR/ChannelFile/Parser.php
deleted file mode 100644
index e630ace224..0000000000
--- a/3rdparty/PEAR/ChannelFile/Parser.php
+++ /dev/null
@@ -1,68 +0,0 @@
-
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Parser.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 1.4.0a1
- */
-
-/**
- * base xml parser class
- */
-require_once 'PEAR/XMLParser.php';
-require_once 'PEAR/ChannelFile.php';
-/**
- * Parser for channel.xml
- * @category pear
- * @package PEAR
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 1.4.0a1
- */
-class PEAR_ChannelFile_Parser extends PEAR_XMLParser
-{
- var $_config;
- var $_logger;
- var $_registry;
-
- function setConfig(&$c)
- {
- $this->_config = &$c;
- $this->_registry = &$c->getRegistry();
- }
-
- function setLogger(&$l)
- {
- $this->_logger = &$l;
- }
-
- function parse($data, $file)
- {
- if (PEAR::isError($err = parent::parse($data, $file))) {
- return $err;
- }
-
- $ret = new PEAR_ChannelFile;
- $ret->setConfig($this->_config);
- if (isset($this->_logger)) {
- $ret->setLogger($this->_logger);
- }
-
- $ret->fromArray($this->_unserializedData);
- // make sure the filelist is in the easy to read format needed
- $ret->flattenFilelist();
- $ret->setPackagefile($file, $archive);
- return $ret;
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command.php b/3rdparty/PEAR/Command.php
deleted file mode 100644
index 13518d4e4b..0000000000
--- a/3rdparty/PEAR/Command.php
+++ /dev/null
@@ -1,414 +0,0 @@
-
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Command.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- */
-
-/**
- * Needed for error handling
- */
-require_once 'PEAR.php';
-require_once 'PEAR/Frontend.php';
-require_once 'PEAR/XMLParser.php';
-
-/**
- * List of commands and what classes they are implemented in.
- * @var array command => implementing class
- */
-$GLOBALS['_PEAR_Command_commandlist'] = array();
-
-/**
- * List of commands and their descriptions
- * @var array command => description
- */
-$GLOBALS['_PEAR_Command_commanddesc'] = array();
-
-/**
- * List of shortcuts to common commands.
- * @var array shortcut => command
- */
-$GLOBALS['_PEAR_Command_shortcuts'] = array();
-
-/**
- * Array of command objects
- * @var array class => object
- */
-$GLOBALS['_PEAR_Command_objects'] = array();
-
-/**
- * PEAR command class, a simple factory class for administrative
- * commands.
- *
- * How to implement command classes:
- *
- * - The class must be called PEAR_Command_Nnn, installed in the
- * "PEAR/Common" subdir, with a method called getCommands() that
- * returns an array of the commands implemented by the class (see
- * PEAR/Command/Install.php for an example).
- *
- * - The class must implement a run() function that is called with three
- * params:
- *
- * (string) command name
- * (array) assoc array with options, freely defined by each
- * command, for example:
- * array('force' => true)
- * (array) list of the other parameters
- *
- * The run() function returns a PEAR_CommandResponse object. Use
- * these methods to get information:
- *
- * int getStatus() Returns PEAR_COMMAND_(SUCCESS|FAILURE|PARTIAL)
- * *_PARTIAL means that you need to issue at least
- * one more command to complete the operation
- * (used for example for validation steps).
- *
- * string getMessage() Returns a message for the user. Remember,
- * no HTML or other interface-specific markup.
- *
- * If something unexpected happens, run() returns a PEAR error.
- *
- * - DON'T OUTPUT ANYTHING! Return text for output instead.
- *
- * - DON'T USE HTML! The text you return will be used from both Gtk,
- * web and command-line interfaces, so for now, keep everything to
- * plain text.
- *
- * - DON'T USE EXIT OR DIE! Always use pear errors. From static
- * classes do PEAR::raiseError(), from other classes do
- * $this->raiseError().
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- */
-class PEAR_Command
-{
- // {{{ factory()
-
- /**
- * Get the right object for executing a command.
- *
- * @param string $command The name of the command
- * @param object $config Instance of PEAR_Config object
- *
- * @return object the command object or a PEAR error
- *
- * @access public
- * @static
- */
- function &factory($command, &$config)
- {
- if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
- PEAR_Command::registerCommands();
- }
- if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
- $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
- }
- if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
- $a = PEAR::raiseError("unknown command `$command'");
- return $a;
- }
- $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
- if (!class_exists($class)) {
- require_once $GLOBALS['_PEAR_Command_objects'][$class];
- }
- if (!class_exists($class)) {
- $a = PEAR::raiseError("unknown command `$command'");
- return $a;
- }
- $ui = PEAR_Command::getFrontendObject();
- $obj = new $class($ui, $config);
- return $obj;
- }
-
- // }}}
- // {{{ & getObject()
- function &getObject($command)
- {
- $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
- if (!class_exists($class)) {
- require_once $GLOBALS['_PEAR_Command_objects'][$class];
- }
- if (!class_exists($class)) {
- return PEAR::raiseError("unknown command `$command'");
- }
- $ui = PEAR_Command::getFrontendObject();
- $config = &PEAR_Config::singleton();
- $obj = &new $class($ui, $config);
- return $obj;
- }
-
- // }}}
- // {{{ & getFrontendObject()
-
- /**
- * Get instance of frontend object.
- *
- * @return object|PEAR_Error
- * @static
- */
- function &getFrontendObject()
- {
- $a = &PEAR_Frontend::singleton();
- return $a;
- }
-
- // }}}
- // {{{ & setFrontendClass()
-
- /**
- * Load current frontend class.
- *
- * @param string $uiclass Name of class implementing the frontend
- *
- * @return object the frontend object, or a PEAR error
- * @static
- */
- function &setFrontendClass($uiclass)
- {
- $a = &PEAR_Frontend::setFrontendClass($uiclass);
- return $a;
- }
-
- // }}}
- // {{{ setFrontendType()
-
- /**
- * Set current frontend.
- *
- * @param string $uitype Name of the frontend type (for example "CLI")
- *
- * @return object the frontend object, or a PEAR error
- * @static
- */
- function setFrontendType($uitype)
- {
- $uiclass = 'PEAR_Frontend_' . $uitype;
- return PEAR_Command::setFrontendClass($uiclass);
- }
-
- // }}}
- // {{{ registerCommands()
-
- /**
- * Scan through the Command directory looking for classes
- * and see what commands they implement.
- *
- * @param bool (optional) if FALSE (default), the new list of
- * commands should replace the current one. If TRUE,
- * new entries will be merged with old.
- *
- * @param string (optional) where (what directory) to look for
- * classes, defaults to the Command subdirectory of
- * the directory from where this file (__FILE__) is
- * included.
- *
- * @return bool TRUE on success, a PEAR error on failure
- *
- * @access public
- * @static
- */
- function registerCommands($merge = false, $dir = null)
- {
- $parser = new PEAR_XMLParser;
- if ($dir === null) {
- $dir = dirname(__FILE__) . '/Command';
- }
- if (!is_dir($dir)) {
- return PEAR::raiseError("registerCommands: opendir($dir) '$dir' does not exist or is not a directory");
- }
- $dp = @opendir($dir);
- if (empty($dp)) {
- return PEAR::raiseError("registerCommands: opendir($dir) failed");
- }
- if (!$merge) {
- $GLOBALS['_PEAR_Command_commandlist'] = array();
- }
-
- while ($file = readdir($dp)) {
- if ($file{0} == '.' || substr($file, -4) != '.xml') {
- continue;
- }
-
- $f = substr($file, 0, -4);
- $class = "PEAR_Command_" . $f;
- // List of commands
- if (empty($GLOBALS['_PEAR_Command_objects'][$class])) {
- $GLOBALS['_PEAR_Command_objects'][$class] = "$dir/" . $f . '.php';
- }
-
- $parser->parse(file_get_contents("$dir/$file"));
- $implements = $parser->getData();
- foreach ($implements as $command => $desc) {
- if ($command == 'attribs') {
- continue;
- }
-
- if (isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
- return PEAR::raiseError('Command "' . $command . '" already registered in ' .
- 'class "' . $GLOBALS['_PEAR_Command_commandlist'][$command] . '"');
- }
-
- $GLOBALS['_PEAR_Command_commandlist'][$command] = $class;
- $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc['summary'];
- if (isset($desc['shortcut'])) {
- $shortcut = $desc['shortcut'];
- if (isset($GLOBALS['_PEAR_Command_shortcuts'][$shortcut])) {
- return PEAR::raiseError('Command shortcut "' . $shortcut . '" already ' .
- 'registered to command "' . $command . '" in class "' .
- $GLOBALS['_PEAR_Command_commandlist'][$command] . '"');
- }
- $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command;
- }
-
- if (isset($desc['options']) && $desc['options']) {
- foreach ($desc['options'] as $oname => $option) {
- if (isset($option['shortopt']) && strlen($option['shortopt']) > 1) {
- return PEAR::raiseError('Option "' . $oname . '" short option "' .
- $option['shortopt'] . '" must be ' .
- 'only 1 character in Command "' . $command . '" in class "' .
- $class . '"');
- }
- }
- }
- }
- }
-
- ksort($GLOBALS['_PEAR_Command_shortcuts']);
- ksort($GLOBALS['_PEAR_Command_commandlist']);
- @closedir($dp);
- return true;
- }
-
- // }}}
- // {{{ getCommands()
-
- /**
- * Get the list of currently supported commands, and what
- * classes implement them.
- *
- * @return array command => implementing class
- *
- * @access public
- * @static
- */
- function getCommands()
- {
- if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
- PEAR_Command::registerCommands();
- }
- return $GLOBALS['_PEAR_Command_commandlist'];
- }
-
- // }}}
- // {{{ getShortcuts()
-
- /**
- * Get the list of command shortcuts.
- *
- * @return array shortcut => command
- *
- * @access public
- * @static
- */
- function getShortcuts()
- {
- if (empty($GLOBALS['_PEAR_Command_shortcuts'])) {
- PEAR_Command::registerCommands();
- }
- return $GLOBALS['_PEAR_Command_shortcuts'];
- }
-
- // }}}
- // {{{ getGetoptArgs()
-
- /**
- * Compiles arguments for getopt.
- *
- * @param string $command command to get optstring for
- * @param string $short_args (reference) short getopt format
- * @param array $long_args (reference) long getopt format
- *
- * @return void
- *
- * @access public
- * @static
- */
- function getGetoptArgs($command, &$short_args, &$long_args)
- {
- if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
- PEAR_Command::registerCommands();
- }
- if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
- $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
- }
- if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
- return null;
- }
- $obj = &PEAR_Command::getObject($command);
- return $obj->getGetoptArgs($command, $short_args, $long_args);
- }
-
- // }}}
- // {{{ getDescription()
-
- /**
- * Get description for a command.
- *
- * @param string $command Name of the command
- *
- * @return string command description
- *
- * @access public
- * @static
- */
- function getDescription($command)
- {
- if (!isset($GLOBALS['_PEAR_Command_commanddesc'][$command])) {
- return null;
- }
- return $GLOBALS['_PEAR_Command_commanddesc'][$command];
- }
-
- // }}}
- // {{{ getHelp()
-
- /**
- * Get help for command.
- *
- * @param string $command Name of the command to return help for
- *
- * @access public
- * @static
- */
- function getHelp($command)
- {
- $cmds = PEAR_Command::getCommands();
- if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
- $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
- }
- if (isset($cmds[$command])) {
- $obj = &PEAR_Command::getObject($command);
- return $obj->getHelp($command);
- }
- return false;
- }
- // }}}
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Auth.php b/3rdparty/PEAR/Command/Auth.php
deleted file mode 100644
index 63cd152b90..0000000000
--- a/3rdparty/PEAR/Command/Auth.php
+++ /dev/null
@@ -1,81 +0,0 @@
-
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Auth.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- * @deprecated since 1.8.0alpha1
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Channels.php';
-
-/**
- * PEAR commands for login/logout
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- * @deprecated since 1.8.0alpha1
- */
-class PEAR_Command_Auth extends PEAR_Command_Channels
-{
- var $commands = array(
- 'login' => array(
- 'summary' => 'Connects and authenticates to remote server [Deprecated in favor of channel-login]',
- 'shortcut' => 'li',
- 'function' => 'doLogin',
- 'options' => array(),
- 'doc' => '
-WARNING: This function is deprecated in favor of using channel-login
-
-Log in to a remote channel server. If is not supplied,
-the default channel is used. To use remote functions in the installer
-that require any kind of privileges, you need to log in first. The
-username and password you enter here will be stored in your per-user
-PEAR configuration (~/.pearrc on Unix-like systems). After logging
-in, your username and password will be sent along in subsequent
-operations on the remote server.',
- ),
- 'logout' => array(
- 'summary' => 'Logs out from the remote server [Deprecated in favor of channel-logout]',
- 'shortcut' => 'lo',
- 'function' => 'doLogout',
- 'options' => array(),
- 'doc' => '
-WARNING: This function is deprecated in favor of using channel-logout
-
-Logs out from the remote server. This command does not actually
-connect to the remote server, it only deletes the stored username and
-password from your user configuration.',
- )
-
- );
-
- /**
- * PEAR_Command_Auth constructor.
- *
- * @access public
- */
- function PEAR_Command_Auth(&$ui, &$config)
- {
- parent::PEAR_Command_Channels($ui, $config);
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Auth.xml b/3rdparty/PEAR/Command/Auth.xml
deleted file mode 100644
index 590193d142..0000000000
--- a/3rdparty/PEAR/Command/Auth.xml
+++ /dev/null
@@ -1,30 +0,0 @@
-
-
- Connects and authenticates to remote server [Deprecated in favor of channel-login]
- doLogin
- li
-
- <channel name>
-WARNING: This function is deprecated in favor of using channel-login
-
-Log in to a remote channel server. If <channel name> is not supplied,
-the default channel is used. To use remote functions in the installer
-that require any kind of privileges, you need to log in first. The
-username and password you enter here will be stored in your per-user
-PEAR configuration (~/.pearrc on Unix-like systems). After logging
-in, your username and password will be sent along in subsequent
-operations on the remote server.
-
-
- Logs out from the remote server [Deprecated in favor of channel-logout]
- doLogout
- lo
-
-
-WARNING: This function is deprecated in favor of using channel-logout
-
-Logs out from the remote server. This command does not actually
-connect to the remote server, it only deletes the stored username and
-password from your user configuration.
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Build.php b/3rdparty/PEAR/Command/Build.php
deleted file mode 100644
index 1de7320246..0000000000
--- a/3rdparty/PEAR/Command/Build.php
+++ /dev/null
@@ -1,85 +0,0 @@
-
- * @author Tomas V.V.Cox
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Build.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Common.php';
-
-/**
- * PEAR commands for building extensions.
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Tomas V.V.Cox
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- */
-class PEAR_Command_Build extends PEAR_Command_Common
-{
- var $commands = array(
- 'build' => array(
- 'summary' => 'Build an Extension From C Source',
- 'function' => 'doBuild',
- 'shortcut' => 'b',
- 'options' => array(),
- 'doc' => '[package.xml]
-Builds one or more extensions contained in a package.'
- ),
- );
-
- /**
- * PEAR_Command_Build constructor.
- *
- * @access public
- */
- function PEAR_Command_Build(&$ui, &$config)
- {
- parent::PEAR_Command_Common($ui, $config);
- }
-
- function doBuild($command, $options, $params)
- {
- require_once 'PEAR/Builder.php';
- if (sizeof($params) < 1) {
- $params[0] = 'package.xml';
- }
-
- $builder = &new PEAR_Builder($this->ui);
- $this->debug = $this->config->get('verbose');
- $err = $builder->build($params[0], array(&$this, 'buildCallback'));
- if (PEAR::isError($err)) {
- return $err;
- }
-
- return true;
- }
-
- function buildCallback($what, $data)
- {
- if (($what == 'cmdoutput' && $this->debug > 1) ||
- ($what == 'output' && $this->debug > 0)) {
- $this->ui->outputData(rtrim($data), 'build');
- }
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Build.xml b/3rdparty/PEAR/Command/Build.xml
deleted file mode 100644
index ec4e6f554c..0000000000
--- a/3rdparty/PEAR/Command/Build.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-
-
- Build an Extension From C Source
- doBuild
- b
-
- [package.xml]
-Builds one or more extensions contained in a package.
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Channels.php b/3rdparty/PEAR/Command/Channels.php
deleted file mode 100644
index fcf01b5039..0000000000
--- a/3rdparty/PEAR/Command/Channels.php
+++ /dev/null
@@ -1,883 +0,0 @@
-
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Channels.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 1.4.0a1
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Common.php';
-
-define('PEAR_COMMAND_CHANNELS_CHANNEL_EXISTS', -500);
-
-/**
- * PEAR commands for managing channels.
- *
- * @category pear
- * @package PEAR
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 1.4.0a1
- */
-class PEAR_Command_Channels extends PEAR_Command_Common
-{
- var $commands = array(
- 'list-channels' => array(
- 'summary' => 'List Available Channels',
- 'function' => 'doList',
- 'shortcut' => 'lc',
- 'options' => array(),
- 'doc' => '
-List all available channels for installation.
-',
- ),
- 'update-channels' => array(
- 'summary' => 'Update the Channel List',
- 'function' => 'doUpdateAll',
- 'shortcut' => 'uc',
- 'options' => array(),
- 'doc' => '
-List all installed packages in all channels.
-'
- ),
- 'channel-delete' => array(
- 'summary' => 'Remove a Channel From the List',
- 'function' => 'doDelete',
- 'shortcut' => 'cde',
- 'options' => array(),
- 'doc' => '
-Delete a channel from the registry. You may not
-remove any channel that has installed packages.
-'
- ),
- 'channel-add' => array(
- 'summary' => 'Add a Channel',
- 'function' => 'doAdd',
- 'shortcut' => 'ca',
- 'options' => array(),
- 'doc' => '
-Add a private channel to the channel list. Note that all
-public channels should be synced using "update-channels".
-Parameter may be either a local file or remote URL to a
-channel.xml.
-'
- ),
- 'channel-update' => array(
- 'summary' => 'Update an Existing Channel',
- 'function' => 'doUpdate',
- 'shortcut' => 'cu',
- 'options' => array(
- 'force' => array(
- 'shortopt' => 'f',
- 'doc' => 'will force download of new channel.xml if an existing channel name is used',
- ),
- 'channel' => array(
- 'shortopt' => 'c',
- 'arg' => 'CHANNEL',
- 'doc' => 'will force download of new channel.xml if an existing channel name is used',
- ),
-),
- 'doc' => '[|]
-Update a channel in the channel list directly. Note that all
-public channels can be synced using "update-channels".
-Parameter may be a local or remote channel.xml, or the name of
-an existing channel.
-'
- ),
- 'channel-info' => array(
- 'summary' => 'Retrieve Information on a Channel',
- 'function' => 'doInfo',
- 'shortcut' => 'ci',
- 'options' => array(),
- 'doc' => '
-List the files in an installed package.
-'
- ),
- 'channel-alias' => array(
- 'summary' => 'Specify an alias to a channel name',
- 'function' => 'doAlias',
- 'shortcut' => 'cha',
- 'options' => array(),
- 'doc' => '
-Specify a specific alias to use for a channel name.
-The alias may not be an existing channel name or
-alias.
-'
- ),
- 'channel-discover' => array(
- 'summary' => 'Initialize a Channel from its server',
- 'function' => 'doDiscover',
- 'shortcut' => 'di',
- 'options' => array(),
- 'doc' => '[|]
-Initialize a channel from its server and create a local channel.xml.
-If is in the format ":@" then
- and will be set as the login username/password for
-. Use caution when passing the username/password in this way, as
-it may allow other users on your computer to briefly view your username/
-password via the system\'s process list.
-'
- ),
- 'channel-login' => array(
- 'summary' => 'Connects and authenticates to remote channel server',
- 'shortcut' => 'cli',
- 'function' => 'doLogin',
- 'options' => array(),
- 'doc' => '
-Log in to a remote channel server. If is not supplied,
-the default channel is used. To use remote functions in the installer
-that require any kind of privileges, you need to log in first. The
-username and password you enter here will be stored in your per-user
-PEAR configuration (~/.pearrc on Unix-like systems). After logging
-in, your username and password will be sent along in subsequent
-operations on the remote server.',
- ),
- 'channel-logout' => array(
- 'summary' => 'Logs out from the remote channel server',
- 'shortcut' => 'clo',
- 'function' => 'doLogout',
- 'options' => array(),
- 'doc' => '
-Logs out from a remote channel server. If is not supplied,
-the default channel is used. This command does not actually connect to the
-remote server, it only deletes the stored username and password from your user
-configuration.',
- ),
- );
-
- /**
- * PEAR_Command_Registry constructor.
- *
- * @access public
- */
- function PEAR_Command_Channels(&$ui, &$config)
- {
- parent::PEAR_Command_Common($ui, $config);
- }
-
- function _sortChannels($a, $b)
- {
- return strnatcasecmp($a->getName(), $b->getName());
- }
-
- function doList($command, $options, $params)
- {
- $reg = &$this->config->getRegistry();
- $registered = $reg->getChannels();
- usort($registered, array(&$this, '_sortchannels'));
- $i = $j = 0;
- $data = array(
- 'caption' => 'Registered Channels:',
- 'border' => true,
- 'headline' => array('Channel', 'Alias', 'Summary')
- );
- foreach ($registered as $channel) {
- $data['data'][] = array($channel->getName(),
- $channel->getAlias(),
- $channel->getSummary());
- }
-
- if (count($registered) === 0) {
- $data = '(no registered channels)';
- }
- $this->ui->outputData($data, $command);
- return true;
- }
-
- function doUpdateAll($command, $options, $params)
- {
- $reg = &$this->config->getRegistry();
- $channels = $reg->getChannels();
-
- $success = true;
- foreach ($channels as $channel) {
- if ($channel->getName() != '__uri') {
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $err = $this->doUpdate('channel-update',
- $options,
- array($channel->getName()));
- if (PEAR::isError($err)) {
- $this->ui->outputData($err->getMessage(), $command);
- $success = false;
- } else {
- $success &= $err;
- }
- }
- }
- return $success;
- }
-
- function doInfo($command, $options, $params)
- {
- if (count($params) !== 1) {
- return $this->raiseError("No channel specified");
- }
-
- $reg = &$this->config->getRegistry();
- $channel = strtolower($params[0]);
- if ($reg->channelExists($channel)) {
- $chan = $reg->getChannel($channel);
- if (PEAR::isError($chan)) {
- return $this->raiseError($chan);
- }
- } else {
- if (strpos($channel, '://')) {
- $downloader = &$this->getDownloader();
- $tmpdir = $this->config->get('temp_dir');
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $loc = $downloader->downloadHttp($channel, $this->ui, $tmpdir);
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($loc)) {
- return $this->raiseError('Cannot open "' . $channel .
- '" (' . $loc->getMessage() . ')');
- } else {
- $contents = implode('', file($loc));
- }
- } else {
- if (!file_exists($params[0])) {
- return $this->raiseError('Unknown channel "' . $channel . '"');
- }
-
- $fp = fopen($params[0], 'r');
- if (!$fp) {
- return $this->raiseError('Cannot open "' . $params[0] . '"');
- }
-
- $contents = '';
- while (!feof($fp)) {
- $contents .= fread($fp, 1024);
- }
- fclose($fp);
- }
-
- if (!class_exists('PEAR_ChannelFile')) {
- require_once 'PEAR/ChannelFile.php';
- }
-
- $chan = new PEAR_ChannelFile;
- $chan->fromXmlString($contents);
- $chan->validate();
- if ($errs = $chan->getErrors(true)) {
- foreach ($errs as $err) {
- $this->ui->outputData($err['level'] . ': ' . $err['message']);
- }
- return $this->raiseError('Channel file "' . $params[0] . '" is not valid');
- }
- }
-
- if (!$chan) {
- return $this->raiseError('Serious error: Channel "' . $params[0] .
- '" has a corrupted registry entry');
- }
-
- $channel = $chan->getName();
- $caption = 'Channel ' . $channel . ' Information:';
- $data1 = array(
- 'caption' => $caption,
- 'border' => true);
- $data1['data']['server'] = array('Name and Server', $chan->getName());
- if ($chan->getAlias() != $chan->getName()) {
- $data1['data']['alias'] = array('Alias', $chan->getAlias());
- }
-
- $data1['data']['summary'] = array('Summary', $chan->getSummary());
- $validate = $chan->getValidationPackage();
- $data1['data']['vpackage'] = array('Validation Package Name', $validate['_content']);
- $data1['data']['vpackageversion'] =
- array('Validation Package Version', $validate['attribs']['version']);
- $d = array();
- $d['main'] = $data1;
-
- $data['data'] = array();
- $data['caption'] = 'Server Capabilities';
- $data['headline'] = array('Type', 'Version/REST type', 'Function Name/REST base');
- if ($chan->supportsREST()) {
- if ($chan->supportsREST()) {
- $funcs = $chan->getFunctions('rest');
- if (!isset($funcs[0])) {
- $funcs = array($funcs);
- }
- foreach ($funcs as $protocol) {
- $data['data'][] = array('rest', $protocol['attribs']['type'],
- $protocol['_content']);
- }
- }
- } else {
- $data['data'][] = array('No supported protocols');
- }
-
- $d['protocols'] = $data;
- $data['data'] = array();
- $mirrors = $chan->getMirrors();
- if ($mirrors) {
- $data['caption'] = 'Channel ' . $channel . ' Mirrors:';
- unset($data['headline']);
- foreach ($mirrors as $mirror) {
- $data['data'][] = array($mirror['attribs']['host']);
- $d['mirrors'] = $data;
- }
-
- foreach ($mirrors as $i => $mirror) {
- $data['data'] = array();
- $data['caption'] = 'Mirror ' . $mirror['attribs']['host'] . ' Capabilities';
- $data['headline'] = array('Type', 'Version/REST type', 'Function Name/REST base');
- if ($chan->supportsREST($mirror['attribs']['host'])) {
- if ($chan->supportsREST($mirror['attribs']['host'])) {
- $funcs = $chan->getFunctions('rest', $mirror['attribs']['host']);
- if (!isset($funcs[0])) {
- $funcs = array($funcs);
- }
-
- foreach ($funcs as $protocol) {
- $data['data'][] = array('rest', $protocol['attribs']['type'],
- $protocol['_content']);
- }
- }
- } else {
- $data['data'][] = array('No supported protocols');
- }
- $d['mirrorprotocols' . $i] = $data;
- }
- }
- $this->ui->outputData($d, 'channel-info');
- }
-
- // }}}
-
- function doDelete($command, $options, $params)
- {
- if (count($params) !== 1) {
- return $this->raiseError('channel-delete: no channel specified');
- }
-
- $reg = &$this->config->getRegistry();
- if (!$reg->channelExists($params[0])) {
- return $this->raiseError('channel-delete: channel "' . $params[0] . '" does not exist');
- }
-
- $channel = $reg->channelName($params[0]);
- if ($channel == 'pear.php.net') {
- return $this->raiseError('Cannot delete the pear.php.net channel');
- }
-
- if ($channel == 'pecl.php.net') {
- return $this->raiseError('Cannot delete the pecl.php.net channel');
- }
-
- if ($channel == 'doc.php.net') {
- return $this->raiseError('Cannot delete the doc.php.net channel');
- }
-
- if ($channel == '__uri') {
- return $this->raiseError('Cannot delete the __uri pseudo-channel');
- }
-
- if (PEAR::isError($err = $reg->listPackages($channel))) {
- return $err;
- }
-
- if (count($err)) {
- return $this->raiseError('Channel "' . $channel .
- '" has installed packages, cannot delete');
- }
-
- if (!$reg->deleteChannel($channel)) {
- return $this->raiseError('Channel "' . $channel . '" deletion failed');
- } else {
- $this->config->deleteChannel($channel);
- $this->ui->outputData('Channel "' . $channel . '" deleted', $command);
- }
- }
-
- function doAdd($command, $options, $params)
- {
- if (count($params) !== 1) {
- return $this->raiseError('channel-add: no channel file specified');
- }
-
- if (strpos($params[0], '://')) {
- $downloader = &$this->getDownloader();
- $tmpdir = $this->config->get('temp_dir');
- if (!file_exists($tmpdir)) {
- require_once 'System.php';
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $err = System::mkdir(array('-p', $tmpdir));
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($err)) {
- return $this->raiseError('channel-add: temp_dir does not exist: "' .
- $tmpdir .
- '" - You can change this location with "pear config-set temp_dir"');
- }
- }
-
- if (!is_writable($tmpdir)) {
- return $this->raiseError('channel-add: temp_dir is not writable: "' .
- $tmpdir .
- '" - You can change this location with "pear config-set temp_dir"');
- }
-
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $loc = $downloader->downloadHttp($params[0], $this->ui, $tmpdir, null, false);
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($loc)) {
- return $this->raiseError('channel-add: Cannot open "' . $params[0] .
- '" (' . $loc->getMessage() . ')');
- }
-
- list($loc, $lastmodified) = $loc;
- $contents = implode('', file($loc));
- } else {
- $lastmodified = $fp = false;
- if (file_exists($params[0])) {
- $fp = fopen($params[0], 'r');
- }
-
- if (!$fp) {
- return $this->raiseError('channel-add: cannot open "' . $params[0] . '"');
- }
-
- $contents = '';
- while (!feof($fp)) {
- $contents .= fread($fp, 1024);
- }
- fclose($fp);
- }
-
- if (!class_exists('PEAR_ChannelFile')) {
- require_once 'PEAR/ChannelFile.php';
- }
-
- $channel = new PEAR_ChannelFile;
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $result = $channel->fromXmlString($contents);
- PEAR::staticPopErrorHandling();
- if (!$result) {
- $exit = false;
- if (count($errors = $channel->getErrors(true))) {
- foreach ($errors as $error) {
- $this->ui->outputData(ucfirst($error['level'] . ': ' . $error['message']));
- if (!$exit) {
- $exit = $error['level'] == 'error' ? true : false;
- }
- }
- if ($exit) {
- return $this->raiseError('channel-add: invalid channel.xml file');
- }
- }
- }
-
- $reg = &$this->config->getRegistry();
- if ($reg->channelExists($channel->getName())) {
- return $this->raiseError('channel-add: Channel "' . $channel->getName() .
- '" exists, use channel-update to update entry', PEAR_COMMAND_CHANNELS_CHANNEL_EXISTS);
- }
-
- $ret = $reg->addChannel($channel, $lastmodified);
- if (PEAR::isError($ret)) {
- return $ret;
- }
-
- if (!$ret) {
- return $this->raiseError('channel-add: adding Channel "' . $channel->getName() .
- '" to registry failed');
- }
-
- $this->config->setChannels($reg->listChannels());
- $this->config->writeConfigFile();
- $this->ui->outputData('Adding Channel "' . $channel->getName() . '" succeeded', $command);
- }
-
- function doUpdate($command, $options, $params)
- {
- if (count($params) !== 1) {
- return $this->raiseError("No channel file specified");
- }
-
- $tmpdir = $this->config->get('temp_dir');
- if (!file_exists($tmpdir)) {
- require_once 'System.php';
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $err = System::mkdir(array('-p', $tmpdir));
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($err)) {
- return $this->raiseError('channel-add: temp_dir does not exist: "' .
- $tmpdir .
- '" - You can change this location with "pear config-set temp_dir"');
- }
- }
-
- if (!is_writable($tmpdir)) {
- return $this->raiseError('channel-add: temp_dir is not writable: "' .
- $tmpdir .
- '" - You can change this location with "pear config-set temp_dir"');
- }
-
- $reg = &$this->config->getRegistry();
- $lastmodified = false;
- if ((!file_exists($params[0]) || is_dir($params[0]))
- && $reg->channelExists(strtolower($params[0]))) {
- $c = $reg->getChannel(strtolower($params[0]));
- if (PEAR::isError($c)) {
- return $this->raiseError($c);
- }
-
- $this->ui->outputData("Updating channel \"$params[0]\"", $command);
- $dl = &$this->getDownloader(array());
- // if force is specified, use a timestamp of "1" to force retrieval
- $lastmodified = isset($options['force']) ? false : $c->lastModified();
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $contents = $dl->downloadHttp('http://' . $c->getName() . '/channel.xml',
- $this->ui, $tmpdir, null, $lastmodified);
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($contents)) {
- // Attempt to fall back to https
- $this->ui->outputData("Channel \"$params[0]\" is not responding over http://, failed with message: " . $contents->getMessage());
- $this->ui->outputData("Trying channel \"$params[0]\" over https:// instead");
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $contents = $dl->downloadHttp('https://' . $c->getName() . '/channel.xml',
- $this->ui, $tmpdir, null, $lastmodified);
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($contents)) {
- return $this->raiseError('Cannot retrieve channel.xml for channel "' .
- $c->getName() . '" (' . $contents->getMessage() . ')');
- }
- }
-
- list($contents, $lastmodified) = $contents;
- if (!$contents) {
- $this->ui->outputData("Channel \"$params[0]\" is up to date");
- return;
- }
-
- $contents = implode('', file($contents));
- if (!class_exists('PEAR_ChannelFile')) {
- require_once 'PEAR/ChannelFile.php';
- }
-
- $channel = new PEAR_ChannelFile;
- $channel->fromXmlString($contents);
- if (!$channel->getErrors()) {
- // security check: is the downloaded file for the channel we got it from?
- if (strtolower($channel->getName()) != strtolower($c->getName())) {
- if (!isset($options['force'])) {
- return $this->raiseError('ERROR: downloaded channel definition file' .
- ' for channel "' . $channel->getName() . '" from channel "' .
- strtolower($c->getName()) . '"');
- }
-
- $this->ui->log(0, 'WARNING: downloaded channel definition file' .
- ' for channel "' . $channel->getName() . '" from channel "' .
- strtolower($c->getName()) . '"');
- }
- }
- } else {
- if (strpos($params[0], '://')) {
- $dl = &$this->getDownloader();
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $loc = $dl->downloadHttp($params[0],
- $this->ui, $tmpdir, null, $lastmodified);
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($loc)) {
- return $this->raiseError("Cannot open " . $params[0] .
- ' (' . $loc->getMessage() . ')');
- }
-
- list($loc, $lastmodified) = $loc;
- $contents = implode('', file($loc));
- } else {
- $fp = false;
- if (file_exists($params[0])) {
- $fp = fopen($params[0], 'r');
- }
-
- if (!$fp) {
- return $this->raiseError("Cannot open " . $params[0]);
- }
-
- $contents = '';
- while (!feof($fp)) {
- $contents .= fread($fp, 1024);
- }
- fclose($fp);
- }
-
- if (!class_exists('PEAR_ChannelFile')) {
- require_once 'PEAR/ChannelFile.php';
- }
-
- $channel = new PEAR_ChannelFile;
- $channel->fromXmlString($contents);
- }
-
- $exit = false;
- if (count($errors = $channel->getErrors(true))) {
- foreach ($errors as $error) {
- $this->ui->outputData(ucfirst($error['level'] . ': ' . $error['message']));
- if (!$exit) {
- $exit = $error['level'] == 'error' ? true : false;
- }
- }
- if ($exit) {
- return $this->raiseError('Invalid channel.xml file');
- }
- }
-
- if (!$reg->channelExists($channel->getName())) {
- return $this->raiseError('Error: Channel "' . $channel->getName() .
- '" does not exist, use channel-add to add an entry');
- }
-
- $ret = $reg->updateChannel($channel, $lastmodified);
- if (PEAR::isError($ret)) {
- return $ret;
- }
-
- if (!$ret) {
- return $this->raiseError('Updating Channel "' . $channel->getName() .
- '" in registry failed');
- }
-
- $this->config->setChannels($reg->listChannels());
- $this->config->writeConfigFile();
- $this->ui->outputData('Update of Channel "' . $channel->getName() . '" succeeded');
- }
-
- function &getDownloader()
- {
- if (!class_exists('PEAR_Downloader')) {
- require_once 'PEAR/Downloader.php';
- }
- $a = new PEAR_Downloader($this->ui, array(), $this->config);
- return $a;
- }
-
- function doAlias($command, $options, $params)
- {
- if (count($params) === 1) {
- return $this->raiseError('No channel alias specified');
- }
-
- if (count($params) !== 2 || (!empty($params[1]) && $params[1]{0} == '-')) {
- return $this->raiseError(
- 'Invalid format, correct is: channel-alias channel alias');
- }
-
- $reg = &$this->config->getRegistry();
- if (!$reg->channelExists($params[0], true)) {
- $extra = '';
- if ($reg->isAlias($params[0])) {
- $extra = ' (use "channel-alias ' . $reg->channelName($params[0]) . ' ' .
- strtolower($params[1]) . '")';
- }
-
- return $this->raiseError('"' . $params[0] . '" is not a valid channel' . $extra);
- }
-
- if ($reg->isAlias($params[1])) {
- return $this->raiseError('Channel "' . $reg->channelName($params[1]) . '" is ' .
- 'already aliased to "' . strtolower($params[1]) . '", cannot re-alias');
- }
-
- $chan = &$reg->getChannel($params[0]);
- if (PEAR::isError($chan)) {
- return $this->raiseError('Corrupt registry? Error retrieving channel "' . $params[0] .
- '" information (' . $chan->getMessage() . ')');
- }
-
- // make it a local alias
- if (!$chan->setAlias(strtolower($params[1]), true)) {
- return $this->raiseError('Alias "' . strtolower($params[1]) .
- '" is not a valid channel alias');
- }
-
- $reg->updateChannel($chan);
- $this->ui->outputData('Channel "' . $chan->getName() . '" aliased successfully to "' .
- strtolower($params[1]) . '"');
- }
-
- /**
- * The channel-discover command
- *
- * @param string $command command name
- * @param array $options option_name => value
- * @param array $params list of additional parameters.
- * $params[0] should contain a string with either:
- * - or
- * - :@
- * @return null|PEAR_Error
- */
- function doDiscover($command, $options, $params)
- {
- if (count($params) !== 1) {
- return $this->raiseError("No channel server specified");
- }
-
- // Look for the possible input format ":@"
- if (preg_match('/^(.+):(.+)@(.+)\\z/', $params[0], $matches)) {
- $username = $matches[1];
- $password = $matches[2];
- $channel = $matches[3];
- } else {
- $channel = $params[0];
- }
-
- $reg = &$this->config->getRegistry();
- if ($reg->channelExists($channel)) {
- if (!$reg->isAlias($channel)) {
- return $this->raiseError("Channel \"$channel\" is already initialized", PEAR_COMMAND_CHANNELS_CHANNEL_EXISTS);
- }
-
- return $this->raiseError("A channel alias named \"$channel\" " .
- 'already exists, aliasing channel "' . $reg->channelName($channel)
- . '"');
- }
-
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $err = $this->doAdd($command, $options, array('http://' . $channel . '/channel.xml'));
- $this->popErrorHandling();
- if (PEAR::isError($err)) {
- if ($err->getCode() === PEAR_COMMAND_CHANNELS_CHANNEL_EXISTS) {
- return $this->raiseError("Discovery of channel \"$channel\" failed (" .
- $err->getMessage() . ')');
- }
- // Attempt fetch via https
- $this->ui->outputData("Discovering channel $channel over http:// failed with message: " . $err->getMessage());
- $this->ui->outputData("Trying to discover channel $channel over https:// instead");
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $err = $this->doAdd($command, $options, array('https://' . $channel . '/channel.xml'));
- $this->popErrorHandling();
- if (PEAR::isError($err)) {
- return $this->raiseError("Discovery of channel \"$channel\" failed (" .
- $err->getMessage() . ')');
- }
- }
-
- // Store username/password if they were given
- // Arguably we should do a logintest on the channel here, but since
- // that's awkward on a REST-based channel (even "pear login" doesn't
- // do it for those), and XML-RPC is deprecated, it's fairly pointless.
- if (isset($username)) {
- $this->config->set('username', $username, 'user', $channel);
- $this->config->set('password', $password, 'user', $channel);
- $this->config->store();
- $this->ui->outputData("Stored login for channel \"$channel\" using username \"$username\"", $command);
- }
-
- $this->ui->outputData("Discovery of channel \"$channel\" succeeded", $command);
- }
-
- /**
- * Execute the 'login' command.
- *
- * @param string $command command name
- * @param array $options option_name => value
- * @param array $params list of additional parameters
- *
- * @return bool TRUE on success or
- * a PEAR error on failure
- *
- * @access public
- */
- function doLogin($command, $options, $params)
- {
- $reg = &$this->config->getRegistry();
-
- // If a parameter is supplied, use that as the channel to log in to
- $channel = isset($params[0]) ? $params[0] : $this->config->get('default_channel');
-
- $chan = $reg->getChannel($channel);
- if (PEAR::isError($chan)) {
- return $this->raiseError($chan);
- }
-
- $server = $this->config->get('preferred_mirror', null, $channel);
- $username = $this->config->get('username', null, $channel);
- if (empty($username)) {
- $username = isset($_ENV['USER']) ? $_ENV['USER'] : null;
- }
- $this->ui->outputData("Logging in to $server.", $command);
-
- list($username, $password) = $this->ui->userDialog(
- $command,
- array('Username', 'Password'),
- array('text', 'password'),
- array($username, '')
- );
- $username = trim($username);
- $password = trim($password);
-
- $ourfile = $this->config->getConfFile('user');
- if (!$ourfile) {
- $ourfile = $this->config->getConfFile('system');
- }
-
- $this->config->set('username', $username, 'user', $channel);
- $this->config->set('password', $password, 'user', $channel);
-
- if ($chan->supportsREST()) {
- $ok = true;
- }
-
- if ($ok !== true) {
- return $this->raiseError('Login failed!');
- }
-
- $this->ui->outputData("Logged in.", $command);
- // avoid changing any temporary settings changed with -d
- $ourconfig = new PEAR_Config($ourfile, $ourfile);
- $ourconfig->set('username', $username, 'user', $channel);
- $ourconfig->set('password', $password, 'user', $channel);
- $ourconfig->store();
-
- return true;
- }
-
- /**
- * Execute the 'logout' command.
- *
- * @param string $command command name
- * @param array $options option_name => value
- * @param array $params list of additional parameters
- *
- * @return bool TRUE on success or
- * a PEAR error on failure
- *
- * @access public
- */
- function doLogout($command, $options, $params)
- {
- $reg = &$this->config->getRegistry();
-
- // If a parameter is supplied, use that as the channel to log in to
- $channel = isset($params[0]) ? $params[0] : $this->config->get('default_channel');
-
- $chan = $reg->getChannel($channel);
- if (PEAR::isError($chan)) {
- return $this->raiseError($chan);
- }
-
- $server = $this->config->get('preferred_mirror', null, $channel);
- $this->ui->outputData("Logging out from $server.", $command);
- $this->config->remove('username', 'user', $channel);
- $this->config->remove('password', 'user', $channel);
- $this->config->store();
- return true;
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Channels.xml b/3rdparty/PEAR/Command/Channels.xml
deleted file mode 100644
index 47b72066ab..0000000000
--- a/3rdparty/PEAR/Command/Channels.xml
+++ /dev/null
@@ -1,123 +0,0 @@
-
-
- List Available Channels
- doList
- lc
-
-
-List all available channels for installation.
-
-
-
- Update the Channel List
- doUpdateAll
- uc
-
-
-List all installed packages in all channels.
-
-
-
- Remove a Channel From the List
- doDelete
- cde
-
- <channel name>
-Delete a channel from the registry. You may not
-remove any channel that has installed packages.
-
-
-
- Add a Channel
- doAdd
- ca
-
- <channel.xml>
-Add a private channel to the channel list. Note that all
-public channels should be synced using "update-channels".
-Parameter may be either a local file or remote URL to a
-channel.xml.
-
-
-
- Update an Existing Channel
- doUpdate
- cu
-
-
- f
- will force download of new channel.xml if an existing channel name is used
-
-
- c
- will force download of new channel.xml if an existing channel name is used
- CHANNEL
-
-
- [<channel.xml>|<channel name>]
-Update a channel in the channel list directly. Note that all
-public channels can be synced using "update-channels".
-Parameter may be a local or remote channel.xml, or the name of
-an existing channel.
-
-
-
- Retrieve Information on a Channel
- doInfo
- ci
-
- <package>
-List the files in an installed package.
-
-
-
- Specify an alias to a channel name
- doAlias
- cha
-
- <channel> <alias>
-Specify a specific alias to use for a channel name.
-The alias may not be an existing channel name or
-alias.
-
-
-
- Initialize a Channel from its server
- doDiscover
- di
-
- [<channel.xml>|<channel name>]
-Initialize a channel from its server and create a local channel.xml.
-If <channel name> is in the format "<username>:<password>@<channel>" then
-<username> and <password> will be set as the login username/password for
-<channel>. Use caution when passing the username/password in this way, as
-it may allow other users on your computer to briefly view your username/
-password via the system's process list.
-
-
-
- Connects and authenticates to remote channel server
- doLogin
- cli
-
- <channel name>
-Log in to a remote channel server. If <channel name> is not supplied,
-the default channel is used. To use remote functions in the installer
-that require any kind of privileges, you need to log in first. The
-username and password you enter here will be stored in your per-user
-PEAR configuration (~/.pearrc on Unix-like systems). After logging
-in, your username and password will be sent along in subsequent
-operations on the remote server.
-
-
- Logs out from the remote channel server
- doLogout
- clo
-
- <channel name>
-Logs out from a remote channel server. If <channel name> is not supplied,
-the default channel is used. This command does not actually connect to the
-remote server, it only deletes the stored username and password from your user
-configuration.
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Common.php b/3rdparty/PEAR/Command/Common.php
deleted file mode 100644
index 279a716623..0000000000
--- a/3rdparty/PEAR/Command/Common.php
+++ /dev/null
@@ -1,273 +0,0 @@
-
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Common.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- */
-
-/**
- * base class
- */
-require_once 'PEAR.php';
-
-/**
- * PEAR commands base class
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- */
-class PEAR_Command_Common extends PEAR
-{
- /**
- * PEAR_Config object used to pass user system and configuration
- * on when executing commands
- *
- * @var PEAR_Config
- */
- var $config;
- /**
- * @var PEAR_Registry
- * @access protected
- */
- var $_registry;
-
- /**
- * User Interface object, for all interaction with the user.
- * @var object
- */
- var $ui;
-
- var $_deps_rel_trans = array(
- 'lt' => '<',
- 'le' => '<=',
- 'eq' => '=',
- 'ne' => '!=',
- 'gt' => '>',
- 'ge' => '>=',
- 'has' => '=='
- );
-
- var $_deps_type_trans = array(
- 'pkg' => 'package',
- 'ext' => 'extension',
- 'php' => 'PHP',
- 'prog' => 'external program',
- 'ldlib' => 'external library for linking',
- 'rtlib' => 'external runtime library',
- 'os' => 'operating system',
- 'websrv' => 'web server',
- 'sapi' => 'SAPI backend'
- );
-
- /**
- * PEAR_Command_Common constructor.
- *
- * @access public
- */
- function PEAR_Command_Common(&$ui, &$config)
- {
- parent::PEAR();
- $this->config = &$config;
- $this->ui = &$ui;
- }
-
- /**
- * Return a list of all the commands defined by this class.
- * @return array list of commands
- * @access public
- */
- function getCommands()
- {
- $ret = array();
- foreach (array_keys($this->commands) as $command) {
- $ret[$command] = $this->commands[$command]['summary'];
- }
-
- return $ret;
- }
-
- /**
- * Return a list of all the command shortcuts defined by this class.
- * @return array shortcut => command
- * @access public
- */
- function getShortcuts()
- {
- $ret = array();
- foreach (array_keys($this->commands) as $command) {
- if (isset($this->commands[$command]['shortcut'])) {
- $ret[$this->commands[$command]['shortcut']] = $command;
- }
- }
-
- return $ret;
- }
-
- function getOptions($command)
- {
- $shortcuts = $this->getShortcuts();
- if (isset($shortcuts[$command])) {
- $command = $shortcuts[$command];
- }
-
- if (isset($this->commands[$command]) &&
- isset($this->commands[$command]['options'])) {
- return $this->commands[$command]['options'];
- }
-
- return null;
- }
-
- function getGetoptArgs($command, &$short_args, &$long_args)
- {
- $short_args = '';
- $long_args = array();
- if (empty($this->commands[$command]) || empty($this->commands[$command]['options'])) {
- return;
- }
-
- reset($this->commands[$command]['options']);
- while (list($option, $info) = each($this->commands[$command]['options'])) {
- $larg = $sarg = '';
- if (isset($info['arg'])) {
- if ($info['arg']{0} == '(') {
- $larg = '==';
- $sarg = '::';
- $arg = substr($info['arg'], 1, -1);
- } else {
- $larg = '=';
- $sarg = ':';
- $arg = $info['arg'];
- }
- }
-
- if (isset($info['shortopt'])) {
- $short_args .= $info['shortopt'] . $sarg;
- }
-
- $long_args[] = $option . $larg;
- }
- }
-
- /**
- * Returns the help message for the given command
- *
- * @param string $command The command
- * @return mixed A fail string if the command does not have help or
- * a two elements array containing [0]=>help string,
- * [1]=> help string for the accepted cmd args
- */
- function getHelp($command)
- {
- $config = &PEAR_Config::singleton();
- if (!isset($this->commands[$command])) {
- return "No such command \"$command\"";
- }
-
- $help = null;
- if (isset($this->commands[$command]['doc'])) {
- $help = $this->commands[$command]['doc'];
- }
-
- if (empty($help)) {
- // XXX (cox) Fallback to summary if there is no doc (show both?)
- if (!isset($this->commands[$command]['summary'])) {
- return "No help for command \"$command\"";
- }
- $help = $this->commands[$command]['summary'];
- }
-
- if (preg_match_all('/{config\s+([^\}]+)}/e', $help, $matches)) {
- foreach($matches[0] as $k => $v) {
- $help = preg_replace("/$v/", $config->get($matches[1][$k]), $help);
- }
- }
-
- return array($help, $this->getHelpArgs($command));
- }
-
- /**
- * Returns the help for the accepted arguments of a command
- *
- * @param string $command
- * @return string The help string
- */
- function getHelpArgs($command)
- {
- if (isset($this->commands[$command]['options']) &&
- count($this->commands[$command]['options']))
- {
- $help = "Options:\n";
- foreach ($this->commands[$command]['options'] as $k => $v) {
- if (isset($v['arg'])) {
- if ($v['arg'][0] == '(') {
- $arg = substr($v['arg'], 1, -1);
- $sapp = " [$arg]";
- $lapp = "[=$arg]";
- } else {
- $sapp = " $v[arg]";
- $lapp = "=$v[arg]";
- }
- } else {
- $sapp = $lapp = "";
- }
-
- if (isset($v['shortopt'])) {
- $s = $v['shortopt'];
- $help .= " -$s$sapp, --$k$lapp\n";
- } else {
- $help .= " --$k$lapp\n";
- }
-
- $p = " ";
- $doc = rtrim(str_replace("\n", "\n$p", $v['doc']));
- $help .= " $doc\n";
- }
-
- return $help;
- }
-
- return null;
- }
-
- function run($command, $options, $params)
- {
- if (empty($this->commands[$command]['function'])) {
- // look for shortcuts
- foreach (array_keys($this->commands) as $cmd) {
- if (isset($this->commands[$cmd]['shortcut']) && $this->commands[$cmd]['shortcut'] == $command) {
- if (empty($this->commands[$cmd]['function'])) {
- return $this->raiseError("unknown command `$command'");
- } else {
- $func = $this->commands[$cmd]['function'];
- }
- $command = $cmd;
-
- //$command = $this->commands[$cmd]['function'];
- break;
- }
- }
- } else {
- $func = $this->commands[$command]['function'];
- }
-
- return $this->$func($command, $options, $params);
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Config.php b/3rdparty/PEAR/Command/Config.php
deleted file mode 100644
index a761b277f5..0000000000
--- a/3rdparty/PEAR/Command/Config.php
+++ /dev/null
@@ -1,414 +0,0 @@
-
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Config.php 313024 2011-07-06 19:51:24Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Common.php';
-
-/**
- * PEAR commands for managing configuration data.
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- */
-class PEAR_Command_Config extends PEAR_Command_Common
-{
- var $commands = array(
- 'config-show' => array(
- 'summary' => 'Show All Settings',
- 'function' => 'doConfigShow',
- 'shortcut' => 'csh',
- 'options' => array(
- 'channel' => array(
- 'shortopt' => 'c',
- 'doc' => 'show configuration variables for another channel',
- 'arg' => 'CHAN',
- ),
-),
- 'doc' => '[layer]
-Displays all configuration values. An optional argument
-may be used to tell which configuration layer to display. Valid
-configuration layers are "user", "system" and "default". To display
-configurations for different channels, set the default_channel
-configuration variable and run config-show again.
-',
- ),
- 'config-get' => array(
- 'summary' => 'Show One Setting',
- 'function' => 'doConfigGet',
- 'shortcut' => 'cg',
- 'options' => array(
- 'channel' => array(
- 'shortopt' => 'c',
- 'doc' => 'show configuration variables for another channel',
- 'arg' => 'CHAN',
- ),
-),
- 'doc' => ' [layer]
-Displays the value of one configuration parameter. The
-first argument is the name of the parameter, an optional second argument
-may be used to tell which configuration layer to look in. Valid configuration
-layers are "user", "system" and "default". If no layer is specified, a value
-will be picked from the first layer that defines the parameter, in the order
-just specified. The configuration value will be retrieved for the channel
-specified by the default_channel configuration variable.
-',
- ),
- 'config-set' => array(
- 'summary' => 'Change Setting',
- 'function' => 'doConfigSet',
- 'shortcut' => 'cs',
- 'options' => array(
- 'channel' => array(
- 'shortopt' => 'c',
- 'doc' => 'show configuration variables for another channel',
- 'arg' => 'CHAN',
- ),
-),
- 'doc' => ' [layer]
-Sets the value of one configuration parameter. The first argument is
-the name of the parameter, the second argument is the new value. Some
-parameters are subject to validation, and the command will fail with
-an error message if the new value does not make sense. An optional
-third argument may be used to specify in which layer to set the
-configuration parameter. The default layer is "user". The
-configuration value will be set for the current channel, which
-is controlled by the default_channel configuration variable.
-',
- ),
- 'config-help' => array(
- 'summary' => 'Show Information About Setting',
- 'function' => 'doConfigHelp',
- 'shortcut' => 'ch',
- 'options' => array(),
- 'doc' => '[parameter]
-Displays help for a configuration parameter. Without arguments it
-displays help for all configuration parameters.
-',
- ),
- 'config-create' => array(
- 'summary' => 'Create a Default configuration file',
- 'function' => 'doConfigCreate',
- 'shortcut' => 'coc',
- 'options' => array(
- 'windows' => array(
- 'shortopt' => 'w',
- 'doc' => 'create a config file for a windows install',
- ),
- ),
- 'doc' => '
-Create a default configuration file with all directory configuration
-variables set to subdirectories of , and save it as .
-This is useful especially for creating a configuration file for a remote
-PEAR installation (using the --remoteconfig option of install, upgrade,
-and uninstall).
-',
- ),
- );
-
- /**
- * PEAR_Command_Config constructor.
- *
- * @access public
- */
- function PEAR_Command_Config(&$ui, &$config)
- {
- parent::PEAR_Command_Common($ui, $config);
- }
-
- function doConfigShow($command, $options, $params)
- {
- $layer = null;
- if (is_array($params)) {
- $layer = isset($params[0]) ? $params[0] : null;
- }
-
- // $params[0] -> the layer
- if ($error = $this->_checkLayer($layer)) {
- return $this->raiseError("config-show:$error");
- }
-
- $keys = $this->config->getKeys();
- sort($keys);
- $channel = isset($options['channel']) ? $options['channel'] :
- $this->config->get('default_channel');
- $reg = &$this->config->getRegistry();
- if (!$reg->channelExists($channel)) {
- return $this->raiseError('Channel "' . $channel . '" does not exist');
- }
-
- $channel = $reg->channelName($channel);
- $data = array('caption' => 'Configuration (channel ' . $channel . '):');
- foreach ($keys as $key) {
- $type = $this->config->getType($key);
- $value = $this->config->get($key, $layer, $channel);
- if ($type == 'password' && $value) {
- $value = '********';
- }
-
- if ($value === false) {
- $value = 'false';
- } elseif ($value === true) {
- $value = 'true';
- }
-
- $data['data'][$this->config->getGroup($key)][] = array($this->config->getPrompt($key) , $key, $value);
- }
-
- foreach ($this->config->getLayers() as $layer) {
- $data['data']['Config Files'][] = array(ucfirst($layer) . ' Configuration File', 'Filename' , $this->config->getConfFile($layer));
- }
-
- $this->ui->outputData($data, $command);
- return true;
- }
-
- function doConfigGet($command, $options, $params)
- {
- $args_cnt = is_array($params) ? count($params) : 0;
- switch ($args_cnt) {
- case 1:
- $config_key = $params[0];
- $layer = null;
- break;
- case 2:
- $config_key = $params[0];
- $layer = $params[1];
- if ($error = $this->_checkLayer($layer)) {
- return $this->raiseError("config-get:$error");
- }
- break;
- case 0:
- default:
- return $this->raiseError("config-get expects 1 or 2 parameters");
- }
-
- $reg = &$this->config->getRegistry();
- $channel = isset($options['channel']) ? $options['channel'] : $this->config->get('default_channel');
- if (!$reg->channelExists($channel)) {
- return $this->raiseError('Channel "' . $channel . '" does not exist');
- }
-
- $channel = $reg->channelName($channel);
- $this->ui->outputData($this->config->get($config_key, $layer, $channel), $command);
- return true;
- }
-
- function doConfigSet($command, $options, $params)
- {
- // $param[0] -> a parameter to set
- // $param[1] -> the value for the parameter
- // $param[2] -> the layer
- $failmsg = '';
- if (count($params) < 2 || count($params) > 3) {
- $failmsg .= "config-set expects 2 or 3 parameters";
- return PEAR::raiseError($failmsg);
- }
-
- if (isset($params[2]) && ($error = $this->_checkLayer($params[2]))) {
- $failmsg .= $error;
- return PEAR::raiseError("config-set:$failmsg");
- }
-
- $channel = isset($options['channel']) ? $options['channel'] : $this->config->get('default_channel');
- $reg = &$this->config->getRegistry();
- if (!$reg->channelExists($channel)) {
- return $this->raiseError('Channel "' . $channel . '" does not exist');
- }
-
- $channel = $reg->channelName($channel);
- if ($params[0] == 'default_channel' && !$reg->channelExists($params[1])) {
- return $this->raiseError('Channel "' . $params[1] . '" does not exist');
- }
-
- if ($params[0] == 'preferred_mirror'
- && (
- !$reg->mirrorExists($channel, $params[1]) &&
- (!$reg->channelExists($params[1]) || $channel != $params[1])
- )
- ) {
- $msg = 'Channel Mirror "' . $params[1] . '" does not exist';
- $msg .= ' in your registry for channel "' . $channel . '".';
- $msg .= "\n" . 'Attempt to run "pear channel-update ' . $channel .'"';
- $msg .= ' if you believe this mirror should exist as you may';
- $msg .= ' have outdated channel information.';
- return $this->raiseError($msg);
- }
-
- if (count($params) == 2) {
- array_push($params, 'user');
- $layer = 'user';
- } else {
- $layer = $params[2];
- }
-
- array_push($params, $channel);
- if (!call_user_func_array(array(&$this->config, 'set'), $params)) {
- array_pop($params);
- $failmsg = "config-set (" . implode(", ", $params) . ") failed, channel $channel";
- } else {
- $this->config->store($layer);
- }
-
- if ($failmsg) {
- return $this->raiseError($failmsg);
- }
-
- $this->ui->outputData('config-set succeeded', $command);
- return true;
- }
-
- function doConfigHelp($command, $options, $params)
- {
- if (empty($params)) {
- $params = $this->config->getKeys();
- }
-
- $data['caption'] = "Config help" . ((count($params) == 1) ? " for $params[0]" : '');
- $data['headline'] = array('Name', 'Type', 'Description');
- $data['border'] = true;
- foreach ($params as $name) {
- $type = $this->config->getType($name);
- $docs = $this->config->getDocs($name);
- if ($type == 'set') {
- $docs = rtrim($docs) . "\nValid set: " .
- implode(' ', $this->config->getSetValues($name));
- }
-
- $data['data'][] = array($name, $type, $docs);
- }
-
- $this->ui->outputData($data, $command);
- }
-
- function doConfigCreate($command, $options, $params)
- {
- if (count($params) != 2) {
- return PEAR::raiseError('config-create: must have 2 parameters, root path and ' .
- 'filename to save as');
- }
-
- $root = $params[0];
- // Clean up the DIRECTORY_SEPARATOR mess
- $ds2 = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR;
- $root = preg_replace(array('!\\\\+!', '!/+!', "!$ds2+!"),
- array('/', '/', '/'),
- $root);
- if ($root{0} != '/') {
- if (!isset($options['windows'])) {
- return PEAR::raiseError('Root directory must be an absolute path beginning ' .
- 'with "/", was: "' . $root . '"');
- }
-
- if (!preg_match('/^[A-Za-z]:/', $root)) {
- return PEAR::raiseError('Root directory must be an absolute path beginning ' .
- 'with "\\" or "C:\\", was: "' . $root . '"');
- }
- }
-
- $windows = isset($options['windows']);
- if ($windows) {
- $root = str_replace('/', '\\', $root);
- }
-
- if (!file_exists($params[1]) && !@touch($params[1])) {
- return PEAR::raiseError('Could not create "' . $params[1] . '"');
- }
-
- $params[1] = realpath($params[1]);
- $config = &new PEAR_Config($params[1], '#no#system#config#', false, false);
- if ($root{strlen($root) - 1} == '/') {
- $root = substr($root, 0, strlen($root) - 1);
- }
-
- $config->noRegistry();
- $config->set('php_dir', $windows ? "$root\\pear\\php" : "$root/pear/php", 'user');
- $config->set('data_dir', $windows ? "$root\\pear\\data" : "$root/pear/data");
- $config->set('www_dir', $windows ? "$root\\pear\\www" : "$root/pear/www");
- $config->set('cfg_dir', $windows ? "$root\\pear\\cfg" : "$root/pear/cfg");
- $config->set('ext_dir', $windows ? "$root\\pear\\ext" : "$root/pear/ext");
- $config->set('doc_dir', $windows ? "$root\\pear\\docs" : "$root/pear/docs");
- $config->set('test_dir', $windows ? "$root\\pear\\tests" : "$root/pear/tests");
- $config->set('cache_dir', $windows ? "$root\\pear\\cache" : "$root/pear/cache");
- $config->set('download_dir', $windows ? "$root\\pear\\download" : "$root/pear/download");
- $config->set('temp_dir', $windows ? "$root\\pear\\temp" : "$root/pear/temp");
- $config->set('bin_dir', $windows ? "$root\\pear" : "$root/pear");
- $config->writeConfigFile();
- $this->_showConfig($config);
- $this->ui->outputData('Successfully created default configuration file "' . $params[1] . '"',
- $command);
- }
-
- function _showConfig(&$config)
- {
- $params = array('user');
- $keys = $config->getKeys();
- sort($keys);
- $channel = 'pear.php.net';
- $data = array('caption' => 'Configuration (channel ' . $channel . '):');
- foreach ($keys as $key) {
- $type = $config->getType($key);
- $value = $config->get($key, 'user', $channel);
- if ($type == 'password' && $value) {
- $value = '********';
- }
-
- if ($value === false) {
- $value = 'false';
- } elseif ($value === true) {
- $value = 'true';
- }
- $data['data'][$config->getGroup($key)][] =
- array($config->getPrompt($key) , $key, $value);
- }
-
- foreach ($config->getLayers() as $layer) {
- $data['data']['Config Files'][] =
- array(ucfirst($layer) . ' Configuration File', 'Filename' ,
- $config->getConfFile($layer));
- }
-
- $this->ui->outputData($data, 'config-show');
- return true;
- }
-
- /**
- * Checks if a layer is defined or not
- *
- * @param string $layer The layer to search for
- * @return mixed False on no error or the error message
- */
- function _checkLayer($layer = null)
- {
- if (!empty($layer) && $layer != 'default') {
- $layers = $this->config->getLayers();
- if (!in_array($layer, $layers)) {
- return " only the layers: \"" . implode('" or "', $layers) . "\" are supported";
- }
- }
-
- return false;
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Config.xml b/3rdparty/PEAR/Command/Config.xml
deleted file mode 100644
index f64a925f52..0000000000
--- a/3rdparty/PEAR/Command/Config.xml
+++ /dev/null
@@ -1,92 +0,0 @@
-
-
- Show All Settings
- doConfigShow
- csh
-
-
- c
- show configuration variables for another channel
- CHAN
-
-
- [layer]
-Displays all configuration values. An optional argument
-may be used to tell which configuration layer to display. Valid
-configuration layers are "user", "system" and "default". To display
-configurations for different channels, set the default_channel
-configuration variable and run config-show again.
-
-
-
- Show One Setting
- doConfigGet
- cg
-
-
- c
- show configuration variables for another channel
- CHAN
-
-
- <parameter> [layer]
-Displays the value of one configuration parameter. The
-first argument is the name of the parameter, an optional second argument
-may be used to tell which configuration layer to look in. Valid configuration
-layers are "user", "system" and "default". If no layer is specified, a value
-will be picked from the first layer that defines the parameter, in the order
-just specified. The configuration value will be retrieved for the channel
-specified by the default_channel configuration variable.
-
-
-
- Change Setting
- doConfigSet
- cs
-
-
- c
- show configuration variables for another channel
- CHAN
-
-
- <parameter> <value> [layer]
-Sets the value of one configuration parameter. The first argument is
-the name of the parameter, the second argument is the new value. Some
-parameters are subject to validation, and the command will fail with
-an error message if the new value does not make sense. An optional
-third argument may be used to specify in which layer to set the
-configuration parameter. The default layer is "user". The
-configuration value will be set for the current channel, which
-is controlled by the default_channel configuration variable.
-
-
-
- Show Information About Setting
- doConfigHelp
- ch
-
- [parameter]
-Displays help for a configuration parameter. Without arguments it
-displays help for all configuration parameters.
-
-
-
- Create a Default configuration file
- doConfigCreate
- coc
-
-
- w
- create a config file for a windows install
-
-
- <root path> <filename>
-Create a default configuration file with all directory configuration
-variables set to subdirectories of <root path>, and save it as <filename>.
-This is useful especially for creating a configuration file for a remote
-PEAR installation (using the --remoteconfig option of install, upgrade,
-and uninstall).
-
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Install.php b/3rdparty/PEAR/Command/Install.php
deleted file mode 100644
index c035f6d20d..0000000000
--- a/3rdparty/PEAR/Command/Install.php
+++ /dev/null
@@ -1,1268 +0,0 @@
-
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Install.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Common.php';
-
-/**
- * PEAR commands for installation or deinstallation/upgrading of
- * packages.
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- */
-class PEAR_Command_Install extends PEAR_Command_Common
-{
- // {{{ properties
-
- var $commands = array(
- 'install' => array(
- 'summary' => 'Install Package',
- 'function' => 'doInstall',
- 'shortcut' => 'i',
- 'options' => array(
- 'force' => array(
- 'shortopt' => 'f',
- 'doc' => 'will overwrite newer installed packages',
- ),
- 'loose' => array(
- 'shortopt' => 'l',
- 'doc' => 'do not check for recommended dependency version',
- ),
- 'nodeps' => array(
- 'shortopt' => 'n',
- 'doc' => 'ignore dependencies, install anyway',
- ),
- 'register-only' => array(
- 'shortopt' => 'r',
- 'doc' => 'do not install files, only register the package as installed',
- ),
- 'soft' => array(
- 'shortopt' => 's',
- 'doc' => 'soft install, fail silently, or upgrade if already installed',
- ),
- 'nobuild' => array(
- 'shortopt' => 'B',
- 'doc' => 'don\'t build C extensions',
- ),
- 'nocompress' => array(
- 'shortopt' => 'Z',
- 'doc' => 'request uncompressed files when downloading',
- ),
- 'installroot' => array(
- 'shortopt' => 'R',
- 'arg' => 'DIR',
- 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT), use packagingroot for RPM',
- ),
- 'packagingroot' => array(
- 'shortopt' => 'P',
- 'arg' => 'DIR',
- 'doc' => 'root directory used when packaging files, like RPM packaging',
- ),
- 'ignore-errors' => array(
- 'doc' => 'force install even if there were errors',
- ),
- 'alldeps' => array(
- 'shortopt' => 'a',
- 'doc' => 'install all required and optional dependencies',
- ),
- 'onlyreqdeps' => array(
- 'shortopt' => 'o',
- 'doc' => 'install all required dependencies',
- ),
- 'offline' => array(
- 'shortopt' => 'O',
- 'doc' => 'do not attempt to download any urls or contact channels',
- ),
- 'pretend' => array(
- 'shortopt' => 'p',
- 'doc' => 'Only list the packages that would be downloaded',
- ),
- ),
- 'doc' => '[channel/] ...
-Installs one or more PEAR packages. You can specify a package to
-install in four ways:
-
-"Package-1.0.tgz" : installs from a local file
-
-"http://example.com/Package-1.0.tgz" : installs from
-anywhere on the net.
-
-"package.xml" : installs the package described in
-package.xml. Useful for testing, or for wrapping a PEAR package in
-another package manager such as RPM.
-
-"Package[-version/state][.tar]" : queries your default channel\'s server
-({config master_server}) and downloads the newest package with
-the preferred quality/state ({config preferred_state}).
-
-To retrieve Package version 1.1, use "Package-1.1," to retrieve
-Package state beta, use "Package-beta." To retrieve an uncompressed
-file, append .tar (make sure there is no file by the same name first)
-
-To download a package from another channel, prefix with the channel name like
-"channel/Package"
-
-More than one package may be specified at once. It is ok to mix these
-four ways of specifying packages.
-'),
- 'upgrade' => array(
- 'summary' => 'Upgrade Package',
- 'function' => 'doInstall',
- 'shortcut' => 'up',
- 'options' => array(
- 'channel' => array(
- 'shortopt' => 'c',
- 'doc' => 'upgrade packages from a specific channel',
- 'arg' => 'CHAN',
- ),
- 'force' => array(
- 'shortopt' => 'f',
- 'doc' => 'overwrite newer installed packages',
- ),
- 'loose' => array(
- 'shortopt' => 'l',
- 'doc' => 'do not check for recommended dependency version',
- ),
- 'nodeps' => array(
- 'shortopt' => 'n',
- 'doc' => 'ignore dependencies, upgrade anyway',
- ),
- 'register-only' => array(
- 'shortopt' => 'r',
- 'doc' => 'do not install files, only register the package as upgraded',
- ),
- 'nobuild' => array(
- 'shortopt' => 'B',
- 'doc' => 'don\'t build C extensions',
- ),
- 'nocompress' => array(
- 'shortopt' => 'Z',
- 'doc' => 'request uncompressed files when downloading',
- ),
- 'installroot' => array(
- 'shortopt' => 'R',
- 'arg' => 'DIR',
- 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)',
- ),
- 'ignore-errors' => array(
- 'doc' => 'force install even if there were errors',
- ),
- 'alldeps' => array(
- 'shortopt' => 'a',
- 'doc' => 'install all required and optional dependencies',
- ),
- 'onlyreqdeps' => array(
- 'shortopt' => 'o',
- 'doc' => 'install all required dependencies',
- ),
- 'offline' => array(
- 'shortopt' => 'O',
- 'doc' => 'do not attempt to download any urls or contact channels',
- ),
- 'pretend' => array(
- 'shortopt' => 'p',
- 'doc' => 'Only list the packages that would be downloaded',
- ),
- ),
- 'doc' => ' ...
-Upgrades one or more PEAR packages. See documentation for the
-"install" command for ways to specify a package.
-
-When upgrading, your package will be updated if the provided new
-package has a higher version number (use the -f option if you need to
-upgrade anyway).
-
-More than one package may be specified at once.
-'),
- 'upgrade-all' => array(
- 'summary' => 'Upgrade All Packages [Deprecated in favor of calling upgrade with no parameters]',
- 'function' => 'doUpgradeAll',
- 'shortcut' => 'ua',
- 'options' => array(
- 'channel' => array(
- 'shortopt' => 'c',
- 'doc' => 'upgrade packages from a specific channel',
- 'arg' => 'CHAN',
- ),
- 'nodeps' => array(
- 'shortopt' => 'n',
- 'doc' => 'ignore dependencies, upgrade anyway',
- ),
- 'register-only' => array(
- 'shortopt' => 'r',
- 'doc' => 'do not install files, only register the package as upgraded',
- ),
- 'nobuild' => array(
- 'shortopt' => 'B',
- 'doc' => 'don\'t build C extensions',
- ),
- 'nocompress' => array(
- 'shortopt' => 'Z',
- 'doc' => 'request uncompressed files when downloading',
- ),
- 'installroot' => array(
- 'shortopt' => 'R',
- 'arg' => 'DIR',
- 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT), use packagingroot for RPM',
- ),
- 'ignore-errors' => array(
- 'doc' => 'force install even if there were errors',
- ),
- 'loose' => array(
- 'doc' => 'do not check for recommended dependency version',
- ),
- ),
- 'doc' => '
-WARNING: This function is deprecated in favor of using the upgrade command with no params
-
-Upgrades all packages that have a newer release available. Upgrades are
-done only if there is a release available of the state specified in
-"preferred_state" (currently {config preferred_state}), or a state considered
-more stable.
-'),
- 'uninstall' => array(
- 'summary' => 'Un-install Package',
- 'function' => 'doUninstall',
- 'shortcut' => 'un',
- 'options' => array(
- 'nodeps' => array(
- 'shortopt' => 'n',
- 'doc' => 'ignore dependencies, uninstall anyway',
- ),
- 'register-only' => array(
- 'shortopt' => 'r',
- 'doc' => 'do not remove files, only register the packages as not installed',
- ),
- 'installroot' => array(
- 'shortopt' => 'R',
- 'arg' => 'DIR',
- 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)',
- ),
- 'ignore-errors' => array(
- 'doc' => 'force install even if there were errors',
- ),
- 'offline' => array(
- 'shortopt' => 'O',
- 'doc' => 'do not attempt to uninstall remotely',
- ),
- ),
- 'doc' => '[channel/] ...
-Uninstalls one or more PEAR packages. More than one package may be
-specified at once. Prefix with channel name to uninstall from a
-channel not in your default channel ({config default_channel})
-'),
- 'bundle' => array(
- 'summary' => 'Unpacks a Pecl Package',
- 'function' => 'doBundle',
- 'shortcut' => 'bun',
- 'options' => array(
- 'destination' => array(
- 'shortopt' => 'd',
- 'arg' => 'DIR',
- 'doc' => 'Optional destination directory for unpacking (defaults to current path or "ext" if exists)',
- ),
- 'force' => array(
- 'shortopt' => 'f',
- 'doc' => 'Force the unpacking even if there were errors in the package',
- ),
- ),
- 'doc' => '
-Unpacks a Pecl Package into the selected location. It will download the
-package if needed.
-'),
- 'run-scripts' => array(
- 'summary' => 'Run Post-Install Scripts bundled with a package',
- 'function' => 'doRunScripts',
- 'shortcut' => 'rs',
- 'options' => array(
- ),
- 'doc' => '
-Run post-installation scripts in package , if any exist.
-'),
- );
-
- // }}}
- // {{{ constructor
-
- /**
- * PEAR_Command_Install constructor.
- *
- * @access public
- */
- function PEAR_Command_Install(&$ui, &$config)
- {
- parent::PEAR_Command_Common($ui, $config);
- }
-
- // }}}
-
- /**
- * For unit testing purposes
- */
- function &getDownloader(&$ui, $options, &$config)
- {
- if (!class_exists('PEAR_Downloader')) {
- require_once 'PEAR/Downloader.php';
- }
- $a = &new PEAR_Downloader($ui, $options, $config);
- return $a;
- }
-
- /**
- * For unit testing purposes
- */
- function &getInstaller(&$ui)
- {
- if (!class_exists('PEAR_Installer')) {
- require_once 'PEAR/Installer.php';
- }
- $a = &new PEAR_Installer($ui);
- return $a;
- }
-
- function enableExtension($binaries, $type)
- {
- if (!($phpini = $this->config->get('php_ini', null, 'pear.php.net'))) {
- return PEAR::raiseError('configuration option "php_ini" is not set to php.ini location');
- }
- $ini = $this->_parseIni($phpini);
- if (PEAR::isError($ini)) {
- return $ini;
- }
- $line = 0;
- if ($type == 'extsrc' || $type == 'extbin') {
- $search = 'extensions';
- $enable = 'extension';
- } else {
- $search = 'zend_extensions';
- ob_start();
- phpinfo(INFO_GENERAL);
- $info = ob_get_contents();
- ob_end_clean();
- $debug = function_exists('leak') ? '_debug' : '';
- $ts = preg_match('/Thread Safety.+enabled/', $info) ? '_ts' : '';
- $enable = 'zend_extension' . $debug . $ts;
- }
- foreach ($ini[$search] as $line => $extension) {
- if (in_array($extension, $binaries, true) || in_array(
- $ini['extension_dir'] . DIRECTORY_SEPARATOR . $extension, $binaries, true)) {
- // already enabled - assume if one is, all are
- return true;
- }
- }
- if ($line) {
- $newini = array_slice($ini['all'], 0, $line);
- } else {
- $newini = array();
- }
- foreach ($binaries as $binary) {
- if ($ini['extension_dir']) {
- $binary = basename($binary);
- }
- $newini[] = $enable . '="' . $binary . '"' . (OS_UNIX ? "\n" : "\r\n");
- }
- $newini = array_merge($newini, array_slice($ini['all'], $line));
- $fp = @fopen($phpini, 'wb');
- if (!$fp) {
- return PEAR::raiseError('cannot open php.ini "' . $phpini . '" for writing');
- }
- foreach ($newini as $line) {
- fwrite($fp, $line);
- }
- fclose($fp);
- return true;
- }
-
- function disableExtension($binaries, $type)
- {
- if (!($phpini = $this->config->get('php_ini', null, 'pear.php.net'))) {
- return PEAR::raiseError('configuration option "php_ini" is not set to php.ini location');
- }
- $ini = $this->_parseIni($phpini);
- if (PEAR::isError($ini)) {
- return $ini;
- }
- $line = 0;
- if ($type == 'extsrc' || $type == 'extbin') {
- $search = 'extensions';
- $enable = 'extension';
- } else {
- $search = 'zend_extensions';
- ob_start();
- phpinfo(INFO_GENERAL);
- $info = ob_get_contents();
- ob_end_clean();
- $debug = function_exists('leak') ? '_debug' : '';
- $ts = preg_match('/Thread Safety.+enabled/', $info) ? '_ts' : '';
- $enable = 'zend_extension' . $debug . $ts;
- }
- $found = false;
- foreach ($ini[$search] as $line => $extension) {
- if (in_array($extension, $binaries, true) || in_array(
- $ini['extension_dir'] . DIRECTORY_SEPARATOR . $extension, $binaries, true)) {
- $found = true;
- break;
- }
- }
- if (!$found) {
- // not enabled
- return true;
- }
- $fp = @fopen($phpini, 'wb');
- if (!$fp) {
- return PEAR::raiseError('cannot open php.ini "' . $phpini . '" for writing');
- }
- if ($line) {
- $newini = array_slice($ini['all'], 0, $line);
- // delete the enable line
- $newini = array_merge($newini, array_slice($ini['all'], $line + 1));
- } else {
- $newini = array_slice($ini['all'], 1);
- }
- foreach ($newini as $line) {
- fwrite($fp, $line);
- }
- fclose($fp);
- return true;
- }
-
- function _parseIni($filename)
- {
- if (!file_exists($filename)) {
- return PEAR::raiseError('php.ini "' . $filename . '" does not exist');
- }
-
- if (filesize($filename) > 300000) {
- return PEAR::raiseError('php.ini "' . $filename . '" is too large, aborting');
- }
-
- ob_start();
- phpinfo(INFO_GENERAL);
- $info = ob_get_contents();
- ob_end_clean();
- $debug = function_exists('leak') ? '_debug' : '';
- $ts = preg_match('/Thread Safety.+enabled/', $info) ? '_ts' : '';
- $zend_extension_line = 'zend_extension' . $debug . $ts;
- $all = @file($filename);
- if (!$all) {
- return PEAR::raiseError('php.ini "' . $filename .'" could not be read');
- }
- $zend_extensions = $extensions = array();
- // assume this is right, but pull from the php.ini if it is found
- $extension_dir = ini_get('extension_dir');
- foreach ($all as $linenum => $line) {
- $line = trim($line);
- if (!$line) {
- continue;
- }
- if ($line[0] == ';') {
- continue;
- }
- if (strtolower(substr($line, 0, 13)) == 'extension_dir') {
- $line = trim(substr($line, 13));
- if ($line[0] == '=') {
- $x = trim(substr($line, 1));
- $x = explode(';', $x);
- $extension_dir = str_replace('"', '', array_shift($x));
- continue;
- }
- }
- if (strtolower(substr($line, 0, 9)) == 'extension') {
- $line = trim(substr($line, 9));
- if ($line[0] == '=') {
- $x = trim(substr($line, 1));
- $x = explode(';', $x);
- $extensions[$linenum] = str_replace('"', '', array_shift($x));
- continue;
- }
- }
- if (strtolower(substr($line, 0, strlen($zend_extension_line))) ==
- $zend_extension_line) {
- $line = trim(substr($line, strlen($zend_extension_line)));
- if ($line[0] == '=') {
- $x = trim(substr($line, 1));
- $x = explode(';', $x);
- $zend_extensions[$linenum] = str_replace('"', '', array_shift($x));
- continue;
- }
- }
- }
- return array(
- 'extensions' => $extensions,
- 'zend_extensions' => $zend_extensions,
- 'extension_dir' => $extension_dir,
- 'all' => $all,
- );
- }
-
- // {{{ doInstall()
-
- function doInstall($command, $options, $params)
- {
- if (!class_exists('PEAR_PackageFile')) {
- require_once 'PEAR/PackageFile.php';
- }
-
- if (isset($options['installroot']) && isset($options['packagingroot'])) {
- return $this->raiseError('ERROR: cannot use both --installroot and --packagingroot');
- }
-
- $reg = &$this->config->getRegistry();
- $channel = isset($options['channel']) ? $options['channel'] : $this->config->get('default_channel');
- if (!$reg->channelExists($channel)) {
- return $this->raiseError('Channel "' . $channel . '" does not exist');
- }
-
- if (empty($this->installer)) {
- $this->installer = &$this->getInstaller($this->ui);
- }
-
- if ($command == 'upgrade' || $command == 'upgrade-all') {
- // If people run the upgrade command but pass nothing, emulate a upgrade-all
- if ($command == 'upgrade' && empty($params)) {
- return $this->doUpgradeAll($command, $options, $params);
- }
- $options['upgrade'] = true;
- } else {
- $packages = $params;
- }
-
- $instreg = &$reg; // instreg used to check if package is installed
- if (isset($options['packagingroot']) && !isset($options['upgrade'])) {
- $packrootphp_dir = $this->installer->_prependPath(
- $this->config->get('php_dir', null, 'pear.php.net'),
- $options['packagingroot']);
- $instreg = new PEAR_Registry($packrootphp_dir); // other instreg!
-
- if ($this->config->get('verbose') > 2) {
- $this->ui->outputData('using package root: ' . $options['packagingroot']);
- }
- }
-
- $abstractpackages = $otherpackages = array();
- // parse params
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
-
- foreach ($params as $param) {
- if (strpos($param, 'http://') === 0) {
- $otherpackages[] = $param;
- continue;
- }
-
- if (strpos($param, 'channel://') === false && @file_exists($param)) {
- if (isset($options['force'])) {
- $otherpackages[] = $param;
- continue;
- }
-
- $pkg = new PEAR_PackageFile($this->config);
- $pf = $pkg->fromAnyFile($param, PEAR_VALIDATE_DOWNLOADING);
- if (PEAR::isError($pf)) {
- $otherpackages[] = $param;
- continue;
- }
-
- $exists = $reg->packageExists($pf->getPackage(), $pf->getChannel());
- $pversion = $reg->packageInfo($pf->getPackage(), 'version', $pf->getChannel());
- $version_compare = version_compare($pf->getVersion(), $pversion, '<=');
- if ($exists && $version_compare) {
- if ($this->config->get('verbose')) {
- $this->ui->outputData('Ignoring installed package ' .
- $reg->parsedPackageNameToString(
- array('package' => $pf->getPackage(),
- 'channel' => $pf->getChannel()), true));
- }
- continue;
- }
- $otherpackages[] = $param;
- continue;
- }
-
- $e = $reg->parsePackageName($param, $channel);
- if (PEAR::isError($e)) {
- $otherpackages[] = $param;
- } else {
- $abstractpackages[] = $e;
- }
- }
- PEAR::staticPopErrorHandling();
-
- // if there are any local package .tgz or remote static url, we can't
- // filter. The filter only works for abstract packages
- if (count($abstractpackages) && !isset($options['force'])) {
- // when not being forced, only do necessary upgrades/installs
- if (isset($options['upgrade'])) {
- $abstractpackages = $this->_filterUptodatePackages($abstractpackages, $command);
- } else {
- $count = count($abstractpackages);
- foreach ($abstractpackages as $i => $package) {
- if (isset($package['group'])) {
- // do not filter out install groups
- continue;
- }
-
- if ($instreg->packageExists($package['package'], $package['channel'])) {
- if ($count > 1) {
- if ($this->config->get('verbose')) {
- $this->ui->outputData('Ignoring installed package ' .
- $reg->parsedPackageNameToString($package, true));
- }
- unset($abstractpackages[$i]);
- } elseif ($count === 1) {
- // Lets try to upgrade it since it's already installed
- $options['upgrade'] = true;
- }
- }
- }
- }
- $abstractpackages =
- array_map(array($reg, 'parsedPackageNameToString'), $abstractpackages);
- } elseif (count($abstractpackages)) {
- $abstractpackages =
- array_map(array($reg, 'parsedPackageNameToString'), $abstractpackages);
- }
-
- $packages = array_merge($abstractpackages, $otherpackages);
- if (!count($packages)) {
- $c = '';
- if (isset($options['channel'])){
- $c .= ' in channel "' . $options['channel'] . '"';
- }
- $this->ui->outputData('Nothing to ' . $command . $c);
- return true;
- }
-
- $this->downloader = &$this->getDownloader($this->ui, $options, $this->config);
- $errors = $downloaded = $binaries = array();
- $downloaded = &$this->downloader->download($packages);
- if (PEAR::isError($downloaded)) {
- return $this->raiseError($downloaded);
- }
-
- $errors = $this->downloader->getErrorMsgs();
- if (count($errors)) {
- $err = array();
- $err['data'] = array();
- foreach ($errors as $error) {
- if ($error !== null) {
- $err['data'][] = array($error);
- }
- }
-
- if (!empty($err['data'])) {
- $err['headline'] = 'Install Errors';
- $this->ui->outputData($err);
- }
-
- if (!count($downloaded)) {
- return $this->raiseError("$command failed");
- }
- }
-
- $data = array(
- 'headline' => 'Packages that would be Installed'
- );
-
- if (isset($options['pretend'])) {
- foreach ($downloaded as $package) {
- $data['data'][] = array($reg->parsedPackageNameToString($package->getParsedPackage()));
- }
- $this->ui->outputData($data, 'pretend');
- return true;
- }
-
- $this->installer->setOptions($options);
- $this->installer->sortPackagesForInstall($downloaded);
- if (PEAR::isError($err = $this->installer->setDownloadedPackages($downloaded))) {
- $this->raiseError($err->getMessage());
- return true;
- }
-
- $binaries = $extrainfo = array();
- foreach ($downloaded as $param) {
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $info = $this->installer->install($param, $options);
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($info)) {
- $oldinfo = $info;
- $pkg = &$param->getPackageFile();
- if ($info->getCode() != PEAR_INSTALLER_NOBINARY) {
- if (!($info = $pkg->installBinary($this->installer))) {
- $this->ui->outputData('ERROR: ' .$oldinfo->getMessage());
- continue;
- }
-
- // we just installed a different package than requested,
- // let's change the param and info so that the rest of this works
- $param = $info[0];
- $info = $info[1];
- }
- }
-
- if (!is_array($info)) {
- return $this->raiseError("$command failed");
- }
-
- if ($param->getPackageType() == 'extsrc' ||
- $param->getPackageType() == 'extbin' ||
- $param->getPackageType() == 'zendextsrc' ||
- $param->getPackageType() == 'zendextbin'
- ) {
- $pkg = &$param->getPackageFile();
- if ($instbin = $pkg->getInstalledBinary()) {
- $instpkg = &$instreg->getPackage($instbin, $pkg->getChannel());
- } else {
- $instpkg = &$instreg->getPackage($pkg->getPackage(), $pkg->getChannel());
- }
-
- foreach ($instpkg->getFilelist() as $name => $atts) {
- $pinfo = pathinfo($atts['installed_as']);
- if (!isset($pinfo['extension']) ||
- in_array($pinfo['extension'], array('c', 'h'))
- ) {
- continue; // make sure we don't match php_blah.h
- }
-
- if ((strpos($pinfo['basename'], 'php_') === 0 &&
- $pinfo['extension'] == 'dll') ||
- // most unices
- $pinfo['extension'] == 'so' ||
- // hp-ux
- $pinfo['extension'] == 'sl') {
- $binaries[] = array($atts['installed_as'], $pinfo);
- break;
- }
- }
-
- if (count($binaries)) {
- foreach ($binaries as $pinfo) {
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $ret = $this->enableExtension(array($pinfo[0]), $param->getPackageType());
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($ret)) {
- $extrainfo[] = $ret->getMessage();
- if ($param->getPackageType() == 'extsrc' ||
- $param->getPackageType() == 'extbin') {
- $exttype = 'extension';
- } else {
- ob_start();
- phpinfo(INFO_GENERAL);
- $info = ob_get_contents();
- ob_end_clean();
- $debug = function_exists('leak') ? '_debug' : '';
- $ts = preg_match('/Thread Safety.+enabled/', $info) ? '_ts' : '';
- $exttype = 'zend_extension' . $debug . $ts;
- }
- $extrainfo[] = 'You should add "' . $exttype . '=' .
- $pinfo[1]['basename'] . '" to php.ini';
- } else {
- $extrainfo[] = 'Extension ' . $instpkg->getProvidesExtension() .
- ' enabled in php.ini';
- }
- }
- }
- }
-
- if ($this->config->get('verbose') > 0) {
- $chan = $param->getChannel();
- $label = $reg->parsedPackageNameToString(
- array(
- 'channel' => $chan,
- 'package' => $param->getPackage(),
- 'version' => $param->getVersion(),
- ));
- $out = array('data' => "$command ok: $label");
- if (isset($info['release_warnings'])) {
- $out['release_warnings'] = $info['release_warnings'];
- }
- $this->ui->outputData($out, $command);
-
- if (!isset($options['register-only']) && !isset($options['offline'])) {
- if ($this->config->isDefinedLayer('ftp')) {
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $info = $this->installer->ftpInstall($param);
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($info)) {
- $this->ui->outputData($info->getMessage());
- $this->ui->outputData("remote install failed: $label");
- } else {
- $this->ui->outputData("remote install ok: $label");
- }
- }
- }
- }
-
- $deps = $param->getDeps();
- if ($deps) {
- if (isset($deps['group'])) {
- $groups = $deps['group'];
- if (!isset($groups[0])) {
- $groups = array($groups);
- }
-
- foreach ($groups as $group) {
- if ($group['attribs']['name'] == 'default') {
- // default group is always installed, unless the user
- // explicitly chooses to install another group
- continue;
- }
- $extrainfo[] = $param->getPackage() . ': Optional feature ' .
- $group['attribs']['name'] . ' available (' .
- $group['attribs']['hint'] . ')';
- }
-
- $extrainfo[] = $param->getPackage() .
- ': To install optional features use "pear install ' .
- $reg->parsedPackageNameToString(
- array('package' => $param->getPackage(),
- 'channel' => $param->getChannel()), true) .
- '#featurename"';
- }
- }
-
- $pkg = &$instreg->getPackage($param->getPackage(), $param->getChannel());
- // $pkg may be NULL if install is a 'fake' install via --packagingroot
- if (is_object($pkg)) {
- $pkg->setConfig($this->config);
- if ($list = $pkg->listPostinstallScripts()) {
- $pn = $reg->parsedPackageNameToString(array('channel' =>
- $param->getChannel(), 'package' => $param->getPackage()), true);
- $extrainfo[] = $pn . ' has post-install scripts:';
- foreach ($list as $file) {
- $extrainfo[] = $file;
- }
- $extrainfo[] = $param->getPackage() .
- ': Use "pear run-scripts ' . $pn . '" to finish setup.';
- $extrainfo[] = 'DO NOT RUN SCRIPTS FROM UNTRUSTED SOURCES';
- }
- }
- }
-
- if (count($extrainfo)) {
- foreach ($extrainfo as $info) {
- $this->ui->outputData($info);
- }
- }
-
- return true;
- }
-
- // }}}
- // {{{ doUpgradeAll()
-
- function doUpgradeAll($command, $options, $params)
- {
- $reg = &$this->config->getRegistry();
- $upgrade = array();
-
- if (isset($options['channel'])) {
- $channels = array($options['channel']);
- } else {
- $channels = $reg->listChannels();
- }
-
- foreach ($channels as $channel) {
- if ($channel == '__uri') {
- continue;
- }
-
- // parse name with channel
- foreach ($reg->listPackages($channel) as $name) {
- $upgrade[] = $reg->parsedPackageNameToString(array(
- 'channel' => $channel,
- 'package' => $name
- ));
- }
- }
-
- $err = $this->doInstall($command, $options, $upgrade);
- if (PEAR::isError($err)) {
- $this->ui->outputData($err->getMessage(), $command);
- }
- }
-
- // }}}
- // {{{ doUninstall()
-
- function doUninstall($command, $options, $params)
- {
- if (count($params) < 1) {
- return $this->raiseError("Please supply the package(s) you want to uninstall");
- }
-
- if (empty($this->installer)) {
- $this->installer = &$this->getInstaller($this->ui);
- }
-
- if (isset($options['remoteconfig'])) {
- $e = $this->config->readFTPConfigFile($options['remoteconfig']);
- if (!PEAR::isError($e)) {
- $this->installer->setConfig($this->config);
- }
- }
-
- $reg = &$this->config->getRegistry();
- $newparams = array();
- $binaries = array();
- $badparams = array();
- foreach ($params as $pkg) {
- $channel = $this->config->get('default_channel');
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $parsed = $reg->parsePackageName($pkg, $channel);
- PEAR::staticPopErrorHandling();
- if (!$parsed || PEAR::isError($parsed)) {
- $badparams[] = $pkg;
- continue;
- }
- $package = $parsed['package'];
- $channel = $parsed['channel'];
- $info = &$reg->getPackage($package, $channel);
- if ($info === null &&
- ($channel == 'pear.php.net' || $channel == 'pecl.php.net')) {
- // make sure this isn't a package that has flipped from pear to pecl but
- // used a package.xml 1.0
- $testc = ($channel == 'pear.php.net') ? 'pecl.php.net' : 'pear.php.net';
- $info = &$reg->getPackage($package, $testc);
- if ($info !== null) {
- $channel = $testc;
- }
- }
- if ($info === null) {
- $badparams[] = $pkg;
- } else {
- $newparams[] = &$info;
- // check for binary packages (this is an alias for those packages if so)
- if ($installedbinary = $info->getInstalledBinary()) {
- $this->ui->log('adding binary package ' .
- $reg->parsedPackageNameToString(array('channel' => $channel,
- 'package' => $installedbinary), true));
- $newparams[] = &$reg->getPackage($installedbinary, $channel);
- }
- // add the contents of a dependency group to the list of installed packages
- if (isset($parsed['group'])) {
- $group = $info->getDependencyGroup($parsed['group']);
- if ($group) {
- $installed = $reg->getInstalledGroup($group);
- if ($installed) {
- foreach ($installed as $i => $p) {
- $newparams[] = &$installed[$i];
- }
- }
- }
- }
- }
- }
- $err = $this->installer->sortPackagesForUninstall($newparams);
- if (PEAR::isError($err)) {
- $this->ui->outputData($err->getMessage(), $command);
- return true;
- }
- $params = $newparams;
- // twist this to use it to check on whether dependent packages are also being uninstalled
- // for circular dependencies like subpackages
- $this->installer->setUninstallPackages($newparams);
- $params = array_merge($params, $badparams);
- $binaries = array();
- foreach ($params as $pkg) {
- $this->installer->pushErrorHandling(PEAR_ERROR_RETURN);
- if ($err = $this->installer->uninstall($pkg, $options)) {
- $this->installer->popErrorHandling();
- if (PEAR::isError($err)) {
- $this->ui->outputData($err->getMessage(), $command);
- continue;
- }
- if ($pkg->getPackageType() == 'extsrc' ||
- $pkg->getPackageType() == 'extbin' ||
- $pkg->getPackageType() == 'zendextsrc' ||
- $pkg->getPackageType() == 'zendextbin') {
- if ($instbin = $pkg->getInstalledBinary()) {
- continue; // this will be uninstalled later
- }
-
- foreach ($pkg->getFilelist() as $name => $atts) {
- $pinfo = pathinfo($atts['installed_as']);
- if (!isset($pinfo['extension']) ||
- in_array($pinfo['extension'], array('c', 'h'))) {
- continue; // make sure we don't match php_blah.h
- }
- if ((strpos($pinfo['basename'], 'php_') === 0 &&
- $pinfo['extension'] == 'dll') ||
- // most unices
- $pinfo['extension'] == 'so' ||
- // hp-ux
- $pinfo['extension'] == 'sl') {
- $binaries[] = array($atts['installed_as'], $pinfo);
- break;
- }
- }
- if (count($binaries)) {
- foreach ($binaries as $pinfo) {
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $ret = $this->disableExtension(array($pinfo[0]), $pkg->getPackageType());
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($ret)) {
- $extrainfo[] = $ret->getMessage();
- if ($pkg->getPackageType() == 'extsrc' ||
- $pkg->getPackageType() == 'extbin') {
- $exttype = 'extension';
- } else {
- ob_start();
- phpinfo(INFO_GENERAL);
- $info = ob_get_contents();
- ob_end_clean();
- $debug = function_exists('leak') ? '_debug' : '';
- $ts = preg_match('/Thread Safety.+enabled/', $info) ? '_ts' : '';
- $exttype = 'zend_extension' . $debug . $ts;
- }
- $this->ui->outputData('Unable to remove "' . $exttype . '=' .
- $pinfo[1]['basename'] . '" from php.ini', $command);
- } else {
- $this->ui->outputData('Extension ' . $pkg->getProvidesExtension() .
- ' disabled in php.ini', $command);
- }
- }
- }
- }
- $savepkg = $pkg;
- if ($this->config->get('verbose') > 0) {
- if (is_object($pkg)) {
- $pkg = $reg->parsedPackageNameToString($pkg);
- }
- $this->ui->outputData("uninstall ok: $pkg", $command);
- }
- if (!isset($options['offline']) && is_object($savepkg) &&
- defined('PEAR_REMOTEINSTALL_OK')) {
- if ($this->config->isDefinedLayer('ftp')) {
- $this->installer->pushErrorHandling(PEAR_ERROR_RETURN);
- $info = $this->installer->ftpUninstall($savepkg);
- $this->installer->popErrorHandling();
- if (PEAR::isError($info)) {
- $this->ui->outputData($info->getMessage());
- $this->ui->outputData("remote uninstall failed: $pkg");
- } else {
- $this->ui->outputData("remote uninstall ok: $pkg");
- }
- }
- }
- } else {
- $this->installer->popErrorHandling();
- if (!is_object($pkg)) {
- return $this->raiseError("uninstall failed: $pkg");
- }
- $pkg = $reg->parsedPackageNameToString($pkg);
- }
- }
-
- return true;
- }
-
- // }}}
-
-
- // }}}
- // {{{ doBundle()
- /*
- (cox) It just downloads and untars the package, does not do
- any check that the PEAR_Installer::_installFile() does.
- */
-
- function doBundle($command, $options, $params)
- {
- $opts = array(
- 'force' => true,
- 'nodeps' => true,
- 'soft' => true,
- 'downloadonly' => true
- );
- $downloader = &$this->getDownloader($this->ui, $opts, $this->config);
- $reg = &$this->config->getRegistry();
- if (count($params) < 1) {
- return $this->raiseError("Please supply the package you want to bundle");
- }
-
- if (isset($options['destination'])) {
- if (!is_dir($options['destination'])) {
- System::mkdir('-p ' . $options['destination']);
- }
- $dest = realpath($options['destination']);
- } else {
- $pwd = getcwd();
- $dir = $pwd . DIRECTORY_SEPARATOR . 'ext';
- $dest = is_dir($dir) ? $dir : $pwd;
- }
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $err = $downloader->setDownloadDir($dest);
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($err)) {
- return PEAR::raiseError('download directory "' . $dest .
- '" is not writeable.');
- }
- $result = &$downloader->download(array($params[0]));
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!isset($result[0])) {
- return $this->raiseError('unable to unpack ' . $params[0]);
- }
- $pkgfile = &$result[0]->getPackageFile();
- $pkgname = $pkgfile->getName();
- $pkgversion = $pkgfile->getVersion();
-
- // Unpacking -------------------------------------------------
- $dest .= DIRECTORY_SEPARATOR . $pkgname;
- $orig = $pkgname . '-' . $pkgversion;
-
- $tar = &new Archive_Tar($pkgfile->getArchiveFile());
- if (!$tar->extractModify($dest, $orig)) {
- return $this->raiseError('unable to unpack ' . $pkgfile->getArchiveFile());
- }
- $this->ui->outputData("Package ready at '$dest'");
- // }}}
- }
-
- // }}}
-
- function doRunScripts($command, $options, $params)
- {
- if (!isset($params[0])) {
- return $this->raiseError('run-scripts expects 1 parameter: a package name');
- }
-
- $reg = &$this->config->getRegistry();
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $parsed = $reg->parsePackageName($params[0], $this->config->get('default_channel'));
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($parsed)) {
- return $this->raiseError($parsed);
- }
-
- $package = &$reg->getPackage($parsed['package'], $parsed['channel']);
- if (!is_object($package)) {
- return $this->raiseError('Could not retrieve package "' . $params[0] . '" from registry');
- }
-
- $package->setConfig($this->config);
- $package->runPostinstallScripts();
- $this->ui->outputData('Install scripts complete', $command);
- return true;
- }
-
- /**
- * Given a list of packages, filter out those ones that are already up to date
- *
- * @param $packages: packages, in parsed array format !
- * @return list of packages that can be upgraded
- */
- function _filterUptodatePackages($packages, $command)
- {
- $reg = &$this->config->getRegistry();
- $latestReleases = array();
-
- $ret = array();
- foreach ($packages as $package) {
- if (isset($package['group'])) {
- $ret[] = $package;
- continue;
- }
-
- $channel = $package['channel'];
- $name = $package['package'];
- if (!$reg->packageExists($name, $channel)) {
- $ret[] = $package;
- continue;
- }
-
- if (!isset($latestReleases[$channel])) {
- // fill in cache for this channel
- $chan = &$reg->getChannel($channel);
- if (PEAR::isError($chan)) {
- return $this->raiseError($chan);
- }
-
- $base2 = false;
- $preferred_mirror = $this->config->get('preferred_mirror', null, $channel);
- if ($chan->supportsREST($preferred_mirror) &&
- (
- //($base2 = $chan->getBaseURL('REST1.4', $preferred_mirror)) ||
- ($base = $chan->getBaseURL('REST1.0', $preferred_mirror))
- )
- ) {
- $dorest = true;
- }
-
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- if (!isset($package['state'])) {
- $state = $this->config->get('preferred_state', null, $channel);
- } else {
- $state = $package['state'];
- }
-
- if ($dorest) {
- if ($base2) {
- $rest = &$this->config->getREST('1.4', array());
- $base = $base2;
- } else {
- $rest = &$this->config->getREST('1.0', array());
- }
-
- $installed = array_flip($reg->listPackages($channel));
- $latest = $rest->listLatestUpgrades($base, $state, $installed, $channel, $reg);
- }
-
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($latest)) {
- $this->ui->outputData('Error getting channel info from ' . $channel .
- ': ' . $latest->getMessage());
- continue;
- }
-
- $latestReleases[$channel] = array_change_key_case($latest);
- }
-
- // check package for latest release
- $name_lower = strtolower($name);
- if (isset($latestReleases[$channel][$name_lower])) {
- // if not set, up to date
- $inst_version = $reg->packageInfo($name, 'version', $channel);
- $channel_version = $latestReleases[$channel][$name_lower]['version'];
- if (version_compare($channel_version, $inst_version, 'le')) {
- // installed version is up-to-date
- continue;
- }
-
- // maintain BC
- if ($command == 'upgrade-all') {
- $this->ui->outputData(array('data' => 'Will upgrade ' .
- $reg->parsedPackageNameToString($package)), $command);
- }
- $ret[] = $package;
- }
- }
-
- return $ret;
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Install.xml b/3rdparty/PEAR/Command/Install.xml
deleted file mode 100644
index 1b1e933c22..0000000000
--- a/3rdparty/PEAR/Command/Install.xml
+++ /dev/null
@@ -1,276 +0,0 @@
-
-
- Install Package
- doInstall
- i
-
-
- f
- will overwrite newer installed packages
-
-
- l
- do not check for recommended dependency version
-
-
- n
- ignore dependencies, install anyway
-
-
- r
- do not install files, only register the package as installed
-
-
- s
- soft install, fail silently, or upgrade if already installed
-
-
- B
- don't build C extensions
-
-
- Z
- request uncompressed files when downloading
-
-
- R
- root directory used when installing files (ala PHP's INSTALL_ROOT), use packagingroot for RPM
- DIR
-
-
- P
- root directory used when packaging files, like RPM packaging
- DIR
-
-
-
- force install even if there were errors
-
-
- a
- install all required and optional dependencies
-
-
- o
- install all required dependencies
-
-
- O
- do not attempt to download any urls or contact channels
-
-
- p
- Only list the packages that would be downloaded
-
-
- [channel/]<package> ...
-Installs one or more PEAR packages. You can specify a package to
-install in four ways:
-
-"Package-1.0.tgz" : installs from a local file
-
-"http://example.com/Package-1.0.tgz" : installs from
-anywhere on the net.
-
-"package.xml" : installs the package described in
-package.xml. Useful for testing, or for wrapping a PEAR package in
-another package manager such as RPM.
-
-"Package[-version/state][.tar]" : queries your default channel's server
-({config master_server}) and downloads the newest package with
-the preferred quality/state ({config preferred_state}).
-
-To retrieve Package version 1.1, use "Package-1.1," to retrieve
-Package state beta, use "Package-beta." To retrieve an uncompressed
-file, append .tar (make sure there is no file by the same name first)
-
-To download a package from another channel, prefix with the channel name like
-"channel/Package"
-
-More than one package may be specified at once. It is ok to mix these
-four ways of specifying packages.
-
-
-
- Upgrade Package
- doInstall
- up
-
-
- c
- upgrade packages from a specific channel
- CHAN
-
-
- f
- overwrite newer installed packages
-
-
- l
- do not check for recommended dependency version
-
-
- n
- ignore dependencies, upgrade anyway
-
-
- r
- do not install files, only register the package as upgraded
-
-
- B
- don't build C extensions
-
-
- Z
- request uncompressed files when downloading
-
-
- R
- root directory used when installing files (ala PHP's INSTALL_ROOT)
- DIR
-
-
-
- force install even if there were errors
-
-
- a
- install all required and optional dependencies
-
-
- o
- install all required dependencies
-
-
- O
- do not attempt to download any urls or contact channels
-
-
- p
- Only list the packages that would be downloaded
-
-
- <package> ...
-Upgrades one or more PEAR packages. See documentation for the
-"install" command for ways to specify a package.
-
-When upgrading, your package will be updated if the provided new
-package has a higher version number (use the -f option if you need to
-upgrade anyway).
-
-More than one package may be specified at once.
-
-
-
- Upgrade All Packages [Deprecated in favor of calling upgrade with no parameters]
- doUpgradeAll
- ua
-
-
- c
- upgrade packages from a specific channel
- CHAN
-
-
- n
- ignore dependencies, upgrade anyway
-
-
- r
- do not install files, only register the package as upgraded
-
-
- B
- don't build C extensions
-
-
- Z
- request uncompressed files when downloading
-
-
- R
- root directory used when installing files (ala PHP's INSTALL_ROOT), use packagingroot for RPM
- DIR
-
-
-
- force install even if there were errors
-
-
-
- do not check for recommended dependency version
-
-
-
-WARNING: This function is deprecated in favor of using the upgrade command with no params
-
-Upgrades all packages that have a newer release available. Upgrades are
-done only if there is a release available of the state specified in
-"preferred_state" (currently {config preferred_state}), or a state considered
-more stable.
-
-
-
- Un-install Package
- doUninstall
- un
-
-
- n
- ignore dependencies, uninstall anyway
-
-
- r
- do not remove files, only register the packages as not installed
-
-
- R
- root directory used when installing files (ala PHP's INSTALL_ROOT)
- DIR
-
-
-
- force install even if there were errors
-
-
- O
- do not attempt to uninstall remotely
-
-
- [channel/]<package> ...
-Uninstalls one or more PEAR packages. More than one package may be
-specified at once. Prefix with channel name to uninstall from a
-channel not in your default channel ({config default_channel})
-
-
-
- Unpacks a Pecl Package
- doBundle
- bun
-
-
- d
- Optional destination directory for unpacking (defaults to current path or "ext" if exists)
- DIR
-
-
- f
- Force the unpacking even if there were errors in the package
-
-
- <package>
-Unpacks a Pecl Package into the selected location. It will download the
-package if needed.
-
-
-
- Run Post-Install Scripts bundled with a package
- doRunScripts
- rs
-
- <package>
-Run post-installation scripts in package <package>, if any exist.
-
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Mirror.php b/3rdparty/PEAR/Command/Mirror.php
deleted file mode 100644
index 4d157c6b88..0000000000
--- a/3rdparty/PEAR/Command/Mirror.php
+++ /dev/null
@@ -1,139 +0,0 @@
-
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Mirror.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 1.2.0
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Common.php';
-
-/**
- * PEAR commands for providing file mirrors
- *
- * @category pear
- * @package PEAR
- * @author Alexander Merz
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 1.2.0
- */
-class PEAR_Command_Mirror extends PEAR_Command_Common
-{
- var $commands = array(
- 'download-all' => array(
- 'summary' => 'Downloads each available package from the default channel',
- 'function' => 'doDownloadAll',
- 'shortcut' => 'da',
- 'options' => array(
- 'channel' =>
- array(
- 'shortopt' => 'c',
- 'doc' => 'specify a channel other than the default channel',
- 'arg' => 'CHAN',
- ),
- ),
- 'doc' => '
-Requests a list of available packages from the default channel ({config default_channel})
-and downloads them to current working directory. Note: only
-packages within preferred_state ({config preferred_state}) will be downloaded'
- ),
- );
-
- /**
- * PEAR_Command_Mirror constructor.
- *
- * @access public
- * @param object PEAR_Frontend a reference to an frontend
- * @param object PEAR_Config a reference to the configuration data
- */
- function PEAR_Command_Mirror(&$ui, &$config)
- {
- parent::PEAR_Command_Common($ui, $config);
- }
-
- /**
- * For unit-testing
- */
- function &factory($a)
- {
- $a = &PEAR_Command::factory($a, $this->config);
- return $a;
- }
-
- /**
- * retrieves a list of avaible Packages from master server
- * and downloads them
- *
- * @access public
- * @param string $command the command
- * @param array $options the command options before the command
- * @param array $params the stuff after the command name
- * @return bool true if succesful
- * @throw PEAR_Error
- */
- function doDownloadAll($command, $options, $params)
- {
- $savechannel = $this->config->get('default_channel');
- $reg = &$this->config->getRegistry();
- $channel = isset($options['channel']) ? $options['channel'] :
- $this->config->get('default_channel');
- if (!$reg->channelExists($channel)) {
- $this->config->set('default_channel', $savechannel);
- return $this->raiseError('Channel "' . $channel . '" does not exist');
- }
- $this->config->set('default_channel', $channel);
-
- $this->ui->outputData('Using Channel ' . $this->config->get('default_channel'));
- $chan = $reg->getChannel($channel);
- if (PEAR::isError($chan)) {
- return $this->raiseError($chan);
- }
-
- if ($chan->supportsREST($this->config->get('preferred_mirror')) &&
- $base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror'))) {
- $rest = &$this->config->getREST('1.0', array());
- $remoteInfo = array_flip($rest->listPackages($base, $channel));
- }
-
- if (PEAR::isError($remoteInfo)) {
- return $remoteInfo;
- }
-
- $cmd = &$this->factory("download");
- if (PEAR::isError($cmd)) {
- return $cmd;
- }
-
- $this->ui->outputData('Using Preferred State of ' .
- $this->config->get('preferred_state'));
- $this->ui->outputData('Gathering release information, please wait...');
-
- /**
- * Error handling not necessary, because already done by
- * the download command
- */
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $err = $cmd->run('download', array('downloadonly' => true), array_keys($remoteInfo));
- PEAR::staticPopErrorHandling();
- $this->config->set('default_channel', $savechannel);
- if (PEAR::isError($err)) {
- $this->ui->outputData($err->getMessage());
- }
-
- return true;
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Mirror.xml b/3rdparty/PEAR/Command/Mirror.xml
deleted file mode 100644
index fe8be9d03b..0000000000
--- a/3rdparty/PEAR/Command/Mirror.xml
+++ /dev/null
@@ -1,18 +0,0 @@
-
-
- Downloads each available package from the default channel
- doDownloadAll
- da
-
-
- c
- specify a channel other than the default channel
- CHAN
-
-
-
-Requests a list of available packages from the default channel ({config default_channel})
-and downloads them to current working directory. Note: only
-packages within preferred_state ({config preferred_state}) will be downloaded
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Package.php b/3rdparty/PEAR/Command/Package.php
deleted file mode 100644
index 81df7bf694..0000000000
--- a/3rdparty/PEAR/Command/Package.php
+++ /dev/null
@@ -1,1124 +0,0 @@
-
- * @author Martin Jansen
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Package.php 313024 2011-07-06 19:51:24Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Common.php';
-
-/**
- * PEAR commands for login/logout
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Martin Jansen
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: @package_version@
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- */
-
-class PEAR_Command_Package extends PEAR_Command_Common
-{
- var $commands = array(
- 'package' => array(
- 'summary' => 'Build Package',
- 'function' => 'doPackage',
- 'shortcut' => 'p',
- 'options' => array(
- 'nocompress' => array(
- 'shortopt' => 'Z',
- 'doc' => 'Do not gzip the package file'
- ),
- 'showname' => array(
- 'shortopt' => 'n',
- 'doc' => 'Print the name of the packaged file.',
- ),
- ),
- 'doc' => '[descfile] [descfile2]
-Creates a PEAR package from its description file (usually called
-package.xml). If a second packagefile is passed in, then
-the packager will check to make sure that one is a package.xml
-version 1.0, and the other is a package.xml version 2.0. The
-package.xml version 1.0 will be saved as "package.xml" in the archive,
-and the other as "package2.xml" in the archive"
-'
- ),
- 'package-validate' => array(
- 'summary' => 'Validate Package Consistency',
- 'function' => 'doPackageValidate',
- 'shortcut' => 'pv',
- 'options' => array(),
- 'doc' => '
-',
- ),
- 'cvsdiff' => array(
- 'summary' => 'Run a "cvs diff" for all files in a package',
- 'function' => 'doCvsDiff',
- 'shortcut' => 'cd',
- 'options' => array(
- 'quiet' => array(
- 'shortopt' => 'q',
- 'doc' => 'Be quiet',
- ),
- 'reallyquiet' => array(
- 'shortopt' => 'Q',
- 'doc' => 'Be really quiet',
- ),
- 'date' => array(
- 'shortopt' => 'D',
- 'doc' => 'Diff against revision of DATE',
- 'arg' => 'DATE',
- ),
- 'release' => array(
- 'shortopt' => 'R',
- 'doc' => 'Diff against tag for package release REL',
- 'arg' => 'REL',
- ),
- 'revision' => array(
- 'shortopt' => 'r',
- 'doc' => 'Diff against revision REV',
- 'arg' => 'REV',
- ),
- 'context' => array(
- 'shortopt' => 'c',
- 'doc' => 'Generate context diff',
- ),
- 'unified' => array(
- 'shortopt' => 'u',
- 'doc' => 'Generate unified diff',
- ),
- 'ignore-case' => array(
- 'shortopt' => 'i',
- 'doc' => 'Ignore case, consider upper- and lower-case letters equivalent',
- ),
- 'ignore-whitespace' => array(
- 'shortopt' => 'b',
- 'doc' => 'Ignore changes in amount of white space',
- ),
- 'ignore-blank-lines' => array(
- 'shortopt' => 'B',
- 'doc' => 'Ignore changes that insert or delete blank lines',
- ),
- 'brief' => array(
- 'doc' => 'Report only whether the files differ, no details',
- ),
- 'dry-run' => array(
- 'shortopt' => 'n',
- 'doc' => 'Don\'t do anything, just pretend',
- ),
- ),
- 'doc' => '
-Compares all the files in a package. Without any options, this
-command will compare the current code with the last checked-in code.
-Using the -r or -R option you may compare the current code with that
-of a specific release.
-',
- ),
- 'svntag' => array(
- 'summary' => 'Set SVN Release Tag',
- 'function' => 'doSvnTag',
- 'shortcut' => 'sv',
- 'options' => array(
- 'quiet' => array(
- 'shortopt' => 'q',
- 'doc' => 'Be quiet',
- ),
- 'slide' => array(
- 'shortopt' => 'F',
- 'doc' => 'Move (slide) tag if it exists',
- ),
- 'delete' => array(
- 'shortopt' => 'd',
- 'doc' => 'Remove tag',
- ),
- 'dry-run' => array(
- 'shortopt' => 'n',
- 'doc' => 'Don\'t do anything, just pretend',
- ),
- ),
- 'doc' => ' [files...]
- Sets a SVN tag on all files in a package. Use this command after you have
- packaged a distribution tarball with the "package" command to tag what
- revisions of what files were in that release. If need to fix something
- after running svntag once, but before the tarball is released to the public,
- use the "slide" option to move the release tag.
-
- to include files (such as a second package.xml, or tests not included in the
- release), pass them as additional parameters.
- ',
- ),
- 'cvstag' => array(
- 'summary' => 'Set CVS Release Tag',
- 'function' => 'doCvsTag',
- 'shortcut' => 'ct',
- 'options' => array(
- 'quiet' => array(
- 'shortopt' => 'q',
- 'doc' => 'Be quiet',
- ),
- 'reallyquiet' => array(
- 'shortopt' => 'Q',
- 'doc' => 'Be really quiet',
- ),
- 'slide' => array(
- 'shortopt' => 'F',
- 'doc' => 'Move (slide) tag if it exists',
- ),
- 'delete' => array(
- 'shortopt' => 'd',
- 'doc' => 'Remove tag',
- ),
- 'dry-run' => array(
- 'shortopt' => 'n',
- 'doc' => 'Don\'t do anything, just pretend',
- ),
- ),
- 'doc' => ' [files...]
-Sets a CVS tag on all files in a package. Use this command after you have
-packaged a distribution tarball with the "package" command to tag what
-revisions of what files were in that release. If need to fix something
-after running cvstag once, but before the tarball is released to the public,
-use the "slide" option to move the release tag.
-
-to include files (such as a second package.xml, or tests not included in the
-release), pass them as additional parameters.
-',
- ),
- 'package-dependencies' => array(
- 'summary' => 'Show package dependencies',
- 'function' => 'doPackageDependencies',
- 'shortcut' => 'pd',
- 'options' => array(),
- 'doc' => ' or or
-List all dependencies the package has.
-Can take a tgz / tar file, package.xml or a package name of an installed package.'
- ),
- 'sign' => array(
- 'summary' => 'Sign a package distribution file',
- 'function' => 'doSign',
- 'shortcut' => 'si',
- 'options' => array(
- 'verbose' => array(
- 'shortopt' => 'v',
- 'doc' => 'Display GnuPG output',
- ),
- ),
- 'doc' => '
-Signs a package distribution (.tar or .tgz) file with GnuPG.',
- ),
- 'makerpm' => array(
- 'summary' => 'Builds an RPM spec file from a PEAR package',
- 'function' => 'doMakeRPM',
- 'shortcut' => 'rpm',
- 'options' => array(
- 'spec-template' => array(
- 'shortopt' => 't',
- 'arg' => 'FILE',
- 'doc' => 'Use FILE as RPM spec file template'
- ),
- 'rpm-pkgname' => array(
- 'shortopt' => 'p',
- 'arg' => 'FORMAT',
- 'doc' => 'Use FORMAT as format string for RPM package name, %s is replaced
-by the PEAR package name, defaults to "PEAR::%s".',
- ),
- ),
- 'doc' => '
-
-Creates an RPM .spec file for wrapping a PEAR package inside an RPM
-package. Intended to be used from the SPECS directory, with the PEAR
-package tarball in the SOURCES directory:
-
-$ pear makerpm ../SOURCES/Net_Socket-1.0.tgz
-Wrote RPM spec file PEAR::Net_Geo-1.0.spec
-$ rpm -bb PEAR::Net_Socket-1.0.spec
-...
-Wrote: /usr/src/redhat/RPMS/i386/PEAR::Net_Socket-1.0-1.i386.rpm
-',
- ),
- 'convert' => array(
- 'summary' => 'Convert a package.xml 1.0 to package.xml 2.0 format',
- 'function' => 'doConvert',
- 'shortcut' => 'c2',
- 'options' => array(
- 'flat' => array(
- 'shortopt' => 'f',
- 'doc' => 'do not beautify the filelist.',
- ),
- ),
- 'doc' => '[descfile] [descfile2]
-Converts a package.xml in 1.0 format into a package.xml
-in 2.0 format. The new file will be named package2.xml by default,
-and package.xml will be used as the old file by default.
-This is not the most intelligent conversion, and should only be
-used for automated conversion or learning the format.
-'
- ),
- );
-
- var $output;
-
- /**
- * PEAR_Command_Package constructor.
- *
- * @access public
- */
- function PEAR_Command_Package(&$ui, &$config)
- {
- parent::PEAR_Command_Common($ui, $config);
- }
-
- function _displayValidationResults($err, $warn, $strict = false)
- {
- foreach ($err as $e) {
- $this->output .= "Error: $e\n";
- }
- foreach ($warn as $w) {
- $this->output .= "Warning: $w\n";
- }
- $this->output .= sprintf('Validation: %d error(s), %d warning(s)'."\n",
- sizeof($err), sizeof($warn));
- if ($strict && count($err) > 0) {
- $this->output .= "Fix these errors and try again.";
- return false;
- }
- return true;
- }
-
- function &getPackager()
- {
- if (!class_exists('PEAR_Packager')) {
- require_once 'PEAR/Packager.php';
- }
- $a = &new PEAR_Packager;
- return $a;
- }
-
- function &getPackageFile($config, $debug = false)
- {
- if (!class_exists('PEAR_Common')) {
- require_once 'PEAR/Common.php';
- }
- if (!class_exists('PEAR_PackageFile')) {
- require_once 'PEAR/PackageFile.php';
- }
- $a = &new PEAR_PackageFile($config, $debug);
- $common = new PEAR_Common;
- $common->ui = $this->ui;
- $a->setLogger($common);
- return $a;
- }
-
- function doPackage($command, $options, $params)
- {
- $this->output = '';
- $pkginfofile = isset($params[0]) ? $params[0] : 'package.xml';
- $pkg2 = isset($params[1]) ? $params[1] : null;
- if (!$pkg2 && !isset($params[0]) && file_exists('package2.xml')) {
- $pkg2 = 'package2.xml';
- }
-
- $packager = &$this->getPackager();
- $compress = empty($options['nocompress']) ? true : false;
- $result = $packager->package($pkginfofile, $compress, $pkg2);
- if (PEAR::isError($result)) {
- return $this->raiseError($result);
- }
-
- // Don't want output, only the package file name just created
- if (isset($options['showname'])) {
- $this->output = $result;
- }
-
- if ($this->output) {
- $this->ui->outputData($this->output, $command);
- }
-
- return true;
- }
-
- function doPackageValidate($command, $options, $params)
- {
- $this->output = '';
- if (count($params) < 1) {
- $params[0] = 'package.xml';
- }
-
- $obj = &$this->getPackageFile($this->config, $this->_debug);
- $obj->rawReturn();
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $info = $obj->fromTgzFile($params[0], PEAR_VALIDATE_NORMAL);
- if (PEAR::isError($info)) {
- $info = $obj->fromPackageFile($params[0], PEAR_VALIDATE_NORMAL);
- } else {
- $archive = $info->getArchiveFile();
- $tar = &new Archive_Tar($archive);
- $tar->extract(dirname($info->getPackageFile()));
- $info->setPackageFile(dirname($info->getPackageFile()) . DIRECTORY_SEPARATOR .
- $info->getPackage() . '-' . $info->getVersion() . DIRECTORY_SEPARATOR .
- basename($info->getPackageFile()));
- }
-
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($info)) {
- return $this->raiseError($info);
- }
-
- $valid = false;
- if ($info->getPackagexmlVersion() == '2.0') {
- if ($valid = $info->validate(PEAR_VALIDATE_NORMAL)) {
- $info->flattenFileList();
- $valid = $info->validate(PEAR_VALIDATE_PACKAGING);
- }
- } else {
- $valid = $info->validate(PEAR_VALIDATE_PACKAGING);
- }
-
- $err = $warn = array();
- if ($errors = $info->getValidationWarnings()) {
- foreach ($errors as $error) {
- if ($error['level'] == 'warning') {
- $warn[] = $error['message'];
- } else {
- $err[] = $error['message'];
- }
- }
- }
-
- $this->_displayValidationResults($err, $warn);
- $this->ui->outputData($this->output, $command);
- return true;
- }
-
- function doSvnTag($command, $options, $params)
- {
- $this->output = '';
- $_cmd = $command;
- if (count($params) < 1) {
- $help = $this->getHelp($command);
- return $this->raiseError("$command: missing parameter: $help[0]");
- }
-
- $packageFile = realpath($params[0]);
- $dir = dirname($packageFile);
- $dir = substr($dir, strrpos($dir, DIRECTORY_SEPARATOR) + 1);
- $obj = &$this->getPackageFile($this->config, $this->_debug);
- $info = $obj->fromAnyFile($packageFile, PEAR_VALIDATE_NORMAL);
- if (PEAR::isError($info)) {
- return $this->raiseError($info);
- }
-
- $err = $warn = array();
- if (!$info->validate()) {
- foreach ($info->getValidationWarnings() as $error) {
- if ($error['level'] == 'warning') {
- $warn[] = $error['message'];
- } else {
- $err[] = $error['message'];
- }
- }
- }
-
- if (!$this->_displayValidationResults($err, $warn, true)) {
- $this->ui->outputData($this->output, $command);
- return $this->raiseError('SVN tag failed');
- }
-
- $version = $info->getVersion();
- $package = $info->getName();
- $svntag = "$package-$version";
-
- if (isset($options['delete'])) {
- return $this->_svnRemoveTag($version, $package, $svntag, $packageFile, $options);
- }
-
- $path = $this->_svnFindPath($packageFile);
-
- // Check if there are any modified files
- $fp = popen('svn st --xml ' . dirname($packageFile), "r");
- $out = '';
- while ($line = fgets($fp, 1024)) {
- $out .= rtrim($line)."\n";
- }
- pclose($fp);
-
- if (!isset($options['quiet']) && strpos($out, 'item="modified"')) {
- $params = array(array(
- 'name' => 'modified',
- 'type' => 'yesno',
- 'default' => 'no',
- 'prompt' => 'You have files in your SVN checkout (' . $path['from'] . ') that have been modified but not commited, do you still want to tag ' . $version . '?',
- ));
- $answers = $this->ui->confirmDialog($params);
-
- if (!in_array($answers['modified'], array('y', 'yes', 'on', '1'))) {
- return true;
- }
- }
-
- if (isset($options['slide'])) {
- $this->_svnRemoveTag($version, $package, $svntag, $packageFile, $options);
- }
-
- // Check if tag already exists
- $releaseTag = $path['local']['base'] . 'tags' . DIRECTORY_SEPARATOR . $svntag;
- $existsCommand = 'svn ls ' . $path['base'] . 'tags/';
-
- $fp = popen($existsCommand, "r");
- $out = '';
- while ($line = fgets($fp, 1024)) {
- $out .= rtrim($line)."\n";
- }
- pclose($fp);
-
- if (in_array($svntag . DIRECTORY_SEPARATOR, explode("\n", $out))) {
- $this->ui->outputData($this->output, $command);
- return $this->raiseError('SVN tag ' . $svntag . ' for ' . $package . ' already exists.');
- } elseif (file_exists($path['local']['base'] . 'tags') === false) {
- return $this->raiseError('Can not locate the tags directory at ' . $path['local']['base'] . 'tags');
- } elseif (is_writeable($path['local']['base'] . 'tags') === false) {
- return $this->raiseError('Can not write to the tag directory at ' . $path['local']['base'] . 'tags');
- } else {
- $makeCommand = 'svn mkdir ' . $releaseTag;
- $this->output .= "+ $makeCommand\n";
- if (empty($options['dry-run'])) {
- // We need to create the tag dir.
- $fp = popen($makeCommand, "r");
- $out = '';
- while ($line = fgets($fp, 1024)) {
- $out .= rtrim($line)."\n";
- }
- pclose($fp);
- $this->output .= "$out\n";
- }
- }
-
- $command = 'svn';
- if (isset($options['quiet'])) {
- $command .= ' -q';
- }
-
- $command .= ' copy --parents ';
-
- $dir = dirname($packageFile);
- $dir = substr($dir, strrpos($dir, DIRECTORY_SEPARATOR) + 1);
- $files = array_keys($info->getFilelist());
- if (!in_array(basename($packageFile), $files)) {
- $files[] = basename($packageFile);
- }
-
- array_shift($params);
- if (count($params)) {
- // add in additional files to be tagged (package files and such)
- $files = array_merge($files, $params);
- }
-
- $commands = array();
- foreach ($files as $file) {
- if (!file_exists($file)) {
- $file = $dir . DIRECTORY_SEPARATOR . $file;
- }
- $commands[] = $command . ' ' . escapeshellarg($file) . ' ' .
- escapeshellarg($releaseTag . DIRECTORY_SEPARATOR . $file);
- }
-
- $this->output .= implode("\n", $commands) . "\n";
- if (empty($options['dry-run'])) {
- foreach ($commands as $command) {
- $fp = popen($command, "r");
- while ($line = fgets($fp, 1024)) {
- $this->output .= rtrim($line)."\n";
- }
- pclose($fp);
- }
- }
-
- $command = 'svn ci -m "Tagging the ' . $version . ' release" ' . $releaseTag . "\n";
- $this->output .= "+ $command\n";
- if (empty($options['dry-run'])) {
- $fp = popen($command, "r");
- while ($line = fgets($fp, 1024)) {
- $this->output .= rtrim($line)."\n";
- }
- pclose($fp);
- }
-
- $this->ui->outputData($this->output, $_cmd);
- return true;
- }
-
- function _svnFindPath($file)
- {
- $xml = '';
- $command = "svn info --xml $file";
- $fp = popen($command, "r");
- while ($line = fgets($fp, 1024)) {
- $xml .= rtrim($line)."\n";
- }
- pclose($fp);
- $url_tag = strpos($xml, '');
- $url = substr($xml, $url_tag + 5, strpos($xml, ' ', $url_tag + 5) - ($url_tag + 5));
-
- $path = array();
- $path['from'] = substr($url, 0, strrpos($url, '/'));
- $path['base'] = substr($path['from'], 0, strrpos($path['from'], '/') + 1);
-
- // Figure out the local paths - see http://pear.php.net/bugs/17463
- $pos = strpos($file, DIRECTORY_SEPARATOR . 'trunk' . DIRECTORY_SEPARATOR);
- if ($pos === false) {
- $pos = strpos($file, DIRECTORY_SEPARATOR . 'branches' . DIRECTORY_SEPARATOR);
- }
- $path['local']['base'] = substr($file, 0, $pos + 1);
-
- return $path;
- }
-
- function _svnRemoveTag($version, $package, $tag, $packageFile, $options)
- {
- $command = 'svn';
-
- if (isset($options['quiet'])) {
- $command .= ' -q';
- }
-
- $command .= ' remove';
- $command .= ' -m "Removing tag for the ' . $version . ' release."';
-
- $path = $this->_svnFindPath($packageFile);
- $command .= ' ' . $path['base'] . 'tags/' . $tag;
-
-
- if ($this->config->get('verbose') > 1) {
- $this->output .= "+ $command\n";
- }
-
- $this->output .= "+ $command\n";
- if (empty($options['dry-run'])) {
- $fp = popen($command, "r");
- while ($line = fgets($fp, 1024)) {
- $this->output .= rtrim($line)."\n";
- }
- pclose($fp);
- }
-
- $this->ui->outputData($this->output, $command);
- return true;
- }
-
- function doCvsTag($command, $options, $params)
- {
- $this->output = '';
- $_cmd = $command;
- if (count($params) < 1) {
- $help = $this->getHelp($command);
- return $this->raiseError("$command: missing parameter: $help[0]");
- }
-
- $packageFile = realpath($params[0]);
- $obj = &$this->getPackageFile($this->config, $this->_debug);
- $info = $obj->fromAnyFile($packageFile, PEAR_VALIDATE_NORMAL);
- if (PEAR::isError($info)) {
- return $this->raiseError($info);
- }
-
- $err = $warn = array();
- if (!$info->validate()) {
- foreach ($info->getValidationWarnings() as $error) {
- if ($error['level'] == 'warning') {
- $warn[] = $error['message'];
- } else {
- $err[] = $error['message'];
- }
- }
- }
-
- if (!$this->_displayValidationResults($err, $warn, true)) {
- $this->ui->outputData($this->output, $command);
- return $this->raiseError('CVS tag failed');
- }
-
- $version = $info->getVersion();
- $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $version);
- $cvstag = "RELEASE_$cvsversion";
- $files = array_keys($info->getFilelist());
- $command = 'cvs';
- if (isset($options['quiet'])) {
- $command .= ' -q';
- }
-
- if (isset($options['reallyquiet'])) {
- $command .= ' -Q';
- }
-
- $command .= ' tag';
- if (isset($options['slide'])) {
- $command .= ' -F';
- }
-
- if (isset($options['delete'])) {
- $command .= ' -d';
- }
-
- $command .= ' ' . $cvstag . ' ' . escapeshellarg($params[0]);
- array_shift($params);
- if (count($params)) {
- // add in additional files to be tagged
- $files = array_merge($files, $params);
- }
-
- $dir = dirname($packageFile);
- $dir = substr($dir, strrpos($dir, '/') + 1);
- foreach ($files as $file) {
- if (!file_exists($file)) {
- $file = $dir . DIRECTORY_SEPARATOR . $file;
- }
- $command .= ' ' . escapeshellarg($file);
- }
-
- if ($this->config->get('verbose') > 1) {
- $this->output .= "+ $command\n";
- }
-
- $this->output .= "+ $command\n";
- if (empty($options['dry-run'])) {
- $fp = popen($command, "r");
- while ($line = fgets($fp, 1024)) {
- $this->output .= rtrim($line)."\n";
- }
- pclose($fp);
- }
-
- $this->ui->outputData($this->output, $_cmd);
- return true;
- }
-
- function doCvsDiff($command, $options, $params)
- {
- $this->output = '';
- if (sizeof($params) < 1) {
- $help = $this->getHelp($command);
- return $this->raiseError("$command: missing parameter: $help[0]");
- }
-
- $file = realpath($params[0]);
- $obj = &$this->getPackageFile($this->config, $this->_debug);
- $info = $obj->fromAnyFile($file, PEAR_VALIDATE_NORMAL);
- if (PEAR::isError($info)) {
- return $this->raiseError($info);
- }
-
- $err = $warn = array();
- if (!$info->validate()) {
- foreach ($info->getValidationWarnings() as $error) {
- if ($error['level'] == 'warning') {
- $warn[] = $error['message'];
- } else {
- $err[] = $error['message'];
- }
- }
- }
-
- if (!$this->_displayValidationResults($err, $warn, true)) {
- $this->ui->outputData($this->output, $command);
- return $this->raiseError('CVS diff failed');
- }
-
- $info1 = $info->getFilelist();
- $files = $info1;
- $cmd = "cvs";
- if (isset($options['quiet'])) {
- $cmd .= ' -q';
- unset($options['quiet']);
- }
-
- if (isset($options['reallyquiet'])) {
- $cmd .= ' -Q';
- unset($options['reallyquiet']);
- }
-
- if (isset($options['release'])) {
- $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $options['release']);
- $cvstag = "RELEASE_$cvsversion";
- $options['revision'] = $cvstag;
- unset($options['release']);
- }
-
- $execute = true;
- if (isset($options['dry-run'])) {
- $execute = false;
- unset($options['dry-run']);
- }
-
- $cmd .= ' diff';
- // the rest of the options are passed right on to "cvs diff"
- foreach ($options as $option => $optarg) {
- $arg = $short = false;
- if (isset($this->commands[$command]['options'][$option])) {
- $arg = $this->commands[$command]['options'][$option]['arg'];
- $short = $this->commands[$command]['options'][$option]['shortopt'];
- }
- $cmd .= $short ? " -$short" : " --$option";
- if ($arg && $optarg) {
- $cmd .= ($short ? '' : '=') . escapeshellarg($optarg);
- }
- }
-
- foreach ($files as $file) {
- $cmd .= ' ' . escapeshellarg($file['name']);
- }
-
- if ($this->config->get('verbose') > 1) {
- $this->output .= "+ $cmd\n";
- }
-
- if ($execute) {
- $fp = popen($cmd, "r");
- while ($line = fgets($fp, 1024)) {
- $this->output .= rtrim($line)."\n";
- }
- pclose($fp);
- }
-
- $this->ui->outputData($this->output, $command);
- return true;
- }
-
- function doPackageDependencies($command, $options, $params)
- {
- // $params[0] -> the PEAR package to list its information
- if (count($params) !== 1) {
- return $this->raiseError("bad parameter(s), try \"help $command\"");
- }
-
- $obj = &$this->getPackageFile($this->config, $this->_debug);
- if (is_file($params[0]) || strpos($params[0], '.xml') > 0) {
- $info = $obj->fromAnyFile($params[0], PEAR_VALIDATE_NORMAL);
- } else {
- $reg = $this->config->getRegistry();
- $info = $obj->fromArray($reg->packageInfo($params[0]));
- }
-
- if (PEAR::isError($info)) {
- return $this->raiseError($info);
- }
-
- $deps = $info->getDeps();
- if (is_array($deps)) {
- if ($info->getPackagexmlVersion() == '1.0') {
- $data = array(
- 'caption' => 'Dependencies for pear/' . $info->getPackage(),
- 'border' => true,
- 'headline' => array("Required?", "Type", "Name", "Relation", "Version"),
- );
-
- foreach ($deps as $d) {
- if (isset($d['optional'])) {
- if ($d['optional'] == 'yes') {
- $req = 'No';
- } else {
- $req = 'Yes';
- }
- } else {
- $req = 'Yes';
- }
-
- if (isset($this->_deps_rel_trans[$d['rel']])) {
- $rel = $this->_deps_rel_trans[$d['rel']];
- } else {
- $rel = $d['rel'];
- }
-
- if (isset($this->_deps_type_trans[$d['type']])) {
- $type = ucfirst($this->_deps_type_trans[$d['type']]);
- } else {
- $type = $d['type'];
- }
-
- if (isset($d['name'])) {
- $name = $d['name'];
- } else {
- $name = '';
- }
-
- if (isset($d['version'])) {
- $version = $d['version'];
- } else {
- $version = '';
- }
-
- $data['data'][] = array($req, $type, $name, $rel, $version);
- }
- } else { // package.xml 2.0 dependencies display
- require_once 'PEAR/Dependency2.php';
- $deps = $info->getDependencies();
- $reg = &$this->config->getRegistry();
- if (is_array($deps)) {
- $d = new PEAR_Dependency2($this->config, array(), '');
- $data = array(
- 'caption' => 'Dependencies for ' . $info->getPackage(),
- 'border' => true,
- 'headline' => array("Required?", "Type", "Name", 'Versioning', 'Group'),
- );
- foreach ($deps as $type => $subd) {
- $req = ($type == 'required') ? 'Yes' : 'No';
- if ($type == 'group') {
- $group = $subd['attribs']['name'];
- } else {
- $group = '';
- }
-
- if (!isset($subd[0])) {
- $subd = array($subd);
- }
-
- foreach ($subd as $groupa) {
- foreach ($groupa as $deptype => $depinfo) {
- if ($deptype == 'attribs') {
- continue;
- }
-
- if ($deptype == 'pearinstaller') {
- $deptype = 'pear Installer';
- }
-
- if (!isset($depinfo[0])) {
- $depinfo = array($depinfo);
- }
-
- foreach ($depinfo as $inf) {
- $name = '';
- if (isset($inf['channel'])) {
- $alias = $reg->channelAlias($inf['channel']);
- if (!$alias) {
- $alias = '(channel?) ' .$inf['channel'];
- }
- $name = $alias . '/';
-
- }
- if (isset($inf['name'])) {
- $name .= $inf['name'];
- } elseif (isset($inf['pattern'])) {
- $name .= $inf['pattern'];
- } else {
- $name .= '';
- }
-
- if (isset($inf['uri'])) {
- $name .= ' [' . $inf['uri'] . ']';
- }
-
- if (isset($inf['conflicts'])) {
- $ver = 'conflicts';
- } else {
- $ver = $d->_getExtraString($inf);
- }
-
- $data['data'][] = array($req, ucfirst($deptype), $name,
- $ver, $group);
- }
- }
- }
- }
- }
- }
-
- $this->ui->outputData($data, $command);
- return true;
- }
-
- // Fallback
- $this->ui->outputData("This package does not have any dependencies.", $command);
- }
-
- function doSign($command, $options, $params)
- {
- // should move most of this code into PEAR_Packager
- // so it'll be easy to implement "pear package --sign"
- if (count($params) !== 1) {
- return $this->raiseError("bad parameter(s), try \"help $command\"");
- }
-
- require_once 'System.php';
- require_once 'Archive/Tar.php';
-
- if (!file_exists($params[0])) {
- return $this->raiseError("file does not exist: $params[0]");
- }
-
- $obj = $this->getPackageFile($this->config, $this->_debug);
- $info = $obj->fromTgzFile($params[0], PEAR_VALIDATE_NORMAL);
- if (PEAR::isError($info)) {
- return $this->raiseError($info);
- }
-
- $tar = new Archive_Tar($params[0]);
-
- $tmpdir = $this->config->get('temp_dir');
- $tmpdir = System::mktemp(' -t "' . $tmpdir . '" -d pearsign');
- if (!$tar->extractList('package2.xml package.xml package.sig', $tmpdir)) {
- return $this->raiseError("failed to extract tar file");
- }
-
- if (file_exists("$tmpdir/package.sig")) {
- return $this->raiseError("package already signed");
- }
-
- $packagexml = 'package.xml';
- if (file_exists("$tmpdir/package2.xml")) {
- $packagexml = 'package2.xml';
- }
-
- if (file_exists("$tmpdir/package.sig")) {
- unlink("$tmpdir/package.sig");
- }
-
- if (!file_exists("$tmpdir/$packagexml")) {
- return $this->raiseError("Extracted file $tmpdir/$packagexml not found.");
- }
-
- $input = $this->ui->userDialog($command,
- array('GnuPG Passphrase'),
- array('password'));
- if (!isset($input[0])) {
- //use empty passphrase
- $input[0] = '';
- }
-
- $devnull = (isset($options['verbose'])) ? '' : ' 2>/dev/null';
- $gpg = popen("gpg --batch --passphrase-fd 0 --armor --detach-sign --output $tmpdir/package.sig $tmpdir/$packagexml" . $devnull, "w");
- if (!$gpg) {
- return $this->raiseError("gpg command failed");
- }
-
- fwrite($gpg, "$input[0]\n");
- if (pclose($gpg) || !file_exists("$tmpdir/package.sig")) {
- return $this->raiseError("gpg sign failed");
- }
-
- if (!$tar->addModify("$tmpdir/package.sig", '', $tmpdir)) {
- return $this->raiseError('failed adding signature to file');
- }
-
- $this->ui->outputData("Package signed.", $command);
- return true;
- }
-
- /**
- * For unit testing purposes
- */
- function &getInstaller(&$ui)
- {
- if (!class_exists('PEAR_Installer')) {
- require_once 'PEAR/Installer.php';
- }
- $a = &new PEAR_Installer($ui);
- return $a;
- }
-
- /**
- * For unit testing purposes
- */
- function &getCommandPackaging(&$ui, &$config)
- {
- if (!class_exists('PEAR_Command_Packaging')) {
- if ($fp = @fopen('PEAR/Command/Packaging.php', 'r', true)) {
- fclose($fp);
- include_once 'PEAR/Command/Packaging.php';
- }
- }
-
- if (class_exists('PEAR_Command_Packaging')) {
- $a = &new PEAR_Command_Packaging($ui, $config);
- } else {
- $a = null;
- }
-
- return $a;
- }
-
- function doMakeRPM($command, $options, $params)
- {
-
- // Check to see if PEAR_Command_Packaging is installed, and
- // transparently switch to use the "make-rpm-spec" command from it
- // instead, if it does. Otherwise, continue to use the old version
- // of "makerpm" supplied with this package (PEAR).
- $packaging_cmd = $this->getCommandPackaging($this->ui, $this->config);
- if ($packaging_cmd !== null) {
- $this->ui->outputData('PEAR_Command_Packaging is installed; using '.
- 'newer "make-rpm-spec" command instead');
- return $packaging_cmd->run('make-rpm-spec', $options, $params);
- }
-
- $this->ui->outputData('WARNING: "pear makerpm" is no longer available; an '.
- 'improved version is available via "pear make-rpm-spec", which '.
- 'is available by installing PEAR_Command_Packaging');
- return true;
- }
-
- function doConvert($command, $options, $params)
- {
- $packagexml = isset($params[0]) ? $params[0] : 'package.xml';
- $newpackagexml = isset($params[1]) ? $params[1] : dirname($packagexml) .
- DIRECTORY_SEPARATOR . 'package2.xml';
- $pkg = &$this->getPackageFile($this->config, $this->_debug);
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $pf = $pkg->fromPackageFile($packagexml, PEAR_VALIDATE_NORMAL);
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($pf)) {
- if (is_array($pf->getUserInfo())) {
- foreach ($pf->getUserInfo() as $warning) {
- $this->ui->outputData($warning['message']);
- }
- }
- return $this->raiseError($pf);
- }
-
- if (is_a($pf, 'PEAR_PackageFile_v2')) {
- $this->ui->outputData($packagexml . ' is already a package.xml version 2.0');
- return true;
- }
-
- $gen = &$pf->getDefaultGenerator();
- $newpf = &$gen->toV2();
- $newpf->setPackagefile($newpackagexml);
- $gen = &$newpf->getDefaultGenerator();
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $state = (isset($options['flat']) ? PEAR_VALIDATE_PACKAGING : PEAR_VALIDATE_NORMAL);
- $saved = $gen->toPackageFile(dirname($newpackagexml), $state, basename($newpackagexml));
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($saved)) {
- if (is_array($saved->getUserInfo())) {
- foreach ($saved->getUserInfo() as $warning) {
- $this->ui->outputData($warning['message']);
- }
- }
-
- $this->ui->outputData($saved->getMessage());
- return true;
- }
-
- $this->ui->outputData('Wrote new version 2.0 package.xml to "' . $saved . '"');
- return true;
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Package.xml b/3rdparty/PEAR/Command/Package.xml
deleted file mode 100644
index d1aff9d48d..0000000000
--- a/3rdparty/PEAR/Command/Package.xml
+++ /dev/null
@@ -1,237 +0,0 @@
-
-
- Build Package
- doPackage
- p
-
-
- Z
- Do not gzip the package file
-
-
- n
- Print the name of the packaged file.
-
-
- [descfile] [descfile2]
-Creates a PEAR package from its description file (usually called
-package.xml). If a second packagefile is passed in, then
-the packager will check to make sure that one is a package.xml
-version 1.0, and the other is a package.xml version 2.0. The
-package.xml version 1.0 will be saved as "package.xml" in the archive,
-and the other as "package2.xml" in the archive"
-
-
-
- Validate Package Consistency
- doPackageValidate
- pv
-
-
-
-
-
- Run a "cvs diff" for all files in a package
- doCvsDiff
- cd
-
-
- q
- Be quiet
-
-
- Q
- Be really quiet
-
-
- D
- Diff against revision of DATE
- DATE
-
-
- R
- Diff against tag for package release REL
- REL
-
-
- r
- Diff against revision REV
- REV
-
-
- c
- Generate context diff
-
-
- u
- Generate unified diff
-
-
- i
- Ignore case, consider upper- and lower-case letters equivalent
-
-
- b
- Ignore changes in amount of white space
-
-
- B
- Ignore changes that insert or delete blank lines
-
-
-
- Report only whether the files differ, no details
-
-
- n
- Don't do anything, just pretend
-
-
- <package.xml>
-Compares all the files in a package. Without any options, this
-command will compare the current code with the last checked-in code.
-Using the -r or -R option you may compare the current code with that
-of a specific release.
-
-
-
- Set SVN Release Tag
- doSvnTag
- sv
-
-
- q
- Be quiet
-
-
- F
- Move (slide) tag if it exists
-
-
- d
- Remove tag
-
-
- n
- Don't do anything, just pretend
-
-
- <package.xml> [files...]
- Sets a SVN tag on all files in a package. Use this command after you have
- packaged a distribution tarball with the "package" command to tag what
- revisions of what files were in that release. If need to fix something
- after running svntag once, but before the tarball is released to the public,
- use the "slide" option to move the release tag.
-
- to include files (such as a second package.xml, or tests not included in the
- release), pass them as additional parameters.
-
-
-
- Set CVS Release Tag
- doCvsTag
- ct
-
-
- q
- Be quiet
-
-
- Q
- Be really quiet
-
-
- F
- Move (slide) tag if it exists
-
-
- d
- Remove tag
-
-
- n
- Don't do anything, just pretend
-
-
- <package.xml> [files...]
-Sets a CVS tag on all files in a package. Use this command after you have
-packaged a distribution tarball with the "package" command to tag what
-revisions of what files were in that release. If need to fix something
-after running cvstag once, but before the tarball is released to the public,
-use the "slide" option to move the release tag.
-
-to include files (such as a second package.xml, or tests not included in the
-release), pass them as additional parameters.
-
-
-
- Show package dependencies
- doPackageDependencies
- pd
-
- <package-file> or <package.xml> or <install-package-name>
-List all dependencies the package has.
-Can take a tgz / tar file, package.xml or a package name of an installed package.
-
-
- Sign a package distribution file
- doSign
- si
-
-
- v
- Display GnuPG output
-
-
- <package-file>
-Signs a package distribution (.tar or .tgz) file with GnuPG.
-
-
- Builds an RPM spec file from a PEAR package
- doMakeRPM
- rpm
-
-
- t
- Use FILE as RPM spec file template
- FILE
-
-
- p
- Use FORMAT as format string for RPM package name, %s is replaced
-by the PEAR package name, defaults to "PEAR::%s".
- FORMAT
-
-
- <package-file>
-
-Creates an RPM .spec file for wrapping a PEAR package inside an RPM
-package. Intended to be used from the SPECS directory, with the PEAR
-package tarball in the SOURCES directory:
-
-$ pear makerpm ../SOURCES/Net_Socket-1.0.tgz
-Wrote RPM spec file PEAR::Net_Geo-1.0.spec
-$ rpm -bb PEAR::Net_Socket-1.0.spec
-...
-Wrote: /usr/src/redhat/RPMS/i386/PEAR::Net_Socket-1.0-1.i386.rpm
-
-
-
- Convert a package.xml 1.0 to package.xml 2.0 format
- doConvert
- c2
-
-
- f
- do not beautify the filelist.
-
-
- [descfile] [descfile2]
-Converts a package.xml in 1.0 format into a package.xml
-in 2.0 format. The new file will be named package2.xml by default,
-and package.xml will be used as the old file by default.
-This is not the most intelligent conversion, and should only be
-used for automated conversion or learning the format.
-
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Pickle.php b/3rdparty/PEAR/Command/Pickle.php
deleted file mode 100644
index 87aa25ea30..0000000000
--- a/3rdparty/PEAR/Command/Pickle.php
+++ /dev/null
@@ -1,421 +0,0 @@
-
- * @copyright 2005-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Pickle.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 1.4.1
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Common.php';
-
-/**
- * PEAR commands for login/logout
- *
- * @category pear
- * @package PEAR
- * @author Greg Beaver
- * @copyright 2005-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 1.4.1
- */
-
-class PEAR_Command_Pickle extends PEAR_Command_Common
-{
- var $commands = array(
- 'pickle' => array(
- 'summary' => 'Build PECL Package',
- 'function' => 'doPackage',
- 'shortcut' => 'pi',
- 'options' => array(
- 'nocompress' => array(
- 'shortopt' => 'Z',
- 'doc' => 'Do not gzip the package file'
- ),
- 'showname' => array(
- 'shortopt' => 'n',
- 'doc' => 'Print the name of the packaged file.',
- ),
- ),
- 'doc' => '[descfile]
-Creates a PECL package from its package2.xml file.
-
-An automatic conversion will be made to a package.xml 1.0 and written out to
-disk in the current directory as "package.xml". Note that
-only simple package.xml 2.0 will be converted. package.xml 2.0 with:
-
- - dependency types other than required/optional PECL package/ext/php/pearinstaller
- - more than one extsrcrelease or zendextsrcrelease
- - zendextbinrelease, extbinrelease, phprelease, or bundle release type
- - dependency groups
- - ignore tags in release filelist
- - tasks other than replace
- - custom roles
-
-will cause pickle to fail, and output an error message. If your package2.xml
-uses any of these features, you are best off using PEAR_PackageFileManager to
-generate both package.xml.
-'
- ),
- );
-
- /**
- * PEAR_Command_Package constructor.
- *
- * @access public
- */
- function PEAR_Command_Pickle(&$ui, &$config)
- {
- parent::PEAR_Command_Common($ui, $config);
- }
-
- /**
- * For unit-testing ease
- *
- * @return PEAR_Packager
- */
- function &getPackager()
- {
- if (!class_exists('PEAR_Packager')) {
- require_once 'PEAR/Packager.php';
- }
-
- $a = &new PEAR_Packager;
- return $a;
- }
-
- /**
- * For unit-testing ease
- *
- * @param PEAR_Config $config
- * @param bool $debug
- * @param string|null $tmpdir
- * @return PEAR_PackageFile
- */
- function &getPackageFile($config, $debug = false)
- {
- if (!class_exists('PEAR_Common')) {
- require_once 'PEAR/Common.php';
- }
-
- if (!class_exists('PEAR_PackageFile')) {
- require_once 'PEAR/PackageFile.php';
- }
-
- $a = &new PEAR_PackageFile($config, $debug);
- $common = new PEAR_Common;
- $common->ui = $this->ui;
- $a->setLogger($common);
- return $a;
- }
-
- function doPackage($command, $options, $params)
- {
- $this->output = '';
- $pkginfofile = isset($params[0]) ? $params[0] : 'package2.xml';
- $packager = &$this->getPackager();
- if (PEAR::isError($err = $this->_convertPackage($pkginfofile))) {
- return $err;
- }
-
- $compress = empty($options['nocompress']) ? true : false;
- $result = $packager->package($pkginfofile, $compress, 'package.xml');
- if (PEAR::isError($result)) {
- return $this->raiseError($result);
- }
-
- // Don't want output, only the package file name just created
- if (isset($options['showname'])) {
- $this->ui->outputData($result, $command);
- }
-
- return true;
- }
-
- function _convertPackage($packagexml)
- {
- $pkg = &$this->getPackageFile($this->config);
- $pf2 = &$pkg->fromPackageFile($packagexml, PEAR_VALIDATE_NORMAL);
- if (!is_a($pf2, 'PEAR_PackageFile_v2')) {
- return $this->raiseError('Cannot process "' .
- $packagexml . '", is not a package.xml 2.0');
- }
-
- require_once 'PEAR/PackageFile/v1.php';
- $pf = new PEAR_PackageFile_v1;
- $pf->setConfig($this->config);
- if ($pf2->getPackageType() != 'extsrc' && $pf2->getPackageType() != 'zendextsrc') {
- return $this->raiseError('Cannot safely convert "' . $packagexml .
- '", is not an extension source package. Using a PEAR_PackageFileManager-based ' .
- 'script is an option');
- }
-
- if (is_array($pf2->getUsesRole())) {
- return $this->raiseError('Cannot safely convert "' . $packagexml .
- '", contains custom roles. Using a PEAR_PackageFileManager-based script or ' .
- 'the convert command is an option');
- }
-
- if (is_array($pf2->getUsesTask())) {
- return $this->raiseError('Cannot safely convert "' . $packagexml .
- '", contains custom tasks. Using a PEAR_PackageFileManager-based script or ' .
- 'the convert command is an option');
- }
-
- $deps = $pf2->getDependencies();
- if (isset($deps['group'])) {
- return $this->raiseError('Cannot safely convert "' . $packagexml .
- '", contains dependency groups. Using a PEAR_PackageFileManager-based script ' .
- 'or the convert command is an option');
- }
-
- if (isset($deps['required']['subpackage']) ||
- isset($deps['optional']['subpackage'])) {
- return $this->raiseError('Cannot safely convert "' . $packagexml .
- '", contains subpackage dependencies. Using a PEAR_PackageFileManager-based '.
- 'script is an option');
- }
-
- if (isset($deps['required']['os'])) {
- return $this->raiseError('Cannot safely convert "' . $packagexml .
- '", contains os dependencies. Using a PEAR_PackageFileManager-based '.
- 'script is an option');
- }
-
- if (isset($deps['required']['arch'])) {
- return $this->raiseError('Cannot safely convert "' . $packagexml .
- '", contains arch dependencies. Using a PEAR_PackageFileManager-based '.
- 'script is an option');
- }
-
- $pf->setPackage($pf2->getPackage());
- $pf->setSummary($pf2->getSummary());
- $pf->setDescription($pf2->getDescription());
- foreach ($pf2->getMaintainers() as $maintainer) {
- $pf->addMaintainer($maintainer['role'], $maintainer['handle'],
- $maintainer['name'], $maintainer['email']);
- }
-
- $pf->setVersion($pf2->getVersion());
- $pf->setDate($pf2->getDate());
- $pf->setLicense($pf2->getLicense());
- $pf->setState($pf2->getState());
- $pf->setNotes($pf2->getNotes());
- $pf->addPhpDep($deps['required']['php']['min'], 'ge');
- if (isset($deps['required']['php']['max'])) {
- $pf->addPhpDep($deps['required']['php']['max'], 'le');
- }
-
- if (isset($deps['required']['package'])) {
- if (!isset($deps['required']['package'][0])) {
- $deps['required']['package'] = array($deps['required']['package']);
- }
-
- foreach ($deps['required']['package'] as $dep) {
- if (!isset($dep['channel'])) {
- return $this->raiseError('Cannot safely convert "' . $packagexml . '"' .
- ' contains uri-based dependency on a package. Using a ' .
- 'PEAR_PackageFileManager-based script is an option');
- }
-
- if ($dep['channel'] != 'pear.php.net'
- && $dep['channel'] != 'pecl.php.net'
- && $dep['channel'] != 'doc.php.net') {
- return $this->raiseError('Cannot safely convert "' . $packagexml . '"' .
- ' contains dependency on a non-standard channel package. Using a ' .
- 'PEAR_PackageFileManager-based script is an option');
- }
-
- if (isset($dep['conflicts'])) {
- return $this->raiseError('Cannot safely convert "' . $packagexml . '"' .
- ' contains conflicts dependency. Using a ' .
- 'PEAR_PackageFileManager-based script is an option');
- }
-
- if (isset($dep['exclude'])) {
- $this->ui->outputData('WARNING: exclude tags are ignored in conversion');
- }
-
- if (isset($dep['min'])) {
- $pf->addPackageDep($dep['name'], $dep['min'], 'ge');
- }
-
- if (isset($dep['max'])) {
- $pf->addPackageDep($dep['name'], $dep['max'], 'le');
- }
- }
- }
-
- if (isset($deps['required']['extension'])) {
- if (!isset($deps['required']['extension'][0])) {
- $deps['required']['extension'] = array($deps['required']['extension']);
- }
-
- foreach ($deps['required']['extension'] as $dep) {
- if (isset($dep['conflicts'])) {
- return $this->raiseError('Cannot safely convert "' . $packagexml . '"' .
- ' contains conflicts dependency. Using a ' .
- 'PEAR_PackageFileManager-based script is an option');
- }
-
- if (isset($dep['exclude'])) {
- $this->ui->outputData('WARNING: exclude tags are ignored in conversion');
- }
-
- if (isset($dep['min'])) {
- $pf->addExtensionDep($dep['name'], $dep['min'], 'ge');
- }
-
- if (isset($dep['max'])) {
- $pf->addExtensionDep($dep['name'], $dep['max'], 'le');
- }
- }
- }
-
- if (isset($deps['optional']['package'])) {
- if (!isset($deps['optional']['package'][0])) {
- $deps['optional']['package'] = array($deps['optional']['package']);
- }
-
- foreach ($deps['optional']['package'] as $dep) {
- if (!isset($dep['channel'])) {
- return $this->raiseError('Cannot safely convert "' . $packagexml . '"' .
- ' contains uri-based dependency on a package. Using a ' .
- 'PEAR_PackageFileManager-based script is an option');
- }
-
- if ($dep['channel'] != 'pear.php.net'
- && $dep['channel'] != 'pecl.php.net'
- && $dep['channel'] != 'doc.php.net') {
- return $this->raiseError('Cannot safely convert "' . $packagexml . '"' .
- ' contains dependency on a non-standard channel package. Using a ' .
- 'PEAR_PackageFileManager-based script is an option');
- }
-
- if (isset($dep['exclude'])) {
- $this->ui->outputData('WARNING: exclude tags are ignored in conversion');
- }
-
- if (isset($dep['min'])) {
- $pf->addPackageDep($dep['name'], $dep['min'], 'ge', 'yes');
- }
-
- if (isset($dep['max'])) {
- $pf->addPackageDep($dep['name'], $dep['max'], 'le', 'yes');
- }
- }
- }
-
- if (isset($deps['optional']['extension'])) {
- if (!isset($deps['optional']['extension'][0])) {
- $deps['optional']['extension'] = array($deps['optional']['extension']);
- }
-
- foreach ($deps['optional']['extension'] as $dep) {
- if (isset($dep['exclude'])) {
- $this->ui->outputData('WARNING: exclude tags are ignored in conversion');
- }
-
- if (isset($dep['min'])) {
- $pf->addExtensionDep($dep['name'], $dep['min'], 'ge', 'yes');
- }
-
- if (isset($dep['max'])) {
- $pf->addExtensionDep($dep['name'], $dep['max'], 'le', 'yes');
- }
- }
- }
-
- $contents = $pf2->getContents();
- $release = $pf2->getReleases();
- if (isset($releases[0])) {
- return $this->raiseError('Cannot safely process "' . $packagexml . '" contains '
- . 'multiple extsrcrelease/zendextsrcrelease tags. Using a PEAR_PackageFileManager-based script ' .
- 'or the convert command is an option');
- }
-
- if ($configoptions = $pf2->getConfigureOptions()) {
- foreach ($configoptions as $option) {
- $default = isset($option['default']) ? $option['default'] : false;
- $pf->addConfigureOption($option['name'], $option['prompt'], $default);
- }
- }
-
- if (isset($release['filelist']['ignore'])) {
- return $this->raiseError('Cannot safely process "' . $packagexml . '" contains '
- . 'ignore tags. Using a PEAR_PackageFileManager-based script or the convert' .
- ' command is an option');
- }
-
- if (isset($release['filelist']['install']) &&
- !isset($release['filelist']['install'][0])) {
- $release['filelist']['install'] = array($release['filelist']['install']);
- }
-
- if (isset($contents['dir']['attribs']['baseinstalldir'])) {
- $baseinstalldir = $contents['dir']['attribs']['baseinstalldir'];
- } else {
- $baseinstalldir = false;
- }
-
- if (!isset($contents['dir']['file'][0])) {
- $contents['dir']['file'] = array($contents['dir']['file']);
- }
-
- foreach ($contents['dir']['file'] as $file) {
- if ($baseinstalldir && !isset($file['attribs']['baseinstalldir'])) {
- $file['attribs']['baseinstalldir'] = $baseinstalldir;
- }
-
- $processFile = $file;
- unset($processFile['attribs']);
- if (count($processFile)) {
- foreach ($processFile as $name => $task) {
- if ($name != $pf2->getTasksNs() . ':replace') {
- return $this->raiseError('Cannot safely process "' . $packagexml .
- '" contains tasks other than replace. Using a ' .
- 'PEAR_PackageFileManager-based script is an option.');
- }
- $file['attribs']['replace'][] = $task;
- }
- }
-
- if (!in_array($file['attribs']['role'], PEAR_Common::getFileRoles())) {
- return $this->raiseError('Cannot safely convert "' . $packagexml .
- '", contains custom roles. Using a PEAR_PackageFileManager-based script ' .
- 'or the convert command is an option');
- }
-
- if (isset($release['filelist']['install'])) {
- foreach ($release['filelist']['install'] as $installas) {
- if ($installas['attribs']['name'] == $file['attribs']['name']) {
- $file['attribs']['install-as'] = $installas['attribs']['as'];
- }
- }
- }
-
- $pf->addFile('/', $file['attribs']['name'], $file['attribs']);
- }
-
- if ($pf2->getChangeLog()) {
- $this->ui->outputData('WARNING: changelog is not translated to package.xml ' .
- '1.0, use PEAR_PackageFileManager-based script if you need changelog-' .
- 'translation for package.xml 1.0');
- }
-
- $gen = &$pf->getDefaultGenerator();
- $gen->toPackageFile('.');
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Pickle.xml b/3rdparty/PEAR/Command/Pickle.xml
deleted file mode 100644
index 721ecea995..0000000000
--- a/3rdparty/PEAR/Command/Pickle.xml
+++ /dev/null
@@ -1,36 +0,0 @@
-
-
- Build PECL Package
- doPackage
- pi
-
-
- Z
- Do not gzip the package file
-
-
- n
- Print the name of the packaged file.
-
-
- [descfile]
-Creates a PECL package from its package2.xml file.
-
-An automatic conversion will be made to a package.xml 1.0 and written out to
-disk in the current directory as "package.xml". Note that
-only simple package.xml 2.0 will be converted. package.xml 2.0 with:
-
- - dependency types other than required/optional PECL package/ext/php/pearinstaller
- - more than one extsrcrelease or zendextsrcrelease
- - zendextbinrelease, extbinrelease, phprelease, or bundle release type
- - dependency groups
- - ignore tags in release filelist
- - tasks other than replace
- - custom roles
-
-will cause pickle to fail, and output an error message. If your package2.xml
-uses any of these features, you are best off using PEAR_PackageFileManager to
-generate both package.xml.
-
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Registry.php b/3rdparty/PEAR/Command/Registry.php
deleted file mode 100644
index 4304db5ddf..0000000000
--- a/3rdparty/PEAR/Command/Registry.php
+++ /dev/null
@@ -1,1145 +0,0 @@
-
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Registry.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Common.php';
-
-/**
- * PEAR commands for registry manipulation
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- */
-class PEAR_Command_Registry extends PEAR_Command_Common
-{
- var $commands = array(
- 'list' => array(
- 'summary' => 'List Installed Packages In The Default Channel',
- 'function' => 'doList',
- 'shortcut' => 'l',
- 'options' => array(
- 'channel' => array(
- 'shortopt' => 'c',
- 'doc' => 'list installed packages from this channel',
- 'arg' => 'CHAN',
- ),
- 'allchannels' => array(
- 'shortopt' => 'a',
- 'doc' => 'list installed packages from all channels',
- ),
- 'channelinfo' => array(
- 'shortopt' => 'i',
- 'doc' => 'output fully channel-aware data, even on failure',
- ),
- ),
- 'doc' => '
-If invoked without parameters, this command lists the PEAR packages
-installed in your php_dir ({config php_dir}). With a parameter, it
-lists the files in a package.
-',
- ),
- 'list-files' => array(
- 'summary' => 'List Files In Installed Package',
- 'function' => 'doFileList',
- 'shortcut' => 'fl',
- 'options' => array(),
- 'doc' => '
-List the files in an installed package.
-'
- ),
- 'shell-test' => array(
- 'summary' => 'Shell Script Test',
- 'function' => 'doShellTest',
- 'shortcut' => 'st',
- 'options' => array(),
- 'doc' => ' [[relation] version]
-Tests if a package is installed in the system. Will exit(1) if it is not.
- The version comparison operator. One of:
- <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
- The version to compare with
-'),
- 'info' => array(
- 'summary' => 'Display information about a package',
- 'function' => 'doInfo',
- 'shortcut' => 'in',
- 'options' => array(),
- 'doc' => '
-Displays information about a package. The package argument may be a
-local package file, an URL to a package file, or the name of an
-installed package.'
- )
- );
-
- /**
- * PEAR_Command_Registry constructor.
- *
- * @access public
- */
- function PEAR_Command_Registry(&$ui, &$config)
- {
- parent::PEAR_Command_Common($ui, $config);
- }
-
- function _sortinfo($a, $b)
- {
- $apackage = isset($a['package']) ? $a['package'] : $a['name'];
- $bpackage = isset($b['package']) ? $b['package'] : $b['name'];
- return strcmp($apackage, $bpackage);
- }
-
- function doList($command, $options, $params)
- {
- $reg = &$this->config->getRegistry();
- $channelinfo = isset($options['channelinfo']);
- if (isset($options['allchannels']) && !$channelinfo) {
- return $this->doListAll($command, array(), $params);
- }
-
- if (isset($options['allchannels']) && $channelinfo) {
- // allchannels with $channelinfo
- unset($options['allchannels']);
- $channels = $reg->getChannels();
- $errors = array();
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- foreach ($channels as $channel) {
- $options['channel'] = $channel->getName();
- $ret = $this->doList($command, $options, $params);
-
- if (PEAR::isError($ret)) {
- $errors[] = $ret;
- }
- }
-
- PEAR::staticPopErrorHandling();
- if (count($errors)) {
- // for now, only give first error
- return PEAR::raiseError($errors[0]);
- }
-
- return true;
- }
-
- if (count($params) === 1) {
- return $this->doFileList($command, $options, $params);
- }
-
- if (isset($options['channel'])) {
- if (!$reg->channelExists($options['channel'])) {
- return $this->raiseError('Channel "' . $options['channel'] .'" does not exist');
- }
-
- $channel = $reg->channelName($options['channel']);
- } else {
- $channel = $this->config->get('default_channel');
- }
-
- $installed = $reg->packageInfo(null, null, $channel);
- usort($installed, array(&$this, '_sortinfo'));
-
- $data = array(
- 'caption' => 'Installed packages, channel ' .
- $channel . ':',
- 'border' => true,
- 'headline' => array('Package', 'Version', 'State'),
- 'channel' => $channel,
- );
- if ($channelinfo) {
- $data['headline'] = array('Channel', 'Package', 'Version', 'State');
- }
-
- if (count($installed) && !isset($data['data'])) {
- $data['data'] = array();
- }
-
- foreach ($installed as $package) {
- $pobj = $reg->getPackage(isset($package['package']) ?
- $package['package'] : $package['name'], $channel);
- if ($channelinfo) {
- $packageinfo = array($pobj->getChannel(), $pobj->getPackage(), $pobj->getVersion(),
- $pobj->getState() ? $pobj->getState() : null);
- } else {
- $packageinfo = array($pobj->getPackage(), $pobj->getVersion(),
- $pobj->getState() ? $pobj->getState() : null);
- }
- $data['data'][] = $packageinfo;
- }
-
- if (count($installed) === 0) {
- if (!$channelinfo) {
- $data = '(no packages installed from channel ' . $channel . ')';
- } else {
- $data = array(
- 'caption' => 'Installed packages, channel ' .
- $channel . ':',
- 'border' => true,
- 'channel' => $channel,
- 'data' => array(array('(no packages installed)')),
- );
- }
- }
-
- $this->ui->outputData($data, $command);
- return true;
- }
-
- function doListAll($command, $options, $params)
- {
- // This duplicate code is deprecated over
- // list --channelinfo, which gives identical
- // output for list and list --allchannels.
- $reg = &$this->config->getRegistry();
- $installed = $reg->packageInfo(null, null, null);
- foreach ($installed as $channel => $packages) {
- usort($packages, array($this, '_sortinfo'));
- $data = array(
- 'caption' => 'Installed packages, channel ' . $channel . ':',
- 'border' => true,
- 'headline' => array('Package', 'Version', 'State'),
- 'channel' => $channel
- );
-
- foreach ($packages as $package) {
- $p = isset($package['package']) ? $package['package'] : $package['name'];
- $pobj = $reg->getPackage($p, $channel);
- $data['data'][] = array($pobj->getPackage(), $pobj->getVersion(),
- $pobj->getState() ? $pobj->getState() : null);
- }
-
- // Adds a blank line after each section
- $data['data'][] = array();
-
- if (count($packages) === 0) {
- $data = array(
- 'caption' => 'Installed packages, channel ' . $channel . ':',
- 'border' => true,
- 'data' => array(array('(no packages installed)'), array()),
- 'channel' => $channel
- );
- }
- $this->ui->outputData($data, $command);
- }
- return true;
- }
-
- function doFileList($command, $options, $params)
- {
- if (count($params) !== 1) {
- return $this->raiseError('list-files expects 1 parameter');
- }
-
- $reg = &$this->config->getRegistry();
- $fp = false;
- if (!is_dir($params[0]) && (file_exists($params[0]) || $fp = @fopen($params[0], 'r'))) {
- if ($fp) {
- fclose($fp);
- }
-
- if (!class_exists('PEAR_PackageFile')) {
- require_once 'PEAR/PackageFile.php';
- }
-
- $pkg = &new PEAR_PackageFile($this->config, $this->_debug);
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $info = &$pkg->fromAnyFile($params[0], PEAR_VALIDATE_NORMAL);
- PEAR::staticPopErrorHandling();
- $headings = array('Package File', 'Install Path');
- $installed = false;
- } else {
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $parsed = $reg->parsePackageName($params[0], $this->config->get('default_channel'));
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($parsed)) {
- return $this->raiseError($parsed);
- }
-
- $info = &$reg->getPackage($parsed['package'], $parsed['channel']);
- $headings = array('Type', 'Install Path');
- $installed = true;
- }
-
- if (PEAR::isError($info)) {
- return $this->raiseError($info);
- }
-
- if ($info === null) {
- return $this->raiseError("`$params[0]' not installed");
- }
-
- $list = ($info->getPackagexmlVersion() == '1.0' || $installed) ?
- $info->getFilelist() : $info->getContents();
- if ($installed) {
- $caption = 'Installed Files For ' . $params[0];
- } else {
- $caption = 'Contents of ' . basename($params[0]);
- }
-
- $data = array(
- 'caption' => $caption,
- 'border' => true,
- 'headline' => $headings);
- if ($info->getPackagexmlVersion() == '1.0' || $installed) {
- foreach ($list as $file => $att) {
- if ($installed) {
- if (empty($att['installed_as'])) {
- continue;
- }
- $data['data'][] = array($att['role'], $att['installed_as']);
- } else {
- if (isset($att['baseinstalldir']) && !in_array($att['role'],
- array('test', 'data', 'doc'))) {
- $dest = $att['baseinstalldir'] . DIRECTORY_SEPARATOR .
- $file;
- } else {
- $dest = $file;
- }
- switch ($att['role']) {
- case 'test':
- case 'data':
- case 'doc':
- $role = $att['role'];
- if ($role == 'test') {
- $role .= 's';
- }
- $dest = $this->config->get($role . '_dir') . DIRECTORY_SEPARATOR .
- $info->getPackage() . DIRECTORY_SEPARATOR . $dest;
- break;
- case 'php':
- default:
- $dest = $this->config->get('php_dir') . DIRECTORY_SEPARATOR .
- $dest;
- }
- $ds2 = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR;
- $dest = preg_replace(array('!\\\\+!', '!/!', "!$ds2+!"),
- array(DIRECTORY_SEPARATOR,
- DIRECTORY_SEPARATOR,
- DIRECTORY_SEPARATOR),
- $dest);
- $file = preg_replace('!/+!', '/', $file);
- $data['data'][] = array($file, $dest);
- }
- }
- } else { // package.xml 2.0, not installed
- if (!isset($list['dir']['file'][0])) {
- $list['dir']['file'] = array($list['dir']['file']);
- }
-
- foreach ($list['dir']['file'] as $att) {
- $att = $att['attribs'];
- $file = $att['name'];
- $role = &PEAR_Installer_Role::factory($info, $att['role'], $this->config);
- $role->setup($this, $info, $att, $file);
- if (!$role->isInstallable()) {
- $dest = '(not installable)';
- } else {
- $dest = $role->processInstallation($info, $att, $file, '');
- if (PEAR::isError($dest)) {
- $dest = '(Unknown role "' . $att['role'] . ')';
- } else {
- list(,, $dest) = $dest;
- }
- }
- $data['data'][] = array($file, $dest);
- }
- }
-
- $this->ui->outputData($data, $command);
- return true;
- }
-
- function doShellTest($command, $options, $params)
- {
- if (count($params) < 1) {
- return PEAR::raiseError('ERROR, usage: pear shell-test packagename [[relation] version]');
- }
-
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $reg = &$this->config->getRegistry();
- $info = $reg->parsePackageName($params[0], $this->config->get('default_channel'));
- if (PEAR::isError($info)) {
- exit(1); // invalid package name
- }
-
- $package = $info['package'];
- $channel = $info['channel'];
- // "pear shell-test Foo"
- if (!$reg->packageExists($package, $channel)) {
- if ($channel == 'pecl.php.net') {
- if ($reg->packageExists($package, 'pear.php.net')) {
- $channel = 'pear.php.net'; // magically change channels for extensions
- }
- }
- }
-
- if (count($params) === 1) {
- if (!$reg->packageExists($package, $channel)) {
- exit(1);
- }
- // "pear shell-test Foo 1.0"
- } elseif (count($params) === 2) {
- $v = $reg->packageInfo($package, 'version', $channel);
- if (!$v || !version_compare("$v", "{$params[1]}", "ge")) {
- exit(1);
- }
- // "pear shell-test Foo ge 1.0"
- } elseif (count($params) === 3) {
- $v = $reg->packageInfo($package, 'version', $channel);
- if (!$v || !version_compare("$v", "{$params[2]}", $params[1])) {
- exit(1);
- }
- } else {
- PEAR::staticPopErrorHandling();
- $this->raiseError("$command: expects 1 to 3 parameters");
- exit(1);
- }
- }
-
- function doInfo($command, $options, $params)
- {
- if (count($params) !== 1) {
- return $this->raiseError('pear info expects 1 parameter');
- }
-
- $info = $fp = false;
- $reg = &$this->config->getRegistry();
- if (is_file($params[0]) && !is_dir($params[0]) &&
- (file_exists($params[0]) || $fp = @fopen($params[0], 'r'))
- ) {
- if ($fp) {
- fclose($fp);
- }
-
- if (!class_exists('PEAR_PackageFile')) {
- require_once 'PEAR/PackageFile.php';
- }
-
- $pkg = &new PEAR_PackageFile($this->config, $this->_debug);
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $obj = &$pkg->fromAnyFile($params[0], PEAR_VALIDATE_NORMAL);
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($obj)) {
- $uinfo = $obj->getUserInfo();
- if (is_array($uinfo)) {
- foreach ($uinfo as $message) {
- if (is_array($message)) {
- $message = $message['message'];
- }
- $this->ui->outputData($message);
- }
- }
-
- return $this->raiseError($obj);
- }
-
- if ($obj->getPackagexmlVersion() != '1.0') {
- return $this->_doInfo2($command, $options, $params, $obj, false);
- }
-
- $info = $obj->toArray();
- } else {
- $parsed = $reg->parsePackageName($params[0], $this->config->get('default_channel'));
- if (PEAR::isError($parsed)) {
- return $this->raiseError($parsed);
- }
-
- $package = $parsed['package'];
- $channel = $parsed['channel'];
- $info = $reg->packageInfo($package, null, $channel);
- if (isset($info['old'])) {
- $obj = $reg->getPackage($package, $channel);
- return $this->_doInfo2($command, $options, $params, $obj, true);
- }
- }
-
- if (PEAR::isError($info)) {
- return $info;
- }
-
- if (empty($info)) {
- $this->raiseError("No information found for `$params[0]'");
- return;
- }
-
- unset($info['filelist']);
- unset($info['dirtree']);
- unset($info['changelog']);
- if (isset($info['xsdversion'])) {
- $info['package.xml version'] = $info['xsdversion'];
- unset($info['xsdversion']);
- }
-
- if (isset($info['packagerversion'])) {
- $info['packaged with PEAR version'] = $info['packagerversion'];
- unset($info['packagerversion']);
- }
-
- $keys = array_keys($info);
- $longtext = array('description', 'summary');
- foreach ($keys as $key) {
- if (is_array($info[$key])) {
- switch ($key) {
- case 'maintainers': {
- $i = 0;
- $mstr = '';
- foreach ($info[$key] as $m) {
- if ($i++ > 0) {
- $mstr .= "\n";
- }
- $mstr .= $m['name'] . " <";
- if (isset($m['email'])) {
- $mstr .= $m['email'];
- } else {
- $mstr .= $m['handle'] . '@php.net';
- }
- $mstr .= "> ($m[role])";
- }
- $info[$key] = $mstr;
- break;
- }
- case 'release_deps': {
- $i = 0;
- $dstr = '';
- foreach ($info[$key] as $d) {
- if (isset($this->_deps_rel_trans[$d['rel']])) {
- $rel = $this->_deps_rel_trans[$d['rel']];
- } else {
- $rel = $d['rel'];
- }
- if (isset($this->_deps_type_trans[$d['type']])) {
- $type = ucfirst($this->_deps_type_trans[$d['type']]);
- } else {
- $type = $d['type'];
- }
- if (isset($d['name'])) {
- $name = $d['name'] . ' ';
- } else {
- $name = '';
- }
- if (isset($d['version'])) {
- $version = $d['version'] . ' ';
- } else {
- $version = '';
- }
- if (isset($d['optional']) && $d['optional'] == 'yes') {
- $optional = ' (optional)';
- } else {
- $optional = '';
- }
- $dstr .= "$type $name$rel $version$optional\n";
- }
- $info[$key] = $dstr;
- break;
- }
- case 'provides' : {
- $debug = $this->config->get('verbose');
- if ($debug < 2) {
- $pstr = 'Classes: ';
- } else {
- $pstr = '';
- }
- $i = 0;
- foreach ($info[$key] as $p) {
- if ($debug < 2 && $p['type'] != "class") {
- continue;
- }
- // Only print classes when verbosity mode is < 2
- if ($debug < 2) {
- if ($i++ > 0) {
- $pstr .= ", ";
- }
- $pstr .= $p['name'];
- } else {
- if ($i++ > 0) {
- $pstr .= "\n";
- }
- $pstr .= ucfirst($p['type']) . " " . $p['name'];
- if (isset($p['explicit']) && $p['explicit'] == 1) {
- $pstr .= " (explicit)";
- }
- }
- }
- $info[$key] = $pstr;
- break;
- }
- case 'configure_options' : {
- foreach ($info[$key] as $i => $p) {
- $info[$key][$i] = array_map(null, array_keys($p), array_values($p));
- $info[$key][$i] = array_map(create_function('$a',
- 'return join(" = ",$a);'), $info[$key][$i]);
- $info[$key][$i] = implode(', ', $info[$key][$i]);
- }
- $info[$key] = implode("\n", $info[$key]);
- break;
- }
- default: {
- $info[$key] = implode(", ", $info[$key]);
- break;
- }
- }
- }
-
- if ($key == '_lastmodified') {
- $hdate = date('Y-m-d', $info[$key]);
- unset($info[$key]);
- $info['Last Modified'] = $hdate;
- } elseif ($key == '_lastversion') {
- $info['Previous Installed Version'] = $info[$key] ? $info[$key] : '- None -';
- unset($info[$key]);
- } else {
- $info[$key] = trim($info[$key]);
- if (in_array($key, $longtext)) {
- $info[$key] = preg_replace('/ +/', ' ', $info[$key]);
- }
- }
- }
-
- $caption = 'About ' . $info['package'] . '-' . $info['version'];
- $data = array(
- 'caption' => $caption,
- 'border' => true);
- foreach ($info as $key => $value) {
- $key = ucwords(trim(str_replace('_', ' ', $key)));
- $data['data'][] = array($key, $value);
- }
- $data['raw'] = $info;
-
- $this->ui->outputData($data, 'package-info');
- }
-
- /**
- * @access private
- */
- function _doInfo2($command, $options, $params, &$obj, $installed)
- {
- $reg = &$this->config->getRegistry();
- $caption = 'About ' . $obj->getChannel() . '/' .$obj->getPackage() . '-' .
- $obj->getVersion();
- $data = array(
- 'caption' => $caption,
- 'border' => true);
- switch ($obj->getPackageType()) {
- case 'php' :
- $release = 'PEAR-style PHP-based Package';
- break;
- case 'extsrc' :
- $release = 'PECL-style PHP extension (source code)';
- break;
- case 'zendextsrc' :
- $release = 'PECL-style Zend extension (source code)';
- break;
- case 'extbin' :
- $release = 'PECL-style PHP extension (binary)';
- break;
- case 'zendextbin' :
- $release = 'PECL-style Zend extension (binary)';
- break;
- case 'bundle' :
- $release = 'Package bundle (collection of packages)';
- break;
- }
- $extends = $obj->getExtends();
- $extends = $extends ?
- $obj->getPackage() . ' (extends ' . $extends . ')' : $obj->getPackage();
- if ($src = $obj->getSourcePackage()) {
- $extends .= ' (source package ' . $src['channel'] . '/' . $src['package'] . ')';
- }
-
- $info = array(
- 'Release Type' => $release,
- 'Name' => $extends,
- 'Channel' => $obj->getChannel(),
- 'Summary' => preg_replace('/ +/', ' ', $obj->getSummary()),
- 'Description' => preg_replace('/ +/', ' ', $obj->getDescription()),
- );
- $info['Maintainers'] = '';
- foreach (array('lead', 'developer', 'contributor', 'helper') as $role) {
- $leads = $obj->{"get{$role}s"}();
- if (!$leads) {
- continue;
- }
-
- if (isset($leads['active'])) {
- $leads = array($leads);
- }
-
- foreach ($leads as $lead) {
- if (!empty($info['Maintainers'])) {
- $info['Maintainers'] .= "\n";
- }
-
- $active = $lead['active'] == 'no' ? ', inactive' : '';
- $info['Maintainers'] .= $lead['name'] . ' <';
- $info['Maintainers'] .= $lead['email'] . "> ($role$active)";
- }
- }
-
- $info['Release Date'] = $obj->getDate();
- if ($time = $obj->getTime()) {
- $info['Release Date'] .= ' ' . $time;
- }
-
- $info['Release Version'] = $obj->getVersion() . ' (' . $obj->getState() . ')';
- $info['API Version'] = $obj->getVersion('api') . ' (' . $obj->getState('api') . ')';
- $info['License'] = $obj->getLicense();
- $uri = $obj->getLicenseLocation();
- if ($uri) {
- if (isset($uri['uri'])) {
- $info['License'] .= ' (' . $uri['uri'] . ')';
- } else {
- $extra = $obj->getInstalledLocation($info['filesource']);
- if ($extra) {
- $info['License'] .= ' (' . $uri['filesource'] . ')';
- }
- }
- }
-
- $info['Release Notes'] = $obj->getNotes();
- if ($compat = $obj->getCompatible()) {
- if (!isset($compat[0])) {
- $compat = array($compat);
- }
-
- $info['Compatible with'] = '';
- foreach ($compat as $package) {
- $info['Compatible with'] .= $package['channel'] . '/' . $package['name'] .
- "\nVersions >= " . $package['min'] . ', <= ' . $package['max'];
- if (isset($package['exclude'])) {
- if (is_array($package['exclude'])) {
- $package['exclude'] = implode(', ', $package['exclude']);
- }
-
- if (!isset($info['Not Compatible with'])) {
- $info['Not Compatible with'] = '';
- } else {
- $info['Not Compatible with'] .= "\n";
- }
- $info['Not Compatible with'] .= $package['channel'] . '/' .
- $package['name'] . "\nVersions " . $package['exclude'];
- }
- }
- }
-
- $usesrole = $obj->getUsesrole();
- if ($usesrole) {
- if (!isset($usesrole[0])) {
- $usesrole = array($usesrole);
- }
-
- foreach ($usesrole as $roledata) {
- if (isset($info['Uses Custom Roles'])) {
- $info['Uses Custom Roles'] .= "\n";
- } else {
- $info['Uses Custom Roles'] = '';
- }
-
- if (isset($roledata['package'])) {
- $rolepackage = $reg->parsedPackageNameToString($roledata, true);
- } else {
- $rolepackage = $roledata['uri'];
- }
- $info['Uses Custom Roles'] .= $roledata['role'] . ' (' . $rolepackage . ')';
- }
- }
-
- $usestask = $obj->getUsestask();
- if ($usestask) {
- if (!isset($usestask[0])) {
- $usestask = array($usestask);
- }
-
- foreach ($usestask as $taskdata) {
- if (isset($info['Uses Custom Tasks'])) {
- $info['Uses Custom Tasks'] .= "\n";
- } else {
- $info['Uses Custom Tasks'] = '';
- }
-
- if (isset($taskdata['package'])) {
- $taskpackage = $reg->parsedPackageNameToString($taskdata, true);
- } else {
- $taskpackage = $taskdata['uri'];
- }
- $info['Uses Custom Tasks'] .= $taskdata['task'] . ' (' . $taskpackage . ')';
- }
- }
-
- $deps = $obj->getDependencies();
- $info['Required Dependencies'] = 'PHP version ' . $deps['required']['php']['min'];
- if (isset($deps['required']['php']['max'])) {
- $info['Required Dependencies'] .= '-' . $deps['required']['php']['max'] . "\n";
- } else {
- $info['Required Dependencies'] .= "\n";
- }
-
- if (isset($deps['required']['php']['exclude'])) {
- if (!isset($info['Not Compatible with'])) {
- $info['Not Compatible with'] = '';
- } else {
- $info['Not Compatible with'] .= "\n";
- }
-
- if (is_array($deps['required']['php']['exclude'])) {
- $deps['required']['php']['exclude'] =
- implode(', ', $deps['required']['php']['exclude']);
- }
- $info['Not Compatible with'] .= "PHP versions\n " .
- $deps['required']['php']['exclude'];
- }
-
- $info['Required Dependencies'] .= 'PEAR installer version';
- if (isset($deps['required']['pearinstaller']['max'])) {
- $info['Required Dependencies'] .= 's ' .
- $deps['required']['pearinstaller']['min'] . '-' .
- $deps['required']['pearinstaller']['max'];
- } else {
- $info['Required Dependencies'] .= ' ' .
- $deps['required']['pearinstaller']['min'] . ' or newer';
- }
-
- if (isset($deps['required']['pearinstaller']['exclude'])) {
- if (!isset($info['Not Compatible with'])) {
- $info['Not Compatible with'] = '';
- } else {
- $info['Not Compatible with'] .= "\n";
- }
-
- if (is_array($deps['required']['pearinstaller']['exclude'])) {
- $deps['required']['pearinstaller']['exclude'] =
- implode(', ', $deps['required']['pearinstaller']['exclude']);
- }
- $info['Not Compatible with'] .= "PEAR installer\n Versions " .
- $deps['required']['pearinstaller']['exclude'];
- }
-
- foreach (array('Package', 'Extension') as $type) {
- $index = strtolower($type);
- if (isset($deps['required'][$index])) {
- if (isset($deps['required'][$index]['name'])) {
- $deps['required'][$index] = array($deps['required'][$index]);
- }
-
- foreach ($deps['required'][$index] as $package) {
- if (isset($package['conflicts'])) {
- $infoindex = 'Not Compatible with';
- if (!isset($info['Not Compatible with'])) {
- $info['Not Compatible with'] = '';
- } else {
- $info['Not Compatible with'] .= "\n";
- }
- } else {
- $infoindex = 'Required Dependencies';
- $info[$infoindex] .= "\n";
- }
-
- if ($index == 'extension') {
- $name = $package['name'];
- } else {
- if (isset($package['channel'])) {
- $name = $package['channel'] . '/' . $package['name'];
- } else {
- $name = '__uri/' . $package['name'] . ' (static URI)';
- }
- }
-
- $info[$infoindex] .= "$type $name";
- if (isset($package['uri'])) {
- $info[$infoindex] .= "\n Download URI: $package[uri]";
- continue;
- }
-
- if (isset($package['max']) && isset($package['min'])) {
- $info[$infoindex] .= " \n Versions " .
- $package['min'] . '-' . $package['max'];
- } elseif (isset($package['min'])) {
- $info[$infoindex] .= " \n Version " .
- $package['min'] . ' or newer';
- } elseif (isset($package['max'])) {
- $info[$infoindex] .= " \n Version " .
- $package['max'] . ' or older';
- }
-
- if (isset($package['recommended'])) {
- $info[$infoindex] .= "\n Recommended version: $package[recommended]";
- }
-
- if (isset($package['exclude'])) {
- if (!isset($info['Not Compatible with'])) {
- $info['Not Compatible with'] = '';
- } else {
- $info['Not Compatible with'] .= "\n";
- }
-
- if (is_array($package['exclude'])) {
- $package['exclude'] = implode(', ', $package['exclude']);
- }
-
- $package['package'] = $package['name']; // for parsedPackageNameToString
- if (isset($package['conflicts'])) {
- $info['Not Compatible with'] .= '=> except ';
- }
- $info['Not Compatible with'] .= 'Package ' .
- $reg->parsedPackageNameToString($package, true);
- $info['Not Compatible with'] .= "\n Versions " . $package['exclude'];
- }
- }
- }
- }
-
- if (isset($deps['required']['os'])) {
- if (isset($deps['required']['os']['name'])) {
- $dep['required']['os']['name'] = array($dep['required']['os']['name']);
- }
-
- foreach ($dep['required']['os'] as $os) {
- if (isset($os['conflicts']) && $os['conflicts'] == 'yes') {
- if (!isset($info['Not Compatible with'])) {
- $info['Not Compatible with'] = '';
- } else {
- $info['Not Compatible with'] .= "\n";
- }
- $info['Not Compatible with'] .= "$os[name] Operating System";
- } else {
- $info['Required Dependencies'] .= "\n";
- $info['Required Dependencies'] .= "$os[name] Operating System";
- }
- }
- }
-
- if (isset($deps['required']['arch'])) {
- if (isset($deps['required']['arch']['pattern'])) {
- $dep['required']['arch']['pattern'] = array($dep['required']['os']['pattern']);
- }
-
- foreach ($dep['required']['arch'] as $os) {
- if (isset($os['conflicts']) && $os['conflicts'] == 'yes') {
- if (!isset($info['Not Compatible with'])) {
- $info['Not Compatible with'] = '';
- } else {
- $info['Not Compatible with'] .= "\n";
- }
- $info['Not Compatible with'] .= "OS/Arch matching pattern '/$os[pattern]/'";
- } else {
- $info['Required Dependencies'] .= "\n";
- $info['Required Dependencies'] .= "OS/Arch matching pattern '/$os[pattern]/'";
- }
- }
- }
-
- if (isset($deps['optional'])) {
- foreach (array('Package', 'Extension') as $type) {
- $index = strtolower($type);
- if (isset($deps['optional'][$index])) {
- if (isset($deps['optional'][$index]['name'])) {
- $deps['optional'][$index] = array($deps['optional'][$index]);
- }
-
- foreach ($deps['optional'][$index] as $package) {
- if (isset($package['conflicts']) && $package['conflicts'] == 'yes') {
- $infoindex = 'Not Compatible with';
- if (!isset($info['Not Compatible with'])) {
- $info['Not Compatible with'] = '';
- } else {
- $info['Not Compatible with'] .= "\n";
- }
- } else {
- $infoindex = 'Optional Dependencies';
- if (!isset($info['Optional Dependencies'])) {
- $info['Optional Dependencies'] = '';
- } else {
- $info['Optional Dependencies'] .= "\n";
- }
- }
-
- if ($index == 'extension') {
- $name = $package['name'];
- } else {
- if (isset($package['channel'])) {
- $name = $package['channel'] . '/' . $package['name'];
- } else {
- $name = '__uri/' . $package['name'] . ' (static URI)';
- }
- }
-
- $info[$infoindex] .= "$type $name";
- if (isset($package['uri'])) {
- $info[$infoindex] .= "\n Download URI: $package[uri]";
- continue;
- }
-
- if ($infoindex == 'Not Compatible with') {
- // conflicts is only used to say that all versions conflict
- continue;
- }
-
- if (isset($package['max']) && isset($package['min'])) {
- $info[$infoindex] .= " \n Versions " .
- $package['min'] . '-' . $package['max'];
- } elseif (isset($package['min'])) {
- $info[$infoindex] .= " \n Version " .
- $package['min'] . ' or newer';
- } elseif (isset($package['max'])) {
- $info[$infoindex] .= " \n Version " .
- $package['min'] . ' or older';
- }
-
- if (isset($package['recommended'])) {
- $info[$infoindex] .= "\n Recommended version: $package[recommended]";
- }
-
- if (isset($package['exclude'])) {
- if (!isset($info['Not Compatible with'])) {
- $info['Not Compatible with'] = '';
- } else {
- $info['Not Compatible with'] .= "\n";
- }
-
- if (is_array($package['exclude'])) {
- $package['exclude'] = implode(', ', $package['exclude']);
- }
-
- $info['Not Compatible with'] .= "Package $package\n Versions " .
- $package['exclude'];
- }
- }
- }
- }
- }
-
- if (isset($deps['group'])) {
- if (!isset($deps['group'][0])) {
- $deps['group'] = array($deps['group']);
- }
-
- foreach ($deps['group'] as $group) {
- $info['Dependency Group ' . $group['attribs']['name']] = $group['attribs']['hint'];
- $groupindex = $group['attribs']['name'] . ' Contents';
- $info[$groupindex] = '';
- foreach (array('Package', 'Extension') as $type) {
- $index = strtolower($type);
- if (isset($group[$index])) {
- if (isset($group[$index]['name'])) {
- $group[$index] = array($group[$index]);
- }
-
- foreach ($group[$index] as $package) {
- if (!empty($info[$groupindex])) {
- $info[$groupindex] .= "\n";
- }
-
- if ($index == 'extension') {
- $name = $package['name'];
- } else {
- if (isset($package['channel'])) {
- $name = $package['channel'] . '/' . $package['name'];
- } else {
- $name = '__uri/' . $package['name'] . ' (static URI)';
- }
- }
-
- if (isset($package['uri'])) {
- if (isset($package['conflicts']) && $package['conflicts'] == 'yes') {
- $info[$groupindex] .= "Not Compatible with $type $name";
- } else {
- $info[$groupindex] .= "$type $name";
- }
-
- $info[$groupindex] .= "\n Download URI: $package[uri]";
- continue;
- }
-
- if (isset($package['conflicts']) && $package['conflicts'] == 'yes') {
- $info[$groupindex] .= "Not Compatible with $type $name";
- continue;
- }
-
- $info[$groupindex] .= "$type $name";
- if (isset($package['max']) && isset($package['min'])) {
- $info[$groupindex] .= " \n Versions " .
- $package['min'] . '-' . $package['max'];
- } elseif (isset($package['min'])) {
- $info[$groupindex] .= " \n Version " .
- $package['min'] . ' or newer';
- } elseif (isset($package['max'])) {
- $info[$groupindex] .= " \n Version " .
- $package['min'] . ' or older';
- }
-
- if (isset($package['recommended'])) {
- $info[$groupindex] .= "\n Recommended version: $package[recommended]";
- }
-
- if (isset($package['exclude'])) {
- if (!isset($info['Not Compatible with'])) {
- $info['Not Compatible with'] = '';
- } else {
- $info[$groupindex] .= "Not Compatible with\n";
- }
-
- if (is_array($package['exclude'])) {
- $package['exclude'] = implode(', ', $package['exclude']);
- }
- $info[$groupindex] .= " Package $package\n Versions " .
- $package['exclude'];
- }
- }
- }
- }
- }
- }
-
- if ($obj->getPackageType() == 'bundle') {
- $info['Bundled Packages'] = '';
- foreach ($obj->getBundledPackages() as $package) {
- if (!empty($info['Bundled Packages'])) {
- $info['Bundled Packages'] .= "\n";
- }
-
- if (isset($package['uri'])) {
- $info['Bundled Packages'] .= '__uri/' . $package['name'];
- $info['Bundled Packages'] .= "\n (URI: $package[uri]";
- } else {
- $info['Bundled Packages'] .= $package['channel'] . '/' . $package['name'];
- }
- }
- }
-
- $info['package.xml version'] = '2.0';
- if ($installed) {
- if ($obj->getLastModified()) {
- $info['Last Modified'] = date('Y-m-d H:i', $obj->getLastModified());
- }
-
- $v = $obj->getLastInstalledVersion();
- $info['Previous Installed Version'] = $v ? $v : '- None -';
- }
-
- foreach ($info as $key => $value) {
- $data['data'][] = array($key, $value);
- }
-
- $data['raw'] = $obj->getArray(); // no validation needed
- $this->ui->outputData($data, 'package-info');
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Registry.xml b/3rdparty/PEAR/Command/Registry.xml
deleted file mode 100644
index 9f4e214967..0000000000
--- a/3rdparty/PEAR/Command/Registry.xml
+++ /dev/null
@@ -1,58 +0,0 @@
-
-
- List Installed Packages In The Default Channel
- doList
- l
-
-
- c
- list installed packages from this channel
- CHAN
-
-
- a
- list installed packages from all channels
-
-
- i
- output fully channel-aware data, even on failure
-
-
- <package>
-If invoked without parameters, this command lists the PEAR packages
-installed in your php_dir ({config php_dir}). With a parameter, it
-lists the files in a package.
-
-
-
- List Files In Installed Package
- doFileList
- fl
-
- <package>
-List the files in an installed package.
-
-
-
- Shell Script Test
- doShellTest
- st
-
- <package> [[relation] version]
-Tests if a package is installed in the system. Will exit(1) if it is not.
- <relation> The version comparison operator. One of:
- <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
- <version> The version to compare with
-
-
-
- Display information about a package
- doInfo
- in
-
- <package>
-Displays information about a package. The package argument may be a
-local package file, an URL to a package file, or the name of an
-installed package.
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Remote.php b/3rdparty/PEAR/Command/Remote.php
deleted file mode 100644
index 74478d83c7..0000000000
--- a/3rdparty/PEAR/Command/Remote.php
+++ /dev/null
@@ -1,810 +0,0 @@
-
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Remote.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Common.php';
-require_once 'PEAR/REST.php';
-
-/**
- * PEAR commands for remote server querying
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- */
-class PEAR_Command_Remote extends PEAR_Command_Common
-{
- var $commands = array(
- 'remote-info' => array(
- 'summary' => 'Information About Remote Packages',
- 'function' => 'doRemoteInfo',
- 'shortcut' => 'ri',
- 'options' => array(),
- 'doc' => '
-Get details on a package from the server.',
- ),
- 'list-upgrades' => array(
- 'summary' => 'List Available Upgrades',
- 'function' => 'doListUpgrades',
- 'shortcut' => 'lu',
- 'options' => array(
- 'channelinfo' => array(
- 'shortopt' => 'i',
- 'doc' => 'output fully channel-aware data, even on failure',
- ),
- ),
- 'doc' => '[preferred_state]
-List releases on the server of packages you have installed where
-a newer version is available with the same release state (stable etc.)
-or the state passed as the second parameter.'
- ),
- 'remote-list' => array(
- 'summary' => 'List Remote Packages',
- 'function' => 'doRemoteList',
- 'shortcut' => 'rl',
- 'options' => array(
- 'channel' =>
- array(
- 'shortopt' => 'c',
- 'doc' => 'specify a channel other than the default channel',
- 'arg' => 'CHAN',
- )
- ),
- 'doc' => '
-Lists the packages available on the configured server along with the
-latest stable release of each package.',
- ),
- 'search' => array(
- 'summary' => 'Search remote package database',
- 'function' => 'doSearch',
- 'shortcut' => 'sp',
- 'options' => array(
- 'channel' =>
- array(
- 'shortopt' => 'c',
- 'doc' => 'specify a channel other than the default channel',
- 'arg' => 'CHAN',
- ),
- 'allchannels' => array(
- 'shortopt' => 'a',
- 'doc' => 'search packages from all known channels',
- ),
- 'channelinfo' => array(
- 'shortopt' => 'i',
- 'doc' => 'output fully channel-aware data, even on failure',
- ),
- ),
- 'doc' => '[packagename] [packageinfo]
-Lists all packages which match the search parameters. The first
-parameter is a fragment of a packagename. The default channel
-will be used unless explicitly overridden. The second parameter
-will be used to match any portion of the summary/description',
- ),
- 'list-all' => array(
- 'summary' => 'List All Packages',
- 'function' => 'doListAll',
- 'shortcut' => 'la',
- 'options' => array(
- 'channel' =>
- array(
- 'shortopt' => 'c',
- 'doc' => 'specify a channel other than the default channel',
- 'arg' => 'CHAN',
- ),
- 'channelinfo' => array(
- 'shortopt' => 'i',
- 'doc' => 'output fully channel-aware data, even on failure',
- ),
- ),
- 'doc' => '
-Lists the packages available on the configured server along with the
-latest stable release of each package.',
- ),
- 'download' => array(
- 'summary' => 'Download Package',
- 'function' => 'doDownload',
- 'shortcut' => 'd',
- 'options' => array(
- 'nocompress' => array(
- 'shortopt' => 'Z',
- 'doc' => 'download an uncompressed (.tar) file',
- ),
- ),
- 'doc' => '...
-Download package tarballs. The files will be named as suggested by the
-server, for example if you download the DB package and the latest stable
-version of DB is 1.6.5, the downloaded file will be DB-1.6.5.tgz.',
- ),
- 'clear-cache' => array(
- 'summary' => 'Clear Web Services Cache',
- 'function' => 'doClearCache',
- 'shortcut' => 'cc',
- 'options' => array(),
- 'doc' => '
-Clear the REST cache. See also the cache_ttl configuration
-parameter.
-',
- ),
- );
-
- /**
- * PEAR_Command_Remote constructor.
- *
- * @access public
- */
- function PEAR_Command_Remote(&$ui, &$config)
- {
- parent::PEAR_Command_Common($ui, $config);
- }
-
- function _checkChannelForStatus($channel, $chan)
- {
- if (PEAR::isError($chan)) {
- $this->raiseError($chan);
- }
- if (!is_a($chan, 'PEAR_ChannelFile')) {
- return $this->raiseError('Internal corruption error: invalid channel "' .
- $channel . '"');
- }
- $rest = new PEAR_REST($this->config);
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $mirror = $this->config->get('preferred_mirror', null,
- $channel);
- $a = $rest->downloadHttp('http://' . $channel .
- '/channel.xml', $chan->lastModified());
- PEAR::staticPopErrorHandling();
- if (!PEAR::isError($a) && $a) {
- $this->ui->outputData('WARNING: channel "' . $channel . '" has ' .
- 'updated its protocols, use "' . PEAR_RUNTYPE . ' channel-update ' . $channel .
- '" to update');
- }
- }
-
- function doRemoteInfo($command, $options, $params)
- {
- if (sizeof($params) != 1) {
- return $this->raiseError("$command expects one param: the remote package name");
- }
- $savechannel = $channel = $this->config->get('default_channel');
- $reg = &$this->config->getRegistry();
- $package = $params[0];
- $parsed = $reg->parsePackageName($package, $channel);
- if (PEAR::isError($parsed)) {
- return $this->raiseError('Invalid package name "' . $package . '"');
- }
-
- $channel = $parsed['channel'];
- $this->config->set('default_channel', $channel);
- $chan = $reg->getChannel($channel);
- if (PEAR::isError($e = $this->_checkChannelForStatus($channel, $chan))) {
- return $e;
- }
-
- $mirror = $this->config->get('preferred_mirror');
- if ($chan->supportsREST($mirror) && $base = $chan->getBaseURL('REST1.0', $mirror)) {
- $rest = &$this->config->getREST('1.0', array());
- $info = $rest->packageInfo($base, $parsed['package'], $channel);
- }
-
- if (!isset($info)) {
- return $this->raiseError('No supported protocol was found');
- }
-
- if (PEAR::isError($info)) {
- $this->config->set('default_channel', $savechannel);
- return $this->raiseError($info);
- }
-
- if (!isset($info['name'])) {
- return $this->raiseError('No remote package "' . $package . '" was found');
- }
-
- $installed = $reg->packageInfo($info['name'], null, $channel);
- $info['installed'] = $installed['version'] ? $installed['version'] : '- no -';
- if (is_array($info['installed'])) {
- $info['installed'] = $info['installed']['release'];
- }
-
- $this->ui->outputData($info, $command);
- $this->config->set('default_channel', $savechannel);
-
- return true;
- }
-
- function doRemoteList($command, $options, $params)
- {
- $savechannel = $channel = $this->config->get('default_channel');
- $reg = &$this->config->getRegistry();
- if (isset($options['channel'])) {
- $channel = $options['channel'];
- if (!$reg->channelExists($channel)) {
- return $this->raiseError('Channel "' . $channel . '" does not exist');
- }
-
- $this->config->set('default_channel', $channel);
- }
-
- $chan = $reg->getChannel($channel);
- if (PEAR::isError($e = $this->_checkChannelForStatus($channel, $chan))) {
- return $e;
- }
-
- $list_options = false;
- if ($this->config->get('preferred_state') == 'stable') {
- $list_options = true;
- }
-
- $available = array();
- if ($chan->supportsREST($this->config->get('preferred_mirror')) &&
- $base = $chan->getBaseURL('REST1.1', $this->config->get('preferred_mirror'))
- ) {
- // use faster list-all if available
- $rest = &$this->config->getREST('1.1', array());
- $available = $rest->listAll($base, $list_options, true, false, false, $chan->getName());
- } elseif ($chan->supportsREST($this->config->get('preferred_mirror')) &&
- $base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror'))) {
- $rest = &$this->config->getREST('1.0', array());
- $available = $rest->listAll($base, $list_options, true, false, false, $chan->getName());
- }
-
- if (PEAR::isError($available)) {
- $this->config->set('default_channel', $savechannel);
- return $this->raiseError($available);
- }
-
- $i = $j = 0;
- $data = array(
- 'caption' => 'Channel ' . $channel . ' Available packages:',
- 'border' => true,
- 'headline' => array('Package', 'Version'),
- 'channel' => $channel
- );
-
- if (count($available) == 0) {
- $data = '(no packages available yet)';
- } else {
- foreach ($available as $name => $info) {
- $version = (isset($info['stable']) && $info['stable']) ? $info['stable'] : '-n/a-';
- $data['data'][] = array($name, $version);
- }
- }
- $this->ui->outputData($data, $command);
- $this->config->set('default_channel', $savechannel);
- return true;
- }
-
- function doListAll($command, $options, $params)
- {
- $savechannel = $channel = $this->config->get('default_channel');
- $reg = &$this->config->getRegistry();
- if (isset($options['channel'])) {
- $channel = $options['channel'];
- if (!$reg->channelExists($channel)) {
- return $this->raiseError("Channel \"$channel\" does not exist");
- }
-
- $this->config->set('default_channel', $channel);
- }
-
- $list_options = false;
- if ($this->config->get('preferred_state') == 'stable') {
- $list_options = true;
- }
-
- $chan = $reg->getChannel($channel);
- if (PEAR::isError($e = $this->_checkChannelForStatus($channel, $chan))) {
- return $e;
- }
-
- if ($chan->supportsREST($this->config->get('preferred_mirror')) &&
- $base = $chan->getBaseURL('REST1.1', $this->config->get('preferred_mirror'))) {
- // use faster list-all if available
- $rest = &$this->config->getREST('1.1', array());
- $available = $rest->listAll($base, $list_options, false, false, false, $chan->getName());
- } elseif ($chan->supportsREST($this->config->get('preferred_mirror')) &&
- $base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror'))) {
- $rest = &$this->config->getREST('1.0', array());
- $available = $rest->listAll($base, $list_options, false, false, false, $chan->getName());
- }
-
- if (PEAR::isError($available)) {
- $this->config->set('default_channel', $savechannel);
- return $this->raiseError('The package list could not be fetched from the remote server. Please try again. (Debug info: "' . $available->getMessage() . '")');
- }
-
- $data = array(
- 'caption' => 'All packages [Channel ' . $channel . ']:',
- 'border' => true,
- 'headline' => array('Package', 'Latest', 'Local'),
- 'channel' => $channel,
- );
-
- if (isset($options['channelinfo'])) {
- // add full channelinfo
- $data['caption'] = 'Channel ' . $channel . ' All packages:';
- $data['headline'] = array('Channel', 'Package', 'Latest', 'Local',
- 'Description', 'Dependencies');
- }
- $local_pkgs = $reg->listPackages($channel);
-
- foreach ($available as $name => $info) {
- $installed = $reg->packageInfo($name, null, $channel);
- if (is_array($installed['version'])) {
- $installed['version'] = $installed['version']['release'];
- }
- $desc = $info['summary'];
- if (isset($params[$name])) {
- $desc .= "\n\n".$info['description'];
- }
- if (isset($options['mode']))
- {
- if ($options['mode'] == 'installed' && !isset($installed['version'])) {
- continue;
- }
- if ($options['mode'] == 'notinstalled' && isset($installed['version'])) {
- continue;
- }
- if ($options['mode'] == 'upgrades'
- && (!isset($installed['version']) || version_compare($installed['version'],
- $info['stable'], '>='))) {
- continue;
- }
- }
- $pos = array_search(strtolower($name), $local_pkgs);
- if ($pos !== false) {
- unset($local_pkgs[$pos]);
- }
-
- if (isset($info['stable']) && !$info['stable']) {
- $info['stable'] = null;
- }
-
- if (isset($options['channelinfo'])) {
- // add full channelinfo
- if ($info['stable'] === $info['unstable']) {
- $state = $info['state'];
- } else {
- $state = 'stable';
- }
- $latest = $info['stable'].' ('.$state.')';
- $local = '';
- if (isset($installed['version'])) {
- $inst_state = $reg->packageInfo($name, 'release_state', $channel);
- $local = $installed['version'].' ('.$inst_state.')';
- }
-
- $packageinfo = array(
- $channel,
- $name,
- $latest,
- $local,
- isset($desc) ? $desc : null,
- isset($info['deps']) ? $info['deps'] : null,
- );
- } else {
- $packageinfo = array(
- $reg->channelAlias($channel) . '/' . $name,
- isset($info['stable']) ? $info['stable'] : null,
- isset($installed['version']) ? $installed['version'] : null,
- isset($desc) ? $desc : null,
- isset($info['deps']) ? $info['deps'] : null,
- );
- }
- $data['data'][$info['category']][] = $packageinfo;
- }
-
- if (isset($options['mode']) && in_array($options['mode'], array('notinstalled', 'upgrades'))) {
- $this->config->set('default_channel', $savechannel);
- $this->ui->outputData($data, $command);
- return true;
- }
-
- foreach ($local_pkgs as $name) {
- $info = &$reg->getPackage($name, $channel);
- $data['data']['Local'][] = array(
- $reg->channelAlias($channel) . '/' . $info->getPackage(),
- '',
- $info->getVersion(),
- $info->getSummary(),
- $info->getDeps()
- );
- }
-
- $this->config->set('default_channel', $savechannel);
- $this->ui->outputData($data, $command);
- return true;
- }
-
- function doSearch($command, $options, $params)
- {
- if ((!isset($params[0]) || empty($params[0]))
- && (!isset($params[1]) || empty($params[1])))
- {
- return $this->raiseError('no valid search string supplied');
- }
-
- $channelinfo = isset($options['channelinfo']);
- $reg = &$this->config->getRegistry();
- if (isset($options['allchannels'])) {
- // search all channels
- unset($options['allchannels']);
- $channels = $reg->getChannels();
- $errors = array();
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- foreach ($channels as $channel) {
- if ($channel->getName() != '__uri') {
- $options['channel'] = $channel->getName();
- $ret = $this->doSearch($command, $options, $params);
- if (PEAR::isError($ret)) {
- $errors[] = $ret;
- }
- }
- }
-
- PEAR::staticPopErrorHandling();
- if (count($errors) !== 0) {
- // for now, only give first error
- return PEAR::raiseError($errors[0]);
- }
-
- return true;
- }
-
- $savechannel = $channel = $this->config->get('default_channel');
- $package = strtolower($params[0]);
- $summary = isset($params[1]) ? $params[1] : false;
- if (isset($options['channel'])) {
- $reg = &$this->config->getRegistry();
- $channel = $options['channel'];
- if (!$reg->channelExists($channel)) {
- return $this->raiseError('Channel "' . $channel . '" does not exist');
- }
-
- $this->config->set('default_channel', $channel);
- }
-
- $chan = $reg->getChannel($channel);
- if (PEAR::isError($e = $this->_checkChannelForStatus($channel, $chan))) {
- return $e;
- }
-
- if ($chan->supportsREST($this->config->get('preferred_mirror')) &&
- $base = $chan->getBaseURL('REST1.0', $this->config->get('preferred_mirror'))) {
- $rest = &$this->config->getREST('1.0', array());
- $available = $rest->listAll($base, false, false, $package, $summary, $chan->getName());
- }
-
- if (PEAR::isError($available)) {
- $this->config->set('default_channel', $savechannel);
- return $this->raiseError($available);
- }
-
- if (!$available && !$channelinfo) {
- // clean exit when not found, no error !
- $data = 'no packages found that match pattern "' . $package . '", for channel '.$channel.'.';
- $this->ui->outputData($data);
- $this->config->set('default_channel', $channel);
- return true;
- }
-
- if ($channelinfo) {
- $data = array(
- 'caption' => 'Matched packages, channel ' . $channel . ':',
- 'border' => true,
- 'headline' => array('Channel', 'Package', 'Stable/(Latest)', 'Local'),
- 'channel' => $channel
- );
- } else {
- $data = array(
- 'caption' => 'Matched packages, channel ' . $channel . ':',
- 'border' => true,
- 'headline' => array('Package', 'Stable/(Latest)', 'Local'),
- 'channel' => $channel
- );
- }
-
- if (!$available && $channelinfo) {
- unset($data['headline']);
- $data['data'] = 'No packages found that match pattern "' . $package . '".';
- $available = array();
- }
-
- foreach ($available as $name => $info) {
- $installed = $reg->packageInfo($name, null, $channel);
- $desc = $info['summary'];
- if (isset($params[$name]))
- $desc .= "\n\n".$info['description'];
-
- if (!isset($info['stable']) || !$info['stable']) {
- $version_remote = 'none';
- } else {
- if ($info['unstable']) {
- $version_remote = $info['unstable'];
- } else {
- $version_remote = $info['stable'];
- }
- $version_remote .= ' ('.$info['state'].')';
- }
- $version = is_array($installed['version']) ? $installed['version']['release'] :
- $installed['version'];
- if ($channelinfo) {
- $packageinfo = array(
- $channel,
- $name,
- $version_remote,
- $version,
- $desc,
- );
- } else {
- $packageinfo = array(
- $name,
- $version_remote,
- $version,
- $desc,
- );
- }
- $data['data'][$info['category']][] = $packageinfo;
- }
-
- $this->ui->outputData($data, $command);
- $this->config->set('default_channel', $channel);
- return true;
- }
-
- function &getDownloader($options)
- {
- if (!class_exists('PEAR_Downloader')) {
- require_once 'PEAR/Downloader.php';
- }
- $a = &new PEAR_Downloader($this->ui, $options, $this->config);
- return $a;
- }
-
- function doDownload($command, $options, $params)
- {
- // make certain that dependencies are ignored
- $options['downloadonly'] = 1;
-
- // eliminate error messages for preferred_state-related errors
- /* TODO: Should be an option, but until now download does respect
- prefered state */
- /* $options['ignorepreferred_state'] = 1; */
- // eliminate error messages for preferred_state-related errors
-
- $downloader = &$this->getDownloader($options);
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $e = $downloader->setDownloadDir(getcwd());
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($e)) {
- return $this->raiseError('Current directory is not writeable, cannot download');
- }
-
- $errors = array();
- $downloaded = array();
- $err = $downloader->download($params);
- if (PEAR::isError($err)) {
- return $err;
- }
-
- $errors = $downloader->getErrorMsgs();
- if (count($errors)) {
- foreach ($errors as $error) {
- if ($error !== null) {
- $this->ui->outputData($error);
- }
- }
-
- return $this->raiseError("$command failed");
- }
-
- $downloaded = $downloader->getDownloadedPackages();
- foreach ($downloaded as $pkg) {
- $this->ui->outputData("File $pkg[file] downloaded", $command);
- }
-
- return true;
- }
-
- function downloadCallback($msg, $params = null)
- {
- if ($msg == 'done') {
- $this->bytes_downloaded = $params;
- }
- }
-
- function doListUpgrades($command, $options, $params)
- {
- require_once 'PEAR/Common.php';
- if (isset($params[0]) && !is_array(PEAR_Common::betterStates($params[0]))) {
- return $this->raiseError($params[0] . ' is not a valid state (stable/beta/alpha/devel/etc.) try "pear help list-upgrades"');
- }
-
- $savechannel = $channel = $this->config->get('default_channel');
- $reg = &$this->config->getRegistry();
- foreach ($reg->listChannels() as $channel) {
- $inst = array_flip($reg->listPackages($channel));
- if (!count($inst)) {
- continue;
- }
-
- if ($channel == '__uri') {
- continue;
- }
-
- $this->config->set('default_channel', $channel);
- $state = empty($params[0]) ? $this->config->get('preferred_state') : $params[0];
-
- $caption = $channel . ' Available Upgrades';
- $chan = $reg->getChannel($channel);
- if (PEAR::isError($e = $this->_checkChannelForStatus($channel, $chan))) {
- return $e;
- }
-
- $latest = array();
- $base2 = false;
- $preferred_mirror = $this->config->get('preferred_mirror');
- if ($chan->supportsREST($preferred_mirror) &&
- (
- //($base2 = $chan->getBaseURL('REST1.4', $preferred_mirror)) ||
- ($base = $chan->getBaseURL('REST1.0', $preferred_mirror))
- )
-
- ) {
- if ($base2) {
- $rest = &$this->config->getREST('1.4', array());
- $base = $base2;
- } else {
- $rest = &$this->config->getREST('1.0', array());
- }
-
- if (empty($state) || $state == 'any') {
- $state = false;
- } else {
- $caption .= ' (' . implode(', ', PEAR_Common::betterStates($state, true)) . ')';
- }
-
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- $latest = $rest->listLatestUpgrades($base, $state, $inst, $channel, $reg);
- PEAR::staticPopErrorHandling();
- }
-
- if (PEAR::isError($latest)) {
- $this->ui->outputData($latest->getMessage());
- continue;
- }
-
- $caption .= ':';
- if (PEAR::isError($latest)) {
- $this->config->set('default_channel', $savechannel);
- return $latest;
- }
-
- $data = array(
- 'caption' => $caption,
- 'border' => 1,
- 'headline' => array('Channel', 'Package', 'Local', 'Remote', 'Size'),
- 'channel' => $channel
- );
-
- foreach ((array)$latest as $pkg => $info) {
- $package = strtolower($pkg);
- if (!isset($inst[$package])) {
- // skip packages we don't have installed
- continue;
- }
-
- extract($info);
- $inst_version = $reg->packageInfo($package, 'version', $channel);
- $inst_state = $reg->packageInfo($package, 'release_state', $channel);
- if (version_compare("$version", "$inst_version", "le")) {
- // installed version is up-to-date
- continue;
- }
-
- if ($filesize >= 20480) {
- $filesize += 1024 - ($filesize % 1024);
- $fs = sprintf("%dkB", $filesize / 1024);
- } elseif ($filesize > 0) {
- $filesize += 103 - ($filesize % 103);
- $fs = sprintf("%.1fkB", $filesize / 1024.0);
- } else {
- $fs = " -"; // XXX center instead
- }
-
- $data['data'][] = array($channel, $pkg, "$inst_version ($inst_state)", "$version ($state)", $fs);
- }
-
- if (isset($options['channelinfo'])) {
- if (empty($data['data'])) {
- unset($data['headline']);
- if (count($inst) == 0) {
- $data['data'] = '(no packages installed)';
- } else {
- $data['data'] = '(no upgrades available)';
- }
- }
- $this->ui->outputData($data, $command);
- } else {
- if (empty($data['data'])) {
- $this->ui->outputData('Channel ' . $channel . ': No upgrades available');
- } else {
- $this->ui->outputData($data, $command);
- }
- }
- }
-
- $this->config->set('default_channel', $savechannel);
- return true;
- }
-
- function doClearCache($command, $options, $params)
- {
- $cache_dir = $this->config->get('cache_dir');
- $verbose = $this->config->get('verbose');
- $output = '';
- if (!file_exists($cache_dir) || !is_dir($cache_dir)) {
- return $this->raiseError("$cache_dir does not exist or is not a directory");
- }
-
- if (!($dp = @opendir($cache_dir))) {
- return $this->raiseError("opendir($cache_dir) failed: $php_errormsg");
- }
-
- if ($verbose >= 1) {
- $output .= "reading directory $cache_dir\n";
- }
-
- $num = 0;
- while ($ent = readdir($dp)) {
- if (preg_match('/rest.cache(file|id)\\z/', $ent)) {
- $path = $cache_dir . DIRECTORY_SEPARATOR . $ent;
- if (file_exists($path)) {
- $ok = @unlink($path);
- } else {
- $ok = false;
- $php_errormsg = '';
- }
-
- if ($ok) {
- if ($verbose >= 2) {
- $output .= "deleted $path\n";
- }
- $num++;
- } elseif ($verbose >= 1) {
- $output .= "failed to delete $path $php_errormsg\n";
- }
- }
- }
-
- closedir($dp);
- if ($verbose >= 1) {
- $output .= "$num cache entries cleared\n";
- }
-
- $this->ui->outputData(rtrim($output), $command);
- return $num;
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Remote.xml b/3rdparty/PEAR/Command/Remote.xml
deleted file mode 100644
index b4f6100c79..0000000000
--- a/3rdparty/PEAR/Command/Remote.xml
+++ /dev/null
@@ -1,109 +0,0 @@
-
-
- Information About Remote Packages
- doRemoteInfo
- ri
-
- <package>
-Get details on a package from the server.
-
-
- List Available Upgrades
- doListUpgrades
- lu
-
-
- i
- output fully channel-aware data, even on failure
-
-
- [preferred_state]
-List releases on the server of packages you have installed where
-a newer version is available with the same release state (stable etc.)
-or the state passed as the second parameter.
-
-
- List Remote Packages
- doRemoteList
- rl
-
-
- c
- specify a channel other than the default channel
- CHAN
-
-
-
-Lists the packages available on the configured server along with the
-latest stable release of each package.
-
-
- Search remote package database
- doSearch
- sp
-
-
- c
- specify a channel other than the default channel
- CHAN
-
-
- a
- search packages from all known channels
-
-
- i
- output fully channel-aware data, even on failure
-
-
- [packagename] [packageinfo]
-Lists all packages which match the search parameters. The first
-parameter is a fragment of a packagename. The default channel
-will be used unless explicitly overridden. The second parameter
-will be used to match any portion of the summary/description
-
-
- List All Packages
- doListAll
- la
-
-
- c
- specify a channel other than the default channel
- CHAN
-
-
- i
- output fully channel-aware data, even on failure
-
-
-
-Lists the packages available on the configured server along with the
-latest stable release of each package.
-
-
- Download Package
- doDownload
- d
-
-
- Z
- download an uncompressed (.tar) file
-
-
- <package>...
-Download package tarballs. The files will be named as suggested by the
-server, for example if you download the DB package and the latest stable
-version of DB is 1.6.5, the downloaded file will be DB-1.6.5.tgz.
-
-
- Clear Web Services Cache
- doClearCache
- cc
-
-
-Clear the XML-RPC/REST cache. See also the cache_ttl configuration
-parameter.
-
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Test.php b/3rdparty/PEAR/Command/Test.php
deleted file mode 100644
index a757d9e579..0000000000
--- a/3rdparty/PEAR/Command/Test.php
+++ /dev/null
@@ -1,337 +0,0 @@
-
- * @author Martin Jansen
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Test.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1
- */
-
-/**
- * base class
- */
-require_once 'PEAR/Command/Common.php';
-
-/**
- * PEAR commands for login/logout
- *
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Martin Jansen
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 0.1
- */
-
-class PEAR_Command_Test extends PEAR_Command_Common
-{
- var $commands = array(
- 'run-tests' => array(
- 'summary' => 'Run Regression Tests',
- 'function' => 'doRunTests',
- 'shortcut' => 'rt',
- 'options' => array(
- 'recur' => array(
- 'shortopt' => 'r',
- 'doc' => 'Run tests in child directories, recursively. 4 dirs deep maximum',
- ),
- 'ini' => array(
- 'shortopt' => 'i',
- 'doc' => 'actual string of settings to pass to php in format " -d setting=blah"',
- 'arg' => 'SETTINGS'
- ),
- 'realtimelog' => array(
- 'shortopt' => 'l',
- 'doc' => 'Log test runs/results as they are run',
- ),
- 'quiet' => array(
- 'shortopt' => 'q',
- 'doc' => 'Only display detail for failed tests',
- ),
- 'simple' => array(
- 'shortopt' => 's',
- 'doc' => 'Display simple output for all tests',
- ),
- 'package' => array(
- 'shortopt' => 'p',
- 'doc' => 'Treat parameters as installed packages from which to run tests',
- ),
- 'phpunit' => array(
- 'shortopt' => 'u',
- 'doc' => 'Search parameters for AllTests.php, and use that to run phpunit-based tests
-If none is found, all .phpt tests will be tried instead.',
- ),
- 'tapoutput' => array(
- 'shortopt' => 't',
- 'doc' => 'Output run-tests.log in TAP-compliant format',
- ),
- 'cgi' => array(
- 'shortopt' => 'c',
- 'doc' => 'CGI php executable (needed for tests with POST/GET section)',
- 'arg' => 'PHPCGI',
- ),
- 'coverage' => array(
- 'shortopt' => 'x',
- 'doc' => 'Generate a code coverage report (requires Xdebug 2.0.0+)',
- ),
- ),
- 'doc' => '[testfile|dir ...]
-Run regression tests with PHP\'s regression testing script (run-tests.php).',
- ),
- );
-
- var $output;
-
- /**
- * PEAR_Command_Test constructor.
- *
- * @access public
- */
- function PEAR_Command_Test(&$ui, &$config)
- {
- parent::PEAR_Command_Common($ui, $config);
- }
-
- function doRunTests($command, $options, $params)
- {
- if (isset($options['phpunit']) && isset($options['tapoutput'])) {
- return $this->raiseError('ERROR: cannot use both --phpunit and --tapoutput at the same time');
- }
-
- require_once 'PEAR/Common.php';
- require_once 'System.php';
- $log = new PEAR_Common;
- $log->ui = &$this->ui; // slightly hacky, but it will work
- $tests = array();
- $depth = isset($options['recur']) ? 14 : 1;
-
- if (!count($params)) {
- $params[] = '.';
- }
-
- if (isset($options['package'])) {
- $oldparams = $params;
- $params = array();
- $reg = &$this->config->getRegistry();
- foreach ($oldparams as $param) {
- $pname = $reg->parsePackageName($param, $this->config->get('default_channel'));
- if (PEAR::isError($pname)) {
- return $this->raiseError($pname);
- }
-
- $package = &$reg->getPackage($pname['package'], $pname['channel']);
- if (!$package) {
- return PEAR::raiseError('Unknown package "' .
- $reg->parsedPackageNameToString($pname) . '"');
- }
-
- $filelist = $package->getFilelist();
- foreach ($filelist as $name => $atts) {
- if (isset($atts['role']) && $atts['role'] != 'test') {
- continue;
- }
-
- if (isset($options['phpunit']) && preg_match('/AllTests\.php\\z/i', $name)) {
- $params[] = $atts['installed_as'];
- continue;
- } elseif (!preg_match('/\.phpt\\z/', $name)) {
- continue;
- }
- $params[] = $atts['installed_as'];
- }
- }
- }
-
- foreach ($params as $p) {
- if (is_dir($p)) {
- if (isset($options['phpunit'])) {
- $dir = System::find(array($p, '-type', 'f',
- '-maxdepth', $depth,
- '-name', 'AllTests.php'));
- if (count($dir)) {
- foreach ($dir as $p) {
- $p = realpath($p);
- if (!count($tests) ||
- (count($tests) && strlen($p) < strlen($tests[0]))) {
- // this is in a higher-level directory, use this one instead.
- $tests = array($p);
- }
- }
- }
- continue;
- }
-
- $args = array($p, '-type', 'f', '-name', '*.phpt');
- } else {
- if (isset($options['phpunit'])) {
- if (preg_match('/AllTests\.php\\z/i', $p)) {
- $p = realpath($p);
- if (!count($tests) ||
- (count($tests) && strlen($p) < strlen($tests[0]))) {
- // this is in a higher-level directory, use this one instead.
- $tests = array($p);
- }
- }
- continue;
- }
-
- if (file_exists($p) && preg_match('/\.phpt$/', $p)) {
- $tests[] = $p;
- continue;
- }
-
- if (!preg_match('/\.phpt\\z/', $p)) {
- $p .= '.phpt';
- }
-
- $args = array(dirname($p), '-type', 'f', '-name', $p);
- }
-
- if (!isset($options['recur'])) {
- $args[] = '-maxdepth';
- $args[] = 1;
- }
-
- $dir = System::find($args);
- $tests = array_merge($tests, $dir);
- }
-
- $ini_settings = '';
- if (isset($options['ini'])) {
- $ini_settings .= $options['ini'];
- }
-
- if (isset($_ENV['TEST_PHP_INCLUDE_PATH'])) {
- $ini_settings .= " -d include_path={$_ENV['TEST_PHP_INCLUDE_PATH']}";
- }
-
- if ($ini_settings) {
- $this->ui->outputData('Using INI settings: "' . $ini_settings . '"');
- }
-
- $skipped = $passed = $failed = array();
- $tests_count = count($tests);
- $this->ui->outputData('Running ' . $tests_count . ' tests', $command);
- $start = time();
- if (isset($options['realtimelog']) && file_exists('run-tests.log')) {
- unlink('run-tests.log');
- }
-
- if (isset($options['tapoutput'])) {
- $tap = '1..' . $tests_count . "\n";
- }
-
- require_once 'PEAR/RunTest.php';
- $run = new PEAR_RunTest($log, $options);
- $run->tests_count = $tests_count;
-
- if (isset($options['coverage']) && extension_loaded('xdebug')){
- $run->xdebug_loaded = true;
- } else {
- $run->xdebug_loaded = false;
- }
-
- $j = $i = 1;
- foreach ($tests as $t) {
- if (isset($options['realtimelog'])) {
- $fp = @fopen('run-tests.log', 'a');
- if ($fp) {
- fwrite($fp, "Running test [$i / $tests_count] $t...");
- fclose($fp);
- }
- }
- PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN);
- if (isset($options['phpunit'])) {
- $result = $run->runPHPUnit($t, $ini_settings);
- } else {
- $result = $run->run($t, $ini_settings, $j);
- }
- PEAR::staticPopErrorHandling();
- if (PEAR::isError($result)) {
- $this->ui->log($result->getMessage());
- continue;
- }
-
- if (isset($options['tapoutput'])) {
- $tap .= $result[0] . ' ' . $i . $result[1] . "\n";
- continue;
- }
-
- if (isset($options['realtimelog'])) {
- $fp = @fopen('run-tests.log', 'a');
- if ($fp) {
- fwrite($fp, "$result\n");
- fclose($fp);
- }
- }
-
- if ($result == 'FAILED') {
- $failed[] = $t;
- }
- if ($result == 'PASSED') {
- $passed[] = $t;
- }
- if ($result == 'SKIPPED') {
- $skipped[] = $t;
- }
-
- $j++;
- }
-
- $total = date('i:s', time() - $start);
- if (isset($options['tapoutput'])) {
- $fp = @fopen('run-tests.log', 'w');
- if ($fp) {
- fwrite($fp, $tap, strlen($tap));
- fclose($fp);
- $this->ui->outputData('wrote TAP-format log to "' .realpath('run-tests.log') .
- '"', $command);
- }
- } else {
- if (count($failed)) {
- $output = "TOTAL TIME: $total\n";
- $output .= count($passed) . " PASSED TESTS\n";
- $output .= count($skipped) . " SKIPPED TESTS\n";
- $output .= count($failed) . " FAILED TESTS:\n";
- foreach ($failed as $failure) {
- $output .= $failure . "\n";
- }
-
- $mode = isset($options['realtimelog']) ? 'a' : 'w';
- $fp = @fopen('run-tests.log', $mode);
-
- if ($fp) {
- fwrite($fp, $output, strlen($output));
- fclose($fp);
- $this->ui->outputData('wrote log to "' . realpath('run-tests.log') . '"', $command);
- }
- } elseif (file_exists('run-tests.log') && !is_dir('run-tests.log')) {
- @unlink('run-tests.log');
- }
- }
- $this->ui->outputData('TOTAL TIME: ' . $total);
- $this->ui->outputData(count($passed) . ' PASSED TESTS', $command);
- $this->ui->outputData(count($skipped) . ' SKIPPED TESTS', $command);
- if (count($failed)) {
- $this->ui->outputData(count($failed) . ' FAILED TESTS:', $command);
- foreach ($failed as $failure) {
- $this->ui->outputData($failure, $command);
- }
- }
-
- return true;
- }
-}
\ No newline at end of file
diff --git a/3rdparty/PEAR/Command/Test.xml b/3rdparty/PEAR/Command/Test.xml
deleted file mode 100644
index bbe9fcccc5..0000000000
--- a/3rdparty/PEAR/Command/Test.xml
+++ /dev/null
@@ -1,54 +0,0 @@
-
-
- Run Regression Tests
- doRunTests
- rt
-
-
- r
- Run tests in child directories, recursively. 4 dirs deep maximum
-
-
- i
- actual string of settings to pass to php in format " -d setting=blah"
- SETTINGS
-
-
- l
- Log test runs/results as they are run
-
-
- q
- Only display detail for failed tests
-
-
- s
- Display simple output for all tests
-
-
- p
- Treat parameters as installed packages from which to run tests
-
-
- u
- Search parameters for AllTests.php, and use that to run phpunit-based tests
-If none is found, all .phpt tests will be tried instead.
-
-
- t
- Output run-tests.log in TAP-compliant format
-
-
- c
- CGI php executable (needed for tests with POST/GET section)
- PHPCGI
-
-
- x
- Generate a code coverage report (requires Xdebug 2.0.0+)
-
-
- [testfile|dir ...]
-Run regression tests with PHP's regression testing script (run-tests.php).
-
-
\ No newline at end of file
diff --git a/3rdparty/PEAR/Common.php b/3rdparty/PEAR/Common.php
deleted file mode 100644
index 83f2de742a..0000000000
--- a/3rdparty/PEAR/Common.php
+++ /dev/null
@@ -1,837 +0,0 @@
-
- * @author Tomas V. V. Cox
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version CVS: $Id: Common.php 313023 2011-07-06 19:17:11Z dufuz $
- * @link http://pear.php.net/package/PEAR
- * @since File available since Release 0.1.0
- * @deprecated File deprecated since Release 1.4.0a1
- */
-
-/**
- * Include error handling
- */
-require_once 'PEAR.php';
-
-/**
- * PEAR_Common error when an invalid PHP file is passed to PEAR_Common::analyzeSourceCode()
- */
-define('PEAR_COMMON_ERROR_INVALIDPHP', 1);
-define('_PEAR_COMMON_PACKAGE_NAME_PREG', '[A-Za-z][a-zA-Z0-9_]+');
-define('PEAR_COMMON_PACKAGE_NAME_PREG', '/^' . _PEAR_COMMON_PACKAGE_NAME_PREG . '\\z/');
-
-// this should allow: 1, 1.0, 1.0RC1, 1.0dev, 1.0dev123234234234, 1.0a1, 1.0b1, 1.0pl1
-define('_PEAR_COMMON_PACKAGE_VERSION_PREG', '\d+(?:\.\d+)*(?:[a-zA-Z]+\d*)?');
-define('PEAR_COMMON_PACKAGE_VERSION_PREG', '/^' . _PEAR_COMMON_PACKAGE_VERSION_PREG . '\\z/i');
-
-// XXX far from perfect :-)
-define('_PEAR_COMMON_PACKAGE_DOWNLOAD_PREG', '(' . _PEAR_COMMON_PACKAGE_NAME_PREG .
- ')(-([.0-9a-zA-Z]+))?');
-define('PEAR_COMMON_PACKAGE_DOWNLOAD_PREG', '/^' . _PEAR_COMMON_PACKAGE_DOWNLOAD_PREG .
- '\\z/');
-
-define('_PEAR_CHANNELS_NAME_PREG', '[A-Za-z][a-zA-Z0-9\.]+');
-define('PEAR_CHANNELS_NAME_PREG', '/^' . _PEAR_CHANNELS_NAME_PREG . '\\z/');
-
-// this should allow any dns or IP address, plus a path - NO UNDERSCORES ALLOWED
-define('_PEAR_CHANNELS_SERVER_PREG', '[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)*(\/[a-zA-Z0-9\-]+)*');
-define('PEAR_CHANNELS_SERVER_PREG', '/^' . _PEAR_CHANNELS_SERVER_PREG . '\\z/i');
-
-define('_PEAR_CHANNELS_PACKAGE_PREG', '(' ._PEAR_CHANNELS_SERVER_PREG . ')\/('
- . _PEAR_COMMON_PACKAGE_NAME_PREG . ')');
-define('PEAR_CHANNELS_PACKAGE_PREG', '/^' . _PEAR_CHANNELS_PACKAGE_PREG . '\\z/i');
-
-define('_PEAR_COMMON_CHANNEL_DOWNLOAD_PREG', '(' . _PEAR_CHANNELS_NAME_PREG . ')::('
- . _PEAR_COMMON_PACKAGE_NAME_PREG . ')(-([.0-9a-zA-Z]+))?');
-define('PEAR_COMMON_CHANNEL_DOWNLOAD_PREG', '/^' . _PEAR_COMMON_CHANNEL_DOWNLOAD_PREG . '\\z/');
-
-/**
- * List of temporary files and directories registered by
- * PEAR_Common::addTempFile().
- * @var array
- */
-$GLOBALS['_PEAR_Common_tempfiles'] = array();
-
-/**
- * Valid maintainer roles
- * @var array
- */
-$GLOBALS['_PEAR_Common_maintainer_roles'] = array('lead','developer','contributor','helper');
-
-/**
- * Valid release states
- * @var array
- */
-$GLOBALS['_PEAR_Common_release_states'] = array('alpha','beta','stable','snapshot','devel');
-
-/**
- * Valid dependency types
- * @var array
- */
-$GLOBALS['_PEAR_Common_dependency_types'] = array('pkg','ext','php','prog','ldlib','rtlib','os','websrv','sapi');
-
-/**
- * Valid dependency relations
- * @var array
- */
-$GLOBALS['_PEAR_Common_dependency_relations'] = array('has','eq','lt','le','gt','ge','not', 'ne');
-
-/**
- * Valid file roles
- * @var array
- */
-$GLOBALS['_PEAR_Common_file_roles'] = array('php','ext','test','doc','data','src','script');
-
-/**
- * Valid replacement types
- * @var array
- */
-$GLOBALS['_PEAR_Common_replacement_types'] = array('php-const', 'pear-config', 'package-info');
-
-/**
- * Valid "provide" types
- * @var array
- */
-$GLOBALS['_PEAR_Common_provide_types'] = array('ext', 'prog', 'class', 'function', 'feature', 'api');
-
-/**
- * Valid "provide" types
- * @var array
- */
-$GLOBALS['_PEAR_Common_script_phases'] = array('pre-install', 'post-install', 'pre-uninstall', 'post-uninstall', 'pre-build', 'post-build', 'pre-configure', 'post-configure', 'pre-setup', 'post-setup');
-
-/**
- * Class providing common functionality for PEAR administration classes.
- * @category pear
- * @package PEAR
- * @author Stig Bakken
- * @author Tomas V. V. Cox
- * @author Greg Beaver
- * @copyright 1997-2009 The Authors
- * @license http://opensource.org/licenses/bsd-license.php New BSD License
- * @version Release: 1.9.4
- * @link http://pear.php.net/package/PEAR
- * @since Class available since Release 1.4.0a1
- * @deprecated This class will disappear, and its components will be spread
- * into smaller classes, like the AT&T breakup, as of Release 1.4.0a1
- */
-class PEAR_Common extends PEAR
-{
- /**
- * User Interface object (PEAR_Frontend_* class). If null,
- * the log() method uses print.
- * @var object
- */
- var $ui = null;
-
- /**
- * Configuration object (PEAR_Config).
- * @var PEAR_Config
- */
- var $config = null;
-
- /** stack of elements, gives some sort of XML context */
- var $element_stack = array();
-
- /** name of currently parsed XML element */
- var $current_element;
-
- /** array of attributes of the currently parsed XML element */
- var $current_attributes = array();
-
- /** assoc with information about a package */
- var $pkginfo = array();
-
- var $current_path = null;
-
- /**
- * Flag variable used to mark a valid package file
- * @var boolean
- * @access private
- */
- var $_validPackageFile;
-
- /**
- * PEAR_Common constructor
- *
- * @access public
- */
- function PEAR_Common()
- {
- parent::PEAR();
- $this->config = PEAR_Config::singleton();
- $this->debug = $this->config->get('verbose');
- }
-
- /**
- * PEAR_Common destructor
- *
- * @access private
- */
- function _PEAR_Common()
- {
- // doesn't work due to bug #14744
- //$tempfiles = $this->_tempfiles;
- $tempfiles =& $GLOBALS['_PEAR_Common_tempfiles'];
- while ($file = array_shift($tempfiles)) {
- if (@is_dir($file)) {
- if (!class_exists('System')) {
- require_once 'System.php';
- }
-
- System::rm(array('-rf', $file));
- } elseif (file_exists($file)) {
- unlink($file);
- }
- }
- }
-
- /**
- * Register a temporary file or directory. When the destructor is
- * executed, all registered temporary files and directories are
- * removed.
- *
- * @param string $file name of file or directory
- *
- * @return void
- *
- * @access public
- */
- function addTempFile($file)
- {
- if (!class_exists('PEAR_Frontend')) {
- require_once 'PEAR/Frontend.php';
- }
- PEAR_Frontend::addTempFile($file);
- }
-
- /**
- * Wrapper to System::mkDir(), creates a directory as well as
- * any necessary parent directories.
- *
- * @param string $dir directory name
- *
- * @return bool TRUE on success, or a PEAR error
- *
- * @access public
- */
- function mkDirHier($dir)
- {
- // Only used in Installer - move it there ?
- $this->log(2, "+ create dir $dir");
- if (!class_exists('System')) {
- require_once 'System.php';
- }
- return System::mkDir(array('-p', $dir));
- }
-
- /**
- * Logging method.
- *
- * @param int $level log level (0 is quiet, higher is noisier)
- * @param string $msg message to write to the log
- *
- * @return void
- *
- * @access public
- * @static
- */
- function log($level, $msg, $append_crlf = true)
- {
- if ($this->debug >= $level) {
- if (!class_exists('PEAR_Frontend')) {
- require_once 'PEAR/Frontend.php';
- }
-
- $ui = &PEAR_Frontend::singleton();
- if (is_a($ui, 'PEAR_Frontend')) {
- $ui->log($msg, $append_crlf);
- } else {
- print "$msg\n";
- }
- }
- }
-
- /**
- * Create and register a temporary directory.
- *
- * @param string $tmpdir (optional) Directory to use as tmpdir.
- * Will use system defaults (for example
- * /tmp or c:\windows\temp) if not specified
- *
- * @return string name of created directory
- *
- * @access public
- */
- function mkTempDir($tmpdir = '')
- {
- $topt = $tmpdir ? array('-t', $tmpdir) : array();
- $topt = array_merge($topt, array('-d', 'pear'));
- if (!class_exists('System')) {
- require_once 'System.php';
- }
-
- if (!$tmpdir = System::mktemp($topt)) {
- return false;
- }
-
- $this->addTempFile($tmpdir);
- return $tmpdir;
- }
-
- /**
- * Set object that represents the frontend to be used.
- *
- * @param object Reference of the frontend object
- * @return void
- * @access public
- */
- function setFrontendObject(&$ui)
- {
- $this->ui = &$ui;
- }
-
- /**
- * Return an array containing all of the states that are more stable than
- * or equal to the passed in state
- *
- * @param string Release state
- * @param boolean Determines whether to include $state in the list
- * @return false|array False if $state is not a valid release state
- */
- function betterStates($state, $include = false)
- {
- static $states = array('snapshot', 'devel', 'alpha', 'beta', 'stable');
- $i = array_search($state, $states);
- if ($i === false) {
- return false;
- }
- if ($include) {
- $i--;
- }
- return array_slice($states, $i + 1);
- }
-
- /**
- * Get the valid roles for a PEAR package maintainer
- *
- * @return array
- * @static
- */
- function getUserRoles()
- {
- return $GLOBALS['_PEAR_Common_maintainer_roles'];
- }
-
- /**
- * Get the valid package release states of packages
- *
- * @return array
- * @static
- */
- function getReleaseStates()
- {
- return $GLOBALS['_PEAR_Common_release_states'];
- }
-
- /**
- * Get the implemented dependency types (php, ext, pkg etc.)
- *
- * @return array
- * @static
- */
- function getDependencyTypes()
- {
- return $GLOBALS['_PEAR_Common_dependency_types'];
- }
-
- /**
- * Get the implemented dependency relations (has, lt, ge etc.)
- *
- * @return array
- * @static
- */
- function getDependencyRelations()
- {
- return $GLOBALS['_PEAR_Common_dependency_relations'];
- }
-
- /**
- * Get the implemented file roles
- *
- * @return array
- * @static
- */
- function getFileRoles()
- {
- return $GLOBALS['_PEAR_Common_file_roles'];
- }
-
- /**
- * Get the implemented file replacement types in
- *
- * @return array
- * @static
- */
- function getReplacementTypes()
- {
- return $GLOBALS['_PEAR_Common_replacement_types'];
- }
-
- /**
- * Get the implemented file replacement types in
- *
- * @return array
- * @static
- */
- function getProvideTypes()
- {
- return $GLOBALS['_PEAR_Common_provide_types'];
- }
-
- /**
- * Get the implemented file replacement types in
- *
- * @return array
- * @static
- */
- function getScriptPhases()
- {
- return $GLOBALS['_PEAR_Common_script_phases'];
- }
-
- /**
- * Test whether a string contains a valid package name.
- *
- * @param string $name the package name to test
- *
- * @return bool
- *
- * @access public
- */
- function validPackageName($name)
- {
- return (bool)preg_match(PEAR_COMMON_PACKAGE_NAME_PREG, $name);
- }
-
- /**
- * Test whether a string contains a valid package version.
- *
- * @param string $ver the package version to test
- *
- * @return bool
- *
- * @access public
- */
- function validPackageVersion($ver)
- {
- return (bool)preg_match(PEAR_COMMON_PACKAGE_VERSION_PREG, $ver);
- }
-
- /**
- * @param string $path relative or absolute include path
- * @return boolean
- * @static
- */
- function isIncludeable($path)
- {
- if (file_exists($path) && is_readable($path)) {
- return true;
- }
-
- $ipath = explode(PATH_SEPARATOR, ini_get('include_path'));
- foreach ($ipath as $include) {
- $test = realpath($include . DIRECTORY_SEPARATOR . $path);
- if (file_exists($test) && is_readable($test)) {
- return true;
- }
- }
-
- return false;
- }
-
- function _postProcessChecks($pf)
- {
- if (!PEAR::isError($pf)) {
- return $this->_postProcessValidPackagexml($pf);
- }
-
- $errs = $pf->getUserinfo();
- if (is_array($errs)) {
- foreach ($errs as $error) {
- $e = $this->raiseError($error['message'], $error['code'], null, null, $error);
- }
- }
-
- return $pf;
- }
-
- /**
- * Returns information about a package file. Expects the name of
- * a gzipped tar file as input.
- *
- * @param string $file name of .tgz file
- *
- * @return array array with package information
- *
- * @access public
- * @deprecated use PEAR_PackageFile->fromTgzFile() instead
- *
- */
- function infoFromTgzFile($file)
- {
- $packagefile = &new PEAR_PackageFile($this->config);
- $pf = &$packagefile->fromTgzFile($file, PEAR_VALIDATE_NORMAL);
- return $this->_postProcessChecks($pf);
- }
-
- /**
- * Returns information about a package file. Expects the name of
- * a package xml file as input.
- *
- * @param string $descfile name of package xml file
- *
- * @return array array with package information
- *
- * @access public
- * @deprecated use PEAR_PackageFile->fromPackageFile() instead
- *
- */
- function infoFromDescriptionFile($descfile)
- {
- $packagefile = &new PEAR_PackageFile($this->config);
- $pf = &$packagefile->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
- return $this->_postProcessChecks($pf);
- }
-
- /**
- * Returns information about a package file. Expects the contents
- * of a package xml file as input.
- *
- * @param string $data contents of package.xml file
- *
- * @return array array with package information
- *
- * @access public
- * @deprecated use PEAR_PackageFile->fromXmlstring() instead
- *
- */
- function infoFromString($data)
- {
- $packagefile = &new PEAR_PackageFile($this->config);
- $pf = &$packagefile->fromXmlString($data, PEAR_VALIDATE_NORMAL, false);
- return $this->_postProcessChecks($pf);
- }
-
- /**
- * @param PEAR_PackageFile_v1|PEAR_PackageFile_v2
- * @return array
- */
- function _postProcessValidPackagexml(&$pf)
- {
- if (!is_a($pf, 'PEAR_PackageFile_v2')) {
- $this->pkginfo = $pf->toArray();
- return $this->pkginfo;
- }
-
- // sort of make this into a package.xml 1.0-style array
- // changelog is not converted to old format.
- $arr = $pf->toArray(true);
- $arr = array_merge($arr, $arr['old']);
- unset($arr['old'], $arr['xsdversion'], $arr['contents'], $arr['compatible'],
- $arr['channel'], $arr['uri'], $arr['dependencies'], $arr['phprelease'],
- $arr['extsrcrelease'], $arr['zendextsrcrelease'], $arr['extbinrelease'],
- $arr['zendextbinrelease'], $arr['bundle'], $arr['lead'], $arr['developer'],
- $arr['helper'], $arr['contributor']);
- $arr['filelist'] = $pf->getFilelist();
- $this->pkginfo = $arr;
- return $arr;
- }
-
- /**
- * Returns package information from different sources
- *
- * This method is able to extract information about a package
- * from a .tgz archive or from a XML package definition file.
- *
- * @access public
- * @param string Filename of the source ('package.xml', '