From 4eeb9c5b9944368611447530ef17007f9e4a9cce Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Sat, 7 Jul 2012 11:30:48 -0400 Subject: Fix indentation and lower case the whole url inside handle() instead of calling for each parameter --- lib/ocs.php | 803 ++++++++++++++++++++++++++++++------------------------------ 1 file changed, 399 insertions(+), 404 deletions(-) (limited to 'lib') diff --git a/lib/ocs.php b/lib/ocs.php index 1be41202d78..25854e9ea33 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; - } - } - } - - 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); } - } + /** + * 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); } + } /** 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(); - } - - // preprocess url - $url=$_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); - - // 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); - - // 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); - - // 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); - - // 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); - - }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); - - // 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); - - }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(); - } + 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(); + } - /** - * 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); - } + // 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 ($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'); + OC_OCS::personcheck($format,$login,$passwd); + + // 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 ($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 ($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'); + 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); - /** - * 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); - } + }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); + } - /** - * 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); - - }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); - - }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); - } - - } - } + /** + * 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. + * @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); + + }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); + + }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); + } - /** - * 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)); - } + xmlwriter_end_element($writer); + xmlwriter_end_document( $writer ); + $txt.=xmlwriter_output_memory( $writer ); + unset($writer); + return($txt); + } + } - /** - * 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 ############################################# + 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); + } + } + } - /** - * 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 - */ + /** + * 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)); + } + + + /** + * 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)){ -- cgit v1.2.3 From e8657c51ba8499fe0f0f46eaa1a8503bff2d2b2a Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Sat, 7 Jul 2012 14:51:06 -0400 Subject: Implement PERSON add --- lib/ocs.php | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/ocs.php b/lib/ocs.php index 25854e9ea33..309e3bb0647 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')){ -- cgit v1.2.3 From 7de97ed20003d1f5ab9e2bfde9386bba07d0eff8 Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Sat, 7 Jul 2012 16:54:07 -0400 Subject: Make readData() exit with a 400 Bad Request for not provided required parameters, and sanitize text --- lib/ocs.php | 95 ++++++++++++++++++++++++++----------------------------------- 1 file changed, 41 insertions(+), 54 deletions(-) (limited to 'lib') diff --git a/lib/ocs.php b/lib/ocs.php index 309e3bb0647..5e697b48304 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(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 if ($method == 'post') { + if (isset($_POST[$key])) { + $data = $_POST[$key]; + } else if (isset($default)) { + return $default; } else { - $data=$default; + $data = false; } } + if ($data === false) { + echo self::generateXml('', 'fail', 400, 'Bad request. Please provide a valid '.$key); + exit(); + } else { + // 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)); -- cgit v1.2.3 From 20838bb9c2f77bf45cf7e4bccf9f941cbc39bbdb Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sat, 28 Jul 2012 21:40:11 +0000 Subject: Basic structure and functionality of api class --- lib/api.php | 91 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 lib/api.php (limited to 'lib') diff --git a/lib/api.php b/lib/api.php new file mode 100644 index 00000000000..767f1d30b7d --- /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 -- cgit v1.2.3 From c375774fca619ee4bd886a9c675908c4006cc980 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sat, 28 Jul 2012 21:50:40 +0000 Subject: Fix odd indentation issue --- lib/api.php | 178 ++++++++++++++++++++++++++++++------------------------------ 1 file changed, 89 insertions(+), 89 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 767f1d30b7d..eaa2bb42f8c 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 -- cgit v1.2.3 From 9dbe5f3703afd84c701d0d1347c06f1b07ff7fe6 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sat, 28 Jul 2012 21:57:24 +0000 Subject: Load routes before calling actions --- lib/api.php | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index eaa2bb42f8c..cf40167b07a 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 -- cgit v1.2.3 From 038af7e636ad8a2dc9ac342eaecd176cc5c35256 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sun, 29 Jul 2012 15:29:26 +0000 Subject: 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 (limited to 'lib') diff --git a/lib/app.php b/lib/app.php old mode 100755 new mode 100644 index 56132c08671..60bd0ef476b --- 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 -- cgit v1.2.3 From e33174f115d7459afb15131f0bc4a6386a673608 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 10:56:21 +0000 Subject: 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 (limited to 'lib') diff --git a/core/routes.php b/core/routes.php new file mode 100644 index 00000000000..4c5004dcf5a --- /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 cf40167b07a..b1176a07077 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(); -- cgit v1.2.3 From 9072106048265ce144227605c8919104acf6d746 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 12:42:18 +0000 Subject: 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 (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index b1176a07077..2203d86ac94 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 00000000000..3b090376e72 --- /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 00000000000..d0cd72e98c5 --- /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 00000000000..b736abe3b9c --- /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 00000000000..f4e4be5ee09 --- /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 00000000000..cb62d60a8d3 --- /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 -- cgit v1.2.3 From 9ffaea480fc77514ac1804ad3ca72487c7ba40e4 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 12:44:34 +0000 Subject: Add the format parameter inside OC_API --- lib/api.php | 2 +- ocs/routes.php | 22 +++++++++++----------- 2 files changed, 12 insertions(+), 12 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 2203d86ac94..c61f50c1bc9 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 e2f70342b85..2f8ab2a8f6a 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 -- cgit v1.2.3 From b563dff10a60e08ad270dc78404102f082abf184 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 12:56:01 +0000 Subject: Record the app that is registering a call to use later with OAuth --- lib/api.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index c61f50c1bc9..46f58debdcf 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); -- cgit v1.2.3 From b0dc4383e14713a79c67f71e8e3f3c1c09d8958c Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 12:57:35 +0000 Subject: Clean code slightly --- lib/api.php | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 46f58debdcf..17663b53b84 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 -- cgit v1.2.3 From c7c16ac49b661d5087cd64612bce1da5630424b0 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 13:39:06 +0000 Subject: Improve merging of api responses --- lib/api.php | 47 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 12 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 17663b53b84..02c3f77e5c2 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 -- cgit v1.2.3 From 3a0e3708a50a0672c94c79e165aa834dfe8f4e9a Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 14:26:15 +0000 Subject: Add public class for registering api calls --- lib/public/api.php | 41 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 lib/public/api.php (limited to 'lib') diff --git a/lib/public/api.php b/lib/public/api.php new file mode 100644 index 00000000000..270aa893297 --- /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); + } + +} -- cgit v1.2.3 From 2f84a8d74627cb20cfae1ac4c004af393b8b07de Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 30 Jul 2012 16:04:09 +0000 Subject: Merge the responses recursively --- lib/api.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 02c3f77e5c2..757e53226b9 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; } -- cgit v1.2.3 From 0271bfa3b7849de64bfbb9dd96313fc35da14e29 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 20:48:03 +0200 Subject: Move loading of routes to OC_Router --- lib/api.php | 19 ------------------- lib/router.php | 15 +++++++++++++++ 2 files changed, 15 insertions(+), 19 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 757e53226b9..00a3dc108e1 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 f037ecdfef4..f76f64ac82b 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(); -- cgit v1.2.3 From 95d3b83a77f189569bbf38a54f771af1b85a9406 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 20:50:32 +0200 Subject: Create OC_Router in OC::init --- lib/base.php | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'lib') diff --git a/lib/base.php b/lib/base.php index 5041f43648e..29a3502e352 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; -- cgit v1.2.3 From 180bd69dbb21dc6e53533a7d93972445b2ff922e Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 20:52:47 +0200 Subject: Fix OC_API::register --- lib/api.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 00a3dc108e1..fd2c621f389 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(); } -- cgit v1.2.3 From 7a24f0cd8d28e60360127da19e40bff4b2e04168 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 21:03:41 +0200 Subject: 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(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index fd2c621f389..515bab6714e 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 60bd0ef476b..7863153d9b9 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 d7a7951fab5..780fd4a6581 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 ab0dc80f4ba..4580221e600 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(); +} -- cgit v1.2.3 From 0a9ca42c3479e1ebd0efee2bfae10958677bb657 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Mon, 30 Jul 2012 21:13:29 +0200 Subject: Fix OC_OCS_Privatedata::privateDataGet --- lib/ocs/privatedata.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/ocs/privatedata.php b/lib/ocs/privatedata.php index cb62d60a8d3..77214046911 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 +?> -- cgit v1.2.3 From cc6911e1f709edc42ea5558e19fcdeea75cdcf39 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 09:28:12 +0000 Subject: Make method static --- lib/public/api.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib') diff --git a/lib/public/api.php b/lib/public/api.php index 270aa893297..518e6f00970 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); } -- cgit v1.2.3 From b05639e745cabf8d11785f673593680448d844a2 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 10:10:15 +0000 Subject: Fix error with namespacing --- lib/public/api.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib') diff --git a/lib/public/api.php b/lib/public/api.php index 518e6f00970..ed1f6ef237c 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); } } -- cgit v1.2.3 From 5922599f48b8eb2403265f4e4a5dad3899d3ebc6 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 12:10:42 +0100 Subject: Handle function not needed in lib/ocs.php --- lib/ocs.php | 181 ------------------------------------------------------------ 1 file changed, 181 deletions(-) (limited to 'lib') diff --git a/lib/ocs.php b/lib/ocs.php index 780fd4a6581..d0b835b522b 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'; -- cgit v1.2.3 From 78bbcc8aeac5585a11dca0c1dc77cdd420182744 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 14:34:45 +0100 Subject: Basic OAuth class based on oauth-php. WIP --- lib/oauth.php | 128 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 128 insertions(+) create mode 100644 lib/oauth.php (limited to 'lib') diff --git a/lib/oauth.php b/lib/oauth.php new file mode 100644 index 00000000000..0eade6ab906 --- /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 -- cgit v1.2.3 From ce41f3801eecc47f578ce8698cc69de16a16330b Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 14:59:07 +0100 Subject: Actually login the user when using OAuth --- lib/oauth.php | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'lib') diff --git a/lib/oauth.php b/lib/oauth.php index 0eade6ab906..f0341b4b0d8 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 -- cgit v1.2.3 From fcf3dbcfc13888a795a85f54179dfd548b34d4aa Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 31 Jul 2012 15:02:51 +0100 Subject: Require a username for OC_OAuth::registerConsumer() --- lib/oauth.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/oauth.php b/lib/oauth.php index f0341b4b0d8..98678d29110 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; } -- cgit v1.2.3 From c2bdb5c71640567e0be3c2fc7e4d32af1469a55e Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 22:18:16 +0200 Subject: Fix require 3rdpartypath --- lib/oauth.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/oauth.php b/lib/oauth.php index 98678d29110..09dbe4cc755 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 -- cgit v1.2.3 From 28537037ae27a8e766d3c4ef129422dc02b45d5f Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 22:19:11 +0200 Subject: 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(-) (limited to 'lib') diff --git a/lib/ocs/activity.php b/lib/ocs/activity.php index 3b090376e72..07b571665ec 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 d0cd72e98c5..2f2aad714a3 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 b736abe3b9c..06103cbeb4f 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 f4e4be5ee09..629a7c2e6c7 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 77214046911..1c781dece8a 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 a913254ebe8..95df0c7ec91 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'); ?> -- cgit v1.2.3 From 9d6a09f58946c8d4e7903d5b25a5fb00f6bcb5e8 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 22:33:11 +0200 Subject: Routing: Method needs to be uppercase --- lib/route.php | 10 +++++----- lib/router.php | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'lib') diff --git a/lib/route.php b/lib/route.php index 0d3339add6c..df3a18e844f 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 f76f64ac82b..c3864cfc91c 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']); -- cgit v1.2.3 From 71918a820f0e5b7e9479711107db059cd3a3b194 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 22:34:35 +0200 Subject: API: set request method for registered urls --- lib/api.php | 1 + 1 file changed, 1 insertion(+) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 515bab6714e..203b07880fd 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'); -- cgit v1.2.3 From 7426217e760601f684c402bf363a51bb8c79947c Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Tue, 31 Jul 2012 23:26:15 +0200 Subject: Fix /privatedata/getattribute route --- lib/api.php | 10 ++++++---- ocs/routes.php | 2 ++ 2 files changed, 8 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 203b07880fd..cf699f547f3 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 95df0c7ec91..ac23e29af8a 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'); -- cgit v1.2.3 From e7f7693b2f28ad87c232db51f1101e720fb29623 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 1 Aug 2012 10:21:33 +0100 Subject: Fix 3rdparty paths, initialise OAuth in correct order --- lib/oauth.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/oauth.php b/lib/oauth.php index 09dbe4cc755..0c6e9af7252 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(); -- cgit v1.2.3 From e315384b4ddc207c1b3f142df4a57e8004a88966 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 1 Aug 2012 10:40:09 +0100 Subject: Remove unnecessary include --- lib/oauth.php | 1 - 1 file changed, 1 deletion(-) (limited to 'lib') diff --git a/lib/oauth.php b/lib/oauth.php index 0c6e9af7252..0621a72a72b 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 -- cgit v1.2.3 From 2afe5f9b2b59094b632e79e0a0fec0cd70509273 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 1 Aug 2012 13:37:00 +0000 Subject: API: add OC_API::checkLoggedIn() --- lib/api.php | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index cf699f547f3..a11dde1c6b8 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(); + } + } + } -- cgit v1.2.3 From c11c2d0fd46fbe2e74ff7fe2ff7205c5cb38ea9f Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 1 Aug 2012 13:39:05 +0000 Subject: Logout the user at the end of a call to be stateless --- lib/api.php | 2 ++ 1 file changed, 2 insertions(+) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index a11dde1c6b8..454a6fd26d3 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(); } /** -- cgit v1.2.3 From 93daa9e247e9c423a6d4bb10af1106fdde37b800 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Wed, 1 Aug 2012 19:48:51 +0200 Subject: API: Complete respond function --- lib/api.php | 25 ++++++++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 454a6fd26d3..6ee570d60e7 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 -- cgit v1.2.3 From 7952c6a31c27718428fddbca71c587506eb071d8 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 2 Aug 2012 17:47:38 +0200 Subject: 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(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 6ee570d60e7..155082fa0d0 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 29a3502e352..43588944d04 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 7cd61035e7c..cb8a1faf876 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) { -- cgit v1.2.3 From 37ef522b057caf0a0058f6be87db39f7a4f1e174 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 2 Aug 2012 17:48:09 +0200 Subject: Quick fix for xml encoding arrays --- lib/api.php | 3 +++ 1 file changed, 3 insertions(+) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 155082fa0d0..1ef4e090e37 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); -- cgit v1.2.3 From 6ba2623485655460440a972e34a8a2a2fda02821 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 2 Aug 2012 17:59:18 +0200 Subject: 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(-) (limited to 'lib') diff --git a/lib/base.php b/lib/base.php index 43588944d04..0d9ececc0c9 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 c3864cfc91c..5c5171cf82d 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 cb8a1faf876..938a57009f7 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']); -- cgit v1.2.3 From 4b9200f6f7a571c251ef89599e1af9e25e2e75f4 Mon Sep 17 00:00:00 2001 From: Bart Visscher Date: Thu, 2 Aug 2012 21:51:31 +0200 Subject: 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(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 1ef4e090e37..05d34ffe870 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 5c5171cf82d..12cd55df414 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 938a57009f7..ce6bad3d450 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) { -- cgit v1.2.3 From e3d88270cc0fcdfc667f0a120040864818b3b2a1 Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Thu, 2 Aug 2012 20:02:31 -0400 Subject: 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 (limited to 'lib') diff --git a/3rdparty/OAuth/LICENSE.TXT b/3rdparty/OAuth/LICENSE.TXT new file mode 100644 index 00000000000..8891c7ddc90 --- /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 00000000000..64b7007ab9d --- /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 05d34ffe870..c8bd0aec2fa 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 0621a72a72b..b72d9aab446 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(); - } - - /** - * 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); +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); } - /** - * 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 2592b926d17..9e7a3c04935 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: /'); -- cgit v1.2.3 From a7906d813ad342f06d4834c10c1200002f7342d2 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 3 Aug 2012 11:47:05 +0000 Subject: Move OAuth classes into lib/oauth --- lib/api.php | 4 +-- lib/oauth.php | 69 ----------------------------------------------- lib/oauth/server.php | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++ lib/oauth/store.php | 29 ++++++++++++++++++++ settings/oauth.php | 2 +- 5 files changed, 108 insertions(+), 72 deletions(-) delete mode 100644 lib/oauth.php create mode 100644 lib/oauth/server.php create mode 100644 lib/oauth/store.php (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index c8bd0aec2fa..8fdfc63070b 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.php deleted file mode 100644 index b72d9aab446..00000000000 --- a/lib/oauth.php +++ /dev/null @@ -1,69 +0,0 @@ -. -* -*/ - -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); - } - - 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()); - } - - /** - * 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($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/lib/oauth/server.php b/lib/oauth/server.php new file mode 100644 index 00000000000..c563c527601 --- /dev/null +++ b/lib/oauth/server.php @@ -0,0 +1,76 @@ +. +* +*/ + +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); + } + + /** + * 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); + $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()); + } + + /** + * 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($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/lib/oauth/store.php b/lib/oauth/store.php new file mode 100644 index 00000000000..2f58e46b5b0 --- /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 b04c798b1b0..7f30161d852 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': -- cgit v1.2.3 From 6047a5fe515091d755e964c24de93fc29a5f9754 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 3 Aug 2012 11:56:11 +0000 Subject: 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(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 8fdfc63070b..90f36aefbcd 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 c563c527601..b14277afea1 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; } -- cgit v1.2.3 From 21f8646ffc9057bd15fe8a30b781ee20766b5656 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 3 Aug 2012 15:20:01 +0000 Subject: 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(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 90f36aefbcd..c91216179e2 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 7f30161d852..f088453a26a 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; } -- cgit v1.2.3 From 0d1d2c0b61a4a0bcbc4b08a927fa815f4673d31e Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 30 Aug 2012 14:01:27 +0000 Subject: Fix class name --- lib/api.php | 2 +- settings/oauth.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index c91216179e2..55de438f429 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 f088453a26a..c6c9be515bf 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; -- cgit v1.2.3 From 67c2d56be81a48ba63ce92d5fa0ff339be9ca5a5 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 30 Aug 2012 14:02:31 +0000 Subject: Add ownCloud OAuth store backend. WIP --- lib/oauth/store.php | 74 +++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 69 insertions(+), 5 deletions(-) (limited to 'lib') diff --git a/lib/oauth/store.php b/lib/oauth/store.php index 2f58e46b5b0..f1df7d49b93 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 -- cgit v1.2.3 From 37bb16becb11caf80fd2e4f608e16f7642c76137 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 4 Sep 2012 11:10:42 +0000 Subject: 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(-) (limited to 'lib') diff --git a/lib/oauth/server.php b/lib/oauth/server.php index b14277afea1..a82a1e2fb0e 100644 --- a/lib/oauth/server.php +++ b/lib/oauth/server.php @@ -26,16 +26,31 @@ 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 * @param string $request the request token to authorise @@ -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 f1df7d49b93..aa68d38957d 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 c6c9be515bf..8dba9b33a53 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); -- cgit v1.2.3 From 4224eb88314bdece2a254decf7ebf9ffd7b57678 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 4 Sep 2012 13:50:56 +0000 Subject: API: remove OAuth auth check, respond in ocs formatted xml/json --- lib/api.php | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 55de438f429..92fa05bd719 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); } /** -- cgit v1.2.3 From 470b87f62574f62ce132cd24a9c014aac51ddc91 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 5 Sep 2012 09:07:15 +0000 Subject: Fix ocs/person/check --- lib/ocs/person.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/ocs/person.php b/lib/ocs/person.php index 629a7c2e6c7..c757385dfe1 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; -- cgit v1.2.3 From 28a11959d744fd5e23c4a5543c24863c77160644 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 5 Sep 2012 12:32:54 +0000 Subject: API: Fix /person/check api method --- lib/ocs/person.php | 1 + 1 file changed, 1 insertion(+) (limited to 'lib') diff --git a/lib/ocs/person.php b/lib/ocs/person.php index c757385dfe1..23b8853533d 100644 --- a/lib/ocs/person.php +++ b/lib/ocs/person.php @@ -16,4 +16,5 @@ class OC_OCS_Person { return 101; } } + } -- cgit v1.2.3 From fa5dff22a02aeb5985215454549ab1020382b197 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 09:41:20 +0000 Subject: API: Require api calls to register the required auth level --- lib/api.php | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 56 insertions(+), 7 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 92fa05bd719..c278f7672f1 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 -- cgit v1.2.3 From 182f890110f86ced32177dde2ac2fc2437bb2305 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 10:32:35 +0000 Subject: Remove a merge conflict --- lib/base.php | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) (limited to 'lib') diff --git a/lib/base.php b/lib/base.php index c7f6fd8ad85..0da33b4d0ff 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'); -- cgit v1.2.3 From b261c980c71112fb74541e4c93901ae12449b0d0 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 10:50:10 +0000 Subject: Fix autoloader merge conflict --- lib/base.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/base.php b/lib/base.php index 0da33b4d0ff..2b05fd7f9ea 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)) { -- cgit v1.2.3 From 8b409dfe2ad634b84dcbcc54cdd668488318e79b Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 14:15:04 +0000 Subject: API: Default to user authentication level --- lib/public/api.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/public/api.php b/lib/public/api.php index ed1f6ef237c..2821554229b 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); } } -- cgit v1.2.3 From a8c82440d0f4158151b9f28c6bfc0bbc14aea3e1 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Thu, 13 Sep 2012 15:18:38 +0000 Subject: API: Use http authentication, check the auth level required --- lib/api.php | 41 ++++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 19 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index c278f7672f1..29446e979fe 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(); - } - } } -- cgit v1.2.3 From 0f07226270d02ba7b8b1da8247cdbcb206a6c744 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Fri, 14 Sep 2012 13:41:06 +0000 Subject: API: Allow admins to access SUBADMIN api methods --- lib/api.php | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 29446e979fe..ba6e880261d 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); } } - + } } -- cgit v1.2.3 From 8926038591a2c290580f13cbb5d8581d0f7861e5 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 17 Sep 2012 12:07:42 +0000 Subject: API: Fix merge conflict remnants --- lib/ocs.php | 1 - 1 file changed, 1 deletion(-) (limited to 'lib') diff --git a/lib/ocs.php b/lib/ocs.php index 6cdb2480860..1cec3ecc7c0 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(); -- cgit v1.2.3 From 3ea01df1cdc3fe8774bf7e2d5eb93cc0fe809345 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 17 Sep 2012 12:08:17 +0000 Subject: API: Parse PUT and DELETE variables --- lib/api.php | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index ba6e880261d..29403030233 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){ -- cgit v1.2.3 From 07111ff672037282a6ca870fc19eab9f36875ea0 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sun, 28 Oct 2012 11:04:23 +0000 Subject: Allow apps to pass defaults and requirements for their API calls --- lib/public/api.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/public/api.php b/lib/public/api.php index 2821554229b..9d6d1153e6c 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); } } -- cgit v1.2.3 From b07944798848bc5196dc75e8d8caea5ca71b0f15 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sun, 28 Oct 2012 11:06:47 +0000 Subject: 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 (limited to 'lib') diff --git a/apps/files_sharing/appinfo/app.php b/apps/files_sharing/appinfo/app.php index 109f86b2e87..1402a146454 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 00000000000..d10607aa600 --- /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 00000000000..b1dc0d9e68e --- /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 29403030233..d11c3799d9a 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)); -- cgit v1.2.3 From 115dbc721d77509274e7a1bacf0239ada565b005 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Tue, 11 Dec 2012 22:36:46 +0000 Subject: API: Specify the response format using a GET parameter --- lib/api.php | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index d11c3799d9a..cc1d9fccaff 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') { -- cgit v1.2.3 From 140141edf2c5d89f083b4d254c0533e0209d517b Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 12 Dec 2012 16:50:25 +0000 Subject: 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 (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index cc1d9fccaff..e119b878210 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 00000000000..a7199cb5ac7 --- /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 -- cgit v1.2.3 From 2a4b554ca67ba55c75bbff75777285e550dca84f Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 12 Dec 2012 17:35:58 +0000 Subject: 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(-) (limited to 'lib') diff --git a/lib/ocs/cloud.php b/lib/ocs/cloud.php index 2f2aad714a3..720cc0ade39 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 06103cbeb4f..eb9e470381a 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 23b8853533d..b5f07d88ae1 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 1c781dece8a..02ca31f2d29 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); } } } -- cgit v1.2.3 From 3cc34055368114d81e722adea03a2118e78d2aac Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 12 Dec 2012 18:06:07 +0000 Subject: 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(-) (limited to 'lib') diff --git a/lib/ocs.php b/lib/ocs.php index 1cec3ecc7c0..001965d45e3 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 720cc0ade39..b5cfbc295e8 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 eb9e470381a..52affcd65ee 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 02ca31f2d29..09d636bd733 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 6b01abe31f2..033d9b79df2 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' => '')); -- cgit v1.2.3 From 228a75ebaa3a8fd543ea473bc23ba0b11a028511 Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 12 Dec 2012 20:58:40 +0000 Subject: API: Include totalitems and itemsperpage meta data when needed. --- lib/ocs/result.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'lib') diff --git a/lib/ocs/result.php b/lib/ocs/result.php index a7199cb5ac7..24029051da5 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; -- cgit v1.2.3 From 1475ff63ddeb56c277836092d2b02861cb47e4ee Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Wed, 12 Dec 2012 21:04:23 +0000 Subject: 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(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index e119b878210..84d1155b594 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'; -- cgit v1.2.3 From 39b51997756ebb233be10ca5a8ced0d6c60d0dac Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Sat, 15 Dec 2012 12:37:44 +0000 Subject: API: PUT and DELETE variables are now accessed from the parameters array --- lib/api.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'lib') diff --git a/lib/api.php b/lib/api.php index 84d1155b594..6c6c351b292 100644 --- a/lib/api.php +++ b/lib/api.php @@ -81,9 +81,9 @@ class OC_API { public static function call($parameters){ // Prepare the request variables if($_SERVER['REQUEST_METHOD'] == 'PUT'){ - parse_str(file_get_contents("php://input"), $_PUT); + parse_str(file_get_contents("php://input"), $parameters['_put']); } else if($_SERVER['REQUEST_METHOD'] == 'DELETE'){ - parse_str(file_get_contents("php://input"), $_DELETE); + parse_str(file_get_contents("php://input"), $parameters['_delete']); } $name = $parameters['_route']; // Check authentication and availability @@ -91,7 +91,7 @@ class OC_API { 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'); + $response = new OC_OCS_Result(null, 998, 'Api method not found'); } } else { $response = new OC_OCS_Result(null, 997, 'Unauthorised'); -- cgit v1.2.3 From 7980bccaabcaa27fe9c6db8a49a6e4a8dc4bd3fe Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Sun, 16 Dec 2012 19:43:32 -0500 Subject: Fall back to default log file if logfile config file not found, suppress writing errors, fixes issue #826 --- lib/log/owncloud.php | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) (limited to 'lib') diff --git a/lib/log/owncloud.php b/lib/log/owncloud.php index ec43208d833..e53dd5fefcd 100644 --- a/lib/log/owncloud.php +++ b/lib/log/owncloud.php @@ -33,8 +33,11 @@ class OC_Log_Owncloud { * Init class data */ public static function init() { - $datadir=OC_Config::getValue( "datadirectory", OC::$SERVERROOT.'/data' ); - self::$logFile=OC_Config::getValue( "logfile", $datadir.'/owncloud.log' ); + $defaultLogFile = OC_Config::getValue("datadirectory", OC::$SERVERROOT.'/data').'/owncloud.log'; + self::$logFile = OC_Config::getValue("logfile", $defaultLogFile); + if (!file_exists(self::$logFile)) { + self::$logFile = $defaultLogFile; + } } /** @@ -47,9 +50,11 @@ class OC_Log_Owncloud { $minLevel=min(OC_Config::getValue( "loglevel", OC_Log::WARN ), OC_Log::ERROR); if($level>=$minLevel) { $entry=array('app'=>$app, 'message'=>$message, 'level'=>$level, 'time'=>time()); - $fh=fopen(self::$logFile, 'a'); - fwrite($fh, json_encode($entry)."\n"); - fclose($fh); + $handle = @fopen(self::$logFile, 'a'); + if ($handle) { + fwrite($handle, json_encode($entry)."\n"); + fclose($handle); + } } } -- cgit v1.2.3 From 218a5ea89014322592bd8c4789d8500d42029b9f Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 31 Dec 2012 14:16:29 +0000 Subject: Remove unused methods --- lib/ocs/result.php | 16 ---------------- 1 file changed, 16 deletions(-) (limited to 'lib') diff --git a/lib/ocs/result.php b/lib/ocs/result.php index 24029051da5..4531da5ae0d 100644 --- a/lib/ocs/result.php +++ b/lib/ocs/result.php @@ -14,14 +14,6 @@ class OC_OCS_Result{ $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 @@ -38,14 +30,6 @@ class OC_OCS_Result{ $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 -- cgit v1.2.3 From 9626d9ce31c6144583481e26763c6a59ca52cf7a Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 31 Dec 2012 16:08:21 +0000 Subject: Code cleanup and add copyright info --- lib/ocs/config.php | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) (limited to 'lib') diff --git a/lib/ocs/config.php b/lib/ocs/config.php index 52affcd65ee..03c54aa2314 100644 --- a/lib/ocs/config.php +++ b/lib/ocs/config.php @@ -1,8 +1,30 @@ . +* +*/ class OC_OCS_Config { - public static function apiConfig($parameters){ + public static function apiConfig($parameters) { $xml['version'] = '1.7'; $xml['website'] = 'ownCloud'; $xml['host'] = OCP\Util::getServerHost(); -- cgit v1.2.3 From 8a5f583cac8952e978e560be46b25d664ba6447a Mon Sep 17 00:00:00 2001 From: Tom Needham Date: Mon, 31 Dec 2012 16:19:46 +0000 Subject: Remove WIP OAuth code --- lib/oauth/server.php | 111 --------------------------------------------------- lib/oauth/store.php | 95 ------------------------------------------- 2 files changed, 206 deletions(-) delete mode 100644 lib/oauth/server.php delete mode 100644 lib/oauth/store.php (limited to 'lib') diff --git a/lib/oauth/server.php b/lib/oauth/server.php deleted file mode 100644 index a82a1e2fb0e..00000000000 --- a/lib/oauth/server.php +++ /dev/null @@ -1,111 +0,0 @@ -. -* -*/ - -require_once(OC::$THIRDPARTYROOT.'/3rdparty/OAuth/OAuth.php'); - -class OC_OAuth_Server extends OAuthServer { - - /** - * 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 - * @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); - $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()); - } - - /** - * 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($scope) { - try { - $request = OAuthRequest::from_request(); - //$this->verify_request(); // TODO cannot use $this in static context - return true; - } 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; - } - - /** - * 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 deleted file mode 100644 index aa68d38957d..00000000000 --- a/lib/oauth/store.php +++ /dev/null @@ -1,95 +0,0 @@ -. -* -*/ - -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_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_success']) ? $details['callback_success'] : 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->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` < ?"); - $result = $query->exec(array($consumer->key, $token, $timestamp - self::$MAX_TIMESTAMP_DIFFERENCE)); - return $result; - } - - 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`, `timestamp`) VALUES (?, ?, ?, ?, ?, ?)"); - $result = $query->execute(array($consumer->key, $key, $secret, $token_type, time())); - return $token; - } - - function new_request_token($consumer, $callback = null) { - return $this->new_token($consumer, 'request'); - } - - 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; - } - -} \ No newline at end of file -- cgit v1.2.3 From 045c0acc92a291d5bc785103e129516f99032f94 Mon Sep 17 00:00:00 2001 From: Thomas Mueller Date: Thu, 3 Jan 2013 00:35:57 +0100 Subject: workaround for 32-bit systems to handle filesizes bigger than 2GB --- lib/filestorage.php | 2 +- lib/filestorage/local.php | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/filestorage.php b/lib/filestorage.php index dd65f4421b7..2e03c4cb6da 100644 --- a/lib/filestorage.php +++ b/lib/filestorage.php @@ -21,7 +21,7 @@ */ /** - * Provde a common interface to all different storage options + * Provide a common interface to all different storage options */ abstract class OC_Filestorage{ abstract public function __construct($parameters); diff --git a/lib/filestorage/local.php b/lib/filestorage/local.php index 6fe45acf8c5..0bf6ad2d3d7 100644 --- a/lib/filestorage/local.php +++ b/lib/filestorage/local.php @@ -29,7 +29,24 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{ return is_file($this->datadir.$path); } public function stat($path) { - return stat($this->datadir.$path); + $fullPath = $this->datadir.$path; + $statResult = stat($fullPath); + + // special case for 32-bit systems + if (PHP_INT_SIZE===4) { + if (!(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')) + $size = (float)exec('stat -c %s '. escapeshellarg ($fullPath)); + else{ + $fsobj = new COM("Scripting.FileSystemObject"); + $f = $fsobj->GetFile($fullPath); + $size = $f->Size; + } + + $statResult['size'] = $size; + $statResult[7] = $size; + } + + return $statResult; } public function filetype($path) { $filetype=filetype($this->datadir.$path); -- cgit v1.2.3 From a52aa69ffe5f6d00de7855c9a376f347c03b99f7 Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Thu, 3 Jan 2013 14:11:00 -0500 Subject: Rearrange code to prepare for updater feedback --- lib/base.php | 100 +++++++++++++++++++++++++++++++++++++---------------------- 1 file changed, 63 insertions(+), 37 deletions(-) (limited to 'lib') diff --git a/lib/base.php b/lib/base.php index ef203b33c2b..eaef984df34 100644 --- a/lib/base.php +++ b/lib/base.php @@ -193,6 +193,15 @@ class OC ); } + public static function checkConfig() { + if (file_exists(OC::$SERVERROOT . "/config/config.php") and !is_writable(OC::$SERVERROOT . "/config/config.php")) { + $tmpl = new OC_Template('', 'error', 'guest'); + $tmpl->assign('errors', array(1 => array('error' => "Can't write into config directory 'config'", 'hint' => "You can usually fix this by giving the webserver user write access to the config directory in owncloud"))); + $tmpl->printPage(); + exit(); + } + } + public static function checkInstalled() { // Redirect to installer if not installed @@ -219,43 +228,58 @@ class OC } } - public static function checkUpgrade() - { - if (OC_Config::getValue('installed', false)) { - $installedVersion = OC_Config::getValue('version', '0.0.0'); - $currentVersion = implode('.', OC_Util::getVersion()); - if (version_compare($currentVersion, $installedVersion, '>')) { - // Check if the .htaccess is existing - this is needed for upgrades from really old ownCloud versions - if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) { - if (!OC_Util::ishtaccessworking()) { - if (!file_exists(OC::$SERVERROOT . '/data/.htaccess')) { - OC_Setup::protectDataDirectory(); - } - } - } - OC_Log::write('core', 'starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, OC_Log::DEBUG); - $result = OC_DB::updateDbFromStructure(OC::$SERVERROOT . '/db_structure.xml'); - if (!$result) { - echo 'Error while upgrading the database'; - die(); - } - if (file_exists(OC::$SERVERROOT . "/config/config.php") and !is_writable(OC::$SERVERROOT . "/config/config.php")) { - $tmpl = new OC_Template('', 'error', 'guest'); - $tmpl->assign('errors', array(1 => array('error' => "Can't write into config directory 'config'", 'hint' => "You can usually fix this by giving the webserver user write access to the config directory in owncloud"))); - $tmpl->printPage(); - exit; - } - $minimizerCSS = new OC_Minimizer_CSS(); - $minimizerCSS->clearCache(); - $minimizerJS = new OC_Minimizer_JS(); - $minimizerJS->clearCache(); - OC_Config::setValue('version', implode('.', OC_Util::getVersion())); - OC_App::checkAppsRequirements(); - // load all apps to also upgrade enabled apps - OC_App::loadApps(); - } - } - } + public static function checkMaintenanceMode() { + if (OC_Config::getValue('maintenance', false)) { + $tmpl = new OC_Template('', 'error', 'guest'); + $tmpl->printPage(); + exit(); + } + } + + public static function checkUpgrade($showTemplate = true) { + if (OC_Config::getValue('installed', false)) { + $installedVersion = OC_Config::getValue('version', '0.0.0'); + $currentVersion = implode('.', OC_Util::getVersion()); + if (version_compare($currentVersion, $installedVersion, '>')) { + if ($showTemplate) { + OC_Log::write('core', 'starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, OC_Log::DEBUG); + $tmpl = new OC_Template('', 'error', 'guest'); + $tmpl->printPage(); + exit(); + } else { + return true; + } + } + return false; + } + } + + public static function doUpgrade() { + if (self::checkUpgrade(false)) { + OC_Config::setValue('maintenance', true); + // Check if the .htaccess is existing - this is needed for upgrades from really old ownCloud versions + if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) { + if (!OC_Util::ishtaccessworking()) { + if (!file_exists(OC::$SERVERROOT . '/data/.htaccess')) { + OC_Setup::protectDataDirectory(); + } + } + } + $result = OC_DB::updateDbFromStructure(OC::$SERVERROOT . '/db_structure.xml'); + if (!$result) { + echo 'Error while upgrading the database'; + die(); + } + $minimizerCSS = new OC_Minimizer_CSS(); + $minimizerCSS->clearCache(); + $minimizerJS = new OC_Minimizer_JS(); + $minimizerJS->clearCache(); + OC_Config::setValue('version', implode('.', OC_Util::getVersion())); + OC_App::checkAppsRequirements(); + // load all apps to also upgrade enabled apps + OC_App::loadApps(); + } + } public static function initTemplateEngine() { @@ -403,10 +427,12 @@ class OC stream_wrapper_register('static', 'OC_StaticStreamWrapper'); stream_wrapper_register('close', 'OC_CloseStreamWrapper'); + self::checkConfig(); self::checkInstalled(); self::checkSSL(); self::initSession(); self::initTemplateEngine(); + self::checkMaintenanceMode(); self::checkUpgrade(); $errors = OC_Util::checkServer(); -- cgit v1.2.3 From 75058370795fda4f06f589ee970edf94dc0ddf88 Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Thu, 3 Jan 2013 21:32:33 -0500 Subject: Basic update progress of database update only --- core/ajax/update.php | 36 ++++++++++++++++++++++++++++++++++ core/css/styles.css | 3 ++- core/templates/update.php | 27 ++++++++++++++++++++++++++ lib/base.php | 49 ++++++++++++----------------------------------- 4 files changed, 77 insertions(+), 38 deletions(-) create mode 100644 core/ajax/update.php create mode 100644 core/templates/update.php (limited to 'lib') diff --git a/core/ajax/update.php b/core/ajax/update.php new file mode 100644 index 00000000000..6f5398f41cb --- /dev/null +++ b/core/ajax/update.php @@ -0,0 +1,36 @@ +send('success', 'Turned on maintenance mode'); + // Check if the .htaccess is existing - this is needed for upgrades from really old ownCloud versions + if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) { + if (!OC_Util::ishtaccessworking()) { + if (!file_exists(OC::$SERVERROOT . '/data/.htaccess')) { + OC_Setup::protectDataDirectory(); + } + } + } + $result = OC_DB::updateDbFromStructure(OC::$SERVERROOT.'/db_structure.xml'); + if (!$result) { + $updateEventSource->send('failure', 'Error updating database'); + $updateEventSource->close(); + die(); + } + $updateEventSource->send('success', 'Updated database'); + $minimizerCSS = new OC_Minimizer_CSS(); + $minimizerCSS->clearCache(); + $minimizerJS = new OC_Minimizer_JS(); + $minimizerJS->clearCache(); + OC_Config::setValue('version', implode('.', OC_Util::getVersion())); + OC_App::checkAppsRequirements(); + // load all apps to also upgrade enabled apps + OC_App::loadApps(); + OC_Config::setValue('maintenance', false); + $updateEventSource->send('success', 'Turned off maintenance mode'); + $updateEventSource->send('done', 'done'); + $updateEventSource->close(); +} \ No newline at end of file diff --git a/core/css/styles.css b/core/css/styles.css index d635916b5ae..6e1cef72eda 100644 --- a/core/css/styles.css +++ b/core/css/styles.css @@ -214,7 +214,8 @@ div.jp-play-bar, div.jp-seek-bar { padding:0; } .pager { list-style:none; float:right; display:inline; margin:.7em 13em 0 0; } .pager li { display:inline-block; } -li.error { width:640px; margin:4em auto; padding:1em 1em 1em 4em; background:#ffe .8em .8em no-repeat; color:#FF3B3B; border:1px solid #ccc; -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; } +li.update, li.error { width:640px; margin:4em auto; padding:1em 1em 1em 4em; background:#ffe .8em .8em no-repeat; border:1px solid #ccc; -moz-border-radius:10px; -webkit-border-radius:10px; border-radius:10px; cursor:default; } +.error { color:#FF3B3B; } .ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { overflow:hidden; text-overflow:ellipsis; } .hint { background-image:url('../img/actions/info.png'); background-repeat:no-repeat; color:#777777; padding-left:25px; background-position:0 0.3em;} .separator { display:inline; border-left:1px solid #d3d3d3; border-right:1px solid #fff; height:10px; width:0px; margin:4px; } diff --git a/core/templates/update.php b/core/templates/update.php new file mode 100644 index 00000000000..cf3f2ab0d79 --- /dev/null +++ b/core/templates/update.php @@ -0,0 +1,27 @@ +
    +
  • + t('Updating ownCloud from version %s to version %s, this may take a while.', array($_['installed'], $_['current'])); ?>

    +
  • +
+ \ No newline at end of file diff --git a/lib/base.php b/lib/base.php index eaef984df34..ec08ccc67be 100644 --- a/lib/base.php +++ b/lib/base.php @@ -229,8 +229,10 @@ class OC } public static function checkMaintenanceMode() { - if (OC_Config::getValue('maintenance', false)) { + // Allow ajax update script to execute without being stopped + if (OC_Config::getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') { $tmpl = new OC_Template('', 'error', 'guest'); + $tmpl->assign('errors', array(1 => array('error' => 'ownCloud is in maintenance mode'))); $tmpl->printPage(); exit(); } @@ -241,9 +243,12 @@ class OC $installedVersion = OC_Config::getValue('version', '0.0.0'); $currentVersion = implode('.', OC_Util::getVersion()); if (version_compare($currentVersion, $installedVersion, '>')) { - if ($showTemplate) { + if ($showTemplate && !OC_Config::getValue('maintenance', false)) { + OC_Config::setValue('maintenance', true); OC_Log::write('core', 'starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, OC_Log::DEBUG); - $tmpl = new OC_Template('', 'error', 'guest'); + $tmpl = new OC_Template('', 'update', 'guest'); + $tmpl->assign('current', $currentVersion); + $tmpl->assign('installed', $installedVersion); $tmpl->printPage(); exit(); } else { @@ -254,33 +259,6 @@ class OC } } - public static function doUpgrade() { - if (self::checkUpgrade(false)) { - OC_Config::setValue('maintenance', true); - // Check if the .htaccess is existing - this is needed for upgrades from really old ownCloud versions - if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) { - if (!OC_Util::ishtaccessworking()) { - if (!file_exists(OC::$SERVERROOT . '/data/.htaccess')) { - OC_Setup::protectDataDirectory(); - } - } - } - $result = OC_DB::updateDbFromStructure(OC::$SERVERROOT . '/db_structure.xml'); - if (!$result) { - echo 'Error while upgrading the database'; - die(); - } - $minimizerCSS = new OC_Minimizer_CSS(); - $minimizerCSS->clearCache(); - $minimizerJS = new OC_Minimizer_JS(); - $minimizerJS->clearCache(); - OC_Config::setValue('version', implode('.', OC_Util::getVersion())); - OC_App::checkAppsRequirements(); - // load all apps to also upgrade enabled apps - OC_App::loadApps(); - } - } - public static function initTemplateEngine() { // Add the stuff we need always @@ -297,12 +275,6 @@ class OC OC_Util::addScript('search', 'result'); OC_Util::addScript('router'); - if (OC_Config::getValue('installed', false)) { - if (OC_Appconfig::getValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') { - OC_Util::addScript('backgroundjobs'); - } - } - OC_Util::addStyle("styles"); OC_Util::addStyle("multiselect"); OC_Util::addStyle("jquery-ui-1.8.16.custom"); @@ -433,7 +405,7 @@ class OC self::initSession(); self::initTemplateEngine(); self::checkMaintenanceMode(); - self::checkUpgrade(); + self::checkUpgrade(); $errors = OC_Util::checkServer(); if (count($errors) > 0) { @@ -508,6 +480,9 @@ class OC if (OC_Util::issetlocaleworking() == false) { OC_Log::write('core', 'setting locate to en_US.UTF-8 failed. Support is probably not installed on your system', OC_Log::ERROR); } + if (OC_Appconfig::getValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') { + OC_Util::addScript('backgroundjobs'); + } } /** -- cgit v1.2.3 From e7eea3dd2e3eb0f5bd77901167656275d835cfb3 Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Fri, 4 Jan 2013 10:21:33 -0500 Subject: Use hooks to send updates from apps --- core/ajax/update.php | 54 ++++++++++++++++++++++++++++++++++++++++++++-------- lib/app.php | 1 + 2 files changed, 47 insertions(+), 8 deletions(-) (limited to 'lib') diff --git a/core/ajax/update.php b/core/ajax/update.php index 6f5398f41cb..0d58f17f097 100644 --- a/core/ajax/update.php +++ b/core/ajax/update.php @@ -5,7 +5,11 @@ require_once '../../lib/base.php'; if (OC::checkUpgrade(false)) { $updateEventSource = new OC_EventSource(); - $updateEventSource->send('success', 'Turned on maintenance mode'); + $watcher = new UpdateWatcher($updateEventSource); + OC_Hook::connect('update', 'success', $watcher, 'success'); + OC_Hook::connect('update', 'error', $watcher, 'error'); + OC_Hook::connect('update', 'error', $watcher, 'failure'); + $watcher->success('Turned on maintenance mode'); // Check if the .htaccess is existing - this is needed for upgrades from really old ownCloud versions if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) { if (!OC_Util::ishtaccessworking()) { @@ -16,11 +20,9 @@ if (OC::checkUpgrade(false)) { } $result = OC_DB::updateDbFromStructure(OC::$SERVERROOT.'/db_structure.xml'); if (!$result) { - $updateEventSource->send('failure', 'Error updating database'); - $updateEventSource->close(); - die(); + $watcher->failure('Error updating database'); } - $updateEventSource->send('success', 'Updated database'); + $watcher->success('Updated database'); $minimizerCSS = new OC_Minimizer_CSS(); $minimizerCSS->clearCache(); $minimizerJS = new OC_Minimizer_JS(); @@ -30,7 +32,43 @@ if (OC::checkUpgrade(false)) { // load all apps to also upgrade enabled apps OC_App::loadApps(); OC_Config::setValue('maintenance', false); - $updateEventSource->send('success', 'Turned off maintenance mode'); - $updateEventSource->send('done', 'done'); - $updateEventSource->close(); + $watcher->success('Turned off maintenance mode'); + $watcher->done(); +} + +class UpdateWatcher { + /** + * @var \OC_EventSource $eventSource; + */ + private $eventSource; + + public function __construct($eventSource) { + $this->eventSource = $eventSource; + } + + public function success($message) { + OC_Util::obEnd(); + $this->eventSource->send('success', $message); + ob_start(); + } + + public function error($message) { + OC_Util::obEnd(); + $this->eventSource->send('error', $message); + ob_start(); + } + + public function failure($message) { + OC_Util::obEnd(); + $this->eventSource->send('failure', $message); + $this->eventSource->close(); + die(); + } + + public function done() { + OC_Util::obEnd(); + $this->eventSource->send('done', ''); + $this->eventSource->close(); + } + } \ No newline at end of file diff --git a/lib/app.php b/lib/app.php index be6d5ab3dd3..596f3bf3a79 100755 --- a/lib/app.php +++ b/lib/app.php @@ -642,6 +642,7 @@ class OC_App{ echo 'Failed to upgrade "'.$app.'". Exception="'.$e->getMessage().'"'; die; } + OC_Hook::emit('update', 'success', 'Updated '.$app.' app'); OC_Appconfig::setValue($app, 'installed_version', OC_App::getAppVersion($app)); } } -- cgit v1.2.3 From f2e6df807d05ef50b28ca2afc9ea51970ec0d87b Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Fri, 4 Jan 2013 14:16:59 -0500 Subject: Add back check if installed around background jobs --- lib/base.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'lib') diff --git a/lib/base.php b/lib/base.php index ec08ccc67be..e6355013c73 100644 --- a/lib/base.php +++ b/lib/base.php @@ -480,8 +480,10 @@ class OC if (OC_Util::issetlocaleworking() == false) { OC_Log::write('core', 'setting locate to en_US.UTF-8 failed. Support is probably not installed on your system', OC_Log::ERROR); } - if (OC_Appconfig::getValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') { - OC_Util::addScript('backgroundjobs'); + if (OC_Config::getValue('installed', false)) { + if (OC_Appconfig::getValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') { + OC_Util::addScript('backgroundjobs'); + } } } -- cgit v1.2.3 From dfc8d757b5dd7e5d7bf54a32b9f11f0798905d4a Mon Sep 17 00:00:00 2001 From: Thomas Mueller Date: Fri, 4 Jan 2013 23:00:51 +0100 Subject: OC_Helper::is_function_enabled() added to find out if a function is available And some documentation adjusted on the way --- lib/helper.php | 61 +++++++++++++++++++++++++++++++++++++++++----------------- 1 file changed, 43 insertions(+), 18 deletions(-) (limited to 'lib') diff --git a/lib/helper.php b/lib/helper.php index be4e4e52677..1aba2a38100 100644 --- a/lib/helper.php +++ b/lib/helper.php @@ -31,8 +31,9 @@ class OC_Helper { /** * @brief Creates an url using a defined route * @param $route - * @param $parameters - * @param $args array with param=>value, will be appended to the returned url + * @param array $parameters + * @return + * @internal param array $args with param=>value, will be appended to the returned url * @returns the url * * Returns a url to the given app and file. @@ -128,6 +129,7 @@ class OC_Helper { /** * @brief Creates an absolute url for remote use * @param string $service id + * @param bool $add_slash * @return string the url * * Returns a absolute url to the given service. @@ -139,6 +141,7 @@ class OC_Helper { /** * @brief Creates an absolute url for public use * @param string $service id + * @param bool $add_slash * @return string the url * * Returns a absolute url to the given service. @@ -450,12 +453,14 @@ class OC_Helper { } /** - * detect if a given program is found in the search PATH - * - * @param string $program name - * @param string $optional search path, defaults to $PATH - * @return bool true if executable program found in path - */ + * detect if a given program is found in the search PATH + * + * @param $name + * @param bool $path + * @internal param string $program name + * @internal param string $optional search path, defaults to $PATH + * @return bool true if executable program found in path + */ public static function canExecute($name, $path = false) { // path defaults to PATH from environment if not set if ($path === false) { @@ -676,16 +681,16 @@ class OC_Helper { } /** - * @brief replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. - * - * @param string $input The input string. .Opposite to the PHP build-in function does not accept an array. - * @param string $replacement The replacement string. - * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string. - * @param int $length Length of the part to be replaced - * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8 - * @return string - * - */ + * @brief replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement. + * + * @param $string + * @param string $replacement The replacement string. + * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string. + * @param int $length Length of the part to be replaced + * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8 + * @internal param string $input The input string. .Opposite to the PHP build-in function does not accept an array. + * @return string + */ public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') { $start = intval($start); $length = intval($length); @@ -758,4 +763,24 @@ class OC_Helper { } return $str; } + + /** + * Checks if a function is available + * @param string $function_name + * @return bool + */ + public static function is_function_enabled($function_name) { + if (!function_exists($function_name)) { + return false; + } + $disabled = explode(', ', ini_get('disable_functions')); + if (in_array($function_name, $disabled)) { + return false; + } + $disabled = explode(', ', ini_get('suhosin.executor.func.blacklist')); + if (in_array($function_name, $disabled)) { + return false; + } + return true; + } } -- cgit v1.2.3 From cedec593ee32d7e8b988c9df7c08020df52dbdb3 Mon Sep 17 00:00:00 2001 From: Thomas Mueller Date: Fri, 4 Jan 2013 23:03:26 +0100 Subject: Fallback to use COM or exec('stat ..') is only executed if stat or filesize return negative values. Special case of BSD has been added as stat syntax differs In addition unknown OS is logged --- lib/filestorage/local.php | 47 +++++++++++++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 12 deletions(-) (limited to 'lib') diff --git a/lib/filestorage/local.php b/lib/filestorage/local.php index 0bf6ad2d3d7..435fcb692a3 100644 --- a/lib/filestorage/local.php +++ b/lib/filestorage/local.php @@ -29,22 +29,15 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{ return is_file($this->datadir.$path); } public function stat($path) { - $fullPath = $this->datadir.$path; + $fullPath = $this->datadir . $path; $statResult = stat($fullPath); - // special case for 32-bit systems - if (PHP_INT_SIZE===4) { - if (!(strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')) - $size = (float)exec('stat -c %s '. escapeshellarg ($fullPath)); - else{ - $fsobj = new COM("Scripting.FileSystemObject"); - $f = $fsobj->GetFile($fullPath); - $size = $f->Size; - } - + if ($statResult['size'] < 0) { + $size = self::getFileSizeFromOS($fullPath); $statResult['size'] = $size; $statResult[7] = $size; } + return $statResult; return $statResult; } @@ -59,7 +52,13 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{ if($this->is_dir($path)) { return 0; }else{ - return filesize($this->datadir.$path); + $fullPath = $this->datadir . $path; + $fileSize = filesize($fullPath); + if ($fileSize < 0) { + return self::getFileSizeFromOS($fullPath); + } + + return $fileSize; } } public function isReadable($path) { @@ -173,6 +172,30 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{ return $return; } + private static function getFileSizeFromOS($fullPath) { + $name = strtolower(php_uname('s')); + // Windows OS: we use COM to access the filesystem + if (strpos($name, 'win') !== false) { + if (class_exists('COM')) { + $fsobj = new COM("Scripting.FileSystemObject"); + $f = $fsobj->GetFile($fullPath); + return $f->Size; + } + } else if (strpos($name, 'bsd') !== false) { + if (\OC_Helper::is_function_enabled('exec')) { + return (float)exec('stat -f %z ' . escapeshellarg($fullPath)); + } + } else if (strpos($name, 'linux') !== false) { + if (\OC_Helper::is_function_enabled('exec')) { + return (float)exec('stat -c %s ' . escapeshellarg($fullPath)); + } + } else { + OC_Log::write('core', 'Unknown OS: '.$name, OC_Log::ERROR); + } + + return 0; + } + public function hash($path, $type, $raw=false) { return hash_file($type, $this->datadir.$path, $raw); } -- cgit v1.2.3 From ac50c2f97322cb8ac2631d092327e91758aa75de Mon Sep 17 00:00:00 2001 From: Thomas Mueller Date: Fri, 4 Jan 2013 23:04:23 +0100 Subject: documentation adjusted on the way --- lib/filestorage/local.php | 1 + 1 file changed, 1 insertion(+) (limited to 'lib') diff --git a/lib/filestorage/local.php b/lib/filestorage/local.php index 435fcb692a3..86cc910d2e1 100644 --- a/lib/filestorage/local.php +++ b/lib/filestorage/local.php @@ -230,6 +230,7 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{ /** * check if a file or folder has been updated since $time + * @param string $path * @param int $time * @return bool */ -- cgit v1.2.3 From 2cb66327525472d1b5f287b20d81554c84c2ddbe Mon Sep 17 00:00:00 2001 From: Thomas Mueller Date: Fri, 4 Jan 2013 23:44:01 +0100 Subject: enhanced log message --- lib/filestorage/local.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib') diff --git a/lib/filestorage/local.php b/lib/filestorage/local.php index 86cc910d2e1..ca68d6b8702 100644 --- a/lib/filestorage/local.php +++ b/lib/filestorage/local.php @@ -190,7 +190,7 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{ return (float)exec('stat -c %s ' . escapeshellarg($fullPath)); } } else { - OC_Log::write('core', 'Unknown OS: '.$name, OC_Log::ERROR); + OC_Log::write('core', 'Unable to determine file size of "'.$fullPath.'". Unknown OS: '.$name, OC_Log::ERROR); } return 0; -- cgit v1.2.3 From da28ae0069b720161deb648028b612563e5f6497 Mon Sep 17 00:00:00 2001 From: Thomas Mueller Date: Sat, 5 Jan 2013 00:09:37 +0100 Subject: remove duplicate return --- lib/filestorage/local.php | 2 -- 1 file changed, 2 deletions(-) (limited to 'lib') diff --git a/lib/filestorage/local.php b/lib/filestorage/local.php index ca68d6b8702..910b3fa039d 100644 --- a/lib/filestorage/local.php +++ b/lib/filestorage/local.php @@ -38,8 +38,6 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{ $statResult[7] = $size; } return $statResult; - - return $statResult; } public function filetype($path) { $filetype=filetype($this->datadir.$path); -- cgit v1.2.3 From a94405b4e4ebbeea2f8bc3a220572dab1ae7cb3a Mon Sep 17 00:00:00 2001 From: Michael Gapczynski Date: Fri, 4 Jan 2013 20:13:00 -0500 Subject: Only show the version updating to instead of worrying about converting internal to a formatted version --- core/templates/update.php | 2 +- lib/base.php | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) (limited to 'lib') diff --git a/core/templates/update.php b/core/templates/update.php index cf3f2ab0d79..41da712c6ca 100644 --- a/core/templates/update.php +++ b/core/templates/update.php @@ -1,6 +1,6 @@
  • - t('Updating ownCloud from version %s to version %s, this may take a while.', array($_['installed'], $_['current'])); ?>

    + t('Updating ownCloud to version %s, this may take a while.', array($_['version'])); ?>