diff --git a/appnet/AppDotNet.php b/appnet/AppDotNet.php index 32361314..3b116d03 100644 --- a/appnet/AppDotNet.php +++ b/appnet/AppDotNet.php @@ -2,7 +2,7 @@ /** * AppDotNet.php * App.net PHP library - * https://github.com/jdolitsky/AppDotNetPHP + * https://github.com/jdolitsky/AppDotNetPHP. * * This class handles a lower level type of access to App.net. It's ideal * for command line scripts and other places where you want full control @@ -13,1635 +13,1840 @@ * etc. EZAppDotNet assumes you're accessing App.net via a browser, whereas * this class tries to make no assumptions at all. */ -class AppDotNet { +class AppDotNet +{ + protected $_baseUrl = 'https://alpha-api.app.net/stream/0/'; + protected $_authUrl = 'https://account.app.net/oauth/'; - protected $_baseUrl = 'https://alpha-api.app.net/stream/0/'; - protected $_authUrl = 'https://account.app.net/oauth/'; + private $_authPostParams = array(); - private $_authPostParams=array(); + // stores the access token after login + private $_accessToken = null; - // stores the access token after login - private $_accessToken = null; + // stores the App access token if we have it + private $_appAccessToken = null; - // stores the App access token if we have it - private $_appAccessToken = null; + // stores the user ID returned when fetching the auth token + private $_user_id = null; - // stores the user ID returned when fetching the auth token - private $_user_id = null; + // stores the username returned when fetching the auth token + private $_username = null; - // stores the username returned when fetching the auth token - private $_username = null; - - // The total number of requests you're allowed within the alloted time period - private $_rateLimit = null; - - // The number of requests you have remaining within the alloted time period - private $_rateLimitRemaining = null; - - // The number of seconds remaining in the alloted time period - private $_rateLimitReset = null; - - // The scope the user has - private $_scope = null; - - // token scopes - private $_scopes=array(); - - // debug info - private $_last_request = null; - private $_last_response = null; - - // ssl certification - private $_sslCA = null; - - // the callback function to be called when an event is received from the stream - private $_streamCallback = null; - - // the stream buffer - private $_streamBuffer = ''; - - // stores the curl handler for the current stream - private $_currentStream = null; - - // stores the curl multi handler for the current stream - private $_multiStream = null; - - // stores the number of failed connects, so we can back off multiple failures - private $_connectFailCounter = 0; - - // stores the most recent stream url, so we can re-connect when needed - private $_streamUrl = null; - - // keeps track of the last time we've received a packet from the api, if it's too long we'll reconnect - private $_lastStreamActivity = null; - - // stores the headers received when connecting to the stream - private $_streamHeaders = null; - - // response meta max_id data - private $_maxid = null; - - // response meta min_id data - private $_minid = null; - - // response meta more data - private $_more = null; - - // response stream marker data - private $_last_marker = null; - - // strip envelope response from returned value - private $_stripResponseEnvelope=true; - - // if processing stream_markers or any fast stream, decrease $sleepFor - public $streamingSleepFor=20000; - - /** - * Constructs an AppDotNet PHP object with the specified client ID and - * client secret. - * @param string $client_id The client ID you received from App.net when - * creating your app. - * @param string $client_secret The client secret you received from - * App.net when creating your app. - */ - public function __construct($client_id,$client_secret) { - $this->_clientId = $client_id; - $this->_clientSecret = $client_secret; - - // if the digicert certificate exists in the same folder as this file, - // remember that fact for later - if (file_exists(dirname(__FILE__).'/DigiCertHighAssuranceEVRootCA.pem')) { - $this->_sslCA = dirname(__FILE__).'/DigiCertHighAssuranceEVRootCA.pem'; - } - } - - /** - * Set whether or not to strip Envelope Response (meta) information - * This option will be deprecated in the future. Is it to allow - * a stepped migration path between code expecting the old behavior - * and new behavior. When not stripped, you still can use the proper - * method to pull the meta information. Please start converting your code ASAP - */ - public function includeResponseEnvelope() { - $this->_stripResponseEnvelope=false; - } - - /** - * Construct the proper Auth URL for the user to visit and either grant - * or not access to your app. Usually you would place this as a link for - * the user to client, or a redirect to send them to the auth URL. - * Also can be called after authentication for additional scopes - * @param string $callbackUri Where you want the user to be directed - * after authenticating with App.net. This must be one of the URIs - * allowed by your App.net application settings. - * @param array $scope An array of scopes (permissions) you wish to obtain - * from the user. Currently options are stream, email, write_post, follow, - * messages, and export. If you don't specify anything, you'll only receive - * access to the user's basic profile (the default). - */ - public function getAuthUrl($callback_uri,$scope=null) { - - // construct an authorization url based on our client id and other data - $data = array( - 'client_id'=>$this->_clientId, - 'response_type'=>'code', - 'redirect_uri'=>$callback_uri, - ); - - $url = $this->_authUrl; - if ($this->_accessToken) { - $url .= 'authorize?'; - } else { - $url .= 'authenticate?'; - } - $url .= $this->buildQueryString($data); - - if ($scope) { - $url .= '&scope='.implode('+',$scope); - } - - // return the constructed url - return $url; - } - - /** - * Call this after they return from the auth page, or anytime you need the - * token. For example, you could store it in a database and use - * setAccessToken() later on to return on behalf of the user. - */ - public function getAccessToken($callback_uri) { - // if there's no access token set, and they're returning from - // the auth page with a code, use the code to get a token - if (!$this->_accessToken && isset($_GET['code']) && $_GET['code']) { - - // construct the necessary elements to get a token - $data = array( - 'client_id'=>$this->_clientId, - 'client_secret'=>$this->_clientSecret, - 'grant_type'=>'authorization_code', - 'redirect_uri'=>$callback_uri, - 'code'=>$_GET['code'] - ); - - // try and fetch the token with the above data - $res = $this->httpReq('post',$this->_authUrl.'access_token', $data); - - // store it for later - $this->_accessToken = $res['access_token']; - $this->_username = $res['username']; - $this->_user_id = $res['user_id']; - } - - // return what we have (this may be a token, or it may be nothing) - return $this->_accessToken; - } - - /** - * Check the scope of current token to see if it has required scopes - * has to be done after a check - */ - public function checkScopes($app_scopes) { - if (!count($this->_scopes)) { - return -1; // _scope is empty - } - $missing=array(); - foreach($app_scopes as $scope) { - if (!in_array($scope,$this->_scopes)) { - if ($scope=='public_messages') { - // messages works for public_messages - if (in_array('messages',$this->_scopes)) { - // if we have messages in our scopes - continue; - } - } - $missing[]=$scope; - } - } - // identify the ones missing - if (count($missing)) { - // do something - return $missing; - } - return 0; // 0 missing - } - - /** - * Set the access token (eg: after retrieving it from offline storage) - * @param string $token A valid access token you're previously received - * from calling getAccessToken(). - */ - public function setAccessToken($token) { - $this->_accessToken = $token; - } - - /** - * Deauthorize the current token (delete your authorization from the API) - * Generally this is useful for logging users out from a web app, so they - * don't get automatically logged back in the next time you redirect them - * to the authorization URL. - */ - public function deauthorizeToken() { - return $this->httpReq('delete',$this->_baseUrl.'token'); - } - - /** - * Retrieve an app access token from the app.net API. This allows you - * to access the API without going through the user access flow if you - * just want to (eg) consume global. App access tokens are required for - * some actions (like streaming global). DO NOT share the return value - * of this function with any user (or save it in a cookie, etc). This - * is considered secret info for your app only. - * @return string The app access token - */ - public function getAppAccessToken() { - - // construct the necessary elements to get a token - $data = array( - 'client_id'=>$this->_clientId, - 'client_secret'=>$this->_clientSecret, - 'grant_type'=>'client_credentials', - ); - - // try and fetch the token with the above data - $res = $this->httpReq('post',$this->_authUrl.'access_token', $data); - - // store it for later - $this->_appAccessToken = $res['access_token']; - $this->_accessToken = $res['access_token']; - $this->_username = null; - $this->_user_id = null; - - return $this->_accessToken; - } - - /** - * Returns the total number of requests you're allowed within the - * alloted time period. - * @see getRateLimitReset() - */ - public function getRateLimit() { - return $this->_rateLimit; - } - - /** - * The number of requests you have remaining within the alloted time period - * @see getRateLimitReset() - */ - public function getRateLimitRemaining() { - return $this->_rateLimitRemaining; - } - - /** - * The number of seconds remaining in the alloted time period. - * When this time is up you'll have getRateLimit() available again. - */ - public function getRateLimitReset() { - return $this->_rateLimitReset; - } - - /** - * The scope the user has - */ - public function getScope() { - return $this->_scope; - } - - /** - * Internal function, parses out important information App.net adds - * to the headers. - */ - protected function parseHeaders($response) { - // take out the headers - // set internal variables - // return the body/content - $this->_rateLimit = null; - $this->_rateLimitRemaining = null; - $this->_rateLimitReset = null; - $this->_scope = null; - - $response = explode("\r\n\r\n",$response,2); - $headers = $response[0]; - - if($headers == 'HTTP/1.1 100 Continue') { - $response = explode("\r\n\r\n",$response[1],2); - $headers = $response[0]; - } - - if (isset($response[1])) { - $content = $response[1]; - } - else { - $content = null; - } - - // this is not a good way to parse http headers - // it will not (for example) take into account multiline headers - // but what we're looking for is pretty basic, so we can ignore those shortcomings - $headers = explode("\r\n",$headers); - foreach ($headers as $header) { - $header = explode(': ',$header,2); - if (count($header)<2) { - continue; - } - list($k,$v) = $header; - switch ($k) { - case 'X-RateLimit-Remaining': - $this->_rateLimitRemaining = $v; - break; - case 'X-RateLimit-Limit': - $this->_rateLimit = $v; - break; - case 'X-RateLimit-Reset': - $this->_rateLimitReset = $v; - break; - case 'X-OAuth-Scopes': - $this->_scope = $v; - $this->_scopes=explode(',',$v); - break; - } - } - return $content; - } - - /** - * Internal function. Used to turn things like TRUE into 1, and then - * calls http_build_query. - */ - protected function buildQueryString($array) { - foreach ($array as $k=>&$v) { - if ($v===true) { - $v = '1'; - } - elseif ($v===false) { - $v = '0'; - } - unset($v); - } - return http_build_query($array); - } - - - /** - * Internal function to handle all - * HTTP requests (POST,PUT,GET,DELETE) - */ - protected function httpReq($act, $req, $params=array(),$contentType='application/x-www-form-urlencoded') { - $ch = curl_init($req); - $headers = array(); - if($act != 'get') { - curl_setopt($ch, CURLOPT_POST, true); - // if they passed an array, build a list of parameters from it - if (is_array($params) && $act != 'post-raw') { - $params = $this->buildQueryString($params); - } - curl_setopt($ch, CURLOPT_POSTFIELDS, $params); - $headers[] = "Content-Type: ".$contentType; - } - if($act != 'post' && $act != 'post-raw') { - curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($act)); - } - if($act == 'get' && isset($params['access_token'])) { - $headers[] = 'Authorization: Bearer '.$params['access_token']; - } - else if ($this->_accessToken) { - $headers[] = 'Authorization: Bearer '.$this->_accessToken; - } - curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch, CURLINFO_HEADER_OUT, true); - curl_setopt($ch, CURLOPT_HEADER, true); - if ($this->_sslCA) { - curl_setopt($ch, CURLOPT_CAINFO, $this->_sslCA); - } - $this->_last_response = curl_exec($ch); - $this->_last_request = curl_getinfo($ch,CURLINFO_HEADER_OUT); - $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); - curl_close($ch); - if ($http_status==0) { - throw new AppDotNetException('Unable to connect to '.$req); - } - if ($http_status<200 || $http_status>=300) { - throw new AppDotNetException('HTTP error '.$this->_last_response); - } - if ($this->_last_request===false) { - if (!curl_getinfo($ch,CURLINFO_SSL_VERIFYRESULT)) { - throw new AppDotNetException('SSL verification failed, connection terminated.'); - } - } - $response = $this->parseHeaders($this->_last_response); - $response = json_decode($response,true); - - if (isset($response['meta'])) { - if (isset($response['meta']['max_id'])) { - $this->_maxid=$response['meta']['max_id']; - $this->_minid=$response['meta']['min_id']; - } - if (isset($response['meta']['more'])) { - $this->_more=$response['meta']['more']; - } - if (isset($response['meta']['marker'])) { - $this->_last_marker=$response['meta']['marker']; - } - } - - // look for errors - if (isset($response['error'])) { - if (is_array($response['error'])) { - throw new AppDotNetException($response['error']['message'], - $response['error']['code']); - } - else { - throw new AppDotNetException($response['error']); - } - } - - // look for response migration errors - elseif (isset($response['meta']) && isset($response['meta']['error_message'])) { - throw new AppDotNetException($response['meta']['error_message'],$response['meta']['code']); - } - - // if we've received a migration response, handle it and return data only - elseif ($this->_stripResponseEnvelope && isset($response['meta']) && isset($response['data'])) { - return $response['data']; - } - - // else non response migration response, just return it - else { - return $response; - } - } - - - /** - * Get max_id from last meta response data envelope - */ - public function getResponseMaxID() { - return $this->_maxid; - } - - /** - * Get min_id from last meta response data envelope - */ - public function getResponseMinID() { - return $this->_minid; - } - - /** - * Get more from last meta response data envelope - */ - public function getResponseMore() { - return $this->_more; - } - - /** - * Get marker from last meta response data envelope - */ - public function getResponseMarker() { - return $this->_last_marker; - } - - /** - * Fetch API configuration object - */ - public function getConfig() { - return $this->httpReq('get',$this->_baseUrl.'config'); - } - - /** - * Return the Filters for the current user. - */ - public function getAllFilters() { - return $this->httpReq('get',$this->_baseUrl.'filters'); - } - - /** - * Create a Filter for the current user. - * @param string $name The name of the new filter - * @param array $filters An associative array of filters to be applied. - * This may change as the API evolves, as of this writing possible - * values are: user_ids, hashtags, link_domains, and mention_user_ids. - * You will need to provide at least one filter name=>value pair. - */ - public function createFilter($name='New filter', $filters=array()) { - $filters['name'] = $name; - return $this->httpReq('post',$this->_baseUrl.'filters',$filters); - } - - /** - * Returns a specific Filter object. - * @param integer $filter_id The ID of the filter you wish to retrieve. - */ - public function getFilter($filter_id=null) { - return $this->httpReq('get',$this->_baseUrl.'filters/'.urlencode($filter_id)); - } - - /** - * Delete a Filter. The Filter must belong to the current User. - * @return object Returns the deleted Filter on success. - */ - public function deleteFilter($filter_id=null) { - return $this->httpReq('delete',$this->_baseUrl.'filters/'.urlencode($filter_id)); - } - - /** - * Process user description, message or post text. - * Mentions and hashtags will be parsed out of the - * text, as will bare URLs. To create a link in the text without using a - * bare URL, include the anchor text in the object text and include a link - * entity in the function call. - * @param string $text The text of the description/message/post - * @param array $data An associative array of optional post data. This - * will likely change as the API evolves, as of this writing allowed keys are: - * reply_to, and annotations. "annotations" may be a complex object represented - * by an associative array. - * @param array $params An associative array of optional data to be included - * in the URL (such as 'include_annotations' and 'include_machine') - * @return array An associative array representing the post. - */ - public function processText($text=null, $data = array(), $params = array()) { - $data['text'] = $text; - $json = json_encode($data); - $qs = ''; - if (!empty($params)) { - $qs = '?'.$this->buildQueryString($params); - } - return $this->httpReq('post',$this->_baseUrl.'text/process'.$qs, $json, 'application/json'); - } - - /** - * Create a new Post object. Mentions and hashtags will be parsed out of the - * post text, as will bare URLs. To create a link in a post without using a - * bare URL, include the anchor text in the post's text and include a link - * entity in the post creation call. - * @param string $text The text of the post - * @param array $data An associative array of optional post data. This - * will likely change as the API evolves, as of this writing allowed keys are: - * reply_to, and annotations. "annotations" may be a complex object represented - * by an associative array. - * @param array $params An associative array of optional data to be included - * in the URL (such as 'include_annotations' and 'include_machine') - * @return array An associative array representing the post. - */ - public function createPost($text=null, $data = array(), $params = array()) { - $data['text'] = $text; - - $json = json_encode($data); - $qs = ''; - if (!empty($params)) { - $qs = '?'.$this->buildQueryString($params); - } - return $this->httpReq('post',$this->_baseUrl.'posts'.$qs, $json, 'application/json'); - } - - /** - * Returns a specific Post. - * @param integer $post_id The ID of the post to retrieve - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: include_annotations. - * @return array An associative array representing the post - */ - public function getPost($post_id=null,$params = array()) { - return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id) - .'?'.$this->buildQueryString($params)); - } - - /** - * Delete a Post. The current user must be the same user who created the Post. - * It returns the deleted Post on success. - * @param integer $post_id The ID of the post to delete - * @param array An associative array representing the post that was deleted - */ - public function deletePost($post_id=null) { - return $this->httpReq('delete',$this->_baseUrl.'posts/'.urlencode($post_id)); - } - - /** - * Retrieve the Posts that are 'in reply to' a specific Post. - * @param integer $post_id The ID of the post you want to retrieve replies for. - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: count, before_id, since_id, include_muted, include_deleted, - * include_directed_posts, and include_annotations. - * @return An array of associative arrays, each representing a single post. - */ - public function getPostReplies($post_id=null,$params = array()) { - return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id) - .'/replies?'.$this->buildQueryString($params)); - } - - /** - * Get the most recent Posts created by a specific User in reverse - * chronological order (most recent first). - * @param mixed $user_id Either the ID of the user you wish to retrieve posts by, - * or the string "me", which will retrieve posts for the user you're authenticated - * as. - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: count, before_id, since_id, include_muted, include_deleted, - * include_directed_posts, and include_annotations. - * @return An array of associative arrays, each representing a single post. - */ - public function getUserPosts($user_id='me', $params = array()) { - return $this->httpReq('get',$this->_baseUrl.'users/'.urlencode($user_id) - .'/posts?'.$this->buildQueryString($params)); - } - - /** - * Get the most recent Posts mentioning by a specific User in reverse - * chronological order (newest first). - * @param mixed $user_id Either the ID of the user who is being mentioned, or - * the string "me", which will retrieve posts for the user you're authenticated - * as. - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: count, before_id, since_id, include_muted, include_deleted, - * include_directed_posts, and include_annotations. - * @return An array of associative arrays, each representing a single post. - */ - public function getUserMentions($user_id='me',$params = array()) { - return $this->httpReq('get',$this->_baseUrl.'users/' - .urlencode($user_id).'/mentions?'.$this->buildQueryString($params)); - } - - /** - * Return the 20 most recent posts from the current User and - * the Users they follow. - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: count, before_id, since_id, include_muted, include_deleted, - * include_directed_posts, and include_annotations. - * @return An array of associative arrays, each representing a single post. - */ - public function getUserStream($params = array()) { - return $this->httpReq('get',$this->_baseUrl.'posts/stream?'.$this->buildQueryString($params)); - } - - /** - * Returns a specific user object. - * @param mixed $user_id The ID of the user you want to retrieve, or the string - * "me" to retrieve data for the users you're currently authenticated as. - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: include_annotations|include_user_annotations. - * @return array An associative array representing the user data. - */ - public function getUser($user_id='me', $params = array()) { - return $this->httpReq('get',$this->_baseUrl.'users/'.urlencode($user_id) - .'?'.$this->buildQueryString($params)); - } - - /** - * Returns multiple users request by an array of user ids - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: include_annotations|include_user_annotations. - * @return array An associative array representing the users data. - */ - public function getUsers($user_arr, $params = array()) { - return $this->httpReq('get',$this->_baseUrl.'users?ids='.join(',',$user_arr) - .'&'.$this->buildQueryString($params)); - } - - /** - * Add the specified user ID to the list of users followed. - * Returns the User object of the user being followed. - * @param integer $user_id The user ID of the user to follow. - * @return array An associative array representing the user you just followed. - */ - public function followUser($user_id=null) { - return $this->httpReq('post',$this->_baseUrl.'users/'.urlencode($user_id).'/follow'); - } - - /** - * Removes the specified user ID to the list of users followed. - * Returns the User object of the user being unfollowed. - * @param integer $user_id The user ID of the user to unfollow. - * @return array An associative array representing the user you just unfollowed. - */ - public function unfollowUser($user_id=null) { - return $this->httpReq('delete',$this->_baseUrl.'users/'.urlencode($user_id).'/follow'); - } - - /** - * Returns an array of User objects the specified user is following. - * @param mixed $user_id Either the ID of the user being followed, or - * the string "me", which will retrieve posts for the user you're authenticated - * as. - * @return array An array of associative arrays, each representing a single - * user following $user_id - */ - public function getFollowing($user_id='me') { - return $this->httpReq('get',$this->_baseUrl.'users/'.$user_id.'/following'); - } - - /** - * Returns an array of User objects for users following the specified user. - * @param mixed $user_id Either the ID of the user being followed, or - * the string "me", which will retrieve posts for the user you're authenticated - * as. - * @return array An array of associative arrays, each representing a single - * user following $user_id - */ - public function getFollowers($user_id='me') { - return $this->httpReq('get',$this->_baseUrl.'users/'.$user_id.'/followers'); - } - - /** - * Return Posts matching a specific #hashtag. - * @param string $hashtag The hashtag you're looking for. - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: count, before_id, since_id, include_muted, include_deleted, - * include_directed_posts, and include_annotations. - * @return An array of associative arrays, each representing a single post. - */ - public function searchHashtags($hashtag=null, $params = array()) { - return $this->httpReq('get',$this->_baseUrl.'posts/tag/' - .urlencode($hashtag).'?'.$this->buildQueryString($params)); - } - - /** - * Retrieve a list of all public Posts on App.net, often referred to as the - * global stream. - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: count, before_id, since_id, include_muted, include_deleted, - * include_directed_posts, and include_annotations. - * @return An array of associative arrays, each representing a single post. - */ - public function getPublicPosts($params = array()) { - return $this->httpReq('get',$this->_baseUrl.'posts/stream/global?'.$this->buildQueryString($params)); - } - - /** - * List User interactions - */ - public function getMyInteractions($params = array()) { - return $this->httpReq('get',$this->_baseUrl.'users/me/interactions?'.$this->buildQueryString($params)); - } - - /** - * Retrieve a user's user ID by specifying their username. - * Now supported by the API. We use the API if we have a token - * Otherwise we scrape the alpha.app.net site for the info. - * @param string $username The username of the user you want the ID of, without - * an @ symbol at the beginning. - * @return integer The user's user ID - */ - public function getIdByUsername($username=null) { - if ($this->_accessToken) { - $res=$this->httpReq('get',$this->_baseUrl.'users/@'.$username); - $user_id=$res['data']['id']; - } else { - $ch = curl_init('https://alpha.app.net/'.urlencode(strtolower($username))); - curl_setopt($ch, CURLOPT_POST, false); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); - curl_setopt($ch,CURLOPT_USERAGENT, - 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1'); - $response = curl_exec($ch); - curl_close($ch); - $temp = explode('title="User Id ',$response); - $temp2 = explode('"',$temp[1]); - $user_id = $temp2[0]; - } - return $user_id; - } - - /** - * Mute a user - * @param integer $user_id The user ID to mute - */ - public function muteUser($user_id=null) { - return $this->httpReq('post',$this->_baseUrl.'users/'.urlencode($user_id).'/mute'); - } - - /** - * Unmute a user - * @param integer $user_id The user ID to unmute - */ - public function unmuteUser($user_id=null) { - return $this->httpReq('delete',$this->_baseUrl.'users/'.urlencode($user_id).'/mute'); - } - - /** - * List the users muted by the current user - * @return array An array of associative arrays, each representing one muted user. - */ - public function getMuted() { - return $this->httpReq('get',$this->_baseUrl.'users/me/muted'); - } - - /** - * Star a post - * @param integer $post_id The post ID to star - */ - public function starPost($post_id=null) { - return $this->httpReq('post',$this->_baseUrl.'posts/'.urlencode($post_id).'/star'); - } - - /** - * Unstar a post - * @param integer $post_id The post ID to unstar - */ - public function unstarPost($post_id=null) { - return $this->httpReq('delete',$this->_baseUrl.'posts/'.urlencode($post_id).'/star'); - } - - /** - * List the posts starred by the current user - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: count, before_id, since_id, include_muted, include_deleted, - * include_directed_posts, and include_annotations. - * See https://github.com/appdotnet/api-spec/blob/master/resources/posts.md#general-parameters - * @return array An array of associative arrays, each representing a single - * user who has starred a post - */ - public function getStarred($user_id='me', $params = array()) { - return $this->httpReq('get',$this->_baseUrl.'users/'.urlencode($user_id).'/stars' - .'?'.$this->buildQueryString($params)); - } - - /** - * List the users who have starred a post - * @param integer $post_id the post ID to get stars from - * @return array An array of associative arrays, each representing one user. - */ - public function getStars($post_id=null) { - return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id).'/stars'); - } - - /** - * Returns an array of User objects of users who reposted the specified post. - * @param integer $post_id the post ID to - * @return array An array of associative arrays, each representing a single - * user who reposted $post_id - */ - public function getReposters($post_id){ - return $this->httpReq('get',$this->_baseUrl.'posts/'.urlencode($post_id).'/reposters'); - } - - /** - * Repost an existing Post object. - * @param integer $post_id The id of the post - * @return not a clue - */ - public function repost($post_id){ - return $this->httpReq('post',$this->_baseUrl.'posts/'.urlencode($post_id).'/repost'); - } - - /** - * Delete a post that the user has reposted. - * @param integer $post_id The id of the post - * @return not a clue - */ - public function deleteRepost($post_id){ - return $this->httpReq('delete',$this->_baseUrl.'posts/'.urlencode($post_id).'/repost'); - } - - /** - * List the posts who match a specific search term - * @param array $params a list of filter, search query, and general Post parameters - * see: https://developers.app.net/reference/resources/post/search/ - * @param string $query The search query. Supports - * normal search terms. Searches post text. - * @return array An array of associative arrays, each representing one post. - * or false on error - */ - public function searchPosts($params = array(), $query='', $order='default') { - if (!is_array($params)) { - return false; - } - if (!empty($query)) { - $params['query']=$query; - } - if ($order=='default') { - if (!empty($query)) { - $params['order']='score'; - } else { - $params['order']='id'; - } - } - return $this->httpReq('get',$this->_baseUrl.'posts/search?'.$this->buildQueryString($params)); - } - - - /** - * List the users who match a specific search term - * @param string $search The search query. Supports @username or #tag searches as - * well as normal search terms. Searches username, display name, bio information. - * Does not search posts. - * @return array An array of associative arrays, each representing one user. - */ - public function searchUsers($search="") { - return $this->httpReq('get',$this->_baseUrl.'users/search?q='.urlencode($search)); - } - - /** - * Return the 20 most recent posts for a stream using a valid Token - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: count, before_id, since_id, include_muted, include_deleted, - * include_directed_posts, and include_annotations. - * @return An array of associative arrays, each representing a single post. - */ - public function getTokenStream($params = array()) { - if ($params['access_token']) { - return $this->httpReq('get',$this->_baseUrl.'posts/stream?'.$this->buildQueryString($params),$params); - } else { - return $this->httpReq('get',$this->_baseUrl.'posts/stream?'.$this->buildQueryString($params)); - } - } - - /** - * Get a user object by username - * @param string $name the @name to get - * @return array representing one user - */ - public function getUserByName($name=null) { - return $this->httpReq('get',$this->_baseUrl.'users/@'.$name); - } - - /** - * Return the 20 most recent Posts from the current User's personalized stream - * and mentions stream merged into one stream. - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: count, before_id, since_id, include_muted, include_deleted, - * include_directed_posts, and include_annotations. - * @return An array of associative arrays, each representing a single post. - */ - public function getUserUnifiedStream($params = array()) { - return $this->httpReq('get',$this->_baseUrl.'posts/stream/unified?'.$this->buildQueryString($params)); - } - - /** - * Update Profile Data via JSON - * @data array containing user descriptors - */ - public function updateUserData($data = array(), $params = array()) { - $json = json_encode($data); - return $this->httpReq('put',$this->_baseUrl.'users/me'.'?'. - $this->buildQueryString($params), $json, 'application/json'); - } - - /** - * Update a user image - * @which avatar|cover - * @image path reference to image - */ - protected function updateUserImage($which = 'avatar', $image = null) { - $data = array($which=>"@$image"); - return $this->httpReq('post-raw',$this->_baseUrl.'users/me/'.$which, $data, 'multipart/form-data'); - } - - public function updateUserAvatar($avatar = null) { - if($avatar != null) - return $this->updateUserImage('avatar', $avatar); - } - - public function updateUserCover($cover = null) { - if($cover != null) - return $this->updateUserImage('cover', $cover); - } - - /** - * update stream marker - */ - public function updateStreamMarker($data = array()) { - $json = json_encode($data); - return $this->httpReq('post',$this->_baseUrl.'posts/marker', $json, 'application/json'); - } - - /** - * get a page of current user subscribed channels - */ - public function getUserSubscriptions($params = array()) { - return $this->httpReq('get',$this->_baseUrl.'channels?'.$this->buildQueryString($params)); - } - - /** - * get user channels - */ - public function getMyChannels($params = array()) { - return $this->httpReq('get',$this->_baseUrl.'channels/me?'.$this->buildQueryString($params)); - } - - /** - * create a channel - * note: you cannot create a channel with type=net.app.core.pm (see createMessage) - */ - public function createChannel($data = array()) { - $json = json_encode($data); - return $this->httpReq('post',$this->_baseUrl.'channels'.($pm?'/pm/messsages':''), $json, 'application/json'); - } - - /** - * get channelid info - */ - public function getChannel($channelid, $params = array()) { - return $this->httpReq('get',$this->_baseUrl.'channels/'.$channelid.'?'.$this->buildQueryString($params)); - } - - /** - * get multiple channels' info by an array of channelids - */ - public function getChannels($channels, $params = array()) { - return $this->httpReq('get',$this->_baseUrl.'channels?ids='.join(',',$channels).'&'.$this->buildQueryString($params)); - } - - /** - * update channelid - */ - public function updateChannel($channelid, $data = array()) { - $json = json_encode($data); - return $this->httpReq('put',$this->_baseUrl.'channels/'.$channelid, $json, 'application/json'); - } - - /** - * subscribe from channelid - */ - public function channelSubscribe($channelid) { - return $this->httpReq('post',$this->_baseUrl.'channels/'.$channelid.'/subscribe'); - } - - /** - * unsubscribe from channelid - */ - public function channelUnsubscribe($channelid) { - return $this->httpReq('delete',$this->_baseUrl.'channels/'.$channelid.'/subscribe'); - } - - /** - * get all user objects subscribed to channelid - */ - public function getChannelSubscriptions($channelid, $params = array()) { - return $this->httpReq('get',$this->_baseUrl.'channel/'.$channelid.'/subscribers?'.$this->buildQueryString($params)); - } - - /** - * get all user IDs subscribed to channelid - */ - public function getChannelSubscriptionsById($channelid) { - return $this->httpReq('get',$this->_baseUrl.'channel/'.$channelid.'/subscribers/ids'); - } - - - /** - * get a page of messages in channelid - */ - public function getMessages($channelid, $params = array()) { - return $this->httpReq('get',$this->_baseUrl.'channels/'.$channelid.'/messages?'.$this->buildQueryString($params)); - } - - /** - * create message - * @param $channelid numeric or "pm" for auto-chanenl (type=net.app.core.pm) - * @param $data array('text'=>'YOUR_MESSAGE') If a type=net.app.core.pm, then "destinations" key can be set to address as an array of people to send this PM too - */ - public function createMessage($channelid,$data) { - $json = json_encode($data); - return $this->httpReq('post',$this->_baseUrl.'channels/'.$channelid.'/messages', $json, 'application/json'); - } - - /** - * get message - */ - public function getMessage($channelid,$messageid) { - return $this->httpReq('get',$this->_baseUrl.'channels/'.$channelid.'/messages/'.$messageid); - } - - /** - * delete messsage - */ - public function deleteMessage($channelid,$messageid) { - return $this->httpReq('delete',$this->_baseUrl.'channels/'.$channelid.'/messages/'.$messageid); - } - - - /** - * Get Application Information - */ - public function getAppTokenInfo() { - // requires appAccessToken - if (!$this->_appAccessToken) { - $this->getAppAccessToken(); - } - // ensure request is made with our appAccessToken - $params['access_token']=$this->_appAccessToken; - return $this->httpReq('get',$this->_baseUrl.'token',$params); - } - - /** - * Get User Information - */ - public function getUserTokenInfo() { - return $this->httpReq('get',$this->_baseUrl.'token'); - } - - /** - * Get Application Authorized User IDs - */ - public function getAppUserIDs() { - // requires appAccessToken - if (!$this->_appAccessToken) { - $this->getAppAccessToken(); - } - // ensure request is made with our appAccessToken - $params['access_token']=$this->_appAccessToken; - return $this->httpReq('get',$this->_baseUrl.'apps/me/tokens/user_ids',$params); - } - - /** - * Get Application Authorized User Tokens - */ - public function getAppUserTokens() { - // requires appAccessToken - if (!$this->_appAccessToken) { - $this->getAppAccessToken(); - } - // ensure request is made with our appAccessToken - $params['access_token']=$this->_appAccessToken; - return $this->httpReq('get',$this->_baseUrl.'apps/me/tokens',$params); - } - - public function getLastRequest() { - return $this->_last_request; - } - public function getLastResponse() { - return $this->_last_response; - } - - /** - * Registers your function (or an array of object and method) to be called - * whenever an event is received via an open app.net stream. Your function - * will receive a single parameter, which is the object wrapper containing - * the meta and data. - * @param mixed A PHP callback (either a string containing the function name, - * or an array where the first element is the class/object and the second - * is the method). - */ - public function registerStreamFunction($function) { - $this->_streamCallback = $function; - } - - /** - * Opens a stream that's been created for this user/app and starts sending - * events/objects to your defined callback functions. You must define at - * least one callback function before opening a stream. - * @param mixed $stream Either a stream ID or the endpoint of a stream - * you've already created. This stream must exist and must be valid for - * your current access token. If you pass a stream ID, the library will - * make an API call to get the endpoint. - * - * This function will return immediately, but your callback functions - * will continue to receive events until you call closeStream() or until - * App.net terminates the stream from their end with an error. - * - * If you're disconnected due to a network error, the library will - * automatically attempt to reconnect you to the same stream, no action - * on your part is necessary for this. However if the app.net API returns - * an error, a reconnection attempt will not be made. - * - * Note there is no closeStream, because once you open a stream you - * can't stop it (unless you exit() or die() or throw an uncaught - * exception, or something else that terminates the script). - * @return boolean True - * @see createStream() - */ - public function openStream($stream) { - // if there's already a stream running, don't allow another - if ($this->_currentStream) { - throw new AppDotNetException('There is already a stream being consumed, only one stream can be consumed per AppDotNetStream instance'); - } - // must register a callback (or the exercise is pointless) - if (!$this->_streamCallback) { - throw new AppDotNetException('You must define your callback function using registerStreamFunction() before calling openStream'); - } - // if the stream is a numeric value, get the stream info from the api - if (is_numeric($stream)) { - $stream = $this->getStream($stream); - $this->_streamUrl = $stream['endpoint']; - } - else { - $this->_streamUrl = $stream; - } - // continue doing this until we get an error back or something...? - $this->httpStream('get',$this->_streamUrl); - - return true; - } - - /** - * Close the currently open stream. - * @return true; - */ - public function closeStream() { - if (!$this->_lastStreamActivity) { - // never opened - return; - } - if (!$this->_multiStream) { - throw new AppDotNetException('You must open a stream before calling closeStream()'); - } - curl_close($this->_currentStream); - curl_multi_remove_handle($this->_multiStream,$this->_currentStream); - curl_multi_close($this->_multiStream); - $this->_currentStream = null; - $this->_multiStream = null; - } - - /** - * Retrieve all streams for the current access token. - * @return array An array of stream definitions. - */ - public function getAllStreams() { - return $this->httpReq('get',$this->_baseUrl.'streams'); - } - - /** - * Returns a single stream specified by a stream ID. The stream must have been - * created with the current access token. - * @return array A stream definition - */ - public function getStream($streamId) { - return $this->httpReq('get',$this->_baseUrl.'streams/'.urlencode($streamId)); - } - - /** - * Creates a stream for the current app access token. - * - * @param array $objectTypes The objects you want to retrieve data for from the - * stream. At time of writing these can be 'post', 'star', and/or 'user_follow'. - * If you don't specify, all events will be retrieved. - */ - public function createStream($objectTypes=null) { - // default object types to everything - if (is_null($objectTypes)) { - $objectTypes = array('post','star','user_follow'); - } - $data = array( - 'object_types'=>$objectTypes, - 'type'=>'long_poll', - ); - $data = json_encode($data); - $response = $this->httpReq('post',$this->_baseUrl.'streams',$data,'application/json'); - return $response; - } - - /** - * Update stream for the current app access token - * - * @param integer $streamId The stream ID to update. This stream must have been - * created by the current access token. - * @param array $data allows object_types, type, filter_id and key to be updated. filter_id/key can be omitted - */ - public function updateStream($streamId,$data) { - // objectTypes is likely required - if (is_null($data['object_types'])) { - $data['object_types'] = array('post','star','user_follow'); - } - // type can still only be long_poll - if (is_null($data['type'])) { - $data['type']='long_poll'; - } - $data = json_encode($data); - $response = $this->httpReq('put',$this->_baseUrl.'streams/'.urlencode($streamId),$data,'application/json'); - return $response; - } - - /** - * Deletes a stream if you no longer need it. - * - * @param integer $streamId The stream ID to delete. This stream must have been - * created by the current access token. - */ - public function deleteStream($streamId) { - return $this->httpReq('delete',$this->_baseUrl.'streams/'.urlencode($streamId)); - } - - /** - * Deletes all streams created by the current access token. - */ - public function deleteAllStreams() { - return $this->httpReq('delete',$this->_baseUrl.'streams'); - } - - /** - * Internal function used to process incoming chunks from the stream. This is only - * public because it needs to be accessed by CURL. Do not call or use this function - * in your own code. - * @ignore - */ - public function httpStreamReceive($ch,$data) { - $this->_lastStreamActivity = time(); - $this->_streamBuffer .= $data; - if (!$this->_streamHeaders) { - $pos = strpos($this->_streamBuffer,"\r\n\r\n"); - if ($pos!==false) { - $this->_streamHeaders = substr($this->_streamBuffer,0,$pos); - $this->_streamBuffer = substr($this->_streamBuffer,$pos+4); - } - } - else { - $pos = strpos($this->_streamBuffer,"\r\n"); - while ($pos!==false) { - $command = substr($this->_streamBuffer,0,$pos); - $this->_streamBuffer = substr($this->_streamBuffer,$pos+2); - $command = json_decode($command,true); - if ($command) { - call_user_func($this->_streamCallback,$command); - } - $pos = strpos($this->_streamBuffer,"\r\n"); - } - } - return strlen($data); - } - - /** - * Opens a long lived HTTP connection to the app.net servers, and sends data - * received to the httpStreamReceive function. As a general rule you should not - * directly call this method, it's used by openStream(). - */ - protected function httpStream($act, $req, $params=array(),$contentType='application/x-www-form-urlencoded') { - if ($this->_currentStream) { - throw new AppDotNetException('There is already an open stream, you must close the existing one before opening a new one'); - } - $headers = array(); - $this->_streamBuffer = ''; - if ($this->_accessToken) { - $headers[] = 'Authorization: Bearer '.$this->_accessToken; - } - $this->_currentStream = curl_init($req); - curl_setopt($this->_currentStream, CURLOPT_HTTPHEADER, $headers); - curl_setopt($this->_currentStream, CURLOPT_RETURNTRANSFER, true); - curl_setopt($this->_currentStream, CURLINFO_HEADER_OUT, true); - curl_setopt($this->_currentStream, CURLOPT_HEADER, true); - if ($this->_sslCA) { - curl_setopt($this->_currentStream, CURLOPT_CAINFO, $this->_sslCA); - } - // every time we receive a chunk of data, forward it to httpStreamReceive - curl_setopt($this->_currentStream, CURLOPT_WRITEFUNCTION, array($this, "httpStreamReceive")); - - // curl_exec($ch); - // return; - - $this->_multiStream = curl_multi_init(); - $this->_lastStreamActivity = time(); - curl_multi_add_handle($this->_multiStream,$this->_currentStream); - } - - public function reconnectStream() { - $this->closeStream(); - $this->_connectFailCounter++; - // if we've failed a few times, back off - if ($this->_connectFailCounter>1) { - $sleepTime = pow(2,$this->_connectFailCounter); - // don't sleep more than 60 seconds - if ($sleepTime>60) { - $sleepTime = 60; - } - sleep($sleepTime); - } - $this->httpStream('get',$this->_streamUrl); - } - - /** - * Process an open stream for x microseconds, then return. This is useful if you want - * to be doing other things while processing the stream. If you just want to - * consume the stream without other actions, you can call processForever() instead. - * @param float @microseconds The number of microseconds to process for before - * returning. There are 1,000,000 microseconds in a second. - * - * @return void - */ - public function processStream($microseconds=null) { - if (!$this->_multiStream) { - throw new AppDotNetException('You must open a stream before calling processStream()'); - } - $start = microtime(true); - $active = null; - $inQueue = null; - $sleepFor = 0; - do { - // if we haven't received anything within 5.5 minutes, reconnect - // keepalives are sent every 5 minutes (measured on 2013-3-12 by @ryantharp) - if (time()-$this->_lastStreamActivity>=330) { - $this->reconnectStream(); - } - curl_multi_exec($this->_multiStream, $active); - if (!$active) { - $httpCode = curl_getinfo($this->_currentStream,CURLINFO_HTTP_CODE); - // don't reconnect on 400 errors - if ($httpCode>=400 && $httpCode<=499) { - throw new AppDotNetException('Received HTTP error '.$httpCode.' check your URL and credentials before reconnecting'); - } - $this->reconnectStream(); - } - // sleep for a max of 2/10 of a second - $timeSoFar = (microtime(true)-$start)*1000000; - $sleepFor = $this->streamingSleepFor; - if ($timeSoFar+$sleepFor>$microseconds) { - $sleepFor = $microseconds - $timeSoFar; - } - - if ($sleepFor>0) { - usleep($sleepFor); - } - } while ($timeSoFar+$sleepFor<$microseconds); - } - - /** - * Process an open stream forever. This function will never return, if you - * want to perform other actions while consuming the stream, you should use - * processFor() instead. - * @return void This function will never return - * @see processFor(); - */ - public function processStreamForever() { - while (true) { - $this->processStream(600); - } - } - - - /** - * Upload a file to a user's file store - * @param string $file A string containing the path of the file to upload. - * @param array $data Additional data about the file you're uploading. At the - * moment accepted keys are: mime-type, kind, type, name, public and annotations. - * - If you don't specify mime-type, ADNPHP will attempt to guess the mime type - * based on the file, however this isn't always reliable. - * - If you don't specify kind ADNPHP will attempt to determine if the file is - * an image or not. - * - If you don't specify name, ADNPHP will use the filename of the first - * parameter. - * - If you don't specify public, your file will be uploaded as a private file. - * - Type is REQUIRED. - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: include_annotations|include_file_annotations. - * @return array An associative array representing the file - */ - public function createFile($file, $data, $params=array()) { - if (!$file) { - throw new AppDotNetException('You must specify a path to a file'); - } - if (!file_exists($file)) { - throw new AppDotNetException('File path specified does not exist'); - } - if (!is_readable($file)) { - throw new AppDotNetException('File path specified is not readable'); - } - - if (!$data) { - $data = array(); - } - - if (!array_key_exists('type',$data) || !$data['type']) { - throw new AppDotNetException('Type is required when creating a file'); - } - - if (!array_key_exists('name',$data)) { - $data['name'] = basename($file); - } - - if (array_key_exists('mime-type',$data)) { - $mimeType = $data['mime-type']; - unset($data['mime-type']); - } - else { - $mimeType = null; - } - if (!array_key_exists('kind',$data)) { - $test = @getimagesize($path); - if ($test && array_key_exists('mime',$test)) { - $data['kind'] = 'image'; - if (!$mimeType) { - $mimeType = $test['mime']; - } - } - else { - $data['kind'] = 'other'; - } - } - if (!$mimeType) { - $finfo = finfo_open(FILEINFO_MIME_TYPE); - $mimeType = finfo_file($finfo, $file); - finfo_close($finfo); - } - if (!$mimeType) { - throw new AppDotNetException('Unable to determine mime type of file, try specifying it explicitly'); - } - if (!array_key_exists('public',$data) || !$data['public']) { - $public = false; - } - else { - $public = true; - } - - $data['content'] = "@$file;type=$mimeType"; - return $this->httpReq('post-raw',$this->_baseUrl.'files', $data, 'multipart/form-data'); - } - - - public function createFilePlaceholder($file = null, $params=array()) { - $name = basename($file); - $data = array('annotations' => $params['annotations'], 'kind' => $params['kind'], - 'name' => $name, 'type' => $params['metadata']); - $json = json_encode($data); - return $this->httpReq('post',$this->_baseUrl.'files', $json, 'application/json'); - } - - public function updateFileContent($fileid, $file) { - - $data = file_get_contents($file); - $finfo = finfo_open(FILEINFO_MIME_TYPE); - $mime = finfo_file($finfo, $file); - finfo_close($finfo); - - return $this->httpReq('put',$this->_baseUrl.'files/' . $fileid - .'/content', $data, $mime); - } - - /** - * Allows for file rename and annotation changes. - * @param integer $file_id The ID of the file to update - * @param array $params An associative array of file parameters. - * @return array An associative array representing the updated file - */ - public function updateFile($file_id=null, $params=array()) { - $data = array('annotations' => $params['annotations'] , 'name' => $params['name']); - $json = json_encode($data); - return $this->httpReq('put',$this->_baseUrl.'files/'.urlencode($file_id), $json, 'application/json'); - } - - /** - * Returns a specific File. - * @param integer $file_id The ID of the file to retrieve - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: include_annotations|include_file_annotations. - * @return array An associative array representing the file - */ - public function getFile($file_id=null,$params = array()) { - return $this->httpReq('get',$this->_baseUrl.'files/'.urlencode($file_id) - .'?'.$this->buildQueryString($params)); - } - - public function getFileContent($file_id=null,$params = array()) { - return $this->httpReq('get',$this->_baseUrl.'files/'.urlencode($file_id) - .'/content?'.$this->buildQueryString($params)); - } - - /** $file_key : derived_file_key */ - public function getDerivedFileContent($file_id=null,$file_key=null,$params = array()) { - return $this->httpReq('get',$this->_baseUrl.'files/'.urlencode($file_id) - .'/content/'.urlencode($file_key) - .'?'.$this->buildQueryString($params)); - } - - /** - * Returns file objects. - * @param array $file_ids The IDs of the files to retrieve - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: include_annotations|include_file_annotations. - * @return array An associative array representing the file data. - */ - public function getFiles($file_ids=array(), $params = array()) { - $ids = ''; - foreach($file_ids as $id) { - $ids .= $id . ','; - } - $params['ids'] = substr($ids, 0, -1); - return $this->httpReq('get',$this->_baseUrl.'files' - .'?'.$this->buildQueryString($params)); - } - - /** - * Returns a user's file objects. - * @param array $params An associative array of optional general parameters. - * This will likely change as the API evolves, as of this writing allowed keys - * are: include_annotations|include_file_annotations|include_user_annotations. - * @return array An associative array representing the file data. - */ - public function getUserFiles($params = array()) { - return $this->httpReq('get',$this->_baseUrl.'users/me/files' - .'?'.$this->buildQueryString($params)); - } - - /** - * Delete a File. The current user must be the same user who created the File. - * It returns the deleted File on success. - * @param integer $file_id The ID of the file to delete - * @return array An associative array representing the file that was deleted - */ - public function deleteFile($file_id=null) { - return $this->httpReq('delete',$this->_baseUrl.'files/'.urlencode($file_id)); - } + // The total number of requests you're allowed within the alloted time period + private $_rateLimit = null; + // The number of requests you have remaining within the alloted time period + private $_rateLimitRemaining = null; + + // The number of seconds remaining in the alloted time period + private $_rateLimitReset = null; + + // The scope the user has + private $_scope = null; + + // token scopes + private $_scopes = array(); + + // debug info + private $_last_request = null; + private $_last_response = null; + + // ssl certification + private $_sslCA = null; + + // the callback function to be called when an event is received from the stream + private $_streamCallback = null; + + // the stream buffer + private $_streamBuffer = ''; + + // stores the curl handler for the current stream + private $_currentStream = null; + + // stores the curl multi handler for the current stream + private $_multiStream = null; + + // stores the number of failed connects, so we can back off multiple failures + private $_connectFailCounter = 0; + + // stores the most recent stream url, so we can re-connect when needed + private $_streamUrl = null; + + // keeps track of the last time we've received a packet from the api, if it's too long we'll reconnect + private $_lastStreamActivity = null; + + // stores the headers received when connecting to the stream + private $_streamHeaders = null; + + // response meta max_id data + private $_maxid = null; + + // response meta min_id data + private $_minid = null; + + // response meta more data + private $_more = null; + + // response stream marker data + private $_last_marker = null; + + // strip envelope response from returned value + private $_stripResponseEnvelope = true; + + // if processing stream_markers or any fast stream, decrease $sleepFor + public $streamingSleepFor = 20000; + + /** + * Constructs an AppDotNet PHP object with the specified client ID and + * client secret. + * + * @param string $client_id The client ID you received from App.net when + * creating your app + * @param string $client_secret The client secret you received from + * App.net when creating your app + */ + public function __construct($client_id, $client_secret) + { + $this->_clientId = $client_id; + $this->_clientSecret = $client_secret; + + // if the digicert certificate exists in the same folder as this file, + // remember that fact for later + if (file_exists(dirname(__FILE__).'/DigiCertHighAssuranceEVRootCA.pem')) { + $this->_sslCA = dirname(__FILE__).'/DigiCertHighAssuranceEVRootCA.pem'; + } + } + + /** + * Set whether or not to strip Envelope Response (meta) information + * This option will be deprecated in the future. Is it to allow + * a stepped migration path between code expecting the old behavior + * and new behavior. When not stripped, you still can use the proper + * method to pull the meta information. Please start converting your code ASAP. + */ + public function includeResponseEnvelope() + { + $this->_stripResponseEnvelope = false; + } + + /** + * Construct the proper Auth URL for the user to visit and either grant + * or not access to your app. Usually you would place this as a link for + * the user to client, or a redirect to send them to the auth URL. + * Also can be called after authentication for additional scopes. + * + * @param string $callbackUri Where you want the user to be directed + * after authenticating with App.net. This must be one of the URIs + * allowed by your App.net application settings + * @param array $scope An array of scopes (permissions) you wish to obtain + * from the user. Currently options are stream, email, write_post, follow, + * messages, and export. If you don't specify anything, you'll only receive + * access to the user's basic profile (the default) + */ + public function getAuthUrl($callback_uri, $scope = null) + { + + // construct an authorization url based on our client id and other data + $data = array( + 'client_id' => $this->_clientId, + 'response_type' => 'code', + 'redirect_uri' => $callback_uri, + ); + + $url = $this->_authUrl; + if ($this->_accessToken) { + $url .= 'authorize?'; + } else { + $url .= 'authenticate?'; + } + $url .= $this->buildQueryString($data); + + if ($scope) { + $url .= '&scope='.implode('+', $scope); + } + + // return the constructed url + return $url; + } + + /** + * Call this after they return from the auth page, or anytime you need the + * token. For example, you could store it in a database and use + * setAccessToken() later on to return on behalf of the user. + */ + public function getAccessToken($callback_uri) + { + // if there's no access token set, and they're returning from + // the auth page with a code, use the code to get a token + if (!$this->_accessToken && isset($_GET['code']) && $_GET['code']) { + + // construct the necessary elements to get a token + $data = array( + 'client_id' => $this->_clientId, + 'client_secret' => $this->_clientSecret, + 'grant_type' => 'authorization_code', + 'redirect_uri' => $callback_uri, + 'code' => $_GET['code'], + ); + + // try and fetch the token with the above data + $res = $this->httpReq('post', $this->_authUrl.'access_token', $data); + + // store it for later + $this->_accessToken = $res['access_token']; + $this->_username = $res['username']; + $this->_user_id = $res['user_id']; + } + + // return what we have (this may be a token, or it may be nothing) + return $this->_accessToken; + } + + /** + * Check the scope of current token to see if it has required scopes + * has to be done after a check. + */ + public function checkScopes($app_scopes) + { + if (!count($this->_scopes)) { + return -1; // _scope is empty + } + $missing = array(); + foreach ($app_scopes as $scope) { + if (!in_array($scope, $this->_scopes)) { + if ($scope == 'public_messages') { + // messages works for public_messages + if (in_array('messages', $this->_scopes)) { + // if we have messages in our scopes + continue; + } + } + $missing[] = $scope; + } + } + // identify the ones missing + if (count($missing)) { + // do something + return $missing; + } + + return 0; // 0 missing + } + + /** + * Set the access token (eg: after retrieving it from offline storage). + * + * @param string $token A valid access token you're previously received + * from calling getAccessToken() + */ + public function setAccessToken($token) + { + $this->_accessToken = $token; + } + + /** + * Deauthorize the current token (delete your authorization from the API) + * Generally this is useful for logging users out from a web app, so they + * don't get automatically logged back in the next time you redirect them + * to the authorization URL. + */ + public function deauthorizeToken() + { + return $this->httpReq('delete', $this->_baseUrl.'token'); + } + + /** + * Retrieve an app access token from the app.net API. This allows you + * to access the API without going through the user access flow if you + * just want to (eg) consume global. App access tokens are required for + * some actions (like streaming global). DO NOT share the return value + * of this function with any user (or save it in a cookie, etc). This + * is considered secret info for your app only. + * + * @return string The app access token + */ + public function getAppAccessToken() + { + + // construct the necessary elements to get a token + $data = array( + 'client_id' => $this->_clientId, + 'client_secret' => $this->_clientSecret, + 'grant_type' => 'client_credentials', + ); + + // try and fetch the token with the above data + $res = $this->httpReq('post', $this->_authUrl.'access_token', $data); + + // store it for later + $this->_appAccessToken = $res['access_token']; + $this->_accessToken = $res['access_token']; + $this->_username = null; + $this->_user_id = null; + + return $this->_accessToken; + } + + /** + * Returns the total number of requests you're allowed within the + * alloted time period. + * + * @see getRateLimitReset() + */ + public function getRateLimit() + { + return $this->_rateLimit; + } + + /** + * The number of requests you have remaining within the alloted time period. + * + * @see getRateLimitReset() + */ + public function getRateLimitRemaining() + { + return $this->_rateLimitRemaining; + } + + /** + * The number of seconds remaining in the alloted time period. + * When this time is up you'll have getRateLimit() available again. + */ + public function getRateLimitReset() + { + return $this->_rateLimitReset; + } + + /** + * The scope the user has. + */ + public function getScope() + { + return $this->_scope; + } + + /** + * Internal function, parses out important information App.net adds + * to the headers. + */ + protected function parseHeaders($response) + { + // take out the headers + // set internal variables + // return the body/content + $this->_rateLimit = null; + $this->_rateLimitRemaining = null; + $this->_rateLimitReset = null; + $this->_scope = null; + + $response = explode("\r\n\r\n", $response, 2); + $headers = $response[0]; + + if ($headers == 'HTTP/1.1 100 Continue') { + $response = explode("\r\n\r\n", $response[1], 2); + $headers = $response[0]; + } + + if (isset($response[1])) { + $content = $response[1]; + } else { + $content = null; + } + + // this is not a good way to parse http headers + // it will not (for example) take into account multiline headers + // but what we're looking for is pretty basic, so we can ignore those shortcomings + $headers = explode("\r\n", $headers); + foreach ($headers as $header) { + $header = explode(': ', $header, 2); + if (count($header) < 2) { + continue; + } + list($k, $v) = $header; + switch ($k) { + case 'X-RateLimit-Remaining': + $this->_rateLimitRemaining = $v; + break; + case 'X-RateLimit-Limit': + $this->_rateLimit = $v; + break; + case 'X-RateLimit-Reset': + $this->_rateLimitReset = $v; + break; + case 'X-OAuth-Scopes': + $this->_scope = $v; + $this->_scopes = explode(',', $v); + break; + } + } + + return $content; + } + + /** + * Internal function. Used to turn things like TRUE into 1, and then + * calls http_build_query. + */ + protected function buildQueryString($array) + { + foreach ($array as $k => &$v) { + if ($v === true) { + $v = '1'; + } elseif ($v === false) { + $v = '0'; + } + unset($v); + } + + return http_build_query($array); + } + + /** + * Internal function to handle all + * HTTP requests (POST,PUT,GET,DELETE). + */ + protected function httpReq($act, $req, $params = array(), $contentType = 'application/x-www-form-urlencoded') + { + $ch = curl_init($req); + $headers = array(); + if ($act != 'get') { + curl_setopt($ch, CURLOPT_POST, true); + // if they passed an array, build a list of parameters from it + if (is_array($params) && $act != 'post-raw') { + $params = $this->buildQueryString($params); + } + curl_setopt($ch, CURLOPT_POSTFIELDS, $params); + $headers[] = 'Content-Type: '.$contentType; + } + if ($act != 'post' && $act != 'post-raw') { + curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($act)); + } + if ($act == 'get' && isset($params['access_token'])) { + $headers[] = 'Authorization: Bearer '.$params['access_token']; + } elseif ($this->_accessToken) { + $headers[] = 'Authorization: Bearer '.$this->_accessToken; + } + curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLINFO_HEADER_OUT, true); + curl_setopt($ch, CURLOPT_HEADER, true); + if ($this->_sslCA) { + curl_setopt($ch, CURLOPT_CAINFO, $this->_sslCA); + } + $this->_last_response = curl_exec($ch); + $this->_last_request = curl_getinfo($ch, CURLINFO_HEADER_OUT); + $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE); + curl_close($ch); + if ($http_status == 0) { + throw new AppDotNetException('Unable to connect to '.$req); + } + if ($http_status < 200 || $http_status >= 300) { + throw new AppDotNetException('HTTP error '.$this->_last_response); + } + if ($this->_last_request === false) { + if (!curl_getinfo($ch, CURLINFO_SSL_VERIFYRESULT)) { + throw new AppDotNetException('SSL verification failed, connection terminated.'); + } + } + $response = $this->parseHeaders($this->_last_response); + $response = json_decode($response, true); + + if (isset($response['meta'])) { + if (isset($response['meta']['max_id'])) { + $this->_maxid = $response['meta']['max_id']; + $this->_minid = $response['meta']['min_id']; + } + if (isset($response['meta']['more'])) { + $this->_more = $response['meta']['more']; + } + if (isset($response['meta']['marker'])) { + $this->_last_marker = $response['meta']['marker']; + } + } + + // look for errors + if (isset($response['error'])) { + if (is_array($response['error'])) { + throw new AppDotNetException($response['error']['message'], + $response['error']['code']); + } else { + throw new AppDotNetException($response['error']); + } + } + + // look for response migration errors + elseif (isset($response['meta']) && isset($response['meta']['error_message'])) { + throw new AppDotNetException($response['meta']['error_message'], $response['meta']['code']); + } + + // if we've received a migration response, handle it and return data only + elseif ($this->_stripResponseEnvelope && isset($response['meta']) && isset($response['data'])) { + return $response['data']; + } + + // else non response migration response, just return it + else { + return $response; + } + } + + /** + * Get max_id from last meta response data envelope. + */ + public function getResponseMaxID() + { + return $this->_maxid; + } + + /** + * Get min_id from last meta response data envelope. + */ + public function getResponseMinID() + { + return $this->_minid; + } + + /** + * Get more from last meta response data envelope. + */ + public function getResponseMore() + { + return $this->_more; + } + + /** + * Get marker from last meta response data envelope. + */ + public function getResponseMarker() + { + return $this->_last_marker; + } + + /** + * Fetch API configuration object. + */ + public function getConfig() + { + return $this->httpReq('get', $this->_baseUrl.'config'); + } + + /** + * Return the Filters for the current user. + */ + public function getAllFilters() + { + return $this->httpReq('get', $this->_baseUrl.'filters'); + } + + /** + * Create a Filter for the current user. + * + * @param string $name The name of the new filter + * @param array $filters An associative array of filters to be applied. + * This may change as the API evolves, as of this writing possible + * values are: user_ids, hashtags, link_domains, and mention_user_ids. + * You will need to provide at least one filter name=>value pair + */ + public function createFilter($name = 'New filter', $filters = array()) + { + $filters['name'] = $name; + + return $this->httpReq('post', $this->_baseUrl.'filters', $filters); + } + + /** + * Returns a specific Filter object. + * + * @param int $filter_id The ID of the filter you wish to retrieve + */ + public function getFilter($filter_id = null) + { + return $this->httpReq('get', $this->_baseUrl.'filters/'.urlencode($filter_id)); + } + + /** + * Delete a Filter. The Filter must belong to the current User. + * + * @return object Returns the deleted Filter on success + */ + public function deleteFilter($filter_id = null) + { + return $this->httpReq('delete', $this->_baseUrl.'filters/'.urlencode($filter_id)); + } + + /** + * Process user description, message or post text. + * Mentions and hashtags will be parsed out of the + * text, as will bare URLs. To create a link in the text without using a + * bare URL, include the anchor text in the object text and include a link + * entity in the function call. + * + * @param string $text The text of the description/message/post + * @param array $data An associative array of optional post data. This + * will likely change as the API evolves, as of this writing allowed keys are: + * reply_to, and annotations. "annotations" may be a complex object represented + * by an associative array + * @param array $params An associative array of optional data to be included + * in the URL (such as 'include_annotations' and 'include_machine') + * + * @return array An associative array representing the post + */ + public function processText($text = null, $data = array(), $params = array()) + { + $data['text'] = $text; + $json = json_encode($data); + $qs = ''; + if (!empty($params)) { + $qs = '?'.$this->buildQueryString($params); + } + + return $this->httpReq('post', $this->_baseUrl.'text/process'.$qs, $json, 'application/json'); + } + + /** + * Create a new Post object. Mentions and hashtags will be parsed out of the + * post text, as will bare URLs. To create a link in a post without using a + * bare URL, include the anchor text in the post's text and include a link + * entity in the post creation call. + * + * @param string $text The text of the post + * @param array $data An associative array of optional post data. This + * will likely change as the API evolves, as of this writing allowed keys are: + * reply_to, and annotations. "annotations" may be a complex object represented + * by an associative array + * @param array $params An associative array of optional data to be included + * in the URL (such as 'include_annotations' and 'include_machine') + * + * @return array An associative array representing the post + */ + public function createPost($text = null, $data = array(), $params = array()) + { + $data['text'] = $text; + + $json = json_encode($data); + $qs = ''; + if (!empty($params)) { + $qs = '?'.$this->buildQueryString($params); + } + + return $this->httpReq('post', $this->_baseUrl.'posts'.$qs, $json, 'application/json'); + } + + /** + * Returns a specific Post. + * + * @param int $post_id The ID of the post to retrieve + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations + * + * @return array An associative array representing the post + */ + public function getPost($post_id = null, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'posts/'.urlencode($post_id) + .'?'.$this->buildQueryString($params)); + } + + /** + * Delete a Post. The current user must be the same user who created the Post. + * It returns the deleted Post on success. + * + * @param int $post_id The ID of the post to delete + * @param array An associative array representing the post that was deleted + */ + public function deletePost($post_id = null) + { + return $this->httpReq('delete', $this->_baseUrl.'posts/'.urlencode($post_id)); + } + + /** + * Retrieve the Posts that are 'in reply to' a specific Post. + * + * @param int $post_id The ID of the post you want to retrieve replies for + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations + * + * @return An array of associative arrays, each representing a single post + */ + public function getPostReplies($post_id = null, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'posts/'.urlencode($post_id) + .'/replies?'.$this->buildQueryString($params)); + } + + /** + * Get the most recent Posts created by a specific User in reverse + * chronological order (most recent first). + * + * @param mixed $user_id Either the ID of the user you wish to retrieve posts by, + * or the string "me", which will retrieve posts for the user you're authenticated + * as + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations + * + * @return An array of associative arrays, each representing a single post + */ + public function getUserPosts($user_id = 'me', $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'users/'.urlencode($user_id) + .'/posts?'.$this->buildQueryString($params)); + } + + /** + * Get the most recent Posts mentioning by a specific User in reverse + * chronological order (newest first). + * + * @param mixed $user_id Either the ID of the user who is being mentioned, or + * the string "me", which will retrieve posts for the user you're authenticated + * as + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations + * + * @return An array of associative arrays, each representing a single post + */ + public function getUserMentions($user_id = 'me', $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'users/' + .urlencode($user_id).'/mentions?'.$this->buildQueryString($params)); + } + + /** + * Return the 20 most recent posts from the current User and + * the Users they follow. + * + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations + * + * @return An array of associative arrays, each representing a single post + */ + public function getUserStream($params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'posts/stream?'.$this->buildQueryString($params)); + } + + /** + * Returns a specific user object. + * + * @param mixed $user_id The ID of the user you want to retrieve, or the string + * "me" to retrieve data for the users you're currently authenticated as + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_user_annotations + * + * @return array An associative array representing the user data + */ + public function getUser($user_id = 'me', $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'users/'.urlencode($user_id) + .'?'.$this->buildQueryString($params)); + } + + /** + * Returns multiple users request by an array of user ids. + * + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_user_annotations + * + * @return array An associative array representing the users data + */ + public function getUsers($user_arr, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'users?ids='.implode(',', $user_arr) + .'&'.$this->buildQueryString($params)); + } + + /** + * Add the specified user ID to the list of users followed. + * Returns the User object of the user being followed. + * + * @param int $user_id The user ID of the user to follow + * + * @return array An associative array representing the user you just followed + */ + public function followUser($user_id = null) + { + return $this->httpReq('post', $this->_baseUrl.'users/'.urlencode($user_id).'/follow'); + } + + /** + * Removes the specified user ID to the list of users followed. + * Returns the User object of the user being unfollowed. + * + * @param int $user_id The user ID of the user to unfollow + * + * @return array An associative array representing the user you just unfollowed + */ + public function unfollowUser($user_id = null) + { + return $this->httpReq('delete', $this->_baseUrl.'users/'.urlencode($user_id).'/follow'); + } + + /** + * Returns an array of User objects the specified user is following. + * + * @param mixed $user_id Either the ID of the user being followed, or + * the string "me", which will retrieve posts for the user you're authenticated + * as + * + * @return array An array of associative arrays, each representing a single + * user following $user_id + */ + public function getFollowing($user_id = 'me') + { + return $this->httpReq('get', $this->_baseUrl.'users/'.$user_id.'/following'); + } + + /** + * Returns an array of User objects for users following the specified user. + * + * @param mixed $user_id Either the ID of the user being followed, or + * the string "me", which will retrieve posts for the user you're authenticated + * as + * + * @return array An array of associative arrays, each representing a single + * user following $user_id + */ + public function getFollowers($user_id = 'me') + { + return $this->httpReq('get', $this->_baseUrl.'users/'.$user_id.'/followers'); + } + + /** + * Return Posts matching a specific #hashtag. + * + * @param string $hashtag The hashtag you're looking for + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations + * + * @return An array of associative arrays, each representing a single post + */ + public function searchHashtags($hashtag = null, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'posts/tag/' + .urlencode($hashtag).'?'.$this->buildQueryString($params)); + } + + /** + * Retrieve a list of all public Posts on App.net, often referred to as the + * global stream. + * + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations + * + * @return An array of associative arrays, each representing a single post + */ + public function getPublicPosts($params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'posts/stream/global?'.$this->buildQueryString($params)); + } + + /** + * List User interactions. + */ + public function getMyInteractions($params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'users/me/interactions?'.$this->buildQueryString($params)); + } + + /** + * Retrieve a user's user ID by specifying their username. + * Now supported by the API. We use the API if we have a token + * Otherwise we scrape the alpha.app.net site for the info. + * + * @param string $username The username of the user you want the ID of, without + * an @ symbol at the beginning + * + * @return int The user's user ID + */ + public function getIdByUsername($username = null) + { + if ($this->_accessToken) { + $res = $this->httpReq('get', $this->_baseUrl.'users/@'.$username); + $user_id = $res['data']['id']; + } else { + $ch = curl_init('https://alpha.app.net/'.urlencode(strtolower($username))); + curl_setopt($ch, CURLOPT_POST, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_USERAGENT, + 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1'); + $response = curl_exec($ch); + curl_close($ch); + $temp = explode('title="User Id ', $response); + $temp2 = explode('"', $temp[1]); + $user_id = $temp2[0]; + } + + return $user_id; + } + + /** + * Mute a user. + * + * @param int $user_id The user ID to mute + */ + public function muteUser($user_id = null) + { + return $this->httpReq('post', $this->_baseUrl.'users/'.urlencode($user_id).'/mute'); + } + + /** + * Unmute a user. + * + * @param int $user_id The user ID to unmute + */ + public function unmuteUser($user_id = null) + { + return $this->httpReq('delete', $this->_baseUrl.'users/'.urlencode($user_id).'/mute'); + } + + /** + * List the users muted by the current user. + * + * @return array An array of associative arrays, each representing one muted user + */ + public function getMuted() + { + return $this->httpReq('get', $this->_baseUrl.'users/me/muted'); + } + + /** + * Star a post. + * + * @param int $post_id The post ID to star + */ + public function starPost($post_id = null) + { + return $this->httpReq('post', $this->_baseUrl.'posts/'.urlencode($post_id).'/star'); + } + + /** + * Unstar a post. + * + * @param int $post_id The post ID to unstar + */ + public function unstarPost($post_id = null) + { + return $this->httpReq('delete', $this->_baseUrl.'posts/'.urlencode($post_id).'/star'); + } + + /** + * List the posts starred by the current user. + * + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations. + * See https://github.com/appdotnet/api-spec/blob/master/resources/posts.md#general-parameters + * + * @return array An array of associative arrays, each representing a single + * user who has starred a post + */ + public function getStarred($user_id = 'me', $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'users/'.urlencode($user_id).'/stars' + .'?'.$this->buildQueryString($params)); + } + + /** + * List the users who have starred a post. + * + * @param int $post_id the post ID to get stars from + * + * @return array An array of associative arrays, each representing one user + */ + public function getStars($post_id = null) + { + return $this->httpReq('get', $this->_baseUrl.'posts/'.urlencode($post_id).'/stars'); + } + + /** + * Returns an array of User objects of users who reposted the specified post. + * + * @param int $post_id the post ID to + * + * @return array An array of associative arrays, each representing a single + * user who reposted $post_id + */ + public function getReposters($post_id) + { + return $this->httpReq('get', $this->_baseUrl.'posts/'.urlencode($post_id).'/reposters'); + } + + /** + * Repost an existing Post object. + * + * @param int $post_id The id of the post + * + * @return not a clue + */ + public function repost($post_id) + { + return $this->httpReq('post', $this->_baseUrl.'posts/'.urlencode($post_id).'/repost'); + } + + /** + * Delete a post that the user has reposted. + * + * @param int $post_id The id of the post + * + * @return not a clue + */ + public function deleteRepost($post_id) + { + return $this->httpReq('delete', $this->_baseUrl.'posts/'.urlencode($post_id).'/repost'); + } + + /** + * List the posts who match a specific search term. + * + * @param array $params a list of filter, search query, and general Post parameters + * see: https://developers.app.net/reference/resources/post/search/ + * @param string $query The search query. Supports + * normal search terms. Searches post text + * + * @return array An array of associative arrays, each representing one post. + * or false on error + */ + public function searchPosts($params = array(), $query = '', $order = 'default') + { + if (!is_array($params)) { + return false; + } + if (!empty($query)) { + $params['query'] = $query; + } + if ($order == 'default') { + if (!empty($query)) { + $params['order'] = 'score'; + } else { + $params['order'] = 'id'; + } + } + + return $this->httpReq('get', $this->_baseUrl.'posts/search?'.$this->buildQueryString($params)); + } + + /** + * List the users who match a specific search term. + * + * @param string $search The search query. Supports @username or #tag searches as + * well as normal search terms. Searches username, display name, bio information. + * Does not search posts + * + * @return array An array of associative arrays, each representing one user + */ + public function searchUsers($search = '') + { + return $this->httpReq('get', $this->_baseUrl.'users/search?q='.urlencode($search)); + } + + /** + * Return the 20 most recent posts for a stream using a valid Token. + * + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations + * + * @return An array of associative arrays, each representing a single post + */ + public function getTokenStream($params = array()) + { + if ($params['access_token']) { + return $this->httpReq('get', $this->_baseUrl.'posts/stream?'.$this->buildQueryString($params), $params); + } else { + return $this->httpReq('get', $this->_baseUrl.'posts/stream?'.$this->buildQueryString($params)); + } + } + + /** + * Get a user object by username. + * + * @param string $name the @name to get + * + * @return array representing one user + */ + public function getUserByName($name = null) + { + return $this->httpReq('get', $this->_baseUrl.'users/@'.$name); + } + + /** + * Return the 20 most recent Posts from the current User's personalized stream + * and mentions stream merged into one stream. + * + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: count, before_id, since_id, include_muted, include_deleted, + * include_directed_posts, and include_annotations + * + * @return An array of associative arrays, each representing a single post + */ + public function getUserUnifiedStream($params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'posts/stream/unified?'.$this->buildQueryString($params)); + } + + /** + * Update Profile Data via JSON. + * + * @data array containing user descriptors + */ + public function updateUserData($data = array(), $params = array()) + { + $json = json_encode($data); + + return $this->httpReq('put', $this->_baseUrl.'users/me'.'?'. + $this->buildQueryString($params), $json, 'application/json'); + } + + /** + * Update a user image. + * + * @which avatar|cover + * @image path reference to image + */ + protected function updateUserImage($which = 'avatar', $image = null) + { + $data = array($which => "@$image"); + + return $this->httpReq('post-raw', $this->_baseUrl.'users/me/'.$which, $data, 'multipart/form-data'); + } + + public function updateUserAvatar($avatar = null) + { + if ($avatar != null) { + return $this->updateUserImage('avatar', $avatar); + } + } + + public function updateUserCover($cover = null) + { + if ($cover != null) { + return $this->updateUserImage('cover', $cover); + } + } + + /** + * update stream marker. + */ + public function updateStreamMarker($data = array()) + { + $json = json_encode($data); + + return $this->httpReq('post', $this->_baseUrl.'posts/marker', $json, 'application/json'); + } + + /** + * get a page of current user subscribed channels. + */ + public function getUserSubscriptions($params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'channels?'.$this->buildQueryString($params)); + } + + /** + * get user channels. + */ + public function getMyChannels($params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'channels/me?'.$this->buildQueryString($params)); + } + + /** + * create a channel + * note: you cannot create a channel with type=net.app.core.pm (see createMessage). + */ + public function createChannel($data = array()) + { + $json = json_encode($data); + + return $this->httpReq('post', $this->_baseUrl.'channels'.($pm ? '/pm/messsages' : ''), $json, 'application/json'); + } + + /** + * get channelid info. + */ + public function getChannel($channelid, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'channels/'.$channelid.'?'.$this->buildQueryString($params)); + } + + /** + * get multiple channels' info by an array of channelids. + */ + public function getChannels($channels, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'channels?ids='.implode(',', $channels).'&'.$this->buildQueryString($params)); + } + + /** + * update channelid. + */ + public function updateChannel($channelid, $data = array()) + { + $json = json_encode($data); + + return $this->httpReq('put', $this->_baseUrl.'channels/'.$channelid, $json, 'application/json'); + } + + /** + * subscribe from channelid. + */ + public function channelSubscribe($channelid) + { + return $this->httpReq('post', $this->_baseUrl.'channels/'.$channelid.'/subscribe'); + } + + /** + * unsubscribe from channelid. + */ + public function channelUnsubscribe($channelid) + { + return $this->httpReq('delete', $this->_baseUrl.'channels/'.$channelid.'/subscribe'); + } + + /** + * get all user objects subscribed to channelid. + */ + public function getChannelSubscriptions($channelid, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'channel/'.$channelid.'/subscribers?'.$this->buildQueryString($params)); + } + + /** + * get all user IDs subscribed to channelid. + */ + public function getChannelSubscriptionsById($channelid) + { + return $this->httpReq('get', $this->_baseUrl.'channel/'.$channelid.'/subscribers/ids'); + } + + /** + * get a page of messages in channelid. + */ + public function getMessages($channelid, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'channels/'.$channelid.'/messages?'.$this->buildQueryString($params)); + } + + /** + * create message. + * + * @param $channelid numeric or "pm" for auto-chanenl (type=net.app.core.pm) + * @param $data array('text'=>'YOUR_MESSAGE') If a type=net.app.core.pm, then "destinations" key can be set to address as an array of people to send this PM too + */ + public function createMessage($channelid, $data) + { + $json = json_encode($data); + + return $this->httpReq('post', $this->_baseUrl.'channels/'.$channelid.'/messages', $json, 'application/json'); + } + + /** + * get message. + */ + public function getMessage($channelid, $messageid) + { + return $this->httpReq('get', $this->_baseUrl.'channels/'.$channelid.'/messages/'.$messageid); + } + + /** + * delete messsage. + */ + public function deleteMessage($channelid, $messageid) + { + return $this->httpReq('delete', $this->_baseUrl.'channels/'.$channelid.'/messages/'.$messageid); + } + + /** + * Get Application Information. + */ + public function getAppTokenInfo() + { + // requires appAccessToken + if (!$this->_appAccessToken) { + $this->getAppAccessToken(); + } + // ensure request is made with our appAccessToken + $params['access_token'] = $this->_appAccessToken; + + return $this->httpReq('get', $this->_baseUrl.'token', $params); + } + + /** + * Get User Information. + */ + public function getUserTokenInfo() + { + return $this->httpReq('get', $this->_baseUrl.'token'); + } + + /** + * Get Application Authorized User IDs. + */ + public function getAppUserIDs() + { + // requires appAccessToken + if (!$this->_appAccessToken) { + $this->getAppAccessToken(); + } + // ensure request is made with our appAccessToken + $params['access_token'] = $this->_appAccessToken; + + return $this->httpReq('get', $this->_baseUrl.'apps/me/tokens/user_ids', $params); + } + + /** + * Get Application Authorized User Tokens. + */ + public function getAppUserTokens() + { + // requires appAccessToken + if (!$this->_appAccessToken) { + $this->getAppAccessToken(); + } + // ensure request is made with our appAccessToken + $params['access_token'] = $this->_appAccessToken; + + return $this->httpReq('get', $this->_baseUrl.'apps/me/tokens', $params); + } + + public function getLastRequest() + { + return $this->_last_request; + } + public function getLastResponse() + { + return $this->_last_response; + } + + /** + * Registers your function (or an array of object and method) to be called + * whenever an event is received via an open app.net stream. Your function + * will receive a single parameter, which is the object wrapper containing + * the meta and data. + * + * @param mixed A PHP callback (either a string containing the function name, + * or an array where the first element is the class/object and the second + * is the method) + */ + public function registerStreamFunction($function) + { + $this->_streamCallback = $function; + } + + /** + * Opens a stream that's been created for this user/app and starts sending + * events/objects to your defined callback functions. You must define at + * least one callback function before opening a stream. + * + * @param mixed $stream Either a stream ID or the endpoint of a stream + * you've already created. This stream must exist and must be valid for + * your current access token. If you pass a stream ID, the library will + * make an API call to get the endpoint. + * + * This function will return immediately, but your callback functions + * will continue to receive events until you call closeStream() or until + * App.net terminates the stream from their end with an error. + * + * If you're disconnected due to a network error, the library will + * automatically attempt to reconnect you to the same stream, no action + * on your part is necessary for this. However if the app.net API returns + * an error, a reconnection attempt will not be made. + * + * Note there is no closeStream, because once you open a stream you + * can't stop it (unless you exit() or die() or throw an uncaught + * exception, or something else that terminates the script) + * + * @return bool True + * + * @see createStream() + */ + public function openStream($stream) + { + // if there's already a stream running, don't allow another + if ($this->_currentStream) { + throw new AppDotNetException('There is already a stream being consumed, only one stream can be consumed per AppDotNetStream instance'); + } + // must register a callback (or the exercise is pointless) + if (!$this->_streamCallback) { + throw new AppDotNetException('You must define your callback function using registerStreamFunction() before calling openStream'); + } + // if the stream is a numeric value, get the stream info from the api + if (is_numeric($stream)) { + $stream = $this->getStream($stream); + $this->_streamUrl = $stream['endpoint']; + } else { + $this->_streamUrl = $stream; + } + // continue doing this until we get an error back or something...? + $this->httpStream('get', $this->_streamUrl); + + return true; + } + + /** + * Close the currently open stream. + * + * @return true; + */ + public function closeStream() + { + if (!$this->_lastStreamActivity) { + // never opened + return; + } + if (!$this->_multiStream) { + throw new AppDotNetException('You must open a stream before calling closeStream()'); + } + curl_close($this->_currentStream); + curl_multi_remove_handle($this->_multiStream, $this->_currentStream); + curl_multi_close($this->_multiStream); + $this->_currentStream = null; + $this->_multiStream = null; + } + + /** + * Retrieve all streams for the current access token. + * + * @return array An array of stream definitions + */ + public function getAllStreams() + { + return $this->httpReq('get', $this->_baseUrl.'streams'); + } + + /** + * Returns a single stream specified by a stream ID. The stream must have been + * created with the current access token. + * + * @return array A stream definition + */ + public function getStream($streamId) + { + return $this->httpReq('get', $this->_baseUrl.'streams/'.urlencode($streamId)); + } + + /** + * Creates a stream for the current app access token. + * + * @param array $objectTypes The objects you want to retrieve data for from the + * stream. At time of writing these can be 'post', 'star', and/or 'user_follow'. + * If you don't specify, all events will be retrieved + */ + public function createStream($objectTypes = null) + { + // default object types to everything + if (is_null($objectTypes)) { + $objectTypes = array('post', 'star', 'user_follow'); + } + $data = array( + 'object_types' => $objectTypes, + 'type' => 'long_poll', + ); + $data = json_encode($data); + $response = $this->httpReq('post', $this->_baseUrl.'streams', $data, 'application/json'); + + return $response; + } + + /** + * Update stream for the current app access token. + * + * @param int $streamId The stream ID to update. This stream must have been + * created by the current access token + * @param array $data allows object_types, type, filter_id and key to be updated. filter_id/key can be omitted + */ + public function updateStream($streamId, $data) + { + // objectTypes is likely required + if (is_null($data['object_types'])) { + $data['object_types'] = array('post', 'star', 'user_follow'); + } + // type can still only be long_poll + if (is_null($data['type'])) { + $data['type'] = 'long_poll'; + } + $data = json_encode($data); + $response = $this->httpReq('put', $this->_baseUrl.'streams/'.urlencode($streamId), $data, 'application/json'); + + return $response; + } + + /** + * Deletes a stream if you no longer need it. + * + * @param int $streamId The stream ID to delete. This stream must have been + * created by the current access token + */ + public function deleteStream($streamId) + { + return $this->httpReq('delete', $this->_baseUrl.'streams/'.urlencode($streamId)); + } + + /** + * Deletes all streams created by the current access token. + */ + public function deleteAllStreams() + { + return $this->httpReq('delete', $this->_baseUrl.'streams'); + } + + /** + * Internal function used to process incoming chunks from the stream. This is only + * public because it needs to be accessed by CURL. Do not call or use this function + * in your own code. + * + * @ignore + */ + public function httpStreamReceive($ch, $data) + { + $this->_lastStreamActivity = time(); + $this->_streamBuffer .= $data; + if (!$this->_streamHeaders) { + $pos = strpos($this->_streamBuffer, "\r\n\r\n"); + if ($pos !== false) { + $this->_streamHeaders = substr($this->_streamBuffer, 0, $pos); + $this->_streamBuffer = substr($this->_streamBuffer, $pos + 4); + } + } else { + $pos = strpos($this->_streamBuffer, "\r\n"); + while ($pos !== false) { + $command = substr($this->_streamBuffer, 0, $pos); + $this->_streamBuffer = substr($this->_streamBuffer, $pos + 2); + $command = json_decode($command, true); + if ($command) { + call_user_func($this->_streamCallback, $command); + } + $pos = strpos($this->_streamBuffer, "\r\n"); + } + } + + return strlen($data); + } + + /** + * Opens a long lived HTTP connection to the app.net servers, and sends data + * received to the httpStreamReceive function. As a general rule you should not + * directly call this method, it's used by openStream(). + */ + protected function httpStream($act, $req, $params = array(), $contentType = 'application/x-www-form-urlencoded') + { + if ($this->_currentStream) { + throw new AppDotNetException('There is already an open stream, you must close the existing one before opening a new one'); + } + $headers = array(); + $this->_streamBuffer = ''; + if ($this->_accessToken) { + $headers[] = 'Authorization: Bearer '.$this->_accessToken; + } + $this->_currentStream = curl_init($req); + curl_setopt($this->_currentStream, CURLOPT_HTTPHEADER, $headers); + curl_setopt($this->_currentStream, CURLOPT_RETURNTRANSFER, true); + curl_setopt($this->_currentStream, CURLINFO_HEADER_OUT, true); + curl_setopt($this->_currentStream, CURLOPT_HEADER, true); + if ($this->_sslCA) { + curl_setopt($this->_currentStream, CURLOPT_CAINFO, $this->_sslCA); + } + // every time we receive a chunk of data, forward it to httpStreamReceive + curl_setopt($this->_currentStream, CURLOPT_WRITEFUNCTION, array($this, 'httpStreamReceive')); + + // curl_exec($ch); + // return; + + $this->_multiStream = curl_multi_init(); + $this->_lastStreamActivity = time(); + curl_multi_add_handle($this->_multiStream, $this->_currentStream); + } + + public function reconnectStream() + { + $this->closeStream(); + ++$this->_connectFailCounter; + // if we've failed a few times, back off + if ($this->_connectFailCounter > 1) { + $sleepTime = pow(2, $this->_connectFailCounter); + // don't sleep more than 60 seconds + if ($sleepTime > 60) { + $sleepTime = 60; + } + sleep($sleepTime); + } + $this->httpStream('get', $this->_streamUrl); + } + + /** + * Process an open stream for x microseconds, then return. This is useful if you want + * to be doing other things while processing the stream. If you just want to + * consume the stream without other actions, you can call processForever() instead. + * + * @param float @microseconds The number of microseconds to process for before + * returning. There are 1,000,000 microseconds in a second + */ + public function processStream($microseconds = null) + { + if (!$this->_multiStream) { + throw new AppDotNetException('You must open a stream before calling processStream()'); + } + $start = microtime(true); + $active = null; + $inQueue = null; + $sleepFor = 0; + do { + // if we haven't received anything within 5.5 minutes, reconnect + // keepalives are sent every 5 minutes (measured on 2013-3-12 by @ryantharp) + if (time() - $this->_lastStreamActivity >= 330) { + $this->reconnectStream(); + } + curl_multi_exec($this->_multiStream, $active); + if (!$active) { + $httpCode = curl_getinfo($this->_currentStream, CURLINFO_HTTP_CODE); + // don't reconnect on 400 errors + if ($httpCode >= 400 && $httpCode <= 499) { + throw new AppDotNetException('Received HTTP error '.$httpCode.' check your URL and credentials before reconnecting'); + } + $this->reconnectStream(); + } + // sleep for a max of 2/10 of a second + $timeSoFar = (microtime(true) - $start) * 1000000; + $sleepFor = $this->streamingSleepFor; + if ($timeSoFar + $sleepFor > $microseconds) { + $sleepFor = $microseconds - $timeSoFar; + } + + if ($sleepFor > 0) { + usleep($sleepFor); + } + } while ($timeSoFar + $sleepFor < $microseconds); + } + + /** + * Process an open stream forever. This function will never return, if you + * want to perform other actions while consuming the stream, you should use + * processFor() instead. + * + * @see processFor(); + */ + public function processStreamForever() + { + while (true) { + $this->processStream(600); + } + } + + /** + * Upload a file to a user's file store. + * + * @param string $file A string containing the path of the file to upload + * @param array $data Additional data about the file you're uploading. At the + * moment accepted keys are: mime-type, kind, type, name, public and annotations. + * - If you don't specify mime-type, ADNPHP will attempt to guess the mime type + * based on the file, however this isn't always reliable. + * - If you don't specify kind ADNPHP will attempt to determine if the file is + * an image or not. + * - If you don't specify name, ADNPHP will use the filename of the first + * parameter. + * - If you don't specify public, your file will be uploaded as a private file. + * - Type is REQUIRED + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_file_annotations + * + * @return array An associative array representing the file + */ + public function createFile($file, $data, $params = array()) + { + if (!$file) { + throw new AppDotNetException('You must specify a path to a file'); + } + if (!file_exists($file)) { + throw new AppDotNetException('File path specified does not exist'); + } + if (!is_readable($file)) { + throw new AppDotNetException('File path specified is not readable'); + } + + if (!$data) { + $data = array(); + } + + if (!array_key_exists('type', $data) || !$data['type']) { + throw new AppDotNetException('Type is required when creating a file'); + } + + if (!array_key_exists('name', $data)) { + $data['name'] = basename($file); + } + + if (array_key_exists('mime-type', $data)) { + $mimeType = $data['mime-type']; + unset($data['mime-type']); + } else { + $mimeType = null; + } + if (!array_key_exists('kind', $data)) { + $test = @getimagesize($path); + if ($test && array_key_exists('mime', $test)) { + $data['kind'] = 'image'; + if (!$mimeType) { + $mimeType = $test['mime']; + } + } else { + $data['kind'] = 'other'; + } + } + if (!$mimeType) { + $finfo = finfo_open(FILEINFO_MIME_TYPE); + $mimeType = finfo_file($finfo, $file); + finfo_close($finfo); + } + if (!$mimeType) { + throw new AppDotNetException('Unable to determine mime type of file, try specifying it explicitly'); + } + if (!array_key_exists('public', $data) || !$data['public']) { + $public = false; + } else { + $public = true; + } + + $data['content'] = "@$file;type=$mimeType"; + + return $this->httpReq('post-raw', $this->_baseUrl.'files', $data, 'multipart/form-data'); + } + + public function createFilePlaceholder($file = null, $params = array()) + { + $name = basename($file); + $data = array('annotations' => $params['annotations'], 'kind' => $params['kind'], + 'name' => $name, 'type' => $params['metadata'], ); + $json = json_encode($data); + + return $this->httpReq('post', $this->_baseUrl.'files', $json, 'application/json'); + } + + public function updateFileContent($fileid, $file) + { + $data = file_get_contents($file); + $finfo = finfo_open(FILEINFO_MIME_TYPE); + $mime = finfo_file($finfo, $file); + finfo_close($finfo); + + return $this->httpReq('put', $this->_baseUrl.'files/'.$fileid + .'/content', $data, $mime); + } + + /** + * Allows for file rename and annotation changes. + * + * @param int $file_id The ID of the file to update + * @param array $params An associative array of file parameters + * + * @return array An associative array representing the updated file + */ + public function updateFile($file_id = null, $params = array()) + { + $data = array('annotations' => $params['annotations'], 'name' => $params['name']); + $json = json_encode($data); + + return $this->httpReq('put', $this->_baseUrl.'files/'.urlencode($file_id), $json, 'application/json'); + } + + /** + * Returns a specific File. + * + * @param int $file_id The ID of the file to retrieve + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_file_annotations + * + * @return array An associative array representing the file + */ + public function getFile($file_id = null, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'files/'.urlencode($file_id) + .'?'.$this->buildQueryString($params)); + } + + public function getFileContent($file_id = null, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'files/'.urlencode($file_id) + .'/content?'.$this->buildQueryString($params)); + } + + /** $file_key : derived_file_key */ + public function getDerivedFileContent($file_id = null, $file_key = null, $params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'files/'.urlencode($file_id) + .'/content/'.urlencode($file_key) + .'?'.$this->buildQueryString($params)); + } + + /** + * Returns file objects. + * + * @param array $file_ids The IDs of the files to retrieve + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_file_annotations + * + * @return array An associative array representing the file data + */ + public function getFiles($file_ids = array(), $params = array()) + { + $ids = ''; + foreach ($file_ids as $id) { + $ids .= $id.','; + } + $params['ids'] = substr($ids, 0, -1); + + return $this->httpReq('get', $this->_baseUrl.'files' + .'?'.$this->buildQueryString($params)); + } + + /** + * Returns a user's file objects. + * + * @param array $params An associative array of optional general parameters. + * This will likely change as the API evolves, as of this writing allowed keys + * are: include_annotations|include_file_annotations|include_user_annotations + * + * @return array An associative array representing the file data + */ + public function getUserFiles($params = array()) + { + return $this->httpReq('get', $this->_baseUrl.'users/me/files' + .'?'.$this->buildQueryString($params)); + } + + /** + * Delete a File. The current user must be the same user who created the File. + * It returns the deleted File on success. + * + * @param int $file_id The ID of the file to delete + * + * @return array An associative array representing the file that was deleted + */ + public function deleteFile($file_id = null) + { + return $this->httpReq('delete', $this->_baseUrl.'files/'.urlencode($file_id)); + } } -class AppDotNetException extends Exception {} +class AppDotNetException extends Exception +{ +} diff --git a/appnet/appnet.php b/appnet/appnet.php index 0c53a49f..eedd24e0 100644 --- a/appnet/appnet.php +++ b/appnet/appnet.php @@ -4,7 +4,7 @@ * Name: App.net Connector * Description: Bidirectional (posting and reading) connector for app.net. * Version: 0.2 - * Author: Michael Vogel + * Author: Michael Vogel . */ /* @@ -15,1248 +15,1312 @@ - https://alpha.app.net/opendev/post/34396399 - location data */ -require_once('include/enotify.php'); -require_once("include/socgraph.php"); +require_once 'include/enotify.php'; +require_once 'include/socgraph.php'; define('APPNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes -function appnet_install() { - register_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local'); - register_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send'); - register_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets'); - register_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron'); - register_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings'); - register_hook('connector_settings_post','addon/appnet/appnet.php', 'appnet_settings_post'); - register_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body'); - register_hook('check_item_notification','addon/appnet/appnet.php', 'appnet_check_item_notification'); +function appnet_install() +{ + register_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local'); + register_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send'); + register_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets'); + register_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron'); + register_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings'); + register_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post'); + register_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body'); + register_hook('check_item_notification', 'addon/appnet/appnet.php', 'appnet_check_item_notification'); } - -function appnet_uninstall() { - unregister_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local'); - unregister_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send'); - unregister_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets'); - unregister_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron'); - unregister_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings'); - unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post'); - unregister_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body'); - unregister_hook('check_item_notification','addon/appnet/appnet.php', 'appnet_check_item_notification'); +function appnet_uninstall() +{ + unregister_hook('post_local', 'addon/appnet/appnet.php', 'appnet_post_local'); + unregister_hook('notifier_normal', 'addon/appnet/appnet.php', 'appnet_send'); + unregister_hook('jot_networks', 'addon/appnet/appnet.php', 'appnet_jot_nets'); + unregister_hook('cron', 'addon/appnet/appnet.php', 'appnet_cron'); + unregister_hook('connector_settings', 'addon/appnet/appnet.php', 'appnet_settings'); + unregister_hook('connector_settings_post', 'addon/appnet/appnet.php', 'appnet_settings_post'); + unregister_hook('prepare_body', 'addon/appnet/appnet.php', 'appnet_prepare_body'); + unregister_hook('check_item_notification', 'addon/appnet/appnet.php', 'appnet_check_item_notification'); } -function appnet_module() {} - -function appnet_content(&$a) { - if(! local_user()) { - notice( t('Permission denied.') . EOL); - return ''; - } - - require_once("mod/settings.php"); - settings_init($a); - - if (isset($a->argv[1])) - switch ($a->argv[1]) { - case "connect": - $o = appnet_connect($a); - break; - default: - $o = print_r($a->argv, true); - break; - } - else - $o = appnet_connect($a); - - return $o; +function appnet_module() +{ } -function appnet_check_item_notification($a, &$notification_data) { - $own_id = get_pconfig($notification_data["uid"], 'appnet', 'ownid'); +function appnet_content(&$a) +{ + if (!local_user()) { + notice(t('Permission denied.').EOL); - $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", - intval($notification_data["uid"]), - dbesc("adn::".$own_id) + return ''; + } + + require_once 'mod/settings.php'; + settings_init($a); + + if (isset($a->argv[1])) { + switch ($a->argv[1]) { + case 'connect': + $o = appnet_connect($a); + break; + default: + $o = print_r($a->argv, true); + break; + } + } else { + $o = appnet_connect($a); + } + + return $o; +} + +function appnet_check_item_notification($a, &$notification_data) +{ + $own_id = get_pconfig($notification_data['uid'], 'appnet', 'ownid'); + + $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", + intval($notification_data['uid']), + dbesc('adn::'.$own_id) ); - if ($own_user) - $notification_data["profiles"][] = $own_user[0]["url"]; -} - -function appnet_plugin_admin(&$a, &$o){ - $t = get_markup_template( "admin.tpl", "addon/appnet/" ); - - $o = replace_macros($t, array( - '$submit' => t('Save Settings'), - // name, label, value, help, [extra values] - '$clientid' => array('clientid', t('Client ID'), get_config('appnet', 'clientid' ), ''), - '$clientsecret' => array('clientsecret', t('Client Secret'), get_config('appnet', 'clientsecret' ), ''), - )); -} - -function appnet_plugin_admin_post(&$a){ - $clientid = ((x($_POST,'clientid')) ? notags(trim($_POST['clientid'])) : ''); - $clientsecret = ((x($_POST,'clientsecret')) ? notags(trim($_POST['clientsecret'])): ''); - set_config('appnet','clientid',$clientid); - set_config('appnet','clientsecret',$clientsecret); - info( t('Settings updated.'). EOL ); -} - -function appnet_connect(&$a) { - require_once 'addon/appnet/AppDotNet.php'; - - $clientId = get_config('appnet','clientid'); - $clientSecret = get_config('appnet','clientsecret'); - - if (($clientId == "") OR ($clientSecret == "")) { - $clientId = get_pconfig(local_user(),'appnet','clientid'); - $clientSecret = get_pconfig(local_user(),'appnet','clientsecret'); - } - - $app = new AppDotNet($clientId, $clientSecret); - - try { - $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect'); - - logger("appnet_connect: authenticated"); - $o .= t("You are now authenticated to app.net. "); - set_pconfig(local_user(),'appnet','token', $token); - } - catch (AppDotNetException $e) { - $o .= t("

Error fetching token. Please try again.

"); - } - - $o .= '
'.t("return to the connector page").''; - - return($o); -} - -function appnet_jot_nets(&$a,&$b) { - if(! local_user()) - return; - - $post = get_pconfig(local_user(),'appnet','post'); - if(intval($post) == 1) { - $defpost = get_pconfig(local_user(),'appnet','post_by_default'); - $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : ''); - $b .= '
' - . t('Post to app.net') . '
'; + if ($own_user) { + $notification_data['profiles'][] = $own_user[0]['url']; } } -function appnet_settings(&$a,&$s) { - require_once 'addon/appnet/AppDotNet.php'; +function appnet_plugin_admin(&$a, &$o) +{ + $t = get_markup_template('admin.tpl', 'addon/appnet/'); - if(! local_user()) - return; - - $token = get_pconfig(local_user(),'appnet','token'); - - $app_clientId = get_config('appnet','clientid'); - $app_clientSecret = get_config('appnet','clientsecret'); - - if (($app_clientId == "") OR ($app_clientSecret == "")) { - $app_clientId = get_pconfig(local_user(),'appnet','clientid'); - $app_clientSecret = get_pconfig(local_user(),'appnet','clientsecret'); - } - - /* Add our stylesheet to the page so we can make our settings look nice */ - $a->page['htmlhead'] .= '' . "\r\n"; - - $enabled = get_pconfig(local_user(),'appnet','post'); - $checked = (($enabled) ? ' checked="checked" ' : ''); - - $css = (($enabled) ? '' : '-disabled'); - - $def_enabled = get_pconfig(local_user(),'appnet','post_by_default'); - $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); - - $importenabled = get_pconfig(local_user(),'appnet','import'); - $importchecked = (($importenabled) ? ' checked="checked" ' : ''); - - $ownid = get_pconfig(local_user(),'appnet','ownid'); - - $s .= ''; - $s .= '

'. t('App.net Import/Export').'

'; - $s .= '
'; - $s .= ''; + $o = replace_macros($t, array( + '$submit' => t('Save Settings'), + // name, label, value, help, [extra values] + '$clientid' => array('clientid', t('Client ID'), get_config('appnet', 'clientid'), ''), + '$clientsecret' => array('clientsecret', t('Client Secret'), get_config('appnet', 'clientsecret'), ''), + )); } -function appnet_settings_post(&$a,&$b) { - - if(x($_POST,'appnet-submit')) { - - if (isset($_POST['appnet-disconnect'])) { - del_pconfig(local_user(), 'appnet', 'clientsecret'); - del_pconfig(local_user(), 'appnet', 'clientid'); - del_pconfig(local_user(), 'appnet', 'token'); - del_pconfig(local_user(), 'appnet', 'post'); - del_pconfig(local_user(), 'appnet', 'post_by_default'); - del_pconfig(local_user(), 'appnet', 'import'); - } - - if (isset($_POST["clientsecret"])) - set_pconfig(local_user(),'appnet','clientsecret', $_POST['clientsecret']); - - if (isset($_POST["clientid"])) - set_pconfig(local_user(),'appnet','clientid', $_POST['clientid']); - - if (isset($_POST["token"]) AND ($_POST["token"] != "")) - set_pconfig(local_user(),'appnet','token', $_POST['token']); - - set_pconfig(local_user(), 'appnet', 'post', intval($_POST['appnet'])); - set_pconfig(local_user(), 'appnet', 'post_by_default', intval($_POST['appnet_bydefault'])); - set_pconfig(local_user(), 'appnet', 'import', intval($_POST['appnet_import'])); - } +function appnet_plugin_admin_post(&$a) +{ + $clientid = ((x($_POST, 'clientid')) ? notags(trim($_POST['clientid'])) : ''); + $clientsecret = ((x($_POST, 'clientsecret')) ? notags(trim($_POST['clientsecret'])) : ''); + set_config('appnet', 'clientid', $clientid); + set_config('appnet', 'clientsecret', $clientsecret); + info(t('Settings updated.').EOL); } -function appnet_post_local(&$a,&$b) { - if($b['edit']) - return; +function appnet_connect(&$a) +{ + require_once 'addon/appnet/AppDotNet.php'; - if((local_user()) && (local_user() == $b['uid']) && (!$b['private']) && (!$b['parent'])) { - $appnet_post = intval(get_pconfig(local_user(),'appnet','post')); - $appnet_enable = (($appnet_post && x($_REQUEST,'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0); + $clientId = get_config('appnet', 'clientid'); + $clientSecret = get_config('appnet', 'clientsecret'); - // if API is used, default to the chosen settings - if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'appnet','post_by_default'))) - $appnet_enable = 1; + if (($clientId == '') or ($clientSecret == '')) { + $clientId = get_pconfig(local_user(), 'appnet', 'clientid'); + $clientSecret = get_pconfig(local_user(), 'appnet', 'clientsecret'); + } - if(! $appnet_enable) - return; + $app = new AppDotNet($clientId, $clientSecret); - if(strlen($b['postopts'])) - $b['postopts'] .= ','; + try { + $token = $app->getAccessToken($a->get_baseurl().'/appnet/connect'); - $b['postopts'] .= 'appnet'; - } + logger('appnet_connect: authenticated'); + $o .= t('You are now authenticated to app.net. '); + set_pconfig(local_user(), 'appnet', 'token', $token); + } catch (AppDotNetException $e) { + $o .= t('

Error fetching token. Please try again.

'); + } + + $o .= '
'.t('return to the connector page').''; + + return $o; } -function appnet_create_entities($a, $b, $postdata) { - require_once("include/bbcode.php"); - require_once("include/plaintext.php"); +function appnet_jot_nets(&$a, &$b) +{ + if (!local_user()) { + return; + } - $bbcode = $b["body"]; - $bbcode = bb_remove_share_information($bbcode, false, true); - - // Change pure links in text to bbcode uris - $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode); - - $URLSearchString = "^\[\]"; - - $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode); - $bbcode = preg_replace("/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'@$2',$bbcode); - $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode); - $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode); - $bbcode = preg_replace("/\[youtube\]https?:\/\/(.*?)\[\/youtube\]/ism",'[url=https://$1]https://$1[/url]',$bbcode); - $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", - '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode); - $bbcode = preg_replace("/\[vimeo\]https?:\/\/(.*?)\[\/vimeo\]/ism",'[url=https://$1]https://$1[/url]',$bbcode); - $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", - '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode); - //$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode); - - $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode); - - - preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls, PREG_SET_ORDER); - - $bbcode = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1',$bbcode); - - $b["body"] = $bbcode; - - // To-Do: - // Bilder - // https://alpha.app.net/heluecht/post/32424376 - // https://alpha.app.net/heluecht/post/32424307 - - $plaintext = plaintext($a, $b, 0, false, 6); - - $text = $plaintext["text"]; - - $start = 0; - $entities = array(); - - foreach ($urls AS $url) { - $lenurl = iconv_strlen($url[1], "UTF-8"); - $len = iconv_strlen($url[2], "UTF-8"); - $pos = iconv_strpos($text, $url[1], $start, "UTF-8"); - $pre = iconv_substr($text, 0, $pos, "UTF-8"); - $post = iconv_substr($text, $pos + $lenurl, 1000000, "UTF-8"); - - $mid = $url[2]; - $html = bbcode($mid, false, false, 6); - $mid = html2plain($html, 0, true); - - $mid = trim(html_entity_decode($mid,ENT_QUOTES,'UTF-8')); - - $text = $pre.$mid.$post; - - if ($mid != "") - $entities[] = array("pos" => $pos, "len" => $len, "url" => $url[1], "text" => $mid); - - $start = $pos + 1; - } - - if (isset($postdata["url"]) AND isset($postdata["title"]) AND ($postdata["type"] != "photo")) { - $postdata["title"] = shortenmsg($postdata["title"], 90); - $max = 256 - strlen($postdata["title"]); - $text = shortenmsg($text, $max); - $text .= "\n[".$postdata["title"]."](".$postdata["url"].")"; - } elseif (isset($postdata["url"]) AND ($postdata["type"] != "photo")) { - $postdata["url"] = short_link($postdata["url"]); - $max = 240; - $text = shortenmsg($text, $max); - $text .= " [".$postdata["url"]."](".$postdata["url"].")"; - } else { - $max = 256; - $text = shortenmsg($text, $max); - } - - if (iconv_strlen($text, "UTF-8") < $max) - $max = iconv_strlen($text, "UTF-8"); - - krsort($entities); - foreach ($entities AS $entity) { - //if (iconv_strlen($text, "UTF-8") >= $entity["pos"] + $entity["len"]) { - if (($entity["pos"] + $entity["len"]) <= $max) { - $pre = iconv_substr($text, 0, $entity["pos"], "UTF-8"); - $post = iconv_substr($text, $entity["pos"] + $entity["len"], 1000000, "UTF-8"); - - $text = $pre."[".$entity["text"]."](".$entity["url"].")".$post; - } - } - - - return($text); + $post = get_pconfig(local_user(), 'appnet', 'post'); + if (intval($post) == 1) { + $defpost = get_pconfig(local_user(), 'appnet', 'post_by_default'); + $selected = ((intval($defpost) == 1) ? ' checked="checked" ' : ''); + $b .= '
' + .t('Post to app.net').'
'; + } } -function appnet_send(&$a,&$b) { +function appnet_settings(&$a, &$s) +{ + require_once 'addon/appnet/AppDotNet.php'; - logger('appnet_send: invoked for post '.$b['id']." ".$b['app']); + if (!local_user()) { + return; + } - if (!get_pconfig($b["uid"],'appnet','import')) { - if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) - return; - } + $token = get_pconfig(local_user(), 'appnet', 'token'); - if($b['parent'] != $b['id']) { - logger("appnet_send: parameter ".print_r($b, true), LOGGER_DATA); + $app_clientId = get_config('appnet', 'clientid'); + $app_clientSecret = get_config('appnet', 'clientsecret'); - // Looking if its a reply to an app.net post - if ((substr($b["parent-uri"], 0, 5) != "adn::") AND (substr($b["extid"], 0, 5) != "adn::") AND (substr($b["thr-parent"], 0, 5) != "adn::")) { - logger("appnet_send: no app.net post ".$b["parent"]); - return; - } + if (($app_clientId == '') or ($app_clientSecret == '')) { + $app_clientId = get_pconfig(local_user(), 'appnet', 'clientid'); + $app_clientSecret = get_pconfig(local_user(), 'appnet', 'clientsecret'); + } - $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1", - dbesc($b["thr-parent"]), - intval($b["uid"])); + /* Add our stylesheet to the page so we can make our settings look nice */ + $a->page['htmlhead'] .= ''."\r\n"; - if(!count($r)) { - logger("appnet_send: no parent found ".$b["thr-parent"]); - return; - } else { - $iscomment = true; - $orig_post = $r[0]; - } + $enabled = get_pconfig(local_user(), 'appnet', 'post'); + $checked = (($enabled) ? ' checked="checked" ' : ''); - $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]); - $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]"; - $nicknameplain = "@".$nicknameplain; + $css = (($enabled) ? '' : '-disabled'); - logger("appnet_send: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG); - if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false)) - $b["body"] = $nickname." ".$b["body"]; + $def_enabled = get_pconfig(local_user(), 'appnet', 'post_by_default'); + $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); - logger("appnet_send: parent found ".print_r($orig_post, true), LOGGER_DATA); - } else { - $iscomment = false; + $importenabled = get_pconfig(local_user(), 'appnet', 'import'); + $importchecked = (($importenabled) ? ' checked="checked" ' : ''); - if($b['private'] OR !strstr($b['postopts'],'appnet')) - return; - } + $ownid = get_pconfig(local_user(), 'appnet', 'ownid'); - if (($b['verb'] == ACTIVITY_POST) AND $b['deleted']) - appnet_action($a, $b["uid"], substr($orig_post["uri"], 5), "delete"); + $s .= ''; + $s .= '

'.t('App.net Import/Export').'

'; + $s .= '
'; + $s .= ''; } -function appnet_action($a, $uid, $pid, $action) { - require_once 'addon/appnet/AppDotNet.php'; +function appnet_settings_post(&$a, &$b) +{ + if (x($_POST, 'appnet-submit')) { + if (isset($_POST['appnet-disconnect'])) { + del_pconfig(local_user(), 'appnet', 'clientsecret'); + del_pconfig(local_user(), 'appnet', 'clientid'); + del_pconfig(local_user(), 'appnet', 'token'); + del_pconfig(local_user(), 'appnet', 'post'); + del_pconfig(local_user(), 'appnet', 'post_by_default'); + del_pconfig(local_user(), 'appnet', 'import'); + } - $token = get_pconfig($uid,'appnet','token'); - $clientId = get_pconfig($uid,'appnet','clientid'); - $clientSecret = get_pconfig($uid,'appnet','clientsecret'); + if (isset($_POST['clientsecret'])) { + set_pconfig(local_user(), 'appnet', 'clientsecret', $_POST['clientsecret']); + } - $app = new AppDotNet($clientId, $clientSecret); - $app->setAccessToken($token); + if (isset($_POST['clientid'])) { + set_pconfig(local_user(), 'appnet', 'clientid', $_POST['clientid']); + } - logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA); + if (isset($_POST['token']) and ($_POST['token'] != '')) { + set_pconfig(local_user(), 'appnet', 'token', $_POST['token']); + } - try { - switch ($action) { - case "delete": - $result = $app->deletePost($pid); - break; - case "like": - $result = $app->starPost($pid); - break; - case "unlike": - $result = $app->unstarPost($pid); - break; - } - logger("appnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG); - } - catch (AppDotNetException $e) { - logger("appnet_action: Error sending action ".$action." pid ".$pid." ".appnet_error($e->getMessage()), LOGGER_DEBUG); - } + set_pconfig(local_user(), 'appnet', 'post', intval($_POST['appnet'])); + set_pconfig(local_user(), 'appnet', 'post_by_default', intval($_POST['appnet_bydefault'])); + set_pconfig(local_user(), 'appnet', 'import', intval($_POST['appnet_import'])); + } } -function appnet_is_repost($a, $uid, $body) { - $body = trim($body); +function appnet_post_local(&$a, &$b) +{ + if ($b['edit']) { + return; + } - // Skip if it isn't a pure repeated messages - // Does it start with a share? - if (strpos($body, "[share") > 0) - return(false); + if ((local_user()) && (local_user() == $b['uid']) && (!$b['private']) && (!$b['parent'])) { + $appnet_post = intval(get_pconfig(local_user(), 'appnet', 'post')); + $appnet_enable = (($appnet_post && x($_REQUEST, 'appnet_enable')) ? intval($_REQUEST['appnet_enable']) : 0); - // Does it end with a share? - if (strlen($body) > (strrpos($body, "[/share]") + 8)) - return(false); + // if API is used, default to the chosen settings + if ($_REQUEST['api_source'] && intval(get_pconfig(local_user(), 'appnet', 'post_by_default'))) { + $appnet_enable = 1; + } - $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body); - // Skip if there is no shared message in there - if ($body == $attributes) - return(false); + if (!$appnet_enable) { + return; + } - $link = ""; - preg_match("/link='(.*?)'/ism", $attributes, $matches); - if ($matches[1] != "") - $link = $matches[1]; + if (strlen($b['postopts'])) { + $b['postopts'] .= ','; + } - preg_match('/link="(.*?)"/ism', $attributes, $matches); - if ($matches[1] != "") - $link = $matches[1]; - - $id = preg_replace("=https?://alpha.app.net/(.*)/post/(.*)=ism", "$2", $link); - if ($id == $link) - return(false); - - logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG); - - require_once 'addon/appnet/AppDotNet.php'; - - $token = get_pconfig($uid,'appnet','token'); - $clientId = get_pconfig($uid,'appnet','clientid'); - $clientSecret = get_pconfig($uid,'appnet','clientsecret'); - - $app = new AppDotNet($clientId, $clientSecret); - $app->setAccessToken($token); - - try { - $result = $app->repost($id); - logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG); - return true; - } - catch (AppDotNetException $e) { - logger('appnet_is_repost: error doing repost '.appnet_error($e->getMessage()), LOGGER_DEBUG); - return false; - } + $b['postopts'] .= 'appnet'; + } } -function appnet_fetchstream($a, $uid) { - require_once("addon/appnet/AppDotNet.php"); - require_once('include/items.php'); +function appnet_create_entities($a, $b, $postdata) +{ + require_once 'include/bbcode.php'; + require_once 'include/plaintext.php'; - $token = get_pconfig($uid,'appnet','token'); - $clientId = get_pconfig($uid,'appnet','clientid'); - $clientSecret = get_pconfig($uid,'appnet','clientsecret'); + $bbcode = $b['body']; + $bbcode = bb_remove_share_information($bbcode, false, true); - $app = new AppDotNet($clientId, $clientSecret); - $app->setAccessToken($token); + // Change pure links in text to bbcode uris + $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode); - $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1", - intval($uid)); + $URLSearchString = "^\[\]"; - if(count($r)) - $me = $r[0]; - else { - logger("appnet_fetchstream: Own contact not found for user ".$uid, LOGGER_DEBUG); - return; - } + $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '#$2', $bbcode); + $bbcode = preg_replace("/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '@$2', $bbcode); + $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism", '[url=$1]$2[/url]', $bbcode); + $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism", '[url=$1]$1[/url]', $bbcode); + $bbcode = preg_replace("/\[youtube\]https?:\/\/(.*?)\[\/youtube\]/ism", '[url=https://$1]https://$1[/url]', $bbcode); + $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism", + '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode); + $bbcode = preg_replace("/\[vimeo\]https?:\/\/(.*?)\[\/vimeo\]/ism", '[url=https://$1]https://$1[/url]', $bbcode); + $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism", + '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode); + //$bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode); - $user = q("SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1", - intval($uid) - ); + $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode); - if(count($user)) - $user = $user[0]; - else { - logger("appnet_fetchstream: Own user not found for user ".$uid, LOGGER_DEBUG); - return; - } + preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls, PREG_SET_ORDER); - $ownid = get_pconfig($uid,'appnet','ownid'); + $bbcode = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", '$1', $bbcode); - // Fetch stream - $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true, - "include_html" => false, "include_post_annotations" => true); + $b['body'] = $bbcode; - $lastid = get_pconfig($uid, 'appnet', 'laststreamid'); + // To-Do: + // Bilder + // https://alpha.app.net/heluecht/post/32424376 + // https://alpha.app.net/heluecht/post/32424307 - if ($lastid <> "") - $param["since_id"] = $lastid; + $plaintext = plaintext($a, $b, 0, false, 6); - try { - $stream = $app->getUserStream($param); - } - catch (AppDotNetException $e) { - logger("appnet_fetchstream: Error fetching stream for user ".$uid." ".appnet_error($e->getMessage())); - return; - } + $text = $plaintext['text']; - if (!is_array($stream)) - $stream = array(); + $start = 0; + $entities = array(); - $stream = array_reverse($stream); - foreach ($stream AS $post) { - $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true); + foreach ($urls as $url) { + $lenurl = iconv_strlen($url[1], 'UTF-8'); + $len = iconv_strlen($url[2], 'UTF-8'); + $pos = iconv_strpos($text, $url[1], $start, 'UTF-8'); + $pre = iconv_substr($text, 0, $pos, 'UTF-8'); + $post = iconv_substr($text, $pos + $lenurl, 1000000, 'UTF-8'); - $item = item_store($postarray); - $postarray["id"] = $item; + $mid = $url[2]; + $html = bbcode($mid, false, false, 6); + $mid = html2plain($html, 0, true); - logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item); + $mid = trim(html_entity_decode($mid, ENT_QUOTES, 'UTF-8')); - $lastid = $post["id"]; + $text = $pre.$mid.$post; - if (($item != 0) AND ($postarray['contact-id'] != $me["id"]) AND !function_exists("check_item_notification")) { - $r = q("SELECT `thread`.`iid` AS `parent` FROM `thread` + if ($mid != '') { + $entities[] = array('pos' => $pos, 'len' => $len, 'url' => $url[1], 'text' => $mid); + } + + $start = $pos + 1; + } + + if (isset($postdata['url']) and isset($postdata['title']) and ($postdata['type'] != 'photo')) { + $postdata['title'] = shortenmsg($postdata['title'], 90); + $max = 256 - strlen($postdata['title']); + $text = shortenmsg($text, $max); + $text .= "\n[".$postdata['title'].']('.$postdata['url'].')'; + } elseif (isset($postdata['url']) and ($postdata['type'] != 'photo')) { + $postdata['url'] = short_link($postdata['url']); + $max = 240; + $text = shortenmsg($text, $max); + $text .= ' ['.$postdata['url'].']('.$postdata['url'].')'; + } else { + $max = 256; + $text = shortenmsg($text, $max); + } + + if (iconv_strlen($text, 'UTF-8') < $max) { + $max = iconv_strlen($text, 'UTF-8'); + } + + krsort($entities); + foreach ($entities as $entity) { + //if (iconv_strlen($text, "UTF-8") >= $entity["pos"] + $entity["len"]) { + if (($entity['pos'] + $entity['len']) <= $max) { + $pre = iconv_substr($text, 0, $entity['pos'], 'UTF-8'); + $post = iconv_substr($text, $entity['pos'] + $entity['len'], 1000000, 'UTF-8'); + + $text = $pre.'['.$entity['text'].']('.$entity['url'].')'.$post; + } + } + + return $text; +} + +function appnet_send(&$a, &$b) +{ + logger('appnet_send: invoked for post '.$b['id'].' '.$b['app']); + + if (!get_pconfig($b['uid'], 'appnet', 'import')) { + if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) { + return; + } + } + + if ($b['parent'] != $b['id']) { + logger('appnet_send: parameter '.print_r($b, true), LOGGER_DATA); + + // Looking if its a reply to an app.net post + if ((substr($b['parent-uri'], 0, 5) != 'adn::') and (substr($b['extid'], 0, 5) != 'adn::') and (substr($b['thr-parent'], 0, 5) != 'adn::')) { + logger('appnet_send: no app.net post '.$b['parent']); + + return; + } + + $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1", + dbesc($b['thr-parent']), + intval($b['uid'])); + + if (!count($r)) { + logger('appnet_send: no parent found '.$b['thr-parent']); + + return; + } else { + $iscomment = true; + $orig_post = $r[0]; + } + + $nicknameplain = preg_replace('=https?://alpha.app.net/(.*)=ism', '$1', $orig_post['author-link']); + $nickname = '@[url='.$orig_post['author-link'].']'.$nicknameplain.'[/url]'; + $nicknameplain = '@'.$nicknameplain; + + logger('appnet_send: comparing '.$nickname.' and '.$nicknameplain.' with '.$b['body'], LOGGER_DEBUG); + if ((strpos($b['body'], $nickname) === false) and (strpos($b['body'], $nicknameplain) === false)) { + $b['body'] = $nickname.' '.$b['body']; + } + + logger('appnet_send: parent found '.print_r($orig_post, true), LOGGER_DATA); + } else { + $iscomment = false; + + if ($b['private'] or !strstr($b['postopts'], 'appnet')) { + return; + } + } + + if (($b['verb'] == ACTIVITY_POST) and $b['deleted']) { + appnet_action($a, $b['uid'], substr($orig_post['uri'], 5), 'delete'); + } + + if ($b['verb'] == ACTIVITY_LIKE) { + logger('appnet_send: '.print_r($b, true), LOGGER_DEBUG); + logger('appnet_send: parameter 2 '.substr($b['thr-parent'], 5), LOGGER_DEBUG); + if ($b['deleted']) { + appnet_action($a, $b['uid'], substr($b['thr-parent'], 5), 'unlike'); + } else { + appnet_action($a, $b['uid'], substr($b['thr-parent'], 5), 'like'); + } + + return; + } + + if ($b['deleted'] || ($b['created'] !== $b['edited'])) { + return; + } + + $token = get_pconfig($b['uid'], 'appnet', 'token'); + + if ($token) { + + // If it's a repeated message from app.net then do a native repost and exit + if (appnet_is_repost($a, $b['uid'], $b['body'])) { + return; + } + + require_once 'addon/appnet/AppDotNet.php'; + + $clientId = get_pconfig($b['uid'], 'appnet', 'clientid'); + $clientSecret = get_pconfig($b['uid'], 'appnet', 'clientsecret'); + + $app = new AppDotNet($clientId, $clientSecret); + $app->setAccessToken($token); + + $data = array(); + + require_once 'include/plaintext.php'; + require_once 'include/network.php'; + + $post = plaintext($a, $b, 256, false, 6); + logger('appnet_send: converted message '.$b['id'].' result: '.print_r($post, true), LOGGER_DEBUG); + + if (isset($post['image'])) { + $img_str = fetch_url($post['image'], true, $redirects, 10); + $tempfile = tempnam(get_temppath(), 'cache'); + file_put_contents($tempfile, $img_str); + + try { + $photoFile = $app->createFile($tempfile, array(type => 'com.github.jdolitsky.appdotnetphp.photo')); + + $data['annotations'][] = array( + 'type' => 'net.app.core.oembed', + 'value' => array( + '+net.app.core.file' => array( + 'file_id' => $photoFile['id'], + 'file_token' => $photoFile['file_token'], + 'format' => 'oembed', ), + ), + ); + } catch (AppDotNetException $e) { + logger('appnet_send: Error creating file '.appnet_error($e->getMessage())); + } + + unlink($tempfile); + } + + // Adding a link to the original post, if it is a root post + if ($b['parent'] == $b['id']) { + $data['annotations'][] = array( + 'type' => 'net.app.core.crosspost', + 'value' => array('canonical_url' => $b['plink']), + ); + } + + // Adding the original post + $attached_data = get_attached_data($b['body']); + $attached_data['post-uri'] = $b['uri']; + $attached_data['post-title'] = $b['title']; + $attached_data['post-body'] = substr($b['body'], 0, 4000); // To-Do: Better shortening + $attached_data['post-tag'] = $b['tag']; + $attached_data['author-name'] = $b['author-name']; + $attached_data['author-link'] = $b['author-link']; + $attached_data['author-avatar'] = $b['author-avatar']; + + $data['annotations'][] = array( + 'type' => 'com.friendica.post', + 'value' => $attached_data, + ); + + if (isset($post['url']) and !isset($post['title']) and ($post['type'] != 'photo')) { + $display_url = str_replace(array('http://www.', 'https://www.'), array('', ''), $post['url']); + $display_url = str_replace(array('http://', 'https://'), array('', ''), $display_url); + + if (strlen($display_url) > 26) { + $display_url = substr($display_url, 0, 25).'…'; + } + + $post['title'] = $display_url; + } + + $text = appnet_create_entities($a, $b, $post); + + $data['entities']['parse_markdown_links'] = true; + + if ($iscomment) { + $data['reply_to'] = substr($orig_post['uri'], 5); + } + + try { + logger('appnet_send: sending message '.$b['id'].' '.$text.' '.print_r($data, true), LOGGER_DEBUG); + $ret = $app->createPost($text, $data); + logger('appnet_send: send message '.$b['id'].' result: '.print_r($ret, true), LOGGER_DEBUG); + if ($iscomment) { + logger('appnet_send: Update extid '.$ret['id'].' for post id '.$b['id']); + q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d", + dbesc('adn::'.$ret['id']), + intval($b['id']) + ); + } + } catch (AppDotNetException $e) { + logger('appnet_send: Error sending message '.$b['id'].' '.appnet_error($e->getMessage())); + } + } +} + +function appnet_action($a, $uid, $pid, $action) +{ + require_once 'addon/appnet/AppDotNet.php'; + + $token = get_pconfig($uid, 'appnet', 'token'); + $clientId = get_pconfig($uid, 'appnet', 'clientid'); + $clientSecret = get_pconfig($uid, 'appnet', 'clientsecret'); + + $app = new AppDotNet($clientId, $clientSecret); + $app->setAccessToken($token); + + logger("appnet_action '".$action."' ID: ".$pid, LOGGER_DATA); + + try { + switch ($action) { + case 'delete': + $result = $app->deletePost($pid); + break; + case 'like': + $result = $app->starPost($pid); + break; + case 'unlike': + $result = $app->unstarPost($pid); + break; + } + logger("appnet_action '".$action."' send, result: ".print_r($result, true), LOGGER_DEBUG); + } catch (AppDotNetException $e) { + logger('appnet_action: Error sending action '.$action.' pid '.$pid.' '.appnet_error($e->getMessage()), LOGGER_DEBUG); + } +} + +function appnet_is_repost($a, $uid, $body) +{ + $body = trim($body); + + // Skip if it isn't a pure repeated messages + // Does it start with a share? + if (strpos($body, '[share') > 0) { + return false; + } + + // Does it end with a share? + if (strlen($body) > (strrpos($body, '[/share]') + 8)) { + return false; + } + + $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", '$1', $body); + // Skip if there is no shared message in there + if ($body == $attributes) { + return false; + } + + $link = ''; + preg_match("/link='(.*?)'/ism", $attributes, $matches); + if ($matches[1] != '') { + $link = $matches[1]; + } + + preg_match('/link="(.*?)"/ism', $attributes, $matches); + if ($matches[1] != '') { + $link = $matches[1]; + } + + $id = preg_replace('=https?://alpha.app.net/(.*)/post/(.*)=ism', '$2', $link); + if ($id == $link) { + return false; + } + + logger('appnet_is_repost: Reposting id '.$id.' for user '.$uid, LOGGER_DEBUG); + + require_once 'addon/appnet/AppDotNet.php'; + + $token = get_pconfig($uid, 'appnet', 'token'); + $clientId = get_pconfig($uid, 'appnet', 'clientid'); + $clientSecret = get_pconfig($uid, 'appnet', 'clientsecret'); + + $app = new AppDotNet($clientId, $clientSecret); + $app->setAccessToken($token); + + try { + $result = $app->repost($id); + logger('appnet_is_repost: result '.print_r($result, true), LOGGER_DEBUG); + + return true; + } catch (AppDotNetException $e) { + logger('appnet_is_repost: error doing repost '.appnet_error($e->getMessage()), LOGGER_DEBUG); + + return false; + } +} + +function appnet_fetchstream($a, $uid) +{ + require_once 'addon/appnet/AppDotNet.php'; + require_once 'include/items.php'; + + $token = get_pconfig($uid, 'appnet', 'token'); + $clientId = get_pconfig($uid, 'appnet', 'clientid'); + $clientSecret = get_pconfig($uid, 'appnet', 'clientsecret'); + + $app = new AppDotNet($clientId, $clientSecret); + $app->setAccessToken($token); + + $r = q('SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1', + intval($uid)); + + if (count($r)) { + $me = $r[0]; + } else { + logger('appnet_fetchstream: Own contact not found for user '.$uid, LOGGER_DEBUG); + + return; + } + + $user = q('SELECT * FROM `user` WHERE `uid` = %d AND `account_expired` = 0 LIMIT 1', + intval($uid) + ); + + if (count($user)) { + $user = $user[0]; + } else { + logger('appnet_fetchstream: Own user not found for user '.$uid, LOGGER_DEBUG); + + return; + } + + $ownid = get_pconfig($uid, 'appnet', 'ownid'); + + // Fetch stream + $param = array('count' => 200, 'include_deleted' => false, 'include_directed_posts' => true, + 'include_html' => false, 'include_post_annotations' => true, ); + + $lastid = get_pconfig($uid, 'appnet', 'laststreamid'); + + if ($lastid != '') { + $param['since_id'] = $lastid; + } + + try { + $stream = $app->getUserStream($param); + } catch (AppDotNetException $e) { + logger('appnet_fetchstream: Error fetching stream for user '.$uid.' '.appnet_error($e->getMessage())); + + return; + } + + if (!is_array($stream)) { + $stream = array(); + } + + $stream = array_reverse($stream); + foreach ($stream as $post) { + $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, true); + + $item = item_store($postarray); + $postarray['id'] = $item; + + logger('appnet_fetchstream: User '.$uid.' posted stream item '.$item); + + $lastid = $post['id']; + + if (($item != 0) and ($postarray['contact-id'] != $me['id']) and !function_exists('check_item_notification')) { + $r = q('SELECT `thread`.`iid` AS `parent` FROM `thread` INNER JOIN `item` ON `thread`.`iid` = `item`.`parent` AND `thread`.`uid` = `item`.`uid` - WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1", dbesc($item)); + WHERE `item`.`id` = %d AND `thread`.`mention` LIMIT 1', dbesc($item)); - if (count($r)) { - require_once('include/enotify.php'); - notification(array( - 'type' => NOTIFY_COMMENT, - 'notify_flags' => $user['notify-flags'], - 'language' => $user['language'], - 'to_name' => $user['username'], - 'to_email' => $user['email'], - 'uid' => $user['uid'], - 'item' => $postarray, - 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)), - 'source_name' => $postarray['author-name'], - 'source_link' => $postarray['author-link'], - 'source_photo' => $postarray['author-avatar'], - 'verb' => ACTIVITY_POST, - 'otype' => 'item', - 'parent' => $r[0]["parent"], - )); - } - } - } + if (count($r)) { + require_once 'include/enotify.php'; + notification(array( + 'type' => NOTIFY_COMMENT, + 'notify_flags' => $user['notify-flags'], + 'language' => $user['language'], + 'to_name' => $user['username'], + 'to_email' => $user['email'], + 'uid' => $user['uid'], + 'item' => $postarray, + 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)), + 'source_name' => $postarray['author-name'], + 'source_link' => $postarray['author-link'], + 'source_photo' => $postarray['author-avatar'], + 'verb' => ACTIVITY_POST, + 'otype' => 'item', + 'parent' => $r[0]['parent'], + )); + } + } + } - set_pconfig($uid, 'appnet', 'laststreamid', $lastid); + set_pconfig($uid, 'appnet', 'laststreamid', $lastid); - // Fetch mentions - $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true, - "include_html" => false, "include_post_annotations" => true); + // Fetch mentions + $param = array('count' => 200, 'include_deleted' => false, 'include_directed_posts' => true, + 'include_html' => false, 'include_post_annotations' => true, ); - $lastid = get_pconfig($uid, 'appnet', 'lastmentionid'); + $lastid = get_pconfig($uid, 'appnet', 'lastmentionid'); - if ($lastid <> "") - $param["since_id"] = $lastid; + if ($lastid != '') { + $param['since_id'] = $lastid; + } - try { - $mentions = $app->getUserMentions("me", $param); - } - catch (AppDotNetException $e) { - logger("appnet_fetchstream: Error fetching mentions for user ".$uid." ".appnet_error($e->getMessage())); - return; - } + try { + $mentions = $app->getUserMentions('me', $param); + } catch (AppDotNetException $e) { + logger('appnet_fetchstream: Error fetching mentions for user '.$uid.' '.appnet_error($e->getMessage())); - if (!is_array($mentions)) - $mentions = array(); + return; + } - $mentions = array_reverse($mentions); - foreach ($mentions AS $post) { - $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false); + if (!is_array($mentions)) { + $mentions = array(); + } - if (isset($postarray["id"])) { - $item = $postarray["id"]; - $parent_id = $postarray['parent']; - } elseif (isset($postarray["body"])) { - $item = item_store($postarray); - $postarray["id"] = $item; + $mentions = array_reverse($mentions); + foreach ($mentions as $post) { + $postarray = appnet_createpost($a, $uid, $post, $me, $user, $ownid, false); - $parent_id = 0; - logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item); + if (isset($postarray['id'])) { + $item = $postarray['id']; + $parent_id = $postarray['parent']; + } elseif (isset($postarray['body'])) { + $item = item_store($postarray); + $postarray['id'] = $item; - if ($item AND function_exists("check_item_notification")) - check_item_notification($item, $uid, NOTIFY_TAGSELF); + $parent_id = 0; + logger('appnet_fetchstream: User '.$uid.' posted mention item '.$item); - } else { - $item = 0; - $parent_id = 0; - } + if ($item and function_exists('check_item_notification')) { + check_item_notification($item, $uid, NOTIFY_TAGSELF); + } + } else { + $item = 0; + $parent_id = 0; + } - // Fetch the parent and id - if (($parent_id == 0) AND ($postarray['uri'] != "")) { - $r = q("SELECT `id`, `parent` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", - dbesc($postarray['uri']), - intval($uid) - ); + // Fetch the parent and id + if (($parent_id == 0) and ($postarray['uri'] != '')) { + $r = q("SELECT `id`, `parent` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", + dbesc($postarray['uri']), + intval($uid) + ); - if (count($r)) { - $item = $r[0]['id']; - $parent_id = $r[0]['parent']; - } - } + if (count($r)) { + $item = $r[0]['id']; + $parent_id = $r[0]['parent']; + } + } - $lastid = $post["id"]; + $lastid = $post['id']; - //if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) { - if (($item != 0) AND !function_exists("check_item_notification")) { - require_once('include/enotify.php'); - notification(array( - 'type' => NOTIFY_TAGSELF, - 'notify_flags' => $user['notify-flags'], - 'language' => $user['language'], - 'to_name' => $user['username'], - 'to_email' => $user['email'], - 'uid' => $user['uid'], - 'item' => $postarray, - 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)), - 'source_name' => $postarray['author-name'], - 'source_link' => $postarray['author-link'], - 'source_photo' => $postarray['author-avatar'], - 'verb' => ACTIVITY_TAG, - 'otype' => 'item', - 'parent' => $parent_id, - )); - } - } - - set_pconfig($uid, 'appnet', 'lastmentionid', $lastid); + //if (($item != 0) AND ($postarray['contact-id'] != $me["id"])) { + if (($item != 0) and !function_exists('check_item_notification')) { + require_once 'include/enotify.php'; + notification(array( + 'type' => NOTIFY_TAGSELF, + 'notify_flags' => $user['notify-flags'], + 'language' => $user['language'], + 'to_name' => $user['username'], + 'to_email' => $user['email'], + 'uid' => $user['uid'], + 'item' => $postarray, + 'link' => $a->get_baseurl().'/display/'.urlencode(get_item_guid($item)), + 'source_name' => $postarray['author-name'], + 'source_link' => $postarray['author-link'], + 'source_photo' => $postarray['author-avatar'], + 'verb' => ACTIVITY_TAG, + 'otype' => 'item', + 'parent' => $parent_id, + )); + } + } + set_pconfig($uid, 'appnet', 'lastmentionid', $lastid); /* To-Do - $param = array("interaction_actions" => "star"); - $interactions = $app->getMyInteractions($param); - foreach ($interactions AS $interaction) - appnet_dolike($a, $uid, $interaction); + $param = array("interaction_actions" => "star"); + $interactions = $app->getMyInteractions($param); + foreach ($interactions AS $interaction) + appnet_dolike($a, $uid, $interaction); */ } -function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true, $nodupcheck = false) { - require_once('include/items.php'); +function appnet_createpost($a, $uid, $post, $me, $user, $ownid, $createuser, $threadcompletion = true, $nodupcheck = false) +{ + require_once 'include/items.php'; - if ($post["machine_only"]) - return; + if ($post['machine_only']) { + return; + } - if ($post["is_deleted"]) - return; + if ($post['is_deleted']) { + return; + } - $postarray = array(); - $postarray['gravity'] = 0; - $postarray['uid'] = $uid; - $postarray['wall'] = 0; - $postarray['verb'] = ACTIVITY_POST; - $postarray['network'] = dbesc(NETWORK_APPNET); - if (is_array($post["repost_of"])) { - // You can't reply to reposts. So use the original id and thread-id - $postarray['uri'] = "adn::".$post["repost_of"]["id"]; - $postarray['parent-uri'] = "adn::".$post["repost_of"]["thread_id"]; - } else { - $postarray['uri'] = "adn::".$post["id"]; - $postarray['parent-uri'] = "adn::".$post["thread_id"]; - } + $postarray = array(); + $postarray['gravity'] = 0; + $postarray['uid'] = $uid; + $postarray['wall'] = 0; + $postarray['verb'] = ACTIVITY_POST; + $postarray['network'] = dbesc(NETWORK_APPNET); + if (is_array($post['repost_of'])) { + // You can't reply to reposts. So use the original id and thread-id + $postarray['uri'] = 'adn::'.$post['repost_of']['id']; + $postarray['parent-uri'] = 'adn::'.$post['repost_of']['thread_id']; + } else { + $postarray['uri'] = 'adn::'.$post['id']; + $postarray['parent-uri'] = 'adn::'.$post['thread_id']; + } - if (!$nodupcheck) { - $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", - dbesc($postarray['uri']), - intval($uid) - ); + if (!$nodupcheck) { + $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", + dbesc($postarray['uri']), + intval($uid) + ); - if (count($r)) - return($r[0]); + if (count($r)) { + return $r[0]; + } - $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1", - dbesc($postarray['uri']), - intval($uid) - ); + $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1", + dbesc($postarray['uri']), + intval($uid) + ); - if (count($r)) - return($r[0]); - } + if (count($r)) { + return $r[0]; + } + } - if (isset($post["reply_to"]) AND ($post["reply_to"] != "")) { - $postarray['thr-parent'] = "adn::".$post["reply_to"]; + if (isset($post['reply_to']) and ($post['reply_to'] != '')) { + $postarray['thr-parent'] = 'adn::'.$post['reply_to']; - // Complete the thread (if the parent doesn't exists) - if ($threadcompletion) { - //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", - // dbesc($postarray['thr-parent']), - // intval($uid) - // ); - //if (!count($r)) { - logger("appnet_createpost: completing thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG); + // Complete the thread (if the parent doesn't exists) + if ($threadcompletion) { + //$r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", + // dbesc($postarray['thr-parent']), + // intval($uid) + // ); + //if (!count($r)) { + logger('appnet_createpost: completing thread '.$post['thread_id'].' for user '.$uid, LOGGER_DEBUG); - require_once("addon/appnet/AppDotNet.php"); + require_once 'addon/appnet/AppDotNet.php'; - $token = get_pconfig($uid,'appnet','token'); - $clientId = get_pconfig($uid,'appnet','clientid'); - $clientSecret = get_pconfig($uid,'appnet','clientsecret'); + $token = get_pconfig($uid, 'appnet', 'token'); + $clientId = get_pconfig($uid, 'appnet', 'clientid'); + $clientSecret = get_pconfig($uid, 'appnet', 'clientsecret'); - $app = new AppDotNet($clientId, $clientSecret); - $app->setAccessToken($token); + $app = new AppDotNet($clientId, $clientSecret); + $app->setAccessToken($token); - $param = array("count" => 200, "include_deleted" => false, "include_directed_posts" => true, - "include_html" => false, "include_post_annotations" => true); - try { - $thread = $app->getPostReplies($post["thread_id"], $param); - } - catch (AppDotNetException $e) { - logger("appnet_createpost: Error fetching thread for user ".$uid." ".appnet_error($e->getMessage())); - } - $thread = array_reverse($thread); + $param = array('count' => 200, 'include_deleted' => false, 'include_directed_posts' => true, + 'include_html' => false, 'include_post_annotations' => true, ); + try { + $thread = $app->getPostReplies($post['thread_id'], $param); + } catch (AppDotNetException $e) { + logger('appnet_createpost: Error fetching thread for user '.$uid.' '.appnet_error($e->getMessage())); + } + $thread = array_reverse($thread); - logger("appnet_createpost: fetched ".count($thread)." items for thread ".$post["thread_id"]." for user ".$uid, LOGGER_DEBUG); + logger('appnet_createpost: fetched '.count($thread).' items for thread '.$post['thread_id'].' for user '.$uid, LOGGER_DEBUG); - foreach ($thread AS $tpost) { - $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, false, false); - $item = item_store($threadpost); - $threadpost["id"] = $item; + foreach ($thread as $tpost) { + $threadpost = appnet_createpost($a, $uid, $tpost, $me, $user, $ownid, false, false); + $item = item_store($threadpost); + $threadpost['id'] = $item; - logger("appnet_createpost: stored post ".$post["id"]." thread ".$post["thread_id"]." in item ".$item, LOGGER_DEBUG); - } - //} - } - // Don't create accounts of people who just comment something - $createuser = false; + logger('appnet_createpost: stored post '.$post['id'].' thread '.$post['thread_id'].' in item '.$item, LOGGER_DEBUG); + } + //} + } + // Don't create accounts of people who just comment something + $createuser = false; - $postarray['object-type'] = ACTIVITY_OBJ_COMMENT; - } else { - $postarray['thr-parent'] = $postarray['uri']; - $postarray['object-type'] = ACTIVITY_OBJ_NOTE; - } + $postarray['object-type'] = ACTIVITY_OBJ_COMMENT; + } else { + $postarray['thr-parent'] = $postarray['uri']; + $postarray['object-type'] = ACTIVITY_OBJ_NOTE; + } - if (($post["user"]["id"] != $ownid) OR ($postarray['thr-parent'] == $postarray['uri'])) { - $postarray['owner-name'] = $post["user"]["name"]; - $postarray['owner-link'] = $post["user"]["canonical_url"]; - $postarray['owner-avatar'] = $post["user"]["avatar_image"]["url"]; - $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post["user"], $me, $createuser); - } else { - $postarray['owner-name'] = $me["name"]; - $postarray['owner-link'] = $me["url"]; - $postarray['owner-avatar'] = $me["thumb"]; - $postarray['contact-id'] = $me["id"]; - } + if (($post['user']['id'] != $ownid) or ($postarray['thr-parent'] == $postarray['uri'])) { + $postarray['owner-name'] = $post['user']['name']; + $postarray['owner-link'] = $post['user']['canonical_url']; + $postarray['owner-avatar'] = $post['user']['avatar_image']['url']; + $postarray['contact-id'] = appnet_fetchcontact($a, $uid, $post['user'], $me, $createuser); + } else { + $postarray['owner-name'] = $me['name']; + $postarray['owner-link'] = $me['url']; + $postarray['owner-avatar'] = $me['thumb']; + $postarray['contact-id'] = $me['id']; + } - $links = array(); + $links = array(); - if (is_array($post["repost_of"])) { - $postarray['author-name'] = $post["repost_of"]["user"]["name"]; - $postarray['author-link'] = $post["repost_of"]["user"]["canonical_url"]; - $postarray['author-avatar'] = $post["repost_of"]["user"]["avatar_image"]["url"]; + if (is_array($post['repost_of'])) { + $postarray['author-name'] = $post['repost_of']['user']['name']; + $postarray['author-link'] = $post['repost_of']['user']['canonical_url']; + $postarray['author-avatar'] = $post['repost_of']['user']['avatar_image']['url']; - $content = $post["repost_of"]; - } else { - $postarray['author-name'] = $postarray['owner-name']; - $postarray['author-link'] = $postarray['owner-link']; - $postarray['author-avatar'] = $postarray['owner-avatar']; + $content = $post['repost_of']; + } else { + $postarray['author-name'] = $postarray['owner-name']; + $postarray['author-link'] = $postarray['owner-link']; + $postarray['author-avatar'] = $postarray['owner-avatar']; - $content = $post; - } + $content = $post; + } - $postarray['plink'] = $content["canonical_url"]; + $postarray['plink'] = $content['canonical_url']; - if (is_array($content["entities"])) { - $converted = appnet_expand_entities($a, $content["text"], $content["entities"]); - $postarray['body'] = $converted["body"]; - $postarray['tag'] = $converted["tags"]; - } else - $postarray['body'] = $content["text"]; + if (is_array($content['entities'])) { + $converted = appnet_expand_entities($a, $content['text'], $content['entities']); + $postarray['body'] = $converted['body']; + $postarray['tag'] = $converted['tags']; + } else { + $postarray['body'] = $content['text']; + } - if (sizeof($content["entities"]["links"])) - foreach($content["entities"]["links"] AS $link) { - $url = normalise_link($link["url"]); - $links[$url] = $link["url"]; - } + if (sizeof($content['entities']['links'])) { + foreach ($content['entities']['links'] as $link) { + $url = normalise_link($link['url']); + $links[$url] = $link['url']; + } + } - /* if (sizeof($content["annotations"])) - foreach($content["annotations"] AS $annotation) { - if ($annotation[type] == "net.app.core.oembed") { - if (isset($annotation["value"]["embeddable_url"])) { - $url = normalise_link($annotation["value"]["embeddable_url"]); - if (isset($links[$url])) - unset($links[$url]); - } - } elseif ($annotation[type] == "com.friendica.post") { - //$links = array(); - //if (isset($annotation["value"]["post-title"])) - // $postarray['title'] = $annotation["value"]["post-title"]; + /* if (sizeof($content["annotations"])) + foreach($content["annotations"] AS $annotation) { + if ($annotation[type] == "net.app.core.oembed") { + if (isset($annotation["value"]["embeddable_url"])) { + $url = normalise_link($annotation["value"]["embeddable_url"]); + if (isset($links[$url])) + unset($links[$url]); + } + } elseif ($annotation[type] == "com.friendica.post") { + //$links = array(); + //if (isset($annotation["value"]["post-title"])) + // $postarray['title'] = $annotation["value"]["post-title"]; - //if (isset($annotation["value"]["post-body"])) - // $postarray['body'] = $annotation["value"]["post-body"]; + //if (isset($annotation["value"]["post-body"])) + // $postarray['body'] = $annotation["value"]["post-body"]; - //if (isset($annotation["value"]["post-tag"])) - // $postarray['tag'] = $annotation["value"]["post-tag"]; + //if (isset($annotation["value"]["post-tag"])) + // $postarray['tag'] = $annotation["value"]["post-tag"]; - if (isset($annotation["value"]["author-name"])) - $postarray['author-name'] = $annotation["value"]["author-name"]; + if (isset($annotation["value"]["author-name"])) + $postarray['author-name'] = $annotation["value"]["author-name"]; - if (isset($annotation["value"]["author-link"])) - $postarray['author-link'] = $annotation["value"]["author-link"]; + if (isset($annotation["value"]["author-link"])) + $postarray['author-link'] = $annotation["value"]["author-link"]; - if (isset($annotation["value"]["author-avatar"])) - $postarray['author-avatar'] = $annotation["value"]["author-avatar"]; - } + if (isset($annotation["value"]["author-avatar"])) + $postarray['author-avatar'] = $annotation["value"]["author-avatar"]; + } - } */ + } */ - $page_info = ""; + $page_info = ''; - if (is_array($content["annotations"])) { - $photo = appnet_expand_annotations($a, $content["annotations"]); - if (($photo["large"] != "") AND ($photo["url"] != "")) - $page_info = "\n[url=".$photo["url"]."][img]".$photo["large"]."[/img][/url]"; - elseif ($photo["url"] != "") - $page_info = "\n[img]".$photo["url"]."[/img]"; + if (is_array($content['annotations'])) { + $photo = appnet_expand_annotations($a, $content['annotations']); + if (($photo['large'] != '') and ($photo['url'] != '')) { + $page_info = "\n[url=".$photo['url'].'][img]'.$photo['large'].'[/img][/url]'; + } elseif ($photo['url'] != '') { + $page_info = "\n[img]".$photo['url'].'[/img]'; + } - if ($photo["url"] != "") - $postarray['object-type'] = ACTIVITY_OBJ_IMAGE; + if ($photo['url'] != '') { + $postarray['object-type'] = ACTIVITY_OBJ_IMAGE; + } + } else { + $photo = array('url' => '', 'large' => ''); + } - } else - $photo = array("url" => "", "large" => ""); + if (sizeof($links)) { + $link = array_pop($links); + $url = str_replace(array('/', '.'), array('\/', '\.'), $link); - if (sizeof($links)) { - $link = array_pop($links); - $url = str_replace(array('/', '.'), array('\/', '\.'), $link); + $page_info = add_page_info($link, false, $photo['url']); - $page_info = add_page_info($link, false, $photo["url"]); + if (trim($page_info) != '') { + $removedlink = preg_replace("/\[url\=".$url."\](.*?)\[\/url\]/ism", '', $postarray['body']); + if (($removedlink == '') or strstr($postarray['body'], $removedlink)) { + $postarray['body'] = $removedlink; + } + } + } - if (trim($page_info) != "") { - $removedlink = preg_replace("/\[url\=".$url."\](.*?)\[\/url\]/ism", '', $postarray['body']); - if (($removedlink == "") OR strstr($postarray['body'], $removedlink)) - $postarray['body'] = $removedlink; - } - } + $postarray['body'] .= $page_info; - $postarray['body'] .= $page_info; + $postarray['created'] = datetime_convert('UTC', 'UTC', $post['created_at']); + $postarray['edited'] = datetime_convert('UTC', 'UTC', $post['created_at']); - $postarray['created'] = datetime_convert('UTC','UTC',$post["created_at"]); - $postarray['edited'] = datetime_convert('UTC','UTC',$post["created_at"]); + $postarray['app'] = $post['source']['name']; - $postarray['app'] = $post["source"]["name"]; - - return($postarray); + return $postarray; } -function appnet_expand_entities($a, $body, $entities) { +function appnet_expand_entities($a, $body, $entities) +{ + if (!function_exists('substr_unicode')) { + function substr_unicode($str, $s, $l = null) + { + return implode('', array_slice( + preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l)); + } + } - if (!function_exists('substr_unicode')) { - function substr_unicode($str, $s, $l = null) { - return join("", array_slice( - preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY), $s, $l)); - } - } + $tags_arr = array(); + $replace = array(); - $tags_arr = array(); - $replace = array(); + foreach ($entities['mentions'] as $mention) { + $url = '@[url=https://alpha.app.net/'.rawurlencode($mention['name']).']'.$mention['name'].'[/url]'; + $tags_arr['@'.$mention['name']] = $url; + $replace[$mention['pos']] = array('pos' => $mention['pos'], 'len' => $mention['len'], 'replace' => $url); + } - foreach ($entities["mentions"] AS $mention) { - $url = "@[url=https://alpha.app.net/".rawurlencode($mention["name"])."]".$mention["name"]."[/url]"; - $tags_arr["@".$mention["name"]] = $url; - $replace[$mention["pos"]] = array("pos"=> $mention["pos"], "len"=> $mention["len"], "replace"=> $url); - } + foreach ($entities['hashtags'] as $hashtag) { + $url = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($hashtag['name']).']'.$hashtag['name'].'[/url]'; + $tags_arr['#'.$hashtag['name']] = $url; + $replace[$hashtag['pos']] = array('pos' => $hashtag['pos'], 'len' => $hashtag['len'], 'replace' => $url); + } - foreach ($entities["hashtags"] AS $hashtag) { - $url = "#[url=".$a->get_baseurl()."/search?tag=".rawurlencode($hashtag["name"])."]".$hashtag["name"]."[/url]"; - $tags_arr["#".$hashtag["name"]] = $url; - $replace[$hashtag["pos"]] = array("pos"=> $hashtag["pos"], "len"=> $hashtag["len"], "replace"=> $url); - } + foreach ($entities['links'] as $links) { + $url = '[url='.$links['url'].']'.$links['text'].'[/url]'; + if (isset($links['amended_len']) and ($links['amended_len'] > $links['len'])) { + $replace[$links['pos']] = array('pos' => $links['pos'], 'len' => $links['amended_len'], 'replace' => $url); + } else { + $replace[$links['pos']] = array('pos' => $links['pos'], 'len' => $links['len'], 'replace' => $url); + } + } - foreach ($entities["links"] AS $links) { - $url = "[url=".$links["url"]."]".$links["text"]."[/url]"; - if (isset($links["amended_len"]) AND ($links["amended_len"] > $links["len"])) - $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["amended_len"], "replace"=> $url); - else - $replace[$links["pos"]] = array("pos"=> $links["pos"], "len"=> $links["len"], "replace"=> $url); - } + if (sizeof($replace)) { + krsort($replace); + foreach ($replace as $entity) { + $pre = substr_unicode($body, 0, $entity['pos']); + $post = substr_unicode($body, $entity['pos'] + $entity['len']); + //$pre = iconv_substr($body, 0, $entity["pos"], "UTF-8"); + //$post = iconv_substr($body, $entity["pos"] + $entity["len"], "UTF-8"); + $body = $pre.$entity['replace'].$post; + } + } - if (sizeof($replace)) { - krsort($replace); - foreach ($replace AS $entity) { - $pre = substr_unicode($body, 0, $entity["pos"]); - $post = substr_unicode($body, $entity["pos"] + $entity["len"]); - //$pre = iconv_substr($body, 0, $entity["pos"], "UTF-8"); - //$post = iconv_substr($body, $entity["pos"] + $entity["len"], "UTF-8"); - - $body = $pre.$entity["replace"].$post; - } - } - - return(array("body" => $body, "tags" => implode($tags_arr, ","))); + return array('body' => $body, 'tags' => implode($tags_arr, ',')); } -function appnet_expand_annotations($a, $annotations) { - $photo = array("url" => "", "large" => ""); - foreach ($annotations AS $annotation) { - if (($annotation[type] == "net.app.core.oembed") AND - ($annotation["value"]["type"] == "photo")) { - if ($annotation["value"]["url"] != "") - $photo["url"] = $annotation["value"]["url"]; +function appnet_expand_annotations($a, $annotations) +{ + $photo = array('url' => '', 'large' => ''); + foreach ($annotations as $annotation) { + if (($annotation[type] == 'net.app.core.oembed') and + ($annotation['value']['type'] == 'photo')) { + if ($annotation['value']['url'] != '') { + $photo['url'] = $annotation['value']['url']; + } - if ($annotation["value"]["thumbnail_large_url"] != "") - $photo["large"] = $annotation["value"]["thumbnail_large_url"]; + if ($annotation['value']['thumbnail_large_url'] != '') { + $photo['large'] = $annotation['value']['thumbnail_large_url']; + } - //if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != "")) - // $embedded = "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]"; - //elseif ($annotation["value"]["url"] != "") - // $embedded = "\n[img]".$annotation["value"]["url"]."[/img]"; - } - } - return $photo; + //if (($annotation["value"]["thumbnail_large_url"] != "") AND ($annotation["value"]["url"] != "")) + // $embedded = "\n[url=".$annotation["value"]["url"]."][img]".$annotation["value"]["thumbnail_large_url"]."[/img][/url]"; + //elseif ($annotation["value"]["url"] != "") + // $embedded = "\n[img]".$annotation["value"]["url"]."[/img]"; + } + } + + return $photo; } -function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) { +function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) +{ + if (function_exists('update_gcontact')) { + update_gcontact(array('url' => $contact['canonical_url'], 'generation' => 2, + 'network' => NETWORK_APPNET, 'photo' => $contact['avatar_image']['url'], + 'name' => $contact['name'], 'nick' => $contact['username'], + 'about' => $contact['description']['text'], 'hide' => true, + 'addr' => $contact['username'].'@app.net', )); + } else { + // Old Code + $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", + dbesc(normalise_link($contact['canonical_url']))); - if (function_exists("update_gcontact")) - update_gcontact(array("url" => $contact["canonical_url"], "generation" => 2, - "network" => NETWORK_APPNET, "photo" => $contact["avatar_image"]["url"], - "name" => $contact["name"], "nick" => $contact["username"], - "about" => $contact["description"]["text"], "hide" => true, - "addr" => $contact["username"]."@app.net")); - else { - // Old Code - $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", - dbesc(normalise_link($contact["canonical_url"]))); + if (count($r) == 0) { + q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')", + dbesc(normalise_link($contact['canonical_url'])), + dbesc($contact['name']), + dbesc($contact['username']), + dbesc($contact['avatar_image']['url'])); + } else { + q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'", + dbesc($contact['name']), + dbesc($contact['username']), + dbesc($contact['avatar_image']['url']), + dbesc(normalise_link($contact['canonical_url']))); + } - if (count($r) == 0) - q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')", - dbesc(normalise_link($contact["canonical_url"])), - dbesc($contact["name"]), - dbesc($contact["username"]), - dbesc($contact["avatar_image"]["url"])); - else - q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'", - dbesc($contact["name"]), - dbesc($contact["username"]), - dbesc($contact["avatar_image"]["url"]), - dbesc(normalise_link($contact["canonical_url"]))); + if (DB_UPDATE_VERSION >= '1177') { + q("UPDATE `unique_contacts` SET `location` = '%s', `about` = '%s' WHERE url = '%s'", + dbesc(''), + dbesc($contact['description']['text']), + dbesc(normalise_link($contact['canonical_url']))); + } + } - if (DB_UPDATE_VERSION >= "1177") - q("UPDATE `unique_contacts` SET `location` = '%s', `about` = '%s' WHERE url = '%s'", - dbesc(""), - dbesc($contact["description"]["text"]), - dbesc(normalise_link($contact["canonical_url"]))); - } + $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", + intval($uid), dbesc('adn::'.$contact['id'])); - $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", - intval($uid), dbesc("adn::".$contact["id"])); + if (!count($r) and !$create_user) { + return $me['id']; + } - if(!count($r) AND !$create_user) - return($me["id"]); + if ($contact['canonical_url'] == '') { + return $me['id']; + } - if ($contact["canonical_url"] == "") - return($me["id"]); + if (count($r) and ($r[0]['readonly'] or $r[0]['blocked'])) { + logger("appnet_fetchcontact: Contact '".$r[0]['nick']."' is blocked or readonly.", LOGGER_DEBUG); - if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) { - logger("appnet_fetchcontact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG); - return(-1); - } + return -1; + } - if(!count($r)) { + if (!count($r)) { + if ($contact['name'] == '') { + $contact['name'] = $contact['username']; + } - if ($contact["name"] == "") - $contact["name"] = $contact["username"]; + if ($contact['username'] == '') { + $contact['username'] = $contact['name']; + } - if ($contact["username"] == "") - $contact["username"] = $contact["name"]; - - // create contact record - q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`, + // create contact record + q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`, `name`, `nick`, `photo`, `network`, `rel`, `priority`, `writable`, `blocked`, `readonly`, `pending` ) VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ", - intval($uid), - dbesc(datetime_convert()), - dbesc($contact["canonical_url"]), - dbesc(normalise_link($contact["canonical_url"])), - dbesc($contact["username"]."@app.net"), - dbesc("adn::".$contact["id"]), - dbesc(''), - dbesc("adn::".$contact["id"]), - dbesc($contact["name"]), - dbesc($contact["username"]), - dbesc($contact["avatar_image"]["url"]), - dbesc(NETWORK_APPNET), - intval(CONTACT_IS_FRIEND), - intval(1), - intval(1) - ); + intval($uid), + dbesc(datetime_convert()), + dbesc($contact['canonical_url']), + dbesc(normalise_link($contact['canonical_url'])), + dbesc($contact['username'].'@app.net'), + dbesc('adn::'.$contact['id']), + dbesc(''), + dbesc('adn::'.$contact['id']), + dbesc($contact['name']), + dbesc($contact['username']), + dbesc($contact['avatar_image']['url']), + dbesc(NETWORK_APPNET), + intval(CONTACT_IS_FRIEND), + intval(1), + intval(1) + ); - $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1", - dbesc("adn::".$contact["id"]), - intval($uid) - ); + $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1", + dbesc('adn::'.$contact['id']), + intval($uid) + ); - if(! count($r)) - return(false); + if (!count($r)) { + return false; + } - $contact_id = $r[0]['id']; + $contact_id = $r[0]['id']; - $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1", - intval($uid) - ); + $g = q('SELECT def_gid FROM user WHERE uid = %d LIMIT 1', + intval($uid) + ); - if($g && intval($g[0]['def_gid'])) { - require_once('include/group.php'); - group_add_member($uid,'',$contact_id,$g[0]['def_gid']); - } + if ($g && intval($g[0]['def_gid'])) { + require_once 'include/group.php'; + group_add_member($uid, '', $contact_id, $g[0]['def_gid']); + } - require_once("Photo.php"); + require_once 'Photo.php'; - $photos = import_profile_photo($contact["avatar_image"]["url"],$uid,$contact_id); + $photos = import_profile_photo($contact['avatar_image']['url'], $uid, $contact_id); - q("UPDATE `contact` SET `photo` = '%s', + q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s', `name-date` = '%s', `uri-date` = '%s', `avatar-date` = '%s' WHERE `id` = %d", - dbesc($photos[0]), - dbesc($photos[1]), - dbesc($photos[2]), - dbesc(datetime_convert()), - dbesc(datetime_convert()), - dbesc(datetime_convert()), - intval($contact_id) - ); + dbesc($photos[0]), + dbesc($photos[1]), + dbesc($photos[2]), + dbesc(datetime_convert()), + dbesc(datetime_convert()), + dbesc(datetime_convert()), + intval($contact_id) + ); - if (DB_UPDATE_VERSION >= "1177") - q("UPDATE `contact` SET `location` = '%s', + if (DB_UPDATE_VERSION >= '1177') { + q("UPDATE `contact` SET `location` = '%s', `about` = '%s' WHERE `id` = %d", - dbesc(""), - dbesc($contact["description"]["text"]), - intval($contact_id) - ); - } else { - // update profile photos once every two weeks as we have no notification of when they change. + dbesc(''), + dbesc($contact['description']['text']), + intval($contact_id) + ); + } + } else { + // update profile photos once every two weeks as we have no notification of when they change. - //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false); - $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours')); + //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false); + $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours')); - // check that we have all the photos, this has been known to fail on occasion + // check that we have all the photos, this has been known to fail on occasion - if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) { + if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) { + logger('appnet_fetchcontact: Updating contact '.$contact['username'], LOGGER_DEBUG); - logger("appnet_fetchcontact: Updating contact ".$contact["username"], LOGGER_DEBUG); + require_once 'Photo.php'; - require_once("Photo.php"); + $photos = import_profile_photo($contact['avatar_image']['url'], $uid, $r[0]['id']); - $photos = import_profile_photo($contact["avatar_image"]["url"], $uid, $r[0]['id']); - - q("UPDATE `contact` SET `photo` = '%s', + q("UPDATE `contact` SET `photo` = '%s', `thumb` = '%s', `micro` = '%s', `name-date` = '%s', @@ -1268,129 +1332,139 @@ function appnet_fetchcontact($a, $uid, $contact, $me, $create_user) { `name` = '%s', `nick` = '%s' WHERE `id` = %d", - dbesc($photos[0]), - dbesc($photos[1]), - dbesc($photos[2]), - dbesc(datetime_convert()), - dbesc(datetime_convert()), - dbesc(datetime_convert()), - dbesc($contact["canonical_url"]), - dbesc(normalise_link($contact["canonical_url"])), - dbesc($contact["username"]."@app.net"), - dbesc($contact["name"]), - dbesc($contact["username"]), - intval($r[0]['id']) - ); - if (DB_UPDATE_VERSION >= "1177") - q("UPDATE `contact` SET `location` = '%s', + dbesc($photos[0]), + dbesc($photos[1]), + dbesc($photos[2]), + dbesc(datetime_convert()), + dbesc(datetime_convert()), + dbesc(datetime_convert()), + dbesc($contact['canonical_url']), + dbesc(normalise_link($contact['canonical_url'])), + dbesc($contact['username'].'@app.net'), + dbesc($contact['name']), + dbesc($contact['username']), + intval($r[0]['id']) + ); + if (DB_UPDATE_VERSION >= '1177') { + q("UPDATE `contact` SET `location` = '%s', `about` = '%s' WHERE `id` = %d", - dbesc(""), - dbesc($contact["description"]["text"]), - intval($r[0]['id']) - ); - } - } + dbesc(''), + dbesc($contact['description']['text']), + intval($r[0]['id']) + ); + } + } + } - return($r[0]["id"]); + return $r[0]['id']; } -function appnet_prepare_body(&$a,&$b) { - if ($b["item"]["network"] != NETWORK_APPNET) - return; +function appnet_prepare_body(&$a, &$b) +{ + if ($b['item']['network'] != NETWORK_APPNET) { + return; + } - if ($b["preview"]) { - $max_char = 256; - require_once("include/plaintext.php"); - $item = $b["item"]; - $item["plink"] = $a->get_baseurl()."/display/".$a->user["nickname"]."/".$item["parent"]; + if ($b['preview']) { + $max_char = 256; + require_once 'include/plaintext.php'; + $item = $b['item']; + $item['plink'] = $a->get_baseurl().'/display/'.$a->user['nickname'].'/'.$item['parent']; - $r = q("SELECT `author-link` FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1", - dbesc($item["thr-parent"]), + $r = q("SELECT `author-link` FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1", + dbesc($item['thr-parent']), intval(local_user())); - if(count($r)) { - $orig_post = $r[0]; + if (count($r)) { + $orig_post = $r[0]; - $nicknameplain = preg_replace("=https?://alpha.app.net/(.*)=ism", "$1", $orig_post["author-link"]); - $nickname = "@[url=".$orig_post["author-link"]."]".$nicknameplain."[/url]"; - $nicknameplain = "@".$nicknameplain; + $nicknameplain = preg_replace('=https?://alpha.app.net/(.*)=ism', '$1', $orig_post['author-link']); + $nickname = '@[url='.$orig_post['author-link'].']'.$nicknameplain.'[/url]'; + $nicknameplain = '@'.$nicknameplain; - if ((strpos($item["body"], $nickname) === false) AND (strpos($item["body"], $nicknameplain) === false)) - $item["body"] = $nickname." ".$item["body"]; - } - - - - $msgarr = plaintext($a, $item, $max_char, true); - $msg = appnet_create_entities($a, $item, $msgarr); - - require_once("library/markdown.php"); - $msg = Markdown($msg); - - $b['html'] = $msg; + if ((strpos($item['body'], $nickname) === false) and (strpos($item['body'], $nicknameplain) === false)) { + $item['body'] = $nickname.' '.$item['body']; + } } + + $msgarr = plaintext($a, $item, $max_char, true); + $msg = appnet_create_entities($a, $item, $msgarr); + + require_once 'library/markdown.php'; + $msg = Markdown($msg); + + $b['html'] = $msg; + } } -function appnet_cron($a,$b) { - $last = get_config('appnet','last_poll'); +function appnet_cron($a, $b) +{ + $last = get_config('appnet', 'last_poll'); - $poll_interval = intval(get_config('appnet','poll_interval')); - if(! $poll_interval) - $poll_interval = APPNET_DEFAULT_POLL_INTERVAL; + $poll_interval = intval(get_config('appnet', 'poll_interval')); + if (!$poll_interval) { + $poll_interval = APPNET_DEFAULT_POLL_INTERVAL; + } - if($last) { - $next = $last + ($poll_interval * 60); - if($next > time()) { - logger('appnet_cron: poll intervall not reached'); - return; - } - } - logger('appnet_cron: cron_start'); + if ($last) { + $next = $last + ($poll_interval * 60); + if ($next > time()) { + logger('appnet_cron: poll intervall not reached'); - $abandon_days = intval(get_config('system','account_abandon_days')); - if ($abandon_days < 1) - $abandon_days = 0; + return; + } + } + logger('appnet_cron: cron_start'); - $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400); + $abandon_days = intval(get_config('system', 'account_abandon_days')); + if ($abandon_days < 1) { + $abandon_days = 0; + } - $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()"); - if(count($r)) { - foreach($r as $rr) { - if ($abandon_days != 0) { - $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit); - if (!count($user)) { - logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported'); - continue; - } - } + $abandon_limit = date('Y-m-d H:i:s', time() - $abandon_days * 86400); - logger('appnet_cron: importing timeline from user '.$rr['uid']); - appnet_fetchstream($a, $rr["uid"]); - } - } + $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'appnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()"); + if (count($r)) { + foreach ($r as $rr) { + if ($abandon_days != 0) { + $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit); + if (!count($user)) { + logger('abandoned account: timeline from user '.$rr['uid'].' will not be imported'); + continue; + } + } - logger('appnet_cron: cron_end'); + logger('appnet_cron: importing timeline from user '.$rr['uid']); + appnet_fetchstream($a, $rr['uid']); + } + } - set_config('appnet','last_poll', time()); + logger('appnet_cron: cron_end'); + + set_config('appnet', 'last_poll', time()); } -function appnet_error($msg) { - $msg = trim($msg); - $pos = strrpos($msg, "\r\n\r\n"); +function appnet_error($msg) +{ + $msg = trim($msg); + $pos = strrpos($msg, "\r\n\r\n"); - if (!$pos) - return($msg); + if (!$pos) { + return $msg; + } - $msg = substr($msg, $pos + 4); + $msg = substr($msg, $pos + 4); - $error = json_decode($msg); + $error = json_decode($msg); - if ($error == NULL) - return($msg); + if ($error == null) { + return $msg; + } - if (isset($error->meta->error_message)) - return($error->meta->error_message); - else - return(print_r($error)); + if (isset($error->meta->error_message)) { + return $error->meta->error_message; + } else { + return print_r($error); + } } diff --git a/appnet/lang/cs/strings.php b/appnet/lang/cs/strings.php index 4bc45427..7043348b 100644 --- a/appnet/lang/cs/strings.php +++ b/appnet/lang/cs/strings.php @@ -1,29 +1,31 @@ =2 && $n<=4) ? 1 : 2;; -}} -; -$a->strings["Permission denied."] = "Přístup odmítnut."; -$a->strings["You are now authenticated to app.net. "] = "Nyní jste přihlášen k app.net."; -$a->strings["

Error fetching token. Please try again.

"] = "

Chyba v přenesení tokenu. Prosím zkuste to znovu.

"; -$a->strings["return to the connector page"] = "návrat ke stránce konektor"; -$a->strings["Post to app.net"] = "Poslat příspěvek na app.net"; -$a->strings["App.net Export"] = "App.net Export"; -$a->strings["Currently connected to: "] = "V současné době připojen k:"; -$a->strings["Enable App.net Post Plugin"] = "Aktivovat App.net Post Plugin"; -$a->strings["Post to App.net by default"] = "Defaultně poslat na App.net"; -$a->strings["Import the remote timeline"] = "Importovat vzdálenou časovou osu"; -$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Chyba v přenesení uživatelského profilu. Prosím zkuste smazat konfiguraci a zkusit to znovu.

"; -$a->strings["

You have two ways to connect to App.net.

"] = "

Máte nyní dvě možnosti jak se připojit k App.net.

"; -$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

První možnost: Registrovat svou žádost na https://account.app.net/developer/apps/ a zadat Client ID and Client Secret. "; +if (!function_exists('string_plural_select_cs')) { + function string_plural_select_cs($n) + { + return ($n == 1) ? 0 : ($n >= 2 && $n <= 4) ? 1 : 2; + } +} + +$a->strings['Permission denied.'] = 'Přístup odmítnut.'; +$a->strings['You are now authenticated to app.net. '] = 'Nyní jste přihlášen k app.net.'; +$a->strings['

Error fetching token. Please try again.

'] = '

Chyba v přenesení tokenu. Prosím zkuste to znovu.

'; +$a->strings['return to the connector page'] = 'návrat ke stránce konektor'; +$a->strings['Post to app.net'] = 'Poslat příspěvek na app.net'; +$a->strings['App.net Export'] = 'App.net Export'; +$a->strings['Currently connected to: '] = 'V současné době připojen k:'; +$a->strings['Enable App.net Post Plugin'] = 'Aktivovat App.net Post Plugin'; +$a->strings['Post to App.net by default'] = 'Defaultně poslat na App.net'; +$a->strings['Import the remote timeline'] = 'Importovat vzdálenou časovou osu'; +$a->strings['

Error fetching user profile. Please clear the configuration and try again.

'] = '

Chyba v přenesení uživatelského profilu. Prosím zkuste smazat konfiguraci a zkusit to znovu.

'; +$a->strings['

You have two ways to connect to App.net.

'] = '

Máte nyní dvě možnosti jak se připojit k App.net.

'; +$a->strings['

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. '] = '

První možnost: Registrovat svou žádost na https://account.app.net/developer/apps/ a zadat Client ID and Client Secret. '; $a->strings["Use '%s' as Redirect URI

"] = "Použít '%s' jako URI pro přesměrování

"; -$a->strings["Client ID"] = "Client ID"; -$a->strings["Client Secret"] = "Client Secret"; -$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

Druhá možnost: vložit token do http://dev-lite.jonathonduerig.com/. "; +$a->strings['Client ID'] = 'Client ID'; +$a->strings['Client Secret'] = 'Client Secret'; +$a->strings['

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. '] = '

Druhá možnost: vložit token do http://dev-lite.jonathonduerig.com/. '; $a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Nastavte tyto rámce: 'Základní', 'Stream', 'Psaní příspěvků, 'Veřejné zprávy', 'Zprávy'.

"; -$a->strings["Token"] = "Token"; -$a->strings["Sign in using App.net"] = "Přihlásit se s použitím App.net"; -$a->strings["Clear OAuth configuration"] = "Vymazat konfiguraci OAuth"; -$a->strings["Save Settings"] = "Uložit Nastavení"; +$a->strings['Token'] = 'Token'; +$a->strings['Sign in using App.net'] = 'Přihlásit se s použitím App.net'; +$a->strings['Clear OAuth configuration'] = 'Vymazat konfiguraci OAuth'; +$a->strings['Save Settings'] = 'Uložit Nastavení'; diff --git a/appnet/lang/de/strings.php b/appnet/lang/de/strings.php index da80cf7c..4f2c28e7 100644 --- a/appnet/lang/de/strings.php +++ b/appnet/lang/de/strings.php @@ -1,29 +1,31 @@ strings["Permission denied."] = "Zugriff verweigert."; -$a->strings["You are now authenticated to app.net. "] = "Du bist nun auf app.net authentifiziert."; -$a->strings["

Error fetching token. Please try again.

"] = "

Fehler beim Holen des Tokens, bitte versuche es später noch einmal.

"; -$a->strings["return to the connector page"] = "zurück zur Connector Seite"; -$a->strings["Post to app.net"] = "Nach app.net senden"; -$a->strings["App.net Export"] = "App.net Export"; -$a->strings["Currently connected to: "] = "Momentan verbunden mit: "; -$a->strings["Enable App.net Post Plugin"] = "Veröffentlichungen bei App.net erlauben"; -$a->strings["Post to App.net by default"] = "Standardmäßig bei App.net veröffentlichen"; -$a->strings["Import the remote timeline"] = "Importiere die entfernte Zeitleiste"; -$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Beim Laden des Nutzerprofils ist ein Fehler aufgetreten. Bitte versuche es später noch einmal.

"; -$a->strings["

You have two ways to connect to App.net.

"] = "

Du hast zwei Wege deinen friendica Account mit App.net zu verbinden.

"; -$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

Erster Weg: Registriere eine Anwendung unter https://account.app.net/developer/apps/ und wähle eine Client ID und ein Client Secret."; +if (!function_exists('string_plural_select_de')) { + function string_plural_select_de($n) + { + return $n != 1; + } +} + +$a->strings['Permission denied.'] = 'Zugriff verweigert.'; +$a->strings['You are now authenticated to app.net. '] = 'Du bist nun auf app.net authentifiziert.'; +$a->strings['

Error fetching token. Please try again.

'] = '

Fehler beim Holen des Tokens, bitte versuche es später noch einmal.

'; +$a->strings['return to the connector page'] = 'zurück zur Connector Seite'; +$a->strings['Post to app.net'] = 'Nach app.net senden'; +$a->strings['App.net Export'] = 'App.net Export'; +$a->strings['Currently connected to: '] = 'Momentan verbunden mit: '; +$a->strings['Enable App.net Post Plugin'] = 'Veröffentlichungen bei App.net erlauben'; +$a->strings['Post to App.net by default'] = 'Standardmäßig bei App.net veröffentlichen'; +$a->strings['Import the remote timeline'] = 'Importiere die entfernte Zeitleiste'; +$a->strings['

Error fetching user profile. Please clear the configuration and try again.

'] = '

Beim Laden des Nutzerprofils ist ein Fehler aufgetreten. Bitte versuche es später noch einmal.

'; +$a->strings['

You have two ways to connect to App.net.

'] = '

Du hast zwei Wege deinen friendica Account mit App.net zu verbinden.

'; +$a->strings['

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. '] = '

Erster Weg: Registriere eine Anwendung unter https://account.app.net/developer/apps/ und wähle eine Client ID und ein Client Secret.'; $a->strings["Use '%s' as Redirect URI

"] = "Verwende '%s' als Redirect URI

"; -$a->strings["Client ID"] = "Client ID"; -$a->strings["Client Secret"] = "Client Secret"; -$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

Zweiter Weg: Beantrage ein Token unter http://dev-lite.jonathonduerig.com/. "; +$a->strings['Client ID'] = 'Client ID'; +$a->strings['Client Secret'] = 'Client Secret'; +$a->strings['

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. '] = '

Zweiter Weg: Beantrage ein Token unter http://dev-lite.jonathonduerig.com/. '; $a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Verwende folgende Scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"; -$a->strings["Token"] = "Token"; -$a->strings["Sign in using App.net"] = "Per App.net anmelden"; -$a->strings["Clear OAuth configuration"] = "OAuth Konfiguration löschen"; -$a->strings["Save Settings"] = "Einstellungen speichern"; +$a->strings['Token'] = 'Token'; +$a->strings['Sign in using App.net'] = 'Per App.net anmelden'; +$a->strings['Clear OAuth configuration'] = 'OAuth Konfiguration löschen'; +$a->strings['Save Settings'] = 'Einstellungen speichern'; diff --git a/appnet/lang/fr/strings.php b/appnet/lang/fr/strings.php index ef9fc9e2..0f15a109 100644 --- a/appnet/lang/fr/strings.php +++ b/appnet/lang/fr/strings.php @@ -1,29 +1,31 @@ 1);; -}} -; -$a->strings["Permission denied."] = "Autorisation refusée"; -$a->strings["You are now authenticated to app.net. "] = "Vous êtes maintenant authentifié sur app.net"; -$a->strings["

Error fetching token. Please try again.

"] = "

Impossible d'obtenir le jeton, merci de réessayer.

"; -$a->strings["return to the connector page"] = "revenir à la page du connecteur"; -$a->strings["Post to app.net"] = "Publier sur app.net"; -$a->strings["App.net Export"] = "Export App.net"; -$a->strings["Currently connected to: "] = "Actuellement connecté à :"; -$a->strings["Enable App.net Post Plugin"] = "Activer le plugin de publication app.net"; -$a->strings["Post to App.net by default"] = "Publier sur App.net par défaut"; -$a->strings["Import the remote timeline"] = "Importer la timeline distante"; -$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Impossible d'obtenir le profil utilisateur. Merci de réinitialiser la configuration et de réessayer.

"; -$a->strings["

You have two ways to connect to App.net.

"] = "

Vous avez deux possibilités pour vous connecter à App.net.

"; -$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

Première méthode: Enregistrer une application sur App.net [en] et entrez l'ID Client et le Secret Client. "; +if (!function_exists('string_plural_select_fr')) { + function string_plural_select_fr($n) + { + return $n > 1; + } +} + +$a->strings['Permission denied.'] = 'Autorisation refusée'; +$a->strings['You are now authenticated to app.net. '] = 'Vous êtes maintenant authentifié sur app.net'; +$a->strings['

Error fetching token. Please try again.

'] = "

Impossible d'obtenir le jeton, merci de réessayer.

"; +$a->strings['return to the connector page'] = 'revenir à la page du connecteur'; +$a->strings['Post to app.net'] = 'Publier sur app.net'; +$a->strings['App.net Export'] = 'Export App.net'; +$a->strings['Currently connected to: '] = 'Actuellement connecté à :'; +$a->strings['Enable App.net Post Plugin'] = 'Activer le plugin de publication app.net'; +$a->strings['Post to App.net by default'] = 'Publier sur App.net par défaut'; +$a->strings['Import the remote timeline'] = 'Importer la timeline distante'; +$a->strings['

Error fetching user profile. Please clear the configuration and try again.

'] = "

Impossible d'obtenir le profil utilisateur. Merci de réinitialiser la configuration et de réessayer.

"; +$a->strings['

You have two ways to connect to App.net.

'] = '

Vous avez deux possibilités pour vous connecter à App.net.

'; +$a->strings['

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. '] = "

Première méthode: Enregistrer une application sur App.net [en] et entrez l'ID Client et le Secret Client. "; $a->strings["Use '%s' as Redirect URI

"] = "Utilisez '%s' pour l'URI de Redirection"; -$a->strings["Client ID"] = "ID Client"; -$a->strings["Client Secret"] = "Secret Client"; -$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

Deuxième méthode: obtenez un jeton ur http://dev-lite.jonathonduerig.com/ [en]. "; -$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Cochez les \"scopes\" suivant: \"Basic\", \"Stream\", \"Write Post\", \"Public Messages\", \"Messages\".

"; -$a->strings["Token"] = "Jeton"; -$a->strings["Sign in using App.net"] = "Se connecter avec App.net"; -$a->strings["Clear OAuth configuration"] = "Effacer la configuration OAuth"; -$a->strings["Save Settings"] = "Sauvegarder les paramètres"; +$a->strings['Client ID'] = 'ID Client'; +$a->strings['Client Secret'] = 'Secret Client'; +$a->strings['

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. '] = '

Deuxième méthode: obtenez un jeton ur http://dev-lite.jonathonduerig.com/ [en]. '; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = 'Cochez les "scopes" suivant: "Basic", "Stream", "Write Post", "Public Messages", "Messages".

'; +$a->strings['Token'] = 'Jeton'; +$a->strings['Sign in using App.net'] = 'Se connecter avec App.net'; +$a->strings['Clear OAuth configuration'] = 'Effacer la configuration OAuth'; +$a->strings['Save Settings'] = 'Sauvegarder les paramètres'; diff --git a/appnet/lang/it/strings.php b/appnet/lang/it/strings.php index 01c56524..80d60a65 100644 --- a/appnet/lang/it/strings.php +++ b/appnet/lang/it/strings.php @@ -1,29 +1,31 @@ strings["Permission denied."] = "Permesso negato."; -$a->strings["You are now authenticated to app.net. "] = "Sei autenticato su app.net"; -$a->strings["

Error fetching token. Please try again.

"] = "

Errore recuperando il token. Prova di nuovo

"; -$a->strings["return to the connector page"] = "ritorna alla pagina del connettore"; -$a->strings["Post to app.net"] = "Invia ad app.net"; -$a->strings["App.net Export"] = "Esporta App.net"; -$a->strings["Currently connected to: "] = "Al momento connesso con:"; -$a->strings["Enable App.net Post Plugin"] = "Abilita il plugin di invio ad App.net"; -$a->strings["Post to App.net by default"] = "Invia sempre ad App.net"; -$a->strings["Import the remote timeline"] = "Importa la timeline remota"; -$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Errore recuperando il profilo utente. Svuota la configurazione e prova di nuovo.

"; -$a->strings["

You have two ways to connect to App.net.

"] = "

Puoi collegarti ad App.net in due modi.

"; -$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

Registrare un'applicazione su https://account.app.net/developer/apps/ e inserire Client ID e Client Secret."; +if (!function_exists('string_plural_select_it')) { + function string_plural_select_it($n) + { + return $n != 1; + } +} + +$a->strings['Permission denied.'] = 'Permesso negato.'; +$a->strings['You are now authenticated to app.net. '] = 'Sei autenticato su app.net'; +$a->strings['

Error fetching token. Please try again.

'] = '

Errore recuperando il token. Prova di nuovo

'; +$a->strings['return to the connector page'] = 'ritorna alla pagina del connettore'; +$a->strings['Post to app.net'] = 'Invia ad app.net'; +$a->strings['App.net Export'] = 'Esporta App.net'; +$a->strings['Currently connected to: '] = 'Al momento connesso con:'; +$a->strings['Enable App.net Post Plugin'] = 'Abilita il plugin di invio ad App.net'; +$a->strings['Post to App.net by default'] = 'Invia sempre ad App.net'; +$a->strings['Import the remote timeline'] = 'Importa la timeline remota'; +$a->strings['

Error fetching user profile. Please clear the configuration and try again.

'] = '

Errore recuperando il profilo utente. Svuota la configurazione e prova di nuovo.

'; +$a->strings['

You have two ways to connect to App.net.

'] = '

Puoi collegarti ad App.net in due modi.

'; +$a->strings['

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. '] = "

Registrare un'applicazione su https://account.app.net/developer/apps/ e inserire Client ID e Client Secret."; $a->strings["Use '%s' as Redirect URI

"] = "Usa '%s' come Redirect URI

"; -$a->strings["Client ID"] = "Client ID"; -$a->strings["Client Secret"] = "Client Secret"; -$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

Oppure puoi recuperare un token su http://dev-lite.jonathonduerig.com/."; +$a->strings['Client ID'] = 'Client ID'; +$a->strings['Client Secret'] = 'Client Secret'; +$a->strings['

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. '] = '

Oppure puoi recuperare un token su http://dev-lite.jonathonduerig.com/.'; $a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Imposta gli ambiti 'Basic', 'Stream', 'Scrivi Post', 'Messaggi Pubblici', 'Messaggi'.

"; -$a->strings["Token"] = "Token"; -$a->strings["Sign in using App.net"] = "Autenticati con App.net"; -$a->strings["Clear OAuth configuration"] = "Pulisci configurazione OAuth"; -$a->strings["Save Settings"] = "Salva Impostazioni"; +$a->strings['Token'] = 'Token'; +$a->strings['Sign in using App.net'] = 'Autenticati con App.net'; +$a->strings['Clear OAuth configuration'] = 'Pulisci configurazione OAuth'; +$a->strings['Save Settings'] = 'Salva Impostazioni'; diff --git a/appnet/lang/nl/strings.php b/appnet/lang/nl/strings.php index ba72e364..72e93981 100644 --- a/appnet/lang/nl/strings.php +++ b/appnet/lang/nl/strings.php @@ -1,29 +1,31 @@ strings["Permission denied."] = "Toegang geweigerd"; -$a->strings["You are now authenticated to app.net. "] = "Je bent nu aangemeld bij app.net."; -$a->strings["

Error fetching token. Please try again.

"] = "

Fout tijdens token fetching. Probeer het nogmaals.

"; -$a->strings["return to the connector page"] = "ga terug naar de connector pagina"; -$a->strings["Post to app.net"] = "Post naar app.net."; -$a->strings["App.net Export"] = "App.net Export"; -$a->strings["Currently connected to: "] = "Momenteel verbonden met:"; -$a->strings["Enable App.net Post Plugin"] = "App.net Post Plugin inschakelen"; -$a->strings["Post to App.net by default"] = "Naar App.net posten als standaard instellen"; -$a->strings["Import the remote timeline"] = "The tijdlijn op afstand importeren"; -$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Fout tijdens het ophalen van gebruikersprofiel. Leeg de configuratie en probeer het opnieuw.

"; -$a->strings["

You have two ways to connect to App.net.

"] = "

Er zijn twee manieren om met App.net te verbinden.

"; -$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = ""; -$a->strings["Use '%s' as Redirect URI

"] = ""; -$a->strings["Client ID"] = ""; -$a->strings["Client Secret"] = ""; -$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = ""; -$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = ""; -$a->strings["Token"] = ""; -$a->strings["Sign in using App.net"] = ""; -$a->strings["Clear OAuth configuration"] = ""; -$a->strings["Save Settings"] = ""; +if (!function_exists('string_plural_select_nl')) { + function string_plural_select_nl($n) + { + return $n != 1; + } +} + +$a->strings['Permission denied.'] = 'Toegang geweigerd'; +$a->strings['You are now authenticated to app.net. '] = 'Je bent nu aangemeld bij app.net.'; +$a->strings['

Error fetching token. Please try again.

'] = '

Fout tijdens token fetching. Probeer het nogmaals.

'; +$a->strings['return to the connector page'] = 'ga terug naar de connector pagina'; +$a->strings['Post to app.net'] = 'Post naar app.net.'; +$a->strings['App.net Export'] = 'App.net Export'; +$a->strings['Currently connected to: '] = 'Momenteel verbonden met:'; +$a->strings['Enable App.net Post Plugin'] = 'App.net Post Plugin inschakelen'; +$a->strings['Post to App.net by default'] = 'Naar App.net posten als standaard instellen'; +$a->strings['Import the remote timeline'] = 'The tijdlijn op afstand importeren'; +$a->strings['

Error fetching user profile. Please clear the configuration and try again.

'] = '

Fout tijdens het ophalen van gebruikersprofiel. Leeg de configuratie en probeer het opnieuw.

'; +$a->strings['

You have two ways to connect to App.net.

'] = '

Er zijn twee manieren om met App.net te verbinden.

'; +$a->strings['

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. '] = ''; +$a->strings["Use '%s' as Redirect URI

"] = ''; +$a->strings['Client ID'] = ''; +$a->strings['Client Secret'] = ''; +$a->strings['

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. '] = ''; +$a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = ''; +$a->strings['Token'] = ''; +$a->strings['Sign in using App.net'] = ''; +$a->strings['Clear OAuth configuration'] = ''; +$a->strings['Save Settings'] = ''; diff --git a/appnet/lang/pt-br/strings.php b/appnet/lang/pt-br/strings.php index b8e1112c..0e30abe2 100644 --- a/appnet/lang/pt-br/strings.php +++ b/appnet/lang/pt-br/strings.php @@ -1,29 +1,31 @@ 1);; -}} -; -$a->strings["Permission denied."] = "Permissão negada."; -$a->strings["You are now authenticated to app.net. "] = "Você está autenticado no app.net."; -$a->strings["

Error fetching token. Please try again.

"] = "Erro ocorrido na obtenção do token. Tente novamente."; -$a->strings["return to the connector page"] = "Volte a página de conectores."; -$a->strings["Post to app.net"] = "Publicar no App.net"; -$a->strings["App.net Export"] = "App.net exportar"; -$a->strings["Currently connected to: "] = "Atualmente conectado em: "; -$a->strings["Enable App.net Post Plugin"] = "Habilitar plug-in para publicar no App.net"; -$a->strings["Post to App.net by default"] = "Publicar em App.net por padrão"; -$a->strings["Import the remote timeline"] = "Importar a linha do tempo remota"; -$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "Erro na obtenção do perfil do usuário. Confira as configurações e tente novamente."; -$a->strings["

You have two ways to connect to App.net.

"] = "

Você possui duas formas de conectar ao App.net

"; -$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

1º Método: Registre uma aplicação em https://account.app.net/developer/apps/ e entre o Client ID e Client Secret"; +if (!function_exists('string_plural_select_pt_br')) { + function string_plural_select_pt_br($n) + { + return $n > 1; + } +} + +$a->strings['Permission denied.'] = 'Permissão negada.'; +$a->strings['You are now authenticated to app.net. '] = 'Você está autenticado no app.net.'; +$a->strings['

Error fetching token. Please try again.

'] = 'Erro ocorrido na obtenção do token. Tente novamente.'; +$a->strings['return to the connector page'] = 'Volte a página de conectores.'; +$a->strings['Post to app.net'] = 'Publicar no App.net'; +$a->strings['App.net Export'] = 'App.net exportar'; +$a->strings['Currently connected to: '] = 'Atualmente conectado em: '; +$a->strings['Enable App.net Post Plugin'] = 'Habilitar plug-in para publicar no App.net'; +$a->strings['Post to App.net by default'] = 'Publicar em App.net por padrão'; +$a->strings['Import the remote timeline'] = 'Importar a linha do tempo remota'; +$a->strings['

Error fetching user profile. Please clear the configuration and try again.

'] = 'Erro na obtenção do perfil do usuário. Confira as configurações e tente novamente.'; +$a->strings['

You have two ways to connect to App.net.

'] = '

Você possui duas formas de conectar ao App.net

'; +$a->strings['

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. '] = '

1º Método: Registre uma aplicação em https://account.app.net/developer/apps/ e entre o Client ID e Client Secret'; $a->strings["Use '%s' as Redirect URI

"] = "Use '%s' como URI redirecionador

"; -$a->strings["Client ID"] = "Client ID"; -$a->strings["Client Secret"] = "Client Secret"; -$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

2º Método: obtenha um token em http://dev-lite.jonathonduerig.com/. "; +$a->strings['Client ID'] = 'Client ID'; +$a->strings['Client Secret'] = 'Client Secret'; +$a->strings['

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. '] = '

2º Método: obtenha um token em http://dev-lite.jonathonduerig.com/. '; $a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Adicione valor as estas saídas: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"; -$a->strings["Token"] = "Token"; -$a->strings["Sign in using App.net"] = "Entre usando o App.net"; -$a->strings["Clear OAuth configuration"] = "Limpar configuração OAuth"; -$a->strings["Save Settings"] = "Salvar Configurações"; +$a->strings['Token'] = 'Token'; +$a->strings['Sign in using App.net'] = 'Entre usando o App.net'; +$a->strings['Clear OAuth configuration'] = 'Limpar configuração OAuth'; +$a->strings['Save Settings'] = 'Salvar Configurações'; diff --git a/appnet/lang/ro/strings.php b/appnet/lang/ro/strings.php index fa8d139d..61da05e1 100644 --- a/appnet/lang/ro/strings.php +++ b/appnet/lang/ro/strings.php @@ -1,29 +1,31 @@ 19)||(($n%100==0)&&($n!=0)))?2:1));; -}} -; -$a->strings["Permission denied."] = "Permisiune refuzată."; -$a->strings["You are now authenticated to app.net. "] = "Acum sunteți autentificat pe App.net."; -$a->strings["

Error fetching token. Please try again.

"] = "

Eroare la procesarea token-ului. Vă rugăm să reîncercați.

"; -$a->strings["return to the connector page"] = "revenire la pagina de conectare"; -$a->strings["Post to app.net"] = "Postați pe App.net"; -$a->strings["App.net Export"] = "Exportare pe App.net"; -$a->strings["Currently connected to: "] = "Conectat curent la:"; -$a->strings["Enable App.net Post Plugin"] = "Activare Modul Postare pe App.net"; -$a->strings["Post to App.net by default"] = "Postați implicit pe App.net"; -$a->strings["Import the remote timeline"] = "Importare cronologie la distanță"; -$a->strings["

Error fetching user profile. Please clear the configuration and try again.

"] = "

Eroare la procesarea profilului de utilizator. Vă rugăm să ștergeți configurarea şi apoi reîncercați.

"; -$a->strings["

You have two ways to connect to App.net.

"] = "

Aveți două modalități de a vă conecta la App.net.

"; -$a->strings["

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. "] = "

Prima modalitate: Înregistrați o cerere pe https://account.app.net/developer/apps/ şi introduceți ID Client şi Cheia Secretă Client."; +if (!function_exists('string_plural_select_ro')) { + function string_plural_select_ro($n) + { + return $n == 1 ? 0 : ((($n % 100 > 19) || (($n % 100 == 0) && ($n != 0))) ? 2 : 1); + } +} + +$a->strings['Permission denied.'] = 'Permisiune refuzată.'; +$a->strings['You are now authenticated to app.net. '] = 'Acum sunteți autentificat pe App.net.'; +$a->strings['

Error fetching token. Please try again.

'] = '

Eroare la procesarea token-ului. Vă rugăm să reîncercați.

'; +$a->strings['return to the connector page'] = 'revenire la pagina de conectare'; +$a->strings['Post to app.net'] = 'Postați pe App.net'; +$a->strings['App.net Export'] = 'Exportare pe App.net'; +$a->strings['Currently connected to: '] = 'Conectat curent la:'; +$a->strings['Enable App.net Post Plugin'] = 'Activare Modul Postare pe App.net'; +$a->strings['Post to App.net by default'] = 'Postați implicit pe App.net'; +$a->strings['Import the remote timeline'] = 'Importare cronologie la distanță'; +$a->strings['

Error fetching user profile. Please clear the configuration and try again.

'] = '

Eroare la procesarea profilului de utilizator. Vă rugăm să ștergeți configurarea şi apoi reîncercați.

'; +$a->strings['

You have two ways to connect to App.net.

'] = '

Aveți două modalități de a vă conecta la App.net.

'; +$a->strings['

First way: Register an application at https://account.app.net/developer/apps/ and enter Client ID and Client Secret. '] = '

Prima modalitate: Înregistrați o cerere pe https://account.app.net/developer/apps/ şi introduceți ID Client şi Cheia Secretă Client.'; $a->strings["Use '%s' as Redirect URI

"] = "Utilizați '%s' ca URI de Redirecţionare

"; -$a->strings["Client ID"] = "ID Client"; -$a->strings["Client Secret"] = "Cheia Secretă Client"; -$a->strings["

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. "] = "

A doua cale: autorizați un indicativ de acces token de pe http://dev-lite.jonathonduerig.com/ ."; +$a->strings['Client ID'] = 'ID Client'; +$a->strings['Client Secret'] = 'Cheia Secretă Client'; +$a->strings['

Second way: fetch a token at http://dev-lite.jonathonduerig.com/. '] = '

A doua cale: autorizați un indicativ de acces token de pe http://dev-lite.jonathonduerig.com/ .'; $a->strings["Set these scopes: 'Basic', 'Stream', 'Write Post', 'Public Messages', 'Messages'.

"] = "Stabiliți aceste scopuri: 'De Bază', 'Flux', 'Scriere Postare', 'Mesaje Publice', 'Mesaje'.

"; -$a->strings["Token"] = "Token"; -$a->strings["Sign in using App.net"] = "Autentificați-vă utilizând App.net"; -$a->strings["Clear OAuth configuration"] = "Ștergeți configurările OAuth"; -$a->strings["Save Settings"] = "Salvare Configurări"; +$a->strings['Token'] = 'Token'; +$a->strings['Sign in using App.net'] = 'Autentificați-vă utilizând App.net'; +$a->strings['Clear OAuth configuration'] = 'Ștergeți configurările OAuth'; +$a->strings['Save Settings'] = 'Salvare Configurări'; diff --git a/blackout/blackout.php b/blackout/blackout.php index 3678969e..e4c270f8 100644 --- a/blackout/blackout.php +++ b/blackout/blackout.php @@ -4,7 +4,7 @@ * Description: Blackout your ~friendica node during a given period, requires PHP >= 5.3 * License: MIT * Version: 1.0 - * Author: Tobias Diekershoff + * Author: Tobias Diekershoff . * * About * ===== @@ -36,10 +36,10 @@ * 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 @@ -48,73 +48,83 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ - - -function blackout_install() { +function blackout_install() +{ register_hook('page_header', 'addon/blackout/blackout.php', 'blackout_redirect'); } -function blackout_uninstall() { +function blackout_uninstall() +{ unregister_hook('page_header', 'addon/blackout/blackout.php', 'blackout_redirect'); } -function blackout_redirect ($a, $b) { +function blackout_redirect($a, $b) +{ // if we have a logged in user, don't throw her out if (local_user()) { return true; } - if (! (version_compare(PHP_VERSION, '5.3.0') >= 0)) - return true; + if (!(version_compare(PHP_VERSION, '5.3.0') >= 0)) { + return true; + } // else... - $mystart = get_config('blackout','begindate'); - $myend = get_config('blackout','enddate'); - $myurl = get_config('blackout','url'); + $mystart = get_config('blackout', 'begindate'); + $myend = get_config('blackout', 'enddate'); + $myurl = get_config('blackout', 'url'); $now = time(); $date1 = DateTime::createFromFormat('Y-m-d G:i', $mystart); $date2 = DateTime::createFromFormat('Y-m-d G:i', $myend); - if ( $date1 && $date2 ) { + if ($date1 && $date2) { $date1 = DateTime::createFromFormat('Y-m-d G:i', $mystart)->format('U'); $date2 = DateTime::createFromFormat('Y-m-d G:i', $myend)->format('U'); } else { - $date1 = 0; - $date2 = 0; + $date1 = 0; + $date2 = 0; } - if (( $date1 <= $now ) && ( $now <= $date2 )) { + if (($date1 <= $now) && ($now <= $date2)) { logger('redirecting user to blackout page'); goaway($myurl); } } -function blackout_plugin_admin(&$a, &$o) { - $mystart = get_config('blackout','begindate'); - if (! is_string($mystart)) { $mystart = "YYYY-MM-DD:hhmm"; } - $myend = get_config('blackout','enddate'); - if (! is_string($myend)) { $myend = "YYYY-MM-DD:hhmm"; } - $myurl = get_config('blackout','url'); - if (! is_string($myurl)) { $myurl = "http://www.example.com"; } - $t = get_markup_template( "admin.tpl", "addon/blackout/" ); - - $o = replace_macros($t, array( +function blackout_plugin_admin(&$a, &$o) +{ + $mystart = get_config('blackout', 'begindate'); + if (!is_string($mystart)) { + $mystart = 'YYYY-MM-DD:hhmm'; + } + $myend = get_config('blackout', 'enddate'); + if (!is_string($myend)) { + $myend = 'YYYY-MM-DD:hhmm'; + } + $myurl = get_config('blackout', 'url'); + if (!is_string($myurl)) { + $myurl = 'http://www.example.com'; + } + $t = get_markup_template('admin.tpl', 'addon/blackout/'); + + $o = replace_macros($t, array( '$submit' => t('Save Settings'), - '$rurl' => array("rurl", "Redirect URL", $myurl, "all your visitors from the web will be redirected to this URL"), - '$startdate' => array("startdate", "Begin of the Blackout
(YYYY-MM-DD hh:mm)", $mystart, "format is YYYY year, MM month, DD day, hh hour and mm minute"), - '$enddate' => array("enddate", "End of the Blackout
(YYYY-MM-DD hh:mm)", $myend, ""), + '$rurl' => array('rurl', 'Redirect URL', $myurl, 'all your visitors from the web will be redirected to this URL'), + '$startdate' => array('startdate', 'Begin of the Blackout
(YYYY-MM-DD hh:mm)', $mystart, 'format is YYYY year, MM month, DD day, hh hour and mm minute'), + '$enddate' => array('enddate', 'End of the Blackout
(YYYY-MM-DD hh:mm)', $myend, ''), )); $date1 = DateTime::createFromFormat('Y-m-d G:i', $mystart); $date2 = DateTime::createFromFormat('Y-m-d G:i', $myend); if ($date2 < $date1) { - $o = "
The end-date is prior to the start-date of the blackout, you should fix this.
" . $o; + $o = "
The end-date is prior to the start-date of the blackout, you should fix this.
".$o; } else { - $o = '

Please double check that the current settings for the blackout. Begin will be '.$mystart.' and it will end '.$myend.'.

' . $o; + $o = '

Please double check that the current settings for the blackout. Begin will be '.$mystart.' and it will end '.$myend.'.

'.$o; } } -function blackout_plugin_admin_post (&$a) { +function blackout_plugin_admin_post(&$a) +{ $begindate = trim($_POST['startdate']); $enddate = trim($_POST['enddate']); $url = trim($_POST['rurl']); - set_config('blackout','begindate',$begindate); - set_config('blackout','enddate',$enddate); - set_config('blackout','url',$url); + set_config('blackout', 'begindate', $begindate); + set_config('blackout', 'enddate', $enddate); + set_config('blackout', 'url', $url); } diff --git a/blackout/lang/ca/strings.php b/blackout/lang/ca/strings.php index 87481b12..aad6b1a8 100644 --- a/blackout/lang/ca/strings.php +++ b/blackout/lang/ca/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Enviar"; +strings['Submit'] = 'Enviar'; diff --git a/blackout/lang/cs/strings.php b/blackout/lang/cs/strings.php index 6bca0c65..09fa368d 100644 --- a/blackout/lang/cs/strings.php +++ b/blackout/lang/cs/strings.php @@ -1,14 +1,16 @@ =2 && $n<=4) ? 1 : 2;; -}} -; -$a->strings["Save Settings"] = "Uložit Nastavení"; -$a->strings["Redirect URL"] = "URL Přesměrování"; -$a->strings["all your visitors from the web will be redirected to this URL"] = "všichni vaši návštěvníci z webu budou přesměrování na tuto URL adresu"; -$a->strings["Begin of the Blackout"] = "Zahájení odstávky"; -$a->strings["format is YYYY year, MM month, DD day, hh hour and mm minute"] = "formát je RRRR rok, MM měsíc, DD den, hh hodina a mm minuta"; -$a->strings["End of the Blackout"] = "Konec odstávky"; -$a->strings["The end-date is prior to the start-date of the blackout, you should fix this."] = "Datum konce odstávky je před datem zahájení odstávky prosím opravte to."; +if (!function_exists('string_plural_select_cs')) { + function string_plural_select_cs($n) + { + return ($n == 1) ? 0 : ($n >= 2 && $n <= 4) ? 1 : 2; + } +} + +$a->strings['Save Settings'] = 'Uložit Nastavení'; +$a->strings['Redirect URL'] = 'URL Přesměrování'; +$a->strings['all your visitors from the web will be redirected to this URL'] = 'všichni vaši návštěvníci z webu budou přesměrování na tuto URL adresu'; +$a->strings['Begin of the Blackout'] = 'Zahájení odstávky'; +$a->strings['format is YYYY year, MM month, DD day, hh hour and mm minute'] = 'formát je RRRR rok, MM měsíc, DD den, hh hodina a mm minuta'; +$a->strings['End of the Blackout'] = 'Konec odstávky'; +$a->strings['The end-date is prior to the start-date of the blackout, you should fix this.'] = 'Datum konce odstávky je před datem zahájení odstávky prosím opravte to.'; diff --git a/blackout/lang/de/strings.php b/blackout/lang/de/strings.php index 66570090..7d65336e 100644 --- a/blackout/lang/de/strings.php +++ b/blackout/lang/de/strings.php @@ -1,14 +1,16 @@ strings["Save Settings"] = "Einstellungen speichern"; -$a->strings["Redirect URL"] = "Umleitungs-URL"; -$a->strings["all your visitors from the web will be redirected to this URL"] = "Alle Besucher der Webseite werden zu dieser URL umgeleitet"; -$a->strings["Begin of the Blackout"] = "Beginn des Blackouts"; -$a->strings["format is YYYY year, MM month, DD day, hh hour and mm minute"] = "Das Format ist YYYY Jahr, MM Monat, DD Tag, hh Stunde und mm Minute"; -$a->strings["End of the Blackout"] = "Ende des Blackouts"; -$a->strings["The end-date is prior to the start-date of the blackout, you should fix this."] = "Das Enddatum liegt vor dem Startdatum des Blackouts, du solltest dies korrigieren."; +if (!function_exists('string_plural_select_de')) { + function string_plural_select_de($n) + { + return $n != 1; + } +} + +$a->strings['Save Settings'] = 'Einstellungen speichern'; +$a->strings['Redirect URL'] = 'Umleitungs-URL'; +$a->strings['all your visitors from the web will be redirected to this URL'] = 'Alle Besucher der Webseite werden zu dieser URL umgeleitet'; +$a->strings['Begin of the Blackout'] = 'Beginn des Blackouts'; +$a->strings['format is YYYY year, MM month, DD day, hh hour and mm minute'] = 'Das Format ist YYYY Jahr, MM Monat, DD Tag, hh Stunde und mm Minute'; +$a->strings['End of the Blackout'] = 'Ende des Blackouts'; +$a->strings['The end-date is prior to the start-date of the blackout, you should fix this.'] = 'Das Enddatum liegt vor dem Startdatum des Blackouts, du solltest dies korrigieren.'; diff --git a/blackout/lang/eo/strings.php b/blackout/lang/eo/strings.php index 68b5936b..36bcddc6 100644 --- a/blackout/lang/eo/strings.php +++ b/blackout/lang/eo/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Sendi"; +strings['Submit'] = 'Sendi'; diff --git a/blackout/lang/es/strings.php b/blackout/lang/es/strings.php index 867a8c9b..f88853e7 100644 --- a/blackout/lang/es/strings.php +++ b/blackout/lang/es/strings.php @@ -1,14 +1,16 @@ strings["Save Settings"] = "Guardar configuración"; -$a->strings["Redirect URL"] = "Redirigir URL"; -$a->strings["all your visitors from the web will be redirected to this URL"] = "todos los visitantes de la web serán redirigidos a esta dirección."; -$a->strings["Begin of the Blackout"] = "Inicio del apagón."; -$a->strings["format is YYYY year, MM month, DD day, hh hour and mm minute"] = "formato es YYYY año, MM mes, DD día, hh hora y mm minuto"; -$a->strings["End of the Blackout"] = "Fin del apagón."; -$a->strings["The end-date is prior to the start-date of the blackout, you should fix this."] = "La fecha de final del apagón es antes de la fecha de inicio, deberías arreglar esto."; +if (!function_exists('string_plural_select_es')) { + function string_plural_select_es($n) + { + return $n != 1; + } +} + +$a->strings['Save Settings'] = 'Guardar configuración'; +$a->strings['Redirect URL'] = 'Redirigir URL'; +$a->strings['all your visitors from the web will be redirected to this URL'] = 'todos los visitantes de la web serán redirigidos a esta dirección.'; +$a->strings['Begin of the Blackout'] = 'Inicio del apagón.'; +$a->strings['format is YYYY year, MM month, DD day, hh hour and mm minute'] = 'formato es YYYY año, MM mes, DD día, hh hora y mm minuto'; +$a->strings['End of the Blackout'] = 'Fin del apagón.'; +$a->strings['The end-date is prior to the start-date of the blackout, you should fix this.'] = 'La fecha de final del apagón es antes de la fecha de inicio, deberías arreglar esto.'; diff --git a/blackout/lang/fr/strings.php b/blackout/lang/fr/strings.php index ce184038..f240c433 100644 --- a/blackout/lang/fr/strings.php +++ b/blackout/lang/fr/strings.php @@ -1,14 +1,16 @@ 1);; -}} -; -$a->strings["Save Settings"] = "Sauvegarder les paramètres"; -$a->strings["Redirect URL"] = "Adresse de redirection"; -$a->strings["all your visitors from the web will be redirected to this URL"] = "Tous vos visiteurs venant du web seront redirigés vers cette URL."; -$a->strings["Begin of the Blackout"] = "Début du blackout"; -$a->strings["format is YYYY year, MM month, DD day, hh hour and mm minute"] = "Le format est YYYY année, MM mois, DD jour, hh heure and mm minute"; -$a->strings["End of the Blackout"] = "Fin du blackout"; -$a->strings["The end-date is prior to the start-date of the blackout, you should fix this."] = "La date de fin est antérieure à la date de début. Veuillez corriger cela."; +if (!function_exists('string_plural_select_fr')) { + function string_plural_select_fr($n) + { + return $n > 1; + } +} + +$a->strings['Save Settings'] = 'Sauvegarder les paramètres'; +$a->strings['Redirect URL'] = 'Adresse de redirection'; +$a->strings['all your visitors from the web will be redirected to this URL'] = 'Tous vos visiteurs venant du web seront redirigés vers cette URL.'; +$a->strings['Begin of the Blackout'] = 'Début du blackout'; +$a->strings['format is YYYY year, MM month, DD day, hh hour and mm minute'] = 'Le format est YYYY année, MM mois, DD jour, hh heure and mm minute'; +$a->strings['End of the Blackout'] = 'Fin du blackout'; +$a->strings['The end-date is prior to the start-date of the blackout, you should fix this.'] = 'La date de fin est antérieure à la date de début. Veuillez corriger cela.'; diff --git a/blackout/lang/is/strings.php b/blackout/lang/is/strings.php index 94f89330..1bae877d 100644 --- a/blackout/lang/is/strings.php +++ b/blackout/lang/is/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Senda inn"; +strings['Submit'] = 'Senda inn'; diff --git a/blackout/lang/it/strings.php b/blackout/lang/it/strings.php index b0142236..32665f99 100644 --- a/blackout/lang/it/strings.php +++ b/blackout/lang/it/strings.php @@ -1,14 +1,16 @@ strings["Save Settings"] = "Salva Impostazioni"; -$a->strings["Redirect URL"] = "URL di reindirizzamento"; -$a->strings["all your visitors from the web will be redirected to this URL"] = "tutti i visitatori dal web verranno reindirizzati a questo URL"; -$a->strings["Begin of the Blackout"] = "Inzio del blackout"; -$a->strings["format is YYYY year, MM month, DD day, hh hour and mm minute"] = "il formato è YYYY anno, MM mese, DD giorno, hh ora e mm minuto"; -$a->strings["End of the Blackout"] = "Fine del blackout"; -$a->strings["The end-date is prior to the start-date of the blackout, you should fix this."] = "La data di fine è precedente alla data di inizio. Dovresti sistemarla."; +if (!function_exists('string_plural_select_it')) { + function string_plural_select_it($n) + { + return $n != 1; + } +} + +$a->strings['Save Settings'] = 'Salva Impostazioni'; +$a->strings['Redirect URL'] = 'URL di reindirizzamento'; +$a->strings['all your visitors from the web will be redirected to this URL'] = 'tutti i visitatori dal web verranno reindirizzati a questo URL'; +$a->strings['Begin of the Blackout'] = 'Inzio del blackout'; +$a->strings['format is YYYY year, MM month, DD day, hh hour and mm minute'] = 'il formato è YYYY anno, MM mese, DD giorno, hh ora e mm minuto'; +$a->strings['End of the Blackout'] = 'Fine del blackout'; +$a->strings['The end-date is prior to the start-date of the blackout, you should fix this.'] = 'La data di fine è precedente alla data di inizio. Dovresti sistemarla.'; diff --git a/blackout/lang/nb-no/strings.php b/blackout/lang/nb-no/strings.php index 9001ec4a..6aca03bd 100644 --- a/blackout/lang/nb-no/strings.php +++ b/blackout/lang/nb-no/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Lagre"; +strings['Submit'] = 'Lagre'; diff --git a/blackout/lang/pl/strings.php b/blackout/lang/pl/strings.php index e18a64fb..96360b86 100644 --- a/blackout/lang/pl/strings.php +++ b/blackout/lang/pl/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Potwierdź"; +strings['Submit'] = 'Potwierdź'; diff --git a/blackout/lang/pt-br/strings.php b/blackout/lang/pt-br/strings.php index 87481b12..aad6b1a8 100644 --- a/blackout/lang/pt-br/strings.php +++ b/blackout/lang/pt-br/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Enviar"; +strings['Submit'] = 'Enviar'; diff --git a/blackout/lang/ro/strings.php b/blackout/lang/ro/strings.php index 498f7c3e..2e46c970 100644 --- a/blackout/lang/ro/strings.php +++ b/blackout/lang/ro/strings.php @@ -1,14 +1,16 @@ 19)||(($n%100==0)&&($n!=0)))?2:1));; -}} -; -$a->strings["Save Settings"] = "Salvare Configurări"; -$a->strings["Redirect URL"] = "URL de Redirecționare"; -$a->strings["all your visitors from the web will be redirected to this URL"] = "toți vizitatorii dvs. de pe web vor fi redirecționați către acest URL"; -$a->strings["Begin of the Blackout"] = "Pornire punct Blackout"; -$a->strings["format is YYYY year, MM month, DD day, hh hour and mm minute"] = "formatul este YYYY anul, MM luna, DD ziua, hh ora și mm minute"; -$a->strings["End of the Blackout"] = "Finalizare punct Blackout"; -$a->strings["The end-date is prior to the start-date of the blackout, you should fix this."] = "Data de finalizare este anterioară punctului blackout de pornire, ar trebui să corectați aceasta."; +if (!function_exists('string_plural_select_ro')) { + function string_plural_select_ro($n) + { + return $n == 1 ? 0 : ((($n % 100 > 19) || (($n % 100 == 0) && ($n != 0))) ? 2 : 1); + } +} + +$a->strings['Save Settings'] = 'Salvare Configurări'; +$a->strings['Redirect URL'] = 'URL de Redirecționare'; +$a->strings['all your visitors from the web will be redirected to this URL'] = 'toți vizitatorii dvs. de pe web vor fi redirecționați către acest URL'; +$a->strings['Begin of the Blackout'] = 'Pornire punct Blackout'; +$a->strings['format is YYYY year, MM month, DD day, hh hour and mm minute'] = 'formatul este YYYY anul, MM luna, DD ziua, hh ora și mm minute'; +$a->strings['End of the Blackout'] = 'Finalizare punct Blackout'; +$a->strings['The end-date is prior to the start-date of the blackout, you should fix this.'] = 'Data de finalizare este anterioară punctului blackout de pornire, ar trebui să corectați aceasta.'; diff --git a/blackout/lang/ru/strings.php b/blackout/lang/ru/strings.php index ab5e2246..f100be77 100644 --- a/blackout/lang/ru/strings.php +++ b/blackout/lang/ru/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Подтвердить"; +strings['Submit'] = 'Подтвердить'; diff --git a/blackout/lang/sv/strings.php b/blackout/lang/sv/strings.php index 3ec569a7..4575a404 100644 --- a/blackout/lang/sv/strings.php +++ b/blackout/lang/sv/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Spara"; +strings['Submit'] = 'Spara'; diff --git a/blackout/lang/zh-cn/strings.php b/blackout/lang/zh-cn/strings.php index d6d8e7d2..241eef3d 100644 --- a/blackout/lang/zh-cn/strings.php +++ b/blackout/lang/zh-cn/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "提交"; +strings['Submit'] = '提交'; diff --git a/blockem/blockem.php b/blockem/blockem.php index 223a1990..7801745c 100755 --- a/blockem/blockem.php +++ b/blockem/blockem.php @@ -5,161 +5,155 @@ * Name: blockem * Description: block people * Version: 1.0 - * Author: Mike Macgirvin - * + * Author: Mike Macgirvin . */ - -function blockem_install() { - register_hook('prepare_body', 'addon/blockem/blockem.php', 'blockem_prepare_body'); - register_hook('display_item', 'addon/blockem/blockem.php', 'blockem_display_item'); - register_hook('plugin_settings', 'addon/blockem/blockem.php', 'blockem_addon_settings'); - register_hook('plugin_settings_post', 'addon/blockem/blockem.php', 'blockem_addon_settings_post'); - register_hook('conversation_start', 'addon/blockem/blockem.php', 'blockem_conversation_start'); - register_hook('item_photo_menu', 'addon/blockem/blockem.php', 'blockem_item_photo_menu'); - register_hook('enotify_store', 'addon/blockem/blockem.php', 'blockem_enotify_store' ); +function blockem_install() +{ + register_hook('prepare_body', 'addon/blockem/blockem.php', 'blockem_prepare_body'); + register_hook('display_item', 'addon/blockem/blockem.php', 'blockem_display_item'); + register_hook('plugin_settings', 'addon/blockem/blockem.php', 'blockem_addon_settings'); + register_hook('plugin_settings_post', 'addon/blockem/blockem.php', 'blockem_addon_settings_post'); + register_hook('conversation_start', 'addon/blockem/blockem.php', 'blockem_conversation_start'); + register_hook('item_photo_menu', 'addon/blockem/blockem.php', 'blockem_item_photo_menu'); + register_hook('enotify_store', 'addon/blockem/blockem.php', 'blockem_enotify_store'); } - -function blockem_uninstall() { - unregister_hook('prepare_body', 'addon/blockem/blockem.php', 'blockem_prepare_body'); - unregister_hook('display_item', 'addon/blockem/blockem.php', 'blockem_display_item'); - unregister_hook('plugin_settings', 'addon/blockem/blockem.php', 'blockem_addon_settings'); - unregister_hook('plugin_settings_post', 'addon/blockem/blockem.php', 'blockem_addon_settings_post'); - unregister_hook('conversation_start', 'addon/blockem/blockem.php', 'blockem_conversation_start'); - unregister_hook('item_photo_menu', 'addon/blockem/blockem.php', 'blockem_item_photo_menu'); - unregister_hook('enotify_store', 'addon/blockem/blockem.php', 'blockem_enotify_store' ); - +function blockem_uninstall() +{ + unregister_hook('prepare_body', 'addon/blockem/blockem.php', 'blockem_prepare_body'); + unregister_hook('display_item', 'addon/blockem/blockem.php', 'blockem_display_item'); + unregister_hook('plugin_settings', 'addon/blockem/blockem.php', 'blockem_addon_settings'); + unregister_hook('plugin_settings_post', 'addon/blockem/blockem.php', 'blockem_addon_settings_post'); + unregister_hook('conversation_start', 'addon/blockem/blockem.php', 'blockem_conversation_start'); + unregister_hook('item_photo_menu', 'addon/blockem/blockem.php', 'blockem_item_photo_menu'); + unregister_hook('enotify_store', 'addon/blockem/blockem.php', 'blockem_enotify_store'); } - - - - -function blockem_addon_settings(&$a,&$s) { - - if(! local_user()) - return; +function blockem_addon_settings(&$a, &$s) +{ + if (!local_user()) { + return; + } /* Add our stylesheet to the page so we can make our settings look nice */ - $a->page['htmlhead'] .= '' . "\r\n"; + $a->page['htmlhead'] .= ''."\r\n"; - - $words = get_pconfig(local_user(),'blockem','words'); - if(! $words) - $words = ''; + $words = get_pconfig(local_user(), 'blockem', 'words'); + if (!$words) { + $words = ''; + } $s .= ''; - $s .= '

' . t('"Blockem"') . '

'; + $s .= '

'.t('"Blockem"').'

'; $s .= '
'; $s .= ''; - - return; + $s .= '
'; + return; } -function blockem_addon_settings_post(&$a,&$b) { +function blockem_addon_settings_post(&$a, &$b) +{ + if (!local_user()) { + return; + } - if(! local_user()) - return; - - if($_POST['blockem-submit']) { - set_pconfig(local_user(),'blockem','words',trim($_POST['blockem-words'])); - info( t('BLOCKEM Settings saved.') . EOL); - } + if ($_POST['blockem-submit']) { + set_pconfig(local_user(), 'blockem', 'words', trim($_POST['blockem-words'])); + info(t('BLOCKEM Settings saved.').EOL); + } } +function blockem_enotify_store(&$a, &$b) +{ + $words = get_pconfig($b['uid'], 'blockem', 'words'); + if ($words) { + $arr = explode(',', $words); + } else { + return; + } -function blockem_enotify_store(&$a,&$b) { + $found = false; + if (count($arr)) { + foreach ($arr as $word) { + if (!strlen(trim($word))) { + continue; + } - $words = get_pconfig($b['uid'],'blockem','words'); - if($words) { - $arr = explode(',',$words); - } - else { - return; - } - - $found = false; - if(count($arr)) { - foreach($arr as $word) { - if(! strlen(trim($word))) { - continue; - } - - if(link_compare($b['url'],$word)) { - $found = true; - break; - } - } - } - if($found) { - $b['abort'] = true; - } + if (link_compare($b['url'], $word)) { + $found = true; + break; + } + } + } + if ($found) { + $b['abort'] = true; + } } -function blockem_prepare_body(&$a,&$b) { +function blockem_prepare_body(&$a, &$b) +{ + if (!local_user()) { + return; + } - if(! local_user()) - return; + $words = null; + if (local_user()) { + $words = get_pconfig(local_user(), 'blockem', 'words'); + } + if ($words) { + $arr = explode(',', $words); + } else { + return; + } - $words = null; - if(local_user()) { - $words = get_pconfig(local_user(),'blockem','words'); - } - if($words) { - $arr = explode(',',$words); - } - else { - return; - } + $found = false; + if (count($arr)) { + foreach ($arr as $word) { + if (!strlen(trim($word))) { + continue; + } - $found = false; - if(count($arr)) { - foreach($arr as $word) { - if(! strlen(trim($word))) { - continue; - } - - if(link_compare($b['item']['author-link'],$word)) { - $found = true; - break; - } - } - } - if($found) { - $rnd = random_string(8); - $b['html'] = ''; - } + if (link_compare($b['item']['author-link'], $word)) { + $found = true; + break; + } + } + } + if ($found) { + $rnd = random_string(8); + $b['html'] = ''; + } } - -function blockem_display_item(&$a,&$b) { - if(strstr($b['output']['body'],'id="blockem-wrap-')) - $b['output']['thumb'] = $a->get_baseurl() . "/images/person-80.jpg"; +function blockem_display_item(&$a, &$b) +{ + if (strstr($b['output']['body'], 'id="blockem-wrap-')) { + $b['output']['thumb'] = $a->get_baseurl().'/images/person-80.jpg'; + } } +function blockem_conversation_start(&$a, &$b) +{ + if (!local_user()) { + return; + } -function blockem_conversation_start(&$a,&$b) { - - if(! local_user()) - return; - - $words = get_pconfig(local_user(),'blockem','words'); - if($words) { - $a->data['blockem'] = explode(',',$words); - } - $a->page['htmlhead'] .= <<< EOT + $words = get_pconfig(local_user(), 'blockem', 'words'); + if ($words) { + $a->data['blockem'] = explode(',', $words); + } + $a->page['htmlhead'] .= <<< 'EOT' EOT; - } -function blockem_item_photo_menu(&$a,&$b) { +function blockem_item_photo_menu(&$a, &$b) +{ + if ((!local_user()) || ($b['item']['self'])) { + return; + } - if((! local_user()) || ($b['item']['self'])) - return; - - $blocked = false; - $author = $b['item']['author-link']; - if(is_array($a->data['blockem'])) { - foreach($a->data['blockem'] as $bloke) { - if(link_compare($bloke,$author)) { - $blocked = true; - break; - } - } - } - if($blocked) - $b['menu'][ t('Unblock Author')] = 'javascript:blockemUnblock(\'' . $author . '\');'; - else - $b['menu'][ t('Block Author')] = 'javascript:blockemBlock(\'' . $author . '\');'; + $blocked = false; + $author = $b['item']['author-link']; + if (is_array($a->data['blockem'])) { + foreach ($a->data['blockem'] as $bloke) { + if (link_compare($bloke, $author)) { + $blocked = true; + break; + } + } + } + if ($blocked) { + $b['menu'][ t('Unblock Author')] = 'javascript:blockemUnblock(\''.$author.'\');'; + } else { + $b['menu'][ t('Block Author')] = 'javascript:blockemBlock(\''.$author.'\');'; + } } -function blockem_module() {} - - -function blockem_init(&$a) { - - if(! local_user()) - return; - - $words = get_pconfig(local_user(),'blockem','words'); - - if(array_key_exists('block',$_GET) && $_GET['block']) { - if(strlen($words)) - $words .= ','; - $words .= trim($_GET['block']); - } - if(array_key_exists('unblock',$_GET) && $_GET['unblock']) { - $arr = explode(',',$words); - $newarr = array(); - - if(count($arr)) { - foreach($arr as $x) { - if(! link_compare(trim($x),trim($_GET['unblock']))) - $newarr[] = $x; - } - } - $words = implode(',',$newarr); - } - - set_pconfig(local_user(),'blockem','words',$words); - info( t('blockem settings updated') . EOL ); - killme(); +function blockem_module() +{ +} + +function blockem_init(&$a) +{ + if (!local_user()) { + return; + } + + $words = get_pconfig(local_user(), 'blockem', 'words'); + + if (array_key_exists('block', $_GET) && $_GET['block']) { + if (strlen($words)) { + $words .= ','; + } + $words .= trim($_GET['block']); + } + if (array_key_exists('unblock', $_GET) && $_GET['unblock']) { + $arr = explode(',', $words); + $newarr = array(); + + if (count($arr)) { + foreach ($arr as $x) { + if (!link_compare(trim($x), trim($_GET['unblock']))) { + $newarr[] = $x; + } + } + } + $words = implode(',', $newarr); + } + + set_pconfig(local_user(), 'blockem', 'words', $words); + info(t('blockem settings updated').EOL); + killme(); } diff --git a/blockem/lang/ca/strings.php b/blockem/lang/ca/strings.php index 5587acd2..f6cfc6dd 100644 --- a/blockem/lang/ca/strings.php +++ b/blockem/lang/ca/strings.php @@ -1,10 +1,10 @@ -strings["\"Blockem\" Settings"] = "Configuració de \"Bloqueig\""; -$a->strings["Comma separated profile URLS to block"] = "URLS dels perfils a bloquejar, separats per comes"; -$a->strings["Submit"] = "Enviar"; -$a->strings["BLOCKEM Settings saved."] = "Guardada la configuració de BLOQUEIG."; -$a->strings["Blocked %s - Click to open/close"] = "Bloquejar %s - Clica per obrir/tancar"; -$a->strings["Unblock Author"] = "Desbloquejar Autor"; -$a->strings["Block Author"] = "Bloquejar Autor"; -$a->strings["blockem settings updated"] = "Actualitzar la Configuració de bloqueig"; +strings['"Blockem" Settings'] = 'Configuració de "Bloqueig"'; +$a->strings['Comma separated profile URLS to block'] = 'URLS dels perfils a bloquejar, separats per comes'; +$a->strings['Submit'] = 'Enviar'; +$a->strings['BLOCKEM Settings saved.'] = 'Guardada la configuració de BLOQUEIG.'; +$a->strings['Blocked %s - Click to open/close'] = 'Bloquejar %s - Clica per obrir/tancar'; +$a->strings['Unblock Author'] = 'Desbloquejar Autor'; +$a->strings['Block Author'] = 'Bloquejar Autor'; +$a->strings['blockem settings updated'] = 'Actualitzar la Configuració de bloqueig'; diff --git a/blockem/lang/cs/strings.php b/blockem/lang/cs/strings.php index fad08059..a34222d7 100644 --- a/blockem/lang/cs/strings.php +++ b/blockem/lang/cs/strings.php @@ -1,15 +1,17 @@ =2 && $n<=4) ? 1 : 2;; -}} -; -$a->strings["\"Blockem\""] = "\"Blockem\""; -$a->strings["Comma separated profile URLS to block"] = "Čárkou oddělené URL adresy profilů určených k ignorování"; -$a->strings["Save Settings"] = "Uložit Nastavení"; -$a->strings["BLOCKEM Settings saved."] = "BLOCKEM nastavení uloženo."; -$a->strings["Blocked %s - Click to open/close"] = "Blokován %s - Klikněte pro otevření/zavření"; -$a->strings["Unblock Author"] = "Odblokovat autora"; -$a->strings["Block Author"] = "Zablokovat autora"; -$a->strings["blockem settings updated"] = "blockem nastavení aktualizováno"; +if (!function_exists('string_plural_select_cs')) { + function string_plural_select_cs($n) + { + return ($n == 1) ? 0 : ($n >= 2 && $n <= 4) ? 1 : 2; + } +} + +$a->strings['"Blockem"'] = '"Blockem"'; +$a->strings['Comma separated profile URLS to block'] = 'Čárkou oddělené URL adresy profilů určených k ignorování'; +$a->strings['Save Settings'] = 'Uložit Nastavení'; +$a->strings['BLOCKEM Settings saved.'] = 'BLOCKEM nastavení uloženo.'; +$a->strings['Blocked %s - Click to open/close'] = 'Blokován %s - Klikněte pro otevření/zavření'; +$a->strings['Unblock Author'] = 'Odblokovat autora'; +$a->strings['Block Author'] = 'Zablokovat autora'; +$a->strings['blockem settings updated'] = 'blockem nastavení aktualizováno'; diff --git a/blockem/lang/de/strings.php b/blockem/lang/de/strings.php index d3089c4d..554e84b7 100644 --- a/blockem/lang/de/strings.php +++ b/blockem/lang/de/strings.php @@ -1,15 +1,17 @@ strings["\"Blockem\" Settings"] = "\"Blockem\"-Einstellungen"; -$a->strings["Comma separated profile URLS to block"] = "Profil-URLs, die geblockt werden sollen (durch Kommas getrennt)"; -$a->strings["Submit"] = "Senden"; -$a->strings["BLOCKEM Settings saved."] = "BLOCKEM-Einstellungen gesichert."; -$a->strings["Blocked %s - Click to open/close"] = "%s blockiert - Zum Öffnen/Schließen klicken"; -$a->strings["Unblock Author"] = "Autor freischalten"; -$a->strings["Block Author"] = "Autor blockieren"; -$a->strings["blockem settings updated"] = "blockem Einstellungen aktualisiert"; +if (!function_exists('string_plural_select_de')) { + function string_plural_select_de($n) + { + return $n != 1; + } +} + +$a->strings['"Blockem" Settings'] = '"Blockem"-Einstellungen'; +$a->strings['Comma separated profile URLS to block'] = 'Profil-URLs, die geblockt werden sollen (durch Kommas getrennt)'; +$a->strings['Submit'] = 'Senden'; +$a->strings['BLOCKEM Settings saved.'] = 'BLOCKEM-Einstellungen gesichert.'; +$a->strings['Blocked %s - Click to open/close'] = '%s blockiert - Zum Öffnen/Schließen klicken'; +$a->strings['Unblock Author'] = 'Autor freischalten'; +$a->strings['Block Author'] = 'Autor blockieren'; +$a->strings['blockem settings updated'] = 'blockem Einstellungen aktualisiert'; diff --git a/blockem/lang/eo/strings.php b/blockem/lang/eo/strings.php index b6116507..774c4301 100644 --- a/blockem/lang/eo/strings.php +++ b/blockem/lang/eo/strings.php @@ -1,10 +1,10 @@ -strings["\"Blockem\" Settings"] = "\"Blockem\" Agordoj"; -$a->strings["Comma separated profile URLS to block"] = "Blokotaj URL adresoj, disigita per komo"; -$a->strings["Submit"] = "Sendi"; -$a->strings["BLOCKEM Settings saved."] = "Konservis Agordojn de BLOCKEM."; -$a->strings["Blocked %s - Click to open/close"] = "%s blokita - Klaku por malfermi/fermi"; -$a->strings["Unblock Author"] = "Malbloki Aŭtoron"; -$a->strings["Block Author"] = "Bloki Aŭtoron"; -$a->strings["blockem settings updated"] = "Ĝisdatigis la blockem agordojn"; +strings['"Blockem" Settings'] = '"Blockem" Agordoj'; +$a->strings['Comma separated profile URLS to block'] = 'Blokotaj URL adresoj, disigita per komo'; +$a->strings['Submit'] = 'Sendi'; +$a->strings['BLOCKEM Settings saved.'] = 'Konservis Agordojn de BLOCKEM.'; +$a->strings['Blocked %s - Click to open/close'] = '%s blokita - Klaku por malfermi/fermi'; +$a->strings['Unblock Author'] = 'Malbloki Aŭtoron'; +$a->strings['Block Author'] = 'Bloki Aŭtoron'; +$a->strings['blockem settings updated'] = 'Ĝisdatigis la blockem agordojn'; diff --git a/blockem/lang/es/strings.php b/blockem/lang/es/strings.php index 3e4ab383..e8858926 100644 --- a/blockem/lang/es/strings.php +++ b/blockem/lang/es/strings.php @@ -1,15 +1,17 @@ strings["\"Blockem\""] = "\"Bloquealos\""; -$a->strings["Comma separated profile URLS to block"] = "URLS separados por coma para bloquear."; -$a->strings["Save Settings"] = "Guardar configuración"; -$a->strings["BLOCKEM Settings saved."] = "Configuración de BLOQUEALOS guardado."; -$a->strings["Blocked %s - Click to open/close"] = "%s bloqueado - click para abrir/cerrar"; -$a->strings["Unblock Author"] = "Desbloquear autor"; -$a->strings["Block Author"] = "Bloquear autor"; -$a->strings["blockem settings updated"] = "configuración de BLOQUEALOS actualizado"; +if (!function_exists('string_plural_select_es')) { + function string_plural_select_es($n) + { + return $n != 1; + } +} + +$a->strings['"Blockem"'] = '"Bloquealos"'; +$a->strings['Comma separated profile URLS to block'] = 'URLS separados por coma para bloquear.'; +$a->strings['Save Settings'] = 'Guardar configuración'; +$a->strings['BLOCKEM Settings saved.'] = 'Configuración de BLOQUEALOS guardado.'; +$a->strings['Blocked %s - Click to open/close'] = '%s bloqueado - click para abrir/cerrar'; +$a->strings['Unblock Author'] = 'Desbloquear autor'; +$a->strings['Block Author'] = 'Bloquear autor'; +$a->strings['blockem settings updated'] = 'configuración de BLOQUEALOS actualizado'; diff --git a/blockem/lang/fr/strings.php b/blockem/lang/fr/strings.php index b9f31180..b1936040 100644 --- a/blockem/lang/fr/strings.php +++ b/blockem/lang/fr/strings.php @@ -1,10 +1,10 @@ -strings["\"Blockem\" Settings"] = "Réglages de Blockem"; -$a->strings["Comma separated profile URLS to block"] = "Liste d'URLS de profils à bloquer, séparés par des virgules"; -$a->strings["Submit"] = "Envoyer"; -$a->strings["BLOCKEM Settings saved."] = "Réglages Blockem sauvés."; -$a->strings["Blocked %s - Click to open/close"] = "Bloqué %s - Cliquez pour ouvrir/fermer"; -$a->strings["Unblock Author"] = "Débloquer l'auteur"; -$a->strings["Block Author"] = "Bloquer l'auteur"; -$a->strings["blockem settings updated"] = "Réglages blockem sauvés"; +strings['"Blockem" Settings'] = 'Réglages de Blockem'; +$a->strings['Comma separated profile URLS to block'] = "Liste d'URLS de profils à bloquer, séparés par des virgules"; +$a->strings['Submit'] = 'Envoyer'; +$a->strings['BLOCKEM Settings saved.'] = 'Réglages Blockem sauvés.'; +$a->strings['Blocked %s - Click to open/close'] = 'Bloqué %s - Cliquez pour ouvrir/fermer'; +$a->strings['Unblock Author'] = "Débloquer l'auteur"; +$a->strings['Block Author'] = "Bloquer l'auteur"; +$a->strings['blockem settings updated'] = 'Réglages blockem sauvés'; diff --git a/blockem/lang/is/strings.php b/blockem/lang/is/strings.php index 3075c457..546de1de 100644 --- a/blockem/lang/is/strings.php +++ b/blockem/lang/is/strings.php @@ -1,10 +1,10 @@ -strings["\"Blockem\" Settings"] = "\"Blockem\" stillingar"; -$a->strings["Comma separated profile URLS to block"] = "Banna lista af forsíðum (komma á milli)"; -$a->strings["Submit"] = "Senda inn"; -$a->strings["BLOCKEM Settings saved."] = "BLOCKEM stillingar vistaðar."; -$a->strings["Blocked %s - Click to open/close"] = "%s sett í straff - Smella til að taka úr/setja á"; -$a->strings["Unblock Author"] = "Leyfa notanda"; -$a->strings["Block Author"] = "Banna notanda"; -$a->strings["blockem settings updated"] = ""; +strings['"Blockem" Settings'] = '"Blockem" stillingar'; +$a->strings['Comma separated profile URLS to block'] = 'Banna lista af forsíðum (komma á milli)'; +$a->strings['Submit'] = 'Senda inn'; +$a->strings['BLOCKEM Settings saved.'] = 'BLOCKEM stillingar vistaðar.'; +$a->strings['Blocked %s - Click to open/close'] = '%s sett í straff - Smella til að taka úr/setja á'; +$a->strings['Unblock Author'] = 'Leyfa notanda'; +$a->strings['Block Author'] = 'Banna notanda'; +$a->strings['blockem settings updated'] = ''; diff --git a/blockem/lang/it/strings.php b/blockem/lang/it/strings.php index 85f8a0ac..3a6b3a96 100644 --- a/blockem/lang/it/strings.php +++ b/blockem/lang/it/strings.php @@ -1,15 +1,17 @@ strings["\"Blockem\""] = "\"Blockem\""; -$a->strings["Comma separated profile URLS to block"] = "Lista, separata da virgola, di indirizzi da bloccare"; -$a->strings["Save Settings"] = "Salva Impostazioni"; -$a->strings["BLOCKEM Settings saved."] = "Impostazioni BLOCKEM salvate."; -$a->strings["Blocked %s - Click to open/close"] = "%s bloccato - Clicca per aprire/chiudere"; -$a->strings["Unblock Author"] = "Sblocca autore"; -$a->strings["Block Author"] = "Blocca autore"; -$a->strings["blockem settings updated"] = "Impostazioni 'blockem' aggiornate."; +if (!function_exists('string_plural_select_it')) { + function string_plural_select_it($n) + { + return $n != 1; + } +} + +$a->strings['"Blockem"'] = '"Blockem"'; +$a->strings['Comma separated profile URLS to block'] = 'Lista, separata da virgola, di indirizzi da bloccare'; +$a->strings['Save Settings'] = 'Salva Impostazioni'; +$a->strings['BLOCKEM Settings saved.'] = 'Impostazioni BLOCKEM salvate.'; +$a->strings['Blocked %s - Click to open/close'] = '%s bloccato - Clicca per aprire/chiudere'; +$a->strings['Unblock Author'] = 'Sblocca autore'; +$a->strings['Block Author'] = 'Blocca autore'; +$a->strings['blockem settings updated'] = "Impostazioni 'blockem' aggiornate."; diff --git a/blockem/lang/nb-no/strings.php b/blockem/lang/nb-no/strings.php index 0dd6660d..91a21c6c 100644 --- a/blockem/lang/nb-no/strings.php +++ b/blockem/lang/nb-no/strings.php @@ -1,10 +1,10 @@ -strings["\"Blockem\" Settings"] = ""; -$a->strings["Comma separated profile URLS to block"] = ""; -$a->strings["Submit"] = "Lagre"; -$a->strings["BLOCKEM Settings saved."] = ""; -$a->strings["Blocked %s - Click to open/close"] = ""; -$a->strings["Unblock Author"] = ""; -$a->strings["Block Author"] = ""; -$a->strings["blockem settings updated"] = ""; +strings['"Blockem" Settings'] = ''; +$a->strings['Comma separated profile URLS to block'] = ''; +$a->strings['Submit'] = 'Lagre'; +$a->strings['BLOCKEM Settings saved.'] = ''; +$a->strings['Blocked %s - Click to open/close'] = ''; +$a->strings['Unblock Author'] = ''; +$a->strings['Block Author'] = ''; +$a->strings['blockem settings updated'] = ''; diff --git a/blockem/lang/pl/strings.php b/blockem/lang/pl/strings.php index 6d7bcf19..8b54bae6 100644 --- a/blockem/lang/pl/strings.php +++ b/blockem/lang/pl/strings.php @@ -1,10 +1,10 @@ -strings["\"Blockem\" Settings"] = ""; -$a->strings["Comma separated profile URLS to block"] = ""; -$a->strings["Submit"] = "Potwierdź"; -$a->strings["BLOCKEM Settings saved."] = ""; -$a->strings["Blocked %s - Click to open/close"] = ""; -$a->strings["Unblock Author"] = "Odblokuj autora"; -$a->strings["Block Author"] = "Zablokuj autora"; -$a->strings["blockem settings updated"] = ""; +strings['"Blockem" Settings'] = ''; +$a->strings['Comma separated profile URLS to block'] = ''; +$a->strings['Submit'] = 'Potwierdź'; +$a->strings['BLOCKEM Settings saved.'] = ''; +$a->strings['Blocked %s - Click to open/close'] = ''; +$a->strings['Unblock Author'] = 'Odblokuj autora'; +$a->strings['Block Author'] = 'Zablokuj autora'; +$a->strings['blockem settings updated'] = ''; diff --git a/blockem/lang/pt-br/strings.php b/blockem/lang/pt-br/strings.php index 49f69cc3..9f4dc944 100644 --- a/blockem/lang/pt-br/strings.php +++ b/blockem/lang/pt-br/strings.php @@ -1,10 +1,10 @@ -strings["\"Blockem\" Settings"] = "Configurações \"Blockem\""; -$a->strings["Comma separated profile URLS to block"] = "URLS de perfis separados por vírgulas a serem bloqueados"; -$a->strings["Submit"] = "Enviar"; -$a->strings["BLOCKEM Settings saved."] = "Configurações BLOCKEM armazenadas."; -$a->strings["Blocked %s - Click to open/close"] = "Bloqueado %s - Clique para abrir/fechar"; -$a->strings["Unblock Author"] = "Desbloqueie Autor"; -$a->strings["Block Author"] = "Bloqueie Autor"; -$a->strings["blockem settings updated"] = "configurações blockem atualizadas"; +strings['"Blockem" Settings'] = 'Configurações "Blockem"'; +$a->strings['Comma separated profile URLS to block'] = 'URLS de perfis separados por vírgulas a serem bloqueados'; +$a->strings['Submit'] = 'Enviar'; +$a->strings['BLOCKEM Settings saved.'] = 'Configurações BLOCKEM armazenadas.'; +$a->strings['Blocked %s - Click to open/close'] = 'Bloqueado %s - Clique para abrir/fechar'; +$a->strings['Unblock Author'] = 'Desbloqueie Autor'; +$a->strings['Block Author'] = 'Bloqueie Autor'; +$a->strings['blockem settings updated'] = 'configurações blockem atualizadas'; diff --git a/blockem/lang/ro/strings.php b/blockem/lang/ro/strings.php index b842467d..5a1ca3d8 100644 --- a/blockem/lang/ro/strings.php +++ b/blockem/lang/ro/strings.php @@ -1,15 +1,17 @@ 19)||(($n%100==0)&&($n!=0)))?2:1));; -}} -; -$a->strings["\"Blockem\""] = "\"Blockem\""; -$a->strings["Comma separated profile URLS to block"] = "Adresele URL de profil, de blocat, separate prin virgulă"; -$a->strings["Save Settings"] = "Salvare Configurări"; -$a->strings["BLOCKEM Settings saved."] = "Configurările BLOCKEM au fost salvate."; -$a->strings["Blocked %s - Click to open/close"] = "%s Blocate - Apăsați pentru a deschide/închide"; -$a->strings["Unblock Author"] = "Deblocare Autor"; -$a->strings["Block Author"] = "Blocare Autor"; -$a->strings["blockem settings updated"] = "Configurările blockem au fost actualizate"; +if (!function_exists('string_plural_select_ro')) { + function string_plural_select_ro($n) + { + return $n == 1 ? 0 : ((($n % 100 > 19) || (($n % 100 == 0) && ($n != 0))) ? 2 : 1); + } +} + +$a->strings['"Blockem"'] = '"Blockem"'; +$a->strings['Comma separated profile URLS to block'] = 'Adresele URL de profil, de blocat, separate prin virgulă'; +$a->strings['Save Settings'] = 'Salvare Configurări'; +$a->strings['BLOCKEM Settings saved.'] = 'Configurările BLOCKEM au fost salvate.'; +$a->strings['Blocked %s - Click to open/close'] = '%s Blocate - Apăsați pentru a deschide/închide'; +$a->strings['Unblock Author'] = 'Deblocare Autor'; +$a->strings['Block Author'] = 'Blocare Autor'; +$a->strings['blockem settings updated'] = 'Configurările blockem au fost actualizate'; diff --git a/blockem/lang/ru/strings.php b/blockem/lang/ru/strings.php index 7617b865..d96cfd2c 100644 --- a/blockem/lang/ru/strings.php +++ b/blockem/lang/ru/strings.php @@ -1,10 +1,10 @@ -strings["\"Blockem\" Settings"] = "\"Blockem\" настройки"; -$a->strings["Comma separated profile URLS to block"] = "URLS, которые заблокировать (список через запятую)"; -$a->strings["Submit"] = "Подтвердить"; -$a->strings["BLOCKEM Settings saved."] = "BLOCKEM-Настройки сохранены."; -$a->strings["Blocked %s - Click to open/close"] = "Заблокированные %s - Нажмите, чтобы открыть/закрыть"; -$a->strings["Unblock Author"] = ""; -$a->strings["Block Author"] = "Блокировать Автора"; -$a->strings["blockem settings updated"] = "\"Blockem\" настройки обновлены"; +strings['"Blockem" Settings'] = '"Blockem" настройки'; +$a->strings['Comma separated profile URLS to block'] = 'URLS, которые заблокировать (список через запятую)'; +$a->strings['Submit'] = 'Подтвердить'; +$a->strings['BLOCKEM Settings saved.'] = 'BLOCKEM-Настройки сохранены.'; +$a->strings['Blocked %s - Click to open/close'] = 'Заблокированные %s - Нажмите, чтобы открыть/закрыть'; +$a->strings['Unblock Author'] = ''; +$a->strings['Block Author'] = 'Блокировать Автора'; +$a->strings['blockem settings updated'] = '"Blockem" настройки обновлены'; diff --git a/blockem/lang/sv/strings.php b/blockem/lang/sv/strings.php index 3ec569a7..4575a404 100644 --- a/blockem/lang/sv/strings.php +++ b/blockem/lang/sv/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Spara"; +strings['Submit'] = 'Spara'; diff --git a/blockem/lang/zh-cn/strings.php b/blockem/lang/zh-cn/strings.php index 3a3dfaeb..3ba67e71 100644 --- a/blockem/lang/zh-cn/strings.php +++ b/blockem/lang/zh-cn/strings.php @@ -1,10 +1,10 @@ -strings["\"Blockem\" Settings"] = "「Blockem」配置"; -$a->strings["Comma separated profile URLS to block"] = "逗号分简介URL为栏"; -$a->strings["Submit"] = "提交"; -$a->strings["BLOCKEM Settings saved."] = "「Blockem」配置保存了。"; -$a->strings["Blocked %s - Click to open/close"] = "%s拦了-点击为开关"; -$a->strings["Unblock Author"] = "不拦作家"; -$a->strings["Block Author"] = "拦作家"; -$a->strings["blockem settings updated"] = "blockem设置更新了"; +strings['"Blockem" Settings'] = '「Blockem」配置'; +$a->strings['Comma separated profile URLS to block'] = '逗号分简介URL为栏'; +$a->strings['Submit'] = '提交'; +$a->strings['BLOCKEM Settings saved.'] = '「Blockem」配置保存了。'; +$a->strings['Blocked %s - Click to open/close'] = '%s拦了-点击为开关'; +$a->strings['Unblock Author'] = '不拦作家'; +$a->strings['Block Author'] = '拦作家'; +$a->strings['blockem settings updated'] = 'blockem设置更新了'; diff --git a/blogger/blogger.php b/blogger/blogger.php index 87f58859..54c90b61 100755 --- a/blogger/blogger.php +++ b/blogger/blogger.php @@ -3,183 +3,181 @@ /** * Name: Blogger Post Connector * Description: Post to Blogger (or anything else which uses blogger XMLRPC API) - * Version: 1.0 - * + * Version: 1.0. */ - -function blogger_install() { +function blogger_install() +{ register_hook('post_local', 'addon/blogger/blogger.php', 'blogger_post_local'); register_hook('notifier_normal', 'addon/blogger/blogger.php', 'blogger_send'); register_hook('jot_networks', 'addon/blogger/blogger.php', 'blogger_jot_nets'); register_hook('connector_settings', 'addon/blogger/blogger.php', 'blogger_settings'); register_hook('connector_settings_post', 'addon/blogger/blogger.php', 'blogger_settings_post'); - } -function blogger_uninstall() { +function blogger_uninstall() +{ unregister_hook('post_local', 'addon/blogger/blogger.php', 'blogger_post_local'); unregister_hook('notifier_normal', 'addon/blogger/blogger.php', 'blogger_send'); unregister_hook('jot_networks', 'addon/blogger/blogger.php', 'blogger_jot_nets'); unregister_hook('connector_settings', 'addon/blogger/blogger.php', 'blogger_settings'); unregister_hook('connector_settings_post', 'addon/blogger/blogger.php', 'blogger_settings_post'); - // obsolete - remove + // obsolete - remove unregister_hook('post_local_end', 'addon/blogger/blogger.php', 'blogger_send'); unregister_hook('plugin_settings', 'addon/blogger/blogger.php', 'blogger_settings'); unregister_hook('plugin_settings_post', 'addon/blogger/blogger.php', 'blogger_settings_post'); - } - -function blogger_jot_nets(&$a,&$b) { - if(! local_user()) +function blogger_jot_nets(&$a, &$b) +{ + if (!local_user()) { return; + } - $bl_post = get_pconfig(local_user(),'blogger','post'); - if(intval($bl_post) == 1) { - $bl_defpost = get_pconfig(local_user(),'blogger','post_by_default'); + $bl_post = get_pconfig(local_user(), 'blogger', 'post'); + if (intval($bl_post) == 1) { + $bl_defpost = get_pconfig(local_user(), 'blogger', 'post_by_default'); $selected = ((intval($bl_defpost) == 1) ? ' checked="checked" ' : ''); - $b .= '
' - . t('Post to blogger') . '
'; + $b .= '
' + .t('Post to blogger').'
'; } } - -function blogger_settings(&$a,&$s) { - - if(! local_user()) +function blogger_settings(&$a, &$s) +{ + if (!local_user()) { return; + } /* Add our stylesheet to the page so we can make our settings look nice */ - $a->page['htmlhead'] .= '' . "\r\n"; + $a->page['htmlhead'] .= ''."\r\n"; /* Get the current state of our config variables */ - $enabled = get_pconfig(local_user(),'blogger','post'); + $enabled = get_pconfig(local_user(), 'blogger', 'post'); $checked = (($enabled) ? ' checked="checked" ' : ''); $css = (($enabled) ? '' : '-disabled'); - $def_enabled = get_pconfig(local_user(),'blogger','post_by_default'); + $def_enabled = get_pconfig(local_user(), 'blogger', 'post_by_default'); $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); - $bl_username = get_pconfig(local_user(), 'blogger', 'bl_username'); - $bl_password = get_pconfig(local_user(), 'blogger', 'bl_password'); - $bl_blog = get_pconfig(local_user(), 'blogger', 'bl_blog'); - + $bl_username = get_pconfig(local_user(), 'blogger', 'bl_username'); + $bl_password = get_pconfig(local_user(), 'blogger', 'bl_password'); + $bl_blog = get_pconfig(local_user(), 'blogger', 'bl_blog'); /* Add some HTML to the existing form */ $s .= ''; - $s .= '

'. t('Blogger Export').'

'; + $s .= '

'.t('Blogger Export').'

'; $s .= '
'; $s .= ''; - + $s .= '
'; } - -function blogger_settings_post(&$a,&$b) { - - if(x($_POST,'blogger-submit')) { - - set_pconfig(local_user(),'blogger','post',intval($_POST['blogger'])); - set_pconfig(local_user(),'blogger','post_by_default',intval($_POST['bl_bydefault'])); - set_pconfig(local_user(),'blogger','bl_username',trim($_POST['bl_username'])); - set_pconfig(local_user(),'blogger','bl_password',trim($_POST['bl_password'])); - set_pconfig(local_user(),'blogger','bl_blog',trim($_POST['bl_blog'])); - - } - +function blogger_settings_post(&$a, &$b) +{ + if (x($_POST, 'blogger-submit')) { + set_pconfig(local_user(), 'blogger', 'post', intval($_POST['blogger'])); + set_pconfig(local_user(), 'blogger', 'post_by_default', intval($_POST['bl_bydefault'])); + set_pconfig(local_user(), 'blogger', 'bl_username', trim($_POST['bl_username'])); + set_pconfig(local_user(), 'blogger', 'bl_password', trim($_POST['bl_password'])); + set_pconfig(local_user(), 'blogger', 'bl_blog', trim($_POST['bl_blog'])); + } } -function blogger_post_local(&$a,&$b) { +function blogger_post_local(&$a, &$b) +{ - // This can probably be changed to allow editing by pointing to a different API endpoint + // This can probably be changed to allow editing by pointing to a different API endpoint - if($b['edit']) - return; + if ($b['edit']) { + return; + } - if((! local_user()) || (local_user() != $b['uid'])) - return; + if ((!local_user()) || (local_user() != $b['uid'])) { + return; + } - if($b['private'] || $b['parent']) - return; + if ($b['private'] || $b['parent']) { + return; + } - $bl_post = intval(get_pconfig(local_user(),'blogger','post')); + $bl_post = intval(get_pconfig(local_user(), 'blogger', 'post')); - $bl_enable = (($bl_post && x($_REQUEST,'blogger_enable')) ? intval($_REQUEST['blogger_enable']) : 0); + $bl_enable = (($bl_post && x($_REQUEST, 'blogger_enable')) ? intval($_REQUEST['blogger_enable']) : 0); - if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'blogger','post_by_default'))) - $bl_enable = 1; + if ($_REQUEST['api_source'] && intval(get_pconfig(local_user(), 'blogger', 'post_by_default'))) { + $bl_enable = 1; + } - if(! $bl_enable) - return; + if (!$bl_enable) { + return; + } - if(strlen($b['postopts'])) - $b['postopts'] .= ','; - $b['postopts'] .= 'blogger'; + if (strlen($b['postopts'])) { + $b['postopts'] .= ','; + } + $b['postopts'] .= 'blogger'; } - - - -function blogger_send(&$a,&$b) { - - if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) +function blogger_send(&$a, &$b) +{ + if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) { return; + } - if(! strstr($b['postopts'],'blogger')) + if (!strstr($b['postopts'], 'blogger')) { return; + } - if($b['parent'] != $b['id']) + if ($b['parent'] != $b['id']) { return; + } + $bl_username = xmlify(get_pconfig($b['uid'], 'blogger', 'bl_username')); + $bl_password = xmlify(get_pconfig($b['uid'], 'blogger', 'bl_password')); + $bl_blog = get_pconfig($b['uid'], 'blogger', 'bl_blog'); - $bl_username = xmlify(get_pconfig($b['uid'],'blogger','bl_username')); - $bl_password = xmlify(get_pconfig($b['uid'],'blogger','bl_password')); - $bl_blog = get_pconfig($b['uid'],'blogger','bl_blog'); + if ($bl_username && $bl_password && $bl_blog) { + require_once 'include/bbcode.php'; - if($bl_username && $bl_password && $bl_blog) { + $title = ''.(($b['title']) ? $b['title'] : t('Post from Friendica')).''; + $post = $title.bbcode($b['body']); + $post = xmlify($post); - require_once('include/bbcode.php'); - - $title = '' . (($b['title']) ? $b['title'] : t('Post from Friendica')) . ''; - $post = $title . bbcode($b['body']); - $post = xmlify($post); - - $xml = <<< EOT + $xml = <<< EOT blogger.newPost @@ -195,12 +193,11 @@ function blogger_send(&$a,&$b) { EOT; - logger('blogger: data: ' . $xml, LOGGER_DATA); + logger('blogger: data: '.$xml, LOGGER_DATA); - if($bl_blog !== 'test') - $x = post_url($bl_blog,$xml); - logger('posted to blogger: ' . (($x) ? $x : ''), LOGGER_DEBUG); - - } + if ($bl_blog !== 'test') { + $x = post_url($bl_blog, $xml); + } + logger('posted to blogger: '.(($x) ? $x : ''), LOGGER_DEBUG); + } } - diff --git a/blogger/lang/ca/strings.php b/blogger/lang/ca/strings.php index 354d354a..a89b2f26 100644 --- a/blogger/lang/ca/strings.php +++ b/blogger/lang/ca/strings.php @@ -1,11 +1,11 @@ -strings["Post to blogger"] = "Enviament a blogger"; -$a->strings["Blogger Post Settings"] = "Ajustos d'enviament a blogger"; -$a->strings["Enable Blogger Post Plugin"] = "Habilita el Plugin d'Enviaments a Blogger"; -$a->strings["Blogger username"] = "Nom d'usuari a blogger"; -$a->strings["Blogger password"] = "Contrasenya a blogger"; -$a->strings["Blogger API URL"] = "Blogger API URL"; -$a->strings["Post to Blogger by default"] = "Enviament a Blogger per defecte"; -$a->strings["Submit"] = "Enviar"; -$a->strings["Post from Friendica"] = "Enviament des de Friendica"; +strings['Post to blogger'] = 'Enviament a blogger'; +$a->strings['Blogger Post Settings'] = "Ajustos d'enviament a blogger"; +$a->strings['Enable Blogger Post Plugin'] = "Habilita el Plugin d'Enviaments a Blogger"; +$a->strings['Blogger username'] = "Nom d'usuari a blogger"; +$a->strings['Blogger password'] = 'Contrasenya a blogger'; +$a->strings['Blogger API URL'] = 'Blogger API URL'; +$a->strings['Post to Blogger by default'] = 'Enviament a Blogger per defecte'; +$a->strings['Submit'] = 'Enviar'; +$a->strings['Post from Friendica'] = 'Enviament des de Friendica'; diff --git a/blogger/lang/de/strings.php b/blogger/lang/de/strings.php index 8e44b4c2..9fff4e10 100644 --- a/blogger/lang/de/strings.php +++ b/blogger/lang/de/strings.php @@ -1,16 +1,18 @@ strings["Post to blogger"] = "Auf Blogger posten"; -$a->strings["Blogger Export"] = "Blogger Export"; -$a->strings["Enable Blogger Post Plugin"] = "Blogger-Post-Plugin aktivieren"; -$a->strings["Blogger username"] = "Blogger-Benutzername"; -$a->strings["Blogger password"] = "Blogger-Passwort"; -$a->strings["Blogger API URL"] = "Blogger-API-URL"; -$a->strings["Post to Blogger by default"] = "Standardmäßig auf Blogger posten"; -$a->strings["Save Settings"] = "Einstellungen speichern"; -$a->strings["Post from Friendica"] = "Post via Friendica"; +if (!function_exists('string_plural_select_de')) { + function string_plural_select_de($n) + { + return $n != 1; + } +} + +$a->strings['Post to blogger'] = 'Auf Blogger posten'; +$a->strings['Blogger Export'] = 'Blogger Export'; +$a->strings['Enable Blogger Post Plugin'] = 'Blogger-Post-Plugin aktivieren'; +$a->strings['Blogger username'] = 'Blogger-Benutzername'; +$a->strings['Blogger password'] = 'Blogger-Passwort'; +$a->strings['Blogger API URL'] = 'Blogger-API-URL'; +$a->strings['Post to Blogger by default'] = 'Standardmäßig auf Blogger posten'; +$a->strings['Save Settings'] = 'Einstellungen speichern'; +$a->strings['Post from Friendica'] = 'Post via Friendica'; diff --git a/blogger/lang/eo/strings.php b/blogger/lang/eo/strings.php index 5ab29790..5c145dae 100644 --- a/blogger/lang/eo/strings.php +++ b/blogger/lang/eo/strings.php @@ -1,11 +1,11 @@ -strings["Post to blogger"] = "Afiŝi al blogger"; -$a->strings["Blogger Post Settings"] = "Agordo pri Blogger Afiŝoj"; -$a->strings["Enable Blogger Post Plugin"] = "Ŝalti la Blogger afiŝo kromprogramon"; -$a->strings["Blogger username"] = "Blogger uzantonomo"; -$a->strings["Blogger password"] = "Blogger pasvorto"; -$a->strings["Blogger API URL"] = "Blogger API URL"; -$a->strings["Post to Blogger by default"] = "Defaŭlte afiŝi al Blogger"; -$a->strings["Submit"] = "Sendi"; -$a->strings["Post from Friendica"] = "Afiŝo de Friendica"; +strings['Post to blogger'] = 'Afiŝi al blogger'; +$a->strings['Blogger Post Settings'] = 'Agordo pri Blogger Afiŝoj'; +$a->strings['Enable Blogger Post Plugin'] = 'Ŝalti la Blogger afiŝo kromprogramon'; +$a->strings['Blogger username'] = 'Blogger uzantonomo'; +$a->strings['Blogger password'] = 'Blogger pasvorto'; +$a->strings['Blogger API URL'] = 'Blogger API URL'; +$a->strings['Post to Blogger by default'] = 'Defaŭlte afiŝi al Blogger'; +$a->strings['Submit'] = 'Sendi'; +$a->strings['Post from Friendica'] = 'Afiŝo de Friendica'; diff --git a/blogger/lang/es/strings.php b/blogger/lang/es/strings.php index 3ef963d9..80025d31 100644 --- a/blogger/lang/es/strings.php +++ b/blogger/lang/es/strings.php @@ -1,11 +1,11 @@ -strings["Post to blogger"] = "Publícar en Blogger"; -$a->strings["Blogger Post Settings"] = "Configuración de las publicaciones en Blogger"; -$a->strings["Enable Blogger Post Plugin"] = "Activar el módulo de publicación en Blogger"; -$a->strings["Blogger username"] = "Nombre de usuario de Blogger"; -$a->strings["Blogger password"] = "Contraseña de Blogger"; -$a->strings["Blogger API URL"] = "Dirección de la API de Blogger"; -$a->strings["Post to Blogger by default"] = "Publicar en Blogger por defecto"; -$a->strings["Submit"] = "Envíar"; -$a->strings["Post from Friendica"] = "Publicado desde Friendica"; +strings['Post to blogger'] = 'Publícar en Blogger'; +$a->strings['Blogger Post Settings'] = 'Configuración de las publicaciones en Blogger'; +$a->strings['Enable Blogger Post Plugin'] = 'Activar el módulo de publicación en Blogger'; +$a->strings['Blogger username'] = 'Nombre de usuario de Blogger'; +$a->strings['Blogger password'] = 'Contraseña de Blogger'; +$a->strings['Blogger API URL'] = 'Dirección de la API de Blogger'; +$a->strings['Post to Blogger by default'] = 'Publicar en Blogger por defecto'; +$a->strings['Submit'] = 'Envíar'; +$a->strings['Post from Friendica'] = 'Publicado desde Friendica'; diff --git a/blogger/lang/fr/strings.php b/blogger/lang/fr/strings.php index 2265182a..df7fee71 100644 --- a/blogger/lang/fr/strings.php +++ b/blogger/lang/fr/strings.php @@ -1,16 +1,18 @@ 1);; -}} -; -$a->strings["Post to blogger"] = "Poster sur Blogger"; -$a->strings["Blogger Export"] = ""; -$a->strings["Enable Blogger Post Plugin"] = "Activer le connecteur Blogger"; -$a->strings["Blogger username"] = "Nom d'utilisateur Blogger"; -$a->strings["Blogger password"] = "Mot de passe Blogger"; -$a->strings["Blogger API URL"] = "URL de l'API de Blogger"; -$a->strings["Post to Blogger by default"] = ""; -$a->strings["Save Settings"] = "Sauvegarder les paramètres"; -$a->strings["Post from Friendica"] = ""; +if (!function_exists('string_plural_select_fr')) { + function string_plural_select_fr($n) + { + return $n > 1; + } +} + +$a->strings['Post to blogger'] = 'Poster sur Blogger'; +$a->strings['Blogger Export'] = ''; +$a->strings['Enable Blogger Post Plugin'] = 'Activer le connecteur Blogger'; +$a->strings['Blogger username'] = "Nom d'utilisateur Blogger"; +$a->strings['Blogger password'] = 'Mot de passe Blogger'; +$a->strings['Blogger API URL'] = "URL de l'API de Blogger"; +$a->strings['Post to Blogger by default'] = ''; +$a->strings['Save Settings'] = 'Sauvegarder les paramètres'; +$a->strings['Post from Friendica'] = ''; diff --git a/blogger/lang/is/strings.php b/blogger/lang/is/strings.php index 01f532f6..c5ab6464 100644 --- a/blogger/lang/is/strings.php +++ b/blogger/lang/is/strings.php @@ -1,16 +1,18 @@ strings["Post to blogger"] = "Senda færslu á bloggara"; -$a->strings["Blogger Export"] = "Flytja út blogg"; -$a->strings["Enable Blogger Post Plugin"] = "Virkja sendiviðbót fyrir blogg"; -$a->strings["Blogger username"] = "Notandanafn bloggara"; -$a->strings["Blogger password"] = "Aðgangsorð bloggara"; -$a->strings["Blogger API URL"] = "API slóð bloggs"; -$a->strings["Post to Blogger by default"] = "Sjálfgefið láta færslur flæða inn á blogg"; -$a->strings["Save Settings"] = "Vista stillingar"; -$a->strings["Post from Friendica"] = "Færslur frá Friendica"; +if (!function_exists('string_plural_select_is')) { + function string_plural_select_is($n) + { + return $n % 10 != 1 || $n % 100 == 11; + } +} + +$a->strings['Post to blogger'] = 'Senda færslu á bloggara'; +$a->strings['Blogger Export'] = 'Flytja út blogg'; +$a->strings['Enable Blogger Post Plugin'] = 'Virkja sendiviðbót fyrir blogg'; +$a->strings['Blogger username'] = 'Notandanafn bloggara'; +$a->strings['Blogger password'] = 'Aðgangsorð bloggara'; +$a->strings['Blogger API URL'] = 'API slóð bloggs'; +$a->strings['Post to Blogger by default'] = 'Sjálfgefið láta færslur flæða inn á blogg'; +$a->strings['Save Settings'] = 'Vista stillingar'; +$a->strings['Post from Friendica'] = 'Færslur frá Friendica'; diff --git a/blogger/lang/it/strings.php b/blogger/lang/it/strings.php index deea28a5..41b5b7d7 100644 --- a/blogger/lang/it/strings.php +++ b/blogger/lang/it/strings.php @@ -1,16 +1,18 @@ strings["Post to blogger"] = "Invia a Blogger"; -$a->strings["Blogger Export"] = "Esporta Blogger"; -$a->strings["Enable Blogger Post Plugin"] = "Abilita il plugin di invio a Blogger"; -$a->strings["Blogger username"] = "Nome utente Blogger"; -$a->strings["Blogger password"] = "Password Blogger"; -$a->strings["Blogger API URL"] = "Indirizzo API Blogger"; -$a->strings["Post to Blogger by default"] = "Invia sempre a Blogger"; -$a->strings["Save Settings"] = "Salva Impostazioni"; -$a->strings["Post from Friendica"] = "Messaggio da Friendica"; +if (!function_exists('string_plural_select_it')) { + function string_plural_select_it($n) + { + return $n != 1; + } +} + +$a->strings['Post to blogger'] = 'Invia a Blogger'; +$a->strings['Blogger Export'] = 'Esporta Blogger'; +$a->strings['Enable Blogger Post Plugin'] = 'Abilita il plugin di invio a Blogger'; +$a->strings['Blogger username'] = 'Nome utente Blogger'; +$a->strings['Blogger password'] = 'Password Blogger'; +$a->strings['Blogger API URL'] = 'Indirizzo API Blogger'; +$a->strings['Post to Blogger by default'] = 'Invia sempre a Blogger'; +$a->strings['Save Settings'] = 'Salva Impostazioni'; +$a->strings['Post from Friendica'] = 'Messaggio da Friendica'; diff --git a/blogger/lang/nb-no/strings.php b/blogger/lang/nb-no/strings.php index de7246bc..c38826e5 100644 --- a/blogger/lang/nb-no/strings.php +++ b/blogger/lang/nb-no/strings.php @@ -1,11 +1,11 @@ -strings["Post to blogger"] = ""; -$a->strings["Blogger Post Settings"] = ""; -$a->strings["Enable Blogger Post Plugin"] = ""; -$a->strings["Blogger username"] = ""; -$a->strings["Blogger password"] = ""; -$a->strings["Blogger API URL"] = ""; -$a->strings["Post to Blogger by default"] = ""; -$a->strings["Submit"] = "Lagre"; -$a->strings["Post from Friendica"] = ""; +strings['Post to blogger'] = ''; +$a->strings['Blogger Post Settings'] = ''; +$a->strings['Enable Blogger Post Plugin'] = ''; +$a->strings['Blogger username'] = ''; +$a->strings['Blogger password'] = ''; +$a->strings['Blogger API URL'] = ''; +$a->strings['Post to Blogger by default'] = ''; +$a->strings['Submit'] = 'Lagre'; +$a->strings['Post from Friendica'] = ''; diff --git a/blogger/lang/pl/strings.php b/blogger/lang/pl/strings.php index a08b447b..de60bdb8 100644 --- a/blogger/lang/pl/strings.php +++ b/blogger/lang/pl/strings.php @@ -1,11 +1,11 @@ -strings["Post to blogger"] = "Post na blogger"; -$a->strings["Blogger Post Settings"] = "Ustawienia postów na Blogger"; -$a->strings["Enable Blogger Post Plugin"] = ""; -$a->strings["Blogger username"] = "Nazwa użytkownika na Blogger"; -$a->strings["Blogger password"] = "Hasło do Blogger"; -$a->strings["Blogger API URL"] = ""; -$a->strings["Post to Blogger by default"] = ""; -$a->strings["Submit"] = "Potwierdź"; -$a->strings["Post from Friendica"] = "Post z Friendica"; +strings['Post to blogger'] = 'Post na blogger'; +$a->strings['Blogger Post Settings'] = 'Ustawienia postów na Blogger'; +$a->strings['Enable Blogger Post Plugin'] = ''; +$a->strings['Blogger username'] = 'Nazwa użytkownika na Blogger'; +$a->strings['Blogger password'] = 'Hasło do Blogger'; +$a->strings['Blogger API URL'] = ''; +$a->strings['Post to Blogger by default'] = ''; +$a->strings['Submit'] = 'Potwierdź'; +$a->strings['Post from Friendica'] = 'Post z Friendica'; diff --git a/blogger/lang/pt-br/strings.php b/blogger/lang/pt-br/strings.php index dcd10fab..4a408619 100644 --- a/blogger/lang/pt-br/strings.php +++ b/blogger/lang/pt-br/strings.php @@ -1,16 +1,18 @@ 1);; -}} -; -$a->strings["Post to blogger"] = "Publicar no Blogger"; -$a->strings["Blogger Export"] = "Exportador Blogger"; -$a->strings["Enable Blogger Post Plugin"] = "Habilitar plug-in para publicar no Blogger"; -$a->strings["Blogger username"] = "Nome de usuário no Blogger"; -$a->strings["Blogger password"] = "Senha do Blogger"; -$a->strings["Blogger API URL"] = "URL da API do Blogger"; -$a->strings["Post to Blogger by default"] = "Publicar no Blogger por padrão"; -$a->strings["Save Settings"] = "Salvar Configurações"; -$a->strings["Post from Friendica"] = "Postar a partir de Friendica"; +if (!function_exists('string_plural_select_pt_br')) { + function string_plural_select_pt_br($n) + { + return $n > 1; + } +} + +$a->strings['Post to blogger'] = 'Publicar no Blogger'; +$a->strings['Blogger Export'] = 'Exportador Blogger'; +$a->strings['Enable Blogger Post Plugin'] = 'Habilitar plug-in para publicar no Blogger'; +$a->strings['Blogger username'] = 'Nome de usuário no Blogger'; +$a->strings['Blogger password'] = 'Senha do Blogger'; +$a->strings['Blogger API URL'] = 'URL da API do Blogger'; +$a->strings['Post to Blogger by default'] = 'Publicar no Blogger por padrão'; +$a->strings['Save Settings'] = 'Salvar Configurações'; +$a->strings['Post from Friendica'] = 'Postar a partir de Friendica'; diff --git a/blogger/lang/ro/strings.php b/blogger/lang/ro/strings.php index f89fd4b9..0a382b8c 100644 --- a/blogger/lang/ro/strings.php +++ b/blogger/lang/ro/strings.php @@ -1,16 +1,18 @@ 19)||(($n%100==0)&&($n!=0)))?2:1));; -}} -; -$a->strings["Post to blogger"] = "Postați pe Blogger"; -$a->strings["Blogger Export"] = "Export pe Blogger "; -$a->strings["Enable Blogger Post Plugin"] = "Activare Modul Postare pe Blogger "; -$a->strings["Blogger username"] = "Utilizator Blogger"; -$a->strings["Blogger password"] = "Parolă Blogger "; -$a->strings["Blogger API URL"] = "URL Cheie API Blogger "; -$a->strings["Post to Blogger by default"] = "Postați implicit pe Blogger"; -$a->strings["Save Settings"] = "Salvare Configurări"; -$a->strings["Post from Friendica"] = "Postați din Friendica"; +if (!function_exists('string_plural_select_ro')) { + function string_plural_select_ro($n) + { + return $n == 1 ? 0 : ((($n % 100 > 19) || (($n % 100 == 0) && ($n != 0))) ? 2 : 1); + } +} + +$a->strings['Post to blogger'] = 'Postați pe Blogger'; +$a->strings['Blogger Export'] = 'Export pe Blogger '; +$a->strings['Enable Blogger Post Plugin'] = 'Activare Modul Postare pe Blogger '; +$a->strings['Blogger username'] = 'Utilizator Blogger'; +$a->strings['Blogger password'] = 'Parolă Blogger '; +$a->strings['Blogger API URL'] = 'URL Cheie API Blogger '; +$a->strings['Post to Blogger by default'] = 'Postați implicit pe Blogger'; +$a->strings['Save Settings'] = 'Salvare Configurări'; +$a->strings['Post from Friendica'] = 'Postați din Friendica'; diff --git a/blogger/lang/ru/strings.php b/blogger/lang/ru/strings.php index 086d83b4..da72b261 100644 --- a/blogger/lang/ru/strings.php +++ b/blogger/lang/ru/strings.php @@ -1,11 +1,11 @@ -strings["Post to blogger"] = ""; -$a->strings["Blogger Post Settings"] = ""; -$a->strings["Enable Blogger Post Plugin"] = ""; -$a->strings["Blogger username"] = ""; -$a->strings["Blogger password"] = ""; -$a->strings["Blogger API URL"] = ""; -$a->strings["Post to Blogger by default"] = ""; -$a->strings["Submit"] = "Подтвердить"; -$a->strings["Post from Friendica"] = "Сообщение от Friendica"; +strings['Post to blogger'] = ''; +$a->strings['Blogger Post Settings'] = ''; +$a->strings['Enable Blogger Post Plugin'] = ''; +$a->strings['Blogger username'] = ''; +$a->strings['Blogger password'] = ''; +$a->strings['Blogger API URL'] = ''; +$a->strings['Post to Blogger by default'] = ''; +$a->strings['Submit'] = 'Подтвердить'; +$a->strings['Post from Friendica'] = 'Сообщение от Friendica'; diff --git a/blogger/lang/sv/strings.php b/blogger/lang/sv/strings.php index 3ec569a7..4575a404 100644 --- a/blogger/lang/sv/strings.php +++ b/blogger/lang/sv/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Spara"; +strings['Submit'] = 'Spara'; diff --git a/blogger/lang/zh-cn/strings.php b/blogger/lang/zh-cn/strings.php index 6134a7d1..d6ad6bd0 100644 --- a/blogger/lang/zh-cn/strings.php +++ b/blogger/lang/zh-cn/strings.php @@ -1,11 +1,11 @@ -strings["Post to blogger"] = "转播到blogger"; -$a->strings["Blogger Post Settings"] = "Blogger转播设置"; -$a->strings["Enable Blogger Post Plugin"] = "使Blogger转播插件可用"; -$a->strings["Blogger username"] = "Blogger用户名"; -$a->strings["Blogger password"] = "Blogger密码"; -$a->strings["Blogger API URL"] = "Blogger API URL"; -$a->strings["Post to Blogger by default"] = "默认地转播到Blogger"; -$a->strings["Submit"] = "提交"; -$a->strings["Post from Friendica"] = "文章从Friendica"; +strings['Post to blogger'] = '转播到blogger'; +$a->strings['Blogger Post Settings'] = 'Blogger转播设置'; +$a->strings['Enable Blogger Post Plugin'] = '使Blogger转播插件可用'; +$a->strings['Blogger username'] = 'Blogger用户名'; +$a->strings['Blogger password'] = 'Blogger密码'; +$a->strings['Blogger API URL'] = 'Blogger API URL'; +$a->strings['Post to Blogger by default'] = '默认地转播到Blogger'; +$a->strings['Submit'] = '提交'; +$a->strings['Post from Friendica'] = '文章从Friendica'; diff --git a/buffer/buffer.php b/buffer/buffer.php index 162600d6..be96e9a5 100644 --- a/buffer/buffer.php +++ b/buffer/buffer.php @@ -3,384 +3,415 @@ * Name: Buffer Post Connector * Description: Post to Buffer (Linkedin, App.net, Google+, Facebook, Twitter) * Version: 0.2 - * Author: Michael Vogel + * Author: Michael Vogel . */ -require('addon/buffer/bufferapp.php'); +require 'addon/buffer/bufferapp.php'; -function buffer_install() { - register_hook('post_local', 'addon/buffer/buffer.php', 'buffer_post_local'); - register_hook('notifier_normal', 'addon/buffer/buffer.php', 'buffer_send'); - register_hook('jot_networks', 'addon/buffer/buffer.php', 'buffer_jot_nets'); - register_hook('connector_settings', 'addon/buffer/buffer.php', 'buffer_settings'); - register_hook('connector_settings_post', 'addon/buffer/buffer.php', 'buffer_settings_post'); +function buffer_install() +{ + register_hook('post_local', 'addon/buffer/buffer.php', 'buffer_post_local'); + register_hook('notifier_normal', 'addon/buffer/buffer.php', 'buffer_send'); + register_hook('jot_networks', 'addon/buffer/buffer.php', 'buffer_jot_nets'); + register_hook('connector_settings', 'addon/buffer/buffer.php', 'buffer_settings'); + register_hook('connector_settings_post', 'addon/buffer/buffer.php', 'buffer_settings_post'); } -function buffer_uninstall() { - unregister_hook('post_local', 'addon/buffer/buffer.php', 'buffer_post_local'); - unregister_hook('notifier_normal', 'addon/buffer/buffer.php', 'buffer_send'); - unregister_hook('jot_networks', 'addon/buffer/buffer.php', 'buffer_jot_nets'); - unregister_hook('connector_settings', 'addon/buffer/buffer.php', 'buffer_settings'); - unregister_hook('connector_settings_post', 'addon/buffer/buffer.php', 'buffer_settings_post'); +function buffer_uninstall() +{ + unregister_hook('post_local', 'addon/buffer/buffer.php', 'buffer_post_local'); + unregister_hook('notifier_normal', 'addon/buffer/buffer.php', 'buffer_send'); + unregister_hook('jot_networks', 'addon/buffer/buffer.php', 'buffer_jot_nets'); + unregister_hook('connector_settings', 'addon/buffer/buffer.php', 'buffer_settings'); + unregister_hook('connector_settings_post', 'addon/buffer/buffer.php', 'buffer_settings_post'); } -function buffer_module() {} - -function buffer_content(&$a) { - - if(! local_user()) { - notice( t('Permission denied.') . EOL); - return ''; - } - - require_once("mod/settings.php"); - settings_init($a); - - if (isset($a->argv[1])) - switch ($a->argv[1]) { - case "connect": - $o = buffer_connect($a); - break; - default: - $o = print_r($a->argv, true); - break; - } - else - $o = buffer_connect($a); - - return $o; +function buffer_module() +{ } -function buffer_plugin_admin(&$a, &$o){ - $t = get_markup_template( "admin.tpl", "addon/buffer/" ); +function buffer_content(&$a) +{ + if (!local_user()) { + notice(t('Permission denied.').EOL); - $o = replace_macros($t, array( - '$submit' => t('Save Settings'), - // name, label, value, help, [extra values] - '$client_id' => array('client_id', t('Client ID'), get_config('buffer', 'client_id' ), ''), - '$client_secret' => array('client_secret', t('Client Secret'), get_config('buffer', 'client_secret' ), ''), - )); -} -function buffer_plugin_admin_post(&$a){ - $client_id = ((x($_POST,'client_id')) ? notags(trim($_POST['client_id'])) : ''); - $client_secret = ((x($_POST,'client_secret')) ? notags(trim($_POST['client_secret'])): ''); - set_config('buffer','client_id',$client_id); - set_config('buffer','client_secret',$client_secret); - info( t('Settings updated.'). EOL ); + return ''; + } + + require_once 'mod/settings.php'; + settings_init($a); + + if (isset($a->argv[1])) { + switch ($a->argv[1]) { + case 'connect': + $o = buffer_connect($a); + break; + default: + $o = print_r($a->argv, true); + break; + } + } else { + $o = buffer_connect($a); + } + + return $o; } -function buffer_connect(&$a) { +function buffer_plugin_admin(&$a, &$o) +{ + $t = get_markup_template('admin.tpl', 'addon/buffer/'); - if (isset($_REQUEST["error"])) { - $o = t('Error when registering buffer connection:')." ".$_REQUEST["error"]; - return $o; - } - // Start a session. This is necessary to hold on to a few keys the callback script will also need - session_start(); - - // Define the needed keys - $client_id = get_config('buffer','client_id'); - $client_secret = get_config('buffer','client_secret'); - - // The callback URL is the script that gets called after the user authenticates with buffer - $callback_url = $a->get_baseurl()."/buffer/connect"; - - $buffer = new BufferApp($client_id, $client_secret, $callback_url); - - if (!$buffer->ok) { - $o .= 'Connect to Buffer!'; - } else { - logger("buffer_connect: authenticated"); - $o .= t("You are now authenticated to buffer. "); - $o .= '
'.t("return to the connector page").''; - set_pconfig(local_user(), 'buffer','access_token', $buffer->access_token); - } - - return($o); + $o = replace_macros($t, array( + '$submit' => t('Save Settings'), + // name, label, value, help, [extra values] + '$client_id' => array('client_id', t('Client ID'), get_config('buffer', 'client_id'), ''), + '$client_secret' => array('client_secret', t('Client Secret'), get_config('buffer', 'client_secret'), ''), + )); +} +function buffer_plugin_admin_post(&$a) +{ + $client_id = ((x($_POST, 'client_id')) ? notags(trim($_POST['client_id'])) : ''); + $client_secret = ((x($_POST, 'client_secret')) ? notags(trim($_POST['client_secret'])) : ''); + set_config('buffer', 'client_id', $client_id); + set_config('buffer', 'client_secret', $client_secret); + info(t('Settings updated.').EOL); } -function buffer_jot_nets(&$a,&$b) { - if(! local_user()) - return; +function buffer_connect(&$a) +{ + if (isset($_REQUEST['error'])) { + $o = t('Error when registering buffer connection:').' '.$_REQUEST['error']; - $buffer_post = get_pconfig(local_user(),'buffer','post'); - if(intval($buffer_post) == 1) { - $buffer_defpost = get_pconfig(local_user(),'buffer','post_by_default'); - $selected = ((intval($buffer_defpost) == 1) ? ' checked="checked" ' : ''); - $b .= '
' - . t('Post to Buffer') . '
'; - } + return $o; + } + // Start a session. This is necessary to hold on to a few keys the callback script will also need + session_start(); + + // Define the needed keys + $client_id = get_config('buffer', 'client_id'); + $client_secret = get_config('buffer', 'client_secret'); + + // The callback URL is the script that gets called after the user authenticates with buffer + $callback_url = $a->get_baseurl().'/buffer/connect'; + + $buffer = new BufferApp($client_id, $client_secret, $callback_url); + + if (!$buffer->ok) { + $o .= 'Connect to Buffer!'; + } else { + logger('buffer_connect: authenticated'); + $o .= t('You are now authenticated to buffer. '); + $o .= '
'.t('return to the connector page').''; + set_pconfig(local_user(), 'buffer', 'access_token', $buffer->access_token); + } + + return $o; } -function buffer_settings(&$a,&$s) { - - if(! local_user()) - return; - - /* Add our stylesheet to the page so we can make our settings look nice */ - - $a->page['htmlhead'] .= '' . "\r\n"; - - /* Get the current state of our config variables */ - - $enabled = get_pconfig(local_user(),'buffer','post'); - $checked = (($enabled) ? ' checked="checked" ' : ''); - $css = (($enabled) ? '' : '-disabled'); - - $def_enabled = get_pconfig(local_user(),'buffer','post_by_default'); - $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); - - /* Add some HTML to the existing form */ - - $s .= ''; - $s .= '

'. t('Buffer Export').'

'; - $s .= '
'; - $s .= ''; +function buffer_jot_nets(&$a, &$b) +{ + if (!local_user()) { + return; + } + $buffer_post = get_pconfig(local_user(), 'buffer', 'post'); + if (intval($buffer_post) == 1) { + $buffer_defpost = get_pconfig(local_user(), 'buffer', 'post_by_default'); + $selected = ((intval($buffer_defpost) == 1) ? ' checked="checked" ' : ''); + $b .= '
' + .t('Post to Buffer').'
'; + } } +function buffer_settings(&$a, &$s) +{ + if (!local_user()) { + return; + } -function buffer_settings_post(&$a,&$b) { + /* Add our stylesheet to the page so we can make our settings look nice */ - if(x($_POST,'buffer-submit')) { - if(x($_POST,'buffer_delete')) { - set_pconfig(local_user(),'buffer','access_token',''); - set_pconfig(local_user(),'buffer','post',false); - set_pconfig(local_user(),'buffer','post_by_default',false); - } else { - set_pconfig(local_user(),'buffer','post',intval($_POST['buffer'])); - set_pconfig(local_user(),'buffer','post_by_default',intval($_POST['buffer_bydefault'])); - } - } + $a->page['htmlhead'] .= ''."\r\n"; + + /* Get the current state of our config variables */ + + $enabled = get_pconfig(local_user(), 'buffer', 'post'); + $checked = (($enabled) ? ' checked="checked" ' : ''); + $css = (($enabled) ? '' : '-disabled'); + + $def_enabled = get_pconfig(local_user(), 'buffer', 'post_by_default'); + $def_checked = (($def_enabled) ? ' checked="checked" ' : ''); + + /* Add some HTML to the existing form */ + + $s .= ''; + $s .= '

'.t('Buffer Export').'

'; + $s .= '
'; + $s .= ''; } -function buffer_post_local(&$a,&$b) { - - if((! local_user()) || (local_user() != $b['uid'])) - return; - - $buffer_post = intval(get_pconfig(local_user(),'buffer','post')); - - $buffer_enable = (($buffer_post && x($_REQUEST,'buffer_enable')) ? intval($_REQUEST['buffer_enable']) : 0); - - if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'buffer','post_by_default'))) - $buffer_enable = 1; - - if(! $buffer_enable) - return; - - if(strlen($b['postopts'])) - $b['postopts'] .= ','; - - $b['postopts'] .= 'buffer'; +function buffer_settings_post(&$a, &$b) +{ + if (x($_POST, 'buffer-submit')) { + if (x($_POST, 'buffer_delete')) { + set_pconfig(local_user(), 'buffer', 'access_token', ''); + set_pconfig(local_user(), 'buffer', 'post', false); + set_pconfig(local_user(), 'buffer', 'post_by_default', false); + } else { + set_pconfig(local_user(), 'buffer', 'post', intval($_POST['buffer'])); + set_pconfig(local_user(), 'buffer', 'post_by_default', intval($_POST['buffer_bydefault'])); + } + } } -function buffer_send(&$a,&$b) { +function buffer_post_local(&$a, &$b) +{ + if ((!local_user()) || (local_user() != $b['uid'])) { + return; + } - if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) - return; + $buffer_post = intval(get_pconfig(local_user(), 'buffer', 'post')); - if(! strstr($b['postopts'],'buffer')) - return; + $buffer_enable = (($buffer_post && x($_REQUEST, 'buffer_enable')) ? intval($_REQUEST['buffer_enable']) : 0); - if($b['parent'] != $b['id']) - return; + if ($_REQUEST['api_source'] && intval(get_pconfig(local_user(), 'buffer', 'post_by_default'))) { + $buffer_enable = 1; + } - // if post comes from buffer don't send it back - //if($b['app'] == "Buffer") - // return; + if (!$buffer_enable) { + return; + } - $client_id = get_config("buffer", "client_id"); - $client_secret = get_config("buffer", "client_secret"); - $access_token = get_pconfig($b['uid'], "buffer","access_token"); + if (strlen($b['postopts'])) { + $b['postopts'] .= ','; + } - if($access_token) { - $buffer = new BufferApp($client_id, $client_secret, $callback_url, $access_token); - - require_once("include/plaintext.php"); - require_once("include/network.php"); - - $profiles = $buffer->go('/profiles'); - if (is_array($profiles)) { - logger("Will send these parameter ".print_r($b, true), LOGGER_DEBUG); - - foreach ($profiles as $profile) { - if (!$profile->default) - continue; - - $send = false; - - switch ($profile->service) { - case 'appdotnet': - $send = ($b["extid"] != NETWORK_APPNET); - $limit = 256; - $markup = false; - $includedlinks = true; - $htmlmode = 6; - break; - case 'facebook': - $send = ($b["extid"] != NETWORK_FACEBOOK); - $limit = 0; - $markup = false; - $includedlinks = false; - $htmlmode = 9; - break; - case 'google': - $send = ($b["extid"] != NETWORK_GPLUS); - $limit = 0; - $markup = true; - $includedlinks = false; - $htmlmode = 9; - break; - case 'twitter': - $send = ($b["extid"] != NETWORK_TWITTER); - $limit = 140; - $markup = false; - $includedlinks = true; - $htmlmode = 8; - break; - case 'linkedin': - $send = ($b["extid"] != NETWORK_LINKEDIN); - $limit = 700; - $markup = false; - $includedlinks = true; - $htmlmode = 2; - break; - } - - if (!$send) - continue; - - $item = $b; - - // Markup for Google+ - if ($markup) { - if ($item["title"] != "") - $item["title"] = "*".$item["title"]."*"; - - $item["body"] = preg_replace("(\[b\](.*?)\[\/b\])ism",'*$1*',$item["body"]); - $item["body"] = preg_replace("(\[i\](.*?)\[\/i\])ism",'_$1_',$item["body"]); - $item["body"] = preg_replace("(\[s\](.*?)\[\/s\])ism",'-$1-',$item["body"]); - } - - $post = plaintext($a, $item, $limit, $includedlinks, $htmlmode); - logger("buffer_send: converted message ".$b["id"]." result: ".print_r($post, true), LOGGER_DEBUG); - - // The image proxy is used as a sanitizer. Buffer seems to be really picky about pictures - require_once("mod/proxy.php"); - if (isset($post["image"])) - $post["image"] = proxy_url($post["image"]); - - if (isset($post["preview"])) - $post["preview"] = proxy_url($post["preview"]); - - //if ($profile->service == "twitter") { - if ($includedlinks) { - if (isset($post["url"])) - $post["url"] = short_link($post["url"]); - if (isset($post["image"])) - $post["image"] = short_link($post["image"]); - if (isset($post["preview"])) - $post["preview"] = short_link($post["preview"]); - } - - // Seems like a bug to me - // Buffer doesn't add links to Twitter and App.net (but pictures) - //if ($includedlinks AND isset($post["url"])) - if (($profile->service == "twitter") AND isset($post["url"]) AND ($post["type"] != "photo")) - $post["text"] .= " ".$post["url"]; - elseif (($profile->service == "appdotnet") AND isset($post["url"]) AND isset($post["title"]) AND ($post["type"] != "photo")) { - $post["title"] = shortenmsg($post["title"], 90); - $post["text"] = shortenmsg($post["text"], $limit - (24 + strlen($post["title"]))); - $post["text"] .= "\n[".$post["title"]."](".$post["url"].")"; - } elseif (($profile->service == "appdotnet") AND isset($post["url"]) AND ($post["type"] != "photo")) - $post["text"] .= " ".$post["url"]; - elseif ($profile->service == "google") - $post["text"] .= html_entity_decode(" ", ENT_QUOTES, 'UTF-8'); // Send a special blank to identify the post through the "fromgplus" addon - - $message = array(); - $message["text"] = $post["text"]; - $message["profile_ids[]"] = $profile->id; - $message["shorten"] = false; - $message["now"] = true; - - if (isset($post["title"])) - $message["media[title]"] = $post["title"]; - - if (isset($post["description"])) - $message["media[description]"] = $post["description"]; - - if (isset($post["url"]) AND ($post["type"] != "photo")) - $message["media[link]"] = $post["url"]; - - if (isset($post["image"])) { - $message["media[picture]"] = $post["image"]; - if ($post["type"] == "photo") - $message["media[thumbnail]"] = $post["image"]; - } - - if (isset($post["preview"])) - $message["media[thumbnail]"] = $post["preview"]; - - //print_r($message); - logger("buffer_send: data for message ".$b["id"].": ".print_r($message, true), LOGGER_DEBUG); - $ret = $buffer->go('/updates/create', $message); - logger("buffer_send: send message ".$b["id"]." result: ".print_r($ret, true), LOGGER_DEBUG); - } - } - } + $b['postopts'] .= 'buffer'; +} + +function buffer_send(&$a, &$b) +{ + if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited'])) { + return; + } + + if (!strstr($b['postopts'], 'buffer')) { + return; + } + + if ($b['parent'] != $b['id']) { + return; + } + + // if post comes from buffer don't send it back + //if($b['app'] == "Buffer") + // return; + + $client_id = get_config('buffer', 'client_id'); + $client_secret = get_config('buffer', 'client_secret'); + $access_token = get_pconfig($b['uid'], 'buffer', 'access_token'); + + if ($access_token) { + $buffer = new BufferApp($client_id, $client_secret, $callback_url, $access_token); + + require_once 'include/plaintext.php'; + require_once 'include/network.php'; + + $profiles = $buffer->go('/profiles'); + if (is_array($profiles)) { + logger('Will send these parameter '.print_r($b, true), LOGGER_DEBUG); + + foreach ($profiles as $profile) { + if (!$profile->default) { + continue; + } + + $send = false; + + switch ($profile->service) { + case 'appdotnet': + $send = ($b['extid'] != NETWORK_APPNET); + $limit = 256; + $markup = false; + $includedlinks = true; + $htmlmode = 6; + break; + case 'facebook': + $send = ($b['extid'] != NETWORK_FACEBOOK); + $limit = 0; + $markup = false; + $includedlinks = false; + $htmlmode = 9; + break; + case 'google': + $send = ($b['extid'] != NETWORK_GPLUS); + $limit = 0; + $markup = true; + $includedlinks = false; + $htmlmode = 9; + break; + case 'twitter': + $send = ($b['extid'] != NETWORK_TWITTER); + $limit = 140; + $markup = false; + $includedlinks = true; + $htmlmode = 8; + break; + case 'linkedin': + $send = ($b['extid'] != NETWORK_LINKEDIN); + $limit = 700; + $markup = false; + $includedlinks = true; + $htmlmode = 2; + break; + } + + if (!$send) { + continue; + } + + $item = $b; + + // Markup for Google+ + if ($markup) { + if ($item['title'] != '') { + $item['title'] = '*'.$item['title'].'*'; + } + + $item['body'] = preg_replace("(\[b\](.*?)\[\/b\])ism", '*$1*', $item['body']); + $item['body'] = preg_replace("(\[i\](.*?)\[\/i\])ism", '_$1_', $item['body']); + $item['body'] = preg_replace("(\[s\](.*?)\[\/s\])ism", '-$1-', $item['body']); + } + + $post = plaintext($a, $item, $limit, $includedlinks, $htmlmode); + logger('buffer_send: converted message '.$b['id'].' result: '.print_r($post, true), LOGGER_DEBUG); + + // The image proxy is used as a sanitizer. Buffer seems to be really picky about pictures + require_once 'mod/proxy.php'; + if (isset($post['image'])) { + $post['image'] = proxy_url($post['image']); + } + + if (isset($post['preview'])) { + $post['preview'] = proxy_url($post['preview']); + } + + //if ($profile->service == "twitter") { + if ($includedlinks) { + if (isset($post['url'])) { + $post['url'] = short_link($post['url']); + } + if (isset($post['image'])) { + $post['image'] = short_link($post['image']); + } + if (isset($post['preview'])) { + $post['preview'] = short_link($post['preview']); + } + } + + // Seems like a bug to me + // Buffer doesn't add links to Twitter and App.net (but pictures) + //if ($includedlinks AND isset($post["url"])) + if (($profile->service == 'twitter') and isset($post['url']) and ($post['type'] != 'photo')) { + $post['text'] .= ' '.$post['url']; + } elseif (($profile->service == 'appdotnet') and isset($post['url']) and isset($post['title']) and ($post['type'] != 'photo')) { + $post['title'] = shortenmsg($post['title'], 90); + $post['text'] = shortenmsg($post['text'], $limit - (24 + strlen($post['title']))); + $post['text'] .= "\n[".$post['title'].']('.$post['url'].')'; + } elseif (($profile->service == 'appdotnet') and isset($post['url']) and ($post['type'] != 'photo')) { + $post['text'] .= ' '.$post['url']; + } elseif ($profile->service == 'google') { + $post['text'] .= html_entity_decode(' ', ENT_QUOTES, 'UTF-8'); + } // Send a special blank to identify the post through the "fromgplus" addon + + $message = array(); + $message['text'] = $post['text']; + $message['profile_ids[]'] = $profile->id; + $message['shorten'] = false; + $message['now'] = true; + + if (isset($post['title'])) { + $message['media[title]'] = $post['title']; + } + + if (isset($post['description'])) { + $message['media[description]'] = $post['description']; + } + + if (isset($post['url']) and ($post['type'] != 'photo')) { + $message['media[link]'] = $post['url']; + } + + if (isset($post['image'])) { + $message['media[picture]'] = $post['image']; + if ($post['type'] == 'photo') { + $message['media[thumbnail]'] = $post['image']; + } + } + + if (isset($post['preview'])) { + $message['media[thumbnail]'] = $post['preview']; + } + + //print_r($message); + logger('buffer_send: data for message '.$b['id'].': '.print_r($message, true), LOGGER_DEBUG); + $ret = $buffer->go('/updates/create', $message); + logger('buffer_send: send message '.$b['id'].' result: '.print_r($ret, true), LOGGER_DEBUG); + } + } + } } diff --git a/buffer/bufferapp.php b/buffer/bufferapp.php index 31250336..c2795832 100644 --- a/buffer/bufferapp.php +++ b/buffer/bufferapp.php @@ -1,205 +1,235 @@ 'get', + private $endpoints = array( + '/user' => 'get', - '/profiles' => 'get', - '/profiles/:id' => 'get', - '/profiles/:id/schedules' => 'get', - '/profiles/:id/schedules/update' => 'post', // Array schedules [0][days][]=mon, [0][times][]=12:00 + '/profiles' => 'get', + '/profiles/:id' => 'get', + '/profiles/:id/schedules' => 'get', + '/profiles/:id/schedules/update' => 'post', // Array schedules [0][days][]=mon, [0][times][]=12:00 - '/updates/:id' => 'get', - '/profiles/:id/updates/pending' => 'get', - '/profiles/:id/updates/sent' => 'get', - '/updates/:id/interactions' => 'get', + '/updates/:id' => 'get', + '/profiles/:id/updates/pending' => 'get', + '/profiles/:id/updates/sent' => 'get', + '/updates/:id/interactions' => 'get', - '/profiles/:id/updates/reorder' => 'post', // Array order, int offset, bool utc - '/profiles/:id/updates/shuffle' => 'post', - '/updates/create' => 'post', // String text, Array profile_ids, Aool shorten, Bool now, Array media ['link'], ['description'], ['picture'] - '/updates/:id/update' => 'post', // String text, Bool now, Array media ['link'], ['description'], ['picture'], Bool utc - '/updates/:id/share' => 'post', - '/updates/:id/destroy' => 'post', - '/updates/:id/move_to_top' => 'post', + '/profiles/:id/updates/reorder' => 'post', // Array order, int offset, bool utc + '/profiles/:id/updates/shuffle' => 'post', + '/updates/create' => 'post', // String text, Array profile_ids, Aool shorten, Bool now, Array media ['link'], ['description'], ['picture'] + '/updates/:id/update' => 'post', // String text, Bool now, Array media ['link'], ['description'], ['picture'], Bool utc + '/updates/:id/share' => 'post', + '/updates/:id/destroy' => 'post', + '/updates/:id/move_to_top' => 'post', - '/links/shares' => 'get', + '/links/shares' => 'get', - '/info/configuration' => 'get', + '/info/configuration' => 'get', - ); + ); - public $errors = array( - 'invalid-endpoint' => 'The endpoint you supplied does not appear to be valid.', + public $errors = array( + 'invalid-endpoint' => 'The endpoint you supplied does not appear to be valid.', - '403' => 'Permission denied.', - '404' => 'Endpoint not found.', - '405' => 'Method not allowed.', - '1000' => 'An unknown error occurred.', - '1001' => 'Access token required.', - '1002' => 'Not within application scope.', - '1003' => 'Parameter not recognized.', - '1004' => 'Required parameter missing.', - '1005' => 'Unsupported response format.', - '1006' => 'Parameter value not within bounds.', - '1010' => 'Profile could not be found.', - '1011' => 'No authorization to access profile.', - '1012' => 'Profile did not save successfully.', - '1013' => 'Profile schedule limit reached.', - '1014' => 'Profile limit for user has been reached.', - '1015' => 'Profile could not be destroyed.', - '1016' => 'Profile buffer could not be emptied.', - '1020' => 'Update could not be found.', - '1021' => 'No authorization to access update.', - '1022' => 'Update did not save successfully.', - '1023' => 'Update limit for profile has been reached.', - '1024' => 'Update limit for team profile has been reached.', - '1025' => "Update was recently posted, can't post duplicate content.", - '1026' => 'Update must be in error status to requeue.', - '1027' => 'Update must be in buffer and not custom scheduled in order to move to top.', - '1028' => 'Update soft limit for profile reached.', - '1029' => 'Event type not supported.', - '1030' => 'Media filetype not supported.', - '1031' => 'Media filesize out of acceptable range.', - '1032' => 'Unable to post image to LinkedIn group(s).', - '1033' => 'Comments can only be posted to Facebook at this time.', - '1034' => 'Cannot schedule updates in the past.', - '1042' => 'User did not save successfully.', - '1050' => 'Client could not be found.', - '1051' => 'No authorization to access client.', - ); + '403' => 'Permission denied.', + '404' => 'Endpoint not found.', + '405' => 'Method not allowed.', + '1000' => 'An unknown error occurred.', + '1001' => 'Access token required.', + '1002' => 'Not within application scope.', + '1003' => 'Parameter not recognized.', + '1004' => 'Required parameter missing.', + '1005' => 'Unsupported response format.', + '1006' => 'Parameter value not within bounds.', + '1010' => 'Profile could not be found.', + '1011' => 'No authorization to access profile.', + '1012' => 'Profile did not save successfully.', + '1013' => 'Profile schedule limit reached.', + '1014' => 'Profile limit for user has been reached.', + '1015' => 'Profile could not be destroyed.', + '1016' => 'Profile buffer could not be emptied.', + '1020' => 'Update could not be found.', + '1021' => 'No authorization to access update.', + '1022' => 'Update did not save successfully.', + '1023' => 'Update limit for profile has been reached.', + '1024' => 'Update limit for team profile has been reached.', + '1025' => "Update was recently posted, can't post duplicate content.", + '1026' => 'Update must be in error status to requeue.', + '1027' => 'Update must be in buffer and not custom scheduled in order to move to top.', + '1028' => 'Update soft limit for profile reached.', + '1029' => 'Event type not supported.', + '1030' => 'Media filetype not supported.', + '1031' => 'Media filesize out of acceptable range.', + '1032' => 'Unable to post image to LinkedIn group(s).', + '1033' => 'Comments can only be posted to Facebook at this time.', + '1034' => 'Cannot schedule updates in the past.', + '1042' => 'User did not save successfully.', + '1050' => 'Client could not be found.', + '1051' => 'No authorization to access client.', + ); - function __construct($client_id = '', $client_secret = '', $callback_url = '', $access_token = '') { - if ($client_id) $this->set_client_id($client_id); - if ($client_secret) $this->set_client_secret($client_secret); - if ($callback_url) $this->set_callback_url($callback_url); - if ($access_token) $this->access_token = $access_token; + public function __construct($client_id = '', $client_secret = '', $callback_url = '', $access_token = '') + { + if ($client_id) { + $this->set_client_id($client_id); + } + if ($client_secret) { + $this->set_client_secret($client_secret); + } + if ($callback_url) { + $this->set_callback_url($callback_url); + } + if ($access_token) { + $this->access_token = $access_token; + } - if (isset($_GET['code']) AND $_GET['code']) { - $this->code = $_GET['code']; - $this->create_access_token_url(); - } + if (isset($_GET['code']) and $_GET['code']) { + $this->code = $_GET['code']; + $this->create_access_token_url(); + } - if (!$access_token) - $this->retrieve_access_token(); - } + if (!$access_token) { + $this->retrieve_access_token(); + } + } - function go($endpoint = '', $data = '') { - if (in_array($endpoint, array_keys($this->endpoints))) { - $done_endpoint = $endpoint; - } else { - $ok = false; + public function go($endpoint = '', $data = '') + { + if (in_array($endpoint, array_keys($this->endpoints))) { + $done_endpoint = $endpoint; + } else { + $ok = false; - foreach (array_keys($this->endpoints) as $done_endpoint) { - if (preg_match('/' . preg_replace('/(\:\w+)/i', '(\w+)', str_replace('/', '\/', $done_endpoint)) . '/i', $endpoint, $match)) { - $ok = true; - break; - } - } + foreach (array_keys($this->endpoints) as $done_endpoint) { + if (preg_match('/'.preg_replace('/(\:\w+)/i', '(\w+)', str_replace('/', '\/', $done_endpoint)).'/i', $endpoint, $match)) { + $ok = true; + break; + } + } - if (!$ok) return $this->error('invalid-endpoint'); - } + if (!$ok) { + return $this->error('invalid-endpoint'); + } + } - if (!$data || !is_array($data)) $data = array(); - $data['access_token'] = $this->access_token; + if (!$data || !is_array($data)) { + $data = array(); + } + $data['access_token'] = $this->access_token; - $method = $this->endpoints[$done_endpoint]; //get() or post() - return $this->$method($this->buffer_url . $endpoint . '.json', $data); - } + $method = $this->endpoints[$done_endpoint]; //get() or post() + return $this->$method($this->buffer_url.$endpoint.'.json', $data); + } - function store_access_token() { - $_SESSION['oauth']['buffer']['access_token'] = $this->access_token; - } + public function store_access_token() + { + $_SESSION['oauth']['buffer']['access_token'] = $this->access_token; + } - function retrieve_access_token() { - $this->access_token = $_SESSION['oauth']['buffer']['access_token']; + public function retrieve_access_token() + { + $this->access_token = $_SESSION['oauth']['buffer']['access_token']; - if ($this->access_token) { - $this->ok = true; - } - } + if ($this->access_token) { + $this->ok = true; + } + } - function error($error) { - return (object) array('error' => $this->errors[$error]); - } + public function error($error) + { + return (object) array('error' => $this->errors[$error]); + } - function create_access_token_url() { - $data = array( - 'code' => $this->code, - 'grant_type' => 'authorization_code', - 'client_id' => $this->client_id, - 'client_secret' => $this->client_secret, - 'redirect_uri' => $this->callback_url, - ); + public function create_access_token_url() + { + $data = array( + 'code' => $this->code, + 'grant_type' => 'authorization_code', + 'client_id' => $this->client_id, + 'client_secret' => $this->client_secret, + 'redirect_uri' => $this->callback_url, + ); - $obj = $this->post($this->access_token_url, $data); - $this->access_token = $obj->access_token; + $obj = $this->post($this->access_token_url, $data); + $this->access_token = $obj->access_token; - $this->store_access_token(); - } + $this->store_access_token(); + } - function req($url = '', $data = '', $post = true) { - if (!$url) return false; - if (!$data || !is_array($data)) $data = array(); + public function req($url = '', $data = '', $post = true) + { + if (!$url) { + return false; + } + if (!$data || !is_array($data)) { + $data = array(); + } - $options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false); + $options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_HEADER => false); - if ($post) { - $options += array( - CURLOPT_POST => $post, - CURLOPT_POSTFIELDS => $data - ); - } else { - $url .= '?' . http_build_query($data); - } + if ($post) { + $options += array( + CURLOPT_POST => $post, + CURLOPT_POSTFIELDS => $data, + ); + } else { + $url .= '?'.http_build_query($data); + } - $ch = curl_init($url); - curl_setopt_array($ch, $options); - $rs = curl_exec($ch); + $ch = curl_init($url); + curl_setopt_array($ch, $options); + $rs = curl_exec($ch); - $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); - if ($code >= 400) { - return $this->error($code); - } + $code = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if ($code >= 400) { + return $this->error($code); + } - return json_decode($rs); - } + return json_decode($rs); + } - function get($url = '', $data = '') { - return $this->req($url, $data, false); - } + public function get($url = '', $data = '') + { + return $this->req($url, $data, false); + } - function post($url = '', $data = '') { - return $this->req($url, $data, true); - } + public function post($url = '', $data = '') + { + return $this->req($url, $data, true); + } - function get_login_url() { - return $this->authorize_url . '?' - . 'client_id=' . $this->client_id - . '&redirect_uri=' . urlencode($this->callback_url) - . '&response_type=code'; - } + public function get_login_url() + { + return $this->authorize_url.'?' + .'client_id='.$this->client_id + .'&redirect_uri='.urlencode($this->callback_url) + .'&response_type=code'; + } - function set_client_id($client_id) { - $this->client_id = $client_id; - } + public function set_client_id($client_id) + { + $this->client_id = $client_id; + } - function set_client_secret($client_secret) { - $this->client_secret = $client_secret; - } + public function set_client_secret($client_secret) + { + $this->client_secret = $client_secret; + } - function set_callback_url($callback_url) { - $this->callback_url = $callback_url; - } - } -?> + public function set_callback_url($callback_url) + { + $this->callback_url = $callback_url; + } + } diff --git a/buffer/lang/cs/strings.php b/buffer/lang/cs/strings.php index 052b3e8e..003d30b3 100644 --- a/buffer/lang/cs/strings.php +++ b/buffer/lang/cs/strings.php @@ -1,21 +1,23 @@ =2 && $n<=4) ? 1 : 2;; -}} -; -$a->strings["Permission denied."] = "Přístup odmítnut."; -$a->strings["Save Settings"] = "Uložit Nastavení"; -$a->strings["Client ID"] = "Client ID"; -$a->strings["Client Secret"] = "Client Secret"; -$a->strings["Error when registering buffer connection:"] = "Chyba při registraci buffer spojená"; -$a->strings["You are now authenticated to buffer. "] = "Nyní jste přihlášen k bufferu."; -$a->strings["return to the connector page"] = "návrat ke stránce konektor"; -$a->strings["Post to Buffer"] = "Příspěvek na Buffer"; -$a->strings["Buffer Export"] = "Buffer Export"; -$a->strings["Authenticate your Buffer connection"] = "Přihlásit ke spojení na Buffer"; -$a->strings["Enable Buffer Post Plugin"] = "Povolit Buffer Post Plugin"; -$a->strings["Post to Buffer by default"] = "Defaultně zaslat na Buffer"; -$a->strings["Check to delete this preset"] = "Zaškrtnout pro smazání tohoto nastavení"; -$a->strings["Posts are going to all accounts that are enabled by default:"] = "Příspěvky jsou zasílány na všechny účty, které jsou defaultně povoleny:"; +if (!function_exists('string_plural_select_cs')) { + function string_plural_select_cs($n) + { + return ($n == 1) ? 0 : ($n >= 2 && $n <= 4) ? 1 : 2; + } +} + +$a->strings['Permission denied.'] = 'Přístup odmítnut.'; +$a->strings['Save Settings'] = 'Uložit Nastavení'; +$a->strings['Client ID'] = 'Client ID'; +$a->strings['Client Secret'] = 'Client Secret'; +$a->strings['Error when registering buffer connection:'] = 'Chyba při registraci buffer spojená'; +$a->strings['You are now authenticated to buffer. '] = 'Nyní jste přihlášen k bufferu.'; +$a->strings['return to the connector page'] = 'návrat ke stránce konektor'; +$a->strings['Post to Buffer'] = 'Příspěvek na Buffer'; +$a->strings['Buffer Export'] = 'Buffer Export'; +$a->strings['Authenticate your Buffer connection'] = 'Přihlásit ke spojení na Buffer'; +$a->strings['Enable Buffer Post Plugin'] = 'Povolit Buffer Post Plugin'; +$a->strings['Post to Buffer by default'] = 'Defaultně zaslat na Buffer'; +$a->strings['Check to delete this preset'] = 'Zaškrtnout pro smazání tohoto nastavení'; +$a->strings['Posts are going to all accounts that are enabled by default:'] = 'Příspěvky jsou zasílány na všechny účty, které jsou defaultně povoleny:'; diff --git a/buffer/lang/de/strings.php b/buffer/lang/de/strings.php index 4ddbf1e9..06ab75af 100644 --- a/buffer/lang/de/strings.php +++ b/buffer/lang/de/strings.php @@ -1,21 +1,23 @@ strings["Permission denied."] = "Zugriff verweigert."; -$a->strings["Save Settings"] = "Einstellungen speichern"; -$a->strings["Client ID"] = "Client ID"; -$a->strings["Client Secret"] = "Client Secret"; -$a->strings["Error when registering buffer connection:"] = "Fehler beim Registrieren des buffer Connectors."; -$a->strings["You are now authenticated to buffer. "] = "Du bist nun auf buffer authentifiziert."; -$a->strings["return to the connector page"] = "zurück zur Connector Seite"; -$a->strings["Post to Buffer"] = "Auf buffer veröffentlichen"; -$a->strings["Buffer Export"] = "Buffer Export"; -$a->strings["Authenticate your Buffer connection"] = "Authentifiziere deine Verbindung zu buffer"; -$a->strings["Enable Buffer Post Plugin"] = "Buffer Post-Plugin aktivieren"; -$a->strings["Post to Buffer by default"] = "Standardmäßig auf buffer veröffentlichen"; -$a->strings["Check to delete this preset"] = "Markieren um dieses Preset zu löschen"; -$a->strings["Posts are going to all accounts that are enabled by default:"] = "Beiträge werden an alle Accounts geschickt, die Standardmäßig aktiviert sind."; +if (!function_exists('string_plural_select_de')) { + function string_plural_select_de($n) + { + return $n != 1; + } +} + +$a->strings['Permission denied.'] = 'Zugriff verweigert.'; +$a->strings['Save Settings'] = 'Einstellungen speichern'; +$a->strings['Client ID'] = 'Client ID'; +$a->strings['Client Secret'] = 'Client Secret'; +$a->strings['Error when registering buffer connection:'] = 'Fehler beim Registrieren des buffer Connectors.'; +$a->strings['You are now authenticated to buffer. '] = 'Du bist nun auf buffer authentifiziert.'; +$a->strings['return to the connector page'] = 'zurück zur Connector Seite'; +$a->strings['Post to Buffer'] = 'Auf buffer veröffentlichen'; +$a->strings['Buffer Export'] = 'Buffer Export'; +$a->strings['Authenticate your Buffer connection'] = 'Authentifiziere deine Verbindung zu buffer'; +$a->strings['Enable Buffer Post Plugin'] = 'Buffer Post-Plugin aktivieren'; +$a->strings['Post to Buffer by default'] = 'Standardmäßig auf buffer veröffentlichen'; +$a->strings['Check to delete this preset'] = 'Markieren um dieses Preset zu löschen'; +$a->strings['Posts are going to all accounts that are enabled by default:'] = 'Beiträge werden an alle Accounts geschickt, die Standardmäßig aktiviert sind.'; diff --git a/buffer/lang/fr/strings.php b/buffer/lang/fr/strings.php index 07460f47..bca41025 100644 --- a/buffer/lang/fr/strings.php +++ b/buffer/lang/fr/strings.php @@ -1,21 +1,23 @@ 1);; -}} -; -$a->strings["Permission denied."] = "Permission refusée."; -$a->strings["Save Settings"] = "Enregistrer les Paramètres"; -$a->strings["Client ID"] = "Identifiant client"; -$a->strings["Client Secret"] = "Secret Client"; -$a->strings["Error when registering buffer connection:"] = "Une erreur est survenue lors de la connexion à Buffer :"; -$a->strings["You are now authenticated to buffer. "] = "Vous êtes maintenant authentifié sur Buffer."; -$a->strings["return to the connector page"] = "revenir à la page du connecteur"; -$a->strings["Post to Buffer"] = "Publier sur Buffer"; -$a->strings["Buffer Export"] = "Export Buffer"; -$a->strings["Authenticate your Buffer connection"] = "Authentifier votre connexion à Buffer"; -$a->strings["Enable Buffer Post Plugin"] = "Activer le connecteur Buffer"; -$a->strings["Post to Buffer by default"] = "Publier sur Buffer par défaut"; -$a->strings["Check to delete this preset"] = "Cocher pour supprimer ce préréglage"; -$a->strings["Posts are going to all accounts that are enabled by default:"] = "Les posts sont envoyés à tous les comptes activés par défault:"; +if (!function_exists('string_plural_select_fr')) { + function string_plural_select_fr($n) + { + return $n > 1; + } +} + +$a->strings['Permission denied.'] = 'Permission refusée.'; +$a->strings['Save Settings'] = 'Enregistrer les Paramètres'; +$a->strings['Client ID'] = 'Identifiant client'; +$a->strings['Client Secret'] = 'Secret Client'; +$a->strings['Error when registering buffer connection:'] = 'Une erreur est survenue lors de la connexion à Buffer :'; +$a->strings['You are now authenticated to buffer. '] = 'Vous êtes maintenant authentifié sur Buffer.'; +$a->strings['return to the connector page'] = 'revenir à la page du connecteur'; +$a->strings['Post to Buffer'] = 'Publier sur Buffer'; +$a->strings['Buffer Export'] = 'Export Buffer'; +$a->strings['Authenticate your Buffer connection'] = 'Authentifier votre connexion à Buffer'; +$a->strings['Enable Buffer Post Plugin'] = 'Activer le connecteur Buffer'; +$a->strings['Post to Buffer by default'] = 'Publier sur Buffer par défaut'; +$a->strings['Check to delete this preset'] = 'Cocher pour supprimer ce préréglage'; +$a->strings['Posts are going to all accounts that are enabled by default:'] = 'Les posts sont envoyés à tous les comptes activés par défault:'; diff --git a/buffer/lang/it/strings.php b/buffer/lang/it/strings.php index 9081af8a..ce490494 100644 --- a/buffer/lang/it/strings.php +++ b/buffer/lang/it/strings.php @@ -1,21 +1,23 @@ strings["Permission denied."] = "Permesso negato."; -$a->strings["Save Settings"] = "Salva Impostazioni"; -$a->strings["Client ID"] = "Client ID"; -$a->strings["Client Secret"] = "Client Secret"; -$a->strings["Error when registering buffer connection:"] = "Errore registrando la connessione a buffer:"; -$a->strings["You are now authenticated to buffer. "] = "Sei autenticato su buffer."; -$a->strings["return to the connector page"] = "ritorna alla pagina del connettore"; -$a->strings["Post to Buffer"] = "Invia a Buffer"; -$a->strings["Buffer Export"] = "Esporta Buffer"; -$a->strings["Authenticate your Buffer connection"] = "Autentica la tua connessione a Buffer"; -$a->strings["Enable Buffer Post Plugin"] = "Abilita il plugin di invio a Buffer"; -$a->strings["Post to Buffer by default"] = "Invia sempre a Buffer"; -$a->strings["Check to delete this preset"] = "Seleziona per eliminare questo preset"; -$a->strings["Posts are going to all accounts that are enabled by default:"] = "I messaggi andranno a tutti gli account che sono abilitati:"; +if (!function_exists('string_plural_select_it')) { + function string_plural_select_it($n) + { + return $n != 1; + } +} + +$a->strings['Permission denied.'] = 'Permesso negato.'; +$a->strings['Save Settings'] = 'Salva Impostazioni'; +$a->strings['Client ID'] = 'Client ID'; +$a->strings['Client Secret'] = 'Client Secret'; +$a->strings['Error when registering buffer connection:'] = 'Errore registrando la connessione a buffer:'; +$a->strings['You are now authenticated to buffer. '] = 'Sei autenticato su buffer.'; +$a->strings['return to the connector page'] = 'ritorna alla pagina del connettore'; +$a->strings['Post to Buffer'] = 'Invia a Buffer'; +$a->strings['Buffer Export'] = 'Esporta Buffer'; +$a->strings['Authenticate your Buffer connection'] = 'Autentica la tua connessione a Buffer'; +$a->strings['Enable Buffer Post Plugin'] = 'Abilita il plugin di invio a Buffer'; +$a->strings['Post to Buffer by default'] = 'Invia sempre a Buffer'; +$a->strings['Check to delete this preset'] = 'Seleziona per eliminare questo preset'; +$a->strings['Posts are going to all accounts that are enabled by default:'] = 'I messaggi andranno a tutti gli account che sono abilitati:'; diff --git a/buffer/lang/pt-br/strings.php b/buffer/lang/pt-br/strings.php index 272a071e..8a89aada 100644 --- a/buffer/lang/pt-br/strings.php +++ b/buffer/lang/pt-br/strings.php @@ -1,21 +1,23 @@ 1);; -}} -; -$a->strings["Permission denied."] = "Permissão negada."; -$a->strings["Save Settings"] = "Salvar configurações"; -$a->strings["Client ID"] = ""; -$a->strings["Client Secret"] = ""; -$a->strings["Error when registering buffer connection:"] = "Erro ao registrar conexão de buffer:"; -$a->strings["You are now authenticated to buffer. "] = "Você está autenticado no buffer."; -$a->strings["return to the connector page"] = "Volte a página de conectores."; -$a->strings["Post to Buffer"] = "Publicar no Buffer"; -$a->strings["Buffer Export"] = "Exportar Buffer"; -$a->strings["Authenticate your Buffer connection"] = "Autenticar sua conexão de Buffer"; -$a->strings["Enable Buffer Post Plugin"] = "Habilita plugin para publicar no Buffer"; -$a->strings["Post to Buffer by default"] = "Publica no Buffer por padrão"; -$a->strings["Check to delete this preset"] = "Marque para excluir este perfil"; -$a->strings["Posts are going to all accounts that are enabled by default:"] = ""; +if (!function_exists('string_plural_select_pt_br')) { + function string_plural_select_pt_br($n) + { + return $n > 1; + } +} + +$a->strings['Permission denied.'] = 'Permissão negada.'; +$a->strings['Save Settings'] = 'Salvar configurações'; +$a->strings['Client ID'] = ''; +$a->strings['Client Secret'] = ''; +$a->strings['Error when registering buffer connection:'] = 'Erro ao registrar conexão de buffer:'; +$a->strings['You are now authenticated to buffer. '] = 'Você está autenticado no buffer.'; +$a->strings['return to the connector page'] = 'Volte a página de conectores.'; +$a->strings['Post to Buffer'] = 'Publicar no Buffer'; +$a->strings['Buffer Export'] = 'Exportar Buffer'; +$a->strings['Authenticate your Buffer connection'] = 'Autenticar sua conexão de Buffer'; +$a->strings['Enable Buffer Post Plugin'] = 'Habilita plugin para publicar no Buffer'; +$a->strings['Post to Buffer by default'] = 'Publica no Buffer por padrão'; +$a->strings['Check to delete this preset'] = 'Marque para excluir este perfil'; +$a->strings['Posts are going to all accounts that are enabled by default:'] = ''; diff --git a/buffer/lang/ro/strings.php b/buffer/lang/ro/strings.php index 7e7e575f..618bb748 100644 --- a/buffer/lang/ro/strings.php +++ b/buffer/lang/ro/strings.php @@ -1,21 +1,23 @@ 19)||(($n%100==0)&&($n!=0)))?2:1));; -}} -; -$a->strings["Permission denied."] = "Permisiune refuzată."; -$a->strings["Save Settings"] = "Salvare Configurări"; -$a->strings["Client ID"] = "ID Client"; -$a->strings["Client Secret"] = "Cheia Secretă Client"; -$a->strings["Error when registering buffer connection:"] = "Eroare la înregistrarea conexiunii Buffer:"; -$a->strings["You are now authenticated to buffer. "] = "Acum sunteți autentificat pe Buffer."; -$a->strings["return to the connector page"] = "revenire la pagina de conectare"; -$a->strings["Post to Buffer"] = "Postați pe Buffer"; -$a->strings["Buffer Export"] = "Export pe Buffer "; -$a->strings["Authenticate your Buffer connection"] = "Autentificați-vă conectarea la Buffer"; -$a->strings["Enable Buffer Post Plugin"] = "Activare Modul Postare pe Buffer"; -$a->strings["Post to Buffer by default"] = "Postați implicit pe Buffer"; -$a->strings["Check to delete this preset"] = "Bifați pentru a șterge această presetare"; -$a->strings["Posts are going to all accounts that are enabled by default:"] = "Posturile merg către toate conturile care sunt activate implicit:"; +if (!function_exists('string_plural_select_ro')) { + function string_plural_select_ro($n) + { + return $n == 1 ? 0 : ((($n % 100 > 19) || (($n % 100 == 0) && ($n != 0))) ? 2 : 1); + } +} + +$a->strings['Permission denied.'] = 'Permisiune refuzată.'; +$a->strings['Save Settings'] = 'Salvare Configurări'; +$a->strings['Client ID'] = 'ID Client'; +$a->strings['Client Secret'] = 'Cheia Secretă Client'; +$a->strings['Error when registering buffer connection:'] = 'Eroare la înregistrarea conexiunii Buffer:'; +$a->strings['You are now authenticated to buffer. '] = 'Acum sunteți autentificat pe Buffer.'; +$a->strings['return to the connector page'] = 'revenire la pagina de conectare'; +$a->strings['Post to Buffer'] = 'Postați pe Buffer'; +$a->strings['Buffer Export'] = 'Export pe Buffer '; +$a->strings['Authenticate your Buffer connection'] = 'Autentificați-vă conectarea la Buffer'; +$a->strings['Enable Buffer Post Plugin'] = 'Activare Modul Postare pe Buffer'; +$a->strings['Post to Buffer by default'] = 'Postați implicit pe Buffer'; +$a->strings['Check to delete this preset'] = 'Bifați pentru a șterge această presetare'; +$a->strings['Posts are going to all accounts that are enabled by default:'] = 'Posturile merg către toate conturile care sunt activate implicit:'; diff --git a/buglink/buglink.php b/buglink/buglink.php index 06eaddbb..bf344366 100755 --- a/buglink/buglink.php +++ b/buglink/buglink.php @@ -3,13 +3,19 @@ * Name: BugLink * Description: Show link to Friendica bug site at bottom of page * Version: 1.0 - * Author: Mike Macgirvin + * Author: Mike Macgirvin . */ +function buglink_install() +{ + register_hook('page_end', 'addon/buglink/buglink.php', 'buglink_active'); +} +function buglink_uninstall() +{ + unregister_hook('page_end', 'addon/buglink/buglink.php', 'buglink_active'); +} -function buglink_install() { register_hook('page_end', 'addon/buglink/buglink.php', 'buglink_active'); } - - -function buglink_uninstall() { unregister_hook('page_end', 'addon/buglink/buglink.php', 'buglink_active'); } - -function buglink_active(&$a,&$b) { $b .= ''; } +function buglink_active(&$a, &$b) +{ + $b .= ''; +} diff --git a/buglink/lang/ca/strings.php b/buglink/lang/ca/strings.php index 01fc9adb..e461cc3e 100644 --- a/buglink/lang/ca/strings.php +++ b/buglink/lang/ca/strings.php @@ -1,3 +1,3 @@ -strings["Report Bug"] = "Informar de problema"; +strings['Report Bug'] = 'Informar de problema'; diff --git a/buglink/lang/cs/strings.php b/buglink/lang/cs/strings.php index 7a9f9204..60625568 100644 --- a/buglink/lang/cs/strings.php +++ b/buglink/lang/cs/strings.php @@ -1,8 +1,10 @@ =2 && $n<=4) ? 1 : 2;; -}} -; -$a->strings["Report Bug"] = "Nahlásit chybu"; +if (!function_exists('string_plural_select_cs')) { + function string_plural_select_cs($n) + { + return ($n == 1) ? 0 : ($n >= 2 && $n <= 4) ? 1 : 2; + } +} + +$a->strings['Report Bug'] = 'Nahlásit chybu'; diff --git a/buglink/lang/de/strings.php b/buglink/lang/de/strings.php index 19123819..a4959575 100644 --- a/buglink/lang/de/strings.php +++ b/buglink/lang/de/strings.php @@ -1,8 +1,10 @@ strings["Report Bug"] = "Fehler melden."; +if (!function_exists('string_plural_select_de')) { + function string_plural_select_de($n) + { + return $n != 1; + } +} + +$a->strings['Report Bug'] = 'Fehler melden.'; diff --git a/buglink/lang/eo/strings.php b/buglink/lang/eo/strings.php index 00d95a40..eb67038b 100644 --- a/buglink/lang/eo/strings.php +++ b/buglink/lang/eo/strings.php @@ -1,3 +1,3 @@ -strings["Report Bug"] = "Skribi cimraporton"; +strings['Report Bug'] = 'Skribi cimraporton'; diff --git a/buglink/lang/es/strings.php b/buglink/lang/es/strings.php index fe632488..92e0d881 100644 --- a/buglink/lang/es/strings.php +++ b/buglink/lang/es/strings.php @@ -1,3 +1,3 @@ -strings["Report Bug"] = "Informe de errores"; +strings['Report Bug'] = 'Informe de errores'; diff --git a/buglink/lang/fr/strings.php b/buglink/lang/fr/strings.php index 0075fb0d..4b15b833 100644 --- a/buglink/lang/fr/strings.php +++ b/buglink/lang/fr/strings.php @@ -1,3 +1,3 @@ -strings["Report Bug"] = "Signaler un bug"; +strings['Report Bug'] = 'Signaler un bug'; diff --git a/buglink/lang/is/strings.php b/buglink/lang/is/strings.php index 7b3823a6..44f67b7f 100644 --- a/buglink/lang/is/strings.php +++ b/buglink/lang/is/strings.php @@ -1,3 +1,3 @@ -strings["Report Bug"] = "Tilkynna bilun"; +strings['Report Bug'] = 'Tilkynna bilun'; diff --git a/buglink/lang/it/strings.php b/buglink/lang/it/strings.php index 449e6b9f..417fccb6 100644 --- a/buglink/lang/it/strings.php +++ b/buglink/lang/it/strings.php @@ -1,8 +1,10 @@ strings["Report Bug"] = "Segnala un Bug"; +if (!function_exists('string_plural_select_it')) { + function string_plural_select_it($n) + { + return $n != 1; + } +} + +$a->strings['Report Bug'] = 'Segnala un Bug'; diff --git a/buglink/lang/nb-no/strings.php b/buglink/lang/nb-no/strings.php index ec212e9a..ee67ff45 100644 --- a/buglink/lang/nb-no/strings.php +++ b/buglink/lang/nb-no/strings.php @@ -1,3 +1,3 @@ -strings["Report Bug"] = ""; +strings['Report Bug'] = ''; diff --git a/buglink/lang/pl/strings.php b/buglink/lang/pl/strings.php index 8229e7a6..297fd94a 100644 --- a/buglink/lang/pl/strings.php +++ b/buglink/lang/pl/strings.php @@ -1,3 +1,3 @@ -strings["Report Bug"] = "Zgłoś problem"; +strings['Report Bug'] = 'Zgłoś problem'; diff --git a/buglink/lang/pt-br/strings.php b/buglink/lang/pt-br/strings.php index 6283d77e..8dd5d38f 100644 --- a/buglink/lang/pt-br/strings.php +++ b/buglink/lang/pt-br/strings.php @@ -1,3 +1,3 @@ -strings["Report Bug"] = "Relate um Bug"; +strings['Report Bug'] = 'Relate um Bug'; diff --git a/buglink/lang/ro/strings.php b/buglink/lang/ro/strings.php index 25a9c769..6e3e5c30 100644 --- a/buglink/lang/ro/strings.php +++ b/buglink/lang/ro/strings.php @@ -1,8 +1,10 @@ 19)||(($n%100==0)&&($n!=0)))?2:1));; -}} -; -$a->strings["Report Bug"] = "Raportează Problema"; +if (!function_exists('string_plural_select_ro')) { + function string_plural_select_ro($n) + { + return $n == 1 ? 0 : ((($n % 100 > 19) || (($n % 100 == 0) && ($n != 0))) ? 2 : 1); + } +} + +$a->strings['Report Bug'] = 'Raportează Problema'; diff --git a/buglink/lang/ru/strings.php b/buglink/lang/ru/strings.php index c4223648..9c4a0940 100644 --- a/buglink/lang/ru/strings.php +++ b/buglink/lang/ru/strings.php @@ -1,3 +1,3 @@ -strings["Report Bug"] = "Сообщить об ошибке"; +strings['Report Bug'] = 'Сообщить об ошибке'; diff --git a/buglink/lang/sv/strings.php b/buglink/lang/sv/strings.php index ab4fa67a..a4abe2da 100644 --- a/buglink/lang/sv/strings.php +++ b/buglink/lang/sv/strings.php @@ -1,2 +1,2 @@ -strings["Report Bug"] = "报案程序错误"; +strings['Report Bug'] = '报案程序错误'; diff --git a/cal/cal.php b/cal/cal.php index 5c2f1021..36d0be99 100644 --- a/cal/cal.php +++ b/cal/cal.php @@ -8,7 +8,6 @@ * Status: Unsupported * ******************************************************************/ - function cal_install() { register_hook('plugin_settings', 'addon/cal/cal.php', 'cal_addon_settings'); @@ -29,86 +28,89 @@ function cal_module() function cal_content() { $a = get_app(); - $o = ""; + $o = ''; if ($a->argc == 1) { - $o .= "

".t('Event Export')."

".t('You can download public events from: ').$a->get_baseurl()."/cal/username/export/ical

"; - } elseif ($a->argc==4) { - // get the parameters from the request we just received - $username = $a->argv[1]; - $do = $a->argv[2]; - $format = $a->argv[3]; - // check that there is a user matching the requested profile - $r = q("SELECT uid FROM user WHERE nickname='".$username."' LIMIT 1;"); - if (count($r)) - { - $uid = $r[0]['uid']; - } else { - killme(); - } - // if we shall do anything other then export, end here - if (! $do == 'export' ) - killme(); - // check if the user allows us to share the profile - $enable = get_pconfig( $uid, 'cal', 'enable'); - if (! $enable == 1) { - info(t('The user does not export the calendar.')); - return; - } - // we are allowed to show events - // get the timezone the user is in - $r = q("SELECT timezone FROM user WHERE uid=".$uid." LIMIT 1;"); - if (count($r)) - $timezone = $r[0]['timezone']; - // does the user who requests happen to be the owner of the events - // requested? then show all of your events, otherwise only those that - // don't have limitations set in allow_cid and allow_gid - if (local_user() == $uid) { - $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location` FROM `event` WHERE `uid`=".$uid." and `cid`=0;"); - } else { - $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location` FROM `event` WHERE `allow_cid`='' and `allow_gid`='' and `uid`='".$uid."' and `cid`='0';"); - } - // we have the events that are available for the requestor - // now format the output according to the requested format - $res = cal_format_output($r, $format, $timezone); - if (! $res=='') - info($res); - } else { - // wrong number of parameters - killme(); + $o .= '

'.t('Event Export').'

'.t('You can download public events from: ').$a->get_baseurl().'/cal/username/export/ical

'; + } elseif ($a->argc == 4) { + // get the parameters from the request we just received + $username = $a->argv[1]; + $do = $a->argv[2]; + $format = $a->argv[3]; + // check that there is a user matching the requested profile + $r = q("SELECT uid FROM user WHERE nickname='".$username."' LIMIT 1;"); + if (count($r)) { + $uid = $r[0]['uid']; + } else { + killme(); + } + // if we shall do anything other then export, end here + if (!$do == 'export') { + killme(); } + // check if the user allows us to share the profile + $enable = get_pconfig($uid, 'cal', 'enable'); + if (!$enable == 1) { + info(t('The user does not export the calendar.')); + + return; + } + // we are allowed to show events + // get the timezone the user is in + $r = q('SELECT timezone FROM user WHERE uid='.$uid.' LIMIT 1;'); + if (count($r)) { + $timezone = $r[0]['timezone']; + } + // does the user who requests happen to be the owner of the events + // requested? then show all of your events, otherwise only those that + // don't have limitations set in allow_cid and allow_gid + if (local_user() == $uid) { + $r = q('SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location` FROM `event` WHERE `uid`='.$uid.' and `cid`=0;'); + } else { + $r = q("SELECT `start`, `finish`, `adjust`, `summary`, `desc`, `location` FROM `event` WHERE `allow_cid`='' and `allow_gid`='' and `uid`='".$uid."' and `cid`='0';"); + } + // we have the events that are available for the requestor + // now format the output according to the requested format + $res = cal_format_output($r, $format, $timezone); + if (!$res == '') { + info($res); + } + } else { + // wrong number of parameters + killme(); + } + return $o; } -function cal_format_output ($r, $f, $tz) +function cal_format_output($r, $f, $tz) { $res = t('This calendar format is not supported'); - switch ($f) - { - // format the exported data as a CSV file - case "csv": - header("Content-type: text/csv"); - $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"' . PHP_EOL; - foreach ($r as $rr) { -// TODO the time / date entries don't include any information about the + switch ($f) { + // format the exported data as a CSV file + case 'csv': + header('Content-type: text/csv'); + $o = '"Subject", "Start Date", "Start Time", "Description", "End Date", "End Time", "Location"'.PHP_EOL; + foreach ($r as $rr) { + // TODO the time / date entries don't include any information about the // timezone the event is scheduled in :-/ - $tmp1 = strtotime($rr['start']); - $tmp2 = strtotime($rr['finish']); - $time_format = "%H:%M:%S"; - $date_format = "%Y-%m-%d"; - $o .= '"'.$rr['summary'].'", "'.strftime($date_format, $tmp1) . - '", "'.strftime($time_format, $tmp1).'", "'.$rr['desc'] . - '", "'.strftime($date_format, $tmp2) . - '", "'.strftime($time_format, $tmp2) . - '", "'.$rr['location'].'"' . PHP_EOL; - } - echo $o; - killme(); + $tmp1 = strtotime($rr['start']); + $tmp2 = strtotime($rr['finish']); + $time_format = '%H:%M:%S'; + $date_format = '%Y-%m-%d'; + $o .= '"'.$rr['summary'].'", "'.strftime($date_format, $tmp1). + '", "'.strftime($time_format, $tmp1).'", "'.$rr['desc']. + '", "'.strftime($date_format, $tmp2). + '", "'.strftime($time_format, $tmp2). + '", "'.$rr['location'].'"'.PHP_EOL; + } + echo $o; + killme(); - case "ical": - header("Content-type: text/ics"); - $o = 'BEGIN:VCALENDAR'. PHP_EOL - . 'VERSION:2.0' . PHP_EOL - . 'PRODID:-//friendica calendar export//0.1//EN' . PHP_EOL; + case 'ical': + header('Content-type: text/ics'); + $o = 'BEGIN:VCALENDAR'.PHP_EOL + .'VERSION:2.0'.PHP_EOL + .'PRODID:-//friendica calendar export//0.1//EN'.PHP_EOL; // TODO include timezone informations in cases were the time is not in UTC // see http://tools.ietf.org/html/rfc2445#section-4.8.3 // . 'BEGIN:VTIMEZONE' . PHP_EOL @@ -117,62 +119,68 @@ function cal_format_output ($r, $f, $tz) // TODO instead of PHP_EOL CRLF should be used for long entries // but test your solution against http://icalvalid.cloudapp.net/ // also long lines SHOULD be split at 75 characters length - foreach ($r as $rr) { - if ($rr['adjust'] == 1) { - $UTC = 'Z'; - } else { - $UTC = ''; - } - $o .= 'BEGIN:VEVENT' . PHP_EOL; - if ($rr[start]) { - $tmp = strtotime($rr['start']); - $dtformat = "%Y%m%dT%H%M%S".$UTC; - $o .= 'DTSTART:'.strftime($dtformat, $tmp).PHP_EOL; - } - if ($rr['finish']) { - $tmp = strtotime($rr['finish']); - $dtformat = "%Y%m%dT%H%M%S".$UTC; - $o .= 'DTEND:'.strftime($dtformat, $tmp).PHP_EOL; - } - if ($rr['summary']) - $tmp = $rr['summary']; - $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp); - $tmp = addcslashes($tmp, ',;'); - $o .= 'SUMMARY:' . $tmp . PHP_EOL; - if ($rr['desc']) - $tmp = $rr['desc']; - $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp); - $tmp = addcslashes($tmp, ',;'); - $o .= 'DESCRIPTION:' . $tmp . PHP_EOL; - if ($rr['location']) { - $tmp = $rr['location']; - $tmp = str_replace(PHP_EOL, PHP_EOL.' ',$tmp); - $tmp = addcslashes($tmp, ',;'); - $o .= 'LOCATION:' . $tmp . PHP_EOL; - } - $o .= 'END:VEVENT' . PHP_EOL; - } - $o .= 'END:VCALENDAR' . PHP_EOL; - echo $o; - killme(); + foreach ($r as $rr) { + if ($rr['adjust'] == 1) { + $UTC = 'Z'; + } else { + $UTC = ''; + } + $o .= 'BEGIN:VEVENT'.PHP_EOL; + if ($rr[start]) { + $tmp = strtotime($rr['start']); + $dtformat = '%Y%m%dT%H%M%S'.$UTC; + $o .= 'DTSTART:'.strftime($dtformat, $tmp).PHP_EOL; + } + if ($rr['finish']) { + $tmp = strtotime($rr['finish']); + $dtformat = '%Y%m%dT%H%M%S'.$UTC; + $o .= 'DTEND:'.strftime($dtformat, $tmp).PHP_EOL; + } + if ($rr['summary']) { + $tmp = $rr['summary']; + } + $tmp = str_replace(PHP_EOL, PHP_EOL.' ', $tmp); + $tmp = addcslashes($tmp, ',;'); + $o .= 'SUMMARY:'.$tmp.PHP_EOL; + if ($rr['desc']) { + $tmp = $rr['desc']; + } + $tmp = str_replace(PHP_EOL, PHP_EOL.' ', $tmp); + $tmp = addcslashes($tmp, ',;'); + $o .= 'DESCRIPTION:'.$tmp.PHP_EOL; + if ($rr['location']) { + $tmp = $rr['location']; + $tmp = str_replace(PHP_EOL, PHP_EOL.' ', $tmp); + $tmp = addcslashes($tmp, ',;'); + $o .= 'LOCATION:'.$tmp.PHP_EOL; + } + $o .= 'END:VEVENT'.PHP_EOL; + } + $o .= 'END:VCALENDAR'.PHP_EOL; + echo $o; + killme(); } + return $res; } -function cal_addon_settings_post ( &$a, &$b ) +function cal_addon_settings_post(&$a, &$b) { - if (! local_user()) - return; + if (!local_user()) { + return; + } - if (!x($_POST,'cal-submit')) - return; + if (!x($_POST, 'cal-submit')) { + return; + } - set_pconfig(local_user(),'cal','enable',intval($_POST['cal-enable'])); + set_pconfig(local_user(), 'cal', 'enable', intval($_POST['cal-enable'])); } -function cal_addon_settings ( &$a, &$s ) +function cal_addon_settings(&$a, &$s) { - if (! local_user()) - return; + if (!local_user()) { + return; + } $enabled = get_pconfig(local_user(), 'cal', 'enable'); $checked = (($enabled) ? ' checked="checked" ' : ''); @@ -189,12 +197,10 @@ function cal_addon_settings ( &$a, &$s ) $s .= '
'; $s .= '

'.t('If this is enabled, your public events will be available at').' '.$url.'

'; $s .= '

'.t('Currently supported formats are ical and csv.').'

'; - $s .= ''; - $s .= ''; - $s .= '
'; + $s .= ''; + $s .= ''; + $s .= '
'; $s .= '
'; $s .= '
'; $s .= ''; } - -?> diff --git a/cal/lang/C/strings.php b/cal/lang/C/strings.php index a72dc119..d4535ccc 100644 --- a/cal/lang/C/strings.php +++ b/cal/lang/C/strings.php @@ -1,12 +1,12 @@ strings["Event Export"] = ""; -$a->strings["You can download public events from: "] = ""; -$a->strings["The user does not export the calendar."] = ""; -$a->strings["This calendar format is not supported"] = ""; -$a->strings["Export Events"] = ""; -$a->strings["If this is enabled, your public events will be available at"] = ""; -$a->strings["Currently supported formats are ical and csv."] = ""; -$a->strings["Enable calendar export"] = ""; -$a->strings["Submit"] = ""; + +$a->strings['Event Export'] = ''; +$a->strings['You can download public events from: '] = ''; +$a->strings['The user does not export the calendar.'] = ''; +$a->strings['This calendar format is not supported'] = ''; +$a->strings['Export Events'] = ''; +$a->strings['If this is enabled, your public events will be available at'] = ''; +$a->strings['Currently supported formats are ical and csv.'] = ''; +$a->strings['Enable calendar export'] = ''; +$a->strings['Submit'] = ''; diff --git a/cal/lang/cs/strings.php b/cal/lang/cs/strings.php index 9a99079d..177a02ab 100644 --- a/cal/lang/cs/strings.php +++ b/cal/lang/cs/strings.php @@ -1,16 +1,18 @@ =2 && $n<=4) ? 1 : 2;; -}} -; -$a->strings["Event Export"] = "Export událostí"; -$a->strings["You can download public events from: "] = "Veřejné události si můžete stánout z:"; -$a->strings["The user does not export the calendar."] = "Uživatel kalenář neexportuje."; -$a->strings["This calendar format is not supported"] = "Tento kalendářový formát není podporován."; -$a->strings["Export Events"] = "Export událostí"; -$a->strings["If this is enabled, your public events will be available at"] = "Pokud je toto povoleno, vaše veřejné události budou viditelné na"; -$a->strings["Currently supported formats are ical and csv."] = "Aktuálně podporované formáty jsou ical a csv."; -$a->strings["Enable calendar export"] = "Povolit export kalendáře"; -$a->strings["Save Settings"] = "Uložit Nastavení"; +if (!function_exists('string_plural_select_cs')) { + function string_plural_select_cs($n) + { + return ($n == 1) ? 0 : ($n >= 2 && $n <= 4) ? 1 : 2; + } +} + +$a->strings['Event Export'] = 'Export událostí'; +$a->strings['You can download public events from: '] = 'Veřejné události si můžete stánout z:'; +$a->strings['The user does not export the calendar.'] = 'Uživatel kalenář neexportuje.'; +$a->strings['This calendar format is not supported'] = 'Tento kalendářový formát není podporován.'; +$a->strings['Export Events'] = 'Export událostí'; +$a->strings['If this is enabled, your public events will be available at'] = 'Pokud je toto povoleno, vaše veřejné události budou viditelné na'; +$a->strings['Currently supported formats are ical and csv.'] = 'Aktuálně podporované formáty jsou ical a csv.'; +$a->strings['Enable calendar export'] = 'Povolit export kalendáře'; +$a->strings['Save Settings'] = 'Uložit Nastavení'; diff --git a/cal/lang/de/strings.php b/cal/lang/de/strings.php index 39359271..75a6e6ef 100644 --- a/cal/lang/de/strings.php +++ b/cal/lang/de/strings.php @@ -1,16 +1,18 @@ strings["Event Export"] = "Ereignis Export"; -$a->strings["You can download public events from: "] = "Du kannst öffentliche Ereignisse hier herunterladen;"; -$a->strings["The user does not export the calendar."] = "Diese_r Nutzer_in exportiert den Kalender nicht."; -$a->strings["This calendar format is not supported"] = "Dieses Kalenderformat wird nicht unterstützt."; -$a->strings["Export Events"] = "Exportiere Ereignisse"; -$a->strings["If this is enabled, your public events will be available at"] = "Wenn dies aktiviert ist, werden alle öffentliche Ereignisse unter folgender URL verfügbar sein"; -$a->strings["Currently supported formats are ical and csv."] = "Derzeit werden die Formate ical und csv unterstützt."; -$a->strings["Enable calendar export"] = "Kalenderexport aktivieren"; -$a->strings["Save Settings"] = "Einstellungen speichern"; +if (!function_exists('string_plural_select_de')) { + function string_plural_select_de($n) + { + return $n != 1; + } +} + +$a->strings['Event Export'] = 'Ereignis Export'; +$a->strings['You can download public events from: '] = 'Du kannst öffentliche Ereignisse hier herunterladen;'; +$a->strings['The user does not export the calendar.'] = 'Diese_r Nutzer_in exportiert den Kalender nicht.'; +$a->strings['This calendar format is not supported'] = 'Dieses Kalenderformat wird nicht unterstützt.'; +$a->strings['Export Events'] = 'Exportiere Ereignisse'; +$a->strings['If this is enabled, your public events will be available at'] = 'Wenn dies aktiviert ist, werden alle öffentliche Ereignisse unter folgender URL verfügbar sein'; +$a->strings['Currently supported formats are ical and csv.'] = 'Derzeit werden die Formate ical und csv unterstützt.'; +$a->strings['Enable calendar export'] = 'Kalenderexport aktivieren'; +$a->strings['Save Settings'] = 'Einstellungen speichern'; diff --git a/cal/lang/fr/strings.php b/cal/lang/fr/strings.php index b3517062..6e8a179d 100644 --- a/cal/lang/fr/strings.php +++ b/cal/lang/fr/strings.php @@ -1,16 +1,18 @@ 1);; -}} -; -$a->strings["Event Export"] = "Exportation d'événement"; -$a->strings["You can download public events from: "] = "Vous pouvez télécharger les événements publiques de :"; -$a->strings["The user does not export the calendar."] = "L'utilisateur n'exporte pas le calendrier."; -$a->strings["This calendar format is not supported"] = "Ce format de calendrier n'est pas pris en charge"; -$a->strings["Export Events"] = "Exporter les événements"; -$a->strings["If this is enabled, your public events will be available at"] = "Si activé, vos événements publiques seront disponible à"; -$a->strings["Currently supported formats are ical and csv."] = "Les formats actuellement pris en charge sont ical et csv."; -$a->strings["Enable calendar export"] = "Activer l'export de calendrier"; -$a->strings["Save Settings"] = "Sauvegarder les paramètres"; +if (!function_exists('string_plural_select_fr')) { + function string_plural_select_fr($n) + { + return $n > 1; + } +} + +$a->strings['Event Export'] = "Exportation d'événement"; +$a->strings['You can download public events from: '] = 'Vous pouvez télécharger les événements publiques de :'; +$a->strings['The user does not export the calendar.'] = "L'utilisateur n'exporte pas le calendrier."; +$a->strings['This calendar format is not supported'] = "Ce format de calendrier n'est pas pris en charge"; +$a->strings['Export Events'] = 'Exporter les événements'; +$a->strings['If this is enabled, your public events will be available at'] = 'Si activé, vos événements publiques seront disponible à'; +$a->strings['Currently supported formats are ical and csv.'] = 'Les formats actuellement pris en charge sont ical et csv.'; +$a->strings['Enable calendar export'] = "Activer l'export de calendrier"; +$a->strings['Save Settings'] = 'Sauvegarder les paramètres'; diff --git a/cal/lang/it/strings.php b/cal/lang/it/strings.php index c7f228bb..dd48f339 100644 --- a/cal/lang/it/strings.php +++ b/cal/lang/it/strings.php @@ -1,16 +1,18 @@ strings["Event Export"] = "Esporta Evento"; -$a->strings["You can download public events from: "] = "Puoi scaricare gli eventi publici da:"; -$a->strings["The user does not export the calendar."] = "L'utente non esporta il calendario."; -$a->strings["This calendar format is not supported"] = "Il formato del calendario non è supportato"; -$a->strings["Export Events"] = "Esporta Eventi"; -$a->strings["If this is enabled, your public events will be available at"] = "Se abilitato, i tuoi eventi pubblici saranno disponibili a"; -$a->strings["Currently supported formats are ical and csv."] = "I formati supportati sono ical e csv."; -$a->strings["Enable calendar export"] = "Abilita esporazione calendario"; -$a->strings["Save Settings"] = "Salva Impostazioni"; +if (!function_exists('string_plural_select_it')) { + function string_plural_select_it($n) + { + return $n != 1; + } +} + +$a->strings['Event Export'] = 'Esporta Evento'; +$a->strings['You can download public events from: '] = 'Puoi scaricare gli eventi publici da:'; +$a->strings['The user does not export the calendar.'] = "L'utente non esporta il calendario."; +$a->strings['This calendar format is not supported'] = 'Il formato del calendario non è supportato'; +$a->strings['Export Events'] = 'Esporta Eventi'; +$a->strings['If this is enabled, your public events will be available at'] = 'Se abilitato, i tuoi eventi pubblici saranno disponibili a'; +$a->strings['Currently supported formats are ical and csv.'] = 'I formati supportati sono ical e csv.'; +$a->strings['Enable calendar export'] = 'Abilita esporazione calendario'; +$a->strings['Save Settings'] = 'Salva Impostazioni'; diff --git a/cal/lang/pt-br/strings.php b/cal/lang/pt-br/strings.php index 69e35ea5..1c9b8501 100644 --- a/cal/lang/pt-br/strings.php +++ b/cal/lang/pt-br/strings.php @@ -1,16 +1,18 @@ 1);; -}} -; -$a->strings["Event Export"] = "Exportar Evento"; -$a->strings["You can download public events from: "] = "Você pode baixar eventos públicos de:"; -$a->strings["The user does not export the calendar."] = "O usuário não exportou o calendário."; -$a->strings["This calendar format is not supported"] = "Esse formato de calendário não é suportado."; -$a->strings["Export Events"] = "Exporta Eventos"; -$a->strings["If this is enabled, your public events will be available at"] = "Se isso estiver habiltiado, seus eventos públicos estarão disponíveis"; -$a->strings["Currently supported formats are ical and csv."] = "Os formatos disponíveis atualmente são ical e csv."; -$a->strings["Enable calendar export"] = "Habilite exportar calendário"; -$a->strings["Save Settings"] = "Salvar as Configurações"; +if (!function_exists('string_plural_select_pt_br')) { + function string_plural_select_pt_br($n) + { + return $n > 1; + } +} + +$a->strings['Event Export'] = 'Exportar Evento'; +$a->strings['You can download public events from: '] = 'Você pode baixar eventos públicos de:'; +$a->strings['The user does not export the calendar.'] = 'O usuário não exportou o calendário.'; +$a->strings['This calendar format is not supported'] = 'Esse formato de calendário não é suportado.'; +$a->strings['Export Events'] = 'Exporta Eventos'; +$a->strings['If this is enabled, your public events will be available at'] = 'Se isso estiver habiltiado, seus eventos públicos estarão disponíveis'; +$a->strings['Currently supported formats are ical and csv.'] = 'Os formatos disponíveis atualmente são ical e csv.'; +$a->strings['Enable calendar export'] = 'Habilite exportar calendário'; +$a->strings['Save Settings'] = 'Salvar as Configurações'; diff --git a/cal/lang/ro/strings.php b/cal/lang/ro/strings.php index 8e328e98..e643ccd4 100644 --- a/cal/lang/ro/strings.php +++ b/cal/lang/ro/strings.php @@ -1,16 +1,18 @@ 19)||(($n%100==0)&&($n!=0)))?2:1));; -}} -; -$a->strings["Event Export"] = "Exportare Eveniment"; -$a->strings["You can download public events from: "] = "Puteți descărca evenimente publice de la:"; -$a->strings["The user does not export the calendar."] = "Utilizatorul nu își exportă calendarul."; -$a->strings["This calendar format is not supported"] = "Acest format de calendar nu este acceptat"; -$a->strings["Export Events"] = "Exportați Evenimente"; -$a->strings["If this is enabled, your public events will be available at"] = "Dacă este activat, evenimente dvs publice vor fi disponibile pe"; -$a->strings["Currently supported formats are ical and csv."] = "Formate acceptate în prezent sunt ical şi csv."; -$a->strings["Enable calendar export"] = "Activați exportarea calendarului"; -$a->strings["Save Settings"] = "Salvare Configurări"; +if (!function_exists('string_plural_select_ro')) { + function string_plural_select_ro($n) + { + return $n == 1 ? 0 : ((($n % 100 > 19) || (($n % 100 == 0) && ($n != 0))) ? 2 : 1); + } +} + +$a->strings['Event Export'] = 'Exportare Eveniment'; +$a->strings['You can download public events from: '] = 'Puteți descărca evenimente publice de la:'; +$a->strings['The user does not export the calendar.'] = 'Utilizatorul nu își exportă calendarul.'; +$a->strings['This calendar format is not supported'] = 'Acest format de calendar nu este acceptat'; +$a->strings['Export Events'] = 'Exportați Evenimente'; +$a->strings['If this is enabled, your public events will be available at'] = 'Dacă este activat, evenimente dvs publice vor fi disponibile pe'; +$a->strings['Currently supported formats are ical and csv.'] = 'Formate acceptate în prezent sunt ical şi csv.'; +$a->strings['Enable calendar export'] = 'Activați exportarea calendarului'; +$a->strings['Save Settings'] = 'Salvare Configurări'; diff --git a/calc/calc.php b/calc/calc.php index a299d45e..db7a6bec 100755 --- a/calc/calc.php +++ b/calc/calc.php @@ -1,363 +1,361 @@ - - */ - - -function calc_install() { - register_hook('app_menu', 'addon/calc/calc.php', 'calc_app_menu'); -} - -function calc_uninstall() { - unregister_hook('app_menu', 'addon/calc/calc.php', 'calc_app_menu'); - -} - -function calc_app_menu($a,&$b) { - $b['app_menu'][] = ''; -} - - -function calc_module() {} - - - - -function calc_init($a) { - -$x = <<< EOT - - - -EOT; -$a->page['htmlhead'] .= $x; -} - -function calc_content($app) { - -$o = ''; - -$o .= <<< EOT - -

Calculator

-

- -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
- - - - -
- - -
- -EOT; -return $o; - -} +. + */ +function calc_install() +{ + register_hook('app_menu', 'addon/calc/calc.php', 'calc_app_menu'); +} + +function calc_uninstall() +{ + unregister_hook('app_menu', 'addon/calc/calc.php', 'calc_app_menu'); +} + +function calc_app_menu($a, &$b) +{ + $b['app_menu'][] = ''; +} + +function calc_module() +{ +} + +function calc_init($a) +{ + $x = <<< 'EOT' + + + +EOT; + $a->page['htmlhead'] .= $x; +} + +function calc_content($app) +{ + $o = ''; + + $o .= <<< 'EOT' + +

Calculator

+

+ +
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + +
+ + +
+ +EOT; + + return $o; +} diff --git a/communityhome/communityhome.php b/communityhome/communityhome.php index ff3215d3..1051d5da 100755 --- a/communityhome/communityhome.php +++ b/communityhome/communityhome.php @@ -3,78 +3,79 @@ * Name: Community home * Description: Show last community activity in homepage * Version: 2.0 - * Author: Fabio Comuni + * Author: Fabio Comuni . */ +require_once 'mod/community.php'; - -require_once('mod/community.php'); - - -function communityhome_install() { - register_hook('home_content', 'addon/communityhome/communityhome.php', 'communityhome_home'); - logger("installed communityhome"); +function communityhome_install() +{ + register_hook('home_content', 'addon/communityhome/communityhome.php', 'communityhome_home'); + logger('installed communityhome'); } -function communityhome_uninstall() { - unregister_hook('home_content', 'addon/communityhome/communityhome.php', 'communityhome_home'); - logger("removed communityhome"); +function communityhome_uninstall() +{ + unregister_hook('home_content', 'addon/communityhome/communityhome.php', 'communityhome_home'); + logger('removed communityhome'); } -function communityhome_home(&$a, &$o){ - // custom css - $a->page['htmlhead'] .= ''; +function communityhome_home(&$a, &$o) +{ + // custom css + $a->page['htmlhead'] .= ''; - if (!get_config('communityhome','hidelogin')){ - $aside = array( - '$tab_1' => t('Login'), - '$tab_2' => t('OpenID'), - '$noOid' => get_config('system','no_openid'), - ); + if (!get_config('communityhome', 'hidelogin')) { + $aside = array( + '$tab_1' => t('Login'), + '$tab_2' => t('OpenID'), + '$noOid' => get_config('system', 'no_openid'), + ); - // login form - $aside['$login_title'] = t('Login'); - $aside['$login_form'] = login(($a->config['register_policy'] == REGISTER_CLOSED) ? false : true); - } else - $aside = array( - //'$tab_1' => t('Login'), - //'$tab_2' => t('OpenID'), - //'$noOid' => get_config('system','no_openid'), - ); + // login form + $aside['$login_title'] = t('Login'); + $aside['$login_form'] = login(($a->config['register_policy'] == REGISTER_CLOSED) ? false : true); + } else { + $aside = array( + //'$tab_1' => t('Login'), + //'$tab_2' => t('OpenID'), + //'$noOid' => get_config('system','no_openid'), + ); + } - // last 12 users - if (get_config('communityhome','showlastusers')===true){ - $aside['$lastusers_title'] = t('Latest users'); - $aside['$lastusers_items'] = array(); - $sql_extra = ""; - $publish = (get_config('system','publish_all') ? '' : " AND `publish` = 1 " ); - $order = " ORDER BY `register_date` DESC "; + // last 12 users + if (get_config('communityhome', 'showlastusers') === true) { + $aside['$lastusers_title'] = t('Latest users'); + $aside['$lastusers_items'] = array(); + $sql_extra = ''; + $publish = (get_config('system', 'publish_all') ? '' : ' AND `publish` = 1 '); + $order = ' ORDER BY `register_date` DESC '; - $r = q("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname` + $r = q("SELECT `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname` FROM `profile` LEFT JOIN `user` ON `user`.`uid` = `profile`.`uid` WHERE `is-default` = 1 $publish AND `user`.`blocked` = 0 $sql_extra $order LIMIT %d , %d ", - 0, - 12 - ); - # $tpl = file_get_contents( dirname(__file__).'/directory_item.tpl'); - $tpl = get_markup_template( 'directory_item.tpl', 'addon/communityhome/' ); - if(count($r)) { - $photo = 'thumb'; - foreach($r as $rr) { - $profile_link = $a->get_baseurl() . '/profile/' . ((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']); - $entry = replace_macros($tpl,array( - '$id' => $rr['id'], - '$profile_link' => $profile_link, - '$photo' => $a->get_cached_avatar_image($rr[$photo]), - '$alt_text' => $rr['name'], - )); - $aside['$lastusers_items'][] = $entry; - } - } - } - // 12 most active users (by posts and contacts) - // this query don't work on some mysql versions - if (get_config('communityhome','showactiveusers')===true){ - $r = q("SELECT `uni`.`contacts`,`uni`.`items`, `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname` FROM + 0, + 12 + ); + // $tpl = file_get_contents( dirname(__file__).'/directory_item.tpl'); + $tpl = get_markup_template('directory_item.tpl', 'addon/communityhome/'); + if (count($r)) { + $photo = 'thumb'; + foreach ($r as $rr) { + $profile_link = $a->get_baseurl().'/profile/'.((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']); + $entry = replace_macros($tpl, array( + '$id' => $rr['id'], + '$profile_link' => $profile_link, + '$photo' => $a->get_cached_avatar_image($rr[$photo]), + '$alt_text' => $rr['name'], + )); + $aside['$lastusers_items'][] = $entry; + } + } + } + // 12 most active users (by posts and contacts) + // this query don't work on some mysql versions + if (get_config('communityhome', 'showactiveusers') === true) { + $r = q('SELECT `uni`.`contacts`,`uni`.`items`, `profile`.*, `profile`.`uid` AS `profile_uid`, `user`.`nickname` FROM (SELECT COUNT(*) as `contacts`, `uid` FROM `contact` WHERE `self`=0 GROUP BY `uid`) AS `con`, (SELECT COUNT(*) as `items`, `uid` FROM `item` WHERE `item`.`changed` > DATE(NOW() - INTERVAL 1 MONTH) AND `item`.`wall` = 1 GROUP BY `uid`) AS `ite`, ( @@ -86,29 +87,29 @@ function communityhome_home(&$a, &$o){ AND `uni`.`uid`=`profile`.`uid` AND `profile`.`publish`=1 GROUP BY `uid` ORDER BY `items` DESC,`contacts` DESC - LIMIT 0,10"); - if($r && count($r)) { - $aside['$activeusers_title'] = t('Most active users'); - $aside['$activeusers_items'] = array(); + LIMIT 0,10'); + if ($r && count($r)) { + $aside['$activeusers_title'] = t('Most active users'); + $aside['$activeusers_items'] = array(); - $photo = 'thumb'; - foreach($r as $rr) { - $profile_link = $a->get_baseurl() . '/profile/' . ((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']); - $entry = replace_macros($tpl,array( - '$id' => $rr['id'], - '$profile_link' => $profile_link, - '$photo' => $rr[$photo], - '$alt_text' => sprintf("%s (%s posts, %s contacts)",$rr['name'], ($rr['items']?$rr['items']:'0'), ($rr['contacts']?$rr['contacts']:'0')) - )); - $aside['$activeusers_items'][] = $entry; - } - } - } - // last 12 photos - if (get_config('communityhome','showlastphotos')===true){ - $aside['$photos_title'] = t('Latest photos'); - $aside['$photos_items'] = array(); - $r = q("SELECT `photo`.`id`, `photo`.`resource-id`, `photo`.`scale`, `photo`.`desc`, `user`.`nickname`, `user`.`username` FROM + $photo = 'thumb'; + foreach ($r as $rr) { + $profile_link = $a->get_baseurl().'/profile/'.((strlen($rr['nickname'])) ? $rr['nickname'] : $rr['profile_uid']); + $entry = replace_macros($tpl, array( + '$id' => $rr['id'], + '$profile_link' => $profile_link, + '$photo' => $rr[$photo], + '$alt_text' => sprintf('%s (%s posts, %s contacts)', $rr['name'], ($rr['items'] ? $rr['items'] : '0'), ($rr['contacts'] ? $rr['contacts'] : '0')), + )); + $aside['$activeusers_items'][] = $entry; + } + } + } + // last 12 photos + if (get_config('communityhome', 'showlastphotos') === true) { + $aside['$photos_title'] = t('Latest photos'); + $aside['$photos_items'] = array(); + $r = q("SELECT `photo`.`id`, `photo`.`resource-id`, `photo`.`scale`, `photo`.`desc`, `user`.`nickname`, `user`.`username` FROM (SELECT `resource-id`, MAX(`scale`) as maxscale FROM `photo` WHERE `profile`=0 AND `contact-id`=0 AND `album` NOT IN ('Contact Photos', '%s', 'Profile Photos', '%s') AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`='' GROUP BY `resource-id`) AS `t1` @@ -119,35 +120,34 @@ function communityhome_home(&$a, &$o){ AND `user`.`hidewall` = 0 ORDER BY `photo`.`edited` DESC LIMIT 0, 12", - dbesc(t('Contact Photos')), - dbesc(t('Profile Photos')) - ); + dbesc(t('Contact Photos')), + dbesc(t('Profile Photos')) + ); + if (count($r)) { + // $tpl = file_get_contents( dirname(__file__).'/directory_item.tpl'); + $tpl = get_markup_template('directory_item.tpl', 'addon/communityhome/'); + foreach ($r as $rr) { + $photo_page = $a->get_baseurl().'/photos/'.$rr['nickname'].'/image/'.$rr['resource-id']; + $photo_url = $a->get_baseurl().'/photo/'.$rr['resource-id'].'-'.$rr['scale'].'.jpg'; - if(count($r)) { - # $tpl = file_get_contents( dirname(__file__).'/directory_item.tpl'); - $tpl = get_markup_template( 'directory_item.tpl', 'addon/communityhome/' ); - foreach($r as $rr) { - $photo_page = $a->get_baseurl() . '/photos/' . $rr['nickname'] . '/image/' . $rr['resource-id']; - $photo_url = $a->get_baseurl() . '/photo/' . $rr['resource-id'] . '-' . $rr['scale'] .'.jpg'; + $entry = replace_macros($tpl, array( + '$id' => $rr['id'], + '$profile_link' => $photo_page, + '$photo' => $photo_url, + '$alt_text' => $rr['username'].' : '.$rr['desc'], + )); - $entry = replace_macros($tpl,array( - '$id' => $rr['id'], - '$profile_link' => $photo_page, - '$photo' => $photo_url, - '$alt_text' => $rr['username']." : ".$rr['desc'], - )); + $aside['$photos_items'][] = $entry; + } + } + } - $aside['$photos_items'][] = $entry; - } - } - } - - // last 10 liked items - if (get_config('communityhome','showlastlike')===true){ - $aside['$like_title'] = t('Latest likes'); - $aside['$like_items'] = array(); - $r = q("SELECT `T1`.`created`, `T1`.`liker`, `T1`.`liker-link`, `item`.* FROM + // last 10 liked items + if (get_config('communityhome', 'showlastlike') === true) { + $aside['$like_title'] = t('Latest likes'); + $aside['$like_items'] = array(); + $r = q("SELECT `T1`.`created`, `T1`.`liker`, `T1`.`liker-link`, `item`.* FROM (SELECT `parent-uri`, `created`, `author-name` AS `liker`,`author-link` AS `liker-link` FROM `item` WHERE `verb`='http://activitystrea.ms/schema/1.0/like' GROUP BY `parent-uri` ORDER BY `created` DESC) AS T1 INNER JOIN `item` ON `item`.`uri`=`T1`.`parent-uri` @@ -155,57 +155,60 @@ function communityhome_home(&$a, &$o){ GROUP BY `uri` ORDER BY `T1`.`created` DESC LIMIT 0,10", - $a->get_baseurl(),$a->get_baseurl() - ); + $a->get_baseurl(), $a->get_baseurl() + ); - foreach ($r as $rr) { - $author = '' . $rr['liker'] . ''; - $objauthor = '' . $rr['author-name'] . ''; + foreach ($r as $rr) { + $author = ''.$rr['liker'].''; + $objauthor = ''.$rr['author-name'].''; - //var_dump($rr['verb'],$rr['object-type']); killme(); - switch($rr['verb']){ - case 'http://activitystrea.ms/schema/1.0/post': - switch ($rr['object-type']){ - case 'http://activitystrea.ms/schema/1.0/event': - $post_type = t('event'); - break; - default: - $post_type = t('status'); - } - break; - default: - if ($rr['resource-id']){ - $post_type = t('photo'); - $m=array(); preg_match("/\[url=([^]]*)\]/", $rr['body'], $m); - $rr['plink'] = $m[1]; - } else { - $post_type = t('status'); - } - } - $plink = '' . $post_type . ''; + //var_dump($rr['verb'],$rr['object-type']); killme(); + switch ($rr['verb']) { + case 'http://activitystrea.ms/schema/1.0/post': + switch ($rr['object-type']) { + case 'http://activitystrea.ms/schema/1.0/event': + $post_type = t('event'); + break; + default: + $post_type = t('status'); + } + break; + default: + if ($rr['resource-id']) { + $post_type = t('photo'); + $m = array(); + preg_match("/\[url=([^]]*)\]/", $rr['body'], $m); + $rr['plink'] = $m[1]; + } else { + $post_type = t('status'); + } + } + $plink = ''.$post_type.''; - $aside['$like_items'][] = sprintf( t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink); + $aside['$like_items'][] = sprintf(t('%1$s likes %2$s\'s %3$s'), $author, $objauthor, $plink); + } + } - } - } +// $tpl = file_get_contents(dirname(__file__).'/communityhome.tpl'); + $tpl = get_markup_template('communityhome.tpl', 'addon/communityhome/'); + $a->page['aside'] = replace_macros($tpl, $aside); -# $tpl = file_get_contents(dirname(__file__).'/communityhome.tpl'); - $tpl = get_markup_template('communityhome.tpl', 'addon/communityhome/'); - $a->page['aside'] = replace_macros($tpl, $aside); + $o = '

'.((x($a->config, 'sitename')) ? sprintf(t('Welcome to %s'), $a->config['sitename']) : '').'

'; - $o = '

' . ((x($a->config,'sitename')) ? sprintf( t("Welcome to %s") ,$a->config['sitename']) : "" ) . '

'; + if (file_exists('home.html')) { + $o = file_get_contents('home.html'); + } - if(file_exists('home.html')) - $o = file_get_contents('home.html'); + if (get_config('communityhome', 'showcommunitystream') === true) { + $oldset = get_config('system', 'community_page_style'); + if ($oldset == CP_NO_COMMUNITY_PAGE) { + set_config('system', 'community_page_style', CP_USERS_ON_SERVER); + } - if (get_config('communityhome','showcommunitystream')===true){ - $oldset = get_config('system','community_page_style'); - if ($oldset == CP_NO_COMMUNITY_PAGE) - set_config('system','community_page_style', CP_USERS_ON_SERVER); + $o .= community_content($a, 1); - $o .= community_content($a,1); - - if ($oldset == CP_NO_COMMUNITY_PAGE) - set_config('system','community_page_style', $oldset); - } + if ($oldset == CP_NO_COMMUNITY_PAGE) { + set_config('system', 'community_page_style', $oldset); + } + } } diff --git a/communityhome/lang/ca/strings.php b/communityhome/lang/ca/strings.php index d0e6bd43..ad21fb1d 100644 --- a/communityhome/lang/ca/strings.php +++ b/communityhome/lang/ca/strings.php @@ -1,14 +1,14 @@ -strings["Login"] = "Identifica't"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "Últims usuaris"; -$a->strings["Most active users"] = "Usuaris més actius"; -$a->strings["Latest photos"] = "Darreres fotos"; -$a->strings["Contact Photos"] = "Fotos de Contacte"; -$a->strings["Profile Photos"] = "Fotos del Perfil"; -$a->strings["Latest likes"] = "Darrers agrada"; -$a->strings["event"] = "esdeveniment"; -$a->strings["status"] = "estatus"; -$a->strings["photo"] = "foto"; -$a->strings["Welcome to %s"] = "Benvingut a %s"; +strings['Login'] = "Identifica't"; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = 'Últims usuaris'; +$a->strings['Most active users'] = 'Usuaris més actius'; +$a->strings['Latest photos'] = 'Darreres fotos'; +$a->strings['Contact Photos'] = 'Fotos de Contacte'; +$a->strings['Profile Photos'] = 'Fotos del Perfil'; +$a->strings['Latest likes'] = 'Darrers agrada'; +$a->strings['event'] = 'esdeveniment'; +$a->strings['status'] = 'estatus'; +$a->strings['photo'] = 'foto'; +$a->strings['Welcome to %s'] = 'Benvingut a %s'; diff --git a/communityhome/lang/cs/strings.php b/communityhome/lang/cs/strings.php index 06cf3f36..58dc7999 100644 --- a/communityhome/lang/cs/strings.php +++ b/communityhome/lang/cs/strings.php @@ -1,20 +1,22 @@ =2 && $n<=4) ? 1 : 2;; -}} -; -$a->strings["Login"] = "Přihlásit se"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "Poslední uživatelé"; -$a->strings["Most active users"] = "Nejaktivnější uživatelé"; -$a->strings["Latest photos"] = "Poslední fotky"; -$a->strings["Contact Photos"] = "Fotogalerie kontaktu"; -$a->strings["Profile Photos"] = "Profilové fotografie"; -$a->strings["Latest likes"] = "Poslední \"líbí se mi\""; -$a->strings["event"] = "událost"; -$a->strings["status"] = "Stav"; -$a->strings["photo"] = "fotografie"; -$a->strings["%1\$s likes %2\$s's %3\$s"] = "Uživateli %1\$s se líbí %3\$s uživatele %2\$s"; -$a->strings["Welcome to %s"] = "Vítá Vás %s"; +if (!function_exists('string_plural_select_cs')) { + function string_plural_select_cs($n) + { + return ($n == 1) ? 0 : ($n >= 2 && $n <= 4) ? 1 : 2; + } +} + +$a->strings['Login'] = 'Přihlásit se'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = 'Poslední uživatelé'; +$a->strings['Most active users'] = 'Nejaktivnější uživatelé'; +$a->strings['Latest photos'] = 'Poslední fotky'; +$a->strings['Contact Photos'] = 'Fotogalerie kontaktu'; +$a->strings['Profile Photos'] = 'Profilové fotografie'; +$a->strings['Latest likes'] = 'Poslední "líbí se mi"'; +$a->strings['event'] = 'událost'; +$a->strings['status'] = 'Stav'; +$a->strings['photo'] = 'fotografie'; +$a->strings["%1\$s likes %2\$s's %3\$s"] = 'Uživateli %1$s se líbí %3$s uživatele %2$s'; +$a->strings['Welcome to %s'] = 'Vítá Vás %s'; diff --git a/communityhome/lang/de/strings.php b/communityhome/lang/de/strings.php index 87b9bccf..55fc5a7a 100644 --- a/communityhome/lang/de/strings.php +++ b/communityhome/lang/de/strings.php @@ -1,20 +1,22 @@ strings["Login"] = "Anmeldung"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "Letzte Benutzer"; -$a->strings["Most active users"] = "Aktivste Nutzer"; -$a->strings["Latest photos"] = "Neueste Fotos"; -$a->strings["Contact Photos"] = "Kontaktbilder"; -$a->strings["Profile Photos"] = "Profilbilder"; -$a->strings["Latest likes"] = "Neueste Favoriten"; -$a->strings["event"] = "Veranstaltung"; -$a->strings["status"] = "Status"; -$a->strings["photo"] = "Foto"; +if (!function_exists('string_plural_select_de')) { + function string_plural_select_de($n) + { + return $n != 1; + } +} + +$a->strings['Login'] = 'Anmeldung'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = 'Letzte Benutzer'; +$a->strings['Most active users'] = 'Aktivste Nutzer'; +$a->strings['Latest photos'] = 'Neueste Fotos'; +$a->strings['Contact Photos'] = 'Kontaktbilder'; +$a->strings['Profile Photos'] = 'Profilbilder'; +$a->strings['Latest likes'] = 'Neueste Favoriten'; +$a->strings['event'] = 'Veranstaltung'; +$a->strings['status'] = 'Status'; +$a->strings['photo'] = 'Foto'; $a->strings["%1\$s likes %2\$s's %3\$s"] = "%1\$s mag %2\$s's %3\$s"; -$a->strings["Welcome to %s"] = "Willkommen zu %s"; +$a->strings['Welcome to %s'] = 'Willkommen zu %s'; diff --git a/communityhome/lang/eo/strings.php b/communityhome/lang/eo/strings.php index db0fc8c0..0e412301 100644 --- a/communityhome/lang/eo/strings.php +++ b/communityhome/lang/eo/strings.php @@ -1,14 +1,14 @@ -strings["Login"] = "Ensaluti"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "Ĵusaj uzantoj"; -$a->strings["Most active users"] = "Plej aktivaj uzantoj"; -$a->strings["Latest photos"] = "Ĵusaj bildoj"; -$a->strings["Contact Photos"] = "Kontaktbildoj"; -$a->strings["Profile Photos"] = "Profilbildoj"; -$a->strings["Latest likes"] = "Ĵusaj ŝatitaĵoj"; -$a->strings["event"] = "okazo"; -$a->strings["status"] = "staton"; -$a->strings["photo"] = "bildo"; -$a->strings["Welcome to %s"] = "Bonvenon ĉe %s"; +strings['Login'] = 'Ensaluti'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = 'Ĵusaj uzantoj'; +$a->strings['Most active users'] = 'Plej aktivaj uzantoj'; +$a->strings['Latest photos'] = 'Ĵusaj bildoj'; +$a->strings['Contact Photos'] = 'Kontaktbildoj'; +$a->strings['Profile Photos'] = 'Profilbildoj'; +$a->strings['Latest likes'] = 'Ĵusaj ŝatitaĵoj'; +$a->strings['event'] = 'okazo'; +$a->strings['status'] = 'staton'; +$a->strings['photo'] = 'bildo'; +$a->strings['Welcome to %s'] = 'Bonvenon ĉe %s'; diff --git a/communityhome/lang/es/strings.php b/communityhome/lang/es/strings.php index 25cea3ef..801cf98b 100644 --- a/communityhome/lang/es/strings.php +++ b/communityhome/lang/es/strings.php @@ -1,14 +1,14 @@ -strings["Login"] = "Acceder"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "Últimos usuarios"; -$a->strings["Most active users"] = "Usuarios más activos"; -$a->strings["Latest photos"] = "Últimas fotos"; -$a->strings["Contact Photos"] = "Foto del contacto"; -$a->strings["Profile Photos"] = "Foto del perfil"; -$a->strings["Latest likes"] = "Últimos me gusta"; -$a->strings["event"] = "evento"; -$a->strings["status"] = "estado"; -$a->strings["photo"] = "foto"; -$a->strings["Welcome to %s"] = "Bienvenido a %s"; +strings['Login'] = 'Acceder'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = 'Últimos usuarios'; +$a->strings['Most active users'] = 'Usuarios más activos'; +$a->strings['Latest photos'] = 'Últimas fotos'; +$a->strings['Contact Photos'] = 'Foto del contacto'; +$a->strings['Profile Photos'] = 'Foto del perfil'; +$a->strings['Latest likes'] = 'Últimos me gusta'; +$a->strings['event'] = 'evento'; +$a->strings['status'] = 'estado'; +$a->strings['photo'] = 'foto'; +$a->strings['Welcome to %s'] = 'Bienvenido a %s'; diff --git a/communityhome/lang/fr/strings.php b/communityhome/lang/fr/strings.php index 42a98c84..5e1607f2 100644 --- a/communityhome/lang/fr/strings.php +++ b/communityhome/lang/fr/strings.php @@ -1,20 +1,22 @@ 1);; -}} -; -$a->strings["Login"] = "Identifiant"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "Derniers utilisateurs"; -$a->strings["Most active users"] = "Utilisateurs les plus actifs"; -$a->strings["Latest photos"] = "Dernières photos"; -$a->strings["Contact Photos"] = "Photos du contact"; -$a->strings["Profile Photos"] = "Photos de profil"; -$a->strings["Latest likes"] = "Derniers likes"; -$a->strings["event"] = "événement"; -$a->strings["status"] = "statut"; -$a->strings["photo"] = "photo"; -$a->strings["%1\$s likes %2\$s's %3\$s"] = "%1\$s aime %3\$s de %2\$s"; -$a->strings["Welcome to %s"] = "Bienvenue sur %s"; +if (!function_exists('string_plural_select_fr')) { + function string_plural_select_fr($n) + { + return $n > 1; + } +} + +$a->strings['Login'] = 'Identifiant'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = 'Derniers utilisateurs'; +$a->strings['Most active users'] = 'Utilisateurs les plus actifs'; +$a->strings['Latest photos'] = 'Dernières photos'; +$a->strings['Contact Photos'] = 'Photos du contact'; +$a->strings['Profile Photos'] = 'Photos de profil'; +$a->strings['Latest likes'] = 'Derniers likes'; +$a->strings['event'] = 'événement'; +$a->strings['status'] = 'statut'; +$a->strings['photo'] = 'photo'; +$a->strings["%1\$s likes %2\$s's %3\$s"] = '%1$s aime %3$s de %2$s'; +$a->strings['Welcome to %s'] = 'Bienvenue sur %s'; diff --git a/communityhome/lang/is/strings.php b/communityhome/lang/is/strings.php index 743d16cd..30f90b50 100644 --- a/communityhome/lang/is/strings.php +++ b/communityhome/lang/is/strings.php @@ -1,14 +1,14 @@ -strings["Login"] = "Innskrá"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = ""; -$a->strings["Most active users"] = "Ofvirkustu notendurnir"; -$a->strings["Latest photos"] = ""; -$a->strings["Contact Photos"] = "Myndir tengiliðs"; -$a->strings["Profile Photos"] = "Forsíðu myndir"; -$a->strings["Latest likes"] = ""; -$a->strings["event"] = "atburður"; -$a->strings["status"] = "staða"; -$a->strings["photo"] = "mynd"; -$a->strings["Welcome to %s"] = "Velkomin(n) til %s"; +strings['Login'] = 'Innskrá'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = ''; +$a->strings['Most active users'] = 'Ofvirkustu notendurnir'; +$a->strings['Latest photos'] = ''; +$a->strings['Contact Photos'] = 'Myndir tengiliðs'; +$a->strings['Profile Photos'] = 'Forsíðu myndir'; +$a->strings['Latest likes'] = ''; +$a->strings['event'] = 'atburður'; +$a->strings['status'] = 'staða'; +$a->strings['photo'] = 'mynd'; +$a->strings['Welcome to %s'] = 'Velkomin(n) til %s'; diff --git a/communityhome/lang/it/strings.php b/communityhome/lang/it/strings.php index 422b35df..94b6486e 100644 --- a/communityhome/lang/it/strings.php +++ b/communityhome/lang/it/strings.php @@ -1,20 +1,22 @@ strings["Login"] = "Accedi"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "Ultimi utenti"; -$a->strings["Most active users"] = "Utenti più attivi"; -$a->strings["Latest photos"] = "Ultime foto"; -$a->strings["Contact Photos"] = "Foto dei contatti"; -$a->strings["Profile Photos"] = "Foto del profilo"; -$a->strings["Latest likes"] = "Ultimi \"mi piace\""; -$a->strings["event"] = "l'evento"; -$a->strings["status"] = "lo stato"; -$a->strings["photo"] = "la foto"; -$a->strings["%1\$s likes %2\$s's %3\$s"] = "a %1\$s piace %2\$s di %3\$s"; -$a->strings["Welcome to %s"] = "Benvenuto su %s"; +if (!function_exists('string_plural_select_it')) { + function string_plural_select_it($n) + { + return $n != 1; + } +} + +$a->strings['Login'] = 'Accedi'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = 'Ultimi utenti'; +$a->strings['Most active users'] = 'Utenti più attivi'; +$a->strings['Latest photos'] = 'Ultime foto'; +$a->strings['Contact Photos'] = 'Foto dei contatti'; +$a->strings['Profile Photos'] = 'Foto del profilo'; +$a->strings['Latest likes'] = 'Ultimi "mi piace"'; +$a->strings['event'] = "l'evento"; +$a->strings['status'] = 'lo stato'; +$a->strings['photo'] = 'la foto'; +$a->strings["%1\$s likes %2\$s's %3\$s"] = 'a %1$s piace %2$s di %3$s'; +$a->strings['Welcome to %s'] = 'Benvenuto su %s'; diff --git a/communityhome/lang/nb-no/strings.php b/communityhome/lang/nb-no/strings.php index d4ef19d3..7592e3c8 100644 --- a/communityhome/lang/nb-no/strings.php +++ b/communityhome/lang/nb-no/strings.php @@ -1,14 +1,14 @@ -strings["Login"] = "Logg inn"; -$a->strings["OpenID"] = ""; -$a->strings["Latest users"] = ""; -$a->strings["Most active users"] = ""; -$a->strings["Latest photos"] = ""; -$a->strings["Contact Photos"] = "Kontaktbilder"; -$a->strings["Profile Photos"] = "Profilbilder"; -$a->strings["Latest likes"] = ""; -$a->strings["event"] = "hendelse"; -$a->strings["status"] = "status"; -$a->strings["photo"] = "bilde"; -$a->strings["Welcome to %s"] = "Velkommen til %s"; +strings['Login'] = 'Logg inn'; +$a->strings['OpenID'] = ''; +$a->strings['Latest users'] = ''; +$a->strings['Most active users'] = ''; +$a->strings['Latest photos'] = ''; +$a->strings['Contact Photos'] = 'Kontaktbilder'; +$a->strings['Profile Photos'] = 'Profilbilder'; +$a->strings['Latest likes'] = ''; +$a->strings['event'] = 'hendelse'; +$a->strings['status'] = 'status'; +$a->strings['photo'] = 'bilde'; +$a->strings['Welcome to %s'] = 'Velkommen til %s'; diff --git a/communityhome/lang/pl/strings.php b/communityhome/lang/pl/strings.php index 86f152ca..1104ca1d 100644 --- a/communityhome/lang/pl/strings.php +++ b/communityhome/lang/pl/strings.php @@ -1,14 +1,14 @@ -strings["Login"] = "Login"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "Ostatni użytkownicy"; -$a->strings["Most active users"] = "najaktywniejsi użytkownicy"; -$a->strings["Latest photos"] = "Ostatnie zdjęcia"; -$a->strings["Contact Photos"] = "Zdjęcia kontaktu"; -$a->strings["Profile Photos"] = "Zdjęcia profilowe"; -$a->strings["Latest likes"] = "Ostatnie polubienia"; -$a->strings["event"] = "wydarzenie"; -$a->strings["status"] = "status"; -$a->strings["photo"] = "zdjęcie"; -$a->strings["Welcome to %s"] = "Witamy w %s"; +strings['Login'] = 'Login'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = 'Ostatni użytkownicy'; +$a->strings['Most active users'] = 'najaktywniejsi użytkownicy'; +$a->strings['Latest photos'] = 'Ostatnie zdjęcia'; +$a->strings['Contact Photos'] = 'Zdjęcia kontaktu'; +$a->strings['Profile Photos'] = 'Zdjęcia profilowe'; +$a->strings['Latest likes'] = 'Ostatnie polubienia'; +$a->strings['event'] = 'wydarzenie'; +$a->strings['status'] = 'status'; +$a->strings['photo'] = 'zdjęcie'; +$a->strings['Welcome to %s'] = 'Witamy w %s'; diff --git a/communityhome/lang/pt-br/strings.php b/communityhome/lang/pt-br/strings.php index d8dfeece..64032dd6 100644 --- a/communityhome/lang/pt-br/strings.php +++ b/communityhome/lang/pt-br/strings.php @@ -1,20 +1,22 @@ 1);; -}} -; -$a->strings["Login"] = "Entrar"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "Usuários mais recentes"; -$a->strings["Most active users"] = "Usuários mais ativos"; -$a->strings["Latest photos"] = "Fotos mais recentes"; -$a->strings["Contact Photos"] = "Fotos dos Contatos"; -$a->strings["Profile Photos"] = "Fotos do Perfil"; -$a->strings["Latest likes"] = "Curtidas recentes"; -$a->strings["event"] = "evento"; -$a->strings["status"] = "status"; -$a->strings["photo"] = "foto"; -$a->strings["%1\$s likes %2\$s's %3\$s"] = "%1\$s curtiu %2\$s que publicou %3\$s"; -$a->strings["Welcome to %s"] = "Bem-vindo a %s"; +if (!function_exists('string_plural_select_pt_br')) { + function string_plural_select_pt_br($n) + { + return $n > 1; + } +} + +$a->strings['Login'] = 'Entrar'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = 'Usuários mais recentes'; +$a->strings['Most active users'] = 'Usuários mais ativos'; +$a->strings['Latest photos'] = 'Fotos mais recentes'; +$a->strings['Contact Photos'] = 'Fotos dos Contatos'; +$a->strings['Profile Photos'] = 'Fotos do Perfil'; +$a->strings['Latest likes'] = 'Curtidas recentes'; +$a->strings['event'] = 'evento'; +$a->strings['status'] = 'status'; +$a->strings['photo'] = 'foto'; +$a->strings["%1\$s likes %2\$s's %3\$s"] = '%1$s curtiu %2$s que publicou %3$s'; +$a->strings['Welcome to %s'] = 'Bem-vindo a %s'; diff --git a/communityhome/lang/ro/strings.php b/communityhome/lang/ro/strings.php index faaf2c7e..4d9daeb0 100644 --- a/communityhome/lang/ro/strings.php +++ b/communityhome/lang/ro/strings.php @@ -1,20 +1,22 @@ 19)||(($n%100==0)&&($n!=0)))?2:1));; -}} -; -$a->strings["Login"] = "Autentificare"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "Cei mai recenți utilizatori"; -$a->strings["Most active users"] = "Cei mai activi utilizatori"; -$a->strings["Latest photos"] = "Cele mai recente fotografii"; -$a->strings["Contact Photos"] = "Fotografiile Contactului"; -$a->strings["Profile Photos"] = "Fotografii de Profil"; -$a->strings["Latest likes"] = "Cele mai recente aprecieri"; -$a->strings["event"] = "eveniment"; -$a->strings["status"] = "status"; -$a->strings["photo"] = "fotografie"; -$a->strings["%1\$s likes %2\$s's %3\$s"] = "%1\$s apreciază %3\$s lui %2\$s"; -$a->strings["Welcome to %s"] = "Bine ați venit la %s"; +if (!function_exists('string_plural_select_ro')) { + function string_plural_select_ro($n) + { + return $n == 1 ? 0 : ((($n % 100 > 19) || (($n % 100 == 0) && ($n != 0))) ? 2 : 1); + } +} + +$a->strings['Login'] = 'Autentificare'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = 'Cei mai recenți utilizatori'; +$a->strings['Most active users'] = 'Cei mai activi utilizatori'; +$a->strings['Latest photos'] = 'Cele mai recente fotografii'; +$a->strings['Contact Photos'] = 'Fotografiile Contactului'; +$a->strings['Profile Photos'] = 'Fotografii de Profil'; +$a->strings['Latest likes'] = 'Cele mai recente aprecieri'; +$a->strings['event'] = 'eveniment'; +$a->strings['status'] = 'status'; +$a->strings['photo'] = 'fotografie'; +$a->strings["%1\$s likes %2\$s's %3\$s"] = '%1$s apreciază %3$s lui %2$s'; +$a->strings['Welcome to %s'] = 'Bine ați venit la %s'; diff --git a/communityhome/lang/ru/strings.php b/communityhome/lang/ru/strings.php index 4cb87277..25631222 100644 --- a/communityhome/lang/ru/strings.php +++ b/communityhome/lang/ru/strings.php @@ -1,14 +1,14 @@ -strings["Login"] = "Вход"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = ""; -$a->strings["Most active users"] = "Самые активные пользователи"; -$a->strings["Latest photos"] = ""; -$a->strings["Contact Photos"] = "Фотографии контакта"; -$a->strings["Profile Photos"] = "Фотографии профиля"; -$a->strings["Latest likes"] = ""; -$a->strings["event"] = "мероприятие"; -$a->strings["status"] = "статус"; -$a->strings["photo"] = "фото"; -$a->strings["Welcome to %s"] = "Добро пожаловать на %s!"; +strings['Login'] = 'Вход'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = ''; +$a->strings['Most active users'] = 'Самые активные пользователи'; +$a->strings['Latest photos'] = ''; +$a->strings['Contact Photos'] = 'Фотографии контакта'; +$a->strings['Profile Photos'] = 'Фотографии профиля'; +$a->strings['Latest likes'] = ''; +$a->strings['event'] = 'мероприятие'; +$a->strings['status'] = 'статус'; +$a->strings['photo'] = 'фото'; +$a->strings['Welcome to %s'] = 'Добро пожаловать на %s!'; diff --git a/communityhome/lang/sv/strings.php b/communityhome/lang/sv/strings.php index 0f350650..0848ca86 100644 --- a/communityhome/lang/sv/strings.php +++ b/communityhome/lang/sv/strings.php @@ -1,8 +1,8 @@ -strings["Login"] = "Logga in"; -$a->strings["Contact Photos"] = "Dina kontakters bilder"; -$a->strings["Profile Photos"] = "Profilbilder"; -$a->strings["status"] = "status"; -$a->strings["photo"] = "bild"; -$a->strings["Welcome to %s"] = "Välkommen till %s"; +strings['Login'] = 'Logga in'; +$a->strings['Contact Photos'] = 'Dina kontakters bilder'; +$a->strings['Profile Photos'] = 'Profilbilder'; +$a->strings['status'] = 'status'; +$a->strings['photo'] = 'bild'; +$a->strings['Welcome to %s'] = 'Välkommen till %s'; diff --git a/communityhome/lang/zh-cn/strings.php b/communityhome/lang/zh-cn/strings.php index 3cabe94d..aa14258c 100644 --- a/communityhome/lang/zh-cn/strings.php +++ b/communityhome/lang/zh-cn/strings.php @@ -1,14 +1,14 @@ -strings["Login"] = "登录"; -$a->strings["OpenID"] = "OpenID"; -$a->strings["Latest users"] = "最近用户"; -$a->strings["Most active users"] = "最积极用户"; -$a->strings["Latest photos"] = "最近照片"; -$a->strings["Contact Photos"] = "熟人照片"; -$a->strings["Profile Photos"] = "简介照片"; -$a->strings["Latest likes"] = "最近喜欢"; -$a->strings["event"] = "项目"; -$a->strings["status"] = "现状"; -$a->strings["photo"] = "照片"; -$a->strings["Welcome to %s"] = "%s欢迎你"; +strings['Login'] = '登录'; +$a->strings['OpenID'] = 'OpenID'; +$a->strings['Latest users'] = '最近用户'; +$a->strings['Most active users'] = '最积极用户'; +$a->strings['Latest photos'] = '最近照片'; +$a->strings['Contact Photos'] = '熟人照片'; +$a->strings['Profile Photos'] = '简介照片'; +$a->strings['Latest likes'] = '最近喜欢'; +$a->strings['event'] = '项目'; +$a->strings['status'] = '现状'; +$a->strings['photo'] = '照片'; +$a->strings['Welcome to %s'] = '%s欢迎你'; diff --git a/convert/UnitConvertor.php b/convert/UnitConvertor.php index d7933a8f..5da6e03c 100755 --- a/convert/UnitConvertor.php +++ b/convert/UnitConvertor.php @@ -1,283 +1,266 @@ - | -// | Co-authored by : CVH, Chris Hansel | -// +----------------------------------------------------------------------+ -// -// $Id: UnitConvertor.php,v 1.00 2002/02/20 11:40:00 stasokhvat Exp $ - -/** -* UnitConvertor is able to convert between different units and currencies. -* -* @author Stanislav Okhvat -* @version $Id: UnitConvertor.php,v 1.00 2002/03/01 17:00:00 stasokhvat Exp $ -* @package UnitConvertor -* @access public -* @history 01.03.2002 Implemented the code for regular and offset-based -* conversions -* -* 13.12.2004 -* By Chris Hansel (CVH): changed getConvSpecs in order to have it look up -* intermediary conversions (also see comments in check_key). -* -* Intermediary conversions are useful when no conversion ratio is specified -* between two units when we calculate between the two. For example, we want -* to convert between Fahrenheit and Kelvin, and we have only -* specified how to convert Centigrade<->Fahrenheit and -* Centigrade<->Kelvin. While a direct (Fahrenheit->Kelvin) or -* reverse (Kelvin->Fahrenheit) lookups fail, looking for an intermediary -* unit linking the two (Centigrade) helps us do the conversion. -* -* 13.12.2004 -* Chris Hansel (CVH): $to_array argument of addConversion method can now -* contain units as 'unit1/unit2/unit3', when all units stand for the same -* thing. See examples in unitconv.php -*/ -class UnitConvertor -{ - /** - * Stores conversion ratios. - * - * @var array - * @access private - */ - var $conversion_table = array(); - - /** - * Decimal point character (default is "." - American - set in constructor). - * - * @var string - * @access private - */ - var $decimal_point; - - /** - * Thousands separator (default is "," - American - set in constructor). - * - * @var string - * @access private - */ - var $thousand_separator; - - /** - * For future use - * - * @var array - * @access private - */ - var $bases = array(); - - /** - * Constructor. Initializes the UnitConvertor object with the most important - * properties. - * - * @param string decimal point character - * @param string thousand separator character - * @return void - * @access public - */ - function UnitConvertor($dec_point = '.', $thousand_sep = ',') - { - $this->decimal_point = $dec_point; - $this->thousand_separator = $thousand_sep; - - } // end func UnitConvertor - - /** - * Adds a conversion ratio to the conversion table. - * - * @param string the name of unit from which to convert - * @param array array( - * "pound"=>array("ratio"=>'', "offset"=>'') - * ) - * "pound" - name of unit to set conversion ration to - * "ratio" - 'double' conversion ratio which, when - * multiplied by the number of $from_unit units produces - * the result - * "offset" - an offset from 0 which will be added to - * the result when converting (needed for temperature - * conversions and defaults to 0). - * @return boolean true if successful, false otherwise - * @access public - */ - function addConversion($from_unit, $to_array) - { - if (!isset($this->conversion_table[$from_unit])) { - while(list($key, $val) = each($to_array)) - { - if (strstr($key, '/')) - { - $to_units = explode('/', $key); - foreach ($to_units as $to_unit) - { - $this->bases[$from_unit][] = $to_unit; - - if (!is_array($val)) - { - $this->conversion_table[$from_unit."_".$to_unit] = array("ratio"=>$val, "offset"=>0); - } - else - { - $this->conversion_table[$from_unit."_".$to_unit] = - array( - "ratio"=>$val['ratio'], - "offset"=>(isset($val['offset']) ? $val['offset'] : 0) - ); - } - } - } - else - { - $this->bases[$from_unit][] = $key; - - if (!is_array($val)) - { - $this->conversion_table[$from_unit."_".$key] = array("ratio"=>$val, "offset"=>0); - } - else - { - $this->conversion_table[$from_unit."_".$key] = - array( - "ratio"=>$val['ratio'], - "offset"=>(isset($val['offset']) ? $val['offset'] : 0) - ); - } - } - } - return true; - } - return false; - - } // end func addConversion - - /** - * Converts from one unit to another using specified precision. - * - * @param double value to convert - * @param string name of the source unit from which to convert - * @param string name of the target unit to which we are converting - * @param integer double precision of the end result - * @return void - * @access public - */ - function convert($value, $from_unit, $to_unit, $precision) - { - if ($this->getConvSpecs($from_unit, $to_unit, $value, $converted )) - { - return number_format($converted , (int)$precision, $this->decimal_point, $this->thousand_separator); - } else { - return false; - } - } // end func - - /** - * CVH : changed this Function getConvSpecs in order to have it look up - * intermediary Conversions from the - * "base" unit being that one that has the highest hierarchical order in one - * "logical" Conversion_Array - * when taking $conv->addConversion('km', - * array('meter'=>1000, 'dmeter'=>10000, 'centimeter'=>100000, - * 'millimeter'=>1000000, 'mile'=>0.62137, 'naut.mile'=>0.53996, - * 'inch(es)/zoll'=>39370, 'ft/foot/feet'=>3280.8, 'yd/yard'=>1093.6)); - * "km" would be the logical base unit for all units of dinstance, thus, - * if the function fails to find a direct or reverse conversion in the table - * it is only logical to suspect that if there is a chance - * converting the value it only is via the "base" unit, and so - * there is not even a need for a recursive search keeping the perfomance - * acceptable and the ressource small... - * - * CVH check_key checks for a key in the Conversiontable and returns a value - */ - function check_key( $key) { - if ( array_key_exists ($key,$this->conversion_table)) { - if (! empty($this->conversion_table[$key])) { - return $this->conversion_table[$key]; - } - } - return false; - } - - /** - * Key function. Finds the conversion ratio and offset from one unit to another. - * - * @param string name of the source unit from which to convert - * @param string name of the target unit to which we are converting - * @param double conversion ratio found. Returned by reference. - * @param double offset which needs to be added (or subtracted, if negative) - * to the result to convert correctly. - * For temperature or some scientific conversions, - * i.e. Fahrenheit -> Celcius - * @return boolean true if ratio and offset are found for the supplied - * units, false otherwise - * @access private - */ - function getConvSpecs($from_unit, $to_unit, $value, &$converted) - { - $key = $from_unit."_".$to_unit; - $revkey = $to_unit."_".$from_unit; - $found = false; - if ($ct_arr = $this->check_key($key)) { - // Conversion Specs found directly - $ratio = (double)$ct_arr['ratio']; - $offset = $ct_arr['offset']; - $converted = (double)(($value * $ratio)+ $offset); - - return true; - } // not found in direct order, try reverse order - elseif ($ct_arr = $this->check_key($revkey)) { - $ratio = (double)(1/$ct_arr['ratio']); - $offset = -$ct_arr['offset']; - $converted = (double)(($value + $offset) * $ratio); - - return true; - } // not found test for intermediary conversion - else { - // return ratio = 1 if keyparts match - if ($key == $revkey) { - $ratio = 1; - $offset = 0; - $converted = $value; - return true; - } - // otherwise search intermediary - reset($this->conversion_table); - while (list($convk, $i1_value) = each($this->conversion_table)) { - // split the key into parts - $keyparts = preg_split("/_/",$convk); - // return ratio = 1 if keyparts match - - // Now test if either part matches the from or to unit - if ($keyparts[1] == $to_unit && ($i2_value = $this->check_key($keyparts[0]."_".$from_unit))) { - // an intermediary $keyparts[0] was found - // now let us put things together intermediary 1 and 2 - $converted = (double)(((($value - $i2_value['offset']) / $i2_value['ratio']) * $i1_value['ratio'])+ $i1_value['offset']); - - $found = true; - - } elseif ($keyparts[1] == $from_unit && ($i2_value = $this->check_key($keyparts[0]."_".$to_unit))) { - // an intermediary $keyparts[0] was found - // now let us put things together intermediary 2 and 1 - $converted = (double)(((($value - $i1_value['offset']) / $i1_value['ratio']) + $i2_value['offset']) * $i2_value['ratio']); - - $found = true; - } - } - return $found; - } - - } // end func getConvSpecs - -} // end class UnitConvertor -?> \ No newline at end of file + | +// | Co-authored by : CVH, Chris Hansel | +// +----------------------------------------------------------------------+ + +// $Id: UnitConvertor.php,v 1.00 2002/02/20 11:40:00 stasokhvat Exp $ + +/** + * UnitConvertor is able to convert between different units and currencies. + * + * @author Stanislav Okhvat + * + * @version $Id: UnitConvertor.php,v 1.00 2002/03/01 17:00:00 stasokhvat Exp $ + * @history 01.03.2002 Implemented the code for regular and offset-based + * conversions + * + * 13.12.2004 + * By Chris Hansel (CVH): changed getConvSpecs in order to have it look up + * intermediary conversions (also see comments in check_key). + * + * Intermediary conversions are useful when no conversion ratio is specified + * between two units when we calculate between the two. For example, we want + * to convert between Fahrenheit and Kelvin, and we have only + * specified how to convert Centigrade<->Fahrenheit and + * Centigrade<->Kelvin. While a direct (Fahrenheit->Kelvin) or + * reverse (Kelvin->Fahrenheit) lookups fail, looking for an intermediary + * unit linking the two (Centigrade) helps us do the conversion. + * + * 13.12.2004 + * Chris Hansel (CVH): $to_array argument of addConversion method can now + * contain units as 'unit1/unit2/unit3', when all units stand for the same + * thing. See examples in unitconv.php + */ +class UnitConvertor +{ + /* + * Stores conversion ratios. + * + * @var array + * @access private + */ + public $conversion_table = array(); + + /* + * Decimal point character (default is "." - American - set in constructor). + * + * @var string + * @access private + */ + public $decimal_point; + + /* + * Thousands separator (default is "," - American - set in constructor). + * + * @var string + * @access private + */ + public $thousand_separator; + + /* + * For future use + * + * @var array + * @access private + */ + public $bases = array(); + + /** + * Constructor. Initializes the UnitConvertor object with the most important + * properties. + * + * @param string decimal point character + * @param string thousand separator character + */ + public function UnitConvertor($dec_point = '.', $thousand_sep = ',') + { + $this->decimal_point = $dec_point; + $this->thousand_separator = $thousand_sep; + } // end func UnitConvertor + + /** + * Adds a conversion ratio to the conversion table. + * + * @param string the name of unit from which to convert + * @param array array( + * "pound"=>array("ratio"=>'', "offset"=>'') + * ) + * "pound" - name of unit to set conversion ration to + * "ratio" - 'double' conversion ratio which, when + * multiplied by the number of $from_unit units produces + * the result + * "offset" - an offset from 0 which will be added to + * the result when converting (needed for temperature + * conversions and defaults to 0) + * + * @return bool true if successful, false otherwise + */ + public function addConversion($from_unit, $to_array) + { + if (!isset($this->conversion_table[$from_unit])) { + while (list($key, $val) = each($to_array)) { + if (strstr($key, '/')) { + $to_units = explode('/', $key); + foreach ($to_units as $to_unit) { + $this->bases[$from_unit][] = $to_unit; + + if (!is_array($val)) { + $this->conversion_table[$from_unit.'_'.$to_unit] = array('ratio' => $val, 'offset' => 0); + } else { + $this->conversion_table[$from_unit.'_'.$to_unit] = + array( + 'ratio' => $val['ratio'], + 'offset' => (isset($val['offset']) ? $val['offset'] : 0), + ); + } + } + } else { + $this->bases[$from_unit][] = $key; + + if (!is_array($val)) { + $this->conversion_table[$from_unit.'_'.$key] = array('ratio' => $val, 'offset' => 0); + } else { + $this->conversion_table[$from_unit.'_'.$key] = + array( + 'ratio' => $val['ratio'], + 'offset' => (isset($val['offset']) ? $val['offset'] : 0), + ); + } + } + } + + return true; + } + + return false; + } // end func addConversion + + /** + * Converts from one unit to another using specified precision. + * + * @param float value to convert + * @param string name of the source unit from which to convert + * @param string name of the target unit to which we are converting + * @param int double precision of the end result + */ + public function convert($value, $from_unit, $to_unit, $precision) + { + if ($this->getConvSpecs($from_unit, $to_unit, $value, $converted)) { + return number_format($converted, (int) $precision, $this->decimal_point, $this->thousand_separator); + } else { + return false; + } + } // end func + + /** + * CVH : changed this Function getConvSpecs in order to have it look up + * intermediary Conversions from the + * "base" unit being that one that has the highest hierarchical order in one + * "logical" Conversion_Array + * when taking $conv->addConversion('km', + * array('meter'=>1000, 'dmeter'=>10000, 'centimeter'=>100000, + * 'millimeter'=>1000000, 'mile'=>0.62137, 'naut.mile'=>0.53996, + * 'inch(es)/zoll'=>39370, 'ft/foot/feet'=>3280.8, 'yd/yard'=>1093.6)); + * "km" would be the logical base unit for all units of dinstance, thus, + * if the function fails to find a direct or reverse conversion in the table + * it is only logical to suspect that if there is a chance + * converting the value it only is via the "base" unit, and so + * there is not even a need for a recursive search keeping the perfomance + * acceptable and the ressource small... + * + * CVH check_key checks for a key in the Conversiontable and returns a value + */ + public function check_key($key) + { + if (array_key_exists($key, $this->conversion_table)) { + if (!empty($this->conversion_table[$key])) { + return $this->conversion_table[$key]; + } + } + + return false; + } + + /** + * Key function. Finds the conversion ratio and offset from one unit to another. + * + * @param string name of the source unit from which to convert + * @param string name of the target unit to which we are converting + * @param float conversion ratio found. Returned by reference + * @param float offset which needs to be added (or subtracted, if negative) + * to the result to convert correctly. + * For temperature or some scientific conversions, + * i.e. Fahrenheit -> Celcius + * + * @return bool true if ratio and offset are found for the supplied + * units, false otherwise + */ + public function getConvSpecs($from_unit, $to_unit, $value, &$converted) + { + $key = $from_unit.'_'.$to_unit; + $revkey = $to_unit.'_'.$from_unit; + $found = false; + if ($ct_arr = $this->check_key($key)) { + // Conversion Specs found directly + $ratio = (float) $ct_arr['ratio']; + $offset = $ct_arr['offset']; + $converted = (float) (($value * $ratio) + $offset); + + return true; + } // not found in direct order, try reverse order + elseif ($ct_arr = $this->check_key($revkey)) { + $ratio = (float) (1 / $ct_arr['ratio']); + $offset = -$ct_arr['offset']; + $converted = (float) (($value + $offset) * $ratio); + + return true; + } // not found test for intermediary conversion + else { + // return ratio = 1 if keyparts match + if ($key == $revkey) { + $ratio = 1; + $offset = 0; + $converted = $value; + + return true; + } + // otherwise search intermediary + reset($this->conversion_table); + while (list($convk, $i1_value) = each($this->conversion_table)) { + // split the key into parts + $keyparts = preg_split('/_/', $convk); + // return ratio = 1 if keyparts match + + // Now test if either part matches the from or to unit + if ($keyparts[1] == $to_unit && ($i2_value = $this->check_key($keyparts[0].'_'.$from_unit))) { + // an intermediary $keyparts[0] was found + // now let us put things together intermediary 1 and 2 + $converted = (float) (((($value - $i2_value['offset']) / $i2_value['ratio']) * $i1_value['ratio']) + $i1_value['offset']); + + $found = true; + } elseif ($keyparts[1] == $from_unit && ($i2_value = $this->check_key($keyparts[0].'_'.$to_unit))) { + // an intermediary $keyparts[0] was found + // now let us put things together intermediary 2 and 1 + $converted = (float) (((($value - $i1_value['offset']) / $i1_value['ratio']) + $i2_value['offset']) * $i2_value['ratio']); + + $found = true; + } + } + + return $found; + } + } // end func getConvSpecs +} // end class UnitConvertor diff --git a/convert/convert.php b/convert/convert.php index 75131650..f1adb1f4 100755 --- a/convert/convert.php +++ b/convert/convert.php @@ -1,228 +1,223 @@ - - */ - -function convert_install() { - register_hook('app_menu', 'addon/convert/convert.php', 'convert_app_menu'); -} - -function convert_uninstall() { - unregister_hook('app_menu', 'addon/convert/convert.php', 'convert_app_menu'); -} - -function convert_app_menu($a,&$b) { - $b['app_menu'][] = ''; -} - - -function convert_module() {} - - - - - - - -function convert_content($app) { - -include("UnitConvertor.php"); - - class TP_Converter extends UnitConvertor { - function TP_Converter($lang = "en") - { - if ($lang != 'en' ) { - $dec_point = '.'; $thousand_sep = "'"; - } else { - $dec_point = '.'; $thousand_sep = ","; - } - - $this->UnitConvertor($dec_point , $thousand_sep ); - - } // end func UnitConvertor - - function find_base_unit($from,$to) { - while (list($skey,$sval) = each($this->bases)) { - if ($skey == $from || $to == $skey || in_array($to,$sval) || in_array($from,$sval)) { - return $skey; - } - } - return false; - } - - function getTable($value, $from_unit, $to_unit, $precision) { - - if ($base_unit = $this->find_base_unit($from_unit,$to_unit)) { - - // A baseunit was found now lets convert from -> $base_unit - - $cell ['value'] = $this->convert($value, $from_unit, $base_unit, $precision)." ".$base_unit; - $cell ['class'] = ($base_unit == $from_unit || $base_unit == $to_unit) ? "framedred": ""; - $cells[] = $cell; - // We now have the base unit and value now lets produce the table; - while (list($key,$val) = each($this->bases[$base_unit])) { - $cell ['value'] = $this->convert($value, $from_unit, $val, $precision)." ".$val; - $cell ['class'] = ($val == $from_unit || $val == $to_unit) ? "framedred": ""; - $cells[] = $cell; - } - - $cc = count($cells); - $string = ""; - $string .= ""; - $i=0; - foreach ($cells as $cell) { - if ($i==0) { - $string .= ""; - $i++; - } else { - $string .= ""; - } - } - $string .= "
$value $from_unit".$cell['value']."
".$cell['value']."
"; - return $string; - } - - } -} - - -$conv = new TP_Converter('en'); - - -$conversions = array( - 'Temperature'=>array('base' =>'Celsius', - 'conv'=>array( - 'Fahrenheit'=>array('ratio'=>1.8, 'offset'=>32), - 'Kelvin'=>array('ratio'=>1, 'offset'=>273), - 'Reaumur'=>0.8 - ) - ), - 'Weight' => array('base' =>'kg', - 'conv'=>array( - 'g'=>1000, - 'mg'=>1000000, - 't'=>0.001, - 'grain'=>15432, - 'oz'=>35.274, - 'lb'=>2.2046, - 'cwt(UK)' => 0.019684, - 'cwt(US)' => 0.022046, - 'ton (US)' => 0.0011023, - 'ton (UK)' => 0.0009842 - ) - ), - 'Distance' => array('base' =>'km', - 'conv'=>array( - 'm'=>1000, - 'dm'=>10000, - 'cm'=>100000, - 'mm'=>1000000, - 'mile'=>0.62137, - 'naut.mile'=>0.53996, - 'inch(es)'=>39370, - 'ft'=>3280.8, - 'yd'=>1093.6, - 'furlong'=>4.970969537898672, - 'fathom'=>546.8066491688539 - ) - ), - 'Area' => array('base' =>'km 2', - 'conv'=>array( - 'ha'=>100, - 'acre'=>247.105, - 'm 2'=>pow(1000,2), - 'dm 2'=>pow(10000,2), - 'cm 2'=>pow(100000,2), - 'mm 2'=>pow(1000000,2), - 'mile 2'=>pow(0.62137,2), - 'naut.miles 2'=>pow(0.53996,2), - 'in 2'=>pow(39370,2), - 'ft 2'=>pow(3280.8,2), - 'yd 2'=>pow(1093.6,2), - ) - ), - 'Volume' => array('base' =>'m 3', - 'conv'=>array( - 'in 3'=>61023.6, - 'ft 3'=>35.315, - 'cm 3'=>pow(10,6), - 'dm 3'=>1000, - 'litre'=>1000, - 'hl'=>10, - 'yd 3'=>1.30795, - 'gal(US)'=>264.172, - 'gal(UK)'=>219.969, - 'pint' => 2113.376, - 'quart' => 1056.688, - 'cup' => 4266.753, - 'fl oz' => 33814.02, - 'tablespoon' => 67628.04, - 'teaspoon' => 202884.1, - 'pt (UK)'=>1000/0.56826, - 'barrel petroleum'=>1000/158.99, - 'Register Tons'=>2.832, - 'Ocean Tons'=>1.1327 - ) - ), - 'Speed' =>array('base' =>'kmph', - 'conv'=>array( - 'mps'=>0.0001726031, - 'milesph'=>0.62137, - 'knots'=>0.53996, - 'mach STP'=>0.0008380431, - 'c (warp)'=>9.265669e-10 - ) - ) -); - - -while (list($key,$val) = each($conversions)) { - $conv->addConversion($val['base'], $val['conv']); - $list[$key][] = $val['base']; - while (list($ukey,$uval) = each($val['conv'])) { - $list[$key][] = $ukey; - } -} - - $o .= '

Unit Conversions

'; - - - if (isset($_POST['from_unit']) && isset($_POST['value'])) { - $_POST['value'] = $_POST['value'] + 0; - - - $o .= ($conv->getTable($_POST['value'], $_POST['from_unit'], $_POST['to_unit'], 5))."

"; - } else { - $o .= "

Select:

"; - } - - if(isset($_POST['value'])) - $value = $_POST['value']; - else - $value = ''; - - $o .= '
'; - $o .= ''; - $o .= ''; - - $o .= '
'; - - return $o; -} +. + */ +function convert_install() +{ + register_hook('app_menu', 'addon/convert/convert.php', 'convert_app_menu'); +} + +function convert_uninstall() +{ + unregister_hook('app_menu', 'addon/convert/convert.php', 'convert_app_menu'); +} + +function convert_app_menu($a, &$b) +{ + $b['app_menu'][] = ''; +} + +function convert_module() +{ +} + +function convert_content($app) +{ + include 'UnitConvertor.php'; + + class TP_Converter extends UnitConvertor + { + public function TP_Converter($lang = 'en') + { + if ($lang != 'en') { + $dec_point = '.'; + $thousand_sep = "'"; + } else { + $dec_point = '.'; + $thousand_sep = ','; + } + + $this->UnitConvertor($dec_point, $thousand_sep); + } // end func UnitConvertor + + public function find_base_unit($from, $to) + { + while (list($skey, $sval) = each($this->bases)) { + if ($skey == $from || $to == $skey || in_array($to, $sval) || in_array($from, $sval)) { + return $skey; + } + } + + return false; + } + + public function getTable($value, $from_unit, $to_unit, $precision) + { + if ($base_unit = $this->find_base_unit($from_unit, $to_unit)) { + + // A baseunit was found now lets convert from -> $base_unit + + $cell ['value'] = $this->convert($value, $from_unit, $base_unit, $precision).' '.$base_unit; + $cell ['class'] = ($base_unit == $from_unit || $base_unit == $to_unit) ? 'framedred' : ''; + $cells[] = $cell; + // We now have the base unit and value now lets produce the table; + while (list($key, $val) = each($this->bases[$base_unit])) { + $cell ['value'] = $this->convert($value, $from_unit, $val, $precision).' '.$val; + $cell ['class'] = ($val == $from_unit || $val == $to_unit) ? 'framedred' : ''; + $cells[] = $cell; + } + + $cc = count($cells); + $string = ''; + $string .= ""; + $i = 0; + foreach ($cells as $cell) { + if ($i == 0) { + $string .= ''; + ++$i; + } else { + $string .= ''; + } + } + $string .= '
$value $from_unit'.$cell['value'].'
'.$cell['value'].'
'; + + return $string; + } + } + } + + $conv = new TP_Converter('en'); + + $conversions = array( + 'Temperature' => array('base' => 'Celsius', + 'conv' => array( + 'Fahrenheit' => array('ratio' => 1.8, 'offset' => 32), + 'Kelvin' => array('ratio' => 1, 'offset' => 273), + 'Reaumur' => 0.8, + ), + ), + 'Weight' => array('base' => 'kg', + 'conv' => array( + 'g' => 1000, + 'mg' => 1000000, + 't' => 0.001, + 'grain' => 15432, + 'oz' => 35.274, + 'lb' => 2.2046, + 'cwt(UK)' => 0.019684, + 'cwt(US)' => 0.022046, + 'ton (US)' => 0.0011023, + 'ton (UK)' => 0.0009842, + ), + ), + 'Distance' => array('base' => 'km', + 'conv' => array( + 'm' => 1000, + 'dm' => 10000, + 'cm' => 100000, + 'mm' => 1000000, + 'mile' => 0.62137, + 'naut.mile' => 0.53996, + 'inch(es)' => 39370, + 'ft' => 3280.8, + 'yd' => 1093.6, + 'furlong' => 4.970969537898672, + 'fathom' => 546.8066491688539, + ), + ), + 'Area' => array('base' => 'km 2', + 'conv' => array( + 'ha' => 100, + 'acre' => 247.105, + 'm 2' => pow(1000, 2), + 'dm 2' => pow(10000, 2), + 'cm 2' => pow(100000, 2), + 'mm 2' => pow(1000000, 2), + 'mile 2' => pow(0.62137, 2), + 'naut.miles 2' => pow(0.53996, 2), + 'in 2' => pow(39370, 2), + 'ft 2' => pow(3280.8, 2), + 'yd 2' => pow(1093.6, 2), + ), + ), + 'Volume' => array('base' => 'm 3', + 'conv' => array( + 'in 3' => 61023.6, + 'ft 3' => 35.315, + 'cm 3' => pow(10, 6), + 'dm 3' => 1000, + 'litre' => 1000, + 'hl' => 10, + 'yd 3' => 1.30795, + 'gal(US)' => 264.172, + 'gal(UK)' => 219.969, + 'pint' => 2113.376, + 'quart' => 1056.688, + 'cup' => 4266.753, + 'fl oz' => 33814.02, + 'tablespoon' => 67628.04, + 'teaspoon' => 202884.1, + 'pt (UK)' => 1000 / 0.56826, + 'barrel petroleum' => 1000 / 158.99, + 'Register Tons' => 2.832, + 'Ocean Tons' => 1.1327, + ), + ), + 'Speed' => array('base' => 'kmph', + 'conv' => array( + 'mps' => 0.0001726031, + 'milesph' => 0.62137, + 'knots' => 0.53996, + 'mach STP' => 0.0008380431, + 'c (warp)' => 9.265669e-10, + ), + ), +); + + while (list($key, $val) = each($conversions)) { + $conv->addConversion($val['base'], $val['conv']); + $list[$key][] = $val['base']; + while (list($ukey, $uval) = each($val['conv'])) { + $list[$key][] = $ukey; + } + } + + $o .= '

Unit Conversions

'; + + if (isset($_POST['from_unit']) && isset($_POST['value'])) { + $_POST['value'] = $_POST['value'] + 0; + + $o .= ($conv->getTable($_POST['value'], $_POST['from_unit'], $_POST['to_unit'], 5)).'

'; + } else { + $o .= '

Select:

'; + } + + if (isset($_POST['value'])) { + $value = $_POST['value']; + } else { + $value = ''; + } + + $o .= '
'; + $o .= ''; + $o .= ''; + + $o .= '
'; + + return $o; +} diff --git a/convpath/convpath.php b/convpath/convpath.php index 0aaeb5f9..ad9872a7 100644 --- a/convpath/convpath.php +++ b/convpath/convpath.php @@ -4,99 +4,113 @@ * Description: Converts all internal paths according to the current scheme (http or https) * Version: 1.0 * Author: Michael Vogel - * Status: Unsupported + * Status: Unsupported. */ - -function convpath_install() { - register_hook('page_end', 'addon/convpath/convpath.php', 'convpath_page_end'); - register_hook('page_header', 'addon/convpath/convpath.php', 'convpath_page_header'); - register_hook('ping_xmlize', 'addon/convpath/convpath.php', 'convpath_ping_xmlize_hook'); - register_hook('prepare_body', 'addon/convpath/convpath.php', 'convpath_prepare_body_hook'); - register_hook('display_item', 'addon/convpath/convpath.php', 'convpath_display_item_hook'); +function convpath_install() +{ + register_hook('page_end', 'addon/convpath/convpath.php', 'convpath_page_end'); + register_hook('page_header', 'addon/convpath/convpath.php', 'convpath_page_header'); + register_hook('ping_xmlize', 'addon/convpath/convpath.php', 'convpath_ping_xmlize_hook'); + register_hook('prepare_body', 'addon/convpath/convpath.php', 'convpath_prepare_body_hook'); + register_hook('display_item', 'addon/convpath/convpath.php', 'convpath_display_item_hook'); } - -function convpath_uninstall() { - unregister_hook('page_end', 'addon/convpath/convpath.php', 'convpath_page_end'); - unregister_hook('page_header', 'addon/convpath/convpath.php', 'convpath_page_header'); - unregister_hook('ping_xmlize', 'addon/convpath/convpath.php', 'convpath_ping_xmlize_hook'); - unregister_hook('prepare_body', 'addon/convpath/convpath.php', 'convpath_prepare_body_hook'); - unregister_hook('display_item', 'addon/convpath/convpath.php', 'convpath_display_item_hook'); +function convpath_uninstall() +{ + unregister_hook('page_end', 'addon/convpath/convpath.php', 'convpath_page_end'); + unregister_hook('page_header', 'addon/convpath/convpath.php', 'convpath_page_header'); + unregister_hook('ping_xmlize', 'addon/convpath/convpath.php', 'convpath_ping_xmlize_hook'); + unregister_hook('prepare_body', 'addon/convpath/convpath.php', 'convpath_prepare_body_hook'); + unregister_hook('display_item', 'addon/convpath/convpath.php', 'convpath_display_item_hook'); } -function convpath_ping_xmlize_hook(&$a, &$o) { - $o["photo"] = convpath_url($a, $o["photo"]); +function convpath_ping_xmlize_hook(&$a, &$o) +{ + $o['photo'] = convpath_url($a, $o['photo']); } -function convpath_page_header(&$a, &$o){ - $o = convpath_convert($o); +function convpath_page_header(&$a, &$o) +{ + $o = convpath_convert($o); } -function convpath_page_end(&$a, &$o){ - $o = convpath_convert($o); - if (isset($a->page['aside'])) - $a->page['aside'] = convpath_convert($a->page['aside']); +function convpath_page_end(&$a, &$o) +{ + $o = convpath_convert($o); + if (isset($a->page['aside'])) { + $a->page['aside'] = convpath_convert($a->page['aside']); + } } -function convpath_prepare_body_hook(&$a, &$o) { - $o["html"] = convpath_convert($o["html"]); +function convpath_prepare_body_hook(&$a, &$o) +{ + $o['html'] = convpath_convert($o['html']); } -function convpath_display_item_hook(&$a, &$o) { - if (isset($o["output"])) { - if (isset($o["output"]["thumb"])) - $o["output"]["thumb"] = convpath_url($a, $o["output"]["thumb"]); - if (isset($o["output"]["author-avatar"])) - $o["output"]["author-avatar"] = convpath_url($a, $o["output"]["author-avatar"]); - if (isset($o["output"]["owner-avatar"])) - $o["output"]["owner-avatar"] = convpath_url($a, $o["output"]["owner-avatar"]); - if (isset($o["output"]["owner_photo"])) - $o["output"]["owner_photo"] = convpath_url($a, $o["output"]["owner_photo"]); - } +function convpath_display_item_hook(&$a, &$o) +{ + if (isset($o['output'])) { + if (isset($o['output']['thumb'])) { + $o['output']['thumb'] = convpath_url($a, $o['output']['thumb']); + } + if (isset($o['output']['author-avatar'])) { + $o['output']['author-avatar'] = convpath_url($a, $o['output']['author-avatar']); + } + if (isset($o['output']['owner-avatar'])) { + $o['output']['owner-avatar'] = convpath_url($a, $o['output']['owner-avatar']); + } + if (isset($o['output']['owner_photo'])) { + $o['output']['owner_photo'] = convpath_url($a, $o['output']['owner_photo']); + } + } } -function convpath_url($a, $path) { - if ($path == "") - return(""); +function convpath_url($a, $path) +{ + if ($path == '') { + return ''; + } - $ssl = (substr($a->get_baseurl(), 0, 8) == "https://"); + $ssl = (substr($a->get_baseurl(), 0, 8) == 'https://'); - if ($ssl) { - $search = "http://".$a->get_hostname(); - $replace = "https://".$a->get_hostname(); - } else { - $search = "https://".$a->get_hostname(); - $replace = "http://".$a->get_hostname(); - } + if ($ssl) { + $search = 'http://'.$a->get_hostname(); + $replace = 'https://'.$a->get_hostname(); + } else { + $search = 'https://'.$a->get_hostname(); + $replace = 'http://'.$a->get_hostname(); + } - $path = str_replace($search, $replace, $path); + $path = str_replace($search, $replace, $path); - return($path); + return $path; } /* Converts a given path according to the current scheme */ -function convpath_convert($path) { - global $a; +function convpath_convert($path) +{ + global $a; - if ($path == "") - return(""); + if ($path == '') { + return ''; + } - $ssl = (substr($a->get_baseurl(), 0, 8) == "https://"); + $ssl = (substr($a->get_baseurl(), 0, 8) == 'https://'); - if ($ssl) { - $search = "http://".$a->get_hostname(); - $replace = "https://".$a->get_hostname(); - } else { - $search = "https://".$a->get_hostname(); - $replace = "http://".$a->get_hostname(); - } - $searcharr = array("src='".$search, 'src="'.$search); - $replacearr = array("src='".$replace, 'src="'.$replace); - $path = str_replace($searcharr, $replacearr, $path); + if ($ssl) { + $search = 'http://'.$a->get_hostname(); + $replace = 'https://'.$a->get_hostname(); + } else { + $search = 'https://'.$a->get_hostname(); + $replace = 'http://'.$a->get_hostname(); + } + $searcharr = array("src='".$search, 'src="'.$search); + $replacearr = array("src='".$replace, 'src="'.$replace); + $path = str_replace($searcharr, $replacearr, $path); - //$path = str_replace($search, $replace, $path); + //$path = str_replace($search, $replace, $path); - return($path); + return $path; } diff --git a/curweather/curweather.php b/curweather/curweather.php index 71d95e46..3b9318de 100644 --- a/curweather/curweather.php +++ b/curweather/curweather.php @@ -1,84 +1,88 @@ * Author: Fabio Comuni - * Author: Tobias Diekershoff - * + * Author: Tobias Diekershoff . */ - -require_once('include/network.php'); -require_once("mod/proxy.php"); -require_once('include/text.php'); +require_once 'include/network.php'; +require_once 'mod/proxy.php'; +require_once 'include/text.php'; // get the weather data from OpenWeatherMap -function getWeather( $loc, $units='metric', $lang='en', $appid='', $cachetime=0) { - $url = "http://api.openweathermap.org/data/2.5/weather?q=".$loc."&appid=".$appid."&lang=".$lang."&units=".$units."&mode=xml"; +function getWeather($loc, $units = 'metric', $lang = 'en', $appid = '', $cachetime = 0) +{ + $url = 'http://api.openweathermap.org/data/2.5/weather?q='.$loc.'&appid='.$appid.'&lang='.$lang.'&units='.$units.'&mode=xml'; $cached = Cache::get('curweather'.md5($url)); $now = new DateTime(); if (!is_null($cached)) { - $cdate = get_pconfig(local_user(), 'curweather', 'last'); - $cached = unserialize($cached); - if ($cdate + $cachetime > $now->getTimestamp()) { - return $cached; - } + $cdate = get_pconfig(local_user(), 'curweather', 'last'); + $cached = unserialize($cached); + if ($cdate + $cachetime > $now->getTimestamp()) { + return $cached; + } } try { - $res = new SimpleXMLElement(fetch_url($url)); + $res = new SimpleXMLElement(fetch_url($url)); } catch (Exception $e) { - info(t('Error fetching weather data.\nError was: '.$e->getMessage())); - return false; + info(t('Error fetching weather data.\nError was: '.$e->getMessage())); + + return false; } - if ((string)$res->temperature['unit']==='metric') { - $tunit = '°C'; - $wunit = 'm/s'; + if ((string) $res->temperature['unit'] === 'metric') { + $tunit = '°C'; + $wunit = 'm/s'; } else { - $tunit = '°F'; - $wunit = 'mph'; + $tunit = '°F'; + $wunit = 'mph'; } - if ( trim((string)$res->weather['value']) == trim((string)$res->clouds['name']) ) { - $desc = (string)$res->clouds['name']; + if (trim((string) $res->weather['value']) == trim((string) $res->clouds['name'])) { + $desc = (string) $res->clouds['name']; } else { - $desc = (string)$res->weather['value'].', '.(string)$res->clouds['name']; + $desc = (string) $res->weather['value'].', '.(string) $res->clouds['name']; } $r = array( - 'city'=> (string) $res->city['name'][0], - 'country' => (string) $res->city->country[0], - 'lat' => (string) $res->city->coord['lat'], - 'lon' => (string) $res->city->coord['lon'], - 'temperature' => (string) $res->temperature['value'][0].$tunit, - 'pressure' => (string) $res->pressure['value'].(string)$res->pressure['unit'], - 'humidity' => (string) $res->humidity['value'].(string)$res->humidity['unit'], - 'descripion' => $desc, - 'wind' => (string)$res->wind->speed['name'].' ('.(string)$res->wind->speed['value'].$wunit.')', - 'update' => (string)$res->lastupdate['value'], - 'icon' => (string)$res->weather['icon'] + 'city' => (string) $res->city['name'][0], + 'country' => (string) $res->city->country[0], + 'lat' => (string) $res->city->coord['lat'], + 'lon' => (string) $res->city->coord['lon'], + 'temperature' => (string) $res->temperature['value'][0].$tunit, + 'pressure' => (string) $res->pressure['value'].(string) $res->pressure['unit'], + 'humidity' => (string) $res->humidity['value'].(string) $res->humidity['unit'], + 'descripion' => $desc, + 'wind' => (string) $res->wind->speed['name'].' ('.(string) $res->wind->speed['value'].$wunit.')', + 'update' => (string) $res->lastupdate['value'], + 'icon' => (string) $res->weather['icon'], ); set_pconfig(local_user(), 'curweather', 'last', $now->getTimestamp()); Cache::set('curweather'.md5($url), serialize($r), CACHE_HOUR); + return $r; } -function curweather_install() { - register_hook('network_mod_init', 'addon/curweather/curweather.php', 'curweather_network_mod_init'); - register_hook('plugin_settings', 'addon/curweather/curweather.php', 'curweather_plugin_settings'); - register_hook('plugin_settings_post', 'addon/curweather/curweather.php', 'curweather_plugin_settings_post'); +function curweather_install() +{ + register_hook('network_mod_init', 'addon/curweather/curweather.php', 'curweather_network_mod_init'); + register_hook('plugin_settings', 'addon/curweather/curweather.php', 'curweather_plugin_settings'); + register_hook('plugin_settings_post', 'addon/curweather/curweather.php', 'curweather_plugin_settings_post'); } -function curweather_uninstall() { - unregister_hook('network_mod_init', 'addon/curweather/curweather.php', 'curweather_network_mod_init'); - unregister_hook('plugin_settings', 'addon/curweather/curweather.php', 'curweather_plugin_settings'); - unregister_hook('plugin_settings_post', 'addon/curweather/curweather.php', 'curweather_plugin_settings_post'); +function curweather_uninstall() +{ + unregister_hook('network_mod_init', 'addon/curweather/curweather.php', 'curweather_network_mod_init'); + unregister_hook('plugin_settings', 'addon/curweather/curweather.php', 'curweather_plugin_settings'); + unregister_hook('plugin_settings_post', 'addon/curweather/curweather.php', 'curweather_plugin_settings_post'); } -function curweather_network_mod_init(&$fk_app,&$b) { - - if(! intval(get_pconfig(local_user(),'curweather','curweather_enable'))) +function curweather_network_mod_init(&$fk_app, &$b) +{ + if (!intval(get_pconfig(local_user(), 'curweather', 'curweather_enable'))) { return; + } - $fk_app->page['htmlhead'] .= '' . "\r\n"; + $fk_app->page['htmlhead'] .= ''."\r\n"; // $rpt value is needed for location // $lang will be taken from the browser session to honour user settings @@ -91,114 +95,119 @@ function curweather_network_mod_init(&$fk_app,&$b) { // linked from lat/log of the reply of OWMp $rpt = get_pconfig(local_user(), 'curweather', 'curweather_loc'); - // set the language to the browsers language and use metric units $lang = $_SESSION['language']; - $units = get_pconfig( local_user(), 'curweather', 'curweather_units'); - $appid = get_config('curweather','appid'); - $cachetime = intval(get_config('curweather','cachetime')); - if ($units==="") - $units = 'metric'; + $units = get_pconfig(local_user(), 'curweather', 'curweather_units'); + $appid = get_config('curweather', 'appid'); + $cachetime = intval(get_config('curweather', 'cachetime')); + if ($units === '') { + $units = 'metric'; + } $ok = true; $res = getWeather($rpt, $units, $lang, $appid, $cachetime); - if ($res===false) - $ok = false; + if ($res === false) { + $ok = false; + } if ($ok) { - $t = get_markup_template("widget.tpl", "addon/curweather/" ); - $curweather = replace_macros ($t, array( - '$title' => t("Current Weather"), - '$icon' => proxy_url('http://openweathermap.org/img/w/'.$res['icon'].'.png'), - '$city' => $res['city'], - '$lon' => $res['lon'], - '$lat' => $res['lat'], - '$description' => $res['descripion'], - '$temp' => $res['temperature'], - '$relhumidity' => array('caption'=>t('Relative Humidity'), 'val'=>$res['humidity']), - '$pressure' => array('caption'=>t('Pressure'), 'val'=>$res['pressure']), - '$wind' => array('caption'=>t('Wind'), 'val'=> $res['wind']), - '$lastupdate' => t('Last Updated').': '.$res['update'].'UTC', - '$databy' => t('Data by'), - '$showonmap' => t('Show on map') - )); + $t = get_markup_template('widget.tpl', 'addon/curweather/'); + $curweather = replace_macros($t, array( + '$title' => t('Current Weather'), + '$icon' => proxy_url('http://openweathermap.org/img/w/'.$res['icon'].'.png'), + '$city' => $res['city'], + '$lon' => $res['lon'], + '$lat' => $res['lat'], + '$description' => $res['descripion'], + '$temp' => $res['temperature'], + '$relhumidity' => array('caption' => t('Relative Humidity'), 'val' => $res['humidity']), + '$pressure' => array('caption' => t('Pressure'), 'val' => $res['pressure']), + '$wind' => array('caption' => t('Wind'), 'val' => $res['wind']), + '$lastupdate' => t('Last Updated').': '.$res['update'].'UTC', + '$databy' => t('Data by'), + '$showonmap' => t('Show on map'), + )); } else { - $t = get_markup_template('widget-error.tpl', 'addon/curweather/'); - $curweather = replace_macros( $t, array( - '$problem' => t('There was a problem accessing the weather data. But have a look'), - '$rpt' => $rpt, - '$atOWM' => t('at OpenWeatherMap') - )); + $t = get_markup_template('widget-error.tpl', 'addon/curweather/'); + $curweather = replace_macros($t, array( + '$problem' => t('There was a problem accessing the weather data. But have a look'), + '$rpt' => $rpt, + '$atOWM' => t('at OpenWeatherMap'), + )); } $fk_app->page['aside'] = $curweather.$fk_app->page['aside']; - } +function curweather_plugin_settings_post($a, $post) +{ + if (!local_user() || (!x($_POST, 'curweather-settings-submit'))) { + return; + } + set_pconfig(local_user(), 'curweather', 'curweather_loc', trim($_POST['curweather_loc'])); + set_pconfig(local_user(), 'curweather', 'curweather_enable', intval($_POST['curweather_enable'])); + set_pconfig(local_user(), 'curweather', 'curweather_units', trim($_POST['curweather_units'])); -function curweather_plugin_settings_post($a,$post) { - if(! local_user() || (! x($_POST,'curweather-settings-submit'))) - return; - set_pconfig(local_user(),'curweather','curweather_loc',trim($_POST['curweather_loc'])); - set_pconfig(local_user(),'curweather','curweather_enable',intval($_POST['curweather_enable'])); - set_pconfig(local_user(),'curweather','curweather_units',trim($_POST['curweather_units'])); - - info( t('Current Weather settings updated.') . EOL); + info(t('Current Weather settings updated.').EOL); } +function curweather_plugin_settings(&$a, &$s) +{ + if (!local_user()) { + return; + } -function curweather_plugin_settings(&$a,&$s) { + /* Get the current state of our config variable */ - if(! local_user()) - return; + $curweather_loc = get_pconfig(local_user(), 'curweather', 'curweather_loc'); + $curweather_units = get_pconfig(local_user(), 'curweather', 'curweather_units'); + $appid = get_config('curweather', 'appid'); + if ($appid == '') { + $noappidtext = t('No APPID found, please contact your admin to obtain one.'); + } else { + $noappidtext = ''; + } + $enable = intval(get_pconfig(local_user(), 'curweather', 'curweather_enable')); + $enable_checked = (($enable) ? ' checked="checked" ' : ''); - /* Get the current state of our config variable */ - - $curweather_loc = get_pconfig(local_user(), 'curweather', 'curweather_loc'); - $curweather_units = get_pconfig(local_user(), 'curweather', 'curweather_units'); - $appid = get_config('curweather','appid'); - if ($appid=="") { - $noappidtext = t('No APPID found, please contact your admin to obtain one.'); - } else { - $noappidtext = ''; - } - $enable = intval(get_pconfig(local_user(),'curweather','curweather_enable')); - $enable_checked = (($enable) ? ' checked="checked" ' : ''); - - // load template and replace the macros - $t = get_markup_template("settings.tpl", "addon/curweather/" ); - $s = replace_macros ($t, array( - '$submit' => t('Save Settings'), - '$header' => t('Current Weather').' '.t('Settings'), - '$noappidtext' => $noappidtext, - '$info' => t('Enter either the name of your location or the zip code.'), - '$curweather_loc' => array( 'curweather_loc', t('Your Location'), $curweather_loc, t('Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE.') ), - '$curweather_units' => array( 'curweather_units', t('Units'), $curweather_units, t('select if the temperature should be displayed in °C or °F'), array('metric'=>'°C', 'imperial'=>'°F')), - '$enabled' => array( 'curweather_enable', t('Show weather data'), $enable, '') - )); - return; + // load template and replace the macros + $t = get_markup_template('settings.tpl', 'addon/curweather/'); + $s = replace_macros($t, array( + '$submit' => t('Save Settings'), + '$header' => t('Current Weather').' '.t('Settings'), + '$noappidtext' => $noappidtext, + '$info' => t('Enter either the name of your location or the zip code.'), + '$curweather_loc' => array('curweather_loc', t('Your Location'), $curweather_loc, t('Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE.')), + '$curweather_units' => array('curweather_units', t('Units'), $curweather_units, t('select if the temperature should be displayed in °C or °F'), array('metric' => '°C', 'imperial' => '°F')), + '$enabled' => array('curweather_enable', t('Show weather data'), $enable, ''), + )); + return; } // Config stuff for the admin panel to let the admin of the node set a APPID // for accessing the API of openweathermap -function curweather_plugin_admin_post (&$a) { - if(! is_site_admin()) - return; - if ($_POST['curweather-submit']) { - set_config('curweather','appid',trim($_POST['appid'])); - set_config('curweather','cachetime',trim($_POST['cachetime'])); - info( t('Curweather settings saved.'.EOL)); - } +function curweather_plugin_admin_post(&$a) +{ + if (!is_site_admin()) { + return; + } + if ($_POST['curweather-submit']) { + set_config('curweather', 'appid', trim($_POST['appid'])); + set_config('curweather', 'cachetime', trim($_POST['cachetime'])); + info(t('Curweather settings saved.'.EOL)); + } } -function curweather_plugin_admin (&$a, &$o) { - if(! is_site_admin()) - return; - $appid = get_config('curweather','appid'); - $cachetime = get_config('curweather','cachetime'); - $t = get_markup_template("admin.tpl", "addon/curweather/" ); - $o = replace_macros ($t, array( - '$submit' => t('Save Settings'), - '$cachetime' => array('cachetime', t('Caching Interval'), $cachetime, t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), array('0'=>t('no cache'), '300'=>'5 '.t('minutes'), '900'=>'15 '.t('minutes'), '1800'=>'30 '.t('minutes'), '3600'=>'60 '.t('minutes'))), - '$appid' => array('appid', t('Your APPID'), $appid, t('Your API key provided by OpenWeatherMap')) +function curweather_plugin_admin(&$a, &$o) +{ + if (!is_site_admin()) { + return; + } + $appid = get_config('curweather', 'appid'); + $cachetime = get_config('curweather', 'cachetime'); + $t = get_markup_template('admin.tpl', 'addon/curweather/'); + $o = replace_macros($t, array( + '$submit' => t('Save Settings'), + '$cachetime' => array('cachetime', t('Caching Interval'), $cachetime, t('For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'), array('0' => t('no cache'), '300' => '5 '.t('minutes'), '900' => '15 '.t('minutes'), '1800' => '30 '.t('minutes'), '3600' => '60 '.t('minutes'))), + '$appid' => array('appid', t('Your APPID'), $appid, t('Your API key provided by OpenWeatherMap')), )); } diff --git a/curweather/lang/ca/strings.php b/curweather/lang/ca/strings.php index 87481b12..aad6b1a8 100644 --- a/curweather/lang/ca/strings.php +++ b/curweather/lang/ca/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Enviar"; +strings['Submit'] = 'Enviar'; diff --git a/curweather/lang/cs/strings.php b/curweather/lang/cs/strings.php index d56c3669..186415b4 100644 --- a/curweather/lang/cs/strings.php +++ b/curweather/lang/cs/strings.php @@ -1,13 +1,15 @@ =2 && $n<=4) ? 1 : 2;; -}} -; -$a->strings["Current Weather"] = "Aktuální počasí"; -$a->strings["Current Weather settings updated."] = "Nastavení pro Aktuální počasí aktualizováno."; -$a->strings["Current Weather Settings"] = "Nastavení Aktuálního počasí"; -$a->strings["Weather Location: "] = "Poloha počasí:"; -$a->strings["Enable Current Weather"] = "Povolit Aktuální počasí"; -$a->strings["Submit"] = "Odeslat"; +if (!function_exists('string_plural_select_cs')) { + function string_plural_select_cs($n) + { + return ($n == 1) ? 0 : ($n >= 2 && $n <= 4) ? 1 : 2; + } +} + +$a->strings['Current Weather'] = 'Aktuální počasí'; +$a->strings['Current Weather settings updated.'] = 'Nastavení pro Aktuální počasí aktualizováno.'; +$a->strings['Current Weather Settings'] = 'Nastavení Aktuálního počasí'; +$a->strings['Weather Location: '] = 'Poloha počasí:'; +$a->strings['Enable Current Weather'] = 'Povolit Aktuální počasí'; +$a->strings['Submit'] = 'Odeslat'; diff --git a/curweather/lang/de/strings.php b/curweather/lang/de/strings.php index 2f1f0e3d..3b4293f2 100644 --- a/curweather/lang/de/strings.php +++ b/curweather/lang/de/strings.php @@ -1,34 +1,36 @@ strings["Error fetching weather data.\\nError was: "] = "Fehler beim abrufen der Wetterdaten.\\nDie Fehlermeldung lautet:"; -$a->strings["Current Weather"] = "Aktuelles Wetter"; -$a->strings["Relative Humidity"] = "Relative Luftfeuchtigkeit"; -$a->strings["Pressure"] = "Luftdruck"; -$a->strings["Wind"] = "Wind"; -$a->strings["Last Updated"] = "Letzte Aktualisierung"; -$a->strings["Data by"] = "Daten von"; -$a->strings["Show on map"] = "Karte anzeigen"; -$a->strings["There was a problem accessing the weather data. But have a look"] = "Es gab ein Problem beim Abrufen der Wetterdaten. Aber werf doch mal einen Blick"; -$a->strings["at OpenWeatherMap"] = "auf OpenWeatherMap"; -$a->strings["Current Weather settings updated."] = "Einstellungen des Aktuellen Wetter Addons aktualisiert."; -$a->strings["No APPID found, please contact your admin to obtain one."] = "Keine APPID gefunden, bitte kontaktiere deinen Admin damit eine eingerichtet wird."; -$a->strings["Save Settings"] = "Einstellungen speichern"; -$a->strings["Settings"] = "Einstellungen"; -$a->strings["Enter either the name of your location or the zip code."] = "Gib entweder den Namen oder die PLZ deines Ortes ein."; -$a->strings["Your Location"] = "Deinen Standort festlegen"; -$a->strings["Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE."] = "Identifikator deines Standorts (Name oder Postleitzahl), z.B. Berlin,DE oder 14476,DE."; -$a->strings["Units"] = "Einheiten"; -$a->strings["select if the temperature should be displayed in °C or °F"] = "wähle ob die Temperatur in °C oder °F angezeigt werden soll"; -$a->strings["Show weather data"] = "Zeige Wetter Daten"; -$a->strings["Curweather settings saved."] = "Curweather Einstellungen gespeichert."; -$a->strings["Caching Interval"] = "Cache Intervall"; -$a->strings["For how long should the weather data be cached? Choose according your OpenWeatherMap account type."] = "Wie lange sollen die Wetter Daten gecached werden? Wähle einen für deinen OpenWeatherMap Account passende Einstellung."; -$a->strings["no cache"] = "kein Cache"; -$a->strings["minutes"] = "Minuten"; -$a->strings["Your APPID"] = "Deine APPID"; -$a->strings["Your API key provided by OpenWeatherMap"] = "Der API Schlüssel von OpenWeatherMap"; +if (!function_exists('string_plural_select_de')) { + function string_plural_select_de($n) + { + return $n != 1; + } +} + +$a->strings['Error fetching weather data.\\nError was: '] = 'Fehler beim abrufen der Wetterdaten.\\nDie Fehlermeldung lautet:'; +$a->strings['Current Weather'] = 'Aktuelles Wetter'; +$a->strings['Relative Humidity'] = 'Relative Luftfeuchtigkeit'; +$a->strings['Pressure'] = 'Luftdruck'; +$a->strings['Wind'] = 'Wind'; +$a->strings['Last Updated'] = 'Letzte Aktualisierung'; +$a->strings['Data by'] = 'Daten von'; +$a->strings['Show on map'] = 'Karte anzeigen'; +$a->strings['There was a problem accessing the weather data. But have a look'] = 'Es gab ein Problem beim Abrufen der Wetterdaten. Aber werf doch mal einen Blick'; +$a->strings['at OpenWeatherMap'] = 'auf OpenWeatherMap'; +$a->strings['Current Weather settings updated.'] = 'Einstellungen des Aktuellen Wetter Addons aktualisiert.'; +$a->strings['No APPID found, please contact your admin to obtain one.'] = 'Keine APPID gefunden, bitte kontaktiere deinen Admin damit eine eingerichtet wird.'; +$a->strings['Save Settings'] = 'Einstellungen speichern'; +$a->strings['Settings'] = 'Einstellungen'; +$a->strings['Enter either the name of your location or the zip code.'] = 'Gib entweder den Namen oder die PLZ deines Ortes ein.'; +$a->strings['Your Location'] = 'Deinen Standort festlegen'; +$a->strings['Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE.'] = 'Identifikator deines Standorts (Name oder Postleitzahl), z.B. Berlin,DE oder 14476,DE.'; +$a->strings['Units'] = 'Einheiten'; +$a->strings['select if the temperature should be displayed in °C or °F'] = 'wähle ob die Temperatur in °C oder °F angezeigt werden soll'; +$a->strings['Show weather data'] = 'Zeige Wetter Daten'; +$a->strings['Curweather settings saved.'] = 'Curweather Einstellungen gespeichert.'; +$a->strings['Caching Interval'] = 'Cache Intervall'; +$a->strings['For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'] = 'Wie lange sollen die Wetter Daten gecached werden? Wähle einen für deinen OpenWeatherMap Account passende Einstellung.'; +$a->strings['no cache'] = 'kein Cache'; +$a->strings['minutes'] = 'Minuten'; +$a->strings['Your APPID'] = 'Deine APPID'; +$a->strings['Your API key provided by OpenWeatherMap'] = 'Der API Schlüssel von OpenWeatherMap'; diff --git a/curweather/lang/eo/strings.php b/curweather/lang/eo/strings.php index 68b5936b..36bcddc6 100644 --- a/curweather/lang/eo/strings.php +++ b/curweather/lang/eo/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Sendi"; +strings['Submit'] = 'Sendi'; diff --git a/curweather/lang/es/strings.php b/curweather/lang/es/strings.php index 2394f48b..8ded94f7 100644 --- a/curweather/lang/es/strings.php +++ b/curweather/lang/es/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Envíar"; +strings['Submit'] = 'Envíar'; diff --git a/curweather/lang/fr/strings.php b/curweather/lang/fr/strings.php index 466a0508..5a30ab29 100644 --- a/curweather/lang/fr/strings.php +++ b/curweather/lang/fr/strings.php @@ -1,34 +1,36 @@ 1);; -}} -; -$a->strings["Error fetching weather data.\\nError was: "] = "Erreur durant la récupération de la météo.\\nL'erreur était : "; -$a->strings["Current Weather"] = "Météo actuelle"; -$a->strings["Relative Humidity"] = "Humidité relative"; -$a->strings["Pressure"] = "Pression"; -$a->strings["Wind"] = "Vent"; -$a->strings["Last Updated"] = "Dernière mise-à-jour"; -$a->strings["Data by"] = "Données de"; -$a->strings["Show on map"] = "Montrer sur la carte"; -$a->strings["There was a problem accessing the weather data. But have a look"] = "Une erreur est survenue lors de l'accès aux données météo. Vous pouvez quand même jeter un oeil"; -$a->strings["at OpenWeatherMap"] = "à OpenWeatherMap"; -$a->strings["Current Weather settings updated."] = "Paramètres de la Météo Actuelle mis à jour."; -$a->strings["No APPID found, please contact your admin to optain one."] = "APPID introuvable, veuillez contacter votre administrateur pour en obtenir un."; -$a->strings["Save Settings"] = "Sauvegarder les paramètres"; -$a->strings["Settings"] = "Paramètres"; -$a->strings["Enter either the name of your location or the zip code."] = "Entrez le nom de votre emplacement ou votre code postal."; -$a->strings["Your Location"] = "Votre position"; -$a->strings["Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE."] = "Identifiant de votre emplacement (nom ou code postal), par exemple Paris 08, Fr ou 75008, FR."; -$a->strings["Units"] = "Unités"; -$a->strings["select if the temperatur should be displayed in °C or °F"] = "choisissez si la température doit être affichée en °C ou °F"; -$a->strings["Show weather data"] = "Montrer les données météos"; -$a->strings["Curweather settings saved."] = "Paramètres Curweather sauvés."; -$a->strings["Caching Interval"] = "Intervalle de mise en cache."; -$a->strings["For how long should the weather data be cached? Choose according your OpenWeatherMap account type."] = "Pendant combien de temps les données météo doivent-elles être mises en cache? Choisissez en fonction du type de compte OpenWeatherMap."; -$a->strings["no cache"] = "pas de cache"; -$a->strings["minutes"] = "minutes"; -$a->strings["Your APPID"] = "Votre APPID"; -$a->strings["Your API key provided by OpenWeatherMap"] = "Votre clé pour l'API de OpenWeatherMap"; +if (!function_exists('string_plural_select_fr')) { + function string_plural_select_fr($n) + { + return $n > 1; + } +} + +$a->strings['Error fetching weather data.\\nError was: '] = "Erreur durant la récupération de la météo.\\nL'erreur était : "; +$a->strings['Current Weather'] = 'Météo actuelle'; +$a->strings['Relative Humidity'] = 'Humidité relative'; +$a->strings['Pressure'] = 'Pression'; +$a->strings['Wind'] = 'Vent'; +$a->strings['Last Updated'] = 'Dernière mise-à-jour'; +$a->strings['Data by'] = 'Données de'; +$a->strings['Show on map'] = 'Montrer sur la carte'; +$a->strings['There was a problem accessing the weather data. But have a look'] = "Une erreur est survenue lors de l'accès aux données météo. Vous pouvez quand même jeter un oeil"; +$a->strings['at OpenWeatherMap'] = 'à OpenWeatherMap'; +$a->strings['Current Weather settings updated.'] = 'Paramètres de la Météo Actuelle mis à jour.'; +$a->strings['No APPID found, please contact your admin to optain one.'] = 'APPID introuvable, veuillez contacter votre administrateur pour en obtenir un.'; +$a->strings['Save Settings'] = 'Sauvegarder les paramètres'; +$a->strings['Settings'] = 'Paramètres'; +$a->strings['Enter either the name of your location or the zip code.'] = 'Entrez le nom de votre emplacement ou votre code postal.'; +$a->strings['Your Location'] = 'Votre position'; +$a->strings['Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE.'] = 'Identifiant de votre emplacement (nom ou code postal), par exemple Paris 08, Fr ou 75008, FR.'; +$a->strings['Units'] = 'Unités'; +$a->strings['select if the temperatur should be displayed in °C or °F'] = 'choisissez si la température doit être affichée en °C ou °F'; +$a->strings['Show weather data'] = 'Montrer les données météos'; +$a->strings['Curweather settings saved.'] = 'Paramètres Curweather sauvés.'; +$a->strings['Caching Interval'] = 'Intervalle de mise en cache.'; +$a->strings['For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'] = 'Pendant combien de temps les données météo doivent-elles être mises en cache? Choisissez en fonction du type de compte OpenWeatherMap.'; +$a->strings['no cache'] = 'pas de cache'; +$a->strings['minutes'] = 'minutes'; +$a->strings['Your APPID'] = 'Votre APPID'; +$a->strings['Your API key provided by OpenWeatherMap'] = "Votre clé pour l'API de OpenWeatherMap"; diff --git a/curweather/lang/is/strings.php b/curweather/lang/is/strings.php index 94f89330..1bae877d 100644 --- a/curweather/lang/is/strings.php +++ b/curweather/lang/is/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Senda inn"; +strings['Submit'] = 'Senda inn'; diff --git a/curweather/lang/it/strings.php b/curweather/lang/it/strings.php index 05319ab4..e9dcf657 100644 --- a/curweather/lang/it/strings.php +++ b/curweather/lang/it/strings.php @@ -1,34 +1,36 @@ strings["Error fetching weather data.\\nError was: "] = "Errore recuperando i dati meteo: "; -$a->strings["Current Weather"] = "Meteo"; -$a->strings["Relative Humidity"] = "Umidità Relativa"; -$a->strings["Pressure"] = "Pressione"; -$a->strings["Wind"] = "Vento"; -$a->strings["Last Updated"] = "Ultimo Aggiornamento: "; -$a->strings["Data by"] = "Data da"; -$a->strings["Show on map"] = "Mostra sulla mappa"; -$a->strings["There was a problem accessing the weather data. But have a look"] = "C'è stato un problema accedendo ai dati meteo, ma dai un'occhiata"; -$a->strings["at OpenWeatherMap"] = "a OpenWeatherMap"; -$a->strings["Current Weather settings updated."] = "Impostazioni Meteo aggiornate."; -$a->strings["No APPID found, please contact your admin to optain one."] = "APPID non trovata, contatta il tuo amministratore per averne una."; -$a->strings["Save Settings"] = "Salva Impostazioni"; -$a->strings["Settings"] = "Impostazioni"; -$a->strings["Enter either the name of your location or the zip code."] = "Inserisci il nome della tua posizione o il CAP"; -$a->strings["Your Location"] = "La tua Posizione"; -$a->strings["Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE."] = "Identificatore della tua posizione (nome o CAP), p.e. Roma, IT or 00186,IT."; -$a->strings["Units"] = "Unità"; -$a->strings["select if the temperatur should be displayed in °C or °F"] = "scegli se la temperatura deve essere mostrata in °C o in °F"; -$a->strings["Show weather data"] = "Mostra dati meteo"; -$a->strings["Curweather settings saved."] = "Impostazioni Curweather salvati."; -$a->strings["Caching Interval"] = "Intervallo di cache"; -$a->strings["For how long should the weather data be cached? Choose according your OpenWeatherMap account type."] = "Per quanto tempo i dati meteo devono essere memorizzati? Scegli a seconda del tuo tipo di account su OpenWeatherMap."; -$a->strings["no cache"] = "nessuna cache"; -$a->strings["minutes"] = "minuti"; -$a->strings["Your APPID"] = "Il tuo APPID"; -$a->strings["Your API key provided by OpenWeatherMap"] = "La tua chiave API da OpenWeatherMap"; +if (!function_exists('string_plural_select_it')) { + function string_plural_select_it($n) + { + return $n != 1; + } +} + +$a->strings['Error fetching weather data.\\nError was: '] = 'Errore recuperando i dati meteo: '; +$a->strings['Current Weather'] = 'Meteo'; +$a->strings['Relative Humidity'] = 'Umidità Relativa'; +$a->strings['Pressure'] = 'Pressione'; +$a->strings['Wind'] = 'Vento'; +$a->strings['Last Updated'] = 'Ultimo Aggiornamento: '; +$a->strings['Data by'] = 'Data da'; +$a->strings['Show on map'] = 'Mostra sulla mappa'; +$a->strings['There was a problem accessing the weather data. But have a look'] = "C'è stato un problema accedendo ai dati meteo, ma dai un'occhiata"; +$a->strings['at OpenWeatherMap'] = 'a OpenWeatherMap'; +$a->strings['Current Weather settings updated.'] = 'Impostazioni Meteo aggiornate.'; +$a->strings['No APPID found, please contact your admin to optain one.'] = 'APPID non trovata, contatta il tuo amministratore per averne una.'; +$a->strings['Save Settings'] = 'Salva Impostazioni'; +$a->strings['Settings'] = 'Impostazioni'; +$a->strings['Enter either the name of your location or the zip code.'] = 'Inserisci il nome della tua posizione o il CAP'; +$a->strings['Your Location'] = 'La tua Posizione'; +$a->strings['Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE.'] = 'Identificatore della tua posizione (nome o CAP), p.e. Roma, IT or 00186,IT.'; +$a->strings['Units'] = 'Unità'; +$a->strings['select if the temperatur should be displayed in °C or °F'] = 'scegli se la temperatura deve essere mostrata in °C o in °F'; +$a->strings['Show weather data'] = 'Mostra dati meteo'; +$a->strings['Curweather settings saved.'] = 'Impostazioni Curweather salvati.'; +$a->strings['Caching Interval'] = 'Intervallo di cache'; +$a->strings['For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'] = 'Per quanto tempo i dati meteo devono essere memorizzati? Scegli a seconda del tuo tipo di account su OpenWeatherMap.'; +$a->strings['no cache'] = 'nessuna cache'; +$a->strings['minutes'] = 'minuti'; +$a->strings['Your APPID'] = 'Il tuo APPID'; +$a->strings['Your API key provided by OpenWeatherMap'] = 'La tua chiave API da OpenWeatherMap'; diff --git a/curweather/lang/nb-no/strings.php b/curweather/lang/nb-no/strings.php index 9001ec4a..6aca03bd 100644 --- a/curweather/lang/nb-no/strings.php +++ b/curweather/lang/nb-no/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Lagre"; +strings['Submit'] = 'Lagre'; diff --git a/curweather/lang/pl/strings.php b/curweather/lang/pl/strings.php index e18a64fb..96360b86 100644 --- a/curweather/lang/pl/strings.php +++ b/curweather/lang/pl/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Potwierdź"; +strings['Submit'] = 'Potwierdź'; diff --git a/curweather/lang/pt-br/strings.php b/curweather/lang/pt-br/strings.php index f50bc4a0..f5022292 100644 --- a/curweather/lang/pt-br/strings.php +++ b/curweather/lang/pt-br/strings.php @@ -1,34 +1,36 @@ 1);; -}} -; -$a->strings["Error fetching weather data.\\nError was: "] = "Houve um erro na obtenção de dados do clima\\nErro:"; -$a->strings["Current Weather"] = "Clima atual"; -$a->strings["Relative Humidity"] = "Umidade relativa"; -$a->strings["Pressure"] = "Pressão"; -$a->strings["Wind"] = "Vento"; -$a->strings["Last Updated"] = "Atualizado"; -$a->strings["Data by"] = "Dados de"; -$a->strings["Show on map"] = "Mostrar no mapa"; -$a->strings["There was a problem accessing the weather data. But have a look"] = "Houve um problema no acesso aos dados do clima. Mas dê uma olhada"; -$a->strings["at OpenWeatherMap"] = "em OpenWeatherMap"; -$a->strings["Current Weather settings updated."] = "Atualização das Configurações de clima."; -$a->strings["No APPID found, please contact your admin to optain one."] = "Não foi encontrado nenhum AppID; fale com seu administrador para receber um."; -$a->strings["Save Settings"] = "Salvar Configurações"; -$a->strings["Settings"] = "Configurações"; -$a->strings["Enter either the name of your location or the zip code."] = "Informe sua localização ou seu CEP."; -$a->strings["Your Location"] = "Sua localização"; -$a->strings["Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE."] = "Identificador da sua localização (nome ou CEP), p.ex. Rio,BR ou 20021,BR."; -$a->strings["Units"] = "Unidades"; -$a->strings["select if the temperatur should be displayed in °C or °F"] = "selecione se a temperatura será exibida em °C or °F"; -$a->strings["Show weather data"] = "Mostrar dados do clima"; -$a->strings["Curweather settings saved."] = "As configurações do Curweather foram salvas."; -$a->strings["Caching Interval"] = "Intervalo de cache"; -$a->strings["For how long should the weather data be cached? Choose according your OpenWeatherMap account type."] = "Por quanto tempo os dados do clima devem ser guardados em cache? Escolha de acordo com o tipo da sua conta no OpenWeatherMap."; -$a->strings["no cache"] = "sem cache"; -$a->strings["minutes"] = "minutos"; -$a->strings["Your APPID"] = "Seu AppID"; -$a->strings["Your API key provided by OpenWeatherMap"] = "Sua chave de API fornecida pelo OpenWeatherMap"; +if (!function_exists('string_plural_select_pt_br')) { + function string_plural_select_pt_br($n) + { + return $n > 1; + } +} + +$a->strings['Error fetching weather data.\\nError was: '] = 'Houve um erro na obtenção de dados do clima\\nErro:'; +$a->strings['Current Weather'] = 'Clima atual'; +$a->strings['Relative Humidity'] = 'Umidade relativa'; +$a->strings['Pressure'] = 'Pressão'; +$a->strings['Wind'] = 'Vento'; +$a->strings['Last Updated'] = 'Atualizado'; +$a->strings['Data by'] = 'Dados de'; +$a->strings['Show on map'] = 'Mostrar no mapa'; +$a->strings['There was a problem accessing the weather data. But have a look'] = 'Houve um problema no acesso aos dados do clima. Mas dê uma olhada'; +$a->strings['at OpenWeatherMap'] = 'em OpenWeatherMap'; +$a->strings['Current Weather settings updated.'] = 'Atualização das Configurações de clima.'; +$a->strings['No APPID found, please contact your admin to optain one.'] = 'Não foi encontrado nenhum AppID; fale com seu administrador para receber um.'; +$a->strings['Save Settings'] = 'Salvar Configurações'; +$a->strings['Settings'] = 'Configurações'; +$a->strings['Enter either the name of your location or the zip code.'] = 'Informe sua localização ou seu CEP.'; +$a->strings['Your Location'] = 'Sua localização'; +$a->strings['Identifier of your location (name or zip code), e.g. Berlin,DE or 14476,DE.'] = 'Identificador da sua localização (nome ou CEP), p.ex. Rio,BR ou 20021,BR.'; +$a->strings['Units'] = 'Unidades'; +$a->strings['select if the temperatur should be displayed in °C or °F'] = 'selecione se a temperatura será exibida em °C or °F'; +$a->strings['Show weather data'] = 'Mostrar dados do clima'; +$a->strings['Curweather settings saved.'] = 'As configurações do Curweather foram salvas.'; +$a->strings['Caching Interval'] = 'Intervalo de cache'; +$a->strings['For how long should the weather data be cached? Choose according your OpenWeatherMap account type.'] = 'Por quanto tempo os dados do clima devem ser guardados em cache? Escolha de acordo com o tipo da sua conta no OpenWeatherMap.'; +$a->strings['no cache'] = 'sem cache'; +$a->strings['minutes'] = 'minutos'; +$a->strings['Your APPID'] = 'Seu AppID'; +$a->strings['Your API key provided by OpenWeatherMap'] = 'Sua chave de API fornecida pelo OpenWeatherMap'; diff --git a/curweather/lang/ro/strings.php b/curweather/lang/ro/strings.php index 0d0ac9e3..e4e13a20 100644 --- a/curweather/lang/ro/strings.php +++ b/curweather/lang/ro/strings.php @@ -1,13 +1,15 @@ 19)||(($n%100==0)&&($n!=0)))?2:1));; -}} -; -$a->strings["Current Weather"] = "Starea Vremii"; -$a->strings["Current Weather settings updated."] = "Configurări actualizate pentru Starea Vremii"; -$a->strings["Current Weather Settings"] = "Configurări pentru Starea Vremii"; -$a->strings["Weather Location: "] = "Locație Meteo:"; -$a->strings["Enable Current Weather"] = "Activare Starea Vremii"; -$a->strings["Submit"] = "Trimite"; +if (!function_exists('string_plural_select_ro')) { + function string_plural_select_ro($n) + { + return $n == 1 ? 0 : ((($n % 100 > 19) || (($n % 100 == 0) && ($n != 0))) ? 2 : 1); + } +} + +$a->strings['Current Weather'] = 'Starea Vremii'; +$a->strings['Current Weather settings updated.'] = 'Configurări actualizate pentru Starea Vremii'; +$a->strings['Current Weather Settings'] = 'Configurări pentru Starea Vremii'; +$a->strings['Weather Location: '] = 'Locație Meteo:'; +$a->strings['Enable Current Weather'] = 'Activare Starea Vremii'; +$a->strings['Submit'] = 'Trimite'; diff --git a/curweather/lang/ru/strings.php b/curweather/lang/ru/strings.php index ab5e2246..f100be77 100644 --- a/curweather/lang/ru/strings.php +++ b/curweather/lang/ru/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Подтвердить"; +strings['Submit'] = 'Подтвердить'; diff --git a/curweather/lang/sv/strings.php b/curweather/lang/sv/strings.php index 3ec569a7..4575a404 100644 --- a/curweather/lang/sv/strings.php +++ b/curweather/lang/sv/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "Spara"; +strings['Submit'] = 'Spara'; diff --git a/curweather/lang/zh-cn/strings.php b/curweather/lang/zh-cn/strings.php index d6d8e7d2..241eef3d 100644 --- a/curweather/lang/zh-cn/strings.php +++ b/curweather/lang/zh-cn/strings.php @@ -1,3 +1,3 @@ -strings["Submit"] = "提交"; +strings['Submit'] = '提交'; diff --git a/dav/SabreDAV/bin/gwdg.php b/dav/SabreDAV/bin/gwdg.php index 00a6f13d..37c119b1 100755 --- a/dav/SabreDAV/bin/gwdg.php +++ b/dav/SabreDAV/bin/gwdg.php @@ -2,7 +2,7 @@ $fileInfo) { - + foreach ($files as $fileName => $fileInfo) { $tokens = token_get_all(file_get_contents($fileName)); - foreach($tokens as $tokenIndex=>$token) { - - if ($token[0]===T_CLASS || $token[0]===T_INTERFACE) { - $classNames[] = $tokens[$tokenIndex+2][1]; + foreach ($tokens as $tokenIndex => $token) { + if ($token[0] === T_CLASS || $token[0] === T_INTERFACE) { + $classNames[] = $tokens[$tokenIndex + 2][1]; } - } - } return $classNames; - } -function getClassTree($classNames) { - +function getClassTree($classNames) +{ $classTree = array(); - foreach($classNames as $className) { - - if (!class_exists($className) && !interface_exists($className)) continue; + foreach ($classNames as $className) { + if (!class_exists($className) && !interface_exists($className)) { + continue; + } $rClass = new ReflectionClass($className); $parent = $rClass->getParentClass(); - if ($parent) $parent = $parent->name; + if ($parent) { + $parent = $parent->name; + } - if (!isset($classTree[$parent])) $classTree[$parent] = array(); + if (!isset($classTree[$parent])) { + $classTree[$parent] = array(); + } $classTree[$parent][] = $className; - foreach($rClass->getInterfaceNames() as $interface) { - + foreach ($rClass->getInterfaceNames() as $interface) { if (!isset($classTree[$interface])) { $classTree[$interface] = array(); } $classTree[$interface][] = $className; - } - } - return $classTree; + return $classTree; } -function createDoc($className, $extendedBy) { +function createDoc($className, $extendedBy) +{ // ew global $packageList; @@ -108,26 +105,28 @@ function createDoc($className, $extendedBy) { ob_start(); $rClass = new ReflectionClass($className); - echo "#summary API documentation for: ", $rClass->getName() , "\n"; + echo '#summary API documentation for: ', $rClass->getName() , "\n"; echo "#labels APIDoc\n"; echo "#sidebar APIIndex\n"; - echo "=`" . $rClass->getName() . "`=\n"; + echo '=`'.$rClass->getName()."`=\n"; echo "\n"; $docs = parseDocs($rClass->getDocComment()); - echo $docs['description'] . "\n"; + echo $docs['description']."\n"; echo "\n"; $parentClass = $rClass->getParentClass(); - if($parentClass) { - echo " * Parent class: [" . $parentClass->getName() . "]\n"; + if ($parentClass) { + echo ' * Parent class: ['.$parentClass->getName()."]\n"; } if ($interfaces = $rClass->getInterfaceNames()) { - $interfaces = array_map(function($int) { return '[' . $int . ']'; },$interfaces); - echo " * Implements: " . implode(", ", $interfaces) . "\n"; + $interfaces = array_map(function ($int) { + return '['.$int.']'; + }, $interfaces); + echo ' * Implements: '.implode(', ', $interfaces)."\n"; } - $classType = $rClass->isInterface()?'interface':'class'; + $classType = $rClass->isInterface() ? 'interface' : 'class'; if (isset($docs['deprecated'])) { echo " * *Warning: This $classType is deprecated, and should not longer be used.*\n"; } @@ -139,7 +138,7 @@ function createDoc($className, $extendedBy) { if (isset($docs['package'])) { $package = $docs['package']; if (isset($docs['subpackage'])) { - $package.='_' . $docs['subpackage']; + $package .= '_'.$docs['subpackage']; } if (!isset($packageList[$package])) { $packageList[$package] = array(); @@ -148,13 +147,12 @@ function createDoc($className, $extendedBy) { } if ($extendedBy) { - echo "\n"; - if ($classType==='interface') { + if ($classType === 'interface') { echo "This interface is extended by the following interfaces:\n"; - foreach($extendedBy as $className) { + foreach ($extendedBy as $className) { if (interface_exists($className)) { - echo " * [" . $className . "]\n"; + echo ' * ['.$className."]\n"; } } echo "\n"; @@ -162,13 +160,12 @@ function createDoc($className, $extendedBy) { } else { echo "This class is extended by the following classes:\n"; } - foreach($extendedBy as $className) { + foreach ($extendedBy as $className) { if (class_exists($className)) { - echo " * [" . $className . "]\n"; + echo ' * ['.$className."]\n"; } } echo "\n"; - } echo "\n"; @@ -178,11 +175,9 @@ function createDoc($className, $extendedBy) { $properties = $rClass->getProperties(ReflectionProperty::IS_STATIC | ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED); - if (count($properties)>0) { - foreach($properties as $rProperty) { - + if (count($properties) > 0) { + foreach ($properties as $rProperty) { createPropertyDoc($rProperty); - } } else { echo "This $classType does not define any public or protected properties.\n"; @@ -196,54 +191,52 @@ function createDoc($className, $extendedBy) { $methods = $rClass->getMethods(ReflectionMethod::IS_PUBLIC | ReflectionMethod::IS_PROTECTED); - if (count($methods)>0) { - foreach($methods as $rMethod) { - + if (count($methods) > 0) { + foreach ($methods as $rMethod) { createMethodDoc($rMethod, $rClass); - } } else { echo "\nThis $classType does not define any public or protected methods.\n"; } return ob_get_clean(); - } -function createMethodDoc($rMethod, $rClass) { - - echo "===`" . $rMethod->getName() . "`===\n"; +function createMethodDoc($rMethod, $rClass) +{ + echo '===`'.$rMethod->getName()."`===\n"; echo "\n"; $docs = parseDocs($rMethod->getDocComment()); - $return = isset($docs['return'])?$docs['return']:'void'; + $return = isset($docs['return']) ? $docs['return'] : 'void'; echo "{{{\n"; - echo $return . " " . $rMethod->class . "::" . $rMethod->getName() . "("; - foreach($rMethod->getParameters() as $parameter) { - if ($parameter->getPosition()>0) echo ", "; + echo $return.' '.$rMethod->class.'::'.$rMethod->getName().'('; + foreach ($rMethod->getParameters() as $parameter) { + if ($parameter->getPosition() > 0) { + echo ', '; + } if ($class = $parameter->getClass()) { - echo $class->name . " "; + echo $class->name.' '; } elseif (isset($docs['param'][$parameter->name])) { - echo $docs['param'][$parameter->name] . " "; + echo $docs['param'][$parameter->name].' '; } - echo '$' . $parameter->name; + echo '$'.$parameter->name; if ($parameter->isOptional() && $parameter->isDefaultValueAvailable()) { $default = $parameter->getDefaultValue(); - $default = var_export($default,true); - $default = str_replace("\n","",$default); - echo " = " . $default; - + $default = var_export($default, true); + $default = str_replace("\n", '', $default); + echo ' = '.$default; } } echo ")\n"; echo "}}}\n"; echo "\n"; - echo $docs['description'] . "\n"; + echo $docs['description']."\n"; echo "\n"; @@ -266,31 +259,36 @@ function createMethodDoc($rMethod, $rClass) { } if ($rMethod->class != $rClass->name) { - echo " * Defined in [" . $rMethod->class . "]\n"; + echo ' * Defined in ['.$rMethod->class."]\n"; $hasProp = true; } - if ($hasProp) echo "\n"; - + if ($hasProp) { + echo "\n"; + } } -function createPropertyDoc($rProperty) { - - echo "===`" . $rProperty->getName() . "`===\n"; +function createPropertyDoc($rProperty) +{ + echo '===`'.$rProperty->getName()."`===\n"; echo "\n"; $docs = parseDocs($rProperty->getDocComment()); $visibility = 'public'; - if ($rProperty->isProtected()) $visibility = 'protected'; - if ($rProperty->isPrivate()) $visibility = 'private'; + if ($rProperty->isProtected()) { + $visibility = 'protected'; + } + if ($rProperty->isPrivate()) { + $visibility = 'private'; + } echo "{{{\n"; - echo $visibility . " " . $rProperty->class . "::$" . $rProperty->getName(); + echo $visibility.' '.$rProperty->class.'::$'.$rProperty->getName(); echo "\n}}}\n"; echo "\n"; - echo $docs['description'] . "\n"; + echo $docs['description']."\n"; echo "\n"; @@ -312,67 +310,62 @@ function createPropertyDoc($rProperty) { $hasProp = true; } - if ($hasProp) echo "\n"; - + if ($hasProp) { + echo "\n"; + } } -function parseDocs($docString) { - +function parseDocs($docString) +{ $params = array(); $description = array(); // Trimming all the comment characters - $docString = trim($docString,"\n*/ "); - $docString = explode("\n",$docString); + $docString = trim($docString, "\n*/ "); + $docString = explode("\n", $docString); - foreach($docString as $str) { - - $str = ltrim($str,'* '); + foreach ($docString as $str) { + $str = ltrim($str, '* '); $str = trim($str); - if ($str && $str[0]==='@') { - $r = explode(' ',substr($str,1),2); + if ($str && $str[0] === '@') { + $r = explode(' ', substr($str, 1), 2); $paramName = $r[0]; - $paramValue = (count($r)>1)?$r[1]:''; + $paramValue = (count($r) > 1) ? $r[1] : ''; // 'param' paramName is special. Confusing, I know. - if ($paramName==='param') { - if (!isset($params['param'])) $params['param'] = array(); - $paramValue = explode(' ', $paramValue,3); - $params['param'][substr($paramValue[1],1)] = $paramValue[0]; + if ($paramName === 'param') { + if (!isset($params['param'])) { + $params['param'] = array(); + } + $paramValue = explode(' ', $paramValue, 3); + $params['param'][substr($paramValue[1], 1)] = $paramValue[0]; } else { $params[$paramName] = trim($paramValue); } } else { - $description[]=$str; + $description[] = $str; } - } - $params['description'] = trim(implode("\n",$description),"\n "); + $params['description'] = trim(implode("\n", $description), "\n "); return $params; - } -function createSidebarIndex($packageList) { - +function createSidebarIndex($packageList) +{ ob_start(); echo "#labels APIDocs\n"; echo "#summary List of all classes, neatly organized\n"; echo "=API Index=\n"; - foreach($packageList as $package=>$classes) { - + foreach ($packageList as $package => $classes) { echo " * $package\n"; sort($classes); - foreach($classes as $class) { - + foreach ($classes as $class) { echo " * [$class $class]\n"; - } - } return ob_get_clean(); - } diff --git a/dav/SabreDAV/bin/migrateto17.php b/dav/SabreDAV/bin/migrateto17.php index 89207877..b9863f61 100644 --- a/dav/SabreDAV/bin/migrateto17.php +++ b/dav/SabreDAV/bin/migrateto17.php @@ -2,8 +2,7 @@ echo "SabreDAV migrate script for version 1.7\n"; -if ($argc<2) { - +if ($argc < 2) { echo <<setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); @@ -54,7 +52,7 @@ $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); echo "Validating existing table layout\n"; // The only cross-db way to do this, is to just fetch a single record. -$row = $pdo->query("SELECT * FROM calendarobjects LIMIT 1")->fetch(); +$row = $pdo->query('SELECT * FROM calendarobjects LIMIT 1')->fetch(); if (!$row) { echo "Error: This database did not have any records in the calendarobjects table, you should just recreate the table.\n"; @@ -62,15 +60,15 @@ if (!$row) { } $requiredFields = array( - 'id', + 'id', 'calendardata', 'uri', - 'calendarid', + 'calendarid', 'lastmodified', ); -foreach($requiredFields as $requiredField) { - if (!array_key_exists($requiredField,$row)) { +foreach ($requiredFields as $requiredField) { + if (!array_key_exists($requiredField, $row)) { echo "Error: The current 'calendarobjects' table was missing a field we expected to exist.\n"; echo "For safety reasons, this process is stopped.\n"; exit(-1); @@ -86,9 +84,9 @@ $fields17 = array( ); $found = 0; -foreach($fields17 as $field) { +foreach ($fields17 as $field) { if (array_key_exists($field, $row)) { - $found++; + ++$found; } } @@ -96,11 +94,11 @@ if ($found === 0) { echo "The database had the 1.6 schema. Table will now be altered.\n"; echo "This may take some time for large tables\n"; - switch($pdo->getAttribute(PDO::ATTR_DRIVER_NAME)) { + switch ($pdo->getAttribute(PDO::ATTR_DRIVER_NAME)) { - case 'mysql' : + case 'mysql': - $pdo->exec(<<exec(<<<'SQL' ALTER TABLE calendarobjects ADD etag VARCHAR(32), ADD size INT(11) UNSIGNED, @@ -110,7 +108,7 @@ ADD lastoccurence INT(11) UNSIGNED SQL ); break; - case 'sqlite' : + case 'sqlite': $pdo->exec('ALTER TABLE calendarobjects ADD etag text'); $pdo->exec('ALTER TABLE calendarobjects ADD size integer'); $pdo->exec('ALTER TABLE calendarobjects ADD componenttype TEXT'); @@ -118,40 +116,34 @@ SQL $pdo->exec('ALTER TABLE calendarobjects ADD lastoccurence integer'); break; - default : - die('This upgrade script does not support this driver (' . $pdo->getAttribute(PDO::ATTR_DRIVER_NAME) . ")\n"); + default: + die('This upgrade script does not support this driver ('.$pdo->getAttribute(PDO::ATTR_DRIVER_NAME).")\n"); - } + } echo "Database schema upgraded.\n"; - } elseif ($found === 5) { - echo "Database already had the 1.7 schema\n"; - } else { - echo "The database had $found out of 5 from the changes for 1.7. This is scary and unusual, so we have to abort.\n"; echo "You can manually try to upgrade the schema, and then run this script again.\n"; exit(-1); - } echo "Now, we need to parse every record and pull out some information.\n"; $result = $pdo->query('SELECT id, calendardata FROM calendarobjects'); -$stmt = $pdo->prepare('UPDATE calendarobjects SET etag = ?, size = ?, componenttype = ?, firstoccurence = ?, lastoccurence = ? WHERE id = ?'); +$stmt = $pdo->prepare('UPDATE calendarobjects SET etag = ?, size = ?, componenttype = ?, firstoccurence = ?, lastoccurence = ? WHERE id = ?'); -echo "Total records found: " . $result->rowCount() . "\n"; +echo 'Total records found: '.$result->rowCount()."\n"; $done = 0; $total = $result->rowCount(); -while($row = $result->fetch()) { - +while ($row = $result->fetch()) { try { $newData = getDenormalizedData($row['calendardata']); } catch (Exception $e) { echo "===\nException caught will trying to parser calendarobject.\n"; - echo "Error message: " . $e->getMessage() . "\n"; - echo "Record id: " . $row['id'] . "\n"; + echo 'Error message: '.$e->getMessage()."\n"; + echo 'Record id: '.$row['id']."\n"; echo "This record is ignored, you should inspect it to see if there's anything wrong.\n===\n"; continue; } @@ -163,11 +155,11 @@ while($row = $result->fetch()) { $newData['lastOccurence'], $row['id'], )); - $done++; + ++$done; if ($done % 500 === 0) { echo "Completed: $done / $total\n"; - } + } } echo "Process completed!\n"; @@ -186,17 +178,18 @@ echo "Process completed!\n"; * * lastOccurence * * @param string $calendarData + * * @return array */ -function getDenormalizedData($calendarData) { - +function getDenormalizedData($calendarData) +{ $vObject = Sabre_VObject_Reader::read($calendarData); $componentType = null; $component = null; $firstOccurence = null; $lastOccurence = null; - foreach($vObject->getComponents() as $component) { - if ($component->name!=='VTIMEZONE') { + foreach ($vObject->getComponents() as $component) { + if ($component->name !== 'VTIMEZONE') { $componentType = $component->name; break; } @@ -214,7 +207,7 @@ function getDenormalizedData($calendarData) { $endDate = clone $component->DTSTART->getDateTime(); $endDate->add(Sabre_VObject_DateTimeParser::parse($component->DURATION->value)); $lastOccurence = $endDate->getTimeStamp(); - } elseif ($component->DTSTART->getDateType()===Sabre_VObject_Property_DateTime::DATE) { + } elseif ($component->DTSTART->getDateType() === Sabre_VObject_Property_DateTime::DATE) { $endDate = clone $component->DTSTART->getDateTime(); $endDate->modify('+1 day'); $lastOccurence = $endDate->getTimeStamp(); @@ -222,20 +215,18 @@ function getDenormalizedData($calendarData) { $lastOccurence = $firstOccurence; } } else { - $it = new Sabre_VObject_RecurrenceIterator($vObject, (string)$component->UID); + $it = new Sabre_VObject_RecurrenceIterator($vObject, (string) $component->UID); $maxDate = new DateTime(Sabre_CalDAV_Backend_PDO::MAX_DATE); if ($it->isInfinite()) { $lastOccurence = $maxDate->getTimeStamp(); } else { $end = $it->getDtEnd(); - while($it->valid() && $end < $maxDate) { + while ($it->valid() && $end < $maxDate) { $end = $it->getDtEnd(); $it->next(); - } $lastOccurence = $end->getTimeStamp(); } - } } @@ -244,7 +235,6 @@ function getDenormalizedData($calendarData) { 'size' => strlen($calendarData), 'componentType' => $componentType, 'firstOccurence' => $firstOccurence, - 'lastOccurence' => $lastOccurence, + 'lastOccurence' => $lastOccurence, ); - } diff --git a/dav/SabreDAV/bin/pearpackage3.php b/dav/SabreDAV/bin/pearpackage3.php index 4af04072..62f733a2 100755 --- a/dav/SabreDAV/bin/pearpackage3.php +++ b/dav/SabreDAV/bin/pearpackage3.php @@ -6,9 +6,11 @@ date_default_timezone_set('UTC'); $make = false; $packageName = null; -foreach($argv as $index=>$arg) { - if ($index==0) continue; - if ($arg=='make') { +foreach ($argv as $index => $arg) { + if ($index == 0) { + continue; + } + if ($arg == 'make') { $make = true; continue; } @@ -21,7 +23,7 @@ if (is_null($packageName)) { die(1); } -if (!is_dir('build/' . $packageName)) { +if (!is_dir('build/'.$packageName)) { echo "Could not find package directory: build/$packageName\n"; die(2); } @@ -31,20 +33,19 @@ if (!is_dir('build/' . $packageName)) { $dependencies = array( array( 'type' => 'php', - 'min' => '5.3.1', + 'min' => '5.3.1', ), array( 'type' => 'pearinstaller', - 'min' => '1.9', + 'min' => '1.9', ), ); +switch ($packageName) { -switch($packageName) { - - case 'Sabre' : + case 'Sabre': $summary = 'Sabretooth base package.'; - $description = << 'package', 'name' => 'Sabre', 'channel' => 'pear.sabredav.org', - 'min' => '1.0.0', + 'min' => '1.0.0', ); $dependencies[] = array( 'type' => 'package', 'name' => 'Sabre_HTTP', 'channel' => 'pear.sabredav.org', - 'min' => '1.6.0', + 'min' => '1.6.0', ); break; - case 'Sabre_HTTP' : + case 'Sabre_HTTP': $summary = 'Sabre_HTTP provides various HTTP helpers, for input and output and authentication'; - $description = << 'package', 'name' => 'Sabre', 'channel' => 'pear.sabredav.org', - 'min' => '1.0.0', + 'min' => '1.0.0', ); break; - case 'Sabre_DAVACL' : + case 'Sabre_DAVACL': $summary = 'Sabre_DAVACL provides rfc3744 support.'; - $description = << 'package', 'name' => 'Sabre', 'channel' => 'pear.sabredav.org', - 'min' => '1.0.0', + 'min' => '1.0.0', ); $dependencies[] = array( 'type' => 'package', 'name' => 'Sabre_DAV', 'channel' => 'pear.sabredav.org', - 'min' => '1.6.0', + 'min' => '1.6.0', ); break; - case 'Sabre_CalDAV' : + case 'Sabre_CalDAV': $summary = 'Sabre_CalDAV provides CalDAV extensions to SabreDAV'; - $description = << 'package', 'name' => 'Sabre', 'channel' => 'pear.sabredav.org', - 'min' => '1.0.0', + 'min' => '1.0.0', ); $dependencies[] = array( 'type' => 'package', 'name' => 'Sabre_HTTP', 'channel' => 'pear.sabredav.org', - 'min' => '1.6.0', + 'min' => '1.6.0', ); $dependencies[] = array( 'type' => 'package', 'name' => 'Sabre_DAV', 'channel' => 'pear.sabredav.org', - 'min' => '1.6.0', + 'min' => '1.6.0', ); $dependencies[] = array( 'type' => 'package', 'name' => 'Sabre_DAVACL', 'channel' => 'pear.sabredav.org', - 'min' => '1.6.0', + 'min' => '1.6.0', ); $dependencies[] = array( 'type' => 'package', 'name' => 'Sabre_VObject', 'channel' => 'pear.sabredav.org', - 'min' => '1.3.0', + 'min' => '1.3.0', ); break; - case 'Sabre_CardDAV' : + case 'Sabre_CardDAV': $summary = 'Sabre_CardDAV provides CardDAV extensions to SabreDAV'; $description = << 'package', 'name' => 'Sabre', 'channel' => 'pear.sabredav.org', - 'min' => '1.0.0', + 'min' => '1.0.0', ); $dependencies[] = array( 'type' => 'package', 'name' => 'Sabre_HTTP', 'channel' => 'pear.sabredav.org', - 'min' => '1.6.0', + 'min' => '1.6.0', ); $dependencies[] = array( 'type' => 'package', 'name' => 'Sabre_DAV', 'channel' => 'pear.sabredav.org', - 'min' => '1.6.0', + 'min' => '1.6.0', ); $dependencies[] = array( 'type' => 'package', 'name' => 'Sabre_DAVACL', 'channel' => 'pear.sabredav.org', - 'min' => '1.6.0', + 'min' => '1.6.0', ); $dependencies[] = array( 'type' => 'package', 'name' => 'Sabre_VObject', 'channel' => 'pear.sabredav.org', - 'min' => '1.3.0', + 'min' => '1.3.0', ); break; - case 'Sabre_VObject' : + case 'Sabre_VObject': $summary = 'Sabre_VObject is a natural-interface iCalendar and vCard reader'; - $description = << 'package', 'name' => 'Sabre', 'channel' => 'pear.sabredav.org', - 'min' => '1.0.0', + 'min' => '1.0.0', ); break; } - if (!isset($version)) { - include 'lib/' . str_replace('_','/',$packageName) . '/Version.php'; - $versionClassName = $packageName . '_Version'; + include 'lib/'.str_replace('_', '/', $packageName).'/Version.php'; + $versionClassName = $packageName.'_Version'; $version = $versionClassName::VERSION; $stability = $versionClassName::STABILITY; } @@ -239,41 +239,44 @@ $notes = 'New release. Read the ChangeLog and announcement for more details'; $channel = 'pear.sabredav.org'; /* This function is intended to generate the full file list */ -function parsePath($fullPath, $role, $padding = 4) { - +function parsePath($fullPath, $role, $padding = 4) +{ $fileList = ''; $file = basename($fullPath); if (is_dir($fullPath)) { - $fileList .= str_repeat(' ', $padding) . "\n"; - foreach(scandir($fullPath) as $subPath) {; - if ($subPath==='.' || $subPath==='..') continue; - $fileList .= parsePath($fullPath. '/' . $subPath,$role, $padding+2); + $fileList .= str_repeat(' ', $padding)."\n"; + foreach (scandir($fullPath) as $subPath) { + if ($subPath === '.' || $subPath === '..') { + continue; + } + $fileList .= parsePath($fullPath.'/'.$subPath, $role, $padding + 2); } - $fileList .= str_repeat(' ', $padding) . "\n"; + $fileList .= str_repeat(' ', $padding)."\n"; } elseif (is_file($fullPath)) { - $fileList .= str_repeat(' ', $padding) . "\n"; + $fileList .= str_repeat(' ', $padding)."\n"; } return $fileList; - } -$rootDir = realpath('build/' . $packageName); +$rootDir = realpath('build/'.$packageName); -$fileList = parsePath($rootDir . '/Sabre', 'php'); -$fileList .= parsePath($rootDir . '/examples', 'doc'); -$fileList .= parsePath($rootDir . '/ChangeLog', 'doc'); -$fileList .= parsePath($rootDir . '/LICENSE', 'doc'); +$fileList = parsePath($rootDir.'/Sabre', 'php'); +$fileList .= parsePath($rootDir.'/examples', 'doc'); +$fileList .= parsePath($rootDir.'/ChangeLog', 'doc'); +$fileList .= parsePath($rootDir.'/LICENSE', 'doc'); $dependenciesXML = "\n"; -foreach($dependencies as $dep) { +foreach ($dependencies as $dep) { $pad = 8; - $dependenciesXML.=str_repeat(' ',$pad) . '<' . $dep['type'] . ">\n"; - foreach($dep as $key=>$value) { - if ($key=='type') continue; - $dependenciesXML.=str_repeat(' ',$pad+2) . "<$key>$value\n"; + $dependenciesXML .= str_repeat(' ', $pad).'<'.$dep['type'].">\n"; + foreach ($dep as $key => $value) { + if ($key == 'type') { + continue; + } + $dependenciesXML .= str_repeat(' ', $pad + 2)."<$key>$value\n"; } - $dependenciesXML.=str_repeat(' ',$pad) . '\n"; + $dependenciesXML .= str_repeat(' ', $pad).'\n"; } $package = << XML; -if (isset($argv) && in_array('make',$argv)) { - file_put_contents($rootDir . '/package.xml',$package); +if (isset($argv) && in_array('make', $argv)) { + file_put_contents($rootDir.'/package.xml', $package); } else { echo $package; } diff --git a/dav/SabreDAV/examples/addressbookserver.php b/dav/SabreDAV/examples/addressbookserver.php index 22b30e61..49eee439 100644 --- a/dav/SabreDAV/examples/addressbookserver.php +++ b/dav/SabreDAV/examples/addressbookserver.php @@ -17,21 +17,22 @@ $baseUri = '/'; /* Database */ $pdo = new PDO('sqlite:data/db.sqlite'); -$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); +$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Mapping PHP errors to exceptions -function exception_error_handler($errno, $errstr, $errfile, $errline ) { +function exception_error_handler($errno, $errstr, $errfile, $errline) +{ throw new ErrorException($errstr, 0, $errno, $errfile, $errline); } -set_error_handler("exception_error_handler"); +set_error_handler('exception_error_handler'); // Autoloader require_once 'lib/Sabre/autoload.php'; // Backends -$authBackend = new Sabre_DAV_Auth_Backend_PDO($pdo); +$authBackend = new Sabre_DAV_Auth_Backend_PDO($pdo); $principalBackend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); -$carddavBackend = new Sabre_CardDAV_Backend_PDO($pdo); +$carddavBackend = new Sabre_CardDAV_Backend_PDO($pdo); //$caldavBackend = new Sabre_CalDAV_Backend_PDO($pdo); // Setting up the directory tree // @@ -46,7 +47,7 @@ $server = new Sabre_DAV_Server($nodes); $server->setBaseUri($baseUri); // Plugins -$server->addPlugin(new Sabre_DAV_Auth_Plugin($authBackend,'SabreDAV')); +$server->addPlugin(new Sabre_DAV_Auth_Plugin($authBackend, 'SabreDAV')); $server->addPlugin(new Sabre_DAV_Browser_Plugin()); //$server->addPlugin(new Sabre_CalDAV_Plugin()); $server->addPlugin(new Sabre_CardDAV_Plugin()); diff --git a/dav/SabreDAV/examples/basicauth.php b/dav/SabreDAV/examples/basicauth.php index 75552f3f..735f510b 100644 --- a/dav/SabreDAV/examples/basicauth.php +++ b/dav/SabreDAV/examples/basicauth.php @@ -17,10 +17,8 @@ $auth = new Sabre_HTTP_BasicAuth(); $result = $auth->getUserPass(); -if (!$result || $result[0]!=$u || $result[1]!=$p) { - +if (!$result || $result[0] != $u || $result[1] != $p) { $auth->requireLogin(); echo "Authentication required\n"; die(); - } diff --git a/dav/SabreDAV/examples/calendarserver.php b/dav/SabreDAV/examples/calendarserver.php index b6cc5c31..9fdfa708 100644 --- a/dav/SabreDAV/examples/calendarserver.php +++ b/dav/SabreDAV/examples/calendarserver.php @@ -17,13 +17,14 @@ date_default_timezone_set('Canada/Eastern'); /* Database */ $pdo = new PDO('sqlite:data/db.sqlite'); -$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); +$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //Mapping PHP errors to exceptions -function exception_error_handler($errno, $errstr, $errfile, $errline ) { +function exception_error_handler($errno, $errstr, $errfile, $errline) +{ throw new ErrorException($errstr, 0, $errno, $errfile, $errline); } -set_error_handler("exception_error_handler"); +set_error_handler('exception_error_handler'); // Files we need require_once 'lib/Sabre/autoload.php'; @@ -33,7 +34,7 @@ $authBackend = new Sabre_DAV_Auth_Backend_PDO($pdo); $calendarBackend = new Sabre_CalDAV_Backend_PDO($pdo); $principalBackend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); -// Directory structure +// Directory structure $tree = array( new Sabre_CalDAV_Principal_Collection($principalBackend), new Sabre_CalDAV_CalendarRootNode($principalBackend, $calendarBackend), @@ -41,11 +42,12 @@ $tree = array( $server = new Sabre_DAV_Server($tree); -if (isset($baseUri)) +if (isset($baseUri)) { $server->setBaseUri($baseUri); +} /* Server Plugins */ -$authPlugin = new Sabre_DAV_Auth_Plugin($authBackend,'SabreDAV'); +$authPlugin = new Sabre_DAV_Auth_Plugin($authBackend, 'SabreDAV'); $server->addPlugin($authPlugin); $aclPlugin = new Sabre_DAVACL_Plugin(); diff --git a/dav/SabreDAV/examples/digestauth.php b/dav/SabreDAV/examples/digestauth.php index 748f7c4f..4c2f28de 100644 --- a/dav/SabreDAV/examples/digestauth.php +++ b/dav/SabreDAV/examples/digestauth.php @@ -17,9 +17,7 @@ $auth = new Sabre_HTTP_DigestAuth(); $auth->init(); if ($auth->getUsername() != $u || !$auth->validatePassword($p)) { - $auth->requireLogin(); echo "Authentication required\n"; die(); - } diff --git a/dav/SabreDAV/examples/fileserver.php b/dav/SabreDAV/examples/fileserver.php index 88a57087..eb93c786 100644 --- a/dav/SabreDAV/examples/fileserver.php +++ b/dav/SabreDAV/examples/fileserver.php @@ -2,7 +2,7 @@ // !!!! Make sure the Sabre directory is in the include_path !!! // example: -set_include_path('lib/' . PATH_SEPARATOR . get_include_path()); +set_include_path('lib/'.PATH_SEPARATOR.get_include_path()); /* @@ -22,7 +22,6 @@ $tmpDir = 'tmpdata'; // You can override the baseUri here. // $baseUri = '/'; - // Files we need require_once 'Sabre/autoload.php'; @@ -32,11 +31,12 @@ $root = new Sabre_DAV_FS_Directory($publicDir); // The rootnode needs in turn to be passed to the server class $server = new Sabre_DAV_Server($root); -if (isset($baseUri)) +if (isset($baseUri)) { $server->setBaseUri($baseUri); +} // Support for LOCK and UNLOCK -$lockBackend = new Sabre_DAV_Locks_Backend_File($tmpDir . '/locksdb'); +$lockBackend = new Sabre_DAV_Locks_Backend_File($tmpDir.'/locksdb'); $lockPlugin = new Sabre_DAV_Locks_Plugin($lockBackend); $server->addPlugin($lockPlugin); @@ -49,7 +49,7 @@ $server->addPlugin(new Sabre_DAV_Browser_GuessContentType()); // Authentication backend $authBackend = new Sabre_DAV_Auth_Backend_File('.htdigest'); -$auth = new Sabre_DAV_Auth_Plugin($authBackend,'SabreDAV'); +$auth = new Sabre_DAV_Auth_Plugin($authBackend, 'SabreDAV'); $server->addPlugin($auth); // Temporary file filter diff --git a/dav/SabreDAV/examples/groupwareserver.php b/dav/SabreDAV/examples/groupwareserver.php index bf8e7430..acc1ddc3 100644 --- a/dav/SabreDAV/examples/groupwareserver.php +++ b/dav/SabreDAV/examples/groupwareserver.php @@ -27,13 +27,13 @@ date_default_timezone_set('UTC'); $baseUri = '/'; /** - * Database + * Database. * * Feel free to switch this to MySQL, it will definitely be better for higher * concurrency. */ $pdo = new PDO('sqlite:data/db.sqlite'); -$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); +$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /** * Mapping PHP errors to exceptions. @@ -42,10 +42,11 @@ $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); * E_NOTICE or anything appears in your code, this allows SabreDAV to intercept * the issue and send a proper response back to the client (HTTP/1.1 500). */ -function exception_error_handler($errno, $errstr, $errfile, $errline ) { +function exception_error_handler($errno, $errstr, $errfile, $errline) +{ throw new ErrorException($errstr, 0, $errno, $errfile, $errline); } -set_error_handler("exception_error_handler"); +set_error_handler('exception_error_handler'); // Autoloader require_once 'lib/Sabre/autoload.php'; @@ -56,13 +57,13 @@ require_once 'lib/Sabre/autoload.php'; * This allows any developer to subclass just any of them and hook into their * own backend systems. */ -$authBackend = new Sabre_DAV_Auth_Backend_PDO($pdo); +$authBackend = new Sabre_DAV_Auth_Backend_PDO($pdo); $principalBackend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); -$carddavBackend = new Sabre_CardDAV_Backend_PDO($pdo); -$caldavBackend = new Sabre_CalDAV_Backend_PDO($pdo); +$carddavBackend = new Sabre_CardDAV_Backend_PDO($pdo); +$caldavBackend = new Sabre_CalDAV_Backend_PDO($pdo); /** - * The directory tree + * The directory tree. * * Basically this is an array which contains the 'top-level' directories in the * WebDAV server. @@ -81,7 +82,7 @@ $server = new Sabre_DAV_Server($nodes); $server->setBaseUri($baseUri); // Plugins -$server->addPlugin(new Sabre_DAV_Auth_Plugin($authBackend,'SabreDAV')); +$server->addPlugin(new Sabre_DAV_Auth_Plugin($authBackend, 'SabreDAV')); $server->addPlugin(new Sabre_DAV_Browser_Plugin()); $server->addPlugin(new Sabre_CalDAV_Plugin()); $server->addPlugin(new Sabre_CardDAV_Plugin()); diff --git a/dav/SabreDAV/examples/simplefsserver.php b/dav/SabreDAV/examples/simplefsserver.php index d7ea3f7c..7c41cb14 100644 --- a/dav/SabreDAV/examples/simplefsserver.php +++ b/dav/SabreDAV/examples/simplefsserver.php @@ -26,91 +26,82 @@ $publicDir = 'public'; // Files we need require_once 'Sabre/autoload.php'; -class MyDirectory extends Sabre_DAV_Directory { +class MyDirectory extends Sabre_DAV_Directory +{ + private $myPath; - private $myPath; + public function __construct($myPath) + { + $this->myPath = $myPath; + } - function __construct($myPath) { - - $this->myPath = $myPath; - - } - - function getChildren() { - - $children = array(); + public function getChildren() + { + $children = array(); // Loop through the directory, and create objects for each node - foreach(scandir($this->myPath) as $node) { + foreach (scandir($this->myPath) as $node) { // Ignoring files staring with . - if ($node[0]==='.') continue; - - $children[] = $this->getChild($node); + if ($node[0] === '.') { + continue; + } + $children[] = $this->getChild($node); } - return $children; + return $children; + } - } - - function getChild($name) { - - $path = $this->myPath . '/' . $name; + public function getChild($name) + { + $path = $this->myPath.'/'.$name; // We have to throw a NotFound exception if the file didn't exist - if (!file_exists($this->myPath)) throw new Sabre_DAV_Exception_NotFound('The file with name: ' . $name . ' could not be found'); + if (!file_exists($this->myPath)) { + throw new Sabre_DAV_Exception_NotFound('The file with name: '.$name.' could not be found'); + } // Some added security - if ($name[0]=='.') throw new Sabre_DAV_Exception_NotFound('Access denied'); - - if (is_dir($path)) { - - return new MyDirectory($name); - - } else { - - return new MyFile($path); - + if ($name[0] == '.') { + throw new Sabre_DAV_Exception_NotFound('Access denied'); } + if (is_dir($path)) { + return new self($name); + } else { + return new MyFile($path); + } } - function getName() { - + public function getName() + { return basename($this->myPath); - } - } -class MyFile extends Sabre_DAV_File { +class MyFile extends Sabre_DAV_File +{ + private $myPath; - private $myPath; + public function __construct($myPath) + { + $this->myPath = $myPath; + } - function __construct($myPath) { + public function getName() + { + return basename($this->myPath); + } - $this->myPath = $myPath; - - } - - function getName() { - - return basename($this->myPath); - - } - - function get() { - - return fopen($this->myPath,'r'); - - } - - function getSize() { - - return filesize($this->myPath); - - } + public function get() + { + return fopen($this->myPath, 'r'); + } + public function getSize() + { + return filesize($this->myPath); + } } // Make sure there is a directory in your current directory named 'public'. We will be exposing that directory to WebDAV diff --git a/dav/SabreDAV/lib/Sabre.includes.php b/dav/SabreDAV/lib/Sabre.includes.php index c1334373..3fba63cc 100644 --- a/dav/SabreDAV/lib/Sabre.includes.php +++ b/dav/SabreDAV/lib/Sabre.includes.php @@ -1,7 +1,7 @@ getCalendarObjects($calendarId); $validator = new Sabre_CalDAV_CalendarQueryValidator(); - foreach($objects as $object) { - + foreach ($objects as $object) { if ($this->validateFilterForObject($object, $filters)) { $result[] = $object['uri']; } - } return $result; - } /** @@ -131,9 +127,11 @@ abstract class Sabre_CalDAV_Backend_Abstract implements Sabre_CalDAV_Backend_Bac * * @param array $object * @param array $filter + * * @return bool */ - protected function validateFilterForObject(array $object, array $filters) { + protected function validateFilterForObject(array $object, array $filters) + { // Unfortunately, setting the 'calendardata' here is optional. If // it was excluded, we actually need another call to get this as @@ -145,9 +143,7 @@ abstract class Sabre_CalDAV_Backend_Abstract implements Sabre_CalDAV_Backend_Bac $vObject = VObject\Reader::read($object['calendardata']); $validator = new Sabre_CalDAV_CalendarQueryValidator(); + return $validator->validate($vObject, $filters); - } - - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Backend/BackendInterface.php b/dav/SabreDAV/lib/Sabre/CalDAV/Backend/BackendInterface.php index 881538ab..fd15ca72 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Backend/BackendInterface.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Backend/BackendInterface.php @@ -2,15 +2,13 @@ /** * Every CalDAV backend must at least implement this interface. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) + * + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved + * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -interface Sabre_CalDAV_Backend_BackendInterface { - +interface Sabre_CalDAV_Backend_BackendInterface +{ /** * Returns a list of calendars for a principal. * @@ -26,6 +24,7 @@ interface Sabre_CalDAV_Backend_BackendInterface { * common one is '{DAV:}displayname'. * * @param string $principalUri + * * @return array */ public function getCalendarsForUser($principalUri); @@ -38,10 +37,9 @@ interface Sabre_CalDAV_Backend_BackendInterface { * * @param string $principalUri * @param string $calendarUri - * @param array $properties - * @return void + * @param array $properties */ - public function createCalendar($principalUri,$calendarUri,array $properties); + public function createCalendar($principalUri, $calendarUri, array $properties); /** * Updates properties for a calendar. @@ -77,15 +75,15 @@ interface Sabre_CalDAV_Backend_BackendInterface { * * @param mixed $calendarId * @param array $mutations + * * @return bool|array */ - public function updateCalendar($calendarId, array $mutations); + public function updateCalendar($calendarId, array $mutations); /** - * Delete a calendar and all it's objects + * Delete a calendar and all it's objects. * * @param mixed $calendarId - * @return void */ public function deleteCalendar($calendarId); @@ -114,6 +112,7 @@ interface Sabre_CalDAV_Backend_BackendInterface { * amount of times this is needed is reduced by a great degree. * * @param mixed $calendarId + * * @return array */ public function getCalendarObjects($calendarId); @@ -126,11 +125,12 @@ interface Sabre_CalDAV_Backend_BackendInterface { * 'calendardata' object is required here though, while it's not required * for getCalendarObjects. * - * @param mixed $calendarId + * @param mixed $calendarId * @param string $objectUri + * * @return array */ - public function getCalendarObject($calendarId,$objectUri); + public function getCalendarObject($calendarId, $objectUri); /** * Creates a new calendar object. @@ -143,12 +143,13 @@ interface Sabre_CalDAV_Backend_BackendInterface { * calendar-data. If the result of a subsequent GET to this object is not * the exact same as this request body, you should omit the ETag. * - * @param mixed $calendarId + * @param mixed $calendarId * @param string $objectUri * @param string $calendarData + * * @return string|null */ - public function createCalendarObject($calendarId,$objectUri,$calendarData); + public function createCalendarObject($calendarId, $objectUri, $calendarData); /** * Updates an existing calendarobject, based on it's uri. @@ -161,21 +162,21 @@ interface Sabre_CalDAV_Backend_BackendInterface { * calendar-data. If the result of a subsequent GET to this object is not * the exact same as this request body, you should omit the ETag. * - * @param mixed $calendarId + * @param mixed $calendarId * @param string $objectUri * @param string $calendarData + * * @return string|null */ - public function updateCalendarObject($calendarId,$objectUri,$calendarData); + public function updateCalendarObject($calendarId, $objectUri, $calendarData); /** * Deletes an existing calendar object. * - * @param mixed $calendarId + * @param mixed $calendarId * @param string $objectUri - * @return void */ - public function deleteCalendarObject($calendarId,$objectUri); + public function deleteCalendarObject($calendarId, $objectUri); /** * Performs a calendar-query on the contents of this calendar. @@ -224,8 +225,8 @@ interface Sabre_CalDAV_Backend_BackendInterface { * * @param mixed $calendarId * @param array $filters + * * @return array */ - public function calendarQuery($calendarId, array $filters); - + public function calendarQuery($calendarId, array $filters); } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Backend/NotificationSupport.php b/dav/SabreDAV/lib/Sabre/CalDAV/Backend/NotificationSupport.php index ad905b1a..839b5663 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Backend/NotificationSupport.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Backend/NotificationSupport.php @@ -6,39 +6,36 @@ * Notifications are defined at: * http://svn.calendarserver.org/repository/calendarserver/CalendarServer/trunk/doc/Extensions/caldav-notifications.txt * - * These notifications are basically a list of server-generated notifications + * These notifications are basically a list of server-generated notifications * displayed to the user. Users can dismiss notifications by deleting them. * * The primary usecase is to allow for calendar-sharing. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) + * + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved + * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -interface Sabre_CalDAV_Backend_NotificationSupport extends Sabre_CalDAV_Backend_BackendInterface { - +interface Sabre_CalDAV_Backend_NotificationSupport extends Sabre_CalDAV_Backend_BackendInterface +{ /** * Returns a list of notifications for a given principal url. * * The returned array should only consist of implementations of - * Sabre_CalDAV_Notifications_INotificationType. - * + * Sabre_CalDAV_Notifications_INotificationType. + * * @param string $principalUri - * @return array + * + * @return array */ public function getNotificationsForPrincipal($principalUri); /** * This deletes a specific notifcation. * - * This may be called by a client once it deems a notification handled. - * - * @param string $principalUri - * @param Sabre_CalDAV_Notifications_INotificationType $notification - * @return void + * This may be called by a client once it deems a notification handled. + * + * @param string $principalUri + * @param Sabre_CalDAV_Notifications_INotificationType $notification */ - public function deleteNotification($principalUri, Sabre_CalDAV_Notifications_INotificationType $notification); - + public function deleteNotification($principalUri, Sabre_CalDAV_Notifications_INotificationType $notification); } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Backend/PDO.php b/dav/SabreDAV/lib/Sabre/CalDAV/Backend/PDO.php index 74b34267..3be0aa66 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Backend/PDO.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Backend/PDO.php @@ -3,21 +3,19 @@ use Sabre\VObject; /** - * PDO CalDAV backend + * PDO CalDAV backend. * * This backend is used to store calendar-data in a PDO database, such as * sqlite or MySQL * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { - +class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract +{ /** - * We need to specify a max date, because we need to stop *somewhere* + * We need to specify a max date, because we need to stop *somewhere*. * * On 32 bit system the maximum for a signed integer is 2147483647, so * MAX_DATE cannot be higher than date('Y-m-d', 2147483647) which results @@ -27,54 +25,53 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { const MAX_DATE = '2038-01-01'; /** - * pdo + * pdo. * * @var PDO */ protected $pdo; /** - * The table name that will be used for calendars + * The table name that will be used for calendars. * * @var string */ protected $calendarTableName; /** - * The table name that will be used for calendar objects + * The table name that will be used for calendar objects. * * @var string */ protected $calendarObjectTableName; /** - * List of CalDAV properties, and how they map to database fieldnames + * List of CalDAV properties, and how they map to database fieldnames. * * Add your own properties by simply adding on to this array * * @var array */ public $propertyMap = array( - '{DAV:}displayname' => 'displayname', + '{DAV:}displayname' => 'displayname', '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description', - '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone', - '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder', - '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor', + '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone', + '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder', + '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor', ); /** - * Creates the backend + * Creates the backend. * - * @param PDO $pdo + * @param PDO $pdo * @param string $calendarTableName * @param string $calendarObjectTableName */ - public function __construct(PDO $pdo, $calendarTableName = 'calendars', $calendarObjectTableName = 'calendarobjects') { - + public function __construct(PDO $pdo, $calendarTableName = 'calendars', $calendarObjectTableName = 'calendarobjects') + { $this->pdo = $pdo; $this->calendarTableName = $calendarTableName; $this->calendarObjectTableName = $calendarObjectTableName; - } /** @@ -92,10 +89,11 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { * common one is '{DAV:}displayname'. * * @param string $principalUri + * * @return array */ - public function getCalendarsForUser($principalUri) { - + public function getCalendarsForUser($principalUri) + { $fields = array_values($this->propertyMap); $fields[] = 'id'; $fields[] = 'uri'; @@ -105,36 +103,32 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { // Making fields a comma-delimited list $fields = implode(', ', $fields); - $stmt = $this->pdo->prepare("SELECT " . $fields . " FROM ".$this->calendarTableName." WHERE principaluri = ? ORDER BY calendarorder ASC"); + $stmt = $this->pdo->prepare('SELECT '.$fields.' FROM '.$this->calendarTableName.' WHERE principaluri = ? ORDER BY calendarorder ASC'); $stmt->execute(array($principalUri)); $calendars = array(); - while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { - + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $components = array(); if ($row['components']) { - $components = explode(',',$row['components']); + $components = explode(',', $row['components']); } $calendar = array( 'id' => $row['id'], 'uri' => $row['uri'], 'principaluri' => $row['principaluri'], - '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $row['ctag']?$row['ctag']:'0', - '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components), + '{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER.'}getctag' => $row['ctag'] ? $row['ctag'] : '0', + '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components), ); - - foreach($this->propertyMap as $xmlName=>$dbName) { + foreach ($this->propertyMap as $xmlName => $dbName) { $calendar[$xmlName] = $row[$dbName]; } $calendars[] = $calendar; - } return $calendars; - } /** @@ -145,11 +139,12 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { * * @param string $principalUri * @param string $calendarUri - * @param array $properties + * @param array $properties + * * @return string */ - public function createCalendar($principalUri, $calendarUri, array $properties) { - + public function createCalendar($principalUri, $calendarUri, array $properties) + { $fieldNames = array( 'principaluri', 'uri', @@ -157,8 +152,8 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { ); $values = array( ':principaluri' => $principalUri, - ':uri' => $calendarUri, - ':ctag' => 1, + ':uri' => $calendarUri, + ':ctag' => 1, ); // Default value @@ -168,24 +163,22 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { $values[':components'] = 'VEVENT,VTODO'; } else { if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) { - throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet'); + throw new Sabre_DAV_Exception('The '.$sccs.' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet'); } - $values[':components'] = implode(',',$properties[$sccs]->getValue()); + $values[':components'] = implode(',', $properties[$sccs]->getValue()); } - foreach($this->propertyMap as $xmlName=>$dbName) { + foreach ($this->propertyMap as $xmlName => $dbName) { if (isset($properties[$xmlName])) { - - $values[':' . $dbName] = $properties[$xmlName]; + $values[':'.$dbName] = $properties[$xmlName]; $fieldNames[] = $dbName; } } - $stmt = $this->pdo->prepare("INSERT INTO ".$this->calendarTableName." (".implode(', ', $fieldNames).") VALUES (".implode(', ',array_keys($values)).")"); + $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarTableName.' ('.implode(', ', $fieldNames).') VALUES ('.implode(', ', array_keys($values)).')'); $stmt->execute($values); return $this->pdo->lastInsertId(); - } /** @@ -221,11 +214,12 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { * (424 Failed Dependency) because the request needs to be atomic. * * @param string $calendarId - * @param array $mutations + * @param array $mutations + * * @return bool|array */ - public function updateCalendar($calendarId, array $mutations) { - + public function updateCalendar($calendarId, array $mutations) + { $newValues = array(); $result = array( 200 => array(), // Ok @@ -235,7 +229,7 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { $hasError = false; - foreach($mutations as $propertyName=>$propertyValue) { + foreach ($mutations as $propertyName => $propertyValue) { // We don't know about this property. if (!isset($this->propertyMap[$propertyName])) { @@ -247,56 +241,53 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { $fieldName = $this->propertyMap[$propertyName]; $newValues[$fieldName] = $propertyValue; - } // If there were any errors we need to fail the request if ($hasError) { // Properties has the remaining properties - foreach($mutations as $propertyName=>$propertyValue) { + foreach ($mutations as $propertyName => $propertyValue) { $result[424][$propertyName] = null; } // Removing unused statuscodes for cleanliness - foreach($result as $status=>$properties) { - if (is_array($properties) && count($properties)===0) unset($result[$status]); + foreach ($result as $status => $properties) { + if (is_array($properties) && count($properties) === 0) { + unset($result[$status]); + } } return $result; - } // Success // Now we're generating the sql query. $valuesSql = array(); - foreach($newValues as $fieldName=>$value) { - $valuesSql[] = $fieldName . ' = ?'; + foreach ($newValues as $fieldName => $value) { + $valuesSql[] = $fieldName.' = ?'; } $valuesSql[] = 'ctag = ctag + 1'; - $stmt = $this->pdo->prepare("UPDATE " . $this->calendarTableName . " SET " . implode(', ',$valuesSql) . " WHERE id = ?"); + $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET '.implode(', ', $valuesSql).' WHERE id = ?'); $newValues['id'] = $calendarId; $stmt->execute(array_values($newValues)); return true; - } /** - * Delete a calendar and all it's objects + * Delete a calendar and all it's objects. * * @param string $calendarId - * @return void */ - public function deleteCalendar($calendarId) { - + public function deleteCalendar($calendarId) + { $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?'); $stmt->execute(array($calendarId)); $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarTableName.' WHERE id = ?'); $stmt->execute(array($calendarId)); - } /** @@ -324,27 +315,27 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { * amount of times this is needed is reduced by a great degree. * * @param string $calendarId + * * @return array */ - public function getCalendarObjects($calendarId) { - + public function getCalendarObjects($calendarId) + { $stmt = $this->pdo->prepare('SELECT id, uri, lastmodified, etag, calendarid, size FROM '.$this->calendarObjectTableName.' WHERE calendarid = ?'); $stmt->execute(array($calendarId)); $result = array(); - foreach($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { + foreach ($stmt->fetchAll(\PDO::FETCH_ASSOC) as $row) { $result[] = array( - 'id' => $row['id'], - 'uri' => $row['uri'], + 'id' => $row['id'], + 'uri' => $row['uri'], 'lastmodified' => $row['lastmodified'], - 'etag' => '"' . $row['etag'] . '"', - 'calendarid' => $row['calendarid'], - 'size' => (int)$row['size'], + 'etag' => '"'.$row['etag'].'"', + 'calendarid' => $row['calendarid'], + 'size' => (int) $row['size'], ); } return $result; - } /** @@ -357,29 +348,30 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { * * @param string $calendarId * @param string $objectUri + * * @return array */ - public function getCalendarObject($calendarId,$objectUri) { - + public function getCalendarObject($calendarId, $objectUri) + { $stmt = $this->pdo->prepare('SELECT id, uri, lastmodified, etag, calendarid, size, calendardata FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri = ?'); $stmt->execute(array($calendarId, $objectUri)); $row = $stmt->fetch(\PDO::FETCH_ASSOC); - if(!$row) return null; + if (!$row) { + return null; + } return array( - 'id' => $row['id'], - 'uri' => $row['uri'], + 'id' => $row['id'], + 'uri' => $row['uri'], 'lastmodified' => $row['lastmodified'], - 'etag' => '"' . $row['etag'] . '"', - 'calendarid' => $row['calendarid'], - 'size' => (int)$row['size'], + 'etag' => '"'.$row['etag'].'"', + 'calendarid' => $row['calendarid'], + 'size' => (int) $row['size'], 'calendardata' => $row['calendardata'], ); - } - /** * Creates a new calendar object. * @@ -391,13 +383,14 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { * calendar-data. If the result of a subsequent GET to this object is not * the exact same as this request body, you should omit the ETag. * - * @param mixed $calendarId + * @param mixed $calendarId * @param string $objectUri * @param string $calendarData + * * @return string|null */ - public function createCalendarObject($calendarId,$objectUri,$calendarData) { - + public function createCalendarObject($calendarId, $objectUri, $calendarData) + { $extraData = $this->getDenormalizedData($calendarData); $stmt = $this->pdo->prepare('INSERT INTO '.$this->calendarObjectTableName.' (calendarid, uri, calendardata, lastmodified, etag, size, componenttype, firstoccurence, lastoccurence) VALUES (?,?,?,?,?,?,?,?,?)'); @@ -415,8 +408,7 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET ctag = ctag + 1 WHERE id = ?'); $stmt->execute(array($calendarId)); - return '"' . $extraData['etag'] . '"'; - + return '"'.$extraData['etag'].'"'; } /** @@ -430,22 +422,22 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { * calendar-data. If the result of a subsequent GET to this object is not * the exact same as this request body, you should omit the ETag. * - * @param mixed $calendarId + * @param mixed $calendarId * @param string $objectUri * @param string $calendarData + * * @return string|null */ - public function updateCalendarObject($calendarId,$objectUri,$calendarData) { - + public function updateCalendarObject($calendarId, $objectUri, $calendarData) + { $extraData = $this->getDenormalizedData($calendarData); $stmt = $this->pdo->prepare('UPDATE '.$this->calendarObjectTableName.' SET calendardata = ?, lastmodified = ?, etag = ?, size = ?, componenttype = ?, firstoccurence = ?, lastoccurence = ? WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarData,time(), $extraData['etag'], $extraData['size'], $extraData['componentType'], $extraData['firstOccurence'], $extraData['lastOccurence'] ,$calendarId,$objectUri)); + $stmt->execute(array($calendarData, time(), $extraData['etag'], $extraData['size'], $extraData['componentType'], $extraData['firstOccurence'], $extraData['lastOccurence'], $calendarId, $objectUri)); $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET ctag = ctag + 1 WHERE id = ?'); $stmt->execute(array($calendarId)); - return '"' . $extraData['etag'] . '"'; - + return '"'.$extraData['etag'].'"'; } /** @@ -460,17 +452,18 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { * * lastOccurence * * @param string $calendarData + * * @return array */ - protected function getDenormalizedData($calendarData) { - + protected function getDenormalizedData($calendarData) + { $vObject = VObject\Reader::read($calendarData); $componentType = null; $component = null; $firstOccurence = null; $lastOccurence = null; - foreach($vObject->getComponents() as $component) { - if ($component->name!=='VTIMEZONE') { + foreach ($vObject->getComponents() as $component) { + if ($component->name !== 'VTIMEZONE') { $componentType = $component->name; break; } @@ -488,7 +481,7 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { $endDate = clone $component->DTSTART->getDateTime(); $endDate->add(VObject\DateTimeParser::parse($component->DURATION->value)); $lastOccurence = $endDate->getTimeStamp(); - } elseif ($component->DTSTART->getDateType()===VObject\Property\DateTime::DATE) { + } elseif ($component->DTSTART->getDateType() === VObject\Property\DateTime::DATE) { $endDate = clone $component->DTSTART->getDateTime(); $endDate->modify('+1 day'); $lastOccurence = $endDate->getTimeStamp(); @@ -496,20 +489,18 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { $lastOccurence = $firstOccurence; } } else { - $it = new VObject\RecurrenceIterator($vObject, (string)$component->UID); + $it = new VObject\RecurrenceIterator($vObject, (string) $component->UID); $maxDate = new DateTime(self::MAX_DATE); if ($it->isInfinite()) { $lastOccurence = $maxDate->getTimeStamp(); } else { $end = $it->getDtEnd(); - while($it->valid() && $end < $maxDate) { + while ($it->valid() && $end < $maxDate) { $end = $it->getDtEnd(); $it->next(); - } $lastOccurence = $end->getTimeStamp(); } - } } @@ -518,9 +509,8 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { 'size' => strlen($calendarData), 'componentType' => $componentType, 'firstOccurence' => $firstOccurence, - 'lastOccurence' => $lastOccurence, + 'lastOccurence' => $lastOccurence, ); - } /** @@ -528,15 +518,13 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { * * @param string $calendarId * @param string $objectUri - * @return void */ - public function deleteCalendarObject($calendarId,$objectUri) { - + public function deleteCalendarObject($calendarId, $objectUri) + { $stmt = $this->pdo->prepare('DELETE FROM '.$this->calendarObjectTableName.' WHERE calendarid = ? AND uri = ?'); - $stmt->execute(array($calendarId,$objectUri)); - $stmt = $this->pdo->prepare('UPDATE '. $this->calendarTableName .' SET ctag = ctag + 1 WHERE id = ?'); + $stmt->execute(array($calendarId, $objectUri)); + $stmt = $this->pdo->prepare('UPDATE '.$this->calendarTableName.' SET ctag = ctag + 1 WHERE id = ?'); $stmt->execute(array($calendarId)); - } /** @@ -588,11 +576,12 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { * specific components, and VEVENT time-ranges. * * @param string $calendarId - * @param array $filters + * @param array $filters + * * @return array */ - public function calendarQuery($calendarId, array $filters) { - + public function calendarQuery($calendarId, array $filters) + { $result = array(); $validator = new Sabre_CalDAV_CalendarQueryValidator(); @@ -617,13 +606,12 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { if ($componentType == 'VEVENT' && isset($filters['comp-filters'][0]['time-range'])) { $timeRange = $filters['comp-filters'][0]['time-range']; } - } if ($requirePostFilter) { - $query = "SELECT uri, calendardata FROM ".$this->calendarObjectTableName." WHERE calendarid = :calendarid"; + $query = 'SELECT uri, calendardata FROM '.$this->calendarObjectTableName.' WHERE calendarid = :calendarid'; } else { - $query = "SELECT uri FROM ".$this->calendarObjectTableName." WHERE calendarid = :calendarid"; + $query = 'SELECT uri FROM '.$this->calendarObjectTableName.' WHERE calendarid = :calendarid'; } $values = array( @@ -631,16 +619,16 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { ); if ($componentType) { - $query.=" AND componenttype = :componenttype"; + $query .= ' AND componenttype = :componenttype'; $values['componenttype'] = $componentType; } if ($timeRange && $timeRange['start']) { - $query.=" AND lastoccurence > :startdate"; + $query .= ' AND lastoccurence > :startdate'; $values['startdate'] = $timeRange['start']->getTimeStamp(); } if ($timeRange && $timeRange['end']) { - $query.=" AND firstoccurence < :enddate"; + $query .= ' AND firstoccurence < :enddate'; $values['enddate'] = $timeRange['end']->getTimeStamp(); } @@ -648,17 +636,15 @@ class Sabre_CalDAV_Backend_PDO extends Sabre_CalDAV_Backend_Abstract { $stmt->execute($values); $result = array(); - while($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { if ($requirePostFilter) { if (!$this->validateFilterForObject($row, $filters)) { continue; } } $result[] = $row['uri']; - } return $result; - } } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Calendar.php b/dav/SabreDAV/lib/Sabre/CalDAV/Calendar.php index bff1b41e..5a3d59ab 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Calendar.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Calendar.php @@ -6,193 +6,193 @@ * A calendar can contain multiple TODO and or Events. These are represented * as Sabre_CalDAV_CalendarObject objects. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_Calendar implements Sabre_CalDAV_ICalendar, Sabre_DAV_IProperties, Sabre_DAVACL_IACL { - +class Sabre_CalDAV_Calendar implements Sabre_CalDAV_ICalendar, Sabre_DAV_IProperties, Sabre_DAVACL_IACL +{ /** - * This is an array with calendar information + * This is an array with calendar information. * * @var array */ protected $calendarInfo; /** - * CalDAV backend + * CalDAV backend. * * @var Sabre_CalDAV_Backend_BackendInterface */ protected $caldavBackend; /** - * Principal backend + * Principal backend. * * @var Sabre_DAVACL_IPrincipalBackend */ protected $principalBackend; /** - * Constructor + * Constructor. * - * @param Sabre_DAVACL_IPrincipalBackend $principalBackend + * @param Sabre_DAVACL_IPrincipalBackend $principalBackend * @param Sabre_CalDAV_Backend_BackendInterface $caldavBackend - * @param array $calendarInfo + * @param array $calendarInfo */ - public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend, Sabre_CalDAV_Backend_BackendInterface $caldavBackend, $calendarInfo) { - + public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend, Sabre_CalDAV_Backend_BackendInterface $caldavBackend, $calendarInfo) + { $this->caldavBackend = $caldavBackend; $this->principalBackend = $principalBackend; $this->calendarInfo = $calendarInfo; - - } /** - * Returns the name of the calendar + * Returns the name of the calendar. * * @return string */ - public function getName() { - + public function getName() + { return $this->calendarInfo['uri']; - } /** - * Updates properties such as the display name and description + * Updates properties such as the display name and description. * * @param array $mutations + * * @return array */ - public function updateProperties($mutations) { - - return $this->caldavBackend->updateCalendar($this->calendarInfo['id'],$mutations); - + public function updateProperties($mutations) + { + return $this->caldavBackend->updateCalendar($this->calendarInfo['id'], $mutations); } /** - * Returns the list of properties + * Returns the list of properties. * * @param array $requestedProperties + * * @return array */ - public function getProperties($requestedProperties) { - + public function getProperties($requestedProperties) + { $response = array(); - foreach($requestedProperties as $prop) switch($prop) { + foreach ($requestedProperties as $prop) { + switch ($prop) { - case '{urn:ietf:params:xml:ns:caldav}supported-calendar-data' : + case '{urn:ietf:params:xml:ns:caldav}supported-calendar-data': $response[$prop] = new Sabre_CalDAV_Property_SupportedCalendarData(); break; - case '{urn:ietf:params:xml:ns:caldav}supported-collation-set' : - $response[$prop] = new Sabre_CalDAV_Property_SupportedCollationSet(); + case '{urn:ietf:params:xml:ns:caldav}supported-collation-set': + $response[$prop] = new Sabre_CalDAV_Property_SupportedCollationSet(); break; - case '{DAV:}owner' : - $response[$prop] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF,$this->calendarInfo['principaluri']); + case '{DAV:}owner': + $response[$prop] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF, $this->calendarInfo['principaluri']); break; - default : - if (isset($this->calendarInfo[$prop])) $response[$prop] = $this->calendarInfo[$prop]; + default: + if (isset($this->calendarInfo[$prop])) { + $response[$prop] = $this->calendarInfo[$prop]; + } break; } - return $response; + } + return $response; } /** - * Returns a calendar object + * Returns a calendar object. * * The contained calendar objects are for example Events or Todo's. * * @param string $name + * * @return Sabre_CalDAV_ICalendarObject */ - public function getChild($name) { - - $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'],$name); - if (!$obj) throw new Sabre_DAV_Exception_NotFound('Calendar object not found'); - return new Sabre_CalDAV_CalendarObject($this->caldavBackend,$this->calendarInfo,$obj); + public function getChild($name) + { + $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name); + if (!$obj) { + throw new Sabre_DAV_Exception_NotFound('Calendar object not found'); + } + return new Sabre_CalDAV_CalendarObject($this->caldavBackend, $this->calendarInfo, $obj); } /** - * Returns the full list of calendar objects + * Returns the full list of calendar objects. * * @return array */ - public function getChildren() { - + public function getChildren() + { $objs = $this->caldavBackend->getCalendarObjects($this->calendarInfo['id']); $children = array(); - foreach($objs as $obj) { - $children[] = new Sabre_CalDAV_CalendarObject($this->caldavBackend,$this->calendarInfo,$obj); + foreach ($objs as $obj) { + $children[] = new Sabre_CalDAV_CalendarObject($this->caldavBackend, $this->calendarInfo, $obj); } - return $children; + return $children; } /** * Checks if a child-node exists. * * @param string $name + * * @return bool */ - public function childExists($name) { - - $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'],$name); - if (!$obj) + public function childExists($name) + { + $obj = $this->caldavBackend->getCalendarObject($this->calendarInfo['id'], $name); + if (!$obj) { return false; - else + } else { return true; - + } } /** - * Creates a new directory + * Creates a new directory. * * We actually block this, as subdirectories are not allowed in calendars. * * @param string $name - * @return void */ - public function createDirectory($name) { - + public function createDirectory($name) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Creating collections in calendar objects is not allowed'); - } /** - * Creates a new file + * Creates a new file. * * The contents of the new file must be a valid ICalendar string. * - * @param string $name + * @param string $name * @param resource $calendarData + * * @return string|null */ - public function createFile($name,$calendarData = null) { - + public function createFile($name, $calendarData = null) + { if (is_resource($calendarData)) { $calendarData = stream_get_contents($calendarData); } - return $this->caldavBackend->createCalendarObject($this->calendarInfo['id'],$name,$calendarData); + return $this->caldavBackend->createCalendarObject($this->calendarInfo['id'], $name, $calendarData); } /** * Deletes the calendar. - * - * @return void */ - public function delete() { - + public function delete() + { $this->caldavBackend->deleteCalendar($this->calendarInfo['id']); - } /** @@ -200,49 +200,42 @@ class Sabre_CalDAV_Calendar implements Sabre_CalDAV_ICalendar, Sabre_DAV_IProper * {DAV:}displayname to display a name to display a name. * * @param string $newName - * @return void */ - public function setName($newName) { - + public function setName($newName) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Renaming calendars is not yet supported'); - } /** * Returns the last modification date as a unix timestamp. - * - * @return void */ - public function getLastModified() { - + public function getLastModified() + { return null; - } /** - * Returns the owner principal + * Returns the owner principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getOwner() { - + public function getOwner() + { return $this->calendarInfo['principaluri']; - } /** - * Returns a group principal + * Returns a group principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getGroup() { - + public function getGroup() + { return null; - } /** @@ -257,8 +250,8 @@ class Sabre_CalDAV_Calendar implements Sabre_CalDAV_ICalendar, Sabre_DAV_IProper * * @return array */ - public function getACL() { - + public function getACL() + { return array( array( 'privilege' => '{DAV:}read', @@ -272,41 +265,38 @@ class Sabre_CalDAV_Calendar implements Sabre_CalDAV_ICalendar, Sabre_DAV_IProper ), array( 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', + 'principal' => $this->calendarInfo['principaluri'].'/calendar-proxy-write', 'protected' => true, ), array( 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', + 'principal' => $this->calendarInfo['principaluri'].'/calendar-proxy-write', 'protected' => true, ), array( 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', + 'principal' => $this->calendarInfo['principaluri'].'/calendar-proxy-read', 'protected' => true, ), array( - 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy', + 'privilege' => '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}read-free-busy', 'principal' => '{DAV:}authenticated', 'protected' => true, ), ); - } /** - * Updates the ACL + * Updates the ACL. * * This method will receive a list of new ACE's. * * @param array $acl - * @return void */ - public function setACL(array $acl) { - + public function setACL(array $acl) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - } /** @@ -321,23 +311,23 @@ class Sabre_CalDAV_Calendar implements Sabre_CalDAV_ICalendar, Sabre_DAV_IProper * * @return array|null */ - public function getSupportedPrivilegeSet() { - + public function getSupportedPrivilegeSet() + { $default = Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet(); // We need to inject 'read-free-busy' in the tree, aggregated under // {DAV:}read. - foreach($default['aggregates'] as &$agg) { - - if ($agg['privilege'] !== '{DAV:}read') continue; + foreach ($default['aggregates'] as &$agg) { + if ($agg['privilege'] !== '{DAV:}read') { + continue; + } $agg['aggregates'][] = array( - 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy', + 'privilege' => '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}read-free-busy', ); - } - return $default; + return $default; } /** @@ -355,12 +345,11 @@ class Sabre_CalDAV_Calendar implements Sabre_CalDAV_ICalendar, Sabre_DAV_IProper * documented by Sabre_CalDAV_CalendarQueryParser. * * @param array $filters + * * @return array */ - public function calendarQuery(array $filters) { - + public function calendarQuery(array $filters) + { return $this->caldavBackend->calendarQuery($this->calendarInfo['id'], $filters); - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/CalendarObject.php b/dav/SabreDAV/lib/Sabre/CalDAV/CalendarObject.php index 318a4fb5..bcde11e3 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/CalendarObject.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/CalendarObject.php @@ -3,44 +3,42 @@ /** * The CalendarObject represents a single VEVENT or VTODO within a Calendar. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_CalendarObject extends Sabre_DAV_File implements Sabre_CalDAV_ICalendarObject, Sabre_DAVACL_IACL { - +class Sabre_CalDAV_CalendarObject extends Sabre_DAV_File implements Sabre_CalDAV_ICalendarObject, Sabre_DAVACL_IACL +{ /** - * Sabre_CalDAV_Backend_BackendInterface + * Sabre_CalDAV_Backend_BackendInterface. * * @var array */ protected $caldavBackend; /** - * Array with information about this CalendarObject + * Array with information about this CalendarObject. * * @var array */ protected $objectData; /** - * Array with information about the containing calendar + * Array with information about the containing calendar. * * @var array */ protected $calendarInfo; /** - * Constructor + * Constructor. * * @param Sabre_CalDAV_Backend_BackendInterface $caldavBackend - * @param array $calendarInfo - * @param array $objectData + * @param array $calendarInfo + * @param array $objectData */ - public function __construct(Sabre_CalDAV_Backend_BackendInterface $caldavBackend,array $calendarInfo,array $objectData) { - + public function __construct(Sabre_CalDAV_Backend_BackendInterface $caldavBackend, array $calendarInfo, array $objectData) + { $this->caldavBackend = $caldavBackend; if (!isset($objectData['calendarid'])) { @@ -52,75 +50,70 @@ class Sabre_CalDAV_CalendarObject extends Sabre_DAV_File implements Sabre_CalDAV $this->calendarInfo = $calendarInfo; $this->objectData = $objectData; - } /** - * Returns the uri for this object + * Returns the uri for this object. * * @return string */ - public function getName() { - + public function getName() + { return $this->objectData['uri']; - } /** - * Returns the ICalendar-formatted object + * Returns the ICalendar-formatted object. * * @return string */ - public function get() { + public function get() + { // Pre-populating the 'calendardata' is optional, if we don't have it // already we fetch it from the backend. if (!isset($this->objectData['calendardata'])) { $this->objectData = $this->caldavBackend->getCalendarObject($this->objectData['calendarid'], $this->objectData['uri']); } - return $this->objectData['calendardata']; + return $this->objectData['calendardata']; } /** - * Updates the ICalendar-formatted object + * Updates the ICalendar-formatted object. * * @param string|resource $calendarData + * * @return string */ - public function put($calendarData) { - + public function put($calendarData) + { if (is_resource($calendarData)) { $calendarData = stream_get_contents($calendarData); } - $etag = $this->caldavBackend->updateCalendarObject($this->calendarInfo['id'],$this->objectData['uri'],$calendarData); + $etag = $this->caldavBackend->updateCalendarObject($this->calendarInfo['id'], $this->objectData['uri'], $calendarData); $this->objectData['calendardata'] = $calendarData; $this->objectData['etag'] = $etag; return $etag; - } /** - * Deletes the calendar object - * - * @return void + * Deletes the calendar object. */ - public function delete() { - - $this->caldavBackend->deleteCalendarObject($this->calendarInfo['id'],$this->objectData['uri']); - + public function delete() + { + $this->caldavBackend->deleteCalendarObject($this->calendarInfo['id'], $this->objectData['uri']); } /** - * Returns the mime content-type + * Returns the mime content-type. * * @return string */ - public function getContentType() { - + public function getContentType() + { return 'text/calendar; charset=utf-8'; - } /** @@ -130,66 +123,61 @@ class Sabre_CalDAV_CalendarObject extends Sabre_DAV_File implements Sabre_CalDAV * * @return string */ - public function getETag() { - + public function getETag() + { if (isset($this->objectData['etag'])) { return $this->objectData['etag']; } else { - return '"' . md5($this->get()). '"'; + return '"'.md5($this->get()).'"'; } - } /** - * Returns the last modification date as a unix timestamp + * Returns the last modification date as a unix timestamp. * * @return int */ - public function getLastModified() { - + public function getLastModified() + { return $this->objectData['lastmodified']; - } /** - * Returns the size of this object in bytes + * Returns the size of this object in bytes. * * @return int */ - public function getSize() { - - if (array_key_exists('size',$this->objectData)) { + public function getSize() + { + if (array_key_exists('size', $this->objectData)) { return $this->objectData['size']; } else { return strlen($this->get()); } - } /** - * Returns the owner principal + * Returns the owner principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getOwner() { - + public function getOwner() + { return $this->calendarInfo['principaluri']; - } /** - * Returns a group principal + * Returns a group principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getGroup() { - + public function getGroup() + { return null; - } /** @@ -204,8 +192,8 @@ class Sabre_CalDAV_CalendarObject extends Sabre_DAV_File implements Sabre_CalDAV * * @return array */ - public function getACL() { - + public function getACL() + { return array( array( 'privilege' => '{DAV:}read', @@ -219,36 +207,33 @@ class Sabre_CalDAV_CalendarObject extends Sabre_DAV_File implements Sabre_CalDAV ), array( 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', + 'principal' => $this->calendarInfo['principaluri'].'/calendar-proxy-write', 'protected' => true, ), array( 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', + 'principal' => $this->calendarInfo['principaluri'].'/calendar-proxy-write', 'protected' => true, ), array( 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', + 'principal' => $this->calendarInfo['principaluri'].'/calendar-proxy-read', 'protected' => true, ), ); - } /** - * Updates the ACL + * Updates the ACL. * * This method will receive a list of new ACE's. * * @param array $acl - * @return void */ - public function setACL(array $acl) { - + public function setACL(array $acl) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - } /** @@ -263,11 +248,8 @@ class Sabre_CalDAV_CalendarObject extends Sabre_DAV_File implements Sabre_CalDAV * * @return array|null */ - public function getSupportedPrivilegeSet() { - + public function getSupportedPrivilegeSet() + { return null; - } - } - diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/CalendarQueryParser.php b/dav/SabreDAV/lib/Sabre/CalDAV/CalendarQueryParser.php index b95095f9..1800a670 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/CalendarQueryParser.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/CalendarQueryParser.php @@ -8,16 +8,14 @@ use Sabre\VObject; * Whoever designed this format, and the CalDAV equivalent even more so, * has no feel for design. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_CalendarQueryParser { - +class Sabre_CalDAV_CalendarQueryParser +{ /** - * List of requested properties the client wanted + * List of requested properties the client wanted. * * @var array */ @@ -31,56 +29,53 @@ class Sabre_CalDAV_CalendarQueryParser { public $filters; /** - * This property will contain null if CALDAV:expand was not specified, - * otherwise it will contain an array with 2 elements (start, end). Each + * This property will contain null if CALDAV:expand was not specified, + * otherwise it will contain an array with 2 elements (start, end). Each * contain a DateTime object. * - * If expand is specified, recurring calendar objects are to be expanded - * into their individual components, and only the components that fall + * If expand is specified, recurring calendar objects are to be expanded + * into their individual components, and only the components that fall * within the specified time-range are to be returned. * * For more details, see rfc4791, section 9.6.5. - * - * @var null|array + * + * @var null|array */ public $expand; /** - * DOM Document + * DOM Document. * * @var DOMDocument */ protected $dom; /** - * DOM XPath object + * DOM XPath object. * * @var DOMXPath */ protected $xpath; /** - * Creates the parser + * Creates the parser. * * @param DOMDocument $dom */ - public function __construct(DOMDocument $dom) { - + public function __construct(DOMDocument $dom) + { $this->dom = $dom; $this->xpath = new DOMXPath($dom); - $this->xpath->registerNameSpace('cal',Sabre_CalDAV_Plugin::NS_CALDAV); - $this->xpath->registerNameSpace('dav','DAV:'); - + $this->xpath->registerNameSpace('cal', Sabre_CalDAV_Plugin::NS_CALDAV); + $this->xpath->registerNameSpace('dav', 'DAV:'); } /** * Parses the request. - * - * @return void */ - public function parse() { - + public function parse() + { $filterNode = null; $filter = $this->xpath->query('/cal:calendar-query/cal:filter'); @@ -89,7 +84,7 @@ class Sabre_CalDAV_CalendarQueryParser { } $compFilters = $this->parseCompFilters($filter->item(0)); - if (count($compFilters)!==1) { + if (count($compFilters) !== 1) { throw new Sabre_DAV_Exception_BadRequest('There must be exactly 1 top-level comp-filter.'); } @@ -97,144 +92,140 @@ class Sabre_CalDAV_CalendarQueryParser { $this->requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($this->dom->firstChild)); $expand = $this->xpath->query('/cal:calendar-query/dav:prop/cal:calendar-data/cal:expand'); - if ($expand->length>0) { + if ($expand->length > 0) { $this->expand = $this->parseExpand($expand->item(0)); } - - } /** - * Parses all the 'comp-filter' elements from a node + * Parses all the 'comp-filter' elements from a node. * * @param DOMElement $parentNode + * * @return array */ - protected function parseCompFilters(DOMElement $parentNode) { - + protected function parseCompFilters(DOMElement $parentNode) + { $compFilterNodes = $this->xpath->query('cal:comp-filter', $parentNode); $result = array(); - for($ii=0; $ii < $compFilterNodes->length; $ii++) { - + for ($ii = 0; $ii < $compFilterNodes->length; ++$ii) { $compFilterNode = $compFilterNodes->item($ii); $compFilter = array(); $compFilter['name'] = $compFilterNode->getAttribute('name'); - $compFilter['is-not-defined'] = $this->xpath->query('cal:is-not-defined', $compFilterNode)->length>0; + $compFilter['is-not-defined'] = $this->xpath->query('cal:is-not-defined', $compFilterNode)->length > 0; $compFilter['comp-filters'] = $this->parseCompFilters($compFilterNode); $compFilter['prop-filters'] = $this->parsePropFilters($compFilterNode); $compFilter['time-range'] = $this->parseTimeRange($compFilterNode); - if ($compFilter['time-range'] && !in_array($compFilter['name'],array( + if ($compFilter['time-range'] && !in_array($compFilter['name'], array( 'VEVENT', 'VTODO', 'VJOURNAL', 'VFREEBUSY', 'VALARM', ))) { - throw new Sabre_DAV_Exception_BadRequest('The time-range filter is not defined for the ' . $compFilter['name'] . ' component'); - }; + throw new Sabre_DAV_Exception_BadRequest('The time-range filter is not defined for the '.$compFilter['name'].' component'); + } $result[] = $compFilter; - } return $result; - } /** - * Parses all the prop-filter elements from a node + * Parses all the prop-filter elements from a node. * * @param DOMElement $parentNode + * * @return array */ - protected function parsePropFilters(DOMElement $parentNode) { - + protected function parsePropFilters(DOMElement $parentNode) + { $propFilterNodes = $this->xpath->query('cal:prop-filter', $parentNode); $result = array(); - for ($ii=0; $ii < $propFilterNodes->length; $ii++) { - + for ($ii = 0; $ii < $propFilterNodes->length; ++$ii) { $propFilterNode = $propFilterNodes->item($ii); $propFilter = array(); $propFilter['name'] = $propFilterNode->getAttribute('name'); - $propFilter['is-not-defined'] = $this->xpath->query('cal:is-not-defined', $propFilterNode)->length>0; + $propFilter['is-not-defined'] = $this->xpath->query('cal:is-not-defined', $propFilterNode)->length > 0; $propFilter['param-filters'] = $this->parseParamFilters($propFilterNode); $propFilter['text-match'] = $this->parseTextMatch($propFilterNode); $propFilter['time-range'] = $this->parseTimeRange($propFilterNode); $result[] = $propFilter; - } return $result; - } /** - * Parses the param-filter element + * Parses the param-filter element. * * @param DOMElement $parentNode + * * @return array */ - protected function parseParamFilters(DOMElement $parentNode) { - + protected function parseParamFilters(DOMElement $parentNode) + { $paramFilterNodes = $this->xpath->query('cal:param-filter', $parentNode); $result = array(); - for($ii=0;$ii<$paramFilterNodes->length;$ii++) { - + for ($ii = 0; $ii < $paramFilterNodes->length; ++$ii) { $paramFilterNode = $paramFilterNodes->item($ii); $paramFilter = array(); $paramFilter['name'] = $paramFilterNode->getAttribute('name'); - $paramFilter['is-not-defined'] = $this->xpath->query('cal:is-not-defined', $paramFilterNode)->length>0; + $paramFilter['is-not-defined'] = $this->xpath->query('cal:is-not-defined', $paramFilterNode)->length > 0; $paramFilter['text-match'] = $this->parseTextMatch($paramFilterNode); $result[] = $paramFilter; - } return $result; - } /** - * Parses the text-match element + * Parses the text-match element. * * @param DOMElement $parentNode + * * @return array|null */ - protected function parseTextMatch(DOMElement $parentNode) { - + protected function parseTextMatch(DOMElement $parentNode) + { $textMatchNodes = $this->xpath->query('cal:text-match', $parentNode); - if ($textMatchNodes->length === 0) + if ($textMatchNodes->length === 0) { return null; + } $textMatchNode = $textMatchNodes->item(0); $negateCondition = $textMatchNode->getAttribute('negate-condition'); - $negateCondition = $negateCondition==='yes'; + $negateCondition = $negateCondition === 'yes'; $collation = $textMatchNode->getAttribute('collation'); - if (!$collation) $collation = 'i;ascii-casemap'; + if (!$collation) { + $collation = 'i;ascii-casemap'; + } return array( 'negate-condition' => $negateCondition, 'collation' => $collation, - 'value' => $textMatchNode->nodeValue + 'value' => $textMatchNode->nodeValue, ); - } /** - * Parses the time-range element + * Parses the time-range element. * * @param DOMElement $parentNode + * * @return array|null */ - protected function parseTimeRange(DOMElement $parentNode) { - + protected function parseTimeRange(DOMElement $parentNode) + { $timeRangeNodes = $this->xpath->query('cal:time-range', $parentNode); if ($timeRangeNodes->length === 0) { return null; @@ -261,29 +252,27 @@ class Sabre_CalDAV_CalendarQueryParser { 'start' => $start, 'end' => $end, ); - } /** - * Parses the CALDAV:expand element - * - * @param DOMElement $parentNode - * @return void + * Parses the CALDAV:expand element. + * + * @param DOMElement $parentNode */ - protected function parseExpand(DOMElement $parentNode) { - + protected function parseExpand(DOMElement $parentNode) + { $start = $parentNode->getAttribute('start'); - if(!$start) { + if (!$start) { throw new Sabre_DAV_Exception_BadRequest('The "start" attribute is required for the CALDAV:expand element'); - } + } $start = VObject\DateTimeParser::parseDateTime($start); $end = $parentNode->getAttribute('end'); - if(!$end) { + if (!$end) { throw new Sabre_DAV_Exception_BadRequest('The "end" attribute is required for the CALDAV:expand element'); - } + } $end = VObject\DateTimeParser::parseDateTime($end); - + if ($end <= $start) { throw new Sabre_DAV_Exception_BadRequest('The end-date must be larger than the start-date in the expand element.'); } @@ -292,7 +281,5 @@ class Sabre_CalDAV_CalendarQueryParser { 'start' => $start, 'end' => $end, ); - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/CalendarQueryValidator.php b/dav/SabreDAV/lib/Sabre/CalDAV/CalendarQueryValidator.php index 53e86fc5..1c851924 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/CalendarQueryValidator.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/CalendarQueryValidator.php @@ -3,7 +3,7 @@ use Sabre\VObject; /** - * CalendarQuery Validator + * CalendarQuery Validator. * * This class is responsible for checking if an iCalendar object matches a set * of filters. The main function to do this is 'validate'. @@ -11,24 +11,24 @@ use Sabre\VObject; * This is used to determine which icalendar objects should be returned for a * calendar-query REPORT request. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_CalendarQueryValidator { - +class Sabre_CalDAV_CalendarQueryValidator +{ /** - * Verify if a list of filters applies to the calendar data object + * Verify if a list of filters applies to the calendar data object. * * The list of filters must be formatted as parsed by Sabre_CalDAV_CalendarQueryParser * * @param VObject\Component $vObject - * @param array $filters + * @param array $filters + * * @return bool */ - public function validate(VObject\Component $vObject,array $filters) { + public function validate(VObject\Component $vObject, array $filters) + { // The top level object is always a component filter. // We'll parse it manually, as it's pretty simple. @@ -39,8 +39,6 @@ class Sabre_CalDAV_CalendarQueryValidator { return $this->validateCompFilters($vObject, $filters['comp-filters']) && $this->validatePropFilters($vObject, $filters['prop-filters']); - - } /** @@ -51,34 +49,33 @@ class Sabre_CalDAV_CalendarQueryValidator { * itself. * * @param VObject\Component $parent - * @param array $filters + * @param array $filters + * * @return bool */ - protected function validateCompFilters(VObject\Component $parent, array $filters) { - - foreach($filters as $filter) { - + protected function validateCompFilters(VObject\Component $parent, array $filters) + { + foreach ($filters as $filter) { $isDefined = isset($parent->$filter['name']); if ($filter['is-not-defined']) { - if ($isDefined) { return false; } else { continue; } - } if (!$isDefined) { return false; } if ($filter['time-range']) { - foreach($parent->$filter['name'] as $subComponent) { + foreach ($parent->$filter['name'] as $subComponent) { if ($this->validateTimeRange($subComponent, $filter['time-range']['start'], $filter['time-range']['end'])) { continue 2; } } + return false; } @@ -88,28 +85,24 @@ class Sabre_CalDAV_CalendarQueryValidator { // If there are sub-filters, we need to find at least one component // for which the subfilters hold true. - foreach($parent->$filter['name'] as $subComponent) { - + foreach ($parent->$filter['name'] as $subComponent) { if ( $this->validateCompFilters($subComponent, $filter['comp-filters']) && $this->validatePropFilters($subComponent, $filter['prop-filters'])) { - // We had a match, so this comp-filter succeeds + // We had a match, so this comp-filter succeeds continue 2; } - } // If we got here it means there were sub-comp-filters or // sub-prop-filters and there was no match. This means this filter // needs to return false. return false; - } // If we got here it means we got through all comp-filters alive so the // filters were all true. return true; - } /** @@ -120,34 +113,33 @@ class Sabre_CalDAV_CalendarQueryValidator { * itself. * * @param VObject\Component $parent - * @param array $filters + * @param array $filters + * * @return bool */ - protected function validatePropFilters(VObject\Component $parent, array $filters) { - - foreach($filters as $filter) { - + protected function validatePropFilters(VObject\Component $parent, array $filters) + { + foreach ($filters as $filter) { $isDefined = isset($parent->$filter['name']); if ($filter['is-not-defined']) { - if ($isDefined) { return false; } else { continue; } - } if (!$isDefined) { return false; } if ($filter['time-range']) { - foreach($parent->$filter['name'] as $subComponent) { + foreach ($parent->$filter['name'] as $subComponent) { if ($this->validateTimeRange($subComponent, $filter['time-range']['start'], $filter['time-range']['end'])) { continue 2; } } + return false; } @@ -157,29 +149,25 @@ class Sabre_CalDAV_CalendarQueryValidator { // If there are sub-filters, we need to find at least one property // for which the subfilters hold true. - foreach($parent->$filter['name'] as $subComponent) { - - if( + foreach ($parent->$filter['name'] as $subComponent) { + if ( $this->validateParamFilters($subComponent, $filter['param-filters']) && (!$filter['text-match'] || $this->validateTextMatch($subComponent, $filter['text-match'])) ) { // We had a match, so this prop-filter succeeds continue 2; } - } // If we got here it means there were sub-param-filters or // text-match filters and there was no match. This means the // filter needs to return false. return false; - } // If we got here it means we got through all prop-filters alive so the // filters were all true. return true; - } /** @@ -190,23 +178,21 @@ class Sabre_CalDAV_CalendarQueryValidator { * itself. * * @param VObject\Property $parent - * @param array $filters + * @param array $filters + * * @return bool */ - protected function validateParamFilters(VObject\Property $parent, array $filters) { - - foreach($filters as $filter) { - + protected function validateParamFilters(VObject\Property $parent, array $filters) + { + foreach ($filters as $filter) { $isDefined = isset($parent[$filter['name']]); if ($filter['is-not-defined']) { - if ($isDefined) { return false; } else { continue; } - } if (!$isDefined) { return false; @@ -218,25 +204,21 @@ class Sabre_CalDAV_CalendarQueryValidator { // If there are sub-filters, we need to find at least one parameter // for which the subfilters hold true. - foreach($parent[$filter['name']] as $subParam) { - - if($this->validateTextMatch($subParam,$filter['text-match'])) { + foreach ($parent[$filter['name']] as $subParam) { + if ($this->validateTextMatch($subParam, $filter['text-match'])) { // We had a match, so this param-filter succeeds continue 2; } - } // If we got here it means there was a text-match filter and there // were no matches. This means the filter needs to return false. return false; - } // If we got here it means we got through all param-filters alive so the // filters were all true. return true; - } /** @@ -246,17 +228,17 @@ class Sabre_CalDAV_CalendarQueryValidator { * or parameter we need to validate. * * @param VObject\Node $parent - * @param array $textMatch + * @param array $textMatch + * * @return bool */ - protected function validateTextMatch(VObject\Node $parent, array $textMatch) { - - $value = (string)$parent; + protected function validateTextMatch(VObject\Node $parent, array $textMatch) + { + $value = (string) $parent; $isMatching = Sabre_DAV_StringUtil::textMatch($value, $textMatch['value'], $textMatch['collation']); - return ($textMatch['negate-condition'] xor $isMatching); - + return $textMatch['negate-condition'] xor $isMatching; } /** @@ -266,12 +248,13 @@ class Sabre_CalDAV_CalendarQueryValidator { * complex. * * @param VObject\Node $component - * @param DateTime $start - * @param DateTime $end + * @param DateTime $start + * @param DateTime $end + * * @return bool */ - protected function validateTimeRange(VObject\Node $component, $start, $end) { - + protected function validateTimeRange(VObject\Node $component, $start, $end) + { if (is_null($start)) { $start = new DateTime('1900-01-01'); } @@ -279,27 +262,27 @@ class Sabre_CalDAV_CalendarQueryValidator { $end = new DateTime('3000-01-01'); } - switch($component->name) { + switch ($component->name) { - case 'VEVENT' : - case 'VTODO' : - case 'VJOURNAL' : + case 'VEVENT': + case 'VTODO': + case 'VJOURNAL': return $component->isInTimeRange($start, $end); - case 'VALARM' : + case 'VALARM': // If the valarm is wrapped in a recurring event, we need to // expand the recursions, and validate each. - // + // Our datamodel doesn't easily allow us to do this straight // in the VALARM component code, so this is a hack, and an // expensive one too. if ($component->parent->name === 'VEVENT' && $component->parent->RRULE) { // Fire up the iterator! - $it = new VObject\RecurrenceIterator($component->parent->parent, (string)$component->parent->UID); - while($it->valid()) { + $it = new VObject\RecurrenceIterator($component->parent->parent, (string) $component->parent->UID); + while ($it->valid()) { $expandedEvent = $it->getEventObject(); // We need to check from these expanded alarms, which @@ -307,14 +290,13 @@ class Sabre_CalDAV_CalendarQueryValidator { // determine if we can 'give up' expanding events. $firstAlarm = null; if ($expandedEvent->VALARM !== null) { - foreach($expandedEvent->VALARM as $expandedAlarm) { - + foreach ($expandedEvent->VALARM as $expandedAlarm) { $effectiveTrigger = $expandedAlarm->getEffectiveTriggerTime(); if ($expandedAlarm->isInTimeRange($start, $end)) { return true; } - if ((string)$expandedAlarm->TRIGGER['VALUE'] === 'DATE-TIME') { + if ((string) $expandedAlarm->TRIGGER['VALUE'] === 'DATE-TIME') { // This is an alarm with a non-relative trigger // time, likely created by a buggy client. The // implication is that every alarm in this @@ -332,7 +314,7 @@ class Sabre_CalDAV_CalendarQueryValidator { } if (is_null($firstAlarm)) { // No alarm was found. - // + // Or technically: No alarm that will change for // every instance of the recurrence was found, // which means we can assume there was no match. @@ -343,30 +325,27 @@ class Sabre_CalDAV_CalendarQueryValidator { } $it->next(); } + return false; } else { return $component->isInTimeRange($start, $end); } - case 'VFREEBUSY' : - throw new Sabre_DAV_Exception_NotImplemented('time-range filters are currently not supported on ' . $component->name . ' components'); + case 'VFREEBUSY': + throw new Sabre_DAV_Exception_NotImplemented('time-range filters are currently not supported on '.$component->name.' components'); - case 'COMPLETED' : - case 'CREATED' : - case 'DTEND' : - case 'DTSTAMP' : - case 'DTSTART' : - case 'DUE' : - case 'LAST-MODIFIED' : - return ($start <= $component->getDateTime() && $end >= $component->getDateTime()); + case 'COMPLETED': + case 'CREATED': + case 'DTEND': + case 'DTSTAMP': + case 'DTSTART': + case 'DUE': + case 'LAST-MODIFIED': + return $start <= $component->getDateTime() && $end >= $component->getDateTime(); - - - default : - throw new Sabre_DAV_Exception_BadRequest('You cannot create a time-range filter on a ' . $component->name . ' component'); + default: + throw new Sabre_DAV_Exception_BadRequest('You cannot create a time-range filter on a '.$component->name.' component'); } - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/CalendarRootNode.php b/dav/SabreDAV/lib/Sabre/CalDAV/CalendarRootNode.php index eb62eea7..5de0d796 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/CalendarRootNode.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/CalendarRootNode.php @@ -1,28 +1,26 @@ caldavBackend = $caldavBackend; - } /** - * Returns the nodename + * Returns the nodename. * * We're overriding this, because the default will be the 'principalPrefix', * and we want it to be Sabre_CalDAV_Plugin::CALENDAR_ROOT * * @return string */ - public function getName() { - + public function getName() + { return Sabre_CalDAV_Plugin::CALENDAR_ROOT; - } /** @@ -65,12 +61,11 @@ class Sabre_CalDAV_CalendarRootNode extends Sabre_DAVACL_AbstractPrincipalCollec * supplied by the authentication backend. * * @param array $principal + * * @return Sabre_DAV_INode */ - public function getChildForPrincipal(array $principal) { - + public function getChildForPrincipal(array $principal) + { return new Sabre_CalDAV_UserCalendars($this->principalBackend, $this->caldavBackend, $principal['uri']); - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Exception/InvalidComponentType.php b/dav/SabreDAV/lib/Sabre/CalDAV/Exception/InvalidComponentType.php index 4ac617d2..1f7f1a98 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Exception/InvalidComponentType.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Exception/InvalidComponentType.php @@ -1,32 +1,27 @@ ownerDocument; - $np = $doc->createElementNS(Sabre_CalDAV_Plugin::NS_CALDAV,'cal:supported-calendar-component'); + $np = $doc->createElementNS(Sabre_CalDAV_Plugin::NS_CALDAV, 'cal:supported-calendar-component'); $errorNode->appendChild($np); - } - -} \ No newline at end of file +} diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/ICSExportPlugin.php b/dav/SabreDAV/lib/Sabre/CalDAV/ICSExportPlugin.php index d3e4e7b7..edb6eab6 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/ICSExportPlugin.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/ICSExportPlugin.php @@ -3,91 +3,94 @@ use Sabre\VObject; /** - * ICS Exporter + * ICS Exporter. * * This plugin adds the ability to export entire calendars as .ics files. * This is useful for clients that don't support CalDAV yet. They often do * support ics files. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_ICSExportPlugin extends Sabre_DAV_ServerPlugin { - +class Sabre_CalDAV_ICSExportPlugin extends Sabre_DAV_ServerPlugin +{ /** - * Reference to Server class + * Reference to Server class. * * @var Sabre_DAV_Server */ private $server; /** - * Initializes the plugin and registers event handlers + * Initializes the plugin and registers event handlers. * * @param Sabre_DAV_Server $server - * @return void */ - public function initialize(Sabre_DAV_Server $server) { - + public function initialize(Sabre_DAV_Server $server) + { $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'), 90); - + $this->server->subscribeEvent('beforeMethod', array($this, 'beforeMethod'), 90); } /** * 'beforeMethod' event handles. This event handles intercepts GET requests ending - * with ?export + * with ?export. * * @param string $method * @param string $uri + * * @return bool */ - public function beforeMethod($method, $uri) { - - if ($method!='GET') return; - if ($this->server->httpRequest->getQueryString()!='export') return; + public function beforeMethod($method, $uri) + { + if ($method != 'GET') { + return; + } + if ($this->server->httpRequest->getQueryString() != 'export') { + return; + } // splitting uri - list($uri) = explode('?',$uri,2); + list($uri) = explode('?', $uri, 2); $node = $this->server->tree->getNodeForPath($uri); - if (!($node instanceof Sabre_CalDAV_Calendar)) return; + if (!($node instanceof Sabre_CalDAV_Calendar)) { + return; + } // Checking ACL, if available. if ($aclPlugin = $this->server->getPlugin('acl')) { $aclPlugin->checkPrivileges($uri, '{DAV:}read'); } - $this->server->httpResponse->setHeader('Content-Type','text/calendar'); + $this->server->httpResponse->setHeader('Content-Type', 'text/calendar'); $this->server->httpResponse->sendStatus(200); $nodes = $this->server->getPropertiesForPath($uri, array( - '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data', - ),1); + '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}calendar-data', + ), 1); $this->server->httpResponse->sendBody($this->generateICS($nodes)); // Returning false to break the event chain return false; - } /** - * Merges all calendar objects, and builds one big ics export + * Merges all calendar objects, and builds one big ics export. * * @param array $nodes + * * @return string */ - public function generateICS(array $nodes) { - + public function generateICS(array $nodes) + { $calendar = new VObject\Component('vcalendar'); $calendar->version = '2.0'; if (Sabre_DAV_Server::$exposeVersion) { - $calendar->prodid = '-//SabreDAV//SabreDAV ' . Sabre_DAV_Version::VERSION . '//EN'; + $calendar->prodid = '-//SabreDAV//SabreDAV '.Sabre_DAV_Version::VERSION.'//EN'; } else { $calendar->prodid = '-//SabreDAV//SabreDAV//EN'; } @@ -98,44 +101,44 @@ class Sabre_CalDAV_ICSExportPlugin extends Sabre_DAV_ServerPlugin { $timezones = array(); $objects = array(); - foreach($nodes as $node) { - - if (!isset($node[200]['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data'])) { + foreach ($nodes as $node) { + if (!isset($node[200]['{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}calendar-data'])) { continue; } - $nodeData = $node[200]['{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data']; + $nodeData = $node[200]['{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}calendar-data']; $nodeComp = VObject\Reader::read($nodeData); - foreach($nodeComp->children() as $child) { - - switch($child->name) { - case 'VEVENT' : - case 'VTODO' : - case 'VJOURNAL' : + foreach ($nodeComp->children() as $child) { + switch ($child->name) { + case 'VEVENT': + case 'VTODO': + case 'VJOURNAL': $objects[] = $child; break; // VTIMEZONE is special, because we need to filter out the duplicates - case 'VTIMEZONE' : + case 'VTIMEZONE': // Naively just checking tzid. - if (in_array((string)$child->TZID, $collectedTimezones)) continue; + if (in_array((string) $child->TZID, $collectedTimezones)) { + continue; + } $timezones[] = $child; $collectedTimezones[] = $child->TZID; break; } - } - } - foreach($timezones as $tz) $calendar->add($tz); - foreach($objects as $obj) $calendar->add($obj); + foreach ($timezones as $tz) { + $calendar->add($tz); + } + foreach ($objects as $obj) { + $calendar->add($obj); + } return $calendar->serialize(); - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/ICalendar.php b/dav/SabreDAV/lib/Sabre/CalDAV/ICalendar.php index 40aa9f95..c0527691 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/ICalendar.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/ICalendar.php @@ -1,18 +1,16 @@ caldavBackend = $caldavBackend; $this->principalUri = $principalUri; - } /** - * Returns all notifications for a principal + * Returns all notifications for a principal. * * @return array */ - public function getChildren() { - + public function getChildren() + { $children = array(); $notifications = $this->caldavBackend->getNotificationsForPrincipal($this->principalUri); - foreach($notifications as $notification) { - + foreach ($notifications as $notification) { $children[] = new Sabre_CalDAV_Notifications_Node( $this->caldavBackend, $notification @@ -63,18 +60,15 @@ class Sabre_CalDAV_Notifications_Collection extends Sabre_DAV_Collection impleme } return $children; - } /** - * Returns the name of this object + * Returns the name of this object. * * @return string */ - public function getName() { - + public function getName() + { return 'notifications'; - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/ICollection.php b/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/ICollection.php index eb873af3..464ffefa 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/ICollection.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/ICollection.php @@ -10,13 +10,10 @@ * This collection should only return Sabre_CalDAV_Notifications_INode nodes as * its children. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -interface Sabre_CalDAV_Notifications_ICollection extends Sabre_DAV_ICollection { - - +interface Sabre_CalDAV_Notifications_ICollection extends Sabre_DAV_ICollection +{ } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/INode.php b/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/INode.php index 5beb4279..d2dd4cce 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/INode.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/INode.php @@ -3,27 +3,24 @@ /** * This node represents a single notification. * - * The signature is mostly identical to that of Sabre_DAV_IFile, but the get() method - * MUST return an xml document that matches the requirements of the + * The signature is mostly identical to that of Sabre_DAV_IFile, but the get() method + * MUST return an xml document that matches the requirements of the * 'caldav-notifications.txt' spec. * - * For a complete example, check out the Notification class, which contains + * For a complete example, check out the Notification class, which contains * some helper functions. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) + * + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved + * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -interface Sabre_CalDAV_Notifications_INode { - +interface Sabre_CalDAV_Notifications_INode +{ /** - * This method must return an xml element, using the + * This method must return an xml element, using the * Sabre_CalDAV_Notifications_INotificationType classes. - * + * * @return Sabre_DAVNotification_INotificationType */ - function getNotificationType(); - + public function getNotificationType(); } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/INotificationType.php b/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/INotificationType.php index ecacd65b..f443d0f6 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/INotificationType.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/INotificationType.php @@ -3,14 +3,12 @@ /** * This interface reflects a single notification type. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -interface Sabre_CalDAV_Notifications_INotificationType extends Sabre_DAV_PropertyInterface { - +interface Sabre_CalDAV_Notifications_INotificationType extends Sabre_DAV_PropertyInterface +{ /** * Serializes the notification as a single property. * @@ -18,29 +16,26 @@ interface Sabre_CalDAV_Notifications_INotificationType extends Sabre_DAV_Propert * notification. * * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void + * @param DOMElement $node */ - function serialize(Sabre_DAV_Server $server, \DOMElement $node); + public function serialize(Sabre_DAV_Server $server, \DOMElement $node); /** * This method serializes the entire notification, as it is used in the * response body. * * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void + * @param DOMElement $node */ - function serializeBody(Sabre_DAV_Server $server, \DOMElement $node); + public function serializeBody(Sabre_DAV_Server $server, \DOMElement $node); /** - * Returns a unique id for this notification + * Returns a unique id for this notification. * * This is just the base url. This should generally be some kind of unique * id. * * @return string */ - function getId(); - + public function getId(); } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/Node.php b/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/Node.php index 910e952c..3a4a1a5f 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/Node.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/Node.php @@ -3,66 +3,60 @@ /** * This node represents a single notification. * - * The signature is mostly identical to that of Sabre_DAV_IFile, but the get() method - * MUST return an xml document that matches the requirements of the + * The signature is mostly identical to that of Sabre_DAV_IFile, but the get() method + * MUST return an xml document that matches the requirements of the * 'caldav-notifications.txt' spec. - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved + * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_Notifications_Node extends Sabre_DAV_Node implements Sabre_CalDAV_Notifications_INode { - +class Sabre_CalDAV_Notifications_Node extends Sabre_DAV_Node implements Sabre_CalDAV_Notifications_INode +{ /** - * The notification backend - * + * The notification backend. + * * @var Sabre_CalDAV_Backend_NotificationSupport */ protected $caldavBackend; /** - * The actual notification - * - * @var Sabre_CalDAV_Notifications_INotificationType + * The actual notification. + * + * @var Sabre_CalDAV_Notifications_INotificationType */ protected $notification; - + /** - * Constructor + * Constructor. * - * @param Sabre_CalDAV_Backend_NotificationSupport $caldavBackend + * @param Sabre_CalDAV_Backend_NotificationSupport $caldavBackend * @param Sabre_CalDAV_Notifications_INotificationType $notification */ - public function __construct(Sabre_CalDAV_Backend_NotificationSupport $caldavBackend, Sabre_CalDAV_Notifications_INotificationType $notification) { - + public function __construct(Sabre_CalDAV_Backend_NotificationSupport $caldavBackend, Sabre_CalDAV_Notifications_INotificationType $notification) + { $this->caldavBackend = $caldavBackend; $this->notification = $notification; - } /** - * Returns the path name for this notification - * - * @return id + * Returns the path name for this notification. + * + * @return id */ - public function getName() { - + public function getName() + { return $this->notification->getId(); - } /** - * This method must return an xml element, using the + * This method must return an xml element, using the * Sabre_CalDAV_Notifications_INotificationType classes. - * + * * @return Sabre_DAVNotification_INotificationType */ - public function getNotificationType() { - + public function getNotificationType() + { return $this->notification; - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/Notification/SystemStatus.php b/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/Notification/SystemStatus.php index 21c86632..7e06a8f0 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/Notification/SystemStatus.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Notifications/Notification/SystemStatus.php @@ -1,25 +1,23 @@ id = $id; $this->type = $type; $this->description = $description; $this->href = $href; - } /** @@ -73,20 +70,19 @@ class Sabre_CalDAV_Notifications_Notification_SystemStatus extends Sabre_DAV_Pro * notification. * * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void + * @param DOMElement $node */ - public function serialize(Sabre_DAV_Server $server, \DOMElement $node) { - - switch($this->type) { - case self::TYPE_LOW : + public function serialize(Sabre_DAV_Server $server, \DOMElement $node) + { + switch ($this->type) { + case self::TYPE_LOW: $type = 'low'; break; - case self::TYPE_MEDIUM : + case self::TYPE_MEDIUM: $type = 'medium'; break; - default : - case self::TYPE_HIGH : + default: + case self::TYPE_HIGH: $type = 'high'; break; } @@ -95,7 +91,6 @@ class Sabre_CalDAV_Notifications_Notification_SystemStatus extends Sabre_DAV_Pro $prop->setAttribute('type', $type); $node->appendChild($prop); - } /** @@ -103,20 +98,19 @@ class Sabre_CalDAV_Notifications_Notification_SystemStatus extends Sabre_DAV_Pro * response body. * * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void + * @param DOMElement $node */ - public function serializeBody(Sabre_DAV_Server $server, \DOMElement $node) { - - switch($this->type) { - case self::TYPE_LOW : + public function serializeBody(Sabre_DAV_Server $server, \DOMElement $node) + { + switch ($this->type) { + case self::TYPE_LOW: $type = 'low'; break; - case self::TYPE_MEDIUM : + case self::TYPE_MEDIUM: $type = 'medium'; break; - default : - case self::TYPE_HIGH : + default: + case self::TYPE_HIGH: $type = 'high'; break; } @@ -138,21 +132,18 @@ class Sabre_CalDAV_Notifications_Notification_SystemStatus extends Sabre_DAV_Pro } $node->appendChild($prop); - } /** - * Returns a unique id for this notification + * Returns a unique id for this notification. * * This is just the base url. This should generally be some kind of unique * id. * * @return string */ - public function getId() { - + public function getId() + { return $this->id; - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Plugin.php b/dav/SabreDAV/lib/Sabre/CalDAV/Plugin.php index c0e4a206..18b01904 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Plugin.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Plugin.php @@ -3,37 +3,35 @@ use Sabre\VObject; /** - * CalDAV plugin + * CalDAV plugin. * * This plugin provides functionality added by CalDAV (RFC 4791) * It implements new reports, and the MKCALENDAR method. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { - +class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin +{ /** - * This is the official CalDAV namespace + * This is the official CalDAV namespace. */ const NS_CALDAV = 'urn:ietf:params:xml:ns:caldav'; /** - * This is the namespace for the proprietary calendarserver extensions + * This is the namespace for the proprietary calendarserver extensions. */ const NS_CALENDARSERVER = 'http://calendarserver.org/ns/'; /** * The hardcoded root for calendar objects. It is unfortunate - * that we're stuck with it, but it will have to do for now + * that we're stuck with it, but it will have to do for now. */ const CALENDAR_ROOT = 'calendars'; /** - * Reference to server object + * Reference to server object. * * @var Sabre_DAV_Server */ @@ -58,12 +56,10 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * events. * * @param Sabre_CalDAV_Schedule_IMip $imipHandler - * @return void */ - public function setIMipHandler(Sabre_CalDAV_Schedule_IMip $imipHandler) { - + public function setIMipHandler(Sabre_CalDAV_Schedule_IMip $imipHandler) + { $this->imipHandler = $imipHandler; - } /** @@ -74,9 +70,11 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * available for the specified uri. * * @param string $uri + * * @return array */ - public function getHTTPMethods($uri) { + public function getHTTPMethods($uri) + { // The MKCALENDAR is only available on unmapped uri's, whose // parents extend IExtendedCollection @@ -91,8 +89,8 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { return array('MKCALENDAR'); } } - return array(); + return array(); } /** @@ -100,10 +98,9 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * * @return array */ - public function getFeatures() { - + public function getFeatures() + { return array('calendar-access', 'calendar-proxy'); - } /** @@ -114,10 +111,9 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * * @return string */ - public function getPluginName() { - + public function getPluginName() + { return 'caldav'; - } /** @@ -128,140 +124,144 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * implement them * * @param string $uri + * * @return array */ - public function getSupportedReportSet($uri) { - + public function getSupportedReportSet($uri) + { $node = $this->server->tree->getNodeForPath($uri); $reports = array(); if ($node instanceof Sabre_CalDAV_ICalendar || $node instanceof Sabre_CalDAV_ICalendarObject) { - $reports[] = '{' . self::NS_CALDAV . '}calendar-multiget'; - $reports[] = '{' . self::NS_CALDAV . '}calendar-query'; + $reports[] = '{'.self::NS_CALDAV.'}calendar-multiget'; + $reports[] = '{'.self::NS_CALDAV.'}calendar-query'; } if ($node instanceof Sabre_CalDAV_ICalendar) { - $reports[] = '{' . self::NS_CALDAV . '}free-busy-query'; + $reports[] = '{'.self::NS_CALDAV.'}free-busy-query'; } - return $reports; + return $reports; } /** - * Initializes the plugin + * Initializes the plugin. * * @param Sabre_DAV_Server $server - * @return void */ - public function initialize(Sabre_DAV_Server $server) { - + public function initialize(Sabre_DAV_Server $server) + { $this->server = $server; - $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); + $server->subscribeEvent('unknownMethod', array($this, 'unknownMethod')); //$server->subscribeEvent('unknownMethod',array($this,'unknownMethod2'),1000); - $server->subscribeEvent('report',array($this,'report')); - $server->subscribeEvent('beforeGetProperties',array($this,'beforeGetProperties')); - $server->subscribeEvent('onHTMLActionsPanel', array($this,'htmlActionsPanel')); - $server->subscribeEvent('onBrowserPostAction', array($this,'browserPostAction')); + $server->subscribeEvent('report', array($this, 'report')); + $server->subscribeEvent('beforeGetProperties', array($this, 'beforeGetProperties')); + $server->subscribeEvent('onHTMLActionsPanel', array($this, 'htmlActionsPanel')); + $server->subscribeEvent('onBrowserPostAction', array($this, 'browserPostAction')); $server->subscribeEvent('beforeWriteContent', array($this, 'beforeWriteContent')); $server->subscribeEvent('beforeCreateFile', array($this, 'beforeCreateFile')); - $server->subscribeEvent('beforeMethod', array($this,'beforeMethod')); + $server->subscribeEvent('beforeMethod', array($this, 'beforeMethod')); $server->xmlNamespaces[self::NS_CALDAV] = 'cal'; $server->xmlNamespaces[self::NS_CALENDARSERVER] = 'cs'; - $server->propertyMap['{' . self::NS_CALDAV . '}supported-calendar-component-set'] = 'Sabre_CalDAV_Property_SupportedCalendarComponentSet'; + $server->propertyMap['{'.self::NS_CALDAV.'}supported-calendar-component-set'] = 'Sabre_CalDAV_Property_SupportedCalendarComponentSet'; $server->resourceTypeMapping['Sabre_CalDAV_ICalendar'] = '{urn:ietf:params:xml:ns:caldav}calendar'; $server->resourceTypeMapping['Sabre_CalDAV_Schedule_IOutbox'] = '{urn:ietf:params:xml:ns:caldav}schedule-outbox'; $server->resourceTypeMapping['Sabre_CalDAV_Principal_ProxyRead'] = '{http://calendarserver.org/ns/}calendar-proxy-read'; $server->resourceTypeMapping['Sabre_CalDAV_Principal_ProxyWrite'] = '{http://calendarserver.org/ns/}calendar-proxy-write'; - $server->resourceTypeMapping['Sabre_CalDAV_Notifications_ICollection'] = '{' . self::NS_CALENDARSERVER . '}notifications'; - $server->resourceTypeMapping['Sabre_CalDAV_Notifications_INode'] = '{' . self::NS_CALENDARSERVER . '}notification'; + $server->resourceTypeMapping['Sabre_CalDAV_Notifications_ICollection'] = '{'.self::NS_CALENDARSERVER.'}notifications'; + $server->resourceTypeMapping['Sabre_CalDAV_Notifications_INode'] = '{'.self::NS_CALENDARSERVER.'}notification'; array_push($server->protectedProperties, - '{' . self::NS_CALDAV . '}supported-calendar-component-set', - '{' . self::NS_CALDAV . '}supported-calendar-data', - '{' . self::NS_CALDAV . '}max-resource-size', - '{' . self::NS_CALDAV . '}min-date-time', - '{' . self::NS_CALDAV . '}max-date-time', - '{' . self::NS_CALDAV . '}max-instances', - '{' . self::NS_CALDAV . '}max-attendees-per-instance', - '{' . self::NS_CALDAV . '}calendar-home-set', - '{' . self::NS_CALDAV . '}supported-collation-set', - '{' . self::NS_CALDAV . '}calendar-data', + '{'.self::NS_CALDAV.'}supported-calendar-component-set', + '{'.self::NS_CALDAV.'}supported-calendar-data', + '{'.self::NS_CALDAV.'}max-resource-size', + '{'.self::NS_CALDAV.'}min-date-time', + '{'.self::NS_CALDAV.'}max-date-time', + '{'.self::NS_CALDAV.'}max-instances', + '{'.self::NS_CALDAV.'}max-attendees-per-instance', + '{'.self::NS_CALDAV.'}calendar-home-set', + '{'.self::NS_CALDAV.'}supported-collation-set', + '{'.self::NS_CALDAV.'}calendar-data', // scheduling extension - '{' . self::NS_CALDAV . '}schedule-inbox-URL', - '{' . self::NS_CALDAV . '}schedule-outbox-URL', - '{' . self::NS_CALDAV . '}calendar-user-address-set', - '{' . self::NS_CALDAV . '}calendar-user-type', + '{'.self::NS_CALDAV.'}schedule-inbox-URL', + '{'.self::NS_CALDAV.'}schedule-outbox-URL', + '{'.self::NS_CALDAV.'}calendar-user-address-set', + '{'.self::NS_CALDAV.'}calendar-user-type', // CalendarServer extensions - '{' . self::NS_CALENDARSERVER . '}getctag', - '{' . self::NS_CALENDARSERVER . '}calendar-proxy-read-for', - '{' . self::NS_CALENDARSERVER . '}calendar-proxy-write-for', - '{' . self::NS_CALENDARSERVER . '}notification-URL', - '{' . self::NS_CALENDARSERVER . '}notificationtype' + '{'.self::NS_CALENDARSERVER.'}getctag', + '{'.self::NS_CALENDARSERVER.'}calendar-proxy-read-for', + '{'.self::NS_CALENDARSERVER.'}calendar-proxy-write-for', + '{'.self::NS_CALENDARSERVER.'}notification-URL', + '{'.self::NS_CALENDARSERVER.'}notificationtype' ); } /** - * This function handles support for the MKCALENDAR method + * This function handles support for the MKCALENDAR method. * * @param string $method * @param string $uri + * * @return bool */ - public function unknownMethod($method, $uri) { - + public function unknownMethod($method, $uri) + { switch ($method) { - case 'MKCALENDAR' : + case 'MKCALENDAR': $this->httpMkCalendar($uri); // false is returned to stop the propagation of the // unknownMethod event. return false; - case 'POST' : + case 'POST': // Checking if we're talking to an outbox try { $node = $this->server->tree->getNodeForPath($uri); } catch (Sabre_DAV_Exception_NotFound $e) { return; } - if (!$node instanceof Sabre_CalDAV_Schedule_IOutbox) + if (!$node instanceof Sabre_CalDAV_Schedule_IOutbox) { return; + } $this->outboxRequest($node); + return false; } - } /** - * This functions handles REPORT requests specific to CalDAV + * This functions handles REPORT requests specific to CalDAV. * - * @param string $reportName + * @param string $reportName * @param DOMNode $dom + * * @return bool */ - public function report($reportName,$dom) { - - switch($reportName) { - case '{'.self::NS_CALDAV.'}calendar-multiget' : + public function report($reportName, $dom) + { + switch ($reportName) { + case '{'.self::NS_CALDAV.'}calendar-multiget': $this->calendarMultiGetReport($dom); + return false; - case '{'.self::NS_CALDAV.'}calendar-query' : + case '{'.self::NS_CALDAV.'}calendar-query': $this->calendarQueryReport($dom); + return false; - case '{'.self::NS_CALDAV.'}free-busy-query' : + case '{'.self::NS_CALDAV.'}free-busy-query': $this->freeBusyQueryReport($dom); + return false; } - - } /** @@ -269,9 +269,9 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * a new calendar. * * @param string $uri - * @return void */ - public function httpMkCalendar($uri) { + public function httpMkCalendar($uri) + { // Due to unforgivable bugs in iCal, we're completely disabling MKCALENDAR support // for clients matching iCal in the user agent @@ -284,85 +284,79 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { $properties = array(); if ($body) { - $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - foreach($dom->firstChild->childNodes as $child) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($child)!=='{DAV:}set') continue; - foreach(Sabre_DAV_XMLUtil::parseProperties($child,$this->server->propertyMap) as $k=>$prop) { + foreach ($dom->firstChild->childNodes as $child) { + if (Sabre_DAV_XMLUtil::toClarkNotation($child) !== '{DAV:}set') { + continue; + } + foreach (Sabre_DAV_XMLUtil::parseProperties($child, $this->server->propertyMap) as $k => $prop) { $properties[$k] = $prop; } - } } - $resourceType = array('{DAV:}collection','{urn:ietf:params:xml:ns:caldav}calendar'); + $resourceType = array('{DAV:}collection', '{urn:ietf:params:xml:ns:caldav}calendar'); - $this->server->createCollection($uri,$resourceType,$properties); + $this->server->createCollection($uri, $resourceType, $properties); $this->server->httpResponse->sendStatus(201); - $this->server->httpResponse->setHeader('Content-Length',0); + $this->server->httpResponse->setHeader('Content-Length', 0); } /** - * beforeGetProperties + * beforeGetProperties. * * This method handler is invoked before any after properties for a * resource are fetched. This allows us to add in any CalDAV specific * properties. * - * @param string $path + * @param string $path * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @return void + * @param array $requestedProperties + * @param array $returnedProperties */ - public function beforeGetProperties($path, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) { - + public function beforeGetProperties($path, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) + { if ($node instanceof Sabre_DAVACL_IPrincipal) { // calendar-home-set property - $calHome = '{' . self::NS_CALDAV . '}calendar-home-set'; - if (in_array($calHome,$requestedProperties)) { + $calHome = '{'.self::NS_CALDAV.'}calendar-home-set'; + if (in_array($calHome, $requestedProperties)) { $principalId = $node->getName(); - $calendarHomePath = self::CALENDAR_ROOT . '/' . $principalId . '/'; + $calendarHomePath = self::CALENDAR_ROOT.'/'.$principalId.'/'; unset($requestedProperties[$calHome]); $returnedProperties[200][$calHome] = new Sabre_DAV_Property_Href($calendarHomePath); } // schedule-outbox-URL property - $scheduleProp = '{' . self::NS_CALDAV . '}schedule-outbox-URL'; - if (in_array($scheduleProp,$requestedProperties)) { + $scheduleProp = '{'.self::NS_CALDAV.'}schedule-outbox-URL'; + if (in_array($scheduleProp, $requestedProperties)) { $principalId = $node->getName(); - $outboxPath = self::CALENDAR_ROOT . '/' . $principalId . '/outbox'; + $outboxPath = self::CALENDAR_ROOT.'/'.$principalId.'/outbox'; unset($requestedProperties[$scheduleProp]); $returnedProperties[200][$scheduleProp] = new Sabre_DAV_Property_Href($outboxPath); } // calendar-user-address-set property - $calProp = '{' . self::NS_CALDAV . '}calendar-user-address-set'; - if (in_array($calProp,$requestedProperties)) { - + $calProp = '{'.self::NS_CALDAV.'}calendar-user-address-set'; + if (in_array($calProp, $requestedProperties)) { $addresses = $node->getAlternateUriSet(); - $addresses[] = $this->server->getBaseUri() . $node->getPrincipalUrl(); + $addresses[] = $this->server->getBaseUri().$node->getPrincipalUrl(); unset($requestedProperties[$calProp]); $returnedProperties[200][$calProp] = new Sabre_DAV_Property_HrefList($addresses, false); - } // These two properties are shortcuts for ical to easily find // other principals this principal has access to. - $propRead = '{' . self::NS_CALENDARSERVER . '}calendar-proxy-read-for'; - $propWrite = '{' . self::NS_CALENDARSERVER . '}calendar-proxy-write-for'; - if (in_array($propRead,$requestedProperties) || in_array($propWrite,$requestedProperties)) { - + $propRead = '{'.self::NS_CALENDARSERVER.'}calendar-proxy-read-for'; + $propWrite = '{'.self::NS_CALENDARSERVER.'}calendar-proxy-write-for'; + if (in_array($propRead, $requestedProperties) || in_array($propWrite, $requestedProperties)) { $membership = $node->getGroupMembership(); $readList = array(); $writeList = array(); - foreach($membership as $group) { - + foreach ($membership as $group) { $groupNode = $this->server->tree->getNodeForPath($group); // If the node is either ap proxy-read or proxy-write @@ -374,62 +368,53 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { if ($groupNode instanceof Sabre_CalDAV_Principal_ProxyWrite) { list($writeList[]) = Sabre_DAV_URLUtil::splitPath($group); } - } - if (in_array($propRead,$requestedProperties)) { + if (in_array($propRead, $requestedProperties)) { unset($requestedProperties[$propRead]); $returnedProperties[200][$propRead] = new Sabre_DAV_Property_HrefList($readList); } - if (in_array($propWrite,$requestedProperties)) { + if (in_array($propWrite, $requestedProperties)) { unset($requestedProperties[$propWrite]); $returnedProperties[200][$propWrite] = new Sabre_DAV_Property_HrefList($writeList); } - } // notification-URL property - $notificationUrl = '{' . self::NS_CALENDARSERVER . '}notification-URL'; + $notificationUrl = '{'.self::NS_CALENDARSERVER.'}notification-URL'; if (($index = array_search($notificationUrl, $requestedProperties)) !== false) { $principalId = $node->getName(); - $calendarHomePath = 'calendars/' . $principalId . '/notifications/'; + $calendarHomePath = 'calendars/'.$principalId.'/notifications/'; unset($requestedProperties[$index]); $returnedProperties[200][$notificationUrl] = new Sabre_DAV_Property_Href($calendarHomePath); } - } // instanceof IPrincipal if ($node instanceof Sabre_CalDAV_Notifications_INode) { - - $propertyName = '{' . self::NS_CALENDARSERVER . '}notificationtype'; + $propertyName = '{'.self::NS_CALENDARSERVER.'}notificationtype'; if (($index = array_search($propertyName, $requestedProperties)) !== false) { - $returnedProperties[200][$propertyName] = $node->getNotificationType(); unset($requestedProperties[$index]); - } - } // instanceof Notifications_INode - if ($node instanceof Sabre_CalDAV_ICalendarObject) { // The calendar-data property is not supposed to be a 'real' // property, but in large chunks of the spec it does act as such. // Therefore we simply expose it as a property. - $calDataProp = '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}calendar-data'; + $calDataProp = '{'.self::NS_CALDAV.'}calendar-data'; if (in_array($calDataProp, $requestedProperties)) { unset($requestedProperties[$calDataProp]); $val = $node->get(); - if (is_resource($val)) + if (is_resource($val)) { $val = stream_get_contents($val); + } // Taking out \r to not screw up the xml output - $returnedProperties[200][$calDataProp] = str_replace("\r","", $val); - + $returnedProperties[200][$calDataProp] = str_replace("\r", '', $val); } } - } /** @@ -439,23 +424,22 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * of urls. Effectively avoiding a lot of redundant requests. * * @param DOMNode $dom - * @return void */ - public function calendarMultiGetReport($dom) { - + public function calendarMultiGetReport($dom) + { $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - $hrefElems = $dom->getElementsByTagNameNS('DAV:','href'); + $hrefElems = $dom->getElementsByTagNameNS('DAV:', 'href'); $xpath = new DOMXPath($dom); - $xpath->registerNameSpace('cal',Sabre_CalDAV_Plugin::NS_CALDAV); - $xpath->registerNameSpace('dav','DAV:'); + $xpath->registerNameSpace('cal', self::NS_CALDAV); + $xpath->registerNameSpace('dav', 'DAV:'); $expand = $xpath->query('/cal:calendar-multiget/dav:prop/cal:calendar-data/cal:expand'); - if ($expand->length>0) { + if ($expand->length > 0) { $expandElem = $expand->item(0); $start = $expandElem->getAttribute('start'); $end = $expandElem->getAttribute('end'); - if(!$start || !$end) { + if (!$start || !$end) { throw new Sabre_DAV_Exception_BadRequest('The "start" and "end" attributes are required for the CALDAV:expand element'); } $start = VObject\DateTimeParser::parseDateTime($start); @@ -466,44 +450,38 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { } $expand = true; - } else { - $expand = false; - } - foreach($hrefElems as $elem) { + foreach ($hrefElems as $elem) { $uri = $this->server->calculateUri($elem->nodeValue); - list($objProps) = $this->server->getPropertiesForPath($uri,$properties); + list($objProps) = $this->server->getPropertiesForPath($uri, $properties); - if ($expand && isset($objProps[200]['{' . self::NS_CALDAV . '}calendar-data'])) { - $vObject = VObject\Reader::read($objProps[200]['{' . self::NS_CALDAV . '}calendar-data']); + if ($expand && isset($objProps[200]['{'.self::NS_CALDAV.'}calendar-data'])) { + $vObject = VObject\Reader::read($objProps[200]['{'.self::NS_CALDAV.'}calendar-data']); $vObject->expand($start, $end); - $objProps[200]['{' . self::NS_CALDAV . '}calendar-data'] = $vObject->serialize(); + $objProps[200]['{'.self::NS_CALDAV.'}calendar-data'] = $vObject->serialize(); } - $propertyList[]=$objProps; - + $propertyList[] = $objProps; } $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList)); - } /** - * This function handles the calendar-query REPORT + * This function handles the calendar-query REPORT. * * This report is used by clients to request calendar objects based on * complex conditions. * * @param DOMNode $dom - * @return void */ - public function calendarQueryReport($dom) { - + public function calendarQueryReport($dom) + { $parser = new Sabre_CalDAV_CalendarQueryParser($dom); $parser->parse(); @@ -516,7 +494,6 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { // The calendarobject was requested directly. In this case we handle // this locally. if ($depth == 0 && $node instanceof Sabre_CalDAV_ICalendarObject) { - $requestedCalendarData = true; $requestedProperties = $parser->requestedProperties; @@ -543,10 +520,9 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { // If there wasn't any calendar-data returned somehow, we ignore // this. if (isset($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data'])) { - $validator = new Sabre_CalDAV_CalendarQueryValidator(); $vObject = VObject\Reader::read($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']); - if ($validator->validate($vObject,$parser->filters)) { + if ($validator->validate($vObject, $parser->filters)) { // If the client didn't require the calendar-data property, // we won't give it back. @@ -555,45 +531,37 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { } else { if ($parser->expand) { $vObject->expand($parser->expand['start'], $parser->expand['end']); - $properties[200]['{' . self::NS_CALDAV . '}calendar-data'] = $vObject->serialize(); + $properties[200]['{'.self::NS_CALDAV.'}calendar-data'] = $vObject->serialize(); } } $result = array($properties); - } - } - } // If we're dealing with a calendar, the calendar itself is responsible // for the calendar-query. if ($node instanceof Sabre_CalDAV_ICalendar && $depth = 1) { - $nodePaths = $node->calendarQuery($parser->filters); - foreach($nodePaths as $path) { - + foreach ($nodePaths as $path) { list($properties) = - $this->server->getPropertiesForPath($this->server->getRequestUri() . '/' . $path, $parser->requestedProperties); + $this->server->getPropertiesForPath($this->server->getRequestUri().'/'.$path, $parser->requestedProperties); if ($parser->expand) { // We need to do some post-processing $vObject = VObject\Reader::read($properties[200]['{urn:ietf:params:xml:ns:caldav}calendar-data']); $vObject->expand($parser->expand['start'], $parser->expand['end']); - $properties[200]['{' . self::NS_CALDAV . '}calendar-data'] = $vObject->serialize(); + $properties[200]['{'.self::NS_CALDAV.'}calendar-data'] = $vObject->serialize(); } $result[] = $properties; - } - } $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->sendBody($this->server->generateMultiStatus($result)); - } /** @@ -601,22 +569,19 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * response for the CALDAV:free-busy-query REPORT. * * @param DOMNode $dom - * @return void */ - protected function freeBusyQueryReport(DOMNode $dom) { - + protected function freeBusyQueryReport(DOMNode $dom) + { $start = null; $end = null; - foreach($dom->firstChild->childNodes as $childNode) { - + foreach ($dom->firstChild->childNodes as $childNode) { $clark = Sabre_DAV_XMLUtil::toClarkNotation($childNode); - if ($clark == '{' . self::NS_CALDAV . '}time-range') { + if ($clark == '{'.self::NS_CALDAV.'}time-range') { $start = $childNode->getAttribute('start'); $end = $childNode->getAttribute('end'); break; } - } if ($start) { $start = VObject\DateTimeParser::parseDateTime($start); @@ -634,18 +599,19 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { throw new Sabre_DAV_Exception('The ACL plugin must be loaded for free-busy queries to work'); } $uri = $this->server->getRequestUri(); - $acl->checkPrivileges($uri,'{' . self::NS_CALDAV . '}read-free-busy'); + $acl->checkPrivileges($uri, '{'.self::NS_CALDAV.'}read-free-busy'); $calendar = $this->server->tree->getNodeForPath($uri); if (!$calendar instanceof Sabre_CalDAV_ICalendar) { throw new Sabre_DAV_Exception_NotImplemented('The free-busy-query REPORT is only implemented on calendars'); } - $objects = array_map(function($child) { + $objects = array_map(function ($child) { $obj = $child->get(); if (is_resource($obj)) { $obj = stream_get_contents($obj); } + return $obj; }, $calendar->getChildren()); @@ -659,7 +625,6 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { $this->server->httpResponse->setHeader('Content-Type', 'text/calendar'); $this->server->httpResponse->setHeader('Content-Length', strlen($result)); $this->server->httpResponse->sendBody($result); - } /** @@ -668,18 +633,17 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * This plugin uses this method to ensure that CalDAV objects receive * valid calendar data. * - * @param string $path + * @param string $path * @param Sabre_DAV_IFile $node - * @param resource $data - * @return void + * @param resource $data */ - public function beforeWriteContent($path, Sabre_DAV_IFile $node, &$data) { - - if (!$node instanceof Sabre_CalDAV_ICalendarObject) + public function beforeWriteContent($path, Sabre_DAV_IFile $node, &$data) + { + if (!$node instanceof Sabre_CalDAV_ICalendarObject) { return; + } $this->validateICalendar($data, $path); - } /** @@ -688,18 +652,17 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * This plugin uses this method to ensure that newly created calendar * objects contain valid calendar data. * - * @param string $path - * @param resource $data + * @param string $path + * @param resource $data * @param Sabre_DAV_ICollection $parentNode - * @return void */ - public function beforeCreateFile($path, &$data, Sabre_DAV_ICollection $parentNode) { - - if (!$parentNode instanceof Sabre_CalDAV_Calendar) + public function beforeCreateFile($path, &$data, Sabre_DAV_ICollection $parentNode) + { + if (!$parentNode instanceof Sabre_CalDAV_Calendar) { return; + } $this->validateICalendar($data, $path); - } /** @@ -707,14 +670,15 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * * We use this to intercept GET calls to notification nodes, and return the * proper response. - * - * @param string $method - * @param string $path - * @return void + * + * @param string $method + * @param string $path */ - public function beforeMethod($method, $path) { - - if ($method!=='GET') return; + public function beforeMethod($method, $path) + { + if ($method !== 'GET') { + return; + } try { $node = $this->server->tree->getNodeForPath($path); @@ -722,26 +686,26 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { return; } - if (!$node instanceof Sabre_CalDAV_Notifications_INode) + if (!$node instanceof Sabre_CalDAV_Notifications_INode) { return; + } $dom = new DOMDocument('1.0', 'UTF-8'); $dom->formatOutput = true; $root = $dom->createElement('cs:notification'); - foreach($this->server->xmlNamespaces as $namespace => $prefix) { - $root->setAttribute('xmlns:' . $prefix, $namespace); + foreach ($this->server->xmlNamespaces as $namespace => $prefix) { + $root->setAttribute('xmlns:'.$prefix, $namespace); } $dom->appendChild($root); $node->getNotificationType()->serializeBody($this->server, $root); - $this->server->httpResponse->setHeader('Content-Type','application/xml'); + $this->server->httpResponse->setHeader('Content-Type', 'application/xml'); $this->server->httpResponse->sendStatus(200); $this->server->httpResponse->sendBody($dom->saveXML()); return false; - } /** @@ -750,10 +714,10 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * An exception is thrown if it's not. * * @param resource|string $data - * @param string $path - * @return void + * @param string $path */ - protected function validateICalendar(&$data, $path) { + protected function validateICalendar(&$data, $path) + { // If it's a stream, we convert it to a string first. if (is_resource($data)) { @@ -764,13 +728,9 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { $data = Sabre_DAV_StringUtil::ensureUTF8($data); try { - $vobj = VObject\Reader::read($data); - } catch (VObject\ParseException $e) { - - throw new Sabre_DAV_Exception_UnsupportedMediaType('This resource only supports valid iCalendar 2.0 data. Parse error: ' . $e->getMessage()); - + throw new Sabre_DAV_Exception_UnsupportedMediaType('This resource only supports valid iCalendar 2.0 data. Parse error: '.$e->getMessage()); } if ($vobj->name !== 'VCALENDAR') { @@ -778,55 +738,54 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { } // Get the Supported Components for the target calendar - list($parentPath,$object) = Sabre_Dav_URLUtil::splitPath($path); - $calendarProperties = $this->server->getProperties($parentPath,array('{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set')); + list($parentPath, $object) = Sabre_Dav_URLUtil::splitPath($path); + $calendarProperties = $this->server->getProperties($parentPath, array('{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set')); $supportedComponents = $calendarProperties['{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set']->getValue(); $foundType = null; $foundUID = null; - foreach($vobj->getComponents() as $component) { - switch($component->name) { - case 'VTIMEZONE' : + foreach ($vobj->getComponents() as $component) { + switch ($component->name) { + case 'VTIMEZONE': continue 2; - case 'VEVENT' : - case 'VTODO' : - case 'VJOURNAL' : + case 'VEVENT': + case 'VTODO': + case 'VJOURNAL': if (is_null($foundType)) { $foundType = $component->name; if (!in_array($foundType, $supportedComponents)) { - throw new Sabre_CalDAV_Exception_InvalidComponentType('This calendar only supports ' . implode(', ', $supportedComponents) . '. We found a ' . $foundType); + throw new Sabre_CalDAV_Exception_InvalidComponentType('This calendar only supports '.implode(', ', $supportedComponents).'. We found a '.$foundType); } if (!isset($component->UID)) { - throw new Sabre_DAV_Exception_BadRequest('Every ' . $component->name . ' component must have an UID'); + throw new Sabre_DAV_Exception_BadRequest('Every '.$component->name.' component must have an UID'); } - $foundUID = (string)$component->UID; + $foundUID = (string) $component->UID; } else { if ($foundType !== $component->name) { - throw new Sabre_DAV_Exception_BadRequest('A calendar object must only contain 1 component. We found a ' . $component->name . ' as well as a ' . $foundType); + throw new Sabre_DAV_Exception_BadRequest('A calendar object must only contain 1 component. We found a '.$component->name.' as well as a '.$foundType); } - if ($foundUID !== (string)$component->UID) { - throw new Sabre_DAV_Exception_BadRequest('Every ' . $component->name . ' in this object must have identical UIDs'); + if ($foundUID !== (string) $component->UID) { + throw new Sabre_DAV_Exception_BadRequest('Every '.$component->name.' in this object must have identical UIDs'); } } break; - default : - throw new Sabre_DAV_Exception_BadRequest('You are not allowed to create components of type: ' . $component->name . ' here'); + default: + throw new Sabre_DAV_Exception_BadRequest('You are not allowed to create components of type: '.$component->name.' here'); } } - if (!$foundType) + if (!$foundType) { throw new Sabre_DAV_Exception_BadRequest('iCalendar object must contain at least 1 of VEVENT, VTODO or VJOURNAL'); - + } } /** - * This method handles POST requests to the schedule-outbox + * This method handles POST requests to the schedule-outbox. * * @param Sabre_CalDAV_Schedule_IOutbox $outboxNode - * @return void */ - public function outboxRequest(Sabre_CalDAV_Schedule_IOutbox $outboxNode) { - + public function outboxRequest(Sabre_CalDAV_Schedule_IOutbox $outboxNode) + { $originator = $this->server->httpRequest->getHeader('Originator'); $recipients = $this->server->httpRequest->getHeader('Recipient'); @@ -840,11 +799,10 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { if (!preg_match('/^mailto:(.*)@(.*)$/i', $originator)) { throw new Sabre_DAV_Exception_BadRequest('Originator must start with mailto: and must be valid email address'); } - $originator = substr($originator,7); - - $recipients = explode(',',$recipients); - foreach($recipients as $k=>$recipient) { + $originator = substr($originator, 7); + $recipients = explode(',', $recipients); + foreach ($recipients as $k => $recipient) { $recipient = trim($recipient); if (!preg_match('/^mailto:(.*)@(.*)$/i', $recipient)) { throw new Sabre_DAV_Exception_BadRequest('Recipients must start with mailto: and must be valid email address'); @@ -856,28 +814,28 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { // We need to make sure that 'originator' matches one of the email // addresses of the selected principal. $principal = $outboxNode->getOwner(); - $props = $this->server->getProperties($principal,array( - '{' . self::NS_CALDAV . '}calendar-user-address-set', + $props = $this->server->getProperties($principal, array( + '{'.self::NS_CALDAV.'}calendar-user-address-set', )); $addresses = array(); - if (isset($props['{' . self::NS_CALDAV . '}calendar-user-address-set'])) { - $addresses = $props['{' . self::NS_CALDAV . '}calendar-user-address-set']->getHrefs(); + if (isset($props['{'.self::NS_CALDAV.'}calendar-user-address-set'])) { + $addresses = $props['{'.self::NS_CALDAV.'}calendar-user-address-set']->getHrefs(); } - if (!in_array('mailto:' . $originator, $addresses)) { + if (!in_array('mailto:'.$originator, $addresses)) { throw new Sabre_DAV_Exception_Forbidden('The addresses specified in the Originator header did not match any addresses in the owners calendar-user-address-set header'); } try { $vObject = VObject\Reader::read($this->server->httpRequest->getBody(true)); } catch (VObject\ParseException $e) { - throw new Sabre_DAV_Exception_BadRequest('The request body must be a valid iCalendar object. Parse error: ' . $e->getMessage()); + throw new Sabre_DAV_Exception_BadRequest('The request body must be a valid iCalendar object. Parse error: '.$e->getMessage()); } // Checking for the object type $componentType = null; - foreach($vObject->getComponents() as $component) { + foreach ($vObject->getComponents() as $component) { if ($component->name !== 'VTIMEZONE') { $componentType = $component->name; break; @@ -888,20 +846,19 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { } // Validating the METHOD - $method = strtoupper((string)$vObject->METHOD); + $method = strtoupper((string) $vObject->METHOD); if (!$method) { throw new Sabre_DAV_Exception_BadRequest('A METHOD property must be specified in iTIP messages'); } - if (in_array($method, array('REQUEST','REPLY','ADD','CANCEL')) && $componentType==='VEVENT') { + if (in_array($method, array('REQUEST', 'REPLY', 'ADD', 'CANCEL')) && $componentType === 'VEVENT') { $result = $this->iMIPMessage($originator, $recipients, $vObject, $principal); $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->setHeader('Content-Type','application/xml'); + $this->server->httpResponse->setHeader('Content-Type', 'application/xml'); $this->server->httpResponse->sendBody($this->generateScheduleResponse($result)); } else { throw new Sabre_DAV_Exception_NotImplemented('This iTIP method is currently not implemented'); } - } /** @@ -920,13 +877,14 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * A list of valid status codes can be found at: * https://tools.ietf.org/html/rfc5546#section-3.6 * - * @param string $originator - * @param array $recipients + * @param string $originator + * @param array $recipients * @param Sabre\VObject\Component $vObject + * * @return array */ - protected function iMIPMessage($originator, array $recipients, VObject\Component $vObject, $principal) { - + protected function iMIPMessage($originator, array $recipients, VObject\Component $vObject, $principal) + { if (!$this->imipHandler) { $resultStatus = '5.2;This server does not support this operation'; } else { @@ -935,38 +893,36 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { } $result = array(); - foreach($recipients as $recipient) { + foreach ($recipients as $recipient) { $result[$recipient] = $resultStatus; } return $result; - } /** - * Generates a schedule-response XML body + * Generates a schedule-response XML body. * * The recipients array is a key->value list, containing email addresses * and iTip status codes. See the iMIPMessage method for a description of * the value. * * @param array $recipients + * * @return string */ - public function generateScheduleResponse(array $recipients) { - - $dom = new DOMDocument('1.0','utf-8'); + public function generateScheduleResponse(array $recipients) + { + $dom = new DOMDocument('1.0', 'utf-8'); $dom->formatOutput = true; $xscheduleResponse = $dom->createElement('cal:schedule-response'); $dom->appendChild($xscheduleResponse); - foreach($this->server->xmlNamespaces as $namespace=>$prefix) { - - $xscheduleResponse->setAttribute('xmlns:' . $prefix, $namespace); - + foreach ($this->server->xmlNamespaces as $namespace => $prefix) { + $xscheduleResponse->setAttribute('xmlns:'.$prefix, $namespace); } - foreach($recipients as $recipient=>$status) { + foreach ($recipients as $recipient => $status) { $xresponse = $dom->createElement('cal:response'); $xrecipient = $dom->createElement('cal:recipient'); @@ -978,11 +934,9 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { $xresponse->appendChild($xrequestStatus); $xscheduleResponse->appendChild($xresponse); - } return $dom->saveXML(); - } /** @@ -991,15 +945,17 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * can use to create new calendars. * * @param Sabre_DAV_INode $node - * @param string $output + * @param string $output + * * @return bool */ - public function htmlActionsPanel(Sabre_DAV_INode $node, &$output) { - - if (!$node instanceof Sabre_CalDAV_UserCalendars) + public function htmlActionsPanel(Sabre_DAV_INode $node, &$output) + { + if (!$node instanceof Sabre_CalDAV_UserCalendars) { return; + } - $output.= '
+ $output .= '

Create new calendar


@@ -1009,7 +965,6 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { '; return false; - } /** @@ -1018,22 +973,23 @@ class Sabre_CalDAV_Plugin extends Sabre_DAV_ServerPlugin { * * @param string $uri * @param string $action - * @param array $postVars + * @param array $postVars + * * @return bool */ - public function browserPostAction($uri, $action, array $postVars) { - - if ($action!=='mkcalendar') + public function browserPostAction($uri, $action, array $postVars) + { + if ($action !== 'mkcalendar') { return; + } - $resourceType = array('{DAV:}collection','{urn:ietf:params:xml:ns:caldav}calendar'); + $resourceType = array('{DAV:}collection', '{urn:ietf:params:xml:ns:caldav}calendar'); $properties = array(); if (isset($postVars['{DAV:}displayname'])) { $properties['{DAV:}displayname'] = $postVars['{DAV:}displayname']; } - $this->server->createCollection($uri . '/' . $postVars['name'],$resourceType,$properties); + $this->server->createCollection($uri.'/'.$postVars['name'], $resourceType, $properties); + return false; - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Principal/Collection.php b/dav/SabreDAV/lib/Sabre/CalDAV/Principal/Collection.php index abbefa55..78619447 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Principal/Collection.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Principal/Collection.php @@ -1,31 +1,28 @@ principalBackend, $principalInfo); - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Principal/ProxyRead.php b/dav/SabreDAV/lib/Sabre/CalDAV/Principal/ProxyRead.php index 4b3f0356..82dffdae 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Principal/ProxyRead.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Principal/ProxyRead.php @@ -1,20 +1,18 @@ principalInfo = $principalInfo; $this->principalBackend = $principalBackend; - } /** @@ -49,103 +46,91 @@ class Sabre_CalDAV_Principal_ProxyRead implements Sabre_DAVACL_IPrincipal { * * @return string */ - public function getName() { - + public function getName() + { return 'calendar-proxy-read'; - } /** - * Returns the last modification time - * - * @return null + * Returns the last modification time. */ - public function getLastModified() { - + public function getLastModified() + { return null; - } /** - * Deletes the current node + * Deletes the current node. * * @throws Sabre_DAV_Exception_Forbidden - * @return void */ - public function delete() { - + public function delete() + { throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); - } /** - * Renames the node + * Renames the node. * * @throws Sabre_DAV_Exception_Forbidden + * * @param string $name The new name - * @return void */ - public function setName($name) { - + public function setName($name) + { throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); - } - /** - * Returns a list of alternative urls for a principal + * Returns a list of alternative urls for a principal. * * This can for example be an email address, or ldap url. * * @return array */ - public function getAlternateUriSet() { - + public function getAlternateUriSet() + { return array(); - } /** - * Returns the full principal url + * Returns the full principal url. * * @return string */ - public function getPrincipalUrl() { - - return $this->principalInfo['uri'] . '/' . $this->getName(); - + public function getPrincipalUrl() + { + return $this->principalInfo['uri'].'/'.$this->getName(); } /** - * Returns the list of group members + * Returns the list of group members. * * If this principal is a group, this function should return * all member principal uri's for the group. * * @return array */ - public function getGroupMemberSet() { - + public function getGroupMemberSet() + { return $this->principalBackend->getGroupMemberSet($this->getPrincipalUrl()); - } /** - * Returns the list of groups this principal is member of + * Returns the list of groups this principal is member of. * * If this principal is a member of a (list of) groups, this function * should return a list of principal uri's for it's members. * * @return array */ - public function getGroupMembership() { - + public function getGroupMembership() + { return $this->principalBackend->getGroupMembership($this->getPrincipalUrl()); - } /** - * Sets a list of group members + * Sets a list of group members. * * If this principal is a group, this method sets all the group members. * The list of members is always overwritten, never appended to. @@ -153,26 +138,22 @@ class Sabre_CalDAV_Principal_ProxyRead implements Sabre_DAVACL_IPrincipal { * This method should throw an exception if the members could not be set. * * @param array $principals - * @return void */ - public function setGroupMemberSet(array $principals) { - + public function setGroupMemberSet(array $principals) + { $this->principalBackend->setGroupMemberSet($this->getPrincipalUrl(), $principals); - } /** - * Returns the displayname + * Returns the displayname. * * This should be a human readable name for the principal. * If none is available, return the nodename. * * @return string */ - public function getDisplayName() { - + public function getDisplayName() + { return $this->getName(); - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Principal/ProxyWrite.php b/dav/SabreDAV/lib/Sabre/CalDAV/Principal/ProxyWrite.php index dd0c2e86..e2089fc6 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Principal/ProxyWrite.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Principal/ProxyWrite.php @@ -1,47 +1,44 @@ principalInfo = $principalInfo; $this->principalBackend = $principalBackend; - } /** @@ -49,103 +46,91 @@ class Sabre_CalDAV_Principal_ProxyWrite implements Sabre_DAVACL_IPrincipal { * * @return string */ - public function getName() { - + public function getName() + { return 'calendar-proxy-write'; - } /** - * Returns the last modification time - * - * @return null + * Returns the last modification time. */ - public function getLastModified() { - + public function getLastModified() + { return null; - } /** - * Deletes the current node + * Deletes the current node. * * @throws Sabre_DAV_Exception_Forbidden - * @return void */ - public function delete() { - + public function delete() + { throw new Sabre_DAV_Exception_Forbidden('Permission denied to delete node'); - } /** - * Renames the node + * Renames the node. * * @throws Sabre_DAV_Exception_Forbidden + * * @param string $name The new name - * @return void */ - public function setName($name) { - + public function setName($name) + { throw new Sabre_DAV_Exception_Forbidden('Permission denied to rename file'); - } - /** - * Returns a list of alternative urls for a principal + * Returns a list of alternative urls for a principal. * * This can for example be an email address, or ldap url. * * @return array */ - public function getAlternateUriSet() { - + public function getAlternateUriSet() + { return array(); - } /** - * Returns the full principal url + * Returns the full principal url. * * @return string */ - public function getPrincipalUrl() { - - return $this->principalInfo['uri'] . '/' . $this->getName(); - + public function getPrincipalUrl() + { + return $this->principalInfo['uri'].'/'.$this->getName(); } /** - * Returns the list of group members + * Returns the list of group members. * * If this principal is a group, this function should return * all member principal uri's for the group. * * @return array */ - public function getGroupMemberSet() { - + public function getGroupMemberSet() + { return $this->principalBackend->getGroupMemberSet($this->getPrincipalUrl()); - } /** - * Returns the list of groups this principal is member of + * Returns the list of groups this principal is member of. * * If this principal is a member of a (list of) groups, this function * should return a list of principal uri's for it's members. * * @return array */ - public function getGroupMembership() { - + public function getGroupMembership() + { return $this->principalBackend->getGroupMembership($this->getPrincipalUrl()); - } /** - * Sets a list of group members + * Sets a list of group members. * * If this principal is a group, this method sets all the group members. * The list of members is always overwritten, never appended to. @@ -153,26 +138,22 @@ class Sabre_CalDAV_Principal_ProxyWrite implements Sabre_DAVACL_IPrincipal { * This method should throw an exception if the members could not be set. * * @param array $principals - * @return void */ - public function setGroupMemberSet(array $principals) { - + public function setGroupMemberSet(array $principals) + { $this->principalBackend->setGroupMemberSet($this->getPrincipalUrl(), $principals); - } /** - * Returns the displayname + * Returns the displayname. * * This should be a human readable name for the principal. * If none is available, return the nodename. * * @return string */ - public function getDisplayName() { - + public function getDisplayName() + { return $this->getName(); - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Principal/User.php b/dav/SabreDAV/lib/Sabre/CalDAV/Principal/User.php index 8453b877..92b66967 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Principal/User.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Principal/User.php @@ -1,103 +1,101 @@ principalBackend->getPrincipalByPath($this->getPrincipalURL() . '/' . $name); + public function getChild($name) + { + $principal = $this->principalBackend->getPrincipalByPath($this->getPrincipalURL().'/'.$name); if (!$principal) { - throw new Sabre_DAV_Exception_NotFound('Node with name ' . $name . ' was not found'); + throw new Sabre_DAV_Exception_NotFound('Node with name '.$name.' was not found'); } - if ($name === 'calendar-proxy-read') + if ($name === 'calendar-proxy-read') { return new Sabre_CalDAV_Principal_ProxyRead($this->principalBackend, $this->principalProperties); + } - if ($name === 'calendar-proxy-write') + if ($name === 'calendar-proxy-write') { return new Sabre_CalDAV_Principal_ProxyWrite($this->principalBackend, $this->principalProperties); + } - throw new Sabre_DAV_Exception_NotFound('Node with name ' . $name . ' was not found'); - + throw new Sabre_DAV_Exception_NotFound('Node with name '.$name.' was not found'); } /** - * Returns an array with all the child nodes + * Returns an array with all the child nodes. * * @return Sabre_DAV_INode[] */ - public function getChildren() { - + public function getChildren() + { $r = array(); - if ($this->principalBackend->getPrincipalByPath($this->getPrincipalURL() . '/calendar-proxy-read')) { + if ($this->principalBackend->getPrincipalByPath($this->getPrincipalURL().'/calendar-proxy-read')) { $r[] = new Sabre_CalDAV_Principal_ProxyRead($this->principalBackend, $this->principalProperties); } - if ($this->principalBackend->getPrincipalByPath($this->getPrincipalURL() . '/calendar-proxy-write')) { + if ($this->principalBackend->getPrincipalByPath($this->getPrincipalURL().'/calendar-proxy-write')) { $r[] = new Sabre_CalDAV_Principal_ProxyWrite($this->principalBackend, $this->principalProperties); } return $r; - } /** - * Returns whether or not the child node exists + * Returns whether or not the child node exists. * * @param string $name + * * @return bool */ - public function childExists($name) { - + public function childExists($name) + { try { $this->getChild($name); + return true; } catch (Sabre_DAV_Exception_NotFound $e) { return false; } - } /** @@ -112,21 +110,20 @@ class Sabre_CalDAV_Principal_User extends Sabre_DAVACL_Principal implements Sabr * * @return array */ - public function getACL() { - + public function getACL() + { $acl = parent::getACL(); $acl[] = array( 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'] . '/calendar-proxy-read', + 'principal' => $this->principalProperties['uri'].'/calendar-proxy-read', 'protected' => true, ); $acl[] = array( 'privilege' => '{DAV:}read', - 'principal' => $this->principalProperties['uri'] . '/calendar-proxy-write', + 'principal' => $this->principalProperties['uri'].'/calendar-proxy-write', 'protected' => true, ); + return $acl; - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php b/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php index 2ea078d7..68990a33 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCalendarComponentSet.php @@ -1,85 +1,77 @@ components = $components; - + public function __construct(array $components) + { + $this->components = $components; } /** - * Returns the list of supported components + * Returns the list of supported components. * * @return array */ - public function getValue() { - + public function getValue() + { return $this->components; - } /** - * Serializes the property in a DOMDocument + * Serializes the property in a DOMDocument. * * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void + * @param DOMElement $node */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - - $doc = $node->ownerDocument; - foreach($this->components as $component) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $node) + { + $doc = $node->ownerDocument; + foreach ($this->components as $component) { $xcomp = $doc->createElement('cal:comp'); - $xcomp->setAttribute('name',$component); + $xcomp->setAttribute('name', $component); $node->appendChild($xcomp); - - } - + } } /** * Unserializes the DOMElement back into a Property class. * * @param DOMElement $node + * * @return Sabre_CalDAV_Property_SupportedCalendarComponentSet */ - static function unserialize(DOMElement $node) { - + public static function unserialize(DOMElement $node) + { $components = array(); - foreach($node->childNodes as $childNode) { - if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)==='{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}comp') { + foreach ($node->childNodes as $childNode) { + if (Sabre_DAV_XMLUtil::toClarkNotation($childNode) === '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}comp') { $components[] = $childNode->getAttribute('name'); } } + return new self($components); - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCalendarData.php b/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCalendarData.php index 1d848dd5..cd3e68e0 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCalendarData.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCalendarData.php @@ -1,38 +1,34 @@ ownerDocument; - $prefix = isset($server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV])?$server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV]:'cal'; + $prefix = isset($server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV]) ? $server->xmlNamespaces[Sabre_CalDAV_Plugin::NS_CALDAV] : 'cal'; - $caldata = $doc->createElement($prefix . ':calendar-data'); - $caldata->setAttribute('content-type','text/calendar'); - $caldata->setAttribute('version','2.0'); + $caldata = $doc->createElement($prefix.':calendar-data'); + $caldata->setAttribute('content-type', 'text/calendar'); + $caldata->setAttribute('version', '2.0'); $node->appendChild($caldata); } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCollationSet.php b/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCollationSet.php index 24e84d4c..94686ed9 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCollationSet.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Property/SupportedCollationSet.php @@ -1,44 +1,40 @@ ownerDocument; $prefix = $node->lookupPrefix('urn:ietf:params:xml:ns:caldav'); - if (!$prefix) $prefix = 'cal'; + if (!$prefix) { + $prefix = 'cal'; + } $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;ascii-casemap') + $doc->createElement($prefix.':supported-collation', 'i;ascii-casemap') ); $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;octet') + $doc->createElement($prefix.':supported-collation', 'i;octet') ); $node->appendChild( - $doc->createElement($prefix . ':supported-collation','i;unicode-casemap') + $doc->createElement($prefix.':supported-collation', 'i;unicode-casemap') ); - - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/IMip.php b/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/IMip.php index f62f94af..c7d1615b 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/IMip.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/IMip.php @@ -12,14 +12,12 @@ use Sabre\VObject; * If you want to customize the email that gets sent out, you can do so by * extending this class and overriding the sendMessage method. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_Schedule_IMip { - +class Sabre_CalDAV_Schedule_IMip +{ /** * Email address used in From: header. * @@ -33,73 +31,64 @@ class Sabre_CalDAV_Schedule_IMip { * @param string $senderEmail. The 'senderEmail' is the email that shows up * in the 'From:' address. This should * generally be some kind of no-reply email - * address you own. + * address you own */ - public function __construct($senderEmail) { - + public function __construct($senderEmail) + { $this->senderEmail = $senderEmail; - } /** * Sends one or more iTip messages through email. * - * @param string $originator Originator Email - * @param array $recipients Array of email addresses + * @param string $originator Originator Email + * @param array $recipients Array of email addresses * @param Sabre\VObject\Component $vObject - * @param string $principal Principal Url of the originator - * @return void + * @param string $principal Principal Url of the originator */ - public function sendMessage($originator, array $recipients, VObject\Component $vObject, $principal) { - - foreach($recipients as $recipient) { - + public function sendMessage($originator, array $recipients, VObject\Component $vObject, $principal) + { + foreach ($recipients as $recipient) { $to = $recipient; $replyTo = $originator; $subject = 'SabreDAV iTIP message'; - switch(strtoupper($vObject->METHOD)) { - case 'REPLY' : - $subject = 'Response for: ' . $vObject->VEVENT->SUMMARY; + switch (strtoupper($vObject->METHOD)) { + case 'REPLY': + $subject = 'Response for: '.$vObject->VEVENT->SUMMARY; break; - case 'REQUEST' : - $subject = 'Invitation for: ' .$vObject->VEVENT->SUMMARY; + case 'REQUEST': + $subject = 'Invitation for: '.$vObject->VEVENT->SUMMARY; break; - case 'CANCEL' : - $subject = 'Cancelled event: ' . $vObject->VEVENT->SUMMARY; + case 'CANCEL': + $subject = 'Cancelled event: '.$vObject->VEVENT->SUMMARY; break; } $headers = array(); - $headers[] = 'Reply-To: ' . $replyTo; - $headers[] = 'From: ' . $this->senderEmail; - $headers[] = 'Content-Type: text/calendar; method=' . (string)$vObject->method . '; charset=utf-8'; + $headers[] = 'Reply-To: '.$replyTo; + $headers[] = 'From: '.$this->senderEmail; + $headers[] = 'Content-Type: text/calendar; method='.(string) $vObject->method.'; charset=utf-8'; if (Sabre_DAV_Server::$exposeVersion) { - $headers[] = 'X-Sabre-Version: ' . Sabre_DAV_Version::VERSION . '-' . Sabre_DAV_Version::STABILITY; + $headers[] = 'X-Sabre-Version: '.Sabre_DAV_Version::VERSION.'-'.Sabre_DAV_Version::STABILITY; } $vcalBody = $vObject->serialize(); $this->mail($to, $subject, $vcalBody, $headers); - } - } /** * This function is reponsible for sending the actual email. * - * @param string $to Recipient email address + * @param string $to Recipient email address * @param string $subject Subject of the email - * @param string $body iCalendar body - * @param array $headers List of headers - * @return void + * @param string $body iCalendar body + * @param array $headers List of headers */ - protected function mail($to, $subject, $body, array $headers) { - + protected function mail($to, $subject, $body, array $headers) + { mail($to, $subject, $body, implode("\r\n", $headers)); - } - - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/IOutbox.php b/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/IOutbox.php index 46d77514..1663d3af 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/IOutbox.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/IOutbox.php @@ -4,13 +4,10 @@ * Implement this interface to have a node be recognized as a CalDAV scheduling * outbox. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -interface Sabre_CalDAV_Schedule_IOutbox extends Sabre_DAV_ICollection, Sabre_DAVACL_IACL { - - +interface Sabre_CalDAV_Schedule_IOutbox extends Sabre_DAV_ICollection, Sabre_DAVACL_IACL +{ } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/Outbox.php b/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/Outbox.php index 09aa07d7..6f048086 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/Outbox.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Schedule/Outbox.php @@ -1,36 +1,33 @@ principalUri = $principalUri; - } /** @@ -40,47 +37,43 @@ class Sabre_CalDAV_Schedule_Outbox extends Sabre_DAV_Collection implements Sabre * * @return string */ - public function getName() { - + public function getName() + { return 'outbox'; - } /** - * Returns an array with all the child nodes + * Returns an array with all the child nodes. * * @return Sabre_DAV_INode[] */ - public function getChildren() { - + public function getChildren() + { return array(); - } /** - * Returns the owner principal + * Returns the owner principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getOwner() { - + public function getOwner() + { return $this->principalUri; - } /** - * Returns a group principal + * Returns a group principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getGroup() { - + public function getGroup() + { return null; - } /** @@ -95,11 +88,11 @@ class Sabre_CalDAV_Schedule_Outbox extends Sabre_DAV_Collection implements Sabre * * @return array */ - public function getACL() { - + public function getACL() + { return array( array( - 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}schedule-query-freebusy', + 'privilege' => '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}schedule-query-freebusy', 'principal' => $this->getOwner(), 'protected' => true, ), @@ -109,21 +102,18 @@ class Sabre_CalDAV_Schedule_Outbox extends Sabre_DAV_Collection implements Sabre 'protected' => true, ), ); - } /** - * Updates the ACL + * Updates the ACL. * * This method will receive a list of new ACE's. * * @param array $acl - * @return void */ - public function setACL(array $acl) { - + public function setACL(array $acl) + { throw new Sabre_DAV_Exception_MethodNotAllowed('You\'re not allowed to update the ACL'); - } /** @@ -138,15 +128,13 @@ class Sabre_CalDAV_Schedule_Outbox extends Sabre_DAV_Collection implements Sabre * * @return array|null */ - public function getSupportedPrivilegeSet() { - + public function getSupportedPrivilegeSet() + { $default = Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet(); $default['aggregates'][] = array( - 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}schedule-query-freebusy', + 'privilege' => '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}schedule-query-freebusy', ); return $default; - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Server.php b/dav/SabreDAV/lib/Sabre/CalDAV/Server.php index 325e3d80..6ebc1162 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Server.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Server.php @@ -1,7 +1,7 @@ authRealm); + $authPlugin = new Sabre_DAV_Auth_Plugin($authBackend, $this->authRealm); $this->addPlugin($authPlugin); $aclPlugin = new Sabre_DAVACL_Plugin(); @@ -62,7 +62,5 @@ class Sabre_CalDAV_Server extends Sabre_DAV_Server { $caldavPlugin = new Sabre_CalDAV_Plugin(); $this->addPlugin($caldavPlugin); - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/UserCalendars.php b/dav/SabreDAV/lib/Sabre/CalDAV/UserCalendars.php index da8c3b60..c74f3e6a 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/UserCalendars.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/UserCalendars.php @@ -1,96 +1,87 @@ principalBackend = $principalBackend; $this->caldavBackend = $caldavBackend; $this->principalInfo = $principalBackend->getPrincipalByPath($userUri); - } /** - * Returns the name of this object + * Returns the name of this object. * * @return string */ - public function getName() { + public function getName() + { + list(, $name) = Sabre_DAV_URLUtil::splitPath($this->principalInfo['uri']); - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalInfo['uri']); return $name; - } /** - * Updates the name of this object + * Updates the name of this object. * * @param string $name - * @return void */ - public function setName($name) { - + public function setName($name) + { throw new Sabre_DAV_Exception_Forbidden(); - } /** - * Deletes this object - * - * @return void + * Deletes this object. */ - public function delete() { - + public function delete() + { throw new Sabre_DAV_Exception_Forbidden(); - } /** - * Returns the last modification date + * Returns the last modification date. * * @return int */ - public function getLastModified() { - + public function getLastModified() + { return null; - } /** @@ -98,14 +89,12 @@ class Sabre_CalDAV_UserCalendars implements Sabre_DAV_IExtendedCollection, Sabre * * This is currently not allowed * - * @param string $filename + * @param string $filename * @param resource $data - * @return void */ - public function createFile($filename, $data=null) { - + public function createFile($filename, $data = null) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); - } /** @@ -114,60 +103,61 @@ class Sabre_CalDAV_UserCalendars implements Sabre_DAV_IExtendedCollection, Sabre * This is currently not allowed. * * @param string $filename - * @return void */ - public function createDirectory($filename) { - + public function createDirectory($filename) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); - } /** - * Returns a single calendar, by name + * Returns a single calendar, by name. * * @param string $name + * * @todo needs optimizing + * * @return Sabre_CalDAV_Calendar */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) + public function getChild($name) + { + foreach ($this->getChildren() as $child) { + if ($name == $child->getName()) { return $child; - + } } - throw new Sabre_DAV_Exception_NotFound('Calendar with name \'' . $name . '\' could not be found'); - + throw new Sabre_DAV_Exception_NotFound('Calendar with name \''.$name.'\' could not be found'); } /** * Checks if a calendar exists. * * @param string $name + * * @todo needs optimizing + * * @return bool */ - public function childExists($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) + public function childExists($name) + { + foreach ($this->getChildren() as $child) { + if ($name == $child->getName()) { return true; - + } } - return false; + return false; } /** - * Returns a list of calendars + * Returns a list of calendars. * * @return array */ - public function getChildren() { - + public function getChildren() + { $calendars = $this->caldavBackend->getCalendarsForUser($this->principalInfo['uri']); $objs = array(); - foreach($calendars as $calendar) { + foreach ($calendars as $calendar) { $objs[] = new Sabre_CalDAV_Calendar($this->principalBackend, $this->caldavBackend, $calendar); } $objs[] = new Sabre_CalDAV_Schedule_Outbox($this->principalInfo['uri']); @@ -176,51 +166,47 @@ class Sabre_CalDAV_UserCalendars implements Sabre_DAV_IExtendedCollection, Sabre if ($this->caldavBackend instanceof Sabre_CalDAV_Backend_NotificationSupport) { $objs[] = new Sabre_CalDAV_Notifications_Collection($this->caldavBackend, $this->principalInfo['uri']); } - return $objs; + return $objs; } /** - * Creates a new calendar + * Creates a new calendar. * * @param string $name - * @param array $resourceType - * @param array $properties - * @return void + * @param array $resourceType + * @param array $properties */ - public function createExtendedCollection($name, array $resourceType, array $properties) { - - if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar',$resourceType) || count($resourceType)!==2) { + public function createExtendedCollection($name, array $resourceType, array $properties) + { + if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar', $resourceType) || count($resourceType) !== 2) { throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); } $this->caldavBackend->createCalendar($this->principalInfo['uri'], $name, $properties); - } /** - * Returns the owner principal + * Returns the owner principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getOwner() { - + public function getOwner() + { return $this->principalInfo['uri']; - } /** - * Returns a group principal + * Returns a group principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getGroup() { - + public function getGroup() + { return null; - } /** @@ -235,8 +221,8 @@ class Sabre_CalDAV_UserCalendars implements Sabre_DAV_IExtendedCollection, Sabre * * @return array */ - public function getACL() { - + public function getACL() + { return array( array( 'privilege' => '{DAV:}read', @@ -250,36 +236,33 @@ class Sabre_CalDAV_UserCalendars implements Sabre_DAV_IExtendedCollection, Sabre ), array( 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', + 'principal' => $this->principalInfo['uri'].'/calendar-proxy-write', 'protected' => true, ), array( 'privilege' => '{DAV:}write', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', + 'principal' => $this->principalInfo['uri'].'/calendar-proxy-write', 'protected' => true, ), array( 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-read', + 'principal' => $this->principalInfo['uri'].'/calendar-proxy-read', 'protected' => true, ), ); - } /** - * Updates the ACL + * Updates the ACL. * * This method will receive a list of new ACE's. * * @param array $acl - * @return void */ - public function setACL(array $acl) { - + public function setACL(array $acl) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - } /** @@ -294,10 +277,8 @@ class Sabre_CalDAV_UserCalendars implements Sabre_DAV_IExtendedCollection, Sabre * * @return array|null */ - public function getSupportedPrivilegeSet() { - + public function getSupportedPrivilegeSet() + { return null; - } - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/Version.php b/dav/SabreDAV/lib/Sabre/CalDAV/Version.php index d862da81..4ed59ddd 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/Version.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/Version.php @@ -3,22 +3,19 @@ /** * This class contains the Sabre_CalDAV version constants. * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_Version { - +class Sabre_CalDAV_Version +{ /** - * Full version number + * Full version number. */ const VERSION = '1.7.0'; /** - * Stability : alpha, beta, stable + * Stability : alpha, beta, stable. */ const STABILITY = 'alpha'; - } diff --git a/dav/SabreDAV/lib/Sabre/CalDAV/includes.php b/dav/SabreDAV/lib/Sabre/CalDAV/includes.php index 1ecb870a..0e621a09 100644 --- a/dav/SabreDAV/lib/Sabre/CalDAV/includes.php +++ b/dav/SabreDAV/lib/Sabre/CalDAV/includes.php @@ -1,43 +1,41 @@ carddavBackend = $carddavBackend; $this->addressBookInfo = $addressBookInfo; - } /** - * Returns the name of the addressbook + * Returns the name of the addressbook. * * @return string */ - public function getName() { - + public function getName() + { return $this->addressBookInfo['uri']; - } /** - * Returns a card + * Returns a card. * * @param string $name + * * @return Sabre_CardDAV_ICard */ - public function getChild($name) { - - $obj = $this->carddavBackend->getCard($this->addressBookInfo['id'],$name); - if (!$obj) throw new Sabre_DAV_Exception_NotFound('Card not found'); - return new Sabre_CardDAV_Card($this->carddavBackend,$this->addressBookInfo,$obj); + public function getChild($name) + { + $obj = $this->carddavBackend->getCard($this->addressBookInfo['id'], $name); + if (!$obj) { + throw new Sabre_DAV_Exception_NotFound('Card not found'); + } + return new Sabre_CardDAV_Card($this->carddavBackend, $this->addressBookInfo, $obj); } /** - * Returns the full list of cards + * Returns the full list of cards. * * @return array */ - public function getChildren() { - + public function getChildren() + { $objs = $this->carddavBackend->getCards($this->addressBookInfo['id']); $children = array(); - foreach($objs as $obj) { - $children[] = new Sabre_CardDAV_Card($this->carddavBackend,$this->addressBookInfo,$obj); + foreach ($objs as $obj) { + $children[] = new Sabre_CardDAV_Card($this->carddavBackend, $this->addressBookInfo, $obj); } - return $children; + return $children; } /** - * Creates a new directory + * Creates a new directory. * * We actually block this, as subdirectories are not allowed in addressbooks. * * @param string $name - * @return void */ - public function createDirectory($name) { - + public function createDirectory($name) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Creating collections in addressbooks is not allowed'); - } /** - * Creates a new file + * Creates a new file. * * The contents of the new file must be a valid VCARD. * * This method may return an ETag. * - * @param string $name + * @param string $name * @param resource $vcardData + * * @return string|null */ - public function createFile($name,$vcardData = null) { - + public function createFile($name, $vcardData = null) + { if (is_resource($vcardData)) { $vcardData = stream_get_contents($vcardData); } // Converting to UTF-8, if needed $vcardData = Sabre_DAV_StringUtil::ensureUTF8($vcardData); - return $this->carddavBackend->createCard($this->addressBookInfo['id'],$name,$vcardData); - + return $this->carddavBackend->createCard($this->addressBookInfo['id'], $name, $vcardData); } /** * Deletes the entire addressbook. - * - * @return void */ - public function delete() { - + public function delete() + { $this->carddavBackend->deleteAddressBook($this->addressBookInfo['id']); - } /** - * Renames the addressbook + * Renames the addressbook. * * @param string $newName - * @return void */ - public function setName($newName) { - + public function setName($newName) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Renaming addressbooks is not yet supported'); - } /** * Returns the last modification date as a unix timestamp. - * - * @return void */ - public function getLastModified() { - + public function getLastModified() + { return null; - } /** - * Updates properties on this node, + * Updates properties on this node,. * * The properties array uses the propertyName in clark-notation as key, * and the array value for the property value. In the case a property @@ -185,12 +174,12 @@ class Sabre_CardDAV_AddressBook extends Sabre_DAV_Collection implements Sabre_Ca * (424 Failed Dependency) because the request needs to be atomic. * * @param array $mutations + * * @return bool|array */ - public function updateProperties($mutations) { - + public function updateProperties($mutations) + { return $this->carddavBackend->updateAddressBook($this->addressBookInfo['id'], $mutations); - } /** @@ -202,49 +191,43 @@ class Sabre_CardDAV_AddressBook extends Sabre_DAV_Collection implements Sabre_Ca * If the array is empty, it means 'all properties' were requested. * * @param array $properties + * * @return array */ - public function getProperties($properties) { - + public function getProperties($properties) + { $response = array(); - foreach($properties as $propertyName) { - + foreach ($properties as $propertyName) { if (isset($this->addressBookInfo[$propertyName])) { - $response[$propertyName] = $this->addressBookInfo[$propertyName]; - } - } return $response; - } /** - * Returns the owner principal + * Returns the owner principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getOwner() { - + public function getOwner() + { return $this->addressBookInfo['principaluri']; - } /** - * Returns a group principal + * Returns a group principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getGroup() { - + public function getGroup() + { return null; - } /** @@ -259,8 +242,8 @@ class Sabre_CardDAV_AddressBook extends Sabre_DAV_Collection implements Sabre_Ca * * @return array */ - public function getACL() { - + public function getACL() + { return array( array( 'privilege' => '{DAV:}read', @@ -274,21 +257,18 @@ class Sabre_CardDAV_AddressBook extends Sabre_DAV_Collection implements Sabre_Ca ), ); - } /** - * Updates the ACL + * Updates the ACL. * * This method will receive a list of new ACE's. * * @param array $acl - * @return void */ - public function setACL(array $acl) { - + public function setACL(array $acl) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - } /** @@ -303,10 +283,8 @@ class Sabre_CardDAV_AddressBook extends Sabre_DAV_Collection implements Sabre_Ca * * @return array|null */ - public function getSupportedPrivilegeSet() { - + public function getSupportedPrivilegeSet() + { return null; - } - } diff --git a/dav/SabreDAV/lib/Sabre/CardDAV/AddressBookQueryParser.php b/dav/SabreDAV/lib/Sabre/CardDAV/AddressBookQueryParser.php index 46bb8ff1..bda91b8b 100644 --- a/dav/SabreDAV/lib/Sabre/CardDAV/AddressBookQueryParser.php +++ b/dav/SabreDAV/lib/Sabre/CardDAV/AddressBookQueryParser.php @@ -6,26 +6,24 @@ * Whoever designed this format, and the CalDAV equivalent even more so, * has no feel for design. * - * @package Sabre - * @subpackage CardDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CardDAV_AddressBookQueryParser { - +class Sabre_CardDAV_AddressBookQueryParser +{ const TEST_ANYOF = 'anyof'; const TEST_ALLOF = 'allof'; /** - * List of requested properties the client wanted + * List of requested properties the client wanted. * * @var array */ public $requestedProperties; /** - * The number of results the client wants + * The number of results the client wants. * * null means it wasn't specified, which in most cases means 'all results'. * @@ -41,58 +39,57 @@ class Sabre_CardDAV_AddressBookQueryParser { public $filters; /** - * Either TEST_ANYOF or TEST_ALLOF + * Either TEST_ANYOF or TEST_ALLOF. * * @var string */ public $test; /** - * DOM Document + * DOM Document. * * @var DOMDocument */ protected $dom; /** - * DOM XPath object + * DOM XPath object. * * @var DOMXPath */ protected $xpath; /** - * Creates the parser + * Creates the parser. * * @param DOMDocument $dom */ - public function __construct(DOMDocument $dom) { - + public function __construct(DOMDocument $dom) + { $this->dom = $dom; $this->xpath = new DOMXPath($dom); - $this->xpath->registerNameSpace('card',Sabre_CardDAV_Plugin::NS_CARDDAV); - + $this->xpath->registerNameSpace('card', Sabre_CardDAV_Plugin::NS_CARDDAV); } /** * Parses the request. - * - * @return void */ - public function parse() { - + public function parse() + { $filterNode = null; $limit = $this->xpath->evaluate('number(/card:addressbook-query/card:limit/card:nresults)'); - if (is_nan($limit)) $limit = null; + if (is_nan($limit)) { + $limit = null; + } $filter = $this->xpath->query('/card:addressbook-query/card:filter'); // According to the CardDAV spec there needs to be exactly 1 filter // element. However, KDE 4.8.2 contains a bug that will encode 0 filter // elements, so this is a workaround for that. - // + // See: https://bugs.kde.org/show_bug.cgi?id=300047 if ($filter->length === 0) { $test = null; @@ -104,7 +101,9 @@ class Sabre_CardDAV_AddressBookQueryParser { throw new Sabre_DAV_Exception_BadRequest('Only one filter element is allowed'); } - if (!$test) $test = self::TEST_ANYOF; + if (!$test) { + $test = self::TEST_ANYOF; + } if ($test !== self::TEST_ANYOF && $test !== self::TEST_ALLOF) { throw new Sabre_DAV_Exception_BadRequest('The test attribute must either hold "anyof" or "allof"'); } @@ -112,108 +111,103 @@ class Sabre_CardDAV_AddressBookQueryParser { $propFilters = array(); $propFilterNodes = $this->xpath->query('card:prop-filter', $filter); - for($ii=0; $ii < $propFilterNodes->length; $ii++) { - + for ($ii = 0; $ii < $propFilterNodes->length; ++$ii) { $propFilters[] = $this->parsePropFilterNode($propFilterNodes->item($ii)); - - } $this->filters = $propFilters; $this->limit = $limit; $this->requestedProperties = array_keys(Sabre_DAV_XMLUtil::parseProperties($this->dom->firstChild)); $this->test = $test; - } /** - * Parses the prop-filter xml element + * Parses the prop-filter xml element. * * @param DOMElement $propFilterNode + * * @return array */ - protected function parsePropFilterNode(DOMElement $propFilterNode) { - + protected function parsePropFilterNode(DOMElement $propFilterNode) + { $propFilter = array(); $propFilter['name'] = $propFilterNode->getAttribute('name'); $propFilter['test'] = $propFilterNode->getAttribute('test'); - if (!$propFilter['test']) $propFilter['test'] = 'anyof'; + if (!$propFilter['test']) { + $propFilter['test'] = 'anyof'; + } - $propFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $propFilterNode)->length>0; + $propFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $propFilterNode)->length > 0; $paramFilterNodes = $this->xpath->query('card:param-filter', $propFilterNode); $propFilter['param-filters'] = array(); - - for($ii=0;$ii<$paramFilterNodes->length;$ii++) { - + for ($ii = 0; $ii < $paramFilterNodes->length; ++$ii) { $propFilter['param-filters'][] = $this->parseParamFilterNode($paramFilterNodes->item($ii)); - } $propFilter['text-matches'] = array(); $textMatchNodes = $this->xpath->query('card:text-match', $propFilterNode); - for($ii=0;$ii<$textMatchNodes->length;$ii++) { - + for ($ii = 0; $ii < $textMatchNodes->length; ++$ii) { $propFilter['text-matches'][] = $this->parseTextMatchNode($textMatchNodes->item($ii)); - } return $propFilter; - } /** - * Parses the param-filter element + * Parses the param-filter element. * * @param DOMElement $paramFilterNode + * * @return array */ - public function parseParamFilterNode(DOMElement $paramFilterNode) { - + public function parseParamFilterNode(DOMElement $paramFilterNode) + { $paramFilter = array(); $paramFilter['name'] = $paramFilterNode->getAttribute('name'); - $paramFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $paramFilterNode)->length>0; + $paramFilter['is-not-defined'] = $this->xpath->query('card:is-not-defined', $paramFilterNode)->length > 0; $paramFilter['text-match'] = null; $textMatch = $this->xpath->query('card:text-match', $paramFilterNode); - if ($textMatch->length>0) { + if ($textMatch->length > 0) { $paramFilter['text-match'] = $this->parseTextMatchNode($textMatch->item(0)); } return $paramFilter; - } /** - * Text match + * Text match. * * @param DOMElement $textMatchNode + * * @return array */ - public function parseTextMatchNode(DOMElement $textMatchNode) { - + public function parseTextMatchNode(DOMElement $textMatchNode) + { $matchType = $textMatchNode->getAttribute('match-type'); - if (!$matchType) $matchType = 'contains'; + if (!$matchType) { + $matchType = 'contains'; + } if (!in_array($matchType, array('contains', 'equals', 'starts-with', 'ends-with'))) { - throw new Sabre_DAV_Exception_BadRequest('Unknown match-type: ' . $matchType); + throw new Sabre_DAV_Exception_BadRequest('Unknown match-type: '.$matchType); } $negateCondition = $textMatchNode->getAttribute('negate-condition'); - $negateCondition = $negateCondition==='yes'; + $negateCondition = $negateCondition === 'yes'; $collation = $textMatchNode->getAttribute('collation'); - if (!$collation) $collation = 'i;unicode-casemap'; + if (!$collation) { + $collation = 'i;unicode-casemap'; + } return array( 'negate-condition' => $negateCondition, 'collation' => $collation, 'match-type' => $matchType, - 'value' => $textMatchNode->nodeValue + 'value' => $textMatchNode->nodeValue, ); - - } - } diff --git a/dav/SabreDAV/lib/Sabre/CardDAV/AddressBookRoot.php b/dav/SabreDAV/lib/Sabre/CardDAV/AddressBookRoot.php index 9d37b15f..85b9323d 100644 --- a/dav/SabreDAV/lib/Sabre/CardDAV/AddressBookRoot.php +++ b/dav/SabreDAV/lib/Sabre/CardDAV/AddressBookRoot.php @@ -1,34 +1,32 @@ carddavBackend = $carddavBackend; parent::__construct($principalBackend, $principalPrefix); - } /** - * Returns the name of the node + * Returns the name of the node. * * @return string */ - public function getName() { - + public function getName() + { return Sabre_CardDAV_Plugin::ADDRESSBOOK_ROOT; - } /** @@ -67,12 +63,11 @@ class Sabre_CardDAV_AddressBookRoot extends Sabre_DAVACL_AbstractPrincipalCollec * supplied by the authentication backend. * * @param array $principal + * * @return Sabre_DAV_INode */ - public function getChildForPrincipal(array $principal) { - + public function getChildForPrincipal(array $principal) + { return new Sabre_CardDAV_UserAddressBooks($this->carddavBackend, $principal['uri']); - } - } diff --git a/dav/SabreDAV/lib/Sabre/CardDAV/Backend/Abstract.php b/dav/SabreDAV/lib/Sabre/CardDAV/Backend/Abstract.php index e4806b71..25533bdc 100644 --- a/dav/SabreDAV/lib/Sabre/CardDAV/Backend/Abstract.php +++ b/dav/SabreDAV/lib/Sabre/CardDAV/Backend/Abstract.php @@ -1,7 +1,7 @@ pdo = $pdo; $this->addressBooksTableName = $addressBooksTableName; $this->cardsTableName = $cardsTableName; - } /** * Returns the list of addressbooks for a specific user. * * @param string $principalUri + * * @return array */ - public function getAddressBooksForUser($principalUri) { - + public function getAddressBooksForUser($principalUri) + { $stmt = $this->pdo->prepare('SELECT id, uri, displayname, principaluri, description, ctag FROM '.$this->addressBooksTableName.' WHERE principaluri = ?'); $stmt->execute(array($principalUri)); $addressBooks = array(); - foreach($stmt->fetchAll() as $row) { - + foreach ($stmt->fetchAll() as $row) { $addressBooks[] = array( - 'id' => $row['id'], + 'id' => $row['id'], 'uri' => $row['uri'], 'principaluri' => $row['principaluri'], '{DAV:}displayname' => $row['displayname'], - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'], + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'], '{http://calendarserver.org/ns/}getctag' => $row['ctag'], - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => - new Sabre_CardDAV_Property_SupportedAddressData(), + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), ); - } return $addressBooks; - } - /** - * Updates an addressbook's properties + * Updates an addressbook's properties. * * See Sabre_DAV_IProperties for a description of the mutations array, as * well as the return value. * * @param mixed $addressBookId * @param array $mutations + * * @see Sabre_DAV_IProperties::updateProperties + * * @return bool|array */ - public function updateAddressBook($addressBookId, array $mutations) { - + public function updateAddressBook($addressBookId, array $mutations) + { $updates = array(); - foreach($mutations as $property=>$newValue) { - - switch($property) { - case '{DAV:}displayname' : + foreach ($mutations as $property => $newValue) { + switch ($property) { + case '{DAV:}displayname': $updates['displayname'] = $newValue; break; - case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : + case '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description': $updates['description'] = $newValue; break; - default : + default: // If any unsupported values were being updated, we must // let the entire request fail. return false; } - } // No values are being updated? @@ -115,11 +108,11 @@ class Sabre_CardDAV_Backend_PDO extends Sabre_CardDAV_Backend_Abstract { return false; } - $query = 'UPDATE ' . $this->addressBooksTableName . ' SET ctag = ctag + 1 '; - foreach($updates as $key=>$value) { - $query.=', `' . $key . '` = :' . $key . ' '; + $query = 'UPDATE '.$this->addressBooksTableName.' SET ctag = ctag + 1 '; + foreach ($updates as $key => $value) { + $query .= ', `'.$key.'` = :'.$key.' '; } - $query.=' WHERE id = :addressbookid'; + $query .= ' WHERE id = :addressbookid'; $stmt = $this->pdo->prepare($query); $updates['addressbookid'] = $addressBookId; @@ -127,19 +120,17 @@ class Sabre_CardDAV_Backend_PDO extends Sabre_CardDAV_Backend_Abstract { $stmt->execute($updates); return true; - } /** - * Creates a new address book + * Creates a new address book. * * @param string $principalUri - * @param string $url Just the 'basename' of the url. - * @param array $properties - * @return void + * @param string $url Just the 'basename' of the url + * @param array $properties */ - public function createAddressBook($principalUri, $url, array $properties) { - + public function createAddressBook($principalUri, $url, array $properties) + { $values = array( 'displayname' => null, 'description' => null, @@ -147,41 +138,36 @@ class Sabre_CardDAV_Backend_PDO extends Sabre_CardDAV_Backend_Abstract { 'uri' => $url, ); - foreach($properties as $property=>$newValue) { - - switch($property) { - case '{DAV:}displayname' : + foreach ($properties as $property => $newValue) { + switch ($property) { + case '{DAV:}displayname': $values['displayname'] = $newValue; break; - case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : + case '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description': $values['description'] = $newValue; break; - default : - throw new Sabre_DAV_Exception_BadRequest('Unknown property: ' . $property); + default: + throw new Sabre_DAV_Exception_BadRequest('Unknown property: '.$property); } - } - $query = 'INSERT INTO ' . $this->addressBooksTableName . ' (uri, displayname, description, principaluri, ctag) VALUES (:uri, :displayname, :description, :principaluri, 1)'; + $query = 'INSERT INTO '.$this->addressBooksTableName.' (uri, displayname, description, principaluri, ctag) VALUES (:uri, :displayname, :description, :principaluri, 1)'; $stmt = $this->pdo->prepare($query); $stmt->execute($values); - } /** - * Deletes an entire addressbook and all its contents + * Deletes an entire addressbook and all its contents. * * @param int $addressBookId - * @return void */ - public function deleteAddressBook($addressBookId) { - - $stmt = $this->pdo->prepare('DELETE FROM ' . $this->cardsTableName . ' WHERE addressbookid = ?'); + public function deleteAddressBook($addressBookId) + { + $stmt = $this->pdo->prepare('DELETE FROM '.$this->cardsTableName.' WHERE addressbookid = ?'); $stmt->execute(array($addressBookId)); - $stmt = $this->pdo->prepare('DELETE FROM ' . $this->addressBooksTableName . ' WHERE id = ?'); + $stmt = $this->pdo->prepare('DELETE FROM '.$this->addressBooksTableName.' WHERE id = ?'); $stmt->execute(array($addressBookId)); - } /** @@ -201,16 +187,15 @@ class Sabre_CardDAV_Backend_PDO extends Sabre_CardDAV_Backend_Abstract { * This may speed up certain requests, especially with large cards. * * @param mixed $addressbookId + * * @return array */ - public function getCards($addressbookId) { - - $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM ' . $this->cardsTableName . ' WHERE addressbookid = ?'); + public function getCards($addressbookId) + { + $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM '.$this->cardsTableName.' WHERE addressbookid = ?'); $stmt->execute(array($addressbookId)); return $stmt->fetchAll(PDO::FETCH_ASSOC); - - } /** @@ -219,19 +204,19 @@ class Sabre_CardDAV_Backend_PDO extends Sabre_CardDAV_Backend_Abstract { * The same set of properties must be returned as with getCards. The only * exception is that 'carddata' is absolutely required. * - * @param mixed $addressBookId + * @param mixed $addressBookId * @param string $cardUri + * * @return array */ - public function getCard($addressBookId, $cardUri) { - - $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM ' . $this->cardsTableName . ' WHERE addressbookid = ? AND uri = ? LIMIT 1'); + public function getCard($addressBookId, $cardUri) + { + $stmt = $this->pdo->prepare('SELECT id, carddata, uri, lastmodified FROM '.$this->cardsTableName.' WHERE addressbookid = ? AND uri = ? LIMIT 1'); $stmt->execute(array($addressBookId, $cardUri)); $result = $stmt->fetchAll(PDO::FETCH_ASSOC); - return (count($result)>0?$result[0]:false); - + return count($result) > 0 ? $result[0] : false; } /** @@ -254,22 +239,22 @@ class Sabre_CardDAV_Backend_PDO extends Sabre_CardDAV_Backend_Abstract { * * If you don't return an ETag, you can just return null. * - * @param mixed $addressBookId + * @param mixed $addressBookId * @param string $cardUri * @param string $cardData + * * @return string|null */ - public function createCard($addressBookId, $cardUri, $cardData) { - - $stmt = $this->pdo->prepare('INSERT INTO ' . $this->cardsTableName . ' (carddata, uri, lastmodified, addressbookid) VALUES (?, ?, ?, ?)'); + public function createCard($addressBookId, $cardUri, $cardData) + { + $stmt = $this->pdo->prepare('INSERT INTO '.$this->cardsTableName.' (carddata, uri, lastmodified, addressbookid) VALUES (?, ?, ?, ?)'); $result = $stmt->execute(array($cardData, $cardUri, time(), $addressBookId)); - $stmt2 = $this->pdo->prepare('UPDATE ' . $this->addressBooksTableName . ' SET ctag = ctag + 1 WHERE id = ?'); + $stmt2 = $this->pdo->prepare('UPDATE '.$this->addressBooksTableName.' SET ctag = ctag + 1 WHERE id = ?'); $stmt2->execute(array($addressBookId)); - return '"' . md5($cardData) . '"'; - + return '"'.md5($cardData).'"'; } /** @@ -292,39 +277,39 @@ class Sabre_CardDAV_Backend_PDO extends Sabre_CardDAV_Backend_Abstract { * * If you don't return an ETag, you can just return null. * - * @param mixed $addressBookId + * @param mixed $addressBookId * @param string $cardUri * @param string $cardData + * * @return string|null */ - public function updateCard($addressBookId, $cardUri, $cardData) { - - $stmt = $this->pdo->prepare('UPDATE ' . $this->cardsTableName . ' SET carddata = ?, lastmodified = ? WHERE uri = ? AND addressbookid =?'); + public function updateCard($addressBookId, $cardUri, $cardData) + { + $stmt = $this->pdo->prepare('UPDATE '.$this->cardsTableName.' SET carddata = ?, lastmodified = ? WHERE uri = ? AND addressbookid =?'); $stmt->execute(array($cardData, time(), $cardUri, $addressBookId)); - $stmt2 = $this->pdo->prepare('UPDATE ' . $this->addressBooksTableName . ' SET ctag = ctag + 1 WHERE id = ?'); + $stmt2 = $this->pdo->prepare('UPDATE '.$this->addressBooksTableName.' SET ctag = ctag + 1 WHERE id = ?'); $stmt2->execute(array($addressBookId)); - return '"' . md5($cardData) . '"'; - + return '"'.md5($cardData).'"'; } /** - * Deletes a card + * Deletes a card. * - * @param mixed $addressBookId + * @param mixed $addressBookId * @param string $cardUri + * * @return bool */ - public function deleteCard($addressBookId, $cardUri) { - - $stmt = $this->pdo->prepare('DELETE FROM ' . $this->cardsTableName . ' WHERE addressbookid = ? AND uri = ?'); + public function deleteCard($addressBookId, $cardUri) + { + $stmt = $this->pdo->prepare('DELETE FROM '.$this->cardsTableName.' WHERE addressbookid = ? AND uri = ?'); $stmt->execute(array($addressBookId, $cardUri)); - $stmt2 = $this->pdo->prepare('UPDATE ' . $this->addressBooksTableName . ' SET ctag = ctag + 1 WHERE id = ?'); + $stmt2 = $this->pdo->prepare('UPDATE '.$this->addressBooksTableName.' SET ctag = ctag + 1 WHERE id = ?'); $stmt2->execute(array($addressBookId)); - return $stmt->rowCount()===1; - + return $stmt->rowCount() === 1; } } diff --git a/dav/SabreDAV/lib/Sabre/CardDAV/Card.php b/dav/SabreDAV/lib/Sabre/CardDAV/Card.php index 36ae24db..35dcbd7a 100644 --- a/dav/SabreDAV/lib/Sabre/CardDAV/Card.php +++ b/dav/SabreDAV/lib/Sabre/CardDAV/Card.php @@ -1,188 +1,177 @@ carddavBackend = $carddavBackend; $this->addressBookInfo = $addressBookInfo; $this->cardData = $cardData; - } /** - * Returns the uri for this object + * Returns the uri for this object. * * @return string */ - public function getName() { - + public function getName() + { return $this->cardData['uri']; - } /** - * Returns the VCard-formatted object + * Returns the VCard-formatted object. * * @return string */ - public function get() { + public function get() + { // Pre-populating 'carddata' is optional. If we don't yet have it // already, we fetch it from the backend. if (!isset($this->cardData['carddata'])) { $this->cardData = $this->carddavBackend->getCard($this->addressBookInfo['id'], $this->cardData['uri']); } - return $this->cardData['carddata']; + return $this->cardData['carddata']; } /** - * Updates the VCard-formatted object + * Updates the VCard-formatted object. * * @param string $cardData + * * @return string|null */ - public function put($cardData) { - - if (is_resource($cardData)) + public function put($cardData) + { + if (is_resource($cardData)) { $cardData = stream_get_contents($cardData); + } // Converting to UTF-8, if needed $cardData = Sabre_DAV_StringUtil::ensureUTF8($cardData); - $etag = $this->carddavBackend->updateCard($this->addressBookInfo['id'],$this->cardData['uri'],$cardData); + $etag = $this->carddavBackend->updateCard($this->addressBookInfo['id'], $this->cardData['uri'], $cardData); $this->cardData['carddata'] = $cardData; $this->cardData['etag'] = $etag; return $etag; - } /** - * Deletes the card - * - * @return void + * Deletes the card. */ - public function delete() { - - $this->carddavBackend->deleteCard($this->addressBookInfo['id'],$this->cardData['uri']); - + public function delete() + { + $this->carddavBackend->deleteCard($this->addressBookInfo['id'], $this->cardData['uri']); } /** - * Returns the mime content-type + * Returns the mime content-type. * * @return string */ - public function getContentType() { - + public function getContentType() + { return 'text/x-vcard; charset=utf-8'; - } /** - * Returns an ETag for this object + * Returns an ETag for this object. * * @return string */ - public function getETag() { - + public function getETag() + { if (isset($this->cardData['etag'])) { return $this->cardData['etag']; } else { - return '"' . md5($this->get()) . '"'; + return '"'.md5($this->get()).'"'; } - } /** - * Returns the last modification date as a unix timestamp + * Returns the last modification date as a unix timestamp. * * @return int */ - public function getLastModified() { - - return isset($this->cardData['lastmodified'])?$this->cardData['lastmodified']:null; - + public function getLastModified() + { + return isset($this->cardData['lastmodified']) ? $this->cardData['lastmodified'] : null; } /** - * Returns the size of this object in bytes + * Returns the size of this object in bytes. * * @return int */ - public function getSize() { - + public function getSize() + { if (array_key_exists('size', $this->cardData)) { return $this->cardData['size']; } else { return strlen($this->get()); } - } /** - * Returns the owner principal + * Returns the owner principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getOwner() { - + public function getOwner() + { return $this->addressBookInfo['principaluri']; - } /** - * Returns a group principal + * Returns a group principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getGroup() { - + public function getGroup() + { return null; - } /** @@ -197,8 +186,8 @@ class Sabre_CardDAV_Card extends Sabre_DAV_File implements Sabre_CardDAV_ICard, * * @return array */ - public function getACL() { - + public function getACL() + { return array( array( 'privilege' => '{DAV:}read', @@ -211,21 +200,18 @@ class Sabre_CardDAV_Card extends Sabre_DAV_File implements Sabre_CardDAV_ICard, 'protected' => true, ), ); - } /** - * Updates the ACL + * Updates the ACL. * * This method will receive a list of new ACE's. * * @param array $acl - * @return void */ - public function setACL(array $acl) { - + public function setACL(array $acl) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - } /** @@ -240,11 +226,8 @@ class Sabre_CardDAV_Card extends Sabre_DAV_File implements Sabre_CardDAV_ICard, * * @return array|null */ - public function getSupportedPrivilegeSet() { - + public function getSupportedPrivilegeSet() + { return null; - } - } - diff --git a/dav/SabreDAV/lib/Sabre/CardDAV/IAddressBook.php b/dav/SabreDAV/lib/Sabre/CardDAV/IAddressBook.php index 2bc275bc..38998155 100644 --- a/dav/SabreDAV/lib/Sabre/CardDAV/IAddressBook.php +++ b/dav/SabreDAV/lib/Sabre/CardDAV/IAddressBook.php @@ -1,18 +1,14 @@ subscribeEvent('beforeGetProperties', array($this, 'beforeGetProperties')); $server->subscribeEvent('afterGetProperties', array($this, 'afterGetProperties')); $server->subscribeEvent('updateProperties', array($this, 'updateProperties')); - $server->subscribeEvent('report', array($this,'report')); - $server->subscribeEvent('onHTMLActionsPanel', array($this,'htmlActionsPanel')); - $server->subscribeEvent('onBrowserPostAction', array($this,'browserPostAction')); + $server->subscribeEvent('report', array($this, 'report')); + $server->subscribeEvent('onHTMLActionsPanel', array($this, 'htmlActionsPanel')); + $server->subscribeEvent('onBrowserPostAction', array($this, 'browserPostAction')); $server->subscribeEvent('beforeWriteContent', array($this, 'beforeWriteContent')); $server->subscribeEvent('beforeCreateFile', array($this, 'beforeCreateFile')); @@ -62,19 +60,18 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { $server->xmlNamespaces[self::NS_CARDDAV] = 'card'; /* Mapping Interfaces to {DAV:}resourcetype values */ - $server->resourceTypeMapping['Sabre_CardDAV_IAddressBook'] = '{' . self::NS_CARDDAV . '}addressbook'; - $server->resourceTypeMapping['Sabre_CardDAV_IDirectory'] = '{' . self::NS_CARDDAV . '}directory'; + $server->resourceTypeMapping['Sabre_CardDAV_IAddressBook'] = '{'.self::NS_CARDDAV.'}addressbook'; + $server->resourceTypeMapping['Sabre_CardDAV_IDirectory'] = '{'.self::NS_CARDDAV.'}directory'; /* Adding properties that may never be changed */ - $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}supported-address-data'; - $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}max-resource-size'; - $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}addressbook-home-set'; - $server->protectedProperties[] = '{' . self::NS_CARDDAV . '}supported-collation-set'; + $server->protectedProperties[] = '{'.self::NS_CARDDAV.'}supported-address-data'; + $server->protectedProperties[] = '{'.self::NS_CARDDAV.'}max-resource-size'; + $server->protectedProperties[] = '{'.self::NS_CARDDAV.'}addressbook-home-set'; + $server->protectedProperties[] = '{'.self::NS_CARDDAV.'}supported-collation-set'; $server->propertyMap['{http://calendarserver.org/ns/}me-card'] = 'Sabre_DAV_Property_Href'; $this->server = $server; - } /** @@ -84,10 +81,9 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { * * @return array */ - public function getFeatures() { - + public function getFeatures() + { return array('addressbook'); - } /** @@ -98,50 +94,48 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { * implement them * * @param string $uri + * * @return array */ - public function getSupportedReportSet($uri) { - + public function getSupportedReportSet($uri) + { $node = $this->server->tree->getNodeForPath($uri); if ($node instanceof Sabre_CardDAV_IAddressBook || $node instanceof Sabre_CardDAV_ICard) { return array( - '{' . self::NS_CARDDAV . '}addressbook-multiget', - '{' . self::NS_CARDDAV . '}addressbook-query', + '{'.self::NS_CARDDAV.'}addressbook-multiget', + '{'.self::NS_CARDDAV.'}addressbook-query', ); } - return array(); + return array(); } - /** - * Adds all CardDAV-specific properties + * Adds all CardDAV-specific properties. * - * @param string $path + * @param string $path * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties - * @return void + * @param array $requestedProperties + * @param array $returnedProperties */ - public function beforeGetProperties($path, Sabre_DAV_INode $node, array &$requestedProperties, array &$returnedProperties) { - + public function beforeGetProperties($path, Sabre_DAV_INode $node, array &$requestedProperties, array &$returnedProperties) + { if ($node instanceof Sabre_DAVACL_IPrincipal) { // calendar-home-set property - $addHome = '{' . self::NS_CARDDAV . '}addressbook-home-set'; - if (in_array($addHome,$requestedProperties)) { + $addHome = '{'.self::NS_CARDDAV.'}addressbook-home-set'; + if (in_array($addHome, $requestedProperties)) { $principalId = $node->getName(); - $addressbookHomePath = self::ADDRESSBOOK_ROOT . '/' . $principalId . '/'; + $addressbookHomePath = self::ADDRESSBOOK_ROOT.'/'.$principalId.'/'; unset($requestedProperties[array_search($addHome, $requestedProperties)]); $returnedProperties[200][$addHome] = new Sabre_DAV_Property_Href($addressbookHomePath); } - $directories = '{' . self::NS_CARDDAV . '}directory-gateway'; + $directories = '{'.self::NS_CARDDAV.'}directory-gateway'; if ($this->directories && in_array($directories, $requestedProperties)) { unset($requestedProperties[array_search($directories, $requestedProperties)]); $returnedProperties[200][$directories] = new Sabre_DAV_Property_HrefList($this->directories); } - } if ($node instanceof Sabre_CardDAV_ICard) { @@ -149,50 +143,44 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { // The address-data property is not supposed to be a 'real' // property, but in large chunks of the spec it does act as such. // Therefore we simply expose it as a property. - $addressDataProp = '{' . self::NS_CARDDAV . '}address-data'; + $addressDataProp = '{'.self::NS_CARDDAV.'}address-data'; if (in_array($addressDataProp, $requestedProperties)) { unset($requestedProperties[$addressDataProp]); $val = $node->get(); - if (is_resource($val)) + if (is_resource($val)) { $val = stream_get_contents($val); + } $returnedProperties[200][$addressDataProp] = $val; - } } if ($node instanceof Sabre_CardDAV_UserAddressBooks) { - $meCardProp = '{http://calendarserver.org/ns/}me-card'; if (in_array($meCardProp, $requestedProperties)) { - $props = $this->server->getProperties($node->getOwner(), array('{http://sabredav.org/ns}vcard-url')); if (isset($props['{http://sabredav.org/ns}vcard-url'])) { - $returnedProperties[200][$meCardProp] = new Sabre_DAV_Property_Href( $props['{http://sabredav.org/ns}vcard-url'] ); $pos = array_search($meCardProp, $requestedProperties); unset($requestedProperties[$pos]); - } - } - } - } /** - * This event is triggered when a PROPPATCH method is executed + * This event is triggered when a PROPPATCH method is executed. * - * @param array $mutations - * @param array $result + * @param array $mutations + * @param array $result * @param Sabre_DAV_INode $node + * * @return bool */ - public function updateProperties(&$mutations, &$result, $node) { - + public function updateProperties(&$mutations, &$result, $node) + { if (!$node instanceof Sabre_CardDAV_UserAddressBooks) { return true; } @@ -200,8 +188,9 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { $meCard = '{http://calendarserver.org/ns/}me-card'; // The only property we care about - if (!isset($mutations[$meCard])) + if (!isset($mutations[$meCard])) { return true; + } $value = $mutations[$meCard]; unset($mutations[$meCard]); @@ -211,6 +200,7 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { $value = $this->server->calculateUri($value); } elseif (!is_null($value)) { $result[400][$meCard] = null; + return false; } @@ -222,40 +212,39 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { ); $closureResult = false; - foreach($innerResult as $status => $props) { + foreach ($innerResult as $status => $props) { if (is_array($props) && array_key_exists('{http://sabredav.org/ns}vcard-url', $props)) { $result[$status][$meCard] = null; - $closureResult = ($status>=200 && $status<300); + $closureResult = ($status >= 200 && $status < 300); } - } return $result; - } /** - * This functions handles REPORT requests specific to CardDAV + * This functions handles REPORT requests specific to CardDAV. * - * @param string $reportName + * @param string $reportName * @param DOMNode $dom + * * @return bool */ - public function report($reportName,$dom) { - - switch($reportName) { - case '{'.self::NS_CARDDAV.'}addressbook-multiget' : + public function report($reportName, $dom) + { + switch ($reportName) { + case '{'.self::NS_CARDDAV.'}addressbook-multiget': $this->addressbookMultiGetReport($dom); + return false; - case '{'.self::NS_CARDDAV.'}addressbook-query' : + case '{'.self::NS_CARDDAV.'}addressbook-query': $this->addressBookQueryReport($dom); + return false; - default : + default: return; } - - } /** @@ -265,26 +254,22 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { * of urls. Effectively avoiding a lot of redundant requests. * * @param DOMNode $dom - * @return void */ - public function addressbookMultiGetReport($dom) { - + public function addressbookMultiGetReport($dom) + { $properties = array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)); - $hrefElems = $dom->getElementsByTagNameNS('DAV:','href'); + $hrefElems = $dom->getElementsByTagNameNS('DAV:', 'href'); $propertyList = array(); - foreach($hrefElems as $elem) { - + foreach ($hrefElems as $elem) { $uri = $this->server->calculateUri($elem->nodeValue); - list($propertyList[]) = $this->server->getPropertiesForPath($uri,$properties); - + list($propertyList[]) = $this->server->getPropertiesForPath($uri, $properties); } $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->sendBody($this->server->generateMultiStatus($propertyList)); - } /** @@ -293,18 +278,17 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { * This plugin uses this method to ensure that Card nodes receive valid * vcard data. * - * @param string $path + * @param string $path * @param Sabre_DAV_IFile $node - * @param resource $data - * @return void + * @param resource $data */ - public function beforeWriteContent($path, Sabre_DAV_IFile $node, &$data) { - - if (!$node instanceof Sabre_CardDAV_ICard) + public function beforeWriteContent($path, Sabre_DAV_IFile $node, &$data) + { + if (!$node instanceof Sabre_CardDAV_ICard) { return; + } $this->validateVCard($data); - } /** @@ -313,18 +297,17 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { * This plugin uses this method to ensure that Card nodes receive valid * vcard data. * - * @param string $path - * @param resource $data + * @param string $path + * @param resource $data * @param Sabre_DAV_ICollection $parentNode - * @return void */ - public function beforeCreateFile($path, &$data, Sabre_DAV_ICollection $parentNode) { - - if (!$parentNode instanceof Sabre_CardDAV_IAddressBook) + public function beforeCreateFile($path, &$data, Sabre_DAV_ICollection $parentNode) + { + if (!$parentNode instanceof Sabre_CardDAV_IAddressBook) { return; + } $this->validateVCard($data); - } /** @@ -333,9 +316,9 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { * An exception is thrown if it's not. * * @param resource|string $data - * @return void */ - protected function validateVCard(&$data) { + protected function validateVCard(&$data) + { // If it's a stream, we convert it to a string first. if (is_resource($data)) { @@ -346,13 +329,9 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { $data = Sabre_DAV_StringUtil::ensureUTF8($data); try { - $vobj = VObject\Reader::read($data); - } catch (VObject\ParseException $e) { - - throw new Sabre_DAV_Exception_UnsupportedMediaType('This resource only supports valid vcard data. Parse error: ' . $e->getMessage()); - + throw new Sabre_DAV_Exception_UnsupportedMediaType('This resource only supports valid vcard data. Parse error: '.$e->getMessage()); } if ($vobj->name !== 'VCARD') { @@ -362,39 +341,36 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { if (!isset($vobj->UID)) { throw new Sabre_DAV_Exception_BadRequest('Every vcard must have an UID.'); } - } - /** - * This function handles the addressbook-query REPORT + * This function handles the addressbook-query REPORT. * * This report is used by the client to filter an addressbook based on a * complex query. * * @param DOMNode $dom - * @return void */ - protected function addressbookQueryReport($dom) { - + protected function addressbookQueryReport($dom) + { $query = new Sabre_CardDAV_AddressBookQueryParser($dom); $query->parse(); $depth = $this->server->getHTTPDepth(0); - if ($depth==0) { + if ($depth == 0) { $candidateNodes = array( - $this->server->tree->getNodeForPath($this->server->getRequestUri()) + $this->server->tree->getNodeForPath($this->server->getRequestUri()), ); } else { $candidateNodes = $this->server->tree->getChildren($this->server->getRequestUri()); } $validNodes = array(); - foreach($candidateNodes as $node) { - - if (!$node instanceof Sabre_CardDAV_ICard) + foreach ($candidateNodes as $node) { + if (!$node instanceof Sabre_CardDAV_ICard) { continue; + } $blob = $node->get(); if (is_resource($blob)) { @@ -411,44 +387,42 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { // We hit the maximum number of items, we can stop now. break; } - } $result = array(); - foreach($validNodes as $validNode) { - - if ($depth==0) { + foreach ($validNodes as $validNode) { + if ($depth == 0) { $href = $this->server->getRequestUri(); } else { - $href = $this->server->getRequestUri() . '/' . $validNode->getName(); + $href = $this->server->getRequestUri().'/'.$validNode->getName(); } list($result[]) = $this->server->getPropertiesForPath($href, $query->requestedProperties, 0); - } $this->server->httpResponse->sendStatus(207); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->sendBody($this->server->generateMultiStatus($result)); - } /** * Validates if a vcard makes it throught a list of filters. * * @param string $vcardData - * @param array $filters - * @param string $test anyof or allof (which means OR or AND) + * @param array $filters + * @param string $test anyof or allof (which means OR or AND) + * * @return bool */ - public function validateFilters($vcardData, array $filters, $test) { - + public function validateFilters($vcardData, array $filters, $test) + { $vcard = VObject\Reader::read($vcardData); - if (!$filters) return true; - - foreach($filters as $filter) { + if (!$filters) { + return true; + } + foreach ($filters as $filter) { $isDefined = isset($vcard->{$filter['name']}); if ($filter['is-not-defined']) { if ($isDefined) { @@ -460,9 +434,7 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { // We only need to check for existence $success = $isDefined; - } else { - $vProperties = $vcard->select($filter['name']); $results = array(); @@ -471,13 +443,14 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { } if ($filter['text-matches']) { $texts = array(); - foreach($vProperties as $vProperty) + foreach ($vProperties as $vProperty) { $texts[] = $vProperty->value; + } $results[] = $this->validateTextMatches($texts, $filter['text-matches'], $filter['test']); } - if (count($results)===1) { + if (count($results) === 1) { $success = $results[0]; } else { if ($filter['test'] === 'anyof') { @@ -486,27 +459,24 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { $success = $results[0] && $results[1]; } } - } // else // There are two conditions where we can already determine whether // or not this filter succeeds. - if ($test==='anyof' && $success) { + if ($test === 'anyof' && $success) { return true; } - if ($test==='allof' && !$success) { + if ($test === 'allof' && !$success) { return false; } - } // foreach // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. - // + // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - + return $test === 'allof'; } /** @@ -514,20 +484,23 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { * * @todo currently we're only validating the first parameter of the passed * property. Any subsequence parameters with the same name are - * ignored. - * @param array $vProperties - * @param array $filters + * ignored + * + * @param array $vProperties + * @param array $filters * @param string $test + * * @return bool */ - protected function validateParamFilters(array $vProperties, array $filters, $test) { - - foreach($filters as $filter) { - + protected function validateParamFilters(array $vProperties, array $filters, $test) + { + foreach ($filters as $filter) { $isDefined = false; - foreach($vProperties as $vProperty) { + foreach ($vProperties as $vProperty) { $isDefined = isset($vProperty[$filter['name']]); - if ($isDefined) break; + if ($isDefined) { + break; + } } if ($filter['is-not-defined']) { @@ -539,83 +512,80 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { // If there's no text-match, we can just check for existence } elseif (!$filter['text-match'] || !$isDefined) { - $success = $isDefined; - } else { - $success = false; - foreach($vProperties as $vProperty) { + foreach ($vProperties as $vProperty) { // If we got all the way here, we'll need to validate the // text-match filter. $success = Sabre_DAV_StringUtil::textMatch($vProperty[$filter['name']]->value, $filter['text-match']['value'], $filter['text-match']['collation'], $filter['text-match']['match-type']); - if ($success) break; + if ($success) { + break; + } } if ($filter['text-match']['negate-condition']) { $success = !$success; } - } // else // There are two conditions where we can already determine whether // or not this filter succeeds. - if ($test==='anyof' && $success) { + if ($test === 'anyof' && $success) { return true; } - if ($test==='allof' && !$success) { + if ($test === 'allof' && !$success) { return false; } - } // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. - // + // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - + return $test === 'allof'; } /** * Validates if a text-filter can be applied to a specific property. * - * @param array $texts - * @param array $filters + * @param array $texts + * @param array $filters * @param string $test + * * @return bool */ - protected function validateTextMatches(array $texts, array $filters, $test) { - - foreach($filters as $filter) { - + protected function validateTextMatches(array $texts, array $filters, $test) + { + foreach ($filters as $filter) { $success = false; - foreach($texts as $haystack) { + foreach ($texts as $haystack) { $success = Sabre_DAV_StringUtil::textMatch($haystack, $filter['value'], $filter['collation'], $filter['match-type']); // Breaking on the first match - if ($success) break; + if ($success) { + break; + } } if ($filter['negate-condition']) { $success = !$success; } - if ($success && $test==='anyof') + if ($success && $test === 'anyof') { return true; + } - if (!$success && $test=='allof') + if (!$success && $test == 'allof') { return false; - - + } } // If we got all the way here, it means we haven't been able to // determine early if the test failed or not. - // + // This implies for 'anyof' that the test failed, and for 'allof' that // we succeeded. Sounds weird, but makes sense. - return $test==='allof'; - + return $test === 'allof'; } /** @@ -623,23 +593,24 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { * * @return bool */ - public function afterGetProperties($uri, &$properties) { + public function afterGetProperties($uri, &$properties) + { // If the request was made using the SOGO connector, we must rewrite // the content-type property. By default SabreDAV will send back // text/x-vcard; charset=utf-8, but for SOGO we must strip that last // part. - if (!isset($properties[200]['{DAV:}getcontenttype'])) - return; - - if (strpos($this->server->httpRequest->getHeader('User-Agent'),'Thunderbird')===false) { + if (!isset($properties[200]['{DAV:}getcontenttype'])) { return; } - if (strpos($properties[200]['{DAV:}getcontenttype'],'text/x-vcard')===0) { + if (strpos($this->server->httpRequest->getHeader('User-Agent'), 'Thunderbird') === false) { + return; + } + + if (strpos($properties[200]['{DAV:}getcontenttype'], 'text/x-vcard') === 0) { $properties[200]['{DAV:}getcontenttype'] = 'text/x-vcard'; } - } /** @@ -648,15 +619,17 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { * can use to create new calendars. * * @param Sabre_DAV_INode $node - * @param string $output + * @param string $output + * * @return bool */ - public function htmlActionsPanel(Sabre_DAV_INode $node, &$output) { - - if (!$node instanceof Sabre_CardDAV_UserAddressBooks) + public function htmlActionsPanel(Sabre_DAV_INode $node, &$output) + { + if (!$node instanceof Sabre_CardDAV_UserAddressBooks) { return; + } - $output.= ' + $output .= '

Create new address book


@@ -666,7 +639,6 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { '; return false; - } /** @@ -675,22 +647,23 @@ class Sabre_CardDAV_Plugin extends Sabre_DAV_ServerPlugin { * * @param string $uri * @param string $action - * @param array $postVars + * @param array $postVars + * * @return bool */ - public function browserPostAction($uri, $action, array $postVars) { - - if ($action!=='mkaddressbook') + public function browserPostAction($uri, $action, array $postVars) + { + if ($action !== 'mkaddressbook') { return; + } - $resourceType = array('{DAV:}collection','{urn:ietf:params:xml:ns:carddav}addressbook'); + $resourceType = array('{DAV:}collection', '{urn:ietf:params:xml:ns:carddav}addressbook'); $properties = array(); if (isset($postVars['{DAV:}displayname'])) { $properties['{DAV:}displayname'] = $postVars['{DAV:}displayname']; } - $this->server->createCollection($uri . '/' . $postVars['name'],$resourceType,$properties); + $this->server->createCollection($uri.'/'.$postVars['name'], $resourceType, $properties); + return false; - } - } diff --git a/dav/SabreDAV/lib/Sabre/CardDAV/Property/SupportedAddressData.php b/dav/SabreDAV/lib/Sabre/CardDAV/Property/SupportedAddressData.php index 36d9306e..8c0763fc 100644 --- a/dav/SabreDAV/lib/Sabre/CardDAV/Property/SupportedAddressData.php +++ b/dav/SabreDAV/lib/Sabre/CardDAV/Property/SupportedAddressData.php @@ -1,33 +1,31 @@ 'text/vcard', 'version' => '3.0'), @@ -35,19 +33,17 @@ class Sabre_CardDAV_Property_SupportedAddressData extends Sabre_DAV_Property { ); } - $this->supportedData = $supportedData; - + $this->supportedData = $supportedData; } /** - * Serializes the property in a DOMDocument + * Serializes the property in a DOMDocument. * * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void + * @param DOMElement $node */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $node) + { $doc = $node->ownerDocument; $prefix = @@ -55,15 +51,11 @@ class Sabre_CardDAV_Property_SupportedAddressData extends Sabre_DAV_Property { $server->xmlNamespaces[Sabre_CardDAV_Plugin::NS_CARDDAV] : 'card'; - foreach($this->supportedData as $supported) { - - $caldata = $doc->createElementNS(Sabre_CardDAV_Plugin::NS_CARDDAV, $prefix . ':address-data-type'); - $caldata->setAttribute('content-type',$supported['contentType']); - $caldata->setAttribute('version',$supported['version']); + foreach ($this->supportedData as $supported) { + $caldata = $doc->createElementNS(Sabre_CardDAV_Plugin::NS_CARDDAV, $prefix.':address-data-type'); + $caldata->setAttribute('content-type', $supported['contentType']); + $caldata->setAttribute('version', $supported['version']); $node->appendChild($caldata); - } - } - } diff --git a/dav/SabreDAV/lib/Sabre/CardDAV/UserAddressBooks.php b/dav/SabreDAV/lib/Sabre/CardDAV/UserAddressBooks.php index 3f11fb11..bc716d59 100644 --- a/dav/SabreDAV/lib/Sabre/CardDAV/UserAddressBooks.php +++ b/dav/SabreDAV/lib/Sabre/CardDAV/UserAddressBooks.php @@ -1,89 +1,80 @@ carddavBackend = $carddavBackend; $this->principalUri = $principalUri; - } /** - * Returns the name of this object + * Returns the name of this object. * * @return string */ - public function getName() { + public function getName() + { + list(, $name) = Sabre_DAV_URLUtil::splitPath($this->principalUri); - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalUri); return $name; - } /** - * Updates the name of this object + * Updates the name of this object. * * @param string $name - * @return void */ - public function setName($name) { - + public function setName($name) + { throw new Sabre_DAV_Exception_MethodNotAllowed(); - } /** - * Deletes this object - * - * @return void + * Deletes this object. */ - public function delete() { - + public function delete() + { throw new Sabre_DAV_Exception_MethodNotAllowed(); - } /** - * Returns the last modification date + * Returns the last modification date. * * @return int */ - public function getLastModified() { - + public function getLastModified() + { return null; - } /** @@ -91,14 +82,12 @@ class Sabre_CardDAV_UserAddressBooks extends Sabre_DAV_Collection implements Sab * * This is currently not allowed * - * @param string $filename + * @param string $filename * @param resource $data - * @return void */ - public function createFile($filename, $data=null) { - + public function createFile($filename, $data = null) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); - } /** @@ -107,89 +96,84 @@ class Sabre_CardDAV_UserAddressBooks extends Sabre_DAV_Collection implements Sab * This is currently not allowed. * * @param string $filename - * @return void */ - public function createDirectory($filename) { - + public function createDirectory($filename) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); - } /** - * Returns a single calendar, by name + * Returns a single calendar, by name. * * @param string $name + * * @todo needs optimizing + * * @return Sabre_CardDAV_AddressBook */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) + public function getChild($name) + { + foreach ($this->getChildren() as $child) { + if ($name == $child->getName()) { return $child; - + } } - throw new Sabre_DAV_Exception_NotFound('Addressbook with name \'' . $name . '\' could not be found'); - + throw new Sabre_DAV_Exception_NotFound('Addressbook with name \''.$name.'\' could not be found'); } /** - * Returns a list of addressbooks + * Returns a list of addressbooks. * * @return array */ - public function getChildren() { - + public function getChildren() + { $addressbooks = $this->carddavBackend->getAddressbooksForUser($this->principalUri); $objs = array(); - foreach($addressbooks as $addressbook) { + foreach ($addressbooks as $addressbook) { $objs[] = new Sabre_CardDAV_AddressBook($this->carddavBackend, $addressbook); } - return $objs; + return $objs; } /** - * Creates a new addressbook + * Creates a new addressbook. * * @param string $name - * @param array $resourceType - * @param array $properties - * @return void + * @param array $resourceType + * @param array $properties */ - public function createExtendedCollection($name, array $resourceType, array $properties) { - - if (!in_array('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook',$resourceType) || count($resourceType)!==2) { + public function createExtendedCollection($name, array $resourceType, array $properties) + { + if (!in_array('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook', $resourceType) || count($resourceType) !== 2) { throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); } $this->carddavBackend->createAddressBook($this->principalUri, $name, $properties); - } /** - * Returns the owner principal + * Returns the owner principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getOwner() { - + public function getOwner() + { return $this->principalUri; - } /** - * Returns a group principal + * Returns a group principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getGroup() { - + public function getGroup() + { return null; - } /** @@ -204,8 +188,8 @@ class Sabre_CardDAV_UserAddressBooks extends Sabre_DAV_Collection implements Sab * * @return array */ - public function getACL() { - + public function getACL() + { return array( array( 'privilege' => '{DAV:}read', @@ -219,21 +203,18 @@ class Sabre_CardDAV_UserAddressBooks extends Sabre_DAV_Collection implements Sab ), ); - } /** - * Updates the ACL + * Updates the ACL. * * This method will receive a list of new ACE's. * * @param array $acl - * @return void */ - public function setACL(array $acl) { - + public function setACL(array $acl) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - } /** @@ -248,10 +229,8 @@ class Sabre_CardDAV_UserAddressBooks extends Sabre_DAV_Collection implements Sab * * @return array|null */ - public function getSupportedPrivilegeSet() { - + public function getSupportedPrivilegeSet() + { return null; - } - } diff --git a/dav/SabreDAV/lib/Sabre/CardDAV/Version.php b/dav/SabreDAV/lib/Sabre/CardDAV/Version.php index e4584043..d55dae5f 100644 --- a/dav/SabreDAV/lib/Sabre/CardDAV/Version.php +++ b/dav/SabreDAV/lib/Sabre/CardDAV/Version.php @@ -1,26 +1,23 @@ currentUser; } - /** * Authenticates the user based on the current request. * @@ -53,12 +52,14 @@ abstract class Sabre_DAV_Auth_Backend_AbstractBasic implements Sabre_DAV_Auth_IB * If authentication fails, an exception must be thrown. * * @param Sabre_DAV_Server $server - * @param string $realm + * @param string $realm + * * @throws Sabre_DAV_Exception_NotAuthenticated + * * @return bool */ - public function authenticate(Sabre_DAV_Server $server, $realm) { - + public function authenticate(Sabre_DAV_Server $server, $realm) + { $auth = new Sabre_HTTP_BasicAuth(); $auth->setHTTPRequest($server->httpRequest); $auth->setHTTPResponse($server->httpResponse); @@ -70,14 +71,12 @@ abstract class Sabre_DAV_Auth_Backend_AbstractBasic implements Sabre_DAV_Auth_IB } // Authenticates the user - if (!$this->validateUserPass($userpass[0],$userpass[1])) { + if (!$this->validateUserPass($userpass[0], $userpass[1])) { $auth->requireLogin(); throw new Sabre_DAV_Exception_NotAuthenticated('Username or password does not match'); } $this->currentUser = $userpass[0]; + return true; } - - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/AbstractDigest.php b/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/AbstractDigest.php index 9833928b..ba1ba17c 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/AbstractDigest.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/AbstractDigest.php @@ -1,20 +1,18 @@ getDigestHash($realm, $username); // If this was false, the user account didn't exist - if ($hash===false || is_null($hash)) { + if ($hash === false || is_null($hash)) { $digest->requireLogin(); throw new Sabre_DAV_Exception_NotAuthenticated('The supplied username was not on file'); } @@ -80,8 +81,8 @@ abstract class Sabre_DAV_Auth_Backend_AbstractDigest implements Sabre_DAV_Auth_I } $this->currentUser = $username; - return true; + return true; } /** @@ -89,10 +90,8 @@ abstract class Sabre_DAV_Auth_Backend_AbstractDigest implements Sabre_DAV_Auth_I * * @return string|null */ - public function getCurrentUser() { - + public function getCurrentUser() + { return $this->currentUser; - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/Apache.php b/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/Apache.php index d4294ea4..05b09025 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/Apache.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/Apache.php @@ -1,23 +1,21 @@ httpRequest->getRawServerValue('REMOTE_USER'); if (is_null($remoteUser)) { throw new Sabre_DAV_Exception('We did not receive the $_SERVER[REMOTE_USER] property. This means that apache might have been misconfigured'); } $this->remoteUser = $remoteUser; - return true; + return true; } /** @@ -52,11 +51,8 @@ class Sabre_DAV_Auth_Backend_Apache implements Sabre_DAV_Auth_IBackend { * * @return array|null */ - public function getCurrentUser() { - + public function getCurrentUser() + { return $this->remoteUser; - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/File.php b/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/File.php index de308d64..da67a9b5 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/File.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/File.php @@ -5,16 +5,14 @@ * * The backend file must conform to Apache's htdigest format * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved + * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_DAV_Auth_Backend_File extends Sabre_DAV_Auth_Backend_AbstractDigest { - +class Sabre_DAV_Auth_Backend_File extends Sabre_DAV_Auth_Backend_AbstractDigest +{ /** - * List of users + * List of users. * * @var array */ @@ -27,11 +25,11 @@ class Sabre_DAV_Auth_Backend_File extends Sabre_DAV_Auth_Backend_AbstractDigest * * @param string|null $filename */ - public function __construct($filename=null) { - - if (!is_null($filename)) + public function __construct($filename = null) + { + if (!is_null($filename)) { $this->loadFile($filename); - + } } /** @@ -39,37 +37,34 @@ class Sabre_DAV_Auth_Backend_File extends Sabre_DAV_Auth_Backend_AbstractDigest * more than 1 file is used. * * @param string $filename - * @return void */ - public function loadFile($filename) { - - foreach(file($filename,FILE_IGNORE_NEW_LINES) as $line) { - - if (substr_count($line, ":") !== 2) + public function loadFile($filename) + { + foreach (file($filename, FILE_IGNORE_NEW_LINES) as $line) { + if (substr_count($line, ':') !== 2) { throw new Sabre_DAV_Exception('Malformed htdigest file. Every line should contain 2 colons'); + } - list($username,$realm,$A1) = explode(':',$line); + list($username, $realm, $A1) = explode(':', $line); - if (!preg_match('/^[a-zA-Z0-9]{32}$/', $A1)) + if (!preg_match('/^[a-zA-Z0-9]{32}$/', $A1)) { throw new Sabre_DAV_Exception('Malformed htdigest file. Invalid md5 hash'); + } - $this->users[$realm . ':' . $username] = $A1; - + $this->users[$realm.':'.$username] = $A1; } - } /** - * Returns a users' information + * Returns a users' information. * * @param string $realm * @param string $username + * * @return string */ - public function getDigestHash($realm, $username) { - - return isset($this->users[$realm . ':' . $username])?$this->users[$realm . ':' . $username]:false; - + public function getDigestHash($realm, $username) + { + return isset($this->users[$realm.':'.$username]) ? $this->users[$realm.':'.$username] : false; } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/PDO.php b/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/PDO.php index eac18a23..a350209b 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/PDO.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Auth/Backend/PDO.php @@ -5,42 +5,38 @@ * * The backend file must conform to Apache's htdigest format * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved + * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_DAV_Auth_Backend_PDO extends Sabre_DAV_Auth_Backend_AbstractDigest { - +class Sabre_DAV_Auth_Backend_PDO extends Sabre_DAV_Auth_Backend_AbstractDigest +{ /** - * Reference to PDO connection + * Reference to PDO connection. * * @var PDO */ protected $pdo; /** - * PDO table name we'll be using + * PDO table name we'll be using. * * @var string */ protected $tableName; - /** * Creates the backend object. * * If the filename argument is passed in, it will parse out the specified file fist. * - * @param PDO $pdo + * @param PDO $pdo * @param string $tableName The PDO table name to use */ - public function __construct(PDO $pdo, $tableName = 'users') { - + public function __construct(PDO $pdo, $tableName = 'users') + { $this->pdo = $pdo; $this->tableName = $tableName; - } /** @@ -48,18 +44,19 @@ class Sabre_DAV_Auth_Backend_PDO extends Sabre_DAV_Auth_Backend_AbstractDigest { * * @param string $realm * @param string $username + * * @return string|null */ - public function getDigestHash($realm,$username) { - + public function getDigestHash($realm, $username) + { $stmt = $this->pdo->prepare('SELECT username, digesta1 FROM '.$this->tableName.' WHERE username = ?'); $stmt->execute(array($username)); $result = $stmt->fetchAll(); - if (!count($result)) return; + if (!count($result)) { + return; + } return $result[0]['digesta1']; - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Auth/IBackend.php b/dav/SabreDAV/lib/Sabre/DAV/Auth/IBackend.php index 5be5d1bc..22e414d8 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Auth/IBackend.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Auth/IBackend.php @@ -3,14 +3,12 @@ /** * This is the base class for any authentication object. * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved + * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -interface Sabre_DAV_Auth_IBackend { - +interface Sabre_DAV_Auth_IBackend +{ /** * Authenticates the user based on the current request. * @@ -18,10 +16,11 @@ interface Sabre_DAV_Auth_IBackend { * If authentication fails, an exception must be thrown. * * @param Sabre_DAV_Server $server - * @param string $realm + * @param string $realm + * * @return bool */ - function authenticate(Sabre_DAV_Server $server,$realm); + public function authenticate(Sabre_DAV_Server $server, $realm); /** * Returns information about the currently logged in username. @@ -30,7 +29,5 @@ interface Sabre_DAV_Auth_IBackend { * * @return string|null */ - function getCurrentUser(); - + public function getCurrentUser(); } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Auth/Plugin.php b/dav/SabreDAV/lib/Sabre/DAV/Auth/Plugin.php index 55a4e391..7e869b7c 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Auth/Plugin.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Auth/Plugin.php @@ -9,23 +9,21 @@ * * {DAV:}current-user-principal property from RFC5397 * * {DAV:}principal-collection-set property from RFC3744 * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_DAV_Auth_Plugin extends Sabre_DAV_ServerPlugin { - +class Sabre_DAV_Auth_Plugin extends Sabre_DAV_ServerPlugin +{ /** - * Reference to main server object + * Reference to main server object. * * @var Sabre_DAV_Server */ private $server; /** - * Authentication backend + * Authentication backend. * * @var Sabre_DAV_Auth_IBackend */ @@ -39,29 +37,26 @@ class Sabre_DAV_Auth_Plugin extends Sabre_DAV_ServerPlugin { private $realm; /** - * __construct + * __construct. * * @param Sabre_DAV_Auth_IBackend $authBackend - * @param string $realm + * @param string $realm */ - public function __construct(Sabre_DAV_Auth_IBackend $authBackend, $realm) { - + public function __construct(Sabre_DAV_Auth_IBackend $authBackend, $realm) + { $this->authBackend = $authBackend; $this->realm = $realm; - } /** - * Initializes the plugin. This function is automatically called by the server + * Initializes the plugin. This function is automatically called by the server. * * @param Sabre_DAV_Server $server - * @return void */ - public function initialize(Sabre_DAV_Server $server) { - + public function initialize(Sabre_DAV_Server $server) + { $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'),10); - + $this->server->subscribeEvent('beforeMethod', array($this, 'beforeMethod'), 10); } /** @@ -72,10 +67,9 @@ class Sabre_DAV_Auth_Plugin extends Sabre_DAV_ServerPlugin { * * @return string */ - public function getPluginName() { - + public function getPluginName() + { return 'auth'; - } /** @@ -85,27 +79,28 @@ class Sabre_DAV_Auth_Plugin extends Sabre_DAV_ServerPlugin { * * @return string|null */ - public function getCurrentUser() { - + public function getCurrentUser() + { $userInfo = $this->authBackend->getCurrentUser(); - if (!$userInfo) return null; + if (!$userInfo) { + return null; + } return $userInfo; - } /** - * This method is called before any HTTP method and forces users to be authenticated + * This method is called before any HTTP method and forces users to be authenticated. * * @param string $method * @param string $uri + * * @throws Sabre_DAV_Exception_NotAuthenticated + * * @return bool */ - public function beforeMethod($method, $uri) { - - $this->authBackend->authenticate($this->server,$this->realm); - + public function beforeMethod($method, $uri) + { + $this->authBackend->authenticate($this->server, $this->realm); } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Browser/GuessContentType.php b/dav/SabreDAV/lib/Sabre/DAV/Browser/GuessContentType.php index b6c00d46..1ffed276 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Browser/GuessContentType.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Browser/GuessContentType.php @@ -1,7 +1,7 @@ subscribeEvent('afterGetProperties',array($this,'afterGetProperties'),200); - + $server->subscribeEvent('afterGetProperties', array($this, 'afterGetProperties'), 200); } /** - * Handler for teh afterGetProperties event + * Handler for teh afterGetProperties event. * * @param string $path - * @param array $properties - * @return void + * @param array $properties */ - public function afterGetProperties($path, &$properties) { - + public function afterGetProperties($path, &$properties) + { if (array_key_exists('{DAV:}getcontenttype', $properties[404])) { - list(, $fileName) = Sabre_DAV_URLUtil::splitPath($path); $contentType = $this->getContentType($fileName); @@ -74,24 +69,23 @@ class Sabre_DAV_Browser_GuessContentType extends Sabre_DAV_ServerPlugin { $properties[200]['{DAV:}getcontenttype'] = $contentType; unset($properties[404]['{DAV:}getcontenttype']); } - } - } /** - * Simple method to return the contenttype + * Simple method to return the contenttype. * * @param string $fileName + * * @return string */ - protected function getContentType($fileName) { + protected function getContentType($fileName) + { // Just grabbing the extension - $extension = strtolower(substr($fileName,strrpos($fileName,'.')+1)); - if (isset($this->extensionMap[$extension])) + $extension = strtolower(substr($fileName, strrpos($fileName, '.') + 1)); + if (isset($this->extensionMap[$extension])) { return $this->extensionMap[$extension]; - + } } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Browser/MapGetToPropFind.php b/dav/SabreDAV/lib/Sabre/DAV/Browser/MapGetToPropFind.php index 15884887..7b7cbdbb 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Browser/MapGetToPropFind.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Browser/MapGetToPropFind.php @@ -6,50 +6,51 @@ * * This should allow easy debugging of PROPFIND * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_DAV_Browser_MapGetToPropFind extends Sabre_DAV_ServerPlugin { - +class Sabre_DAV_Browser_MapGetToPropFind extends Sabre_DAV_ServerPlugin +{ /** - * reference to server class + * reference to server class. * * @var Sabre_DAV_Server */ protected $server; /** - * Initializes the plugin and subscribes to events + * Initializes the plugin and subscribes to events. * * @param Sabre_DAV_Server $server - * @return void */ - public function initialize(Sabre_DAV_Server $server) { - + public function initialize(Sabre_DAV_Server $server) + { $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor')); + $this->server->subscribeEvent('beforeMethod', array($this, 'httpGetInterceptor')); } /** - * This method intercepts GET requests to non-files, and changes it into an HTTP PROPFIND request + * This method intercepts GET requests to non-files, and changes it into an HTTP PROPFIND request. * * @param string $method * @param string $uri + * * @return bool */ - public function httpGetInterceptor($method, $uri) { - - if ($method!='GET') return true; + public function httpGetInterceptor($method, $uri) + { + if ($method != 'GET') { + return true; + } $node = $this->server->tree->getNodeForPath($uri); - if ($node instanceof Sabre_DAV_IFile) return; + if ($node instanceof Sabre_DAV_IFile) { + return; + } + + $this->server->invokeMethod('PROPFIND', $uri); - $this->server->invokeMethod('PROPFIND',$uri); return false; - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Browser/Plugin.php b/dav/SabreDAV/lib/Sabre/DAV/Browser/Plugin.php index 09bbdd2a..9bc67dcf 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Browser/Plugin.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Browser/Plugin.php @@ -1,7 +1,7 @@ enablePost = $enablePost; $this->enableAssets = $enableAssets; - } /** - * Initializes the plugin and subscribes to events + * Initializes the plugin and subscribes to events. * * @param Sabre_DAV_Server $server - * @return void */ - public function initialize(Sabre_DAV_Server $server) { - + public function initialize(Sabre_DAV_Server $server) + { $this->server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'httpGetInterceptor')); - $this->server->subscribeEvent('onHTMLActionsPanel', array($this, 'htmlActionsPanel'),200); - if ($this->enablePost) $this->server->subscribeEvent('unknownMethod',array($this,'httpPOSTHandler')); + $this->server->subscribeEvent('beforeMethod', array($this, 'httpGetInterceptor')); + $this->server->subscribeEvent('onHTMLActionsPanel', array($this, 'htmlActionsPanel'), 200); + if ($this->enablePost) { + $this->server->subscribeEvent('unknownMethod', array($this, 'httpPOSTHandler')); + } } /** - * This method intercepts GET requests to collections and returns the html + * This method intercepts GET requests to collections and returns the html. * * @param string $method * @param string $uri + * * @return bool */ - public function httpGetInterceptor($method, $uri) { - - if ($method !== 'GET') return true; + public function httpGetInterceptor($method, $uri) + { + if ($method !== 'GET') { + return true; + } // We're not using straight-up $_GET, because we want everything to be // unit testable. @@ -115,6 +116,7 @@ class Sabre_DAV_Browser_Plugin extends Sabre_DAV_ServerPlugin { if (isset($getVars['sabreAction']) && $getVars['sabreAction'] === 'asset' && isset($getVars['assetName'])) { $this->serveAsset($getVars['assetName']); + return false; } @@ -125,18 +127,18 @@ class Sabre_DAV_Browser_Plugin extends Sabre_DAV_ServerPlugin { // with other plugins. return; } - if ($node instanceof Sabre_DAV_IFile) + if ($node instanceof Sabre_DAV_IFile) { return; + } $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->setHeader('Content-Type','text/html; charset=utf-8'); + $this->server->httpResponse->setHeader('Content-Type', 'text/html; charset=utf-8'); $this->server->httpResponse->sendBody( $this->generateDirectoryIndex($uri) ); return false; - } /** @@ -144,176 +146,182 @@ class Sabre_DAV_Browser_Plugin extends Sabre_DAV_ServerPlugin { * * @param string $method * @param string $uri + * * @return bool */ - public function httpPOSTHandler($method, $uri) { - - if ($method!='POST') return; + public function httpPOSTHandler($method, $uri) + { + if ($method != 'POST') { + return; + } $contentType = $this->server->httpRequest->getHeader('Content-Type'); list($contentType) = explode(';', $contentType); if ($contentType !== 'application/x-www-form-urlencoded' && $contentType !== 'multipart/form-data') { - return; + return; } $postVars = $this->server->httpRequest->getPostVars(); - if (!isset($postVars['sabreAction'])) + if (!isset($postVars['sabreAction'])) { return; + } if ($this->server->broadcastEvent('onBrowserPostAction', array($uri, $postVars['sabreAction'], $postVars))) { + switch ($postVars['sabreAction']) { - switch($postVars['sabreAction']) { - - case 'mkcol' : + case 'mkcol': if (isset($postVars['name']) && trim($postVars['name'])) { // Using basename() because we won't allow slashes list(, $folderName) = Sabre_DAV_URLUtil::splitPath(trim($postVars['name'])); - $this->server->createDirectory($uri . '/' . $folderName); + $this->server->createDirectory($uri.'/'.$folderName); } break; - case 'put' : - if ($_FILES) $file = current($_FILES); - else break; + case 'put': + if ($_FILES) { + $file = current($_FILES); + } else { + break; + } list(, $newName) = Sabre_DAV_URLUtil::splitPath(trim($file['name'])); - if (isset($postVars['name']) && trim($postVars['name'])) + if (isset($postVars['name']) && trim($postVars['name'])) { $newName = trim($postVars['name']); + } // Making sure we only have a 'basename' component list(, $newName) = Sabre_DAV_URLUtil::splitPath($newName); if (is_uploaded_file($file['tmp_name'])) { - $this->server->createFile($uri . '/' . $newName, fopen($file['tmp_name'],'r')); + $this->server->createFile($uri.'/'.$newName, fopen($file['tmp_name'], 'r')); } break; } - } - $this->server->httpResponse->setHeader('Location',$this->server->httpRequest->getUri()); + $this->server->httpResponse->setHeader('Location', $this->server->httpRequest->getUri()); $this->server->httpResponse->sendStatus(302); - return false; + return false; } /** * Escapes a string for html. * * @param string $value + * * @return string */ - public function escapeHTML($value) { - - return htmlspecialchars($value,ENT_QUOTES,'UTF-8'); - + public function escapeHTML($value) + { + return htmlspecialchars($value, ENT_QUOTES, 'UTF-8'); } /** - * Generates the html directory index for a given url + * Generates the html directory index for a given url. * * @param string $path + * * @return string */ - public function generateDirectoryIndex($path) { - + public function generateDirectoryIndex($path) + { $version = ''; if (Sabre_DAV_Server::$exposeVersion) { - $version = Sabre_DAV_Version::VERSION ."-". Sabre_DAV_Version::STABILITY; + $version = Sabre_DAV_Version::VERSION.'-'.Sabre_DAV_Version::STABILITY; } - $html = " + $html = ' - Index for " . $this->escapeHTML($path) . "/ - SabreDAV " . $version . " - - "; + '; if ($this->enableAssets) { - $html.=''; + $html .= ''; } - $html .= " + $html .= ' -

Index for " . $this->escapeHTML($path) . "/

+

Index for ' .$this->escapeHTML($path).'/

- - "; + + '; - $files = $this->server->getPropertiesForPath($path,array( + $files = $this->server->getPropertiesForPath($path, array( '{DAV:}displayname', '{DAV:}resourcetype', '{DAV:}getcontenttype', '{DAV:}getcontentlength', '{DAV:}getlastmodified', - ),1); + ), 1); $parent = $this->server->tree->getNodeForPath($path); - if ($path) { - list($parentUri) = Sabre_DAV_URLUtil::splitPath($path); - $fullPath = Sabre_DAV_URLUtil::encodePath($this->server->getBaseUri() . $parentUri); + $fullPath = Sabre_DAV_URLUtil::encodePath($this->server->getBaseUri().$parentUri); - $icon = $this->enableAssets?'Parent':''; - $html.= " + $icon = $this->enableAssets ? 'Parent' : ''; + $html .= ""; - } - foreach($files as $file) { + foreach ($files as $file) { // This is the current directory, we can skip it - if (rtrim($file['href'],'/')==$path) continue; + if (rtrim($file['href'], '/') == $path) { + continue; + } list(, $name) = Sabre_DAV_URLUtil::splitPath($file['href']); $type = null; - if (isset($file[200]['{DAV:}resourcetype'])) { $type = $file[200]['{DAV:}resourcetype']->getValue(); // resourcetype can have multiple values - if (!is_array($type)) $type = array($type); + if (!is_array($type)) { + $type = array($type); + } - foreach($type as $k=>$v) { + foreach ($type as $k => $v) { // Some name mapping is preferred - switch($v) { - case '{DAV:}collection' : + switch ($v) { + case '{DAV:}collection': $type[$k] = 'Collection'; break; - case '{DAV:}principal' : + case '{DAV:}principal': $type[$k] = 'Principal'; break; - case '{urn:ietf:params:xml:ns:carddav}addressbook' : + case '{urn:ietf:params:xml:ns:carddav}addressbook': $type[$k] = 'Addressbook'; break; - case '{urn:ietf:params:xml:ns:caldav}calendar' : + case '{urn:ietf:params:xml:ns:caldav}calendar': $type[$k] = 'Calendar'; break; - case '{urn:ietf:params:xml:ns:caldav}schedule-inbox' : + case '{urn:ietf:params:xml:ns:caldav}schedule-inbox': $type[$k] = 'Schedule Inbox'; break; - case '{urn:ietf:params:xml:ns:caldav}schedule-outbox' : + case '{urn:ietf:params:xml:ns:caldav}schedule-outbox': $type[$k] = 'Schedule Outbox'; break; - case '{http://calendarserver.org/ns/}calendar-proxy-read' : + case '{http://calendarserver.org/ns/}calendar-proxy-read': $type[$k] = 'Proxy-Read'; break; - case '{http://calendarserver.org/ns/}calendar-proxy-write' : + case '{http://calendarserver.org/ns/}calendar-proxy-write': $type[$k] = 'Proxy-Write'; break; } - } $type = implode(', ', $type); } @@ -323,14 +331,16 @@ class Sabre_DAV_Browser_Plugin extends Sabre_DAV_ServerPlugin { if (!$type && isset($file[200]['{DAV:}getcontenttype'])) { $type = $file[200]['{DAV:}getcontenttype']; } - if (!$type) $type = 'Unknown'; + if (!$type) { + $type = 'Unknown'; + } - $size = isset($file[200]['{DAV:}getcontentlength'])?(int)$file[200]['{DAV:}getcontentlength']:''; - $lastmodified = isset($file[200]['{DAV:}getlastmodified'])?$file[200]['{DAV:}getlastmodified']->getTime()->format(DateTime::ATOM):''; + $size = isset($file[200]['{DAV:}getcontentlength']) ? (int) $file[200]['{DAV:}getcontentlength'] : ''; + $lastmodified = isset($file[200]['{DAV:}getlastmodified']) ? $file[200]['{DAV:}getlastmodified']->getTime()->format(DateTime::ATOM) : ''; - $fullPath = Sabre_DAV_URLUtil::encodePath('/' . trim($this->server->getBaseUri() . ($path?$path . '/':'') . $name,'/')); + $fullPath = Sabre_DAV_URLUtil::encodePath('/'.trim($this->server->getBaseUri().($path ? $path.'/' : '').$name, '/')); - $displayName = isset($file[200]['{DAV:}displayname'])?$file[200]['{DAV:}displayname']:$name; + $displayName = isset($file[200]['{DAV:}displayname']) ? $file[200]['{DAV:}displayname'] : $name; $displayName = $this->escapeHTML($displayName); $type = $this->escapeHTML($type); @@ -339,45 +349,39 @@ class Sabre_DAV_Browser_Plugin extends Sabre_DAV_ServerPlugin { if ($this->enableAssets) { $node = $parent->getChild($name); - foreach(array_reverse($this->iconMap) as $class=>$iconName) { - + foreach (array_reverse($this->iconMap) as $class => $iconName) { if ($node instanceof $class) { - $icon = ''; + $icon = ''; break; } - - } - } - $html.= " + $html .= ""; - } - $html.= ""; + $html .= ''; $output = ''; if ($this->enablePost) { - $this->server->broadcastEvent('onHTMLActionsPanel',array($parent, &$output)); + $this->server->broadcastEvent('onHTMLActionsPanel', array($parent, &$output)); } - $html.=$output; + $html .= $output; - $html.= "
NameTypeSizeLast modified

NameTypeSizeLast modified

$icon .. [parent]
$icon {$displayName} {$type} {$size} {$lastmodified}


-
Generated by SabreDAV " . $version . " (c)2007-2012 http://code.google.com/p/sabredav/
+ $html .= ' +
Generated by SabreDAV ' .$version.' (c)2007-2012 http://code.google.com/p/sabredav/
- "; + '; return $html; - } /** @@ -388,20 +392,21 @@ class Sabre_DAV_Browser_Plugin extends Sabre_DAV_ServerPlugin { * creating new directories. * * @param Sabre_DAV_INode $node - * @param mixed $output - * @return void + * @param mixed $output */ - public function htmlActionsPanel(Sabre_DAV_INode $node, &$output) { - - if (!$node instanceof Sabre_DAV_ICollection) + public function htmlActionsPanel(Sabre_DAV_INode $node, &$output) + { + if (!$node instanceof Sabre_DAV_ICollection) { return; + } // We also know fairly certain that if an object is a non-extended // SimpleCollection, we won't need to show the panel either. - if (get_class($node)==='Sabre_DAV_SimpleCollection') + if (get_class($node) === 'Sabre_DAV_SimpleCollection') { return; + } - $output.= ' + $output .= '

Create new folder

Name:
@@ -415,7 +420,6 @@ class Sabre_DAV_Browser_Plugin extends Sabre_DAV_ServerPlugin {
'; - } /** @@ -423,52 +427,53 @@ class Sabre_DAV_Browser_Plugin extends Sabre_DAV_ServerPlugin { * suiteable for http access. * * @param string $assetName + * * @return string */ - protected function getAssetUrl($assetName) { - - return $this->server->getBaseUri() . '?sabreAction=asset&assetName=' . urlencode($assetName); - + protected function getAssetUrl($assetName) + { + return $this->server->getBaseUri().'?sabreAction=asset&assetName='.urlencode($assetName); } /** * This method returns a local pathname to an asset. * * @param string $assetName + * * @return string */ - protected function getLocalAssetPath($assetName) { + protected function getLocalAssetPath($assetName) + { // Making sure people aren't trying to escape from the base path. $assetSplit = explode('/', $assetName); - if (in_array('..',$assetSplit)) { + if (in_array('..', $assetSplit)) { throw new Sabre_DAV_Exception('Incorrect asset path'); } - $path = __DIR__ . '/assets/' . $assetName; - return $path; + $path = __DIR__.'/assets/'.$assetName; + return $path; } /** * This method reads an asset from disk and generates a full http response. * * @param string $assetName - * @return void */ - protected function serveAsset($assetName) { - + protected function serveAsset($assetName) + { $assetPath = $this->getLocalAssetPath($assetName); if (!file_exists($assetPath)) { throw new Sabre_DAV_Exception_NotFound('Could not find an asset with this name'); } // Rudimentary mime type detection - switch(strtolower(substr($assetPath,strpos($assetPath,'.')+1))) { + switch (strtolower(substr($assetPath, strpos($assetPath, '.') + 1))) { - case 'ico' : + case 'ico': $mime = 'image/vnd.microsoft.icon'; break; - case 'png' : + case 'png': $mime = 'image/png'; break; @@ -482,8 +487,6 @@ class Sabre_DAV_Browser_Plugin extends Sabre_DAV_ServerPlugin { $this->server->httpResponse->setHeader('Content-Length', filesize($assetPath)); $this->server->httpResponse->setHeader('Cache-Control', 'public, max-age=1209600'); $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->sendBody(fopen($assetPath,'r')); - + $this->server->httpResponse->sendBody(fopen($assetPath, 'r')); } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Client.php b/dav/SabreDAV/lib/Sabre/DAV/Client.php index 8f3dcc78..a51ff726 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Client.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Client.php @@ -1,21 +1,19 @@ $validSetting = $settings[$validSetting]; } @@ -96,11 +94,10 @@ class Sabre_DAV_Client { } $this->propertyMap['{DAV:}resourcetype'] = 'Sabre_DAV_Property_ResourceType'; - } /** - * Does a PROPFIND request + * Does a PROPFIND request. * * The list of requested properties must be specified as an array, in clark * notation. @@ -116,127 +113,117 @@ class Sabre_DAV_Client { * made to the server to also return all child resources. * * @param string $url - * @param array $properties - * @param int $depth + * @param array $properties + * @param int $depth + * * @return array */ - public function propFind($url, array $properties, $depth = 0) { - - $body = '' . "\n"; - $body.= '' . "\n"; - $body.= ' ' . "\n"; - - foreach($properties as $property) { + public function propFind($url, array $properties, $depth = 0) + { + $body = ''."\n"; + $body .= ''."\n"; + $body .= ' '."\n"; + foreach ($properties as $property) { list( $namespace, $elementName ) = Sabre_DAV_XMLUtil::parseClarkNotation($property); if ($namespace === 'DAV:') { - $body.=' ' . "\n"; + $body .= ' '."\n"; } else { - $body.=" \n"; + $body .= ' \n"; } - } - $body.= ' ' . "\n"; - $body.= ''; + $body .= ' '."\n"; + $body .= ''; $response = $this->request('PROPFIND', $url, $body, array( 'Depth' => $depth, - 'Content-Type' => 'application/xml' + 'Content-Type' => 'application/xml', )); $result = $this->parseMultiStatus($response['body']); // If depth was 0, we only return the top item - if ($depth===0) { + if ($depth === 0) { reset($result); $result = current($result); + return $result[200]; } $newResult = array(); - foreach($result as $href => $statusList) { - + foreach ($result as $href => $statusList) { $newResult[$href] = $statusList[200]; - } return $newResult; - } /** - * Updates a list of properties on the server + * Updates a list of properties on the server. * * The list of properties must have clark-notation properties for the keys, * and the actual (string) value for the value. If the value is null, an * attempt is made to delete the property. * * @todo Must be building the request using the DOM, and does not yet - * support complex properties. + * support complex properties + * * @param string $url - * @param array $properties - * @return void + * @param array $properties */ - public function propPatch($url, array $properties) { - - $body = '' . "\n"; - $body.= '' . "\n"; - - foreach($properties as $propName => $propValue) { + public function propPatch($url, array $properties) + { + $body = ''."\n"; + $body .= ''."\n"; + foreach ($properties as $propName => $propValue) { list( $namespace, $elementName ) = Sabre_DAV_XMLUtil::parseClarkNotation($propName); if ($propValue === null) { - - $body.="\n"; + $body .= "\n"; if ($namespace === 'DAV:') { - $body.=' ' . "\n"; + $body .= ' '."\n"; } else { - $body.=" \n"; + $body .= ' \n"; } - $body.="\n"; - + $body .= "\n"; } else { - - $body.="\n"; + $body .= "\n"; if ($namespace === 'DAV:') { - $body.=' '; + $body .= ' '; } else { - $body.=" "; + $body .= ' '; } // Shitty.. i know - $body.=htmlspecialchars($propValue, ENT_NOQUOTES, 'UTF-8'); + $body .= htmlspecialchars($propValue, ENT_NOQUOTES, 'UTF-8'); if ($namespace === 'DAV:') { - $body.='' . "\n"; + $body .= ''."\n"; } else { - $body.="\n"; + $body .= '\n"; } - $body.="\n"; - + $body .= "\n"; } - } - $body.= ''; + $body .= ''; $this->request('PROPPATCH', $url, $body, array( - 'Content-Type' => 'application/xml' + 'Content-Type' => 'application/xml', )); - } /** - * Performs an HTTP options request + * Performs an HTTP options request. * * This method returns all the features from the 'DAV:' header as an array. * If there was no DAV header, or no contents this method will return an @@ -244,19 +231,19 @@ class Sabre_DAV_Client { * * @return array */ - public function options() { - + public function options() + { $result = $this->request('OPTIONS'); if (!isset($result['headers']['dav'])) { return array(); } $features = explode(',', $result['headers']['dav']); - foreach($features as &$v) { + foreach ($features as &$v) { $v = trim($v); } - return $features; + return $features; } /** @@ -274,11 +261,12 @@ class Sabre_DAV_Client { * @param string $method * @param string $url * @param string $body - * @param array $headers + * @param array $headers + * * @return array */ - public function request($method, $url = '', $body = null, $headers = array()) { - + public function request($method, $url = '', $body = null, $headers = array()) + { $url = $this->getAbsoluteUrl($url); $curlSettings = array( @@ -292,7 +280,7 @@ class Sabre_DAV_Client { ); switch ($method) { - case 'HEAD' : + case 'HEAD': // do not read body with HEAD requests (this is neccessary because cURL does not ignore the body with HEAD // requests when the Content-Length header is given - which in turn is perfectly valid according to HTTP @@ -311,10 +299,8 @@ class Sabre_DAV_Client { // Adding HTTP headers $nHeaders = array(); - foreach($headers as $key=>$value) { - - $nHeaders[] = $key . ': ' . $value; - + foreach ($headers as $key => $value) { + $nHeaders[] = $key.': '.$value; } $curlSettings[CURLOPT_HTTPHEADER] = $nHeaders; @@ -331,7 +317,7 @@ class Sabre_DAV_Client { $curlType |= CURLAUTH_DIGEST; } $curlSettings[CURLOPT_HTTPAUTH] = $curlType; - $curlSettings[CURLOPT_USERPWD] = $this->userName . ':' . $this->password; + $curlSettings[CURLOPT_USERPWD] = $this->userName.':'.$this->password; } list( @@ -350,15 +336,15 @@ class Sabre_DAV_Client { $headerBlob = explode("\r\n\r\n", trim($headerBlob, "\r\n")); // We only care about the last set of headers - $headerBlob = $headerBlob[count($headerBlob)-1]; + $headerBlob = $headerBlob[count($headerBlob) - 1]; // Splitting headers $headerBlob = explode("\r\n", $headerBlob); $headers = array(); - foreach($headerBlob as $header) { + foreach ($headerBlob as $header) { $parts = explode(':', $header, 2); - if (count($parts)==2) { + if (count($parts) == 2) { $headers[strtolower(trim($parts[0]))] = trim($parts[1]); } } @@ -366,46 +352,45 @@ class Sabre_DAV_Client { $response = array( 'body' => $response, 'statusCode' => $curlInfo['http_code'], - 'headers' => $headers + 'headers' => $headers, ); if ($curlErrNo) { - throw new Sabre_DAV_Exception('[CURL] Error while making request: ' . $curlError . ' (error code: ' . $curlErrNo . ')'); + throw new Sabre_DAV_Exception('[CURL] Error while making request: '.$curlError.' (error code: '.$curlErrNo.')'); } - if ($response['statusCode']>=400) { + if ($response['statusCode'] >= 400) { switch ($response['statusCode']) { - case 400 : + case 400: throw new Sabre_DAV_Exception_BadRequest('Bad request'); - case 401 : + case 401: throw new Sabre_DAV_Exception_NotAuthenticated('Not authenticated'); - case 402 : + case 402: throw new Sabre_DAV_Exception_PaymentRequired('Payment required'); - case 403 : + case 403: throw new Sabre_DAV_Exception_Forbidden('Forbidden'); case 404: throw new Sabre_DAV_Exception_NotFound('Resource not found.'); - case 405 : + case 405: throw new Sabre_DAV_Exception_MethodNotAllowed('Method not allowed'); - case 409 : + case 409: throw new Sabre_DAV_Exception_Conflict('Conflict'); - case 412 : + case 412: throw new Sabre_DAV_Exception_PreconditionFailed('Precondition failed'); - case 416 : + case 416: throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('Requested Range Not Satisfiable'); - case 500 : + case 500: throw new Sabre_DAV_Exception('Internal server error'); - case 501 : + case 501: throw new Sabre_DAV_Exception_NotImplemented('Not Implemeneted'); - case 507 : + case 507: throw new Sabre_DAV_Exception_InsufficientStorage('Insufficient storage'); default: - throw new Sabre_DAV_Exception('HTTP error response. (errorcode ' . $response['statusCode'] . ')'); + throw new Sabre_DAV_Exception('HTTP error response. (errorcode '.$response['statusCode'].')'); } } return $response; - } /** @@ -415,11 +400,12 @@ class Sabre_DAV_Client { * becomes easier to unittest. * * @param string $url - * @param array $settings + * @param array $settings + * * @return array */ - protected function curlRequest($url, $settings) { - + protected function curlRequest($url, $settings) + { $curl = curl_init($url); curl_setopt_array($curl, $settings); @@ -427,9 +413,8 @@ class Sabre_DAV_Client { curl_exec($curl), curl_getinfo($curl), curl_errno($curl), - curl_error($curl) + curl_error($curl), ); - } /** @@ -437,9 +422,11 @@ class Sabre_DAV_Client { * urls are expanded based on the base url as given by the server. * * @param string $url + * * @return string */ - protected function getAbsoluteUrl($url) { + protected function getAbsoluteUrl($url) + { // If the url starts with http:// or https://, the url is already absolute. if (preg_match('/^http(s?):\/\//', $url)) { @@ -448,18 +435,18 @@ class Sabre_DAV_Client { // If the url starts with a slash, we must calculate the url based off // the root of the base url. - if (strpos($url,'/') === 0) { + if (strpos($url, '/') === 0) { $parts = parse_url($this->baseUri); - return $parts['scheme'] . '://' . $parts['host'] . (isset($parts['port'])?':' . $parts['port']:'') . $url; + + return $parts['scheme'].'://'.$parts['host'].(isset($parts['port']) ? ':'.$parts['port'] : '').$url; } // Otherwise... - return $this->baseUri . $url; - + return $this->baseUri.$url; } /** - * Parses a WebDAV multistatus response body + * Parses a WebDAV multistatus response body. * * This method returns an array with the following structure * @@ -481,12 +468,13 @@ class Sabre_DAV_Client { * * * @param string $body xml body + * * @return array */ - public function parseMultiStatus($body) { - + public function parseMultiStatus($body) + { $responseXML = simplexml_load_string($body, null, LIBXML_NOBLANKS | LIBXML_NOCDATA); - if ($responseXML===false) { + if ($responseXML === false) { throw new InvalidArgumentException('The passed data is not valid XML'); } @@ -494,29 +482,24 @@ class Sabre_DAV_Client { $propResult = array(); - foreach($responseXML->xpath('d:response') as $response) { + foreach ($responseXML->xpath('d:response') as $response) { $response->registerXPathNamespace('d', 'DAV:'); $href = $response->xpath('d:href'); - $href = (string)$href[0]; + $href = (string) $href[0]; $properties = array(); - foreach($response->xpath('d:propstat') as $propStat) { - + foreach ($response->xpath('d:propstat') as $propStat) { $propStat->registerXPathNamespace('d', 'DAV:'); $status = $propStat->xpath('d:status'); - list($httpVersion, $statusCode, $message) = explode(' ', (string)$status[0],3); + list($httpVersion, $statusCode, $message) = explode(' ', (string) $status[0], 3); $properties[$statusCode] = Sabre_DAV_XMLUtil::parseProperties(dom_import_simplexml($propStat), $this->propertyMap); - } $propResult[$href] = $properties; - } return $propResult; - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Collection.php b/dav/SabreDAV/lib/Sabre/DAV/Collection.php index c7648a8a..0e10f761 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Collection.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Collection.php @@ -1,19 +1,17 @@ getChildren() as $child) { - - if ($child->getName()==$name) return $child; - + public function getChild($name) + { + foreach ($this->getChildren() as $child) { + if ($child->getName() == $name) { + return $child; + } } - throw new Sabre_DAV_Exception_NotFound('File not found: ' . $name); - + throw new Sabre_DAV_Exception_NotFound('File not found: '.$name); } /** @@ -45,25 +44,22 @@ abstract class Sabre_DAV_Collection extends Sabre_DAV_Node implements Sabre_DAV_ * It is generally a good idea to try and override this. Usually it can be optimized. * * @param string $name + * * @return bool */ - public function childExists($name) { - + public function childExists($name) + { try { - $this->getChild($name); + return true; - - } catch(Sabre_DAV_Exception_NotFound $e) { - + } catch (Sabre_DAV_Exception_NotFound $e) { return false; - } - } /** - * Creates a new file in the directory + * Creates a new file in the directory. * * Data will either be supplied as a stream resource, or in certain cases * as a string. Keep in mind that you may have to support either. @@ -82,29 +78,25 @@ abstract class Sabre_DAV_Collection extends Sabre_DAV_Node implements Sabre_DAV_ * return the same contents of what was submitted here, you are strongly * recommended to omit the ETag. * - * @param string $name Name of the file + * @param string $name Name of the file * @param resource|string $data Initial payload + * * @return null|string */ - public function createFile($name, $data = null) { - - throw new Sabre_DAV_Exception_Forbidden('Permission denied to create file (filename ' . $name . ')'); - + public function createFile($name, $data = null) + { + throw new Sabre_DAV_Exception_Forbidden('Permission denied to create file (filename '.$name.')'); } /** - * Creates a new subdirectory + * Creates a new subdirectory. * * @param string $name + * * @throws Sabre_DAV_Exception_Forbidden - * @return void */ - public function createDirectory($name) { - + public function createDirectory($name) + { throw new Sabre_DAV_Exception_Forbidden('Permission denied to create directory'); - } - - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Exception.php b/dav/SabreDAV/lib/Sabre/DAV/Exception.php index a2cd6cf5..790435d6 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Exception.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Exception.php @@ -1,14 +1,12 @@ lock) { - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:no-conflicting-lock'); + $error = $errorNode->ownerDocument->createElementNS('DAV:', 'd:no-conflicting-lock'); $errorNode->appendChild($error); - if (!is_object($this->lock)) var_dump($this->lock); - $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri)); + if (!is_object($this->lock)) { + var_dump($this->lock); + } + $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:', 'd:href', $this->lock->uri)); } - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Exception/FileNotFound.php b/dav/SabreDAV/lib/Sabre/DAV/Exception/FileNotFound.php index d76e400c..19563637 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Exception/FileNotFound.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Exception/FileNotFound.php @@ -1,19 +1,18 @@ ownerDocument->createElementNS('DAV:','d:valid-resourcetype'); + public function serialize(Sabre_DAV_Server $server, DOMElement $errorNode) + { + $error = $errorNode->ownerDocument->createElementNS('DAV:', 'd:valid-resourcetype'); $errorNode->appendChild($error); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php b/dav/SabreDAV/lib/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php index 80ab7aff..96566270 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Exception/LockTokenMatchesRequestUri.php @@ -1,39 +1,33 @@ message = 'The locktoken supplied does not match any locks on this entity'; - } /** - * This method allows the exception to include additional information into the WebDAV error response + * This method allows the exception to include additional information into the WebDAV error response. * * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void + * @param DOMElement $errorNode */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:lock-token-matches-request-uri'); + public function serialize(Sabre_DAV_Server $server, DOMElement $errorNode) + { + $error = $errorNode->ownerDocument->createElementNS('DAV:', 'd:lock-token-matches-request-uri'); $errorNode->appendChild($error); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Exception/Locked.php b/dav/SabreDAV/lib/Sabre/DAV/Exception/Locked.php index 976365ac..cbf2aba6 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Exception/Locked.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Exception/Locked.php @@ -1,67 +1,61 @@ lock = $lock; - } /** - * Returns the HTTP statuscode for this exception + * Returns the HTTP statuscode for this exception. * * @return int */ - public function getHTTPCode() { - + public function getHTTPCode() + { return 423; - } /** - * This method allows the exception to include additional information into the WebDAV error response + * This method allows the exception to include additional information into the WebDAV error response. * * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void + * @param DOMElement $errorNode */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $errorNode) + { if ($this->lock) { - $error = $errorNode->ownerDocument->createElementNS('DAV:','d:lock-token-submitted'); + $error = $errorNode->ownerDocument->createElementNS('DAV:', 'd:lock-token-submitted'); $errorNode->appendChild($error); - if (!is_object($this->lock)) var_dump($this->lock); - $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:','d:href',$this->lock->uri)); + if (!is_object($this->lock)) { + var_dump($this->lock); + } + $error->appendChild($errorNode->ownerDocument->createElementNS('DAV:', 'd:href', $this->lock->uri)); } - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Exception/MethodNotAllowed.php b/dav/SabreDAV/lib/Sabre/DAV/Exception/MethodNotAllowed.php index 31875751..1bba3649 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Exception/MethodNotAllowed.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Exception/MethodNotAllowed.php @@ -1,27 +1,24 @@ getAllowedMethods($server->getRequestUri()); return array( - 'Allow' => strtoupper(implode(', ',$methods)), + 'Allow' => strtoupper(implode(', ', $methods)), ); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Exception/NotAuthenticated.php b/dav/SabreDAV/lib/Sabre/DAV/Exception/NotAuthenticated.php index 87ca6244..77013df0 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Exception/NotAuthenticated.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Exception/NotAuthenticated.php @@ -1,28 +1,24 @@ header = $header; - } /** - * Returns the HTTP statuscode for this exception + * Returns the HTTP statuscode for this exception. * * @return int */ - public function getHTTPCode() { - + public function getHTTPCode() + { return 412; - } /** - * This method allows the exception to include additional information into the WebDAV error response + * This method allows the exception to include additional information into the WebDAV error response. * * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void + * @param DOMElement $errorNode */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $errorNode) + { if ($this->header) { $prop = $errorNode->ownerDocument->createElement('s:header'); $prop->nodeValue = $this->header; $errorNode->appendChild($prop); } - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Exception/ReportNotImplemented.php b/dav/SabreDAV/lib/Sabre/DAV/Exception/ReportNotImplemented.php index e86800f3..bf11630a 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Exception/ReportNotImplemented.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Exception/ReportNotImplemented.php @@ -1,30 +1,25 @@ ownerDocument->createElementNS('DAV:','d:supported-report'); + public function serialize(Sabre_DAV_Server $server, DOMElement $errorNode) + { + $error = $errorNode->ownerDocument->createElementNS('DAV:', 'd:supported-report'); $errorNode->appendChild($error); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php b/dav/SabreDAV/lib/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php index 29ee3654..352b8208 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Exception/RequestedRangeNotSatisfiable.php @@ -1,29 +1,24 @@ path . '/' . $name; - file_put_contents($newPath,$data); - + public function createFile($name, $data = null) + { + $newPath = $this->path.'/'.$name; + file_put_contents($newPath, $data); } /** - * Creates a new subdirectory + * Creates a new subdirectory. * * @param string $name - * @return void */ - public function createDirectory($name) { - - $newPath = $this->path . '/' . $name; + public function createDirectory($name) + { + $newPath = $this->path.'/'.$name; mkdir($newPath); - } /** - * Returns a specific child node, referenced by its name + * Returns a specific child node, referenced by its name. * * This method must throw Sabre_DAV_Exception_NotFound if the node does not * exist. * * @param string $name + * * @throws Sabre_DAV_Exception_NotFound + * * @return Sabre_DAV_INode */ - public function getChild($name) { - - $path = $this->path . '/' . $name; - - if (!file_exists($path)) throw new Sabre_DAV_Exception_NotFound('File with name ' . $path . ' could not be located'); - - if (is_dir($path)) { - - return new Sabre_DAV_FS_Directory($path); - - } else { - - return new Sabre_DAV_FS_File($path); + public function getChild($name) + { + $path = $this->path.'/'.$name; + if (!file_exists($path)) { + throw new Sabre_DAV_Exception_NotFound('File with name '.$path.' could not be located'); } + if (is_dir($path)) { + return new self($path); + } else { + return new Sabre_DAV_FS_File($path); + } } /** - * Returns an array with all the child nodes + * Returns an array with all the child nodes. * * @return Sabre_DAV_INode[] */ - public function getChildren() { - + public function getChildren() + { $nodes = array(); - foreach(scandir($this->path) as $node) if($node!='.' && $node!='..') $nodes[] = $this->getChild($node); - return $nodes; + foreach (scandir($this->path) as $node) { + if ($node != '.' && $node != '..') { + $nodes[] = $this->getChild($node); + } + } + return $nodes; } /** * Checks if a child exists. * * @param string $name + * * @return bool */ - public function childExists($name) { + public function childExists($name) + { + $path = $this->path.'/'.$name; - $path = $this->path . '/' . $name; return file_exists($path); - } /** - * Deletes all files in this directory, and then itself - * - * @return void + * Deletes all files in this directory, and then itself. */ - public function delete() { - - foreach($this->getChildren() as $child) $child->delete(); + public function delete() + { + foreach ($this->getChildren() as $child) { + $child->delete(); + } rmdir($this->path); - } /** - * Returns available diskspace information + * Returns available diskspace information. * * @return array */ - public function getQuotaInfo() { - + public function getQuotaInfo() + { return array( - disk_total_space($this->path)-disk_free_space($this->path), - disk_free_space($this->path) + disk_total_space($this->path) - disk_free_space($this->path), + disk_free_space($this->path), ); - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/FS/File.php b/dav/SabreDAV/lib/Sabre/DAV/FS/File.php index 6a8039fe..1af56403 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/FS/File.php +++ b/dav/SabreDAV/lib/Sabre/DAV/FS/File.php @@ -1,63 +1,54 @@ path,$data); - + public function put($data) + { + file_put_contents($this->path, $data); } /** - * Returns the data + * Returns the data. * * @return string */ - public function get() { - - return fopen($this->path,'r'); - + public function get() + { + return fopen($this->path, 'r'); } /** - * Delete the current file - * - * @return void + * Delete the current file. */ - public function delete() { - + public function delete() + { unlink($this->path); - } /** - * Returns the size of the node, in bytes + * Returns the size of the node, in bytes. * * @return int */ - public function getSize() { - + public function getSize() + { return filesize($this->path); - } /** - * Returns the ETag for a file + * Returns the ETag for a file. * * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. * The ETag is an arbitrary string, but MUST be surrounded by double-quotes. @@ -66,24 +57,20 @@ class Sabre_DAV_FS_File extends Sabre_DAV_FS_Node implements Sabre_DAV_IFile { * * @return mixed */ - public function getETag() { - + public function getETag() + { return null; - } /** - * Returns the mime-type for a file + * Returns the mime-type for a file. * * If null is returned, we'll assume application/octet-stream * * @return mixed */ - public function getContentType() { - + public function getContentType() + { return null; - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/FS/Node.php b/dav/SabreDAV/lib/Sabre/DAV/FS/Node.php index 1283e9d0..8fe33eaf 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/FS/Node.php +++ b/dav/SabreDAV/lib/Sabre/DAV/FS/Node.php @@ -1,80 +1,68 @@ path = $path; - } - - /** - * Returns the name of the node + * Returns the name of the node. * * @return string */ - public function getName() { + public function getName() + { + list(, $name) = Sabre_DAV_URLUtil::splitPath($this->path); - list(, $name) = Sabre_DAV_URLUtil::splitPath($this->path); return $name; - } /** - * Renames the node + * Renames the node. * * @param string $name The new name - * @return void */ - public function setName($name) { - - list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); + public function setName($name) + { + list($parentPath) = Sabre_DAV_URLUtil::splitPath($this->path); list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); - $newPath = $parentPath . '/' . $newName; - rename($this->path,$newPath); + $newPath = $parentPath.'/'.$newName; + rename($this->path, $newPath); $this->path = $newPath; - } - - /** - * Returns the last modification time, as a unix timestamp + * Returns the last modification time, as a unix timestamp. * * @return int */ - public function getLastModified() { - + public function getLastModified() + { return filemtime($this->path); - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/FSExt/Directory.php b/dav/SabreDAV/lib/Sabre/DAV/FSExt/Directory.php index 70dfdc2c..06a90d92 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/FSExt/Directory.php +++ b/dav/SabreDAV/lib/Sabre/DAV/FSExt/Directory.php @@ -1,18 +1,16 @@ path . '/' . $name; - file_put_contents($newPath,$data); - - return '"' . md5_file($newPath) . '"'; + if ($name == '.' || $name == '..') { + throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); + } + $newPath = $this->path.'/'.$name; + file_put_contents($newPath, $data); + return '"'.md5_file($newPath).'"'; } /** - * Creates a new subdirectory + * Creates a new subdirectory. * * @param string $name - * @return void */ - public function createDirectory($name) { + public function createDirectory($name) + { // We're not allowing dots - if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - $newPath = $this->path . '/' . $name; + if ($name == '.' || $name == '..') { + throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); + } + $newPath = $this->path.'/'.$name; mkdir($newPath); - } /** - * Returns a specific child node, referenced by its name + * Returns a specific child node, referenced by its name. * * This method must throw Sabre_DAV_Exception_NotFound if the node does not * exist. * * @param string $name + * * @throws Sabre_DAV_Exception_NotFound + * * @return Sabre_DAV_INode */ - public function getChild($name) { - - $path = $this->path . '/' . $name; - - if (!file_exists($path)) throw new Sabre_DAV_Exception_NotFound('File could not be located'); - if ($name=='.' || $name=='..') throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); - - if (is_dir($path)) { - - return new Sabre_DAV_FSExt_Directory($path); - - } else { - - return new Sabre_DAV_FSExt_File($path); + public function getChild($name) + { + $path = $this->path.'/'.$name; + if (!file_exists($path)) { + throw new Sabre_DAV_Exception_NotFound('File could not be located'); + } + if ($name == '.' || $name == '..') { + throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); } + if (is_dir($path)) { + return new self($path); + } else { + return new Sabre_DAV_FSExt_File($path); + } } /** * Checks if a child exists. * * @param string $name + * * @return bool */ - public function childExists($name) { - - if ($name=='.' || $name=='..') + public function childExists($name) + { + if ($name == '.' || $name == '..') { throw new Sabre_DAV_Exception_Forbidden('Permission denied to . and ..'); + } + + $path = $this->path.'/'.$name; - $path = $this->path . '/' . $name; return file_exists($path); - } /** - * Returns an array with all the child nodes + * Returns an array with all the child nodes. * * @return Sabre_DAV_INode[] */ - public function getChildren() { - + public function getChildren() + { $nodes = array(); - foreach(scandir($this->path) as $node) if($node!='.' && $node!='..' && $node!='.sabredav') $nodes[] = $this->getChild($node); - return $nodes; + foreach (scandir($this->path) as $node) { + if ($node != '.' && $node != '..' && $node != '.sabredav') { + $nodes[] = $this->getChild($node); + } + } + return $nodes; } /** - * Deletes all files in this directory, and then itself + * Deletes all files in this directory, and then itself. * * @return bool */ - public function delete() { + public function delete() + { // Deleting all children - foreach($this->getChildren() as $child) $child->delete(); + foreach ($this->getChildren() as $child) { + $child->delete(); + } // Removing resource info, if its still around - if (file_exists($this->path . '/.sabredav')) unlink($this->path . '/.sabredav'); + if (file_exists($this->path.'/.sabredav')) { + unlink($this->path.'/.sabredav'); + } // Removing the directory itself rmdir($this->path); return parent::delete(); - } /** - * Returns available diskspace information + * Returns available diskspace information. * * @return array */ - public function getQuotaInfo() { - + public function getQuotaInfo() + { return array( - disk_total_space($this->path)-disk_free_space($this->path), - disk_free_space($this->path) + disk_total_space($this->path) - disk_free_space($this->path), + disk_free_space($this->path), ); - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/FSExt/File.php b/dav/SabreDAV/lib/Sabre/DAV/FSExt/File.php index 590fb808..191a14b5 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/FSExt/File.php +++ b/dav/SabreDAV/lib/Sabre/DAV/FSExt/File.php @@ -1,80 +1,77 @@ path,$data); - return '"' . md5_file($this->path) . '"'; + public function put($data) + { + file_put_contents($this->path, $data); + return '"'.md5_file($this->path).'"'; } /** - * Updates the data at a given offset + * Updates the data at a given offset. * * The data argument is a readable stream resource. * The offset argument is a 0-based offset where the data should be * written. * * param resource|string $data - * @return void */ - public function putRange($data, $offset) { - + public function putRange($data, $offset) + { $f = fopen($this->path, 'c'); - fseek($f,$offset-1); + fseek($f, $offset - 1); if (is_string($data)) { fwrite($f, $data); } else { - stream_copy_to_stream($data,$f); + stream_copy_to_stream($data, $f); } fclose($f); - return '"' . md5_file($this->path) . '"'; + return '"'.md5_file($this->path).'"'; } /** - * Returns the data + * Returns the data. * * @return resource */ - public function get() { - - return fopen($this->path,'r'); - + public function get() + { + return fopen($this->path, 'r'); } /** - * Delete the current file + * Delete the current file. * * @return bool */ - public function delete() { - + public function delete() + { unlink($this->path); - return parent::delete(); + return parent::delete(); } /** - * Returns the ETag for a file + * Returns the ETag for a file. * * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. * The ETag is an arbitrary string, but MUST be surrounded by double-quotes. @@ -83,35 +80,30 @@ class Sabre_DAV_FSExt_File extends Sabre_DAV_FSExt_Node implements Sabre_DAV_Par * * @return string|null */ - public function getETag() { - - return '"' . md5_file($this->path). '"'; - + public function getETag() + { + return '"'.md5_file($this->path).'"'; } /** - * Returns the mime-type for a file + * Returns the mime-type for a file. * * If null is returned, we'll assume application/octet-stream * * @return string|null */ - public function getContentType() { - + public function getContentType() + { return null; - } /** - * Returns the size of the file, in bytes + * Returns the size of the file, in bytes. * * @return int */ - public function getSize() { - + public function getSize() + { return filesize($this->path); - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/FSExt/Node.php b/dav/SabreDAV/lib/Sabre/DAV/FSExt/Node.php index 68ca06be..bc391c9b 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/FSExt/Node.php +++ b/dav/SabreDAV/lib/Sabre/DAV/FSExt/Node.php @@ -1,30 +1,30 @@ getResourceData(); - foreach($properties as $propertyName=>$propertyValue) { + foreach ($properties as $propertyName => $propertyValue) { // If it was null, we need to delete the property if (is_null($propertyValue)) { @@ -34,68 +34,74 @@ abstract class Sabre_DAV_FSExt_Node extends Sabre_DAV_FS_Node implements Sabre_D } else { $resourceData['properties'][$propertyName] = $propertyValue; } - } $this->putResourceData($resourceData); + return true; } /** - * Returns a list of properties for this nodes.; + * Returns a list of properties for this nodes.;. * * The properties list is a list of propertynames the client requested, encoded as xmlnamespace#tagName, for example: http://www.example.org/namespace#author * If the array is empty, all properties should be returned * * @param array $properties + * * @return array */ - function getProperties($properties) { - + public function getProperties($properties) + { $resourceData = $this->getResourceData(); // if the array was empty, we need to return everything - if (!$properties) return $resourceData['properties']; + if (!$properties) { + return $resourceData['properties']; + } $props = array(); - foreach($properties as $property) { - if (isset($resourceData['properties'][$property])) $props[$property] = $resourceData['properties'][$property]; + foreach ($properties as $property) { + if (isset($resourceData['properties'][$property])) { + $props[$property] = $resourceData['properties'][$property]; + } } return $props; - } /** - * Returns the path to the resource file + * Returns the path to the resource file. * * @return string */ - protected function getResourceInfoPath() { - + protected function getResourceInfoPath() + { list($parentDir) = Sabre_DAV_URLUtil::splitPath($this->path); - return $parentDir . '/.sabredav'; + return $parentDir.'/.sabredav'; } /** - * Returns all the stored resource information + * Returns all the stored resource information. * * @return array */ - protected function getResourceData() { - + protected function getResourceData() + { $path = $this->getResourceInfoPath(); - if (!file_exists($path)) return array('properties' => array()); + if (!file_exists($path)) { + return array('properties' => array()); + } // opening up the file, and creating a shared lock - $handle = fopen($path,'r'); - flock($handle,LOCK_SH); + $handle = fopen($path, 'r'); + flock($handle, LOCK_SH); $data = ''; // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); + while (!feof($handle)) { + $data .= fread($handle, 8192); } // We're all good @@ -108,105 +114,104 @@ abstract class Sabre_DAV_FSExt_Node extends Sabre_DAV_FS_Node implements Sabre_D } $data = $data[$this->getName()]; - if (!isset($data['properties'])) $data['properties'] = array(); - return $data; + if (!isset($data['properties'])) { + $data['properties'] = array(); + } + return $data; } /** - * Updates the resource information + * Updates the resource information. * * @param array $newData - * @return void */ - protected function putResourceData(array $newData) { - + protected function putResourceData(array $newData) + { $path = $this->getResourceInfoPath(); // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); + $handle = fopen($path, 'a+'); + flock($handle, LOCK_EX); $data = ''; rewind($handle); // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); + while (!feof($handle)) { + $data .= fread($handle, 8192); } // Unserializing and checking if the resource file contains data for this file $data = unserialize($data); $data[$this->getName()] = $newData; - ftruncate($handle,0); + ftruncate($handle, 0); rewind($handle); - fwrite($handle,serialize($data)); + fwrite($handle, serialize($data)); fclose($handle); - } /** - * Renames the node + * Renames the node. * * @param string $name The new name - * @return void */ - public function setName($name) { - - list($parentPath, ) = Sabre_DAV_URLUtil::splitPath($this->path); + public function setName($name) + { + list($parentPath) = Sabre_DAV_URLUtil::splitPath($this->path); list(, $newName) = Sabre_DAV_URLUtil::splitPath($name); - $newPath = $parentPath . '/' . $newName; + $newPath = $parentPath.'/'.$newName; // We're deleting the existing resourcedata, and recreating it // for the new path. $resourceData = $this->getResourceData(); $this->deleteResourceData(); - rename($this->path,$newPath); + rename($this->path, $newPath); $this->path = $newPath; $this->putResourceData($resourceData); - - } /** * @return bool */ - public function deleteResourceData() { + public function deleteResourceData() + { // When we're deleting this node, we also need to delete any resource information $path = $this->getResourceInfoPath(); - if (!file_exists($path)) return true; + if (!file_exists($path)) { + return true; + } // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); + $handle = fopen($path, 'a+'); + flock($handle, LOCK_EX); $data = ''; rewind($handle); // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); + while (!feof($handle)) { + $data .= fread($handle, 8192); } // Unserializing and checking if the resource file contains data for this file $data = unserialize($data); - if (isset($data[$this->getName()])) unset($data[$this->getName()]); - ftruncate($handle,0); + if (isset($data[$this->getName()])) { + unset($data[$this->getName()]); + } + ftruncate($handle, 0); rewind($handle); - fwrite($handle,serialize($data)); + fwrite($handle, serialize($data)); fclose($handle); return true; } - public function delete() { - + public function delete() + { return $this->deleteResourceData(); - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/File.php b/dav/SabreDAV/lib/Sabre/DAV/File.php index 3126bd8d..b4c14a42 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/File.php +++ b/dav/SabreDAV/lib/Sabre/DAV/File.php @@ -1,44 +1,39 @@ dataDir = $dataDir; - } - protected function getFileNameForUri($uri) { - - return $this->dataDir . '/sabredav_' . md5($uri) . '.locks'; - + protected function getFileNameForUri($uri) + { + return $this->dataDir.'/sabredav_'.md5($uri).'.locks'; } - /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects + * Returns a list of Sabre_DAV_Locks_LockInfo objects. * * This method should return all the locks for a particular uri, including * locks that might be set on a parent uri. @@ -51,108 +47,117 @@ class Sabre_DAV_Locks_Backend_FS extends Sabre_DAV_Locks_Backend_Abstract { * any locks in the subtree of the uri for locks. * * @param string $uri - * @param bool $returnChildLocks + * @param bool $returnChildLocks + * * @return array */ - public function getLocks($uri, $returnChildLocks) { - + public function getLocks($uri, $returnChildLocks) + { $lockList = array(); $currentPath = ''; - foreach(explode('/',$uri) as $uriPart) { + foreach (explode('/', $uri) as $uriPart) { // weird algorithm that can probably be improved, but we're traversing the path top down - if ($currentPath) $currentPath.='/'; - $currentPath.=$uriPart; + if ($currentPath) { + $currentPath .= '/'; + } + $currentPath .= $uriPart; $uriLocks = $this->getData($currentPath); - foreach($uriLocks as $uriLock) { + foreach ($uriLocks as $uriLock) { // Unless we're on the leaf of the uri-tree we should ignore locks with depth 0 - if($uri==$currentPath || $uriLock->depth!=0) { + if ($uri == $currentPath || $uriLock->depth != 0) { $uriLock->uri = $currentPath; $lockList[] = $uriLock; } - } - } // Checking if we can remove any of these locks - foreach($lockList as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($lockList[$k]); + foreach ($lockList as $k => $lock) { + if (time() > $lock->timeout + $lock->created) { + unset($lockList[$k]); + } } - return $lockList; + return $lockList; } /** - * Locks a uri + * Locks a uri. * - * @param string $uri + * @param string $uri * @param Sabre_DAV_Locks_LockInfo $lockInfo + * * @return bool */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + public function lock($uri, Sabre_DAV_Locks_LockInfo $lockInfo) + { // We're making the lock timeout 30 minutes $lockInfo->timeout = 1800; $lockInfo->created = time(); - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - if ($lock->token == $lockInfo->token) unset($locks[$k]); - } - $locks[] = $lockInfo; - $this->putData($uri,$locks); - return true; - - } - - /** - * Removes a lock from a uri - * - * @param string $uri - * @param Sabre_DAV_Locks_LockInfo $lockInfo - * @return bool - */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - $locks = $this->getLocks($uri,false); - foreach($locks as $k=>$lock) { - + $locks = $this->getLocks($uri, false); + foreach ($locks as $k => $lock) { if ($lock->token == $lockInfo->token) { - unset($locks[$k]); - $this->putData($uri,$locks); - return true; - } } - return false; + $locks[] = $lockInfo; + $this->putData($uri, $locks); + return true; } /** - * Returns the stored data for a uri + * Removes a lock from a uri. + * + * @param string $uri + * @param Sabre_DAV_Locks_LockInfo $lockInfo + * + * @return bool + */ + public function unlock($uri, Sabre_DAV_Locks_LockInfo $lockInfo) + { + $locks = $this->getLocks($uri, false); + foreach ($locks as $k => $lock) { + if ($lock->token == $lockInfo->token) { + unset($locks[$k]); + $this->putData($uri, $locks); + + return true; + } + } + + return false; + } + + /** + * Returns the stored data for a uri. * * @param string $uri + * * @return array */ - protected function getData($uri) { - + protected function getData($uri) + { $path = $this->getFilenameForUri($uri); - if (!file_exists($path)) return array(); + if (!file_exists($path)) { + return array(); + } // opening up the file, and creating a shared lock - $handle = fopen($path,'r'); - flock($handle,LOCK_SH); + $handle = fopen($path, 'r'); + flock($handle, LOCK_SH); $data = ''; // Reading data until the eof - while(!feof($handle)) { - $data.=fread($handle,8192); + while (!feof($handle)) { + $data .= fread($handle, 8192); } // We're all good @@ -160,32 +165,30 @@ class Sabre_DAV_Locks_Backend_FS extends Sabre_DAV_Locks_Backend_Abstract { // Unserializing and checking if the resource file contains data for this file $data = unserialize($data); - if (!$data) return array(); - return $data; + if (!$data) { + return array(); + } + return $data; } /** - * Updates the lock information + * Updates the lock information. * * @param string $uri - * @param array $newData - * @return void + * @param array $newData */ - protected function putData($uri,array $newData) { - + protected function putData($uri, array $newData) + { $path = $this->getFileNameForUri($uri); // opening up the file, and creating a shared lock - $handle = fopen($path,'a+'); - flock($handle,LOCK_EX); - ftruncate($handle,0); + $handle = fopen($path, 'a+'); + flock($handle, LOCK_EX); + ftruncate($handle, 0); rewind($handle); - fwrite($handle,serialize($newData)); + fwrite($handle, serialize($newData)); fclose($handle); - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Locks/Backend/File.php b/dav/SabreDAV/lib/Sabre/DAV/Locks/Backend/File.php index c33f9635..b333d0d3 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Locks/Backend/File.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Locks/Backend/File.php @@ -8,34 +8,31 @@ * Note that this is not nearly as robust as a database, you are encouraged * to use the PDO backend instead. * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_DAV_Locks_Backend_File extends Sabre_DAV_Locks_Backend_Abstract { - +class Sabre_DAV_Locks_Backend_File extends Sabre_DAV_Locks_Backend_Abstract +{ /** - * The storage file + * The storage file. * * @var string */ private $locksFile; /** - * Constructor + * Constructor. * * @param string $locksFile path to file */ - public function __construct($locksFile) { - + public function __construct($locksFile) + { $this->locksFile = $locksFile; - } /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects + * Returns a list of Sabre_DAV_Locks_LockInfo objects. * * This method should return all the locks for a particular uri, including * locks that might be set on a parent uri. @@ -44,46 +41,47 @@ class Sabre_DAV_Locks_Backend_File extends Sabre_DAV_Locks_Backend_Abstract { * any locks in the subtree of the uri for locks. * * @param string $uri - * @param bool $returnChildLocks + * @param bool $returnChildLocks + * * @return array */ - public function getLocks($uri, $returnChildLocks) { - + public function getLocks($uri, $returnChildLocks) + { $newLocks = array(); $locks = $this->getData(); - foreach($locks as $lock) { - + foreach ($locks as $lock) { if ($lock->uri === $uri || //deep locks on parents - ($lock->depth!=0 && strpos($uri, $lock->uri . '/')===0) || + ($lock->depth != 0 && strpos($uri, $lock->uri.'/') === 0) || // locks on children - ($returnChildLocks && (strpos($lock->uri, $uri . '/')===0)) ) { - + ($returnChildLocks && (strpos($lock->uri, $uri.'/') === 0))) { $newLocks[] = $lock; - } - } // Checking if we can remove any of these locks - foreach($newLocks as $k=>$lock) { - if (time() > $lock->timeout + $lock->created) unset($newLocks[$k]); + foreach ($newLocks as $k => $lock) { + if (time() > $lock->timeout + $lock->created) { + unset($newLocks[$k]); + } } - return $newLocks; + return $newLocks; } /** - * Locks a uri + * Locks a uri. * - * @param string $uri + * @param string $uri * @param Sabre_DAV_Locks_LockInfo $lockInfo + * * @return bool */ - public function lock($uri, Sabre_DAV_Locks_LockInfo $lockInfo) { + public function lock($uri, Sabre_DAV_Locks_LockInfo $lockInfo) + { // We're making the lock timeout 30 minutes $lockInfo->timeout = 1800; @@ -92,7 +90,7 @@ class Sabre_DAV_Locks_Backend_File extends Sabre_DAV_Locks_Backend_Abstract { $locks = $this->getData(); - foreach($locks as $k=>$lock) { + foreach ($locks as $k => $lock) { if ( ($lock->token == $lockInfo->token) || (time() > $lock->timeout + $lock->created) @@ -102,32 +100,31 @@ class Sabre_DAV_Locks_Backend_File extends Sabre_DAV_Locks_Backend_Abstract { } $locks[] = $lockInfo; $this->putData($locks); - return true; + return true; } /** - * Removes a lock from a uri + * Removes a lock from a uri. * - * @param string $uri + * @param string $uri * @param Sabre_DAV_Locks_LockInfo $lockInfo + * * @return bool */ - public function unlock($uri, Sabre_DAV_Locks_LockInfo $lockInfo) { - + public function unlock($uri, Sabre_DAV_Locks_LockInfo $lockInfo) + { $locks = $this->getData(); - foreach($locks as $k=>$lock) { - + foreach ($locks as $k => $lock) { if ($lock->token == $lockInfo->token) { - unset($locks[$k]); $this->putData($locks); - return true; + return true; } } - return false; + return false; } /** @@ -135,13 +132,15 @@ class Sabre_DAV_Locks_Backend_File extends Sabre_DAV_Locks_Backend_Abstract { * * @return array */ - protected function getData() { - - if (!file_exists($this->locksFile)) return array(); + protected function getData() + { + if (!file_exists($this->locksFile)) { + return array(); + } // opening up the file, and creating a shared lock - $handle = fopen($this->locksFile,'r'); - flock($handle,LOCK_SH); + $handle = fopen($this->locksFile, 'r'); + flock($handle, LOCK_SH); // Reading data until the eof $data = stream_get_contents($handle); @@ -151,31 +150,30 @@ class Sabre_DAV_Locks_Backend_File extends Sabre_DAV_Locks_Backend_Abstract { // Unserializing and checking if the resource file contains data for this file $data = unserialize($data); - if (!$data) return array(); - return $data; + if (!$data) { + return array(); + } + return $data; } /** - * Saves the lockdata + * Saves the lockdata. * * @param array $newData - * @return void */ - protected function putData(array $newData) { + protected function putData(array $newData) + { // opening up the file, and creating an exclusive lock - $handle = fopen($this->locksFile,'a+'); - flock($handle,LOCK_EX); + $handle = fopen($this->locksFile, 'a+'); + flock($handle, LOCK_EX); // We can only truncate and rewind once the lock is acquired. - ftruncate($handle,0); + ftruncate($handle, 0); rewind($handle); - fwrite($handle,serialize($newData)); + fwrite($handle, serialize($newData)); fclose($handle); - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Locks/Backend/PDO.php b/dav/SabreDAV/lib/Sabre/DAV/Locks/Backend/PDO.php index acce8063..3baf441f 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Locks/Backend/PDO.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Locks/Backend/PDO.php @@ -6,16 +6,14 @@ * This Lock Manager stores all its data in a database. You must pass a PDO * connection object in the constructor. * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_DAV_Locks_Backend_PDO extends Sabre_DAV_Locks_Backend_Abstract { - +class Sabre_DAV_Locks_Backend_PDO extends Sabre_DAV_Locks_Backend_Abstract +{ /** - * The PDO connection object + * The PDO connection object. * * @var pdo */ @@ -29,20 +27,19 @@ class Sabre_DAV_Locks_Backend_PDO extends Sabre_DAV_Locks_Backend_Abstract { protected $tableName; /** - * Constructor + * Constructor. * - * @param PDO $pdo + * @param PDO $pdo * @param string $tableName */ - public function __construct(PDO $pdo, $tableName = 'locks') { - + public function __construct(PDO $pdo, $tableName = 'locks') + { $this->pdo = $pdo; $this->tableName = $tableName; - } /** - * Returns a list of Sabre_DAV_Locks_LockInfo objects + * Returns a list of Sabre_DAV_Locks_LockInfo objects. * * This method should return all the locks for a particular uri, including * locks that might be set on a parent uri. @@ -51,50 +48,49 @@ class Sabre_DAV_Locks_Backend_PDO extends Sabre_DAV_Locks_Backend_Abstract { * any locks in the subtree of the uri for locks. * * @param string $uri - * @param bool $returnChildLocks + * @param bool $returnChildLocks + * * @return array */ - public function getLocks($uri, $returnChildLocks) { + public function getLocks($uri, $returnChildLocks) + { // NOTE: the following 10 lines or so could be easily replaced by // pure sql. MySQL's non-standard string concatenation prevents us // from doing this though. $query = 'SELECT owner, token, timeout, created, scope, depth, uri FROM '.$this->tableName.' WHERE ((created + timeout) > CAST(? AS UNSIGNED INTEGER)) AND ((uri = ?)'; - $params = array(time(),$uri); + $params = array(time(), $uri); // We need to check locks for every part in the uri. - $uriParts = explode('/',$uri); + $uriParts = explode('/', $uri); // We already covered the last part of the uri array_pop($uriParts); - $currentPath=''; + $currentPath = ''; - foreach($uriParts as $part) { + foreach ($uriParts as $part) { + if ($currentPath) { + $currentPath .= '/'; + } + $currentPath .= $part; - if ($currentPath) $currentPath.='/'; - $currentPath.=$part; - - $query.=' OR (depth!=0 AND uri = ?)'; + $query .= ' OR (depth!=0 AND uri = ?)'; $params[] = $currentPath; - } if ($returnChildLocks) { - - $query.=' OR (uri LIKE ?)'; - $params[] = $uri . '/%'; - + $query .= ' OR (uri LIKE ?)'; + $params[] = $uri.'/%'; } - $query.=')'; + $query .= ')'; $stmt = $this->pdo->prepare($query); $stmt->execute($params); $result = $stmt->fetchAll(); $lockList = array(); - foreach($result as $row) { - + foreach ($result as $row) { $lockInfo = new Sabre_DAV_Locks_LockInfo(); $lockInfo->owner = $row['owner']; $lockInfo->token = $row['token']; @@ -102,64 +98,61 @@ class Sabre_DAV_Locks_Backend_PDO extends Sabre_DAV_Locks_Backend_Abstract { $lockInfo->created = $row['created']; $lockInfo->scope = $row['scope']; $lockInfo->depth = $row['depth']; - $lockInfo->uri = $row['uri']; + $lockInfo->uri = $row['uri']; $lockList[] = $lockInfo; - } return $lockList; - } /** - * Locks a uri + * Locks a uri. * - * @param string $uri + * @param string $uri * @param Sabre_DAV_Locks_LockInfo $lockInfo + * * @return bool */ - public function lock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + public function lock($uri, Sabre_DAV_Locks_LockInfo $lockInfo) + { // We're making the lock timeout 30 minutes - $lockInfo->timeout = 30*60; + $lockInfo->timeout = 30 * 60; $lockInfo->created = time(); $lockInfo->uri = $uri; - $locks = $this->getLocks($uri,false); + $locks = $this->getLocks($uri, false); $exists = false; - foreach($locks as $lock) { - if ($lock->token == $lockInfo->token) $exists = true; + foreach ($locks as $lock) { + if ($lock->token == $lockInfo->token) { + $exists = true; + } } if ($exists) { $stmt = $this->pdo->prepare('UPDATE '.$this->tableName.' SET owner = ?, timeout = ?, scope = ?, depth = ?, uri = ?, created = ? WHERE token = ?'); - $stmt->execute(array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); + $stmt->execute(array($lockInfo->owner, $lockInfo->timeout, $lockInfo->scope, $lockInfo->depth, $uri, $lockInfo->created, $lockInfo->token)); } else { $stmt = $this->pdo->prepare('INSERT INTO '.$this->tableName.' (owner,timeout,scope,depth,uri,created,token) VALUES (?,?,?,?,?,?,?)'); - $stmt->execute(array($lockInfo->owner,$lockInfo->timeout,$lockInfo->scope,$lockInfo->depth,$uri,$lockInfo->created,$lockInfo->token)); + $stmt->execute(array($lockInfo->owner, $lockInfo->timeout, $lockInfo->scope, $lockInfo->depth, $uri, $lockInfo->created, $lockInfo->token)); } return true; - } - - /** - * Removes a lock from a uri + * Removes a lock from a uri. * - * @param string $uri + * @param string $uri * @param Sabre_DAV_Locks_LockInfo $lockInfo + * * @return bool */ - public function unlock($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - + public function unlock($uri, Sabre_DAV_Locks_LockInfo $lockInfo) + { $stmt = $this->pdo->prepare('DELETE FROM '.$this->tableName.' WHERE uri = ? AND token = ?'); - $stmt->execute(array($uri,$lockInfo->token)); - - return $stmt->rowCount()===1; + $stmt->execute(array($uri, $lockInfo->token)); + return $stmt->rowCount() === 1; } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Locks/LockInfo.php b/dav/SabreDAV/lib/Sabre/DAV/Locks/LockInfo.php index 9df014a4..ddbbc9b4 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Locks/LockInfo.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Locks/LockInfo.php @@ -1,81 +1,78 @@ addPlugin($lockPlugin); * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { - +class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin +{ /** - * locksBackend + * locksBackend. * * @var Sabre_DAV_Locks_Backend_Abstract */ private $locksBackend; /** - * server + * server. * * @var Sabre_DAV_Server */ private $server; /** - * __construct + * __construct. * * @param Sabre_DAV_Locks_Backend_Abstract $locksBackend */ - public function __construct(Sabre_DAV_Locks_Backend_Abstract $locksBackend = null) { - + public function __construct(Sabre_DAV_Locks_Backend_Abstract $locksBackend = null) + { $this->locksBackend = $locksBackend; - } /** - * Initializes the plugin + * Initializes the plugin. * * This method is automatically called by the Server class after addPlugin. * * @param Sabre_DAV_Server $server - * @return void */ - public function initialize(Sabre_DAV_Server $server) { - + public function initialize(Sabre_DAV_Server $server) + { $this->server = $server; - $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); - $server->subscribeEvent('beforeMethod',array($this,'beforeMethod'),50); - $server->subscribeEvent('afterGetProperties',array($this,'afterGetProperties')); - + $server->subscribeEvent('unknownMethod', array($this, 'unknownMethod')); + $server->subscribeEvent('beforeMethod', array($this, 'beforeMethod'), 50); + $server->subscribeEvent('afterGetProperties', array($this, 'afterGetProperties')); } /** @@ -68,10 +63,9 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { * * @return string */ - public function getPluginName() { - + public function getPluginName() + { return 'locks'; - } /** @@ -82,54 +76,57 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { * * @param string $method * @param string $uri + * * @return bool */ - public function unknownMethod($method, $uri) { + public function unknownMethod($method, $uri) + { + switch ($method) { - switch($method) { + case 'LOCK': $this->httpLock($uri); - case 'LOCK' : $this->httpLock($uri); return false; - case 'UNLOCK' : $this->httpUnlock($uri); return false; +return false; + case 'UNLOCK': $this->httpUnlock($uri); + +return false; } - } /** * This method is called after most properties have been found - * it allows us to add in any Lock-related properties + * it allows us to add in any Lock-related properties. * * @param string $path - * @param array $newProperties + * @param array $newProperties + * * @return bool */ - public function afterGetProperties($path, &$newProperties) { + public function afterGetProperties($path, &$newProperties) + { + foreach ($newProperties[404] as $propName => $discard) { + switch ($propName) { - foreach($newProperties[404] as $propName=>$discard) { - - switch($propName) { - - case '{DAV:}supportedlock' : + case '{DAV:}supportedlock': $val = false; - if ($this->locksBackend) $val = true; + if ($this->locksBackend) { + $val = true; + } $newProperties[200][$propName] = new Sabre_DAV_Property_SupportedLock($val); unset($newProperties[404][$propName]); break; - case '{DAV:}lockdiscovery' : + case '{DAV:}lockdiscovery': $newProperties[200][$propName] = new Sabre_DAV_Property_LockDiscovery($this->getLocks($path)); unset($newProperties[404][$propName]); break; } - - } + return true; - } - /** * This method is called before the logic for any HTTP method is * handled. @@ -138,44 +135,48 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { * * @param string $method * @param string $uri + * * @return bool */ - public function beforeMethod($method, $uri) { + public function beforeMethod($method, $uri) + { + switch ($method) { - switch($method) { - - case 'DELETE' : + case 'DELETE': $lastLock = null; - if (!$this->validateLock($uri,$lastLock, true)) + if (!$this->validateLock($uri, $lastLock, true)) { throw new Sabre_DAV_Exception_Locked($lastLock); + } break; - case 'MKCOL' : - case 'PROPPATCH' : - case 'PUT' : - case 'PATCH' : + case 'MKCOL': + case 'PROPPATCH': + case 'PUT': + case 'PATCH': $lastLock = null; - if (!$this->validateLock($uri,$lastLock)) + if (!$this->validateLock($uri, $lastLock)) { throw new Sabre_DAV_Exception_Locked($lastLock); + } break; - case 'MOVE' : + case 'MOVE': $lastLock = null; if (!$this->validateLock(array( $uri, $this->server->calculateUri($this->server->httpRequest->getHeader('Destination')), - ),$lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); + ), $lastLock, true)) { + throw new Sabre_DAV_Exception_Locked($lastLock); + } break; - case 'COPY' : + case 'COPY': $lastLock = null; if (!$this->validateLock( $this->server->calculateUri($this->server->httpRequest->getHeader('Destination')), - $lastLock, true)) - throw new Sabre_DAV_Exception_Locked($lastLock); + $lastLock, true)) { + throw new Sabre_DAV_Exception_Locked($lastLock); + } break; } return true; - } /** @@ -186,15 +187,16 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { * available for the specified uri. * * @param string $uri + * * @return array */ - public function getHTTPMethods($uri) { - - if ($this->locksBackend) - return array('LOCK','UNLOCK'); + public function getHTTPMethods($uri) + { + if ($this->locksBackend) { + return array('LOCK', 'UNLOCK'); + } return array(); - } /** @@ -205,14 +207,13 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { * * @return array */ - public function getFeatures() { - + public function getFeatures() + { return array(2); - } /** - * Returns all lock information on a particular uri + * Returns all lock information on a particular uri. * * This function should return an array with Sabre_DAV_Locks_LockInfo objects. If there are no locks on a file, return an empty array. * @@ -221,22 +222,23 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { * for any possible locks and return those as well. * * @param string $uri - * @param bool $returnChildLocks + * @param bool $returnChildLocks + * * @return array */ - public function getLocks($uri, $returnChildLocks = false) { - + public function getLocks($uri, $returnChildLocks = false) + { $lockList = array(); - if ($this->locksBackend) - $lockList = array_merge($lockList,$this->locksBackend->getLocks($uri, $returnChildLocks)); + if ($this->locksBackend) { + $lockList = array_merge($lockList, $this->locksBackend->getLocks($uri, $returnChildLocks)); + } return $lockList; - } /** - * Locks an uri + * Locks an uri. * * The WebDAV lock request can be operated to either create a new lock on a file, or to refresh an existing lock * If a new lock is created, a full XML body should be supplied, containing information about the lock such as the type @@ -247,19 +249,17 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { * Additionally, a lock can be requested for a non-existent file. In these case we're obligated to create an empty file as per RFC4918:S7.3 * * @param string $uri - * @return void */ - protected function httpLock($uri) { - + protected function httpLock($uri) + { $lastLock = null; - if (!$this->validateLock($uri,$lastLock)) { + if (!$this->validateLock($uri, $lastLock)) { // If the existing lock was an exclusive lock, we need to fail if (!$lastLock || $lastLock->scope == Sabre_DAV_Locks_LockInfo::EXCLUSIVE) { //var_dump($lastLock); throw new Sabre_DAV_Exception_ConflictingLock($lastLock); } - } if ($body = $this->server->httpRequest->getBody(true)) { @@ -267,24 +267,27 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { $lockInfo = $this->parseLockRequest($body); $lockInfo->depth = $this->server->getHTTPDepth(); $lockInfo->uri = $uri; - if($lastLock && $lockInfo->scope != Sabre_DAV_Locks_LockInfo::SHARED) throw new Sabre_DAV_Exception_ConflictingLock($lastLock); - + if ($lastLock && $lockInfo->scope != Sabre_DAV_Locks_LockInfo::SHARED) { + throw new Sabre_DAV_Exception_ConflictingLock($lastLock); + } } elseif ($lastLock) { // This must have been a lock refresh $lockInfo = $lastLock; // The resource could have been locked through another uri. - if ($uri!=$lockInfo->uri) $uri = $lockInfo->uri; - + if ($uri != $lockInfo->uri) { + $uri = $lockInfo->uri; + } } else { // There was neither a lock refresh nor a new lock request throw new Sabre_DAV_Exception_BadRequest('An xml body is required for lock requests'); - } - if ($timeout = $this->getTimeoutHeader()) $lockInfo->timeout = $timeout; + if ($timeout = $this->getTimeoutHeader()) { + $lockInfo->timeout = $timeout; + } $newFile = false; @@ -294,103 +297,106 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { // We need to call the beforeWriteContent event for RFC3744 // Edit: looks like this is not used, and causing problems now. - // + // See Issue 222 // $this->server->broadcastEvent('beforeWriteContent',array($uri)); - } catch (Sabre_DAV_Exception_NotFound $e) { // It didn't, lets create it - $this->server->createFile($uri,fopen('php://memory','r')); + $this->server->createFile($uri, fopen('php://memory', 'r')); $newFile = true; - } - $this->lockNode($uri,$lockInfo); + $this->lockNode($uri, $lockInfo); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); - $this->server->httpResponse->setHeader('Lock-Token','token . '>'); - $this->server->httpResponse->sendStatus($newFile?201:200); + $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); + $this->server->httpResponse->setHeader('Lock-Token', 'token.'>'); + $this->server->httpResponse->sendStatus($newFile ? 201 : 200); $this->server->httpResponse->sendBody($this->generateLockResponse($lockInfo)); - } /** - * Unlocks a uri + * Unlocks a uri. * * This WebDAV method allows you to remove a lock from a node. The client should provide a valid locktoken through the Lock-token http header * The server should return 204 (No content) on success * * @param string $uri - * @return void */ - protected function httpUnlock($uri) { - + protected function httpUnlock($uri) + { $lockToken = $this->server->httpRequest->getHeader('Lock-Token'); // If the locktoken header is not supplied, we need to throw a bad request exception - if (!$lockToken) throw new Sabre_DAV_Exception_BadRequest('No lock token was supplied'); + if (!$lockToken) { + throw new Sabre_DAV_Exception_BadRequest('No lock token was supplied'); + } $locks = $this->getLocks($uri); // Windows sometimes forgets to include < and > in the Lock-Token // header - if ($lockToken[0]!=='<') $lockToken = '<' . $lockToken . '>'; + if ($lockToken[0] !== '<') { + $lockToken = '<'.$lockToken.'>'; + } - foreach($locks as $lock) { - - if ('token . '>' == $lockToken) { - - $this->unlockNode($uri,$lock); - $this->server->httpResponse->setHeader('Content-Length','0'); + foreach ($locks as $lock) { + if ('token.'>' == $lockToken) { + $this->unlockNode($uri, $lock); + $this->server->httpResponse->setHeader('Content-Length', '0'); $this->server->httpResponse->sendStatus(204); + return; - } - } // If we got here, it means the locktoken was invalid throw new Sabre_DAV_Exception_LockTokenMatchesRequestUri(); - } /** - * Locks a uri + * Locks a uri. * * All the locking information is supplied in the lockInfo object. The object has a suggested timeout, but this can be safely ignored * It is important that if the existing timeout is ignored, the property is overwritten, as this needs to be sent back to the client * - * @param string $uri + * @param string $uri * @param Sabre_DAV_Locks_LockInfo $lockInfo + * * @return bool */ - public function lockNode($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { + public function lockNode($uri, Sabre_DAV_Locks_LockInfo $lockInfo) + { + if (!$this->server->broadcastEvent('beforeLock', array($uri, $lockInfo))) { + return; + } - if (!$this->server->broadcastEvent('beforeLock',array($uri,$lockInfo))) return; - - if ($this->locksBackend) return $this->locksBackend->lock($uri,$lockInfo); + if ($this->locksBackend) { + return $this->locksBackend->lock($uri, $lockInfo); + } throw new Sabre_DAV_Exception_MethodNotAllowed('Locking support is not enabled for this resource. No Locking backend was found so if you didn\'t expect this error, please check your configuration.'); - } /** - * Unlocks a uri + * Unlocks a uri. * * This method removes a lock from a uri. It is assumed all the supplied information is correct and verified * - * @param string $uri + * @param string $uri * @param Sabre_DAV_Locks_LockInfo $lockInfo + * * @return bool */ - public function unlockNode($uri,Sabre_DAV_Locks_LockInfo $lockInfo) { - - if (!$this->server->broadcastEvent('beforeUnlock',array($uri,$lockInfo))) return; - if ($this->locksBackend) return $this->locksBackend->unlock($uri,$lockInfo); - + public function unlockNode($uri, Sabre_DAV_Locks_LockInfo $lockInfo) + { + if (!$this->server->broadcastEvent('beforeUnlock', array($uri, $lockInfo))) { + return; + } + if ($this->locksBackend) { + return $this->locksBackend->unlock($uri, $lockInfo); + } } - /** * Returns the contents of the HTTP Timeout header. * @@ -398,61 +404,61 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { * * @return int */ - public function getTimeoutHeader() { - + public function getTimeoutHeader() + { $header = $this->server->httpRequest->getHeader('Timeout'); if ($header) { - - if (stripos($header,'second-')===0) $header = (int)(substr($header,7)); - else if (strtolower($header)=='infinite') $header=Sabre_DAV_Locks_LockInfo::TIMEOUT_INFINITE; - else throw new Sabre_DAV_Exception_BadRequest('Invalid HTTP timeout header'); - + if (stripos($header, 'second-') === 0) { + $header = (int) (substr($header, 7)); + } elseif (strtolower($header) == 'infinite') { + $header = Sabre_DAV_Locks_LockInfo::TIMEOUT_INFINITE; + } else { + throw new Sabre_DAV_Exception_BadRequest('Invalid HTTP timeout header'); + } } else { - $header = 0; - } return $header; - } /** - * Generates the response for successful LOCK requests + * Generates the response for successful LOCK requests. * * @param Sabre_DAV_Locks_LockInfo $lockInfo + * * @return string */ - protected function generateLockResponse(Sabre_DAV_Locks_LockInfo $lockInfo) { - - $dom = new DOMDocument('1.0','utf-8'); + protected function generateLockResponse(Sabre_DAV_Locks_LockInfo $lockInfo) + { + $dom = new DOMDocument('1.0', 'utf-8'); $dom->formatOutput = true; - $prop = $dom->createElementNS('DAV:','d:prop'); + $prop = $dom->createElementNS('DAV:', 'd:prop'); $dom->appendChild($prop); - $lockDiscovery = $dom->createElementNS('DAV:','d:lockdiscovery'); + $lockDiscovery = $dom->createElementNS('DAV:', 'd:lockdiscovery'); $prop->appendChild($lockDiscovery); - $lockObj = new Sabre_DAV_Property_LockDiscovery(array($lockInfo),true); - $lockObj->serialize($this->server,$lockDiscovery); + $lockObj = new Sabre_DAV_Property_LockDiscovery(array($lockInfo), true); + $lockObj->serialize($this->server, $lockDiscovery); return $dom->saveXML(); - } /** * validateLock should be called when a write operation is about to happen - * It will check if the requested url is locked, and see if the correct lock tokens are passed + * It will check if the requested url is locked, and see if the correct lock tokens are passed. + * + * @param mixed $urls List of relevant urls. Can be an array, a string or nothing at all for the current request uri + * @param mixed $lastLock This variable will be populated with the last checked lock object (Sabre_DAV_Locks_LockInfo) + * @param bool $checkChildLocks If set to true, this function will also look for any locks set on child resources of the supplied urls. This is needed for for example deletion of entire trees * - * @param mixed $urls List of relevant urls. Can be an array, a string or nothing at all for the current request uri - * @param mixed $lastLock This variable will be populated with the last checked lock object (Sabre_DAV_Locks_LockInfo) - * @param bool $checkChildLocks If set to true, this function will also look for any locks set on child resources of the supplied urls. This is needed for for example deletion of entire trees. * @return bool */ - protected function validateLock($urls = null,&$lastLock = null, $checkChildLocks = false) { - + protected function validateLock($urls = null, &$lastLock = null, $checkChildLocks = false) + { if (is_null($urls)) { $urls = array($this->server->getRequestUri()); } elseif (is_string($urls)) { @@ -464,22 +470,23 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { $conditions = $this->getIfConditions(); // We're going to loop through the urls and make sure all lock conditions are satisfied - foreach($urls as $url) { - + foreach ($urls as $url) { $locks = $this->getLocks($url, $checkChildLocks); // If there were no conditions, but there were locks, we fail if (!$conditions && $locks) { reset($locks); $lastLock = current($locks); + return false; } // If there were no locks or conditions, we go to the next url - if (!$locks && !$conditions) continue; - - foreach($conditions as $condition) { + if (!$locks && !$conditions) { + continue; + } + foreach ($conditions as $condition) { if (!$condition['uri']) { $conditionUri = $this->server->getRequestUri(); } else { @@ -487,32 +494,29 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { } // If the condition has a url, and it isn't part of the affected url at all, check the next condition - if ($conditionUri && strpos($url,$conditionUri)!==0) continue; + if ($conditionUri && strpos($url, $conditionUri) !== 0) { + continue; + } // The tokens array contians arrays with 2 elements. 0=true/false for normal/not condition, 1=locktoken // At least 1 condition has to be satisfied - foreach($condition['tokens'] as $conditionToken) { - + foreach ($condition['tokens'] as $conditionToken) { $etagValid = true; - $lockValid = true; + $lockValid = true; // key 2 can contain an etag if ($conditionToken[2]) { - - $uri = $conditionUri?$conditionUri:$this->server->getRequestUri(); + $uri = $conditionUri ? $conditionUri : $this->server->getRequestUri(); $node = $this->server->tree->getNodeForPath($uri); - $etagValid = $node->getETag()==$conditionToken[2]; - + $etagValid = $node->getETag() == $conditionToken[2]; } // key 1 can contain a lock token if ($conditionToken[1]) { - $lockValid = false; // Match all the locks - foreach($locks as $lockIndex=>$lock) { - - $lockToken = 'opaquelocktoken:' . $lock->token; + foreach ($locks as $lockIndex => $lock) { + $lockToken = 'opaquelocktoken:'.$lock->token; // Checking NOT if (!$conditionToken[0] && $lockToken != $conditionToken[1]) { @@ -522,48 +526,42 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { break; } if ($conditionToken[0] && $lockToken == $conditionToken[1]) { - $lastLock = $lock; // Condition valid and lock matched unset($locks[$lockIndex]); $lockValid = true; break; - } - } - } // If, after checking both etags and locks they are stil valid, // we can continue with the next condition. - if ($etagValid && $lockValid) continue 2; - } + if ($etagValid && $lockValid) { + continue 2; + } + } // No conditions matched, so we fail - throw new Sabre_DAV_Exception_PreconditionFailed('The tokens provided in the if header did not match','If'); + throw new Sabre_DAV_Exception_PreconditionFailed('The tokens provided in the if header did not match', 'If'); } // Conditions were met, we'll also need to check if all the locks are gone if (count($locks)) { - reset($locks); // There's still locks, we fail $lastLock = current($locks); + return false; - } - - } // We got here, this means every condition was satisfied return true; - } /** - * This method is created to extract information from the WebDAV HTTP 'If:' header + * This method is created to extract information from the WebDAV HTTP 'If:' header. * * The If header can be quite complex, and has a bunch of features. We're using a regex to extract all relevant information * The function will return an array, containing structs with the following keys @@ -575,63 +573,61 @@ class Sabre_DAV_Locks_Plugin extends Sabre_DAV_ServerPlugin { * * @return array */ - public function getIfConditions() { - + public function getIfConditions() + { $header = $this->server->httpRequest->getHeader('If'); - if (!$header) return array(); + if (!$header) { + return array(); + } $matches = array(); $regex = '/(?:\<(?P.*?)\>\s)?\((?PNot\s)?(?:\<(?P[^\>]*)\>)?(?:\s?)(?:\[(?P[^\]]*)\])?\)/im'; - preg_match_all($regex,$header,$matches,PREG_SET_ORDER); + preg_match_all($regex, $header, $matches, PREG_SET_ORDER); $conditions = array(); - foreach($matches as $match) { - + foreach ($matches as $match) { $condition = array( - 'uri' => $match['uri'], + 'uri' => $match['uri'], 'tokens' => array( - array($match['not']?0:1,$match['token'],isset($match['etag'])?$match['etag']:'') + array($match['not'] ? 0 : 1, $match['token'], isset($match['etag']) ? $match['etag'] : ''), ), ); - if (!$condition['uri'] && count($conditions)) $conditions[count($conditions)-1]['tokens'][] = array( - $match['not']?0:1, + if (!$condition['uri'] && count($conditions)) { + $conditions[count($conditions) - 1]['tokens'][] = array( + $match['not'] ? 0 : 1, $match['token'], - isset($match['etag'])?$match['etag']:'' + isset($match['etag']) ? $match['etag'] : '', ); - else { + } else { $conditions[] = $condition; } - } return $conditions; - } /** - * Parses a webdav lock xml body, and returns a new Sabre_DAV_Locks_LockInfo object + * Parses a webdav lock xml body, and returns a new Sabre_DAV_Locks_LockInfo object. * * @param string $body + * * @return Sabre_DAV_Locks_LockInfo */ - protected function parseLockRequest($body) { - - $xml = simplexml_load_string($body,null,LIBXML_NOWARNING); - $xml->registerXPathNamespace('d','DAV:'); + protected function parseLockRequest($body) + { + $xml = simplexml_load_string($body, null, LIBXML_NOWARNING); + $xml->registerXPathNamespace('d', 'DAV:'); $lockInfo = new Sabre_DAV_Locks_LockInfo(); - $children = $xml->children("DAV:"); - $lockInfo->owner = (string)$children->owner; + $children = $xml->children('DAV:'); + $lockInfo->owner = (string) $children->owner; $lockInfo->token = Sabre_DAV_UUIDUtil::getUUID(); - $lockInfo->scope = count($xml->xpath('d:lockscope/d:exclusive'))>0?Sabre_DAV_Locks_LockInfo::EXCLUSIVE:Sabre_DAV_Locks_LockInfo::SHARED; + $lockInfo->scope = count($xml->xpath('d:lockscope/d:exclusive')) > 0 ? Sabre_DAV_Locks_LockInfo::EXCLUSIVE : Sabre_DAV_Locks_LockInfo::SHARED; return $lockInfo; - } - - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Mount/Plugin.php b/dav/SabreDAV/lib/Sabre/DAV/Mount/Plugin.php index b37a90ae..c3071a21 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Mount/Plugin.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Mount/Plugin.php @@ -1,80 +1,76 @@ server = $server; - $this->server->subscribeEvent('beforeMethod',array($this,'beforeMethod'), 90); - + $this->server->subscribeEvent('beforeMethod', array($this, 'beforeMethod'), 90); } /** * 'beforeMethod' event handles. This event handles intercepts GET requests ending - * with ?mount + * with ?mount. * * @param string $method * @param string $uri + * * @return bool */ - public function beforeMethod($method, $uri) { - - if ($method!='GET') return; - if ($this->server->httpRequest->getQueryString()!='mount') return; + public function beforeMethod($method, $uri) + { + if ($method != 'GET') { + return; + } + if ($this->server->httpRequest->getQueryString() != 'mount') { + return; + } $currentUri = $this->server->httpRequest->getAbsoluteUri(); // Stripping off everything after the ? - list($currentUri) = explode('?',$currentUri); + list($currentUri) = explode('?', $currentUri); $this->davMount($currentUri); // Returning false to break the event chain return false; - } /** - * Generates the davmount response + * Generates the davmount response. * * @param string $uri absolute uri - * @return void */ - public function davMount($uri) { - + public function davMount($uri) + { $this->server->httpResponse->sendStatus(200); - $this->server->httpResponse->setHeader('Content-Type','application/davmount+xml'); + $this->server->httpResponse->setHeader('Content-Type', 'application/davmount+xml'); ob_start(); echo '', "\n"; echo "\n"; - echo " ", htmlspecialchars($uri, ENT_NOQUOTES, 'UTF-8'), "\n"; - echo ""; + echo ' ', htmlspecialchars($uri, ENT_NOQUOTES, 'UTF-8'), "\n"; + echo ''; $this->server->httpResponse->sendBody(ob_get_clean()); - } - - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Node.php b/dav/SabreDAV/lib/Sabre/DAV/Node.php index 3b95dfec..f3a7fb2b 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Node.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Node.php @@ -1,55 +1,47 @@ rootNode = $rootNode; - } /** - * Returns the INode object for the requested path + * Returns the INode object for the requested path. * * @param string $path + * * @return Sabre_DAV_INode */ - public function getNodeForPath($path) { - - $path = trim($path,'/'); - if (isset($this->cache[$path])) return $this->cache[$path]; + public function getNodeForPath($path) + { + $path = trim($path, '/'); + if (isset($this->cache[$path])) { + return $this->cache[$path]; + } //if (!$path || $path=='.') return $this->rootNode; $currentNode = $this->rootNode; // We're splitting up the path variable into folder/subfolder components and traverse to the correct node.. - foreach(explode('/',$path) as $pathPart) { + foreach (explode('/', $path) as $pathPart) { // If this part of the path is just a dot, it actually means we can skip it - if ($pathPart=='.' || $pathPart=='') continue; + if ($pathPart == '.' || $pathPart == '') { + continue; + } - if (!($currentNode instanceof Sabre_DAV_ICollection)) - throw new Sabre_DAV_Exception_NotFound('Could not find node at path: ' . $path); + if (!($currentNode instanceof Sabre_DAV_ICollection)) { + throw new Sabre_DAV_Exception_NotFound('Could not find node at path: '.$path); + } $currentNode = $currentNode->getChild($pathPart); - } $this->cache[$path] = $currentNode; - return $currentNode; + return $currentNode; } /** * This function allows you to check if a node exists. * * @param string $path + * * @return bool */ - public function nodeExists($path) { - + public function nodeExists($path) + { try { // The root always exists - if ($path==='') return true; + if ($path === '') { + return true; + } list($parent, $base) = Sabre_DAV_URLUtil::splitPath($path); $parentNode = $this->getNodeForPath($parent); - if (!$parentNode instanceof Sabre_DAV_ICollection) return false; + if (!$parentNode instanceof Sabre_DAV_ICollection) { + return false; + } + return $parentNode->childExists($base); - } catch (Sabre_DAV_Exception_NotFound $e) { - return false; - } - } /** * Returns a list of childnodes for a given path. * * @param string $path + * * @return array */ - public function getChildren($path) { - + public function getChildren($path) + { $node = $this->getNodeForPath($path); $children = $node->getChildren(); - foreach($children as $child) { - - $this->cache[trim($path,'/') . '/' . $child->getName()] = $child; - + foreach ($children as $child) { + $this->cache[trim($path, '/').'/'.$child->getName()] = $child; } - return $children; + return $children; } /** - * This method is called with every tree update + * This method is called with every tree update. * * Examples of tree updates are: * * node deletions @@ -134,20 +137,17 @@ class Sabre_DAV_ObjectTree extends Sabre_DAV_Tree { * If a path is passed, it is assumed that the entire subtree is dirty * * @param string $path - * @return void */ - public function markDirty($path) { + public function markDirty($path) + { // We don't care enough about sub-paths // flushing the entire cache - $path = trim($path,'/'); - foreach($this->cache as $nodePath=>$node) { - if ($nodePath == $path || strpos($nodePath,$path.'/')===0) + $path = trim($path, '/'); + foreach ($this->cache as $nodePath => $node) { + if ($nodePath == $path || strpos($nodePath, $path.'/') === 0) { unset($this->cache[$nodePath]); - + } } - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/PartialUpdate/IFile.php b/dav/SabreDAV/lib/Sabre/DAV/PartialUpdate/IFile.php index cf5ad55c..686939a5 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/PartialUpdate/IFile.php +++ b/dav/SabreDAV/lib/Sabre/DAV/PartialUpdate/IFile.php @@ -3,18 +3,16 @@ /** * This interface provides a way to modify only part of a target resource * It may be used to update a file chunk, upload big a file into smaller - * chunks or resume an upload + * chunks or resume an upload. * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Jean-Tiare LE BIGOT (http://www.jtlebi.fr/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -interface Sabre_DAV_PartialUpdate_IFile extends Sabre_DAV_IFile { - +interface Sabre_DAV_PartialUpdate_IFile extends Sabre_DAV_IFile +{ /** - * Updates the data at a given offset + * Updates the data at a given offset. * * The data argument is a readable stream resource. * The offset argument is an integer describing the offset. Contrary to @@ -29,10 +27,9 @@ interface Sabre_DAV_PartialUpdate_IFile extends Sabre_DAV_IFile { * time. * * @param resource $data - * @param integer $offset + * @param int $offset + * * @return string|null */ - function putRange($data, $offset); - + public function putRange($data, $offset); } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/PartialUpdate/Plugin.php b/dav/SabreDAV/lib/Sabre/DAV/PartialUpdate/Plugin.php index 170acbc9..d9028b16 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/PartialUpdate/Plugin.php +++ b/dav/SabreDAV/lib/Sabre/DAV/PartialUpdate/Plugin.php @@ -1,6 +1,6 @@ addPlugin($patchPlugin); * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Jean-Tiare LE BIGOT (http://www.jtlebi.fr/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_DAV_PartialUpdate_Plugin extends Sabre_DAV_ServerPlugin { - +class Sabre_DAV_PartialUpdate_Plugin extends Sabre_DAV_ServerPlugin +{ /** - * Reference to server + * Reference to server. * * @var Sabre_DAV_Server */ protected $server; /** - * Initializes the plugin + * Initializes the plugin. * * This method is automatically called by the Server class after addPlugin. * * @param Sabre_DAV_Server $server - * @return void */ - public function initialize(Sabre_DAV_Server $server) { - + public function initialize(Sabre_DAV_Server $server) + { $this->server = $server; - $server->subscribeEvent('unknownMethod',array($this,'unknownMethod')); - + $server->subscribeEvent('unknownMethod', array($this, 'unknownMethod')); } /** @@ -47,10 +43,9 @@ class Sabre_DAV_PartialUpdate_Plugin extends Sabre_DAV_ServerPlugin { * * @return string */ - public function getPluginName() { - + public function getPluginName() + { return 'partialupdate'; - } /** @@ -61,17 +56,17 @@ class Sabre_DAV_PartialUpdate_Plugin extends Sabre_DAV_ServerPlugin { * * @param string $method * @param string $uri + * * @return bool|null */ - public function unknownMethod($method, $uri) { + public function unknownMethod($method, $uri) + { + switch ($method) { - switch($method) { - case 'PATCH': return $this->httpPatch($uri); } - } /** @@ -80,25 +75,25 @@ class Sabre_DAV_PartialUpdate_Plugin extends Sabre_DAV_ServerPlugin { * * This method is passed a uri. It should only return HTTP methods that are * available for the specified uri. - * + * * We claim to support PATCH method (partial update) if and only if * - the node exist * - the node implements our partial update interface * * @param string $uri + * * @return array */ - public function getHTTPMethods($uri) { - + public function getHTTPMethods($uri) + { $tree = $this->server->tree; - - if ($tree->nodeExists($uri) && + + if ($tree->nodeExists($uri) && $tree->getNodeForPath($uri) instanceof Sabre_DAV_PartialUpdate_IFile) { return array('PATCH'); - } - - return array(); + } + return array(); } /** @@ -106,23 +101,22 @@ class Sabre_DAV_PartialUpdate_Plugin extends Sabre_DAV_ServerPlugin { * * @return array */ - public function getFeatures() { - + public function getFeatures() + { return array('sabredav-partialupdate'); - } /** - * Patch an uri + * Patch an uri. * - * The WebDAV patch request can be used to modify only a part of an + * The WebDAV patch request can be used to modify only a part of an * existing resource. If the resource does not exist yet and the first * offset is not 0, the request fails * * @param string $uri - * @return void */ - protected function httpPatch($uri) { + protected function httpPatch($uri) + { // Get the node. Will throw a 404 if not found $node = $this->server->tree->getNodeForPath($uri); @@ -135,48 +129,54 @@ class Sabre_DAV_PartialUpdate_Plugin extends Sabre_DAV_ServerPlugin { if (!$range) { throw new Sabre_DAV_Exception_BadRequest('No valid "X-Update-Range" found in the headers'); } - + $contentType = strtolower( $this->server->httpRequest->getHeader('Content-Type') ); - + if ($contentType != 'application/x-sabredav-partialupdate') { - throw new Sabre_DAV_Exception_UnsupportedMediaType('Unknown Content-Type header "' . $contentType . '"'); + throw new Sabre_DAV_Exception_UnsupportedMediaType('Unknown Content-Type header "'.$contentType.'"'); } $len = $this->server->httpRequest->getHeader('Content-Length'); // Load the begin and end data - $start = ($range[0])?$range[0]:0; - $end = ($range[1])?$range[1]:$len-1; + $start = ($range[0]) ? $range[0] : 0; + $end = ($range[1]) ? $range[1] : $len - 1; // Check consistency - if($end < $start) - throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The end offset (' . $range[1] . ') is lower than the start offset (' . $range[0] . ')'); - if($end - $start + 1 != $len) - throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('Actual data length (' . $len . ') is not consistent with begin (' . $range[0] . ') and end (' . $range[1] . ') offsets'); + if ($end < $start) { + throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The end offset ('.$range[1].') is lower than the start offset ('.$range[0].')'); + } + if ($end - $start + 1 != $len) { + throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('Actual data length ('.$len.') is not consistent with begin ('.$range[0].') and end ('.$range[1].') offsets'); + } // Checking If-None-Match and related headers. - if (!$this->server->checkPreconditions()) return; - - if (!$this->server->broadcastEvent('beforeWriteContent',array($uri, $node, null))) + if (!$this->server->checkPreconditions()) { return; + } + + if (!$this->server->broadcastEvent('beforeWriteContent', array($uri, $node, null))) { + return; + } $body = $this->server->httpRequest->getBody(); - $etag = $node->putRange($body, $start-1); + $etag = $node->putRange($body, $start - 1); - $this->server->broadcastEvent('afterWriteContent',array($uri, $node)); + $this->server->broadcastEvent('afterWriteContent', array($uri, $node)); - $this->server->httpResponse->setHeader('Content-Length','0'); - if ($etag) $this->server->httpResponse->setHeader('ETag',$etag); + $this->server->httpResponse->setHeader('Content-Length', '0'); + if ($etag) { + $this->server->httpResponse->setHeader('ETag', $etag); + } $this->server->httpResponse->sendStatus(204); return false; - } - - /** - * Returns the HTTP custom range update header + + /** + * Returns the HTTP custom range update header. * * This method returns null if there is no well-formed HTTP range request * header or array($start, $end). @@ -189,21 +189,26 @@ class Sabre_DAV_PartialUpdate_Plugin extends Sabre_DAV_ServerPlugin { * * @return array|null */ - public function getHTTPUpdateRange() { - + public function getHTTPUpdateRange() + { $range = $this->server->httpRequest->getHeader('X-Update-Range'); - if (is_null($range)) return null; + if (is_null($range)) { + return null; + } // Matching "Range: bytes=1234-5678: both numbers are optional - if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i',$range,$matches)) return null; + if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i', $range, $matches)) { + return null; + } - if ($matches[1]==='' && $matches[2]==='') return null; + if ($matches[1] === '' && $matches[2] === '') { + return null; + } return array( - $matches[1]!==''?$matches[1]:null, - $matches[2]!==''?$matches[2]:null, + $matches[1] !== '' ? $matches[1] : null, + $matches[2] !== '' ? $matches[2] : null, ); - } } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Property.php b/dav/SabreDAV/lib/Sabre/DAV/Property.php index 26f2c1d0..69b75b89 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Property.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Property.php @@ -1,23 +1,18 @@ time = $time; } elseif (is_int($time) || ctype_digit($time)) { - $this->time = new DateTime('@' . $time); + $this->time = new DateTime('@'.$time); } else { $this->time = new DateTime($time); } // Setting timezone to UTC $this->time->setTimezone(new DateTimeZone('UTC')); - } /** - * serialize + * serialize. * * @param Sabre_DAV_Server $server * @param DOMElement $prop - * @return void */ - public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $prop) + { $doc = $prop->ownerDocument; - $prop->setAttribute('xmlns:b','urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/'); - $prop->setAttribute('b:dt','dateTime.rfc1123'); + $prop->setAttribute('xmlns:b', 'urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/'); + $prop->setAttribute('b:dt', 'dateTime.rfc1123'); $prop->nodeValue = Sabre_HTTP_Util::toHTTPDate($this->time); - } /** - * getTime + * getTime. * * @return DateTime */ - public function getTime() { - + public function getTime() + { return $this->time; - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Property/Href.php b/dav/SabreDAV/lib/Sabre/DAV/Property/Href.php index dac564f2..b3933911 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Property/Href.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Property/Href.php @@ -1,55 +1,51 @@ href = $href; $this->autoPrefix = $autoPrefix; - } /** - * Returns the uri + * Returns the uri. * * @return string */ - public function getHref() { - + public function getHref() + { return $this->href; - } /** @@ -58,34 +54,31 @@ class Sabre_DAV_Property_Href extends Sabre_DAV_Property implements Sabre_DAV_Pr * It will additionally prepend the href property with the server's base uri. * * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void + * @param DOMElement $dom */ - public function serialize(Sabre_DAV_Server $server, DOMElement $dom) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $dom) + { $prefix = $server->xmlNamespaces['DAV:']; - $elem = $dom->ownerDocument->createElement($prefix . ':href'); - $elem->nodeValue = ($this->autoPrefix?$server->getBaseUri():'') . $this->href; + $elem = $dom->ownerDocument->createElement($prefix.':href'); + $elem->nodeValue = ($this->autoPrefix ? $server->getBaseUri() : '').$this->href; $dom->appendChild($elem); - } /** - * Unserializes this property from a DOM Element + * Unserializes this property from a DOM Element. * * This method returns an instance of this class. * It will only decode {DAV:}href values. For non-compatible elements null will be returned. * * @param DOMElement $dom + * * @return Sabre_DAV_Property_Href */ - static function unserialize(DOMElement $dom) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)==='{DAV:}href') { - return new self($dom->firstChild->textContent,false); + public static function unserialize(DOMElement $dom) + { + if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild) === '{DAV:}href') { + return new self($dom->firstChild->textContent, false); } - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Property/HrefList.php b/dav/SabreDAV/lib/Sabre/DAV/Property/HrefList.php index 282c452c..f1b65380 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Property/HrefList.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Property/HrefList.php @@ -1,54 +1,50 @@ hrefs = $hrefs; $this->autoPrefix = $autoPrefix; - } /** - * Returns the uris + * Returns the uris. * * @return array */ - public function getHrefs() { - + public function getHrefs() + { return $this->hrefs; - } /** @@ -57,40 +53,38 @@ class Sabre_DAV_Property_HrefList extends Sabre_DAV_Property { * It will additionally prepend the href property with the server's base uri. * * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void + * @param DOMElement $dom */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $dom) + { $prefix = $server->xmlNamespaces['DAV:']; - foreach($this->hrefs as $href) { - $elem = $dom->ownerDocument->createElement($prefix . ':href'); - $elem->nodeValue = ($this->autoPrefix?$server->getBaseUri():'') . $href; + foreach ($this->hrefs as $href) { + $elem = $dom->ownerDocument->createElement($prefix.':href'); + $elem->nodeValue = ($this->autoPrefix ? $server->getBaseUri() : '').$href; $dom->appendChild($elem); } - } /** - * Unserializes this property from a DOM Element + * Unserializes this property from a DOM Element. * * This method returns an instance of this class. * It will only decode {DAV:}href values. * * @param DOMElement $dom + * * @return Sabre_DAV_Property_HrefList */ - static function unserialize(DOMElement $dom) { - + public static function unserialize(DOMElement $dom) + { $hrefs = array(); - foreach($dom->childNodes as $child) { - if (Sabre_DAV_XMLUtil::toClarkNotation($child)==='{DAV:}href') { + foreach ($dom->childNodes as $child) { + if (Sabre_DAV_XMLUtil::toClarkNotation($child) === '{DAV:}href') { $hrefs[] = $child->textContent; } } + return new self($hrefs, false); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Property/IHref.php b/dav/SabreDAV/lib/Sabre/DAV/Property/IHref.php index 5c040906..3571e6d2 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Property/IHref.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Property/IHref.php @@ -1,25 +1,22 @@ locks = $locks; $this->revealLockToken = $revealLockToken; - } /** - * serialize + * serialize. * * @param Sabre_DAV_Server $server * @param DOMElement $prop - * @return void */ - public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $prop) + { $doc = $prop->ownerDocument; - foreach($this->locks as $lock) { - - $activeLock = $doc->createElementNS('DAV:','d:activelock'); + foreach ($this->locks as $lock) { + $activeLock = $doc->createElementNS('DAV:', 'd:activelock'); $prop->appendChild($activeLock); - $lockScope = $doc->createElementNS('DAV:','d:lockscope'); + $lockScope = $doc->createElementNS('DAV:', 'd:lockscope'); $activeLock->appendChild($lockScope); - $lockScope->appendChild($doc->createElementNS('DAV:','d:' . ($lock->scope==Sabre_DAV_Locks_LockInfo::EXCLUSIVE?'exclusive':'shared'))); + $lockScope->appendChild($doc->createElementNS('DAV:', 'd:'.($lock->scope == Sabre_DAV_Locks_LockInfo::EXCLUSIVE ? 'exclusive' : 'shared'))); - $lockType = $doc->createElementNS('DAV:','d:locktype'); + $lockType = $doc->createElementNS('DAV:', 'd:locktype'); $activeLock->appendChild($lockType); - $lockType->appendChild($doc->createElementNS('DAV:','d:write')); + $lockType->appendChild($doc->createElementNS('DAV:', 'd:write')); /* {DAV:}lockroot */ if (!self::$hideLockRoot) { - $lockRoot = $doc->createElementNS('DAV:','d:lockroot'); + $lockRoot = $doc->createElementNS('DAV:', 'd:lockroot'); $activeLock->appendChild($lockRoot); - $href = $doc->createElementNS('DAV:','d:href'); - $href->appendChild($doc->createTextNode($server->getBaseUri() . $lock->uri)); + $href = $doc->createElementNS('DAV:', 'd:href'); + $href->appendChild($doc->createTextNode($server->getBaseUri().$lock->uri)); $lockRoot->appendChild($href); } - $activeLock->appendChild($doc->createElementNS('DAV:','d:depth',($lock->depth == Sabre_DAV_Server::DEPTH_INFINITY?'infinity':$lock->depth))); - $activeLock->appendChild($doc->createElementNS('DAV:','d:timeout','Second-' . $lock->timeout)); + $activeLock->appendChild($doc->createElementNS('DAV:', 'd:depth', ($lock->depth == Sabre_DAV_Server::DEPTH_INFINITY ? 'infinity' : $lock->depth))); + $activeLock->appendChild($doc->createElementNS('DAV:', 'd:timeout', 'Second-'.$lock->timeout)); if ($this->revealLockToken) { - $lockToken = $doc->createElementNS('DAV:','d:locktoken'); + $lockToken = $doc->createElementNS('DAV:', 'd:locktoken'); $activeLock->appendChild($lockToken); - $lockToken->appendChild($doc->createElementNS('DAV:','d:href','opaquelocktoken:' . $lock->token)); + $lockToken->appendChild($doc->createElementNS('DAV:', 'd:href', 'opaquelocktoken:'.$lock->token)); } - $activeLock->appendChild($doc->createElementNS('DAV:','d:owner',$lock->owner)); - + $activeLock->appendChild($doc->createElementNS('DAV:', 'd:owner', $lock->owner)); } - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Property/ResourceType.php b/dav/SabreDAV/lib/Sabre/DAV/Property/ResourceType.php index f6269611..dd1d1f30 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Property/ResourceType.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Property/ResourceType.php @@ -1,125 +1,113 @@ resourceType = array(); - elseif ($resourceType === Sabre_DAV_Server::NODE_DIRECTORY) + } elseif ($resourceType === Sabre_DAV_Server::NODE_DIRECTORY) { $this->resourceType = array('{DAV:}collection'); - elseif (is_array($resourceType)) + } elseif (is_array($resourceType)) { $this->resourceType = $resourceType; - else + } else { $this->resourceType = array($resourceType); - + } } /** - * serialize + * serialize. * * @param Sabre_DAV_Server $server - * @param DOMElement $prop - * @return void + * @param DOMElement $prop */ - public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $prop) + { $propName = null; $rt = $this->resourceType; - foreach($rt as $resourceType) { - if (preg_match('/^{([^}]*)}(.*)$/',$resourceType,$propName)) { - + foreach ($rt as $resourceType) { + if (preg_match('/^{([^}]*)}(.*)$/', $resourceType, $propName)) { if (isset($server->xmlNamespaces[$propName[1]])) { - $prop->appendChild($prop->ownerDocument->createElement($server->xmlNamespaces[$propName[1]] . ':' . $propName[2])); + $prop->appendChild($prop->ownerDocument->createElement($server->xmlNamespaces[$propName[1]].':'.$propName[2])); } else { - $prop->appendChild($prop->ownerDocument->createElementNS($propName[1],'custom:' . $propName[2])); + $prop->appendChild($prop->ownerDocument->createElementNS($propName[1], 'custom:'.$propName[2])); } - } } - } /** - * Returns the values in clark-notation + * Returns the values in clark-notation. * * For example array('{DAV:}collection') * * @return array */ - public function getValue() { - + public function getValue() + { return $this->resourceType; - } /** - * Checks if the principal contains a certain value + * Checks if the principal contains a certain value. * * @param string $type + * * @return bool */ - public function is($type) { - + public function is($type) + { return in_array($type, $this->resourceType); - } /** - * Adds a resourcetype value to this property + * Adds a resourcetype value to this property. * * @param string $type - * @return void */ - public function add($type) { - + public function add($type) + { $this->resourceType[] = $type; $this->resourceType = array_unique($this->resourceType); - } /** * Unserializes a DOM element into a ResourceType property. * * @param DOMElement $dom + * * @return Sabre_DAV_Property_ResourceType */ - static public function unserialize(DOMElement $dom) { - + public static function unserialize(DOMElement $dom) + { $value = array(); - foreach($dom->childNodes as $child) { - + foreach ($dom->childNodes as $child) { $value[] = Sabre_DAV_XMLUtil::toClarkNotation($child); - } return new self($value); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Property/Response.php b/dav/SabreDAV/lib/Sabre/DAV/Property/Response.php index 9f21163d..21f5a18b 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Property/Response.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Property/Response.php @@ -1,29 +1,27 @@ href = $href; $this->responseProperties = $responseProperties; - } /** - * Returns the url + * Returns the url. * * @return string */ - public function getHref() { - + public function getHref() + { return $this->href; - } /** - * Returns the property list + * Returns the property list. * * @return array */ - public function getResponseProperties() { - + public function getResponseProperties() + { return $this->responseProperties; - } /** - * serialize + * serialize. * * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void + * @param DOMElement $dom */ - public function serialize(Sabre_DAV_Server $server, DOMElement $dom) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $dom) + { $document = $dom->ownerDocument; $properties = $this->responseProperties; @@ -83,20 +77,24 @@ class Sabre_DAV_Property_Response extends Sabre_DAV_Property implements Sabre_DA $uri = Sabre_DAV_URLUtil::encodePath($this->href); // Adding the baseurl to the beginning of the url - $uri = $server->getBaseUri() . $uri; + $uri = $server->getBaseUri().$uri; - $xresponse->appendChild($document->createElement('d:href',$uri)); + $xresponse->appendChild($document->createElement('d:href', $uri)); // The properties variable is an array containing properties, grouped by // HTTP status - foreach($properties as $httpStatus=>$propertyGroup) { + foreach ($properties as $httpStatus => $propertyGroup) { // The 'href' is also in this array, and it's special cased. // We will ignore it - if ($httpStatus=='href') continue; + if ($httpStatus == 'href') { + continue; + } // If there are no properties in this group, we can also just carry on - if (!count($propertyGroup)) continue; + if (!count($propertyGroup)) { + continue; + } $xpropstat = $document->createElement('d:propstat'); $xresponse->appendChild($xpropstat); @@ -106,50 +104,41 @@ class Sabre_DAV_Property_Response extends Sabre_DAV_Property implements Sabre_DA $nsList = $server->xmlNamespaces; - foreach($propertyGroup as $propertyName=>$propertyValue) { - + foreach ($propertyGroup as $propertyName => $propertyValue) { $propName = null; - preg_match('/^{([^}]*)}(.*)$/',$propertyName,$propName); + preg_match('/^{([^}]*)}(.*)$/', $propertyName, $propName); // special case for empty namespaces - if ($propName[1]=='') { - + if ($propName[1] == '') { $currentProperty = $document->createElement($propName[2]); $xprop->appendChild($currentProperty); - $currentProperty->setAttribute('xmlns',''); - + $currentProperty->setAttribute('xmlns', ''); } else { - if (!isset($nsList[$propName[1]])) { - $nsList[$propName[1]] = 'x' . count($nsList); + $nsList[$propName[1]] = 'x'.count($nsList); } // If the namespace was defined in the top-level xml namespaces, it means // there was already a namespace declaration, and we don't have to worry about it. if (isset($server->xmlNamespaces[$propName[1]])) { - $currentProperty = $document->createElement($nsList[$propName[1]] . ':' . $propName[2]); + $currentProperty = $document->createElement($nsList[$propName[1]].':'.$propName[2]); } else { - $currentProperty = $document->createElementNS($propName[1],$nsList[$propName[1]].':' . $propName[2]); + $currentProperty = $document->createElementNS($propName[1], $nsList[$propName[1]].':'.$propName[2]); } $xprop->appendChild($currentProperty); - } if (is_scalar($propertyValue)) { $text = $document->createTextNode($propertyValue); $currentProperty->appendChild($text); } elseif ($propertyValue instanceof Sabre_DAV_PropertyInterface) { - $propertyValue->serialize($server,$currentProperty); + $propertyValue->serialize($server, $currentProperty); } elseif (!is_null($propertyValue)) { - throw new Sabre_DAV_Exception('Unknown property value type: ' . gettype($propertyValue) . ' for property: ' . $propertyName); + throw new Sabre_DAV_Exception('Unknown property value type: '.gettype($propertyValue).' for property: '.$propertyName); } - } - $xpropstat->appendChild($document->createElement('d:status',$server->httpResponse->getStatusMessage($httpStatus))); - + $xpropstat->appendChild($document->createElement('d:status', $server->httpResponse->getStatusMessage($httpStatus))); } - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Property/ResponseList.php b/dav/SabreDAV/lib/Sabre/DAV/Property/ResponseList.php index cae923af..b7de543d 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Property/ResponseList.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Property/ResponseList.php @@ -1,20 +1,18 @@ responses = $responses; - } /** - * serialize + * serialize. * * @param Sabre_DAV_Server $server - * @param DOMElement $dom - * @return void + * @param DOMElement $dom */ - public function serialize(Sabre_DAV_Server $server,DOMElement $dom) { - - foreach($this->responses as $response) { + public function serialize(Sabre_DAV_Server $server, DOMElement $dom) + { + foreach ($this->responses as $response) { $response->serialize($server, $dom); } - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/Property/SupportedLock.php b/dav/SabreDAV/lib/Sabre/DAV/Property/SupportedLock.php index 4e3aaf23..b86ff05d 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Property/SupportedLock.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Property/SupportedLock.php @@ -1,76 +1,71 @@ supportsLocks = $supportsLocks; - } /** - * serialize + * serialize. * * @param Sabre_DAV_Server $server * @param DOMElement $prop - * @return void */ - public function serialize(Sabre_DAV_Server $server,DOMElement $prop) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $prop) + { $doc = $prop->ownerDocument; - if (!$this->supportsLocks) return null; + if (!$this->supportsLocks) { + return null; + } - $lockEntry1 = $doc->createElementNS('DAV:','d:lockentry'); - $lockEntry2 = $doc->createElementNS('DAV:','d:lockentry'); + $lockEntry1 = $doc->createElementNS('DAV:', 'd:lockentry'); + $lockEntry2 = $doc->createElementNS('DAV:', 'd:lockentry'); $prop->appendChild($lockEntry1); $prop->appendChild($lockEntry2); - $lockScope1 = $doc->createElementNS('DAV:','d:lockscope'); - $lockScope2 = $doc->createElementNS('DAV:','d:lockscope'); - $lockType1 = $doc->createElementNS('DAV:','d:locktype'); - $lockType2 = $doc->createElementNS('DAV:','d:locktype'); + $lockScope1 = $doc->createElementNS('DAV:', 'd:lockscope'); + $lockScope2 = $doc->createElementNS('DAV:', 'd:lockscope'); + $lockType1 = $doc->createElementNS('DAV:', 'd:locktype'); + $lockType2 = $doc->createElementNS('DAV:', 'd:locktype'); $lockEntry1->appendChild($lockScope1); $lockEntry1->appendChild($lockType1); $lockEntry2->appendChild($lockScope2); $lockEntry2->appendChild($lockType2); - $lockScope1->appendChild($doc->createElementNS('DAV:','d:exclusive')); - $lockScope2->appendChild($doc->createElementNS('DAV:','d:shared')); + $lockScope1->appendChild($doc->createElementNS('DAV:', 'd:exclusive')); + $lockScope2->appendChild($doc->createElementNS('DAV:', 'd:shared')); - $lockType1->appendChild($doc->createElementNS('DAV:','d:write')); - $lockType2->appendChild($doc->createElementNS('DAV:','d:write')); + $lockType1->appendChild($doc->createElementNS('DAV:', 'd:write')); + $lockType2->appendChild($doc->createElementNS('DAV:', 'd:write')); //$frag->appendXML(''); //$frag->appendXML(''); - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Property/SupportedReportSet.php b/dav/SabreDAV/lib/Sabre/DAV/Property/SupportedReportSet.php index e62699f3..82c01200 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Property/SupportedReportSet.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Property/SupportedReportSet.php @@ -6,23 +6,21 @@ * This property is defined in RFC3253, but since it's * so common in other webdav-related specs, it is part of the core server. * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_DAV_Property_SupportedReportSet extends Sabre_DAV_Property { - +class Sabre_DAV_Property_SupportedReportSet extends Sabre_DAV_Property +{ /** - * List of reports + * List of reports. * * @var array */ protected $reports = array(); /** - * Creates the property + * Creates the property. * * Any reports passed in the constructor * should be valid report-types in clark-notation. @@ -31,79 +29,72 @@ class Sabre_DAV_Property_SupportedReportSet extends Sabre_DAV_Property { * * @param mixed $reports */ - public function __construct($reports = null) { - - if (!is_null($reports)) + public function __construct($reports = null) + { + if (!is_null($reports)) { $this->addReport($reports); - + } } /** - * Adds a report to this property + * Adds a report to this property. * * The report must be a string in clark-notation. * Multiple reports can be specified as an array. * * @param mixed $report - * @return void */ - public function addReport($report) { - - if (!is_array($report)) $report = array($report); - - foreach($report as $r) { - - if (!preg_match('/^{([^}]*)}(.*)$/',$r)) - throw new Sabre_DAV_Exception('Reportname must be in clark-notation'); - - $this->reports[] = $r; - + public function addReport($report) + { + if (!is_array($report)) { + $report = array($report); } + foreach ($report as $r) { + if (!preg_match('/^{([^}]*)}(.*)$/', $r)) { + throw new Sabre_DAV_Exception('Reportname must be in clark-notation'); + } + + $this->reports[] = $r; + } } /** - * Returns the list of supported reports + * Returns the list of supported reports. * * @return array */ - public function getValue() { - + public function getValue() + { return $this->reports; - } /** - * Serializes the node + * Serializes the node. * * @param Sabre_DAV_Server $server - * @param DOMElement $prop - * @return void + * @param DOMElement $prop */ - public function serialize(Sabre_DAV_Server $server, DOMElement $prop) { - - foreach($this->reports as $reportName) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $prop) + { + foreach ($this->reports as $reportName) { $supportedReport = $prop->ownerDocument->createElement('d:supported-report'); $prop->appendChild($supportedReport); $report = $prop->ownerDocument->createElement('d:report'); $supportedReport->appendChild($report); - preg_match('/^{([^}]*)}(.*)$/',$reportName,$matches); + preg_match('/^{([^}]*)}(.*)$/', $reportName, $matches); list(, $namespace, $element) = $matches; - $prefix = isset($server->xmlNamespaces[$namespace])?$server->xmlNamespaces[$namespace]:null; + $prefix = isset($server->xmlNamespaces[$namespace]) ? $server->xmlNamespaces[$namespace] : null; if ($prefix) { - $report->appendChild($prop->ownerDocument->createElement($prefix . ':' . $element)); + $report->appendChild($prop->ownerDocument->createElement($prefix.':'.$element)); } else { - $report->appendChild($prop->ownerDocument->createElementNS($namespace, 'x:' . $element)); + $report->appendChild($prop->ownerDocument->createElementNS($namespace, 'x:'.$element)); } - } - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/PropertyInterface.php b/dav/SabreDAV/lib/Sabre/DAV/PropertyInterface.php index 515072cb..dc40bf0c 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/PropertyInterface.php +++ b/dav/SabreDAV/lib/Sabre/DAV/PropertyInterface.php @@ -1,21 +1,17 @@ tree = $treeOrNode; } elseif ($treeOrNode instanceof Sabre_DAV_INode) { @@ -174,7 +172,7 @@ class Sabre_DAV_Server { // If it's an array, a list of nodes was passed, and we need to // create the root node. - foreach($treeOrNode as $node) { + foreach ($treeOrNode as $node) { if (!($node instanceof Sabre_DAV_INode)) { throw new Sabre_DAV_Exception('Invalid argument passed to constructor. If you\'re passing an array, all the values must implement Sabre_DAV_INode'); } @@ -182,7 +180,6 @@ class Sabre_DAV_Server { $root = new Sabre_DAV_SimpleCollection('root', $treeOrNode); $this->tree = new Sabre_DAV_ObjectTree($root); - } elseif (is_null($treeOrNode)) { $root = new Sabre_DAV_SimpleCollection('root'); $this->tree = new Sabre_DAV_ObjectTree($root); @@ -191,94 +188,83 @@ class Sabre_DAV_Server { } $this->httpResponse = new Sabre_HTTP_Response(); $this->httpRequest = new Sabre_HTTP_Request(); - } /** - * Starts the DAV Server - * - * @return void + * Starts the DAV Server. */ - public function exec() { - + public function exec() + { try { - $this->invokeMethod($this->httpRequest->getMethod(), $this->getRequestUri()); - } catch (Exception $e) { - try { $this->broadcastEvent('exception', array($e)); } catch (Exception $ignore) { } - $DOM = new DOMDocument('1.0','utf-8'); + $DOM = new DOMDocument('1.0', 'utf-8'); $DOM->formatOutput = true; - $error = $DOM->createElementNS('DAV:','d:error'); - $error->setAttribute('xmlns:s',self::NS_SABREDAV); + $error = $DOM->createElementNS('DAV:', 'd:error'); + $error->setAttribute('xmlns:s', self::NS_SABREDAV); $DOM->appendChild($error); - $error->appendChild($DOM->createElement('s:exception',get_class($e))); - $error->appendChild($DOM->createElement('s:message',$e->getMessage())); + $error->appendChild($DOM->createElement('s:exception', get_class($e))); + $error->appendChild($DOM->createElement('s:message', $e->getMessage())); if ($this->debugExceptions) { - $error->appendChild($DOM->createElement('s:file',$e->getFile())); - $error->appendChild($DOM->createElement('s:line',$e->getLine())); - $error->appendChild($DOM->createElement('s:code',$e->getCode())); - $error->appendChild($DOM->createElement('s:stacktrace',$e->getTraceAsString())); - + $error->appendChild($DOM->createElement('s:file', $e->getFile())); + $error->appendChild($DOM->createElement('s:line', $e->getLine())); + $error->appendChild($DOM->createElement('s:code', $e->getCode())); + $error->appendChild($DOM->createElement('s:stacktrace', $e->getTraceAsString())); } if (self::$exposeVersion) { - $error->appendChild($DOM->createElement('s:sabredav-version',Sabre_DAV_Version::VERSION)); + $error->appendChild($DOM->createElement('s:sabredav-version', Sabre_DAV_Version::VERSION)); } - if($e instanceof Sabre_DAV_Exception) { - + if ($e instanceof Sabre_DAV_Exception) { $httpCode = $e->getHTTPCode(); - $e->serialize($this,$error); + $e->serialize($this, $error); $headers = $e->getHTTPHeaders($this); - } else { - $httpCode = 500; $headers = array(); - } $headers['Content-Type'] = 'application/xml; charset=utf-8'; $this->httpResponse->sendStatus($httpCode); $this->httpResponse->setHeaders($headers); $this->httpResponse->sendBody($DOM->saveXML()); - } - } /** - * Sets the base server uri + * Sets the base server uri. * * @param string $uri - * @return void */ - public function setBaseUri($uri) { + public function setBaseUri($uri) + { // If the baseUri does not end with a slash, we must add it - if ($uri[strlen($uri)-1]!=='/') - $uri.='/'; + if ($uri[strlen($uri) - 1] !== '/') { + $uri .= '/'; + } $this->baseUri = $uri; - } /** - * Returns the base responding uri + * Returns the base responding uri. * * @return string */ - public function getBaseUri() { + public function getBaseUri() + { + if (is_null($this->baseUri)) { + $this->baseUri = $this->guessBaseUri(); + } - if (is_null($this->baseUri)) $this->baseUri = $this->guessBaseUri(); return $this->baseUri; - } /** @@ -289,8 +275,8 @@ class Sabre_DAV_Server { * * @return string */ - public function guessBaseUri() { - + public function guessBaseUri() + { $pathInfo = $this->httpRequest->getRawServerValue('PATH_INFO'); $uri = $this->httpRequest->getRawServerValue('REQUEST_URI'); @@ -298,8 +284,9 @@ class Sabre_DAV_Server { if (!empty($pathInfo)) { // We need to make sure we ignore the QUERY_STRING part - if ($pos = strpos($uri,'?')) - $uri = substr($uri,0,$pos); + if ($pos = strpos($uri, '?')) { + $uri = substr($uri, 0, $pos); + } // PATH_INFO is only set for urls, such as: /example.php/path // in that case PATH_INFO contains '/path'. @@ -309,33 +296,30 @@ class Sabre_DAV_Server { $decodedUri = Sabre_DAV_URLUtil::decodePath($uri); // A simple sanity check: - if(substr($decodedUri,strlen($decodedUri)-strlen($pathInfo))===$pathInfo) { - $baseUri = substr($decodedUri,0,strlen($decodedUri)-strlen($pathInfo)); - return rtrim($baseUri,'/') . '/'; + if (substr($decodedUri, strlen($decodedUri) - strlen($pathInfo)) === $pathInfo) { + $baseUri = substr($decodedUri, 0, strlen($decodedUri) - strlen($pathInfo)); + + return rtrim($baseUri, '/').'/'; } - throw new Sabre_DAV_Exception('The REQUEST_URI ('. $uri . ') did not end with the contents of PATH_INFO (' . $pathInfo . '). This server might be misconfigured.'); - + throw new Sabre_DAV_Exception('The REQUEST_URI ('.$uri.') did not end with the contents of PATH_INFO ('.$pathInfo.'). This server might be misconfigured.'); } // The last fallback is that we're just going to assume the server root. return '/'; - } /** - * Adds a plugin to the server + * Adds a plugin to the server. * * For more information, console the documentation of Sabre_DAV_ServerPlugin * * @param Sabre_DAV_ServerPlugin $plugin - * @return void */ - public function addPlugin(Sabre_DAV_ServerPlugin $plugin) { - + public function addPlugin(Sabre_DAV_ServerPlugin $plugin) + { $this->plugins[$plugin->getPluginName()] = $plugin; $plugin->initialize($this); - } /** @@ -344,34 +328,35 @@ class Sabre_DAV_Server { * This function returns null if the plugin was not found. * * @param string $name + * * @return Sabre_DAV_ServerPlugin */ - public function getPlugin($name) { - - if (isset($this->plugins[$name])) + public function getPlugin($name) + { + if (isset($this->plugins[$name])) { return $this->plugins[$name]; + } // This is a fallback and deprecated. - foreach($this->plugins as $plugin) { - if (get_class($plugin)===$name) return $plugin; + foreach ($this->plugins as $plugin) { + if (get_class($plugin) === $name) { + return $plugin; + } } return null; - } /** - * Returns all plugins + * Returns all plugins. * * @return array */ - public function getPlugins() { - + public function getPlugins() + { return $this->plugins; - } - /** * Subscribe to an event. * @@ -383,62 +368,61 @@ class Sabre_DAV_Server { * is triggered before anything else. If it's not needed to change this * number, it is recommended to ommit. * - * @param string $event + * @param string $event * @param callback $callback - * @param int $priority - * @return void + * @param int $priority */ - public function subscribeEvent($event, $callback, $priority = 100) { - + public function subscribeEvent($event, $callback, $priority = 100) + { if (!isset($this->eventSubscriptions[$event])) { $this->eventSubscriptions[$event] = array(); } - while(isset($this->eventSubscriptions[$event][$priority])) $priority++; + while (isset($this->eventSubscriptions[$event][$priority])) { + $priority++; + } $this->eventSubscriptions[$event][$priority] = $callback; ksort($this->eventSubscriptions[$event]); - } /** - * Broadcasts an event + * Broadcasts an event. * * This method will call all subscribers. If one of the subscribers returns false, the process stops. * * The arguments parameter will be sent to all subscribers * * @param string $eventName - * @param array $arguments + * @param array $arguments + * * @return bool */ - public function broadcastEvent($eventName,$arguments = array()) { - + public function broadcastEvent($eventName, $arguments = array()) + { if (isset($this->eventSubscriptions[$eventName])) { - - foreach($this->eventSubscriptions[$eventName] as $subscriber) { - - $result = call_user_func_array($subscriber,$arguments); - if ($result===false) return false; - + foreach ($this->eventSubscriptions[$eventName] as $subscriber) { + $result = call_user_func_array($subscriber, $arguments); + if ($result === false) { + return false; + } } - } return true; - } /** - * Handles a http request, and execute a method based on its name + * Handles a http request, and execute a method based on its name. * * @param string $method * @param string $uri - * @return void */ - public function invokeMethod($method, $uri) { - + public function invokeMethod($method, $uri) + { $method = strtoupper($method); - if (!$this->broadcastEvent('beforeMethod',array($method, $uri))) return; + if (!$this->broadcastEvent('beforeMethod', array($method, $uri))) { + return; + } // Make sure this is a HTTP method we support $internalMethods = array( @@ -452,73 +436,73 @@ class Sabre_DAV_Server { 'PROPPATCH', 'COPY', 'MOVE', - 'REPORT' + 'REPORT', ); - if (in_array($method,$internalMethods)) { - - call_user_func(array($this,'http' . $method), $uri); - + if (in_array($method, $internalMethods)) { + call_user_func(array($this, 'http'.$method), $uri); } else { - - if ($this->broadcastEvent('unknownMethod',array($method, $uri))) { + if ($this->broadcastEvent('unknownMethod', array($method, $uri))) { // Unsupported method - throw new Sabre_DAV_Exception_NotImplemented('There was no handler found for this "' . $method . '" method'); + throw new Sabre_DAV_Exception_NotImplemented('There was no handler found for this "'.$method.'" method'); } - } - } // {{{ HTTP Method implementations /** - * HTTP OPTIONS + * HTTP OPTIONS. * * @param string $uri - * @return void */ - protected function httpOptions($uri) { - + protected function httpOptions($uri) + { $methods = $this->getAllowedMethods($uri); - $this->httpResponse->setHeader('Allow',strtoupper(implode(', ',$methods))); - $features = array('1','3', 'extended-mkcol'); + $this->httpResponse->setHeader('Allow', strtoupper(implode(', ', $methods))); + $features = array('1', '3', 'extended-mkcol'); - foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures()); - - $this->httpResponse->setHeader('DAV',implode(', ',$features)); - $this->httpResponse->setHeader('MS-Author-Via','DAV'); - $this->httpResponse->setHeader('Accept-Ranges','bytes'); - if (self::$exposeVersion) { - $this->httpResponse->setHeader('X-Sabre-Version',Sabre_DAV_Version::VERSION); + foreach ($this->plugins as $plugin) { + $features = array_merge($features, $plugin->getFeatures()); } - $this->httpResponse->setHeader('Content-Length',0); - $this->httpResponse->sendStatus(200); + $this->httpResponse->setHeader('DAV', implode(', ', $features)); + $this->httpResponse->setHeader('MS-Author-Via', 'DAV'); + $this->httpResponse->setHeader('Accept-Ranges', 'bytes'); + if (self::$exposeVersion) { + $this->httpResponse->setHeader('X-Sabre-Version', Sabre_DAV_Version::VERSION); + } + $this->httpResponse->setHeader('Content-Length', 0); + $this->httpResponse->sendStatus(200); } /** - * HTTP GET + * HTTP GET. * * This method simply fetches the contents of a uri, like normal * * @param string $uri + * * @return bool */ - protected function httpGet($uri) { + protected function httpGet($uri) + { + $node = $this->tree->getNodeForPath($uri, 0); - $node = $this->tree->getNodeForPath($uri,0); + if (!$this->checkPreconditions(true)) { + return false; + } - if (!$this->checkPreconditions(true)) return false; - - if (!$node instanceof Sabre_DAV_IFile) throw new Sabre_DAV_Exception_NotImplemented('GET is only implemented on File objects'); + if (!$node instanceof Sabre_DAV_IFile) { + throw new Sabre_DAV_Exception_NotImplemented('GET is only implemented on File objects'); + } $body = $node->get(); // Converting string into stream, if needed. if (is_string($body)) { - $stream = fopen('php://temp','r+'); - fwrite($stream,$body); + $stream = fopen('php://temp', 'r+'); + fwrite($stream, $body); rewind($stream); $body = $stream; } @@ -536,14 +520,11 @@ class Sabre_DAV_Server { $httpHeaders['Content-Type'] = 'application/octet-stream'; } - if (isset($httpHeaders['Content-Length'])) { - $nodeSize = $httpHeaders['Content-Length']; // Need to unset Content-Length, because we'll handle that during figuring out the range unset($httpHeaders['Content-Length']); - } else { $nodeSize = null; } @@ -565,17 +546,22 @@ class Sabre_DAV_Server { // It's a date. We must check if the entity is modified since // the specified date. - if (!isset($httpHeaders['Last-Modified'])) $ignoreRangeHeader = true; - else { + if (!isset($httpHeaders['Last-Modified'])) { + $ignoreRangeHeader = true; + } else { $modified = new DateTime($httpHeaders['Last-Modified']); - if($modified > $ifRangeDate) $ignoreRangeHeader = true; + if ($modified > $ifRangeDate) { + $ignoreRangeHeader = true; + } } - } catch (Exception $e) { // It's an entity. We can do a simple comparison. - if (!isset($httpHeaders['ETag'])) $ignoreRangeHeader = true; - elseif ($httpHeaders['ETag']!==$ifRange) $ignoreRangeHeader = true; + if (!isset($httpHeaders['ETag'])) { + $ignoreRangeHeader = true; + } elseif ($httpHeaders['ETag'] !== $ifRange) { + $ignoreRangeHeader = true; + } } } @@ -584,57 +570,56 @@ class Sabre_DAV_Server { // Determining the exact byte offsets if (!is_null($range[0])) { - $start = $range[0]; - $end = $range[1]?$range[1]:$nodeSize-1; - if($start >= $nodeSize) - throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The start offset (' . $range[0] . ') exceeded the size of the entity (' . $nodeSize . ')'); - - if($end < $start) throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The end offset (' . $range[1] . ') is lower than the start offset (' . $range[0] . ')'); - if($end >= $nodeSize) $end = $nodeSize-1; + $end = $range[1] ? $range[1] : $nodeSize - 1; + if ($start >= $nodeSize) { + throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The start offset ('.$range[0].') exceeded the size of the entity ('.$nodeSize.')'); + } + if ($end < $start) { + throw new Sabre_DAV_Exception_RequestedRangeNotSatisfiable('The end offset ('.$range[1].') is lower than the start offset ('.$range[0].')'); + } + if ($end >= $nodeSize) { + $end = $nodeSize - 1; + } } else { + $start = $nodeSize - $range[1]; + $end = $nodeSize - 1; - $start = $nodeSize-$range[1]; - $end = $nodeSize-1; - - if ($start<0) $start = 0; - + if ($start < 0) { + $start = 0; + } } // New read/write stream - $newStream = fopen('php://temp','r+'); + $newStream = fopen('php://temp', 'r+'); - stream_copy_to_stream($body, $newStream, $end-$start+1, $start); + stream_copy_to_stream($body, $newStream, $end - $start + 1, $start); rewind($newStream); - $this->httpResponse->setHeader('Content-Length', $end-$start+1); - $this->httpResponse->setHeader('Content-Range','bytes ' . $start . '-' . $end . '/' . $nodeSize); + $this->httpResponse->setHeader('Content-Length', $end - $start + 1); + $this->httpResponse->setHeader('Content-Range', 'bytes '.$start.'-'.$end.'/'.$nodeSize); $this->httpResponse->sendStatus(206); $this->httpResponse->sendBody($newStream); - - } else { - - if ($nodeSize) $this->httpResponse->setHeader('Content-Length',$nodeSize); + if ($nodeSize) { + $this->httpResponse->setHeader('Content-Length', $nodeSize); + } $this->httpResponse->sendStatus(200); $this->httpResponse->sendBody($body); - } - } /** - * HTTP HEAD + * HTTP HEAD. * * This method is normally used to take a peak at a url, and only get the HTTP response headers, without the body * This is used by clients to determine if a remote file was changed, so they can use a local cached version, instead of downloading it again * * @param string $uri - * @return void */ - protected function httpHead($uri) { - + protected function httpHead($uri) + { $node = $this->tree->getNodeForPath($uri); /* This information is only collection for File objects. * Ideally we want to throw 405 Method Not Allowed for every @@ -648,31 +633,29 @@ class Sabre_DAV_Server { $this->httpResponse->setHeaders($headers); } $this->httpResponse->sendStatus(200); - } /** - * HTTP Delete + * HTTP Delete. * * The HTTP delete method, deletes a given uri * * @param string $uri - * @return void */ - protected function httpDelete($uri) { - - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return; + protected function httpDelete($uri) + { + if (!$this->broadcastEvent('beforeUnbind', array($uri))) { + return; + } $this->tree->delete($uri); - $this->broadcastEvent('afterUnbind',array($uri)); + $this->broadcastEvent('afterUnbind', array($uri)); $this->httpResponse->sendStatus(204); - $this->httpResponse->setHeader('Content-Length','0'); - + $this->httpResponse->setHeader('Content-Length', '0'); } - /** - * WebDAV PROPFIND + * WebDAV PROPFIND. * * This WebDAV method requests information about an uri resource, or a list of resources * If a client wants to receive the properties for a single resource it will add an HTTP Depth: header with a 0 value @@ -684,76 +667,78 @@ class Sabre_DAV_Server { * It has to return a HTTP 207 Multi-status status code * * @param string $uri - * @return void */ - protected function httpPropfind($uri) { + protected function httpPropfind($uri) + { // $xml = new Sabre_DAV_XMLReader(file_get_contents('php://input')); $requestedProperties = $this->parsePropfindRequest($this->httpRequest->getBody(true)); $depth = $this->getHTTPDepth(1); // The only two options for the depth of a propfind is 0 or 1 - if ($depth!=0) $depth = 1; + if ($depth != 0) { + $depth = 1; + } - $newProperties = $this->getPropertiesForPath($uri,$requestedProperties,$depth); + $newProperties = $this->getPropertiesForPath($uri, $requestedProperties, $depth); // This is a multi-status response $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); // Normally this header is only needed for OPTIONS responses, however.. // iCal seems to also depend on these being set for PROPFIND. Since // this is not harmful, we'll add it. - $features = array('1','3', 'extended-mkcol'); - foreach($this->plugins as $plugin) $features = array_merge($features,$plugin->getFeatures()); - $this->httpResponse->setHeader('DAV',implode(', ',$features)); + $features = array('1', '3', 'extended-mkcol'); + foreach ($this->plugins as $plugin) { + $features = array_merge($features, $plugin->getFeatures()); + } + $this->httpResponse->setHeader('DAV', implode(', ', $features)); $data = $this->generateMultiStatus($newProperties); $this->httpResponse->sendBody($data); - } /** - * WebDAV PROPPATCH + * WebDAV PROPPATCH. * * This method is called to update properties on a Node. The request is an XML body with all the mutations. * In this XML body it is specified which properties should be set/updated and/or deleted * * @param string $uri - * @return void */ - protected function httpPropPatch($uri) { - + protected function httpPropPatch($uri) + { $newProperties = $this->parsePropPatchRequest($this->httpRequest->getBody(true)); $result = $this->updateProperties($uri, $newProperties); $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->httpResponse->sendBody( $this->generateMultiStatus(array($result)) ); - } /** - * HTTP PUT method + * HTTP PUT method. * * This HTTP method updates a file, or creates a new one. * * If a new resource was created, a 201 Created status code should be returned. If an existing resource is updated, it's a 204 No Content * * @param string $uri + * * @return bool */ - protected function httpPut($uri) { - + protected function httpPut($uri) + { $body = $this->httpRequest->getBody(); // Intercepting Content-Range if ($this->httpRequest->getHeader('Content-Range')) { - /** + /* Content-Range is dangerous for PUT requests: PUT per definition stores a full resource. draft-ietf-httpbis-p2-semantics-15 says in section 7.6: @@ -782,241 +767,223 @@ class Sabre_DAV_Server { // Intercepting the Finder problem if (($expected = $this->httpRequest->getHeader('X-Expected-Entity-Length')) && $expected > 0) { - /** - Many webservers will not cooperate well with Finder PUT requests, - because it uses 'Chunked' transfer encoding for the request body. - - The symptom of this problem is that Finder sends files to the - server, but they arrive as 0-length files in PHP. - - If we don't do anything, the user might think they are uploading - files successfully, but they end up empty on the server. Instead, - we throw back an error if we detect this. - - The reason Finder uses Chunked, is because it thinks the files - might change as it's being uploaded, and therefore the - Content-Length can vary. - - Instead it sends the X-Expected-Entity-Length header with the size - of the file at the very start of the request. If this header is set, - but we don't get a request body we will fail the request to - protect the end-user. - */ +/** + protect the end-user. + */ // Only reading first byte - $firstByte = fread($body,1); - if (strlen($firstByte)!==1) { + $firstByte = fread($body, 1); + if (strlen($firstByte) !== 1) { throw new Sabre_DAV_Exception_Forbidden('This server is not compatible with OS/X finder. Consider using a different WebDAV client or webserver.'); } // The body needs to stay intact, so we copy everything to a // temporary stream. - $newBody = fopen('php://temp','r+'); - fwrite($newBody,$firstByte); + $newBody = fopen('php://temp', 'r+'); + fwrite($newBody, $firstByte); stream_copy_to_stream($body, $newBody); rewind($newBody); $body = $newBody; - } if ($this->tree->nodeExists($uri)) { - $node = $this->tree->getNodeForPath($uri); // Checking If-None-Match and related headers. - if (!$this->checkPreconditions()) return; + if (!$this->checkPreconditions()) { + return; + } // If the node is a collection, we'll deny it - if (!($node instanceof Sabre_DAV_IFile)) throw new Sabre_DAV_Exception_Conflict('PUT is not allowed on non-files.'); - if (!$this->broadcastEvent('beforeWriteContent',array($uri, $node, &$body))) return false; + if (!($node instanceof Sabre_DAV_IFile)) { + throw new Sabre_DAV_Exception_Conflict('PUT is not allowed on non-files.'); + } + if (!$this->broadcastEvent('beforeWriteContent', array($uri, $node, &$body))) { + return false; + } $etag = $node->put($body); - $this->broadcastEvent('afterWriteContent',array($uri, $node)); + $this->broadcastEvent('afterWriteContent', array($uri, $node)); - $this->httpResponse->setHeader('Content-Length','0'); - if ($etag) $this->httpResponse->setHeader('ETag',$etag); + $this->httpResponse->setHeader('Content-Length', '0'); + if ($etag) { + $this->httpResponse->setHeader('ETag', $etag); + } $this->httpResponse->sendStatus(204); - } else { - $etag = null; // If we got here, the resource didn't exist yet. - if (!$this->createFile($this->getRequestUri(),$body,$etag)) { + if (!$this->createFile($this->getRequestUri(), $body, $etag)) { // For one reason or another the file was not created. return; } - $this->httpResponse->setHeader('Content-Length','0'); - if ($etag) $this->httpResponse->setHeader('ETag', $etag); + $this->httpResponse->setHeader('Content-Length', '0'); + if ($etag) { + $this->httpResponse->setHeader('ETag', $etag); + } $this->httpResponse->sendStatus(201); - } - } - /** - * WebDAV MKCOL + * WebDAV MKCOL. * * The MKCOL method is used to create a new collection (directory) on the server * * @param string $uri - * @return void */ - protected function httpMkcol($uri) { - + protected function httpMkcol($uri) + { $requestBody = $this->httpRequest->getBody(true); if ($requestBody) { - $contentType = $this->httpRequest->getHeader('Content-Type'); - if (strpos($contentType,'application/xml')!==0 && strpos($contentType,'text/xml')!==0) { + if (strpos($contentType, 'application/xml') !== 0 && strpos($contentType, 'text/xml') !== 0) { // We must throw 415 for unsupported mkcol bodies throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must have an xml Content-Type'); - } $dom = Sabre_DAV_XMLUtil::loadDOMDocument($requestBody); - if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild)!=='{DAV:}mkcol') { + if (Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild) !== '{DAV:}mkcol') { // We must throw 415 for unsupported mkcol bodies throw new Sabre_DAV_Exception_UnsupportedMediaType('The request body for the MKCOL request must be a {DAV:}mkcol request construct.'); - } $properties = array(); - foreach($dom->firstChild->childNodes as $childNode) { - - if (Sabre_DAV_XMLUtil::toClarkNotation($childNode)!=='{DAV:}set') continue; + foreach ($dom->firstChild->childNodes as $childNode) { + if (Sabre_DAV_XMLUtil::toClarkNotation($childNode) !== '{DAV:}set') { + continue; + } $properties = array_merge($properties, Sabre_DAV_XMLUtil::parseProperties($childNode, $this->propertyMap)); - } - if (!isset($properties['{DAV:}resourcetype'])) + if (!isset($properties['{DAV:}resourcetype'])) { throw new Sabre_DAV_Exception_BadRequest('The mkcol request must include a {DAV:}resourcetype property'); + } $resourceType = $properties['{DAV:}resourcetype']->getValue(); unset($properties['{DAV:}resourcetype']); - } else { - $properties = array(); $resourceType = array('{DAV:}collection'); - } $result = $this->createCollection($uri, $resourceType, $properties); if (is_array($result)) { $this->httpResponse->sendStatus(207); - $this->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->httpResponse->sendBody( $this->generateMultiStatus(array($result)) ); - } else { - $this->httpResponse->setHeader('Content-Length','0'); + $this->httpResponse->setHeader('Content-Length', '0'); $this->httpResponse->sendStatus(201); } - } /** - * WebDAV HTTP MOVE method + * WebDAV HTTP MOVE method. * * This method moves one uri to a different uri. A lot of the actual request processing is done in getCopyMoveInfo * * @param string $uri + * * @return bool */ - protected function httpMove($uri) { - + protected function httpMove($uri) + { $moveInfo = $this->getCopyAndMoveInfo(); // If the destination is part of the source tree, we must fail - if ($moveInfo['destination']==$uri) + if ($moveInfo['destination'] == $uri) { throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.'); - - if ($moveInfo['destinationExists']) { - - if (!$this->broadcastEvent('beforeUnbind',array($moveInfo['destination']))) return false; - $this->tree->delete($moveInfo['destination']); - $this->broadcastEvent('afterUnbind',array($moveInfo['destination'])); - } - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return false; - if (!$this->broadcastEvent('beforeBind',array($moveInfo['destination']))) return false; - $this->tree->move($uri,$moveInfo['destination']); - $this->broadcastEvent('afterUnbind',array($uri)); - $this->broadcastEvent('afterBind',array($moveInfo['destination'])); + if ($moveInfo['destinationExists']) { + if (!$this->broadcastEvent('beforeUnbind', array($moveInfo['destination']))) { + return false; + } + $this->tree->delete($moveInfo['destination']); + $this->broadcastEvent('afterUnbind', array($moveInfo['destination'])); + } + + if (!$this->broadcastEvent('beforeUnbind', array($uri))) { + return false; + } + if (!$this->broadcastEvent('beforeBind', array($moveInfo['destination']))) { + return false; + } + $this->tree->move($uri, $moveInfo['destination']); + $this->broadcastEvent('afterUnbind', array($uri)); + $this->broadcastEvent('afterBind', array($moveInfo['destination'])); // If a resource was overwritten we should send a 204, otherwise a 201 - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus($moveInfo['destinationExists']?204:201); - + $this->httpResponse->setHeader('Content-Length', '0'); + $this->httpResponse->sendStatus($moveInfo['destinationExists'] ? 204 : 201); } /** - * WebDAV HTTP COPY method + * WebDAV HTTP COPY method. * * This method copies one uri to a different uri, and works much like the MOVE request * A lot of the actual request processing is done in getCopyMoveInfo * * @param string $uri + * * @return bool */ - protected function httpCopy($uri) { - + protected function httpCopy($uri) + { $copyInfo = $this->getCopyAndMoveInfo(); // If the destination is part of the source tree, we must fail - if ($copyInfo['destination']==$uri) + if ($copyInfo['destination'] == $uri) { throw new Sabre_DAV_Exception_Forbidden('Source and destination uri are identical.'); + } if ($copyInfo['destinationExists']) { - if (!$this->broadcastEvent('beforeUnbind',array($copyInfo['destination']))) return false; + if (!$this->broadcastEvent('beforeUnbind', array($copyInfo['destination']))) { + return false; + } $this->tree->delete($copyInfo['destination']); - } - if (!$this->broadcastEvent('beforeBind',array($copyInfo['destination']))) return false; - $this->tree->copy($uri,$copyInfo['destination']); - $this->broadcastEvent('afterBind',array($copyInfo['destination'])); + if (!$this->broadcastEvent('beforeBind', array($copyInfo['destination']))) { + return false; + } + $this->tree->copy($uri, $copyInfo['destination']); + $this->broadcastEvent('afterBind', array($copyInfo['destination'])); // If a resource was overwritten we should send a 204, otherwise a 201 - $this->httpResponse->setHeader('Content-Length','0'); - $this->httpResponse->sendStatus($copyInfo['destinationExists']?204:201); - + $this->httpResponse->setHeader('Content-Length', '0'); + $this->httpResponse->sendStatus($copyInfo['destinationExists'] ? 204 : 201); } - - /** - * HTTP REPORT method implementation + * HTTP REPORT method implementation. * * Although the REPORT method is not part of the standard WebDAV spec (it's from rfc3253) * It's used in a lot of extensions, so it made sense to implement it into the core. * * @param string $uri - * @return void */ - protected function httpReport($uri) { - + protected function httpReport($uri) + { $body = $this->httpRequest->getBody(true); $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); $reportName = Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild); - if ($this->broadcastEvent('report',array($reportName,$dom, $uri))) { + if ($this->broadcastEvent('report', array($reportName, $dom, $uri))) { // If broadcastEvent returned true, it means the report was not supported throw new Sabre_DAV_Exception_ReportNotImplemented(); - } - } // }}} @@ -1026,10 +993,11 @@ class Sabre_DAV_Server { * Returns an array with all the supported HTTP methods for a specific uri. * * @param string $uri + * * @return array */ - public function getAllowedMethods($uri) { - + public function getAllowedMethods($uri) + { $methods = array( 'OPTIONS', 'GET', @@ -1040,7 +1008,7 @@ class Sabre_DAV_Server { 'PROPPATCH', 'COPY', 'MOVE', - 'REPORT' + 'REPORT', ); // The MKCOL is only allowed on an unmapped uri @@ -1051,87 +1019,87 @@ class Sabre_DAV_Server { } // We're also checking if any of the plugins register any new methods - foreach($this->plugins as $plugin) $methods = array_merge($methods, $plugin->getHTTPMethods($uri)); + foreach ($this->plugins as $plugin) { + $methods = array_merge($methods, $plugin->getHTTPMethods($uri)); + } array_unique($methods); return $methods; - } /** - * Gets the uri for the request, keeping the base uri into consideration + * Gets the uri for the request, keeping the base uri into consideration. * * @return string */ - public function getRequestUri() { - + public function getRequestUri() + { return $this->calculateUri($this->httpRequest->getUri()); - } /** - * Calculates the uri for a request, making sure that the base uri is stripped out + * Calculates the uri for a request, making sure that the base uri is stripped out. * * @param string $uri + * * @throws Sabre_DAV_Exception_Forbidden A permission denied exception is thrown whenever there was an attempt to supply a uri outside of the base uri + * * @return string */ - public function calculateUri($uri) { - - if ($uri[0]!='/' && strpos($uri,'://')) { - - $uri = parse_url($uri,PHP_URL_PATH); - + public function calculateUri($uri) + { + if ($uri[0] != '/' && strpos($uri, '://')) { + $uri = parse_url($uri, PHP_URL_PATH); } - $uri = str_replace('//','/',$uri); + $uri = str_replace('//', '/', $uri); - if (strpos($uri,$this->getBaseUri())===0) { - - return trim(Sabre_DAV_URLUtil::decodePath(substr($uri,strlen($this->getBaseUri()))),'/'); + if (strpos($uri, $this->getBaseUri()) === 0) { + return trim(Sabre_DAV_URLUtil::decodePath(substr($uri, strlen($this->getBaseUri()))), '/'); // A special case, if the baseUri was accessed without a trailing // slash, we'll accept it as well. } elseif ($uri.'/' === $this->getBaseUri()) { - return ''; - } else { - - throw new Sabre_DAV_Exception_Forbidden('Requested uri (' . $uri . ') is out of base uri (' . $this->getBaseUri() . ')'); - + throw new Sabre_DAV_Exception_Forbidden('Requested uri ('.$uri.') is out of base uri ('.$this->getBaseUri().')'); } - } /** - * Returns the HTTP depth header + * Returns the HTTP depth header. * * This method returns the contents of the HTTP depth request header. If the depth header was 'infinity' it will return the Sabre_DAV_Server::DEPTH_INFINITY object * It is possible to supply a default depth value, which is used when the depth header has invalid content, or is completely non-existent * * @param mixed $default + * * @return int */ - public function getHTTPDepth($default = self::DEPTH_INFINITY) { + public function getHTTPDepth($default = self::DEPTH_INFINITY) + { // If its not set, we'll grab the default $depth = $this->httpRequest->getHeader('Depth'); - if (is_null($depth)) return $default; - - if ($depth == 'infinity') return self::DEPTH_INFINITY; + if (is_null($depth)) { + return $default; + } + if ($depth == 'infinity') { + return self::DEPTH_INFINITY; + } // If its an unknown value. we'll grab the default - if (!ctype_digit($depth)) return $default; - - return (int)$depth; + if (!ctype_digit($depth)) { + return $default; + } + return (int) $depth; } /** - * Returns the HTTP range header + * Returns the HTTP range header. * * This method returns null if there is no well-formed HTTP range request * header or array($start, $end). @@ -1144,27 +1112,31 @@ class Sabre_DAV_Server { * * @return array|null */ - public function getHTTPRange() { - + public function getHTTPRange() + { $range = $this->httpRequest->getHeader('range'); - if (is_null($range)) return null; + if (is_null($range)) { + return null; + } // Matching "Range: bytes=1234-5678: both numbers are optional - if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i',$range,$matches)) return null; + if (!preg_match('/^bytes=([0-9]*)-([0-9]*)$/i', $range, $matches)) { + return null; + } - if ($matches[1]==='' && $matches[2]==='') return null; + if ($matches[1] === '' && $matches[2] === '') { + return null; + } return array( - $matches[1]!==''?$matches[1]:null, - $matches[2]!==''?$matches[2]:null, + $matches[1] !== '' ? $matches[1] : null, + $matches[2] !== '' ? $matches[2] : null, ); - } - /** - * Returns information about Copy and Move requests + * Returns information about Copy and Move requests. * * This function is created to help getting information about the source and the destination for the * WebDAV MOVE and COPY HTTP request. It also validates a lot of information and throws proper exceptions @@ -1175,23 +1147,35 @@ class Sabre_DAV_Server { * * @return array */ - public function getCopyAndMoveInfo() { + public function getCopyAndMoveInfo() + { // Collecting the relevant HTTP headers - if (!$this->httpRequest->getHeader('Destination')) throw new Sabre_DAV_Exception_BadRequest('The destination header was not supplied'); + if (!$this->httpRequest->getHeader('Destination')) { + throw new Sabre_DAV_Exception_BadRequest('The destination header was not supplied'); + } $destination = $this->calculateUri($this->httpRequest->getHeader('Destination')); $overwrite = $this->httpRequest->getHeader('Overwrite'); - if (!$overwrite) $overwrite = 'T'; - if (strtoupper($overwrite)=='T') $overwrite = true; - elseif (strtoupper($overwrite)=='F') $overwrite = false; + if (!$overwrite) { + $overwrite = 'T'; + } + if (strtoupper($overwrite) == 'T') { + $overwrite = true; + } elseif (strtoupper($overwrite) == 'F') { + $overwrite = false; + } // We need to throw a bad request exception, if the header was invalid - else throw new Sabre_DAV_Exception_BadRequest('The HTTP Overwrite header should be either T or F'); + else { + throw new Sabre_DAV_Exception_BadRequest('The HTTP Overwrite header should be either T or F'); + } list($destinationDir) = Sabre_DAV_URLUtil::splitPath($destination); try { $destinationParent = $this->tree->getNodeForPath($destinationDir); - if (!($destinationParent instanceof Sabre_DAV_ICollection)) throw new Sabre_DAV_Exception_UnsupportedMediaType('The destination node is not a collection'); + if (!($destinationParent instanceof Sabre_DAV_ICollection)) { + throw new Sabre_DAV_Exception_UnsupportedMediaType('The destination node is not a collection'); + } } catch (Sabre_DAV_Exception_NotFound $e) { // If the destination parent node is not found, we throw a 409 @@ -1199,46 +1183,42 @@ class Sabre_DAV_Server { } try { - $destinationNode = $this->tree->getNodeForPath($destination); // If this succeeded, it means the destination already exists // we'll need to throw precondition failed in case overwrite is false - if (!$overwrite) throw new Sabre_DAV_Exception_PreconditionFailed('The destination node already exists, and the overwrite header is set to false','Overwrite'); - + if (!$overwrite) { + throw new Sabre_DAV_Exception_PreconditionFailed('The destination node already exists, and the overwrite header is set to false', 'Overwrite'); + } } catch (Sabre_DAV_Exception_NotFound $e) { // Destination didn't exist, we're all good $destinationNode = false; - - - } // These are the three relevant properties we need to return return array( - 'destination' => $destination, - 'destinationExists' => $destinationNode==true, - 'destinationNode' => $destinationNode, + 'destination' => $destination, + 'destinationExists' => $destinationNode == true, + 'destinationNode' => $destinationNode, ); - } /** - * Returns a list of properties for a path + * Returns a list of properties for a path. * * This is a simplified version getPropertiesForPath. * if you aren't interested in status codes, but you just * want to have a flat list of properties. Use this method. * * @param string $path - * @param array $propertyNames + * @param array $propertyNames */ - public function getProperties($path, $propertyNames) { + public function getProperties($path, $propertyNames) + { + $result = $this->getPropertiesForPath($path, $propertyNames, 0); - $result = $this->getPropertiesForPath($path,$propertyNames,0); return $result[0][200]; - } /** @@ -1250,26 +1230,28 @@ class Sabre_DAV_Server { * The parent node will not be returned. * * @param string $path - * @param array $propertyNames + * @param array $propertyNames + * * @return array */ - public function getPropertiesForChildren($path, $propertyNames) { - + public function getPropertiesForChildren($path, $propertyNames) + { $result = array(); - foreach($this->getPropertiesForPath($path,$propertyNames,1) as $k=>$row) { + foreach ($this->getPropertiesForPath($path, $propertyNames, 1) as $k => $row) { // Skipping the parent path - if ($k === 0) continue; + if ($k === 0) { + continue; + } $result[$row['href']] = $row[200]; - } - return $result; + return $result; } /** - * Returns a list of HTTP headers for a particular resource + * Returns a list of HTTP headers for a particular resource. * * The generated http headers are based on properties provided by the * resource. The method basically provides a simple mapping between @@ -1278,22 +1260,25 @@ class Sabre_DAV_Server { * The headers are intended to be used for HEAD and GET requests. * * @param string $path + * * @return array */ - public function getHTTPHeaders($path) { - + public function getHTTPHeaders($path) + { $propertyMap = array( - '{DAV:}getcontenttype' => 'Content-Type', + '{DAV:}getcontenttype' => 'Content-Type', '{DAV:}getcontentlength' => 'Content-Length', - '{DAV:}getlastmodified' => 'Last-Modified', - '{DAV:}getetag' => 'ETag', + '{DAV:}getlastmodified' => 'Last-Modified', + '{DAV:}getetag' => 'ETag', ); - $properties = $this->getProperties($path,array_keys($propertyMap)); + $properties = $this->getProperties($path, array_keys($propertyMap)); $headers = array(); - foreach($propertyMap as $property=>$header) { - if (!isset($properties[$property])) continue; + foreach ($propertyMap as $property => $header) { + if (!isset($properties[$property])) { + continue; + } if (is_scalar($properties[$property])) { $headers[$header] = $properties[$property]; @@ -1302,15 +1287,13 @@ class Sabre_DAV_Server { } elseif ($properties[$property] instanceof Sabre_DAV_Property_GetLastModified) { $headers[$header] = Sabre_HTTP_Util::toHTTPDate($properties[$property]->getTime()); } - } return $headers; - } /** - * Returns a list of properties for a given path + * Returns a list of properties for a given path. * * The path that should be supplied should have the baseUrl stripped out * The list of properties should be supplied in Clark notation. If the list is empty @@ -1319,32 +1302,35 @@ class Sabre_DAV_Server { * If a depth of 1 is requested child elements will also be returned. * * @param string $path - * @param array $propertyNames - * @param int $depth + * @param array $propertyNames + * @param int $depth + * * @return array */ - public function getPropertiesForPath($path, $propertyNames = array(), $depth = 0) { - - if ($depth!=0) $depth = 1; + public function getPropertiesForPath($path, $propertyNames = array(), $depth = 0) + { + if ($depth != 0) { + $depth = 1; + } $returnPropertyList = array(); $parentNode = $this->tree->getNodeForPath($path); $nodes = array( - $path => $parentNode + $path => $parentNode, ); - if ($depth==1 && $parentNode instanceof Sabre_DAV_ICollection) { - foreach($this->tree->getChildren($path) as $childNode) - $nodes[$path . '/' . $childNode->getName()] = $childNode; + if ($depth == 1 && $parentNode instanceof Sabre_DAV_ICollection) { + foreach ($this->tree->getChildren($path) as $childNode) { + $nodes[$path.'/'.$childNode->getName()] = $childNode; + } } // If the propertyNames array is empty, it means all properties are requested. // We shouldn't actually return everything we know though, and only return a // sensible list. - $allProperties = count($propertyNames)==0; - - foreach($nodes as $myPath=>$node) { + $allProperties = count($propertyNames) == 0; + foreach ($nodes as $myPath => $node) { $currentPropertyNames = $propertyNames; $newProperties = array( @@ -1370,93 +1356,105 @@ class Sabre_DAV_Server { // to make certain decisions about the entry. // WebDAV dictates we should add a / and the end of href's for collections $removeRT = false; - if (!in_array('{DAV:}resourcetype',$currentPropertyNames)) { + if (!in_array('{DAV:}resourcetype', $currentPropertyNames)) { $currentPropertyNames[] = '{DAV:}resourcetype'; $removeRT = true; } - $result = $this->broadcastEvent('beforeGetProperties',array($myPath, $node, &$currentPropertyNames, &$newProperties)); + $result = $this->broadcastEvent('beforeGetProperties', array($myPath, $node, &$currentPropertyNames, &$newProperties)); // If this method explicitly returned false, we must ignore this // node as it is inaccessible. - if ($result===false) continue; - - if (count($currentPropertyNames) > 0) { - - if ($node instanceof Sabre_DAV_IProperties) - $newProperties['200'] = $newProperties[200] + $node->getProperties($currentPropertyNames); - + if ($result === false) { + continue; } + if (count($currentPropertyNames) > 0) { + if ($node instanceof Sabre_DAV_IProperties) { + $newProperties['200'] = $newProperties[200] + $node->getProperties($currentPropertyNames); + } + } - foreach($currentPropertyNames as $prop) { + foreach ($currentPropertyNames as $prop) { + if (isset($newProperties[200][$prop])) { + continue; + } - if (isset($newProperties[200][$prop])) continue; - - switch($prop) { - case '{DAV:}getlastmodified' : if ($node->getLastModified()) $newProperties[200][$prop] = new Sabre_DAV_Property_GetLastModified($node->getLastModified()); break; - case '{DAV:}getcontentlength' : + switch ($prop) { + case '{DAV:}getlastmodified': if ($node->getLastModified()) { + $newProperties[200][$prop] = new Sabre_DAV_Property_GetLastModified($node->getLastModified()); + } break; + case '{DAV:}getcontentlength': if ($node instanceof Sabre_DAV_IFile) { $size = $node->getSize(); if (!is_null($size)) { - $newProperties[200][$prop] = (int)$node->getSize(); + $newProperties[200][$prop] = (int) $node->getSize(); } } break; - case '{DAV:}quota-used-bytes' : + case '{DAV:}quota-used-bytes': if ($node instanceof Sabre_DAV_IQuota) { $quotaInfo = $node->getQuotaInfo(); $newProperties[200][$prop] = $quotaInfo[0]; } break; - case '{DAV:}quota-available-bytes' : + case '{DAV:}quota-available-bytes': if ($node instanceof Sabre_DAV_IQuota) { $quotaInfo = $node->getQuotaInfo(); $newProperties[200][$prop] = $quotaInfo[1]; } break; - case '{DAV:}getetag' : if ($node instanceof Sabre_DAV_IFile && $etag = $node->getETag()) $newProperties[200][$prop] = $etag; break; - case '{DAV:}getcontenttype' : if ($node instanceof Sabre_DAV_IFile && $ct = $node->getContentType()) $newProperties[200][$prop] = $ct; break; - case '{DAV:}supported-report-set' : + case '{DAV:}getetag': if ($node instanceof Sabre_DAV_IFile && $etag = $node->getETag()) { + $newProperties[200][$prop] = $etag; + } break; + case '{DAV:}getcontenttype': if ($node instanceof Sabre_DAV_IFile && $ct = $node->getContentType()) { + $newProperties[200][$prop] = $ct; + } break; + case '{DAV:}supported-report-set': $reports = array(); - foreach($this->plugins as $plugin) { + foreach ($this->plugins as $plugin) { $reports = array_merge($reports, $plugin->getSupportedReportSet($myPath)); } $newProperties[200][$prop] = new Sabre_DAV_Property_SupportedReportSet($reports); break; - case '{DAV:}resourcetype' : + case '{DAV:}resourcetype': $newProperties[200]['{DAV:}resourcetype'] = new Sabre_DAV_Property_ResourceType(); - foreach($this->resourceTypeMapping as $className => $resourceType) { - if ($node instanceof $className) $newProperties[200]['{DAV:}resourcetype']->add($resourceType); + foreach ($this->resourceTypeMapping as $className => $resourceType) { + if ($node instanceof $className) { + $newProperties[200]['{DAV:}resourcetype']->add($resourceType); + } } break; } // If we were unable to find the property, we will list it as 404. - if (!$allProperties && !isset($newProperties[200][$prop])) $newProperties[404][$prop] = null; - + if (!$allProperties && !isset($newProperties[200][$prop])) { + $newProperties[404][$prop] = null; + } } - $this->broadcastEvent('afterGetProperties',array(trim($myPath,'/'),&$newProperties)); + $this->broadcastEvent('afterGetProperties', array(trim($myPath, '/'), &$newProperties)); - $newProperties['href'] = trim($myPath,'/'); + $newProperties['href'] = trim($myPath, '/'); // Its is a WebDAV recommendation to add a trailing slash to collectionnames. // Apple's iCal also requires a trailing slash for principals (rfc 3744). // Therefore we add a trailing / for any non-file. This might need adjustments // if we find there are other edge cases. - if ($myPath!='' && isset($newProperties[200]['{DAV:}resourcetype']) && count($newProperties[200]['{DAV:}resourcetype']->getValue())>0) $newProperties['href'] .='/'; + if ($myPath != '' && isset($newProperties[200]['{DAV:}resourcetype']) && count($newProperties[200]['{DAV:}resourcetype']->getValue()) > 0) { + $newProperties['href'] .= '/'; + } // If the resourcetype property was manually added to the requested property list, // we will remove it again. - if ($removeRT) unset($newProperties[200]['{DAV:}resourcetype']); + if ($removeRT) { + unset($newProperties[200]['{DAV:}resourcetype']); + } $returnPropertyList[] = $newProperties; - } return $returnPropertyList; - } /** @@ -1471,23 +1469,28 @@ class Sabre_DAV_Server { * @param string $uri * @param resource $data * @param string $etag + * * @return bool */ - public function createFile($uri,$data, &$etag = null) { + public function createFile($uri, $data, &$etag = null) + { + list($dir, $name) = Sabre_DAV_URLUtil::splitPath($uri); - list($dir,$name) = Sabre_DAV_URLUtil::splitPath($uri); - - if (!$this->broadcastEvent('beforeBind',array($uri))) return false; + if (!$this->broadcastEvent('beforeBind', array($uri))) { + return false; + } $parent = $this->tree->getNodeForPath($dir); - if (!$this->broadcastEvent('beforeCreateFile',array($uri, &$data, $parent))) return false; + if (!$this->broadcastEvent('beforeCreateFile', array($uri, &$data, $parent))) { + return false; + } - $etag = $parent->createFile($name,$data); + $etag = $parent->createFile($name, $data); $this->tree->markDirty($dir); - $this->broadcastEvent('afterBind',array($uri)); - $this->broadcastEvent('afterCreateFile',array($uri, $parent)); + $this->broadcastEvent('afterBind', array($uri)); + $this->broadcastEvent('afterCreateFile', array($uri, $parent)); return true; } @@ -1496,46 +1499,40 @@ class Sabre_DAV_Server { * This method is invoked by sub-systems creating a new directory. * * @param string $uri - * @return void */ - public function createDirectory($uri) { - - $this->createCollection($uri,array('{DAV:}collection'),array()); - + public function createDirectory($uri) + { + $this->createCollection($uri, array('{DAV:}collection'), array()); } /** - * Use this method to create a new collection + * Use this method to create a new collection. * * The {DAV:}resourcetype is specified using the resourceType array. * At the very least it must contain {DAV:}collection. * * The properties array can contain a list of additional properties. * - * @param string $uri The new uri - * @param array $resourceType The resourceType(s) - * @param array $properties A list of properties + * @param string $uri The new uri + * @param array $resourceType The resourceType(s) + * @param array $properties A list of properties + * * @return array|null */ - public function createCollection($uri, array $resourceType, array $properties) { - - list($parentUri,$newName) = Sabre_DAV_URLUtil::splitPath($uri); + public function createCollection($uri, array $resourceType, array $properties) + { + list($parentUri, $newName) = Sabre_DAV_URLUtil::splitPath($uri); // Making sure {DAV:}collection was specified as resourceType if (!in_array('{DAV:}collection', $resourceType)) { throw new Sabre_DAV_Exception_InvalidResourceType('The resourceType for this collection must at least include {DAV:}collection'); } - // Making sure the parent exists try { - $parent = $this->tree->getNodeForPath($parentUri); - } catch (Sabre_DAV_Exception_NotFound $e) { - throw new Sabre_DAV_Exception_Conflict('Parent node does not exist'); - } // Making sure the parent is a collection @@ -1543,33 +1540,29 @@ class Sabre_DAV_Server { throw new Sabre_DAV_Exception_Conflict('Parent node is not a collection'); } - - // Making sure the child does not already exist try { $parent->getChild($newName); // If we got here.. it means there's already a node on that url, and we need to throw a 405 throw new Sabre_DAV_Exception_MethodNotAllowed('The resource you tried to create already exists'); - } catch (Sabre_DAV_Exception_NotFound $e) { // This is correct } - - if (!$this->broadcastEvent('beforeBind',array($uri))) return; + if (!$this->broadcastEvent('beforeBind', array($uri))) { + return; + } // There are 2 modes of operation. The standard collection // creates the directory, and then updates properties // the extended collection can create it directly. if ($parent instanceof Sabre_DAV_IExtendedCollection) { - $parent->createExtendedCollection($newName, $resourceType, $properties); - } else { // No special resourcetypes are supported - if (count($resourceType)>1) { + if (count($resourceType) > 1) { throw new Sabre_DAV_Exception_InvalidResourceType('The {DAV:}resourcetype you specified is not supported here.'); } @@ -1578,42 +1571,38 @@ class Sabre_DAV_Server { $exception = null; $errorResult = null; - if (count($properties)>0) { - + if (count($properties) > 0) { try { - $errorResult = $this->updateProperties($uri, $properties); if (!isset($errorResult[200])) { $rollBack = true; } - } catch (Sabre_DAV_Exception $e) { - $rollBack = true; $exception = $e; - } - } if ($rollBack) { - if (!$this->broadcastEvent('beforeUnbind',array($uri))) return; + if (!$this->broadcastEvent('beforeUnbind', array($uri))) { + return; + } $this->tree->delete($uri); // Re-throwing exception - if ($exception) throw $exception; + if ($exception) { + throw $exception; + } return $errorResult; } - } $this->tree->markDirty($parentUri); - $this->broadcastEvent('afterBind',array($uri)); - + $this->broadcastEvent('afterBind', array($uri)); } /** - * This method updates a resource's properties + * This method updates a resource's properties. * * The properties array must be a list of properties. Array-keys are * property names in clarknotation, array-values are it's values. @@ -1627,10 +1616,12 @@ class Sabre_DAV_Server { * to generate a multistatus body. * * @param string $uri - * @param array $properties + * @param array $properties + * * @return array */ - public function updateProperties($uri, array $properties) { + public function updateProperties($uri, array $properties) + { // we'll start by grabbing the node, this will throw the appropriate // exceptions if it doesn't. @@ -1645,20 +1636,22 @@ class Sabre_DAV_Server { $hasError = false; // Running through all properties to make sure none of them are protected - if (!$hasError) foreach($properties as $propertyName => $value) { - if(in_array($propertyName, $this->protectedProperties)) { - $result[403][$propertyName] = null; - unset($remainingProperties[$propertyName]); - $hasError = true; + if (!$hasError) { + foreach ($properties as $propertyName => $value) { + if (in_array($propertyName, $this->protectedProperties)) { + $result[403][$propertyName] = null; + unset($remainingProperties[$propertyName]); + $hasError = true; + } } } if (!$hasError) { // Allowing plugins to take care of property updating - $hasError = !$this->broadcastEvent('updateProperties',array( + $hasError = !$this->broadcastEvent('updateProperties', array( &$remainingProperties, &$result, - $node + $node, )); } @@ -1666,7 +1659,7 @@ class Sabre_DAV_Server { // property is 403 Forbidden if (!$hasError && count($remainingProperties) && !($node instanceof Sabre_DAV_IProperties)) { $hasError = true; - foreach($properties as $propertyName=> $value) { + foreach ($properties as $propertyName => $value) { $result[403][$propertyName] = null; } $remainingProperties = array(); @@ -1674,60 +1667,55 @@ class Sabre_DAV_Server { // Only if there were no errors we may attempt to update the resource if (!$hasError) { - - if (count($remainingProperties)>0) { - + if (count($remainingProperties) > 0) { $updateResult = $node->updateProperties($remainingProperties); - if ($updateResult===true) { + if ($updateResult === true) { // success - foreach($remainingProperties as $propertyName=>$value) { + foreach ($remainingProperties as $propertyName => $value) { $result[200][$propertyName] = null; } - - } elseif ($updateResult===false) { + } elseif ($updateResult === false) { // The node failed to update the properties for an // unknown reason - foreach($remainingProperties as $propertyName=>$value) { + foreach ($remainingProperties as $propertyName => $value) { $result[403][$propertyName] = null; } - } elseif (is_array($updateResult)) { // The node has detailed update information // We need to merge the results with the earlier results. - foreach($updateResult as $status => $props) { + foreach ($updateResult as $status => $props) { if (is_array($props)) { - if (!isset($result[$status])) + if (!isset($result[$status])) { $result[$status] = array(); + } $result[$status] = array_merge($result[$status], $updateResult[$status]); } } - } else { throw new Sabre_DAV_Exception('Invalid result from updateProperties'); } $remainingProperties = array(); } - } - foreach($remainingProperties as $propertyName=>$value) { + foreach ($remainingProperties as $propertyName => $value) { // if there are remaining properties, it must mean // there's a dependency failure $result[424][$propertyName] = null; } // Removing empty array values - foreach($result as $status=>$props) { - - if (count($props)===0) unset($result[$status]); - + foreach ($result as $status => $props) { + if (count($props) === 0) { + unset($result[$status]); + } } $result['href'] = $uri; - return $result; + return $result; } /** @@ -1753,10 +1741,11 @@ class Sabre_DAV_Server { * desired behaviour for HTTP GET and HTTP HEAD requests. * * @param bool $handleAsGET + * * @return bool */ - public function checkPreconditions($handleAsGET = false) { - + public function checkPreconditions($handleAsGET = false) + { $uri = $this->getRequestUri(); $node = null; $lastMod = null; @@ -1771,34 +1760,33 @@ class Sabre_DAV_Server { try { $node = $this->tree->getNodeForPath($uri); } catch (Sabre_DAV_Exception_NotFound $e) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified and the resource did not exist','If-Match'); + throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified and the resource did not exist', 'If-Match'); } // Only need to check entity tags if they are not * - if ($ifMatch!=='*') { + if ($ifMatch !== '*') { // There can be multiple etags - $ifMatch = explode(',',$ifMatch); + $ifMatch = explode(',', $ifMatch); $haveMatch = false; - foreach($ifMatch as $ifMatchItem) { + foreach ($ifMatch as $ifMatchItem) { // Stripping any extra spaces - $ifMatchItem = trim($ifMatchItem,' '); + $ifMatchItem = trim($ifMatchItem, ' '); $etag = $node->getETag(); - if ($etag===$ifMatchItem) { + if ($etag === $ifMatchItem) { $haveMatch = true; } else { // Evolution has a bug where it sometimes prepends the " // with a \. This is our workaround. - if (str_replace('\\"','"', $ifMatchItem) === $etag) { + if (str_replace('\\"', '"', $ifMatchItem) === $etag) { $haveMatch = true; } } - } if (!$haveMatch) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified, but none of the specified the ETags matched.','If-Match'); + throw new Sabre_DAV_Exception_PreconditionFailed('An If-Match header was specified, but none of the specified the ETags matched.', 'If-Match'); } } } @@ -1819,34 +1807,35 @@ class Sabre_DAV_Server { } if ($nodeExists) { $haveMatch = false; - if ($ifNoneMatch==='*') $haveMatch = true; - else { + if ($ifNoneMatch === '*') { + $haveMatch = true; + } else { // There might be multiple etags $ifNoneMatch = explode(',', $ifNoneMatch); $etag = $node->getETag(); - foreach($ifNoneMatch as $ifNoneMatchItem) { + foreach ($ifNoneMatch as $ifNoneMatchItem) { // Stripping any extra spaces - $ifNoneMatchItem = trim($ifNoneMatchItem,' '); - - if ($etag===$ifNoneMatchItem) $haveMatch = true; + $ifNoneMatchItem = trim($ifNoneMatchItem, ' '); + if ($etag === $ifNoneMatchItem) { + $haveMatch = true; + } } - } if ($haveMatch) { if ($handleAsGET) { $this->httpResponse->sendStatus(304); + return false; } else { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-None-Match header was specified, but the ETag matched (or * was specified).','If-None-Match'); + throw new Sabre_DAV_Exception_PreconditionFailed('An If-None-Match header was specified, but the ETag matched (or * was specified).', 'If-None-Match'); } } } - } if (!$ifNoneMatch && ($ifModifiedSince = $this->httpRequest->getHeader('If-Modified-Since'))) { @@ -1865,10 +1854,11 @@ class Sabre_DAV_Server { } $lastMod = $node->getLastModified(); if ($lastMod) { - $lastMod = new DateTime('@' . $lastMod); + $lastMod = new DateTime('@'.$lastMod); if ($lastMod <= $date) { $this->httpResponse->sendStatus(304); $this->httpResponse->setHeader('Last-Modified', Sabre_HTTP_Util::toHTTPDate($lastMod)); + return false; } } @@ -1888,58 +1878,52 @@ class Sabre_DAV_Server { } $lastMod = $node->getLastModified(); if ($lastMod) { - $lastMod = new DateTime('@' . $lastMod); + $lastMod = new DateTime('@'.$lastMod); if ($lastMod > $date) { - throw new Sabre_DAV_Exception_PreconditionFailed('An If-Unmodified-Since header was specified, but the entity has been changed since the specified date.','If-Unmodified-Since'); + throw new Sabre_DAV_Exception_PreconditionFailed('An If-Unmodified-Since header was specified, but the entity has been changed since the specified date.', 'If-Unmodified-Since'); } } } - } - return true; + return true; } // }}} // {{{ XML Readers & Writers - /** - * Generates a WebDAV propfind response body based on a list of nodes + * Generates a WebDAV propfind response body based on a list of nodes. * * @param array $fileProperties The list with nodes + * * @return string */ - public function generateMultiStatus(array $fileProperties) { - - $dom = new DOMDocument('1.0','utf-8'); + public function generateMultiStatus(array $fileProperties) + { + $dom = new DOMDocument('1.0', 'utf-8'); //$dom->formatOutput = true; $multiStatus = $dom->createElement('d:multistatus'); $dom->appendChild($multiStatus); // Adding in default namespaces - foreach($this->xmlNamespaces as $namespace=>$prefix) { - - $multiStatus->setAttribute('xmlns:' . $prefix,$namespace); - + foreach ($this->xmlNamespaces as $namespace => $prefix) { + $multiStatus->setAttribute('xmlns:'.$prefix, $namespace); } - foreach($fileProperties as $entry) { - + foreach ($fileProperties as $entry) { $href = $entry['href']; unset($entry['href']); - $response = new Sabre_DAV_Property_Response($href,$entry); - $response->serialize($this,$multiStatus); - + $response = new Sabre_DAV_Property_Response($href, $entry); + $response->serialize($this, $multiStatus); } return $dom->saveXML(); - } /** - * This method parses a PropPatch request + * This method parses a PropPatch request. * * PropPatch changes the properties for a resource. This method * returns a list of properties. @@ -1949,62 +1933,65 @@ class Sabre_DAV_Server { * will be null. * * @param string $body xml body + * * @return array list of properties in need of updating or deletion */ - public function parsePropPatchRequest($body) { + public function parsePropPatchRequest($body) + { //We'll need to change the DAV namespace declaration to something else in order to make it parsable $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); $newProperties = array(); - foreach($dom->firstChild->childNodes as $child) { - - if ($child->nodeType !== XML_ELEMENT_NODE) continue; + foreach ($dom->firstChild->childNodes as $child) { + if ($child->nodeType !== XML_ELEMENT_NODE) { + continue; + } $operation = Sabre_DAV_XMLUtil::toClarkNotation($child); - if ($operation!=='{DAV:}set' && $operation!=='{DAV:}remove') continue; + if ($operation !== '{DAV:}set' && $operation !== '{DAV:}remove') { + continue; + } $innerProperties = Sabre_DAV_XMLUtil::parseProperties($child, $this->propertyMap); - foreach($innerProperties as $propertyName=>$propertyValue) { - - if ($operation==='{DAV:}remove') { + foreach ($innerProperties as $propertyName => $propertyValue) { + if ($operation === '{DAV:}remove') { $propertyValue = null; } $newProperties[$propertyName] = $propertyValue; - } - } return $newProperties; - } /** - * This method parses the PROPFIND request and returns its information + * This method parses the PROPFIND request and returns its information. * * This will either be a list of properties, or an empty array; in which case * an {DAV:}allprop was requested. * * @param string $body + * * @return array */ - public function parsePropFindRequest($body) { + public function parsePropFindRequest($body) + { // If the propfind body was empty, it means IE is requesting 'all' properties - if (!$body) return array(); + if (!$body) { + return array(); + } $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); - $elem = $dom->getElementsByTagNameNS('DAV:','propfind')->item(0); - return array_keys(Sabre_DAV_XMLUtil::parseProperties($elem)); + $elem = $dom->getElementsByTagNameNS('DAV:', 'propfind')->item(0); + return array_keys(Sabre_DAV_XMLUtil::parseProperties($elem)); } // }}} - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/ServerPlugin.php b/dav/SabreDAV/lib/Sabre/DAV/ServerPlugin.php index 131863d1..05d818c1 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/ServerPlugin.php +++ b/dav/SabreDAV/lib/Sabre/DAV/ServerPlugin.php @@ -5,14 +5,12 @@ * * Plugins can modify or extend the servers behaviour. * - * @package Sabre - * @subpackage DAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -abstract class Sabre_DAV_ServerPlugin { - +abstract class Sabre_DAV_ServerPlugin +{ /** * This initializes the plugin. * @@ -22,7 +20,6 @@ abstract class Sabre_DAV_ServerPlugin { * This method should set up the requires event subscriptions. * * @param Sabre_DAV_Server $server - * @return void */ abstract public function initialize(Sabre_DAV_Server $server); @@ -34,10 +31,9 @@ abstract class Sabre_DAV_ServerPlugin { * * @return array */ - public function getFeatures() { - + public function getFeatures() + { return array(); - } /** @@ -48,12 +44,12 @@ abstract class Sabre_DAV_ServerPlugin { * available for the specified uri. * * @param string $uri + * * @return array */ - public function getHTTPMethods($uri) { - + public function getHTTPMethods($uri) + { return array(); - } /** @@ -64,10 +60,9 @@ abstract class Sabre_DAV_ServerPlugin { * * @return string */ - public function getPluginName() { - + public function getPluginName() + { return get_class($this); - } /** @@ -78,13 +73,11 @@ abstract class Sabre_DAV_ServerPlugin { * implement them * * @param string $uri + * * @return array */ - public function getSupportedReportSet($uri) { - + public function getSupportedReportSet($uri) + { return array(); - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/SimpleCollection.php b/dav/SabreDAV/lib/Sabre/DAV/SimpleCollection.php index 79e2eaaa..1d462182 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/SimpleCollection.php +++ b/dav/SabreDAV/lib/Sabre/DAV/SimpleCollection.php @@ -1,75 +1,69 @@ name = $name; - foreach($children as $child) { - - if (!($child instanceof Sabre_DAV_INode)) throw new Sabre_DAV_Exception('Only instances of Sabre_DAV_INode are allowed to be passed in the children argument'); + foreach ($children as $child) { + if (!($child instanceof Sabre_DAV_INode)) { + throw new Sabre_DAV_Exception('Only instances of Sabre_DAV_INode are allowed to be passed in the children argument'); + } $this->addChild($child); - } - } /** - * Adds a new childnode to this collection + * Adds a new childnode to this collection. * * @param Sabre_DAV_INode $child - * @return void */ - public function addChild(Sabre_DAV_INode $child) { - + public function addChild(Sabre_DAV_INode $child) + { $this->children[$child->getName()] = $child; - } /** - * Returns the name of the collection + * Returns the name of the collection. * * @return string */ - public function getName() { - + public function getName() + { return $this->name; - } /** @@ -82,27 +76,26 @@ class Sabre_DAV_SimpleCollection extends Sabre_DAV_Collection { * exist. * * @param string $name + * * @throws Sabre_DAV_Exception_NotFound + * * @return Sabre_DAV_INode */ - public function getChild($name) { - - if (isset($this->children[$name])) return $this->children[$name]; - throw new Sabre_DAV_Exception_NotFound('File not found: ' . $name . ' in \'' . $this->getName() . '\''); - + public function getChild($name) + { + if (isset($this->children[$name])) { + return $this->children[$name]; + } + throw new Sabre_DAV_Exception_NotFound('File not found: '.$name.' in \''.$this->getName().'\''); } /** - * Returns a list of children for this collection + * Returns a list of children for this collection. * * @return array */ - public function getChildren() { - + public function getChildren() + { return array_values($this->children); - } - - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/SimpleFile.php b/dav/SabreDAV/lib/Sabre/DAV/SimpleFile.php index 58330d68..7edab4fe 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/SimpleFile.php +++ b/dav/SabreDAV/lib/Sabre/DAV/SimpleFile.php @@ -1,57 +1,54 @@ name = $name; $this->contents = $contents; $this->mimeType = $mimeType; - } /** @@ -61,23 +58,21 @@ class Sabre_DAV_SimpleFile extends Sabre_DAV_File { * * @return string */ - public function getName() { - + public function getName() + { return $this->name; - } /** - * Returns the data + * Returns the data. * * This method may either return a string or a readable stream resource * * @return mixed */ - public function get() { - + public function get() + { return $this->contents; - } /** @@ -85,37 +80,35 @@ class Sabre_DAV_SimpleFile extends Sabre_DAV_File { * * @return int */ - public function getSize() { - + public function getSize() + { return strlen($this->contents); - } /** - * Returns the ETag for a file + * Returns the ETag for a file. * * An ETag is a unique identifier representing the current version of the file. If the file changes, the ETag MUST change. * The ETag is an arbitrary string, but MUST be surrounded by double-quotes. * * Return null if the ETag can not effectively be determined + * * @return string */ - public function getETag() { - - return '"' . md5($this->contents) . '"'; - + public function getETag() + { + return '"'.md5($this->contents).'"'; } /** - * Returns the mime-type for a file + * Returns the mime-type for a file. * * If null is returned, we'll assume application/octet-stream + * * @return string */ - public function getContentType() { - + public function getContentType() + { return $this->mimeType; - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/StringUtil.php b/dav/SabreDAV/lib/Sabre/DAV/StringUtil.php index b126a94c..f11a42b4 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/StringUtil.php +++ b/dav/SabreDAV/lib/Sabre/DAV/StringUtil.php @@ -1,69 +1,67 @@ dataDir = $dataDir; - } /** - * Initialize the plugin + * Initialize the plugin. * * This is called automatically be the Server class after this plugin is * added with Sabre_DAV_Server::addPlugin() * * @param Sabre_DAV_Server $server - * @return void */ - public function initialize(Sabre_DAV_Server $server) { - + public function initialize(Sabre_DAV_Server $server) + { $this->server = $server; - $server->subscribeEvent('beforeMethod',array($this,'beforeMethod')); - $server->subscribeEvent('beforeCreateFile',array($this,'beforeCreateFile')); - + $server->subscribeEvent('beforeMethod', array($this, 'beforeMethod')); + $server->subscribeEvent('beforeCreateFile', array($this, 'beforeCreateFile')); } /** - * This method is called before any HTTP method handler + * This method is called before any HTTP method handler. * * This method intercepts any GET, DELETE, PUT and PROPFIND calls to * filenames that are known to match the 'temporary file' regex. * * @param string $method * @param string $uri + * * @return bool */ - public function beforeMethod($method, $uri) { - - if (!$tempLocation = $this->isTempFile($uri)) + public function beforeMethod($method, $uri) + { + if (!$tempLocation = $this->isTempFile($uri)) { return true; + } - switch($method) { - case 'GET' : + switch ($method) { + case 'GET': return $this->httpGet($tempLocation); - case 'PUT' : + case 'PUT': return $this->httpPut($tempLocation); - case 'PROPFIND' : + case 'PROPFIND': return $this->httpPropfind($tempLocation, $uri); - case 'DELETE' : + case 'DELETE': return $this->httpDelete($tempLocation); } - return true; + return true; } /** @@ -128,21 +129,22 @@ class Sabre_DAV_TemporaryFileFilterPlugin extends Sabre_DAV_ServerPlugin { * This is used to deal with HTTP LOCK requests which create a new * file. * - * @param string $uri + * @param string $uri * @param resource $data + * * @return bool */ - public function beforeCreateFile($uri,$data) { - + public function beforeCreateFile($uri, $data) + { if ($tempPath = $this->isTempFile($uri)) { - $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); - file_put_contents($tempPath,$data); + $hR->setHeader('X-Sabre-Temp', 'true'); + file_put_contents($tempPath, $data); + return false; } - return true; + return true; } /** @@ -151,69 +153,71 @@ class Sabre_DAV_TemporaryFileFilterPlugin extends Sabre_DAV_ServerPlugin { * temporary file storage. * * @param string $path - * @return boolean|string + * + * @return bool|string */ - protected function isTempFile($path) { + protected function isTempFile($path) + { // We're only interested in the basename. list(, $tempPath) = Sabre_DAV_URLUtil::splitPath($path); - foreach($this->temporaryFilePatterns as $tempFile) { - - if (preg_match($tempFile,$tempPath)) { - return $this->getDataDir() . '/sabredav_' . md5($path) . '.tempfile'; + foreach ($this->temporaryFilePatterns as $tempFile) { + if (preg_match($tempFile, $tempPath)) { + return $this->getDataDir().'/sabredav_'.md5($path).'.tempfile'; } - } return false; - } - /** * This method handles the GET method for temporary files. * If the file doesn't exist, it will return false which will kick in * the regular system for the GET method. * * @param string $tempLocation + * * @return bool */ - public function httpGet($tempLocation) { - - if (!file_exists($tempLocation)) return true; + public function httpGet($tempLocation) + { + if (!file_exists($tempLocation)) { + return true; + } $hR = $this->server->httpResponse; - $hR->setHeader('Content-Type','application/octet-stream'); - $hR->setHeader('Content-Length',filesize($tempLocation)); - $hR->setHeader('X-Sabre-Temp','true'); + $hR->setHeader('Content-Type', 'application/octet-stream'); + $hR->setHeader('Content-Length', filesize($tempLocation)); + $hR->setHeader('X-Sabre-Temp', 'true'); $hR->sendStatus(200); - $hR->sendBody(fopen($tempLocation,'r')); - return false; + $hR->sendBody(fopen($tempLocation, 'r')); + return false; } /** * This method handles the PUT method. * * @param string $tempLocation + * * @return bool */ - public function httpPut($tempLocation) { - + public function httpPut($tempLocation) + { $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); + $hR->setHeader('X-Sabre-Temp', 'true'); $newFile = !file_exists($tempLocation); if (!$newFile && ($this->server->httpRequest->getHeader('If-None-Match'))) { - throw new Sabre_DAV_Exception_PreconditionFailed('The resource already exists, and an If-None-Match header was supplied'); + throw new Sabre_DAV_Exception_PreconditionFailed('The resource already exists, and an If-None-Match header was supplied'); } - file_put_contents($tempLocation,$this->server->httpRequest->getBody()); - $hR->sendStatus($newFile?201:200); - return false; + file_put_contents($tempLocation, $this->server->httpRequest->getBody()); + $hR->sendStatus($newFile ? 201 : 200); + return false; } /** @@ -223,18 +227,21 @@ class Sabre_DAV_TemporaryFileFilterPlugin extends Sabre_DAV_ServerPlugin { * standard HTTP DELETE handler kick in. * * @param string $tempLocation + * * @return bool */ - public function httpDelete($tempLocation) { - - if (!file_exists($tempLocation)) return true; + public function httpDelete($tempLocation) + { + if (!file_exists($tempLocation)) { + return true; + } unlink($tempLocation); $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); + $hR->setHeader('X-Sabre-Temp', 'true'); $hR->sendStatus(204); - return false; + return false; } /** @@ -246,16 +253,19 @@ class Sabre_DAV_TemporaryFileFilterPlugin extends Sabre_DAV_ServerPlugin { * * @param string $tempLocation * @param string $uri + * * @return bool */ - public function httpPropfind($tempLocation, $uri) { - - if (!file_exists($tempLocation)) return true; + public function httpPropfind($tempLocation, $uri) + { + if (!file_exists($tempLocation)) { + return true; + } $hR = $this->server->httpResponse; - $hR->setHeader('X-Sabre-Temp','true'); + $hR->setHeader('X-Sabre-Temp', 'true'); $hR->sendStatus(207); - $hR->setHeader('Content-Type','application/xml; charset=utf-8'); + $hR->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->parsePropFindRequest($this->server->httpRequest->getBody(true)); @@ -272,11 +282,10 @@ class Sabre_DAV_TemporaryFileFilterPlugin extends Sabre_DAV_ServerPlugin { $data = $this->server->generateMultiStatus(array($properties)); $hR->sendBody($data); + return false; - } - /** * This method returns the directory where the temporary files should be stored. * diff --git a/dav/SabreDAV/lib/Sabre/DAV/Tree.php b/dav/SabreDAV/lib/Sabre/DAV/Tree.php index 50216394..165216a3 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Tree.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Tree.php @@ -1,25 +1,25 @@ getNodeForPath($path); + return true; - } catch (Sabre_DAV_Exception_NotFound $e) { - return false; - } - } /** - * Copies a file from path to another + * Copies a file from path to another. * - * @param string $sourcePath The source location + * @param string $sourcePath The source location * @param string $destinationPath The full destination path - * @return void */ - public function copy($sourcePath, $destinationPath) { - + public function copy($sourcePath, $destinationPath) + { $sourceNode = $this->getNodeForPath($sourcePath); // grab the dirname and basename components list($destinationDir, $destinationName) = Sabre_DAV_URLUtil::splitPath($destinationPath); $destinationParent = $this->getNodeForPath($destinationDir); - $this->copyNode($sourceNode,$destinationParent,$destinationName); + $this->copyNode($sourceNode, $destinationParent, $destinationName); $this->markDirty($destinationDir); - } /** - * Moves a file from one location to another + * Moves a file from one location to another. * - * @param string $sourcePath The path to the file which should be moved + * @param string $sourcePath The path to the file which should be moved * @param string $destinationPath The full destination path, so not just the destination parent node + * * @return int */ - public function move($sourcePath, $destinationPath) { - + public function move($sourcePath, $destinationPath) + { list($sourceDir, $sourceName) = Sabre_DAV_URLUtil::splitPath($sourcePath); list($destinationDir, $destinationName) = Sabre_DAV_URLUtil::splitPath($destinationPath); - if ($sourceDir===$destinationDir) { + if ($sourceDir === $destinationDir) { $renameable = $this->getNodeForPath($sourcePath); $renameable->setName($destinationName); } else { - $this->copy($sourcePath,$destinationPath); + $this->copy($sourcePath, $destinationPath); $this->getNodeForPath($sourcePath)->delete(); } $this->markDirty($sourceDir); $this->markDirty($destinationDir); - } /** - * Deletes a node from the tree + * Deletes a node from the tree. * * @param string $path - * @return void */ - public function delete($path) { - + public function delete($path) + { $node = $this->getNodeForPath($path); $node->delete(); list($parent) = Sabre_DAV_URLUtil::splitPath($path); $this->markDirty($parent); - } /** * Returns a list of childnodes for a given path. * * @param string $path + * * @return array */ - public function getChildren($path) { - + public function getChildren($path) + { $node = $this->getNodeForPath($path); - return $node->getChildren(); + return $node->getChildren(); } /** - * This method is called with every tree update + * This method is called with every tree update. * * Examples of tree updates are: * * node deletions @@ -135,59 +129,47 @@ abstract class Sabre_DAV_Tree { * If a path is passed, it is assumed that the entire subtree is dirty * * @param string $path - * @return void */ - public function markDirty($path) { - - + public function markDirty($path) + { } /** - * copyNode + * copyNode. * - * @param Sabre_DAV_INode $source + * @param Sabre_DAV_INode $source * @param Sabre_DAV_ICollection $destinationParent - * @param string $destinationName - * @return void + * @param string $destinationName */ - protected function copyNode(Sabre_DAV_INode $source,Sabre_DAV_ICollection $destinationParent,$destinationName = null) { - - if (!$destinationName) $destinationName = $source->getName(); + protected function copyNode(Sabre_DAV_INode $source, Sabre_DAV_ICollection $destinationParent, $destinationName = null) + { + if (!$destinationName) { + $destinationName = $source->getName(); + } if ($source instanceof Sabre_DAV_IFile) { - $data = $source->get(); // If the body was a string, we need to convert it to a stream if (is_string($data)) { - $stream = fopen('php://temp','r+'); - fwrite($stream,$data); + $stream = fopen('php://temp', 'r+'); + fwrite($stream, $data); rewind($stream); $data = $stream; } - $destinationParent->createFile($destinationName,$data); + $destinationParent->createFile($destinationName, $data); $destination = $destinationParent->getChild($destinationName); - } elseif ($source instanceof Sabre_DAV_ICollection) { - $destinationParent->createDirectory($destinationName); $destination = $destinationParent->getChild($destinationName); - foreach($source->getChildren() as $child) { - - $this->copyNode($child,$destination); - + foreach ($source->getChildren() as $child) { + $this->copyNode($child, $destination); } - } if ($source instanceof Sabre_DAV_IProperties && $destination instanceof Sabre_DAV_IProperties) { - $props = $source->getProperties(array()); $destination->updateProperties($props); - } - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/Tree/Filesystem.php b/dav/SabreDAV/lib/Sabre/DAV/Tree/Filesystem.php index 40580ae3..ddc4e4ab 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/Tree/Filesystem.php +++ b/dav/SabreDAV/lib/Sabre/DAV/Tree/Filesystem.php @@ -1,16 +1,14 @@ basePath = $basePath; - } /** - * Returns a new node for the given path + * Returns a new node for the given path. * * @param string $path + * * @return Sabre_DAV_FS_Node */ - public function getNodeForPath($path) { - + public function getNodeForPath($path) + { $realPath = $this->getRealPath($path); - if (!file_exists($realPath)) throw new Sabre_DAV_Exception_NotFound('File at location ' . $realPath . ' not found'); + if (!file_exists($realPath)) { + throw new Sabre_DAV_Exception_NotFound('File at location '.$realPath.' not found'); + } if (is_dir($realPath)) { return new Sabre_DAV_FS_Directory($realPath); } else { return new Sabre_DAV_FS_File($realPath); } - } /** * Returns the real filesystem path for a webdav url. * * @param string $publicPath + * * @return string */ - protected function getRealPath($publicPath) { - - return rtrim($this->basePath,'/') . '/' . trim($publicPath,'/'); - + protected function getRealPath($publicPath) + { + return rtrim($this->basePath, '/').'/'.trim($publicPath, '/'); } /** @@ -69,37 +68,33 @@ class Sabre_DAV_Tree_Filesystem extends Sabre_DAV_Tree { * * @param string $source * @param string $destination - * @return void */ - public function copy($source,$destination) { - + public function copy($source, $destination) + { $source = $this->getRealPath($source); $destination = $this->getRealPath($destination); - $this->realCopy($source,$destination); - + $this->realCopy($source, $destination); } /** - * Used by self::copy + * Used by self::copy. * * @param string $source * @param string $destination - * @return void */ - protected function realCopy($source,$destination) { - + protected function realCopy($source, $destination) + { if (is_file($source)) { - copy($source,$destination); + copy($source, $destination); } else { mkdir($destination); - foreach(scandir($source) as $subnode) { - - if ($subnode=='.' || $subnode=='..') continue; - $this->realCopy($source.'/'.$subnode,$destination.'/'.$subnode); - + foreach (scandir($source) as $subnode) { + if ($subnode == '.' || $subnode == '..') { + continue; + } + $this->realCopy($source.'/'.$subnode, $destination.'/'.$subnode); } } - } /** @@ -109,15 +104,11 @@ class Sabre_DAV_Tree_Filesystem extends Sabre_DAV_Tree { * * @param string $source * @param string $destination - * @return void */ - public function move($source,$destination) { - + public function move($source, $destination) + { $source = $this->getRealPath($source); $destination = $this->getRealPath($destination); - rename($source,$destination); - + rename($source, $destination); } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAV/URLUtil.php b/dav/SabreDAV/lib/Sabre/DAV/URLUtil.php index 794665a4..4839f4d9 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/URLUtil.php +++ b/dav/SabreDAV/lib/Sabre/DAV/URLUtil.php @@ -1,7 +1,7 @@ nodeType !== XML_ELEMENT_NODE) return null; + public static function toClarkNotation(DOMNode $dom) + { + if ($dom->nodeType !== XML_ELEMENT_NODE) { + return null; + } $ns = $dom->namespaceURI; // Mapping to clark notation - return '{' . $ns . '}' . $dom->localName; - + return '{'.$ns.'}'.$dom->localName; } /** @@ -44,20 +44,21 @@ class Sabre_DAV_XMLUtil { * If the string was invalid, it will throw an InvalidArgumentException. * * @param string $str + * * @throws InvalidArgumentException + * * @return array */ - static function parseClarkNotation($str) { - - if (!preg_match('/^{([^}]*)}(.*)$/',$str,$matches)) { - throw new InvalidArgumentException('\'' . $str . '\' is not a valid clark-notation formatted string'); + public static function parseClarkNotation($str) + { + if (!preg_match('/^{([^}]*)}(.*)$/', $str, $matches)) { + throw new InvalidArgumentException('\''.$str.'\' is not a valid clark-notation formatted string'); } return array( $matches[1], - $matches[2] + $matches[2], ); - } /** @@ -67,30 +68,32 @@ class Sabre_DAV_XMLUtil { * It does not preserve whitespace. * * @param string $xml + * * @throws Sabre_DAV_Exception_BadRequest + * * @return DOMDocument */ - static function loadDOMDocument($xml) { - - if (empty($xml)) + public static function loadDOMDocument($xml) + { + if (empty($xml)) { throw new Sabre_DAV_Exception_BadRequest('Empty XML document sent'); + } // The BitKinex client sends xml documents as UTF-16. PHP 5.3.1 (and presumably lower) // does not support this, so we must intercept this and convert to UTF-8. - if (substr($xml,0,12) === "\x3c\x00\x3f\x00\x78\x00\x6d\x00\x6c\x00\x20\x00") { + if (substr($xml, 0, 12) === "\x3c\x00\x3f\x00\x78\x00\x6d\x00\x6c\x00\x20\x00") { // Note: the preceeding byte sequence is "]*)encoding="UTF-16"([^>]*)>|u','',$xml); - + $xml = preg_replace('|<\?xml([^>]*)encoding="UTF-16"([^>]*)>|u', '', $xml); } // Retaining old error setting - $oldErrorSetting = libxml_use_internal_errors(true); + $oldErrorSetting = libxml_use_internal_errors(true); // Clearing any previous errors libxml_clear_errors(); @@ -99,23 +102,24 @@ class Sabre_DAV_XMLUtil { // We don't generally care about any whitespace $dom->preserveWhiteSpace = false; - - $dom->loadXML($xml,LIBXML_NOWARNING | LIBXML_NOERROR); + + $dom->loadXML($xml, LIBXML_NOWARNING | LIBXML_NOERROR); if ($error = libxml_get_last_error()) { libxml_clear_errors(); - throw new Sabre_DAV_Exception_BadRequest('The request body had an invalid XML body. (message: ' . $error->message . ', errorcode: ' . $error->code . ', line: ' . $error->line . ')'); + throw new Sabre_DAV_Exception_BadRequest('The request body had an invalid XML body. (message: '.$error->message.', errorcode: '.$error->code.', line: '.$error->line.')'); } // Restoring old mechanism for error handling - if ($oldErrorSetting===false) libxml_use_internal_errors(false); + if ($oldErrorSetting === false) { + libxml_use_internal_errors(false); + } return $dom; - } /** - * Parses all WebDAV properties out of a DOM Element + * Parses all WebDAV properties out of a DOM Element. * * Generally WebDAV properties are enclosed in {DAV:}prop elements. This * method helps by going through all these and pulling out the actual @@ -133,33 +137,34 @@ class Sabre_DAV_XMLUtil { * (statically) called. The result of this method is used as the value. * * @param DOMElement $parentNode - * @param array $propertyMap + * @param array $propertyMap + * * @return array */ - static function parseProperties(DOMElement $parentNode, array $propertyMap = array()) { - + public static function parseProperties(DOMElement $parentNode, array $propertyMap = array()) + { $propList = array(); - foreach($parentNode->childNodes as $propNode) { + foreach ($parentNode->childNodes as $propNode) { + if (self::toClarkNotation($propNode) !== '{DAV:}prop') { + continue; + } - if (Sabre_DAV_XMLUtil::toClarkNotation($propNode)!=='{DAV:}prop') continue; - - foreach($propNode->childNodes as $propNodeData) { + foreach ($propNode->childNodes as $propNodeData) { /* If there are no elements in here, we actually get 1 text node, this special case is dedicated to netdrive */ - if ($propNodeData->nodeType != XML_ELEMENT_NODE) continue; + if ($propNodeData->nodeType != XML_ELEMENT_NODE) { + continue; + } - $propertyName = Sabre_DAV_XMLUtil::toClarkNotation($propNodeData); + $propertyName = self::toClarkNotation($propNodeData); if (isset($propertyMap[$propertyName])) { - $propList[$propertyName] = call_user_func(array($propertyMap[$propertyName],'unserialize'),$propNodeData); + $propList[$propertyName] = call_user_func(array($propertyMap[$propertyName], 'unserialize'), $propNodeData); } else { $propList[$propertyName] = $propNodeData->textContent; } } - - } + return $propList; - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAV/includes.php b/dav/SabreDAV/lib/Sabre/DAV/includes.php index 07ecb16f..47312f1e 100644 --- a/dav/SabreDAV/lib/Sabre/DAV/includes.php +++ b/dav/SabreDAV/lib/Sabre/DAV/includes.php @@ -1,95 +1,93 @@ principalPrefix = $principalPrefix; $this->principalBackend = $principalBackend; - } /** @@ -65,56 +62,59 @@ abstract class Sabre_DAVACL_AbstractPrincipalCollection extends Sabre_DAV_Collec * supplied by the authentication backend. * * @param array $principalInfo + * * @return Sabre_DAVACL_IPrincipal */ - abstract function getChildForPrincipal(array $principalInfo); + abstract public function getChildForPrincipal(array $principalInfo); /** * Returns the name of this collection. * * @return string */ - public function getName() { + public function getName() + { + list(, $name) = Sabre_DAV_URLUtil::splitPath($this->principalPrefix); - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalPrefix); return $name; - } /** - * Return the list of users + * Return the list of users. * * @return array */ - public function getChildren() { - - if ($this->disableListing) + public function getChildren() + { + if ($this->disableListing) { throw new Sabre_DAV_Exception_MethodNotAllowed('Listing members of this collection is disabled'); + } $children = array(); - foreach($this->principalBackend->getPrincipalsByPrefix($this->principalPrefix) as $principalInfo) { - + foreach ($this->principalBackend->getPrincipalsByPrefix($this->principalPrefix) as $principalInfo) { $children[] = $this->getChildForPrincipal($principalInfo); - - } - return $children; + return $children; } /** * Returns a child object, by its name. * * @param string $name + * * @throws Sabre_DAV_Exception_NotFound + * * @return Sabre_DAVACL_IPrincipal */ - public function getChild($name) { + public function getChild($name) + { + $principalInfo = $this->principalBackend->getPrincipalByPath($this->principalPrefix.'/'.$name); + if (!$principalInfo) { + throw new Sabre_DAV_Exception_NotFound('Principal with name '.$name.' not found'); + } - $principalInfo = $this->principalBackend->getPrincipalByPath($this->principalPrefix . '/' . $name); - if (!$principalInfo) throw new Sabre_DAV_Exception_NotFound('Principal with name ' . $name . ' not found'); return $this->getChildForPrincipal($principalInfo); - } /** @@ -136,19 +136,18 @@ abstract class Sabre_DAVACL_AbstractPrincipalCollection extends Sabre_DAV_Collec * used to call $this->getChild in the future. * * @param array $searchProperties + * * @return array */ - public function searchPrincipals(array $searchProperties) { - + public function searchPrincipals(array $searchProperties) + { $result = $this->principalBackend->searchPrincipals($this->principalPrefix, $searchProperties); $r = array(); - foreach($result as $row) { + foreach ($result as $row) { list(, $r[]) = Sabre_DAV_URLUtil::splitPath($row); } return $r; - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Exception/AceConflict.php b/dav/SabreDAV/lib/Sabre/DAVACL/Exception/AceConflict.php index 4b9f93b0..37861d8e 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Exception/AceConflict.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Exception/AceConflict.php @@ -1,32 +1,27 @@ ownerDocument; - $np = $doc->createElementNS('DAV:','d:no-ace-conflict'); + $np = $doc->createElementNS('DAV:', 'd:no-ace-conflict'); $errorNode->appendChild($np); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NeedPrivileges.php b/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NeedPrivileges.php index 9b055dd9..d9871f05 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NeedPrivileges.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NeedPrivileges.php @@ -1,21 +1,19 @@ uri = $uri; $this->privileges = $privileges; - parent::__construct('User did not have the required privileges (' . implode(',', $privileges) . ') for path "' . $uri . '"'); - + parent::__construct('User did not have the required privileges ('.implode(',', $privileges).') for path "'.$uri.'"'); } /** @@ -49,33 +46,26 @@ class Sabre_DAVACL_Exception_NeedPrivileges extends Sabre_DAV_Exception_Forbidde * This method adds the {DAV:}need-privileges element as defined in rfc3744 * * @param Sabre_DAV_Server $server - * @param DOMElement $errorNode - * @return void + * @param DOMElement $errorNode */ - public function serialize(Sabre_DAV_Server $server,DOMElement $errorNode) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $errorNode) + { $doc = $errorNode->ownerDocument; - $np = $doc->createElementNS('DAV:','d:need-privileges'); + $np = $doc->createElementNS('DAV:', 'd:need-privileges'); $errorNode->appendChild($np); - foreach($this->privileges as $privilege) { - - $resource = $doc->createElementNS('DAV:','d:resource'); + foreach ($this->privileges as $privilege) { + $resource = $doc->createElementNS('DAV:', 'd:resource'); $np->appendChild($resource); - $resource->appendChild($doc->createElementNS('DAV:','d:href',$server->getBaseUri() . $this->uri)); + $resource->appendChild($doc->createElementNS('DAV:', 'd:href', $server->getBaseUri().$this->uri)); - $priv = $doc->createElementNS('DAV:','d:privilege'); + $priv = $doc->createElementNS('DAV:', 'd:privilege'); $resource->appendChild($priv); - preg_match('/^{([^}]*)}(.*)$/',$privilege,$privilegeParts); - $priv->appendChild($doc->createElementNS($privilegeParts[1],'d:' . $privilegeParts[2])); - - + preg_match('/^{([^}]*)}(.*)$/', $privilege, $privilegeParts); + $priv->appendChild($doc->createElementNS($privilegeParts[1], 'd:'.$privilegeParts[2])); } - } - } - diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NoAbstract.php b/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NoAbstract.php index f44e3e32..5a16e2b0 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NoAbstract.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NoAbstract.php @@ -1,32 +1,27 @@ ownerDocument; - $np = $doc->createElementNS('DAV:','d:no-abstract'); + $np = $doc->createElementNS('DAV:', 'd:no-abstract'); $errorNode->appendChild($np); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php b/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php index 8d1e38ca..a514a46b 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NotRecognizedPrincipal.php @@ -1,32 +1,27 @@ ownerDocument; - $np = $doc->createElementNS('DAV:','d:recognized-principal'); + $np = $doc->createElementNS('DAV:', 'd:recognized-principal'); $errorNode->appendChild($np); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NotSupportedPrivilege.php b/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NotSupportedPrivilege.php index 3b5d012d..9bacf295 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NotSupportedPrivilege.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Exception/NotSupportedPrivilege.php @@ -1,32 +1,27 @@ ownerDocument; - $np = $doc->createElementNS('DAV:','d:not-supported-privilege'); + $np = $doc->createElementNS('DAV:', 'd:not-supported-privilege'); $errorNode->appendChild($np); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/IACL.php b/dav/SabreDAV/lib/Sabre/DAVACL/IACL.php index 356bb481..7b09730e 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/IACL.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/IACL.php @@ -1,35 +1,33 @@ getCurrentUserPrivilegeSet($uri); @@ -194,31 +193,30 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { if ($this->allowAccessToNodesWithoutACL) { return true; } else { - if ($throwExceptions) - throw new Sabre_DAVACL_Exception_NeedPrivileges($uri,$privileges); - else + if ($throwExceptions) { + throw new Sabre_DAVACL_Exception_NeedPrivileges($uri, $privileges); + } else { return false; - + } } } $failed = array(); - foreach($privileges as $priv) { - + foreach ($privileges as $priv) { if (!in_array($priv, $acl)) { $failed[] = $priv; } - } if ($failed) { - if ($throwExceptions) - throw new Sabre_DAVACL_Exception_NeedPrivileges($uri,$failed); - else + if ($throwExceptions) { + throw new Sabre_DAVACL_Exception_NeedPrivileges($uri, $failed); + } else { return false; + } } - return true; + return true; } /** @@ -229,17 +227,19 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * * @return string|null */ - public function getCurrentUserPrincipal() { - + public function getCurrentUserPrincipal() + { $authPlugin = $this->server->getPlugin('auth'); - if (is_null($authPlugin)) return null; + if (is_null($authPlugin)) { + return null; + } /** @var $authPlugin Sabre_DAV_Auth_Plugin */ - $userName = $authPlugin->getCurrentUser(); - if (!$userName) return null; - - return $this->defaultUsernamePath . '/' . $userName; + if (!$userName) { + return null; + } + return $this->defaultUsernamePath.'/'.$userName; } /** @@ -248,38 +248,32 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * * @return array */ - public function getCurrentUserPrincipals() { - + public function getCurrentUserPrincipals() + { $currentUser = $this->getCurrentUserPrincipal(); - if (is_null($currentUser)) return array(); + if (is_null($currentUser)) { + return array(); + } $check = array($currentUser); $principals = array($currentUser); - while(count($check)) { - + while (count($check)) { $principal = array_shift($check); $node = $this->server->tree->getNodeForPath($principal); if ($node instanceof Sabre_DAVACL_IPrincipal) { - foreach($node->getGroupMembership() as $groupMember) { - + foreach ($node->getGroupMembership() as $groupMember) { if (!in_array($groupMember, $principals)) { - $check[] = $groupMember; $principals[] = $groupMember; - } - } - } - } return $principals; - } /** @@ -292,10 +286,11 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * specifying a Node. * * @param string|Sabre_DAV_INode $node + * * @return array */ - public function getSupportedPrivilegeSet($node) { - + public function getSupportedPrivilegeSet($node) + { if (is_string($node)) { $node = $this->server->tree->getNodeForPath($node); } @@ -303,12 +298,12 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { if ($node instanceof Sabre_DAVACL_IACL) { $result = $node->getSupportedPrivilegeSet(); - if ($result) + if ($result) { return $result; + } } return self::getDefaultSupportedPrivilegeSet(); - } /** @@ -317,61 +312,60 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * * @return array */ - static function getDefaultSupportedPrivilegeSet() { - + public static function getDefaultSupportedPrivilegeSet() + { return array( - 'privilege' => '{DAV:}all', - 'abstract' => true, + 'privilege' => '{DAV:}all', + 'abstract' => true, 'aggregates' => array( array( - 'privilege' => '{DAV:}read', + 'privilege' => '{DAV:}read', 'aggregates' => array( array( 'privilege' => '{DAV:}read-acl', - 'abstract' => true, + 'abstract' => true, ), array( 'privilege' => '{DAV:}read-current-user-privilege-set', - 'abstract' => true, + 'abstract' => true, ), ), ), // {DAV:}read array( - 'privilege' => '{DAV:}write', + 'privilege' => '{DAV:}write', 'aggregates' => array( array( 'privilege' => '{DAV:}write-acl', - 'abstract' => true, + 'abstract' => true, ), array( 'privilege' => '{DAV:}write-properties', - 'abstract' => true, + 'abstract' => true, ), array( 'privilege' => '{DAV:}write-content', - 'abstract' => true, + 'abstract' => true, ), array( 'privilege' => '{DAV:}bind', - 'abstract' => true, + 'abstract' => true, ), array( 'privilege' => '{DAV:}unbind', - 'abstract' => true, + 'abstract' => true, ), array( 'privilege' => '{DAV:}unlock', - 'abstract' => true, + 'abstract' => true, ), ), ), // {DAV:}write ), ); // {DAV:}all - } /** - * Returns the supported privilege set as a flat list + * Returns the supported privilege set as a flat list. * * This is much easier to parse. * @@ -382,21 +376,21 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * - concrete * * @param string|Sabre_DAV_INode $node + * * @return array */ - final public function getFlatPrivilegeSet($node) { - + final public function getFlatPrivilegeSet($node) + { $privs = $this->getSupportedPrivilegeSet($node); $flat = array(); $this->getFPSTraverse($privs, null, $flat); return $flat; - } /** - * Traverses the privilege set tree for reordering + * Traverses the privilege set tree for reordering. * * This function is solely used by getFlatPrivilegeSet, and would have been * a closure if it wasn't for the fact I need to support PHP 5.2. @@ -404,32 +398,29 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * @param array $priv * @param $concrete * @param array $flat - * @return void */ - final private function getFPSTraverse($priv, $concrete, &$flat) { - + final private function getFPSTraverse($priv, $concrete, &$flat) + { $myPriv = array( 'privilege' => $priv['privilege'], 'abstract' => isset($priv['abstract']) && $priv['abstract'], 'aggregates' => array(), - 'concrete' => isset($priv['abstract']) && $priv['abstract']?$concrete:$priv['privilege'], + 'concrete' => isset($priv['abstract']) && $priv['abstract'] ? $concrete : $priv['privilege'], ); - if (isset($priv['aggregates'])) - foreach($priv['aggregates'] as $subPriv) $myPriv['aggregates'][] = $subPriv['privilege']; + if (isset($priv['aggregates'])) { + foreach ($priv['aggregates'] as $subPriv) { + $myPriv['aggregates'][] = $subPriv['privilege']; + } + } $flat[$priv['privilege']] = $myPriv; if (isset($priv['aggregates'])) { - - foreach($priv['aggregates'] as $subPriv) { - + foreach ($priv['aggregates'] as $subPriv) { $this->getFPSTraverse($subPriv, $myPriv['concrete'], $flat); - } - } - } /** @@ -440,10 +431,11 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * null will be returned if the node doesn't support ACLs. * * @param string|Sabre_DAV_INode $node + * * @return array */ - public function getACL($node) { - + public function getACL($node) + { if (is_string($node)) { $node = $this->server->tree->getNodeForPath($node); } @@ -451,15 +443,15 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { return null; } $acl = $node->getACL(); - foreach($this->adminPrincipals as $adminPrincipal) { + foreach ($this->adminPrincipals as $adminPrincipal) { $acl[] = array( 'principal' => $adminPrincipal, 'privilege' => '{DAV:}all', 'protected' => true, ); } - return $acl; + return $acl; } /** @@ -471,107 +463,102 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * null will be returned if the node doesn't support ACLs. * * @param string|Sabre_DAV_INode $node + * * @return array */ - public function getCurrentUserPrivilegeSet($node) { - + public function getCurrentUserPrivilegeSet($node) + { if (is_string($node)) { $node = $this->server->tree->getNodeForPath($node); } $acl = $this->getACL($node); - if (is_null($acl)) return null; + if (is_null($acl)) { + return null; + } $principals = $this->getCurrentUserPrincipals(); $collected = array(); - foreach($acl as $ace) { - + foreach ($acl as $ace) { $principal = $ace['principal']; - switch($principal) { + switch ($principal) { - case '{DAV:}owner' : + case '{DAV:}owner': $owner = $node->getOwner(); if ($owner && in_array($owner, $principals)) { $collected[] = $ace; } break; - // 'all' matches for every user - case '{DAV:}all' : + case '{DAV:}all': // 'authenticated' matched for every user that's logged in. // Since it's not possible to use ACL while not being logged // in, this is also always true. - case '{DAV:}authenticated' : + case '{DAV:}authenticated': $collected[] = $ace; break; // 'unauthenticated' can never occur either, so we simply // ignore these. - case '{DAV:}unauthenticated' : + case '{DAV:}unauthenticated': break; - default : + default: if (in_array($ace['principal'], $principals)) { $collected[] = $ace; } break; } - - - } // Now we deduct all aggregated privileges. $flat = $this->getFlatPrivilegeSet($node); $collected2 = array(); - while(count($collected)) { - + while (count($collected)) { $current = array_pop($collected); $collected2[] = $current['privilege']; - foreach($flat[$current['privilege']]['aggregates'] as $subPriv) { + foreach ($flat[$current['privilege']]['aggregates'] as $subPriv) { $collected2[] = $subPriv; $collected[] = $flat[$subPriv]; } - } return array_values(array_unique($collected2)); - } /** - * Principal property search + * Principal property search. * * This method can search for principals matching certain values in * properties. * * This method will return a list of properties for the matched properties. * - * @param array $searchProperties The properties to search on. This is a - * key-value list. The keys are property - * names, and the values the strings to - * match them on. - * @param array $requestedProperties This is the list of properties to - * return for every match. - * @param string $collectionUri The principal collection to search on. - * If this is ommitted, the standard - * principal collection-set will be used. - * @return array This method returns an array structure similar to - * Sabre_DAV_Server::getPropertiesForPath. Returned - * properties are index by a HTTP status code. + * @param array $searchProperties The properties to search on. This is a + * key-value list. The keys are property + * names, and the values the strings to + * match them on + * @param array $requestedProperties This is the list of properties to + * return for every match + * @param string $collectionUri The principal collection to search on. + * If this is ommitted, the standard + * principal collection-set will be used * + * @return array This method returns an array structure similar to + * Sabre_DAV_Server::getPropertiesForPath. Returned + * properties are index by a HTTP status code */ - public function principalSearch(array $searchProperties, array $requestedProperties, $collectionUri = null) { - + public function principalSearch(array $searchProperties, array $requestedProperties, $collectionUri = null) + { if (!is_null($collectionUri)) { $uris = array($collectionUri); } else { @@ -579,8 +566,7 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { } $lookupResults = array(); - foreach($uris as $uri) { - + foreach ($uris as $uri) { $principalCollection = $this->server->tree->getNodeForPath($uri); if (!$principalCollection instanceof Sabre_DAVACL_AbstractPrincipalCollection) { // Not a principal collection, we're simply going to ignore @@ -589,43 +575,38 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { } $results = $principalCollection->searchPrincipals($searchProperties); - foreach($results as $result) { - $lookupResults[] = rtrim($uri,'/') . '/' . $result; + foreach ($results as $result) { + $lookupResults[] = rtrim($uri, '/').'/'.$result; } - } $matches = array(); - foreach($lookupResults as $lookupResult) { - + foreach ($lookupResults as $lookupResult) { list($matches[]) = $this->server->getPropertiesForPath($lookupResult, $requestedProperties, 0); - } return $matches; - } /** - * Sets up the plugin + * Sets up the plugin. * * This method is automatically called by the server class. * * @param Sabre_DAV_Server $server - * @return void */ - public function initialize(Sabre_DAV_Server $server) { - + public function initialize(Sabre_DAV_Server $server) + { $this->server = $server; - $server->subscribeEvent('beforeGetProperties',array($this,'beforeGetProperties')); + $server->subscribeEvent('beforeGetProperties', array($this, 'beforeGetProperties')); - $server->subscribeEvent('beforeMethod', array($this,'beforeMethod'),20); - $server->subscribeEvent('beforeBind', array($this,'beforeBind'),20); - $server->subscribeEvent('beforeUnbind', array($this,'beforeUnbind'),20); - $server->subscribeEvent('updateProperties',array($this,'updateProperties')); - $server->subscribeEvent('beforeUnlock', array($this,'beforeUnlock'),20); - $server->subscribeEvent('report',array($this,'report')); + $server->subscribeEvent('beforeMethod', array($this, 'beforeMethod'), 20); + $server->subscribeEvent('beforeBind', array($this, 'beforeBind'), 20); + $server->subscribeEvent('beforeUnbind', array($this, 'beforeUnbind'), 20); + $server->subscribeEvent('updateProperties', array($this, 'updateProperties')); + $server->subscribeEvent('beforeUnlock', array($this, 'beforeUnlock'), 20); + $server->subscribeEvent('report', array($this, 'report')); $server->subscribeEvent('unknownMethod', array($this, 'unknownMethod')); array_push($server->protectedProperties, @@ -650,73 +631,70 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { // Mapping the group-member-set property to the HrefList property // class. $server->propertyMap['{DAV:}group-member-set'] = 'Sabre_DAV_Property_HrefList'; - } - /* {{{ Event handlers */ /** - * Triggered before any method is handled + * Triggered before any method is handled. * * @param string $method * @param string $uri - * @return void */ - public function beforeMethod($method, $uri) { - + public function beforeMethod($method, $uri) + { $exists = $this->server->tree->nodeExists($uri); // If the node doesn't exists, none of these checks apply - if (!$exists) return; + if (!$exists) { + return; + } - switch($method) { + switch ($method) { - case 'GET' : - case 'HEAD' : - case 'OPTIONS' : + case 'GET': + case 'HEAD': + case 'OPTIONS': // For these 3 we only need to know if the node is readable. - $this->checkPrivileges($uri,'{DAV:}read'); + $this->checkPrivileges($uri, '{DAV:}read'); break; - case 'PUT' : - case 'LOCK' : - case 'UNLOCK' : + case 'PUT': + case 'LOCK': + case 'UNLOCK': // This method requires the write-content priv if the node // already exists, and bind on the parent if the node is being // created. // The bind privilege is handled in the beforeBind event. - $this->checkPrivileges($uri,'{DAV:}write-content'); + $this->checkPrivileges($uri, '{DAV:}write-content'); break; - - case 'PROPPATCH' : - $this->checkPrivileges($uri,'{DAV:}write-properties'); + case 'PROPPATCH': + $this->checkPrivileges($uri, '{DAV:}write-properties'); break; - case 'ACL' : - $this->checkPrivileges($uri,'{DAV:}write-acl'); + case 'ACL': + $this->checkPrivileges($uri, '{DAV:}write-acl'); break; - case 'COPY' : - case 'MOVE' : + case 'COPY': + case 'MOVE': // Copy requires read privileges on the entire source tree. // If the target exists write-content normally needs to be // checked, however, we're deleting the node beforehand and // creating a new one after, so this is handled by the // beforeUnbind event. - // + // The creation of the new node is handled by the beforeBind // event. - // + // If MOVE is used beforeUnbind will also be used to check if // the sourcenode can be deleted. - $this->checkPrivileges($uri,'{DAV:}read',self::R_RECURSIVE); + $this->checkPrivileges($uri, '{DAV:}read', self::R_RECURSIVE); break; } - } /** @@ -726,58 +704,54 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * new node, such as PUT, MKCOL, MKCALENDAR, LOCK, COPY and MOVE. * * @param string $uri - * @return void */ - public function beforeBind($uri) { - - list($parentUri,$nodeName) = Sabre_DAV_URLUtil::splitPath($uri); - $this->checkPrivileges($parentUri,'{DAV:}bind'); - + public function beforeBind($uri) + { + list($parentUri, $nodeName) = Sabre_DAV_URLUtil::splitPath($uri); + $this->checkPrivileges($parentUri, '{DAV:}bind'); } /** - * Triggered before a node is deleted + * Triggered before a node is deleted. * * This allows us to check permissions for any operation that will delete * an existing node. * * @param string $uri - * @return void */ - public function beforeUnbind($uri) { - - list($parentUri,$nodeName) = Sabre_DAV_URLUtil::splitPath($uri); - $this->checkPrivileges($parentUri,'{DAV:}unbind',self::R_RECURSIVEPARENTS); - + public function beforeUnbind($uri) + { + list($parentUri, $nodeName) = Sabre_DAV_URLUtil::splitPath($uri); + $this->checkPrivileges($parentUri, '{DAV:}unbind', self::R_RECURSIVEPARENTS); } /** * Triggered before a node is unlocked. * - * @param string $uri + * @param string $uri * @param Sabre_DAV_Locks_LockInfo $lock * @TODO: not yet implemented - * @return void */ - public function beforeUnlock($uri, Sabre_DAV_Locks_LockInfo $lock) { - - + public function beforeUnlock($uri, Sabre_DAV_Locks_LockInfo $lock) + { } /** * Triggered before properties are looked up in specific nodes. * - * @param string $uri + * @param string $uri * @param Sabre_DAV_INode $node - * @param array $requestedProperties - * @param array $returnedProperties + * @param array $requestedProperties + * @param array $returnedProperties * @TODO really should be broken into multiple methods, or even a class. + * * @return bool */ - public function beforeGetProperties($uri, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) { + public function beforeGetProperties($uri, Sabre_DAV_INode $node, &$requestedProperties, &$returnedProperties) + { // Checking the read permission - if (!$this->checkPrivileges($uri,'{DAV:}read',self::R_PARENT,false)) { + if (!$this->checkPrivileges($uri, '{DAV:}read', self::R_PARENT, false)) { // User is not allowed to read properties if ($this->hideNodesFromListings) { @@ -785,76 +759,59 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { } // Marking all requested properties as '403'. - foreach($requestedProperties as $key=>$requestedProperty) { + foreach ($requestedProperties as $key => $requestedProperty) { unset($requestedProperties[$key]); $returnedProperties[403][$requestedProperty] = null; } - return; + return; } /* Adding principal properties */ if ($node instanceof Sabre_DAVACL_IPrincipal) { - if (false !== ($index = array_search('{DAV:}alternate-URI-set', $requestedProperties))) { - unset($requestedProperties[$index]); $returnedProperties[200]['{DAV:}alternate-URI-set'] = new Sabre_DAV_Property_HrefList($node->getAlternateUriSet()); - } if (false !== ($index = array_search('{DAV:}principal-URL', $requestedProperties))) { - unset($requestedProperties[$index]); - $returnedProperties[200]['{DAV:}principal-URL'] = new Sabre_DAV_Property_Href($node->getPrincipalUrl() . '/'); - + $returnedProperties[200]['{DAV:}principal-URL'] = new Sabre_DAV_Property_Href($node->getPrincipalUrl().'/'); } if (false !== ($index = array_search('{DAV:}group-member-set', $requestedProperties))) { - unset($requestedProperties[$index]); $returnedProperties[200]['{DAV:}group-member-set'] = new Sabre_DAV_Property_HrefList($node->getGroupMemberSet()); - } if (false !== ($index = array_search('{DAV:}group-membership', $requestedProperties))) { - unset($requestedProperties[$index]); $returnedProperties[200]['{DAV:}group-membership'] = new Sabre_DAV_Property_HrefList($node->getGroupMembership()); - } if (false !== ($index = array_search('{DAV:}displayname', $requestedProperties))) { - $returnedProperties[200]['{DAV:}displayname'] = $node->getDisplayName(); - } - } if (false !== ($index = array_search('{DAV:}principal-collection-set', $requestedProperties))) { - unset($requestedProperties[$index]); $val = $this->principalCollectionSet; // Ensuring all collections end with a slash - foreach($val as $k=>$v) $val[$k] = $v . '/'; + foreach ($val as $k => $v) { + $val[$k] = $v.'/'; + } $returnedProperties[200]['{DAV:}principal-collection-set'] = new Sabre_DAV_Property_HrefList($val); - } if (false !== ($index = array_search('{DAV:}current-user-principal', $requestedProperties))) { - unset($requestedProperties[$index]); if ($url = $this->getCurrentUserPrincipal()) { - $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF, $url . '/'); + $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF, $url.'/'); } else { $returnedProperties[200]['{DAV:}current-user-principal'] = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::UNAUTHENTICATED); } - } if (false !== ($index = array_search('{DAV:}supported-privilege-set', $requestedProperties))) { - unset($requestedProperties[$index]); $returnedProperties[200]['{DAV:}supported-privilege-set'] = new Sabre_DAVACL_Property_SupportedPrivilegeSet($this->getSupportedPrivilegeSet($node)); - } if (false !== ($index = array_search('{DAV:}current-user-privilege-set', $requestedProperties))) { - if (!$this->checkPrivileges($uri, '{DAV:}read-current-user-privilege-set', self::R_PARENT, false)) { $returnedProperties[403]['{DAV:}current-user-privilege-set'] = null; unset($requestedProperties[$index]); @@ -865,27 +822,20 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { $returnedProperties[200]['{DAV:}current-user-privilege-set'] = new Sabre_DAVACL_Property_CurrentUserPrivilegeSet($val); } } - } /* The ACL property contains all the permissions */ if (false !== ($index = array_search('{DAV:}acl', $requestedProperties))) { - if (!$this->checkPrivileges($uri, '{DAV:}read-acl', self::R_PARENT, false)) { - unset($requestedProperties[$index]); $returnedProperties[403]['{DAV:}acl'] = null; - } else { - $acl = $this->getACL($node); if (!is_null($acl)) { unset($requestedProperties[$index]); $returnedProperties[200]['{DAV:}acl'] = new Sabre_DAVACL_Property_Acl($this->getACL($node)); } - } - } /* The acl-restrictions property contains information on how privileges @@ -895,22 +845,23 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { unset($requestedProperties[$index]); $returnedProperties[200]['{DAV:}acl-restrictions'] = new Sabre_DAVACL_Property_AclRestrictions(); } - } /** * This method intercepts PROPPATCH methods and make sure the * group-member-set is updated correctly. * - * @param array $propertyDelta - * @param array $result + * @param array $propertyDelta + * @param array $result * @param Sabre_DAV_INode $node + * * @return bool */ - public function updateProperties(&$propertyDelta, &$result, Sabre_DAV_INode $node) { - - if (!array_key_exists('{DAV:}group-member-set', $propertyDelta)) + public function updateProperties(&$propertyDelta, &$result, Sabre_DAV_INode $node) + { + if (!array_key_exists('{DAV:}group-member-set', $propertyDelta)) { return; + } if (is_null($propertyDelta['{DAV:}group-member-set'])) { $memberSet = array(); @@ -932,32 +883,34 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { $result[200]['{DAV:}group-member-set'] = null; unset($propertyDelta['{DAV:}group-member-set']); - } /** - * This method handles HTTP REPORT requests + * This method handles HTTP REPORT requests. * - * @param string $reportName + * @param string $reportName * @param DOMNode $dom + * * @return bool */ - public function report($reportName, $dom) { + public function report($reportName, $dom) + { + switch ($reportName) { - switch($reportName) { - - case '{DAV:}principal-property-search' : + case '{DAV:}principal-property-search': $this->principalPropertySearchReport($dom); + return false; - case '{DAV:}principal-search-property-set' : + case '{DAV:}principal-search-property-set': $this->principalSearchPropertySetReport($dom); + return false; - case '{DAV:}expand-property' : + case '{DAV:}expand-property': $this->expandPropertyReport($dom); + return false; } - } /** @@ -966,25 +919,27 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * * @param string $method * @param string $uri + * * @return bool */ - public function unknownMethod($method, $uri) { - - if ($method!=='ACL') return; + public function unknownMethod($method, $uri) + { + if ($method !== 'ACL') { + return; + } $this->httpACL($uri); - return false; + return false; } /** * This method is responsible for handling the 'ACL' event. * * @param string $uri - * @return void */ - public function httpACL($uri) { - + public function httpACL($uri) + { $body = $this->server->httpRequest->getBody(true); $dom = Sabre_DAV_XMLUtil::loadDOMDocument($body); @@ -993,7 +948,7 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { ->getPrivileges(); // Normalizing urls - foreach($newAcl as $k=>$newAce) { + foreach ($newAcl as $k => $newAce) { $newAcl[$k]['principal'] = $this->server->calculateUri($newAce['principal']); } @@ -1009,49 +964,49 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { /* Checking if protected principals from the existing principal set are not overwritten. */ - foreach($oldAcl as $oldAce) { - - if (!isset($oldAce['protected']) || !$oldAce['protected']) continue; + foreach ($oldAcl as $oldAce) { + if (!isset($oldAce['protected']) || !$oldAce['protected']) { + continue; + } $found = false; - foreach($newAcl as $newAce) { + foreach ($newAcl as $newAce) { if ( $newAce['privilege'] === $oldAce['privilege'] && $newAce['principal'] === $oldAce['principal'] && $newAce['protected'] - ) - $found = true; + ) { + $found = true; + } } - if (!$found) + if (!$found) { throw new Sabre_DAVACL_Exception_AceConflict('This resource contained a protected {DAV:}ace, but this privilege did not occur in the ACL request'); - + } } - foreach($newAcl as $newAce) { + foreach ($newAcl as $newAce) { // Do we recognize the privilege if (!isset($supportedPrivileges[$newAce['privilege']])) { - throw new Sabre_DAVACL_Exception_NotSupportedPrivilege('The privilege you specified (' . $newAce['privilege'] . ') is not recognized by this server'); + throw new Sabre_DAVACL_Exception_NotSupportedPrivilege('The privilege you specified ('.$newAce['privilege'].') is not recognized by this server'); } if ($supportedPrivileges[$newAce['privilege']]['abstract']) { - throw new Sabre_DAVACL_Exception_NoAbstract('The privilege you specified (' . $newAce['privilege'] . ') is an abstract privilege'); + throw new Sabre_DAVACL_Exception_NoAbstract('The privilege you specified ('.$newAce['privilege'].') is an abstract privilege'); } // Looking up the principal try { $principal = $this->server->tree->getNodeForPath($newAce['principal']); } catch (Sabre_DAV_Exception_NotFound $e) { - throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified principal (' . $newAce['principal'] . ') does not exist'); + throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified principal ('.$newAce['principal'].') does not exist'); } if (!($principal instanceof Sabre_DAVACL_IPrincipal)) { - throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified uri (' . $newAce['principal'] . ') is not a principal'); + throw new Sabre_DAVACL_Exception_NotRecognizedPrincipal('The specified uri ('.$newAce['principal'].') is not a principal'); } - } $node->setACL($newAcl); - } /* }}} */ @@ -1070,37 +1025,33 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * it in this plugin. * * @param DOMElement $dom - * @return void */ - protected function expandPropertyReport($dom) { - + protected function expandPropertyReport($dom) + { $requestedProperties = $this->parseExpandPropertyReportRequest($dom->firstChild->firstChild); $depth = $this->server->getHTTPDepth(0); $requestUri = $this->server->getRequestUri(); - $result = $this->expandProperties($requestUri,$requestedProperties,$depth); + $result = $this->expandProperties($requestUri, $requestedProperties, $depth); - $dom = new DOMDocument('1.0','utf-8'); + $dom = new DOMDocument('1.0', 'utf-8'); $dom->formatOutput = true; $multiStatus = $dom->createElement('d:multistatus'); $dom->appendChild($multiStatus); // Adding in default namespaces - foreach($this->server->xmlNamespaces as $namespace=>$prefix) { - - $multiStatus->setAttribute('xmlns:' . $prefix,$namespace); - + foreach ($this->server->xmlNamespaces as $namespace => $prefix) { + $multiStatus->setAttribute('xmlns:'.$prefix, $namespace); } - foreach($result as $response) { + foreach ($result as $response) { $response->serialize($this->server, $multiStatus); } $xml = $dom->saveXML(); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->sendStatus(207); $this->server->httpResponse->sendBody($xml); - } /** @@ -1108,62 +1059,64 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * out the entire HTTP request. * * @param DOMElement $node + * * @return array */ - protected function parseExpandPropertyReportRequest($node) { - + protected function parseExpandPropertyReportRequest($node) + { $requestedProperties = array(); do { - - if (Sabre_DAV_XMLUtil::toClarkNotation($node)!=='{DAV:}property') continue; + if (Sabre_DAV_XMLUtil::toClarkNotation($node) !== '{DAV:}property') { + continue; + } if ($node->firstChild) { - $children = $this->parseExpandPropertyReportRequest($node->firstChild); - } else { - $children = array(); - } $namespace = $node->getAttribute('namespace'); - if (!$namespace) $namespace = 'DAV:'; + if (!$namespace) { + $namespace = 'DAV:'; + } - $propName = '{'.$namespace.'}' . $node->getAttribute('name'); + $propName = '{'.$namespace.'}'.$node->getAttribute('name'); $requestedProperties[$propName] = $children; - } while ($node = $node->nextSibling); return $requestedProperties; - } /** * This method expands all the properties and returns - * a list with property values + * a list with property values. * * @param array $path * @param array $requestedProperties the list of required properties - * @param int $depth + * @param int $depth + * * @return array */ - protected function expandProperties($path, array $requestedProperties, $depth) { - + protected function expandProperties($path, array $requestedProperties, $depth) + { $foundProperties = $this->server->getPropertiesForPath($path, array_keys($requestedProperties), $depth); $result = array(); - foreach($foundProperties as $node) { - - foreach($requestedProperties as $propertyName=>$childRequestedProperties) { + foreach ($foundProperties as $node) { + foreach ($requestedProperties as $propertyName => $childRequestedProperties) { // We're only traversing if sub-properties were requested - if(count($childRequestedProperties)===0) continue; + if (count($childRequestedProperties) === 0) { + continue; + } // We only have to do the expansion if the property was found // and it contains an href element. - if (!array_key_exists($propertyName,$node[200])) continue; + if (!array_key_exists($propertyName, $node[200])) { + continue; + } if ($node[200][$propertyName] instanceof Sabre_DAV_Property_IHref) { $hrefs = array($node[200][$propertyName]->getHref()); @@ -1172,22 +1125,19 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { } $childProps = array(); - foreach($hrefs as $href) { + foreach ($hrefs as $href) { $childProps = array_merge($childProps, $this->expandProperties($href, $childRequestedProperties, 0)); } $node[200][$propertyName] = new Sabre_DAV_Property_ResponseList($childProps); - } $result[] = new Sabre_DAV_Property_Response($path, $node); - } return $result; - } /** - * principalSearchPropertySetReport + * principalSearchPropertySetReport. * * This method responsible for handing the * {DAV:}principal-search-property-set report. This report returns a list @@ -1195,33 +1145,30 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * {DAV:}principal-property-search report. * * @param DOMDocument $dom - * @return void */ - protected function principalSearchPropertySetReport(DOMDocument $dom) { - + protected function principalSearchPropertySetReport(DOMDocument $dom) + { $httpDepth = $this->server->getHTTPDepth(0); - if ($httpDepth!==0) { + if ($httpDepth !== 0) { throw new Sabre_DAV_Exception_BadRequest('This report is only defined when Depth: 0'); } - if ($dom->firstChild->hasChildNodes()) + if ($dom->firstChild->hasChildNodes()) { throw new Sabre_DAV_Exception_BadRequest('The principal-search-property-set report element is not allowed to have child elements'); + } - $dom = new DOMDocument('1.0','utf-8'); + $dom = new DOMDocument('1.0', 'utf-8'); $dom->formatOutput = true; $root = $dom->createElement('d:principal-search-property-set'); $dom->appendChild($root); // Adding in default namespaces - foreach($this->server->xmlNamespaces as $namespace=>$prefix) { - - $root->setAttribute('xmlns:' . $prefix,$namespace); - + foreach ($this->server->xmlNamespaces as $namespace => $prefix) { + $root->setAttribute('xmlns:'.$prefix, $namespace); } $nsList = $this->server->xmlNamespaces; - foreach($this->principalSearchPropertySet as $propertyName=>$description) { - + foreach ($this->principalSearchPropertySet as $propertyName => $description) { $psp = $dom->createElement('d:principal-search-property'); $root->appendChild($psp); @@ -1229,27 +1176,24 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { $psp->appendChild($prop); $propName = null; - preg_match('/^{([^}]*)}(.*)$/',$propertyName,$propName); + preg_match('/^{([^}]*)}(.*)$/', $propertyName, $propName); - $currentProperty = $dom->createElement($nsList[$propName[1]] . ':' . $propName[2]); + $currentProperty = $dom->createElement($nsList[$propName[1]].':'.$propName[2]); $prop->appendChild($currentProperty); $descriptionElem = $dom->createElement('d:description'); - $descriptionElem->setAttribute('xml:lang','en'); + $descriptionElem->setAttribute('xml:lang', 'en'); $descriptionElem->appendChild($dom->createTextNode($description)); $psp->appendChild($descriptionElem); - - } - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->sendStatus(200); $this->server->httpResponse->sendBody($dom->saveXML()); - } /** - * principalPropertySearchReport + * principalPropertySearchReport. * * This method is responsible for handing the * {DAV:}principal-property-search report. This report can be used for @@ -1257,10 +1201,9 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * or more properties. * * @param DOMDocument $dom - * @return void */ - protected function principalPropertySearchReport(DOMDocument $dom) { - + protected function principalPropertySearchReport(DOMDocument $dom) + { list($searchProperties, $requestedProperties, $applyToPrincipalCollectionSet) = $this->parsePrincipalPropertySearchReportRequest($dom); $uri = null; @@ -1270,14 +1213,13 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { $result = $this->principalSearch($searchProperties, $requestedProperties, $uri); $xml = $this->server->generateMultiStatus($result); - $this->server->httpResponse->setHeader('Content-Type','application/xml; charset=utf-8'); + $this->server->httpResponse->setHeader('Content-Type', 'application/xml; charset=utf-8'); $this->server->httpResponse->sendStatus(207); $this->server->httpResponse->sendBody($xml); - } /** - * parsePrincipalPropertySearchReportRequest + * parsePrincipalPropertySearchReportRequest. * * This method parses the request body from a * {DAV:}principal-property-search report. @@ -1287,12 +1229,13 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { * 2. a list of propertyvalues that should be returned for the request. * * @param DOMDocument $dom + * * @return array */ - protected function parsePrincipalPropertySearchReportRequest($dom) { - + protected function parsePrincipalPropertySearchReportRequest($dom) + { $httpDepth = $this->server->getHTTPDepth(0); - if ($httpDepth!==0) { + if ($httpDepth !== 0) { throw new Sabre_DAV_Exception_BadRequest('This report is only defined when Depth: 0'); } @@ -1301,49 +1244,43 @@ class Sabre_DAVACL_Plugin extends Sabre_DAV_ServerPlugin { $applyToPrincipalCollectionSet = false; // Parsing the search request - foreach($dom->firstChild->childNodes as $searchNode) { - + foreach ($dom->firstChild->childNodes as $searchNode) { if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode) == '{DAV:}apply-to-principal-collection-set') { $applyToPrincipalCollectionSet = true; } - if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode)!=='{DAV:}property-search') + if (Sabre_DAV_XMLUtil::toClarkNotation($searchNode) !== '{DAV:}property-search') { continue; + } $propertyName = null; $propertyValue = null; - foreach($searchNode->childNodes as $childNode) { + foreach ($searchNode->childNodes as $childNode) { + switch (Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { - switch(Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { - - case '{DAV:}prop' : + case '{DAV:}prop': $property = Sabre_DAV_XMLUtil::parseProperties($searchNode); reset($property); $propertyName = key($property); break; - case '{DAV:}match' : + case '{DAV:}match': $propertyValue = $childNode->textContent; break; } - - } - if (is_null($propertyName) || is_null($propertyValue)) - throw new Sabre_DAV_Exception_BadRequest('Invalid search request. propertyname: ' . $propertyName . '. propertvvalue: ' . $propertyValue); + if (is_null($propertyName) || is_null($propertyValue)) { + throw new Sabre_DAV_Exception_BadRequest('Invalid search request. propertyname: '.$propertyName.'. propertvvalue: '.$propertyValue); + } $searchProperties[$propertyName] = $propertyValue; - } return array($searchProperties, array_keys(Sabre_DAV_XMLUtil::parseProperties($dom->firstChild)), $applyToPrincipalCollectionSet); - } - /* }}} */ - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Principal.php b/dav/SabreDAV/lib/Sabre/DAVACL/Principal.php index 51c6658a..ef94bc0a 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Principal.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Principal.php @@ -1,7 +1,7 @@ principalBackend = $principalBackend; $this->principalProperties = $principalProperties; - } /** - * Returns the full principal url + * Returns the full principal url. * * @return string */ - public function getPrincipalUrl() { - + public function getPrincipalUrl() + { return $this->principalProperties['uri']; - } /** - * Returns a list of alternative urls for a principal + * Returns a list of alternative urls for a principal. * * This can for example be an email address, or ldap url. * * @return array */ - public function getAlternateUriSet() { - + public function getAlternateUriSet() + { $uris = array(); if (isset($this->principalProperties['{DAV:}alternate-URI-set'])) { - $uris = $this->principalProperties['{DAV:}alternate-URI-set']; - } if (isset($this->principalProperties['{http://sabredav.org/ns}email-address'])) { - $uris[] = 'mailto:' . $this->principalProperties['{http://sabredav.org/ns}email-address']; + $uris[] = 'mailto:'.$this->principalProperties['{http://sabredav.org/ns}email-address']; } return array_unique($uris); - } /** - * Returns the list of group members + * Returns the list of group members. * * If this principal is a group, this function should return * all member principal uri's for the group. * * @return array */ - public function getGroupMemberSet() { - + public function getGroupMemberSet() + { return $this->principalBackend->getGroupMemberSet($this->principalProperties['uri']); - } /** - * Returns the list of groups this principal is member of + * Returns the list of groups this principal is member of. * * If this principal is a member of a (list of) groups, this function * should return a list of principal uri's for it's members. * * @return array */ - public function getGroupMembership() { - + public function getGroupMembership() + { return $this->principalBackend->getGroupMemberShip($this->principalProperties['uri']); - } - /** - * Sets a list of group members + * Sets a list of group members. * * If this principal is a group, this method sets all the group members. * The list of members is always overwritten, never appended to. @@ -122,102 +112,94 @@ class Sabre_DAVACL_Principal extends Sabre_DAV_Node implements Sabre_DAVACL_IPri * This method should throw an exception if the members could not be set. * * @param array $groupMembers - * @return void */ - public function setGroupMemberSet(array $groupMembers) { - + public function setGroupMemberSet(array $groupMembers) + { $this->principalBackend->setGroupMemberSet($this->principalProperties['uri'], $groupMembers); - } - /** * Returns this principals name. * * @return string */ - public function getName() { - + public function getName() + { $uri = $this->principalProperties['uri']; list(, $name) = Sabre_DAV_URLUtil::splitPath($uri); - return $name; + return $name; } /** - * Returns the name of the user + * Returns the name of the user. * * @return string */ - public function getDisplayName() { - + public function getDisplayName() + { if (isset($this->principalProperties['{DAV:}displayname'])) { return $this->principalProperties['{DAV:}displayname']; } else { return $this->getName(); } - } /** - * Returns a list of properties + * Returns a list of properties. * * @param array $requestedProperties + * * @return array */ - public function getProperties($requestedProperties) { - + public function getProperties($requestedProperties) + { $newProperties = array(); - foreach($requestedProperties as $propName) { - + foreach ($requestedProperties as $propName) { if (isset($this->principalProperties[$propName])) { $newProperties[$propName] = $this->principalProperties[$propName]; } - } return $newProperties; - } /** * Updates this principals properties. - * + * * @param array $mutations + * * @see Sabre_DAV_IProperties::updateProperties + * * @return bool|array */ - public function updateProperties($mutations) { - + public function updateProperties($mutations) + { return $this->principalBackend->updatePrincipal($this->principalProperties['uri'], $mutations); - } /** - * Returns the owner principal + * Returns the owner principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getOwner() { - + public function getOwner() + { return $this->principalProperties['uri']; - - } /** - * Returns a group principal + * Returns a group principal. * * This must be a url to a principal, or null if there's no owner * * @return string|null */ - public function getGroup() { - + public function getGroup() + { return null; - } /** @@ -232,8 +214,8 @@ class Sabre_DAVACL_Principal extends Sabre_DAV_Node implements Sabre_DAVACL_IPri * * @return array */ - public function getACL() { - + public function getACL() + { return array( array( 'privilege' => '{DAV:}read', @@ -241,21 +223,18 @@ class Sabre_DAVACL_Principal extends Sabre_DAV_Node implements Sabre_DAVACL_IPri 'protected' => true, ), ); - } /** - * Updates the ACL + * Updates the ACL. * * This method will receive a list of new ACE's. * * @param array $acl - * @return void */ - public function setACL(array $acl) { - + public function setACL(array $acl) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Updating ACLs is not allowed here'); - } /** @@ -270,10 +249,8 @@ class Sabre_DAVACL_Principal extends Sabre_DAV_Node implements Sabre_DAVACL_IPri * * @return array|null */ - public function getSupportedPrivilegeSet() { - + public function getSupportedPrivilegeSet() + { return null; - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/PrincipalBackend/PDO.php b/dav/SabreDAV/lib/Sabre/DAVACL/PrincipalBackend/PDO.php index a76b4a9d..3f69dbf8 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/PrincipalBackend/PDO.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/PrincipalBackend/PDO.php @@ -1,7 +1,7 @@ array( 'dbField' => 'displayname', ), - /** + /* * This property is actually used by the CardDAV plugin, where it gets * mapped to {http://calendarserver.orgi/ns/}me-card. * @@ -63,7 +61,7 @@ class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBacken '{http://sabredav.org/ns}vcard-url' => array( 'dbField' => 'vcardurl', ), - /** + /* * This is the users' primary email-address. */ '{http://sabredav.org/ns}email-address' => array( @@ -74,19 +72,17 @@ class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBacken /** * Sets up the backend. * - * @param PDO $pdo + * @param PDO $pdo * @param string $tableName * @param string $groupMembersTableName */ - public function __construct(PDO $pdo, $tableName = 'principals', $groupMembersTableName = 'groupmembers') { - + public function __construct(PDO $pdo, $tableName = 'principals', $groupMembersTableName = 'groupmembers') + { $this->pdo = $pdo; $this->tableName = $tableName; $this->groupMembersTableName = $groupMembersTableName; - } - /** * Returns a list of principals based on a prefix. * @@ -101,41 +97,42 @@ class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBacken * you have an email address, use this property. * * @param string $prefixPath + * * @return array */ - public function getPrincipalsByPrefix($prefixPath) { - + public function getPrincipalsByPrefix($prefixPath) + { $fields = array( 'uri', ); - foreach($this->fieldMap as $key=>$value) { + foreach ($this->fieldMap as $key => $value) { $fields[] = $value['dbField']; } - $result = $this->pdo->query('SELECT '.implode(',', $fields).' FROM '. $this->tableName); + $result = $this->pdo->query('SELECT '.implode(',', $fields).' FROM '.$this->tableName); $principals = array(); - while($row = $result->fetch(PDO::FETCH_ASSOC)) { + while ($row = $result->fetch(PDO::FETCH_ASSOC)) { // Checking if the principal is in the prefix list($rowPrefix) = Sabre_DAV_URLUtil::splitPath($row['uri']); - if ($rowPrefix !== $prefixPath) continue; + if ($rowPrefix !== $prefixPath) { + continue; + } $principal = array( 'uri' => $row['uri'], ); - foreach($this->fieldMap as $key=>$value) { + foreach ($this->fieldMap as $key => $value) { if ($row[$value['dbField']]) { $principal[$key] = $row[$value['dbField']]; } } $principals[] = $principal; - } return $principals; - } /** @@ -144,35 +141,38 @@ class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBacken * getPrincipalsByPrefix. * * @param string $path + * * @return array */ - public function getPrincipalByPath($path) { - + public function getPrincipalByPath($path) + { $fields = array( 'id', 'uri', ); - foreach($this->fieldMap as $key=>$value) { + foreach ($this->fieldMap as $key => $value) { $fields[] = $value['dbField']; } - $stmt = $this->pdo->prepare('SELECT '.implode(',', $fields).' FROM '. $this->tableName . ' WHERE uri = ?'); + $stmt = $this->pdo->prepare('SELECT '.implode(',', $fields).' FROM '.$this->tableName.' WHERE uri = ?'); $stmt->execute(array($path)); $row = $stmt->fetch(PDO::FETCH_ASSOC); - if (!$row) return; + if (!$row) { + return; + } $principal = array( - 'id' => $row['id'], + 'id' => $row['id'], 'uri' => $row['uri'], ); - foreach($this->fieldMap as $key=>$value) { + foreach ($this->fieldMap as $key => $value) { if ($row[$value['dbField']]) { $principal[$key] = $row[$value['dbField']]; } } - return $principal; + return $principal; } /** @@ -220,17 +220,17 @@ class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBacken * return true or false. * * @param string $path - * @param array $mutations + * @param array $mutations + * * @return array|bool */ - public function updatePrincipal($path, $mutations) { - + public function updatePrincipal($path, $mutations) + { $updateAble = array(); - foreach($mutations as $key=>$value) { + foreach ($mutations as $key => $value) { // We are not aware of this field, we must fail. if (!isset($this->fieldMap[$key])) { - $response = array( 403 => array( $key => null, @@ -239,36 +239,35 @@ class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBacken ); // Adding the rest to the response as a 424 - foreach($mutations as $subKey=>$subValue) { + foreach ($mutations as $subKey => $subValue) { if ($subKey !== $key) { $response[424][$subKey] = null; } } + return $response; } $updateAble[$this->fieldMap[$key]['dbField']] = $value; - } // No fields to update - $query = "UPDATE " . $this->tableName . " SET "; + $query = 'UPDATE '.$this->tableName.' SET '; $first = true; - foreach($updateAble as $key => $value) { + foreach ($updateAble as $key => $value) { if (!$first) { - $query.= ', '; + $query .= ', '; } $first = false; - $query.= "$key = :$key "; + $query .= "$key = :$key "; } - $query.='WHERE uri = :uri'; + $query .= 'WHERE uri = :uri'; $stmt = $this->pdo->prepare($query); - $updateAble['uri'] = $path; + $updateAble['uri'] = $path; $stmt->execute($updateAble); return true; - } /** @@ -296,60 +295,62 @@ class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBacken * from working. * * @param string $prefixPath - * @param array $searchProperties + * @param array $searchProperties + * * @return array */ - public function searchPrincipals($prefixPath, array $searchProperties) { - - $query = 'SELECT uri FROM ' . $this->tableName . ' WHERE 1=1 '; + public function searchPrincipals($prefixPath, array $searchProperties) + { + $query = 'SELECT uri FROM '.$this->tableName.' WHERE 1=1 '; $values = array(); - foreach($searchProperties as $property => $value) { + foreach ($searchProperties as $property => $value) { + switch ($property) { - switch($property) { - - case '{DAV:}displayname' : - $query.=' AND displayname LIKE ?'; - $values[] = '%' . $value . '%'; + case '{DAV:}displayname': + $query .= ' AND displayname LIKE ?'; + $values[] = '%'.$value.'%'; break; - case '{http://sabredav.org/ns}email-address' : - $query.=' AND email LIKE ?'; - $values[] = '%' . $value . '%'; + case '{http://sabredav.org/ns}email-address': + $query .= ' AND email LIKE ?'; + $values[] = '%'.$value.'%'; break; - default : + default: // Unsupported property return array(); } - } $stmt = $this->pdo->prepare($query); $stmt->execute($values); $principals = array(); - while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // Checking if the principal is in the prefix list($rowPrefix) = Sabre_DAV_URLUtil::splitPath($row['uri']); - if ($rowPrefix !== $prefixPath) continue; + if ($rowPrefix !== $prefixPath) { + continue; + } $principals[] = $row['uri']; - } return $principals; - } /** - * Returns the list of members for a group-principal + * Returns the list of members for a group-principal. * * @param string $principal + * * @return array */ - public function getGroupMemberSet($principal) { - + public function getGroupMemberSet($principal) + { $principal = $this->getPrincipalByPath($principal); - if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); + if (!$principal) { + throw new Sabre_DAV_Exception('Principal not found'); + } $stmt = $this->pdo->prepare('SELECT principals.uri as uri FROM '.$this->groupMembersTableName.' AS groupmembers LEFT JOIN '.$this->tableName.' AS principals ON groupmembers.member_id = principals.id WHERE groupmembers.principal_id = ?'); $stmt->execute(array($principal['id'])); @@ -358,20 +359,23 @@ class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBacken while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $result[] = $row['uri']; } - return $result; + return $result; } /** - * Returns the list of groups a principal is a member of + * Returns the list of groups a principal is a member of. * * @param string $principal + * * @return array */ - public function getGroupMembership($principal) { - + public function getGroupMembership($principal) + { $principal = $this->getPrincipalByPath($principal); - if (!$principal) throw new Sabre_DAV_Exception('Principal not found'); + if (!$principal) { + throw new Sabre_DAV_Exception('Principal not found'); + } $stmt = $this->pdo->prepare('SELECT principals.uri as uri FROM '.$this->groupMembersTableName.' AS groupmembers LEFT JOIN '.$this->tableName.' AS principals ON groupmembers.principal_id = principals.id WHERE groupmembers.member_id = ?'); $stmt->execute(array($principal['id'])); @@ -380,8 +384,8 @@ class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBacken while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $result[] = $row['uri']; } - return $result; + return $result; } /** @@ -390,38 +394,36 @@ class Sabre_DAVACL_PrincipalBackend_PDO implements Sabre_DAVACL_IPrincipalBacken * The principals should be passed as a list of uri's. * * @param string $principal - * @param array $members - * @return void + * @param array $members */ - public function setGroupMemberSet($principal, array $members) { + public function setGroupMemberSet($principal, array $members) + { // Grabbing the list of principal id's. - $stmt = $this->pdo->prepare('SELECT id, uri FROM '.$this->tableName.' WHERE uri IN (? ' . str_repeat(', ? ', count($members)) . ');'); + $stmt = $this->pdo->prepare('SELECT id, uri FROM '.$this->tableName.' WHERE uri IN (? '.str_repeat(', ? ', count($members)).');'); $stmt->execute(array_merge(array($principal), $members)); $memberIds = array(); $principalId = null; - while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { if ($row['uri'] == $principal) { $principalId = $row['id']; } else { $memberIds[] = $row['id']; } } - if (!$principalId) throw new Sabre_DAV_Exception('Principal not found'); + if (!$principalId) { + throw new Sabre_DAV_Exception('Principal not found'); + } // Wiping out old members $stmt = $this->pdo->prepare('DELETE FROM '.$this->groupMembersTableName.' WHERE principal_id = ?;'); $stmt->execute(array($principalId)); - foreach($memberIds as $memberId) { - + foreach ($memberIds as $memberId) { $stmt = $this->pdo->prepare('INSERT INTO '.$this->groupMembersTableName.' (principal_id, member_id) VALUES (?, ?);'); $stmt->execute(array($principalId, $memberId)); - } - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/PrincipalCollection.php b/dav/SabreDAV/lib/Sabre/DAVACL/PrincipalCollection.php index c3e4cb83..61a3fbbb 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/PrincipalCollection.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/PrincipalCollection.php @@ -1,21 +1,19 @@ principalBackend, $principal); - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Property/Acl.php b/dav/SabreDAV/lib/Sabre/DAVACL/Property/Acl.php index 3f79a8d5..eda74886 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Property/Acl.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Property/Acl.php @@ -1,18 +1,16 @@ privileges = $privileges; $this->prefixBaseUrl = $prefixBaseUrl; - } /** - * Returns the list of privileges for this property + * Returns the list of privileges for this property. * * @return array */ - public function getPrivileges() { - + public function getPrivileges() + { return $this->privileges; - } /** - * Serializes the property into a DOMElement + * Serializes the property into a DOMElement. * * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void + * @param DOMElement $node */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $node) + { $doc = $node->ownerDocument; - foreach($this->privileges as $ace) { - + foreach ($this->privileges as $ace) { $this->serializeAce($doc, $node, $ace, $server); - } - } /** * Unserializes the {DAV:}acl xml element. * * @param DOMElement $dom + * * @return Sabre_DAVACL_Property_Acl */ - static public function unserialize(DOMElement $dom) { - + public static function unserialize(DOMElement $dom) + { $privileges = array(); - $xaces = $dom->getElementsByTagNameNS('DAV:','ace'); - for($ii=0; $ii < $xaces->length; $ii++) { - + $xaces = $dom->getElementsByTagNameNS('DAV:', 'ace'); + for ($ii = 0; $ii < $xaces->length; ++$ii) { $xace = $xaces->item($ii); - $principal = $xace->getElementsByTagNameNS('DAV:','principal'); + $principal = $xace->getElementsByTagNameNS('DAV:', 'principal'); if ($principal->length !== 1) { throw new Sabre_DAV_Exception_BadRequest('Each {DAV:}ace element must have one {DAV:}principal element'); } $principal = Sabre_DAVACL_Property_Principal::unserialize($principal->item(0)); - switch($principal->getType()) { - case Sabre_DAVACL_Property_Principal::HREF : + switch ($principal->getType()) { + case Sabre_DAVACL_Property_Principal::HREF: $principal = $principal->getHref(); break; - case Sabre_DAVACL_Property_Principal::AUTHENTICATED : + case Sabre_DAVACL_Property_Principal::AUTHENTICATED: $principal = '{DAV:}authenticated'; break; - case Sabre_DAVACL_Property_Principal::UNAUTHENTICATED : + case Sabre_DAVACL_Property_Principal::UNAUTHENTICATED: $principal = '{DAV:}unauthenticated'; break; - case Sabre_DAVACL_Property_Principal::ALL : + case Sabre_DAVACL_Property_Principal::ALL: $principal = '{DAV:}all'; break; @@ -116,25 +108,23 @@ class Sabre_DAVACL_Property_Acl extends Sabre_DAV_Property { $protected = false; - if ($xace->getElementsByTagNameNS('DAV:','protected')->length > 0) { + if ($xace->getElementsByTagNameNS('DAV:', 'protected')->length > 0) { $protected = true; } - $grants = $xace->getElementsByTagNameNS('DAV:','grant'); + $grants = $xace->getElementsByTagNameNS('DAV:', 'grant'); if ($grants->length < 1) { throw new Sabre_DAV_Exception_NotImplemented('Every {DAV:}ace element must have a {DAV:}grant element. {DAV:}deny is not yet supported'); } $grant = $grants->item(0); - $xprivs = $grant->getElementsByTagNameNS('DAV:','privilege'); - for($jj=0; $jj<$xprivs->length; $jj++) { - + $xprivs = $grant->getElementsByTagNameNS('DAV:', 'privilege'); + for ($jj = 0; $jj < $xprivs->length; ++$jj) { $xpriv = $xprivs->item($jj); $privilegeName = null; - for ($kk=0;$kk<$xpriv->childNodes->length;$kk++) { - + for ($kk = 0; $kk < $xpriv->childNodes->length; ++$kk) { $childNode = $xpriv->childNodes->item($kk); if ($t = Sabre_DAV_XMLUtil::toClarkNotation($childNode)) { $privilegeName = $t; @@ -150,60 +140,55 @@ class Sabre_DAVACL_Property_Acl extends Sabre_DAV_Property { 'protected' => $protected, 'privilege' => $privilegeName, ); - } - } return new self($privileges); - } /** * Serializes a single access control entry. * - * @param DOMDocument $doc - * @param DOMElement $node - * @param array $ace + * @param DOMDocument $doc + * @param DOMElement $node + * @param array $ace * @param Sabre_DAV_Server $server - * @return void */ - private function serializeAce($doc,$node,$ace, $server) { - - $xace = $doc->createElementNS('DAV:','d:ace'); + private function serializeAce($doc, $node, $ace, $server) + { + $xace = $doc->createElementNS('DAV:', 'd:ace'); $node->appendChild($xace); - $principal = $doc->createElementNS('DAV:','d:principal'); + $principal = $doc->createElementNS('DAV:', 'd:principal'); $xace->appendChild($principal); - switch($ace['principal']) { - case '{DAV:}authenticated' : - $principal->appendChild($doc->createElementNS('DAV:','d:authenticated')); + switch ($ace['principal']) { + case '{DAV:}authenticated': + $principal->appendChild($doc->createElementNS('DAV:', 'd:authenticated')); break; - case '{DAV:}unauthenticated' : - $principal->appendChild($doc->createElementNS('DAV:','d:unauthenticated')); + case '{DAV:}unauthenticated': + $principal->appendChild($doc->createElementNS('DAV:', 'd:unauthenticated')); break; - case '{DAV:}all' : - $principal->appendChild($doc->createElementNS('DAV:','d:all')); + case '{DAV:}all': + $principal->appendChild($doc->createElementNS('DAV:', 'd:all')); break; default: - $principal->appendChild($doc->createElementNS('DAV:','d:href',($this->prefixBaseUrl?$server->getBaseUri():'') . $ace['principal'] . '/')); + $principal->appendChild($doc->createElementNS('DAV:', 'd:href', ($this->prefixBaseUrl ? $server->getBaseUri() : '').$ace['principal'].'/')); } - $grant = $doc->createElementNS('DAV:','d:grant'); + $grant = $doc->createElementNS('DAV:', 'd:grant'); $xace->appendChild($grant); $privParts = null; - preg_match('/^{([^}]*)}(.*)$/',$ace['privilege'],$privParts); + preg_match('/^{([^}]*)}(.*)$/', $ace['privilege'], $privParts); - $xprivilege = $doc->createElementNS('DAV:','d:privilege'); + $xprivilege = $doc->createElementNS('DAV:', 'd:privilege'); $grant->appendChild($xprivilege); - $xprivilege->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); + $xprivilege->appendChild($doc->createElementNS($privParts[1], 'd:'.$privParts[2])); - if (isset($ace['protected']) && $ace['protected']) + if (isset($ace['protected']) && $ace['protected']) { $xace->appendChild($doc->createElement('d:protected')); - + } } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Property/AclRestrictions.php b/dav/SabreDAV/lib/Sabre/DAVACL/Property/AclRestrictions.php index a8b05495..75c64ebf 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Property/AclRestrictions.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Property/AclRestrictions.php @@ -1,32 +1,27 @@ ownerDocument; - $elem->appendChild($doc->createElementNS('DAV:','d:grant-only')); - $elem->appendChild($doc->createElementNS('DAV:','d:no-invert')); - + $elem->appendChild($doc->createElementNS('DAV:', 'd:grant-only')); + $elem->appendChild($doc->createElementNS('DAV:', 'd:no-invert')); } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php b/dav/SabreDAV/lib/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php index 94a29640..b891880e 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Property/CurrentUserPrivilegeSet.php @@ -1,75 +1,65 @@ privileges = $privileges; - } /** - * Serializes the property in the DOM + * Serializes the property in the DOM. * * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void + * @param DOMElement $node */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $node) + { $doc = $node->ownerDocument; - foreach($this->privileges as $privName) { - - $this->serializePriv($doc,$node,$privName); - + foreach ($this->privileges as $privName) { + $this->serializePriv($doc, $node, $privName); } - } /** - * Serializes one privilege + * Serializes one privilege. * * @param DOMDocument $doc - * @param DOMElement $node - * @param string $privName - * @return void + * @param DOMElement $node + * @param string $privName */ - protected function serializePriv($doc,$node,$privName) { - - $xp = $doc->createElementNS('DAV:','d:privilege'); + protected function serializePriv($doc, $node, $privName) + { + $xp = $doc->createElementNS('DAV:', 'd:privilege'); $node->appendChild($xp); $privParts = null; - preg_match('/^{([^}]*)}(.*)$/',$privName,$privParts); - - $xp->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); + preg_match('/^{([^}]*)}(.*)$/', $privName, $privParts); + $xp->appendChild($doc->createElementNS($privParts[1], 'd:'.$privParts[2])); } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Property/Principal.php b/dav/SabreDAV/lib/Sabre/DAVACL/Property/Principal.php index 3f681742..57cf1580 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Property/Principal.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Property/Principal.php @@ -1,41 +1,39 @@ type = $type; - if ($type===self::HREF && is_null($href)) { + if ($type === self::HREF && is_null($href)) { throw new Sabre_DAV_Exception('The href argument must be specified for the HREF principal type.'); } $this->href = $href; - } /** - * Returns the principal type + * Returns the principal type. * * @return int */ - public function getType() { - + public function getType() + { return $this->type; - } /** @@ -89,72 +85,68 @@ class Sabre_DAVACL_Property_Principal extends Sabre_DAV_Property implements Sabr * * @return string */ - public function getHref() { - + public function getHref() + { return $this->href; - } /** * Serializes the property into a DOMElement. * * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void + * @param DOMElement $node */ - public function serialize(Sabre_DAV_Server $server, DOMElement $node) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $node) + { $prefix = $server->xmlNamespaces['DAV:']; - switch($this->type) { + switch ($this->type) { - case self::UNAUTHENTICATED : + case self::UNAUTHENTICATED: $node->appendChild( - $node->ownerDocument->createElement($prefix . ':unauthenticated') + $node->ownerDocument->createElement($prefix.':unauthenticated') ); break; - case self::AUTHENTICATED : + case self::AUTHENTICATED: $node->appendChild( - $node->ownerDocument->createElement($prefix . ':authenticated') + $node->ownerDocument->createElement($prefix.':authenticated') ); break; - case self::HREF : - $href = $node->ownerDocument->createElement($prefix . ':href'); - $href->nodeValue = $server->getBaseUri() . $this->href; + case self::HREF: + $href = $node->ownerDocument->createElement($prefix.':href'); + $href->nodeValue = $server->getBaseUri().$this->href; $node->appendChild($href); break; } - } /** * Deserializes a DOM element into a property object. * * @param DOMElement $dom + * * @return Sabre_DAVACL_Property_Principal */ - static public function unserialize(DOMElement $dom) { - + public static function unserialize(DOMElement $dom) + { $parent = $dom->firstChild; - while(!Sabre_DAV_XMLUtil::toClarkNotation($parent)) { + while (!Sabre_DAV_XMLUtil::toClarkNotation($parent)) { $parent = $parent->nextSibling; } - switch(Sabre_DAV_XMLUtil::toClarkNotation($parent)) { + switch (Sabre_DAV_XMLUtil::toClarkNotation($parent)) { - case '{DAV:}unauthenticated' : + case '{DAV:}unauthenticated': return new self(self::UNAUTHENTICATED); - case '{DAV:}authenticated' : + case '{DAV:}authenticated': return new self(self::AUTHENTICATED); case '{DAV:}href': return new self(self::HREF, $parent->textContent); case '{DAV:}all': return new self(self::ALL); - default : - throw new Sabre_DAV_Exception_BadRequest('Unexpected element (' . Sabre_DAV_XMLUtil::toClarkNotation($parent) . '). Could not deserialize'); + default: + throw new Sabre_DAV_Exception_BadRequest('Unexpected element ('.Sabre_DAV_XMLUtil::toClarkNotation($parent).'). Could not deserialize'); } - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Property/SupportedPrivilegeSet.php b/dav/SabreDAV/lib/Sabre/DAVACL/Property/SupportedPrivilegeSet.php index 276d57ae..81e75f9b 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Property/SupportedPrivilegeSet.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Property/SupportedPrivilegeSet.php @@ -1,7 +1,7 @@ privileges = $privileges; - } /** * Serializes the property into a domdocument. * * @param Sabre_DAV_Server $server - * @param DOMElement $node - * @return void + * @param DOMElement $node */ - public function serialize(Sabre_DAV_Server $server,DOMElement $node) { - + public function serialize(Sabre_DAV_Server $server, DOMElement $node) + { $doc = $node->ownerDocument; $this->serializePriv($doc, $node, $this->privileges); - } /** - * Serializes a property + * Serializes a property. * * This is a recursive function. * * @param DOMDocument $doc - * @param DOMElement $node - * @param array $privilege - * @return void + * @param DOMElement $node + * @param array $privilege */ - private function serializePriv($doc,$node,$privilege) { - - $xsp = $doc->createElementNS('DAV:','d:supported-privilege'); + private function serializePriv($doc, $node, $privilege) + { + $xsp = $doc->createElementNS('DAV:', 'd:supported-privilege'); $node->appendChild($xsp); - $xp = $doc->createElementNS('DAV:','d:privilege'); + $xp = $doc->createElementNS('DAV:', 'd:privilege'); $xsp->appendChild($xp); $privParts = null; - preg_match('/^{([^}]*)}(.*)$/',$privilege['privilege'],$privParts); + preg_match('/^{([^}]*)}(.*)$/', $privilege['privilege'], $privParts); - $xp->appendChild($doc->createElementNS($privParts[1],'d:'.$privParts[2])); + $xp->appendChild($doc->createElementNS($privParts[1], 'd:'.$privParts[2])); if (isset($privilege['abstract']) && $privilege['abstract']) { - $xsp->appendChild($doc->createElementNS('DAV:','d:abstract')); + $xsp->appendChild($doc->createElementNS('DAV:', 'd:abstract')); } if (isset($privilege['description'])) { - $xsp->appendChild($doc->createElementNS('DAV:','d:description',$privilege['description'])); + $xsp->appendChild($doc->createElementNS('DAV:', 'd:description', $privilege['description'])); } if (isset($privilege['aggregates'])) { - foreach($privilege['aggregates'] as $subPrivilege) { - $this->serializePriv($doc,$xsp,$subPrivilege); + foreach ($privilege['aggregates'] as $subPrivilege) { + $this->serializePriv($doc, $xsp, $subPrivilege); } } - } - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/Version.php b/dav/SabreDAV/lib/Sabre/DAVACL/Version.php index 9950f748..61c42f3d 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/Version.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/Version.php @@ -3,22 +3,19 @@ /** * This class contains the SabreDAV version constants. * - * @package Sabre - * @subpackage DAVACL - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_DAVACL_Version { - +class Sabre_DAVACL_Version +{ /** - * Full version number + * Full version number. */ const VERSION = '1.6.0'; /** - * Stability : alpha, beta, stable + * Stability : alpha, beta, stable. */ const STABILITY = 'stable'; - } diff --git a/dav/SabreDAV/lib/Sabre/DAVACL/includes.php b/dav/SabreDAV/lib/Sabre/DAVACL/includes.php index 28fa3eed..65812294 100644 --- a/dav/SabreDAV/lib/Sabre/DAVACL/includes.php +++ b/dav/SabreDAV/lib/Sabre/DAVACL/includes.php @@ -1,38 +1,36 @@ httpRequest->getHeader('Authorization'); - $authHeader = explode(' ',$authHeader); + $authHeader = explode(' ', $authHeader); - if ($authHeader[0]!='AWS' || !isset($authHeader[1])) { + if ($authHeader[0] != 'AWS' || !isset($authHeader[1])) { $this->errorCode = self::ERR_NOAWSHEADER; - return false; + + return false; } - list($this->accessKey,$this->signature) = explode(':',$authHeader[1]); + list($this->accessKey, $this->signature) = explode(':', $authHeader[1]); return true; - } /** - * Returns the username for the request + * Returns the username for the request. * * @return string */ - public function getAccessKey() { - + public function getAccessKey() + { return $this->accessKey; - } /** - * Validates the signature based on the secretKey + * Validates the signature based on the secretKey. * * @param string $secretKey + * * @return bool */ - public function validate($secretKey) { - + public function validate($secretKey) + { $contentMD5 = $this->httpRequest->getHeader('Content-MD5'); if ($contentMD5) { // We need to validate the integrity of the request $body = $this->httpRequest->getBody(true); - $this->httpRequest->setBody($body,true); + $this->httpRequest->setBody($body, true); - if ($contentMD5!=base64_encode(md5($body,true))) { + if ($contentMD5 != base64_encode(md5($body, true))) { // content-md5 header did not match md5 signature of body $this->errorCode = self::ERR_MD5CHECKSUMWRONG; + return false; } - } - if (!$requestDate = $this->httpRequest->getHeader('x-amz-date')) + if (!$requestDate = $this->httpRequest->getHeader('x-amz-date')) { $requestDate = $this->httpRequest->getHeader('Date'); + } - if (!$this->validateRFC2616Date($requestDate)) + if (!$this->validateRFC2616Date($requestDate)) { return false; + } $amzHeaders = $this->getAmzHeaders(); $signature = base64_encode( $this->hmacsha1($secretKey, - $this->httpRequest->getMethod() . "\n" . - $contentMD5 . "\n" . - $this->httpRequest->getHeader('Content-type') . "\n" . - $requestDate . "\n" . - $amzHeaders . + $this->httpRequest->getMethod()."\n". + $contentMD5."\n". + $this->httpRequest->getHeader('Content-type')."\n". + $requestDate."\n". + $amzHeaders. $this->httpRequest->getURI() ) ); if ($this->signature != $signature) { - $this->errorCode = self::ERR_INVALIDSIGNATURE; - return false; + return false; } return true; - } - /** - * Returns an HTTP 401 header, forcing login + * Returns an HTTP 401 header, forcing login. * * This should be called when username and password are incorrect, or not supplied at all - * - * @return void */ - public function requireLogin() { - - $this->httpResponse->setHeader('WWW-Authenticate','AWS'); + public function requireLogin() + { + $this->httpResponse->setHeader('WWW-Authenticate', 'AWS'); $this->httpResponse->sendStatus(401); - } /** @@ -154,15 +148,17 @@ class Sabre_HTTP_AWSAuth extends Sabre_HTTP_AbstractAuth { * system date, to prevent replay attacks. * * @param string $dateHeader + * * @return bool */ - protected function validateRFC2616Date($dateHeader) { - + protected function validateRFC2616Date($dateHeader) + { $date = Sabre_HTTP_Util::parseHTTPDate($dateHeader); // Unknown format if (!$date) { $this->errorCode = self::ERR_INVALIDDATEFORMAT; + return false; } @@ -172,56 +168,56 @@ class Sabre_HTTP_AWSAuth extends Sabre_HTTP_AbstractAuth { // We allow 15 minutes around the current date/time if ($date > $max || $date < $min) { $this->errorCode = self::ERR_REQUESTTIMESKEWED; + return false; } return $date; - } /** - * Returns a list of AMZ headers + * Returns a list of AMZ headers. * * @return string */ - protected function getAmzHeaders() { - + protected function getAmzHeaders() + { $amzHeaders = array(); $headers = $this->httpRequest->getHeaders(); - foreach($headers as $headerName => $headerValue) { - if (strpos(strtolower($headerName),'x-amz-')===0) { - $amzHeaders[strtolower($headerName)] = str_replace(array("\r\n"),array(' '),$headerValue) . "\n"; + foreach ($headers as $headerName => $headerValue) { + if (strpos(strtolower($headerName), 'x-amz-') === 0) { + $amzHeaders[strtolower($headerName)] = str_replace(array("\r\n"), array(' '), $headerValue)."\n"; } } ksort($amzHeaders); $headerStr = ''; - foreach($amzHeaders as $h=>$v) { - $headerStr.=$h.':'.$v; + foreach ($amzHeaders as $h => $v) { + $headerStr .= $h.':'.$v; } return $headerStr; - } /** - * Generates an HMAC-SHA1 signature + * Generates an HMAC-SHA1 signature. * * @param string $key * @param string $message + * * @return string */ - private function hmacsha1($key, $message) { + private function hmacsha1($key, $message) + { + $blocksize = 64; + if (strlen($key) > $blocksize) { + $key = pack('H*', sha1($key)); + } + $key = str_pad($key, $blocksize, chr(0x00)); + $ipad = str_repeat(chr(0x36), $blocksize); + $opad = str_repeat(chr(0x5c), $blocksize); + $hmac = pack('H*', sha1(($key ^ $opad).pack('H*', sha1(($key ^ $ipad).$message)))); - $blocksize=64; - if (strlen($key)>$blocksize) - $key=pack('H*', sha1($key)); - $key=str_pad($key,$blocksize,chr(0x00)); - $ipad=str_repeat(chr(0x36),$blocksize); - $opad=str_repeat(chr(0x5c),$blocksize); - $hmac = pack('H*',sha1(($key^$opad).pack('H*',sha1(($key^$ipad).$message)))); return $hmac; - } - } diff --git a/dav/SabreDAV/lib/Sabre/HTTP/AbstractAuth.php b/dav/SabreDAV/lib/Sabre/HTTP/AbstractAuth.php index 3bccabcd..bb0a319b 100644 --- a/dav/SabreDAV/lib/Sabre/HTTP/AbstractAuth.php +++ b/dav/SabreDAV/lib/Sabre/HTTP/AbstractAuth.php @@ -1,20 +1,18 @@ httpResponse = new Sabre_HTTP_Response(); $this->httpRequest = new Sabre_HTTP_Request(); - } /** - * Sets an alternative HTTP response object + * Sets an alternative HTTP response object. * * @param Sabre_HTTP_Response $response - * @return void */ - public function setHTTPResponse(Sabre_HTTP_Response $response) { - + public function setHTTPResponse(Sabre_HTTP_Response $response) + { $this->httpResponse = $response; - } /** - * Sets an alternative HTTP request object + * Sets an alternative HTTP request object. * * @param Sabre_HTTP_Request $request - * @return void */ - public function setHTTPRequest(Sabre_HTTP_Request $request) { - + public function setHTTPRequest(Sabre_HTTP_Request $request) + { $this->httpRequest = $request; - } - /** - * Sets the realm + * Sets the realm. * * The realm is often displayed in authentication dialog boxes * Commonly an application name displayed here * * @param string $realm - * @return void */ - public function setRealm($realm) { - + public function setRealm($realm) + { $this->realm = $realm; - } /** - * Returns the realm + * Returns the realm. * * @return string */ - public function getRealm() { - + public function getRealm() + { return $this->realm; - } /** - * Returns an HTTP 401 header, forcing login + * Returns an HTTP 401 header, forcing login. * * This should be called when username and password are incorrect, or not supplied at all - * - * @return void */ abstract public function requireLogin(); - } diff --git a/dav/SabreDAV/lib/Sabre/HTTP/BasicAuth.php b/dav/SabreDAV/lib/Sabre/HTTP/BasicAuth.php index f90ed24f..e529c096 100644 --- a/dav/SabreDAV/lib/Sabre/HTTP/BasicAuth.php +++ b/dav/SabreDAV/lib/Sabre/HTTP/BasicAuth.php @@ -1,18 +1,16 @@ httpRequest->getRawServerValue('PHP_AUTH_USER')) && ($pass = $this->httpRequest->getRawServerValue('PHP_AUTH_PW'))) { - - return array($user,$pass); - + return array($user, $pass); } // Most other webservers @@ -42,26 +39,25 @@ class Sabre_HTTP_BasicAuth extends Sabre_HTTP_AbstractAuth { $auth = $this->httpRequest->getRawServerValue('REDIRECT_HTTP_AUTHORIZATION'); } - if (!$auth) return false; + if (!$auth) { + return false; + } - if (strpos(strtolower($auth),'basic')!==0) return false; - - return explode(':', base64_decode(substr($auth, 6)),2); + if (strpos(strtolower($auth), 'basic') !== 0) { + return false; + } + return explode(':', base64_decode(substr($auth, 6)), 2); } /** - * Returns an HTTP 401 header, forcing login + * Returns an HTTP 401 header, forcing login. * * This should be called when username and password are incorrect, or not supplied at all - * - * @return void */ - public function requireLogin() { - - $this->httpResponse->setHeader('WWW-Authenticate','Basic realm="' . $this->realm . '"'); + public function requireLogin() + { + $this->httpResponse->setHeader('WWW-Authenticate', 'Basic realm="'.$this->realm.'"'); $this->httpResponse->sendStatus(401); - } - } diff --git a/dav/SabreDAV/lib/Sabre/HTTP/DigestAuth.php b/dav/SabreDAV/lib/Sabre/HTTP/DigestAuth.php index ee7f05c0..530513af 100644 --- a/dav/SabreDAV/lib/Sabre/HTTP/DigestAuth.php +++ b/dav/SabreDAV/lib/Sabre/HTTP/DigestAuth.php @@ -1,7 +1,7 @@ nonce = uniqid(); $this->opaque = md5($this->realm); parent::__construct(); - } /** - * Gathers all information from the headers + * Gathers all information from the headers. * * This method needs to be called prior to anything else. - * - * @return void */ - public function init() { - + public function init() + { $digest = $this->getDigest(); $this->digestParts = $this->parseDigest($digest); - } /** @@ -78,12 +72,10 @@ class Sabre_HTTP_DigestAuth extends Sabre_HTTP_AbstractAuth { * request body to be md5'ed, which can put strains on CPU and memory. * * @param int $qop - * @return void */ - public function setQOP($qop) { - + public function setQOP($qop) + { $this->qop = $qop; - } /** @@ -92,13 +84,14 @@ class Sabre_HTTP_DigestAuth extends Sabre_HTTP_AbstractAuth { * The A1 parameter should be md5($username . ':' . $realm . ':' . $password); * * @param string $A1 + * * @return bool */ - public function validateA1($A1) { - + public function validateA1($A1) + { $this->A1 = $A1; - return $this->validate(); + return $this->validate(); } /** @@ -106,79 +99,77 @@ class Sabre_HTTP_DigestAuth extends Sabre_HTTP_AbstractAuth { * It is strongly recommended not store the password in plain-text and use validateA1 instead. * * @param string $password + * * @return bool */ - public function validatePassword($password) { + public function validatePassword($password) + { + $this->A1 = md5($this->digestParts['username'].':'.$this->realm.':'.$password); - $this->A1 = md5($this->digestParts['username'] . ':' . $this->realm . ':' . $password); return $this->validate(); - } /** - * Returns the username for the request + * Returns the username for the request. * * @return string */ - public function getUsername() { - + public function getUsername() + { return $this->digestParts['username']; - } /** - * Validates the digest challenge + * Validates the digest challenge. * * @return bool */ - protected function validate() { + protected function validate() + { + $A2 = $this->httpRequest->getMethod().':'.$this->digestParts['uri']; - $A2 = $this->httpRequest->getMethod() . ':' . $this->digestParts['uri']; - - if ($this->digestParts['qop']=='auth-int') { + if ($this->digestParts['qop'] == 'auth-int') { // Making sure we support this qop value - if (!($this->qop & self::QOP_AUTHINT)) return false; + if (!($this->qop & self::QOP_AUTHINT)) { + return false; + } // We need to add an md5 of the entire request body to the A2 part of the hash $body = $this->httpRequest->getBody(true); - $this->httpRequest->setBody($body,true); - $A2 .= ':' . md5($body); + $this->httpRequest->setBody($body, true); + $A2 .= ':'.md5($body); } else { // We need to make sure we support this qop value - if (!($this->qop & self::QOP_AUTH)) return false; + if (!($this->qop & self::QOP_AUTH)) { + return false; + } } $A2 = md5($A2); $validResponse = md5("{$this->A1}:{$this->digestParts['nonce']}:{$this->digestParts['nc']}:{$this->digestParts['cnonce']}:{$this->digestParts['qop']}:{$A2}"); - return $this->digestParts['response']==$validResponse; - - + return $this->digestParts['response'] == $validResponse; } /** - * Returns an HTTP 401 header, forcing login + * Returns an HTTP 401 header, forcing login. * * This should be called when username and password are incorrect, or not supplied at all - * - * @return void */ - public function requireLogin() { - + public function requireLogin() + { $qop = ''; - switch($this->qop) { - case self::QOP_AUTH : $qop = 'auth'; break; - case self::QOP_AUTHINT : $qop = 'auth-int'; break; - case self::QOP_AUTH | self::QOP_AUTHINT : $qop = 'auth,auth-int'; break; + switch ($this->qop) { + case self::QOP_AUTH: $qop = 'auth'; break; + case self::QOP_AUTHINT: $qop = 'auth-int'; break; + case self::QOP_AUTH | self::QOP_AUTHINT: $qop = 'auth,auth-int'; break; } - $this->httpResponse->setHeader('WWW-Authenticate','Digest realm="' . $this->realm . '",qop="'.$qop.'",nonce="' . $this->nonce . '",opaque="' . $this->opaque . '"'); + $this->httpResponse->setHeader('WWW-Authenticate', 'Digest realm="'.$this->realm.'",qop="'.$qop.'",nonce="'.$this->nonce.'",opaque="'.$this->opaque.'"'); $this->httpResponse->sendStatus(401); - } - /** * This method returns the full digest string. * @@ -188,11 +179,14 @@ class Sabre_HTTP_DigestAuth extends Sabre_HTTP_AbstractAuth { * * @return mixed */ - public function getDigest() { + public function getDigest() + { // mod_php $digest = $this->httpRequest->getRawServerValue('PHP_AUTH_DIGEST'); - if ($digest) return $digest; + if ($digest) { + return $digest; + } // most other servers $digest = $this->httpRequest->getHeader('Authorization'); @@ -203,27 +197,27 @@ class Sabre_HTTP_DigestAuth extends Sabre_HTTP_AbstractAuth { $digest = $this->httpRequest->getRawServerValue('REDIRECT_HTTP_AUTHORIZATION'); } - if ($digest && strpos(strtolower($digest),'digest')===0) { - return substr($digest,7); + if ($digest && strpos(strtolower($digest), 'digest') === 0) { + return substr($digest, 7); } else { return null; } - } - /** * Parses the different pieces of the digest string into an array. * * This method returns false if an incomplete digest was supplied * * @param string $digest + * * @return mixed */ - protected function parseDigest($digest) { + protected function parseDigest($digest) + { // protect against missing data - $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1); + $needed_parts = array('nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1); $data = array(); preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER); @@ -234,7 +228,5 @@ class Sabre_HTTP_DigestAuth extends Sabre_HTTP_AbstractAuth { } return $needed_parts ? false : $data; - } - } diff --git a/dav/SabreDAV/lib/Sabre/HTTP/Request.php b/dav/SabreDAV/lib/Sabre/HTTP/Request.php index 74d5ed3d..5553c32a 100644 --- a/dav/SabreDAV/lib/Sabre/HTTP/Request.php +++ b/dav/SabreDAV/lib/Sabre/HTTP/Request.php @@ -1,7 +1,7 @@ _SERVER = $serverData; - else $this->_SERVER =& $_SERVER; - - if ($postData) $this->_POST = $postData; - else $this->_POST =& $_POST; + public function __construct(array $serverData = null, array $postData = null) + { + if ($serverData) { + $this->_SERVER = $serverData; + } else { + $this->_SERVER = &$_SERVER; + } + if ($postData) { + $this->_POST = $postData; + } else { + $this->_POST = &$_POST; + } } /** @@ -75,28 +78,29 @@ class Sabre_HTTP_Request { * This method returns null if the header did not exist. * * @param string $name + * * @return string */ - public function getHeader($name) { - - $name = strtoupper(str_replace(array('-'),array('_'),$name)); - if (isset($this->_SERVER['HTTP_' . $name])) { - return $this->_SERVER['HTTP_' . $name]; + public function getHeader($name) + { + $name = strtoupper(str_replace(array('-'), array('_'), $name)); + if (isset($this->_SERVER['HTTP_'.$name])) { + return $this->_SERVER['HTTP_'.$name]; } // There's a few headers that seem to end up in the top-level // server array. - switch($name) { - case 'CONTENT_TYPE' : - case 'CONTENT_LENGTH' : + switch ($name) { + case 'CONTENT_TYPE': + case 'CONTENT_LENGTH': if (isset($this->_SERVER[$name])) { return $this->_SERVER[$name]; } break; } - return; + return; } /** @@ -107,107 +111,103 @@ class Sabre_HTTP_Request { * * @return array */ - public function getHeaders() { - + public function getHeaders() + { $hdrs = array(); - foreach($this->_SERVER as $key=>$value) { - - switch($key) { - case 'CONTENT_LENGTH' : - case 'CONTENT_TYPE' : - $hdrs[strtolower(str_replace('_','-',$key))] = $value; + foreach ($this->_SERVER as $key => $value) { + switch ($key) { + case 'CONTENT_LENGTH': + case 'CONTENT_TYPE': + $hdrs[strtolower(str_replace('_', '-', $key))] = $value; break; - default : - if (strpos($key,'HTTP_')===0) { - $hdrs[substr(strtolower(str_replace('_','-',$key)),5)] = $value; + default: + if (strpos($key, 'HTTP_') === 0) { + $hdrs[substr(strtolower(str_replace('_', '-', $key)), 5)] = $value; } break; } - } return $hdrs; - } /** - * Returns the HTTP request method + * Returns the HTTP request method. * * This is for example POST or GET * * @return string */ - public function getMethod() { - + public function getMethod() + { return $this->_SERVER['REQUEST_METHOD']; - } /** - * Returns the requested uri + * Returns the requested uri. * * @return string */ - public function getUri() { - + public function getUri() + { return $this->_SERVER['REQUEST_URI']; - } /** - * Will return protocol + the hostname + the uri + * Will return protocol + the hostname + the uri. * * @return string */ - public function getAbsoluteUri() { + public function getAbsoluteUri() + { // Checking if the request was made through HTTPS. The last in line is for IIS - $protocol = isset($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']!='off'); - return ($protocol?'https':'http') . '://' . $this->getHeader('Host') . $this->getUri(); + $protocol = isset($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS']) && ($this->_SERVER['HTTPS'] != 'off'); + return ($protocol ? 'https' : 'http').'://'.$this->getHeader('Host').$this->getUri(); } /** - * Returns everything after the ? from the current url + * Returns everything after the ? from the current url. * * @return string */ - public function getQueryString() { - - return isset($this->_SERVER['QUERY_STRING'])?$this->_SERVER['QUERY_STRING']:''; - + public function getQueryString() + { + return isset($this->_SERVER['QUERY_STRING']) ? $this->_SERVER['QUERY_STRING'] : ''; } /** - * Returns the HTTP request body body + * Returns the HTTP request body body. * * This method returns a readable stream resource. * If the asString parameter is set to true, a string is sent instead. * * @param bool $asString + * * @return resource */ - public function getBody($asString = false) { - + public function getBody($asString = false) + { if (is_null($this->body)) { if (!is_null(self::$defaultInputStream)) { $this->body = self::$defaultInputStream; } else { - $this->body = fopen('php://input','r'); + $this->body = fopen('php://input', 'r'); self::$defaultInputStream = $this->body; } } if ($asString) { $body = stream_get_contents($this->body); + return $body; } else { return $this->body; } - } /** - * Sets the contents of the HTTP request body + * Sets the contents of the HTTP request body. * * This method can either accept a string, or a readable stream resource. * @@ -215,17 +215,15 @@ class Sabre_HTTP_Request { * script the supplied body will be used instead of php://input. * * @param mixed $body - * @param bool $setAsDefaultInputStream - * @return void + * @param bool $setAsDefaultInputStream */ - public function setBody($body,$setAsDefaultInputStream = false) { - - if(is_resource($body)) { + public function setBody($body, $setAsDefaultInputStream = false) + { + if (is_resource($body)) { $this->body = $body; } else { - - $stream = fopen('php://temp','r+'); - fputs($stream,$body); + $stream = fopen('php://temp', 'r+'); + fputs($stream, $body); rewind($stream); // String is assumed $this->body = $stream; @@ -233,7 +231,6 @@ class Sabre_HTTP_Request { if ($setAsDefaultInputStream) { self::$defaultInputStream = $this->body; } - } /** @@ -244,10 +241,9 @@ class Sabre_HTTP_Request { * * @return array */ - public function getPostVars() { - + public function getPostVars() + { return $this->_POST; - } /** @@ -256,13 +252,11 @@ class Sabre_HTTP_Request { * Do not rely on this feature, it is for internal use only. * * @param string $field + * * @return string */ - public function getRawServerValue($field) { - - return isset($this->_SERVER[$field])?$this->_SERVER[$field]:null; - + public function getRawServerValue($field) + { + return isset($this->_SERVER[$field]) ? $this->_SERVER[$field] : null; } - } - diff --git a/dav/SabreDAV/lib/Sabre/HTTP/Response.php b/dav/SabreDAV/lib/Sabre/HTTP/Response.php index ffe9bda2..e868bc52 100644 --- a/dav/SabreDAV/lib/Sabre/HTTP/Response.php +++ b/dav/SabreDAV/lib/Sabre/HTTP/Response.php @@ -1,24 +1,23 @@ 'Continue', 101 => 'Switching Protocols', @@ -81,77 +80,73 @@ class Sabre_HTTP_Response { 511 => 'Network Authentication Required', // draft-nottingham-http-new-status ); - return 'HTTP/1.1 ' . $code . ' ' . $msg[$code]; - + return 'HTTP/1.1 '.$code.' '.$msg[$code]; } /** - * Sends an HTTP status header to the client + * Sends an HTTP status header to the client. * * @param int $code HTTP status code + * * @return bool */ - public function sendStatus($code) { - - if (!headers_sent()) + public function sendStatus($code) + { + if (!headers_sent()) { return header($this->getStatusMessage($code)); - else return false; - + } else { + return false; + } } /** - * Sets an HTTP header for the response + * Sets an HTTP header for the response. * * @param string $name * @param string $value - * @param bool $replace + * @param bool $replace + * * @return bool */ - public function setHeader($name, $value, $replace = true) { - - $value = str_replace(array("\r","\n"),array('\r','\n'),$value); - if (!headers_sent()) - return header($name . ': ' . $value, $replace); - else return false; - + public function setHeader($name, $value, $replace = true) + { + $value = str_replace(array("\r", "\n"), array('\r', '\n'), $value); + if (!headers_sent()) { + return header($name.': '.$value, $replace); + } else { + return false; + } } /** - * Sets a bunch of HTTP Headers + * Sets a bunch of HTTP Headers. * * headersnames are specified as keys, value in the array value * * @param array $headers - * @return void */ - public function setHeaders(array $headers) { - - foreach($headers as $key=>$value) + public function setHeaders(array $headers) + { + foreach ($headers as $key => $value) { $this->setHeader($key, $value); - + } } /** - * Sends the entire response body + * Sends the entire response body. * * This method can accept either an open filestream, or a string. * * @param mixed $body - * @return void */ - public function sendBody($body) { - + public function sendBody($body) + { if (is_resource($body)) { - fpassthru($body); - } else { // We assume a string echo $body; - } - } - } diff --git a/dav/SabreDAV/lib/Sabre/HTTP/Util.php b/dav/SabreDAV/lib/Sabre/HTTP/Util.php index 67bdd489..00ecf262 100644 --- a/dav/SabreDAV/lib/Sabre/HTTP/Util.php +++ b/dav/SabreDAV/lib/Sabre/HTTP/Util.php @@ -1,26 +1,26 @@ = 0) - return new DateTime('@' . $realDate, new DateTimeZone('UTC')); - + if ($realDate !== false && $realDate >= 0) { + return new DateTime('@'.$realDate, new DateTimeZone('UTC')); + } } /** @@ -67,16 +68,17 @@ class Sabre_HTTP_Util { * specified as GMT. * * @param DateTime $dateTime + * * @return string */ - static function toHTTPDate(DateTime $dateTime) { + public static function toHTTPDate(DateTime $dateTime) + { // We need to clone it, as we don't want to affect the existing // DateTime. $dateTime = clone $dateTime; $dateTime->setTimeZone(new DateTimeZone('GMT')); + return $dateTime->format('D, d M Y H:i:s \G\M\T'); - } - } diff --git a/dav/SabreDAV/lib/Sabre/HTTP/Version.php b/dav/SabreDAV/lib/Sabre/HTTP/Version.php index e6b4f7e5..0e24f6b1 100644 --- a/dav/SabreDAV/lib/Sabre/HTTP/Version.php +++ b/dav/SabreDAV/lib/Sabre/HTTP/Version.php @@ -3,22 +3,19 @@ /** * This class contains the Sabre_HTTP version constants. * - * @package Sabre - * @subpackage HTTP - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_HTTP_Version { - +class Sabre_HTTP_Version +{ /** - * Full version number + * Full version number. */ const VERSION = '1.6.4'; /** - * Stability : alpha, beta, stable + * Stability : alpha, beta, stable. */ const STABILITY = 'stable'; - } diff --git a/dav/SabreDAV/lib/Sabre/HTTP/includes.php b/dav/SabreDAV/lib/Sabre/HTTP/includes.php index 9d34bf3a..72276c78 100644 --- a/dav/SabreDAV/lib/Sabre/HTTP/includes.php +++ b/dav/SabreDAV/lib/Sabre/HTTP/includes.php @@ -1,27 +1,25 @@ pdo); $this->assertTrue($backend instanceof Sabre_CalDAV_Backend_PDO); - } /** * @depends testConstruct */ - function testGetCalendarsForUserNoCalendars() { - + public function testGetCalendarsForUserNoCalendars() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); $calendars = $backend->getCalendarsForUser('principals/user2'); - $this->assertEquals(array(),$calendars); - + $this->assertEquals(array(), $calendars); } /** * @depends testConstruct */ - function testCreateCalendarAndFetch() { - + public function testCreateCalendarAndFetch() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array( + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array( '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT')), '{DAV:}displayname' => 'Hello!', )); $calendars = $backend->getCalendarsForUser('principals/user2'); $elementCheck = array( - 'id' => $returnedId, - 'uri' => 'somerandomid', + 'id' => $returnedId, + 'uri' => 'somerandomid', '{DAV:}displayname' => 'Hello!', '{urn:ietf:params:xml:ns:caldav}calendar-description' => '', ); - $this->assertInternalType('array',$calendars); - $this->assertEquals(1,count($calendars)); - - foreach($elementCheck as $name=>$value) { + $this->assertInternalType('array', $calendars); + $this->assertEquals(1, count($calendars)); + foreach ($elementCheck as $name => $value) { $this->assertArrayHasKey($name, $calendars[0]); - $this->assertEquals($value,$calendars[0][$name]); - + $this->assertEquals($value, $calendars[0][$name]); } - } /** * @depends testConstruct */ - function testUpdateCalendarAndFetch() { - + public function testUpdateCalendarAndFetch() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); //Creating a new calendar - $newId = $backend->createCalendar('principals/user2','somerandomid',array()); + $newId = $backend->createCalendar('principals/user2', 'somerandomid', array()); // Updating the calendar - $result = $backend->updateCalendar($newId,array( + $result = $backend->updateCalendar($newId, array( '{DAV:}displayname' => 'myCalendar', )); @@ -76,40 +71,37 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te // Checking if all the information is still correct $elementCheck = array( - 'id' => $newId, - 'uri' => 'somerandomid', + 'id' => $newId, + 'uri' => 'somerandomid', '{DAV:}displayname' => 'myCalendar', '{urn:ietf:params:xml:ns:caldav}calendar-description' => '', '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => '', '{http://calendarserver.org/ns/}getctag' => '2', ); - $this->assertInternalType('array',$calendars); - $this->assertEquals(1,count($calendars)); - - foreach($elementCheck as $name=>$value) { + $this->assertInternalType('array', $calendars); + $this->assertEquals(1, count($calendars)); + foreach ($elementCheck as $name => $value) { $this->assertArrayHasKey($name, $calendars[0]); - $this->assertEquals($value,$calendars[0][$name]); - + $this->assertEquals($value, $calendars[0][$name]); } - } /** * @depends testUpdateCalendarAndFetch */ - function testUpdateCalendarUnknownProperty() { - + public function testUpdateCalendarUnknownProperty() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); //Creating a new calendar - $newId = $backend->createCalendar('principals/user2','somerandomid',array()); + $newId = $backend->createCalendar('principals/user2', 'somerandomid', array()); // Updating the calendar - $result = $backend->updateCalendar($newId,array( + $result = $backend->updateCalendar($newId, array( '{DAV:}displayname' => 'myCalendar', - '{DAV:}yourmom' => 'wittycomment', + '{DAV:}yourmom' => 'wittycomment', )); // Verifying the result of the update @@ -117,16 +109,15 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te '403' => array('{DAV:}yourmom' => null), '424' => array('{DAV:}displayname' => null), ), $result); - } /** * @depends testCreateCalendarAndFetch */ - function testDeleteCalendar() { - + public function testDeleteCalendar() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array( + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array( '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT')), '{DAV:}displayname' => 'Hello!', )); @@ -134,29 +125,27 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te $backend->deleteCalendar($returnedId); $calendars = $backend->getCalendarsForUser('principals/user2'); - $this->assertEquals(array(),$calendars); - + $this->assertEquals(array(), $calendars); } /** * @depends testCreateCalendarAndFetch * @expectedException Sabre_DAV_Exception */ - function testCreateCalendarIncorrectComponentSet() {; - + public function testCreateCalendarIncorrectComponentSet() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); //Creating a new calendar - $newId = $backend->createCalendar('principals/user2','somerandomid',array( + $newId = $backend->createCalendar('principals/user2', 'somerandomid', array( '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => 'blabla', )); - } - function testCreateCalendarObject() { - + public function testCreateCalendarObject() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array()); + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array()); $object = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; @@ -168,34 +157,32 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te 'size' => strlen($object), 'calendardata' => $object, 'firstoccurence' => strtotime('20120101'), - 'lastoccurence' => strtotime('20120101')+(3600*24), + 'lastoccurence' => strtotime('20120101') + (3600 * 24), 'componenttype' => 'VEVENT', ), $result->fetch(PDO::FETCH_ASSOC)); - } /** * @expectedException Sabre_DAV_Exception_BadRequest * @depends testCreateCalendarObject */ - function testCreateCalendarObjectNoComponent() { - + public function testCreateCalendarObjectNoComponent() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array()); + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array()); $object = "BEGIN:VCALENDAR\r\nBEGIN:VTIMEZONE\r\nEND:VTIMEZONE\r\nEND:VCALENDAR\r\n"; $backend->createCalendarObject($returnedId, 'random-id', $object); - } /** * @depends testCreateCalendarObject */ - function testCreateCalendarObjectDuration() { - + public function testCreateCalendarObjectDuration() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array()); + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array()); $object = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE:20120101\r\nDURATION:P2D\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; @@ -207,19 +194,18 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te 'size' => strlen($object), 'calendardata' => $object, 'firstoccurence' => strtotime('20120101'), - 'lastoccurence' => strtotime('20120101')+(3600*48), + 'lastoccurence' => strtotime('20120101') + (3600 * 48), 'componenttype' => 'VEVENT', ), $result->fetch(PDO::FETCH_ASSOC)); - } /** * @depends testCreateCalendarObject */ - function testCreateCalendarObjectNoDTEND() { - + public function testCreateCalendarObjectNoDTEND() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array()); + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array()); $object = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE-TIME:20120101T100000Z\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; @@ -234,16 +220,15 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te 'lastoccurence' => strtotime('2012-01-01 10:00:00'), 'componenttype' => 'VEVENT', ), $result->fetch(PDO::FETCH_ASSOC)); - } /** * @depends testCreateCalendarObject */ - function testCreateCalendarObjectInfiniteReccurence() { - + public function testCreateCalendarObjectInfiniteReccurence() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array()); + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array()); $object = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE-TIME:20120101T100000Z\r\nRRULE:FREQ=DAILY\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; @@ -258,16 +243,15 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te 'lastoccurence' => strtotime(Sabre_CalDAV_Backend_PDO::MAX_DATE), 'componenttype' => 'VEVENT', ), $result->fetch(PDO::FETCH_ASSOC)); - } /** * @depends testCreateCalendarObject */ - function testCreateCalendarObjectEndingReccurence() { - + public function testCreateCalendarObjectEndingReccurence() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array()); + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array()); $object = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE-TIME:20120101T100000Z\r\nDTEND;VALUE=DATE-TIME:20120101T110000Z\r\nRRULE:FREQ=DAILY;COUNT=1000\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; @@ -282,16 +266,15 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te 'lastoccurence' => strtotime('2012-01-01 11:00:00') + (3600 * 24 * 999), 'componenttype' => 'VEVENT', ), $result->fetch(PDO::FETCH_ASSOC)); - } /** * @depends testCreateCalendarObject */ - function testCreateCalendarObjectTask() { - + public function testCreateCalendarObjectTask() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array()); + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array()); $object = "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nDUE;VALUE=DATE-TIME:20120101T100000Z\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"; @@ -306,73 +289,67 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te 'lastoccurence' => null, 'componenttype' => 'VTODO', ), $result->fetch(PDO::FETCH_ASSOC)); - } /** * @depends testCreateCalendarObject */ - function testGetCalendarObjects() { - + public function testGetCalendarObjects() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array()); + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array()); $object = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; $backend->createCalendarObject($returnedId, 'random-id', $object); - $data = $backend->getCalendarObjects($returnedId,'random-id'); + $data = $backend->getCalendarObjects($returnedId, 'random-id'); $this->assertEquals(1, count($data)); $data = $data[0]; $this->assertEquals($returnedId, $data['calendarid']); $this->assertEquals('random-id', $data['uri']); - $this->assertEquals(strlen($object),$data['size']); - - + $this->assertEquals(strlen($object), $data['size']); } /** * @depends testCreateCalendarObject */ - function testUpdateCalendarObject() { - + public function testUpdateCalendarObject() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array()); + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array()); $object = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; $object2 = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE:20130101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; $backend->createCalendarObject($returnedId, 'random-id', $object); $backend->updateCalendarObject($returnedId, 'random-id', $object2); - $data = $backend->getCalendarObject($returnedId,'random-id'); + $data = $backend->getCalendarObject($returnedId, 'random-id'); $this->assertEquals($object2, $data['calendardata']); $this->assertEquals($returnedId, $data['calendarid']); $this->assertEquals('random-id', $data['uri']); - - } /** * @depends testCreateCalendarObject */ - function testDeleteCalendarObject() { - + public function testDeleteCalendarObject() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $returnedId = $backend->createCalendar('principals/user2','somerandomid',array()); + $returnedId = $backend->createCalendar('principals/user2', 'somerandomid', array()); $object = "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; $backend->createCalendarObject($returnedId, 'random-id', $object); $backend->deleteCalendarObject($returnedId, 'random-id'); - $data = $backend->getCalendarObject($returnedId,'random-id'); + $data = $backend->getCalendarObject($returnedId, 'random-id'); $this->assertNull($data); - } - function testCalendarQueryNoResult() { - + public function testCalendarQueryNoResult() + { $abstract = new Sabre_CalDAV_Backend_PDO($this->pdo); $filters = array( 'name' => 'VCALENDAR', @@ -392,14 +369,13 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te $this->assertEquals(array( ), $abstract->calendarQuery(1, $filters)); - } - function testCalendarQueryTodo() { - + public function testCalendarQueryTodo() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $backend->createCalendarObject(1, "todo", "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"); - $backend->createCalendarObject(1, "event", "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); + $backend->createCalendarObject(1, 'todo', "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"); + $backend->createCalendarObject(1, 'event', "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); $filters = array( 'name' => 'VCALENDAR', @@ -418,15 +394,14 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te ); $this->assertEquals(array( - "todo", + 'todo', ), $backend->calendarQuery(1, $filters)); - } - function testCalendarQueryTodoNotMatch() { - + public function testCalendarQueryTodoNotMatch() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $backend->createCalendarObject(1, "todo", "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"); - $backend->createCalendarObject(1, "event", "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); + $backend->createCalendarObject(1, 'todo', "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"); + $backend->createCalendarObject(1, 'event', "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); $filters = array( 'name' => 'VCALENDAR', @@ -454,14 +429,13 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te $this->assertEquals(array( ), $backend->calendarQuery(1, $filters)); - } - function testCalendarQueryNoFilter() { - + public function testCalendarQueryNoFilter() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $backend->createCalendarObject(1, "todo", "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"); - $backend->createCalendarObject(1, "event", "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); + $backend->createCalendarObject(1, 'todo', "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"); + $backend->createCalendarObject(1, 'event', "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); $filters = array( 'name' => 'VCALENDAR', @@ -474,15 +448,14 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te $result = $backend->calendarQuery(1, $filters); $this->assertTrue(in_array('todo', $result)); $this->assertTrue(in_array('event', $result)); - } - function testCalendarQueryTimeRange() { - + public function testCalendarQueryTimeRange() + { $backend = new Sabre_CalDAV_Backend_PDO($this->pdo); - $backend->createCalendarObject(1, "todo", "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"); - $backend->createCalendarObject(1, "event", "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); - $backend->createCalendarObject(1, "event2", "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20120103\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); + $backend->createCalendarObject(1, 'todo', "BEGIN:VCALENDAR\r\nBEGIN:VTODO\r\nEND:VTODO\r\nEND:VCALENDAR\r\n"); + $backend->createCalendarObject(1, 'event', "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20120101\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); + $backend->createCalendarObject(1, 'event2', "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nDTSTART:20120103\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); $filters = array( 'name' => 'VCALENDAR', @@ -494,7 +467,7 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te 'is-not-defined' => false, 'time-range' => array( 'start' => new DateTime('20120103'), - 'end' => new DateTime('20120104'), + 'end' => new DateTime('20120104'), ), ), ), @@ -504,8 +477,7 @@ abstract class Sabre_CalDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_Te ); $this->assertEquals(array( - "event2", + 'event2', ), $backend->calendarQuery(1, $filters)); - } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Backend/AbstractTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Backend/AbstractTest.php index 5e393f5f..e45da69f 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Backend/AbstractTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Backend/AbstractTest.php @@ -1,16 +1,15 @@ assertEquals(false, $abstract->updateCalendar('randomid', array('{DAV:}displayname' => 'anything'))); - } - function testCalendarQuery() { - + public function testCalendarQuery() + { $abstract = new Sabre_CalDAV_Backend_AbstractMock(); $filters = array( 'name' => 'VCALENDAR', @@ -31,18 +30,22 @@ class Sabre_CalDAV_Backend_AbstractTest extends PHPUnit_Framework_TestCase { $this->assertEquals(array( 'event1.ics', ), $abstract->calendarQuery(1, $filters)); - } - } -class Sabre_CalDAV_Backend_AbstractMock extends Sabre_CalDAV_Backend_Abstract { - - function getCalendarsForUser($principalUri) { } - function createCalendar($principalUri,$calendarUri,array $properties) { } - function deleteCalendar($calendarId) { } - function getCalendarObjects($calendarId) { - +class Sabre_CalDAV_Backend_AbstractMock extends Sabre_CalDAV_Backend_Abstract +{ + public function getCalendarsForUser($principalUri) + { + } + public function createCalendar($principalUri, $calendarUri, array $properties) + { + } + public function deleteCalendar($calendarId) + { + } + public function getCalendarObjects($calendarId) + { return array( array( 'id' => 1, @@ -55,20 +58,19 @@ class Sabre_CalDAV_Backend_AbstractMock extends Sabre_CalDAV_Backend_Abstract { 'uri' => 'task1.ics', ), ); - } - function getCalendarObject($calendarId,$objectUri) { + public function getCalendarObject($calendarId, $objectUri) + { + switch ($objectUri) { - switch($objectUri) { - - case 'event1.ics' : + case 'event1.ics': return array( 'id' => 1, 'calendarid' => 1, 'uri' => 'event1.ics', 'calendardata' => "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n", ); - case 'task1.ics' : + case 'task1.ics': return array( 'id' => 1, 'calendarid' => 1, @@ -77,10 +79,14 @@ class Sabre_CalDAV_Backend_AbstractMock extends Sabre_CalDAV_Backend_Abstract { ); } - } - function createCalendarObject($calendarId,$objectUri,$calendarData) { } - function updateCalendarObject($calendarId,$objectUri,$calendarData) { } - function deleteCalendarObject($calendarId,$objectUri) { } - + public function createCalendarObject($calendarId, $objectUri, $calendarData) + { + } + public function updateCalendarObject($calendarId, $objectUri, $calendarData) + { + } + public function deleteCalendarObject($calendarId, $objectUri) + { + } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Backend/Mock.php b/dav/SabreDAV/tests/Sabre/CalDAV/Backend/Mock.php index d9a5a7a0..6b9688c7 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Backend/Mock.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Backend/Mock.php @@ -1,17 +1,16 @@ calendars = $calendars; $this->calendarData = $calendarData; $this->notifications = $notifications; - } /** @@ -29,19 +28,19 @@ class Sabre_CalDAV_Backend_Mock extends Sabre_CalDAV_Backend_Abstract implements * common one is '{DAV:}displayname'. * * @param string $principalUri + * * @return array */ - function getCalendarsForUser($principalUri) { - + public function getCalendarsForUser($principalUri) + { $r = array(); - foreach($this->calendars as $row) { + foreach ($this->calendars as $row) { if ($row['principaluri'] == $principalUri) { $r[] = $row; } } return $r; - } /** @@ -55,25 +54,25 @@ class Sabre_CalDAV_Backend_Mock extends Sabre_CalDAV_Backend_Abstract implements * * @param string $principalUri * @param string $calendarUri - * @param array $properties + * @param array $properties + * * @return string|int */ - function createCalendar($principalUri,$calendarUri,array $properties) { - + public function createCalendar($principalUri, $calendarUri, array $properties) + { $id = Sabre_DAV_UUIDUtil::getUUID(); $this->calendars[] = array_merge(array( 'id' => $id, 'principaluri' => $principalUri, 'uri' => $calendarUri, - '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT','VTODO')), + '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT', 'VTODO')), ), $properties); return $id; - } /** - * Updates properties on this node, + * Updates properties on this node,. * * The properties array uses the propertyName in clark-notation as key, * and the array value for the property value. In the case a property @@ -105,29 +104,27 @@ class Sabre_CalDAV_Backend_Mock extends Sabre_CalDAV_Backend_Abstract implements * (424 Failed Dependency) because the request needs to be atomic. * * @param string $calendarId - * @param array $properties + * @param array $properties + * * @return bool|array */ - public function updateCalendar($calendarId, array $properties) { - + public function updateCalendar($calendarId, array $properties) + { return false; - } /** - * Delete a calendar and all it's objects + * Delete a calendar and all it's objects. * * @param string $calendarId - * @return void */ - public function deleteCalendar($calendarId) { - - foreach($this->calendars as $k=>$calendar) { + public function deleteCalendar($calendarId) + { + foreach ($this->calendars as $k => $calendar) { if ($calendar['id'] === $calendarId) { unset($this->calendars[$k]); } } - } /** @@ -150,21 +147,22 @@ class Sabre_CalDAV_Backend_Mock extends Sabre_CalDAV_Backend_Abstract implements * calendardata. * * @param string $calendarId + * * @return array */ - public function getCalendarObjects($calendarId) { - - if (!isset($this->calendarData[$calendarId])) + public function getCalendarObjects($calendarId) + { + if (!isset($this->calendarData[$calendarId])) { return array(); + } $objects = $this->calendarData[$calendarId]; - foreach($objects as $uri => &$object) { + foreach ($objects as $uri => &$object) { $object['calendarid'] = $calendarId; $object['uri'] = $uri; - } - return $objects; + return $objects; } /** @@ -177,18 +175,19 @@ class Sabre_CalDAV_Backend_Mock extends Sabre_CalDAV_Backend_Abstract implements * * @param string $calendarId * @param string $objectUri + * * @return array */ - function getCalendarObject($calendarId,$objectUri) { - + public function getCalendarObject($calendarId, $objectUri) + { if (!isset($this->calendarData[$calendarId][$objectUri])) { throw new Sabre_DAV_Exception_NotFound('Object could not be found'); } $object = $this->calendarData[$calendarId][$objectUri]; $object['calendarid'] = $calendarId; $object['uri'] = $objectUri; - return $object; + return $object; } /** @@ -197,16 +196,14 @@ class Sabre_CalDAV_Backend_Mock extends Sabre_CalDAV_Backend_Abstract implements * @param string $calendarId * @param string $objectUri * @param string $calendarData - * @return void */ - function createCalendarObject($calendarId,$objectUri,$calendarData) { - + public function createCalendarObject($calendarId, $objectUri, $calendarData) + { $this->calendarData[$calendarId][$objectUri] = array( 'calendardata' => $calendarData, 'calendarid' => $calendarId, 'uri' => $objectUri, ); - } /** @@ -215,16 +212,14 @@ class Sabre_CalDAV_Backend_Mock extends Sabre_CalDAV_Backend_Abstract implements * @param string $calendarId * @param string $objectUri * @param string $calendarData - * @return void */ - function updateCalendarObject($calendarId,$objectUri,$calendarData) { - + public function updateCalendarObject($calendarId, $objectUri, $calendarData) + { $this->calendarData[$calendarId][$objectUri] = array( 'calendardata' => $calendarData, 'calendarid' => $calendarId, 'uri' => $objectUri, ); - } /** @@ -232,13 +227,10 @@ class Sabre_CalDAV_Backend_Mock extends Sabre_CalDAV_Backend_Abstract implements * * @param string $calendarId * @param string $objectUri - * @return void */ - function deleteCalendarObject($calendarId,$objectUri) { - + public function deleteCalendarObject($calendarId, $objectUri) + { throw new Exception('Not implemented'); - - } /** @@ -248,15 +240,16 @@ class Sabre_CalDAV_Backend_Mock extends Sabre_CalDAV_Backend_Abstract implements * Sabre_CalDAV_Notifications_INotificationType. * * @param string $principalUri + * * @return array */ - public function getNotificationsForPrincipal($principalUri) { - + public function getNotificationsForPrincipal($principalUri) + { if (isset($this->notifications[$principalUri])) { return $this->notifications[$principalUri]; } - return array(); + return array(); } /** @@ -264,14 +257,11 @@ class Sabre_CalDAV_Backend_Mock extends Sabre_CalDAV_Backend_Abstract implements * * This may be called by a client once it deems a notification handled. * - * @param string $principalUri + * @param string $principalUri * @param Sabre_CalDAV_Notifications_INotificationType $notification - * @return void */ - public function deleteNotification($principalUri, Sabre_CalDAV_Notifications_INotificationType $notification) { - + public function deleteNotification($principalUri, Sabre_CalDAV_Notifications_INotificationType $notification) + { throw new Sabre_DAV_Exception_NotImplemented('This doesn\'t work!'); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Backend/PDOMySQLTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Backend/PDOMySQLTest.php index 8898cdec..6c010923 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Backend/PDOMySQLTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Backend/PDOMySQLTest.php @@ -4,34 +4,36 @@ require_once 'Sabre/TestUtil.php'; require_once 'Sabre/CalDAV/TestUtil.php'; require_once 'Sabre/CalDAV/Backend/AbstractPDOTest.php'; -class Sabre_CalDAV_Backend_PDOMySQLTest extends Sabre_CalDAV_Backend_AbstractPDOTest { - - function setup() { - - if (!SABRE_HASMYSQL) $this->markTestSkipped('MySQL driver is not available, or not properly configured'); +class Sabre_CalDAV_Backend_PDOMySQLTest extends Sabre_CalDAV_Backend_AbstractPDOTest +{ + public function setup() + { + if (!SABRE_HASMYSQL) { + $this->markTestSkipped('MySQL driver is not available, or not properly configured'); + } $pdo = Sabre_TestUtil::getMySQLDB(); - if (!$pdo) $this->markTestSkipped('Could not connect to mysql database'); + if (!$pdo) { + $this->markTestSkipped('Could not connect to mysql database'); + } $pdo->query('DROP TABLE IF EXISTS calendarobjects, calendars'); $queries = explode( ';', - file_get_contents(__DIR__ . '/../../../../examples/sql/mysql.calendars.sql') + file_get_contents(__DIR__.'/../../../../examples/sql/mysql.calendars.sql') ); - foreach($queries as $query) { - $query = trim($query," \r\n\t"); - if ($query) + foreach ($queries as $query) { + $query = trim($query, " \r\n\t"); + if ($query) { $pdo->exec($query); + } } $this->pdo = $pdo; - } - function teardown() { - + public function teardown() + { $this->pdo = null; - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Backend/PDOSqliteTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Backend/PDOSqliteTest.php index 8b7045df..6d7b517f 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Backend/PDOSqliteTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Backend/PDOSqliteTest.php @@ -2,20 +2,19 @@ require_once 'Sabre/CalDAV/Backend/AbstractPDOTest.php'; -class Sabre_CalDAV_Backend_PDOSQLiteTest extends Sabre_CalDAV_Backend_AbstractPDOTest { - - function setup() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); +class Sabre_CalDAV_Backend_PDOSqliteTest extends Sabre_CalDAV_Backend_AbstractPDOTest +{ + public function setup() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $this->pdo = Sabre_CalDAV_TestUtil::getSQLiteDB(); - } - function teardown() { - + public function teardown() + { $this->pdo = null; - unlink(SABRE_TEMPDIR . '/testdb.sqlite'); - + unlink(SABRE_TEMPDIR.'/testdb.sqlite'); } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/CalendarObjectTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/CalendarObjectTest.php index 3a10a4a9..636504cc 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/CalendarObjectTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/CalendarObjectTest.php @@ -5,8 +5,8 @@ require_once 'Sabre/DAV/Auth/MockBackend.php'; require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; require_once 'Sabre/CalDAV/Backend/Mock.php'; -class Sabre_CalDAV_CalendarObjectTest extends PHPUnit_Framework_TestCase { - +class Sabre_CalDAV_CalendarObjectTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_CalDAV_Backend_PDO */ @@ -17,116 +17,109 @@ class Sabre_CalDAV_CalendarObjectTest extends PHPUnit_Framework_TestCase { protected $calendar; protected $principalBackend; - function setup() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function setup() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $this->backend = Sabre_CalDAV_TestUtil::getBackend(); - $this->principalBackend = new Sabre_DAVACL_MockPrincipalBackend; + $this->principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $calendars = $this->backend->getCalendarsForUser('principals/user1'); - $this->assertEquals(2,count($calendars)); - $this->calendar = new Sabre_CalDAV_Calendar($this->principalBackend,$this->backend, $calendars[0]); - + $this->assertEquals(2, count($calendars)); + $this->calendar = new Sabre_CalDAV_Calendar($this->principalBackend, $this->backend, $calendars[0]); } - function teardown() { - + public function teardown() + { unset($this->calendar); unset($this->backend); - } - function testSetup() { - + public function testSetup() + { $children = $this->calendar->getChildren(); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); - $this->assertInternalType('string',$children[0]->getName()); - $this->assertInternalType('string',$children[0]->get()); - $this->assertInternalType('string',$children[0]->getETag()); + $this->assertInternalType('string', $children[0]->getName()); + $this->assertInternalType('string', $children[0]->get()); + $this->assertInternalType('string', $children[0]->getETag()); $this->assertEquals('text/calendar; charset=utf-8', $children[0]->getContentType()); - } /** * @expectedException InvalidArgumentException */ - function testInvalidArg1() { - + public function testInvalidArg1() + { $obj = new Sabre_CalDAV_CalendarObject( - new Sabre_CalDAV_Backend_Mock(array(),array()), + new Sabre_CalDAV_Backend_Mock(array(), array()), array(), array() ); - } /** * @expectedException InvalidArgumentException */ - function testInvalidArg2() { - + public function testInvalidArg2() + { $obj = new Sabre_CalDAV_CalendarObject( - new Sabre_CalDAV_Backend_Mock(array(),array()), + new Sabre_CalDAV_Backend_Mock(array(), array()), array(), array('calendarid' => '1') ); - } /** * @depends testSetup */ - function testPut() { - + public function testPut() + { $children = $this->calendar->getChildren(); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); $newData = Sabre_CalDAV_TestUtil::getTestCalendarData(); $children[0]->put($newData); $this->assertEquals($newData, $children[0]->get()); - } /** * @depends testSetup */ - function testPutStream() { - + public function testPutStream() + { $children = $this->calendar->getChildren(); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); $newData = Sabre_CalDAV_TestUtil::getTestCalendarData(); - $stream = fopen('php://temp','r+'); + $stream = fopen('php://temp', 'r+'); fwrite($stream, $newData); rewind($stream); $children[0]->put($stream); $this->assertEquals($newData, $children[0]->get()); - } - /** * @depends testSetup */ - function testDelete() { - + public function testDelete() + { $children = $this->calendar->getChildren(); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); $obj = $children[0]; $obj->delete(); - $children2 = $this->calendar->getChildren(); - $this->assertEquals(count($children)-1, count($children2)); - + $children2 = $this->calendar->getChildren(); + $this->assertEquals(count($children) - 1, count($children2)); } /** * @depends testSetup */ - function testGetLastModified() { - + public function testGetLastModified() + { $children = $this->calendar->getChildren(); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); @@ -134,14 +127,13 @@ class Sabre_CalDAV_CalendarObjectTest extends PHPUnit_Framework_TestCase { $lastMod = $obj->getLastModified(); $this->assertTrue(is_int($lastMod) || ctype_digit($lastMod)); - } /** * @depends testSetup */ - function testGetSize() { - + public function testGetSize() + { $children = $this->calendar->getChildren(); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); @@ -149,31 +141,28 @@ class Sabre_CalDAV_CalendarObjectTest extends PHPUnit_Framework_TestCase { $size = $obj->getSize(); $this->assertInternalType('int', $size); - } - function testGetOwner() { - + public function testGetOwner() + { $children = $this->calendar->getChildren(); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); $obj = $children[0]; $this->assertEquals('principals/user1', $obj->getOwner()); - } - function testGetGroup() { - + public function testGetGroup() + { $children = $this->calendar->getChildren(); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); $obj = $children[0]; $this->assertNull($obj->getGroup()); - } - function testGetACL() { - + public function testGetACL() + { $expected = array( array( 'privilege' => '{DAV:}read', @@ -207,30 +196,28 @@ class Sabre_CalDAV_CalendarObjectTest extends PHPUnit_Framework_TestCase { $obj = $children[0]; $this->assertEquals($expected, $obj->getACL()); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testSetACL() { - + public function testSetACL() + { $children = $this->calendar->getChildren(); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); $obj = $children[0]; $obj->setACL(array()); - } - function testGet() { - + public function testGet() + { $children = $this->calendar->getChildren(); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); $obj = $children[0]; - $expected = "BEGIN:VCALENDAR + $expected = 'BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Apple Inc.//iCal 4.0.1//EN CALSCALE:GREGORIAN @@ -261,91 +248,83 @@ DTEND;TZID=Asia/Seoul:20100223T070000 ATTENDEE;PARTSTAT=NEEDS-ACTION:mailto:lisa@example.com SEQUENCE:2 END:VEVENT -END:VCALENDAR"; - - +END:VCALENDAR'; $this->assertEquals($expected, $obj->get()); - } - function testGetRefetch() { - + public function testGetRefetch() + { $backend = new Sabre_CalDAV_Backend_Mock(array(), array( 1 => array( 'foo' => array( 'calendardata' => 'foo', - 'uri' => 'foo' + 'uri' => 'foo', ), - ) + ), )); $obj = new Sabre_CalDAV_CalendarObject($backend, array(), array('calendarid' => 1, 'uri' => 'foo')); $this->assertEquals('foo', $obj->get()); - } - function testGetEtag1() { - + public function testGetEtag1() + { $objectInfo = array( 'calendardata' => 'foo', 'uri' => 'foo', 'etag' => 'bar', - 'calendarid' => 1 + 'calendarid' => 1, ); $backend = new Sabre_CalDAV_Backend_Mock(array(), array()); $obj = new Sabre_CalDAV_CalendarObject($backend, array(), $objectInfo); $this->assertEquals('bar', $obj->getETag()); - } - function testGetEtag2() { - + public function testGetEtag2() + { $objectInfo = array( 'calendardata' => 'foo', 'uri' => 'foo', - 'calendarid' => 1 + 'calendarid' => 1, ); $backend = new Sabre_CalDAV_Backend_Mock(array(), array()); $obj = new Sabre_CalDAV_CalendarObject($backend, array(), $objectInfo); - $this->assertEquals('"' . md5('foo') . '"', $obj->getETag()); - + $this->assertEquals('"'.md5('foo').'"', $obj->getETag()); } - function testGetSupportedPrivilegesSet() { - + public function testGetSupportedPrivilegesSet() + { $objectInfo = array( 'calendardata' => 'foo', 'uri' => 'foo', - 'calendarid' => 1 + 'calendarid' => 1, ); $backend = new Sabre_CalDAV_Backend_Mock(array(), array()); $obj = new Sabre_CalDAV_CalendarObject($backend, array(), $objectInfo); $this->assertNull($obj->getSupportedPrivilegeSet()); - } - function testGetSize1() { - + public function testGetSize1() + { $objectInfo = array( 'calendardata' => 'foo', 'uri' => 'foo', - 'calendarid' => 1 + 'calendarid' => 1, ); $backend = new Sabre_CalDAV_Backend_Mock(array(), array()); $obj = new Sabre_CalDAV_CalendarObject($backend, array(), $objectInfo); $this->assertEquals(3, $obj->getSize()); - } - function testGetSize2() { - + public function testGetSize2() + { $objectInfo = array( 'uri' => 'foo', 'calendarid' => 1, @@ -355,6 +334,5 @@ END:VCALENDAR"; $backend = new Sabre_CalDAV_Backend_Mock(array(), array()); $obj = new Sabre_CalDAV_CalendarObject($backend, array(), $objectInfo); $this->assertEquals(4, $obj->getSize()); - } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryParserTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryParserTest.php index fa373469..8969b8e7 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryParserTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryParserTest.php @@ -1,54 +1,52 @@ -' . implode("\n", $xml) . ' +' .implode("\n", $xml).' '; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); $q = new Sabre_CalDAV_CalendarQueryParser($dom); $q->parse(); - return $q->filters; + return $q->filters; } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testNoFilter() { - + public function testNoFilter() + { $xml = array(); $this->parse($xml); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testTwoCompFilter() { - + public function testTwoCompFilter() + { $xml = array( '', ' ', ' ', - '' + '', ); $this->parse($xml); - } - function testBasicFilter() { - + public function testBasicFilter() + { $xml = array( '', ' ', - '' + '', ); $result = $this->parse($xml); @@ -57,18 +55,17 @@ class Sabre_CalDAV_CalendarQueryParserTest extends PHPUnit_Framework_TestCase { 'comp-filters' => array(), 'prop-filters' => array(), 'is-not-defined' => false, - 'time-range' => false + 'time-range' => false, ); $this->assertEquals( $expected, $result ); - } - function testCompIsNotDefined() { - + public function testCompIsNotDefined() + { $xml = array( '', ' ', @@ -76,7 +73,7 @@ class Sabre_CalDAV_CalendarQueryParserTest extends PHPUnit_Framework_TestCase { ' ', ' ', ' ', - '' + '', ); $result = $this->parse($xml); @@ -88,39 +85,37 @@ class Sabre_CalDAV_CalendarQueryParserTest extends PHPUnit_Framework_TestCase { 'comp-filters' => array(), 'prop-filters' => array(), 'is-not-defined' => true, - 'time-range' => false + 'time-range' => false, ), ), 'prop-filters' => array(), 'is-not-defined' => false, - 'time-range' => false + 'time-range' => false, ); $this->assertEquals( $expected, $result ); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testCompTimeRangeOnVCALENDAR() { - + public function testCompTimeRangeOnVCALENDAR() + { $xml = array( '', ' ', ' ', ' ', - '' + '', ); $result = $this->parse($xml); - } - function testCompTimeRange() { - + public function testCompTimeRange() + { $xml = array( '', ' ', @@ -134,7 +129,7 @@ class Sabre_CalDAV_CalendarQueryParserTest extends PHPUnit_Framework_TestCase { ' ', ' ', ' ', - '' + '', ); $result = $this->parse($xml); @@ -174,21 +169,20 @@ class Sabre_CalDAV_CalendarQueryParserTest extends PHPUnit_Framework_TestCase { ), 'prop-filters' => array(), 'is-not-defined' => false, - 'time-range' => false + 'time-range' => false, ); $this->assertEquals( $expected, $result ); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testCompTimeRangeBadRange() { - + public function testCompTimeRangeBadRange() + { $xml = array( '', ' ', @@ -196,14 +190,13 @@ class Sabre_CalDAV_CalendarQueryParserTest extends PHPUnit_Framework_TestCase { ' ', ' ', ' ', - '' + '', ); $this->parse($xml); - } - function testProp() { - + public function testProp() + { $xml = array( '', ' ', @@ -213,7 +206,7 @@ class Sabre_CalDAV_CalendarQueryParserTest extends PHPUnit_Framework_TestCase { ' ', ' ', ' ', - '' + '', ); $result = $this->parse($xml); @@ -242,18 +235,17 @@ class Sabre_CalDAV_CalendarQueryParserTest extends PHPUnit_Framework_TestCase { ), 'prop-filters' => array(), 'is-not-defined' => false, - 'time-range' => false + 'time-range' => false, ); $this->assertEquals( $expected, $result ); - } - function testComplex() { - + public function testComplex() + { $xml = array( '', ' ', @@ -274,7 +266,7 @@ class Sabre_CalDAV_CalendarQueryParserTest extends PHPUnit_Framework_TestCase { ' ', ' ', ' ', - '' + '', ); $result = $this->parse($xml); @@ -337,21 +329,21 @@ class Sabre_CalDAV_CalendarQueryParserTest extends PHPUnit_Framework_TestCase { ), 'prop-filters' => array(), 'is-not-defined' => false, - 'time-range' => false + 'time-range' => false, ); $this->assertEquals( $expected, $result ); - } - function testOther1() { + public function testOther1() + { // This body was exactly sent to us from the sabredav mailing list. Checking if this parses correctly. - $body = << @@ -399,11 +391,10 @@ BLA; ); $this->assertEquals($expectedFilters, $q->filters); - } - function testExpand() { - + public function testExpand() + { $xml = array( '', ' ', @@ -412,26 +403,25 @@ BLA; '', '', ' ', - '' + '', ); $xml = ' -' . implode("\n", $xml) . ' +' .implode("\n", $xml).' '; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); $q = new Sabre_CalDAV_CalendarQueryParser($dom); $q->parse(); - $expected = array( 'name' => 'VCALENDAR', 'comp-filters' => array(), 'prop-filters' => array(), 'is-not-defined' => false, - 'time-range' => false + 'time-range' => false, ); $this->assertEquals( @@ -450,14 +440,13 @@ BLA; ), $q->expand ); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testExpandNoStart() { - + public function testExpandNoStart() + { $xml = array( '', ' ', @@ -466,25 +455,24 @@ BLA; '', '', ' ', - '' + '', ); $xml = ' -' . implode("\n", $xml) . ' +' .implode("\n", $xml).' '; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); $q = new Sabre_CalDAV_CalendarQueryParser($dom); $q->parse(); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testExpandNoEnd() { - + public function testExpandNoEnd() + { $xml = array( '', ' ', @@ -493,25 +481,24 @@ BLA; '', '', ' ', - '' + '', ); $xml = ' -' . implode("\n", $xml) . ' +' .implode("\n", $xml).' '; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); $q = new Sabre_CalDAV_CalendarQueryParser($dom); $q->parse(); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testExpandBadTimes() { - + public function testExpandBadTimes() + { $xml = array( '', ' ', @@ -520,18 +507,17 @@ BLA; '', '', ' ', - '' + '', ); $xml = ' -' . implode("\n", $xml) . ' +' .implode("\n", $xml).' '; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); $q = new Sabre_CalDAV_CalendarQueryParser($dom); $q->parse(); - } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryVAlarmTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryVAlarmTest.php index 1ee3b9a6..45ef9b27 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryVAlarmTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryVAlarmTest.php @@ -2,14 +2,14 @@ use Sabre\VObject; -class Sabre_CalDAV_CalendarQueryVAlarmTest extends PHPUnit_Framework_TestCase { - +class Sabre_CalDAV_CalendarQueryVAlarmTest extends PHPUnit_Framework_TestCase +{ /** * This test is specifically for a time-range query on a VALARM, contained - * in a VEVENT that's recurring + * in a VEVENT that's recurring. */ - function testValarm() { - + public function testValarm() + { $vevent = VObject\Component::create('VEVENT'); $vevent->RRULE = 'FREQ=MONTHLY'; $vevent->DTSTART = '20120101T120000Z'; @@ -52,7 +52,6 @@ class Sabre_CalDAV_CalendarQueryVAlarmTest extends PHPUnit_Framework_TestCase { $validator = new Sabre_CalDAV_CalendarQueryValidator(); $this->assertTrue($validator->validate($vcalendar, $filter)); - // A limited recurrence rule, should return false $vevent = VObject\Component::create('VEVENT'); $vevent->RRULE = 'FREQ=MONTHLY;COUNT=1'; @@ -69,8 +68,8 @@ class Sabre_CalDAV_CalendarQueryVAlarmTest extends PHPUnit_Framework_TestCase { $this->assertFalse($validator->validate($vcalendar, $filter)); } - function testAlarmWayBefore() { - + public function testAlarmWayBefore() + { $vevent = VObject\Component::create('VEVENT'); $vevent->DTSTART = '20120101T120000Z'; $vevent->UID = 'bla'; @@ -111,7 +110,5 @@ class Sabre_CalDAV_CalendarQueryVAlarmTest extends PHPUnit_Framework_TestCase { $validator = new Sabre_CalDAV_CalendarQueryValidator(); $this->assertTrue($validator->validate($vcalendar, $filter)); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryValidatorTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryValidatorTest.php index dede4764..bf150dc9 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryValidatorTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/CalendarQueryValidatorTest.php @@ -2,13 +2,13 @@ use Sabre\VObject; -class Sabre_CalDAV_CalendarQueryValidatorTest extends PHPUnit_Framework_TestCase { - +class Sabre_CalDAV_CalendarQueryValidatorTest extends PHPUnit_Framework_TestCase +{ /** * @dataProvider provider */ - function testValid($icalObject, $filters, $outcome) { - + public function testValid($icalObject, $filters, $outcome) + { $validator = new Sabre_CalDAV_CalendarQueryValidator(); // Wrapping filter in a VCALENDAR component filter, as this is always @@ -23,14 +23,14 @@ class Sabre_CalDAV_CalendarQueryValidatorTest extends PHPUnit_Framework_TestCase $vObject = VObject\Reader::read($icalObject); - switch($outcome) { - case 0 : + switch ($outcome) { + case 0: $this->assertFalse($validator->validate($vObject, $filters)); break; - case 1 : + case 1: $this->assertTrue($validator->validate($vObject, $filters)); break; - case -1 : + case -1: try { $validator->validate($vObject, $filters); } catch (Exception $e) { @@ -39,12 +39,11 @@ class Sabre_CalDAV_CalendarQueryValidatorTest extends PHPUnit_Framework_TestCase break; } - } - function provider() { - - $blob1 = << array( 'start' => new DateTime('2012-07-01 00:00:00', new DateTimeZone('UTC')), 'end' => new DateTime('2012-08-01 00:00:00', new DateTimeZone('UTC')), - ) + ), ); return array( @@ -754,7 +751,6 @@ yow; array($blob30, $filter31, 0), array($blob30, $filter32, 0), - // Time-range with RRULE array($blob31, $filter20, 1), array($blob32, $filter20, 0), @@ -763,7 +759,5 @@ yow; array($blob33, $filter38, 1), ); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/CalendarTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/CalendarTest.php index a2787075..6a717b28 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/CalendarTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/CalendarTest.php @@ -3,8 +3,8 @@ require_once 'Sabre/CalDAV/TestUtil.php'; require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; -class Sabre_CalDAV_CalendarTest extends PHPUnit_Framework_TestCase { - +class Sabre_CalDAV_CalendarTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_CalDAV_Backend_PDO */ @@ -19,36 +19,34 @@ class Sabre_CalDAV_CalendarTest extends PHPUnit_Framework_TestCase { */ protected $calendars; - function setup() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function setup() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $this->backend = Sabre_CalDAV_TestUtil::getBackend(); $this->principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $this->calendars = $this->backend->getCalendarsForUser('principals/user1'); $this->assertEquals(2, count($this->calendars)); $this->calendar = new Sabre_CalDAV_Calendar($this->principalBackend, $this->backend, $this->calendars[0]); - - } - function teardown() { - + public function teardown() + { unset($this->backend); - } - function testSimple() { - + public function testSimple() + { $this->assertEquals($this->calendars[0]['uri'], $this->calendar->getName()); - } /** * @depends testSimple */ - function testUpdateProperties() { - + public function testUpdateProperties() + { $result = $this->calendar->updateProperties(array( '{DAV:}displayname' => 'NewName', )); @@ -56,15 +54,14 @@ class Sabre_CalDAV_CalendarTest extends PHPUnit_Framework_TestCase { $this->assertEquals(true, $result); $calendars2 = $this->backend->getCalendarsForUser('principals/user1'); - $this->assertEquals('NewName',$calendars2[0]['{DAV:}displayname']); - + $this->assertEquals('NewName', $calendars2[0]['{DAV:}displayname']); } /** * @depends testSimple */ - function testGetProperties() { - + public function testGetProperties() + { $question = array( '{DAV:}owner', '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set', @@ -74,125 +71,115 @@ class Sabre_CalDAV_CalendarTest extends PHPUnit_Framework_TestCase { $result = $this->calendar->getProperties($question); - foreach($question as $q) $this->assertArrayHasKey($q,$result); + foreach ($question as $q) { + $this->assertArrayHasKey($q, $result); + } - $this->assertEquals(array('VEVENT','VTODO'), $result['{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set']->getValue()); + $this->assertEquals(array('VEVENT', 'VTODO'), $result['{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set']->getValue()); $this->assertTrue($result['{urn:ietf:params:xml:ns:caldav}supported-collation-set'] instanceof Sabre_CalDAV_Property_SupportedCollationSet); $this->assertTrue($result['{DAV:}owner'] instanceof Sabre_DAVACL_Property_Principal); $this->assertEquals('principals/user1', $result['{DAV:}owner']->getHref()); - } /** * @expectedException Sabre_DAV_Exception_NotFound * @depends testSimple */ - function testGetChildNotFound() { - + public function testGetChildNotFound() + { $this->calendar->getChild('randomname'); - } /** * @depends testSimple */ - function testGetChildren() { - + public function testGetChildren() + { $children = $this->calendar->getChildren(); - $this->assertEquals(1,count($children)); + $this->assertEquals(1, count($children)); $this->assertTrue($children[0] instanceof Sabre_CalDAV_CalendarObject); - } /** * @depends testGetChildren */ - function testChildExists() { - + public function testChildExists() + { $this->assertFalse($this->calendar->childExists('foo')); $children = $this->calendar->getChildren(); $this->assertTrue($this->calendar->childExists($children[0]->getName())); } - - /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testCreateDirectory() { - + public function testCreateDirectory() + { $this->calendar->createDirectory('hello'); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testSetName() { - + public function testSetName() + { $this->calendar->setName('hello'); - } - function testGetLastModified() { - + public function testGetLastModified() + { $this->assertNull($this->calendar->getLastModified()); - } - function testCreateFile() { - - $file = fopen('php://memory','r+'); - fwrite($file,Sabre_CalDAV_TestUtil::getTestCalendarData()); + public function testCreateFile() + { + $file = fopen('php://memory', 'r+'); + fwrite($file, Sabre_CalDAV_TestUtil::getTestCalendarData()); rewind($file); - $this->calendar->createFile('hello',$file); + $this->calendar->createFile('hello', $file); $file = $this->calendar->getChild('hello'); $this->assertTrue($file instanceof Sabre_CalDAV_CalendarObject); - } - function testCreateFileNoSupportedComponents() { - - $file = fopen('php://memory','r+'); - fwrite($file,Sabre_CalDAV_TestUtil::getTestCalendarData()); + public function testCreateFileNoSupportedComponents() + { + $file = fopen('php://memory', 'r+'); + fwrite($file, Sabre_CalDAV_TestUtil::getTestCalendarData()); rewind($file); $calendar = new Sabre_CalDAV_Calendar($this->principalBackend, $this->backend, $this->calendars[1]); - $calendar->createFile('hello',$file); + $calendar->createFile('hello', $file); $file = $calendar->getChild('hello'); $this->assertTrue($file instanceof Sabre_CalDAV_CalendarObject); - } - function testDelete() { - + public function testDelete() + { $this->calendar->delete(); $calendars = $this->backend->getCalendarsForUser('principals/user1'); $this->assertEquals(1, count($calendars)); } - function testGetOwner() { - - $this->assertEquals('principals/user1',$this->calendar->getOwner()); - + public function testGetOwner() + { + $this->assertEquals('principals/user1', $this->calendar->getOwner()); } - function testGetGroup() { - + public function testGetGroup() + { $this->assertNull($this->calendar->getGroup()); - } - function testGetACL() { - + public function testGetACL() + { $expected = array( array( 'privilege' => '{DAV:}read', @@ -220,34 +207,29 @@ class Sabre_CalDAV_CalendarTest extends PHPUnit_Framework_TestCase { 'protected' => true, ), array( - 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy', + 'privilege' => '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}read-free-busy', 'principal' => '{DAV:}authenticated', 'protected' => true, ), ); $this->assertEquals($expected, $this->calendar->getACL()); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testSetACL() { - + public function testSetACL() + { $this->calendar->setACL(array()); - } - function testGetSupportedPrivilegesSet() { - + public function testGetSupportedPrivilegesSet() + { $result = $this->calendar->getSupportedPrivilegeSet(); $this->assertEquals( - '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy', + '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}read-free-busy', $result['aggregates'][0]['aggregates'][2]['privilege'] ); - } - - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDTSTARTandDTENDTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDTSTARTandDTENDTest.php index 444dc496..7c76a611 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDTSTARTandDTENDTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDTSTARTandDTENDTest.php @@ -3,15 +3,15 @@ use Sabre\VObject; /** - * This unittests is created to find out why recurring events have wrong DTSTART value + * This unittests is created to find out why recurring events have wrong DTSTART value. * * - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_ExpandEventsDTSTARTandDTENDTest extends Sabre_DAVServerTest { - +class Sabre_CalDAV_ExpandEventsDTSTARTandDTENDTest extends Sabre_DAVServerTest +{ protected $setupCalDAV = true; protected $caldavCalendars = array( @@ -20,7 +20,7 @@ class Sabre_CalDAV_ExpandEventsDTSTARTandDTENDTest extends Sabre_DAVServerTest { 'name' => 'Calendar', 'principaluri' => 'principals/user1', 'uri' => 'calendar1', - ) + ), ); protected $caldavCalendarObjects = array( @@ -49,8 +49,8 @@ END:VCALENDAR ), ); - function testExpand() { - + public function testExpand() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'HTTP_CONTENT_TYPE' => 'application/xml', @@ -83,7 +83,7 @@ END:VCALENDAR $start = strpos($response->body, 'BEGIN:VCALENDAR'), strpos($response->body, 'END:VCALENDAR') - $start + 13 ); - $body = str_replace(' ','',$body); + $body = str_replace(' ', '', $body); $vObject = VObject\Reader::read($body); @@ -92,7 +92,6 @@ END:VCALENDAR /** @var $vevent Sabre\VObject\Component_VEvent */ foreach ($vevent->children as $child) { /** @var $child Sabre\VObject\Property */ - if ($child->name == 'DTSTART') { // DTSTART has to be one of three valid values $this->assertContains($child->value, array('20120207T171500Z', '20120208T171500Z', '20120209T171500Z'), 'DTSTART is not a valid value: '.$child->value); @@ -103,6 +102,4 @@ END:VCALENDAR } } } - } - diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDTSTARTandDTENDbyDayTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDTSTARTandDTENDbyDayTest.php index a183082b..af6dda64 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDTSTARTandDTENDbyDayTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDTSTARTandDTENDbyDayTest.php @@ -3,15 +3,15 @@ use Sabre\VObject; /** - * This unittests is created to find out why recurring events have wrong DTSTART value + * This unittests is created to find out why recurring events have wrong DTSTART value. * * - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_ExpandEventsDTSTARTandDTENDbyDayTest extends Sabre_DAVServerTest { - +class Sabre_CalDAV_ExpandEventsDTSTARTandDTENDbyDayTest extends Sabre_DAVServerTest +{ protected $setupCalDAV = true; protected $caldavCalendars = array( @@ -20,7 +20,7 @@ class Sabre_CalDAV_ExpandEventsDTSTARTandDTENDbyDayTest extends Sabre_DAVServerT 'name' => 'Calendar', 'principaluri' => 'principals/user1', 'uri' => 'calendar1', - ) + ), ); protected $caldavCalendarObjects = array( @@ -41,8 +41,8 @@ END:VCALENDAR ), ); - function testExpandRecurringByDayEvent() { - + public function testExpandRecurringByDayEvent() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'HTTP_CONTENT_TYPE' => 'application/xml', @@ -75,7 +75,7 @@ END:VCALENDAR $start = strpos($response->body, 'BEGIN:VCALENDAR'), strpos($response->body, 'END:VCALENDAR') - $start + 13 ); - $body = str_replace(' ','',$body); + $body = str_replace(' ', '', $body); $vObject = VObject\Reader::read($body); @@ -86,7 +86,6 @@ END:VCALENDAR /** @var $vevent Sabre\VObject\Component\VEvent */ foreach ($vevent->children as $child) { /** @var $child Sabre\VObject\Property */ - if ($child->name == 'DTSTART') { // DTSTART has to be one of two valid values $this->assertContains($child->value, array('20120214T171500Z', '20120216T171500Z'), 'DTSTART is not a valid value: '.$child->value); @@ -97,6 +96,4 @@ END:VCALENDAR } } } - } - diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDoubleEventsTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDoubleEventsTest.php index 087c384f..20513169 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDoubleEventsTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/ExpandEventsDoubleEventsTest.php @@ -8,12 +8,12 @@ use Sabre\VObject; * Hopefully, by the time I'm done with this, I've both found the problem, and * fixed it :) * - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_ExpandEventsDoubleEventsTest extends Sabre_DAVServerTest { - +class Sabre_CalDAV_ExpandEventsDoubleEventsTest extends Sabre_DAVServerTest +{ protected $setupCalDAV = true; protected $caldavCalendars = array( @@ -22,7 +22,7 @@ class Sabre_CalDAV_ExpandEventsDoubleEventsTest extends Sabre_DAVServerTest { 'name' => 'Calendar', 'principaluri' => 'principals/user1', 'uri' => 'calendar1', - ) + ), ); protected $caldavCalendarObjects = array( @@ -51,8 +51,8 @@ END:VCALENDAR ), ); - function testExpand() { - + public function testExpand() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'HTTP_CONTENT_TYPE' => 'application/xml', @@ -85,17 +85,14 @@ END:VCALENDAR $start = strpos($response->body, 'BEGIN:VCALENDAR'), strpos($response->body, 'END:VCALENDAR') - $start + 13 ); - $body = str_replace(' ','',$body); + $body = str_replace(' ', '', $body); $vObject = VObject\Reader::read($body); // We only expect 3 events - $this->assertEquals(3, count($vObject->VEVENT),'We got 6 events instead of 3. Output: ' . $body); + $this->assertEquals(3, count($vObject->VEVENT), 'We got 6 events instead of 3. Output: '.$body); // TZID should be gone $this->assertFalse(isset($vObject->VEVENT->DTSTART['TZID'])); - } - } - diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/FreeBusyReportTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/FreeBusyReportTest.php index 3ccefdf4..60966993 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/FreeBusyReportTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/FreeBusyReportTest.php @@ -4,8 +4,8 @@ require_once 'Sabre/CalDAV/Backend/Mock.php'; require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_CalDAV_FreeBusyReportTest extends PHPUnit_Framework_TestCase { - +class Sabre_CalDAV_FreeBusyReportTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_CalDAV_Plugin */ @@ -15,9 +15,9 @@ class Sabre_CalDAV_FreeBusyReportTest extends PHPUnit_Framework_TestCase { */ protected $server; - function setUp() { - - $obj1 = << array( 'calendarid' => 1, 'uri' => 'event2.ics', - 'calendardata' => $obj2 - ) + 'calendardata' => $obj2, + ), ), ); - $caldavBackend = new Sabre_CalDAV_Backend_Mock(array(), $calendarData); $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); - $calendar = new Sabre_CalDAV_Calendar($principalBackend,$caldavBackend, array( + $calendar = new Sabre_CalDAV_Calendar($principalBackend, $caldavBackend, array( 'id' => 1, 'uri' => 'calendar', 'principaluri' => 'principals/user1', @@ -73,12 +72,11 @@ ics $this->plugin = new Sabre_CalDAV_Plugin(); $this->server->addPlugin($this->plugin); $this->server->addPlugin(new Sabre_DAVACL_Plugin()); - } - function testFreeBusyReport() { - - $reportXML = << @@ -90,16 +88,15 @@ XML; $this->assertEquals('HTTP/1.1 200 OK', $this->server->httpResponse->status); $this->assertEquals('text/calendar', $this->server->httpResponse->headers['Content-Type']); - $this->assertTrue(strpos($this->server->httpResponse->body,'BEGIN:VFREEBUSY')!==false); - + $this->assertTrue(strpos($this->server->httpResponse->body, 'BEGIN:VFREEBUSY') !== false); } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testFreeBusyReportNoTimeRange() { - - $reportXML = << @@ -107,20 +104,19 @@ XML; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($reportXML); $this->plugin->report('{urn:ietf:params:xml:ns:caldav}free-busy-query', $dom); - } /** * @expectedException Sabre_DAV_Exception_NotImplemented */ - function testFreeBusyReportWrongNode() { - + public function testFreeBusyReportWrongNode() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_URI' => '/', )); $this->server->httpRequest = $request; - $reportXML = << @@ -129,19 +125,18 @@ XML; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($reportXML); $this->plugin->report('{urn:ietf:params:xml:ns:caldav}free-busy-query', $dom); - } /** * @expectedException Sabre_DAV_Exception */ - function testFreeBusyReportNoACLPlugin() { - + public function testFreeBusyReportNoACLPlugin() + { $this->server = new Sabre_DAV_Server(); $this->plugin = new Sabre_CalDAV_Plugin(); $this->server->addPlugin($this->plugin); - $reportXML = << @@ -150,6 +145,5 @@ XML; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($reportXML); $this->plugin->report('{urn:ietf:params:xml:ns:caldav}free-busy-query', $dom); - } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/GetEventsByTimerangeTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/GetEventsByTimerangeTest.php index d9a6d586..e2286ef9 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/GetEventsByTimerangeTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/GetEventsByTimerangeTest.php @@ -3,15 +3,15 @@ use Sabre\VObject; /** - * This unittest is created to check if queries for time-range include the start timestamp or not + * This unittest is created to check if queries for time-range include the start timestamp or not. * * - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_GetEventsByTimerangeTest extends Sabre_DAVServerTest { - +class Sabre_CalDAV_GetEventsByTimerangeTest extends Sabre_DAVServerTest +{ protected $setupCalDAV = true; protected $caldavCalendars = array( @@ -20,7 +20,7 @@ class Sabre_CalDAV_GetEventsByTimerangeTest extends Sabre_DAVServerTest { 'name' => 'Calendar', 'principaluri' => 'principals/user1', 'uri' => 'calendar1', - ) + ), ); protected $caldavCalendarObjects = array( @@ -44,8 +44,8 @@ END:VCALENDAR ), ); - function testQueryTimerange() { - + public function testQueryTimerange() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'HTTP_CONTENT_TYPE' => 'application/xml', @@ -82,14 +82,11 @@ END:VCALENDAR $start = strpos($response->body, 'BEGIN:VCALENDAR'), strpos($response->body, 'END:VCALENDAR') - $start + 13 ); - $body = str_replace(' ','',$body); + $body = str_replace(' ', '', $body); $vObject = VObject\Reader::read($body); // We expect 1 event - $this->assertEquals(1, count($vObject->VEVENT), 'We got 0 events instead of 1. Output: ' . $body); - + $this->assertEquals(1, count($vObject->VEVENT), 'We got 0 events instead of 1. Output: '.$body); } - } - diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/ICSExportPluginTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/ICSExportPluginTest.php index c569da8f..632d7cb8 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/ICSExportPluginTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/ICSExportPluginTest.php @@ -6,29 +6,30 @@ require_once 'Sabre/CalDAV/TestUtil.php'; require_once 'Sabre/DAV/Auth/MockBackend.php'; require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_CalDAV_ICSExportPluginTest extends PHPUnit_Framework_TestCase { - - function testInit() { - +class Sabre_CalDAV_ICSExportPluginTest extends PHPUnit_Framework_TestCase +{ + public function testInit() + { $p = new Sabre_CalDAV_ICSExportPlugin(); $s = new Sabre_DAV_Server(); $s->addPlugin($p); - } - function testBeforeMethod() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function testBeforeMethod() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $cbackend = Sabre_CalDAV_TestUtil::getBackend(); $pbackend = new Sabre_DAVACL_MockPrincipalBackend(); $props = array( - 'uri'=>'UUID-123467', + 'uri' => 'UUID-123467', 'principaluri' => 'admin', 'id' => 1, ); $tree = array( - new Sabre_CalDAV_Calendar($pbackend,$cbackend,$props), + new Sabre_CalDAV_Calendar($pbackend, $cbackend, $props), ); $p = new Sabre_CalDAV_ICSExportPlugin(); @@ -44,37 +45,38 @@ class Sabre_CalDAV_ICSExportPluginTest extends PHPUnit_Framework_TestCase { $s->httpRequest = $h; $s->httpResponse = new Sabre_HTTP_ResponseMock(); - $this->assertFalse($p->beforeMethod('GET','UUID-123467?export')); + $this->assertFalse($p->beforeMethod('GET', 'UUID-123467?export')); - $this->assertEquals('HTTP/1.1 200 OK',$s->httpResponse->status); + $this->assertEquals('HTTP/1.1 200 OK', $s->httpResponse->status); $this->assertEquals(array( 'Content-Type' => 'text/calendar', ), $s->httpResponse->headers); $obj = VObject\Reader::read($s->httpResponse->body); - $this->assertEquals(5,count($obj->children())); - $this->assertEquals(1,count($obj->VERSION)); - $this->assertEquals(1,count($obj->CALSCALE)); - $this->assertEquals(1,count($obj->PRODID)); - $this->assertTrue(strpos((string)$obj->PRODID, Sabre_DAV_Version::VERSION)!==false); - $this->assertEquals(1,count($obj->VTIMEZONE)); - $this->assertEquals(1,count($obj->VEVENT)); - + $this->assertEquals(5, count($obj->children())); + $this->assertEquals(1, count($obj->VERSION)); + $this->assertEquals(1, count($obj->CALSCALE)); + $this->assertEquals(1, count($obj->PRODID)); + $this->assertTrue(strpos((string) $obj->PRODID, Sabre_DAV_Version::VERSION) !== false); + $this->assertEquals(1, count($obj->VTIMEZONE)); + $this->assertEquals(1, count($obj->VEVENT)); } - function testBeforeMethodNoVersion() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function testBeforeMethodNoVersion() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $cbackend = Sabre_CalDAV_TestUtil::getBackend(); $pbackend = new Sabre_DAVACL_MockPrincipalBackend(); $props = array( - 'uri'=>'UUID-123467', + 'uri' => 'UUID-123467', 'principaluri' => 'admin', 'id' => 1, ); $tree = array( - new Sabre_CalDAV_Calendar($pbackend,$cbackend,$props), + new Sabre_CalDAV_Calendar($pbackend, $cbackend, $props), ); $p = new Sabre_CalDAV_ICSExportPlugin(); @@ -92,64 +94,63 @@ class Sabre_CalDAV_ICSExportPluginTest extends PHPUnit_Framework_TestCase { $s->httpResponse = new Sabre_HTTP_ResponseMock(); Sabre_DAV_Server::$exposeVersion = false; - $this->assertFalse($p->beforeMethod('GET','UUID-123467?export')); - Sabre_DAV_Server::$exposeVersion = true; + $this->assertFalse($p->beforeMethod('GET', 'UUID-123467?export')); + Sabre_DAV_Server::$exposeVersion = true; - $this->assertEquals('HTTP/1.1 200 OK',$s->httpResponse->status); + $this->assertEquals('HTTP/1.1 200 OK', $s->httpResponse->status); $this->assertEquals(array( 'Content-Type' => 'text/calendar', ), $s->httpResponse->headers); $obj = VObject\Reader::read($s->httpResponse->body); - $this->assertEquals(5,count($obj->children())); - $this->assertEquals(1,count($obj->VERSION)); - $this->assertEquals(1,count($obj->CALSCALE)); - $this->assertEquals(1,count($obj->PRODID)); - $this->assertFalse(strpos((string)$obj->PRODID, Sabre_DAV_Version::VERSION)!==false); - $this->assertEquals(1,count($obj->VTIMEZONE)); - $this->assertEquals(1,count($obj->VEVENT)); - + $this->assertEquals(5, count($obj->children())); + $this->assertEquals(1, count($obj->VERSION)); + $this->assertEquals(1, count($obj->CALSCALE)); + $this->assertEquals(1, count($obj->PRODID)); + $this->assertFalse(strpos((string) $obj->PRODID, Sabre_DAV_Version::VERSION) !== false); + $this->assertEquals(1, count($obj->VTIMEZONE)); + $this->assertEquals(1, count($obj->VEVENT)); } - function testBeforeMethodNoGET() { - + public function testBeforeMethodNoGET() + { $p = new Sabre_CalDAV_ICSExportPlugin(); $s = new Sabre_DAV_Server(); $s->addPlugin($p); - $this->assertNull($p->beforeMethod('POST','UUID-123467?export')); - + $this->assertNull($p->beforeMethod('POST', 'UUID-123467?export')); } - function testBeforeMethodNoExport() { - + public function testBeforeMethodNoExport() + { $p = new Sabre_CalDAV_ICSExportPlugin(); $s = new Sabre_DAV_Server(); $s->addPlugin($p); - $this->assertNull($p->beforeMethod('GET','UUID-123467')); - + $this->assertNull($p->beforeMethod('GET', 'UUID-123467')); } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testACLIntegrationBlocked() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function testACLIntegrationBlocked() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $cbackend = Sabre_CalDAV_TestUtil::getBackend(); $pbackend = new Sabre_DAVACL_MockPrincipalBackend(); $props = array( - 'uri'=>'UUID-123467', + 'uri' => 'UUID-123467', 'principaluri' => 'admin', 'id' => 1, ); $tree = array( - new Sabre_CalDAV_Calendar($pbackend,$cbackend,$props), + new Sabre_CalDAV_Calendar($pbackend, $cbackend, $props), ); $p = new Sabre_CalDAV_ICSExportPlugin(); @@ -166,23 +167,24 @@ class Sabre_CalDAV_ICSExportPluginTest extends PHPUnit_Framework_TestCase { $s->httpRequest = $h; $s->httpResponse = new Sabre_HTTP_ResponseMock(); - $p->beforeMethod('GET','UUID-123467?export'); - + $p->beforeMethod('GET', 'UUID-123467?export'); } - function testACLIntegrationNotBlocked() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function testACLIntegrationNotBlocked() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $cbackend = Sabre_CalDAV_TestUtil::getBackend(); $pbackend = new Sabre_DAVACL_MockPrincipalBackend(); $props = array( - 'uri'=>'UUID-123467', + 'uri' => 'UUID-123467', 'principaluri' => 'admin', 'id' => 1, ); $tree = array( - new Sabre_CalDAV_Calendar($pbackend,$cbackend,$props), + new Sabre_CalDAV_Calendar($pbackend, $cbackend, $props), new Sabre_DAVACL_PrincipalCollection($pbackend), ); @@ -192,7 +194,7 @@ class Sabre_CalDAV_ICSExportPluginTest extends PHPUnit_Framework_TestCase { $s->addPlugin($p); $s->addPlugin(new Sabre_CalDAV_Plugin()); $s->addPlugin(new Sabre_DAVACL_Plugin()); - $s->addPlugin(new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'SabreDAV')); + $s->addPlugin(new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'SabreDAV')); // Forcing login $s->getPlugin('acl')->adminPrincipals = array('principals/admin'); @@ -208,19 +210,18 @@ class Sabre_CalDAV_ICSExportPluginTest extends PHPUnit_Framework_TestCase { $s->exec(); - $this->assertEquals('HTTP/1.1 200 OK',$s->httpResponse->status,'Invalid status received. Response body: '. $s->httpResponse->body); + $this->assertEquals('HTTP/1.1 200 OK', $s->httpResponse->status, 'Invalid status received. Response body: '.$s->httpResponse->body); $this->assertEquals(array( 'Content-Type' => 'text/calendar', ), $s->httpResponse->headers); $obj = VObject\Reader::read($s->httpResponse->body); - $this->assertEquals(5,count($obj->children())); - $this->assertEquals(1,count($obj->VERSION)); - $this->assertEquals(1,count($obj->CALSCALE)); - $this->assertEquals(1,count($obj->PRODID)); - $this->assertEquals(1,count($obj->VTIMEZONE)); - $this->assertEquals(1,count($obj->VEVENT)); - + $this->assertEquals(5, count($obj->children())); + $this->assertEquals(1, count($obj->VERSION)); + $this->assertEquals(1, count($obj->CALSCALE)); + $this->assertEquals(1, count($obj->PRODID)); + $this->assertEquals(1, count($obj->VTIMEZONE)); + $this->assertEquals(1, count($obj->VEVENT)); } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Issue166Test.php b/dav/SabreDAV/tests/Sabre/CalDAV/Issue166Test.php index 11d2f21c..b3d3ed0c 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Issue166Test.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Issue166Test.php @@ -2,11 +2,11 @@ use Sabre\VObject; -class Sabre_CalDAV_Issue166Test extends PHPUnit_Framework_TestCase { - - function testFlaw() { - - $input = << false, 'time-range' => array( 'start' => new DateTime('2011-12-01'), - 'end' => new DateTime('2012-02-01'), + 'end' => new DateTime('2012-02-01'), ), ), ), @@ -54,8 +54,6 @@ HI; 'time-range' => null, ); $input = VObject\Reader::read($input); - $this->assertTrue($validator->validate($input,$filters)); - + $this->assertTrue($validator->validate($input, $filters)); } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Issue172Test.php b/dav/SabreDAV/tests/Sabre/CalDAV/Issue172Test.php index 90e13fd8..b32079b0 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Issue172Test.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Issue172Test.php @@ -2,11 +2,12 @@ use Sabre\VObject; -class Sabre_CalDAV_Issue172Test extends PHPUnit_Framework_TestCase { - +class Sabre_CalDAV_Issue172Test extends PHPUnit_Framework_TestCase +{ // DateTimeZone() native name: America/Los_Angeles (GMT-8 in January) - function testBuiltInTimezoneName() { - $input = << false, 'time-range' => array( 'start' => new DateTime('2012-01-18 21:00:00 GMT-08:00'), - 'end' => new DateTime('2012-01-18 21:00:00 GMT-08:00'), + 'end' => new DateTime('2012-01-18 21:00:00 GMT-08:00'), ), ), ), 'prop-filters' => array(), ); $input = VObject\Reader::read($input); - $this->assertTrue($validator->validate($input,$filters)); + $this->assertTrue($validator->validate($input, $filters)); } // Pacific Standard Time, translates to America/Los_Angeles (GMT-8 in January) - function testOutlookTimezoneName() { - $input = << false, 'time-range' => array( 'start' => new DateTime('2012-01-13 10:30:00 GMT-08:00'), - 'end' => new DateTime('2012-01-13 10:30:00 GMT-08:00'), + 'end' => new DateTime('2012-01-13 10:30:00 GMT-08:00'), ), ), ), 'prop-filters' => array(), ); $input = VObject\Reader::read($input); - $this->assertTrue($validator->validate($input,$filters)); + $this->assertTrue($validator->validate($input, $filters)); } // X-LIC-LOCATION, translates to America/Los_Angeles (GMT-8 in January) - function testLibICalLocationName() { - $input = << false, 'time-range' => array( 'start' => new DateTime('2012-01-13 10:30:00 GMT-08:00'), - 'end' => new DateTime('2012-01-13 10:30:00 GMT-08:00'), + 'end' => new DateTime('2012-01-13 10:30:00 GMT-08:00'), ), ), ), 'prop-filters' => array(), ); $input = VObject\Reader::read($input); - $this->assertTrue($validator->validate($input,$filters)); + $this->assertTrue($validator->validate($input, $filters)); } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Issue203Test.php b/dav/SabreDAV/tests/Sabre/CalDAV/Issue203Test.php index 4cb8eec9..42ded05b 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Issue203Test.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Issue203Test.php @@ -3,15 +3,15 @@ use Sabre\VObject; /** - * This unittest is created to find out why an overwritten DAILY event has wrong DTSTART, DTEND, SUMMARY and RECURRENCEID + * This unittest is created to find out why an overwritten DAILY event has wrong DTSTART, DTEND, SUMMARY and RECURRENCEID. * * - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_Issue203Test extends Sabre_DAVServerTest { - +class Sabre_CalDAV_Issue203Test extends Sabre_DAVServerTest +{ protected $setupCalDAV = true; protected $caldavCalendars = array( @@ -20,7 +20,7 @@ class Sabre_CalDAV_Issue203Test extends Sabre_DAVServerTest { 'name' => 'Calendar', 'principaluri' => 'principals/user1', 'uri' => 'calendar1', - ) + ), ); protected $caldavCalendarObjects = array( @@ -54,8 +54,8 @@ END:VCALENDAR ), ); - function testIssue203() { - + public function testIssue203() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'HTTP_CONTENT_TYPE' => 'application/xml', @@ -88,38 +88,34 @@ END:VCALENDAR $start = strpos($response->body, 'BEGIN:VCALENDAR'), strpos($response->body, 'END:VCALENDAR') - $start + 13 ); - $body = str_replace(' ','',$body); + $body = str_replace(' ', '', $body); $vObject = VObject\Reader::read($body); $this->assertEquals(2, count($vObject->VEVENT)); - $expectedEvents = array( array( 'DTSTART' => '20120326T135200Z', - 'DTEND' => '20120326T145200Z', + 'DTEND' => '20120326T145200Z', 'SUMMARY' => 'original summary', ), array( - 'DTSTART' => '20120328T135200Z', - 'DTEND' => '20120328T145200Z', - 'SUMMARY' => 'overwritten summary', + 'DTSTART' => '20120328T135200Z', + 'DTEND' => '20120328T145200Z', + 'SUMMARY' => 'overwritten summary', 'RECURRENCE-ID' => '20120327T135200Z', - ) + ), ); // try to match agains $expectedEvents array foreach ($expectedEvents as $expectedEvent) { - $matching = false; foreach ($vObject->VEVENT as $vevent) { /** @var $vevent Sabre\VObject\Component\VEvent */ - foreach ($vevent->children as $child) { /** @var $child Sabre\VObject\Property */ - if (isset($expectedEvent[$child->name])) { if ($expectedEvent[$child->name] != $child->value) { continue 2; diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Issue205Test.php b/dav/SabreDAV/tests/Sabre/CalDAV/Issue205Test.php index 6e9e497c..b07b30a9 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Issue205Test.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Issue205Test.php @@ -3,15 +3,15 @@ use Sabre\VObject; /** - * This unittest is created to check if a VALARM TRIGGER of PT0S is supported + * This unittest is created to check if a VALARM TRIGGER of PT0S is supported. * * - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_Issue205Test extends Sabre_DAVServerTest { - +class Sabre_CalDAV_Issue205Test extends Sabre_DAVServerTest +{ protected $setupCalDAV = true; protected $caldavCalendars = array( @@ -20,7 +20,7 @@ class Sabre_CalDAV_Issue205Test extends Sabre_DAVServerTest { 'name' => 'Calendar', 'principaluri' => 'principals/user1', 'uri' => 'calendar1', - ) + ), ); protected $caldavCalendarObjects = array( @@ -47,8 +47,8 @@ END:VCALENDAR ), ); - function testIssue205() { - + public function testIssue205() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'HTTP_CONTENT_TYPE' => 'application/xml', @@ -77,8 +77,8 @@ END:VCALENDAR $response = $this->request($request); - $this->assertFalse(strpos($response->body, 'Exception'), 'Exception occurred: ' . $response->body); - $this->assertFalse(strpos($response->body, 'Unknown or bad format'), 'DateTime unknown format Exception: ' . $response->body); + $this->assertFalse(strpos($response->body, 'Exception'), 'Exception occurred: '.$response->body); + $this->assertFalse(strpos($response->body, 'Unknown or bad format'), 'DateTime unknown format Exception: '.$response->body); // Everts super awesome xml parser. $body = substr( @@ -86,11 +86,10 @@ END:VCALENDAR $start = strpos($response->body, 'BEGIN:VCALENDAR'), strpos($response->body, 'END:VCALENDAR') - $start + 13 ); - $body = str_replace(' ','',$body); + $body = str_replace(' ', '', $body); $vObject = VObject\Reader::read($body); $this->assertEquals(1, count($vObject->VEVENT)); - } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Issue211Test.php b/dav/SabreDAV/tests/Sabre/CalDAV/Issue211Test.php index b48ad604..e9b564b0 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Issue211Test.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Issue211Test.php @@ -1,15 +1,15 @@ 'Calendar', 'principaluri' => 'principals/user1', 'uri' => 'calendar1', - ) + ), ); protected $caldavCalendarObjects = array( @@ -50,8 +50,8 @@ END:VCALENDAR ), ); - function testIssue211() { - + public function testIssue211() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'HTTP_CONTENT_TYPE' => 'application/xml', @@ -81,6 +81,5 @@ END:VCALENDAR // if this assert is reached, the endless loop is gone // There should be no matching events $this->assertFalse(strpos('BEGIN:VEVENT', $response->body)); - } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Issue220Test.php b/dav/SabreDAV/tests/Sabre/CalDAV/Issue220Test.php index f4f87535..6a9b6580 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Issue220Test.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Issue220Test.php @@ -1,15 +1,15 @@ 'Calendar', 'principaluri' => 'principals/user1', 'uri' => 'calendar1', - ) + ), ); protected $caldavCalendarObjects = array( @@ -60,8 +60,8 @@ END:VCALENDAR ), ); - function testIssue220() { - + public function testIssue220() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'HTTP_CONTENT_TYPE' => 'application/xml', @@ -88,8 +88,8 @@ END:VCALENDAR $response = $this->request($request); - $this->assertFalse(strpos($response->body, 'PHPUnit_Framework_Error_Warning'), 'Error Warning occurred: ' . $response->body); - $this->assertFalse(strpos($response->body, 'Invalid argument supplied for foreach()'), 'Invalid argument supplied for foreach(): ' . $response->body); + $this->assertFalse(strpos($response->body, 'PHPUnit_Framework_Error_Warning'), 'Error Warning occurred: '.$response->body); + $this->assertFalse(strpos($response->body, 'Invalid argument supplied for foreach()'), 'Invalid argument supplied for foreach(): '.$response->body); $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status); } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Issue228Test.php b/dav/SabreDAV/tests/Sabre/CalDAV/Issue228Test.php index f251ab13..799b681d 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Issue228Test.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Issue228Test.php @@ -1,14 +1,14 @@ 'Calendar', 'principaluri' => 'principals/user1', 'uri' => 'calendar1', - ) + ), ); protected $caldavCalendarObjects = array( @@ -39,8 +39,8 @@ END:VCALENDAR ), ); - function testIssue228() { - + public function testIssue228() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'HTTP_CONTENT_TYPE' => 'application/xml', @@ -70,6 +70,5 @@ END:VCALENDAR // We must check if absolutely nothing was returned from this query. $this->assertFalse(strpos($response->body, 'BEGIN:VCALENDAR')); - } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/CollectionTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/CollectionTest.php index 1d396d6d..5ae76982 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/CollectionTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/CollectionTest.php @@ -1,27 +1,24 @@ array( - $systemStatus - ) - )); - + $systemStatus, + ), + )); $col = new Sabre_CalDAV_Notifications_Collection($caldavBackend, $principalUri); $this->assertEquals('notifications', $col->getName()); $this->assertEquals(array( - new Sabre_CalDAV_Notifications_Node($caldavBackend, $systemStatus) - ), $col->getChildren()); - + new Sabre_CalDAV_Notifications_Node($caldavBackend, $systemStatus), + ), $col->getChildren()); } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/NodeTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/NodeTest.php index dba636e9..e5c722db 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/NodeTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/NodeTest.php @@ -1,23 +1,20 @@ array( - $systemStatus - ) - )); - + $systemStatus, + ), + )); $node = new Sabre_CalDAV_Notifications_Node($caldavBackend, $systemStatus); $this->assertEquals($systemStatus->getId(), $node->getName()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/Notification/SystemStatusTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/Notification/SystemStatusTest.php index ddaf5ce4..fe73dd66 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/Notification/SystemStatusTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Notifications/Notification/SystemStatusTest.php @@ -1,55 +1,50 @@ assertEquals('foo', $notification->getId()); - - $dom = new DOMDocument('1.0','UTF-8'); + $dom = new DOMDocument('1.0', 'UTF-8'); $elem = $dom->createElement('cs:root'); - $elem->setAttribute('xmlns:cs',Sabre_CalDAV_Plugin::NS_CALENDARSERVER); + $elem->setAttribute('xmlns:cs', Sabre_CalDAV_Plugin::NS_CALENDARSERVER); $dom->appendChild($elem); $notification->serialize(new Sabre_DAV_Server(), $elem); $this->assertEquals($expected1, $dom->saveXML()); - $dom = new DOMDocument('1.0','UTF-8'); + $dom = new DOMDocument('1.0', 'UTF-8'); $elem = $dom->createElement('cs:root'); - $elem->setAttribute('xmlns:cs',Sabre_CalDAV_Plugin::NS_CALENDARSERVER); + $elem->setAttribute('xmlns:cs', Sabre_CalDAV_Plugin::NS_CALENDARSERVER); $dom->appendChild($elem); $notification->serializeBody(new Sabre_DAV_Server(), $elem); $this->assertEquals($expected2, $dom->saveXML()); - - } - function dataProvider() { - + public function dataProvider() + { return array( array( new Sabre_CalDAV_Notifications_Notification_SystemStatus('foo'), - '' . "\n" . '' . "\n", - '' . "\n" . '' . "\n", + ''."\n".''."\n", + ''."\n".''."\n", ), array( - new Sabre_CalDAV_Notifications_Notification_SystemStatus('foo',Sabre_CalDAV_Notifications_Notification_SystemStatus::TYPE_MEDIUM,'bar'), - '' . "\n" . '' . "\n", - '' . "\n" . 'bar' . "\n", + new Sabre_CalDAV_Notifications_Notification_SystemStatus('foo', Sabre_CalDAV_Notifications_Notification_SystemStatus::TYPE_MEDIUM, 'bar'), + ''."\n".''."\n", + ''."\n".'bar'."\n", ), array( - new Sabre_CalDAV_Notifications_Notification_SystemStatus('foo',Sabre_CalDAV_Notifications_Notification_SystemStatus::TYPE_LOW,null,'http://example.org/'), - '' . "\n" . '' . "\n", - '' . "\n" . 'http://example.org/' . "\n", - ) + new Sabre_CalDAV_Notifications_Notification_SystemStatus('foo', Sabre_CalDAV_Notifications_Notification_SystemStatus::TYPE_LOW, null, 'http://example.org/'), + ''."\n".''."\n", + ''."\n".'http://example.org/'."\n", + ), ); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/OutboxPostTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/OutboxPostTest.php index 6c618cac..f1fc22cf 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/OutboxPostTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/OutboxPostTest.php @@ -3,115 +3,107 @@ require_once 'Sabre/DAVServerTest.php'; require_once 'Sabre/CalDAV/Schedule/IMip/Mock.php'; -class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { - +class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest +{ protected $setupCalDAV = true; - function testPostPassThruNotFound() { - + public function testPostPassThruNotFound() + { $req = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'POST', 'REQUEST_URI' => '/notfound', )); $this->assertHTTPStatus(501, $req); - } - function testPostPassThruNoOutBox() { - + public function testPostPassThruNoOutBox() + { $req = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'POST', 'REQUEST_URI' => '/calendars', )); $this->assertHTTPStatus(501, $req); - } - function testNoOriginator() { - + public function testNoOriginator() + { $req = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'POST', 'REQUEST_URI' => '/calendars/admin/outbox', )); $this->assertHTTPStatus(400, $req); - } - function testNoRecipient() { - + public function testNoRecipient() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/admin/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/admin/outbox', 'HTTP_ORIGINATOR' => 'mailto:orig@example.org', )); $this->assertHTTPStatus(400, $req); - } - function testBadOriginator() { - + public function testBadOriginator() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/admin/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/admin/outbox', 'HTTP_ORIGINATOR' => 'nomailto:orig@example.org', - 'HTTP_RECIPIENT' => 'mailto:user1@example.org', + 'HTTP_RECIPIENT' => 'mailto:user1@example.org', )); $this->assertHTTPStatus(400, $req); - } - function testBadRecipient() { - + public function testBadRecipient() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/admin/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/admin/outbox', 'HTTP_ORIGINATOR' => 'mailto:orig@example.org', - 'HTTP_RECIPIENT' => 'http://user1@example.org, mailto:user2@example.org', + 'HTTP_RECIPIENT' => 'http://user1@example.org, mailto:user2@example.org', )); $this->assertHTTPStatus(400, $req); - } - function testIncorrectOriginator() { - + public function testIncorrectOriginator() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/admin/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/admin/outbox', 'HTTP_ORIGINATOR' => 'mailto:orig@example.org', - 'HTTP_RECIPIENT' => 'mailto:user1@example.org, mailto:user2@example.org', + 'HTTP_RECIPIENT' => 'mailto:user1@example.org, mailto:user2@example.org', )); $this->assertHTTPStatus(403, $req); - } - function testInvalidIcalBody() { - + public function testInvalidIcalBody() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/user1/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/user1/outbox', 'HTTP_ORIGINATOR' => 'mailto:user1.sabredav@sabredav.org', - 'HTTP_RECIPIENT' => 'mailto:user2@example.org', + 'HTTP_RECIPIENT' => 'mailto:user2@example.org', )); $req->setBody('foo'); $this->assertHTTPStatus(400, $req); - } - function testNoVEVENT() { - + public function testNoVEVENT() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/user1/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/user1/outbox', 'HTTP_ORIGINATOR' => 'mailto:user1.sabredav@sabredav.org', - 'HTTP_RECIPIENT' => 'mailto:user2@example.org', + 'HTTP_RECIPIENT' => 'mailto:user2@example.org', )); $body = array( @@ -121,19 +113,18 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { 'END:VCALENDAR', ); - $req->setBody(implode("\r\n",$body)); + $req->setBody(implode("\r\n", $body)); $this->assertHTTPStatus(400, $req); - } - function testNoMETHOD() { - + public function testNoMETHOD() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/user1/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/user1/outbox', 'HTTP_ORIGINATOR' => 'mailto:user1.sabredav@sabredav.org', - 'HTTP_RECIPIENT' => 'mailto:user2@example.org', + 'HTTP_RECIPIENT' => 'mailto:user2@example.org', )); $body = array( @@ -143,19 +134,18 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { 'END:VCALENDAR', ); - $req->setBody(implode("\r\n",$body)); + $req->setBody(implode("\r\n", $body)); $this->assertHTTPStatus(400, $req); - } - function testUnsupportedMethod() { - + public function testUnsupportedMethod() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/user1/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/user1/outbox', 'HTTP_ORIGINATOR' => 'mailto:user1.sabredav@sabredav.org', - 'HTTP_RECIPIENT' => 'mailto:user2@example.org', + 'HTTP_RECIPIENT' => 'mailto:user2@example.org', )); $body = array( @@ -166,19 +156,18 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { 'END:VCALENDAR', ); - $req->setBody(implode("\r\n",$body)); + $req->setBody(implode("\r\n", $body)); $this->assertHTTPStatus(501, $req); - } - function testNoIMIPHandler() { - + public function testNoIMIPHandler() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/user1/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/user1/outbox', 'HTTP_ORIGINATOR' => 'mailto:user1.sabredav@sabredav.org', - 'HTTP_RECIPIENT' => 'mailto:user2@example.org', + 'HTTP_RECIPIENT' => 'mailto:user2@example.org', )); $body = array( @@ -189,8 +178,7 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { 'END:VCALENDAR', ); - $req->setBody(implode("\r\n",$body)); - + $req->setBody(implode("\r\n", $body)); $response = $this->request($req); $this->assertEquals('HTTP/1.1 200 OK', $response->status); @@ -199,19 +187,17 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { ), $response->headers); // Lazily checking the body for a few expected values. - $this->assertTrue(strpos($response->body, '5.2;')!==false); - $this->assertTrue(strpos($response->body,'user2@example.org')!==false); - - + $this->assertTrue(strpos($response->body, '5.2;') !== false); + $this->assertTrue(strpos($response->body, 'user2@example.org') !== false); } - function testSuccessRequest() { - + public function testSuccessRequest() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/user1/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/user1/outbox', 'HTTP_ORIGINATOR' => 'mailto:user1.sabredav@sabredav.org', - 'HTTP_RECIPIENT' => 'mailto:user2@example.org', + 'HTTP_RECIPIENT' => 'mailto:user2@example.org', )); $body = array( @@ -223,7 +209,7 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { 'END:VCALENDAR', ); - $req->setBody(implode("\r\n",$body)); + $req->setBody(implode("\r\n", $body)); $handler = new Sabre_CalDAV_Schedule_IMip_Mock('server@example.org'); @@ -236,32 +222,31 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { ), $response->headers); // Lazily checking the body for a few expected values. - $this->assertTrue(strpos($response->body, '2.0;')!==false); - $this->assertTrue(strpos($response->body,'user2@example.org')!==false); + $this->assertTrue(strpos($response->body, '2.0;') !== false); + $this->assertTrue(strpos($response->body, 'user2@example.org') !== false); $this->assertEquals(array( array( 'to' => 'user2@example.org', 'subject' => 'Invitation for: An invitation', - 'body' => implode("\r\n", $body) . "\r\n", + 'body' => implode("\r\n", $body)."\r\n", 'headers' => array( 'Reply-To: user1.sabredav@sabredav.org', 'From: server@example.org', 'Content-Type: text/calendar; method=REQUEST; charset=utf-8', - 'X-Sabre-Version: ' . Sabre_DAV_Version::VERSION . '-' . Sabre_DAV_Version::STABILITY, + 'X-Sabre-Version: '.Sabre_DAV_Version::VERSION.'-'.Sabre_DAV_Version::STABILITY, ), - ) + ), ), $handler->getSentEmails()); - } - function testSuccessRequestUpperCased() { - + public function testSuccessRequestUpperCased() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/user1/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/user1/outbox', 'HTTP_ORIGINATOR' => 'MAILTO:user1.sabredav@sabredav.org', - 'HTTP_RECIPIENT' => 'MAILTO:user2@example.org', + 'HTTP_RECIPIENT' => 'MAILTO:user2@example.org', )); $body = array( @@ -273,7 +258,7 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { 'END:VCALENDAR', ); - $req->setBody(implode("\r\n",$body)); + $req->setBody(implode("\r\n", $body)); $handler = new Sabre_CalDAV_Schedule_IMip_Mock('server@example.org'); @@ -286,32 +271,31 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { ), $response->headers); // Lazily checking the body for a few expected values. - $this->assertTrue(strpos($response->body, '2.0;')!==false); - $this->assertTrue(strpos($response->body,'user2@example.org')!==false); + $this->assertTrue(strpos($response->body, '2.0;') !== false); + $this->assertTrue(strpos($response->body, 'user2@example.org') !== false); $this->assertEquals(array( array( 'to' => 'user2@example.org', 'subject' => 'Invitation for: An invitation', - 'body' => implode("\r\n", $body) . "\r\n", + 'body' => implode("\r\n", $body)."\r\n", 'headers' => array( 'Reply-To: user1.sabredav@sabredav.org', 'From: server@example.org', 'Content-Type: text/calendar; method=REQUEST; charset=utf-8', - 'X-Sabre-Version: ' . Sabre_DAV_Version::VERSION . '-' . Sabre_DAV_Version::STABILITY, + 'X-Sabre-Version: '.Sabre_DAV_Version::VERSION.'-'.Sabre_DAV_Version::STABILITY, ), - ) + ), ), $handler->getSentEmails()); - } - function testSuccessReply() { - + public function testSuccessReply() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/user1/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/user1/outbox', 'HTTP_ORIGINATOR' => 'mailto:user1.sabredav@sabredav.org', - 'HTTP_RECIPIENT' => 'mailto:user2@example.org', + 'HTTP_RECIPIENT' => 'mailto:user2@example.org', )); $body = array( @@ -323,7 +307,7 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { 'END:VCALENDAR', ); - $req->setBody(implode("\r\n",$body)); + $req->setBody(implode("\r\n", $body)); $handler = new Sabre_CalDAV_Schedule_IMip_Mock('server@example.org'); @@ -334,25 +318,24 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { array( 'to' => 'user2@example.org', 'subject' => 'Response for: An invitation', - 'body' => implode("\r\n", $body) . "\r\n", + 'body' => implode("\r\n", $body)."\r\n", 'headers' => array( 'Reply-To: user1.sabredav@sabredav.org', 'From: server@example.org', 'Content-Type: text/calendar; method=REPLY; charset=utf-8', - 'X-Sabre-Version: ' . Sabre_DAV_Version::VERSION . '-' . Sabre_DAV_Version::STABILITY, + 'X-Sabre-Version: '.Sabre_DAV_Version::VERSION.'-'.Sabre_DAV_Version::STABILITY, ), - ) + ), ), $handler->getSentEmails()); - } - function testSuccessCancel() { - + public function testSuccessCancel() + { $req = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'REQUEST_URI' => '/calendars/user1/outbox', + 'REQUEST_METHOD' => 'POST', + 'REQUEST_URI' => '/calendars/user1/outbox', 'HTTP_ORIGINATOR' => 'mailto:user1.sabredav@sabredav.org', - 'HTTP_RECIPIENT' => 'mailto:user2@example.org', + 'HTTP_RECIPIENT' => 'mailto:user2@example.org', )); $body = array( @@ -364,7 +347,7 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { 'END:VCALENDAR', ); - $req->setBody(implode("\r\n",$body)); + $req->setBody(implode("\r\n", $body)); $handler = new Sabre_CalDAV_Schedule_IMip_Mock('server@example.org'); @@ -375,16 +358,14 @@ class Sabre_CalDAV_OutboxPostTest extends Sabre_DAVServerTest { array( 'to' => 'user2@example.org', 'subject' => 'Cancelled event: An invitation', - 'body' => implode("\r\n", $body) . "\r\n", + 'body' => implode("\r\n", $body)."\r\n", 'headers' => array( 'Reply-To: user1.sabredav@sabredav.org', 'From: server@example.org', 'Content-Type: text/calendar; method=CANCEL; charset=utf-8', - 'X-Sabre-Version: ' . Sabre_DAV_Version::VERSION . '-' . Sabre_DAV_Version::STABILITY, + 'X-Sabre-Version: '.Sabre_DAV_Version::VERSION.'-'.Sabre_DAV_Version::STABILITY, ), - ) + ), ), $handler->getSentEmails()); - - } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/PluginTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/PluginTest.php index 6ff57285..e4533804 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/PluginTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/PluginTest.php @@ -5,8 +5,8 @@ require_once 'Sabre/DAV/Auth/MockBackend.php'; require_once 'Sabre/CalDAV/TestUtil.php'; require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; -class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase { - +class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_DAV_Server */ @@ -21,8 +21,8 @@ class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase { */ protected $caldavBackend; - function setup() { - + public function setup() + { $this->caldavBackend = new Sabre_CalDAV_Backend_Mock(array( array( 'id' => 1, @@ -32,7 +32,7 @@ class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase { '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'Calendar description', '{http://apple.com/ns/ical/}calendar-order' => '1', '{http://apple.com/ns/ical/}calendar-color' => '#FF0000', - '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT','VTODO')), + '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT', 'VTODO')), ), array( 'id' => 2, @@ -42,18 +42,18 @@ class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase { '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'Calendar description', '{http://apple.com/ns/ical/}calendar-order' => '1', '{http://apple.com/ns/ical/}calendar-color' => '#FF0000', - '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT','VTODO')), - ) + '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT', 'VTODO')), + ), ), array( 1 => array( 'UUID-2345' => array( 'calendardata' => Sabre_CalDAV_TestUtil::getTestCalendarData(), - ) - ) + ), + ), )); $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); - $principalBackend->setGroupMemberSet('principals/admin/calendar-proxy-read',array('principals/user1')); - $principalBackend->setGroupMemberSet('principals/admin/calendar-proxy-write',array('principals/user1')); + $principalBackend->setGroupMemberSet('principals/admin/calendar-proxy-read', array('principals/user1')); + $principalBackend->setGroupMemberSet('principals/admin/calendar-proxy-write', array('principals/user1')); $principalBackend->addPrincipal(array( 'uri' => 'principals/admin/calendar-proxy-read', )); @@ -61,7 +61,7 @@ class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase { 'uri' => 'principals/admin/calendar-proxy-write', )); - $calendars = new Sabre_CalDAV_CalendarRootNode($principalBackend,$this->caldavBackend); + $calendars = new Sabre_CalDAV_CalendarRootNode($principalBackend, $this->caldavBackend); $principals = new Sabre_CalDAV_Principal_Collection($principalBackend); $root = new Sabre_DAV_SimpleCollection('root'); @@ -77,37 +77,34 @@ class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase { $this->response = new Sabre_HTTP_ResponseMock(); $this->server->httpResponse = $this->response; - } - function testSimple() { - + public function testSimple() + { $this->assertEquals(array('MKCALENDAR'), $this->plugin->getHTTPMethods('calendars/user1/randomnewcalendar')); - $this->assertEquals(array('calendar-access','calendar-proxy'), $this->plugin->getFeatures()); + $this->assertEquals(array('calendar-access', 'calendar-proxy'), $this->plugin->getFeatures()); $this->assertArrayHasKey('urn:ietf:params:xml:ns:caldav', $this->server->xmlNamespaces); - } - function testUnknownMethodPassThrough() { - + public function testUnknownMethodPassThrough() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'MKBREAKFAST', - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', )); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 501 Not Implemented', $this->response->status,'Incorrect status returned. Full response body:' . $this->response->body); - + $this->assertEquals('HTTP/1.1 501 Not Implemented', $this->response->status, 'Incorrect status returned. Full response body:'.$this->response->body); } - function testReportPassThrough() { - + public function testReportPassThrough() + { $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'REPORT', + 'REQUEST_METHOD' => 'REPORT', 'HTTP_CONTENT_TYPE' => 'application/xml', - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', )); $request->setBody(''); @@ -115,14 +112,13 @@ class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase { $this->server->exec(); $this->assertEquals('HTTP/1.1 501 Not Implemented', $this->response->status); - } - function testMkCalendarBadLocation() { - + public function testMkCalendarBadLocation() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'MKCALENDAR', - 'REQUEST_URI' => '/blabla', + 'REQUEST_URI' => '/blabla', )); $body = ' @@ -168,14 +164,13 @@ class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase { $this->server->exec(); $this->assertEquals('HTTP/1.1 403 Forbidden', $this->response->status); - } - function testMkCalendarNoParentNode() { - + public function testMkCalendarNoParentNode() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'MKCALENDAR', - 'REQUEST_URI' => '/doesntexist/calendar', + 'REQUEST_URI' => '/doesntexist/calendar', )); $body = ' @@ -221,14 +216,13 @@ class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase { $this->server->exec(); $this->assertEquals('HTTP/1.1 409 Conflict', $this->response->status); - } - function testMkCalendarExistingCalendar() { - + public function testMkCalendarExistingCalendar() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'MKCALENDAR', - 'REQUEST_URI' => '/calendars/user1/UUID-123467', + 'REQUEST_URI' => '/calendars/user1/UUID-123467', )); $body = ' @@ -274,14 +268,13 @@ class Sabre_CalDAV_PluginTest extends PHPUnit_Framework_TestCase { $this->server->exec(); $this->assertEquals('HTTP/1.1 405 Method Not Allowed', $this->response->status); - } - function testMkCalendarSucceed() { - + public function testMkCalendarSucceed() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'MKCALENDAR', - 'REQUEST_URI' => '/calendars/user1/NEWCALENDAR', + 'REQUEST_URI' => '/calendars/user1/NEWCALENDAR', )); $timezone = 'BEGIN:VCALENDAR @@ -318,7 +311,7 @@ END:VCALENDAR'; - + '; @@ -327,20 +320,20 @@ END:VCALENDAR'; $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 201 Created', $this->response->status,'Invalid response code received. Full response body: ' .$this->response->body); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status, 'Invalid response code received. Full response body: '.$this->response->body); $calendars = $this->caldavBackend->getCalendarsForUser('principals/user1'); $this->assertEquals(3, count($calendars)); $newCalendar = null; - foreach($calendars as $calendar) { - if ($calendar['uri'] === 'NEWCALENDAR') { + foreach ($calendars as $calendar) { + if ($calendar['uri'] === 'NEWCALENDAR') { $newCalendar = $calendar; break; - } + } } - $this->assertInternalType('array',$newCalendar); + $this->assertInternalType('array', $newCalendar); $keys = array( 'uri' => 'NEWCALENDAR', @@ -351,45 +344,44 @@ END:VCALENDAR'; '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => null, ); - foreach($keys as $key=>$value) { - + foreach ($keys as $key => $value) { $this->assertArrayHasKey($key, $newCalendar); - if (is_null($value)) continue; + if (is_null($value)) { + continue; + } $this->assertEquals($value, $newCalendar[$key]); - } $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'; $this->assertTrue($newCalendar[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet); - $this->assertEquals(array('VEVENT'),$newCalendar[$sccs]->getValue()); - + $this->assertEquals(array('VEVENT'), $newCalendar[$sccs]->getValue()); } - function testMkCalendarEmptyBodySucceed() { - + public function testMkCalendarEmptyBodySucceed() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'MKCALENDAR', - 'REQUEST_URI' => '/calendars/user1/NEWCALENDAR', + 'REQUEST_URI' => '/calendars/user1/NEWCALENDAR', )); $request->setBody(''); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 201 Created', $this->response->status,'Invalid response code received. Full response body: ' .$this->response->body); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status, 'Invalid response code received. Full response body: '.$this->response->body); $calendars = $this->caldavBackend->getCalendarsForUser('principals/user1'); $this->assertEquals(3, count($calendars)); $newCalendar = null; - foreach($calendars as $calendar) { - if ($calendar['uri'] === 'NEWCALENDAR') { + foreach ($calendars as $calendar) { + if ($calendar['uri'] === 'NEWCALENDAR') { $newCalendar = $calendar; break; - } + } } - $this->assertInternalType('array',$newCalendar); + $this->assertInternalType('array', $newCalendar); $keys = array( 'uri' => 'NEWCALENDAR', @@ -397,60 +389,57 @@ END:VCALENDAR'; '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => null, ); - foreach($keys as $key=>$value) { - + foreach ($keys as $key => $value) { $this->assertArrayHasKey($key, $newCalendar); - if (is_null($value)) continue; + if (is_null($value)) { + continue; + } $this->assertEquals($value, $newCalendar[$key]); - } $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'; $this->assertTrue($newCalendar[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet); - $this->assertEquals(array('VEVENT','VTODO'),$newCalendar[$sccs]->getValue()); - + $this->assertEquals(array('VEVENT', 'VTODO'), $newCalendar[$sccs]->getValue()); } - function testPrincipalProperties() { - + public function testPrincipalProperties() + { $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_HOST' => 'sabredav.org', )); $this->server->httpRequest = $httpRequest; - $props = $this->server->getPropertiesForPath('/principals/user1',array( + $props = $this->server->getPropertiesForPath('/principals/user1', array( '{urn:ietf:params:xml:ns:caldav}calendar-home-set', '{urn:ietf:params:xml:ns:caldav}schedule-outbox-URL', '{urn:ietf:params:xml:ns:caldav}calendar-user-address-set', - '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}calendar-proxy-read-for', - '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}calendar-proxy-write-for', - '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}notification-URL', + '{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER.'}calendar-proxy-read-for', + '{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER.'}calendar-proxy-write-for', + '{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER.'}notification-URL', )); - $this->assertArrayHasKey(0,$props); - $this->assertArrayHasKey(200,$props[0]); + $this->assertArrayHasKey(0, $props); + $this->assertArrayHasKey(200, $props[0]); - - $this->assertArrayHasKey('{urn:ietf:params:xml:ns:caldav}calendar-home-set',$props[0][200]); + $this->assertArrayHasKey('{urn:ietf:params:xml:ns:caldav}calendar-home-set', $props[0][200]); $prop = $props[0][200]['{urn:ietf:params:xml:ns:caldav}calendar-home-set']; $this->assertTrue($prop instanceof Sabre_DAV_Property_Href); - $this->assertEquals('calendars/user1/',$prop->getHref()); + $this->assertEquals('calendars/user1/', $prop->getHref()); - $this->assertArrayHasKey('{urn:ietf:params:xml:ns:caldav}schedule-outbox-URL',$props[0][200]); + $this->assertArrayHasKey('{urn:ietf:params:xml:ns:caldav}schedule-outbox-URL', $props[0][200]); $prop = $props[0][200]['{urn:ietf:params:xml:ns:caldav}schedule-outbox-URL']; $this->assertTrue($prop instanceof Sabre_DAV_Property_Href); - $this->assertEquals('calendars/user1/outbox',$prop->getHref()); + $this->assertEquals('calendars/user1/outbox', $prop->getHref()); - $this->assertArrayHasKey('{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER .'}notification-URL',$props[0][200]); - $prop = $props[0][200]['{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER .'}notification-URL']; + $this->assertArrayHasKey('{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER.'}notification-URL', $props[0][200]); + $prop = $props[0][200]['{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER.'}notification-URL']; $this->assertTrue($prop instanceof Sabre_DAV_Property_Href); - $this->assertEquals('calendars/user1/notifications/',$prop->getHref()); + $this->assertEquals('calendars/user1/notifications/', $prop->getHref()); - - $this->assertArrayHasKey('{urn:ietf:params:xml:ns:caldav}calendar-user-address-set',$props[0][200]); + $this->assertArrayHasKey('{urn:ietf:params:xml:ns:caldav}calendar-user-address-set', $props[0][200]); $prop = $props[0][200]['{urn:ietf:params:xml:ns:caldav}calendar-user-address-set']; $this->assertTrue($prop instanceof Sabre_DAV_Property_HrefList); - $this->assertEquals(array('mailto:user1.sabredav@sabredav.org','/principals/user1'),$prop->getHrefs()); + $this->assertEquals(array('mailto:user1.sabredav@sabredav.org', '/principals/user1'), $prop->getHrefs()); $this->assertArrayHasKey('{http://calendarserver.org/ns/}calendar-proxy-read-for', $props[0][200]); $prop = $props[0][200]['{http://calendarserver.org/ns/}calendar-proxy-read-for']; @@ -461,41 +450,38 @@ END:VCALENDAR'; $prop = $props[0][200]['{http://calendarserver.org/ns/}calendar-proxy-write-for']; $this->assertInstanceOf('Sabre_DAV_Property_HrefList', $prop); $this->assertEquals(array('principals/admin'), $prop->getHrefs()); - - } - function testSupportedReportSetPropertyNonCalendar() { - - $props = $this->server->getPropertiesForPath('/calendars/user1',array( + public function testSupportedReportSetPropertyNonCalendar() + { + $props = $this->server->getPropertiesForPath('/calendars/user1', array( '{DAV:}supported-report-set', )); - $this->assertArrayHasKey(0,$props); - $this->assertArrayHasKey(200,$props[0]); - $this->assertArrayHasKey('{DAV:}supported-report-set',$props[0][200]); + $this->assertArrayHasKey(0, $props); + $this->assertArrayHasKey(200, $props[0]); + $this->assertArrayHasKey('{DAV:}supported-report-set', $props[0][200]); $prop = $props[0][200]['{DAV:}supported-report-set']; $this->assertTrue($prop instanceof Sabre_DAV_Property_SupportedReportSet); $value = array( ); - $this->assertEquals($value,$prop->getValue()); - + $this->assertEquals($value, $prop->getValue()); } /** * @depends testSupportedReportSetPropertyNonCalendar */ - function testSupportedReportSetProperty() { - - $props = $this->server->getPropertiesForPath('/calendars/user1/UUID-123467',array( + public function testSupportedReportSetProperty() + { + $props = $this->server->getPropertiesForPath('/calendars/user1/UUID-123467', array( '{DAV:}supported-report-set', )); - $this->assertArrayHasKey(0,$props); - $this->assertArrayHasKey(200,$props[0]); - $this->assertArrayHasKey('{DAV:}supported-report-set',$props[0][200]); + $this->assertArrayHasKey(0, $props); + $this->assertArrayHasKey(200, $props[0]); + $this->assertArrayHasKey('{DAV:}supported-report-set', $props[0][200]); $prop = $props[0][200]['{DAV:}supported-report-set']; @@ -505,41 +491,40 @@ END:VCALENDAR'; '{urn:ietf:params:xml:ns:caldav}calendar-query', '{urn:ietf:params:xml:ns:caldav}free-busy-query', ); - $this->assertEquals($value,$prop->getValue()); - + $this->assertEquals($value, $prop->getValue()); } /** * @depends testSupportedReportSetProperty */ - function testCalendarMultiGetReport() { - + public function testCalendarMultiGetReport() + { $body = - '' . - '' . - '' . - ' ' . - ' ' . - '' . - '/calendars/user1/UUID-123467/UUID-2345' . + ''. + ''. + ''. + ' '. + ' '. + ''. + '/calendars/user1/UUID-123467/UUID-2345'. ''; $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', - 'REQUEST_URI' => '/calendars/user1', - 'HTTP_DEPTH' => '1', + 'REQUEST_URI' => '/calendars/user1', + 'HTTP_DEPTH' => '1', )); $request->setBody($body); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'Invalid HTTP status received. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'Invalid HTTP status received. Full response body: '.$this->response->body); $xml = simplexml_load_string($this->response->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('c','urn:ietf:params:xml:ns:caldav'); + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:caldav'); $check = array( '/d:multistatus', @@ -552,56 +537,55 @@ END:VCALENDAR'; '/d:multistatus/d:response/d:propstat/d:status' => 'HTTP/1.1 200 OK', ); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); - $this->assertEquals(1,count($result)); - - if (!is_int($v1)) $this->assertEquals($v2,(string)$result[0]); + $this->assertEquals(1, count($result)); + if (!is_int($v1)) { + $this->assertEquals($v2, (string) $result[0]); + } } // The response object should have a reference to the Asia/Seoul // timezone. - $this->assertTrue(strpos($this->response->body,'Asia/Seoul')!==false); - + $this->assertTrue(strpos($this->response->body, 'Asia/Seoul') !== false); } /** * @depends testCalendarMultiGetReport */ - function testCalendarMultiGetReportExpand() { - + public function testCalendarMultiGetReportExpand() + { $body = - '' . - '' . - '' . - ' ' . - ' ' . - ' ' . - ' ' . - '' . - '/calendars/user1/UUID-123467/UUID-2345' . + ''. + ''. + ''. + ' '. + ' '. + ' '. + ' '. + ''. + '/calendars/user1/UUID-123467/UUID-2345'. ''; $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', - 'REQUEST_URI' => '/calendars/user1', - 'HTTP_DEPTH' => '1', + 'REQUEST_URI' => '/calendars/user1', + 'HTTP_DEPTH' => '1', )); $request->setBody($body); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'Invalid HTTP status received. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'Invalid HTTP status received. Full response body: '.$this->response->body); $xml = simplexml_load_string($this->response->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('c','urn:ietf:params:xml:ns:caldav'); + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:caldav'); $check = array( '/d:multistatus', @@ -614,59 +598,58 @@ END:VCALENDAR'; '/d:multistatus/d:response/d:propstat/d:status' => 'HTTP/1.1 200 OK', ); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); - $this->assertEquals(1,count($result)); - - if (!is_int($v1)) $this->assertEquals($v2,(string)$result[0]); + $this->assertEquals(1, count($result)); + if (!is_int($v1)) { + $this->assertEquals($v2, (string) $result[0]); + } } // The response object should no longer hold references to timezones. - $this->assertTrue(strpos($this->response->body,'Asia/Seoul')===false); - + $this->assertTrue(strpos($this->response->body, 'Asia/Seoul') === false); } /** * @depends testSupportedReportSetProperty * @depends testCalendarMultiGetReport */ - function testCalendarQueryReport() { - + public function testCalendarQueryReport() + { $body = - '' . - '' . - '' . - ' ' . - ' ' . - ' ' . - ' ' . - '' . - '' . - ' ' . - ' ' . - ' ' . - '' . + ''. + ''. + ''. + ' '. + ' '. + ' '. + ' '. + ''. + ''. + ' '. + ' '. + ' '. + ''. ''; $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', - 'REQUEST_URI' => '/calendars/user1/UUID-123467', - 'HTTP_DEPTH' => '1', + 'REQUEST_URI' => '/calendars/user1/UUID-123467', + 'HTTP_DEPTH' => '1', )); $request->setBody($body); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'Received an unexpected status. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'Received an unexpected status. Full response body: '.$this->response->body); $xml = simplexml_load_string($this->response->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('c','urn:ietf:params:xml:ns:caldav'); + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:caldav'); $check = array( '/d:multistatus', @@ -679,53 +662,52 @@ END:VCALENDAR'; '/d:multistatus/d:response/d:propstat/d:status' => 'HTTP/1.1 200 OK', ); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); - $this->assertEquals(1,count($result), 'We expected 1 ' . $xpath . ' elements. We\'ve found ' . count($result) . '. Full result: ' . $this->response->body); - - if (!is_int($v1)) $this->assertEquals($v2,(string)$result[0]); + $this->assertEquals(1, count($result), 'We expected 1 '.$xpath.' elements. We\'ve found '.count($result).'. Full result: '.$this->response->body); + if (!is_int($v1)) { + $this->assertEquals($v2, (string) $result[0]); + } } - } /** * @depends testCalendarQueryReport */ - function testCalendarQueryReportNoCalData() { - + public function testCalendarQueryReportNoCalData() + { $body = - '' . - '' . - '' . - ' ' . - '' . - '' . - ' ' . - ' ' . - ' ' . - '' . + ''. + ''. + ''. + ' '. + ''. + ''. + ' '. + ' '. + ' '. + ''. ''; $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', - 'REQUEST_URI' => '/calendars/user1//UUID-123467', - 'HTTP_DEPTH' => '1', + 'REQUEST_URI' => '/calendars/user1//UUID-123467', + 'HTTP_DEPTH' => '1', )); $request->setBody($body); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'Received an unexpected status. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'Received an unexpected status. Full response body: '.$this->response->body); $xml = simplexml_load_string($this->response->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('c','urn:ietf:params:xml:ns:caldav'); + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:caldav'); $check = array( '/d:multistatus', @@ -737,84 +719,82 @@ END:VCALENDAR'; '/d:multistatus/d:response/d:propstat/d:status' => 'HTTP/1.1 200 OK', ); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); - $this->assertEquals(1,count($result), 'We expected 1 ' . $xpath . ' elements. We\'ve found ' . count($result) . '. Full result: ' . $this->response->body); - - if (!is_int($v1)) $this->assertEquals($v2,(string)$result[0]); + $this->assertEquals(1, count($result), 'We expected 1 '.$xpath.' elements. We\'ve found '.count($result).'. Full result: '.$this->response->body); + if (!is_int($v1)) { + $this->assertEquals($v2, (string) $result[0]); + } } - } /** * @depends testCalendarQueryReport */ - function testCalendarQueryReportNoFilters() { - + public function testCalendarQueryReportNoFilters() + { $body = - '' . - '' . - '' . - ' ' . - ' ' . - '' . + ''. + ''. + ''. + ' '. + ' '. + ''. ''; $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', - 'REQUEST_URI' => '/calendars/user1//UUID-123467', + 'REQUEST_URI' => '/calendars/user1//UUID-123467', )); $request->setBody($body); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 400 Bad request',$this->response->status,'Received an unexpected status. Full response body: ' . $this->response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $this->response->status, 'Received an unexpected status. Full response body: '.$this->response->body); } /** * @depends testSupportedReportSetProperty * @depends testCalendarMultiGetReport */ - function testCalendarQueryReport1Object() { - + public function testCalendarQueryReport1Object() + { $body = - '' . - '' . - '' . - ' ' . - ' ' . - ' ' . - ' ' . - '' . - '' . - ' ' . - ' ' . - ' ' . - '' . + ''. + ''. + ''. + ' '. + ' '. + ' '. + ' '. + ''. + ''. + ' '. + ' '. + ' '. + ''. ''; $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', - 'REQUEST_URI' => '/calendars/user1/UUID-123467/UUID-2345', - 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/calendars/user1/UUID-123467/UUID-2345', + 'HTTP_DEPTH' => '0', )); $request->setBody($body); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'Received an unexpected status. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'Received an unexpected status. Full response body: '.$this->response->body); $xml = simplexml_load_string($this->response->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('c','urn:ietf:params:xml:ns:caldav'); + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:caldav'); $check = array( '/d:multistatus', @@ -827,54 +807,53 @@ END:VCALENDAR'; '/d:multistatus/d:response/d:propstat/d:status' => 'HTTP/1.1 200 OK', ); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); - $this->assertEquals(1,count($result), 'We expected 1 ' . $xpath . ' elements. We\'ve found ' . count($result) . '. Full result: ' . $this->response->body); - - if (!is_int($v1)) $this->assertEquals($v2,(string)$result[0]); + $this->assertEquals(1, count($result), 'We expected 1 '.$xpath.' elements. We\'ve found '.count($result).'. Full result: '.$this->response->body); + if (!is_int($v1)) { + $this->assertEquals($v2, (string) $result[0]); + } } - } /** * @depends testSupportedReportSetProperty * @depends testCalendarMultiGetReport */ - function testCalendarQueryReport1ObjectNoCalData() { - + public function testCalendarQueryReport1ObjectNoCalData() + { $body = - '' . - '' . - '' . - ' ' . - '' . - '' . - ' ' . - ' ' . - ' ' . - '' . + ''. + ''. + ''. + ' '. + ''. + ''. + ' '. + ' '. + ' '. + ''. ''; $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', - 'REQUEST_URI' => '/calendars/user1/UUID-123467/UUID-2345', - 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/calendars/user1/UUID-123467/UUID-2345', + 'HTTP_DEPTH' => '0', )); $request->setBody($body); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'Received an unexpected status. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'Received an unexpected status. Full response body: '.$this->response->body); $xml = simplexml_load_string($this->response->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('c','urn:ietf:params:xml:ns:caldav'); + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('c', 'urn:ietf:params:xml:ns:caldav'); $check = array( '/d:multistatus', @@ -886,31 +865,29 @@ END:VCALENDAR'; '/d:multistatus/d:response/d:propstat/d:status' => 'HTTP/1.1 200 OK', ); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); - $this->assertEquals(1,count($result), 'We expected 1 ' . $xpath . ' elements. We\'ve found ' . count($result) . '. Full result: ' . $this->response->body); - - if (!is_int($v1)) $this->assertEquals($v2,(string)$result[0]); + $this->assertEquals(1, count($result), 'We expected 1 '.$xpath.' elements. We\'ve found '.count($result).'. Full result: '.$this->response->body); + if (!is_int($v1)) { + $this->assertEquals($v2, (string) $result[0]); + } } - } - function testHTMLActionsPanel() { - + public function testHTMLActionsPanel() + { $output = ''; $r = $this->server->broadcastEvent('onHTMLActionsPanel', array($this->server->tree->getNodeForPath('calendars/user1'), &$output)); $this->assertFalse($r); - $this->assertTrue(!!strpos($output,'Display name')); - + $this->assertTrue((bool) strpos($output, 'Display name')); } - function testBrowserPostAction() { - + public function testBrowserPostAction() + { $r = $this->server->broadcastEvent('onBrowserPostAction', array('calendars/user1', 'mkcalendar', array( 'name' => 'NEWCALENDAR', '{DAV:}displayname' => 'foo', @@ -921,115 +898,111 @@ END:VCALENDAR'; $this->assertEquals(3, count($calendars)); $newCalendar = null; - foreach($calendars as $calendar) { - if ($calendar['uri'] === 'NEWCALENDAR') { + foreach ($calendars as $calendar) { + if ($calendar['uri'] === 'NEWCALENDAR') { $newCalendar = $calendar; break; - } + } } - if (!$newCalendar) + if (!$newCalendar) { $this->fail('Could not find newly created calendar'); - - + } } /** * @depends testCalendarMultiGetReport */ - function testCalendarMultiGetReportNoEnd() { - + public function testCalendarMultiGetReportNoEnd() + { $body = - '' . - '' . - '' . - ' ' . - ' ' . - ' ' . - ' ' . - '' . - '/calendars/user1/UUID-123467/UUID-2345' . + ''. + ''. + ''. + ' '. + ' '. + ' '. + ' '. + ''. + '/calendars/user1/UUID-123467/UUID-2345'. ''; $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', - 'REQUEST_URI' => '/calendars/user1', - 'HTTP_DEPTH' => '1', + 'REQUEST_URI' => '/calendars/user1', + 'HTTP_DEPTH' => '1', )); $request->setBody($body); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 400 Bad request',$this->response->status,'Invalid HTTP status received. Full response body: ' . $this->response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $this->response->status, 'Invalid HTTP status received. Full response body: '.$this->response->body); } /** * @depends testCalendarMultiGetReport */ - function testCalendarMultiGetReportNoStart() { - + public function testCalendarMultiGetReportNoStart() + { $body = - '' . - '' . - '' . - ' ' . - ' ' . - ' ' . - ' ' . - '' . - '/calendars/user1/UUID-123467/UUID-2345' . + ''. + ''. + ''. + ' '. + ' '. + ' '. + ' '. + ''. + '/calendars/user1/UUID-123467/UUID-2345'. ''; $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', - 'REQUEST_URI' => '/calendars/user1', - 'HTTP_DEPTH' => '1', + 'REQUEST_URI' => '/calendars/user1', + 'HTTP_DEPTH' => '1', )); $request->setBody($body); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 400 Bad request',$this->response->status,'Invalid HTTP status received. Full response body: ' . $this->response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $this->response->status, 'Invalid HTTP status received. Full response body: '.$this->response->body); } /** * @depends testCalendarMultiGetReport */ - function testCalendarMultiGetReportEndBeforeStart() { - + public function testCalendarMultiGetReportEndBeforeStart() + { $body = - '' . - '' . - '' . - ' ' . - ' ' . - ' ' . - ' ' . - '' . - '/calendars/user1/UUID-123467/UUID-2345' . + ''. + ''. + ''. + ' '. + ' '. + ' '. + ' '. + ''. + '/calendars/user1/UUID-123467/UUID-2345'. ''; $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', - 'REQUEST_URI' => '/calendars/user1', - 'HTTP_DEPTH' => '1', + 'REQUEST_URI' => '/calendars/user1', + 'HTTP_DEPTH' => '1', )); $request->setBody($body); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 400 Bad request',$this->response->status,'Invalid HTTP status received. Full response body: ' . $this->response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $this->response->status, 'Invalid HTTP status received. Full response body: '.$this->response->body); } - function testNotificationProperties() { - + public function testNotificationProperties() + { $request = array( - '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}notificationtype', + '{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER.'}notificationtype', ); $result = array(); $notification = new Sabre_CalDAV_Notifications_Node( @@ -1041,14 +1014,13 @@ END:VCALENDAR'; $this->assertEquals( array( 200 => array( - '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}notificationtype' => $notification->getNotificationType() - ) + '{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER.'}notificationtype' => $notification->getNotificationType(), + ), ), $result); - } - function testNotificationGet() { - + public function testNotificationGet() + { $notification = new Sabre_CalDAV_Notifications_Node( $this->caldavBackend, new Sabre_CalDAV_Notifications_Notification_SystemStatus('foo') @@ -1062,14 +1034,14 @@ END:VCALENDAR'; $server->addPlugin($caldav); - $caldav->beforeMethod('GET','foo'); + $caldav->beforeMethod('GET', 'foo'); $this->assertEquals('HTTP/1.1 200 OK', $httpResponse->status); $this->assertEquals(array( 'Content-Type' => 'application/xml', ), $httpResponse->headers); - $expected = + $expected = ' @@ -1077,8 +1049,5 @@ END:VCALENDAR'; '; $this->assertEquals($expected, $httpResponse->body); - - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Principal/CollectionTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Principal/CollectionTest.php index 0495df10..59fd3131 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Principal/CollectionTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Principal/CollectionTest.php @@ -2,17 +2,15 @@ require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; -class Sabre_CalDAV_Principal_CollectionTest extends PHPUnit_Framework_TestCase { - - function testGetChildForPrincipal() { - +class Sabre_CalDAV_Principal_CollectionTest extends PHPUnit_Framework_TestCase +{ + public function testGetChildForPrincipal() + { $back = new Sabre_DAVACL_MockPrincipalBackend(); $col = new Sabre_CalDAV_Principal_Collection($back); $r = $col->getChildForPrincipal(array( 'uri' => 'principals/admin', )); $this->assertInstanceOf('Sabre_CalDAV_Principal_User', $r); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Principal/ProxyReadTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Principal/ProxyReadTest.php index 41ec2f26..a3cb6acb 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Principal/ProxyReadTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Principal/ProxyReadTest.php @@ -1,98 +1,88 @@ 'principal/user', )); $this->backend = $backend; + return $principal; + } - } - - function testGetName() { - + public function testGetName() + { $i = $this->getInstance(); $this->assertEquals('calendar-proxy-read', $i->getName()); - } - function testGetDisplayName() { - + public function testGetDisplayName() + { $i = $this->getInstance(); $this->assertEquals('calendar-proxy-read', $i->getDisplayName()); - } - function testGetLastModified() { - + public function testGetLastModified() + { $i = $this->getInstance(); $this->assertNull($i->getLastModified()); - } /** * @expectedException Sabre_DAV_Exception_Forbidden */ - function testDelete() { - + public function testDelete() + { $i = $this->getInstance(); $i->delete(); - } /** * @expectedException Sabre_DAV_Exception_Forbidden */ - function testSetName() { - + public function testSetName() + { $i = $this->getInstance(); $i->setName('foo'); - } - function testGetAlternateUriSet() { - + public function testGetAlternateUriSet() + { $i = $this->getInstance(); $this->assertEquals(array(), $i->getAlternateUriSet()); - } - function testGetPrincipalUri() { - + public function testGetPrincipalUri() + { $i = $this->getInstance(); $this->assertEquals('principal/user/calendar-proxy-read', $i->getPrincipalUrl()); - } - function testGetGroupMemberSet() { - + public function testGetGroupMemberSet() + { $i = $this->getInstance(); $this->assertEquals(array(), $i->getGroupMemberSet()); - } - function testGetGroupMembership() { - + public function testGetGroupMembership() + { $i = $this->getInstance(); $this->assertEquals(array(), $i->getGroupMembership()); - } - function testSetGroupMemberSet() { - + public function testSetGroupMemberSet() + { $i = $this->getInstance(); $i->setGroupMemberSet(array('principals/foo')); $expected = array( - $i->getPrincipalUrl() => array('principals/foo') + $i->getPrincipalUrl() => array('principals/foo'), ); $this->assertEquals($expected, $this->backend->groupMembers); - } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Principal/ProxyWriteTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Principal/ProxyWriteTest.php index 02bce59b..504f0db6 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Principal/ProxyWriteTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Principal/ProxyWriteTest.php @@ -1,36 +1,32 @@ 'principal/user', )); $this->backend = $backend; - return $principal; + return $principal; } - function testGetName() { - + public function testGetName() + { $i = $this->getInstance(); $this->assertEquals('calendar-proxy-write', $i->getName()); - } - function testGetDisplayName() { - + public function testGetDisplayName() + { $i = $this->getInstance(); $this->assertEquals('calendar-proxy-write', $i->getDisplayName()); - } - function testGetPrincipalUri() { - + public function testGetPrincipalUri() + { $i = $this->getInstance(); $this->assertEquals('principal/user/calendar-proxy-write', $i->getPrincipalUrl()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Principal/UserTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Principal/UserTest.php index ddd20ade..bd9786dd 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Principal/UserTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Principal/UserTest.php @@ -1,9 +1,9 @@ addPrincipal(array( 'uri' => 'principals/user/calendar-proxy-read', @@ -14,89 +14,81 @@ class Sabre_CalDAV_Principal_UserTest extends PHPUnit_Framework_TestCase { $backend->addPrincipal(array( 'uri' => 'principals/user/random', )); + return new Sabre_CalDAV_Principal_User($backend, array( 'uri' => 'principals/user', )); - } /** * @expectedException Sabre_DAV_Exception_Forbidden */ - function testCreateFile() { - + public function testCreateFile() + { $u = $this->getInstance(); $u->createFile('test'); - } /** * @expectedException Sabre_DAV_Exception_Forbidden */ - function testCreateDirectory() { - + public function testCreateDirectory() + { $u = $this->getInstance(); $u->createDirectory('test'); - } - function testGetChildProxyRead() { - + public function testGetChildProxyRead() + { $u = $this->getInstance(); $child = $u->getChild('calendar-proxy-read'); $this->assertInstanceOf('Sabre_CalDAV_Principal_ProxyRead', $child); - } - function testGetChildProxyWrite() { - + public function testGetChildProxyWrite() + { $u = $this->getInstance(); $child = $u->getChild('calendar-proxy-write'); $this->assertInstanceOf('Sabre_CalDAV_Principal_ProxyWrite', $child); - } /** * @expectedException Sabre_DAV_Exception_NotFound */ - function testGetChildNotFound() { - + public function testGetChildNotFound() + { $u = $this->getInstance(); $child = $u->getChild('foo'); - } /** * @expectedException Sabre_DAV_Exception_NotFound */ - function testGetChildNotFound2() { - + public function testGetChildNotFound2() + { $u = $this->getInstance(); $child = $u->getChild('random'); - } - function testGetChildren() { - + public function testGetChildren() + { $u = $this->getInstance(); $children = $u->getChildren(); $this->assertEquals(2, count($children)); $this->assertInstanceOf('Sabre_CalDAV_Principal_ProxyRead', $children[0]); $this->assertInstanceOf('Sabre_CalDAV_Principal_ProxyWrite', $children[1]); - } - function testChildExist() { - + public function testChildExist() + { $u = $this->getInstance(); $this->assertTrue($u->childExists('calendar-proxy-read')); $this->assertTrue($u->childExists('calendar-proxy-write')); $this->assertFalse($u->childExists('foo')); - } - function testGetACL() { - + public function testGetACL() + { $expected = array( array( 'privilege' => '{DAV:}read', @@ -117,7 +109,5 @@ class Sabre_CalDAV_Principal_UserTest extends PHPUnit_Framework_TestCase { $u = $this->getInstance(); $this->assertEquals($expected, $u->getACL()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCalendarComponentSetTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCalendarComponentSetTest.php index 52e127c2..9fe320f8 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCalendarComponentSetTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCalendarComponentSetTest.php @@ -1,25 +1,24 @@ assertEquals(array('VEVENT'), $sccs->getValue()); - } /** * @depends testSimple */ - function testSerialize() { - - $property = new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT','VJOURNAL')); + public function testSerialize() + { + $property = new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT', 'VJOURNAL')); $doc = new DOMDocument(); $root = $doc->createElement('d:root'); - $root->setAttribute('xmlns:d','DAV:'); - $root->setAttribute('xmlns:cal',Sabre_CalDAV_Plugin::NS_CALDAV); + $root->setAttribute('xmlns:d', 'DAV:'); + $root->setAttribute('xmlns:cal', Sabre_CalDAV_Plugin::NS_CALDAV); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -31,23 +30,22 @@ class Sabre_CalDAV_Property_SupportedCalendarComponentSetTest extends PHPUnit_Fr $this->assertEquals( ' -' . -'' . -'' . +'. +''. +''. ' ', $xml); - } /** * @depends testSimple */ - function testUnserializer() { - + public function testUnserializer() + { $xml = ' -' . -'' . -'' . +'. +''. +''. ''; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); @@ -60,7 +58,5 @@ class Sabre_CalDAV_Property_SupportedCalendarComponentSetTest extends PHPUnit_Fr 'VJOURNAL', ), $property->getValue()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCalendarDataTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCalendarDataTest.php index 3b3c84c9..b9201322 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCalendarDataTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCalendarDataTest.php @@ -1,24 +1,23 @@ createElement('d:root'); - $root->setAttribute('xmlns:d','DAV:'); - $root->setAttribute('xmlns:cal',Sabre_CalDAV_Plugin::NS_CALDAV); + $root->setAttribute('xmlns:d', 'DAV:'); + $root->setAttribute('xmlns:cal', Sabre_CalDAV_Plugin::NS_CALDAV); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -30,11 +29,9 @@ class Sabre_CalDAV_Property_SupportedCalendarDataTest extends PHPUnit_Framework_ $this->assertEquals( ' -' . -'' . +'. +''. ' ', $xml); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCollationSetTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCollationSetTest.php index 75ce2413..d47ad0f6 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCollationSetTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Property/SupportedCollationSetTest.php @@ -1,24 +1,23 @@ createElement('d:root'); - $root->setAttribute('xmlns:d','DAV:'); - $root->setAttribute('xmlns:cal',Sabre_CalDAV_Plugin::NS_CALDAV); + $root->setAttribute('xmlns:d', 'DAV:'); + $root->setAttribute('xmlns:cal', Sabre_CalDAV_Plugin::NS_CALDAV); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -30,13 +29,11 @@ class Sabre_CalDAV_Property_SupportedCollationSetTest extends PHPUnit_Framework_ $this->assertEquals( ' -' . -'i;ascii-casemap' . -'i;octet' . -'i;unicode-casemap' . +'. +'i;ascii-casemap'. +'i;octet'. +'i;unicode-casemap'. ' ', $xml); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Schedule/IMip/Mock.php b/dav/SabreDAV/tests/Sabre/CalDAV/Schedule/IMip/Mock.php index 3dc83fff..273a6e4e 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Schedule/IMip/Mock.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Schedule/IMip/Mock.php @@ -3,48 +3,41 @@ /** * iMIP handler. * - * This class is responsible for sending out iMIP messages. iMIP is the - * email-based transport for iTIP. iTIP deals with scheduling operations for + * This class is responsible for sending out iMIP messages. iMIP is the + * email-based transport for iTIP. iTIP deals with scheduling operations for * iCalendar objects. * - * If you want to customize the email that gets sent out, you can do so by + * If you want to customize the email that gets sent out, you can do so by * extending this class and overriding the sendMessage method. - * - * @package Sabre - * @subpackage CalDAV - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. - * @author Evert Pot (http://www.rooftopsolutions.nl/) + * + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved + * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class Sabre_CalDAV_Schedule_IMip_Mock extends Sabre_CalDAV_Schedule_IMip { - +class Sabre_CalDAV_Schedule_IMip_Mock extends Sabre_CalDAV_Schedule_IMip +{ protected $emails = array(); /** * This function is reponsible for sending the actual email. * - * @param string $to Recipient email address + * @param string $to Recipient email address * @param string $subject Subject of the email - * @param string $body iCalendar body - * @param array $headers List of headers - * @return void + * @param string $body iCalendar body + * @param array $headers List of headers */ - protected function mail($to, $subject, $body, array $headers) { - + protected function mail($to, $subject, $body, array $headers) + { $this->emails[] = array( 'to' => $to, 'subject' => $subject, 'body' => $body, 'headers' => $headers, ); - } - public function getSentEmails() { - + public function getSentEmails() + { return $this->emails; - } - - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/Schedule/OutboxTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/Schedule/OutboxTest.php index b6b7afdc..fb27b7e5 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/Schedule/OutboxTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/Schedule/OutboxTest.php @@ -1,9 +1,9 @@ assertEquals('outbox', $outbox->getName()); $this->assertEquals(array(), $outbox->getChildren()); @@ -12,7 +12,7 @@ class Sabre_CalDAV_Schedule_OutboxTest extends PHPUnit_Framework_TestCase { $this->assertEquals(array( array( - 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}schedule-query-freebusy', + 'privilege' => '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}schedule-query-freebusy', 'principal' => 'principals/user1', 'protected' => true, ), @@ -32,27 +32,22 @@ class Sabre_CalDAV_Schedule_OutboxTest extends PHPUnit_Framework_TestCase { if (!$ok) { $this->fail('Exception was not emitted'); } - } - function testGetSupportedPrivilegeSet() { - + public function testGetSupportedPrivilegeSet() + { $outbox = new Sabre_CalDAV_Schedule_Outbox('principals/user1'); $r = $outbox->getSupportedPrivilegeSet(); $ok = false; - foreach($r['aggregates'] as $priv) { - - if ($priv['privilege'] == '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}schedule-query-freebusy') { + foreach ($r['aggregates'] as $priv) { + if ($priv['privilege'] == '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}schedule-query-freebusy') { $ok = true; } } if (!$ok) { - $this->fail('{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}schedule-query-freebusy was not found as a supported privilege'); + $this->fail('{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}schedule-query-freebusy was not found as a supported privilege'); } - } - - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/ServerTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/ServerTest.php index f00be7b1..51986302 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/ServerTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/ServerTest.php @@ -2,16 +2,18 @@ require_once 'Sabre/CalDAV/TestUtil.php'; -class Sabre_CalDAV_ServerTest extends PHPUnit_Framework_TestCase { - +class Sabre_CalDAV_ServerTest extends PHPUnit_Framework_TestCase +{ /** * The CalDAV server is a simple script that just composes a * Sabre_DAV_Server. All we really have to do is check if the setup * is done correctly. */ - function testSetup() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function testSetup() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $pdo = Sabre_CalDAV_TestUtil::getSQLiteDB(); $server = new Sabre_CalDAV_Server($pdo); @@ -25,7 +27,5 @@ class Sabre_CalDAV_ServerTest extends PHPUnit_Framework_TestCase { $this->assertTrue($node instanceof Sabre_DAV_SimpleCollection); $this->assertEquals('root', $node->getName()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/TestUtil.php b/dav/SabreDAV/tests/Sabre/CalDAV/TestUtil.php index 01065fec..7f91e970 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/TestUtil.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/TestUtil.php @@ -1,25 +1,26 @@ setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); + $pdo = new PDO('sqlite:'.SABRE_TEMPDIR.'/testdb.sqlite'); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Yup this is definitely not 'fool proof', but good enough for now. - $queries = explode(';', file_get_contents(__DIR__ . '/../../../examples/sql/sqlite.calendars.sql')); - foreach($queries as $query) { + $queries = explode(';', file_get_contents(__DIR__.'/../../../examples/sql/sqlite.calendars.sql')); + foreach ($queries as $query) { $pdo->exec($query); } // Inserting events through a backend class. @@ -45,12 +46,12 @@ class Sabre_CalDAV_TestUtil { ) ); $backend->createCalendarObject($calendarId, 'UUID-2345', self::getTestCalendarData()); - return $pdo; + return $pdo; } - static function getTestCalendarData($type = 1) { - + public static function getTestCalendarData($type = 1) + { $calendarData = 'BEGIN:VCALENDAR VERSION:2.0 PRODID:-//Apple Inc.//iCal 4.0.1//EN @@ -78,108 +79,106 @@ TRANSP:TRANSPARENT SUMMARY:Something here DTSTAMP:20100228T130202Z'; - switch($type) { - case 1 : - $calendarData.="\nDTSTART;TZID=Asia/Seoul:20100223T060000\nDTEND;TZID=Asia/Seoul:20100223T070000\n"; + switch ($type) { + case 1: + $calendarData .= "\nDTSTART;TZID=Asia/Seoul:20100223T060000\nDTEND;TZID=Asia/Seoul:20100223T070000\n"; break; - case 2 : - $calendarData.="\nDTSTART:20100223T060000\nDTEND:20100223T070000\n"; + case 2: + $calendarData .= "\nDTSTART:20100223T060000\nDTEND:20100223T070000\n"; break; - case 3 : - $calendarData.="\nDTSTART;VALUE=DATE:20100223\nDTEND;VALUE=DATE:20100223\n"; + case 3: + $calendarData .= "\nDTSTART;VALUE=DATE:20100223\nDTEND;VALUE=DATE:20100223\n"; break; - case 4 : - $calendarData.="\nDTSTART;TZID=Asia/Seoul:20100223T060000\nDURATION:PT1H\n"; + case 4: + $calendarData .= "\nDTSTART;TZID=Asia/Seoul:20100223T060000\nDURATION:PT1H\n"; break; - case 5 : - $calendarData.="\nDTSTART;TZID=Asia/Seoul:20100223T060000\nDURATION:-P5D\n"; + case 5: + $calendarData .= "\nDTSTART;TZID=Asia/Seoul:20100223T060000\nDURATION:-P5D\n"; break; - case 6 : - $calendarData.="\nDTSTART;VALUE=DATE:20100223\n"; + case 6: + $calendarData .= "\nDTSTART;VALUE=DATE:20100223\n"; break; - case 7 : - $calendarData.="\nDTSTART;VALUE=DATETIME:20100223T060000\n"; + case 7: + $calendarData .= "\nDTSTART;VALUE=DATETIME:20100223T060000\n"; break; // No DTSTART, so intentionally broken - case 'X' : - $calendarData.="\n"; + case 'X': + $calendarData .= "\n"; break; } - - $calendarData.='ATTENDEE;PARTSTAT=NEEDS-ACTION:mailto:lisa@example.com + $calendarData .= 'ATTENDEE;PARTSTAT=NEEDS-ACTION:mailto:lisa@example.com SEQUENCE:2 END:VEVENT END:VCALENDAR'; return $calendarData; - } - static function getTestTODO($type = 'due') { + public static function getTestTODO($type = 'due') + { + switch ($type) { - switch($type) { - - case 'due' : - $extra = "DUE:20100104T000000Z"; + case 'due': + $extra = 'DUE:20100104T000000Z'; break; - case 'due2' : - $extra = "DUE:20060104T000000Z"; + case 'due2': + $extra = 'DUE:20060104T000000Z'; break; - case 'due_date' : - $extra = "DUE;VALUE=DATE:20060104"; + case 'due_date': + $extra = 'DUE;VALUE=DATE:20060104'; break; - case 'due_tz' : - $extra = "DUE;TZID=Asia/Seoul:20060104T000000Z"; + case 'due_tz': + $extra = 'DUE;TZID=Asia/Seoul:20060104T000000Z'; break; - case 'due_dtstart' : + case 'due_dtstart': $extra = "DTSTART:20050223T060000Z\nDUE:20060104T000000Z"; break; - case 'due_dtstart2' : + case 'due_dtstart2': $extra = "DTSTART:20090223T060000Z\nDUE:20100104T000000Z"; break; - case 'dtstart' : + case 'dtstart': $extra = 'DTSTART:20100223T060000Z'; break; - case 'dtstart2' : + case 'dtstart2': $extra = 'DTSTART:20060223T060000Z'; break; - case 'dtstart_date' : + case 'dtstart_date': $extra = 'DTSTART;VALUE=DATE:20100223'; break; - case 'dtstart_tz' : + case 'dtstart_tz': $extra = 'DTSTART;TZID=Asia/Seoul:20100223T060000Z'; break; - case 'dtstart_duration' : + case 'dtstart_duration': $extra = "DTSTART:20061023T060000Z\nDURATION:PT1H"; break; - case 'dtstart_duration2' : + case 'dtstart_duration2': $extra = "DTSTART:20101023T060000Z\nDURATION:PT1H"; break; - case 'completed' : + case 'completed': $extra = 'COMPLETED:20060601T000000Z'; break; - case 'completed2' : + case 'completed2': $extra = 'COMPLETED:20090601T000000Z'; break; - case 'created' : + case 'created': $extra = 'CREATED:20060601T000000Z'; break; - case 'created2' : + case 'created2': $extra = 'CREATED:20090601T000000Z'; break; - case 'completedcreated' : + case 'completedcreated': $extra = "CREATED:20060601T000000Z\nCOMPLETED:20070101T000000Z"; break; - case 'completedcreated2' : + case 'completedcreated2': $extra = "CREATED:20090601T000000Z\nCOMPLETED:20100101T000000Z"; break; - case 'notime' : + case 'notime': $extra = 'X-FILLER:oh hello'; break; - default : - throw new Exception('Unknown type: ' . $type); + default: + throw new Exception('Unknown type: '.$type); } @@ -188,7 +187,7 @@ VERSION:2.0 PRODID:-//Example Corp.//CalDAV Client//EN BEGIN:VTODO DTSTAMP:20060205T235335Z -' . $extra . ' +' .$extra.' STATUS:NEEDS-ACTION SUMMARY:Task #1 UID:DDDEEB7915FA61233B861457@example.com @@ -200,7 +199,5 @@ END:VTODO END:VCALENDAR'; return $todo; - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/UserCalendarsTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/UserCalendarsTest.php index 7dfb6121..39a349e7 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/UserCalendarsTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/UserCalendarsTest.php @@ -6,8 +6,8 @@ require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; /** * @covers Sabre_CalDAV_UserCalendars */ -class Sabre_CalDAV_UserCalendarsTest extends PHPUnit_Framework_TestCase { - +class Sabre_CalDAV_UserCalendarsTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_CalDAV_UserCalendars */ @@ -18,52 +18,48 @@ class Sabre_CalDAV_UserCalendarsTest extends PHPUnit_Framework_TestCase { protected $backend; protected $principalBackend; - function setup() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function setup() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $this->backend = Sabre_CalDAV_TestUtil::getBackend(); $this->principalBackend = new Sabre_DAVACL_MockPrincipalBackend('realm'); $this->usercalendars = new Sabre_CalDAV_UserCalendars($this->principalBackend, $this->backend, 'principals/user1'); - } - function testSimple() { - - $this->assertEquals('user1',$this->usercalendars->getName()); - + public function testSimple() + { + $this->assertEquals('user1', $this->usercalendars->getName()); } /** * @expectedException Sabre_DAV_Exception_NotFound * @depends testSimple */ - function testGetChildNotFound() { - + public function testGetChildNotFound() + { $this->usercalendars->getChild('randomname'); - } - function testChildExists() { - + public function testChildExists() + { $this->assertFalse($this->usercalendars->childExists('foo')); $this->assertTrue($this->usercalendars->childExists('UUID-123467')); - } - function testGetOwner() { - + public function testGetOwner() + { $this->assertEquals('principals/user1', $this->usercalendars->getOwner()); - } - function testGetGroup() { - + public function testGetGroup() + { $this->assertNull($this->usercalendars->getGroup()); - } - function testGetACL() { - + public function testGetACL() + { $expected = array( array( 'privilege' => '{DAV:}read', @@ -92,94 +88,82 @@ class Sabre_CalDAV_UserCalendarsTest extends PHPUnit_Framework_TestCase { ), ); $this->assertEquals($expected, $this->usercalendars->getACL()); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testSetACL() { - + public function testSetACL() + { $this->usercalendars->setACL(array()); - } /** * @expectedException Sabre_DAV_Exception_Forbidden * @depends testSimple */ - function testSetName() { - + public function testSetName() + { $this->usercalendars->setName('bla'); - } /** * @expectedException Sabre_DAV_Exception_Forbidden * @depends testSimple */ - function testDelete() { - + public function testDelete() + { $this->usercalendars->delete(); - } /** * @depends testSimple */ - function testGetLastModified() { - + public function testGetLastModified() + { $this->assertNull($this->usercalendars->getLastModified()); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed * @depends testSimple */ - function testCreateFile() { - + public function testCreateFile() + { $this->usercalendars->createFile('bla'); - } - /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed * @depends testSimple */ - function testCreateDirectory() { - + public function testCreateDirectory() + { $this->usercalendars->createDirectory('bla'); - } /** * @depends testSimple */ - function testCreateExtendedCollection() { - + public function testCreateExtendedCollection() + { $result = $this->usercalendars->createExtendedCollection('newcalendar', array('{DAV:}collection', '{urn:ietf:params:xml:ns:caldav}calendar'), array()); $this->assertNull($result); $cals = $this->backend->getCalendarsForUser('principals/user1'); - $this->assertEquals(3,count($cals)); - + $this->assertEquals(3, count($cals)); } /** * @expectedException Sabre_DAV_Exception_InvalidResourceType * @depends testSimple */ - function testCreateExtendedCollectionBadResourceType() { - - $this->usercalendars->createExtendedCollection('newcalendar', array('{DAV:}collection','{DAV:}blabla'), array()); - + public function testCreateExtendedCollectionBadResourceType() + { + $this->usercalendars->createExtendedCollection('newcalendar', array('{DAV:}collection', '{DAV:}blabla'), array()); } - function testGetSupportedPrivilegesSet() { - + public function testGetSupportedPrivilegesSet() + { $this->assertNull($this->usercalendars->getSupportedPrivilegeSet()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/ValidateICalTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/ValidateICalTest.php index 42e8aebb..cc4bce7c 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/ValidateICalTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/ValidateICalTest.php @@ -4,8 +4,8 @@ require_once 'Sabre/CalDAV/Backend/Mock.php'; require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { - +class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_DAV_Server */ @@ -15,24 +15,24 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { */ protected $calBackend; - function setUp() { - + public function setUp() + { $calendars = array( array( 'id' => 'calendar1', 'principaluri' => 'principals/admin', 'uri' => 'calendar1', - '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet( array('VEVENT','VTODO','VJOURNAL') ), + '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VEVENT', 'VTODO', 'VJOURNAL')), ), array( 'id' => 'calendar2', 'principaluri' => 'principals/admin', 'uri' => 'calendar2', - '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet( array('VTODO','VJOURNAL') ), - ) + '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet(array('VTODO', 'VJOURNAL')), + ), ); - $this->calBackend = new Sabre_CalDAV_Backend_Mock($calendars,array()); + $this->calBackend = new Sabre_CalDAV_Backend_Mock($calendars, array()); $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $tree = array( @@ -47,20 +47,18 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = new Sabre_HTTP_ResponseMock(); $this->server->httpResponse = $response; - } - function request(Sabre_HTTP_Request $request) { - + public function request(Sabre_HTTP_Request $request) + { $this->server->httpRequest = $request; $this->server->exec(); return $this->server->httpResponse; - } - function testCreateFile() { - + public function testCreateFile() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar1/blabla.ics', @@ -69,11 +67,10 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $response->status); - } - function testCreateFileValid() { - + public function testCreateFileValid() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar1/blabla.ics', @@ -82,19 +79,18 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 201 Created', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); + $this->assertEquals('HTTP/1.1 201 Created', $response->status, 'Incorrect status returned! Full response body: '.$response->body); $expected = array( - 'uri' => 'blabla.ics', + 'uri' => 'blabla.ics', 'calendardata' => "BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nUID:foo\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n", - 'calendarid' => 'calendar1', + 'calendarid' => 'calendar1', ); - $this->assertEquals($expected, $this->calBackend->getCalendarObject('calendar1','blabla.ics')); - + $this->assertEquals($expected, $this->calBackend->getCalendarObject('calendar1', 'blabla.ics')); } - function testCreateFileNoComponents() { - + public function testCreateFileNoComponents() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar1/blabla.ics', @@ -103,12 +99,11 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: '.$response->body); } - function testCreateFileNoUID() { - + public function testCreateFileNoUID() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar1/blabla.ics', @@ -117,12 +112,11 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: '.$response->body); } - function testCreateFileVCard() { - + public function testCreateFileVCard() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar1/blabla.ics', @@ -131,12 +125,11 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); - + $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $response->status, 'Incorrect status returned! Full response body: '.$response->body); } - function testCreateFile2Components() { - + public function testCreateFile2Components() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar1/blabla.ics', @@ -145,12 +138,11 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: '.$response->body); } - function testCreateFile2UIDS() { - + public function testCreateFile2UIDS() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar1/blabla.ics', @@ -159,12 +151,11 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: '.$response->body); } - function testCreateFileWrongComponent() { - + public function testCreateFileWrongComponent() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar1/blabla.ics', @@ -173,13 +164,12 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: '.$response->body); } - function testUpdateFile() { - - $this->calBackend->createCalendarObject('calendar1','blabla.ics','foo'); + public function testUpdateFile() + { + $this->calBackend->createCalendarObject('calendar1', 'blabla.ics', 'foo'); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar1/blabla.ics', @@ -188,12 +178,11 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $response->status); - } - function testUpdateFileParsableBody() { - - $this->calBackend->createCalendarObject('calendar1','blabla.ics','foo'); + public function testUpdateFileParsableBody() + { + $this->calBackend->createCalendarObject('calendar1', 'blabla.ics', 'foo'); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar1/blabla.ics', @@ -206,17 +195,16 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $this->assertEquals('HTTP/1.1 204 No Content', $response->status); $expected = array( - 'uri' => 'blabla.ics', + 'uri' => 'blabla.ics', 'calendardata' => $body, - 'calendarid' => 'calendar1', + 'calendarid' => 'calendar1', ); - $this->assertEquals($expected, $this->calBackend->getCalendarObject('calendar1','blabla.ics')); - + $this->assertEquals($expected, $this->calBackend->getCalendarObject('calendar1', 'blabla.ics')); } - function testCreateFileInvalidComponent() { - + public function testCreateFileInvalidComponent() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar2/blabla.ics', @@ -225,13 +213,12 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 403 Forbidden', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); - + $this->assertEquals('HTTP/1.1 403 Forbidden', $response->status, 'Incorrect status returned! Full response body: '.$response->body); } - function testUpdateFileInvalidComponent() { - - $this->calBackend->createCalendarObject('calendar2','blabla.ics','foo'); + public function testUpdateFileInvalidComponent() + { + $this->calBackend->createCalendarObject('calendar2', 'blabla.ics', 'foo'); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/calendars/admin/calendar2/blabla.ics', @@ -240,7 +227,6 @@ class Sabre_CalDAV_ValidateICalTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 403 Forbidden', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); - + $this->assertEquals('HTTP/1.1 403 Forbidden', $response->status, 'Incorrect status returned! Full response body: '.$response->body); } } diff --git a/dav/SabreDAV/tests/Sabre/CalDAV/VersionTest.php b/dav/SabreDAV/tests/Sabre/CalDAV/VersionTest.php index 717edd8a..f698dbde 100644 --- a/dav/SabreDAV/tests/Sabre/CalDAV/VersionTest.php +++ b/dav/SabreDAV/tests/Sabre/CalDAV/VersionTest.php @@ -1,15 +1,13 @@ assertEquals(-1, version_compare('1.0.0',$v)); + $this->assertEquals(-1, version_compare('1.0.0', $v)); $s = Sabre_CalDAV_Version::STABILITY; - $this->assertTrue($s == 'alpha' || $s == 'beta' || $s =='stable'); - + $this->assertTrue($s == 'alpha' || $s == 'beta' || $s == 'stable'); } - } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/AbstractPluginTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/AbstractPluginTest.php index 3b40d45e..437e127f 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/AbstractPluginTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/AbstractPluginTest.php @@ -3,8 +3,8 @@ require_once 'Sabre/CardDAV/Backend/Mock.php'; require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; -abstract class Sabre_CardDAV_AbstractPluginTest extends PHPUnit_Framework_TestCase { - +abstract class Sabre_CardDAV_AbstractPluginTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_CardDAV_Plugin */ @@ -18,14 +18,14 @@ abstract class Sabre_CardDAV_AbstractPluginTest extends PHPUnit_Framework_TestCa */ protected $backend; - function setUp() { - + public function setUp() + { $this->backend = new Sabre_CardDAV_Backend_Mock(); $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $tree = array( new Sabre_CardDAV_AddressBookRoot($principalBackend, $this->backend), - new Sabre_DAVACL_PrincipalCollection($principalBackend) + new Sabre_DAVACL_PrincipalCollection($principalBackend), ); $this->plugin = new Sabre_CardDAV_Plugin(); @@ -33,7 +33,5 @@ abstract class Sabre_CardDAV_AbstractPluginTest extends PHPUnit_Framework_TestCa $this->server = new Sabre_DAV_Server($tree); $this->server->addPlugin($this->plugin); $this->server->debugExceptions = true; - } - } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookQueryParserTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookQueryParserTest.php index 54fa5344..b84a8ccf 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookQueryParserTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookQueryParserTest.php @@ -1,20 +1,20 @@ parse(); - return $q; + return $q; } - function testFilterBasic() { - + public function testFilterBasic() + { $xml = array( '', '', @@ -24,7 +24,7 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas ' ', ' ', ' ', - '' + '', ); $q = $this->parse($xml); @@ -49,10 +49,10 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas $this->assertNull($q->limit); $this->assertEquals('anyof', $q->test); - } - function testNoFilter() { + public function testNoFilter() + { // This is non-standard, but helps working around a KDE bug $xml = array( @@ -61,7 +61,7 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas ' ', ' ', ' ', - '' + '', ); $q = $this->parse($xml); @@ -78,14 +78,13 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas $this->assertNull($q->limit); $this->assertEquals('anyof', $q->test); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testFilterDoubleFilter() { - + public function testFilterDoubleFilter() + { $xml = array( '', '', @@ -98,17 +97,16 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas ' ', ' ', ' ', - '' + '', ); $q = $this->parse($xml); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testFilterCorruptTest() { - + public function testFilterCorruptTest() + { $xml = array( '', '', @@ -118,15 +116,14 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas ' ', ' ', ' ', - '' + '', ); $q = $this->parse($xml); - } - function testPropFilter() { - + public function testPropFilter() + { $xml = array( '', '', @@ -141,7 +138,7 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas ' ', ' ', ' 4', - '' + '', ); $q = $this->parse($xml); @@ -173,13 +170,12 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas $q->filters ); - $this->assertEquals(4,$q->limit); + $this->assertEquals(4, $q->limit); $this->assertEquals('allof', $q->test); - } - function testParamFilter() { - + public function testParamFilter() + { $xml = array( '', '', @@ -194,7 +190,7 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas ' ', ' ', ' ', - '' + '', ); $q = $this->parse($xml); @@ -209,12 +205,12 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas array( 'name' => 'BLA', 'is-not-defined' => false, - 'text-match' => null + 'text-match' => null, ), array( 'name' => 'BLA2', 'is-not-defined' => true, - 'text-match' => null + 'text-match' => null, ), ), 'text-matches' => array(), @@ -222,11 +218,10 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas ), $q->filters ); - } - function testTextMatch() { - + public function testTextMatch() + { $xml = array( '', '', @@ -244,7 +239,7 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas ' ', ' ', ' ', - '' + '', ); $q = $this->parse($xml); @@ -263,7 +258,7 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas 'negate-condition' => false, 'collation' => 'i;unicode-casemap', 'match-type' => 'contains', - 'value' => 'foo', + 'value' => 'foo', ), ), ), @@ -272,39 +267,38 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas 'negate-condition' => false, 'collation' => 'i;unicode-casemap', 'match-type' => 'contains', - 'value' => 'evert', + 'value' => 'evert', ), array( 'negate-condition' => false, 'collation' => 'i;octet', 'match-type' => 'contains', - 'value' => 'evert', + 'value' => 'evert', ), array( 'negate-condition' => true, 'collation' => 'i;unicode-casemap', 'match-type' => 'contains', - 'value' => 'rene', + 'value' => 'rene', ), array( 'negate-condition' => false, 'collation' => 'i;unicode-casemap', 'match-type' => 'starts-with', - 'value' => 'e', + 'value' => 'e', ), ), ), ), $q->filters ); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testBadTextMatch() { - + public function testBadTextMatch() + { $xml = array( '', '', @@ -316,10 +310,9 @@ class Sabre_CardDAV_AddressBookQueryParserTest extends PHPUnit_Framework_TestCas ' evert', ' ', ' ', - '' + '', ); $q = $this->parse($xml); - } } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookQueryTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookQueryTest.php index 598f653b..3a1f4762 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookQueryTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookQueryTest.php @@ -3,10 +3,10 @@ require_once 'Sabre/CardDAV/AbstractPluginTest.php'; require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_CardDAV_AddressBookQueryTest extends Sabre_CardDAV_AbstractPluginTest { - - function testQuery() { - +class Sabre_CardDAV_AddressBookQueryTest extends Sabre_CardDAV_AbstractPluginTest +{ + public function testQuery() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'REQUEST_URI' => '/addressbooks/user1/book1', @@ -32,31 +32,29 @@ class Sabre_CardDAV_AddressBookQueryTest extends Sabre_CardDAV_AbstractPluginTes $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:' . $response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:'.$response->body); // using the client for parsing - $client = new Sabre_DAV_Client(array('baseUri'=>'/')); + $client = new Sabre_DAV_Client(array('baseUri' => '/')); $result = $client->parseMultiStatus($response->body); $this->assertEquals(array( '/addressbooks/user1/book1/card1' => array( 200 => array( - '{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD") . '"', + '{DAV:}getetag' => '"'.md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD").'"', ), ), '/addressbooks/user1/book1/card2' => array( 200 => array( - '{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:45678\nEND:VCARD") . '"', + '{DAV:}getetag' => '"'.md5("BEGIN:VCARD\nVERSION:3.0\nUID:45678\nEND:VCARD").'"', ), - ) + ), ), $result); - - } - function testQueryDepth0() { - + public function testQueryDepth0() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'REQUEST_URI' => '/addressbooks/user1/book1/card1', @@ -82,26 +80,24 @@ class Sabre_CardDAV_AddressBookQueryTest extends Sabre_CardDAV_AbstractPluginTes $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:' . $response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:'.$response->body); // using the client for parsing - $client = new Sabre_DAV_Client(array('baseUri'=>'/')); + $client = new Sabre_DAV_Client(array('baseUri' => '/')); $result = $client->parseMultiStatus($response->body); $this->assertEquals(array( '/addressbooks/user1/book1/card1' => array( 200 => array( - '{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD") . '"', + '{DAV:}getetag' => '"'.md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD").'"', ), ), ), $result); - - } - function testQueryNoMatch() { - + public function testQueryNoMatch() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'REQUEST_URI' => '/addressbooks/user1/book1', @@ -127,19 +123,18 @@ class Sabre_CardDAV_AddressBookQueryTest extends Sabre_CardDAV_AbstractPluginTes $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:' . $response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:'.$response->body); // using the client for parsing - $client = new Sabre_DAV_Client(array('baseUri'=>'/')); + $client = new Sabre_DAV_Client(array('baseUri' => '/')); $result = $client->parseMultiStatus($response->body); $this->assertEquals(array(), $result); - } - function testQueryLimit() { - + public function testQueryLimit() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'REQUEST_URI' => '/addressbooks/user1/book1', @@ -166,22 +161,19 @@ class Sabre_CardDAV_AddressBookQueryTest extends Sabre_CardDAV_AbstractPluginTes $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:' . $response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:'.$response->body); // using the client for parsing - $client = new Sabre_DAV_Client(array('baseUri'=>'/')); + $client = new Sabre_DAV_Client(array('baseUri' => '/')); $result = $client->parseMultiStatus($response->body); $this->assertEquals(array( '/addressbooks/user1/book1/card1' => array( 200 => array( - '{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD"). '"', + '{DAV:}getetag' => '"'.md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD").'"', ), ), ), $result); - - } - } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookRootTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookRootTest.php index aac3ea1d..d1f244e9 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookRootTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookRootTest.php @@ -1,18 +1,17 @@ assertEquals('addressbooks', $root->getName()); - } - function testGetChildForPrincipal() { - + public function testGetChildForPrincipal() + { $pBackend = new Sabre_DAVACL_MockPrincipalBackend(); $cBackend = new Sabre_CardDAV_Backend_Mock(); $root = new Sabre_CardDAV_AddressBookRoot($pBackend, $cBackend); @@ -22,6 +21,5 @@ class Sabre_CardDAV_AddressBookRootTest extends PHPUnit_Framework_TestCase { $this->assertInstanceOf('Sabre_CardDAV_UserAddressBooks', $children[0]); $this->assertEquals('user1', $children[0]->getName()); - } } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookTest.php index f0271db4..44b31731 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/AddressBookTest.php @@ -2,16 +2,16 @@ require_once 'Sabre/CardDAV/Backend/Mock.php'; -class Sabre_CardDAV_AddressBookTest extends PHPUnit_Framework_TestCase { - +class Sabre_CardDAV_AddressBookTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_CardDAV_AddressBook */ protected $ab; protected $backend; - function setUp() { - + public function setUp() + { $this->backend = new Sabre_CardDAV_Backend_Mock(); $this->ab = new Sabre_CardDAV_AddressBook( $this->backend, @@ -22,105 +22,93 @@ class Sabre_CardDAV_AddressBookTest extends PHPUnit_Framework_TestCase { 'principaluri' => 'principals/user1', ) ); - } - function testGetName() { - + public function testGetName() + { $this->assertEquals('book1', $this->ab->getName()); - } - function testGetChild() { - + public function testGetChild() + { $card = $this->ab->getChild('card1'); $this->assertInstanceOf('Sabre_CardDAV_Card', $card); $this->assertEquals('card1', $card->getName()); - } /** * @expectedException Sabre_DAV_Exception_NotFound */ - function testGetChildNotFound() { - + public function testGetChildNotFound() + { $card = $this->ab->getChild('card3'); - } - function testGetChildren() { - + public function testGetChildren() + { $cards = $this->ab->getChildren(); $this->assertEquals(2, count($cards)); $this->assertEquals('card1', $cards[0]->getName()); $this->assertEquals('card2', $cards[1]->getName()); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testCreateDirectory() { - + public function testCreateDirectory() + { $this->ab->createDirectory('name'); - } - function testCreateFile() { - - $file = fopen('php://memory','r+'); - fwrite($file,'foo'); + public function testCreateFile() + { + $file = fopen('php://memory', 'r+'); + fwrite($file, 'foo'); rewind($file); - $this->ab->createFile('card2',$file); + $this->ab->createFile('card2', $file); $this->assertEquals('foo', $this->backend->cards['foo']['card2']); - } - function testDelete() { - + public function testDelete() + { $this->ab->delete(); $this->assertEquals(array(), $this->backend->addressBooks); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testSetName() { - + public function testSetName() + { $this->ab->setName('foo'); - } - function testGetLastModified() { - + public function testGetLastModified() + { $this->assertNull($this->ab->getLastModified()); - } - function testUpdateProperties() { - + public function testUpdateProperties() + { $this->assertTrue( $this->ab->updateProperties(array('{DAV:}displayname' => 'barrr')) ); $this->assertEquals('barrr', $this->backend->addressBooks[0]['{DAV:}displayname']); - } - function testGetProperties() { - + public function testGetProperties() + { $props = $this->ab->getProperties(array('{DAV:}displayname')); $this->assertEquals(array( '{DAV:}displayname' => 'd-name', ), $props); - } - function testACLMethods() { - + public function testACLMethods() + { $this->assertEquals('principals/user1', $this->ab->getOwner()); $this->assertNull($this->ab->getGroup()); $this->assertEquals(array( @@ -135,25 +123,20 @@ class Sabre_CardDAV_AddressBookTest extends PHPUnit_Framework_TestCase { 'protected' => true, ), ), $this->ab->getACL()); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testSetACL() { - - $this->ab->setACL(array()); - + public function testSetACL() + { + $this->ab->setACL(array()); } - function testGetSupportedPrivilegeSet() { - + public function testGetSupportedPrivilegeSet() + { $this->assertNull( $this->ab->getSupportedPrivilegeSet() ); - } - - } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/Backend/AbstractPDOTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/Backend/AbstractPDOTest.php index 02179ff0..f4be00df 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/Backend/AbstractPDOTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/Backend/AbstractPDOTest.php @@ -1,7 +1,7 @@ backend = new Sabre_CardDAV_Backend_PDO($this->getPDO()); - } - public function testGetAddressBooksForUser() { - + public function testGetAddressBooksForUser() + { $result = $this->backend->getAddressBooksForUser('principals/user1'); $expected = array( @@ -29,21 +29,20 @@ abstract class Sabre_CardDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_T 'uri' => 'book1', 'principaluri' => 'principals/user1', '{DAV:}displayname' => 'book1', - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => 'addressbook 1', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => 'addressbook 1', '{http://calendarserver.org/ns/}getctag' => 1, - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), - ) + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), + ), ); $this->assertEquals($expected, $result); - } - public function testUpdateAddressBookInvalidProp() { - + public function testUpdateAddressBookInvalidProp() + { $result = $this->backend->updateAddressBook(1, array( '{DAV:}displayname' => 'updated', - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => 'updated', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => 'updated', '{DAV:}foo' => 'bar', )); @@ -57,18 +56,17 @@ abstract class Sabre_CardDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_T 'uri' => 'book1', 'principaluri' => 'principals/user1', '{DAV:}displayname' => 'book1', - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => 'addressbook 1', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => 'addressbook 1', '{http://calendarserver.org/ns/}getctag' => 1, - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), - ) + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), + ), ); $this->assertEquals($expected, $result); - } - public function testUpdateAddressBookNoProps() { - + public function testUpdateAddressBookNoProps() + { $result = $this->backend->updateAddressBook(1, array()); $this->assertFalse($result); @@ -81,22 +79,20 @@ abstract class Sabre_CardDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_T 'uri' => 'book1', 'principaluri' => 'principals/user1', '{DAV:}displayname' => 'book1', - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => 'addressbook 1', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => 'addressbook 1', '{http://calendarserver.org/ns/}getctag' => 1, - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), - ) + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), + ), ); $this->assertEquals($expected, $result); - - } - public function testUpdateAddressBookSuccess() { - + public function testUpdateAddressBookSuccess() + { $result = $this->backend->updateAddressBook(1, array( '{DAV:}displayname' => 'updated', - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => 'updated', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => 'updated', )); $this->assertTrue($result); @@ -109,41 +105,37 @@ abstract class Sabre_CardDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_T 'uri' => 'book1', 'principaluri' => 'principals/user1', '{DAV:}displayname' => 'updated', - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => 'updated', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => 'updated', '{http://calendarserver.org/ns/}getctag' => 2, - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), - ) + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), + ), ); $this->assertEquals($expected, $result); - - } - public function testDeleteAddressBook() { - + public function testDeleteAddressBook() + { $this->backend->deleteAddressBook(1); $this->assertEquals(array(), $this->backend->getAddressBooksForUser('principals/user1')); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - public function testCreateAddressBookUnsupportedProp() { - - $this->backend->createAddressBook('principals/user1','book2', array( + public function testCreateAddressBookUnsupportedProp() + { + $this->backend->createAddressBook('principals/user1', 'book2', array( '{DAV:}foo' => 'bar', )); - } - public function testCreateAddressBookSuccess() { - - $this->backend->createAddressBook('principals/user1','book2', array( + public function testCreateAddressBookSuccess() + { + $this->backend->createAddressBook('principals/user1', 'book2', array( '{DAV:}displayname' => 'book2', - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => 'addressbook 2', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => 'addressbook 2', )); $expected = array( @@ -152,27 +144,26 @@ abstract class Sabre_CardDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_T 'uri' => 'book1', 'principaluri' => 'principals/user1', '{DAV:}displayname' => 'book1', - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => 'addressbook 1', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => 'addressbook 1', '{http://calendarserver.org/ns/}getctag' => 1, - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), ), array( 'id' => 2, 'uri' => 'book2', 'principaluri' => 'principals/user1', '{DAV:}displayname' => 'book2', - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => 'addressbook 2', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => 'addressbook 2', '{http://calendarserver.org/ns/}getctag' => 1, - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), - ) + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), + ), ); $result = $this->backend->getAddressBooksForUser('principals/user1'); $this->assertEquals($expected, $result); - } - public function testGetCards() { - + public function testGetCards() + { $result = $this->backend->getCards(1); $expected = array( @@ -181,16 +172,15 @@ abstract class Sabre_CardDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_T 'uri' => 'card1', 'carddata' => 'card1', 'lastmodified' => 0, - ) + ), ); $this->assertEquals($expected, $result); - } - public function testGetCard() { - - $result = $this->backend->getCard(1,'card1'); + public function testGetCard() + { + $result = $this->backend->getCard(1, 'card1'); $expected = array( 'id' => 1, @@ -200,46 +190,41 @@ abstract class Sabre_CardDAV_Backend_AbstractPDOTest extends PHPUnit_Framework_T ); $this->assertEquals($expected, $result); - } /** * @depends testGetCard */ - public function testCreateCard() { - + public function testCreateCard() + { $result = $this->backend->createCard(1, 'card2', 'data2'); - $this->assertEquals('"' . md5('data2') . '"', $result); - $result = $this->backend->getCard(1,'card2'); + $this->assertEquals('"'.md5('data2').'"', $result); + $result = $this->backend->getCard(1, 'card2'); $this->assertEquals(2, $result['id']); $this->assertEquals('card2', $result['uri']); $this->assertEquals('data2', $result['carddata']); - } /** * @depends testGetCard */ - public function testUpdateCard() { - + public function testUpdateCard() + { $result = $this->backend->updateCard(1, 'card1', 'newdata'); - $this->assertEquals('"' . md5('newdata') . '"', $result); + $this->assertEquals('"'.md5('newdata').'"', $result); - $result = $this->backend->getCard(1,'card1'); + $result = $this->backend->getCard(1, 'card1'); $this->assertEquals(1, $result['id']); $this->assertEquals('newdata', $result['carddata']); - } /** * @depends testGetCard */ - public function testDeleteCard() { - + public function testDeleteCard() + { $this->backend->deleteCard(1, 'card1'); - $result = $this->backend->getCard(1,'card1'); + $result = $this->backend->getCard(1, 'card1'); $this->assertFalse($result); - } } - diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/Backend/Mock.php b/dav/SabreDAV/tests/Sabre/CardDAV/Backend/Mock.php index bd66dbb4..ab9992f6 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/Backend/Mock.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/Backend/Mock.php @@ -1,12 +1,12 @@ addressBooks = $addressBooks; $this->cards = $cards; @@ -27,72 +27,71 @@ class Sabre_CardDAV_Backend_Mock extends Sabre_CardDAV_Backend_Abstract { ), ); } - } - - function getAddressBooksForUser($principalUri) { - + public function getAddressBooksForUser($principalUri) + { $books = array(); - foreach($this->addressBooks as $book) { + foreach ($this->addressBooks as $book) { if ($book['principaluri'] === $principalUri) { $books[] = $book; } } - return $books; + return $books; } - function updateAddressBook($addressBookId, array $mutations) { - - foreach($this->addressBooks as &$book) { - if ($book['id'] !== $addressBookId) + public function updateAddressBook($addressBookId, array $mutations) + { + foreach ($this->addressBooks as &$book) { + if ($book['id'] !== $addressBookId) { continue; + } - foreach($mutations as $key=>$value) { + foreach ($mutations as $key => $value) { $book[$key] = $value; } + return true; } - return false; + return false; } - function createAddressBook($principalUri, $url, array $properties) { - + public function createAddressBook($principalUri, $url, array $properties) + { $this->addressBooks[] = array_merge($properties, array( 'id' => $url, 'uri' => $url, 'principaluri' => $principalUri, )); - } - function deleteAddressBook($addressBookId) { - - foreach($this->addressBooks as $key=>$value) { - if ($value['id'] === $addressBookId) + public function deleteAddressBook($addressBookId) + { + foreach ($this->addressBooks as $key => $value) { + if ($value['id'] === $addressBookId) { unset($this->addressBooks[$key]); + } } unset($this->cards[$addressBookId]); - } - function getCards($addressBookId) { - + public function getCards($addressBookId) + { $cards = array(); - foreach($this->cards[$addressBookId] as $uri=>$data) { + foreach ($this->cards[$addressBookId] as $uri => $data) { $cards[] = array( 'uri' => $uri, 'carddata' => $data, ); } - return $cards; + return $cards; } - function getCard($addressBookId, $cardUri) { - + public function getCard($addressBookId, $cardUri) + { if (!isset($this->cards[$addressBookId][$cardUri])) { return false; } @@ -101,25 +100,20 @@ class Sabre_CardDAV_Backend_Mock extends Sabre_CardDAV_Backend_Abstract { 'uri' => $cardUri, 'carddata' => $this->cards[$addressBookId][$cardUri], ); - } - function createCard($addressBookId, $cardUri, $cardData) { - + public function createCard($addressBookId, $cardUri, $cardData) + { $this->cards[$addressBookId][$cardUri] = $cardData; - } - function updateCard($addressBookId, $cardUri, $cardData) { - + public function updateCard($addressBookId, $cardUri, $cardData) + { $this->cards[$addressBookId][$cardUri] = $cardData; - } - function deleteCard($addressBookId, $cardUri) { - + public function deleteCard($addressBookId, $cardUri) + { unset($this->cards[$addressBookId][$cardUri]); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/Backend/PDOMySQLTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/Backend/PDOMySQLTest.php index da3ffd7c..ed7e9aaa 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/Backend/PDOMySQLTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/Backend/PDOMySQLTest.php @@ -2,20 +2,24 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_CardDAV_Backend_PDOMySQLTest extends Sabre_CardDAV_Backend_AbstractPDOTest { - +class Sabre_CardDAV_Backend_PDOMySQLTest extends Sabre_CardDAV_Backend_AbstractPDOTest +{ /** * @return PDO */ - public function getPDO() { - - if (!SABRE_HASMYSQL) $this->markTestSkipped('MySQL driver is not available, or not properly configured'); + public function getPDO() + { + if (!SABRE_HASMYSQL) { + $this->markTestSkipped('MySQL driver is not available, or not properly configured'); + } $pdo = Sabre_TestUtil::getMySQLDB(); - if (!$pdo) $this->markTestSkipped('Could not connect to MySQL database'); + if (!$pdo) { + $this->markTestSkipped('Could not connect to MySQL database'); + } - $pdo->query("DROP TABLE IF EXISTS addressbooks"); - $pdo->query("DROP TABLE IF EXISTS cards"); + $pdo->query('DROP TABLE IF EXISTS addressbooks'); + $pdo->query('DROP TABLE IF EXISTS cards'); $pdo->query(" CREATE TABLE addressbooks ( id INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, @@ -34,7 +38,7 @@ VALUES ('principals/user1', 'book1', 'book1', 'addressbook 1', 1); "); - $pdo->query(" + $pdo->query(' CREATE TABLE cards ( id INT(11) UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, addressbookid INT(11) UNSIGNED NOT NULL, @@ -42,7 +46,7 @@ CREATE TABLE cards ( uri VARCHAR(100), lastmodified INT(11) UNSIGNED ); -"); +'); $pdo->query(" INSERT INTO cards @@ -50,9 +54,7 @@ INSERT INTO cards VALUES (1, 'card1', 'card1', 0); "); + return $pdo; - } - } - diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/Backend/PDOSqliteTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/Backend/PDOSqliteTest.php index 347eb732..f3e64b7b 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/Backend/PDOSqliteTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/Backend/PDOSqliteTest.php @@ -2,27 +2,32 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_CardDAV_Backend_PDOSqliteTest extends Sabre_CardDAV_Backend_AbstractPDOTest { - - function tearDown() { - - if (file_exists(SABRE_TEMPDIR . '/pdobackend')) unlink(SABRE_TEMPDIR . '/pdobackend'); - if (file_exists(SABRE_TEMPDIR . '/pdobackend2')) unlink(SABRE_TEMPDIR . '/pdobackend2'); - +class Sabre_CardDAV_Backend_PDOSqliteTest extends Sabre_CardDAV_Backend_AbstractPDOTest +{ + public function tearDown() + { + if (file_exists(SABRE_TEMPDIR.'/pdobackend')) { + unlink(SABRE_TEMPDIR.'/pdobackend'); + } + if (file_exists(SABRE_TEMPDIR.'/pdobackend2')) { + unlink(SABRE_TEMPDIR.'/pdobackend2'); + } } /** * @return PDO */ - function getPDO() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function getPDO() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $pdo = new PDO('sqlite:'.SABRE_TEMPDIR.'/pdobackend'); - $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); - $pdo->query("DROP TABLE IF EXISTS addressbooks"); - $pdo->query("DROP TABLE IF EXISTS cards"); - $pdo->query(" + $pdo->query('DROP TABLE IF EXISTS addressbooks'); + $pdo->query('DROP TABLE IF EXISTS cards'); + $pdo->query(' CREATE TABLE addressbooks ( id integer primary key asc, principaluri text, @@ -32,7 +37,7 @@ CREATE TABLE addressbooks ( ctag integer ); -"); +'); $pdo->query(" INSERT INTO addressbooks @@ -41,7 +46,7 @@ VALUES ('principals/user1', 'book1', 'book1', 'addressbook 1', 1); "); - $pdo->query(" + $pdo->query(' CREATE TABLE cards ( id integer primary key asc, @@ -51,7 +56,7 @@ CREATE TABLE cards ( lastmodified integer ); -"); +'); $pdo->query(" INSERT INTO cards (addressbookid, carddata, uri, lastmodified) @@ -60,8 +65,5 @@ VALUES "); return $pdo; - } - } - diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/CardTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/CardTest.php index 7e3643fd..d6855192 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/CardTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/CardTest.php @@ -1,7 +1,7 @@ backend = new Sabre_CardDAV_Backend_Mock(); $this->card = new Sabre_CardDAV_Card( $this->backend, @@ -27,17 +27,15 @@ class Sabre_CardDAV_CardTest extends PHPUnit_Framework_TestCase { 'carddata' => 'card', ) ); - } - function testGet() { - + public function testGet() + { $result = $this->card->get(); $this->assertEquals('card', $result); - } - function testGet2() { - + public function testGet2() + { $this->card = new Sabre_CardDAV_Card( $this->backend, array( @@ -52,46 +50,39 @@ class Sabre_CardDAV_CardTest extends PHPUnit_Framework_TestCase { ); $result = $this->card->get(); $this->assertEquals("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD", $result); - } - /** * @depends testGet */ - function testPut() { - - $file = fopen('php://memory','r+'); + public function testPut() + { + $file = fopen('php://memory', 'r+'); fwrite($file, 'newdata'); rewind($file); $this->card->put($file); $result = $this->card->get(); $this->assertEquals('newdata', $result); - } - - function testDelete() { - + public function testDelete() + { $this->card->delete(); $this->assertEquals(1, count($this->backend->cards['foo'])); - } - function testGetContentType() { - + public function testGetContentType() + { $this->assertEquals('text/x-vcard; charset=utf-8', $this->card->getContentType()); - } - function testGetETag() { - - $this->assertEquals('"' . md5('card') . '"' , $this->card->getETag()); - + public function testGetETag() + { + $this->assertEquals('"'.md5('card').'"', $this->card->getETag()); } - function testGetETag2() { - + public function testGetETag2() + { $card = new Sabre_CardDAV_Card( $this->backend, array( @@ -106,25 +97,22 @@ class Sabre_CardDAV_CardTest extends PHPUnit_Framework_TestCase { 'etag' => '"blabla"', ) ); - $this->assertEquals('"blabla"' , $card->getETag()); - + $this->assertEquals('"blabla"', $card->getETag()); } - function testGetLastModified() { - + public function testGetLastModified() + { $this->assertEquals(null, $this->card->getLastModified()); - } - function testGetSize() { - + public function testGetSize() + { $this->assertEquals(4, $this->card->getSize()); $this->assertEquals(4, $this->card->getSize()); - } - function testGetSize2() { - + public function testGetSize2() + { $card = new Sabre_CardDAV_Card( $this->backend, array( @@ -140,11 +128,10 @@ class Sabre_CardDAV_CardTest extends PHPUnit_Framework_TestCase { ) ); $this->assertEquals(4, $card->getSize()); - } - function testACLMethods() { - + public function testACLMethods() + { $this->assertEquals('principals/user1', $this->card->getOwner()); $this->assertNull($this->card->getGroup()); $this->assertEquals(array( @@ -159,24 +146,20 @@ class Sabre_CardDAV_CardTest extends PHPUnit_Framework_TestCase { 'protected' => true, ), ), $this->card->getACL()); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testSetACL() { - - $this->card->setACL(array()); - + public function testSetACL() + { + $this->card->setACL(array()); } - function testGetSupportedPrivilegeSet() { - + public function testGetSupportedPrivilegeSet() + { $this->assertNull( $this->card->getSupportedPrivilegeSet() ); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/IDirectoryTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/IDirectoryTest.php index 9a247a03..809c02f6 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/IDirectoryTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/IDirectoryTest.php @@ -1,11 +1,11 @@ addPlugin($plugin); $props = $server->getProperties('directory', array('{DAV:}resourcetype')); - $this->assertTrue($props['{DAV:}resourcetype']->is('{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}directory')); - + $this->assertTrue($props['{DAV:}resourcetype']->is('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}directory')); } - } -class Sabre_CardDAV_DirectoryMock extends Sabre_DAV_SimpleCollection implements Sabre_CardDAV_IDirectory { - - +class Sabre_CardDAV_DirectoryMock extends Sabre_DAV_SimpleCollection implements Sabre_CardDAV_IDirectory +{ } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/MultiGetTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/MultiGetTest.php index 50301c6f..1e172c2c 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/MultiGetTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/MultiGetTest.php @@ -2,10 +2,10 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_CardDAV_MultiGetTest extends Sabre_CardDAV_AbstractPluginTest { - - function testMultiGet() { - +class Sabre_CardDAV_MultiGetTest extends Sabre_CardDAV_AbstractPluginTest +{ + public function testMultiGet() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'REPORT', 'REQUEST_URI' => '/addressbooks/user1/book1', @@ -29,22 +29,20 @@ class Sabre_CardDAV_MultiGetTest extends Sabre_CardDAV_AbstractPluginTest { $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:' . $response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $response->status, 'Incorrect status code. Full response body:'.$response->body); // using the client for parsing - $client = new Sabre_DAV_Client(array('baseUri'=>'/')); + $client = new Sabre_DAV_Client(array('baseUri' => '/')); $result = $client->parseMultiStatus($response->body); $this->assertEquals(array( '/addressbooks/user1/book1/card1' => array( 200 => array( - '{DAV:}getetag' => '"' . md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD") . '"', + '{DAV:}getetag' => '"'.md5("BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD").'"', '{urn:ietf:params:xml:ns:carddav}address-data' => "BEGIN:VCARD\nVERSION:3.0\nUID:12345\nEND:VCARD", - ) - ) + ), + ), ), $result); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/PluginTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/PluginTest.php index f1792d79..86246c8c 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/PluginTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/PluginTest.php @@ -3,45 +3,41 @@ require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; require_once 'Sabre/CardDAV/AbstractPluginTest.php'; -class Sabre_CardDAV_PluginTest extends Sabre_CardDAV_AbstractPluginTest { - - function testConstruct() { - +class Sabre_CardDAV_PluginTest extends Sabre_CardDAV_AbstractPluginTest +{ + public function testConstruct() + { $this->assertEquals('card', $this->server->xmlNamespaces[Sabre_CardDAV_Plugin::NS_CARDDAV]); - $this->assertEquals('{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook', $this->server->resourceTypeMapping['Sabre_CardDAV_IAddressBook']); + $this->assertEquals('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook', $this->server->resourceTypeMapping['Sabre_CardDAV_IAddressBook']); $this->assertTrue(in_array('addressbook', $this->plugin->getFeatures())); - } - function testSupportedReportSet() { - + public function testSupportedReportSet() + { $this->assertEquals(array( - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-multiget', - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-query', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-multiget', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-query', ), $this->plugin->getSupportedReportSet('addressbooks/user1/book1')); - } - function testSupportedReportSetEmpty() { - + public function testSupportedReportSetEmpty() + { $this->assertEquals(array( ), $this->plugin->getSupportedReportSet('')); - } - function testAddressBookHomeSet() { - - $result = $this->server->getProperties('principals/user1', array('{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-home-set')); + public function testAddressBookHomeSet() + { + $result = $this->server->getProperties('principals/user1', array('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-home-set')); $this->assertEquals(1, count($result)); - $this->assertTrue(isset($result['{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-home-set'])); - $this->assertEquals('addressbooks/user1/', $result['{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-home-set']->getHref()); - + $this->assertTrue(isset($result['{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-home-set'])); + $this->assertEquals('addressbooks/user1/', $result['{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-home-set']->getHref()); } - function testMeCardTest() { - + public function testMeCardTest() + { $result = $this->server->getProperties( 'addressbooks/user1', array( @@ -51,42 +47,37 @@ class Sabre_CardDAV_PluginTest extends Sabre_CardDAV_AbstractPluginTest { $this->assertEquals( array( - '{http://calendarserver.org/ns/}me-card' => - new Sabre_DAV_Property_Href('addressbooks/user1/book1/vcard1.vcf') + '{http://calendarserver.org/ns/}me-card' => new Sabre_DAV_Property_Href('addressbooks/user1/book1/vcard1.vcf'), ), $result ); - } - function testDirectoryGateway() { - - $result = $this->server->getProperties('principals/user1', array('{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}directory-gateway')); + public function testDirectoryGateway() + { + $result = $this->server->getProperties('principals/user1', array('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}directory-gateway')); $this->assertEquals(1, count($result)); - $this->assertTrue(isset($result['{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}directory-gateway'])); - $this->assertEquals(array('directory'), $result['{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}directory-gateway']->getHrefs()); - + $this->assertTrue(isset($result['{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}directory-gateway'])); + $this->assertEquals(array('directory'), $result['{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}directory-gateway']->getHrefs()); } - function testReportPassThrough() { - + public function testReportPassThrough() + { $this->assertNull($this->plugin->report('{DAV:}foo', new DomDocument())); - } - function testHTMLActionsPanel() { - + public function testHTMLActionsPanel() + { $output = ''; $r = $this->server->broadcastEvent('onHTMLActionsPanel', array($this->server->tree->getNodeForPath('addressbooks/user1'), &$output)); $this->assertFalse($r); - $this->assertTrue(!!strpos($output,'Display name')); - + $this->assertTrue((bool) strpos($output, 'Display name')); } - function testBrowserPostAction() { - + public function testBrowserPostAction() + { $r = $this->server->broadcastEvent('onBrowserPostAction', array('addressbooks/user1', 'mkaddressbook', array( 'name' => 'NEWADDRESSBOOK', '{DAV:}displayname' => 'foo', @@ -97,21 +88,21 @@ class Sabre_CardDAV_PluginTest extends Sabre_CardDAV_AbstractPluginTest { $this->assertEquals(2, count($addressbooks)); $newAddressBook = null; - foreach($addressbooks as $addressbook) { - if ($addressbook['uri'] === 'NEWADDRESSBOOK') { + foreach ($addressbooks as $addressbook) { + if ($addressbook['uri'] === 'NEWADDRESSBOOK') { $newAddressBook = $addressbook; break; - } + } } - if (!$newAddressBook) + if (!$newAddressBook) { $this->fail('Could not find newly created addressbook'); - + } } - function testUpdatePropertiesMeCard() { - + public function testUpdatePropertiesMeCard() + { $result = $this->server->updateProperties('addressbooks/user1', array( - '{http://calendarserver.org/ns/}me-card' => new Sabre_DAV_Property_Href('/addressbooks/user1/book1/vcard2',true), + '{http://calendarserver.org/ns/}me-card' => new Sabre_DAV_Property_Href('/addressbooks/user1/book1/vcard2', true), )); $this->assertEquals( @@ -123,11 +114,10 @@ class Sabre_CardDAV_PluginTest extends Sabre_CardDAV_AbstractPluginTest { ), $result ); - } - function testUpdatePropertiesMeCardBadValue() { - + public function testUpdatePropertiesMeCardBadValue() + { $result = $this->server->updateProperties('addressbooks/user1', array( '{http://calendarserver.org/ns/}me-card' => new Sabre_DAV_Property_HrefList(array()), )); @@ -141,6 +131,5 @@ class Sabre_CardDAV_PluginTest extends Sabre_CardDAV_AbstractPluginTest { ), $result ); - } } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/Property/SupportedAddressDataTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/Property/SupportedAddressDataTest.php index e85c5d8f..4ea5acc8 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/Property/SupportedAddressDataTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/Property/SupportedAddressDataTest.php @@ -1,23 +1,22 @@ createElementNS(Sabre_CardDAV_Plugin::NS_CARDDAV, 'card:root'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $server = new Sabre_DAV_Server(); @@ -28,12 +27,10 @@ class Sabre_CardDAV_Property_SupportedAddressDataDataTest extends PHPUnit_Framew $this->assertEquals( ' -' . -'' . -'' . +'. +''. +''. ' ', $xml); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/SogoStripContentTypeTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/SogoStripContentTypeTest.php index 8cbc4201..abaf1bd5 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/SogoStripContentTypeTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/SogoStripContentTypeTest.php @@ -1,11 +1,11 @@ 1, + 'id' => 1, 'uri' => 'book1', 'principaluri' => 'principals/user1', ), @@ -16,24 +16,21 @@ class Sabre_CardDAV_SogoStripContentType extends Sabre_DAVServerTest { ), ); - function testDontStrip() { - - $result = $this->server->getProperties('addressbooks/user1/book1/card1.vcf',array('{DAV:}getcontenttype')); + public function testDontStrip() + { + $result = $this->server->getProperties('addressbooks/user1/book1/card1.vcf', array('{DAV:}getcontenttype')); $this->assertEquals(array( - '{DAV:}getcontenttype' => 'text/x-vcard; charset=utf-8' + '{DAV:}getcontenttype' => 'text/x-vcard; charset=utf-8', ), $result); - } - function testStrip() { - + public function testStrip() + { $this->server->httpRequest = new Sabre_HTTP_Request(array( 'HTTP_USER_AGENT' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:10.0.2) Gecko/20120216 Thunderbird/10.0.2 Lightning/1.2.1', )); - $result = $this->server->getProperties('addressbooks/user1/book1/card1.vcf',array('{DAV:}getcontenttype')); + $result = $this->server->getProperties('addressbooks/user1/book1/card1.vcf', array('{DAV:}getcontenttype')); $this->assertEquals(array( - '{DAV:}getcontenttype' => 'text/x-vcard' + '{DAV:}getcontenttype' => 'text/x-vcard', ), $result); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/UserAddressBooksTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/UserAddressBooksTest.php index f4183ce3..d3191f35 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/UserAddressBooksTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/UserAddressBooksTest.php @@ -1,101 +1,91 @@ backend = new Sabre_CardDAV_Backend_Mock(); $this->s = new Sabre_CardDAV_UserAddressBooks( $this->backend, 'principals/user1' ); - } - function testGetName() { - + public function testGetName() + { $this->assertEquals('user1', $this->s->getName()); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testSetName() { - + public function testSetName() + { $this->s->setName('user2'); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testDelete() { - + public function testDelete() + { $this->s->delete(); - } - function testGetLastModified() { - + public function testGetLastModified() + { $this->assertNull($this->s->getLastModified()); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testCreateFile() { - + public function testCreateFile() + { $this->s->createFile('bla'); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testCreateDirectory() { - + public function testCreateDirectory() + { $this->s->createDirectory('bla'); - } - function testGetChild() { - + public function testGetChild() + { $child = $this->s->getChild('book1'); $this->assertInstanceOf('Sabre_CardDAV_AddressBook', $child); $this->assertEquals('book1', $child->getName()); - } /** * @expectedException Sabre_DAV_Exception_NotFound */ - function testGetChild404() { - + public function testGetChild404() + { $this->s->getChild('book2'); - } - function testGetChildren() { - + public function testGetChildren() + { $children = $this->s->getChildren(); $this->assertEquals(1, count($children)); $this->assertInstanceOf('Sabre_CardDAV_AddressBook', $children[0]); $this->assertEquals('book1', $children[0]->getName()); - } - function testCreateExtendedCollection() { - + public function testCreateExtendedCollection() + { $resourceType = array( - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook', + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook', '{DAV:}collection', ); $this->s->createExtendedCollection('book2', $resourceType, array('{DAV:}displayname' => 'a-book 2')); @@ -106,24 +96,21 @@ class Sabre_CardDAV_UserAddressBooksTest extends PHPUnit_Framework_TestCase { '{DAV:}displayname' => 'a-book 2', 'principaluri' => 'principals/user1', ), $this->backend->addressBooks[1]); - } /** * @expectedException Sabre_DAV_Exception_InvalidResourceType */ - function testCreateExtendedCollectionInvalid() { - + public function testCreateExtendedCollectionInvalid() + { $resourceType = array( '{DAV:}collection', ); $this->s->createExtendedCollection('book2', $resourceType, array('{DAV:}displayname' => 'a-book 2')); - } - - function testACLMethods() { - + public function testACLMethods() + { $this->assertEquals('principals/user1', $this->s->getOwner()); $this->assertNull($this->s->getGroup()); $this->assertEquals(array( @@ -138,23 +125,20 @@ class Sabre_CardDAV_UserAddressBooksTest extends PHPUnit_Framework_TestCase { 'protected' => true, ), ), $this->s->getACL()); - } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testSetACL() { - - $this->s->setACL(array()); - + public function testSetACL() + { + $this->s->setACL(array()); } - function testGetSupportedPrivilegeSet() { - + public function testGetSupportedPrivilegeSet() + { $this->assertNull( $this->s->getSupportedPrivilegeSet() ); - } } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/ValidateFilterTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/ValidateFilterTest.php index ef7f1932..744a5b14 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/ValidateFilterTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/ValidateFilterTest.php @@ -2,24 +2,23 @@ require_once 'Sabre/CardDAV/AbstractPluginTest.php'; -class Sabre_CardDAV_ValidateFilterTest extends Sabre_CardDAV_AbstractPluginTest { - +class Sabre_CardDAV_ValidateFilterTest extends Sabre_CardDAV_AbstractPluginTest +{ /** * @dataProvider data */ - function testFilter($input, $filters, $test, $result, $message = null) { - + public function testFilter($input, $filters, $test, $result, $message = null) + { if ($result) { $this->assertTrue($this->plugin->validateFilters($input, $filters, $test), $message); } else { $this->assertFalse($this->plugin->validateFilters($input, $filters, $test), $message); } - } - function data() { - - $body1 = << 'type', 'is-not-defined' => false, - 'text-match' => null + 'text-match' => null, ), ), 'text-matches' => array(), @@ -138,7 +137,6 @@ HELLO; $filter16 = $filter15; $filter16['param-filters'][0]['text-match']['negate-condition'] = true; - // Param filter + text filter $filter17 = $filter5; $filter17['test'] = 'anyof'; @@ -157,18 +155,18 @@ HELLO; return array( // Basic filters - array($body1, array($filter1), 'anyof',true), - array($body1, array($filter2), 'anyof',false), - array($body1, array($filter3), 'anyof',false), - array($body1, array($filter4), 'anyof',true), + array($body1, array($filter1), 'anyof', true), + array($body1, array($filter2), 'anyof', false), + array($body1, array($filter3), 'anyof', false), + array($body1, array($filter4), 'anyof', true), // Combinations - array($body1, array($filter1, $filter2), 'anyof',true), - array($body1, array($filter1, $filter2), 'allof',false), - array($body1, array($filter1, $filter4), 'anyof',true), - array($body1, array($filter1, $filter4), 'allof',true), - array($body1, array($filter2, $filter3), 'anyof',false), - array($body1, array($filter2, $filter3), 'allof',false), + array($body1, array($filter1, $filter2), 'anyof', true), + array($body1, array($filter1, $filter2), 'allof', false), + array($body1, array($filter1, $filter4), 'anyof', true), + array($body1, array($filter1, $filter4), 'allof', true), + array($body1, array($filter2, $filter3), 'anyof', false), + array($body1, array($filter2, $filter3), 'allof', false), // Basic parameters array($body1, array($filter5), 'anyof', true, 'TEL;TYPE is defined, so this should return true'), @@ -196,7 +194,5 @@ HELLO; array($body1, array($filter18), 'anyof', false), array($body1, array($filter18), 'anyof', false), ); - } - } diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/ValidateVCardTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/ValidateVCardTest.php index a4c8e801..45b5f6ba 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/ValidateVCardTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/ValidateVCardTest.php @@ -4,22 +4,22 @@ require_once 'Sabre/CardDAV/Backend/Mock.php'; require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_CardDAV_ValidateVCardTest extends PHPUnit_Framework_TestCase { - +class Sabre_CardDAV_ValidateVCardTest extends PHPUnit_Framework_TestCase +{ protected $server; protected $cardBackend; - function setUp() { - + public function setUp() + { $addressbooks = array( array( 'id' => 'addressbook1', 'principaluri' => 'principals/admin', 'uri' => 'addressbook1', - ) + ), ); - $this->cardBackend = new Sabre_CardDAV_Backend_Mock($addressbooks,array()); + $this->cardBackend = new Sabre_CardDAV_Backend_Mock($addressbooks, array()); $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $tree = array( @@ -34,20 +34,18 @@ class Sabre_CardDAV_ValidateVCardTest extends PHPUnit_Framework_TestCase { $response = new Sabre_HTTP_ResponseMock(); $this->server->httpResponse = $response; - } - function request(Sabre_HTTP_Request $request) { - + public function request(Sabre_HTTP_Request $request) + { $this->server->httpRequest = $request; $this->server->exec(); return $this->server->httpResponse; - } - function testCreateFile() { - + public function testCreateFile() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/addressbooks/admin/addressbook1/blabla.vcf', @@ -56,11 +54,10 @@ class Sabre_CardDAV_ValidateVCardTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $response->status); - } - function testCreateFileValid() { - + public function testCreateFileValid() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/addressbooks/admin/addressbook1/blabla.vcf', @@ -69,18 +66,17 @@ class Sabre_CardDAV_ValidateVCardTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 201 Created', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); + $this->assertEquals('HTTP/1.1 201 Created', $response->status, 'Incorrect status returned! Full response body: '.$response->body); $expected = array( - 'uri' => 'blabla.vcf', + 'uri' => 'blabla.vcf', 'carddata' => "BEGIN:VCARD\r\nUID:foo\r\nEND:VCARD\r\n", ); - $this->assertEquals($expected, $this->cardBackend->getCard('addressbook1','blabla.vcf')); - + $this->assertEquals($expected, $this->cardBackend->getCard('addressbook1', 'blabla.vcf')); } - function testCreateFileNoUID() { - + public function testCreateFileNoUID() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/addressbooks/admin/addressbook1/blabla.vcf', @@ -89,13 +85,11 @@ class Sabre_CardDAV_ValidateVCardTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Incorrect status returned! Full response body: '.$response->body); } - - function testCreateFileVCalendar() { - + public function testCreateFileVCalendar() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/addressbooks/admin/addressbook1/blabla.vcf', @@ -104,13 +98,12 @@ class Sabre_CardDAV_ValidateVCardTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); - $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $response->status, 'Incorrect status returned! Full response body: ' . $response->body); - + $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $response->status, 'Incorrect status returned! Full response body: '.$response->body); } - function testUpdateFile() { - - $this->cardBackend->createCard('addressbook1','blabla.vcf','foo'); + public function testUpdateFile() + { + $this->cardBackend->createCard('addressbook1', 'blabla.vcf', 'foo'); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/addressbooks/admin/addressbook1/blabla.vcf', @@ -119,12 +112,11 @@ class Sabre_CardDAV_ValidateVCardTest extends PHPUnit_Framework_TestCase { $response = $this->request($request); $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $response->status); - } - function testUpdateFileParsableBody() { - - $this->cardBackend->createCard('addressbook1','blabla.vcf','foo'); + public function testUpdateFileParsableBody() + { + $this->cardBackend->createCard('addressbook1', 'blabla.vcf', 'foo'); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PUT', 'REQUEST_URI' => '/addressbooks/admin/addressbook1/blabla.vcf', @@ -137,13 +129,10 @@ class Sabre_CardDAV_ValidateVCardTest extends PHPUnit_Framework_TestCase { $this->assertEquals('HTTP/1.1 204 No Content', $response->status); $expected = array( - 'uri' => 'blabla.vcf', + 'uri' => 'blabla.vcf', 'carddata' => $body, ); - $this->assertEquals($expected, $this->cardBackend->getCard('addressbook1','blabla.vcf')); - + $this->assertEquals($expected, $this->cardBackend->getCard('addressbook1', 'blabla.vcf')); } } - -?> diff --git a/dav/SabreDAV/tests/Sabre/CardDAV/VersionTest.php b/dav/SabreDAV/tests/Sabre/CardDAV/VersionTest.php index caec5719..c3c320d7 100644 --- a/dav/SabreDAV/tests/Sabre/CardDAV/VersionTest.php +++ b/dav/SabreDAV/tests/Sabre/CardDAV/VersionTest.php @@ -1,15 +1,13 @@ assertEquals(-1, version_compare('0.1',$v)); + $this->assertEquals(-1, version_compare('0.1', $v)); $s = Sabre_CardDAV_Version::STABILITY; - $this->assertTrue($s == 'alpha' || $s == 'beta' || $s =='stable'); - + $this->assertTrue($s == 'alpha' || $s == 'beta' || $s == 'stable'); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/AbstractServer.php b/dav/SabreDAV/tests/Sabre/DAV/AbstractServer.php index 3ba41f9e..46ba97b5 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/AbstractServer.php +++ b/dav/SabreDAV/tests/Sabre/DAV/AbstractServer.php @@ -2,8 +2,8 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -abstract class Sabre_DAV_AbstractServer extends PHPUnit_Framework_TestCase { - +abstract class Sabre_DAV_AbstractServer extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_HTTP_ResponseMock */ @@ -15,46 +15,42 @@ abstract class Sabre_DAV_AbstractServer extends PHPUnit_Framework_TestCase { protected $server; protected $tempDir = SABRE_TEMPDIR; - function setUp() { - + public function setUp() + { $this->response = new Sabre_HTTP_ResponseMock(); $this->server = new Sabre_DAV_Server($this->getRootNode()); $this->server->httpResponse = $this->response; $this->server->debugExceptions = true; - file_put_contents(SABRE_TEMPDIR . '/test.txt', 'Test contents'); - mkdir(SABRE_TEMPDIR . '/dir'); - file_put_contents(SABRE_TEMPDIR . '/dir/child.txt', 'Child contents'); - - + file_put_contents(SABRE_TEMPDIR.'/test.txt', 'Test contents'); + mkdir(SABRE_TEMPDIR.'/dir'); + file_put_contents(SABRE_TEMPDIR.'/dir/child.txt', 'Child contents'); } - function tearDown() { - - $this->deleteTree(SABRE_TEMPDIR,false); - + public function tearDown() + { + $this->deleteTree(SABRE_TEMPDIR, false); } - protected function getRootNode() { - + protected function getRootNode() + { return new Sabre_DAV_FS_Directory(SABRE_TEMPDIR); - } - private function deleteTree($path,$deleteRoot = true) { - - foreach(scandir($path) as $node) { - - if ($node=='.' || $node=='.svn' || $node=='..') continue; - $myPath = $path.'/'. $node; + private function deleteTree($path, $deleteRoot = true) + { + foreach (scandir($path) as $node) { + if ($node == '.' || $node == '.svn' || $node == '..') { + continue; + } + $myPath = $path.'/'.$node; if (is_file($myPath)) { unlink($myPath); } else { $this->deleteTree($myPath); } - } - if ($deleteRoot) rmdir($path); - + if ($deleteRoot) { + rmdir($path); + } } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractBasicTest.php b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractBasicTest.php index 58439a1e..f569b883 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractBasicTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractBasicTest.php @@ -2,28 +2,27 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_DAV_Auth_Backend_AbstractBasicTest extends PHPUnit_Framework_TestCase { - +class Sabre_DAV_Auth_Backend_AbstractBasicTest extends PHPUnit_Framework_TestCase +{ /** * @expectedException Sabre_DAV_Exception_NotAuthenticated */ - public function testAuthenticateNoHeaders() { - + public function testAuthenticateNoHeaders() + { $response = new Sabre_HTTP_ResponseMock(); $tree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla')); $server = new Sabre_DAV_Server($tree); $server->httpResponse = $response; $backend = new Sabre_DAV_Auth_Backend_AbstractBasicMock(); - $backend->authenticate($server,'myRealm'); - + $backend->authenticate($server, 'myRealm'); } /** * @expectedException Sabre_DAV_Exception_NotAuthenticated */ - public function testAuthenticateUnknownUser() { - + public function testAuthenticateUnknownUser() + { $response = new Sabre_HTTP_ResponseMock(); $tree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla')); $server = new Sabre_DAV_Server($tree); @@ -36,12 +35,11 @@ class Sabre_DAV_Auth_Backend_AbstractBasicTest extends PHPUnit_Framework_TestCas $server->httpRequest = $request; $backend = new Sabre_DAV_Auth_Backend_AbstractBasicMock(); - $backend->authenticate($server,'myRealm'); - + $backend->authenticate($server, 'myRealm'); } - public function testAuthenticate() { - + public function testAuthenticate() + { $response = new Sabre_HTTP_ResponseMock(); $tree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla')); $server = new Sabre_DAV_Server($tree); @@ -54,34 +52,29 @@ class Sabre_DAV_Auth_Backend_AbstractBasicTest extends PHPUnit_Framework_TestCas $server->httpRequest = $request; $backend = new Sabre_DAV_Auth_Backend_AbstractBasicMock(); - $this->assertTrue($backend->authenticate($server,'myRealm')); + $this->assertTrue($backend->authenticate($server, 'myRealm')); $result = $backend->getCurrentUser(); $this->assertEquals('username', $result); - } - - } - -class Sabre_DAV_Auth_Backend_AbstractBasicMock extends Sabre_DAV_Auth_Backend_AbstractBasic { - +class Sabre_DAV_Auth_Backend_AbstractBasicMock extends Sabre_DAV_Auth_Backend_AbstractBasic +{ /** - * Validates a username and password + * Validates a username and password. * * This method should return true or false depending on if login * succeeded. * * @param string $username * @param string $password + * * @return bool */ - function validateUserPass($username, $password) { - - return ($username == 'username' && $password == 'password'); - + public function validateUserPass($username, $password) + { + return $username == 'username' && $password == 'password'; } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractDigestTest.php b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractDigestTest.php index 6cc46f5c..daf75842 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractDigestTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractDigestTest.php @@ -2,28 +2,27 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_DAV_Auth_Backend_AbstractDigestTest extends PHPUnit_Framework_TestCase { - +class Sabre_DAV_Auth_Backend_AbstractDigestTest extends PHPUnit_Framework_TestCase +{ /** * @expectedException Sabre_DAV_Exception_NotAuthenticated */ - public function testAuthenticateNoHeaders() { - + public function testAuthenticateNoHeaders() + { $response = new Sabre_HTTP_ResponseMock(); $tree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla')); $server = new Sabre_DAV_Server($tree); $server->httpResponse = $response; $backend = new Sabre_DAV_Auth_Backend_AbstractDigestMock(); - $backend->authenticate($server,'myRealm'); - + $backend->authenticate($server, 'myRealm'); } /** * @expectedException Sabre_DAV_Exception */ - public function testAuthenticateBadGetUserInfoResponse() { - + public function testAuthenticateBadGetUserInfoResponse() + { $response = new Sabre_HTTP_ResponseMock(); $tree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla')); $server = new Sabre_DAV_Server($tree); @@ -36,15 +35,14 @@ class Sabre_DAV_Auth_Backend_AbstractDigestTest extends PHPUnit_Framework_TestCa $server->httpRequest = $request; $backend = new Sabre_DAV_Auth_Backend_AbstractDigestMock(); - $backend->authenticate($server,'myRealm'); - + $backend->authenticate($server, 'myRealm'); } /** * @expectedException Sabre_DAV_Exception */ - public function testAuthenticateBadGetUserInfoResponse2() { - + public function testAuthenticateBadGetUserInfoResponse2() + { $response = new Sabre_HTTP_ResponseMock(); $tree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla')); $server = new Sabre_DAV_Server($tree); @@ -57,15 +55,14 @@ class Sabre_DAV_Auth_Backend_AbstractDigestTest extends PHPUnit_Framework_TestCa $server->httpRequest = $request; $backend = new Sabre_DAV_Auth_Backend_AbstractDigestMock(); - $backend->authenticate($server,'myRealm'); - + $backend->authenticate($server, 'myRealm'); } /** * @expectedException Sabre_DAV_Exception_NotAuthenticated */ - public function testAuthenticateUnknownUser() { - + public function testAuthenticateUnknownUser() + { $response = new Sabre_HTTP_ResponseMock(); $tree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla')); $server = new Sabre_DAV_Server($tree); @@ -78,15 +75,14 @@ class Sabre_DAV_Auth_Backend_AbstractDigestTest extends PHPUnit_Framework_TestCa $server->httpRequest = $request; $backend = new Sabre_DAV_Auth_Backend_AbstractDigestMock(); - $backend->authenticate($server,'myRealm'); - + $backend->authenticate($server, 'myRealm'); } /** * @expectedException Sabre_DAV_Exception_NotAuthenticated */ - public function testAuthenticateBadPassword() { - + public function testAuthenticateBadPassword() + { $response = new Sabre_HTTP_ResponseMock(); $tree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla')); $server = new Sabre_DAV_Server($tree); @@ -95,56 +91,49 @@ class Sabre_DAV_Auth_Backend_AbstractDigestTest extends PHPUnit_Framework_TestCa $header = 'username=user, realm=myRealm, nonce=12345, uri=/, response=HASH, opaque=1, qop=auth, nc=1, cnonce=1'; $request = new Sabre_HTTP_Request(array( 'PHP_AUTH_DIGEST' => $header, - 'REQUEST_METHOD' => 'PUT', + 'REQUEST_METHOD' => 'PUT', )); $server->httpRequest = $request; $backend = new Sabre_DAV_Auth_Backend_AbstractDigestMock(); - $backend->authenticate($server,'myRealm'); - + $backend->authenticate($server, 'myRealm'); } - public function testAuthenticate() { - + public function testAuthenticate() + { $response = new Sabre_HTTP_ResponseMock(); $tree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla')); $server = new Sabre_DAV_Server($tree); $server->httpResponse = $response; - $digestHash = md5('HELLO:12345:1:1:auth:' . md5('GET:/')); + $digestHash = md5('HELLO:12345:1:1:auth:'.md5('GET:/')); $header = 'username=user, realm=myRealm, nonce=12345, uri=/, response='.$digestHash.', opaque=1, qop=auth, nc=1, cnonce=1'; $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'GET', + 'REQUEST_METHOD' => 'GET', 'PHP_AUTH_DIGEST' => $header, - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', )); $server->httpRequest = $request; $backend = new Sabre_DAV_Auth_Backend_AbstractDigestMock(); - $this->assertTrue($backend->authenticate($server,'myRealm')); + $this->assertTrue($backend->authenticate($server, 'myRealm')); $result = $backend->getCurrentUser(); $this->assertEquals('user', $result); $this->assertEquals('HELLO', $backend->getDigestHash('myRealm', $result)); - } - - } - -class Sabre_DAV_Auth_Backend_AbstractDigestMock extends Sabre_DAV_Auth_Backend_AbstractDigest { - - function getDigestHash($realm, $userName) { - - switch($userName) { - case 'null' : return null; - case 'false' : return false; - case 'array' : return array(); - case 'user' : return 'HELLO'; +class Sabre_DAV_Auth_Backend_AbstractDigestMock extends Sabre_DAV_Auth_Backend_AbstractDigest +{ + public function getDigestHash($realm, $userName) + { + switch ($userName) { + case 'null': return null; + case 'false': return false; + case 'array': return array(); + case 'user': return 'HELLO'; } - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractPDOTest.php b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractPDOTest.php index 8adbf9ca..f401b454 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractPDOTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/AbstractPDOTest.php @@ -1,31 +1,28 @@ getPDO(); $backend = new Sabre_DAV_Auth_Backend_PDO($pdo); $this->assertTrue($backend instanceof Sabre_DAV_Auth_Backend_PDO); - } /** * @depends testConstruct */ - function testUserInfo() { - + public function testUserInfo() + { $pdo = $this->getPDO(); $backend = new Sabre_DAV_Auth_Backend_PDO($pdo); - $this->assertNull($backend->getDigestHash('realm','blabla')); + $this->assertNull($backend->getDigestHash('realm', 'blabla')); $expected = 'hash'; - $this->assertEquals($expected, $backend->getDigestHash('realm','user')); - + $this->assertEquals($expected, $backend->getDigestHash('realm', 'user')); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/ApacheTest.php b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/ApacheTest.php index 2eb52abb..2ef26813 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/ApacheTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/ApacheTest.php @@ -1,26 +1,24 @@ authenticate($server,'Realm'); - + $backend->authenticate($server, 'Realm'); } - function testRemoteUser() { - + public function testRemoteUser() + { $backend = new Sabre_DAV_Auth_Backend_Apache(); $server = new Sabre_DAV_Server(); @@ -34,7 +32,5 @@ class Sabre_DAV_Auth_Backend_ApacheTest extends PHPUnit_Framework_TestCase { $userInfo = 'username'; $this->assertEquals($userInfo, $backend->getCurrentUser()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/FileTest.php b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/FileTest.php index 9b5f1cdc..194daa3b 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/FileTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/FileTest.php @@ -1,40 +1,37 @@ assertTrue($file instanceof Sabre_DAV_Auth_Backend_File); - } /** * @expectedException Sabre_DAV_Exception */ - function testLoadFileBroken() { - - file_put_contents(SABRE_TEMPDIR . '/backend','user:realm:hash'); + public function testLoadFileBroken() + { + file_put_contents(SABRE_TEMPDIR.'/backend', 'user:realm:hash'); $file = new Sabre_DAV_Auth_Backend_File(); - $file->loadFile(SABRE_TEMPDIR .'/backend'); - + $file->loadFile(SABRE_TEMPDIR.'/backend'); } - function testLoadFile() { - - file_put_contents(SABRE_TEMPDIR . '/backend','user:realm:' . md5('user:realm:password')); + public function testLoadFile() + { + file_put_contents(SABRE_TEMPDIR.'/backend', 'user:realm:'.md5('user:realm:password')); $file = new Sabre_DAV_Auth_Backend_File(); - $file->loadFile(SABRE_TEMPDIR . '/backend'); - - $this->assertFalse($file->getDigestHash('realm','blabla')); - $this->assertEquals(md5('user:realm:password'), $file->getDigesthash('realm','user')); + $file->loadFile(SABRE_TEMPDIR.'/backend'); + $this->assertFalse($file->getDigestHash('realm', 'blabla')); + $this->assertEquals(md5('user:realm:password'), $file->getDigesthash('realm', 'user')); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/PDOMySQLTest.php b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/PDOMySQLTest.php index c35cb69e..65f06164 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/PDOMySQLTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/PDOMySQLTest.php @@ -2,15 +2,19 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_DAV_Auth_Backend_PDOMySQLTest extends Sabre_DAV_Auth_Backend_AbstractPDOTest { - - function getPDO() { - - if (!SABRE_HASMYSQL) $this->markTestSkipped('MySQL driver is not available, or not properly configured'); +class Sabre_DAV_Auth_Backend_PDOMySQLTest extends Sabre_DAV_Auth_Backend_AbstractPDOTest +{ + public function getPDO() + { + if (!SABRE_HASMYSQL) { + $this->markTestSkipped('MySQL driver is not available, or not properly configured'); + } $pdo = Sabre_TestUtil::getMySQLDB(); - if (!$pdo) $this->markTestSkipped('Could not connect to MySQL database'); - $pdo->query("DROP TABLE IF EXISTS users"); - $pdo->query(" + if (!$pdo) { + $this->markTestSkipped('Could not connect to MySQL database'); + } + $pdo->query('DROP TABLE IF EXISTS users'); + $pdo->query(' create table users ( id integer unsigned not null primary key auto_increment, username varchar(50), @@ -18,12 +22,10 @@ create table users ( email varchar(80), displayname varchar(80), unique(username) -);"); +);'); $pdo->query("INSERT INTO users (username,digesta1,email,displayname) VALUES ('user','hash','user@example.org','User')"); return $pdo; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/PDOSqliteTest.php b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/PDOSqliteTest.php index bc84c4f6..f79d97e8 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/PDOSqliteTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Auth/Backend/PDOSqliteTest.php @@ -2,25 +2,28 @@ require_once 'Sabre/DAV/Auth/Backend/AbstractPDOTest.php'; -class Sabre_DAV_Auth_Backend_PDOSQLiteTest extends Sabre_DAV_Auth_Backend_AbstractPDOTest { - - function tearDown() { - - if (file_exists(SABRE_TEMPDIR . '/pdobackend')) unlink(SABRE_TEMPDIR . '/pdobackend'); - if (file_exists(SABRE_TEMPDIR . '/pdobackend2')) unlink(SABRE_TEMPDIR . '/pdobackend2'); - +class Sabre_DAV_Auth_Backend_PDOSqliteTest extends Sabre_DAV_Auth_Backend_AbstractPDOTest +{ + public function tearDown() + { + if (file_exists(SABRE_TEMPDIR.'/pdobackend')) { + unlink(SABRE_TEMPDIR.'/pdobackend'); + } + if (file_exists(SABRE_TEMPDIR.'/pdobackend2')) { + unlink(SABRE_TEMPDIR.'/pdobackend2'); + } } - function getPDO() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function getPDO() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $pdo = new PDO('sqlite:'.SABRE_TEMPDIR.'/pdobackend'); - $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->query('CREATE TABLE users (username TEXT, digesta1 TEXT, email VARCHAR(80), displayname VARCHAR(80))'); $pdo->query('INSERT INTO users VALUES ("user","hash","user@example.org","User")'); return $pdo; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Auth/MockBackend.php b/dav/SabreDAV/tests/Sabre/DAV/Auth/MockBackend.php index 6cc6b3ef..c26b737d 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Auth/MockBackend.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Auth/MockBackend.php @@ -1,32 +1,31 @@ currentUser = 'admin'; - } - function setCurrentUser($user) { - + public function setCurrentUser($user) + { $this->currentUser = $user; - } - function getCurrentUser() { - + public function getCurrentUser() + { return $this->currentUser; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Auth/PluginTest.php b/dav/SabreDAV/tests/Sabre/DAV/Auth/PluginTest.php index e89f4c5a..ee485f6f 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Auth/PluginTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Auth/PluginTest.php @@ -3,49 +3,44 @@ require_once 'Sabre/DAV/Auth/MockBackend.php'; require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_DAV_Auth_PluginTest extends PHPUnit_Framework_TestCase { - - function testInit() { - +class Sabre_DAV_Auth_PluginTest extends PHPUnit_Framework_TestCase +{ + public function testInit() + { $fakeServer = new Sabre_DAV_Server(new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla'))); - $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'realm'); + $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'realm'); $this->assertTrue($plugin instanceof Sabre_DAV_Auth_Plugin); $fakeServer->addPlugin($plugin); $this->assertEquals($plugin, $fakeServer->getPlugin('auth')); - } /** * @depends testInit */ - function testAuthenticate() { - + public function testAuthenticate() + { $fakeServer = new Sabre_DAV_Server(new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla'))); - $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'realm'); + $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'realm'); $fakeServer->addPlugin($plugin); - $fakeServer->broadCastEvent('beforeMethod',array('GET','/')); - + $fakeServer->broadCastEvent('beforeMethod', array('GET', '/')); } - - /** * @depends testInit * @expectedException Sabre_DAV_Exception_NotAuthenticated */ - function testAuthenticateFail() { - + public function testAuthenticateFail() + { $fakeServer = new Sabre_DAV_Server(new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla'))); - $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'failme'); + $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'failme'); $fakeServer->addPlugin($plugin); - $fakeServer->broadCastEvent('beforeMethod',array('GET','/')); - + $fakeServer->broadCastEvent('beforeMethod', array('GET', '/')); } - function testReportPassThrough() { - + public function testReportPassThrough() + { $fakeServer = new Sabre_DAV_Server(new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla'))); - $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'realm'); + $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'realm'); $fakeServer->addPlugin($plugin); $request = new Sabre_HTTP_Request(array( @@ -60,21 +55,17 @@ class Sabre_DAV_Auth_PluginTest extends PHPUnit_Framework_TestCase { $fakeServer->exec(); $this->assertEquals('HTTP/1.1 501 Not Implemented', $fakeServer->httpResponse->status); - } /** * @depends testInit */ - function testGetCurrentUserPrincipal() { - + public function testGetCurrentUserPrincipal() + { $fakeServer = new Sabre_DAV_Server(new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('bla'))); - $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'realm'); + $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'realm'); $fakeServer->addPlugin($plugin); - $fakeServer->broadCastEvent('beforeMethod',array('GET','/')); + $fakeServer->broadCastEvent('beforeMethod', array('GET', '/')); $this->assertEquals('admin', $plugin->getCurrentUser()); - } - } - diff --git a/dav/SabreDAV/tests/Sabre/DAV/BasicNodeTest.php b/dav/SabreDAV/tests/Sabre/DAV/BasicNodeTest.php index 8297cee4..034cf2de 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/BasicNodeTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/BasicNodeTest.php @@ -1,232 +1,205 @@ put('hi'); - } /** * @expectedException Sabre_DAV_Exception_Forbidden */ - public function testGet() { - + public function testGet() + { $file = new Sabre_DAV_FileMock(); $file->get(); - } - public function testGetSize() { - + public function testGetSize() + { $file = new Sabre_DAV_FileMock(); - $this->assertEquals(0,$file->getSize()); - + $this->assertEquals(0, $file->getSize()); } - - public function testGetETag() { - + public function testGetETag() + { $file = new Sabre_DAV_FileMock(); $this->assertNull($file->getETag()); - } - public function testGetContentType() { - + public function testGetContentType() + { $file = new Sabre_DAV_FileMock(); $this->assertNull($file->getContentType()); - } /** * @expectedException Sabre_DAV_Exception_Forbidden */ - public function testDelete() { - + public function testDelete() + { $file = new Sabre_DAV_FileMock(); $file->delete(); - } /** * @expectedException Sabre_DAV_Exception_Forbidden */ - public function testSetName() { - + public function testSetName() + { $file = new Sabre_DAV_FileMock(); $file->setName('hi'); - } - public function testGetLastModified() { - + public function testGetLastModified() + { $file = new Sabre_DAV_FileMock(); // checking if lastmod is within the range of a few seconds $lastMod = $file->getLastModified(); - $compareTime = ($lastMod + 1)-time(); + $compareTime = ($lastMod + 1) - time(); $this->assertTrue($compareTime < 3); - } - public function testGetChild() { - + public function testGetChild() + { $dir = new Sabre_DAV_DirectoryMock(); $file = $dir->getChild('mockfile'); $this->assertTrue($file instanceof Sabre_DAV_FileMock); - } - public function testChildExists() { - + public function testChildExists() + { $dir = new Sabre_DAV_DirectoryMock(); $this->assertTrue($dir->childExists('mockfile')); - } - public function testChildExistsFalse() { - + public function testChildExistsFalse() + { $dir = new Sabre_DAV_DirectoryMock(); $this->assertFalse($dir->childExists('mockfile2')); - } /** * @expectedException Sabre_DAV_Exception_NotFound */ - public function testGetChild404() { - + public function testGetChild404() + { $dir = new Sabre_DAV_DirectoryMock(); $file = $dir->getChild('blabla'); - } /** * @expectedException Sabre_DAV_Exception_Forbidden */ - public function testCreateFile() { - + public function testCreateFile() + { $dir = new Sabre_DAV_DirectoryMock(); - $dir->createFile('hello','data'); - + $dir->createFile('hello', 'data'); } /** * @expectedException Sabre_DAV_Exception_Forbidden */ - public function testCreateDirectory() { - + public function testCreateDirectory() + { $dir = new Sabre_DAV_DirectoryMock(); $dir->createDirectory('hello'); - } - public function testSimpleDirectoryConstruct() { - - $dir = new Sabre_DAV_SimpleCollection('simpledir',array()); - + public function testSimpleDirectoryConstruct() + { + $dir = new Sabre_DAV_SimpleCollection('simpledir', array()); } /** * @depends testSimpleDirectoryConstruct */ - public function testSimpleDirectoryConstructChild() { - + public function testSimpleDirectoryConstructChild() + { $file = new Sabre_DAV_FileMock(); - $dir = new Sabre_DAV_SimpleCollection('simpledir',array($file)); + $dir = new Sabre_DAV_SimpleCollection('simpledir', array($file)); $file2 = $dir->getChild('mockfile'); - $this->assertEquals($file,$file2); - + $this->assertEquals($file, $file2); } /** * @expectedException Sabre_DAV_Exception * @depends testSimpleDirectoryConstruct */ - public function testSimpleDirectoryBadParam() { - - $dir = new Sabre_DAV_SimpleCollection('simpledir',array('string shouldn\'t be here')); - + public function testSimpleDirectoryBadParam() + { + $dir = new Sabre_DAV_SimpleCollection('simpledir', array('string shouldn\'t be here')); } /** * @depends testSimpleDirectoryConstruct */ - public function testSimpleDirectoryAddChild() { - + public function testSimpleDirectoryAddChild() + { $file = new Sabre_DAV_FileMock(); $dir = new Sabre_DAV_SimpleCollection('simpledir'); $dir->addChild($file); $file2 = $dir->getChild('mockfile'); - $this->assertEquals($file,$file2); - + $this->assertEquals($file, $file2); } /** * @depends testSimpleDirectoryConstruct * @depends testSimpleDirectoryAddChild */ - public function testSimpleDirectoryGetChildren() { - + public function testSimpleDirectoryGetChildren() + { $file = new Sabre_DAV_FileMock(); $dir = new Sabre_DAV_SimpleCollection('simpledir'); $dir->addChild($file); - $this->assertEquals(array($file),$dir->getChildren()); - + $this->assertEquals(array($file), $dir->getChildren()); } /* * @depends testSimpleDirectoryConstruct */ - public function testSimpleDirectoryGetName() { - + public function testSimpleDirectoryGetName() + { $dir = new Sabre_DAV_SimpleCollection('simpledir'); - $this->assertEquals('simpledir',$dir->getName()); - + $this->assertEquals('simpledir', $dir->getName()); } /** * @depends testSimpleDirectoryConstruct * @expectedException Sabre_DAV_Exception_NotFound */ - public function testSimpleDirectoryGetChild404() { - + public function testSimpleDirectoryGetChild404() + { $dir = new Sabre_DAV_SimpleCollection('simpledir'); $dir->getChild('blabla'); - } } -class Sabre_DAV_DirectoryMock extends Sabre_DAV_Collection { - - function getName() { - +class Sabre_DAV_DirectoryMock extends Sabre_DAV_Collection +{ + public function getName() + { return 'mockdir'; - } - function getChildren() { - + public function getChildren() + { return array(new Sabre_DAV_FileMock()); - } - } -class Sabre_DAV_FileMock extends Sabre_DAV_File { - - function getName() { - +class Sabre_DAV_FileMock extends Sabre_DAV_File +{ + public function getName() + { return 'mockfile'; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Browser/GuessContentTypeTest.php b/dav/SabreDAV/tests/Sabre/DAV/Browser/GuessContentTypeTest.php index ad8c3d2e..2c73c414 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Browser/GuessContentTypeTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Browser/GuessContentTypeTest.php @@ -1,64 +1,60 @@ server->getPropertiesForPath('/somefile.jpg',$properties); - $this->assertArrayHasKey(0,$result); - $this->assertArrayHasKey(404,$result[0]); - $this->assertArrayHasKey('{DAV:}getcontenttype',$result[0][404]); - + $result = $this->server->getPropertiesForPath('/somefile.jpg', $properties); + $this->assertArrayHasKey(0, $result); + $this->assertArrayHasKey(404, $result[0]); + $this->assertArrayHasKey('{DAV:}getcontenttype', $result[0][404]); } /** * @depends testGetProperties */ - function testGetPropertiesPluginEnabled() { - + public function testGetPropertiesPluginEnabled() + { $this->server->addPlugin(new Sabre_DAV_Browser_GuessContentType()); $properties = array( '{DAV:}getcontenttype', ); - $result = $this->server->getPropertiesForPath('/somefile.jpg',$properties); - $this->assertArrayHasKey(0,$result); - $this->assertArrayHasKey(200,$result[0]); - $this->assertArrayHasKey('{DAV:}getcontenttype',$result[0][200]); - $this->assertEquals('image/jpeg',$result[0][200]['{DAV:}getcontenttype']); - + $result = $this->server->getPropertiesForPath('/somefile.jpg', $properties); + $this->assertArrayHasKey(0, $result); + $this->assertArrayHasKey(200, $result[0]); + $this->assertArrayHasKey('{DAV:}getcontenttype', $result[0][200]); + $this->assertEquals('image/jpeg', $result[0][200]['{DAV:}getcontenttype']); } /** * @depends testGetPropertiesPluginEnabled */ - function testGetPropertiesUnknown() { - + public function testGetPropertiesUnknown() + { $this->server->addPlugin(new Sabre_DAV_Browser_GuessContentType()); $properties = array( '{DAV:}getcontenttype', ); - $result = $this->server->getPropertiesForPath('/somefile.hoi',$properties); - $this->assertArrayHasKey(0,$result); - $this->assertArrayHasKey(404,$result[0]); - $this->assertArrayHasKey('{DAV:}getcontenttype',$result[0][404]); - + $result = $this->server->getPropertiesForPath('/somefile.hoi', $properties); + $this->assertArrayHasKey(0, $result); + $this->assertArrayHasKey(404, $result[0]); + $this->assertArrayHasKey('{DAV:}getcontenttype', $result[0][404]); } } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Browser/MapGetToPropFindTest.php b/dav/SabreDAV/tests/Sabre/DAV/Browser/MapGetToPropFindTest.php index 5f42d93a..1b37b70c 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Browser/MapGetToPropFindTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Browser/MapGetToPropFindTest.php @@ -2,19 +2,18 @@ require_once 'Sabre/DAV/AbstractServer.php'; -class Sabre_DAV_Browser_MapGetToPropFindTest extends Sabre_DAV_AbstractServer { - - function setUp() { - +class Sabre_DAV_Browser_MapGetToPropFindTest extends Sabre_DAV_AbstractServer +{ + public function setUp() + { parent::setUp(); $this->server->addPlugin(new Sabre_DAV_Browser_MapGetToPropFind()); - } - function testCollectionGet() { - + public function testCollectionGet() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'GET', ); @@ -30,9 +29,6 @@ class Sabre_DAV_Browser_MapGetToPropFindTest extends Sabre_DAV_AbstractServer { $this->response->headers ); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'Incorrect status response received. Full response body: ' . $this->response->body); - + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'Incorrect status response received. Full response body: '.$this->response->body); } - - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Browser/PluginTest.php b/dav/SabreDAV/tests/Sabre/DAV/Browser/PluginTest.php index d03c6fd3..296e3b0f 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Browser/PluginTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Browser/PluginTest.php @@ -2,19 +2,18 @@ require_once 'Sabre/DAV/AbstractServer.php'; -class Sabre_DAV_Browser_PluginTest extends Sabre_DAV_AbstractServer{ - - function setUp() { - +class Sabre_DAV_Browser_PluginTest extends Sabre_DAV_AbstractServer +{ + public function setUp() + { parent::setUp(); $this->server->addPlugin(new Sabre_DAV_Browser_Plugin()); - } - function testCollectionGet() { - + public function testCollectionGet() + { $serverVars = array( - 'REQUEST_URI' => '/dir', + 'REQUEST_URI' => '/dir', 'REQUEST_METHOD' => 'GET', ); @@ -22,7 +21,7 @@ class Sabre_DAV_Browser_PluginTest extends Sabre_DAV_AbstractServer{ $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals(array( 'Content-Type' => 'text/html; charset=utf-8', ), @@ -30,13 +29,12 @@ class Sabre_DAV_Browser_PluginTest extends Sabre_DAV_AbstractServer{ ); $this->assertTrue(strpos($this->response->body, 'Index for dir/') !== false); - } - function testNotFound() { - + public function testNotFound() + { $serverVars = array( - 'REQUEST_URI' => '/random', + 'REQUEST_URI' => '/random', 'REQUEST_METHOD' => 'GET', ); @@ -44,14 +42,13 @@ class Sabre_DAV_Browser_PluginTest extends Sabre_DAV_AbstractServer{ $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 404 Not Found',$this->response->status); - + $this->assertEquals('HTTP/1.1 404 Not Found', $this->response->status); } - function testPostOtherContentType() { - + public function testPostOtherContentType() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'text/xml', ); @@ -60,30 +57,28 @@ class Sabre_DAV_Browser_PluginTest extends Sabre_DAV_AbstractServer{ $this->server->exec(); $this->assertEquals('HTTP/1.1 501 Not Implemented', $this->response->status); - } - function testPostNoSabreAction() { - + public function testPostNoSabreAction() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', ); $postVars = array(); - $request = new Sabre_HTTP_Request($serverVars,$postVars); + $request = new Sabre_HTTP_Request($serverVars, $postVars); $this->server->httpRequest = $request; $this->server->exec(); $this->assertEquals('HTTP/1.1 501 Not Implemented', $this->response->status); - } - function testPostMkCol() { - + public function testPostMkCol() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'POST', 'CONTENT_TYPE' => 'application/x-www-form-urlencoded', ); @@ -92,7 +87,7 @@ class Sabre_DAV_Browser_PluginTest extends Sabre_DAV_AbstractServer{ 'name' => 'new_collection', ); - $request = new Sabre_HTTP_Request($serverVars,$postVars); + $request = new Sabre_HTTP_Request($serverVars, $postVars); $this->server->httpRequest = $request; $this->server->exec(); @@ -101,8 +96,6 @@ class Sabre_DAV_Browser_PluginTest extends Sabre_DAV_AbstractServer{ 'Location' => '/', ), $this->response->headers); - $this->assertTrue(is_dir(SABRE_TEMPDIR . '/new_collection')); - + $this->assertTrue(is_dir(SABRE_TEMPDIR.'/new_collection')); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ClientMock.php b/dav/SabreDAV/tests/Sabre/DAV/ClientMock.php index 83c51a3d..f3859811 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ClientMock.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ClientMock.php @@ -1,30 +1,29 @@ url = $url; $this->curlSettings = $curlSettings; - return $this->response; + return $this->response; } /** - * Just making this method public + * Just making this method public. * * @param string $url + * * @return string */ - public function getAbsoluteUrl($url) { - + public function getAbsoluteUrl($url) + { return parent::getAbsoluteUrl($url); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ClientTest.php b/dav/SabreDAV/tests/Sabre/DAV/ClientTest.php index 4d23e278..54d7189f 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ClientTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ClientTest.php @@ -2,36 +2,34 @@ require_once 'Sabre/DAV/ClientMock.php'; -class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { - - function testConstruct() { - +class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase +{ + public function testConstruct() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => '/', )); - } /** * @expectedException InvalidArgumentException */ - function testConstructNoBaseUri() { - + public function testConstructNoBaseUri() + { $client = new Sabre_DAV_ClientMock(array()); - } - function testRequest() { - + public function testRequest() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "Content-Type: text/plain", - "", - "Hello there!" + 'HTTP/1.1 200 OK', + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -41,7 +39,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); $result = $client->request('POST', 'baz', 'sillybody', array('Content-Type' => 'text/plain')); @@ -62,25 +60,22 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'headers' => array( 'content-type' => 'text/plain', ), - 'body' => 'Hello there!' + 'body' => 'Hello there!', ), $result); - - } - - function testRequestProxy() { - + public function testRequestProxy() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', 'proxy' => 'http://localhost:8000/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "Content-Type: text/plain", - "", - "Hello there!" + 'HTTP/1.1 200 OK', + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -90,7 +85,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); $result = $client->request('POST', 'baz', 'sillybody', array('Content-Type' => 'text/plain')); @@ -112,14 +107,12 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'headers' => array( 'content-type' => 'text/plain', ), - 'body' => 'Hello there!' + 'body' => 'Hello there!', ), $result); - } - - function testRequestAuth() { - + public function testRequestAuth() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', 'userName' => 'user', @@ -127,10 +120,10 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { )); $responseBlob = array( - "HTTP/1.1 200 OK", - "Content-Type: text/plain", - "", - "Hello there!" + 'HTTP/1.1 200 OK', + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -140,7 +133,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); $result = $client->request('POST', 'baz', 'sillybody', array('Content-Type' => 'text/plain')); @@ -155,7 +148,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => array('Content-Type: text/plain'), CURLOPT_HTTPAUTH => CURLAUTH_BASIC | CURLAUTH_DIGEST, - CURLOPT_USERPWD => 'user:password' + CURLOPT_USERPWD => 'user:password', ), $client->curlSettings); $this->assertEquals(array( @@ -163,13 +156,12 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'headers' => array( 'content-type' => 'text/plain', ), - 'body' => 'Hello there!' + 'body' => 'Hello there!', ), $result); - } - function testRequestAuthBasic() { - + public function testRequestAuthBasic() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', 'userName' => 'user', @@ -178,10 +170,10 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { )); $responseBlob = array( - "HTTP/1.1 200 OK", - "Content-Type: text/plain", - "", - "Hello there!" + 'HTTP/1.1 200 OK', + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -191,7 +183,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); $result = $client->request('POST', 'baz', 'sillybody', array('Content-Type' => 'text/plain')); @@ -206,7 +198,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => array('Content-Type: text/plain'), CURLOPT_HTTPAUTH => CURLAUTH_BASIC, - CURLOPT_USERPWD => 'user:password' + CURLOPT_USERPWD => 'user:password', ), $client->curlSettings); $this->assertEquals(array( @@ -214,13 +206,12 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'headers' => array( 'content-type' => 'text/plain', ), - 'body' => 'Hello there!' + 'body' => 'Hello there!', ), $result); - } - function testRequestAuthDigest() { - + public function testRequestAuthDigest() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', 'userName' => 'user', @@ -229,10 +220,10 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { )); $responseBlob = array( - "HTTP/1.1 200 OK", - "Content-Type: text/plain", - "", - "Hello there!" + 'HTTP/1.1 200 OK', + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -242,7 +233,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); $result = $client->request('POST', 'baz', 'sillybody', array('Content-Type' => 'text/plain')); @@ -257,7 +248,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => array('Content-Type: text/plain'), CURLOPT_HTTPAUTH => CURLAUTH_DIGEST, - CURLOPT_USERPWD => 'user:password' + CURLOPT_USERPWD => 'user:password', ), $client->curlSettings); $this->assertEquals(array( @@ -265,21 +256,20 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'headers' => array( 'content-type' => 'text/plain', ), - 'body' => 'Hello there!' + 'body' => 'Hello there!', ), $result); - } - function testRequestError() { - + public function testRequestError() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "Content-Type: text/plain", - "", - "Hello there!" + 'HTTP/1.1 200 OK', + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -289,7 +279,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), CURLE_COULDNT_CONNECT, - "Could not connect, or something" + 'Could not connect, or something', ); $caught = false; @@ -301,20 +291,19 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { if (!$caught) { $this->markTestFailed('Exception was not thrown'); } - } - function testRequestHTTPError() { - + public function testRequestHTTPError() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 400 Bad Request", - "Content-Type: text/plain", - "", - "Hello there!" + 'HTTP/1.1 400 Bad Request', + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -324,7 +313,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 400, ), 0, - "" + '', ); $caught = false; @@ -336,20 +325,19 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { if (!$caught) { $this->fail('Exception was not thrown'); } - } - function testRequestHTTP404() { - + public function testRequestHTTP404() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 404 Not Found", - "Content-Type: text/plain", - "", - "Hello there!" + 'HTTP/1.1 404 Not Found', + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -359,7 +347,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 404, ), 0, - "" + '', ); $caught = false; @@ -371,23 +359,22 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { if (!$caught) { $this->fail('Exception was not thrown'); } - } /** * @dataProvider supportedHTTPCodes */ - function testSpecificHTTPErrors($error) { - + public function testSpecificHTTPErrors($error) + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( "HTTP/1.1 $error blabla", - "Content-Type: text/plain", - "", - "Hello there!" + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -397,7 +384,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => $error, ), 0, - "" + '', ); $caught = false; @@ -410,12 +397,10 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { if (!$caught) { $this->fail('Exception was not thrown'); } - - } - public function supportedHTTPCodes() { - + public function supportedHTTPCodes() + { return array( array(400), array(401), @@ -430,11 +415,10 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { array(501), array(507), ); - } - function testGetAbsoluteUrl() { - + public function testGetAbsoluteUrl() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/', )); @@ -453,19 +437,18 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http://example.com/bar', $client->getAbsoluteUrl('http://example.com/bar') ); - } - function testOptions() { - + public function testOptions() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "DAV: feature1, feature2", - "", + 'HTTP/1.1 200 OK', + 'DAV: feature1, feature2', + '', ); $client->response = array( @@ -475,7 +458,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); $result = $client->options(); @@ -483,18 +466,17 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { array('feature1', 'feature2'), $result ); - } - function testOptionsNoDav() { - + public function testOptionsNoDav() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "", + 'HTTP/1.1 200 OK', + '', ); $client->response = array( @@ -504,7 +486,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); $result = $client->options(); @@ -512,21 +494,20 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { array(), $result ); - } /** * @expectedException InvalidArgumentException */ - function testPropFindNoXML() { - + public function testPropFindNoXML() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "", + 'HTTP/1.1 200 OK', + '', ); $client->response = array( @@ -536,40 +517,39 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); - $client->propfind('', array('{DAV:}foo','{DAV:}bar')); - + $client->propfind('', array('{DAV:}foo', '{DAV:}bar')); } - function testPropFind() { - + public function testPropFind() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "", - "", - "", - " ", - " /foo/bar/", - " ", - " ", - " hello", - " ", - " HTTP/1.1 200 OK", - " ", - " ", - " ", - " ", - " ", - " HTTP/1.1 404 Not Found", - " ", - " ", - "", + 'HTTP/1.1 200 OK', + '', + '', + '', + ' ', + ' /foo/bar/', + ' ', + ' ', + ' hello', + ' ', + ' HTTP/1.1 200 OK', + ' ', + ' ', + ' ', + ' ', + ' ', + ' HTTP/1.1 404 Not Found', + ' ', + ' ', + '', ); $client->response = array( @@ -579,10 +559,10 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); - $result = $client->propfind('', array('{DAV:}foo','{DAV:}bar')); + $result = $client->propfind('', array('{DAV:}foo', '{DAV:}bar')); $this->assertEquals(array( '{DAV:}foo' => 'hello', @@ -595,36 +575,35 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { ' ', ' ', ' ', - '' + '', ); $requestBody = implode("\n", $requestBody); $this->assertEquals($requestBody, $client->curlSettings[CURLOPT_POSTFIELDS]); - } - function testPropFindDepth1CustomProp() { - + public function testPropFindDepth1CustomProp() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "", - "", - "", - " ", - " /foo/bar/", - " ", - " ", - " hello", - " world", - " ", - " HTTP/1.1 200 OK", - " ", - " ", - "", + 'HTTP/1.1 200 OK', + '', + '', + '', + ' ', + ' /foo/bar/', + ' ', + ' ', + ' hello', + ' world', + ' ', + ' HTTP/1.1 200 OK', + ' ', + ' ', + '', ); $client->response = array( @@ -634,13 +613,13 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); - $result = $client->propfind('', array('{DAV:}foo','{urn:custom}bar'),1); + $result = $client->propfind('', array('{DAV:}foo', '{urn:custom}bar'), 1); $this->assertEquals(array( - "/foo/bar/" => array( + '/foo/bar/' => array( '{DAV:}foo' => 'hello', '{urn:custom}bar' => 'world', ), @@ -653,23 +632,22 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { ' ', ' ', ' ', - '' + '', ); $requestBody = implode("\n", $requestBody); $this->assertEquals($requestBody, $client->curlSettings[CURLOPT_POSTFIELDS]); - } - function testPropPatch() { - + public function testPropPatch() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "", + 'HTTP/1.1 200 OK', + '', ); $client->response = array( @@ -679,7 +657,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); $client->proppatch('', array( @@ -704,25 +682,24 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { '', ' ', '', - '' + '', ); $requestBody = implode("\n", $requestBody); $this->assertEquals($requestBody, $client->curlSettings[CURLOPT_POSTFIELDS]); - } - function testHEADRequest() { - + public function testHEADRequest() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "Content-Type: text/plain", - "", - "Hello there!" + 'HTTP/1.1 200 OK', + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -732,7 +709,7 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); $result = $client->request('HEAD', 'baz'); @@ -748,20 +725,19 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { CURLOPT_HTTPHEADER => array(), CURLOPT_POSTFIELDS => null, ), $client->curlSettings); - } - function testPUTRequest() { - + public function testPUTRequest() + { $client = new Sabre_DAV_ClientMock(array( 'baseUri' => 'http://example.org/foo/bar/', )); $responseBlob = array( - "HTTP/1.1 200 OK", - "Content-Type: text/plain", - "", - "Hello there!" + 'HTTP/1.1 200 OK', + 'Content-Type: text/plain', + '', + 'Hello there!', ); $client->response = array( @@ -771,21 +747,20 @@ class Sabre_DAV_ClientTest extends PHPUnit_Framework_TestCase { 'http_code' => 200, ), 0, - "" + '', ); - $result = $client->request('PUT', 'bar','newcontent'); + $result = $client->request('PUT', 'bar', 'newcontent'); $this->assertEquals('http://example.org/foo/bar/bar', $client->url); $this->assertEquals(array( CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 5, - CURLOPT_CUSTOMREQUEST => "PUT", + CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_POSTFIELDS => 'newcontent', CURLOPT_HEADER => true, CURLOPT_HTTPHEADER => array(), ), $client->curlSettings); - } } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Exception/PaymentRequiredTest.php b/dav/SabreDAV/tests/Sabre/DAV/Exception/PaymentRequiredTest.php index 1c37796b..489c5972 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Exception/PaymentRequiredTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Exception/PaymentRequiredTest.php @@ -1,12 +1,10 @@ assertEquals(402, $ex->getHTTPCode()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ExceptionTest.php b/dav/SabreDAV/tests/Sabre/DAV/ExceptionTest.php index a40f0ee4..bfb46465 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ExceptionTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ExceptionTest.php @@ -1,28 +1,23 @@ assertEquals(500,$e->getHTTPCode()); - + $this->assertEquals(500, $e->getHTTPCode()); } - function testExceptionStatuses() { - + public function testExceptionStatuses() + { $c = array( - 'Sabre_DAV_Exception_NotAuthenticated' => 401, + 'Sabre_DAV_Exception_NotAuthenticated' => 401, 'Sabre_DAV_Exception_InsufficientStorage' => 507, ); - foreach($c as $class=>$status) { - + foreach ($c as $class => $status) { $obj = new $class(); $this->assertEquals($status, $obj->getHTTPCode()); - } - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/FSExt/FileTest.php b/dav/SabreDAV/tests/Sabre/DAV/FSExt/FileTest.php index 4e188feb..5c27523e 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/FSExt/FileTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/FSExt/FileTest.php @@ -2,75 +2,65 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_DAV_FSExt_FileTest extends PHPUnit_Framework_TestCase { - - function setUp() { - - file_put_contents(SABRE_TEMPDIR . '/file.txt', 'Contents'); - +class Sabre_DAV_FSExt_FileTest extends PHPUnit_Framework_TestCase +{ + public function setUp() + { + file_put_contents(SABRE_TEMPDIR.'/file.txt', 'Contents'); } - function tearDown() { - + public function tearDown() + { Sabre_TestUtil::clearTempDir(); - } - function testPut() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/file.txt'); - $result = $file->put('New contents'); - - $this->assertEquals('New contents',file_get_contents(SABRE_TEMPDIR . '/file.txt')); - $this->assertEquals('"' . md5('New contents') . '"', $result); + public function testPut() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/file.txt'); + $result = $file->put('New contents'); + $this->assertEquals('New contents', file_get_contents(SABRE_TEMPDIR.'/file.txt')); + $this->assertEquals('"'.md5('New contents').'"', $result); } - function testRange() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/file.txt'); - $file->put('0000000'); - $file->putRange('111',3); - - $this->assertEquals('0011100',file_get_contents(SABRE_TEMPDIR . '/file.txt')); + public function testRange() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/file.txt'); + $file->put('0000000'); + $file->putRange('111', 3); + $this->assertEquals('0011100', file_get_contents(SABRE_TEMPDIR.'/file.txt')); } - function testGet() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/file.txt'); - $this->assertEquals('Contents',stream_get_contents($file->get())); - + public function testGet() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/file.txt'); + $this->assertEquals('Contents', stream_get_contents($file->get())); } - function testDelete() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/file.txt'); - $file->delete(); - - $this->assertFalse(file_exists(SABRE_TEMPDIR . '/file.txt')); + public function testDelete() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/file.txt'); + $file->delete(); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/file.txt')); } - function testGetETag() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/file.txt'); - $this->assertEquals('"' . md5('Contents') . '"',$file->getETag()); - + public function testGetETag() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/file.txt'); + $this->assertEquals('"'.md5('Contents').'"', $file->getETag()); } - function testGetContentType() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/file.txt'); - $this->assertNull($file->getContentType()); - + public function testGetContentType() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/file.txt'); + $this->assertNull($file->getContentType()); } - function testGetSize() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/file.txt'); - $this->assertEquals(8,$file->getSize()); - + public function testGetSize() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/file.txt'); + $this->assertEquals(8, $file->getSize()); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/FSExt/NodeTest.php b/dav/SabreDAV/tests/Sabre/DAV/FSExt/NodeTest.php index e556e0a5..db1254e5 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/FSExt/NodeTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/FSExt/NodeTest.php @@ -2,25 +2,23 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase { - - function setUp() { - - mkdir(SABRE_TEMPDIR . '/dir'); - file_put_contents(SABRE_TEMPDIR . '/dir/file.txt', 'Contents'); - file_put_contents(SABRE_TEMPDIR . '/dir/file2.txt', 'Contents2'); - +class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase +{ + public function setUp() + { + mkdir(SABRE_TEMPDIR.'/dir'); + file_put_contents(SABRE_TEMPDIR.'/dir/file.txt', 'Contents'); + file_put_contents(SABRE_TEMPDIR.'/dir/file2.txt', 'Contents2'); } - function tearDown() { - + public function tearDown() + { Sabre_TestUtil::clearTempDir(); - } - function testUpdateProperties() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/dir/file.txt'); + public function testUpdateProperties() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/dir/file.txt'); $properties = array( '{http://sabredav.org/NS/2010}test1' => 'foo', '{http://sabredav.org/NS/2010}test2' => 'bar', @@ -34,15 +32,14 @@ class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase { $getProperties = $file->getProperties(array_keys($properties)); $this->assertEquals($properties, $getProperties); - } /** * @depends testUpdateProperties */ - function testUpdatePropertiesAgain() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/dir/file.txt'); + public function testUpdatePropertiesAgain() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/dir/file.txt'); $mutations = array( '{http://sabredav.org/NS/2010}test1' => 'foo', '{http://sabredav.org/NS/2010}test2' => 'bar', @@ -65,9 +62,9 @@ class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase { /** * @depends testUpdateProperties */ - function testUpdatePropertiesDelete() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/dir/file.txt'); + public function testUpdatePropertiesDelete() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/dir/file.txt'); $mutations = array( '{http://sabredav.org/NS/2010}test1' => 'foo', @@ -80,14 +77,14 @@ class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase { $mutations = array( '{http://sabredav.org/NS/2010}test1' => null, - '{http://sabredav.org/NS/2010}test3' => null + '{http://sabredav.org/NS/2010}test3' => null, ); $result = $file->updateProperties($mutations); $this->assertEquals(true, $result); - $properties = $file->getProperties(array('http://sabredav.org/NS/2010}test1','{http://sabredav.org/NS/2010}test2','{http://sabredav.org/NS/2010}test3')); + $properties = $file->getProperties(array('http://sabredav.org/NS/2010}test1', '{http://sabredav.org/NS/2010}test2', '{http://sabredav.org/NS/2010}test3')); $this->assertEquals(array( '{http://sabredav.org/NS/2010}test2' => 'bar', @@ -97,9 +94,9 @@ class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase { /** * @depends testUpdateProperties */ - function testUpdatePropertiesMove() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/dir/file.txt'); + public function testUpdatePropertiesMove() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/dir/file.txt'); $mutations = array( '{http://sabredav.org/NS/2010}test1' => 'foo', @@ -110,7 +107,7 @@ class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase { $this->assertEquals(true, $result); - $properties = $file->getProperties(array('{http://sabredav.org/NS/2010}test1','{http://sabredav.org/NS/2010}test2','{http://sabredav.org/NS/2010}test3')); + $properties = $file->getProperties(array('{http://sabredav.org/NS/2010}test1', '{http://sabredav.org/NS/2010}test2', '{http://sabredav.org/NS/2010}test3')); $this->assertEquals(array( '{http://sabredav.org/NS/2010}test1' => 'foo', @@ -120,14 +117,14 @@ class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase { // Renaming $file->setName('file3.txt'); - $this->assertFalse(file_exists(SABRE_TEMPDIR . '/dir/file.txt')); - $this->assertTrue(file_exists(SABRE_TEMPDIR . '/dir/file3.txt')); - $this->assertEquals('file3.txt',$file->getName()); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/dir/file.txt')); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/dir/file3.txt')); + $this->assertEquals('file3.txt', $file->getName()); - $newFile = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/dir/file3.txt'); - $this->assertEquals('file3.txt',$newFile->getName()); + $newFile = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/dir/file3.txt'); + $this->assertEquals('file3.txt', $newFile->getName()); - $properties = $newFile->getProperties(array('{http://sabredav.org/NS/2010}test1','{http://sabredav.org/NS/2010}test2','{http://sabredav.org/NS/2010}test3')); + $properties = $newFile->getProperties(array('{http://sabredav.org/NS/2010}test1', '{http://sabredav.org/NS/2010}test2', '{http://sabredav.org/NS/2010}test3')); $this->assertEquals(array( '{http://sabredav.org/NS/2010}test1' => 'foo', @@ -138,9 +135,9 @@ class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase { /** * @depends testUpdatePropertiesMove */ - function testUpdatePropertiesDeleteBleed() { - - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/dir/file.txt'); + public function testUpdatePropertiesDeleteBleed() + { + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/dir/file.txt'); $mutations = array( '{http://sabredav.org/NS/2010}test1' => 'foo', '{http://sabredav.org/NS/2010}test2' => 'bar', @@ -150,7 +147,7 @@ class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase { $this->assertEquals(true, $result); - $properties = $file->getProperties(array('{http://sabredav.org/NS/2010}test1','{http://sabredav.org/NS/2010}test2','{http://sabredav.org/NS/2010}test3')); + $properties = $file->getProperties(array('{http://sabredav.org/NS/2010}test1', '{http://sabredav.org/NS/2010}test2', '{http://sabredav.org/NS/2010}test3')); $this->assertEquals(array( '{http://sabredav.org/NS/2010}test1' => 'foo', @@ -160,16 +157,14 @@ class Sabre_DAV_FSExt_NodeTest extends PHPUnit_Framework_TestCase { // Deleting $file->delete(); - $this->assertFalse(file_exists(SABRE_TEMPDIR . '/dir/file.txt')); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/dir/file.txt')); // Creating it again - file_put_contents(SABRE_TEMPDIR . '/dir/file.txt','New Contents'); - $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR . '/dir/file.txt'); + file_put_contents(SABRE_TEMPDIR.'/dir/file.txt', 'New Contents'); + $file = new Sabre_DAV_FSExt_File(SABRE_TEMPDIR.'/dir/file.txt'); - $properties = $file->getProperties(array('http://sabredav.org/NS/2010}test1','{http://sabredav.org/NS/2010}test2','{http://sabredav.org/NS/2010}test3')); + $properties = $file->getProperties(array('http://sabredav.org/NS/2010}test1', '{http://sabredav.org/NS/2010}test2', '{http://sabredav.org/NS/2010}test3')); $this->assertEquals(array(), $properties); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/FSExt/ServerTest.php b/dav/SabreDAV/tests/Sabre/DAV/FSExt/ServerTest.php index 2e308d53..c4a19916 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/FSExt/ServerTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/FSExt/ServerTest.php @@ -2,18 +2,17 @@ require_once 'Sabre/DAV/AbstractServer.php'; -class Sabre_DAV_FSExt_ServerTest extends Sabre_DAV_AbstractServer{ - - protected function getRootNode() { - +class Sabre_DAV_FSExt_ServerTest extends Sabre_DAV_AbstractServer +{ + protected function getRootNode() + { return new Sabre_DAV_FSExt_Directory($this->tempDir); - } - function testGet() { - + public function testGet() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', ); @@ -24,21 +23,20 @@ class Sabre_DAV_FSExt_ServerTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/octet-stream', 'Content-Length' => 13, - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), - 'ETag' => '"' .md5_file($this->tempDir . '/test.txt') . '"', + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), + 'ETag' => '"'.md5_file($this->tempDir.'/test.txt').'"', ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('Test contents', stream_get_contents($this->response->body)); - } - function testHEAD() { - + public function testHEAD() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'HEAD', ); @@ -49,21 +47,20 @@ class Sabre_DAV_FSExt_ServerTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/octet-stream', 'Content-Length' => 13, - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), - 'ETag' => '"' . md5_file($this->tempDir . '/test.txt') . '"', + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), + 'ETag' => '"'.md5_file($this->tempDir.'/test.txt').'"', ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('', $this->response->body); - } - function testPut() { - + public function testPut() + { $serverVars = array( - 'REQUEST_URI' => '/testput.txt', + 'REQUEST_URI' => '/testput.txt', 'REQUEST_METHOD' => 'PUT', ); @@ -74,19 +71,18 @@ class Sabre_DAV_FSExt_ServerTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Length' => 0, - 'ETag' => '"' . md5('Testing new file') . '"', + 'ETag' => '"'.md5('Testing new file').'"', ), $this->response->headers); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals('', $this->response->body); - $this->assertEquals('Testing new file',file_get_contents($this->tempDir . '/testput.txt')); - + $this->assertEquals('Testing new file', file_get_contents($this->tempDir.'/testput.txt')); } - function testPutAlreadyExists() { - + public function testPutAlreadyExists() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'PUT', 'HTTP_IF_NONE_MATCH' => '*', ); @@ -98,39 +94,37 @@ class Sabre_DAV_FSExt_ServerTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 412 Precondition failed',$this->response->status); - $this->assertNotEquals('Testing new file',file_get_contents($this->tempDir . '/test.txt')); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 412 Precondition failed', $this->response->status); + $this->assertNotEquals('Testing new file', file_get_contents($this->tempDir.'/test.txt')); } - function testMkcol() { - + public function testMkcol() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', ); $request = new Sabre_HTTP_Request($serverVars); - $request->setBody(""); + $request->setBody(''); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals(array( 'Content-Length' => '0', - ),$this->response->headers); + ), $this->response->headers); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals('', $this->response->body); - $this->assertTrue(is_dir($this->tempDir . '/testcol')); - + $this->assertTrue(is_dir($this->tempDir.'/testcol')); } - function testPutUpdate() { - + public function testPutUpdate() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'PUT', ); @@ -141,16 +135,15 @@ class Sabre_DAV_FSExt_ServerTest extends Sabre_DAV_AbstractServer{ $this->assertEquals('0', $this->response->headers['Content-Length']); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status); + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status); $this->assertEquals('', $this->response->body); - $this->assertEquals('Testing updated file',file_get_contents($this->tempDir . '/test.txt')); - + $this->assertEquals('Testing updated file', file_get_contents($this->tempDir.'/test.txt')); } - function testDelete() { - + public function testDelete() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'DELETE', ); @@ -160,23 +153,22 @@ class Sabre_DAV_FSExt_ServerTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Length' => '0', - ),$this->response->headers); + ), $this->response->headers); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status); + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status); $this->assertEquals('', $this->response->body); - $this->assertFalse(file_exists($this->tempDir . '/test.txt')); - + $this->assertFalse(file_exists($this->tempDir.'/test.txt')); } - function testDeleteDirectory() { - + public function testDeleteDirectory() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'DELETE', ); mkdir($this->tempDir.'/testcol'); - file_put_contents($this->tempDir.'/testcol/test.txt','Hi! I\'m a file with a short lifespan'); + file_put_contents($this->tempDir.'/testcol/test.txt', 'Hi! I\'m a file with a short lifespan'); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = ($request); @@ -184,17 +176,16 @@ class Sabre_DAV_FSExt_ServerTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Length' => '0', - ),$this->response->headers); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status); $this->assertEquals('', $this->response->body); - $this->assertFalse(file_exists($this->tempDir . '/col')); - + $this->assertFalse(file_exists($this->tempDir.'/col')); } - function testOptions() { - + public function testOptions() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'OPTIONS', ); @@ -203,17 +194,15 @@ class Sabre_DAV_FSExt_ServerTest extends Sabre_DAV_AbstractServer{ $this->server->exec(); $this->assertEquals(array( - 'DAV' => '1, 3, extended-mkcol', - 'MS-Author-Via' => 'DAV', - 'Allow' => 'OPTIONS, GET, HEAD, DELETE, PROPFIND, PUT, PROPPATCH, COPY, MOVE, REPORT', - 'Accept-Ranges' => 'bytes', + 'DAV' => '1, 3, extended-mkcol', + 'MS-Author-Via' => 'DAV', + 'Allow' => 'OPTIONS, GET, HEAD, DELETE, PROPFIND, PUT, PROPPATCH, COPY, MOVE, REPORT', + 'Accept-Ranges' => 'bytes', 'Content-Length' => '0', - 'X-Sabre-Version'=> Sabre_DAV_Version::VERSION, - ),$this->response->headers); + 'X-Sabre-Version' => Sabre_DAV_Version::VERSION, + ), $this->response->headers); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('', $this->response->body); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Issue33Test.php b/dav/SabreDAV/tests/Sabre/DAV/Issue33Test.php index 1795b5cd..25d00984 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Issue33Test.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Issue33Test.php @@ -2,18 +2,17 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_DAV_Issue33Test extends PHPUnit_Framework_TestCase { - - function setUp() { - +class Sabre_DAV_Issue33Test extends PHPUnit_Framework_TestCase +{ + public function setUp() + { Sabre_TestUtil::clearTempDir(); - } - function testCopyMoveInfo() { - + public function testCopyMoveInfo() + { $foo = new Sabre_DAV_SimpleCollection('foo'); - $root = new Sabre_DAV_SimpleCollection('webdav',array($foo)); + $root = new Sabre_DAV_SimpleCollection('webdav', array($foo)); $tree = new Sabre_DAV_ObjectTree($root); $server = new Sabre_DAV_Server($tree); @@ -34,38 +33,36 @@ class Sabre_DAV_Issue33Test extends PHPUnit_Framework_TestCase { $this->assertEquals('%C3%A0fo%C3%B3', urlencode($info['destination'])); $this->assertFalse($info['destinationExists']); $this->assertFalse($info['destinationNode']); - } - function testTreeMove() { - - mkdir(SABRE_TEMPDIR . '/issue33'); - $dir = new Sabre_DAV_FS_Directory(SABRE_TEMPDIR . '/issue33'); + public function testTreeMove() + { + mkdir(SABRE_TEMPDIR.'/issue33'); + $dir = new Sabre_DAV_FS_Directory(SABRE_TEMPDIR.'/issue33'); $dir->createDirectory('foo'); $tree = new Sabre_DAV_ObjectTree($dir); - $tree->move('foo',urldecode('%C3%A0fo%C3%B3')); + $tree->move('foo', urldecode('%C3%A0fo%C3%B3')); $node = $tree->getNodeForPath(urldecode('%C3%A0fo%C3%B3')); - $this->assertEquals(urldecode('%C3%A0fo%C3%B3'),$node->getName()); - + $this->assertEquals(urldecode('%C3%A0fo%C3%B3'), $node->getName()); } - function testDirName() { - + public function testDirName() + { $dirname1 = 'foo'; - $dirname2 = urlencode('%C3%A0fo%C3%B3');; - - $this->assertTrue(dirname($dirname1)==dirname($dirname2)); + $dirname2 = urlencode('%C3%A0fo%C3%B3'); + $this->assertTrue(dirname($dirname1) == dirname($dirname2)); } /** * @depends testTreeMove * @depends testCopyMoveInfo */ - function testEverything() { + public function testEverything() + { // Request object $serverVars = array( @@ -81,8 +78,8 @@ class Sabre_DAV_Issue33Test extends PHPUnit_Framework_TestCase { $response = new Sabre_HTTP_ResponseMock(); // Server setup - mkdir(SABRE_TEMPDIR . '/issue33'); - $dir = new Sabre_DAV_FS_Directory(SABRE_TEMPDIR . '/issue33'); + mkdir(SABRE_TEMPDIR.'/issue33'); + $dir = new Sabre_DAV_FS_Directory(SABRE_TEMPDIR.'/issue33'); $dir->createDirectory('foo'); @@ -95,8 +92,6 @@ class Sabre_DAV_Issue33Test extends PHPUnit_Framework_TestCase { $server->httpResponse = $response; $server->exec(); - $this->assertTrue(file_exists(SABRE_TEMPDIR . '/issue33/' . urldecode('%C3%A0fo%C3%B3'))); - + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/issue33/'.urldecode('%C3%A0fo%C3%B3'))); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/AbstractTest.php b/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/AbstractTest.php index 3fecac43..88d9908b 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/AbstractTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/AbstractTest.php @@ -1,25 +1,25 @@ getBackend(); - $this->assertInstanceOf('Sabre_DAV_Locks_Backend_Abstract', $backend); + abstract public function getBackend(); + public function testSetup() + { + $backend = $this->getBackend(); + $this->assertInstanceOf('Sabre_DAV_Locks_Backend_Abstract', $backend); } /** * @depends testSetup */ - function testGetLocks() { - + public function testGetLocks() + { $backend = $this->getBackend(); $lock = new Sabre_DAV_Locks_LockInfo(); @@ -27,23 +27,22 @@ abstract class Sabre_DAV_Locks_Backend_AbstractTest extends PHPUnit_Framework_Te $lock->timeout = 60; $lock->created = time(); $lock->token = 'MY-UNIQUE-TOKEN'; - $lock->uri ='someuri'; + $lock->uri = 'someuri'; $this->assertTrue($backend->lock('someuri', $lock)); $locks = $backend->getLocks('someuri', false); - $this->assertEquals(1,count($locks)); - $this->assertEquals('Sinterklaas',$locks[0]->owner); - $this->assertEquals('someuri',$locks[0]->uri); - + $this->assertEquals(1, count($locks)); + $this->assertEquals('Sinterklaas', $locks[0]->owner); + $this->assertEquals('someuri', $locks[0]->uri); } /** * @depends testGetLocks */ - function testGetLocksParent() { - + public function testGetLocksParent() + { $backend = $this->getBackend(); $lock = new Sabre_DAV_Locks_LockInfo(); @@ -57,18 +56,16 @@ abstract class Sabre_DAV_Locks_Backend_AbstractTest extends PHPUnit_Framework_Te $locks = $backend->getLocks('someuri/child', false); - $this->assertEquals(1,count($locks)); - $this->assertEquals('Sinterklaas',$locks[0]->owner); - $this->assertEquals('someuri',$locks[0]->uri); - + $this->assertEquals(1, count($locks)); + $this->assertEquals('Sinterklaas', $locks[0]->owner); + $this->assertEquals('someuri', $locks[0]->uri); } - /** * @depends testGetLocks */ - function testGetLocksParentDepth0() { - + public function testGetLocksParentDepth0() + { $backend = $this->getBackend(); $lock = new Sabre_DAV_Locks_LockInfo(); @@ -82,12 +79,11 @@ abstract class Sabre_DAV_Locks_Backend_AbstractTest extends PHPUnit_Framework_Te $locks = $backend->getLocks('someuri/child', false); - $this->assertEquals(0,count($locks)); - + $this->assertEquals(0, count($locks)); } - function testGetLocksChildren() { - + public function testGetLocksChildren() + { $backend = $this->getBackend(); $lock = new Sabre_DAV_Locks_LockInfo(); @@ -100,21 +96,20 @@ abstract class Sabre_DAV_Locks_Backend_AbstractTest extends PHPUnit_Framework_Te $this->assertTrue($backend->lock('someuri/child', $lock)); $locks = $backend->getLocks('someuri/child', false); - $this->assertEquals(1,count($locks)); + $this->assertEquals(1, count($locks)); $locks = $backend->getLocks('someuri', false); - $this->assertEquals(0,count($locks)); + $this->assertEquals(0, count($locks)); $locks = $backend->getLocks('someuri', true); - $this->assertEquals(1,count($locks)); - + $this->assertEquals(1, count($locks)); } /** * @depends testGetLocks */ - function testLockRefresh() { - + public function testLockRefresh() + { $backend = $this->getBackend(); $lock = new Sabre_DAV_Locks_LockInfo(); @@ -131,18 +126,17 @@ abstract class Sabre_DAV_Locks_Backend_AbstractTest extends PHPUnit_Framework_Te $locks = $backend->getLocks('someuri', false); - $this->assertEquals(1,count($locks)); - - $this->assertEquals('Santa Clause',$locks[0]->owner); - $this->assertEquals('someuri',$locks[0]->uri); + $this->assertEquals(1, count($locks)); + $this->assertEquals('Santa Clause', $locks[0]->owner); + $this->assertEquals('someuri', $locks[0]->uri); } /** * @depends testGetLocks */ - function testUnlock() { - + public function testUnlock() + { $backend = $this->getBackend(); $lock = new Sabre_DAV_Locks_LockInfo(); @@ -154,20 +148,19 @@ abstract class Sabre_DAV_Locks_Backend_AbstractTest extends PHPUnit_Framework_Te $this->assertTrue($backend->lock('someuri', $lock)); $locks = $backend->getLocks('someuri', false); - $this->assertEquals(1,count($locks)); + $this->assertEquals(1, count($locks)); - $this->assertTrue($backend->unlock('someuri',$lock)); + $this->assertTrue($backend->unlock('someuri', $lock)); $locks = $backend->getLocks('someuri', false); - $this->assertEquals(0,count($locks)); - + $this->assertEquals(0, count($locks)); } /** * @depends testUnlock */ - function testUnlockUnknownToken() { - + public function testUnlockUnknownToken() + { $backend = $this->getBackend(); $lock = new Sabre_DAV_Locks_LockInfo(); @@ -179,14 +172,12 @@ abstract class Sabre_DAV_Locks_Backend_AbstractTest extends PHPUnit_Framework_Te $this->assertTrue($backend->lock('someuri', $lock)); $locks = $backend->getLocks('someuri', false); - $this->assertEquals(1,count($locks)); + $this->assertEquals(1, count($locks)); $lock->token = 'SOME-OTHER-TOKEN'; - $this->assertFalse($backend->unlock('someuri',$lock)); + $this->assertFalse($backend->unlock('someuri', $lock)); $locks = $backend->getLocks('someuri', false); - $this->assertEquals(1,count($locks)); - + $this->assertEquals(1, count($locks)); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/FSTest.php b/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/FSTest.php index ddf4f500..70ee655f 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/FSTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/FSTest.php @@ -2,28 +2,26 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_DAV_Locks_Backend_FSTest extends Sabre_DAV_Locks_Backend_AbstractTest { - - function getBackend() { - +class Sabre_DAV_Locks_Backend_FSTest extends Sabre_DAV_Locks_Backend_AbstractTest +{ + public function getBackend() + { Sabre_TestUtil::clearTempDir(); - mkdir(SABRE_TEMPDIR . '/locks'); - $backend = new Sabre_DAV_Locks_Backend_FS(SABRE_TEMPDIR . '/locks/'); + mkdir(SABRE_TEMPDIR.'/locks'); + $backend = new Sabre_DAV_Locks_Backend_FS(SABRE_TEMPDIR.'/locks/'); + return $backend; - } - function tearDown() { - + public function tearDown() + { Sabre_TestUtil::clearTempDir(); - } - function testGetLocksChildren() { + public function testGetLocksChildren() + { // We're skipping this test. This doesn't work, and it will // never. The class is deprecated anyway. - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/FileTest.php b/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/FileTest.php index b482b02f..f61226bf 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/FileTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/FileTest.php @@ -2,21 +2,18 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_DAV_Locks_Backend_FileTest extends Sabre_DAV_Locks_Backend_AbstractTest { - - function getBackend() { - +class Sabre_DAV_Locks_Backend_FileTest extends Sabre_DAV_Locks_Backend_AbstractTest +{ + public function getBackend() + { Sabre_TestUtil::clearTempDir(); - $backend = new Sabre_DAV_Locks_Backend_File(SABRE_TEMPDIR . '/lockdb'); + $backend = new Sabre_DAV_Locks_Backend_File(SABRE_TEMPDIR.'/lockdb'); + return $backend; - } - - function tearDown() { - + public function tearDown() + { Sabre_TestUtil::clearTempDir(); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/PDOMySQLTest.php b/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/PDOMySQLTest.php index 3af17ae7..9f128f80 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/PDOMySQLTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/PDOMySQLTest.php @@ -2,15 +2,19 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_DAV_Locks_Backend_PDOMySQLTest extends Sabre_DAV_Locks_Backend_AbstractTest { - - function getBackend() { - - if (!SABRE_HASMYSQL) $this->markTestSkipped('MySQL driver is not available, or it was not properly configured'); +class Sabre_DAV_Locks_Backend_PDOMySQLTest extends Sabre_DAV_Locks_Backend_AbstractTest +{ + public function getBackend() + { + if (!SABRE_HASMYSQL) { + $this->markTestSkipped('MySQL driver is not available, or it was not properly configured'); + } $pdo = Sabre_TestUtil::getMySQLDB(); - if (!$pdo) $this->markTestSkipped('Could not connect to MySQL database'); + if (!$pdo) { + $this->markTestSkipped('Could not connect to MySQL database'); + } $pdo->query('DROP TABLE IF EXISTS locks;'); - $pdo->query(" + $pdo->query(' CREATE TABLE locks ( id INTEGER UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, owner VARCHAR(100), @@ -20,11 +24,10 @@ CREATE TABLE locks ( scope TINYINT, depth TINYINT, uri text -);"); +);'); $backend = new Sabre_DAV_Locks_Backend_PDO($pdo); + return $backend; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/PDOTest.php b/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/PDOTest.php index 5aebc6b1..3d03aa09 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/PDOTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Locks/Backend/PDOTest.php @@ -3,25 +3,25 @@ require_once 'Sabre/TestUtil.php'; require_once 'Sabre/DAV/Locks/Backend/AbstractTest.php'; -class Sabre_DAV_Locks_Backend_PDOTest extends Sabre_DAV_Locks_Backend_AbstractTest { - - function getBackend() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); +class Sabre_DAV_Locks_Backend_PDOTest extends Sabre_DAV_Locks_Backend_AbstractTest +{ + public function getBackend() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } Sabre_TestUtil::clearTempDir(); - mkdir(SABRE_TEMPDIR . '/pdolocks'); - $pdo = new PDO('sqlite:' . SABRE_TEMPDIR . '/pdolocks/db.sqlite'); - $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); + mkdir(SABRE_TEMPDIR.'/pdolocks'); + $pdo = new PDO('sqlite:'.SABRE_TEMPDIR.'/pdolocks/db.sqlite'); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->query('CREATE TABLE locks ( id integer primary key asc, owner text, timeout text, created integer, token text, scope integer, depth integer, uri text)'); $backend = new Sabre_DAV_Locks_Backend_PDO($pdo); + return $backend; - } - function tearDown() { - + public function tearDown() + { Sabre_TestUtil::clearTempDir(); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Locks/GetIfConditionsTest.php b/dav/SabreDAV/tests/Sabre/DAV/Locks/GetIfConditionsTest.php index a564ddc7..e058d935 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Locks/GetIfConditionsTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Locks/GetIfConditionsTest.php @@ -3,24 +3,23 @@ require_once 'Sabre/HTTP/ResponseMock.php'; require_once 'Sabre/DAV/AbstractServer.php'; -class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { - +class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer +{ /** * @var Sabre_DAV_Locks_Plugin */ protected $locksPlugin; - function setUp() { - + public function setUp() + { parent::setUp(); $locksPlugin = new Sabre_DAV_Locks_Plugin(); $this->server->addPlugin($locksPlugin); $this->locksPlugin = $locksPlugin; - } - function testNoConditions() { - + public function testNoConditions() + { $serverVars = array( ); @@ -28,12 +27,11 @@ class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = ($request); $conditions = $this->locksPlugin->getIfConditions(); - $this->assertEquals(array(),$conditions); - + $this->assertEquals(array(), $conditions); } - function testLockToken() { - + public function testLockToken() + { $serverVars = array( 'HTTP_IF' => '()', ); @@ -59,12 +57,11 @@ class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { ); - $this->assertEquals($compare,$conditions); - + $this->assertEquals($compare, $conditions); } - function testNotLockToken() { - + public function testNotLockToken() + { $serverVars = array( 'HTTP_IF' => '(Not )', ); @@ -89,12 +86,11 @@ class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { ), ); - $this->assertEquals($compare,$conditions); - + $this->assertEquals($compare, $conditions); } - function testLockTokenUrl() { - + public function testLockTokenUrl() + { $serverVars = array( 'HTTP_IF' => ' ()', ); @@ -119,12 +115,11 @@ class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { ), ); - $this->assertEquals($compare,$conditions); - + $this->assertEquals($compare, $conditions); } - function test2LockTokens() { - + public function test2LockTokens() + { $serverVars = array( 'HTTP_IF' => '() (Not )', ); @@ -154,12 +149,11 @@ class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { ), ); - $this->assertEquals($compare,$conditions); - + $this->assertEquals($compare, $conditions); } - function test2UriLockTokens() { - + public function test2UriLockTokens() + { $serverVars = array( 'HTTP_IF' => ' () (Not )', ); @@ -194,12 +188,11 @@ class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { ), ); - $this->assertEquals($compare,$conditions); - + $this->assertEquals($compare, $conditions); } - function test2UriMultiLockTokens() { - + public function test2UriMultiLockTokens() + { $serverVars = array( 'HTTP_IF' => ' () () (Not )', ); @@ -239,12 +232,11 @@ class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { ), ); - $this->assertEquals($compare,$conditions); - + $this->assertEquals($compare, $conditions); } - function testEtag() { - + public function testEtag() + { $serverVars = array( 'HTTP_IF' => '([etag1])', ); @@ -268,12 +260,11 @@ class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { ), ); - $this->assertEquals($compare,$conditions); - + $this->assertEquals($compare, $conditions); } - function test2Etags() { - + public function test2Etags() + { $serverVars = array( 'HTTP_IF' => ' ([etag1]) ([etag2])', ); @@ -302,15 +293,14 @@ class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { ), ); - $this->assertEquals($compare,$conditions); - + $this->assertEquals($compare, $conditions); } - function testComplexIf() { - + public function testComplexIf() + { $serverVars = array( - 'HTTP_IF' => ' ( [etag1]) ' . - '(Not ) ([etag2]) ' . + 'HTTP_IF' => ' ( [etag1]) '. + '(Not ) ([etag2]) '. '() (Not ) ([etag3])', ); @@ -363,8 +353,6 @@ class Sabre_DAV_Locks_GetIfConditionsTest extends Sabre_DAV_AbstractServer { ), ); - $this->assertEquals($compare,$conditions); - + $this->assertEquals($compare, $conditions); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Locks/MSWordTest.php b/dav/SabreDAV/tests/Sabre/DAV/Locks/MSWordTest.php index 63e8a0b4..cb766517 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Locks/MSWordTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Locks/MSWordTest.php @@ -3,16 +3,16 @@ require_once 'Sabre/HTTP/ResponseMock.php'; require_once 'Sabre/TestUtil.php'; -class Sabre_DAV_Locks_MSWordTest extends PHPUnit_Framework_TestCase { - - function testLockEtc() { - - mkdir(SABRE_TEMPDIR . '/mstest'); - $tree = new Sabre_DAV_FS_Directory(SABRE_TEMPDIR . '/mstest'); +class Sabre_DAV_Locks_MSWordTest extends PHPUnit_Framework_TestCase +{ + public function testLockEtc() + { + mkdir(SABRE_TEMPDIR.'/mstest'); + $tree = new Sabre_DAV_FS_Directory(SABRE_TEMPDIR.'/mstest'); $server = new Sabre_DAV_Server($tree); $server->debugExceptions = true; - $locksBackend = new Sabre_DAV_Locks_Backend_File(SABRE_TEMPDIR . '/locksdb'); + $locksBackend = new Sabre_DAV_Locks_Backend_File(SABRE_TEMPDIR.'/locksdb'); $locksPlugin = new Sabre_DAV_Locks_Plugin($locksBackend); $server->addPlugin($locksPlugin); @@ -45,22 +45,20 @@ class Sabre_DAV_Locks_MSWordTest extends PHPUnit_Framework_TestCase { $server->exec(); $this->assertEquals('HTTP/1.1 204 No Content', $server->httpResponse->status); - } - function tearDown() { - + public function tearDown() + { Sabre_TestUtil::clearTempDir(); - } - function getLockRequest() { - + public function getLockRequest() + { $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'LOCK', + 'REQUEST_METHOD' => 'LOCK', 'HTTP_CONTENT_TYPE' => 'application/xml', - 'HTTP_TIMEOUT' => 'Second-3600', - 'REQUEST_URI' => '/Nouveau%20Microsoft%20Office%20Excel%20Worksheet.xlsx', + 'HTTP_TIMEOUT' => 'Second-3600', + 'REQUEST_URI' => '/Nouveau%20Microsoft%20Office%20Excel%20Worksheet.xlsx', )); $request->setBody(' @@ -76,15 +74,14 @@ class Sabre_DAV_Locks_MSWordTest extends PHPUnit_Framework_TestCase { '); return $request; - } - function getLockRequest2() { - + public function getLockRequest2() + { $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'LOCK', + 'REQUEST_METHOD' => 'LOCK', 'HTTP_CONTENT_TYPE' => 'application/xml', - 'HTTP_TIMEOUT' => 'Second-3600', - 'REQUEST_URI' => '/~$Nouveau%20Microsoft%20Office%20Excel%20Worksheet.xlsx', + 'HTTP_TIMEOUT' => 'Second-3600', + 'REQUEST_URI' => '/~$Nouveau%20Microsoft%20Office%20Excel%20Worksheet.xlsx', )); $request->setBody(' @@ -100,19 +97,17 @@ class Sabre_DAV_Locks_MSWordTest extends PHPUnit_Framework_TestCase { '); return $request; - } - function getPutRequest($lockToken) { - + public function getPutRequest($lockToken) + { $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'PUT', - 'REQUEST_URI' => '/Nouveau%20Microsoft%20Office%20Excel%20Worksheet.xlsx', - 'HTTP_IF' => 'If: ('.$lockToken.')', + 'REQUEST_METHOD' => 'PUT', + 'REQUEST_URI' => '/Nouveau%20Microsoft%20Office%20Excel%20Worksheet.xlsx', + 'HTTP_IF' => 'If: ('.$lockToken.')', )); $request->setBody('FAKE BODY'); + return $request; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Locks/PluginTest.php b/dav/SabreDAV/tests/Sabre/DAV/Locks/PluginTest.php index 0ce0eb3a..e0a06264 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Locks/PluginTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Locks/PluginTest.php @@ -2,53 +2,48 @@ require_once 'Sabre/DAV/AbstractServer.php'; -class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { - +class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer +{ /** * @var Sabre_DAV_Locks_Plugin */ protected $locksPlugin; - function setUp() { - + public function setUp() + { parent::setUp(); - $locksBackend = new Sabre_DAV_Locks_Backend_File(SABRE_TEMPDIR . '/locksdb'); + $locksBackend = new Sabre_DAV_Locks_Backend_File(SABRE_TEMPDIR.'/locksdb'); $locksPlugin = new Sabre_DAV_Locks_Plugin($locksBackend); $this->server->addPlugin($locksPlugin); $this->locksPlugin = $locksPlugin; - } - function testGetFeatures() { - - $this->assertEquals(array(2),$this->locksPlugin->getFeatures()); - + public function testGetFeatures() + { + $this->assertEquals(array(2), $this->locksPlugin->getFeatures()); } - function testGetHTTPMethods() { - - $this->assertEquals(array('LOCK','UNLOCK'),$this->locksPlugin->getHTTPMethods('')); - + public function testGetHTTPMethods() + { + $this->assertEquals(array('LOCK', 'UNLOCK'), $this->locksPlugin->getHTTPMethods('')); } - function testGetHTTPMethodsNoBackend() { - + public function testGetHTTPMethodsNoBackend() + { $locksPlugin = new Sabre_DAV_Locks_Plugin(); $this->server->addPlugin($locksPlugin); - $this->assertEquals(array(),$locksPlugin->getHTTPMethods('')); - + $this->assertEquals(array(), $locksPlugin->getHTTPMethods('')); } - function testUnknownMethodPassthough() { - - $this->assertNull($this->locksPlugin->unknownMethod('BLA','/')); - + public function testUnknownMethodPassthough() + { + $this->assertNull($this->locksPlugin->unknownMethod('BLA', '/')); } - function testLockNoBody() { - + public function testLockNoBody() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -63,14 +58,13 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->response->headers ); - $this->assertEquals('HTTP/1.1 400 Bad request',$this->response->status); - + $this->assertEquals('HTTP/1.1 400 Bad request', $this->response->status); } - function testLock() { - + public function testLock() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -87,14 +81,14 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status,'Got an incorrect status back. Response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status, 'Got an incorrect status back. Response body: '.$this->response->body); - $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/","xmlns\\1=\"DAV:\"",$this->response->body); + $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/", 'xmlns\\1="DAV:"', $this->response->body); $xml = simplexml_load_string($body); - $xml->registerXPathNamespace('d','DAV:'); + $xml->registerXPathNamespace('d', 'DAV:'); $elements = array( '/d:prop', @@ -113,26 +107,25 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { '/d:prop/d:lockdiscovery/d:activelock/d:locktoken/d:href', ); - foreach($elements as $elem) { + foreach ($elements as $elem) { $data = $xml->xpath($elem); - $this->assertEquals(1,count($data),'We expected 1 match for the xpath expression "' . $elem . '". ' . count($data) . ' were found. Full response body: ' . $this->response->body); + $this->assertEquals(1, count($data), 'We expected 1 match for the xpath expression "'.$elem.'". '.count($data).' were found. Full response body: '.$this->response->body); } $depth = $xml->xpath('/d:prop/d:lockdiscovery/d:activelock/d:depth'); - $this->assertEquals('infinity',(string)$depth[0]); + $this->assertEquals('infinity', (string) $depth[0]); $token = $xml->xpath('/d:prop/d:lockdiscovery/d:activelock/d:locktoken/d:href'); - $this->assertEquals($this->response->headers['Lock-Token'],'<' . (string)$token[0] . '>','Token in response body didn\'t match token in response header.'); - + $this->assertEquals($this->response->headers['Lock-Token'], '<'.(string) $token[0].'>', 'Token in response body didn\'t match token in response header.'); } /** * @depends testLock */ - function testDoubleLock() { - + public function testDoubleLock() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -154,19 +147,18 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - - $this->assertEquals('HTTP/1.1 423 Locked',$this->response->status); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertEquals('HTTP/1.1 423 Locked', $this->response->status); } /** * @depends testLock */ - function testLockRefresh() { - + public function testLockRefresh() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -191,7 +183,7 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $serverVars = array( 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'LOCK', - 'HTTP_IF' => '(' . $lockToken . ')', + 'HTTP_IF' => '('.$lockToken.')', ); $request = new Sabre_HTTP_Request($serverVars); $request->setBody(''); @@ -199,19 +191,18 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status,'We received an incorrect status code. Full response body: ' . $this->response->body); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status, 'We received an incorrect status code. Full response body: '.$this->response->body); } /** * @depends testLock */ - function testLockNoFile() { - + public function testLockNoFile() + { $serverVars = array( - 'REQUEST_URI' => '/notfound.txt', + 'REQUEST_URI' => '/notfound.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -228,20 +219,19 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); - - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); } /** * @depends testLock */ - function testUnlockNoToken() { - + public function testUnlockNoToken() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'UNLOCK', ); @@ -255,18 +245,17 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->response->headers ); - $this->assertEquals('HTTP/1.1 400 Bad request',$this->response->status); - + $this->assertEquals('HTTP/1.1 400 Bad request', $this->response->status); } /** * @depends testLock */ - function testUnlockBadToken() { - + public function testUnlockBadToken() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', - 'REQUEST_METHOD' => 'UNLOCK', + 'REQUEST_URI' => '/test.txt', + 'REQUEST_METHOD' => 'UNLOCK', 'HTTP_LOCK_TOKEN' => '', ); @@ -280,17 +269,16 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->response->headers ); - $this->assertEquals('HTTP/1.1 409 Conflict',$this->response->status,'Got an incorrect status code. Full response body: ' . $this->response->body); - + $this->assertEquals('HTTP/1.1 409 Conflict', $this->response->status, 'Got an incorrect status code. Full response body: '.$this->response->body); } /** * @depends testLock */ - function testLockPutNoToken() { - + public function testLockPutNoToken() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -307,13 +295,13 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'PUT', ); @@ -322,18 +310,17 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); - - $this->assertEquals('HTTP/1.1 423 Locked',$this->response->status); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); + $this->assertEquals('HTTP/1.1 423 Locked', $this->response->status); } /** * @depends testLock */ - function testUnlock() { - + public function testUnlock() + { $request = new Sabre_HTTP_Request(array()); $this->server->httpRequest = $request; @@ -346,7 +333,7 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { '); - $this->server->invokeMethod('LOCK','test.txt'); + $this->server->invokeMethod('LOCK', 'test.txt'); $lockToken = $this->server->httpResponse->headers['Lock-Token']; $serverVars = array( @@ -358,21 +345,19 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpResponse = new Sabre_HTTP_ResponseMock(); $this->server->invokeMethod('UNLOCK', 'test.txt'); - $this->assertEquals('HTTP/1.1 204 No Content',$this->server->httpResponse->status,'Got an incorrect status code. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 204 No Content', $this->server->httpResponse->status, 'Got an incorrect status code. Full response body: '.$this->response->body); $this->assertEquals(array( 'Content-Length' => '0', ), $this->server->httpResponse->headers ); - - } /** * @depends testLock */ - function testUnlockWindowsBug() { - + public function testUnlockWindowsBug() + { $request = new Sabre_HTTP_Request(array()); $this->server->httpRequest = $request; @@ -385,11 +370,11 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { '); - $this->server->invokeMethod('LOCK','test.txt'); + $this->server->invokeMethod('LOCK', 'test.txt'); $lockToken = $this->server->httpResponse->headers['Lock-Token']; // See Issue 123 - $lockToken = trim($lockToken,'<>'); + $lockToken = trim($lockToken, '<>'); $serverVars = array( 'HTTP_LOCK_TOKEN' => $lockToken, @@ -400,21 +385,19 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpResponse = new Sabre_HTTP_ResponseMock(); $this->server->invokeMethod('UNLOCK', 'test.txt'); - $this->assertEquals('HTTP/1.1 204 No Content',$this->server->httpResponse->status,'Got an incorrect status code. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 204 No Content', $this->server->httpResponse->status, 'Got an incorrect status code. Full response body: '.$this->response->body); $this->assertEquals(array( 'Content-Length' => '0', ), $this->server->httpResponse->headers ); - - } /** * @depends testLock */ - function testLockRetainOwner() { - + public function testLockRetainOwner() + { $request = new Sabre_HTTP_Request(array()); $this->server->httpRequest = $request; @@ -425,23 +408,21 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { Evert '); - $this->server->invokeMethod('LOCK','test.txt'); + $this->server->invokeMethod('LOCK', 'test.txt'); $lockToken = $this->server->httpResponse->headers['Lock-Token']; $locks = $this->locksPlugin->getLocks('test.txt'); - $this->assertEquals(1,count($locks)); - $this->assertEquals('Evert',$locks[0]->owner); - - + $this->assertEquals(1, count($locks)); + $this->assertEquals('Evert', $locks[0]->owner); } /** * @depends testLock */ - function testLockPutBadToken() { - + public function testLockPutBadToken() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -458,13 +439,13 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'PUT', 'HTTP_IF' => '()', ); @@ -474,20 +455,19 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); - - $this->assertEquals('HTTP/1.1 412 Precondition failed',$this->response->status); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); + $this->assertEquals('HTTP/1.1 412 Precondition failed', $this->response->status); } /** * @depends testLock */ - function testLockDeleteParent() { - + public function testLockDeleteParent() + { $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -504,13 +484,13 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/dir', + 'REQUEST_URI' => '/dir', 'REQUEST_METHOD' => 'DELETE', ); @@ -518,17 +498,16 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 423 Locked',$this->response->status); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - + $this->assertEquals('HTTP/1.1 423 Locked', $this->response->status); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); } /** * @depends testLock */ - function testLockDeleteSucceed() { - + public function testLockDeleteSucceed() + { $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -545,33 +524,32 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'DELETE', - 'HTTP_IF' => '(' . $this->response->headers['Lock-Token'] . ')', + 'HTTP_IF' => '('.$this->response->headers['Lock-Token'].')', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); } /** * @depends testLock */ - function testLockCopyLockSource() { - + public function testLockCopyLockSource() + { $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -588,13 +566,13 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'COPY', 'HTTP_DESTINATION' => '/dir/child2.txt', ); @@ -603,17 +581,16 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status,'Copy must succeed if only the source is locked, but not the destination'); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status, 'Copy must succeed if only the source is locked, but not the destination'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); } /** * @depends testLock */ - function testLockCopyLockDestination() { - + public function testLockCopyLockDestination() + { $serverVars = array( - 'REQUEST_URI' => '/dir/child2.txt', + 'REQUEST_URI' => '/dir/child2.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -630,13 +607,13 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'COPY', 'HTTP_DESTINATION' => '/dir/child2.txt', ); @@ -645,18 +622,17 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 423 Locked',$this->response->status,'Copy must succeed if only the source is locked, but not the destination'); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - + $this->assertEquals('HTTP/1.1 423 Locked', $this->response->status, 'Copy must succeed if only the source is locked, but not the destination'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); } /** * @depends testLock */ - function testLockMoveLockSourceLocked() { - + public function testLockMoveLockSourceLocked() + { $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -673,13 +649,13 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'MOVE', 'HTTP_DESTINATION' => '/dir/child2.txt', ); @@ -688,18 +664,17 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 423 Locked',$this->response->status,'Copy must succeed if only the source is locked, but not the destination'); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - + $this->assertEquals('HTTP/1.1 423 Locked', $this->response->status, 'Copy must succeed if only the source is locked, but not the destination'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); } /** * @depends testLock */ - function testLockMoveLockSourceSucceed() { - + public function testLockMoveLockSourceSucceed() + { $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -716,33 +691,32 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'MOVE', 'HTTP_DESTINATION' => '/dir/child2.txt', - 'HTTP_IF' => '(' . $this->response->headers['Lock-Token'] . ')', + 'HTTP_IF' => '('.$this->response->headers['Lock-Token'].')', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status,'A valid lock-token was provided for the source, so this MOVE operation must succeed. Full response body: ' . $this->response->body); - + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status, 'A valid lock-token was provided for the source, so this MOVE operation must succeed. Full response body: '.$this->response->body); } /** * @depends testLock */ - function testLockMoveLockDestination() { - + public function testLockMoveLockDestination() + { $serverVars = array( - 'REQUEST_URI' => '/dir/child2.txt', + 'REQUEST_URI' => '/dir/child2.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -759,13 +733,13 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'MOVE', 'HTTP_DESTINATION' => '/dir/child2.txt', ); @@ -774,17 +748,16 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 423 Locked',$this->response->status,'Copy must succeed if only the source is locked, but not the destination'); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - + $this->assertEquals('HTTP/1.1 423 Locked', $this->response->status, 'Copy must succeed if only the source is locked, but not the destination'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); } /** * @depends testLock */ - function testLockMoveLockParent() { - + public function testLockMoveLockParent() + { $serverVars = array( - 'REQUEST_URI' => '/dir', + 'REQUEST_URI' => '/dir', 'REQUEST_METHOD' => 'LOCK', 'HTTP_DEPTH' => 'infinite', ); @@ -802,34 +775,33 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/dir/child.txt', + 'REQUEST_URI' => '/dir/child.txt', 'REQUEST_METHOD' => 'MOVE', 'HTTP_DESTINATION' => '/dir/child2.txt', - 'HTTP_IF' => ' (' . $this->response->headers['Lock-Token'] . ')', + 'HTTP_IF' => ' ('.$this->response->headers['Lock-Token'].')', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status,'We locked the parent of both the source and destination, but the move didn\'t succeed.'); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status, 'We locked the parent of both the source and destination, but the move didn\'t succeed.'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); } /** * @depends testLock */ - function testLockPutGoodToken() { - + public function testLockPutGoodToken() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -846,13 +818,13 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'PUT', 'HTTP_IF' => '('.$this->response->headers['Lock-Token'].')', ); @@ -862,17 +834,16 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); - - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status); } - function testPutWithIncorrectETag() { - + public function testPutWithIncorrectETag() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'PUT', 'HTTP_IF' => '(["etag1"])', ); @@ -881,22 +852,22 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $request->setBody('newbody'); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 412 Precondition failed',$this->response->status); - + $this->assertEquals('HTTP/1.1 412 Precondition failed', $this->response->status); } /** * @depends testPutWithIncorrectETag */ - function testPutWithCorrectETag() { + public function testPutWithCorrectETag() + { // We need an etag-enabled file node. $tree = new Sabre_DAV_ObjectTree(new Sabre_DAV_FSExt_Directory(SABRE_TEMPDIR)); $this->server->tree = $tree; - $etag = md5(file_get_contents(SABRE_TEMPDIR . '/test.txt')); + $etag = md5(file_get_contents(SABRE_TEMPDIR.'/test.txt')); $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'PUT', 'HTTP_IF' => '(["'.$etag.'"])', ); @@ -905,57 +876,48 @@ class Sabre_DAV_Locks_PluginTest extends Sabre_DAV_AbstractServer { $request->setBody('newbody'); $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status, 'Incorrect status received. Full response body:' . $this->response->body); - + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status, 'Incorrect status received. Full response body:'.$this->response->body); } - function testGetTimeoutHeader() { - + public function testGetTimeoutHeader() + { $request = new Sabre_HTTP_Request(array( 'HTTP_TIMEOUT' => 'second-100', )); $this->server->httpRequest = $request; $this->assertEquals(100, $this->locksPlugin->getTimeoutHeader()); - } - - function testGetTimeoutHeaderNotSet() { - + public function testGetTimeoutHeaderNotSet() + { $request = new Sabre_HTTP_Request(array( )); $this->server->httpRequest = $request; $this->assertEquals(0, $this->locksPlugin->getTimeoutHeader()); - } - - function testGetTimeoutHeaderInfinite() { - + public function testGetTimeoutHeaderInfinite() + { $request = new Sabre_HTTP_Request(array( 'HTTP_TIMEOUT' => 'infinite', )); $this->server->httpRequest = $request; $this->assertEquals(Sabre_DAV_Locks_LockInfo::TIMEOUT_INFINITE, $this->locksPlugin->getTimeoutHeader()); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testGetTimeoutHeaderInvalid() { - + public function testGetTimeoutHeaderInvalid() + { $request = new Sabre_HTTP_Request(array( 'HTTP_TIMEOUT' => 'yourmom', )); $this->server->httpRequest = $request; $this->locksPlugin->getTimeoutHeader(); - } - - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Mount/PluginTest.php b/dav/SabreDAV/tests/Sabre/DAV/Mount/PluginTest.php index 21f31089..98aa6ad2 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Mount/PluginTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Mount/PluginTest.php @@ -2,19 +2,18 @@ require_once 'Sabre/DAV/AbstractServer.php'; -class Sabre_DAV_Mount_PluginTest extends Sabre_DAV_AbstractServer { - - function setUp() { - +class Sabre_DAV_Mount_PluginTest extends Sabre_DAV_AbstractServer +{ + public function setUp() + { parent::setUp(); $this->server->addPlugin(new Sabre_DAV_Mount_Plugin()); - } - function testPassThrough() { - + public function testPassThrough() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'GET', ); @@ -22,32 +21,29 @@ class Sabre_DAV_Mount_PluginTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 501 Not Implemented',$this->response->status,'We expected GET to not be implemented for Directories. Response body: ' . $this->response->body); - + $this->assertEquals('HTTP/1.1 501 Not Implemented', $this->response->status, 'We expected GET to not be implemented for Directories. Response body: '.$this->response->body); } - function testMountResponse() { - + public function testMountResponse() + { $serverVars = array( - 'REQUEST_URI' => '/?mount', + 'REQUEST_URI' => '/?mount', 'REQUEST_METHOD' => 'GET', - 'QUERY_STRING' => 'mount', - 'HTTP_HOST' => 'example.org', + 'QUERY_STRING' => 'mount', + 'HTTP_HOST' => 'example.org', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $xml = simplexml_load_string($this->response->body); - $this->assertTrue($xml==true,'Response was not a valid xml document'); + $this->assertTrue($xml == true, 'Response was not a valid xml document'); - $xml->registerXPathNamespace('dm','http://purl.org/NET/webdav/mount'); + $xml->registerXPathNamespace('dm', 'http://purl.org/NET/webdav/mount'); $url = $xml->xpath('//dm:url'); - $this->assertEquals('http://example.org/',(string)$url[0]); - + $this->assertEquals('http://example.org/', (string) $url[0]); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ObjectTreeTest.php b/dav/SabreDAV/tests/Sabre/DAV/ObjectTreeTest.php index 9059cefb..02d8ba76 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ObjectTreeTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ObjectTreeTest.php @@ -2,97 +2,87 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_DAV_ObjectTreeTest extends PHPUnit_Framework_TestCase { - +class Sabre_DAV_ObjectTreeTest extends PHPUnit_Framework_TestCase +{ protected $tree; - function setup() { - + public function setup() + { Sabre_TestUtil::clearTempDir(); - mkdir(SABRE_TEMPDIR . '/root'); - mkdir(SABRE_TEMPDIR . '/root/subdir'); - file_put_contents(SABRE_TEMPDIR . '/root/file.txt','contents'); - file_put_contents(SABRE_TEMPDIR . '/root/subdir/subfile.txt','subcontents'); - $rootNode = new Sabre_DAV_FSExt_Directory(SABRE_TEMPDIR . '/root'); + mkdir(SABRE_TEMPDIR.'/root'); + mkdir(SABRE_TEMPDIR.'/root/subdir'); + file_put_contents(SABRE_TEMPDIR.'/root/file.txt', 'contents'); + file_put_contents(SABRE_TEMPDIR.'/root/subdir/subfile.txt', 'subcontents'); + $rootNode = new Sabre_DAV_FSExt_Directory(SABRE_TEMPDIR.'/root'); $this->tree = new Sabre_DAV_ObjectTree($rootNode); - } - function teardown() { - + public function teardown() + { Sabre_TestUtil::clearTempDir(); - } - function testGetRootNode() { - + public function testGetRootNode() + { $root = $this->tree->getNodeForPath(''); - $this->assertInstanceOf('Sabre_DAV_FSExt_Directory',$root); - + $this->assertInstanceOf('Sabre_DAV_FSExt_Directory', $root); } - function testGetSubDir() { - + public function testGetSubDir() + { $root = $this->tree->getNodeForPath('subdir'); - $this->assertInstanceOf('Sabre_DAV_FSExt_Directory',$root); - + $this->assertInstanceOf('Sabre_DAV_FSExt_Directory', $root); } - function testCopyFile() { - - $this->tree->copy('file.txt','file2.txt'); - $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/file2.txt')); - $this->assertEquals('contents',file_get_contents(SABRE_TEMPDIR.'/root/file2.txt')); - + public function testCopyFile() + { + $this->tree->copy('file.txt', 'file2.txt'); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/file2.txt')); + $this->assertEquals('contents', file_get_contents(SABRE_TEMPDIR.'/root/file2.txt')); } /** * @depends testCopyFile */ - function testCopyDirectory() { - - $this->tree->copy('subdir','subdir2'); - $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/subdir2')); - $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/subdir2/subfile.txt')); - $this->assertEquals('subcontents',file_get_contents(SABRE_TEMPDIR.'/root/subdir2/subfile.txt')); - + public function testCopyDirectory() + { + $this->tree->copy('subdir', 'subdir2'); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/subdir2')); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/subdir2/subfile.txt')); + $this->assertEquals('subcontents', file_get_contents(SABRE_TEMPDIR.'/root/subdir2/subfile.txt')); } /** * @depends testCopyFile */ - function testMoveFile() { - - $this->tree->move('file.txt','file2.txt'); - $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/file2.txt')); - $this->assertFalse(file_exists(SABRE_TEMPDIR.'/root/file.txt')); - $this->assertEquals('contents',file_get_contents(SABRE_TEMPDIR.'/root/file2.txt')); - + public function testMoveFile() + { + $this->tree->move('file.txt', 'file2.txt'); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/file2.txt')); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/root/file.txt')); + $this->assertEquals('contents', file_get_contents(SABRE_TEMPDIR.'/root/file2.txt')); } /** * @depends testMoveFile */ - function testMoveFileNewParent() { - - $this->tree->move('file.txt','subdir/file2.txt'); - $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/subdir/file2.txt')); - $this->assertFalse(file_exists(SABRE_TEMPDIR.'/root/file.txt')); - $this->assertEquals('contents',file_get_contents(SABRE_TEMPDIR.'/root/subdir/file2.txt')); - + public function testMoveFileNewParent() + { + $this->tree->move('file.txt', 'subdir/file2.txt'); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/subdir/file2.txt')); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/root/file.txt')); + $this->assertEquals('contents', file_get_contents(SABRE_TEMPDIR.'/root/subdir/file2.txt')); } /** * @depends testCopyDirectory */ - function testMoveDirectory() { - - $this->tree->move('subdir','subdir2'); - $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/subdir2')); - $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/subdir2/subfile.txt')); - $this->assertFalse(file_exists(SABRE_TEMPDIR.'/root/subdir')); - $this->assertEquals('subcontents',file_get_contents(SABRE_TEMPDIR.'/root/subdir2/subfile.txt')); - + public function testMoveDirectory() + { + $this->tree->move('subdir', 'subdir2'); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/subdir2')); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/root/subdir2/subfile.txt')); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/root/subdir')); + $this->assertEquals('subcontents', file_get_contents(SABRE_TEMPDIR.'/root/subdir2/subfile.txt')); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/PartialUpdate/FileMock.php b/dav/SabreDAV/tests/Sabre/DAV/PartialUpdate/FileMock.php index 17c52e38..f5e7b30e 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/PartialUpdate/FileMock.php +++ b/dav/SabreDAV/tests/Sabre/DAV/PartialUpdate/FileMock.php @@ -1,76 +1,62 @@ data = $str; - } - function putRange($str,$start) { - + public function putRange($str, $start) + { if (is_resource($str)) { $str = stream_get_contents($str); } - $this->data = substr($this->data, 0, $start) . $str . substr($this->data, $start + strlen($str)); - - - + $this->data = substr($this->data, 0, $start).$str.substr($this->data, $start + strlen($str)); } - function get() { - + public function get() + { return $this->data; - } - function getContentType() { - + public function getContentType() + { return 'text/plain'; - } - function getSize() { - + public function getSize() + { return strlen($this->data); - } - function getETag() { - - return '"' . $this->data . '"'; - + public function getETag() + { + return '"'.$this->data.'"'; } - function delete() { - + public function delete() + { throw new Sabre_DAV_Exception_MethodNotAllowed(); - } - function setName($name) { - + public function setName($name) + { throw new Sabre_DAV_Exception_MethodNotAllowed(); - } - function getName() { - + public function getName() + { return 'partial'; - } - function getLastModified() { - + public function getLastModified() + { return null; - } - - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/PartialUpdate/PluginTest.php b/dav/SabreDAV/tests/Sabre/DAV/PartialUpdate/PluginTest.php index 6555f50f..a626dcc8 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/PartialUpdate/PluginTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/PartialUpdate/PluginTest.php @@ -2,13 +2,13 @@ require_once 'Sabre/DAV/PartialUpdate/FileMock.php'; -class Sabre_DAV_PartialUpdate_PluginTest extends Sabre_DAVServerTest { - +class Sabre_DAV_PartialUpdate_PluginTest extends Sabre_DAVServerTest +{ protected $node; protected $plugin; - public function setUp() { - + public function setUp() + { $this->node = new Sabre_DAV_PartialUpdate_FileMock(); $this->tree[] = $this->node; @@ -16,44 +16,39 @@ class Sabre_DAV_PartialUpdate_PluginTest extends Sabre_DAVServerTest { $this->plugin = new Sabre_DAV_PartialUpdate_Plugin(); $this->server->addPlugin($this->plugin); - - - } - public function testInit() { - + public function testInit() + { $this->assertEquals('partialupdate', $this->plugin->getPluginName()); $this->assertEquals(array('sabredav-partialupdate'), $this->plugin->getFeatures()); $this->assertEquals(array( - 'PATCH' + 'PATCH', ), $this->plugin->getHTTPMethods('partial')); $this->assertEquals(array( ), $this->plugin->getHTTPMethods('')); - $this->assertNull($this->plugin->unknownMethod('FOO','partial')); - + $this->assertNull($this->plugin->unknownMethod('FOO', 'partial')); } - public function testPatchNoRange() { - + public function testPatchNoRange() + { $this->node->put('00000000'); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PATCH', - 'REQUEST_URI' => '/partial', + 'REQUEST_URI' => '/partial', )); $response = $this->request($request); - $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Full response body:' . $response->body); - + $this->assertEquals('HTTP/1.1 400 Bad request', $response->status, 'Full response body:'.$response->body); } - public function testPatchNotSupported() { - + public function testPatchNotSupported() + { $this->node->put('00000000'); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'PATCH', - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'X_UPDATE_RANGE' => '3-4', )); @@ -62,16 +57,15 @@ class Sabre_DAV_PartialUpdate_PluginTest extends Sabre_DAVServerTest { ); $response = $this->request($request); - $this->assertEquals('HTTP/1.1 405 Method Not Allowed', $response->status, 'Full response body:' . $response->body); - + $this->assertEquals('HTTP/1.1 405 Method Not Allowed', $response->status, 'Full response body:'.$response->body); } - public function testPatchNoContentType() { - + public function testPatchNoContentType() + { $this->node->put('00000000'); $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'PATCH', - 'REQUEST_URI' => '/partial', + 'REQUEST_METHOD' => 'PATCH', + 'REQUEST_URI' => '/partial', 'HTTP_X_UPDATE_RANGE' => 'bytes=3-4', )); @@ -80,36 +74,34 @@ class Sabre_DAV_PartialUpdate_PluginTest extends Sabre_DAVServerTest { ); $response = $this->request($request); - $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $response->status, 'Full response body:' . $response->body); - + $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $response->status, 'Full response body:'.$response->body); } - public function testPatchBadRange() { - + public function testPatchBadRange() + { $this->node->put('00000000'); $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'PATCH', - 'REQUEST_URI' => '/partial', + 'REQUEST_METHOD' => 'PATCH', + 'REQUEST_URI' => '/partial', 'HTTP_X_UPDATE_RANGE' => 'bytes=3-4', - 'HTTP_CONTENT_TYPE' => 'application/x-sabredav-partialupdate', + 'HTTP_CONTENT_TYPE' => 'application/x-sabredav-partialupdate', )); $request->setBody( '111' ); $response = $this->request($request); - $this->assertEquals('HTTP/1.1 416 Requested Range Not Satisfiable', $response->status, 'Full response body:' . $response->body); - + $this->assertEquals('HTTP/1.1 416 Requested Range Not Satisfiable', $response->status, 'Full response body:'.$response->body); } - public function testPatchSuccess() { - + public function testPatchSuccess() + { $this->node->put('00000000'); $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'PATCH', - 'REQUEST_URI' => '/partial', + 'REQUEST_METHOD' => 'PATCH', + 'REQUEST_URI' => '/partial', 'HTTP_X_UPDATE_RANGE' => 'bytes=3-5', - 'HTTP_CONTENT_TYPE' => 'application/x-sabredav-partialupdate', + 'HTTP_CONTENT_TYPE' => 'application/x-sabredav-partialupdate', 'HTTP_CONTENT_LENGTH' => 3, )); $request->setBody( @@ -117,9 +109,7 @@ class Sabre_DAV_PartialUpdate_PluginTest extends Sabre_DAVServerTest { ); $response = $this->request($request); - $this->assertEquals('HTTP/1.1 204 No Content', $response->status, 'Full response body:' . $response->body); + $this->assertEquals('HTTP/1.1 204 No Content', $response->status, 'Full response body:'.$response->body); $this->assertEquals('00111000', $this->node->get()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Property/GetLastModifiedTest.php b/dav/SabreDAV/tests/Sabre/DAV/Property/GetLastModifiedTest.php index 4c493cf8..8e97db39 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Property/GetLastModifiedTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Property/GetLastModifiedTest.php @@ -1,39 +1,36 @@ assertEquals($dt->format(DateTime::ATOM), $lastMod->getTime()->format(DateTime::ATOM)); - } - function testConstructString() { - + public function testConstructString() + { $dt = new DateTime('2010-03-14 16:35', new DateTimeZone('UTC')); $lastMod = new Sabre_DAV_Property_GetLastModified('2010-03-14 16:35'); $this->assertEquals($dt->format(DateTime::ATOM), $lastMod->getTime()->format(DateTime::ATOM)); - } - function testConstructInt() { - + public function testConstructInt() + { $dt = new DateTime('2010-03-14 16:35', new DateTimeZone('UTC')); - $lastMod = new Sabre_DAV_Property_GetLastModified((int)$dt->format('U')); + $lastMod = new Sabre_DAV_Property_GetLastModified((int) $dt->format('U')); $this->assertEquals($dt->format(DateTime::ATOM), $lastMod->getTime()->format(DateTime::ATOM)); - } - function testSerialize() { - + public function testSerialize() + { $dt = new DateTime('2010-03-14 16:35', new DateTimeZone('UTC')); $lastMod = new Sabre_DAV_Property_GetLastModified($dt); $doc = new DOMDocument(); $root = $doc->createElement('d:getlastmodified'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -46,7 +43,7 @@ class Sabre_DAV_Property_GetLastModifiedTest extends PHPUnit_Framework_TestCase $this->assertEquals( ' ' . -Sabre_HTTP_Util::toHTTPDate($dt) . +Sabre_HTTP_Util::toHTTPDate($dt). ' ', $xml); @@ -56,8 +53,8 @@ Sabre_HTTP_Util::toHTTPDate($dt) . } catch (Sabre_DAV_Exception $e) { $ok = true; } - if (!$ok) $this->markTestFailed('Unserialize should not be supported'); - + if (!$ok) { + $this->markTestFailed('Unserialize should not be supported'); + } } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Property/HrefListTest.php b/dav/SabreDAV/tests/Sabre/DAV/Property/HrefListTest.php index c420f22d..2f70490c 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Property/HrefListTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Property/HrefListTest.php @@ -1,22 +1,21 @@ assertEquals(array('foo','bar'),$href->getHrefs()); - +class Sabre_DAV_Property_HrefListTest extends PHPUnit_Framework_TestCase +{ + public function testConstruct() + { + $href = new Sabre_DAV_Property_HrefList(array('foo', 'bar')); + $this->assertEquals(array('foo', 'bar'), $href->getHrefs()); } - function testSerialize() { - - $href = new Sabre_DAV_Property_HrefList(array('foo','bar')); - $this->assertEquals(array('foo','bar'),$href->getHrefs()); + public function testSerialize() + { + $href = new Sabre_DAV_Property_HrefList(array('foo', 'bar')); + $this->assertEquals(array('foo', 'bar'), $href->getHrefs()); $doc = new DOMDocument(); $root = $doc->createElement('d:anything'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $server = new Sabre_DAV_Server(); @@ -30,17 +29,16 @@ class Sabre_DAV_Property_HrefListTest extends PHPUnit_Framework_TestCase { ' /bla/foo/bla/bar ', $xml); - } - function testSerializeNoPrefix() { - - $href = new Sabre_DAV_Property_HrefList(array('foo','bar'), false); - $this->assertEquals(array('foo','bar'),$href->getHrefs()); + public function testSerializeNoPrefix() + { + $href = new Sabre_DAV_Property_HrefList(array('foo', 'bar'), false); + $this->assertEquals(array('foo', 'bar'), $href->getHrefs()); $doc = new DOMDocument(); $root = $doc->createElement('d:anything'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $server = new Sabre_DAV_Server(); @@ -54,11 +52,10 @@ class Sabre_DAV_Property_HrefListTest extends PHPUnit_Framework_TestCase { ' foobar ', $xml); - } - function testUnserialize() { - + public function testUnserialize() + { $xml = ' /bla/foo/bla/bar '; @@ -67,12 +64,11 @@ class Sabre_DAV_Property_HrefListTest extends PHPUnit_Framework_TestCase { $dom->loadXML($xml); $href = Sabre_DAV_Property_HrefList::unserialize($dom->firstChild); - $this->assertEquals(array('/bla/foo','/bla/bar'),$href->getHrefs()); - + $this->assertEquals(array('/bla/foo', '/bla/bar'), $href->getHrefs()); } - function testUnserializeIncompatible() { - + public function testUnserializeIncompatible() + { $xml = ' /bla/foo '; @@ -82,7 +78,5 @@ class Sabre_DAV_Property_HrefListTest extends PHPUnit_Framework_TestCase { $href = Sabre_DAV_Property_HrefList::unserialize($dom->firstChild); $this->assertEquals(array(), $href->getHrefs()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Property/HrefTest.php b/dav/SabreDAV/tests/Sabre/DAV/Property/HrefTest.php index 12f0a594..1717dbe1 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Property/HrefTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Property/HrefTest.php @@ -1,22 +1,21 @@ assertEquals('path',$href->getHref()); - + $this->assertEquals('path', $href->getHref()); } - function testSerialize() { - + public function testSerialize() + { $href = new Sabre_DAV_Property_Href('path'); - $this->assertEquals('path',$href->getHref()); + $this->assertEquals('path', $href->getHref()); $doc = new DOMDocument(); $root = $doc->createElement('d:anything'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $server = new Sabre_DAV_Server(); @@ -30,17 +29,16 @@ class Sabre_DAV_Property_HrefTest extends PHPUnit_Framework_TestCase { ' /bla/path ', $xml); - } - function testSerializeNoPrefix() { - - $href = new Sabre_DAV_Property_Href('path',false); - $this->assertEquals('path',$href->getHref()); + public function testSerializeNoPrefix() + { + $href = new Sabre_DAV_Property_Href('path', false); + $this->assertEquals('path', $href->getHref()); $doc = new DOMDocument(); $root = $doc->createElement('d:anything'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $server = new Sabre_DAV_Server(); @@ -54,11 +52,10 @@ class Sabre_DAV_Property_HrefTest extends PHPUnit_Framework_TestCase { ' path ', $xml); - } - function testUnserialize() { - + public function testUnserialize() + { $xml = ' /bla/path '; @@ -67,12 +64,11 @@ class Sabre_DAV_Property_HrefTest extends PHPUnit_Framework_TestCase { $dom->loadXML($xml); $href = Sabre_DAV_Property_Href::unserialize($dom->firstChild); - $this->assertEquals('/bla/path',$href->getHref()); - + $this->assertEquals('/bla/path', $href->getHref()); } - function testUnserializeIncompatible() { - + public function testUnserializeIncompatible() + { $xml = ' /bla/path '; @@ -82,7 +78,5 @@ class Sabre_DAV_Property_HrefTest extends PHPUnit_Framework_TestCase { $href = Sabre_DAV_Property_Href::unserialize($dom->firstChild); $this->assertNull($href); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Property/ResourceTypeTest.php b/dav/SabreDAV/tests/Sabre/DAV/Property/ResourceTypeTest.php index 36f82041..42e19a60 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Property/ResourceTypeTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Property/ResourceTypeTest.php @@ -1,33 +1,32 @@ assertEquals(array('{DAV:}collection'),$resourceType->getValue()); + $this->assertEquals(array('{DAV:}collection'), $resourceType->getValue()); $resourceType = new Sabre_DAV_Property_ResourceType(Sabre_DAV_Server::NODE_FILE); - $this->assertEquals(array(),$resourceType->getValue()); + $this->assertEquals(array(), $resourceType->getValue()); $resourceType = new Sabre_DAV_Property_ResourceType(Sabre_DAV_Server::NODE_DIRECTORY); - $this->assertEquals(array('{DAV:}collection'),$resourceType->getValue()); + $this->assertEquals(array('{DAV:}collection'), $resourceType->getValue()); $resourceType = new Sabre_DAV_Property_ResourceType('{DAV:}principal'); - $this->assertEquals(array('{DAV:}principal'),$resourceType->getValue()); - + $this->assertEquals(array('{DAV:}principal'), $resourceType->getValue()); } /** * @depends testConstruct */ - function testSerialize() { - - $resourceType = new Sabre_DAV_Property_ResourceType(array('{DAV:}collection','{DAV:}principal')); + public function testSerialize() + { + $resourceType = new Sabre_DAV_Property_ResourceType(array('{DAV:}collection', '{DAV:}principal')); $doc = new DOMDocument(); $root = $doc->createElement('d:anything'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $server = new Sabre_DAV_Server(); @@ -39,19 +38,18 @@ class Sabre_DAV_Property_ResourceTypeTest extends PHPUnit_Framework_TestCase { ' ', $xml); - } /** * @depends testSerialize */ - function testSerializeCustomNS() { - + public function testSerializeCustomNS() + { $resourceType = new Sabre_DAV_Property_ResourceType(array('{http://example.org/NS}article')); $doc = new DOMDocument(); $root = $doc->createElement('d:anything'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $server = new Sabre_DAV_Server(); @@ -63,45 +61,40 @@ class Sabre_DAV_Property_ResourceTypeTest extends PHPUnit_Framework_TestCase { ' ', $xml); - } /** * @depends testConstruct */ - function testIs() { - - $resourceType = new Sabre_DAV_Property_ResourceType(array('{DAV:}collection','{DAV:}principal')); + public function testIs() + { + $resourceType = new Sabre_DAV_Property_ResourceType(array('{DAV:}collection', '{DAV:}principal')); $this->assertTrue($resourceType->is('{DAV:}collection')); $this->assertFalse($resourceType->is('{DAV:}blabla')); - } /** * @depends testConstruct */ - function testAdd() { - - $resourceType = new Sabre_DAV_Property_ResourceType(array('{DAV:}collection','{DAV:}principal')); + public function testAdd() + { + $resourceType = new Sabre_DAV_Property_ResourceType(array('{DAV:}collection', '{DAV:}principal')); $resourceType->add('{DAV:}foo'); - $this->assertEquals(array('{DAV:}collection','{DAV:}principal','{DAV:}foo'), $resourceType->getValue()); - + $this->assertEquals(array('{DAV:}collection', '{DAV:}principal', '{DAV:}foo'), $resourceType->getValue()); } /** * @depends testConstruct */ - function testUnserialize() { - - $xml =' + public function testUnserialize() + { + $xml = ' '; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); $resourceType = Sabre_DAV_Property_ResourceType::unserialize($dom->firstChild); - $this->assertEquals(array('{DAV:}collection','{DAV:}principal'),$resourceType->getValue()); - + $this->assertEquals(array('{DAV:}collection', '{DAV:}principal'), $resourceType->getValue()); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Property/ResponseTest.php b/dav/SabreDAV/tests/Sabre/DAV/Property/ResponseTest.php index f6a0ef78..7c4d6891 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Property/ResponseTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Property/ResponseTest.php @@ -1,45 +1,43 @@ array( '{DAV:}displayname' => 'my file', ), 404 => array( '{DAV:}owner' => null, - ) + ), ); - $property = new Sabre_DAV_Property_Response('uri',$innerProps); - - $this->assertEquals('uri',$property->getHref()); - $this->assertEquals($innerProps,$property->getResponseProperties()); - + $property = new Sabre_DAV_Property_Response('uri', $innerProps); + $this->assertEquals('uri', $property->getHref()); + $this->assertEquals($innerProps, $property->getResponseProperties()); } /** * @depends testSimple */ - function testSerialize() { - + public function testSerialize() + { $innerProps = array( 200 => array( '{DAV:}displayname' => 'my file', ), 404 => array( '{DAV:}owner' => null, - ) + ), ); - $property = new Sabre_DAV_Property_Response('uri',$innerProps); + $property = new Sabre_DAV_Property_Response('uri', $innerProps); $doc = new DOMDocument(); $root = $doc->createElement('d:root'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -52,44 +50,43 @@ class Sabre_DAV_Property_ResponseTest extends PHPUnit_Framework_TestCase { $this->assertEquals( ' ' . -'' . -'/uri' . -'' . -'' . -'my file' . -'' . -'HTTP/1.1 200 OK' . -'' . -'' . -'' . -'' . -'' . -'HTTP/1.1 404 Not Found' . -'' . -'' . +''. +'/uri'. +''. +''. +'my file'. +''. +'HTTP/1.1 200 OK'. +''. +''. +''. +''. +''. +'HTTP/1.1 404 Not Found'. +''. +''. ' ', $xml); - } /** - * This one is specifically for testing properties with no namespaces, which is legal xml + * This one is specifically for testing properties with no namespaces, which is legal xml. * * @depends testSerialize */ - function testSerializeEmptyNamespace() { - + public function testSerializeEmptyNamespace() + { $innerProps = array( 200 => array( '{}propertyname' => 'value', ), ); - $property = new Sabre_DAV_Property_Response('uri',$innerProps); + $property = new Sabre_DAV_Property_Response('uri', $innerProps); $doc = new DOMDocument(); $root = $doc->createElement('d:root'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -102,38 +99,37 @@ class Sabre_DAV_Property_ResponseTest extends PHPUnit_Framework_TestCase { $this->assertEquals( ' ' . -'' . -'/uri' . -'' . -'' . -'value' . -'' . -'HTTP/1.1 200 OK' . -'' . -'' . +''. +'/uri'. +''. +''. +'value'. +''. +'HTTP/1.1 200 OK'. +''. +''. ' ', $xml); - } /** - * This one is specifically for testing properties with no namespaces, which is legal xml + * This one is specifically for testing properties with no namespaces, which is legal xml. * * @depends testSerialize */ - function testSerializeCustomNamespace() { - + public function testSerializeCustomNamespace() + { $innerProps = array( 200 => array( '{http://sabredav.org/NS/example}propertyname' => 'value', ), ); - $property = new Sabre_DAV_Property_Response('uri',$innerProps); + $property = new Sabre_DAV_Property_Response('uri', $innerProps); $doc = new DOMDocument(); $root = $doc->createElement('d:root'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -146,36 +142,35 @@ class Sabre_DAV_Property_ResponseTest extends PHPUnit_Framework_TestCase { $this->assertEquals( ' ' . -'' . -'/uri' . -'' . -'' . -'value' . -'' . -'HTTP/1.1 200 OK' . -'' . -'' . +''. +'/uri'. +''. +''. +'value'. +''. +'HTTP/1.1 200 OK'. +''. +''. ' ', $xml); - } /** * @depends testSerialize */ - function testSerializeComplexProperty() { - + public function testSerializeComplexProperty() + { $innerProps = array( 200 => array( - '{DAV:}link' => new Sabre_DAV_Property_Href('http://sabredav.org/', false) + '{DAV:}link' => new Sabre_DAV_Property_Href('http://sabredav.org/', false), ), ); - $property = new Sabre_DAV_Property_Response('uri',$innerProps); + $property = new Sabre_DAV_Property_Response('uri', $innerProps); $doc = new DOMDocument(); $root = $doc->createElement('d:root'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -188,44 +183,41 @@ class Sabre_DAV_Property_ResponseTest extends PHPUnit_Framework_TestCase { $this->assertEquals( ' ' . -'' . -'/uri' . -'' . -'' . -'http://sabredav.org/' . -'' . -'HTTP/1.1 200 OK' . -'' . -'' . +''. +'/uri'. +''. +''. +'http://sabredav.org/'. +''. +'HTTP/1.1 200 OK'. +''. +''. ' ', $xml); - } /** * @depends testSerialize * @expectedException Sabre_DAV_Exception */ - function testSerializeBreak() { - + public function testSerializeBreak() + { $innerProps = array( 200 => array( - '{DAV:}link' => new STDClass() + '{DAV:}link' => new STDClass(), ), ); - $property = new Sabre_DAV_Property_Response('uri',$innerProps); + $property = new Sabre_DAV_Property_Response('uri', $innerProps); $doc = new DOMDocument(); $root = $doc->createElement('d:root'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); $server = new Sabre_DAV_Server($objectTree); $property->serialize($server, $root); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Property/SupportedReportSetTest.php b/dav/SabreDAV/tests/Sabre/DAV/Property/SupportedReportSetTest.php index 086d59a9..74c543d8 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Property/SupportedReportSetTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Property/SupportedReportSetTest.php @@ -3,14 +3,14 @@ require_once 'Sabre/HTTP/ResponseMock.php'; require_once 'Sabre/DAV/AbstractServer.php'; -class Sabre_DAV_Property_SupportedReportSetTest extends Sabre_DAV_AbstractServer { - - public function sendPROPFIND($body) { - +class Sabre_DAV_Property_SupportedReportSetTest extends Sabre_DAV_AbstractServer +{ + public function sendPROPFIND($body) + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'PROPFIND', - 'HTTP_DEPTH' => '0', + 'HTTP_DEPTH' => '0', ); $request = new Sabre_HTTP_Request($serverVars); @@ -18,14 +18,13 @@ class Sabre_DAV_Property_SupportedReportSetTest extends Sabre_DAV_AbstractServer $this->server->httpRequest = ($request); $this->server->exec(); - } /** * @covers Sabre_DAV_Property_SupportedReportSet */ - function testNoReports() { - + public function testNoReports() + { $xml = ' @@ -35,33 +34,33 @@ class Sabre_DAV_Property_SupportedReportSetTest extends Sabre_DAV_AbstractServer $this->sendPROPFIND($xml); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'We expected a multi-status response. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'We expected a multi-status response. Full response body: '.$this->response->body); - $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/","xmlns\\1=\"DAV:\"",$this->response->body); + $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/", 'xmlns\\1="DAV:"', $this->response->body); $xml = simplexml_load_string($body); - $xml->registerXPathNamespace('d','DAV:'); + $xml->registerXPathNamespace('d', 'DAV:'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop'); - $this->assertEquals(1,count($data),'We expected 1 \'d:prop\' element'); + $this->assertEquals(1, count($data), 'We expected 1 \'d:prop\' element'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supported-report-set'); - $this->assertEquals(1,count($data),'We expected 1 \'d:supported-report-set\' element'); + $this->assertEquals(1, count($data), 'We expected 1 \'d:supported-report-set\' element'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:status'); - $this->assertEquals(1,count($data),'We expected 1 \'d:status\' element'); - - $this->assertEquals('HTTP/1.1 200 OK',(string)$data[0],'The status for this property should have been 200'); + $this->assertEquals(1, count($data), 'We expected 1 \'d:status\' element'); + $this->assertEquals('HTTP/1.1 200 OK', (string) $data[0], 'The status for this property should have been 200'); } /** * @covers Sabre_DAV_Property_SupportedReportSet * @depends testNoReports */ - function testCustomReport() { + public function testCustomReport() + { // Intercepting the report property - $this->server->subscribeEvent('afterGetProperties',array($this,'addProp')); + $this->server->subscribeEvent('afterGetProperties', array($this, 'addProp')); $xml = ' @@ -72,52 +71,45 @@ class Sabre_DAV_Property_SupportedReportSetTest extends Sabre_DAV_AbstractServer $this->sendPROPFIND($xml); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'We expected a multi-status response. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'We expected a multi-status response. Full response body: '.$this->response->body); - $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/","xmlns\\1=\"DAV:\"",$this->response->body); + $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/", 'xmlns\\1="DAV:"', $this->response->body); $xml = simplexml_load_string($body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('x','http://www.rooftopsolutions.nl/testnamespace'); + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('x', 'http://www.rooftopsolutions.nl/testnamespace'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop'); - $this->assertEquals(1,count($data),'We expected 1 \'d:prop\' element'); + $this->assertEquals(1, count($data), 'We expected 1 \'d:prop\' element'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supported-report-set'); - $this->assertEquals(1,count($data),'We expected 1 \'d:supported-report-set\' element'); + $this->assertEquals(1, count($data), 'We expected 1 \'d:supported-report-set\' element'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supported-report-set/d:supported-report'); - $this->assertEquals(2,count($data),'We expected 2 \'d:supported-report\' elements'); + $this->assertEquals(2, count($data), 'We expected 2 \'d:supported-report\' elements'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supported-report-set/d:supported-report/d:report'); - $this->assertEquals(2,count($data),'We expected 2 \'d:report\' elements'); + $this->assertEquals(2, count($data), 'We expected 2 \'d:report\' elements'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supported-report-set/d:supported-report/d:report/x:myreport'); - $this->assertEquals(1,count($data),'We expected 1 \'x:myreport\' element. Full body: ' . $this->response->body); + $this->assertEquals(1, count($data), 'We expected 1 \'x:myreport\' element. Full body: '.$this->response->body); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supported-report-set/d:supported-report/d:report/d:anotherreport'); - $this->assertEquals(1,count($data),'We expected 1 \'d:anotherreport\' element. Full body: ' . $this->response->body); + $this->assertEquals(1, count($data), 'We expected 1 \'d:anotherreport\' element. Full body: '.$this->response->body); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:status'); - $this->assertEquals(1,count($data),'We expected 1 \'d:status\' element'); - - $this->assertEquals('HTTP/1.1 200 OK',(string)$data[0],'The status for this property should have been 200'); + $this->assertEquals(1, count($data), 'We expected 1 \'d:status\' element'); + $this->assertEquals('HTTP/1.1 200 OK', (string) $data[0], 'The status for this property should have been 200'); } /** - * This method is used as a callback for afterGetProperties + * This method is used as a callback for afterGetProperties. */ - function addProp($path, &$properties) { - + public function addProp($path, &$properties) + { if (isset($properties[200]['{DAV:}supported-report-set'])) { $properties[200]['{DAV:}supported-report-set']->addReport('{http://www.rooftopsolutions.nl/testnamespace}myreport'); $properties[200]['{DAV:}supported-report-set']->addReport('{DAV:}anotherreport'); } - } - - - } - -?> diff --git a/dav/SabreDAV/tests/Sabre/DAV/ServerCopyMoveTest.php b/dav/SabreDAV/tests/Sabre/DAV/ServerCopyMoveTest.php index b7f5b474..6f9db946 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ServerCopyMoveTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ServerCopyMoveTest.php @@ -2,52 +2,47 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { - +class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase +{ private $response; /** * @var Sabre_DAV_Server */ private $server; - function setUp() { - + public function setUp() + { $this->response = new Sabre_HTTP_ResponseMock(); $dir = new Sabre_DAV_FS_Directory(SABRE_TEMPDIR); $tree = new Sabre_DAV_ObjectTree($dir); $this->server = new Sabre_DAV_Server($tree); $this->server->debugExceptions = true; $this->server->httpResponse = $this->response; - file_put_contents(SABRE_TEMPDIR . '/test.txt', 'Test contents'); - file_put_contents(SABRE_TEMPDIR . '/test2.txt', 'Test contents2'); - mkdir(SABRE_TEMPDIR . '/col'); - file_put_contents(SABRE_TEMPDIR . 'col/test.txt', 'Test contents'); - + file_put_contents(SABRE_TEMPDIR.'/test.txt', 'Test contents'); + file_put_contents(SABRE_TEMPDIR.'/test2.txt', 'Test contents2'); + mkdir(SABRE_TEMPDIR.'/col'); + file_put_contents(SABRE_TEMPDIR.'col/test.txt', 'Test contents'); } - function tearDown() { - - $cleanUp = array('test.txt','testput.txt','testcol','test2.txt','test3.txt','col/test.txt','col','col2/test.txt','col2'); - foreach($cleanUp as $file) { - $tmpFile = SABRE_TEMPDIR . '/' . $file; + public function tearDown() + { + $cleanUp = array('test.txt', 'testput.txt', 'testcol', 'test2.txt', 'test3.txt', 'col/test.txt', 'col', 'col2/test.txt', 'col2'); + foreach ($cleanUp as $file) { + $tmpFile = SABRE_TEMPDIR.'/'.$file; if (file_exists($tmpFile)) { - if (is_dir($tmpFile)) { rmdir($tmpFile); } else { unlink($tmpFile); } - } } - } - - function testCopyOverWrite() { - + public function testCopyOverWrite() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'COPY', 'HTTP_DESTINATION' => '/test2.txt', ); @@ -56,21 +51,20 @@ class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status,'Received an incorrect HTTP status. Full body inspection: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status, 'Received an incorrect HTTP status. Full body inspection: '.$this->response->body); $this->assertEquals(array( 'Content-Length' => '0', ), $this->response->headers ); - $this->assertEquals('Test contents',file_get_contents(SABRE_TEMPDIR. '/test2.txt')); - + $this->assertEquals('Test contents', file_get_contents(SABRE_TEMPDIR.'/test2.txt')); } - function testCopyToSelf() { - + public function testCopyToSelf() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'COPY', 'HTTP_DESTINATION' => '/test.txt', ); @@ -79,15 +73,14 @@ class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 403 Forbidden',$this->response->status,'Received an incorrect HTTP status. Full body inspection: ' . $this->response->body); - $this->assertEquals('Test contents',file_get_contents(SABRE_TEMPDIR. '/test.txt')); - + $this->assertEquals('HTTP/1.1 403 Forbidden', $this->response->status, 'Received an incorrect HTTP status. Full body inspection: '.$this->response->body); + $this->assertEquals('Test contents', file_get_contents(SABRE_TEMPDIR.'/test.txt')); } - function testMoveToSelf() { - + public function testMoveToSelf() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'MOVE', 'HTTP_DESTINATION' => '/test.txt', ); @@ -96,15 +89,14 @@ class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 403 Forbidden',$this->response->status,'Received an incorrect HTTP status. Full body inspection: ' . $this->response->body); - $this->assertEquals('Test contents',file_get_contents(SABRE_TEMPDIR. '/test.txt')); - + $this->assertEquals('HTTP/1.1 403 Forbidden', $this->response->status, 'Received an incorrect HTTP status. Full body inspection: '.$this->response->body); + $this->assertEquals('Test contents', file_get_contents(SABRE_TEMPDIR.'/test.txt')); } - function testMoveOverWrite() { - + public function testMoveOverWrite() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'MOVE', 'HTTP_DESTINATION' => '/test2.txt', ); @@ -119,19 +111,18 @@ class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { $this->response->headers ); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status); - $this->assertEquals('Test contents',file_get_contents(SABRE_TEMPDIR . '/test2.txt')); - $this->assertFalse(file_exists(SABRE_TEMPDIR . '/test.txt'),'The sourcefile test.txt should no longer exist at this point'); - + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status); + $this->assertEquals('Test contents', file_get_contents(SABRE_TEMPDIR.'/test2.txt')); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/test.txt'), 'The sourcefile test.txt should no longer exist at this point'); } - function testBlockedOverWrite() { - + public function testBlockedOverWrite() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', - 'REQUEST_METHOD' => 'COPY', + 'REQUEST_URI' => '/test.txt', + 'REQUEST_METHOD' => 'COPY', 'HTTP_DESTINATION' => '/test2.txt', - 'HTTP_OVERWRITE' => 'F', + 'HTTP_OVERWRITE' => 'F', ); $request = new Sabre_HTTP_Request($serverVars); @@ -144,19 +135,17 @@ class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { $this->response->headers ); - $this->assertEquals('HTTP/1.1 412 Precondition failed',$this->response->status); - $this->assertEquals('Test contents2',file_get_contents(SABRE_TEMPDIR . '/test2.txt')); - - + $this->assertEquals('HTTP/1.1 412 Precondition failed', $this->response->status); + $this->assertEquals('Test contents2', file_get_contents(SABRE_TEMPDIR.'/test2.txt')); } - function testNonExistantParent() { - + public function testNonExistantParent() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', - 'REQUEST_METHOD' => 'COPY', + 'REQUEST_URI' => '/test.txt', + 'REQUEST_METHOD' => 'COPY', 'HTTP_DESTINATION' => '/testcol2/test2.txt', - 'HTTP_OVERWRITE' => 'F', + 'HTTP_OVERWRITE' => 'F', ); $request = new Sabre_HTTP_Request($serverVars); @@ -169,31 +158,29 @@ class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { $this->response->headers ); - $this->assertEquals('HTTP/1.1 409 Conflict',$this->response->status); - + $this->assertEquals('HTTP/1.1 409 Conflict', $this->response->status); } - function testRandomOverwriteHeader() { - + public function testRandomOverwriteHeader() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', - 'REQUEST_METHOD' => 'COPY', + 'REQUEST_URI' => '/test.txt', + 'REQUEST_METHOD' => 'COPY', 'HTTP_DESTINATION' => '/testcol2/test2.txt', - 'HTTP_OVERWRITE' => 'SURE!', + 'HTTP_OVERWRITE' => 'SURE!', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 400 Bad request',$this->response->status); - + $this->assertEquals('HTTP/1.1 400 Bad request', $this->response->status); } - function testCopyDirectory() { - + public function testCopyDirectory() + { $serverVars = array( - 'REQUEST_URI' => '/col', + 'REQUEST_URI' => '/col', 'REQUEST_METHOD' => 'COPY', 'HTTP_DESTINATION' => '/col2', ); @@ -208,15 +195,14 @@ class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { $this->response->headers ); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); - $this->assertEquals('Test contents',file_get_contents(SABRE_TEMPDIR . '/col2/test.txt')); - + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); + $this->assertEquals('Test contents', file_get_contents(SABRE_TEMPDIR.'/col2/test.txt')); } - function testSimpleCopyFile() { - + public function testSimpleCopyFile() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'COPY', 'HTTP_DESTINATION' => '/test3.txt', ); @@ -231,15 +217,14 @@ class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { $this->response->headers ); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); - $this->assertEquals('Test contents',file_get_contents(SABRE_TEMPDIR . '/test3.txt')); - + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); + $this->assertEquals('Test contents', file_get_contents(SABRE_TEMPDIR.'/test3.txt')); } - function testSimpleCopyCollection() { - + public function testSimpleCopyCollection() + { $serverVars = array( - 'REQUEST_URI' => '/col', + 'REQUEST_URI' => '/col', 'REQUEST_METHOD' => 'COPY', 'HTTP_DESTINATION' => '/col2', ); @@ -248,7 +233,7 @@ class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status,'Incorrect status received. Full response body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status, 'Incorrect status received. Full response body: '.$this->response->body); $this->assertEquals(array( 'Content-Length' => '0', @@ -256,9 +241,6 @@ class Sabre_DAV_ServerCopyMoveTest extends PHPUnit_Framework_TestCase { $this->response->headers ); - - $this->assertEquals('Test contents',file_get_contents(SABRE_TEMPDIR . '/col2/test.txt')); - + $this->assertEquals('Test contents', file_get_contents(SABRE_TEMPDIR.'/col2/test.txt')); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ServerEventsTest.php b/dav/SabreDAV/tests/Sabre/DAV/ServerEventsTest.php index 7208fed2..4641a5f1 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ServerEventsTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ServerEventsTest.php @@ -2,33 +2,31 @@ require_once 'Sabre/DAV/AbstractServer.php'; -class Sabre_DAV_ServerEventsTest extends Sabre_DAV_AbstractServer { - +class Sabre_DAV_ServerEventsTest extends Sabre_DAV_AbstractServer +{ private $tempPath; private $exception; - function testAfterBind() { - - $this->server->subscribeEvent('afterBind',array($this,'afterBindHandler')); + public function testAfterBind() + { + $this->server->subscribeEvent('afterBind', array($this, 'afterBindHandler')); $newPath = 'afterBind'; $this->tempPath = ''; - $this->server->createFile($newPath,'body'); + $this->server->createFile($newPath, 'body'); $this->assertEquals($newPath, $this->tempPath); - } - function afterBindHandler($path) { - - $this->tempPath = $path; - + public function afterBindHandler($path) + { + $this->tempPath = $path; } - function testBeforeBindCancel() { - - $this->server->subscribeEvent('beforeBind', array($this,'beforeBindCancelHandler')); - $this->assertFalse($this->server->createFile('bla','body')); + public function testBeforeBindCancel() + { + $this->server->subscribeEvent('beforeBind', array($this, 'beforeBindCancelHandler')); + $this->assertFalse($this->server->createFile('bla', 'body')); // Also testing put() $req = new Sabre_HTTP_Request(array( @@ -39,18 +37,16 @@ class Sabre_DAV_ServerEventsTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = $req; $this->server->exec(); - $this->assertEquals('',$this->server->httpResponse->status); - + $this->assertEquals('', $this->server->httpResponse->status); } - function beforeBindCancelHandler() { - + public function beforeBindCancelHandler() + { return false; - } - function testException() { - + public function testException() + { $this->server->subscribeEvent('exception', array($this, 'exceptionHandler')); $req = new Sabre_HTTP_Request(array( @@ -61,13 +57,10 @@ class Sabre_DAV_ServerEventsTest extends Sabre_DAV_AbstractServer { $this->server->exec(); $this->assertInstanceOf('Sabre_DAV_Exception_NotFound', $this->exception); - } - function exceptionHandler(Exception $exception) { - + public function exceptionHandler(Exception $exception) + { $this->exception = $exception; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ServerFinderBlockTest.php b/dav/SabreDAV/tests/Sabre/DAV/ServerFinderBlockTest.php index 622e6b62..501a7fb9 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ServerFinderBlockTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ServerFinderBlockTest.php @@ -4,12 +4,12 @@ require_once 'Sabre/HTTP/ResponseMock.php'; require_once 'Sabre/DAV/AbstractServer.php'; require_once 'Sabre/DAV/Exception.php'; -class Sabre_DAV_ServerFinderBlockTest extends Sabre_DAV_AbstractServer{ - - function testPut() { - +class Sabre_DAV_ServerFinderBlockTest extends Sabre_DAV_AbstractServer +{ + public function testPut() + { $serverVars = array( - 'REQUEST_URI' => '/testput.txt', + 'REQUEST_URI' => '/testput.txt', 'REQUEST_METHOD' => 'PUT', 'HTTP_X_EXPECTED_ENTITY_LENGTH' => '20', ); @@ -20,17 +20,16 @@ class Sabre_DAV_ServerFinderBlockTest extends Sabre_DAV_AbstractServer{ $this->server->exec(); $this->assertEquals('', $this->response->body); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals('0', $this->response->headers['Content-Length']); - $this->assertEquals('Testing finder',file_get_contents(SABRE_TEMPDIR . '/testput.txt')); - + $this->assertEquals('Testing finder', file_get_contents(SABRE_TEMPDIR.'/testput.txt')); } - function testPutFail() { - + public function testPutFail() + { $serverVars = array( - 'REQUEST_URI' => '/testput.txt', + 'REQUEST_URI' => '/testput.txt', 'REQUEST_METHOD' => 'PUT', 'HTTP_X_EXPECTED_ENTITY_LENGTH' => '20', ); @@ -40,11 +39,11 @@ class Sabre_DAV_ServerFinderBlockTest extends Sabre_DAV_AbstractServer{ $this->server->httpRequest = $request; $this->server->exec(); - $this->assertEquals('HTTP/1.1 403 Forbidden',$this->response->status); + $this->assertEquals('HTTP/1.1 403 Forbidden', $this->response->status); $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); + ), $this->response->headers); - $this->assertFalse(file_exists(SABRE_TEMPDIR . '/testput.txt')); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/testput.txt')); } } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ServerMKCOLTest.php b/dav/SabreDAV/tests/Sabre/DAV/ServerMKCOLTest.php index a9abc181..7faab6a7 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ServerMKCOLTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ServerMKCOLTest.php @@ -4,84 +4,81 @@ require_once 'Sabre/HTTP/ResponseMock.php'; require_once 'Sabre/DAV/AbstractServer.php'; require_once 'Sabre/DAV/Exception.php'; -class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { - - function testMkcol() { - +class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer +{ + public function testMkcol() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', ); $request = new Sabre_HTTP_Request($serverVars); - $request->setBody(""); + $request->setBody(''); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals(array( 'Content-Length' => '0', - ),$this->response->headers); + ), $this->response->headers); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals('', $this->response->body); - $this->assertTrue(is_dir($this->tempDir . '/testcol')); - + $this->assertTrue(is_dir($this->tempDir.'/testcol')); } /** * @depends testMkcol */ - function testMKCOLUnknownBody() { - + public function testMKCOLUnknownBody() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', ); $request = new Sabre_HTTP_Request($serverVars); - $request->setBody("Hello"); + $request->setBody('Hello'); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 415 Unsupported Media Type',$this->response->status); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $this->response->status); } /** * @depends testMkcol */ - function testMKCOLBrokenXML() { - + public function testMKCOLBrokenXML() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', 'HTTP_CONTENT_TYPE' => 'application/xml', ); $request = new Sabre_HTTP_Request($serverVars); - $request->setBody("Hello"); + $request->setBody('Hello'); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 400 Bad request',$this->response->status); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 400 Bad request', $this->response->status); } /** * @depends testMkcol */ - function testMKCOLUnknownXML() { - + public function testMKCOLUnknownXML() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', 'HTTP_CONTENT_TYPE' => 'application/xml', ); @@ -93,19 +90,18 @@ class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 415 Unsupported Media Type',$this->response->status); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 415 Unsupported Media Type', $this->response->status); } /** * @depends testMkcol */ - function testMKCOLNoResourceType() { - + public function testMKCOLNoResourceType() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', 'HTTP_CONTENT_TYPE' => 'application/xml', ); @@ -124,19 +120,18 @@ class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 400 Bad request',$this->response->status,'Wrong statuscode received. Full response body: ' .$this->response->body); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 400 Bad request', $this->response->status, 'Wrong statuscode received. Full response body: '.$this->response->body); } /** * @depends testMKCOLNoResourceType */ - function testMKCOLIncorrectResourceType() { - + public function testMKCOLIncorrectResourceType() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', 'HTTP_CONTENT_TYPE' => 'application/xml', ); @@ -155,19 +150,18 @@ class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 403 Forbidden',$this->response->status,'Wrong statuscode received. Full response body: ' .$this->response->body); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 403 Forbidden', $this->response->status, 'Wrong statuscode received. Full response body: '.$this->response->body); } /** * @depends testMKCOLIncorrectResourceType */ - function testMKCOLIncorrectResourceType2() { - + public function testMKCOLIncorrectResourceType2() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', 'HTTP_CONTENT_TYPE' => 'application/xml', ); @@ -186,19 +180,18 @@ class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 403 Forbidden',$this->response->status,'Wrong statuscode received. Full response body: ' .$this->response->body); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 403 Forbidden', $this->response->status, 'Wrong statuscode received. Full response body: '.$this->response->body); } /** * @depends testMKCOLIncorrectResourceType2 */ - function testMKCOLSuccess() { - + public function testMKCOLSuccess() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', 'HTTP_CONTENT_TYPE' => 'application/xml', ); @@ -217,19 +210,18 @@ class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { $this->assertEquals(array( 'Content-Length' => '0', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status,'Wrong statuscode received. Full response body: ' .$this->response->body); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status, 'Wrong statuscode received. Full response body: '.$this->response->body); } /** * @depends testMKCOLIncorrectResourceType2 */ - function testMKCOLWhiteSpaceResourceType() { - + public function testMKCOLWhiteSpaceResourceType() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', 'HTTP_CONTENT_TYPE' => 'application/xml', ); @@ -250,19 +242,18 @@ class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { $this->assertEquals(array( 'Content-Length' => '0', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status,'Wrong statuscode received. Full response body: ' .$this->response->body); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status, 'Wrong statuscode received. Full response body: '.$this->response->body); } /** * @depends testMKCOLIncorrectResourceType2 */ - function testMKCOLNoParent() { - + public function testMKCOLNoParent() + { $serverVars = array( - 'REQUEST_URI' => '/testnoparent/409me', + 'REQUEST_URI' => '/testnoparent/409me', 'REQUEST_METHOD' => 'MKCOL', ); @@ -274,19 +265,18 @@ class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 409 Conflict',$this->response->status,'Wrong statuscode received. Full response body: ' .$this->response->body); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 409 Conflict', $this->response->status, 'Wrong statuscode received. Full response body: '.$this->response->body); } /** * @depends testMKCOLIncorrectResourceType2 */ - function testMKCOLParentIsNoCollection() { - + public function testMKCOLParentIsNoCollection() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt/409me', + 'REQUEST_URI' => '/test.txt/409me', 'REQUEST_METHOD' => 'MKCOL', ); @@ -298,19 +288,18 @@ class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 409 Conflict',$this->response->status,'Wrong statuscode received. Full response body: ' .$this->response->body); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 409 Conflict', $this->response->status, 'Wrong statuscode received. Full response body: '.$this->response->body); } /** * @depends testMKCOLIncorrectResourceType2 */ - function testMKCOLAlreadyExists() { - + public function testMKCOLAlreadyExists() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'MKCOL', ); @@ -322,21 +311,20 @@ class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - 'Allow' => 'OPTIONS, GET, HEAD, DELETE, PROPFIND, PUT, PROPPATCH, COPY, MOVE, REPORT', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 405 Method Not Allowed',$this->response->status,'Wrong statuscode received. Full response body: ' .$this->response->body); + 'Allow' => 'OPTIONS, GET, HEAD, DELETE, PROPFIND, PUT, PROPPATCH, COPY, MOVE, REPORT', + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 405 Method Not Allowed', $this->response->status, 'Wrong statuscode received. Full response body: '.$this->response->body); } /** * @depends testMKCOLSuccess * @depends testMKCOLAlreadyExists */ - function testMKCOLAndProps() { - + public function testMKCOLAndProps() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'MKCOL', 'HTTP_CONTENT_TYPE' => 'application/xml', ); @@ -354,14 +342,10 @@ class Sabre_DAV_ServerMKCOLTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'Wrong statuscode received. Full response body: ' .$this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'Wrong statuscode received. Full response body: '.$this->response->body); $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - - + ), $this->response->headers); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ServerPluginTest.php b/dav/SabreDAV/tests/Sabre/DAV/ServerPluginTest.php index fd719792..7b079958 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ServerPluginTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ServerPluginTest.php @@ -3,38 +3,36 @@ require_once 'Sabre/DAV/AbstractServer.php'; require_once 'Sabre/DAV/TestPlugin.php'; -class Sabre_DAV_ServerPluginTest extends Sabre_DAV_AbstractServer { - +class Sabre_DAV_ServerPluginTest extends Sabre_DAV_AbstractServer +{ /** * @var Sabre_DAV_TestPlugin */ protected $testPlugin; - function setUp() { - + public function setUp() + { parent::setUp(); $testPlugin = new Sabre_DAV_TestPlugin(); $this->server->addPlugin($testPlugin); $this->testPlugin = $testPlugin; - } /** * @covers Sabre_DAV_ServerPlugin */ - function testBaseClass() { - + public function testBaseClass() + { $p = new Sabre_DAV_ServerPluginMock(); - $this->assertEquals(array(),$p->getFeatures()); - $this->assertEquals(array(),$p->getHTTPMethods('')); - + $this->assertEquals(array(), $p->getFeatures()); + $this->assertEquals(array(), $p->getHTTPMethods('')); } - function testOptions() { - + public function testOptions() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'OPTIONS', ); @@ -43,53 +41,46 @@ class Sabre_DAV_ServerPluginTest extends Sabre_DAV_AbstractServer { $this->server->exec(); $this->assertEquals(array( - 'DAV' => '1, 3, extended-mkcol, drinking', - 'MS-Author-Via' => 'DAV', - 'Allow' => 'OPTIONS, GET, HEAD, DELETE, PROPFIND, PUT, PROPPATCH, COPY, MOVE, REPORT, BEER, WINE', - 'Accept-Ranges' => 'bytes', - 'Content-Length' => '0', + 'DAV' => '1, 3, extended-mkcol, drinking', + 'MS-Author-Via' => 'DAV', + 'Allow' => 'OPTIONS, GET, HEAD, DELETE, PROPFIND, PUT, PROPPATCH, COPY, MOVE, REPORT, BEER, WINE', + 'Accept-Ranges' => 'bytes', + 'Content-Length' => '0', 'X-Sabre-Version' => Sabre_DAV_Version::VERSION, - ),$this->response->headers); + ), $this->response->headers); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('', $this->response->body); - $this->assertEquals('OPTIONS',$this->testPlugin->beforeMethod); - - + $this->assertEquals('OPTIONS', $this->testPlugin->beforeMethod); } - function testGetPlugin() { - - $this->assertEquals($this->testPlugin,$this->server->getPlugin(get_class($this->testPlugin))); - + public function testGetPlugin() + { + $this->assertEquals($this->testPlugin, $this->server->getPlugin(get_class($this->testPlugin))); } - function testUnknownPlugin() { - + public function testUnknownPlugin() + { $this->assertNull($this->server->getPlugin('SomeRandomClassName')); - } - function testGetSupportedReportSet() { - + public function testGetSupportedReportSet() + { $this->assertEquals(array(), $this->testPlugin->getSupportedReportSet('/')); - } - function testGetPlugins() { - + public function testGetPlugins() + { $this->assertEquals( array(get_class($this->testPlugin) => $this->testPlugin), $this->server->getPlugins() ); - } - - } -class Sabre_DAV_ServerPluginMock extends Sabre_DAV_ServerPlugin { - - function initialize(Sabre_DAV_Server $s) { } - +class Sabre_DAV_ServerPluginMock extends Sabre_DAV_ServerPlugin +{ + public function initialize(Sabre_DAV_Server $s) + { + } } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ServerPreconditionTest.php b/dav/SabreDAV/tests/Sabre/DAV/ServerPreconditionTest.php index 6ce4733a..3e4a171e 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ServerPreconditionTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ServerPreconditionTest.php @@ -2,76 +2,72 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_DAV_ServerPreconditionsTest extends PHPUnit_Framework_TestCase { - +class Sabre_DAV_ServerPreconditionsTest extends PHPUnit_Framework_TestCase +{ /** * @covers Sabre_DAV_Server::checkPreconditions * @expectedException Sabre_DAV_Exception_PreconditionFailed */ - function testIfMatchNoNode() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfMatchNoNode() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_MATCH' => '*', - 'REQUEST_URI' => '/bar' + 'REQUEST_URI' => '/bar', )); $server->httpRequest = $httpRequest; $server->checkPreconditions(); - } /** * @covers Sabre_DAV_Server::checkPreconditions */ - function testIfMatchHasNode() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfMatchHasNode() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_MATCH' => '*', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $this->assertTrue($server->checkPreconditions()); - } /** * @covers Sabre_DAV_Server::checkPreconditions * @expectedException Sabre_DAV_Exception_PreconditionFailed */ - function testIfMatchWrongEtag() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfMatchWrongEtag() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_MATCH' => '1234', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->checkPreconditions(); - } /** * @covers Sabre_DAV_Server::checkPreconditions */ - function testIfMatchCorrectEtag() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfMatchCorrectEtag() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_MATCH' => '"abc123"', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $this->assertTrue($server->checkPreconditions()); - } /** @@ -80,312 +76,288 @@ class Sabre_DAV_ServerPreconditionsTest extends PHPUnit_Framework_TestCase { * @covers Sabre_DAV_Server::checkPreconditions * @depends testIfMatchCorrectEtag */ - function testIfMatchEvolutionEtag() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfMatchEvolutionEtag() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_MATCH' => '\\"abc123\\"', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $this->assertTrue($server->checkPreconditions()); - } /** * @covers Sabre_DAV_Server::checkPreconditions */ - function testIfMatchMultiple() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfMatchMultiple() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_MATCH' => '"hellothere", "abc123"', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $this->assertTrue($server->checkPreconditions()); - } /** * @covers Sabre_DAV_Server::checkPreconditions */ - function testIfNoneMatchNoNode() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfNoneMatchNoNode() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_NONE_MATCH' => '*', - 'REQUEST_URI' => '/bar' + 'REQUEST_URI' => '/bar', )); $server->httpRequest = $httpRequest; $this->assertTrue($server->checkPreconditions()); - } /** * @covers Sabre_DAV_Server::checkPreconditions * @expectedException Sabre_DAV_Exception_PreconditionFailed */ - function testIfNoneMatchHasNode() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfNoneMatchHasNode() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_NONE_MATCH' => '*', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->checkPreconditions(); - } /** * @covers Sabre_DAV_Server::checkPreconditions */ - function testIfNoneMatchWrongEtag() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfNoneMatchWrongEtag() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_NONE_MATCH' => '"1234"', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $this->assertTrue($server->checkPreconditions()); - } /** * @covers Sabre_DAV_Server::checkPreconditions */ - function testIfNoneMatchWrongEtagMultiple() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfNoneMatchWrongEtagMultiple() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_NONE_MATCH' => '"1234", "5678"', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $this->assertTrue($server->checkPreconditions()); - } /** * @covers Sabre_DAV_Server::checkPreconditions * @expectedException Sabre_DAV_Exception_PreconditionFailed */ - public function testIfNoneMatchCorrectEtag() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfNoneMatchCorrectEtag() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_NONE_MATCH' => '"abc123"', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->checkPreconditions(); - } /** * @covers Sabre_DAV_Server::checkPreconditions * @expectedException Sabre_DAV_Exception_PreconditionFailed */ - public function testIfNoneMatchCorrectEtagMultiple() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfNoneMatchCorrectEtagMultiple() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_NONE_MATCH' => '"1234", "abc123"', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->checkPreconditions(); - } /** * @covers Sabre_DAV_Server::checkPreconditions */ - public function testIfNoneMatchCorrectEtagAsGet() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfNoneMatchCorrectEtagAsGet() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_NONE_MATCH' => '"abc123"', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->httpResponse = new Sabre_HTTP_ResponseMock(); $this->assertFalse($server->checkPreconditions(true)); - $this->assertEquals('HTTP/1.1 304 Not Modified',$server->httpResponse->status); - + $this->assertEquals('HTTP/1.1 304 Not Modified', $server->httpResponse->status); } /** * @covers Sabre_DAV_Server::checkPreconditions */ - public function testIfModifiedSinceUnModified() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfModifiedSinceUnModified() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 06 Nov 1994 08:49:37 GMT', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->httpResponse = new Sabre_HTTP_ResponseMock(); $this->assertFalse($server->checkPreconditions()); - $this->assertEquals('HTTP/1.1 304 Not Modified',$server->httpResponse->status); + $this->assertEquals('HTTP/1.1 304 Not Modified', $server->httpResponse->status); $this->assertEquals(array( 'Last-Modified' => 'Sat, 06 Apr 1985 23:30:00 GMT', ), $server->httpResponse->headers); - } - /** * @covers Sabre_DAV_Server::checkPreconditions */ - public function testIfModifiedSinceModified() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfModifiedSinceModified() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_MODIFIED_SINCE' => 'Tue, 06 Nov 1984 08:49:37 GMT', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->httpResponse = new Sabre_HTTP_ResponseMock(); $this->assertTrue($server->checkPreconditions()); - } /** * @covers Sabre_DAV_Server::checkPreconditions */ - public function testIfModifiedSinceInvalidDate() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfModifiedSinceInvalidDate() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_MODIFIED_SINCE' => 'Your mother', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->httpResponse = new Sabre_HTTP_ResponseMock(); // Invalid dates must be ignored, so this should return true $this->assertTrue($server->checkPreconditions()); - } /** * @covers Sabre_DAV_Server::checkPreconditions */ - public function testIfModifiedSinceInvalidDate2() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfModifiedSinceInvalidDate2() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_MODIFIED_SINCE' => 'Sun, 06 Nov 1994 08:49:37 EST', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->httpResponse = new Sabre_HTTP_ResponseMock(); $this->assertTrue($server->checkPreconditions()); - } - /** * @covers Sabre_DAV_Server::checkPreconditions */ - public function testIfUnmodifiedSinceUnModified() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfUnmodifiedSinceUnModified() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_UNMODIFIED_SINCE' => 'Sun, 06 Nov 1994 08:49:37 GMT', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $this->assertTrue($server->checkPreconditions()); - } - /** * @covers Sabre_DAV_Server::checkPreconditions * @expectedException Sabre_DAV_Exception_PreconditionFailed */ - public function testIfUnmodifiedSinceModified() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfUnmodifiedSinceModified() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_UNMODIFIED_SINCE' => 'Tue, 06 Nov 1984 08:49:37 GMT', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->httpResponse = new Sabre_HTTP_ResponseMock(); $server->checkPreconditions(); - } /** * @covers Sabre_DAV_Server::checkPreconditions */ - public function testIfUnmodifiedSinceInvalidDate() { - - $root = new Sabre_DAV_SimpleCollection('root',array(new Sabre_DAV_ServerPreconditionsNode())); + public function testIfUnmodifiedSinceInvalidDate() + { + $root = new Sabre_DAV_SimpleCollection('root', array(new Sabre_DAV_ServerPreconditionsNode())); $server = new Sabre_DAV_Server($root); $httpRequest = new Sabre_HTTP_Request(array( 'HTTP_IF_UNMODIFIED_SINCE' => 'Sun, 06 Nov 1984 08:49:37 CET', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', )); $server->httpRequest = $httpRequest; $server->httpResponse = new Sabre_HTTP_ResponseMock(); $this->assertTrue($server->checkPreconditions()); - } - - } -class Sabre_DAV_ServerPreconditionsNode extends Sabre_DAV_File { - - function getETag() { - +class Sabre_DAV_ServerPreconditionsNode extends Sabre_DAV_File +{ + public function getETag() + { return '"abc123"'; - } - function getLastModified() { + public function getLastModified() + { /* my birthday & time, I believe */ return strtotime('1985-04-07 01:30 +02:00'); - } - function getName() { - + public function getName() + { return 'foo'; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ServerPropsTest.php b/dav/SabreDAV/tests/Sabre/DAV/ServerPropsTest.php index 63a204cf..48257eeb 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ServerPropsTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ServerPropsTest.php @@ -3,38 +3,39 @@ require_once 'Sabre/HTTP/ResponseMock.php'; require_once 'Sabre/DAV/AbstractServer.php'; -class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { - - protected function getRootNode() { - +class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer +{ + protected function getRootNode() + { return new Sabre_DAV_FSExt_Directory(SABRE_TEMPDIR); - } - function setUp() { - - if (file_exists(SABRE_TEMPDIR.'../.sabredav')) unlink(SABRE_TEMPDIR.'../.sabredav'); + public function setUp() + { + if (file_exists(SABRE_TEMPDIR.'../.sabredav')) { + unlink(SABRE_TEMPDIR.'../.sabredav'); + } parent::setUp(); - file_put_contents(SABRE_TEMPDIR . '/test2.txt', 'Test contents2'); - mkdir(SABRE_TEMPDIR . '/col'); - file_put_contents(SABRE_TEMPDIR . 'col/test.txt', 'Test contents'); - $this->server->addPlugin(new Sabre_DAV_Locks_Plugin(new Sabre_DAV_Locks_Backend_File(SABRE_TEMPDIR . '/.locksdb'))); - + file_put_contents(SABRE_TEMPDIR.'/test2.txt', 'Test contents2'); + mkdir(SABRE_TEMPDIR.'/col'); + file_put_contents(SABRE_TEMPDIR.'col/test.txt', 'Test contents'); + $this->server->addPlugin(new Sabre_DAV_Locks_Plugin(new Sabre_DAV_Locks_Backend_File(SABRE_TEMPDIR.'/.locksdb'))); } - function tearDown() { - + public function tearDown() + { parent::tearDown(); - if (file_exists(SABRE_TEMPDIR.'../.locksdb')) unlink(SABRE_TEMPDIR.'../.locksdb'); - + if (file_exists(SABRE_TEMPDIR.'../.locksdb')) { + unlink(SABRE_TEMPDIR.'../.locksdb'); + } } - private function sendRequest($body) { - + private function sendRequest($body) + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'PROPFIND', - 'HTTP_DEPTH' => '0', + 'HTTP_DEPTH' => '0', ); $request = new Sabre_HTTP_Request($serverVars); @@ -42,14 +43,13 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = ($request); $this->server->exec(); - } - public function testPropFindEmptyBody() { + public function testPropFindEmptyBody() + { + $this->sendRequest(''); - $this->sendRequest(""); - - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status); $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', @@ -58,20 +58,19 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { $this->response->headers ); - $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/","xmlns\\1=\"DAV:\"",$this->response->body); + $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/", 'xmlns\\1="DAV:"', $this->response->body); $xml = simplexml_load_string($body); - $xml->registerXPathNamespace('d','DAV:'); + $xml->registerXPathNamespace('d', 'DAV:'); list($data) = $xml->xpath('/d:multistatus/d:response/d:href'); - $this->assertEquals('/',(string)$data,'href element should have been /'); + $this->assertEquals('/', (string) $data, 'href element should have been /'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:resourcetype'); - $this->assertEquals(1,count($data)); - + $this->assertEquals(1, count($data)); } - function testSupportedLocks() { - + public function testSupportedLocks() + { $xml = ' @@ -81,31 +80,31 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { $this->sendRequest($xml); - $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/","xmlns\\1=\"DAV:\"",$this->response->body); + $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/", 'xmlns\\1="DAV:"', $this->response->body); $xml = simplexml_load_string($body); - $xml->registerXPathNamespace('d','DAV:'); + $xml->registerXPathNamespace('d', 'DAV:'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supportedlock/d:lockentry'); - $this->assertEquals(2,count($data),'We expected two \'d:lockentry\' tags'); + $this->assertEquals(2, count($data), 'We expected two \'d:lockentry\' tags'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supportedlock/d:lockentry/d:lockscope'); - $this->assertEquals(2,count($data),'We expected two \'d:lockscope\' tags'); + $this->assertEquals(2, count($data), 'We expected two \'d:lockscope\' tags'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supportedlock/d:lockentry/d:locktype'); - $this->assertEquals(2,count($data),'We expected two \'d:locktype\' tags'); + $this->assertEquals(2, count($data), 'We expected two \'d:locktype\' tags'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supportedlock/d:lockentry/d:lockscope/d:shared'); - $this->assertEquals(1,count($data),'We expected a \'d:shared\' tag'); + $this->assertEquals(1, count($data), 'We expected a \'d:shared\' tag'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supportedlock/d:lockentry/d:lockscope/d:exclusive'); - $this->assertEquals(1,count($data),'We expected a \'d:exclusive\' tag'); + $this->assertEquals(1, count($data), 'We expected a \'d:exclusive\' tag'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:supportedlock/d:lockentry/d:locktype/d:write'); - $this->assertEquals(2,count($data),'We expected two \'d:write\' tags'); + $this->assertEquals(2, count($data), 'We expected two \'d:write\' tags'); } - function testLockDiscovery() { - + public function testLockDiscovery() + { $xml = ' @@ -115,17 +114,16 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { $this->sendRequest($xml); - $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/","xmlns\\1=\"DAV:\"",$this->response->body); + $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/", 'xmlns\\1="DAV:"', $this->response->body); $xml = simplexml_load_string($body); - $xml->registerXPathNamespace('d','DAV:'); + $xml->registerXPathNamespace('d', 'DAV:'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:lockdiscovery'); - $this->assertEquals(1,count($data),'We expected a \'d:lockdiscovery\' tag'); - + $this->assertEquals(1, count($data), 'We expected a \'d:lockdiscovery\' tag'); } - function testUnknownProperty() { - + public function testUnknownProperty() + { $xml = ' @@ -134,9 +132,9 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { '; $this->sendRequest($xml); - $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/","xmlns\\1=\"DAV:\"",$this->response->body); + $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/", 'xmlns\\1="DAV:"', $this->response->body); $xml = simplexml_load_string($body); - $xml->registerXPathNamespace('d','DAV:'); + $xml->registerXPathNamespace('d', 'DAV:'); $pathTests = array( '/d:multistatus', '/d:multistatus/d:response', @@ -145,21 +143,20 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { '/d:multistatus/d:response/d:propstat/d:prop', '/d:multistatus/d:response/d:propstat/d:prop/d:macaroni', ); - foreach($pathTests as $test) { - $this->assertTrue(count($xml->xpath($test))==true,'We expected the ' . $test . ' element to appear in the response, we got: ' . $body); + foreach ($pathTests as $test) { + $this->assertTrue(count($xml->xpath($test)) == true, 'We expected the '.$test.' element to appear in the response, we got: '.$body); } $val = $xml->xpath('/d:multistatus/d:response/d:propstat/d:status'); - $this->assertEquals(1,count($val),$body); - $this->assertEquals('HTTP/1.1 404 Not Found',(string)$val[0]); - + $this->assertEquals(1, count($val), $body); + $this->assertEquals('HTTP/1.1 404 Not Found', (string) $val[0]); } /** * @covers Sabre_DAV_Server::parsePropPatchRequest */ - public function testParsePropPatchRequest() { - + public function testParsePropPatchRequest() + { $body = ' somevalue @@ -174,54 +171,51 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { '{http://sabredav.org/NS/test}someprop2' => null, '{http://sabredav.org/NS/test}someprop3' => null, ), $result); - } /** * @covers Sabre_DAV_Server::updateProperties */ - public function testUpdateProperties() { - + public function testUpdateProperties() + { $props = array( '{http://sabredav.org/NS/test}someprop' => 'somevalue', ); - $result = $this->server->updateProperties('/test2.txt',$props); + $result = $this->server->updateProperties('/test2.txt', $props); $this->assertEquals(array( '200' => array('{http://sabredav.org/NS/test}someprop' => null), 'href' => '/test2.txt', ), $result); - } /** * @covers Sabre_DAV_Server::updateProperties * @depends testUpdateProperties */ - public function testUpdatePropertiesProtected() { - + public function testUpdatePropertiesProtected() + { $props = array( '{http://sabredav.org/NS/test}someprop' => 'somevalue', '{DAV:}getcontentlength' => 50, ); - $result = $this->server->updateProperties('/test2.txt',$props); + $result = $this->server->updateProperties('/test2.txt', $props); $this->assertEquals(array( '424' => array('{http://sabredav.org/NS/test}someprop' => null), '403' => array('{DAV:}getcontentlength' => null), 'href' => '/test2.txt', ), $result); - } /** * @covers Sabre_DAV_Server::updateProperties * @depends testUpdateProperties */ - public function testUpdatePropertiesFail1() { - + public function testUpdatePropertiesFail1() + { $dir = new Sabre_DAV_PropTestDirMock('updatepropsfalse'); $objectTree = new Sabre_DAV_ObjectTree($dir); $this->server->tree = $objectTree; @@ -230,21 +224,20 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { '{http://sabredav.org/NS/test}someprop' => 'somevalue', ); - $result = $this->server->updateProperties('/',$props); + $result = $this->server->updateProperties('/', $props); $this->assertEquals(array( '403' => array('{http://sabredav.org/NS/test}someprop' => null), 'href' => '/', ), $result); - } /** * @covers Sabre_DAV_Server::updateProperties * @depends testUpdateProperties */ - public function testUpdatePropertiesFail2() { - + public function testUpdatePropertiesFail2() + { $dir = new Sabre_DAV_PropTestDirMock('updatepropsarray'); $objectTree = new Sabre_DAV_ObjectTree($dir); $this->server->tree = $objectTree; @@ -253,13 +246,12 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { '{http://sabredav.org/NS/test}someprop' => 'somevalue', ); - $result = $this->server->updateProperties('/',$props); + $result = $this->server->updateProperties('/', $props); $this->assertEquals(array( '402' => array('{http://sabredav.org/NS/test}someprop' => null), 'href' => '/', ), $result); - } /** @@ -267,8 +259,8 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { * @depends testUpdateProperties * @expectedException Sabre_DAV_Exception */ - public function testUpdatePropertiesFail3() { - + public function testUpdatePropertiesFail3() + { $dir = new Sabre_DAV_PropTestDirMock('updatepropsobj'); $objectTree = new Sabre_DAV_ObjectTree($dir); $this->server->tree = $objectTree; @@ -277,8 +269,7 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { '{http://sabredav.org/NS/test}someprop' => 'somevalue', ); - $result = $this->server->updateProperties('/',$props); - + $result = $this->server->updateProperties('/', $props); } /** @@ -286,10 +277,10 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { * @depends testUpdateProperties * @covers Sabre_DAV_Server::httpPropPatch */ - public function testPropPatch() { - + public function testPropPatch() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'PROPPATCH', ); @@ -310,31 +301,30 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { $this->response->headers ); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'We got the wrong status. Full XML response: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'We got the wrong status. Full XML response: '.$this->response->body); - $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/","xmlns\\1=\"DAV:\"",$this->response->body); + $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/", 'xmlns\\1="DAV:"', $this->response->body); $xml = simplexml_load_string($body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('bla','http://www.rooftopsolutions.nl/testnamespace'); + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('bla', 'http://www.rooftopsolutions.nl/testnamespace'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop'); - $this->assertEquals(1,count($data),'We expected one \'d:prop\' element. Response body: ' . $body); + $this->assertEquals(1, count($data), 'We expected one \'d:prop\' element. Response body: '.$body); $data = $xml->xpath('//bla:someprop'); - $this->assertEquals(1,count($data),'We expected one \'s:someprop\' element. Response body: ' . $body); + $this->assertEquals(1, count($data), 'We expected one \'s:someprop\' element. Response body: '.$body); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:status'); - $this->assertEquals(1,count($data),'We expected one \'s:status\' element. Response body: ' . $body); - - $this->assertEquals('HTTP/1.1 200 OK',(string)$data[0]); + $this->assertEquals(1, count($data), 'We expected one \'s:status\' element. Response body: '.$body); + $this->assertEquals('HTTP/1.1 200 OK', (string) $data[0]); } /** * @depends testPropPatch */ - public function testPropPatchAndFetch() { - + public function testPropPatchAndFetch() + { $this->testPropPatch(); $xml = ' @@ -345,49 +335,46 @@ class Sabre_DAV_ServerPropsTest extends Sabre_DAV_AbstractServer { $this->sendRequest($xml); - $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/","xmlns\\1=\"DAV:\"",$this->response->body); + $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/", 'xmlns\\1="DAV:"', $this->response->body); $xml = simplexml_load_string($body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('bla','http://www.rooftopsolutions.nl/testnamespace'); + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('bla', 'http://www.rooftopsolutions.nl/testnamespace'); - $xpath='//bla:someprop'; + $xpath = '//bla:someprop'; $result = $xml->xpath($xpath); - $this->assertEquals(1,count($result),'We couldn\'t find our new property in the response. Full response body:' . "\n" . $body); - $this->assertEquals('somevalue',(string)$result[0],'We couldn\'t find our new property in the response. Full response body:' . "\n" . $body); - + $this->assertEquals(1, count($result), 'We couldn\'t find our new property in the response. Full response body:'."\n".$body); + $this->assertEquals('somevalue', (string) $result[0], 'We couldn\'t find our new property in the response. Full response body:'."\n".$body); } - } -class Sabre_DAV_PropTestDirMock extends Sabre_DAV_SimpleCollection implements Sabre_DAV_IProperties { - +class Sabre_DAV_PropTestDirMock extends Sabre_DAV_SimpleCollection implements Sabre_DAV_IProperties +{ public $type; - function __construct($type) { - - $this->type =$type; + public function __construct($type) + { + $this->type = $type; parent::__construct('root'); - } - function updateProperties($updateProperties) { - - switch($this->type) { - case 'updatepropsfalse' : return false; - case 'updatepropsarray' : + public function updateProperties($updateProperties) + { + switch ($this->type) { + case 'updatepropsfalse': return false; + case 'updatepropsarray': $r = array(402 => array()); - foreach($updateProperties as $k=>$v) $r[402][$k] = null; + foreach ($updateProperties as $k => $v) { + $r[402][$k] = null; + } + return $r; - case 'updatepropsobj' : + case 'updatepropsobj': return new STDClass(); } - } - function getProperties($requestedPropeties) { - + public function getProperties($requestedPropeties) + { return array(); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ServerRangeTest.php b/dav/SabreDAV/tests/Sabre/DAV/ServerRangeTest.php index 9426e1be..37fd4bee 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ServerRangeTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ServerRangeTest.php @@ -2,20 +2,19 @@ require_once 'Sabre/DAV/AbstractServer.php'; -class Sabre_DAV_ServerRangeTest extends Sabre_DAV_AbstractServer{ - - protected function getRootNode() { - +class Sabre_DAV_ServerRangeTest extends Sabre_DAV_AbstractServer +{ + protected function getRootNode() + { return new Sabre_DAV_FSExt_Directory(SABRE_TEMPDIR); - } - function testRange() { - + public function testRange() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', - 'HTTP_RANGE' => 'bytes=2-5', + 'HTTP_RANGE' => 'bytes=2-5', ); $request = new Sabre_HTTP_Request($serverVars); @@ -26,26 +25,25 @@ class Sabre_DAV_ServerRangeTest extends Sabre_DAV_AbstractServer{ 'Content-Type' => 'application/octet-stream', 'Content-Length' => 4, 'Content-Range' => 'bytes 2-5/13', - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), - 'ETag' => '"' . md5(file_get_contents(SABRE_TEMPDIR . '/test.txt')). '"', + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), + 'ETag' => '"'.md5(file_get_contents(SABRE_TEMPDIR.'/test.txt')).'"', ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 206 Partial Content',$this->response->status); + $this->assertEquals('HTTP/1.1 206 Partial Content', $this->response->status); $this->assertEquals('st c', stream_get_contents($this->response->body)); - } /** * @depends testRange */ - function testStartRange() { - + public function testStartRange() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', - 'HTTP_RANGE' => 'bytes=2-', + 'HTTP_RANGE' => 'bytes=2-', ); $request = new Sabre_HTTP_Request($serverVars); @@ -56,26 +54,25 @@ class Sabre_DAV_ServerRangeTest extends Sabre_DAV_AbstractServer{ 'Content-Type' => 'application/octet-stream', 'Content-Length' => 11, 'Content-Range' => 'bytes 2-12/13', - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), - 'ETag' => '"' . md5(file_get_contents(SABRE_TEMPDIR . '/test.txt')) . '"', + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), + 'ETag' => '"'.md5(file_get_contents(SABRE_TEMPDIR.'/test.txt')).'"', ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 206 Partial Content',$this->response->status); + $this->assertEquals('HTTP/1.1 206 Partial Content', $this->response->status); $this->assertEquals('st contents', stream_get_contents($this->response->body)); - } /** * @depends testRange */ - function testEndRange() { - + public function testEndRange() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', - 'HTTP_RANGE' => 'bytes=-8', + 'HTTP_RANGE' => 'bytes=-8', ); $request = new Sabre_HTTP_Request($serverVars); @@ -86,68 +83,65 @@ class Sabre_DAV_ServerRangeTest extends Sabre_DAV_AbstractServer{ 'Content-Type' => 'application/octet-stream', 'Content-Length' => 8, 'Content-Range' => 'bytes 5-12/13', - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), - 'ETag' => '"' . md5(file_get_contents(SABRE_TEMPDIR . '/test.txt')). '"', + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), + 'ETag' => '"'.md5(file_get_contents(SABRE_TEMPDIR.'/test.txt')).'"', ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 206 Partial Content',$this->response->status); + $this->assertEquals('HTTP/1.1 206 Partial Content', $this->response->status); $this->assertEquals('contents', stream_get_contents($this->response->body)); - } /** * @depends testRange */ - function testTooHighRange() { - + public function testTooHighRange() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', - 'HTTP_RANGE' => 'bytes=100-200', + 'HTTP_RANGE' => 'bytes=100-200', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 416 Requested Range Not Satisfiable',$this->response->status); - + $this->assertEquals('HTTP/1.1 416 Requested Range Not Satisfiable', $this->response->status); } /** * @depends testRange */ - function testCrazyRange() { - + public function testCrazyRange() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', - 'HTTP_RANGE' => 'bytes=8-4', + 'HTTP_RANGE' => 'bytes=8-4', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 416 Requested Range Not Satisfiable',$this->response->status); - + $this->assertEquals('HTTP/1.1 416 Requested Range Not Satisfiable', $this->response->status); } /** * @depends testRange * @covers Sabre_DAV_Server::httpGet */ - function testIfRangeEtag() { - + public function testIfRangeEtag() + { $node = $this->server->tree->getNodeForPath('test.txt'); $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', - 'HTTP_RANGE' => 'bytes=2-5', - 'HTTP_IF_RANGE' => $node->getETag(), + 'HTTP_RANGE' => 'bytes=2-5', + 'HTTP_IF_RANGE' => $node->getETag(), ); $request = new Sabre_HTTP_Request($serverVars); @@ -158,30 +152,29 @@ class Sabre_DAV_ServerRangeTest extends Sabre_DAV_AbstractServer{ 'Content-Type' => 'application/octet-stream', 'Content-Length' => 4, 'Content-Range' => 'bytes 2-5/13', - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), - 'ETag' => '"' . md5(file_get_contents(SABRE_TEMPDIR . '/test.txt')) . '"', + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), + 'ETag' => '"'.md5(file_get_contents(SABRE_TEMPDIR.'/test.txt')).'"', ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 206 Partial Content',$this->response->status); + $this->assertEquals('HTTP/1.1 206 Partial Content', $this->response->status); $this->assertEquals('st c', stream_get_contents($this->response->body)); - } /** * @depends testRange * @covers Sabre_DAV_Server::httpGet */ - function testIfRangeEtagIncorrect() { - + public function testIfRangeEtagIncorrect() + { $node = $this->server->tree->getNodeForPath('test.txt'); $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', - 'HTTP_RANGE' => 'bytes=2-5', - 'HTTP_IF_RANGE' => $node->getETag() . 'blabla', + 'HTTP_RANGE' => 'bytes=2-5', + 'HTTP_IF_RANGE' => $node->getETag().'blabla', ); $request = new Sabre_HTTP_Request($serverVars); @@ -191,30 +184,29 @@ class Sabre_DAV_ServerRangeTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/octet-stream', 'Content-Length' => 13, - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), - 'ETag' => '"' . md5(file_get_contents(SABRE_TEMPDIR . '/test.txt')) . '"', + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), + 'ETag' => '"'.md5(file_get_contents(SABRE_TEMPDIR.'/test.txt')).'"', ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('Test contents', stream_get_contents($this->response->body)); - } /** * @depends testRange * @covers Sabre_DAV_Server::httpGet */ - function testIfRangeModificationDate() { - + public function testIfRangeModificationDate() + { $node = $this->server->tree->getNodeForPath('test.txt'); $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', - 'HTTP_RANGE' => 'bytes=2-5', - 'HTTP_IF_RANGE' => 'tomorrow', + 'HTTP_RANGE' => 'bytes=2-5', + 'HTTP_IF_RANGE' => 'tomorrow', ); $request = new Sabre_HTTP_Request($serverVars); @@ -225,30 +217,29 @@ class Sabre_DAV_ServerRangeTest extends Sabre_DAV_AbstractServer{ 'Content-Type' => 'application/octet-stream', 'Content-Length' => 4, 'Content-Range' => 'bytes 2-5/13', - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), - 'ETag' => '"' . md5(file_get_contents(SABRE_TEMPDIR . '/test.txt')) . '"', + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), + 'ETag' => '"'.md5(file_get_contents(SABRE_TEMPDIR.'/test.txt')).'"', ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 206 Partial Content',$this->response->status); + $this->assertEquals('HTTP/1.1 206 Partial Content', $this->response->status); $this->assertEquals('st c', stream_get_contents($this->response->body)); - } /** * @depends testRange * @covers Sabre_DAV_Server::httpGet */ - function testIfRangeModificationDateModified() { - + public function testIfRangeModificationDateModified() + { $node = $this->server->tree->getNodeForPath('test.txt'); $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', - 'HTTP_RANGE' => 'bytes=2-5', - 'HTTP_IF_RANGE' => '-2 years', + 'HTTP_RANGE' => 'bytes=2-5', + 'HTTP_IF_RANGE' => '-2 years', ); $request = new Sabre_HTTP_Request($serverVars); @@ -258,14 +249,13 @@ class Sabre_DAV_ServerRangeTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/octet-stream', 'Content-Length' => 13, - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), - 'ETag' => '"' . md5(file_get_contents(SABRE_TEMPDIR . '/test.txt')) . '"', + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), + 'ETag' => '"'.md5(file_get_contents(SABRE_TEMPDIR.'/test.txt')).'"', ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('Test contents', stream_get_contents($this->response->body)); - } } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ServerSimpleTest.php b/dav/SabreDAV/tests/Sabre/DAV/ServerSimpleTest.php index 37f03e2b..fbd4618e 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ServerSimpleTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ServerSimpleTest.php @@ -4,46 +4,43 @@ require_once 'Sabre/HTTP/ResponseMock.php'; require_once 'Sabre/DAV/AbstractServer.php'; require_once 'Sabre/DAV/Exception.php'; -class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ - - function testConstructArray() { - +class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer +{ + public function testConstructArray() + { $nodes = array( - new Sabre_DAV_SimpleCollection('hello') + new Sabre_DAV_SimpleCollection('hello'), ); $server = new Sabre_DAV_Server($nodes); $this->assertEquals($nodes[0], $server->tree->getNodeForPath('hello')); - } /** * @expectedException Sabre_DAV_Exception */ - function testConstructIncorrectObj() { - + public function testConstructIncorrectObj() + { $nodes = array( new Sabre_DAV_SimpleCollection('hello'), new STDClass(), ); $server = new Sabre_DAV_Server($nodes); - } /** * @expectedException Sabre_DAV_Exception */ - function testConstructInvalidArg() { - + public function testConstructInvalidArg() + { $server = new Sabre_DAV_Server(1); - } - function testGet() { - + public function testGet() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'GET', ); @@ -54,54 +51,50 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/octet-stream', 'Content-Length' => 13, - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('Test contents', stream_get_contents($this->response->body)); - } - function testGetDoesntExist() { - + public function testGetDoesntExist() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt_randomblbla', + 'REQUEST_URI' => '/test.txt_randomblbla', 'REQUEST_METHOD' => 'GET', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 404 Not Found',$this->response->status); - + $this->assertEquals('HTTP/1.1 404 Not Found', $this->response->status); } - function testGetDoesntExist2() { - + public function testGetDoesntExist2() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt/randomblbla', + 'REQUEST_URI' => '/test.txt/randomblbla', 'REQUEST_METHOD' => 'GET', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 404 Not Found',$this->response->status); - + $this->assertEquals('HTTP/1.1 404 Not Found', $this->response->status); } /** * This test should have the exact same result as testGet. * * The idea is that double slashes // are converted to single ones / - * */ - function testGetDoubleSlash() { - + public function testGetDoubleSlash() + { $serverVars = array( - 'REQUEST_URI' => '//test.txt', + 'REQUEST_URI' => '//test.txt', 'REQUEST_METHOD' => 'GET', ); @@ -112,21 +105,19 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/octet-stream', 'Content-Length' => 13, - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('Test contents', stream_get_contents($this->response->body)); - } - - function testHEAD() { - + public function testHEAD() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'HEAD', ); @@ -137,20 +128,19 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/octet-stream', 'Content-Length' => 13, - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('', $this->response->body); - } - function testPut() { - + public function testPut() + { $serverVars = array( - 'REQUEST_URI' => '/testput.txt', + 'REQUEST_URI' => '/testput.txt', 'REQUEST_METHOD' => 'PUT', ); @@ -160,19 +150,18 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->server->exec(); $this->assertEquals('', $this->response->body); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals(array( - "Content-Length" => "0", + 'Content-Length' => '0', ), $this->response->headers); - $this->assertEquals('Testing new file',file_get_contents($this->tempDir . '/testput.txt')); - + $this->assertEquals('Testing new file', file_get_contents($this->tempDir.'/testput.txt')); } - function testPutAlreadyExists() { - + public function testPutAlreadyExists() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'PUT', 'HTTP_IF_NONE_MATCH' => '*', ); @@ -184,17 +173,16 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 412 Precondition failed',$this->response->status); - $this->assertNotEquals('Testing new file',file_get_contents($this->tempDir . '/test.txt')); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 412 Precondition failed', $this->response->status); + $this->assertNotEquals('Testing new file', file_get_contents($this->tempDir.'/test.txt')); } - function testPutUpdate() { - + public function testPutUpdate() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'PUT', ); @@ -205,16 +193,15 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->assertEquals('0', $this->response->headers['Content-Length']); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status); + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status); $this->assertEquals('', $this->response->body); - $this->assertEquals('Testing updated file',file_get_contents($this->tempDir . '/test.txt')); - + $this->assertEquals('Testing updated file', file_get_contents($this->tempDir.'/test.txt')); } - function testPutContentRange() { - + public function testPutContentRange() + { $serverVars = array( - 'REQUEST_URI' => '/testput.txt', + 'REQUEST_URI' => '/testput.txt', 'REQUEST_METHOD' => 'PUT', 'HTTP_CONTENT_RANGE' => 'bytes/100-200', ); @@ -224,15 +211,13 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 501 Not Implemented',$this->response->status); - + $this->assertEquals('HTTP/1.1 501 Not Implemented', $this->response->status); } - - function testDelete() { - + public function testDelete() + { $serverVars = array( - 'REQUEST_URI' => '/test.txt', + 'REQUEST_URI' => '/test.txt', 'REQUEST_METHOD' => 'DELETE', ); @@ -242,23 +227,22 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Length' => '0', - ),$this->response->headers); + ), $this->response->headers); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status); + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status); $this->assertEquals('', $this->response->body); - $this->assertFalse(file_exists($this->tempDir . '/test.txt')); - + $this->assertFalse(file_exists($this->tempDir.'/test.txt')); } - function testDeleteDirectory() { - + public function testDeleteDirectory() + { $serverVars = array( - 'REQUEST_URI' => '/testcol', + 'REQUEST_URI' => '/testcol', 'REQUEST_METHOD' => 'DELETE', ); mkdir($this->tempDir.'/testcol'); - file_put_contents($this->tempDir.'/testcol/test.txt','Hi! I\'m a file with a short lifespan'); + file_put_contents($this->tempDir.'/testcol/test.txt', 'Hi! I\'m a file with a short lifespan'); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = ($request); @@ -266,17 +250,16 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Length' => '0', - ),$this->response->headers); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status); $this->assertEquals('', $this->response->body); - $this->assertFalse(file_exists($this->tempDir . '/col')); - + $this->assertFalse(file_exists($this->tempDir.'/col')); } - function testOptions() { - + public function testOptions() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'OPTIONS', ); @@ -285,23 +268,21 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->server->exec(); $this->assertEquals(array( - 'DAV' => '1, 3, extended-mkcol', - 'MS-Author-Via' => 'DAV', - 'Allow' => 'OPTIONS, GET, HEAD, DELETE, PROPFIND, PUT, PROPPATCH, COPY, MOVE, REPORT', - 'Accept-Ranges' => 'bytes', + 'DAV' => '1, 3, extended-mkcol', + 'MS-Author-Via' => 'DAV', + 'Allow' => 'OPTIONS, GET, HEAD, DELETE, PROPFIND, PUT, PROPPATCH, COPY, MOVE, REPORT', + 'Accept-Ranges' => 'bytes', 'Content-Length' => '0', 'X-Sabre-Version' => Sabre_DAV_Version::VERSION, - ),$this->response->headers); + ), $this->response->headers); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('', $this->response->body); - - } - function testNonExistantMethod() { - + public function testNonExistantMethod() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'BLABLA', ); @@ -311,17 +292,15 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 501 Not Implemented',$this->response->status); - + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 501 Not Implemented', $this->response->status); } - function testGETOnCollection() { - + public function testGETOnCollection() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'GET', ); @@ -331,16 +310,15 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 501 Not Implemented',$this->response->status); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 501 Not Implemented', $this->response->status); } - function testHEADOnCollection() { - + public function testHEADOnCollection() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'HEAD', ); @@ -348,57 +326,53 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); - + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); } - function testBaseUri() { - + public function testBaseUri() + { $serverVars = array( - 'REQUEST_URI' => '/blabla/test.txt', + 'REQUEST_URI' => '/blabla/test.txt', 'REQUEST_METHOD' => 'GET', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->setBaseUri('/blabla/'); - $this->assertEquals('/blabla/',$this->server->getBaseUri()); + $this->assertEquals('/blabla/', $this->server->getBaseUri()); $this->server->httpRequest = ($request); $this->server->exec(); $this->assertEquals(array( 'Content-Type' => 'application/octet-stream', 'Content-Length' => 13, - 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@' . filemtime($this->tempDir . '/test.txt'))), + 'Last-Modified' => Sabre_HTTP_Util::toHTTPDate(new DateTime('@'.filemtime($this->tempDir.'/test.txt'))), ), $this->response->headers ); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals('Test contents', stream_get_contents($this->response->body)); - } - function testBaseUriAddSlash() { - + public function testBaseUriAddSlash() + { $tests = array( - '/' => '/', - '/foo' => '/foo/', - '/foo/' => '/foo/', - '/foo/bar' => '/foo/bar/', + '/' => '/', + '/foo' => '/foo/', + '/foo/' => '/foo/', + '/foo/bar' => '/foo/bar/', '/foo/bar/' => '/foo/bar/', ); - foreach($tests as $test=>$result) { + foreach ($tests as $test => $result) { $this->server->setBaseUri($test); $this->assertEquals($result, $this->server->getBaseUri()); - } - } - function testCalculateUri() { - + public function testCalculateUri() + { $uris = array( 'http://www.example.org/root/somepath', '/root/somepath', @@ -407,89 +381,73 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->server->setBaseUri('/root/'); - foreach($uris as $uri) { - - $this->assertEquals('somepath',$this->server->calculateUri($uri)); - + foreach ($uris as $uri) { + $this->assertEquals('somepath', $this->server->calculateUri($uri)); } $this->server->setBaseUri('/root'); - foreach($uris as $uri) { - - $this->assertEquals('somepath',$this->server->calculateUri($uri)); - + foreach ($uris as $uri) { + $this->assertEquals('somepath', $this->server->calculateUri($uri)); } $this->assertEquals('', $this->server->calculateUri('/root')); - } - function testCalculateUriSpecialChars() { - + public function testCalculateUriSpecialChars() + { $uris = array( 'http://www.example.org/root/%C3%A0fo%C3%B3', '/root/%C3%A0fo%C3%B3', - '/root/%C3%A0fo%C3%B3/' + '/root/%C3%A0fo%C3%B3/', ); $this->server->setBaseUri('/root/'); - foreach($uris as $uri) { - - $this->assertEquals("\xc3\xa0fo\xc3\xb3",$this->server->calculateUri($uri)); - + foreach ($uris as $uri) { + $this->assertEquals("\xc3\xa0fo\xc3\xb3", $this->server->calculateUri($uri)); } $this->server->setBaseUri('/root'); - foreach($uris as $uri) { - - $this->assertEquals("\xc3\xa0fo\xc3\xb3",$this->server->calculateUri($uri)); - + foreach ($uris as $uri) { + $this->assertEquals("\xc3\xa0fo\xc3\xb3", $this->server->calculateUri($uri)); } $this->server->setBaseUri('/'); - foreach($uris as $uri) { - - $this->assertEquals("root/\xc3\xa0fo\xc3\xb3",$this->server->calculateUri($uri)); - + foreach ($uris as $uri) { + $this->assertEquals("root/\xc3\xa0fo\xc3\xb3", $this->server->calculateUri($uri)); } - } - function testBaseUriCheck() { - + public function testBaseUriCheck() + { $uris = array( 'http://www.example.org/root/somepath', '/root/somepath', - '/root/somepath/' + '/root/somepath/', ); try { - $this->server->setBaseUri('root/'); $this->server->calculateUri('/root/testuri'); $this->fail('Expected an exception'); - } catch (Sabre_DAV_Exception_Forbidden $e) { // This was expected - } - } /** * @covers Sabre_DAV_Server::guessBaseUri */ - function testGuessBaseUri() { - + public function testGuessBaseUri() + { $serverVars = array( 'REQUEST_URI' => '/index.php/root', - 'PATH_INFO' => '/root', + 'PATH_INFO' => '/root', ); $httpRequest = new Sabre_HTTP_Request($serverVars); @@ -497,18 +455,17 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $server->httpRequest = $httpRequest; $this->assertEquals('/index.php/', $server->guessBaseUri()); - } /** * @depends testGuessBaseUri * @covers Sabre_DAV_Server::guessBaseUri */ - function testGuessBaseUriPercentEncoding() { - + public function testGuessBaseUriPercentEncoding() + { $serverVars = array( 'REQUEST_URI' => '/index.php/dir/path2/path%20with%20spaces', - 'PATH_INFO' => '/dir/path2/path with spaces', + 'PATH_INFO' => '/dir/path2/path with spaces', ); $httpRequest = new Sabre_HTTP_Request($serverVars); @@ -516,7 +473,6 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $server->httpRequest = $httpRequest; $this->assertEquals('/index.php/', $server->guessBaseUri()); - } /** @@ -540,11 +496,11 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ }*/ - function testGuessBaseUri2() { - + public function testGuessBaseUri2() + { $serverVars = array( 'REQUEST_URI' => '/index.php/root/', - 'PATH_INFO' => '/root/', + 'PATH_INFO' => '/root/', ); $httpRequest = new Sabre_HTTP_Request($serverVars); @@ -552,11 +508,10 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $server->httpRequest = $httpRequest; $this->assertEquals('/index.php/', $server->guessBaseUri()); - } - function testGuessBaseUriNoPathInfo() { - + public function testGuessBaseUriNoPathInfo() + { $serverVars = array( 'REQUEST_URI' => '/index.php/root', ); @@ -566,11 +521,10 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $server->httpRequest = $httpRequest; $this->assertEquals('/', $server->guessBaseUri()); - } - function testGuessBaseUriNoPathInfo2() { - + public function testGuessBaseUriNoPathInfo2() + { $serverVars = array( 'REQUEST_URI' => '/a/b/c/test.php', ); @@ -580,19 +534,17 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $server->httpRequest = $httpRequest; $this->assertEquals('/', $server->guessBaseUri()); - } - /** * @covers Sabre_DAV_Server::guessBaseUri * @depends testGuessBaseUri */ - function testGuessBaseUriQueryString() { - + public function testGuessBaseUriQueryString() + { $serverVars = array( 'REQUEST_URI' => '/index.php/root?query_string=blabla', - 'PATH_INFO' => '/root', + 'PATH_INFO' => '/root', ); $httpRequest = new Sabre_HTTP_Request($serverVars); @@ -600,32 +552,29 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $server->httpRequest = $httpRequest; $this->assertEquals('/index.php/', $server->guessBaseUri()); - } - function testTriggerException() { - - $this->server->subscribeEvent('beforeMethod',array($this,'exceptionTrigger')); + public function testTriggerException() + { + $this->server->subscribeEvent('beforeMethod', array($this, 'exceptionTrigger')); $this->server->exec(); $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - - $this->assertEquals('HTTP/1.1 500 Internal Server Error',$this->response->status); + ), $this->response->headers); + $this->assertEquals('HTTP/1.1 500 Internal Server Error', $this->response->status); } - function exceptionTrigger() { - + public function exceptionTrigger() + { throw new Sabre_DAV_Exception('Hola'); - } - function testReportNotFound() { - + public function testReportNotFound() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'REPORT', ); @@ -640,21 +589,20 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->response->headers ); - $this->assertEquals('HTTP/1.1 501 Not Implemented',$this->response->status,'We got an incorrect status back. Full response body follows: ' . $this->response->body); - + $this->assertEquals('HTTP/1.1 501 Not Implemented', $this->response->status, 'We got an incorrect status back. Full response body follows: '.$this->response->body); } - function testReportIntercepted() { - + public function testReportIntercepted() + { $serverVars = array( - 'REQUEST_URI' => '/', + 'REQUEST_URI' => '/', 'REQUEST_METHOD' => 'REPORT', ); $request = new Sabre_HTTP_Request($serverVars); $this->server->httpRequest = ($request); $this->server->httpRequest->setBody(''); - $this->server->subscribeEvent('report',array($this,'reportHandler')); + $this->server->subscribeEvent('report', array($this, 'reportHandler')); $this->server->exec(); $this->assertEquals(array( @@ -663,24 +611,24 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ $this->response->headers ); - $this->assertEquals('HTTP/1.1 418 I\'m a teapot',$this->response->status,'We got an incorrect status back. Full response body follows: ' . $this->response->body); - + $this->assertEquals('HTTP/1.1 418 I\'m a teapot', $this->response->status, 'We got an incorrect status back. Full response body follows: '.$this->response->body); } - function reportHandler($reportName) { - - if ($reportName=='{http://www.rooftopsolutions.nl/NS}myreport') { + public function reportHandler($reportName) + { + if ($reportName == '{http://www.rooftopsolutions.nl/NS}myreport') { $this->server->httpResponse->sendStatus(418); - $this->server->httpResponse->setHeader('testheader','testvalue'); - return false; - } - else return; + $this->server->httpResponse->setHeader('testheader', 'testvalue'); + return false; + } else { + return; + } } - function testGetPropertiesForChildren() { - - $result = $this->server->getPropertiesForChildren('',array( + public function testGetPropertiesForChildren() + { + $result = $this->server->getPropertiesForChildren('', array( '{DAV:}getcontentlength', )); @@ -689,8 +637,6 @@ class Sabre_DAV_ServerSimpleTest extends Sabre_DAV_AbstractServer{ 'dir/' => array(), ); - $this->assertEquals($expected,$result); - + $this->assertEquals($expected, $result); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/ServerUpdatePropertiesTest.php b/dav/SabreDAV/tests/Sabre/DAV/ServerUpdatePropertiesTest.php index 646f8ab9..9f9cd777 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/ServerUpdatePropertiesTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/ServerUpdatePropertiesTest.php @@ -1,16 +1,16 @@ updateProperties('foo', array( - '{DAV:}foo' => 'bar' + '{DAV:}foo' => 'bar', )); $expected = array( @@ -20,11 +20,10 @@ class Sabre_DAV_ServerUpdatePropertiesTest extends PHPUnit_Framework_TestCase { ), ); $this->assertEquals($expected, $result); - } - function testUpdatePropertiesProtected() { - + public function testUpdatePropertiesProtected() + { $tree = array( new Sabre_DAV_SimpleCollection('foo'), ); @@ -32,7 +31,7 @@ class Sabre_DAV_ServerUpdatePropertiesTest extends PHPUnit_Framework_TestCase { $result = $server->updateProperties('foo', array( '{DAV:}getetag' => 'bla', - '{DAV:}foo' => 'bar' + '{DAV:}foo' => 'bar', )); $expected = array( @@ -45,16 +44,15 @@ class Sabre_DAV_ServerUpdatePropertiesTest extends PHPUnit_Framework_TestCase { ), ); $this->assertEquals($expected, $result); - } - function testUpdatePropertiesEventFail() { - + public function testUpdatePropertiesEventFail() + { $tree = array( new Sabre_DAV_SimpleCollection('foo'), ); $server = new Sabre_DAV_Server($tree); - $server->subscribeEvent('updateProperties', array($this,'updatepropfail')); + $server->subscribeEvent('updateProperties', array($this, 'updatepropfail')); $result = $server->updateProperties('foo', array( '{DAV:}foo' => 'bar', @@ -71,27 +69,25 @@ class Sabre_DAV_ServerUpdatePropertiesTest extends PHPUnit_Framework_TestCase { ), ); $this->assertEquals($expected, $result); - } - function updatePropFail(&$propertyDelta, &$result, $node) { - + public function updatePropFail(&$propertyDelta, &$result, $node) + { $result[404] = array( '{DAV:}foo' => null, ); unset($propertyDelta['{DAV:}foo']); - return false; + return false; } - - function testUpdatePropertiesEventSuccess() { - + public function testUpdatePropertiesEventSuccess() + { $tree = array( new Sabre_DAV_SimpleCollection('foo'), ); $server = new Sabre_DAV_Server($tree); - $server->subscribeEvent('updateProperties', array($this,'updatepropsuccess')); + $server->subscribeEvent('updateProperties', array($this, 'updatepropsuccess')); $result = $server->updateProperties('foo', array( '{DAV:}foo' => 'bar', @@ -108,11 +104,10 @@ class Sabre_DAV_ServerUpdatePropertiesTest extends PHPUnit_Framework_TestCase { ), ); $this->assertEquals($expected, $result); - } - function updatePropSuccess(&$propertyDelta, &$result, $node) { - + public function updatePropSuccess(&$propertyDelta, &$result, $node) + { $result[200] = array( '{DAV:}foo' => null, ); @@ -121,7 +116,7 @@ class Sabre_DAV_ServerUpdatePropertiesTest extends PHPUnit_Framework_TestCase { ); unset($propertyDelta['{DAV:}foo']); unset($propertyDelta['{DAV:}foo2']); - return; + return; } } diff --git a/dav/SabreDAV/tests/Sabre/DAV/SimpleFileTest.php b/dav/SabreDAV/tests/Sabre/DAV/SimpleFileTest.php index a7bef38d..68e0c60f 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/SimpleFileTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/SimpleFileTest.php @@ -1,17 +1,15 @@ assertEquals('filename.txt', $file->getName()); $this->assertEquals('contents', $file->get()); $this->assertEquals('8', $file->getSize()); - $this->assertEquals('"' . md5('contents') . '"', $file->getETag()); + $this->assertEquals('"'.md5('contents').'"', $file->getETag()); $this->assertEquals('text/plain', $file->getContentType()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/StringUtilTest.php b/dav/SabreDAV/tests/Sabre/DAV/StringUtilTest.php index b87e79cd..bc7a8213 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/StringUtilTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/StringUtilTest.php @@ -1,18 +1,17 @@ assertEquals($result, Sabre_DAV_StringUtil::textMatch($haystack, $needle, $collation, $matchType)); - } - function dataset() { - + public function dataset() + { return array( array('FOOBAR', 'FOO', 'i;octet', 'contains', true), array('FOOBAR', 'foo', 'i;octet', 'contains', false), @@ -59,62 +58,54 @@ class Sabre_DAV_StringUtilTest extends PHPUnit_Framework_TestCase { array('FOOBAR', 'BAR', 'i;unicode-casemap', 'ends-with', true), array('FOOBAR', 'bar', 'i;unicode-casemap', 'ends-with', true), ); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - public function testBadCollation() { - - Sabre_DAV_StringUtil::textMatch('foobar','foo','blabla','contains'); - + public function testBadCollation() + { + Sabre_DAV_StringUtil::textMatch('foobar', 'foo', 'blabla', 'contains'); } - /** * @expectedException Sabre_DAV_Exception_BadRequest */ - public function testBadMatchType() { - - Sabre_DAV_StringUtil::textMatch('foobar','foo','i;octet','booh'); - + public function testBadMatchType() + { + Sabre_DAV_StringUtil::textMatch('foobar', 'foo', 'i;octet', 'booh'); } - public function testEnsureUTF8_ascii() { - - $inputString = "harkema"; - $outputString = "harkema"; + public function testEnsureUTF8_ascii() + { + $inputString = 'harkema'; + $outputString = 'harkema'; $this->assertEquals( $outputString, Sabre_DAV_StringUtil::ensureUTF8($inputString) ); - } - public function testEnsureUTF8_latin1() { - + public function testEnsureUTF8_latin1() + { $inputString = "m\xfcnster"; - $outputString = "münster"; + $outputString = 'münster'; $this->assertEquals( $outputString, Sabre_DAV_StringUtil::ensureUTF8($inputString) ); - } - public function testEnsureUTF8_utf8() { - + public function testEnsureUTF8_utf8() + { $inputString = "m\xc3\xbcnster"; - $outputString = "münster"; + $outputString = 'münster'; $this->assertEquals( $outputString, Sabre_DAV_StringUtil::ensureUTF8($inputString) ); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/TemporaryFileFilterTest.php b/dav/SabreDAV/tests/Sabre/DAV/TemporaryFileFilterTest.php index acd64380..ea917a6b 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/TemporaryFileFilterTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/TemporaryFileFilterTest.php @@ -1,19 +1,18 @@ server->addPlugin($plugin); - } - function testPutNormal() { - + public function testPutNormal() + { $serverVars = array( - 'REQUEST_URI' => '/testput.txt', + 'REQUEST_URI' => '/testput.txt', 'REQUEST_METHOD' => 'PUT', ); @@ -23,18 +22,18 @@ class Sabre_DAV_TemporaryFileFilterTest extends Sabre_DAV_AbstractServer { $this->server->exec(); $this->assertEquals('', $this->response->body); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals('0', $this->response->headers['Content-Length']); - $this->assertEquals('Testing new file',file_get_contents(SABRE_TEMPDIR . '/testput.txt')); - + $this->assertEquals('Testing new file', file_get_contents(SABRE_TEMPDIR.'/testput.txt')); } - function testPutTemp() { + public function testPutTemp() + { // mimicking an OS/X resource fork $serverVars = array( - 'REQUEST_URI' => '/._testput.txt', + 'REQUEST_URI' => '/._testput.txt', 'REQUEST_METHOD' => 'PUT', ); @@ -44,21 +43,21 @@ class Sabre_DAV_TemporaryFileFilterTest extends Sabre_DAV_AbstractServer { $this->server->exec(); $this->assertEquals('', $this->response->body); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals(array( 'X-Sabre-Temp' => 'true', - ),$this->response->headers); - - $this->assertFalse(file_exists(SABRE_TEMPDIR . '/._testput.txt'),'._testput.txt should not exist in the regular file structure.'); + ), $this->response->headers); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/._testput.txt'), '._testput.txt should not exist in the regular file structure.'); } - function testPutTempIfNoneMatch() { + public function testPutTempIfNoneMatch() + { // mimicking an OS/X resource fork $serverVars = array( - 'REQUEST_URI' => '/._testput.txt', - 'REQUEST_METHOD' => 'PUT', + 'REQUEST_URI' => '/._testput.txt', + 'REQUEST_METHOD' => 'PUT', 'HTTP_IF_NONE_MATCH' => '*', ); @@ -68,29 +67,28 @@ class Sabre_DAV_TemporaryFileFilterTest extends Sabre_DAV_AbstractServer { $this->server->exec(); $this->assertEquals('', $this->response->body); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals(array( 'X-Sabre-Temp' => 'true', - ),$this->response->headers); - - $this->assertFalse(file_exists(SABRE_TEMPDIR . '/._testput.txt'),'._testput.txt should not exist in the regular file structure.'); + ), $this->response->headers); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/._testput.txt'), '._testput.txt should not exist in the regular file structure.'); $this->server->exec(); - $this->assertEquals('HTTP/1.1 412 Precondition failed',$this->response->status); + $this->assertEquals('HTTP/1.1 412 Precondition failed', $this->response->status); $this->assertEquals(array( 'X-Sabre-Temp' => 'true', 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); - + ), $this->response->headers); } - function testPutGet() { + public function testPutGet() + { // mimicking an OS/X resource fork $serverVars = array( - 'REQUEST_URI' => '/._testput.txt', + 'REQUEST_URI' => '/._testput.txt', 'REQUEST_METHOD' => 'PUT', ); @@ -100,13 +98,13 @@ class Sabre_DAV_TemporaryFileFilterTest extends Sabre_DAV_AbstractServer { $this->server->exec(); $this->assertEquals('', $this->response->body); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals(array( 'X-Sabre-Temp' => 'true', - ),$this->response->headers); + ), $this->response->headers); $serverVars = array( - 'REQUEST_URI' => '/._testput.txt', + 'REQUEST_URI' => '/._testput.txt', 'REQUEST_METHOD' => 'GET', ); @@ -114,27 +112,26 @@ class Sabre_DAV_TemporaryFileFilterTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 200 OK',$this->response->status); + $this->assertEquals('HTTP/1.1 200 OK', $this->response->status); $this->assertEquals(array( 'X-Sabre-Temp' => 'true', 'Content-Length' => 16, 'Content-Type' => 'application/octet-stream', - ),$this->response->headers); - - $this->assertEquals('Testing new file',stream_get_contents($this->response->body)); + ), $this->response->headers); + $this->assertEquals('Testing new file', stream_get_contents($this->response->body)); } - function testLockNonExistant() { - - mkdir(SABRE_TEMPDIR . '/locksdir'); - $locksBackend = new Sabre_DAV_Locks_Backend_FS(SABRE_TEMPDIR . '/locksdir'); + public function testLockNonExistant() + { + mkdir(SABRE_TEMPDIR.'/locksdir'); + $locksBackend = new Sabre_DAV_Locks_Backend_FS(SABRE_TEMPDIR.'/locksdir'); $locksPlugin = new Sabre_DAV_Locks_Plugin($locksBackend); $this->server->addPlugin($locksPlugin); // mimicking an OS/X resource fork $serverVars = array( - 'REQUEST_URI' => '/._testlock.txt', + 'REQUEST_URI' => '/._testlock.txt', 'REQUEST_METHOD' => 'LOCK', ); @@ -152,20 +149,20 @@ class Sabre_DAV_TemporaryFileFilterTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); - $this->assertEquals('application/xml; charset=utf-8',$this->response->headers['Content-Type']); - $this->assertTrue(preg_match('/^$/',$this->response->headers['Lock-Token'])===1,'We did not get a valid Locktoken back (' . $this->response->headers['Lock-Token'] . ')'); - $this->assertEquals('true',$this->response->headers['X-Sabre-Temp']); - - $this->assertFalse(file_exists(SABRE_TEMPDIR . '/._testlock.txt'),'._testlock.txt should not exist in the regular file structure.'); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); + $this->assertEquals('application/xml; charset=utf-8', $this->response->headers['Content-Type']); + $this->assertTrue(preg_match('/^$/', $this->response->headers['Lock-Token']) === 1, 'We did not get a valid Locktoken back ('.$this->response->headers['Lock-Token'].')'); + $this->assertEquals('true', $this->response->headers['X-Sabre-Temp']); + $this->assertFalse(file_exists(SABRE_TEMPDIR.'/._testlock.txt'), '._testlock.txt should not exist in the regular file structure.'); } - function testPutDelete() { + public function testPutDelete() + { // mimicking an OS/X resource fork $serverVars = array( - 'REQUEST_URI' => '/._testput.txt', + 'REQUEST_URI' => '/._testput.txt', 'REQUEST_METHOD' => 'PUT', ); @@ -175,13 +172,13 @@ class Sabre_DAV_TemporaryFileFilterTest extends Sabre_DAV_AbstractServer { $this->server->exec(); $this->assertEquals('', $this->response->body); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals(array( 'X-Sabre-Temp' => 'true', - ),$this->response->headers); + ), $this->response->headers); $serverVars = array( - 'REQUEST_URI' => '/._testput.txt', + 'REQUEST_URI' => '/._testput.txt', 'REQUEST_METHOD' => 'DELETE', ); @@ -189,20 +186,20 @@ class Sabre_DAV_TemporaryFileFilterTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 204 No Content',$this->response->status, "Incorrect status code received. Full body:\n". $this->response->body); + $this->assertEquals('HTTP/1.1 204 No Content', $this->response->status, "Incorrect status code received. Full body:\n".$this->response->body); $this->assertEquals(array( 'X-Sabre-Temp' => 'true', - ),$this->response->headers); - - $this->assertEquals('',$this->response->body); + ), $this->response->headers); + $this->assertEquals('', $this->response->body); } - function testPutPropfind() { + public function testPutPropfind() + { // mimicking an OS/X resource fork $serverVars = array( - 'REQUEST_URI' => '/._testput.txt', + 'REQUEST_URI' => '/._testput.txt', 'REQUEST_METHOD' => 'PUT', ); @@ -212,13 +209,13 @@ class Sabre_DAV_TemporaryFileFilterTest extends Sabre_DAV_AbstractServer { $this->server->exec(); $this->assertEquals('', $this->response->body); - $this->assertEquals('HTTP/1.1 201 Created',$this->response->status); + $this->assertEquals('HTTP/1.1 201 Created', $this->response->status); $this->assertEquals(array( 'X-Sabre-Temp' => 'true', - ),$this->response->headers); + ), $this->response->headers); $serverVars = array( - 'REQUEST_URI' => '/._testput.txt', + 'REQUEST_URI' => '/._testput.txt', 'REQUEST_METHOD' => 'PROPFIND', ); @@ -227,22 +224,20 @@ class Sabre_DAV_TemporaryFileFilterTest extends Sabre_DAV_AbstractServer { $this->server->httpRequest = ($request); $this->server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status',$this->response->status,'Incorrect status code returned. Body: ' . $this->response->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $this->response->status, 'Incorrect status code returned. Body: '.$this->response->body); $this->assertEquals(array( 'X-Sabre-Temp' => 'true', 'Content-Type' => 'application/xml; charset=utf-8', - ),$this->response->headers); + ), $this->response->headers); - $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/","xmlns\\1=\"DAV:\"",$this->response->body); + $body = preg_replace("/xmlns(:[A-Za-z0-9_])?=(\"|\')DAV:(\"|\')/", 'xmlns\\1="DAV:"', $this->response->body); $xml = simplexml_load_string($body); - $xml->registerXPathNamespace('d','DAV:'); + $xml->registerXPathNamespace('d', 'DAV:'); list($data) = $xml->xpath('/d:multistatus/d:response/d:href'); - $this->assertEquals('/._testput.txt',(string)$data,'href element should have been /._testput.txt'); + $this->assertEquals('/._testput.txt', (string) $data, 'href element should have been /._testput.txt'); $data = $xml->xpath('/d:multistatus/d:response/d:propstat/d:prop/d:resourcetype'); - $this->assertEquals(1,count($data)); - + $this->assertEquals(1, count($data)); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/TestPlugin.php b/dav/SabreDAV/tests/Sabre/DAV/TestPlugin.php index cbd96d96..61eaeb4a 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/TestPlugin.php +++ b/dav/SabreDAV/tests/Sabre/DAV/TestPlugin.php @@ -1,32 +1,28 @@ subscribeEvent('beforeMethod',array($this,'beforeMethod')); - + public function initialize(Sabre_DAV_Server $server) + { + $server->subscribeEvent('beforeMethod', array($this, 'beforeMethod')); } - function beforeMethod($method) { - + public function beforeMethod($method) + { $this->beforeMethod = $method; + return true; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/Tree/FilesystemTest.php b/dav/SabreDAV/tests/Sabre/DAV/Tree/FilesystemTest.php index 67d5bbeb..09e7cfa7 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/Tree/FilesystemTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/Tree/FilesystemTest.php @@ -7,68 +7,59 @@ * @covers Sabre_DAV_FS_File * @covers Sabre_DAV_FS_Directory */ -class Sabre_DAV_Tree_FilesystemTest extends PHPUnit_Framework_TestCase { - - function setUp() { - +class Sabre_DAV_Tree_FilesystemTest extends PHPUnit_Framework_TestCase +{ + public function setUp() + { Sabre_TestUtil::clearTempDir(); - file_put_contents(SABRE_TEMPDIR. '/file.txt','Body'); + file_put_contents(SABRE_TEMPDIR.'/file.txt', 'Body'); mkdir(SABRE_TEMPDIR.'/dir'); - file_put_contents(SABRE_TEMPDIR.'/dir/subfile.txt','Body'); - + file_put_contents(SABRE_TEMPDIR.'/dir/subfile.txt', 'Body'); } - function tearDown() { - + public function tearDown() + { Sabre_TestUtil::clearTempDir(); - } - function testGetNodeForPath_File() { - + public function testGetNodeForPath_File() + { $fs = new Sabre_DAV_Tree_Filesystem(SABRE_TEMPDIR); $node = $fs->getNodeForPath('file.txt'); $this->assertTrue($node instanceof Sabre_DAV_FS_File); - } - function testGetNodeForPath_Directory() { - + public function testGetNodeForPath_Directory() + { $fs = new Sabre_DAV_Tree_Filesystem(SABRE_TEMPDIR); $node = $fs->getNodeForPath('dir'); $this->assertTrue($node instanceof Sabre_DAV_FS_Directory); $this->assertEquals('dir', $node->getName()); $this->assertInternalType('array', $node->getChildren()); - } - function testCopy() { - + public function testCopy() + { $fs = new Sabre_DAV_Tree_Filesystem(SABRE_TEMPDIR); - $fs->copy('file.txt','file2.txt'); - $this->assertTrue(file_exists(SABRE_TEMPDIR . '/file2.txt')); - $this->assertEquals('Body',file_get_contents(SABRE_TEMPDIR . '/file2.txt')); - + $fs->copy('file.txt', 'file2.txt'); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/file2.txt')); + $this->assertEquals('Body', file_get_contents(SABRE_TEMPDIR.'/file2.txt')); } - function testCopyDir() { - + public function testCopyDir() + { $fs = new Sabre_DAV_Tree_Filesystem(SABRE_TEMPDIR); - $fs->copy('dir','dir2'); - $this->assertTrue(file_exists(SABRE_TEMPDIR . '/dir2')); - $this->assertEquals('Body',file_get_contents(SABRE_TEMPDIR . '/dir2/subfile.txt')); - + $fs->copy('dir', 'dir2'); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/dir2')); + $this->assertEquals('Body', file_get_contents(SABRE_TEMPDIR.'/dir2/subfile.txt')); } - function testMove() { - + public function testMove() + { $fs = new Sabre_DAV_Tree_Filesystem(SABRE_TEMPDIR); - $fs->move('file.txt','file2.txt'); - $this->assertTrue(file_exists(SABRE_TEMPDIR . '/file2.txt')); - $this->assertTrue(!file_exists(SABRE_TEMPDIR . '/file.txt')); - $this->assertEquals('Body',file_get_contents(SABRE_TEMPDIR . '/file2.txt')); - + $fs->move('file.txt', 'file2.txt'); + $this->assertTrue(file_exists(SABRE_TEMPDIR.'/file2.txt')); + $this->assertTrue(!file_exists(SABRE_TEMPDIR.'/file.txt')); + $this->assertEquals('Body', file_get_contents(SABRE_TEMPDIR.'/file2.txt')); } - - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/TreeTest.php b/dav/SabreDAV/tests/Sabre/DAV/TreeTest.php index d0a8023b..f97501bd 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/TreeTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/TreeTest.php @@ -3,171 +3,158 @@ /** * @covers Sabre_DAV_Tree */ -class Sabre_DAV_TreeTest extends PHPUnit_Framework_TestCase { - - function testNodeExists() { - +class Sabre_DAV_TreeTest extends PHPUnit_Framework_TestCase +{ + public function testNodeExists() + { $tree = new Sabre_DAV_TreeMock(); $this->assertTrue($tree->nodeExists('hi')); $this->assertFalse($tree->nodeExists('hello')); - } - function testCopy() { - + public function testCopy() + { $tree = new Sabre_DAV_TreeMock(); - $tree->copy('hi','hi2'); + $tree->copy('hi', 'hi2'); $this->assertArrayHasKey('hi2', $tree->getNodeForPath('')->newDirectories); $this->assertEquals('foobar', $tree->getNodeForPath('hi/file')->get()); - $this->assertEquals(array('test1'=>'value'), $tree->getNodeForPath('hi/file')->getProperties(array())); - + $this->assertEquals(array('test1' => 'value'), $tree->getNodeForPath('hi/file')->getProperties(array())); } - function testMove() { - + public function testMove() + { $tree = new Sabre_DAV_TreeMock(); - $tree->move('hi','hi2'); + $tree->move('hi', 'hi2'); $this->assertEquals('hi2', $tree->getNodeForPath('hi')->getName()); $this->assertTrue($tree->getNodeForPath('hi')->isRenamed); - } - function testDeepMove() { - + public function testDeepMove() + { $tree = new Sabre_DAV_TreeMock(); - $tree->move('hi/sub','hi2'); + $tree->move('hi/sub', 'hi2'); $this->assertArrayHasKey('hi2', $tree->getNodeForPath('')->newDirectories); $this->assertTrue($tree->getNodeForPath('hi/sub')->isDeleted); - } - function testDelete() { - + public function testDelete() + { $tree = new Sabre_DAV_TreeMock(); $tree->delete('hi'); $this->assertTrue($tree->getNodeForPath('hi')->isDeleted); - } - function testGetChildren() { - + public function testGetChildren() + { $tree = new Sabre_DAV_TreeMock(); $children = $tree->getChildren(''); - $this->assertEquals(1,count($children)); + $this->assertEquals(1, count($children)); $this->assertEquals('hi', $children[0]->getName()); - } - } -class Sabre_DAV_TreeMock extends Sabre_DAV_Tree { - +class Sabre_DAV_TreeMock extends Sabre_DAV_Tree +{ private $nodes = array(); - function __construct() { - + public function __construct() + { $this->nodes['hi/sub'] = new Sabre_DAV_TreeDirectoryTester('sub'); $this->nodes['hi/file'] = new Sabre_DAV_TreeFileTester('file'); $this->nodes['hi/file']->properties = array('test1' => 'value'); $this->nodes['hi/file']->data = 'foobar'; - $this->nodes['hi'] = new Sabre_DAV_TreeDirectoryTester('hi',array($this->nodes['hi/sub'], $this->nodes['hi/file'])); + $this->nodes['hi'] = new Sabre_DAV_TreeDirectoryTester('hi', array($this->nodes['hi/sub'], $this->nodes['hi/file'])); $this->nodes[''] = new Sabre_DAV_TreeDirectoryTester('hi', array($this->nodes['hi'])); - } - function getNodeForPath($path) { - - if (isset($this->nodes[$path])) return $this->nodes[$path]; + public function getNodeForPath($path) + { + if (isset($this->nodes[$path])) { + return $this->nodes[$path]; + } throw new Sabre_DAV_Exception_NotFound('item not found'); - } - } -class Sabre_DAV_TreeDirectoryTester extends Sabre_DAV_SimpleCollection { - +class Sabre_DAV_TreeDirectoryTester extends Sabre_DAV_SimpleCollection +{ public $newDirectories = array(); public $newFiles = array(); public $isDeleted = false; public $isRenamed = false; - function createDirectory($name) { - + public function createDirectory($name) + { $this->newDirectories[$name] = true; - } - function createFile($name,$data = null) { - + public function createFile($name, $data = null) + { $this->newFiles[$name] = $data; - } - function getChild($name) { + public function getChild($name) + { + if (isset($this->newDirectories[$name])) { + return new self($name); + } + if (isset($this->newFiles[$name])) { + return new Sabre_DAV_TreeFileTester($name, $this->newFiles[$name]); + } - if (isset($this->newDirectories[$name])) return new Sabre_DAV_TreeDirectoryTester($name); - if (isset($this->newFiles[$name])) return new Sabre_DAV_TreeFileTester($name, $this->newFiles[$name]); return parent::getChild($name); - } - function delete() { - + public function delete() + { $this->isDeleted = true; - } - function setName($name) { - + public function setName($name) + { $this->isRenamed = true; $this->name = $name; - } - } -class Sabre_DAV_TreeFileTester extends Sabre_DAV_File implements Sabre_DAV_IProperties { - +class Sabre_DAV_TreeFileTester extends Sabre_DAV_File implements Sabre_DAV_IProperties +{ public $name; public $data; public $properties; - function __construct($name, $data = null) { - + public function __construct($name, $data = null) + { $this->name = $name; - if (is_null($data)) $data = 'bla'; + if (is_null($data)) { + $data = 'bla'; + } $this->data = $data; - } - function getName() { - + public function getName() + { return $this->name; - } - function get() { - + public function get() + { return $this->data; - } - function getProperties($properties) { - + public function getProperties($properties) + { return $this->properties; - } - function updateProperties($properties) { - + public function updateProperties($properties) + { $this->properties = $properties; + return true; - } - } - diff --git a/dav/SabreDAV/tests/Sabre/DAV/URLUtilTest.php b/dav/SabreDAV/tests/Sabre/DAV/URLUtilTest.php index 90b913dc..5b3826c9 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/URLUtilTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/URLUtilTest.php @@ -1,11 +1,13 @@ assertEquals($str,Sabre_DAV_URLUtil::decodePath($newStr)); - + $this->assertEquals($str, Sabre_DAV_URLUtil::decodePath($newStr)); } - function testEncodePathSegment() { - + public function testEncodePathSegment() + { $str = ''; - for($i=0;$i<128;$i++) $str.=chr($i); + for ($i = 0; $i < 128; ++$i) { + $str .= chr($i); + } $newStr = Sabre_DAV_URLUtil::encodePathSegment($str); @@ -38,92 +41,81 @@ class Sabre_DAV_URLUtilTest extends PHPUnit_Framework_TestCase{ '%10%11%12%13%14%15%16%17%18%19%1a%1b%1c%1d%1e%1f'. '%20%21%22%23%24%25%26%27()%2a%2b%2c-.%2f'. '0123456789%3a%3b%3c%3d%3e%3f'. - '%40ABCDEFGHIJKLMNO' . - 'PQRSTUVWXYZ%5b%5c%5d%5e_' . - '%60abcdefghijklmno' . + '%40ABCDEFGHIJKLMNO'. + 'PQRSTUVWXYZ%5b%5c%5d%5e_'. + '%60abcdefghijklmno'. 'pqrstuvwxyz%7b%7c%7d~%7f', $newStr); - $this->assertEquals($str,Sabre_DAV_URLUtil::decodePathSegment($newStr)); - + $this->assertEquals($str, Sabre_DAV_URLUtil::decodePathSegment($newStr)); } - function testDecode() { - + public function testDecode() + { $str = 'Hello%20Test+Test2.txt'; $newStr = Sabre_DAV_URLUtil::decodePath($str); - $this->assertEquals('Hello Test+Test2.txt',$newStr); - + $this->assertEquals('Hello Test+Test2.txt', $newStr); } /** * @depends testDecode */ - function testDecodeUmlaut() { - + public function testDecodeUmlaut() + { $str = 'Hello%C3%BC.txt'; $newStr = Sabre_DAV_URLUtil::decodePath($str); - $this->assertEquals("Hello\xC3\xBC.txt",$newStr); - + $this->assertEquals("Hello\xC3\xBC.txt", $newStr); } /** * @depends testDecodeUmlaut */ - function testDecodeUmlautLatin1() { - + public function testDecodeUmlautLatin1() + { $str = 'Hello%FC.txt'; $newStr = Sabre_DAV_URLUtil::decodePath($str); - $this->assertEquals("Hello\xC3\xBC.txt",$newStr); - + $this->assertEquals("Hello\xC3\xBC.txt", $newStr); } /** - * This testcase was sent by a bug reporter + * This testcase was sent by a bug reporter. * * @depends testDecode */ - function testDecodeAccentsWindows7() { - + public function testDecodeAccentsWindows7() + { $str = '/webdav/%C3%A0fo%C3%B3'; $newStr = Sabre_DAV_URLUtil::decodePath($str); - $this->assertEquals(strtolower($str),Sabre_DAV_URLUtil::encodePath($newStr)); - + $this->assertEquals(strtolower($str), Sabre_DAV_URLUtil::encodePath($newStr)); } - function testSplitPath() { - + public function testSplitPath() + { $strings = array( // input // expected result - '/foo/bar' => array('/foo','bar'), - '/foo/bar/' => array('/foo','bar'), - 'foo/bar/' => array('foo','bar'), - 'foo/bar' => array('foo','bar'), - 'foo/bar/baz' => array('foo/bar','baz'), - 'foo/bar/baz/' => array('foo/bar','baz'), - 'foo' => array('','foo'), - 'foo/' => array('','foo'), - '/foo/' => array('','foo'), - '/foo' => array('','foo'), - '' => array(null,null), + '/foo/bar' => array('/foo', 'bar'), + '/foo/bar/' => array('/foo', 'bar'), + 'foo/bar/' => array('foo', 'bar'), + 'foo/bar' => array('foo', 'bar'), + 'foo/bar/baz' => array('foo/bar', 'baz'), + 'foo/bar/baz/' => array('foo/bar', 'baz'), + 'foo' => array('', 'foo'), + 'foo/' => array('', 'foo'), + '/foo/' => array('', 'foo'), + '/foo' => array('', 'foo'), + '' => array(null, null), // UTF-8 - "/\xC3\xA0fo\xC3\xB3/bar" => array("/\xC3\xA0fo\xC3\xB3",'bar'), - "/\xC3\xA0foo/b\xC3\xBCr/" => array("/\xC3\xA0foo","b\xC3\xBCr"), - "foo/\xC3\xA0\xC3\xBCr" => array("foo","\xC3\xA0\xC3\xBCr"), + "/\xC3\xA0fo\xC3\xB3/bar" => array("/\xC3\xA0fo\xC3\xB3", 'bar'), + "/\xC3\xA0foo/b\xC3\xBCr/" => array("/\xC3\xA0foo", "b\xC3\xBCr"), + "foo/\xC3\xA0\xC3\xBCr" => array('foo', "\xC3\xA0\xC3\xBCr"), ); - foreach($strings as $input => $expected) { - + foreach ($strings as $input => $expected) { $output = Sabre_DAV_URLUtil::splitPath($input); - $this->assertEquals($expected, $output, 'The expected output for \'' . $input . '\' was incorrect'); - - + $this->assertEquals($expected, $output, 'The expected output for \''.$input.'\' was incorrect'); } - - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/UUIDUtilTest.php b/dav/SabreDAV/tests/Sabre/DAV/UUIDUtilTest.php index 613461b3..d65affd3 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/UUIDUtilTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/UUIDUtilTest.php @@ -1,9 +1,9 @@ assertTrue( Sabre_DAV_UUIDUtil::validateUUID('11111111-2222-3333-4444-555555555555') ); @@ -16,8 +16,5 @@ class Sabre_DAV_UUIDUtilTest extends PHPUnit_Framework_TestCase { $this->assertFalse( Sabre_DAV_UUIDUtil::validateUUID('fffffffg-2222-3333-4444-555555555555') ); - - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAV/XMLUtilTest.php b/dav/SabreDAV/tests/Sabre/DAV/XMLUtilTest.php index f7fcbb68..cc615dc7 100644 --- a/dav/SabreDAV/tests/Sabre/DAV/XMLUtilTest.php +++ b/dav/SabreDAV/tests/Sabre/DAV/XMLUtilTest.php @@ -1,9 +1,9 @@ loadXML('Testdoc'); @@ -11,11 +11,10 @@ class Sabre_DAV_XMLUtilTest extends PHPUnit_Framework_TestCase { '{http://www.example.org/}test1', Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild) ); - } - function testToClarkNotation2() { - + public function testToClarkNotation2() + { $dom = new DOMDocument(); $dom->loadXML('Testdoc'); @@ -23,11 +22,10 @@ class Sabre_DAV_XMLUtilTest extends PHPUnit_Framework_TestCase { '{http://www.example.org/}test1', Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild) ); - } - function testToClarkNotationDAVNamespace() { - + public function testToClarkNotationDAVNamespace() + { $dom = new DOMDocument(); $dom->loadXML('Testdoc'); @@ -35,64 +33,57 @@ class Sabre_DAV_XMLUtilTest extends PHPUnit_Framework_TestCase { '{DAV:}test1', Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild) ); - } - function testToClarkNotationNoElem() { - + public function testToClarkNotationNoElem() + { $dom = new DOMDocument(); $dom->loadXML('Testdoc'); $this->assertNull( Sabre_DAV_XMLUtil::toClarkNotation($dom->firstChild->firstChild) ); - } - function testLoadDOMDocument() { - - $xml=''; + public function testLoadDOMDocument() + { + $xml = ''; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); $this->assertTrue($dom instanceof DOMDocument); - } /** * @depends testLoadDOMDocument * @expectedException Sabre_DAV_Exception_BadRequest */ - function testLoadDOMDocumentEmpty() { - + public function testLoadDOMDocumentEmpty() + { Sabre_DAV_XMLUtil::loadDOMDocument(''); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testLoadDOMDocumentInvalid() { - - $xml='assertEquals('blabla',$dom->firstChild->nodeValue); - + $this->assertEquals('blabla', $dom->firstChild->nodeValue); } - - function testParseProperties() { - - $xml=' + public function testParseProperties() + { + $xml = ' Calendars @@ -105,17 +96,14 @@ class Sabre_DAV_XMLUtilTest extends PHPUnit_Framework_TestCase { $this->assertEquals(array( '{DAV:}displayname' => 'Calendars', ), $properties); - - - } /** * @depends testParseProperties */ - function testParsePropertiesEmpty() { - - $xml=' + public function testParsePropertiesEmpty() + { + $xml = ' Calendars @@ -130,18 +118,16 @@ class Sabre_DAV_XMLUtilTest extends PHPUnit_Framework_TestCase { $this->assertEquals(array( '{DAV:}displayname' => 'Calendars', - '{http://www.rooftopsolutions.nl/example}example' => null + '{http://www.rooftopsolutions.nl/example}example' => null, ), $properties); - } - /** * @depends testParseProperties */ - function testParsePropertiesComplex() { - - $xml=' + public function testParsePropertiesComplex() + { + $xml = ' Calendars @@ -156,18 +142,16 @@ class Sabre_DAV_XMLUtilTest extends PHPUnit_Framework_TestCase { $this->assertEquals(array( '{DAV:}displayname' => 'Calendars', - '{DAV:}someprop' => 'Complex value right here', + '{DAV:}someprop' => 'Complex value right here', ), $properties); - } - /** * @depends testParseProperties */ - function testParsePropertiesNoProperties() { - - $xml=' + public function testParsePropertiesNoProperties() + { + $xml = ' @@ -177,12 +161,11 @@ class Sabre_DAV_XMLUtilTest extends PHPUnit_Framework_TestCase { $properties = Sabre_DAV_XMLUtil::parseProperties($dom->firstChild); $this->assertEquals(array(), $properties); - } - function testParsePropertiesMapHref() { - - $xml=' + public function testParsePropertiesMapHref() + { + $xml = ' Calendars @@ -193,17 +176,16 @@ class Sabre_DAV_XMLUtilTest extends PHPUnit_Framework_TestCase { '; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); - $properties = Sabre_DAV_XMLUtil::parseProperties($dom->firstChild,array('{DAV:}someprop'=>'Sabre_DAV_Property_Href')); + $properties = Sabre_DAV_XMLUtil::parseProperties($dom->firstChild, array('{DAV:}someprop' => 'Sabre_DAV_Property_Href')); $this->assertEquals(array( '{DAV:}displayname' => 'Calendars', - '{DAV:}someprop' => new Sabre_DAV_Property_Href('http://sabredav.org/',false), + '{DAV:}someprop' => new Sabre_DAV_Property_Href('http://sabredav.org/', false), ), $properties); - } - function testParseClarkNotation() { - + public function testParseClarkNotation() + { $this->assertEquals(array( 'DAV:', 'foo', @@ -218,11 +200,8 @@ class Sabre_DAV_XMLUtilTest extends PHPUnit_Framework_TestCase { /** * @expectedException InvalidArgumentException */ - function testParseClarkNotationFail() { - + public function testParseClarkNotationFail() + { Sabre_DAV_XMLUtil::parseClarkNotation('}foo'); - } - } - diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/ACLMethodTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/ACLMethodTest.php index 4b492012..520616b2 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/ACLMethodTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/ACLMethodTest.php @@ -1,37 +1,35 @@ addPlugin($acl); - $acl->unknownMethod('ACL','test'); - + $acl->unknownMethod('ACL', 'test'); } - function testCallbackPassthru() { - + public function testCallbackPassthru() + { $acl = new Sabre_DAVACL_Plugin(); $server = new Sabre_DAV_Server(); $server->addPlugin($acl); - $this->assertNull($acl->unknownMethod('FOO','test')); - + $this->assertNull($acl->unknownMethod('FOO', 'test')); } /** - /** + /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - function testNotSupportedByNode() { - + public function testNotSupportedByNode() + { $tree = array( new Sabre_DAV_SimpleCollection('test'), ); @@ -45,13 +43,12 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { $server->addPlugin($acl); $acl->httpACL('test'); - } - function testSuccessSimple() { - + public function testSuccessSimple() + { $tree = array( - new Sabre_DAVACL_MockACLNode('test',array()), + new Sabre_DAVACL_MockACLNode('test', array()), ); $acl = new Sabre_DAVACL_Plugin(); $server = new Sabre_DAV_Server($tree); @@ -63,16 +60,15 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { $server->addPlugin($acl); $this->assertNull($acl->httpACL('test')); - } /** * @expectedException Sabre_DAVACL_Exception_NotRecognizedPrincipal */ - function testUnrecognizedPrincipal() { - + public function testUnrecognizedPrincipal() + { $tree = array( - new Sabre_DAVACL_MockACLNode('test',array()), + new Sabre_DAVACL_MockACLNode('test', array()), ); $acl = new Sabre_DAVACL_Plugin(); $server = new Sabre_DAV_Server($tree); @@ -88,17 +84,16 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { $server->addPlugin($acl); $acl->httpACL('test'); - } /** * @expectedException Sabre_DAVACL_Exception_NotRecognizedPrincipal */ - function testUnrecognizedPrincipal2() { - + public function testUnrecognizedPrincipal2() + { $tree = array( - new Sabre_DAVACL_MockACLNode('test',array()), - new Sabre_DAV_SimpleCollection('principals',array( + new Sabre_DAVACL_MockACLNode('test', array()), + new Sabre_DAV_SimpleCollection('principals', array( new Sabre_DAV_SimpleCollection('notaprincipal'), )), ); @@ -116,16 +111,15 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { $server->addPlugin($acl); $acl->httpACL('test'); - } /** * @expectedException Sabre_DAVACL_Exception_NotSupportedPrivilege */ - function testUnknownPrivilege() { - + public function testUnknownPrivilege() + { $tree = array( - new Sabre_DAVACL_MockACLNode('test',array()), + new Sabre_DAVACL_MockACLNode('test', array()), ); $acl = new Sabre_DAVACL_Plugin(); $server = new Sabre_DAV_Server($tree); @@ -141,16 +135,15 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { $server->addPlugin($acl); $acl->httpACL('test'); - } /** * @expectedException Sabre_DAVACL_Exception_NoAbstract */ - function testAbstractPrivilege() { - + public function testAbstractPrivilege() + { $tree = array( - new Sabre_DAVACL_MockACLNode('test',array()), + new Sabre_DAVACL_MockACLNode('test', array()), ); $acl = new Sabre_DAVACL_Plugin(); $server = new Sabre_DAV_Server($tree); @@ -166,14 +159,13 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { $server->addPlugin($acl); $acl->httpACL('test'); - } /** * @expectedException Sabre_DAVACL_Exception_AceConflict */ - function testUpdateProtectedPrivilege() { - + public function testUpdateProtectedPrivilege() + { $oldACL = array( array( 'principal' => 'principals/notfound', @@ -183,7 +175,7 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { ); $tree = array( - new Sabre_DAVACL_MockACLNode('test',$oldACL), + new Sabre_DAVACL_MockACLNode('test', $oldACL), ); $acl = new Sabre_DAVACL_Plugin(); $server = new Sabre_DAV_Server($tree); @@ -199,14 +191,13 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { $server->addPlugin($acl); $acl->httpACL('test'); - } /** * @expectedException Sabre_DAVACL_Exception_AceConflict */ - function testUpdateProtectedPrivilege2() { - + public function testUpdateProtectedPrivilege2() + { $oldACL = array( array( 'principal' => 'principals/notfound', @@ -216,7 +207,7 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { ); $tree = array( - new Sabre_DAVACL_MockACLNode('test',$oldACL), + new Sabre_DAVACL_MockACLNode('test', $oldACL), ); $acl = new Sabre_DAVACL_Plugin(); $server = new Sabre_DAV_Server($tree); @@ -232,14 +223,13 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { $server->addPlugin($acl); $acl->httpACL('test'); - } /** * @expectedException Sabre_DAVACL_Exception_AceConflict */ - function testUpdateProtectedPrivilege3() { - + public function testUpdateProtectedPrivilege3() + { $oldACL = array( array( 'principal' => 'principals/notfound', @@ -249,7 +239,7 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { ); $tree = array( - new Sabre_DAVACL_MockACLNode('test',$oldACL), + new Sabre_DAVACL_MockACLNode('test', $oldACL), ); $acl = new Sabre_DAVACL_Plugin(); $server = new Sabre_DAV_Server($tree); @@ -265,11 +255,10 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { $server->addPlugin($acl); $acl->httpACL('test'); - } - function testSuccessComplex () { - + public function testSuccessComplex() + { $oldACL = array( array( 'principal' => 'principals/foo', @@ -283,10 +272,10 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { ); $tree = array( - $node = new Sabre_DAVACL_MockACLNode('test',$oldACL), + $node = new Sabre_DAVACL_MockACLNode('test', $oldACL), new Sabre_DAV_SimpleCollection('principals', array( - new Sabre_DAVACL_MockPrincipal('foo','principals/foo'), - new Sabre_DAVACL_MockPrincipal('baz','principals/baz'), + new Sabre_DAVACL_MockPrincipal('foo', 'principals/foo'), + new Sabre_DAVACL_MockPrincipal('baz', 'principals/baz'), )), ); $acl = new Sabre_DAVACL_Plugin(); @@ -307,7 +296,7 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { $server->httpRequest->setBody($body); $server->addPlugin($acl); - $this->assertFalse($acl->unknownMethod('ACL','test')); + $this->assertFalse($acl->unknownMethod('ACL', 'test')); $this->assertEquals(array( array( @@ -321,6 +310,5 @@ class Sabre_DAVACL_ACLMethodTest extends PHPUnit_Framework_TestCase { 'protected' => false, ), ), $node->getACL()); - } } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/AllowAccessTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/AllowAccessTest.php index 34236944..f6f53c3f 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/AllowAccessTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/AllowAccessTest.php @@ -1,14 +1,14 @@ allowAccessToNodesWithoutACL = true; $this->server->addPlugin($aclPlugin); - } - function testGet() { - - $this->assertTrue($this->server->broadcastEvent('beforeMethod',array('GET','testdir'))); - + public function testGet() + { + $this->assertTrue($this->server->broadcastEvent('beforeMethod', array('GET', 'testdir'))); } - function testGetDoesntExist() { - - $r = $this->server->broadcastEvent('beforeMethod',array('GET','foo')); + public function testGetDoesntExist() + { + $r = $this->server->broadcastEvent('beforeMethod', array('GET', 'foo')); $this->assertTrue($r); - } - function testHEAD() { - - $this->assertTrue($this->server->broadcastEvent('beforeMethod',array('HEAD','testdir'))); - + public function testHEAD() + { + $this->assertTrue($this->server->broadcastEvent('beforeMethod', array('HEAD', 'testdir'))); } - function testOPTIONS() { - - $this->assertTrue($this->server->broadcastEvent('beforeMethod',array('OPTIONS','testdir'))); - + public function testOPTIONS() + { + $this->assertTrue($this->server->broadcastEvent('beforeMethod', array('OPTIONS', 'testdir'))); } - function testPUT() { - - $this->assertTrue($this->server->broadcastEvent('beforeMethod',array('PUT','testdir'))); - + public function testPUT() + { + $this->assertTrue($this->server->broadcastEvent('beforeMethod', array('PUT', 'testdir'))); } - function testACL() { - - $this->assertTrue($this->server->broadcastEvent('beforeMethod',array('ACL','testdir'))); - + public function testACL() + { + $this->assertTrue($this->server->broadcastEvent('beforeMethod', array('ACL', 'testdir'))); } - function testPROPPATCH() { - - $this->assertTrue($this->server->broadcastEvent('beforeMethod',array('PROPPATCH','testdir'))); - + public function testPROPPATCH() + { + $this->assertTrue($this->server->broadcastEvent('beforeMethod', array('PROPPATCH', 'testdir'))); } - function testCOPY() { - - $this->assertTrue($this->server->broadcastEvent('beforeMethod',array('COPY','testdir'))); - + public function testCOPY() + { + $this->assertTrue($this->server->broadcastEvent('beforeMethod', array('COPY', 'testdir'))); } - function testMOVE() { - - $this->assertTrue($this->server->broadcastEvent('beforeMethod',array('MOVE','testdir'))); - + public function testMOVE() + { + $this->assertTrue($this->server->broadcastEvent('beforeMethod', array('MOVE', 'testdir'))); } - function testLOCK() { - - $this->assertTrue($this->server->broadcastEvent('beforeMethod',array('LOCK','testdir'))); - + public function testLOCK() + { + $this->assertTrue($this->server->broadcastEvent('beforeMethod', array('LOCK', 'testdir'))); } - function testBeforeBind() { - - $this->assertTrue($this->server->broadcastEvent('beforeBind',array('testdir/file'))); - + public function testBeforeBind() + { + $this->assertTrue($this->server->broadcastEvent('beforeBind', array('testdir/file'))); } - - function testBeforeUnbind() { - - $this->assertTrue($this->server->broadcastEvent('beforeUnbind',array('testdir'))); - + public function testBeforeUnbind() + { + $this->assertTrue($this->server->broadcastEvent('beforeUnbind', array('testdir'))); } - function testAfterGetProperties() { - + public function testAfterGetProperties() + { $properties = array( 'href' => 'foo', '200' => array( @@ -124,11 +110,9 @@ class Sabre_DAVACL_AllowAccessTest extends PHPUnit_Framework_TestCase { ), ); - $r = $this->server->broadcastEvent('afterGetProperties',array('testdir',&$properties)); + $r = $this->server->broadcastEvent('afterGetProperties', array('testdir', &$properties)); $this->assertTrue($r); $this->assertEquals($expected, $properties); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/BlockAccessTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/BlockAccessTest.php index a1f6ab12..a9654511 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/BlockAccessTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/BlockAccessTest.php @@ -1,15 +1,15 @@ plugin = new Sabre_DAVACL_Plugin(); $this->plugin->allowAccessToNodesWithoutACL = false; $this->server->addPlugin($this->plugin); - } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testGet() { - - $this->server->broadcastEvent('beforeMethod',array('GET','testdir')); - + public function testGet() + { + $this->server->broadcastEvent('beforeMethod', array('GET', 'testdir')); } - function testGetDoesntExist() { - - $r = $this->server->broadcastEvent('beforeMethod',array('GET','foo')); + public function testGetDoesntExist() + { + $r = $this->server->broadcastEvent('beforeMethod', array('GET', 'foo')); $this->assertTrue($r); - } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testHEAD() { - - $this->server->broadcastEvent('beforeMethod',array('HEAD','testdir')); - + public function testHEAD() + { + $this->server->broadcastEvent('beforeMethod', array('HEAD', 'testdir')); } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testOPTIONS() { - - $this->server->broadcastEvent('beforeMethod',array('OPTIONS','testdir')); - + public function testOPTIONS() + { + $this->server->broadcastEvent('beforeMethod', array('OPTIONS', 'testdir')); } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testPUT() { - - $this->server->broadcastEvent('beforeMethod',array('PUT','testdir')); - + public function testPUT() + { + $this->server->broadcastEvent('beforeMethod', array('PUT', 'testdir')); } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testPROPPATCH() { - - $this->server->broadcastEvent('beforeMethod',array('PROPPATCH','testdir')); - + public function testPROPPATCH() + { + $this->server->broadcastEvent('beforeMethod', array('PROPPATCH', 'testdir')); } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testCOPY() { - - $this->server->broadcastEvent('beforeMethod',array('COPY','testdir')); - + public function testCOPY() + { + $this->server->broadcastEvent('beforeMethod', array('COPY', 'testdir')); } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testMOVE() { - - $this->server->broadcastEvent('beforeMethod',array('MOVE','testdir')); - + public function testMOVE() + { + $this->server->broadcastEvent('beforeMethod', array('MOVE', 'testdir')); } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testACL() { - - $this->server->broadcastEvent('beforeMethod',array('ACL','testdir')); - + public function testACL() + { + $this->server->broadcastEvent('beforeMethod', array('ACL', 'testdir')); } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testLOCK() { - - $this->server->broadcastEvent('beforeMethod',array('LOCK','testdir')); - + public function testLOCK() + { + $this->server->broadcastEvent('beforeMethod', array('LOCK', 'testdir')); } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testBeforeBind() { - - $this->server->broadcastEvent('beforeBind',array('testdir/file')); - + public function testBeforeBind() + { + $this->server->broadcastEvent('beforeBind', array('testdir/file')); } /** * @expectedException Sabre_DAVACL_Exception_NeedPrivileges */ - function testBeforeUnbind() { - - $this->server->broadcastEvent('beforeUnbind',array('testdir')); - + public function testBeforeUnbind() + { + $this->server->broadcastEvent('beforeUnbind', array('testdir')); } - function testBeforeGetProperties() { - + public function testBeforeGetProperties() + { $requestedProperties = array( '{DAV:}displayname', '{DAV:}getcontentlength', @@ -141,9 +128,9 @@ class Sabre_DAVACL_BlockAccessTest extends PHPUnit_Framework_TestCase { 'testdir', new Sabre_DAV_SimpleCollection('testdir'), &$requestedProperties, - &$returnedProperties + &$returnedProperties, ); - $r = $this->server->broadcastEvent('beforeGetProperties',$arguments); + $r = $this->server->broadcastEvent('beforeGetProperties', $arguments); $this->assertTrue($r); $expected = array( @@ -157,11 +144,10 @@ class Sabre_DAVACL_BlockAccessTest extends PHPUnit_Framework_TestCase { $this->assertEquals($expected, $returnedProperties); $this->assertEquals(array(), $requestedProperties); - } - function testBeforeGetPropertiesNoListing() { - + public function testBeforeGetPropertiesNoListing() + { $this->plugin->hideNodesFromListings = true; $requestedProperties = array( @@ -176,10 +162,9 @@ class Sabre_DAVACL_BlockAccessTest extends PHPUnit_Framework_TestCase { 'testdir', new Sabre_DAV_SimpleCollection('testdir'), &$requestedProperties, - &$returnedProperties + &$returnedProperties, ); - $r = $this->server->broadcastEvent('beforeGetProperties',$arguments); + $r = $this->server->broadcastEvent('beforeGetProperties', $arguments); $this->assertFalse($r); - } } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/Exception/AceConflictTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/Exception/AceConflictTest.php index 4e0f3eef..ab0aaaed 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/Exception/AceConflictTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/Exception/AceConflictTest.php @@ -1,14 +1,14 @@ createElementNS('DAV:','d:root'); + $dom = new DOMDocument('1.0', 'utf-8'); + $root = $dom->createElementNS('DAV:', 'd:root'); $dom->appendChild($root); $ex->serialize($server, $root); @@ -23,13 +23,9 @@ class Sabre_DAVACL_Exception_AceConflictTest extends PHPUnit_Framework_TestCase $dom2->loadXML($dom->saveXML()); $dxpath = new DOMXPath($dom2); - $dxpath->registerNamespace('d','DAV:'); - foreach($xpaths as $xpath=>$count) { - - $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : ' . $xpath . ', we could only find ' . $dxpath->query($xpath)->length . ' elements, while we expected ' . $count); - + $dxpath->registerNamespace('d', 'DAV:'); + foreach ($xpaths as $xpath => $count) { + $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : '.$xpath.', we could only find '.$dxpath->query($xpath)->length.' elements, while we expected '.$count); } - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NeedPrivilegesExceptionTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NeedPrivilegesExceptionTest.php index 7f4da276..d60e1dc0 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NeedPrivilegesExceptionTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NeedPrivilegesExceptionTest.php @@ -1,9 +1,9 @@ createElementNS('DAV:','d:root'); + $dom = new DOMDocument('1.0', 'utf-8'); + $root = $dom->createElementNS('DAV:', 'd:root'); $dom->appendChild($root); $ex->serialize($server, $root); @@ -33,13 +33,9 @@ class Sabre_DAVACL_Exception_NeedPrivilegesTest extends PHPUnit_Framework_TestCa $dom2->loadXML($dom->saveXML()); $dxpath = new DOMXPath($dom2); - $dxpath->registerNamespace('d','DAV:'); - foreach($xpaths as $xpath=>$count) { - - $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : ' . $xpath . ', we could only find ' . $dxpath->query($xpath)->length . ' elements, while we expected ' . $count); - + $dxpath->registerNamespace('d', 'DAV:'); + foreach ($xpaths as $xpath => $count) { + $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : '.$xpath.', we could only find '.$dxpath->query($xpath)->length.' elements, while we expected '.$count); } - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NoAbstractTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NoAbstractTest.php index e469dacd..adb49037 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NoAbstractTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NoAbstractTest.php @@ -1,14 +1,14 @@ createElementNS('DAV:','d:root'); + $dom = new DOMDocument('1.0', 'utf-8'); + $root = $dom->createElementNS('DAV:', 'd:root'); $dom->appendChild($root); $ex->serialize($server, $root); @@ -23,13 +23,9 @@ class Sabre_DAVACL_Exception_NoAbstractTest extends PHPUnit_Framework_TestCase { $dom2->loadXML($dom->saveXML()); $dxpath = new DOMXPath($dom2); - $dxpath->registerNamespace('d','DAV:'); - foreach($xpaths as $xpath=>$count) { - - $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : ' . $xpath . ', we could only find ' . $dxpath->query($xpath)->length . ' elements, while we expected ' . $count); - + $dxpath->registerNamespace('d', 'DAV:'); + foreach ($xpaths as $xpath => $count) { + $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : '.$xpath.', we could only find '.$dxpath->query($xpath)->length.' elements, while we expected '.$count); } - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NotRecognizedPrincipalTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NotRecognizedPrincipalTest.php index d6769083..c98f70f7 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NotRecognizedPrincipalTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NotRecognizedPrincipalTest.php @@ -1,14 +1,14 @@ createElementNS('DAV:','d:root'); + $dom = new DOMDocument('1.0', 'utf-8'); + $root = $dom->createElementNS('DAV:', 'd:root'); $dom->appendChild($root); $ex->serialize($server, $root); @@ -23,13 +23,9 @@ class Sabre_DAVACL_Exception_NotRecognizedPrincipalTest extends PHPUnit_Framewor $dom2->loadXML($dom->saveXML()); $dxpath = new DOMXPath($dom2); - $dxpath->registerNamespace('d','DAV:'); - foreach($xpaths as $xpath=>$count) { - - $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : ' . $xpath . ', we could only find ' . $dxpath->query($xpath)->length . ' elements, while we expected ' . $count); - + $dxpath->registerNamespace('d', 'DAV:'); + foreach ($xpaths as $xpath => $count) { + $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : '.$xpath.', we could only find '.$dxpath->query($xpath)->length.' elements, while we expected '.$count); } - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NotSupportedPrivilegeTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NotSupportedPrivilegeTest.php index 09c58bba..270a7f96 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NotSupportedPrivilegeTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/Exception/NotSupportedPrivilegeTest.php @@ -1,14 +1,14 @@ createElementNS('DAV:','d:root'); + $dom = new DOMDocument('1.0', 'utf-8'); + $root = $dom->createElementNS('DAV:', 'd:root'); $dom->appendChild($root); $ex->serialize($server, $root); @@ -23,13 +23,9 @@ class Sabre_DAVACL_Exception_NotSupportedPrivilegeTest extends PHPUnit_Framework $dom2->loadXML($dom->saveXML()); $dxpath = new DOMXPath($dom2); - $dxpath->registerNamespace('d','DAV:'); - foreach($xpaths as $xpath=>$count) { - - $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : ' . $xpath . ', we could only find ' . $dxpath->query($xpath)->length . ' elements, while we expected ' . $count); - + $dxpath->registerNamespace('d', 'DAV:'); + foreach ($xpaths as $xpath => $count) { + $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : '.$xpath.', we could only find '.$dxpath->query($xpath)->length.' elements, while we expected '.$count); } - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/ExpandPropertiesTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/ExpandPropertiesTest.php index e571bc8c..567b4641 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/ExpandPropertiesTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/ExpandPropertiesTest.php @@ -2,24 +2,24 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { - - function getServer() { - +class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase +{ + public function getServer() + { $tree = array( new Sabre_DAVACL_MockPropertyNode('node1', array( '{http://sabredav.org/ns}simple' => 'foo', - '{http://sabredav.org/ns}href' => new Sabre_DAV_Property_Href('node2'), - '{DAV:}displayname' => 'Node 1', + '{http://sabredav.org/ns}href' => new Sabre_DAV_Property_Href('node2'), + '{DAV:}displayname' => 'Node 1', )), new Sabre_DAVACL_MockPropertyNode('node2', array( '{http://sabredav.org/ns}simple' => 'simple', - '{http://sabredav.org/ns}hreflist' => new Sabre_DAV_Property_HrefList(array('node1','node3')), - '{DAV:}displayname' => 'Node 2', + '{http://sabredav.org/ns}hreflist' => new Sabre_DAV_Property_HrefList(array('node1', 'node3')), + '{DAV:}displayname' => 'Node 2', )), new Sabre_DAVACL_MockPropertyNode('node3', array( '{http://sabredav.org/ns}simple' => 'simple', - '{DAV:}displayname' => 'Node 3', + '{DAV:}displayname' => 'Node 3', )), ); @@ -34,11 +34,10 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { $this->assertEquals($plugin, $fakeServer->getPlugin('acl')); return $fakeServer; - } - function testSimple() { - + public function testSimple() + { $xml = ' @@ -49,8 +48,8 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '0', - 'REQUEST_URI' => '/node1', + 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/node1', ); $request = new Sabre_HTTP_Request($serverVars); @@ -61,12 +60,11 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { $server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status', $server->httpResponse->status,'Incorrect status code received. Full body: ' . $server->httpResponse->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $server->httpResponse->status, 'Incorrect status code received. Full body: '.$server->httpResponse->body); $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - $check = array( '/d:multistatus', '/d:multistatus/d:response' => 1, @@ -80,28 +78,27 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { ); $xml = simplexml_load_string($server->httpResponse->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('s','http://sabredav.org/ns'); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('s', 'http://sabredav.org/ns'); + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); $count = 1; - if (!is_int($v1)) $count = $v2; - - $this->assertEquals($count,count($result), 'we expected ' . $count . ' appearances of ' . $xpath . ' . We found ' . count($result) . '. Full response: ' . $server->httpResponse->body); + if (!is_int($v1)) { + $count = $v2; + } + $this->assertEquals($count, count($result), 'we expected '.$count.' appearances of '.$xpath.' . We found '.count($result).'. Full response: '.$server->httpResponse->body); } - } /** * @depends testSimple */ - function testExpand() { - + public function testExpand() + { $xml = ' @@ -111,8 +108,8 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '0', - 'REQUEST_URI' => '/node1', + 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/node1', ); $request = new Sabre_HTTP_Request($serverVars); @@ -123,12 +120,11 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { $server->exec(); - $this->assertEquals('HTTP/1.1 207 Multi-Status', $server->httpResponse->status, 'Incorrect response status received. Full response body: ' . $server->httpResponse->body); + $this->assertEquals('HTTP/1.1 207 Multi-Status', $server->httpResponse->status, 'Incorrect response status received. Full response body: '.$server->httpResponse->body); $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - $check = array( '/d:multistatus', '/d:multistatus/d:response' => 1, @@ -144,28 +140,27 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { ); $xml = simplexml_load_string($server->httpResponse->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('s','http://sabredav.org/ns'); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('s', 'http://sabredav.org/ns'); + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); $count = 1; - if (!is_int($v1)) $count = $v2; - - $this->assertEquals($count,count($result), 'we expected ' . $count . ' appearances of ' . $xpath . ' . We found ' . count($result)); + if (!is_int($v1)) { + $count = $v2; + } + $this->assertEquals($count, count($result), 'we expected '.$count.' appearances of '.$xpath.' . We found '.count($result)); } - } /** * @depends testSimple */ - function testExpandHrefList() { - + public function testExpandHrefList() + { $xml = ' @@ -175,8 +170,8 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '0', - 'REQUEST_URI' => '/node2', + 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/node2', ); $request = new Sabre_HTTP_Request($serverVars); @@ -192,7 +187,6 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - $check = array( '/d:multistatus', '/d:multistatus/d:response' => 1, @@ -208,28 +202,27 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { ); $xml = simplexml_load_string($server->httpResponse->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('s','http://sabredav.org/ns'); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('s', 'http://sabredav.org/ns'); + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); $count = 1; - if (!is_int($v1)) $count = $v2; - - $this->assertEquals($count,count($result), 'we expected ' . $count . ' appearances of ' . $xpath . ' . We found ' . count($result)); + if (!is_int($v1)) { + $count = $v2; + } + $this->assertEquals($count, count($result), 'we expected '.$count.' appearances of '.$xpath.' . We found '.count($result)); } - } /** * @depends testExpand */ - function testExpandDeep() { - + public function testExpandDeep() + { $xml = ' @@ -242,8 +235,8 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '0', - 'REQUEST_URI' => '/node2', + 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/node2', ); $request = new Sabre_HTTP_Request($serverVars); @@ -259,7 +252,6 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - $check = array( '/d:multistatus', '/d:multistatus/d:response' => 1, @@ -281,73 +273,65 @@ class Sabre_DAVACL_ExpandPropertiesTest extends PHPUnit_Framework_TestCase { ); $xml = simplexml_load_string($server->httpResponse->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('s','http://sabredav.org/ns'); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('s', 'http://sabredav.org/ns'); + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); $count = 1; - if (!is_int($v1)) $count = $v2; - - $this->assertEquals($count,count($result), 'we expected ' . $count . ' appearances of ' . $xpath . ' . We found ' . count($result)); + if (!is_int($v1)) { + $count = $v2; + } + $this->assertEquals($count, count($result), 'we expected '.$count.' appearances of '.$xpath.' . We found '.count($result)); } - } } -class Sabre_DAVACL_MockPropertyNode implements Sabre_DAV_INode, Sabre_DAV_IProperties { - - function __construct($name, array $properties) { - +class Sabre_DAVACL_MockPropertyNode implements Sabre_DAV_INode, Sabre_DAV_IProperties +{ + public function __construct($name, array $properties) + { $this->name = $name; $this->properties = $properties; - } - function getName() { - + public function getName() + { return $this->name; - } - function getProperties($requestedProperties) { - + public function getProperties($requestedProperties) + { $returnedProperties = array(); - foreach($requestedProperties as $requestedProperty) { + foreach ($requestedProperties as $requestedProperty) { if (isset($this->properties[$requestedProperty])) { $returnedProperties[$requestedProperty] = $this->properties[$requestedProperty]; } } + return $returnedProperties; - } - function delete() { - + public function delete() + { throw new Sabre_DAV_Exception('Not implemented'); - } - function setName($name) { - + public function setName($name) + { throw new Sabre_DAV_Exception('Not implemented'); - } - function getLastModified() { - + public function getLastModified() + { return null; - } - function updateProperties($properties) { - + public function updateProperties($properties) + { throw new Sabre_DAV_Exception('Not implemented'); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/MockACLNode.php b/dav/SabreDAV/tests/Sabre/DAVACL/MockACLNode.php index 15fd72a6..426b40e2 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/MockACLNode.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/MockACLNode.php @@ -1,51 +1,43 @@ name = $name; $this->acl = $acl; - } - function getName() { - + public function getName() + { return $this->name; - } - function getOwner() { - + public function getOwner() + { return null; - } - function getGroup() { - + public function getGroup() + { return null; - } - function getACL() { - + public function getACL() + { return $this->acl; - } - function setACL(array $acl) { - + public function setACL(array $acl) + { $this->acl = $acl; - } - function getSupportedPrivilegeSet() { - + public function getSupportedPrivilegeSet() + { return null; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/MockPrincipal.php b/dav/SabreDAV/tests/Sabre/DAVACL/MockPrincipal.php index 1ea2de3e..40c4d7a5 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/MockPrincipal.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/MockPrincipal.php @@ -1,61 +1,52 @@ name = $name; $this->principalUrl = $principalUrl; $this->groupMembership = $groupMembership; $this->groupMemberSet = $groupMemberSet; - } - function getName() { - + public function getName() + { return $this->name; - } - function getDisplayName() { - + public function getDisplayName() + { return $this->getName(); - } - function getAlternateUriSet() { - + public function getAlternateUriSet() + { return array(); - } - function getPrincipalUrl() { - + public function getPrincipalUrl() + { return $this->principalUrl; - } - function getGroupMemberSet() { - + public function getGroupMemberSet() + { return $this->groupMemberSet; - } - function getGroupMemberShip() { - + public function getGroupMemberShip() + { return $this->groupMembership; - } - function setGroupMemberSet(array $groupMemberSet) { - + public function setGroupMemberSet(array $groupMemberSet) + { $this->groupMemberSet = $groupMemberSet; - } } - diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/MockPrincipalBackend.php b/dav/SabreDAV/tests/Sabre/DAVACL/MockPrincipalBackend.php index e6b48cc6..c7cac8ca 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/MockPrincipalBackend.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/MockPrincipalBackend.php @@ -1,12 +1,12 @@ principals = array( array( 'uri' => 'principals/user1', @@ -24,83 +24,76 @@ class Sabre_DAVACL_MockPrincipalBackend implements Sabre_DAVACL_IPrincipalBacken '{http://sabredav.org/ns}email-address' => 'user2.sabredav@sabredav.org', ), ); - - } - function getPrincipalsByPrefix($prefix) { - - $prefix = trim($prefix,'/') . '/'; + public function getPrincipalsByPrefix($prefix) + { + $prefix = trim($prefix, '/').'/'; $return = array(); - foreach($this->principals as $principal) { - - if (strpos($principal['uri'], $prefix)!==0) continue; + foreach ($this->principals as $principal) { + if (strpos($principal['uri'], $prefix) !== 0) { + continue; + } $return[] = $principal; - } return $return; - } - function addPrincipal(array $principal) { - + public function addPrincipal(array $principal) + { $this->principals[] = $principal; - } - function getPrincipalByPath($path) { - - foreach($this->getPrincipalsByPrefix('principals') as $principal) { - if ($principal['uri'] === $path) return $principal; + public function getPrincipalByPath($path) + { + foreach ($this->getPrincipalsByPrefix('principals') as $principal) { + if ($principal['uri'] === $path) { + return $principal; + } } - } - function searchPrincipals($prefixPath, array $searchProperties) { - + public function searchPrincipals($prefixPath, array $searchProperties) + { $matches = array(); - foreach($this->getPrincipalsByPrefix($prefixPath) as $principal) { - - foreach($searchProperties as $key=>$value) { - + foreach ($this->getPrincipalsByPrefix($prefixPath) as $principal) { + foreach ($searchProperties as $key => $value) { if (!isset($principal[$key])) { continue 2; } - if (mb_stripos($principal[$key],$value, 0, 'UTF-8')===false) { + if (mb_stripos($principal[$key], $value, 0, 'UTF-8') === false) { continue 2; } - } $matches[] = $principal['uri']; - } + return $matches; - } - function getGroupMemberSet($path) { - + public function getGroupMemberSet($path) + { return isset($this->groupMembers[$path]) ? $this->groupMembers[$path] : array(); - } - function getGroupMembership($path) { - + public function getGroupMembership($path) + { $membership = array(); - foreach($this->groupMembers as $group=>$members) { - if (in_array($path, $members)) $membership[] = $group; + foreach ($this->groupMembers as $group => $members) { + if (in_array($path, $members)) { + $membership[] = $group; + } } - return $membership; + return $membership; } - function setGroupMemberSet($path, array $members) { - + public function setGroupMemberSet($path, array $members) + { $this->groupMembers[$path] = $members; - } /** @@ -148,35 +141,33 @@ class Sabre_DAVACL_MockPrincipalBackend implements Sabre_DAVACL_IPrincipalBacken * return true or false. * * @param string $path - * @param array $mutations + * @param array $mutations + * * @return array|bool */ - public function updatePrincipal($path, $mutations) { - + public function updatePrincipal($path, $mutations) + { $value = null; - foreach($this->principals as $principalIndex=>$value) { + foreach ($this->principals as $principalIndex => $value) { if ($value['uri'] === $path) { $principal = $value; break; } } - if (!$principal) return false; - - foreach($mutations as $prop=>$value) { + if (!$principal) { + return false; + } + foreach ($mutations as $prop => $value) { if (is_null($value) && isset($principal[$prop])) { unset($principal[$prop]); } else { $principal[$prop] = $value; } - } $this->principals[$principalIndex] = $principal; return true; - } - - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/PluginAdminTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/PluginAdminTest.php index 56bfb2ef..59148e96 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/PluginAdminTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/PluginAdminTest.php @@ -5,19 +5,19 @@ require_once 'Sabre/DAV/Auth/MockBackend.php'; require_once 'Sabre/HTTP/ResponseMock.php'; require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; -class Sabre_DAVACL_PluginAdminTest extends PHPUnit_Framework_TestCase { - - function testNoAdminAccess() { - +class Sabre_DAVACL_PluginAdminTest extends PHPUnit_Framework_TestCase +{ + public function testNoAdminAccess() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $tree = array( new Sabre_DAVACL_MockACLNode('adminonly', array()), - new Sabre_DAVACL_PrincipalCollection($principalBackend), + new Sabre_DAVACL_PrincipalCollection($principalBackend), ); $fakeServer = new Sabre_DAV_Server($tree); - $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'realm'); + $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'realm'); $fakeServer->addPlugin($plugin); $plugin = new Sabre_DAVACL_Plugin(); $fakeServer->addPlugin($plugin); @@ -35,24 +35,23 @@ class Sabre_DAVACL_PluginAdminTest extends PHPUnit_Framework_TestCase { $fakeServer->exec(); - $this->assertEquals('HTTP/1.1 403 Forbidden', $response->status); - + $this->assertEquals('HTTP/1.1 403 Forbidden', $response->status); } /** * @depends testNoAdminAccess */ - function testAdminAccess() { - + public function testAdminAccess() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $tree = array( new Sabre_DAVACL_MockACLNode('adminonly', array()), - new Sabre_DAVACL_PrincipalCollection($principalBackend), + new Sabre_DAVACL_PrincipalCollection($principalBackend), ); $fakeServer = new Sabre_DAV_Server($tree); - $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'realm'); + $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'realm'); $fakeServer->addPlugin($plugin); $plugin = new Sabre_DAVACL_Plugin(); $plugin->adminPrincipals = array( @@ -73,7 +72,6 @@ class Sabre_DAVACL_PluginAdminTest extends PHPUnit_Framework_TestCase { $fakeServer->exec(); - $this->assertEquals('HTTP/1.1 200 OK', $response->status); - + $this->assertEquals('HTTP/1.1 200 OK', $response->status); } } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/PluginPropertiesTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/PluginPropertiesTest.php index c7a1b333..165d8b7d 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/PluginPropertiesTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/PluginPropertiesTest.php @@ -3,10 +3,10 @@ require_once 'Sabre/DAV/Auth/MockBackend.php'; require_once 'Sabre/DAVACL/MockPrincipal.php'; -class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { - - function testPrincipalCollectionSet() { - +class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase +{ + public function testPrincipalCollectionSet() + { $plugin = new Sabre_DAVACL_Plugin(); $plugin->principalCollectionSet = array( 'principals1', @@ -27,8 +27,8 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { $this->assertNull($plugin->beforeGetProperties('', new Sabre_DAV_SimpleCollection('root'), $requestedProperties, $returnedProperties)); - $this->assertEquals(1,count($returnedProperties[200])); - $this->assertArrayHasKey('{DAV:}principal-collection-set',$returnedProperties[200]); + $this->assertEquals(1, count($returnedProperties[200])); + $this->assertArrayHasKey('{DAV:}principal-collection-set', $returnedProperties[200]); $this->assertInstanceOf('Sabre_DAV_Property_HrefList', $returnedProperties[200]['{DAV:}principal-collection-set']); $expected = array( @@ -36,21 +36,17 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { 'principals2/', ); - $this->assertEquals($expected, $returnedProperties[200]['{DAV:}principal-collection-set']->getHrefs()); - - } - function testCurrentUserPrincipal() { - + public function testCurrentUserPrincipal() + { $fakeServer = new Sabre_DAV_Server(); - $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'realm'); + $plugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'realm'); $fakeServer->addPlugin($plugin); $plugin = new Sabre_DAVACL_Plugin(); $fakeServer->addPlugin($plugin); - $requestedProperties = array( '{DAV:}current-user-principal', ); @@ -62,14 +58,13 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { $this->assertNull($plugin->beforeGetProperties('', new Sabre_DAV_SimpleCollection('root'), $requestedProperties, $returnedProperties)); - $this->assertEquals(1,count($returnedProperties[200])); - $this->assertArrayHasKey('{DAV:}current-user-principal',$returnedProperties[200]); + $this->assertEquals(1, count($returnedProperties[200])); + $this->assertArrayHasKey('{DAV:}current-user-principal', $returnedProperties[200]); $this->assertInstanceOf('Sabre_DAVACL_Property_Principal', $returnedProperties[200]['{DAV:}current-user-principal']); $this->assertEquals(Sabre_DAVACL_Property_Principal::UNAUTHENTICATED, $returnedProperties[200]['{DAV:}current-user-principal']->getType()); // This will force the login - $fakeServer->broadCastEvent('beforeMethod',array('GET','')); - + $fakeServer->broadCastEvent('beforeMethod', array('GET', '')); $requestedProperties = array( '{DAV:}current-user-principal', @@ -80,20 +75,17 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { 404 => array(), ); - $this->assertNull($plugin->beforeGetProperties('', new Sabre_DAV_SimpleCollection('root'), $requestedProperties, $returnedProperties)); - - $this->assertEquals(1,count($returnedProperties[200])); - $this->assertArrayHasKey('{DAV:}current-user-principal',$returnedProperties[200]); + $this->assertEquals(1, count($returnedProperties[200])); + $this->assertArrayHasKey('{DAV:}current-user-principal', $returnedProperties[200]); $this->assertInstanceOf('Sabre_DAVACL_Property_Principal', $returnedProperties[200]['{DAV:}current-user-principal']); $this->assertEquals(Sabre_DAVACL_Property_Principal::HREF, $returnedProperties[200]['{DAV:}current-user-principal']->getType()); $this->assertEquals('principals/admin/', $returnedProperties[200]['{DAV:}current-user-principal']->getHref()); - } - function testSupportedPrivilegeSet() { - + public function testSupportedPrivilegeSet() + { $plugin = new Sabre_DAVACL_Plugin(); $server = new Sabre_DAV_Server(); $server->addPlugin($plugin); @@ -107,11 +99,10 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { 404 => array(), ); - $this->assertNull($plugin->beforeGetProperties('', new Sabre_DAV_SimpleCollection('root'), $requestedProperties, $returnedProperties)); - $this->assertEquals(1,count($returnedProperties[200])); - $this->assertArrayHasKey('{DAV:}supported-privilege-set',$returnedProperties[200]); + $this->assertEquals(1, count($returnedProperties[200])); + $this->assertArrayHasKey('{DAV:}supported-privilege-set', $returnedProperties[200]); $this->assertInstanceOf('Sabre_DAVACL_Property_SupportedPrivilegeSet', $returnedProperties[200]['{DAV:}supported-privilege-set']); $server = new Sabre_DAV_Server(); @@ -119,11 +110,10 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { $dom = new DOMDocument('1.0', 'utf-8'); $root = $dom->createElement('d:root'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $dom->appendChild($root); $prop->serialize($server, $root); - $xpaths = array( '/d:root' => 1, '/d:root/d:supported-privilege' => 1, @@ -147,23 +137,19 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { '/d:root/d:supported-privilege/d:supported-privilege/d:supported-privilege/d:abstract' => 8, ); - // reloading because php dom sucks $dom2 = new DOMDocument('1.0', 'utf-8'); $dom2->loadXML($dom->saveXML()); $dxpath = new DOMXPath($dom2); - $dxpath->registerNamespace('d','DAV:'); - foreach($xpaths as $xpath=>$count) { - - $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : ' . $xpath . ', we could only find ' . $dxpath->query($xpath)->length . ' elements, while we expected ' . $count); - + $dxpath->registerNamespace('d', 'DAV:'); + foreach ($xpaths as $xpath => $count) { + $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : '.$xpath.', we could only find '.$dxpath->query($xpath)->length.' elements, while we expected '.$count); } - } - function testACL() { - + public function testACL() + { $plugin = new Sabre_DAVACL_Plugin(); $nodes = array( @@ -171,21 +157,21 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { array( 'principal' => 'principals/admin', 'privilege' => '{DAV:}read', - ) + ), )), new Sabre_DAV_SimpleCollection('principals', array( - $principal = new Sabre_DAVACL_MockPrincipal('admin','principals/admin'), + $principal = new Sabre_DAVACL_MockPrincipal('admin', 'principals/admin'), )), ); $server = new Sabre_DAV_Server($nodes); $server->addPlugin($plugin); - $authPlugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'realm'); + $authPlugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'realm'); $server->addPlugin($authPlugin); // Force login - $authPlugin->beforeMethod('BLA','foo'); + $authPlugin->beforeMethod('BLA', 'foo'); $requestedProperties = array( '{DAV:}acl', @@ -196,17 +182,15 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { 404 => array(), ); - $this->assertNull($plugin->beforeGetProperties('foo', $nodes[0], $requestedProperties, $returnedProperties)); - $this->assertEquals(1,count($returnedProperties[200]),'The {DAV:}acl property did not return from the list. Full list: ' . print_r($returnedProperties,true)); - $this->assertArrayHasKey('{DAV:}acl',$returnedProperties[200]); + $this->assertEquals(1, count($returnedProperties[200]), 'The {DAV:}acl property did not return from the list. Full list: '.print_r($returnedProperties, true)); + $this->assertArrayHasKey('{DAV:}acl', $returnedProperties[200]); $this->assertInstanceOf('Sabre_DAVACL_Property_ACL', $returnedProperties[200]['{DAV:}acl']); - } - function testACLRestrictions() { - + public function testACLRestrictions() + { $plugin = new Sabre_DAVACL_Plugin(); $nodes = array( @@ -214,21 +198,21 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { array( 'principal' => 'principals/admin', 'privilege' => '{DAV:}read', - ) + ), )), new Sabre_DAV_SimpleCollection('principals', array( - $principal = new Sabre_DAVACL_MockPrincipal('admin','principals/admin'), + $principal = new Sabre_DAVACL_MockPrincipal('admin', 'principals/admin'), )), ); $server = new Sabre_DAV_Server($nodes); $server->addPlugin($plugin); - $authPlugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'realm'); + $authPlugin = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'realm'); $server->addPlugin($authPlugin); // Force login - $authPlugin->beforeMethod('BLA','foo'); + $authPlugin->beforeMethod('BLA', 'foo'); $requestedProperties = array( '{DAV:}acl-restrictions', @@ -239,20 +223,18 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { 404 => array(), ); - $this->assertNull($plugin->beforeGetProperties('foo', $nodes[0], $requestedProperties, $returnedProperties)); - $this->assertEquals(1,count($returnedProperties[200]),'The {DAV:}acl-restrictions property did not return from the list. Full list: ' . print_r($returnedProperties,true)); - $this->assertArrayHasKey('{DAV:}acl-restrictions',$returnedProperties[200]); + $this->assertEquals(1, count($returnedProperties[200]), 'The {DAV:}acl-restrictions property did not return from the list. Full list: '.print_r($returnedProperties, true)); + $this->assertArrayHasKey('{DAV:}acl-restrictions', $returnedProperties[200]); $this->assertInstanceOf('Sabre_DAVACL_Property_ACLRestrictions', $returnedProperties[200]['{DAV:}acl-restrictions']); - } - function testAlternateUriSet() { - + public function testAlternateUriSet() + { $tree = array( new Sabre_DAV_SimpleCollection('principals', array( - $principal = new Sabre_DAVACL_MockPrincipal('user','principals/user'), + $principal = new Sabre_DAVACL_MockPrincipal('user', 'principals/user'), )), ); @@ -267,7 +249,7 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { ); $returnedProperties = array(); - $result = $plugin->beforeGetProperties('principals/user',$principal,$requestedProperties,$returnedProperties); + $result = $plugin->beforeGetProperties('principals/user', $principal, $requestedProperties, $returnedProperties); $this->assertNull($result); @@ -276,14 +258,13 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { $this->assertInstanceOf('Sabre_DAV_Property_HrefList', $returnedProperties[200]['{DAV:}alternate-URI-set']); $this->assertEquals(array(), $returnedProperties[200]['{DAV:}alternate-URI-set']->getHrefs()); - } - function testPrincipalURL() { - + public function testPrincipalURL() + { $tree = array( new Sabre_DAV_SimpleCollection('principals', array( - $principal = new Sabre_DAVACL_MockPrincipal('user','principals/user'), + $principal = new Sabre_DAVACL_MockPrincipal('user', 'principals/user'), )), ); @@ -298,7 +279,7 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { ); $returnedProperties = array(); - $result = $plugin->beforeGetProperties('principals/user',$principal,$requestedProperties,$returnedProperties); + $result = $plugin->beforeGetProperties('principals/user', $principal, $requestedProperties, $returnedProperties); $this->assertNull($result); @@ -307,14 +288,13 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { $this->assertInstanceOf('Sabre_DAV_Property_Href', $returnedProperties[200]['{DAV:}principal-URL']); $this->assertEquals('principals/user/', $returnedProperties[200]['{DAV:}principal-URL']->getHref()); - } - function testGroupMemberSet() { - + public function testGroupMemberSet() + { $tree = array( new Sabre_DAV_SimpleCollection('principals', array( - $principal = new Sabre_DAVACL_MockPrincipal('user','principals/user'), + $principal = new Sabre_DAVACL_MockPrincipal('user', 'principals/user'), )), ); @@ -329,7 +309,7 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { ); $returnedProperties = array(); - $result = $plugin->beforeGetProperties('principals/user',$principal,$requestedProperties,$returnedProperties); + $result = $plugin->beforeGetProperties('principals/user', $principal, $requestedProperties, $returnedProperties); $this->assertNull($result); @@ -338,14 +318,13 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { $this->assertInstanceOf('Sabre_DAV_Property_HrefList', $returnedProperties[200]['{DAV:}group-member-set']); $this->assertEquals(array(), $returnedProperties[200]['{DAV:}group-member-set']->getHrefs()); - } - function testGroupMemberShip() { - + public function testGroupMemberShip() + { $tree = array( new Sabre_DAV_SimpleCollection('principals', array( - $principal = new Sabre_DAVACL_MockPrincipal('user','principals/user'), + $principal = new Sabre_DAVACL_MockPrincipal('user', 'principals/user'), )), ); @@ -360,7 +339,7 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { ); $returnedProperties = array(); - $result = $plugin->beforeGetProperties('principals/user',$principal,$requestedProperties,$returnedProperties); + $result = $plugin->beforeGetProperties('principals/user', $principal, $requestedProperties, $returnedProperties); $this->assertNull($result); @@ -369,14 +348,13 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { $this->assertInstanceOf('Sabre_DAV_Property_HrefList', $returnedProperties[200]['{DAV:}group-membership']); $this->assertEquals(array(), $returnedProperties[200]['{DAV:}group-membership']->getHrefs()); - } - function testGetDisplayName() { - + public function testGetDisplayName() + { $tree = array( new Sabre_DAV_SimpleCollection('principals', array( - $principal = new Sabre_DAVACL_MockPrincipal('user','principals/user'), + $principal = new Sabre_DAVACL_MockPrincipal('user', 'principals/user'), )), ); @@ -391,7 +369,7 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { ); $returnedProperties = array(); - $result = $plugin->beforeGetProperties('principals/user',$principal,$requestedProperties,$returnedProperties); + $result = $plugin->beforeGetProperties('principals/user', $principal, $requestedProperties, $returnedProperties); $this->assertNull($result); @@ -399,6 +377,5 @@ class Sabre_DAVACL_PluginPropertiesTest extends PHPUnit_Framework_TestCase { $this->assertTrue(isset($returnedProperties[200]['{DAV:}displayname'])); $this->assertEquals('user', $returnedProperties[200]['{DAV:}displayname']); - } } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/PluginUpdatePropertiesTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/PluginUpdatePropertiesTest.php index ad0d940a..6a1381ab 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/PluginUpdatePropertiesTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/PluginUpdatePropertiesTest.php @@ -2,10 +2,10 @@ require_once 'Sabre/DAVACL/MockPrincipal.php'; -class Sabre_DAVACL_PluginUpdatePropertiesTest extends PHPUnit_Framework_TestCase { - - public function testUpdatePropertiesPassthrough() { - +class Sabre_DAVACL_PluginUpdatePropertiesTest extends PHPUnit_Framework_TestCase +{ + public function testUpdatePropertiesPassthrough() + { $tree = array( new Sabre_DAV_SimpleCollection('foo'), ); @@ -24,13 +24,12 @@ class Sabre_DAVACL_PluginUpdatePropertiesTest extends PHPUnit_Framework_TestCase ); $this->assertEquals($expected, $result); - } - public function testRemoveGroupMembers() { - + public function testRemoveGroupMembers() + { $tree = array( - new Sabre_DAVACL_MockPrincipal('foo','foo'), + new Sabre_DAVACL_MockPrincipal('foo', 'foo'), ); $server = new Sabre_DAV_Server($tree); $server->addPlugin(new Sabre_DAVACL_Plugin()); @@ -47,20 +46,19 @@ class Sabre_DAVACL_PluginUpdatePropertiesTest extends PHPUnit_Framework_TestCase ); $this->assertEquals($expected, $result); - $this->assertEquals(array(),$tree[0]->getGroupMemberSet()); - + $this->assertEquals(array(), $tree[0]->getGroupMemberSet()); } - public function testSetGroupMembers() { - + public function testSetGroupMembers() + { $tree = array( - new Sabre_DAVACL_MockPrincipal('foo','foo'), + new Sabre_DAVACL_MockPrincipal('foo', 'foo'), ); $server = new Sabre_DAV_Server($tree); $server->addPlugin(new Sabre_DAVACL_Plugin()); $result = $server->updateProperties('foo', array( - '{DAV:}group-member-set' => new Sabre_DAV_Property_HrefList(array('bar','baz')), + '{DAV:}group-member-set' => new Sabre_DAV_Property_HrefList(array('bar', 'baz')), )); $expected = array( @@ -71,17 +69,16 @@ class Sabre_DAVACL_PluginUpdatePropertiesTest extends PHPUnit_Framework_TestCase ); $this->assertEquals($expected, $result); - $this->assertEquals(array('bar','baz'),$tree[0]->getGroupMemberSet()); - + $this->assertEquals(array('bar', 'baz'), $tree[0]->getGroupMemberSet()); } /** * @expectedException sabre_DAV_Exception */ - public function testSetBadValue() { - + public function testSetBadValue() + { $tree = array( - new Sabre_DAVACL_MockPrincipal('foo','foo'), + new Sabre_DAVACL_MockPrincipal('foo', 'foo'), ); $server = new Sabre_DAV_Server($tree); $server->addPlugin(new Sabre_DAVACL_Plugin()); @@ -89,11 +86,10 @@ class Sabre_DAVACL_PluginUpdatePropertiesTest extends PHPUnit_Framework_TestCase $result = $server->updateProperties('foo', array( '{DAV:}group-member-set' => new StdClass(), )); - } - public function testSetBadNode() { - + public function testSetBadNode() + { $tree = array( new Sabre_DAV_SimpleCollection('foo'), ); @@ -101,7 +97,7 @@ class Sabre_DAVACL_PluginUpdatePropertiesTest extends PHPUnit_Framework_TestCase $server->addPlugin(new Sabre_DAVACL_Plugin()); $result = $server->updateProperties('foo', array( - '{DAV:}group-member-set' => new Sabre_DAV_Property_HrefList(array('bar','baz')), + '{DAV:}group-member-set' => new Sabre_DAV_Property_HrefList(array('bar', 'baz')), '{DAV:}bar' => 'baz', )); @@ -116,6 +112,5 @@ class Sabre_DAVACL_PluginUpdatePropertiesTest extends PHPUnit_Framework_TestCase ); $this->assertEquals($expected, $result); - } } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/AbstractPDOTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/AbstractPDOTest.php index 0c8e6e28..3eacb81c 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/AbstractPDOTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/AbstractPDOTest.php @@ -1,22 +1,21 @@ getPDO(); $backend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); $this->assertTrue($backend instanceof Sabre_DAVACL_PrincipalBackend_PDO); - } /** * @depends testConstruct */ - function testGetPrincipalsByPrefix() { - + public function testGetPrincipalsByPrefix() + { $pdo = $this->getPDO(); $backend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); @@ -35,14 +34,13 @@ abstract class Sabre_DAVACL_PrincipalBackend_AbstractPDOTest extends PHPUnit_Fra $this->assertEquals($expected, $backend->getPrincipalsByPrefix('principals')); $this->assertEquals(array(), $backend->getPrincipalsByPrefix('foo')); - } /** * @depends testConstruct */ - function testGetPrincipalByPath() { - + public function testGetPrincipalByPath() + { $pdo = $this->getPDO(); $backend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); @@ -55,31 +53,28 @@ abstract class Sabre_DAVACL_PrincipalBackend_AbstractPDOTest extends PHPUnit_Fra $this->assertEquals($expected, $backend->getPrincipalByPath('principals/user')); $this->assertEquals(null, $backend->getPrincipalByPath('foo')); - } - function testGetGroupMemberSet() { - + public function testGetGroupMemberSet() + { $pdo = $this->getPDO(); $backend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); $expected = array('principals/user'); - $this->assertEquals($expected,$backend->getGroupMemberSet('principals/group')); - + $this->assertEquals($expected, $backend->getGroupMemberSet('principals/group')); } - function testGetGroupMembership() { - + public function testGetGroupMembership() + { $pdo = $this->getPDO(); $backend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); $expected = array('principals/group'); - $this->assertEquals($expected,$backend->getGroupMembership('principals/user')); - + $this->assertEquals($expected, $backend->getGroupMembership('principals/user')); } - function testSetGroupMemberSet() { - + public function testSetGroupMemberSet() + { $pdo = $this->getPDO(); // Start situation @@ -93,12 +88,10 @@ abstract class Sabre_DAVACL_PrincipalBackend_AbstractPDOTest extends PHPUnit_Fra // Adding principals again $backend->setGroupMemberSet('principals/group', array('principals/user')); $this->assertEquals(array('principals/user'), $backend->getGroupMemberSet('principals/group')); - - } - function testSearchPrincipals() { - + public function testSearchPrincipals() + { $pdo = $this->getPDO(); $backend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); @@ -114,11 +107,10 @@ abstract class Sabre_DAVACL_PrincipalBackend_AbstractPDOTest extends PHPUnit_Fra $result = $backend->searchPrincipals('mom', array('{DAV:}displayname' => 'UsEr', '{http://sabredav.org/ns}email-address' => 'USER@EXAMPLE')); $this->assertEquals(array(), $result); - } - function testUpdatePrincipal() { - + public function testUpdatePrincipal() + { $pdo = $this->getPDO(); $backend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); @@ -136,11 +128,10 @@ abstract class Sabre_DAVACL_PrincipalBackend_AbstractPDOTest extends PHPUnit_Fra '{http://sabredav.org/ns}vcard-url' => 'blabla', '{http://sabredav.org/ns}email-address' => 'user@example.org', ), $backend->getPrincipalByPath('principals/user')); - } - function testUpdatePrincipalUnknownField() { - + public function testUpdatePrincipalUnknownField() + { $pdo = $this->getPDO(); $backend = new Sabre_DAVACL_PrincipalBackend_PDO($pdo); @@ -158,7 +149,7 @@ abstract class Sabre_DAVACL_PrincipalBackend_AbstractPDOTest extends PHPUnit_Fra 403 => array( '{DAV:}unknown' => null, ), - ), $result); + ), $result); $this->assertEquals(array( 'id' => '1', @@ -166,7 +157,5 @@ abstract class Sabre_DAVACL_PrincipalBackend_AbstractPDOTest extends PHPUnit_Fra '{DAV:}displayname' => 'User', '{http://sabredav.org/ns}email-address' => 'user@example.org', ), $backend->getPrincipalByPath('principals/user')); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/PDOMySQLTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/PDOMySQLTest.php index d9a83655..215b4318 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/PDOMySQLTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/PDOMySQLTest.php @@ -2,15 +2,19 @@ require_once 'Sabre/TestUtil.php'; -class Sabre_DAVACL_PrincipalBackend_PDOMySQLTest extends Sabre_DAVACL_PrincipalBackend_AbstractPDOTest { - - function getPDO() { - - if (!SABRE_HASMYSQL) $this->markTestSkipped('MySQL driver is not available, or not properly configured'); +class Sabre_DAVACL_PrincipalBackend_PDOMySQLTest extends Sabre_DAVACL_PrincipalBackend_AbstractPDOTest +{ + public function getPDO() + { + if (!SABRE_HASMYSQL) { + $this->markTestSkipped('MySQL driver is not available, or not properly configured'); + } $pdo = Sabre_TestUtil::getMySQLDB(); - if (!$pdo) $this->markTestSkipped('Could not connect to MySQL database'); - $pdo->query("DROP TABLE IF EXISTS principals"); - $pdo->query(" + if (!$pdo) { + $this->markTestSkipped('Could not connect to MySQL database'); + } + $pdo->query('DROP TABLE IF EXISTS principals'); + $pdo->query(' create table principals ( id integer unsigned not null primary key auto_increment, uri varchar(50), @@ -18,22 +22,20 @@ create table principals ( displayname VARCHAR(80), vcardurl VARCHAR(80), unique(uri) -);"); +);'); $pdo->query("INSERT INTO principals (uri,email,displayname) VALUES ('principals/user','user@example.org','User')"); $pdo->query("INSERT INTO principals (uri,email,displayname) VALUES ('principals/group','group@example.org','Group')"); - $pdo->query("DROP TABLE IF EXISTS groupmembers"); - $pdo->query("CREATE TABLE groupmembers ( + $pdo->query('DROP TABLE IF EXISTS groupmembers'); + $pdo->query('CREATE TABLE groupmembers ( id INTEGER UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, principal_id INTEGER UNSIGNED NOT NULL, member_id INTEGER UNSIGNED NOT NULL, UNIQUE(principal_id, member_id) - );"); + );'); - $pdo->query("INSERT INTO groupmembers (principal_id,member_id) VALUES (2,1)"); + $pdo->query('INSERT INTO groupmembers (principal_id,member_id) VALUES (2,1)'); return $pdo; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/PDOSqliteTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/PDOSqliteTest.php index 274065b2..1e3ecdcd 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/PDOSqliteTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalBackend/PDOSqliteTest.php @@ -2,35 +2,38 @@ require_once 'Sabre/DAV/Auth/Backend/AbstractPDOTest.php'; -class Sabre_DAVACL_PrincipalBackend_PDOSQLiteTest extends Sabre_DAVACL_PrincipalBackend_AbstractPDOTest { - - function tearDown() { - - if (file_exists(SABRE_TEMPDIR . '/pdobackend')) unlink(SABRE_TEMPDIR . '/pdobackend'); - if (file_exists(SABRE_TEMPDIR . '/pdobackend2')) unlink(SABRE_TEMPDIR . '/pdobackend2'); - +class Sabre_DAVACL_PrincipalBackend_PDOSqliteTest extends Sabre_DAVACL_PrincipalBackend_AbstractPDOTest +{ + public function tearDown() + { + if (file_exists(SABRE_TEMPDIR.'/pdobackend')) { + unlink(SABRE_TEMPDIR.'/pdobackend'); + } + if (file_exists(SABRE_TEMPDIR.'/pdobackend2')) { + unlink(SABRE_TEMPDIR.'/pdobackend2'); + } } - function getPDO() { - - if (!SABRE_HASSQLITE) $this->markTestSkipped('SQLite driver is not available'); + public function getPDO() + { + if (!SABRE_HASSQLITE) { + $this->markTestSkipped('SQLite driver is not available'); + } $pdo = new PDO('sqlite:'.SABRE_TEMPDIR.'/pdobackend'); - $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->query('CREATE TABLE principals (id INTEGER PRIMARY KEY ASC, uri TEXT, email VARCHAR(80), displayname VARCHAR(80), vcardurl VARCHAR(80))'); $pdo->query('INSERT INTO principals VALUES (1, "principals/user","user@example.org","User",null)'); $pdo->query('INSERT INTO principals VALUES (2, "principals/group","group@example.org","Group",null)'); - $pdo->query("CREATE TABLE groupmembers ( + $pdo->query('CREATE TABLE groupmembers ( id INTEGER PRIMARY KEY ASC, principal_id INT, member_id INT, UNIQUE(principal_id, member_id) - );"); + );'); - $pdo->query("INSERT INTO groupmembers (principal_id,member_id) VALUES (2,1)"); + $pdo->query('INSERT INTO groupmembers (principal_id,member_id) VALUES (2,1)'); return $pdo; - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalCollectionTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalCollectionTest.php index f0a475e8..553f1b76 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalCollectionTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalCollectionTest.php @@ -2,47 +2,43 @@ require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; -class Sabre_DAVACL_PrincipalCollectionTest extends PHPUnit_Framework_TestCase { - - public function testBasic() { - +class Sabre_DAVACL_PrincipalCollectionTest extends PHPUnit_Framework_TestCase +{ + public function testBasic() + { $backend = new Sabre_DAVACL_MockPrincipalBackend(); $pc = new Sabre_DAVACL_PrincipalCollection($backend); $this->assertTrue($pc instanceof Sabre_DAVACL_PrincipalCollection); - $this->assertEquals('principals',$pc->getName()); - + $this->assertEquals('principals', $pc->getName()); } /** * @depends testBasic */ - public function testGetChildren() { - + public function testGetChildren() + { $backend = new Sabre_DAVACL_MockPrincipalBackend(); $pc = new Sabre_DAVACL_PrincipalCollection($backend); $children = $pc->getChildren(); $this->assertTrue(is_array($children)); - foreach($children as $child) { + foreach ($children as $child) { $this->assertTrue($child instanceof Sabre_DAVACL_IPrincipal); } - } /** * @depends testBasic * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - public function testGetChildrenDisable() { - + public function testGetChildrenDisable() + { $backend = new Sabre_DAVACL_MockPrincipalBackend(); $pc = new Sabre_DAVACL_PrincipalCollection($backend); $pc->disableListing = true; $children = $pc->getChildren(); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalPropertySearchTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalPropertySearchTest.php index 0f1cc8ab..dabb5b48 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalPropertySearchTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalPropertySearchTest.php @@ -4,10 +4,10 @@ require_once 'Sabre/HTTP/ResponseMock.php'; require_once 'Sabre/DAV/Auth/MockBackend.php'; require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; -class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCase { - - function getServer() { - +class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCase +{ + public function getServer() + { $backend = new Sabre_DAVACL_MockPrincipalBackend(); $dir = new Sabre_DAV_SimpleCollection('root'); @@ -17,7 +17,7 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas $fakeServer = new Sabre_DAV_Server(new Sabre_DAV_ObjectTree($dir)); $fakeServer->httpResponse = new Sabre_HTTP_ResponseMock(); $fakeServer->debugExceptions = true; - $plugin = new Sabre_DAVACL_MockPlugin($backend,'realm'); + $plugin = new Sabre_DAVACL_MockPlugin($backend, 'realm'); $plugin->allowAccessToNodesWithoutACL = true; $this->assertTrue($plugin instanceof Sabre_DAVACL_Plugin); @@ -25,11 +25,10 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas $this->assertEquals($plugin, $fakeServer->getPlugin('acl')); return $fakeServer; - } - function testDepth1() { - + public function testDepth1() + { $xml = ' @@ -46,8 +45,8 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '1', - 'REQUEST_URI' => '/principals', + 'HTTP_DEPTH' => '1', + 'REQUEST_URI' => '/principals', ); $request = new Sabre_HTTP_Request($serverVars); @@ -62,12 +61,10 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - } - - function testUnknownSearchField() { - + public function testUnknownSearchField() + { $xml = ' @@ -84,8 +81,8 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '0', - 'REQUEST_URI' => '/principals', + 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/principals', ); $request = new Sabre_HTTP_Request($serverVars); @@ -100,11 +97,10 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - } - function testCorrect() { - + public function testCorrect() + { $xml = ' @@ -122,8 +118,8 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '0', - 'REQUEST_URI' => '/', + 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/', ); $request = new Sabre_HTTP_Request($serverVars); @@ -139,7 +135,6 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - $check = array( '/d:multistatus', '/d:multistatus/d:response' => 2, @@ -152,23 +147,22 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas ); $xml = simplexml_load_string($server->httpResponse->body); - $xml->registerXPathNamespace('d','DAV:'); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + $xml->registerXPathNamespace('d', 'DAV:'); + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); $count = 1; - if (!is_int($v1)) $count = $v2; - - $this->assertEquals($count,count($result), 'we expected ' . $count . ' appearances of ' . $xpath . ' . We found ' . count($result) . '. Full response body: ' . $server->httpResponse->body); + if (!is_int($v1)) { + $count = $v2; + } + $this->assertEquals($count, count($result), 'we expected '.$count.' appearances of '.$xpath.' . We found '.count($result).'. Full response body: '.$server->httpResponse->body); } - } - function testWrongUri() { - + public function testWrongUri() + { $xml = ' @@ -185,8 +179,8 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '0', - 'REQUEST_URI' => '/', + 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/', ); $request = new Sabre_HTTP_Request($serverVars); @@ -202,39 +196,35 @@ class Sabre_DAVACL_PrincipalPropertySearchTest extends PHPUnit_Framework_TestCas 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - $check = array( '/d:multistatus', '/d:multistatus/d:response' => 0, ); $xml = simplexml_load_string($server->httpResponse->body); - $xml->registerXPathNamespace('d','DAV:'); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + $xml->registerXPathNamespace('d', 'DAV:'); + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); $count = 1; - if (!is_int($v1)) $count = $v2; - - $this->assertEquals($count,count($result), 'we expected ' . $count . ' appearances of ' . $xpath . ' . We found ' . count($result) . '. Full response body: ' . $server->httpResponse->body); + if (!is_int($v1)) { + $count = $v2; + } + $this->assertEquals($count, count($result), 'we expected '.$count.' appearances of '.$xpath.' . We found '.count($result).'. Full response body: '.$server->httpResponse->body); } - } } -class Sabre_DAVACL_MockPlugin extends Sabre_DAVACL_Plugin { - - function getCurrentUserPrivilegeSet($node) { - +class Sabre_DAVACL_MockPlugin extends Sabre_DAVACL_Plugin +{ + public function getCurrentUserPrivilegeSet($node) + { return array( '{DAV:}read', '{DAV:}write', ); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalSearchPropertySetTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalSearchPropertySetTest.php index 35801ebe..c2c7144e 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalSearchPropertySetTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalSearchPropertySetTest.php @@ -3,10 +3,10 @@ require_once 'Sabre/HTTP/ResponseMock.php'; require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; -class Sabre_DAVACL_PrincipalSearchPropertySetTest extends PHPUnit_Framework_TestCase { - - function getServer() { - +class Sabre_DAVACL_PrincipalSearchPropertySetTest extends PHPUnit_Framework_TestCase +{ + public function getServer() + { $backend = new Sabre_DAVACL_MockPrincipalBackend(); $dir = new Sabre_DAV_SimpleCollection('root'); @@ -15,24 +15,23 @@ class Sabre_DAVACL_PrincipalSearchPropertySetTest extends PHPUnit_Framework_Test $fakeServer = new Sabre_DAV_Server(new Sabre_DAV_ObjectTree($dir)); $fakeServer->httpResponse = new Sabre_HTTP_ResponseMock(); - $plugin = new Sabre_DAVACL_Plugin($backend,'realm'); + $plugin = new Sabre_DAVACL_Plugin($backend, 'realm'); $this->assertTrue($plugin instanceof Sabre_DAVACL_Plugin); $fakeServer->addPlugin($plugin); $this->assertEquals($plugin, $fakeServer->getPlugin('acl')); return $fakeServer; - } - function testDepth1() { - + public function testDepth1() + { $xml = ' '; $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '1', - 'REQUEST_URI' => '/principals', + 'HTTP_DEPTH' => '1', + 'REQUEST_URI' => '/principals', ); $request = new Sabre_HTTP_Request($serverVars); @@ -47,18 +46,17 @@ class Sabre_DAVACL_PrincipalSearchPropertySetTest extends PHPUnit_Framework_Test $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - } - function testDepthIncorrectXML() { - + public function testDepthIncorrectXML() + { $xml = ' '; $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '0', - 'REQUEST_URI' => '/principals', + 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/principals', ); $request = new Sabre_HTTP_Request($serverVars); @@ -73,18 +71,17 @@ class Sabre_DAVACL_PrincipalSearchPropertySetTest extends PHPUnit_Framework_Test $this->assertEquals(array( 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - } - function testCorrect() { - + public function testCorrect() + { $xml = ' '; $serverVars = array( 'REQUEST_METHOD' => 'REPORT', - 'HTTP_DEPTH' => '0', - 'REQUEST_URI' => '/principals', + 'HTTP_DEPTH' => '0', + 'REQUEST_URI' => '/principals', ); $request = new Sabre_HTTP_Request($serverVars); @@ -100,7 +97,6 @@ class Sabre_DAVACL_PrincipalSearchPropertySetTest extends PHPUnit_Framework_Test 'Content-Type' => 'application/xml; charset=utf-8', ), $server->httpResponse->headers); - $check = array( '/d:principal-search-property-set', '/d:principal-search-property-set/d:principal-search-property' => 2, @@ -111,21 +107,19 @@ class Sabre_DAVACL_PrincipalSearchPropertySetTest extends PHPUnit_Framework_Test ); $xml = simplexml_load_string($server->httpResponse->body); - $xml->registerXPathNamespace('d','DAV:'); - $xml->registerXPathNamespace('s','http://sabredav.org/ns'); - foreach($check as $v1=>$v2) { - - $xpath = is_int($v1)?$v2:$v1; + $xml->registerXPathNamespace('d', 'DAV:'); + $xml->registerXPathNamespace('s', 'http://sabredav.org/ns'); + foreach ($check as $v1 => $v2) { + $xpath = is_int($v1) ? $v2 : $v1; $result = $xml->xpath($xpath); $count = 1; - if (!is_int($v1)) $count = $v2; - - $this->assertEquals($count,count($result), 'we expected ' . $count . ' appearances of ' . $xpath . ' . We found ' . count($result) . '. Full response body: ' . $server->httpResponse->body); + if (!is_int($v1)) { + $count = $v2; + } + $this->assertEquals($count, count($result), 'we expected '.$count.' appearances of '.$xpath.' . We found '.count($result).'. Full response body: '.$server->httpResponse->body); } - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalTest.php index b00e1239..baad76a5 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/PrincipalTest.php @@ -2,50 +2,46 @@ require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; -class Sabre_DAVACL_PrincipalTest extends PHPUnit_Framework_TestCase { - - public function testConstruct() { - +class Sabre_DAVACL_PrincipalTest extends PHPUnit_Framework_TestCase +{ + public function testConstruct() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); $this->assertTrue($principal instanceof Sabre_DAVACL_Principal); - } /** * @expectedException Sabre_DAV_Exception */ - public function testConstructNoUri() { - + public function testConstructNoUri() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array()); - } - public function testGetName() { - + public function testGetName() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); - $this->assertEquals('admin',$principal->getName()); - + $this->assertEquals('admin', $principal->getName()); } - public function testGetDisplayName() { - + public function testGetDisplayName() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); - $this->assertEquals('admin',$principal->getDisplayname()); + $this->assertEquals('admin', $principal->getDisplayname()); $principal = new Sabre_DAVACL_Principal($principalBackend, array( 'uri' => 'principals/admin', - '{DAV:}displayname' => 'Mr. Admin' + '{DAV:}displayname' => 'Mr. Admin', )); - $this->assertEquals('Mr. Admin',$principal->getDisplayname()); - + $this->assertEquals('Mr. Admin', $principal->getDisplayname()); } - public function testGetProperties() { - + public function testGetProperties() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array( 'uri' => 'principals/admin', @@ -61,32 +57,32 @@ class Sabre_DAVACL_PrincipalTest extends PHPUnit_Framework_TestCase { ); $props = $principal->getProperties($keys); - foreach($keys as $key) $this->assertArrayHasKey($key,$props); + foreach ($keys as $key) { + $this->assertArrayHasKey($key, $props); + } - $this->assertEquals('Mr. Admin',$props['{DAV:}displayname']); + $this->assertEquals('Mr. Admin', $props['{DAV:}displayname']); $this->assertEquals('admin@example.org', $props['{http://sabredav.org/ns}email-address']); } - public function testUpdateProperties() { - + public function testUpdateProperties() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); - $result = $principal->updateProperties(array('{DAV:}yourmom'=>'test')); - $this->assertEquals(true,$result); - + $result = $principal->updateProperties(array('{DAV:}yourmom' => 'test')); + $this->assertEquals(true, $result); } - public function testGetPrincipalUrl() { - + public function testGetPrincipalUrl() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); - $this->assertEquals('principals/admin',$principal->getPrincipalUrl()); - + $this->assertEquals('principals/admin', $principal->getPrincipalUrl()); } - public function testGetAlternateUriSet() { - + public function testGetAlternateUriSet() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array( 'uri' => 'principals/admin', @@ -106,11 +102,10 @@ class Sabre_DAVACL_PrincipalTest extends PHPUnit_Framework_TestCase { 'mailto:admin@example.org', ); - $this->assertEquals($expected,$principal->getAlternateUriSet()); - + $this->assertEquals($expected, $principal->getAlternateUriSet()); } - public function testGetAlternateUriSetEmpty() { - + public function testGetAlternateUriSetEmpty() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array( 'uri' => 'principals/admin', @@ -118,27 +113,24 @@ class Sabre_DAVACL_PrincipalTest extends PHPUnit_Framework_TestCase { $expected = array(); - $this->assertEquals($expected,$principal->getAlternateUriSet()); - + $this->assertEquals($expected, $principal->getAlternateUriSet()); } - public function testGetGroupMemberSet() { - + public function testGetGroupMemberSet() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); - $this->assertEquals(array(),$principal->getGroupMemberSet()); - + $this->assertEquals(array(), $principal->getGroupMemberSet()); } - public function testGetGroupMembership() { - + public function testGetGroupMembership() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); - $this->assertEquals(array(),$principal->getGroupMembership()); - + $this->assertEquals(array(), $principal->getGroupMembership()); } - public function testSetGroupMemberSet() { - + public function testSetGroupMemberSet() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); $principal->setGroupMemberSet(array('principals/foo')); @@ -146,27 +138,24 @@ class Sabre_DAVACL_PrincipalTest extends PHPUnit_Framework_TestCase { $this->assertEquals(array( 'principals/admin' => array('principals/foo'), ), $principalBackend->groupMembers); - } - public function testGetOwner() { - + public function testGetOwner() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); - $this->assertEquals('principals/admin',$principal->getOwner()); - + $this->assertEquals('principals/admin', $principal->getOwner()); } - public function testGetGroup() { - + public function testGetGroup() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); $this->assertNull($principal->getGroup()); - } - public function testGetACl() { - + public function testGetACl() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); $this->assertEquals(array( @@ -174,28 +163,24 @@ class Sabre_DAVACL_PrincipalTest extends PHPUnit_Framework_TestCase { 'privilege' => '{DAV:}read', 'principal' => 'principals/admin', 'protected' => true, - ) - ),$principal->getACL()); - + ), + ), $principal->getACL()); } /** * @expectedException Sabre_DAV_Exception_MethodNotAllowed */ - public function testSetACl() { - + public function testSetACl() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); $principal->setACL(array()); - } - public function testGetSupportedPrivilegeSet() { - + public function testGetSupportedPrivilegeSet() + { $principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); $principal = new Sabre_DAVACL_Principal($principalBackend, array('uri' => 'principals/admin')); $this->assertNull($principal->getSupportedPrivilegeSet()); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/Property/ACLRestrictionsTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/Property/ACLRestrictionsTest.php index 921052bc..9d6eb344 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/Property/ACLRestrictionsTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/Property/ACLRestrictionsTest.php @@ -1,17 +1,16 @@ createElementNS('DAV:','d:root'); + $root = $dom->createElementNS('DAV:', 'd:root'); $dom->appendChild($root); @@ -23,8 +22,5 @@ class Sabre_DAVACL_Property_ACLRestrictionsTest extends PHPUnit_Framework_TestCa '; $this->assertEquals($expected, $xml); - } - - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/Property/ACLTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/Property/ACLTest.php index a6efee2d..bf37d057 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/Property/ACLTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/Property/ACLTest.php @@ -1,17 +1,16 @@ createElementNS('DAV:','d:root'); + $root = $dom->createElementNS('DAV:', 'd:root'); $dom->appendChild($root); @@ -23,13 +22,12 @@ class Sabre_DAVACL_Property_ACLTest extends PHPUnit_Framework_TestCase { '; $this->assertEquals($expected, $xml); - } - function testSerialize() { - + public function testSerialize() + { $dom = new DOMDocument('1.0'); - $root = $dom->createElementNS('DAV:','d:root'); + $root = $dom->createElementNS('DAV:', 'd:root'); $dom->appendChild($root); @@ -37,12 +35,12 @@ class Sabre_DAVACL_Property_ACLTest extends PHPUnit_Framework_TestCase { array( 'principal' => 'principals/evert', 'privilege' => '{DAV:}write', - 'uri' => 'articles', + 'uri' => 'articles', ), array( 'principal' => 'principals/foo', 'privilege' => '{DAV:}read', - 'uri' => 'articles', + 'uri' => 'articles', 'protected' => true, ), ); @@ -79,13 +77,12 @@ class Sabre_DAVACL_Property_ACLTest extends PHPUnit_Framework_TestCase { '; $this->assertEquals($expected, $xml); - } - function testSerializeSpecialPrincipals() { - + public function testSerializeSpecialPrincipals() + { $dom = new DOMDocument('1.0'); - $root = $dom->createElementNS('DAV:','d:root'); + $root = $dom->createElementNS('DAV:', 'd:root'); $dom->appendChild($root); @@ -93,17 +90,17 @@ class Sabre_DAVACL_Property_ACLTest extends PHPUnit_Framework_TestCase { array( 'principal' => '{DAV:}authenticated', 'privilege' => '{DAV:}write', - 'uri' => 'articles', + 'uri' => 'articles', ), array( 'principal' => '{DAV:}unauthenticated', 'privilege' => '{DAV:}write', - 'uri' => 'articles', + 'uri' => 'articles', ), array( 'principal' => '{DAV:}all', 'privilege' => '{DAV:}write', - 'uri' => 'articles', + 'uri' => 'articles', ), ); @@ -149,11 +146,10 @@ class Sabre_DAVACL_Property_ACLTest extends PHPUnit_Framework_TestCase { '; $this->assertEquals($expected, $xml); - } - function testUnserialize() { - + public function testUnserialize() + { $source = ' @@ -199,15 +195,13 @@ class Sabre_DAVACL_Property_ACLTest extends PHPUnit_Framework_TestCase { ); $this->assertEquals($expected, $result->getPrivileges()); - - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testUnserializeNoPrincipal() { - + public function testUnserializeNoPrincipal() + { $source = ' @@ -222,11 +216,10 @@ class Sabre_DAVACL_Property_ACLTest extends PHPUnit_Framework_TestCase { $dom = Sabre_DAV_XMLUtil::loadDOMDocument($source); Sabre_DAVACL_Property_Acl::unserialize($dom->firstChild); - } - function testUnserializeOtherPrincipal() { - + public function testUnserializeOtherPrincipal() + { $source = ' @@ -280,15 +273,13 @@ class Sabre_DAVACL_Property_ACLTest extends PHPUnit_Framework_TestCase { ); $this->assertEquals($expected, $result->getPrivileges()); - - } /** * @expectedException Sabre_DAV_Exception_NotImplemented */ - function testUnserializeDeny() { - + public function testUnserializeDeny() + { $source = ' @@ -309,8 +300,8 @@ class Sabre_DAVACL_Property_ACLTest extends PHPUnit_Framework_TestCase { /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testUnserializeMissingPriv() { - + public function testUnserializeMissingPriv() + { $source = ' @@ -324,6 +315,5 @@ class Sabre_DAVACL_Property_ACLTest extends PHPUnit_Framework_TestCase { $dom = Sabre_DAV_XMLUtil::loadDOMDocument($source); Sabre_DAVACL_Property_Acl::unserialize($dom->firstChild); - } } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/Property/CurrentUserPrivilegeSetTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/Property/CurrentUserPrivilegeSetTest.php index 40a8983b..850eaf66 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/Property/CurrentUserPrivilegeSetTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/Property/CurrentUserPrivilegeSetTest.php @@ -1,9 +1,9 @@ createElementNS('DAV:','d:root'); + $dom = new DOMDocument('1.0', 'utf-8'); + $root = $dom->createElementNS('DAV:', 'd:root'); $dom->appendChild($root); $prop->serialize($server, $root); @@ -29,13 +29,9 @@ class Sabre_DAVACL_Property_CurrentUserPrivilegeSetTest extends PHPUnit_Framewor $dom2->loadXML($dom->saveXML()); $dxpath = new DOMXPath($dom2); - $dxpath->registerNamespace('d','DAV:'); - foreach($xpaths as $xpath=>$count) { - - $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : ' . $xpath . ', we could only find ' . $dxpath->query($xpath)->length . ' elements, while we expected ' . $count); - + $dxpath->registerNamespace('d', 'DAV:'); + foreach ($xpaths as $xpath => $count) { + $this->assertEquals($count, $dxpath->query($xpath)->length, 'Looking for : '.$xpath.', we could only find '.$dxpath->query($xpath)->length.' elements, while we expected '.$count); } - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/Property/PrincipalTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/Property/PrincipalTest.php index 3f8592e8..c452e35c 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/Property/PrincipalTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/Property/PrincipalTest.php @@ -1,9 +1,9 @@ assertEquals(Sabre_DAVACL_Property_Principal::UNAUTHENTICATED, $principal->getType()); $this->assertNull($principal->getHref()); @@ -12,32 +12,30 @@ class Sabre_DAVACL_Property_PrincipalTest extends PHPUnit_Framework_TestCase { $this->assertEquals(Sabre_DAVACL_Property_Principal::AUTHENTICATED, $principal->getType()); $this->assertNull($principal->getHref()); - $principal = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF,'admin'); + $principal = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF, 'admin'); $this->assertEquals(Sabre_DAVACL_Property_Principal::HREF, $principal->getType()); - $this->assertEquals('admin',$principal->getHref()); - + $this->assertEquals('admin', $principal->getHref()); } /** * @depends testSimple * @expectedException Sabre_DAV_Exception */ - function testNoHref() { - + public function testNoHref() + { $principal = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF); - } /** * @depends testSimple */ - function testSerializeUnAuthenticated() { - + public function testSerializeUnAuthenticated() + { $prin = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::UNAUTHENTICATED); $doc = new DOMDocument(); $root = $doc->createElement('d:principal'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -50,23 +48,21 @@ class Sabre_DAVACL_Property_PrincipalTest extends PHPUnit_Framework_TestCase { $this->assertEquals( ' ' . -'' . +''. ' ', $xml); - } - /** * @depends testSerializeUnAuthenticated */ - function testSerializeAuthenticated() { - + public function testSerializeAuthenticated() + { $prin = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::AUTHENTICATED); $doc = new DOMDocument(); $root = $doc->createElement('d:principal'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -79,23 +75,21 @@ class Sabre_DAVACL_Property_PrincipalTest extends PHPUnit_Framework_TestCase { $this->assertEquals( ' ' . -'' . +''. ' ', $xml); - } - /** * @depends testSerializeUnAuthenticated */ - function testSerializeHref() { - - $prin = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF,'principals/admin'); + public function testSerializeHref() + { + $prin = new Sabre_DAVACL_Property_Principal(Sabre_DAVACL_Property_Principal::HREF, 'principals/admin'); $doc = new DOMDocument(); $root = $doc->createElement('d:principal'); - $root->setAttribute('xmlns:d','DAV:'); + $root->setAttribute('xmlns:d', 'DAV:'); $doc->appendChild($root); $objectTree = new Sabre_DAV_ObjectTree(new Sabre_DAV_SimpleCollection('rootdir')); @@ -108,17 +102,16 @@ class Sabre_DAVACL_Property_PrincipalTest extends PHPUnit_Framework_TestCase { $this->assertEquals( ' ' . -'/principals/admin' . +'/principals/admin'. ' ', $xml); - } - function testUnserializeHref() { - + public function testUnserializeHref() + { $xml = ' ' . -'/principals/admin' . +'/principals/admin'. ''; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); @@ -126,51 +119,46 @@ class Sabre_DAVACL_Property_PrincipalTest extends PHPUnit_Framework_TestCase { $principal = Sabre_DAVACL_Property_Principal::unserialize($dom->firstChild); $this->assertEquals(Sabre_DAVACL_Property_Principal::HREF, $principal->getType()); $this->assertEquals('/principals/admin', $principal->getHref()); - } - function testUnserializeAuthenticated() { - + public function testUnserializeAuthenticated() + { $xml = ' ' . -' ' . +' '. ''; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); $principal = Sabre_DAVACL_Property_Principal::unserialize($dom->firstChild); $this->assertEquals(Sabre_DAVACL_Property_Principal::AUTHENTICATED, $principal->getType()); - } - function testUnserializeUnauthenticated() { - + public function testUnserializeUnauthenticated() + { $xml = ' ' . -' ' . +' '. ''; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); $principal = Sabre_DAVACL_Property_Principal::unserialize($dom->firstChild); $this->assertEquals(Sabre_DAVACL_Property_Principal::UNAUTHENTICATED, $principal->getType()); - } /** * @expectedException Sabre_DAV_Exception_BadRequest */ - function testUnserializeUnknown() { - + public function testUnserializeUnknown() + { $xml = ' ' . -' ' . +' '. ''; $dom = Sabre_DAV_XMLUtil::loadDOMDocument($xml); Sabre_DAVACL_Property_Principal::unserialize($dom->firstChild); - } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/Property/SupportedPrivilegeSetTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/Property/SupportedPrivilegeSetTest.php index 0dc94836..0c21b6c5 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/Property/SupportedPrivilegeSetTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/Property/SupportedPrivilegeSetTest.php @@ -1,21 +1,19 @@ '{DAV:}all', )); - } - /** * @depends testSimple */ - function testSerializeSimple() { - + public function testSerializeSimple() + { $prop = new Sabre_DAVACL_Property_SupportedPrivilegeSet(array( 'privilege' => '{DAV:}all', )); @@ -33,24 +31,23 @@ class Sabre_DAVACL_Property_SupportedPrivilegeSetTest extends PHPUnit_Framework_ $this->assertEquals( ' ' . -'' . -'' . -'' . -'' . -'' . +''. +''. +''. +''. +''. ' ', $xml); - } /** * @depends testSimple */ - function testSerializeAggregate() { - + public function testSerializeAggregate() + { $prop = new Sabre_DAVACL_Property_SupportedPrivilegeSet(array( 'privilege' => '{DAV:}all', - 'abstract' => true, + 'abstract' => true, 'aggregates' => array( array( 'privilege' => '{DAV:}read', @@ -75,25 +72,24 @@ class Sabre_DAVACL_Property_SupportedPrivilegeSetTest extends PHPUnit_Framework_ $this->assertEquals( ' ' . -'' . -'' . -'' . -'' . -'' . -'' . -'' . -'' . -'' . -'' . -'' . -'' . -'' . -'' . -'booh' . -'' . -'' . +''. +''. +''. +''. +''. +''. +''. +''. +''. +''. +''. +''. +''. +''. +'booh'. +''. +''. ' ', $xml); - } } diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/SimplePluginTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/SimplePluginTest.php index de224ae6..ab01ca64 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/SimplePluginTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/SimplePluginTest.php @@ -4,28 +4,27 @@ require_once 'Sabre/DAV/Auth/MockBackend.php'; require_once 'Sabre/DAVACL/MockPrincipal.php'; require_once 'Sabre/DAVACL/MockACLNode.php'; -class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { - - function testValues() { - +class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase +{ + public function testValues() + { $aclPlugin = new Sabre_DAVACL_Plugin(); - $this->assertEquals('acl',$aclPlugin->getPluginName()); + $this->assertEquals('acl', $aclPlugin->getPluginName()); $this->assertEquals(array('access-control'), $aclPlugin->getFeatures()); $this->assertEquals( array( '{DAV:}expand-property', '{DAV:}principal-property-search', - '{DAV:}principal-search-property-set' + '{DAV:}principal-search-property-set', ), $aclPlugin->getSupportedReportSet('')); $this->assertEquals(array('ACL'), $aclPlugin->getMethods('')); - } - function testGetFlatPrivilegeSet() { - + public function testGetFlatPrivilegeSet() + { $expected = array( '{DAV:}all' => array( 'privilege' => '{DAV:}all', @@ -113,26 +112,24 @@ class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { $server = new Sabre_DAV_Server(); $server->addPlugin($plugin); $this->assertEquals($expected, $plugin->getFlatPrivilegeSet('')); - } - function testCurrentUserPrincipalsNotLoggedIn() { - + public function testCurrentUserPrincipalsNotLoggedIn() + { $acl = new Sabre_DAVACL_Plugin(); $server = new Sabre_DAV_Server(); $server->addPlugin($acl); - $this->assertEquals(array(),$acl->getCurrentUserPrincipals()); - + $this->assertEquals(array(), $acl->getCurrentUserPrincipals()); } - function testCurrentUserPrincipalsSimple() { - + public function testCurrentUserPrincipalsSimple() + { $tree = array( new Sabre_DAV_SimpleCollection('principals', array( - new Sabre_DAVACL_MockPrincipal('admin','principals/admin'), - )) + new Sabre_DAVACL_MockPrincipal('admin', 'principals/admin'), + )), ); @@ -140,26 +137,25 @@ class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { $server = new Sabre_DAV_Server($tree); $server->addPlugin($acl); - $auth = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'SabreDAV'); + $auth = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'SabreDAV'); $server->addPlugin($auth); //forcing login - $auth->beforeMethod('GET','/'); - - $this->assertEquals(array('principals/admin'),$acl->getCurrentUserPrincipals()); + $auth->beforeMethod('GET', '/'); + $this->assertEquals(array('principals/admin'), $acl->getCurrentUserPrincipals()); } - function testCurrentUserPrincipalsGroups() { - + public function testCurrentUserPrincipalsGroups() + { $tree = array( new Sabre_DAV_SimpleCollection('principals', array( - new Sabre_DAVACL_MockPrincipal('admin','principals/admin',array('principals/administrators', 'principals/everyone')), - new Sabre_DAVACL_MockPrincipal('administrators','principals/administrators',array('principals/groups'), array('principals/admin')), - new Sabre_DAVACL_MockPrincipal('everyone','principals/everyone',array(), array('principals/admin')), - new Sabre_DAVACL_MockPrincipal('groups','principals/groups',array(), array('principals/administrators')), - )) + new Sabre_DAVACL_MockPrincipal('admin', 'principals/admin', array('principals/administrators', 'principals/everyone')), + new Sabre_DAVACL_MockPrincipal('administrators', 'principals/administrators', array('principals/groups'), array('principals/admin')), + new Sabre_DAVACL_MockPrincipal('everyone', 'principals/everyone', array(), array('principals/admin')), + new Sabre_DAVACL_MockPrincipal('groups', 'principals/groups', array(), array('principals/administrators')), + )), ); @@ -167,11 +163,11 @@ class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { $server = new Sabre_DAV_Server($tree); $server->addPlugin($acl); - $auth = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'SabreDAV'); + $auth = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'SabreDAV'); $server->addPlugin($auth); //forcing login - $auth->beforeMethod('GET','/'); + $auth->beforeMethod('GET', '/'); $expected = array( 'principals/admin', @@ -180,12 +176,11 @@ class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { 'principals/groups', ); - $this->assertEquals($expected,$acl->getCurrentUserPrincipals()); - + $this->assertEquals($expected, $acl->getCurrentUserPrincipals()); } - function testGetACL() { - + public function testGetACL() + { $acl = array( array( 'principal' => 'principals/admin', @@ -197,21 +192,19 @@ class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { ), ); - $tree = array( - new Sabre_DAVACL_MockACLNode('foo',$acl), + new Sabre_DAVACL_MockACLNode('foo', $acl), ); $server = new Sabre_DAV_Server($tree); $aclPlugin = new Sabre_DAVACL_Plugin(); $server->addPlugin($aclPlugin); - $this->assertEquals($acl,$aclPlugin->getACL('foo')); - + $this->assertEquals($acl, $aclPlugin->getACL('foo')); } - function testGetCurrentUserPrivilegeSet() { - + public function testGetCurrentUserPrivilegeSet() + { $acl = array( array( 'principal' => 'principals/admin', @@ -227,12 +220,11 @@ class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { ), ); - $tree = array( - new Sabre_DAVACL_MockACLNode('foo',$acl), + new Sabre_DAVACL_MockACLNode('foo', $acl), new Sabre_DAV_SimpleCollection('principals', array( - new Sabre_DAVACL_MockPrincipal('admin','principals/admin'), + new Sabre_DAVACL_MockPrincipal('admin', 'principals/admin'), )), ); @@ -241,11 +233,11 @@ class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { $aclPlugin = new Sabre_DAVACL_Plugin(); $server->addPlugin($aclPlugin); - $auth = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'SabreDAV'); + $auth = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'SabreDAV'); $server->addPlugin($auth); //forcing login - $auth->beforeMethod('GET','/'); + $auth->beforeMethod('GET', '/'); $expected = array( '{DAV:}write', @@ -260,12 +252,11 @@ class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { '{DAV:}read-current-user-privilege-set', ); - $this->assertEquals($expected,$aclPlugin->getCurrentUserPrivilegeSet('foo')); - + $this->assertEquals($expected, $aclPlugin->getCurrentUserPrivilegeSet('foo')); } - function testCheckPrivileges() { - + public function testCheckPrivileges() + { $acl = array( array( 'principal' => 'principals/admin', @@ -281,12 +272,11 @@ class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { ), ); - $tree = array( - new Sabre_DAVACL_MockACLNode('foo',$acl), + new Sabre_DAVACL_MockACLNode('foo', $acl), new Sabre_DAV_SimpleCollection('principals', array( - new Sabre_DAVACL_MockPrincipal('admin','principals/admin'), + new Sabre_DAVACL_MockPrincipal('admin', 'principals/admin'), )), ); @@ -295,17 +285,12 @@ class Sabre_DAVACL_SimplePluginTest extends PHPUnit_Framework_TestCase { $aclPlugin = new Sabre_DAVACL_Plugin(); $server->addPlugin($aclPlugin); - $auth = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(),'SabreDAV'); + $auth = new Sabre_DAV_Auth_Plugin(new Sabre_DAV_Auth_MockBackend(), 'SabreDAV'); $server->addPlugin($auth); //forcing login //$auth->beforeMethod('GET','/'); $this->assertFalse($aclPlugin->checkPrivileges('foo', array('{DAV:}read'), Sabre_DAVACL_Plugin::R_PARENT, false)); - } } - - - - diff --git a/dav/SabreDAV/tests/Sabre/DAVACL/VersionTest.php b/dav/SabreDAV/tests/Sabre/DAVACL/VersionTest.php index 216bd05c..fe7feead 100644 --- a/dav/SabreDAV/tests/Sabre/DAVACL/VersionTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVACL/VersionTest.php @@ -1,15 +1,13 @@ assertEquals(-1, version_compare('1.0.0',$v)); + $this->assertEquals(-1, version_compare('1.0.0', $v)); $s = Sabre_DAVACL_Version::STABILITY; - $this->assertTrue($s == 'alpha' || $s == 'beta' || $s =='stable'); - + $this->assertTrue($s == 'alpha' || $s == 'beta' || $s == 'stable'); } - } diff --git a/dav/SabreDAV/tests/Sabre/DAVServerTest.php b/dav/SabreDAV/tests/Sabre/DAVServerTest.php index 910e77b8..7112d75e 100644 --- a/dav/SabreDAV/tests/Sabre/DAVServerTest.php +++ b/dav/SabreDAV/tests/Sabre/DAVServerTest.php @@ -11,13 +11,12 @@ require_once 'Sabre/DAVACL/MockPrincipalBackend.php'; * This class is supposed to provide a reasonably big framework to quickly get * a testing environment running. * - * @package Sabre - * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved. + * @copyright Copyright (C) 2007-2012 Rooftop Solutions. All rights reserved * @author Evert Pot (http://www.rooftopsolutions.nl/) * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -abstract class Sabre_DAVServerTest extends PHPUnit_Framework_TestCase { - +abstract class Sabre_DAVServerTest extends PHPUnit_Framework_TestCase +{ protected $setupCalDAV = false; protected $setupCardDAV = false; @@ -43,8 +42,8 @@ abstract class Sabre_DAVServerTest extends PHPUnit_Framework_TestCase { protected $caldavPlugin; protected $carddavPlugin; - function setUp() { - + public function setUp() + { $this->setUpBackends(); $this->setUpTree(); @@ -58,7 +57,6 @@ abstract class Sabre_DAVServerTest extends PHPUnit_Framework_TestCase { $this->carddavPlugin = new Sabre_CardDAV_Plugin(); $this->server->addPlugin($this->carddavPlugin); } - } /** @@ -68,10 +66,11 @@ abstract class Sabre_DAVServerTest extends PHPUnit_Framework_TestCase { * which will then be used as the _SERVER array. * * @param array|Sabre_HTTP_Request $request + * * @return Sabre_HTTP_Response */ - function request($request) { - + public function request($request) + { if (is_array($request)) { $request = new Sabre_HTTP_Request($request); } @@ -80,11 +79,10 @@ abstract class Sabre_DAVServerTest extends PHPUnit_Framework_TestCase { $this->server->exec(); return $this->server->httpResponse; - } - function setUpTree() { - + public function setUpTree() + { if ($this->setupCalDAV) { $this->tree[] = new Sabre_CalDAV_CalendarRootNode( $this->principalBackend, @@ -103,11 +101,10 @@ abstract class Sabre_DAVServerTest extends PHPUnit_Framework_TestCase { $this->principalBackend ); } - } - function setUpBackends() { - + public function setUpBackends() + { if ($this->setupCalDAV) { $this->caldavBackend = new Sabre_CalDAV_Backend_Mock($this->caldavCalendars, $this->caldavCalendarObjects); } @@ -117,15 +114,11 @@ abstract class Sabre_DAVServerTest extends PHPUnit_Framework_TestCase { if ($this->setupCardDAV || $this->setupCalDAV) { $this->principalBackend = new Sabre_DAVACL_MockPrincipalBackend(); } - } - - function assertHTTPStatus($expectedStatus, Sabre_HTTP_Request $req) { - + public function assertHTTPStatus($expectedStatus, Sabre_HTTP_Request $req) + { $resp = $this->request($req); - $this->assertEquals($resp->getStatusMessage($expectedStatus), $resp->status,'Incorrect HTTP status received: ' . $resp->body); - + $this->assertEquals($resp->getStatusMessage($expectedStatus), $resp->status, 'Incorrect HTTP status received: '.$resp->body); } - } diff --git a/dav/SabreDAV/tests/Sabre/HTTP/AWSAuthTest.php b/dav/SabreDAV/tests/Sabre/HTTP/AWSAuthTest.php index b402146a..23c0ab7c 100644 --- a/dav/SabreDAV/tests/Sabre/HTTP/AWSAuthTest.php +++ b/dav/SabreDAV/tests/Sabre/HTTP/AWSAuthTest.php @@ -2,8 +2,8 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_HTTP_AWSAuthTest extends PHPUnit_Framework_TestCase { - +class Sabre_HTTP_AWSAuthTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_HTTP_ResponseMock */ @@ -15,17 +15,16 @@ class Sabre_HTTP_AWSAuthTest extends PHPUnit_Framework_TestCase { const REALM = 'SabreDAV unittest'; - public function setUp() { - + public function setUp() + { $this->response = new Sabre_HTTP_ResponseMock(); $this->auth = new Sabre_HTTP_AWSAuth(); $this->auth->setRealm(self::REALM); $this->auth->setHTTPResponse($this->response); - } - public function testNoHeader() { - + public function testNoHeader() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'GET', )); @@ -34,21 +33,20 @@ class Sabre_HTTP_AWSAuthTest extends PHPUnit_Framework_TestCase { $result = $this->auth->init(); - $this->assertFalse($result,'No AWS Authorization header was supplied, so we should have gotten false'); - $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_NOAWSHEADER,$this->auth->errorCode); - + $this->assertFalse($result, 'No AWS Authorization header was supplied, so we should have gotten false'); + $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_NOAWSHEADER, $this->auth->errorCode); } - public function testIncorrectContentMD5() { - + public function testIncorrectContentMD5() + { $accessKey = 'accessKey'; $secretKey = 'secretKey'; $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'GET', - 'HTTP_AUTHORIZATION' => "AWS $accessKey:sig", - 'HTTP_CONTENT_MD5' => 'garbage', - 'REQUEST_URI' => '/', + 'REQUEST_METHOD' => 'GET', + 'HTTP_AUTHORIZATION' => "AWS $accessKey:sig", + 'HTTP_CONTENT_MD5' => 'garbage', + 'REQUEST_URI' => '/', )); $this->auth->setHTTPRequest($request); @@ -56,22 +54,20 @@ class Sabre_HTTP_AWSAuthTest extends PHPUnit_Framework_TestCase { $result = $this->auth->validate($secretKey); $this->assertFalse($result); - $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_MD5CHECKSUMWRONG,$this->auth->errorCode); - + $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_MD5CHECKSUMWRONG, $this->auth->errorCode); } - public function testNoDate() { - + public function testNoDate() + { $accessKey = 'accessKey'; $secretKey = 'secretKey'; $content = 'thisisthebody'; - $contentMD5 = base64_encode(md5($content,true)); - + $contentMD5 = base64_encode(md5($content, true)); $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'HTTP_AUTHORIZATION' => "AWS $accessKey:sig", - 'HTTP_CONTENT_MD5' => $contentMD5, + 'REQUEST_METHOD' => 'POST', + 'HTTP_AUTHORIZATION' => "AWS $accessKey:sig", + 'HTTP_CONTENT_MD5' => $contentMD5, )); $request->setBody($content); @@ -81,26 +77,25 @@ class Sabre_HTTP_AWSAuthTest extends PHPUnit_Framework_TestCase { $result = $this->auth->validate($secretKey); $this->assertFalse($result); - $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_INVALIDDATEFORMAT,$this->auth->errorCode); - + $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_INVALIDDATEFORMAT, $this->auth->errorCode); } - public function testFutureDate() { - + public function testFutureDate() + { $accessKey = 'accessKey'; $secretKey = 'secretKey'; $content = 'thisisthebody'; - $contentMD5 = base64_encode(md5($content,true)); + $contentMD5 = base64_encode(md5($content, true)); - $date = new DateTime('@' . (time() + (60*20))); + $date = new DateTime('@'.(time() + (60 * 20))); $date->setTimeZone(new DateTimeZone('GMT')); $date = $date->format('D, d M Y H:i:s \\G\\M\\T'); $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'HTTP_AUTHORIZATION' => "AWS $accessKey:sig", - 'HTTP_CONTENT_MD5' => $contentMD5, - 'HTTP_DATE' => $date, + 'REQUEST_METHOD' => 'POST', + 'HTTP_AUTHORIZATION' => "AWS $accessKey:sig", + 'HTTP_CONTENT_MD5' => $contentMD5, + 'HTTP_DATE' => $date, )); $request->setBody($content); @@ -110,26 +105,25 @@ class Sabre_HTTP_AWSAuthTest extends PHPUnit_Framework_TestCase { $result = $this->auth->validate($secretKey); $this->assertFalse($result); - $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_REQUESTTIMESKEWED,$this->auth->errorCode); - + $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_REQUESTTIMESKEWED, $this->auth->errorCode); } - public function testPastDate() { - + public function testPastDate() + { $accessKey = 'accessKey'; $secretKey = 'secretKey'; $content = 'thisisthebody'; - $contentMD5 = base64_encode(md5($content,true)); + $contentMD5 = base64_encode(md5($content, true)); - $date = new DateTime('@' . (time() - (60*20))); + $date = new DateTime('@'.(time() - (60 * 20))); $date->setTimeZone(new DateTimeZone('GMT')); $date = $date->format('D, d M Y H:i:s \\G\\M\\T'); $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'HTTP_AUTHORIZATION' => "AWS $accessKey:sig", - 'HTTP_CONTENT_MD5' => $contentMD5, - 'HTTP_X_AMZ_DATE' => $date, + 'REQUEST_METHOD' => 'POST', + 'HTTP_AUTHORIZATION' => "AWS $accessKey:sig", + 'HTTP_CONTENT_MD5' => $contentMD5, + 'HTTP_X_AMZ_DATE' => $date, )); $request->setBody($content); @@ -139,28 +133,27 @@ class Sabre_HTTP_AWSAuthTest extends PHPUnit_Framework_TestCase { $result = $this->auth->validate($secretKey); $this->assertFalse($result); - $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_REQUESTTIMESKEWED,$this->auth->errorCode); - + $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_REQUESTTIMESKEWED, $this->auth->errorCode); } - public function testIncorrectSignature() { - + public function testIncorrectSignature() + { $accessKey = 'accessKey'; $secretKey = 'secretKey'; $content = 'thisisthebody'; - $contentMD5 = base64_encode(md5($content,true)); + $contentMD5 = base64_encode(md5($content, true)); $date = new DateTime('now'); $date->setTimeZone(new DateTimeZone('GMT')); $date = $date->format('D, d M Y H:i:s \\G\\M\\T'); $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'HTTP_AUTHORIZATION' => "AWS $accessKey:sig", - 'HTTP_CONTENT_MD5' => $contentMD5, - 'HTTP_X_AMZ_DATE' => $date, - 'REQUEST_URI' => '/', + 'REQUEST_METHOD' => 'POST', + 'HTTP_AUTHORIZATION' => "AWS $accessKey:sig", + 'HTTP_CONTENT_MD5' => $contentMD5, + 'HTTP_X_AMZ_DATE' => $date, + 'REQUEST_URI' => '/', )); $request->setBody($content); @@ -170,32 +163,30 @@ class Sabre_HTTP_AWSAuthTest extends PHPUnit_Framework_TestCase { $result = $this->auth->validate($secretKey); $this->assertFalse($result); - $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_INVALIDSIGNATURE,$this->auth->errorCode); - + $this->assertEquals(Sabre_HTTP_AWSAuth::ERR_INVALIDSIGNATURE, $this->auth->errorCode); } - public function testValidRequest() { - + public function testValidRequest() + { $accessKey = 'accessKey'; $secretKey = 'secretKey'; $content = 'thisisthebody'; - $contentMD5 = base64_encode(md5($content,true)); + $contentMD5 = base64_encode(md5($content, true)); $date = new DateTime('now'); $date->setTimeZone(new DateTimeZone('GMT')); $date = $date->format('D, d M Y H:i:s \\G\\M\\T'); - $sig = base64_encode($this->hmacsha1($secretKey, "POST\n$contentMD5\n\n$date\nx-amz-date:$date\n/evert" )); $request = new Sabre_HTTP_Request(array( - 'REQUEST_METHOD' => 'POST', - 'HTTP_AUTHORIZATION' => "AWS $accessKey:$sig", - 'HTTP_CONTENT_MD5' => $contentMD5, - 'HTTP_X_AMZ_DATE' => $date, - 'REQUEST_URI' => '/evert', + 'REQUEST_METHOD' => 'POST', + 'HTTP_AUTHORIZATION' => "AWS $accessKey:$sig", + 'HTTP_CONTENT_MD5' => $contentMD5, + 'HTTP_X_AMZ_DATE' => $date, + 'REQUEST_URI' => '/evert', )); $request->setBody($content); @@ -204,37 +195,36 @@ class Sabre_HTTP_AWSAuthTest extends PHPUnit_Framework_TestCase { $this->auth->init(); $result = $this->auth->validate($secretKey); - $this->assertTrue($result,'Signature did not validate, got errorcode ' . $this->auth->errorCode); - $this->assertEquals($accessKey,$this->auth->getAccessKey()); - + $this->assertTrue($result, 'Signature did not validate, got errorcode '.$this->auth->errorCode); + $this->assertEquals($accessKey, $this->auth->getAccessKey()); } - public function test401() { - + public function test401() + { $this->auth->requireLogin(); - $test = preg_match('/^AWS$/',$this->response->headers['WWW-Authenticate'],$matches); - $this->assertTrue($test==true,'The WWW-Authenticate response didn\'t match our pattern'); - + $test = preg_match('/^AWS$/', $this->response->headers['WWW-Authenticate'], $matches); + $this->assertTrue($test == true, 'The WWW-Authenticate response didn\'t match our pattern'); } /** - * Generates an HMAC-SHA1 signature + * Generates an HMAC-SHA1 signature. * * @param string $key * @param string $message + * * @return string */ - private function hmacsha1($key, $message) { + private function hmacsha1($key, $message) + { + $blocksize = 64; + if (strlen($key) > $blocksize) { + $key = pack('H*', sha1($key)); + } + $key = str_pad($key, $blocksize, chr(0x00)); + $ipad = str_repeat(chr(0x36), $blocksize); + $opad = str_repeat(chr(0x5c), $blocksize); + $hmac = pack('H*', sha1(($key ^ $opad).pack('H*', sha1(($key ^ $ipad).$message)))); - $blocksize=64; - if (strlen($key)>$blocksize) - $key=pack('H*', sha1($key)); - $key=str_pad($key,$blocksize,chr(0x00)); - $ipad=str_repeat(chr(0x36),$blocksize); - $opad=str_repeat(chr(0x5c),$blocksize); - $hmac = pack('H*',sha1(($key^$opad).pack('H*',sha1(($key^$ipad).$message)))); return $hmac; - } - } diff --git a/dav/SabreDAV/tests/Sabre/HTTP/BasicAuthTest.php b/dav/SabreDAV/tests/Sabre/HTTP/BasicAuthTest.php index 1bebcf85..7eb31fa5 100644 --- a/dav/SabreDAV/tests/Sabre/HTTP/BasicAuthTest.php +++ b/dav/SabreDAV/tests/Sabre/HTTP/BasicAuthTest.php @@ -2,8 +2,8 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_HTTP_BasicAuthTest extends PHPUnit_Framework_TestCase { - +class Sabre_HTTP_BasicAuthTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_HTTP_ResponseMock */ @@ -13,19 +13,18 @@ class Sabre_HTTP_BasicAuthTest extends PHPUnit_Framework_TestCase { */ private $basicAuth; - function setUp() { - + public function setUp() + { $this->response = new Sabre_HTTP_ResponseMock(); $this->basicAuth = new Sabre_HTTP_BasicAuth(); $this->basicAuth->setHTTPResponse($this->response); - } - function testGetUserPassApache() { - + public function testGetUserPassApache() + { $server = array( 'PHP_AUTH_USER' => 'admin', - 'PHP_AUTH_PW' => '1234', + 'PHP_AUTH_PW' => '1234', ); $request = new Sabre_HTTP_Request($server); @@ -34,17 +33,16 @@ class Sabre_HTTP_BasicAuthTest extends PHPUnit_Framework_TestCase { $userPass = $this->basicAuth->getUserPass(); $this->assertEquals( - array('admin','1234'), + array('admin', '1234'), $userPass, 'We did not get the username and password we expected' ); - } - function testGetUserPassIIS() { - + public function testGetUserPassIIS() + { $server = array( - 'HTTP_AUTHORIZATION' => 'Basic ' . base64_encode('admin:1234'), + 'HTTP_AUTHORIZATION' => 'Basic '.base64_encode('admin:1234'), ); $request = new Sabre_HTTP_Request($server); @@ -53,17 +51,16 @@ class Sabre_HTTP_BasicAuthTest extends PHPUnit_Framework_TestCase { $userPass = $this->basicAuth->getUserPass(); $this->assertEquals( - array('admin','1234'), + array('admin', '1234'), $userPass, 'We did not get the username and password we expected' ); - } - function testGetUserPassWithColon() { - + public function testGetUserPassWithColon() + { $server = array( - 'HTTP_AUTHORIZATION' => 'Basic ' . base64_encode('admin:1234:5678'), + 'HTTP_AUTHORIZATION' => 'Basic '.base64_encode('admin:1234:5678'), ); $request = new Sabre_HTTP_Request($server); @@ -72,17 +69,16 @@ class Sabre_HTTP_BasicAuthTest extends PHPUnit_Framework_TestCase { $userPass = $this->basicAuth->getUserPass(); $this->assertEquals( - array('admin','1234:5678'), + array('admin', '1234:5678'), $userPass, 'We did not get the username and password we expected' ); - } - function testGetUserPassApacheEdgeCase() { - + public function testGetUserPassApacheEdgeCase() + { $server = array( - 'REDIRECT_HTTP_AUTHORIZATION' => 'Basic ' . base64_encode('admin:1234'), + 'REDIRECT_HTTP_AUTHORIZATION' => 'Basic '.base64_encode('admin:1234'), ); $request = new Sabre_HTTP_Request($server); @@ -91,26 +87,24 @@ class Sabre_HTTP_BasicAuthTest extends PHPUnit_Framework_TestCase { $userPass = $this->basicAuth->getUserPass(); $this->assertEquals( - array('admin','1234'), + array('admin', '1234'), $userPass, 'We did not get the username and password we expected' ); - } - function testGetUserPassNothing() { - + public function testGetUserPassNothing() + { $this->assertEquals( false, $this->basicAuth->getUserPass() ); - } - function testRequireLogin() { - + public function testRequireLogin() + { $this->basicAuth->requireLogin(); - $this->assertEquals('SabreDAV',$this->basicAuth->getRealm()); + $this->assertEquals('SabreDAV', $this->basicAuth->getRealm()); $this->assertEquals( 'HTTP/1.1 401 Unauthorized', $this->response->status, @@ -122,9 +116,5 @@ class Sabre_HTTP_BasicAuthTest extends PHPUnit_Framework_TestCase { $this->response->headers['WWW-Authenticate'], 'The WWW-Autenticate header was not set!' ); - - - } - } diff --git a/dav/SabreDAV/tests/Sabre/HTTP/DigestAuthTest.php b/dav/SabreDAV/tests/Sabre/HTTP/DigestAuthTest.php index c5bf5358..f0fc5f36 100644 --- a/dav/SabreDAV/tests/Sabre/HTTP/DigestAuthTest.php +++ b/dav/SabreDAV/tests/Sabre/HTTP/DigestAuthTest.php @@ -2,8 +2,8 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase { - +class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_HTTP_ResponseMock */ @@ -15,18 +15,17 @@ class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase { const REALM = 'SabreDAV unittest'; - public function setUp() { - + public function setUp() + { $this->response = new Sabre_HTTP_ResponseMock(); $this->auth = new Sabre_HTTP_DigestAuth(); $this->auth->setRealm(self::REALM); $this->auth->setHTTPResponse($this->response); - } - public function testDigest() { - - list($nonce,$opaque) = $this->getServerTokens(); + public function testDigest() + { + list($nonce, $opaque) = $this->getServerTokens(); $username = 'admin'; $password = 12345; @@ -34,32 +33,31 @@ class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase { $cnonce = uniqid(); $digestHash = md5( - md5($username . ':' . self::REALM . ':' . $password) . ':' . - $nonce . ':' . - $nc . ':' . - $cnonce . ':' . - 'auth:' . - md5('GET' . ':' . '/') + md5($username.':'.self::REALM.':'.$password).':'. + $nonce.':'. + $nc.':'. + $cnonce.':'. + 'auth:'. + md5('GET'.':'.'/') ); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'GET', - 'PHP_AUTH_DIGEST' => 'username="'.$username.'", realm="' . self::REALM . '", nonce="' . $nonce . '", uri="/", response="' . $digestHash . '", opaque="' . $opaque . '", qop=auth,nc='.$nc.',cnonce="' . $cnonce . '"', + 'PHP_AUTH_DIGEST' => 'username="'.$username.'", realm="'.self::REALM.'", nonce="'.$nonce.'", uri="/", response="'.$digestHash.'", opaque="'.$opaque.'", qop=auth,nc='.$nc.',cnonce="'.$cnonce.'"', )); $this->auth->setHTTPRequest($request); $this->auth->init(); - $this->assertEquals($username,$this->auth->getUserName()); - $this->assertEquals(self::REALM,$this->auth->getRealm()); - $this->assertTrue($this->auth->validateA1(md5($username . ':' . self::REALM . ':' . $password)),'Authentication is deemed invalid through validateA1'); - $this->assertTrue($this->auth->validatePassword($password),'Authentication is deemed invalid through validatePassword'); - + $this->assertEquals($username, $this->auth->getUserName()); + $this->assertEquals(self::REALM, $this->auth->getRealm()); + $this->assertTrue($this->auth->validateA1(md5($username.':'.self::REALM.':'.$password)), 'Authentication is deemed invalid through validateA1'); + $this->assertTrue($this->auth->validatePassword($password), 'Authentication is deemed invalid through validatePassword'); } - public function testDigestCGIFormat() { - - list($nonce,$opaque) = $this->getServerTokens(); + public function testDigestCGIFormat() + { + list($nonce, $opaque) = $this->getServerTokens(); $username = 'admin'; $password = 12345; @@ -67,30 +65,29 @@ class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase { $cnonce = uniqid(); $digestHash = md5( - md5($username . ':' . self::REALM . ':' . $password) . ':' . - $nonce . ':' . - $nc . ':' . - $cnonce . ':' . - 'auth:' . - md5('GET' . ':' . '/') + md5($username.':'.self::REALM.':'.$password).':'. + $nonce.':'. + $nc.':'. + $cnonce.':'. + 'auth:'. + md5('GET'.':'.'/') ); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'GET', - 'HTTP_AUTHORIZATION' => 'Digest username="'.$username.'", realm="' . self::REALM . '", nonce="' . $nonce . '", uri="/", response="' . $digestHash . '", opaque="' . $opaque . '", qop=auth,nc='.$nc.',cnonce="' . $cnonce . '"', + 'HTTP_AUTHORIZATION' => 'Digest username="'.$username.'", realm="'.self::REALM.'", nonce="'.$nonce.'", uri="/", response="'.$digestHash.'", opaque="'.$opaque.'", qop=auth,nc='.$nc.',cnonce="'.$cnonce.'"', )); $this->auth->setHTTPRequest($request); $this->auth->init(); - $this->assertTrue($this->auth->validateA1(md5($username . ':' . self::REALM . ':' . $password)),'Authentication is deemed invalid through validateA1'); - $this->assertTrue($this->auth->validatePassword($password),'Authentication is deemed invalid through validatePassword'); - + $this->assertTrue($this->auth->validateA1(md5($username.':'.self::REALM.':'.$password)), 'Authentication is deemed invalid through validateA1'); + $this->assertTrue($this->auth->validatePassword($password), 'Authentication is deemed invalid through validatePassword'); } - public function testDigestApacheEdgeCase() { - - list($nonce,$opaque) = $this->getServerTokens(); + public function testDigestApacheEdgeCase() + { + list($nonce, $opaque) = $this->getServerTokens(); $username = 'admin'; $password = 12345; @@ -98,30 +95,29 @@ class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase { $cnonce = uniqid(); $digestHash = md5( - md5($username . ':' . self::REALM . ':' . $password) . ':' . - $nonce . ':' . - $nc . ':' . - $cnonce . ':' . - 'auth:' . - md5('GET' . ':' . '/') + md5($username.':'.self::REALM.':'.$password).':'. + $nonce.':'. + $nc.':'. + $cnonce.':'. + 'auth:'. + md5('GET'.':'.'/') ); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'GET', - 'REDIRECT_HTTP_AUTHORIZATION' => 'Digest username="'.$username.'", realm="' . self::REALM . '", nonce="' . $nonce . '", uri="/", response="' . $digestHash . '", opaque="' . $opaque . '", qop=auth,nc='.$nc.',cnonce="' . $cnonce . '"', + 'REDIRECT_HTTP_AUTHORIZATION' => 'Digest username="'.$username.'", realm="'.self::REALM.'", nonce="'.$nonce.'", uri="/", response="'.$digestHash.'", opaque="'.$opaque.'", qop=auth,nc='.$nc.',cnonce="'.$cnonce.'"', )); $this->auth->setHTTPRequest($request); $this->auth->init(); - $this->assertTrue($this->auth->validateA1(md5($username . ':' . self::REALM . ':' . $password)),'Authentication is deemed invalid through validateA1'); - $this->assertTrue($this->auth->validatePassword($password),'Authentication is deemed invalid through validatePassword'); - + $this->assertTrue($this->auth->validateA1(md5($username.':'.self::REALM.':'.$password)), 'Authentication is deemed invalid through validateA1'); + $this->assertTrue($this->auth->validatePassword($password), 'Authentication is deemed invalid through validatePassword'); } - public function testInvalidDigest() { - - list($nonce,$opaque) = $this->getServerTokens(); + public function testInvalidDigest() + { + list($nonce, $opaque) = $this->getServerTokens(); $username = 'admin'; $password = 12345; @@ -129,28 +125,27 @@ class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase { $cnonce = uniqid(); $digestHash = md5( - md5($username . ':' . self::REALM . ':' . $password) . ':' . - $nonce . ':' . - $nc . ':' . - $cnonce . ':' . - 'auth:' . - md5('GET' . ':' . '/') + md5($username.':'.self::REALM.':'.$password).':'. + $nonce.':'. + $nc.':'. + $cnonce.':'. + 'auth:'. + md5('GET'.':'.'/') ); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'GET', - 'PHP_AUTH_DIGEST' => 'username="'.$username.'", realm="' . self::REALM . '", nonce="' . $nonce . '", uri="/", response="' . $digestHash . '", opaque="' . $opaque . '", qop=auth,nc='.$nc.',cnonce="' . $cnonce . '"', + 'PHP_AUTH_DIGEST' => 'username="'.$username.'", realm="'.self::REALM.'", nonce="'.$nonce.'", uri="/", response="'.$digestHash.'", opaque="'.$opaque.'", qop=auth,nc='.$nc.',cnonce="'.$cnonce.'"', )); $this->auth->setHTTPRequest($request); $this->auth->init(); - $this->assertFalse($this->auth->validateA1(md5($username . ':' . self::REALM . ':' . ($password . 'randomness'))),'Authentication is deemed invalid through validateA1'); - + $this->assertFalse($this->auth->validateA1(md5($username.':'.self::REALM.':'.($password.'randomness'))), 'Authentication is deemed invalid through validateA1'); } - public function testInvalidDigest2() { - + public function testInvalidDigest2() + { $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'GET', 'HTTP_AUTHORIZATION' => 'basic blablabla', @@ -160,14 +155,12 @@ class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase { $this->auth->init(); $this->assertFalse($this->auth->validateA1(md5('user:realm:password'))); - } - - public function testDigestAuthInt() { - + public function testDigestAuthInt() + { $this->auth->setQOP(Sabre_HTTP_DigestAuth::QOP_AUTHINT | Sabre_HTTP_DigestAuth::QOP_AUTH); - list($nonce,$opaque) = $this->getServerTokens(Sabre_HTTP_DigestAuth::QOP_AUTHINT| Sabre_HTTP_DigestAuth::QOP_AUTH); + list($nonce, $opaque) = $this->getServerTokens(Sabre_HTTP_DigestAuth::QOP_AUTHINT | Sabre_HTTP_DigestAuth::QOP_AUTH); $username = 'admin'; $password = 12345; @@ -175,17 +168,17 @@ class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase { $cnonce = uniqid(); $digestHash = md5( - md5($username . ':' . self::REALM . ':' . $password) . ':' . - $nonce . ':' . - $nc . ':' . - $cnonce . ':' . - 'auth-int:' . - md5('POST' . ':' . '/' . ':' . md5('body')) + md5($username.':'.self::REALM.':'.$password).':'. + $nonce.':'. + $nc.':'. + $cnonce.':'. + 'auth-int:'. + md5('POST'.':'.'/'.':'.md5('body')) ); $request = new Sabre_HTTP_Request(array( 'REQUEST_METHOD' => 'POST', - 'PHP_AUTH_DIGEST' => 'username="'.$username.'", realm="' . self::REALM . '", nonce="' . $nonce . '", uri="/", response="' . $digestHash . '", opaque="' . $opaque . '", qop=auth-int,nc='.$nc.',cnonce="' . $cnonce . '"', + 'PHP_AUTH_DIGEST' => 'username="'.$username.'", realm="'.self::REALM.'", nonce="'.$nonce.'", uri="/", response="'.$digestHash.'", opaque="'.$opaque.'", qop=auth-int,nc='.$nc.',cnonce="'.$cnonce.'"', )); $request->setBody('body'); @@ -193,24 +186,23 @@ class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase { $this->auth->init(); - $this->assertTrue($this->auth->validateA1(md5($username . ':' . self::REALM . ':' . $password)),'Authentication is deemed invalid through validateA1'); - + $this->assertTrue($this->auth->validateA1(md5($username.':'.self::REALM.':'.$password)), 'Authentication is deemed invalid through validateA1'); } - private function getServerTokens($qop = Sabre_HTTP_DigestAuth::QOP_AUTH) { - + private function getServerTokens($qop = Sabre_HTTP_DigestAuth::QOP_AUTH) + { $this->auth->requireLogin(); - switch($qop) { - case Sabre_HTTP_DigestAuth::QOP_AUTH : $qopstr='auth'; break; - case Sabre_HTTP_DigestAuth::QOP_AUTHINT : $qopstr='auth-int'; break; - default : $qopstr='auth,auth-int'; break; + switch ($qop) { + case Sabre_HTTP_DigestAuth::QOP_AUTH: $qopstr = 'auth'; break; + case Sabre_HTTP_DigestAuth::QOP_AUTHINT: $qopstr = 'auth-int'; break; + default: $qopstr = 'auth,auth-int'; break; } $test = preg_match('/Digest realm="'.self::REALM.'",qop="'.$qopstr.'",nonce="([0-9a-f]*)",opaque="([0-9a-f]*)"/', - $this->response->headers['WWW-Authenticate'],$matches); + $this->response->headers['WWW-Authenticate'], $matches); - $this->assertTrue($test==true,'The WWW-Authenticate response didn\'t match our pattern. We received: ' . $this->response->headers['WWW-Authenticate']); + $this->assertTrue($test == true, 'The WWW-Authenticate response didn\'t match our pattern. We received: '.$this->response->headers['WWW-Authenticate']); $nonce = $matches[1]; $opaque = $matches[2]; @@ -219,8 +211,6 @@ class Sabre_HTTP_DigestAuthTest extends PHPUnit_Framework_TestCase { $this->setUp(); $this->auth->setQOP($qop); - return array($nonce,$opaque); - + return array($nonce, $opaque); } - } diff --git a/dav/SabreDAV/tests/Sabre/HTTP/RequestTest.php b/dav/SabreDAV/tests/Sabre/HTTP/RequestTest.php index ef2326e0..2c7cc8ef 100644 --- a/dav/SabreDAV/tests/Sabre/HTTP/RequestTest.php +++ b/dav/SabreDAV/tests/Sabre/HTTP/RequestTest.php @@ -3,103 +3,93 @@ /** * @covers Sabre_HTTP_Request */ -class Sabre_HTTP_RequestTest extends PHPUnit_Framework_TestCase { - +class Sabre_HTTP_RequestTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_HTTP_Request */ private $request; - function setUp() { - + public function setUp() + { $server = array( - 'HTTP_HOST' => 'www.example.org', + 'HTTP_HOST' => 'www.example.org', 'REQUEST_METHOD' => 'PUT', - 'REQUEST_URI' => '/testuri/', - 'CONTENT_TYPE' => 'text/xml', + 'REQUEST_URI' => '/testuri/', + 'CONTENT_TYPE' => 'text/xml', ); $this->request = new Sabre_HTTP_Request($server); - } - function testGetHeader() { - + public function testGetHeader() + { $this->assertEquals('www.example.org', $this->request->getHeader('Host')); $this->assertEquals('text/xml', $this->request->getHeader('Content-Type')); - } - function testGetNonExistantHeader() { - + public function testGetNonExistantHeader() + { $this->assertNull($this->request->getHeader('doesntexist')); $this->assertNull($this->request->getHeader('Content-Length')); - } - function testGetHeaders() { - + public function testGetHeaders() + { $expected = array( 'host' => 'www.example.org', 'content-type' => 'text/xml', ); $this->assertEquals($expected, $this->request->getHeaders()); - } - function testGetMethod() { - + public function testGetMethod() + { $this->assertEquals('PUT', $this->request->getMethod(), 'It seems as if we didn\'t get a valid HTTP Request method back'); - } - function testGetUri() { - + public function testGetUri() + { $this->assertEquals('/testuri/', $this->request->getUri(), 'We got an invalid uri back'); - } - function testSetGetBody() { - - $h = fopen('php://memory','r+'); - fwrite($h,'testing'); + public function testSetGetBody() + { + $h = fopen('php://memory', 'r+'); + fwrite($h, 'testing'); rewind($h); $this->request->setBody($h); - $this->assertEquals('testing',$this->request->getBody(true),'We didn\'t get our testbody back'); - + $this->assertEquals('testing', $this->request->getBody(true), 'We didn\'t get our testbody back'); } - function testSetGetBodyStream() { - - $h = fopen('php://memory','r+'); - fwrite($h,'testing'); + public function testSetGetBodyStream() + { + $h = fopen('php://memory', 'r+'); + fwrite($h, 'testing'); rewind($h); $this->request->setBody($h); - $this->assertEquals('testing',stream_get_contents($this->request->getBody()),'We didn\'t get our testbody back'); - + $this->assertEquals('testing', stream_get_contents($this->request->getBody()), 'We didn\'t get our testbody back'); } - - function testDefaultInputStream() { - - $h = fopen('php://memory','r+'); - fwrite($h,'testing'); + public function testDefaultInputStream() + { + $h = fopen('php://memory', 'r+'); + fwrite($h, 'testing'); rewind($h); $previousValue = Sabre_HTTP_Request::$defaultInputStream; Sabre_HTTP_Request::$defaultInputStream = $h; - $this->assertEquals('testing',$this->request->getBody(true),'We didn\'t get our testbody back'); + $this->assertEquals('testing', $this->request->getBody(true), 'We didn\'t get our testbody back'); Sabre_HTTP_Request::$defaultInputStream = $previousValue; - } - function testGetAbsoluteUri() { - + public function testGetAbsoluteUri() + { $s = array( 'HTTP_HOST' => 'sabredav.org', - 'REQUEST_URI' => '/foo' + 'REQUEST_URI' => '/foo', ); $r = new Sabre_HTTP_Request($s); @@ -107,19 +97,18 @@ class Sabre_HTTP_RequestTest extends PHPUnit_Framework_TestCase { $this->assertEquals('http://sabredav.org/foo', $r->getAbsoluteUri()); $s = array( - 'HTTP_HOST' => 'sabredav.org', + 'HTTP_HOST' => 'sabredav.org', 'REQUEST_URI' => '/foo', - 'HTTPS' => 'on', + 'HTTPS' => 'on', ); $r = new Sabre_HTTP_Request($s); $this->assertEquals('https://sabredav.org/foo', $r->getAbsoluteUri()); - } - function testGetQueryString() { - + public function testGetQueryString() + { $s = array( 'QUERY_STRING' => 'bla', ); @@ -131,18 +120,14 @@ class Sabre_HTTP_RequestTest extends PHPUnit_Framework_TestCase { $r = new Sabre_HTTP_Request($s); $this->assertEquals('', $r->getQueryString()); - } - function testGetPostVars() { - + public function testGetPostVars() + { $post = array( 'bla' => 'foo', ); - $r = new Sabre_HTTP_Request(array(),$post); + $r = new Sabre_HTTP_Request(array(), $post); $this->assertEquals($post, $r->getPostVars('bla')); - } - - } diff --git a/dav/SabreDAV/tests/Sabre/HTTP/ResponseMock.php b/dav/SabreDAV/tests/Sabre/HTTP/ResponseMock.php index 70b3ebff..6891ae40 100644 --- a/dav/SabreDAV/tests/Sabre/HTTP/ResponseMock.php +++ b/dav/SabreDAV/tests/Sabre/HTTP/ResponseMock.php @@ -1,27 +1,23 @@ headers[$name] = $value; - } - function sendStatus($code) { - + public function sendStatus($code) + { $this->status = $this->getStatusMessage($code); - } - function sendBody($body) { - + public function sendBody($body) + { $this->body = $body; - } - } diff --git a/dav/SabreDAV/tests/Sabre/HTTP/ResponseTest.php b/dav/SabreDAV/tests/Sabre/HTTP/ResponseTest.php index d40b0cf4..652726ad 100644 --- a/dav/SabreDAV/tests/Sabre/HTTP/ResponseTest.php +++ b/dav/SabreDAV/tests/Sabre/HTTP/ResponseTest.php @@ -2,60 +2,52 @@ require_once 'Sabre/HTTP/ResponseMock.php'; -class Sabre_HTTP_ResponseTest extends PHPUnit_Framework_TestCase { - +class Sabre_HTTP_ResponseTest extends PHPUnit_Framework_TestCase +{ /** * @var Sabre_HTTP_ResponseMock */ private $response; - function setUp() { - + public function setUp() + { $this->response = new Sabre_HTTP_ResponseMock(); - } - function testGetStatusMessage() { - + public function testGetStatusMessage() + { $msg = $this->response->getStatusMessage(200); - $this->assertEquals('HTTP/1.1 200 OK',$msg); - + $this->assertEquals('HTTP/1.1 200 OK', $msg); } - function testSetHeader() { - - $this->response->setHeader('Content-Type','text/html'); + public function testSetHeader() + { + $this->response->setHeader('Content-Type', 'text/html'); $this->assertEquals('text/html', $this->response->headers['Content-Type']); - - } - function testSendStatus() { - + public function testSendStatus() + { $this->response->sendStatus(404); $this->assertEquals('HTTP/1.1 404 Not Found', $this->response->status); - } - function testSendBody() { - + public function testSendBody() + { ob_start(); $response = new Sabre_HTTP_Response(); $response->sendBody('hello'); - $this->assertEquals('hello',ob_get_clean()); - + $this->assertEquals('hello', ob_get_clean()); } - function testSendBodyStream() { - + public function testSendBodyStream() + { ob_start(); - $stream = fopen('php://memory','r+'); - fwrite($stream,'hello'); + $stream = fopen('php://memory', 'r+'); + fwrite($stream, 'hello'); rewind($stream); $response = new Sabre_HTTP_Response(); $response->sendBody($stream); - $this->assertEquals('hello',ob_get_clean()); - + $this->assertEquals('hello', ob_get_clean()); } - } diff --git a/dav/SabreDAV/tests/Sabre/HTTP/UtilTest.php b/dav/SabreDAV/tests/Sabre/HTTP/UtilTest.php index 2374561c..5047d860 100644 --- a/dav/SabreDAV/tests/Sabre/HTTP/UtilTest.php +++ b/dav/SabreDAV/tests/Sabre/HTTP/UtilTest.php @@ -1,9 +1,9 @@ assertEquals($expected, $result->format('U')); } $result = Sabre_HTTP_Util::parseHTTPDate('Wed Oct 6 10:26:00 2010'); $this->assertEquals(1286360760, $result->format('U')); - } - function testParseHTTPDateFail() { - + public function testParseHTTPDateFail() + { $times = array( //random string 'NOW', @@ -33,32 +32,28 @@ class Sabre_Util_UtilTest extends PHPUnit_Framework_TestCase { 'Wed Oct 6 10:26:00 2010', ); - foreach($times as $time) { - $this->assertFalse(Sabre_HTTP_Util::parseHTTPDate($time), 'We used the string: ' . $time); + foreach ($times as $time) { + $this->assertFalse(Sabre_HTTP_Util::parseHTTPDate($time), 'We used the string: '.$time); } - } - function testTimezones() { - + public function testTimezones() + { $default = date_default_timezone_get(); date_default_timezone_set('Europe/Amsterdam'); $this->testParseHTTPDate(); date_default_timezone_set($default); - } - function testToHTTPDate() { - + public function testToHTTPDate() + { $dt = new DateTime('2011-12-10 12:00:00 +0200'); $this->assertEquals( 'Sat, 10 Dec 2011 10:00:00 GMT', Sabre_HTTP_Util::toHTTPDate($dt) ); - } - } diff --git a/dav/SabreDAV/tests/Sabre/HTTP/VersionTest.php b/dav/SabreDAV/tests/Sabre/HTTP/VersionTest.php index 5cb124ef..e22e0131 100644 --- a/dav/SabreDAV/tests/Sabre/HTTP/VersionTest.php +++ b/dav/SabreDAV/tests/Sabre/HTTP/VersionTest.php @@ -1,15 +1,13 @@ assertEquals(-1, version_compare('1.0.0',$v)); + $this->assertEquals(-1, version_compare('1.0.0', $v)); $s = Sabre_HTTP_Version::STABILITY; - $this->assertTrue($s == 'alpha' || $s == 'beta' || $s =='stable'); - + $this->assertTrue($s == 'alpha' || $s == 'beta' || $s == 'stable'); } - } diff --git a/dav/SabreDAV/tests/Sabre/TestUtil.php b/dav/SabreDAV/tests/Sabre/TestUtil.php index 62ee1fba..0ffead1e 100644 --- a/dav/SabreDAV/tests/Sabre/TestUtil.php +++ b/dav/SabreDAV/tests/Sabre/TestUtil.php @@ -1,49 +1,42 @@ setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); + $pdo = new PDO(SABRE_MYSQLDSN, SABRE_MYSQLUSER, SABRE_MYSQLPASS); + $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + return $pdo; } catch (PDOException $e) { return null; } - } - - } diff --git a/dav/SabreDAV/tests/bootstrap.php b/dav/SabreDAV/tests/bootstrap.php index c3be7366..74671460 100644 --- a/dav/SabreDAV/tests/bootstrap.php +++ b/dav/SabreDAV/tests/bootstrap.php @@ -1,22 +1,26 @@ email = $email; - $this->type = $type; - } + public function __construct($type, $email) + { + $this->email = $email; + $this->type = $type; + } } class vcard_source_data_homepage { - public $homepage, $type; + public $homepage, $type; - function __construct($type, $homepage) - { - $this->homepage = $homepage; - $this->type = $type; - } + public function __construct($type, $homepage) + { + $this->homepage = $homepage; + $this->type = $type; + } } class vcard_source_data_telephone { - public $telephone, $type; + public $telephone, $type; - function __construct($type, $telephone) - { - $this->telephone = $telephone; - $this->type = $type; - } + public function __construct($type, $telephone) + { + $this->telephone = $telephone; + $this->type = $type; + } } class vcard_source_data_socialnetwork { - public $nick, $type, $url; + public $nick, $type, $url; - function __construct($type, $nick, $url) - { - $this->nick = $nick; - $this->type = $type; - $this->url = $url; - } + public function __construct($type, $nick, $url) + { + $this->nick = $nick; + $this->type = $type; + $this->url = $url; + } } class vcard_source_data_address { - public $street, $street2, $zip, $city, $country, $type; + public $street, $street2, $zip, $city, $country, $type; } class vcard_source_data_photo { - public $binarydata; - public $width, $height; - public $type; + public $binarydata; + public $width, $height; + public $type; } class vcard_source_data { - function __construct($name_first, $name_middle, $name_last) - { - $this->name_first = $name_first; - $this->name_middle = $name_middle; - $this->name_last = $name_last; - } + public function __construct($name_first, $name_middle, $name_last) + { + $this->name_first = $name_first; + $this->name_middle = $name_middle; + $this->name_last = $name_last; + } - public $name_first, $name_middle, $name_last; - public $last_update; - public $picture_data; + public $name_first, $name_middle, $name_last; + public $last_update; + public $picture_data; - /** @var array|vcard_source_data_telephone[] $telephones */ - public $telephones; + /** @var array|vcard_source_data_telephone[] $telephones */ + public $telephones; - /** @var array|vcard_source_data_homepage[] $homepages */ - public $homepages; + /** @var array|vcard_source_data_homepage[] $homepages */ + public $homepages; - /** @var array|vcard_source_data_socialnetwork[] $socialnetworks */ - public $socialnetworks; + /** @var array|vcard_source_data_socialnetwork[] $socialnetworks */ + public $socialnetworks; - /** @var array|vcard_source_data_email[] $email */ - public $emails; + /** @var array|vcard_source_data_email[] $email */ + public $emails; - /** @var array|vcard_source_data_address[] $addresses */ - public $addresses; + /** @var array|vcard_source_data_address[] $addresses */ + public $addresses; - /** @var vcard_source_data_photo */ - public $photo; + /** @var vcard_source_data_photo */ + public $photo; } /** * @param vcard_source_data $vcardsource + * * @return string */ function vcard_source_compile($vcardsource) { - $str = "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Friendica//DAV-Plugin//EN\r\n"; - $str .= "N:" . str_replace(";", ",", $vcardsource->name_last) . ";" . str_replace(";", ",", $vcardsource->name_first) . ";" . str_replace(";", ",", $vcardsource->name_middle) . ";;\r\n"; - $str .= "FN:" . str_replace(";", ",", $vcardsource->name_first) . " " . str_replace(";", ",", $vcardsource->name_middle) . " " . str_replace(";", ",", $vcardsource->name_last) . "\r\n"; - $str .= "REV:" . str_replace(" ", "T", $vcardsource->last_update) . "Z\r\n"; + $str = "BEGIN:VCARD\r\nVERSION:3.0\r\nPRODID:-//Friendica//DAV-Plugin//EN\r\n"; + $str .= 'N:'.str_replace(';', ',', $vcardsource->name_last).';'.str_replace(';', ',', $vcardsource->name_first).';'.str_replace(';', ',', $vcardsource->name_middle).";;\r\n"; + $str .= 'FN:'.str_replace(';', ',', $vcardsource->name_first).' '.str_replace(';', ',', $vcardsource->name_middle).' '.str_replace(';', ',', $vcardsource->name_last)."\r\n"; + $str .= 'REV:'.str_replace(' ', 'T', $vcardsource->last_update)."Z\r\n"; - $item_count = 0; - for ($i = 0; $i < count($vcardsource->homepages); $i++) { - if ($i == 0) $str .= "URL;type=" . $vcardsource->homepages[0]->type . ":" . $vcardsource->homepages[0]->homepage . "\r\n"; - else { - $c = ++$item_count; - $str .= "item$c.URL;type=" . $vcardsource->homepages[0]->type . ":" . $vcardsource->homepages[0]->homepage . "\r\n"; - $str .= "item$c.X-ABLabel:_\$!!\$_\r\n"; - } - } + $item_count = 0; + for ($i = 0; $i < count($vcardsource->homepages); ++$i) { + if ($i == 0) { + $str .= 'URL;type='.$vcardsource->homepages[0]->type.':'.$vcardsource->homepages[0]->homepage."\r\n"; + } else { + $c = ++$item_count; + $str .= "item$c.URL;type=".$vcardsource->homepages[0]->type.':'.$vcardsource->homepages[0]->homepage."\r\n"; + $str .= "item$c.X-ABLabel:_\$!!\$_\r\n"; + } + } - if (is_object($vcardsource->photo)) { - $data = base64_encode($vcardsource->photo->binarydata); - $str .= "PHOTO;ENCODING=BASE64;TYPE=" . $vcardsource->photo->type . ":" . $data . "\r\n"; - } + if (is_object($vcardsource->photo)) { + $data = base64_encode($vcardsource->photo->binarydata); + $str .= 'PHOTO;ENCODING=BASE64;TYPE='.$vcardsource->photo->type.':'.$data."\r\n"; + } - if (isset($vcardsource->socialnetworks) && is_array($vcardsource->socialnetworks)) foreach ($vcardsource->socialnetworks as $netw) switch ($netw->type) { - case "dfrn": - $str .= "X-SOCIALPROFILE;type=dfrn;x-user=" . $netw->nick . ":" . $netw->url . "\r\n"; - break; - case "facebook": - $str .= "X-SOCIALPROFILE;type=facebook;x-user=" . $netw->nick . ":" . $netw->url . "\r\n"; - break; - case "twitter": - $str .= "X-SOCIALPROFILE;type=twitter;x-user=" . $netw->nick . ":" . $netw->url . "\r\n"; - break; - } + if (isset($vcardsource->socialnetworks) && is_array($vcardsource->socialnetworks)) { + foreach ($vcardsource->socialnetworks as $netw) { + switch ($netw->type) { + case 'dfrn': + $str .= 'X-SOCIALPROFILE;type=dfrn;x-user='.$netw->nick.':'.$netw->url."\r\n"; + break; + case 'facebook': + $str .= 'X-SOCIALPROFILE;type=facebook;x-user='.$netw->nick.':'.$netw->url."\r\n"; + break; + case 'twitter': + $str .= 'X-SOCIALPROFILE;type=twitter;x-user='.$netw->nick.':'.$netw->url."\r\n"; + break; + } + } + } - $str .= "END:VCARD\r\n"; - return $str; + $str .= "END:VCARD\r\n"; + + return $str; } - /** * @param int $phpDate (UTC) + * * @return string (Lokalzeit) */ function wdcal_php2MySqlTime($phpDate) { - return date("Y-m-d H:i:s", $phpDate); + return date('Y-m-d H:i:s', $phpDate); } /** * @param string $sqlDate + * * @return int */ function wdcal_mySql2PhpTime($sqlDate) { - $ts = DateTime::createFromFormat("Y-m-d H:i:s", $sqlDate); - return $ts->format("U"); + $ts = DateTime::createFromFormat('Y-m-d H:i:s', $sqlDate); + + return $ts->format('U'); } /** * @param string $myqlDate + * * @return array */ function wdcal_mySql2icalTime($myqlDate) { - $x = explode(" ", $myqlDate); - $y = explode("-", $x[0]); - $ret = array("year"=> $y[0], "month"=> $y[1], "day"=> $y[2]); - $y = explode(":", $x[1]); - $ret["hour"] = $y[0]; - $ret["minute"] = $y[1]; - $ret["second"] = $y[2]; - return $ret; -} + $x = explode(' ', $myqlDate); + $y = explode('-', $x[0]); + $ret = array('year' => $y[0], 'month' => $y[1], 'day' => $y[2]); + $y = explode(':', $x[1]); + $ret['hour'] = $y[0]; + $ret['minute'] = $y[1]; + $ret['second'] = $y[2]; + return $ret; +} /** * @param string $str + * * @return string */ -function icalendar_sanitize_string($str = "") +function icalendar_sanitize_string($str = '') { - return preg_replace("/[\\r\\n]+/siu", "\r\n", $str); + return preg_replace('/[\\r\\n]+/siu', "\r\n", $str); } - /** * @return Sabre_CalDAV_AnimexxCalendarRootNode */ function dav_createRootCalendarNode() { - $backends = array(Sabre_CalDAV_Backend_Private::getInstance()); - foreach ($GLOBALS["CALDAV_PRIVATE_SYSTEM_BACKENDS"] as $backendclass) $backends[] = $backendclass::getInstance(); - return new Sabre_CalDAV_AnimexxCalendarRootNode(Sabre_DAVACL_PrincipalBackend_Std::getInstance(), $backends); + $backends = array(Sabre_CalDAV_Backend_Private::getInstance()); + foreach ($GLOBALS['CALDAV_PRIVATE_SYSTEM_BACKENDS'] as $backendclass) { + $backends[] = $backendclass::getInstance(); + } + + return new Sabre_CalDAV_AnimexxCalendarRootNode(Sabre_DAVACL_PrincipalBackend_Std::getInstance(), $backends); } /** @@ -205,171 +216,198 @@ function dav_createRootCalendarNode() */ function dav_createRootContactsNode() { - $backends = array(Sabre_CardDAV_Backend_Std::getInstance()); - foreach ($GLOBALS["CARDDAV_PRIVATE_SYSTEM_BACKENDS"] as $backendclass) $backends[] = $backendclass::getInstance(); + $backends = array(Sabre_CardDAV_Backend_Std::getInstance()); + foreach ($GLOBALS['CARDDAV_PRIVATE_SYSTEM_BACKENDS'] as $backendclass) { + $backends[] = $backendclass::getInstance(); + } - return new Sabre_CardDAV_AddressBookRootFriendica(Sabre_DAVACL_PrincipalBackend_Std::getInstance(), $backends); + return new Sabre_CardDAV_AddressBookRootFriendica(Sabre_DAVACL_PrincipalBackend_Std::getInstance(), $backends); } - /** * @param bool $force_authentication * @param bool $needs_caldav * @param bool $needs_carddav + * * @return Sabre_DAV_Server */ function dav_create_server($force_authentication = false, $needs_caldav = true, $needs_carddav = true) { - $arr = array( - new Sabre_DAV_SimpleCollection('principals', array( - new Sabre_CalDAV_Principal_Collection(Sabre_DAVACL_PrincipalBackend_Std::getInstance(), "principals/users"), - )), - ); - if ($needs_caldav) $arr[] = dav_createRootCalendarNode(); - if ($needs_carddav) $arr[] = dav_createRootContactsNode(); + $arr = array( + new Sabre_DAV_SimpleCollection('principals', array( + new Sabre_CalDAV_Principal_Collection(Sabre_DAVACL_PrincipalBackend_Std::getInstance(), 'principals/users'), + )), + ); + if ($needs_caldav) { + $arr[] = dav_createRootCalendarNode(); + } + if ($needs_carddav) { + $arr[] = dav_createRootContactsNode(); + } - - $tree = new Sabre_DAV_SimpleCollection('root', $arr); + $tree = new Sabre_DAV_SimpleCollection('root', $arr); // The object tree needs in turn to be passed to the server class - $server = new Sabre_DAV_Server($tree); + $server = new Sabre_DAV_Server($tree); - if (CALDAV_URL_PREFIX != "") $server->setBaseUri(CALDAV_URL_PREFIX); + if (CALDAV_URL_PREFIX != '') { + $server->setBaseUri(CALDAV_URL_PREFIX); + } - $authPlugin = new Sabre_DAV_Auth_Plugin(Sabre_DAV_Auth_Backend_Std::getInstance(), DAV_APPNAME); - $server->addPlugin($authPlugin); + $authPlugin = new Sabre_DAV_Auth_Plugin(Sabre_DAV_Auth_Backend_Std::getInstance(), DAV_APPNAME); + $server->addPlugin($authPlugin); - if ($needs_caldav) { - $caldavPlugin = new Sabre_CalDAV_Plugin(); - $server->addPlugin($caldavPlugin); - } - if ($needs_carddav) { - $carddavPlugin = new Sabre_CardDAV_Plugin(); - $server->addPlugin($carddavPlugin); - } + if ($needs_caldav) { + $caldavPlugin = new Sabre_CalDAV_Plugin(); + $server->addPlugin($caldavPlugin); + } + if ($needs_carddav) { + $carddavPlugin = new Sabre_CardDAV_Plugin(); + $server->addPlugin($carddavPlugin); + } - if ($GLOBALS["CALDAV_ACL_PLUGIN_CLASS"] != "") { - $aclPlugin = new $GLOBALS["CALDAV_ACL_PLUGIN_CLASS"](); - $aclPlugin->defaultUsernamePath = "principals/users"; - $server->addPlugin($aclPlugin); - } else { - $aclPlugin = new Sabre_DAVACL_Plugin(); - $aclPlugin->defaultUsernamePath = "principals/users"; - $server->addPlugin($aclPlugin); - } + if ($GLOBALS['CALDAV_ACL_PLUGIN_CLASS'] != '') { + $aclPlugin = new $GLOBALS['CALDAV_ACL_PLUGIN_CLASS'](); + $aclPlugin->defaultUsernamePath = 'principals/users'; + $server->addPlugin($aclPlugin); + } else { + $aclPlugin = new Sabre_DAVACL_Plugin(); + $aclPlugin->defaultUsernamePath = 'principals/users'; + $server->addPlugin($aclPlugin); + } - if ($force_authentication) $server->broadcastEvent('beforeMethod', array("GET", "/")); // Make it authenticate + if ($force_authentication) { + $server->broadcastEvent('beforeMethod', array('GET', '/')); + } // Make it authenticate - return $server; + return $server; } - /** * @param Sabre_DAV_Server $server - * @param string $with_privilege + * @param string $with_privilege + * * @return array|Sabre_CalDAV_Calendar[] */ -function dav_get_current_user_calendars(&$server, $with_privilege = "") +function dav_get_current_user_calendars(&$server, $with_privilege = '') { - if ($with_privilege == "") $with_privilege = DAV_ACL_READ; + if ($with_privilege == '') { + $with_privilege = DAV_ACL_READ; + } - $a = get_app(); - $calendar_path = "/calendars/" . strtolower($a->user["nickname"]) . "/"; + $a = get_app(); + $calendar_path = '/calendars/'.strtolower($a->user['nickname']).'/'; - /** @var Sabre_CalDAV_AnimexxUserCalendars $tree */ - $tree = $server->tree->getNodeForPath($calendar_path); - /** @var array|Sabre_CalDAV_Calendar[] $calendars */ - $children = $tree->getChildren(); + /** @var Sabre_CalDAV_AnimexxUserCalendars $tree */ + $tree = $server->tree->getNodeForPath($calendar_path); + /** @var array|Sabre_CalDAV_Calendar[] $calendars */ + $children = $tree->getChildren(); - $calendars = array(); - /** @var Sabre_DAVACL_Plugin $aclplugin */ - $aclplugin = $server->getPlugin("acl"); - foreach ($children as $child) if (is_a($child, "Sabre_CalDAV_Calendar") || is_subclass_of($child, "Sabre_CalDAV_Calendar")) { - if ($with_privilege != "") { - $caluri = $calendar_path . $child->getName(); - if ($aclplugin->checkPrivileges($caluri, $with_privilege, Sabre_DAVACL_Plugin::R_PARENT, false)) $calendars[] = $child; - } else { - $calendars[] = $child; - } - } - return $calendars; + $calendars = array(); + /** @var Sabre_DAVACL_Plugin $aclplugin */ + $aclplugin = $server->getPlugin('acl'); + foreach ($children as $child) { + if (is_a($child, 'Sabre_CalDAV_Calendar') || is_subclass_of($child, 'Sabre_CalDAV_Calendar')) { + if ($with_privilege != '') { + $caluri = $calendar_path.$child->getName(); + if ($aclplugin->checkPrivileges($caluri, $with_privilege, Sabre_DAVACL_Plugin::R_PARENT, false)) { + $calendars[] = $child; + } + } else { + $calendars[] = $child; + } + } + } + + return $calendars; } - /** - * @param Sabre_DAV_Server $server + * @param Sabre_DAV_Server $server * @param Sabre_CalDAV_Calendar $calendar - * @param string $calendarobject_uri - * @param string $with_privilege + * @param string $calendarobject_uri + * @param string $with_privilege + * * @return null|Sabre\VObject\Component\VCalendar */ -function dav_get_current_user_calendarobject(&$server, &$calendar, $calendarobject_uri, $with_privilege = "") +function dav_get_current_user_calendarobject(&$server, &$calendar, $calendarobject_uri, $with_privilege = '') { - $obj = $calendar->getChild($calendarobject_uri); + $obj = $calendar->getChild($calendarobject_uri); - if ($with_privilege == "") $with_privilege = DAV_ACL_READ; + if ($with_privilege == '') { + $with_privilege = DAV_ACL_READ; + } - $a = get_app(); - $uri = "/calendars/" . strtolower($a->user["nickname"]) . "/" . $calendar->getName() . "/" . $calendarobject_uri; + $a = get_app(); + $uri = '/calendars/'.strtolower($a->user['nickname']).'/'.$calendar->getName().'/'.$calendarobject_uri; - /** @var Sabre_DAVACL_Plugin $aclplugin */ - $aclplugin = $server->getPlugin("acl"); - if (!$aclplugin->checkPrivileges($uri, $with_privilege, Sabre_DAVACL_Plugin::R_PARENT, false)) return null; + /** @var Sabre_DAVACL_Plugin $aclplugin */ + $aclplugin = $server->getPlugin('acl'); + if (!$aclplugin->checkPrivileges($uri, $with_privilege, Sabre_DAVACL_Plugin::R_PARENT, false)) { + return null; + } - $data = $obj->get(); - $vObject = Sabre\VObject\Reader::read($data); + $data = $obj->get(); + $vObject = Sabre\VObject\Reader::read($data); - return $vObject; + return $vObject; } - /** * @param Sabre_DAV_Server $server - * @param int $id - * @param string $with_privilege + * @param int $id + * @param string $with_privilege + * * @return null|Sabre_CalDAV_Calendar */ -function dav_get_current_user_calendar_by_id(&$server, $id, $with_privilege = "") +function dav_get_current_user_calendar_by_id(&$server, $id, $with_privilege = '') { - $calendars = dav_get_current_user_calendars($server, $with_privilege); + $calendars = dav_get_current_user_calendars($server, $with_privilege); - $calendar = null; - foreach ($calendars as $cal) { - $prop = $cal->getProperties(array("id")); - if (isset($prop["id"]) && $prop["id"] == $id) $calendar = $cal; - } + $calendar = null; + foreach ($calendars as $cal) { + $prop = $cal->getProperties(array('id')); + if (isset($prop['id']) && $prop['id'] == $id) { + $calendar = $cal; + } + } - return $calendar; + return $calendar; } - /** * @param string $uid + * * @return Sabre\VObject\Component\VCalendar $vObject */ -function dav_create_empty_vevent($uid = "") +function dav_create_empty_vevent($uid = '') { - if ($uid == "") $uid = uniqid(); - return Sabre\VObject\Reader::read("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//" . DAV_APPNAME . "//DAV-Plugin//EN\r\nBEGIN:VEVENT\r\nUID:" . $uid . "@" . dav_compat_get_hostname() . - "\r\nDTSTAMP:" . date("Ymd") . "T" . date("His") . "Z\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); -} + if ($uid == '') { + $uid = uniqid(); + } + return Sabre\VObject\Reader::read("BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//".DAV_APPNAME."//DAV-Plugin//EN\r\nBEGIN:VEVENT\r\nUID:".$uid.'@'.dav_compat_get_hostname(). + "\r\nDTSTAMP:".date('Ymd').'T'.date('His')."Z\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"); +} /** * @param Sabre\VObject\Component\VCalendar $vObject + * * @return Sabre\VObject\Component\VEvent|null */ function dav_get_eventComponent(&$vObject) { - $component = null; - $componentType = ""; - foreach ($vObject->getComponents() as $component) { - if ($component->name !== 'VTIMEZONE') { - $componentType = $component->name; - break; - } - } - if ($componentType != "VEVENT") return null; + $component = null; + $componentType = ''; + foreach ($vObject->getComponents() as $component) { + if ($component->name !== 'VTIMEZONE') { + $componentType = $component->name; + break; + } + } + if ($componentType != 'VEVENT') { + return null; + } - return $component; + return $component; } diff --git a/dav/common/calendar_rendering.fnk.php b/dav/common/calendar_rendering.fnk.php index d80892f7..dd2913da 100644 --- a/dav/common/calendar_rendering.fnk.php +++ b/dav/common/calendar_rendering.fnk.php @@ -1,187 +1,197 @@ __get("TRIGGER"); - if (!isset($trigger['VALUE']) || strtoupper($trigger['VALUE']) === 'DURATION') { - $triggerDuration = Sabre\VObject\DateTimeParser::parseDuration($trigger->value); + $trigger = $alarm->__get('TRIGGER'); + if (!isset($trigger['VALUE']) || strtoupper($trigger['VALUE']) === 'DURATION') { + $triggerDuration = Sabre\VObject\DateTimeParser::parseDuration($trigger->value); - $related = (isset($trigger['RELATED']) && strtoupper($trigger['RELATED']) == 'END') ? 'END' : 'START'; + $related = (isset($trigger['RELATED']) && strtoupper($trigger['RELATED']) == 'END') ? 'END' : 'START'; - if ($related === 'START') { - /** @var Sabre\VObject\Property\DateTime $dtstart */ - $dtstart = $parent->__get("DTSTART"); - $effectiveTrigger = $dtstart->getDateTime(); - $effectiveTrigger->add($triggerDuration); - } else { - if ($parent->name === 'VTODO') { - $endProp = 'DUE'; - } else { - $endProp = 'DTEND'; - } + if ($related === 'START') { + /** @var Sabre\VObject\Property\DateTime $dtstart */ + $dtstart = $parent->__get('DTSTART'); + $effectiveTrigger = $dtstart->getDateTime(); + $effectiveTrigger->add($triggerDuration); + } else { + if ($parent->name === 'VTODO') { + $endProp = 'DUE'; + } else { + $endProp = 'DTEND'; + } - /** @var Sabre\VObject\Property\DateTime $dtstart */ - $dtstart = $parent->__get("DTSTART"); - if (isset($parent->$endProp)) { - $effectiveTrigger = clone $parent->$endProp->getDateTime(); - $effectiveTrigger->add($triggerDuration); - } elseif ($parent->__get("DURATION") != "") { - $effectiveTrigger = clone $dtstart->getDateTime(); - $duration = Sabre\VObject\DateTimeParser::parseDuration($parent->__get("DURATION")); - $effectiveTrigger->add($duration); - $effectiveTrigger->add($triggerDuration); - } else { - $effectiveTrigger = clone $dtstart->getDateTime(); - $effectiveTrigger->add($triggerDuration); - } - } - } else { - // ??? @TODO - $effectiveTrigger = $trigger->getDateTime(); - } - return $effectiveTrigger; + /** @var Sabre\VObject\Property\DateTime $dtstart */ + $dtstart = $parent->__get('DTSTART'); + if (isset($parent->$endProp)) { + $effectiveTrigger = clone $parent->$endProp->getDateTime(); + $effectiveTrigger->add($triggerDuration); + } elseif ($parent->__get('DURATION') != '') { + $effectiveTrigger = clone $dtstart->getDateTime(); + $duration = Sabre\VObject\DateTimeParser::parseDuration($parent->__get('DURATION')); + $effectiveTrigger->add($duration); + $effectiveTrigger->add($triggerDuration); + } else { + $effectiveTrigger = clone $dtstart->getDateTime(); + $effectiveTrigger->add($triggerDuration); + } + } + } else { + // ??? @TODO + $effectiveTrigger = $trigger->getDateTime(); + } + + return $effectiveTrigger; } /** * @param array $calendar * @param array $calendarobject + * * @throws Sabre_DAV_Exception_BadRequest - * @return void */ function renderCalDavEntry_data(&$calendar, &$calendarobject) { - /** @var Sabre\VObject\Component\VCalendar $vObject */ - $vObject = Sabre\VObject\Reader::read($calendarobject["calendardata"]); - $componentType = null; - /** @var Sabre\VObject\Component\VEvent $component */ - $component = null; - foreach ($vObject->getComponents() as $component) { - if ($component->name !== 'VTIMEZONE') { - $componentType = $component->name; - break; - } - } - if (!$componentType) { - throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component'); - } + /** @var Sabre\VObject\Component\VCalendar $vObject */ + $vObject = Sabre\VObject\Reader::read($calendarobject['calendardata']); + $componentType = null; + /** @var Sabre\VObject\Component\VEvent $component */ + $component = null; + foreach ($vObject->getComponents() as $component) { + if ($component->name !== 'VTIMEZONE') { + $componentType = $component->name; + break; + } + } + if (!$componentType) { + throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component'); + } - $timezoneOffset = date("P"); // @TODO Get the actual timezone from the event + $timezoneOffset = date('P'); // @TODO Get the actual timezone from the event + if ($componentType !== 'VEVENT') { + return; + } - if ($componentType !== 'VEVENT') return; + $event = array( + 'description' => ($component->__get('DESCRIPTION') ? $component->__get('DESCRIPTION')->value : null), + 'summary' => ($component->__get('SUMMARY') ? $component->__get('SUMMARY')->value : null), + 'location' => ($component->__get('LOCATION') ? $component->__get('LOCATION')->value : null), + 'color' => ($component->__get('X-ANIMEXX-COLOR') ? $component->__get('X-ANIMEXX-COLOR')->value : null), + ); - $event = array( - "description" => ($component->__get("DESCRIPTION") ? $component->__get("DESCRIPTION")->value : null), - "summary" => ($component->__get("SUMMARY") ? $component->__get("SUMMARY")->value : null), - "location" => ($component->__get("LOCATION") ? $component->__get("LOCATION")->value : null), - "color" => ($component->__get("X-ANIMEXX-COLOR") ? $component->__get("X-ANIMEXX-COLOR")->value : null), - ); + $recurring = ($component->__get('RRULE') ? 1 : 0); + /** @var Sabre\VObject\Property\DateTime $dtstart */ + $dtstart = $component->__get('DTSTART'); + $allday = ($dtstart->getDateType() == Sabre\VObject\Property\DateTime::DATE ? 1 : 0); - $recurring = ($component->__get("RRULE") ? 1 : 0); - /** @var Sabre\VObject\Property\DateTime $dtstart */ - $dtstart = $component->__get("DTSTART"); - $allday = ($dtstart->getDateType() == Sabre\VObject\Property\DateTime::DATE ? 1 : 0); + /** @var array|Sabre\VObject\Component\VAlarm[] $alarms */ + $alarms = array(); + foreach ($component->getComponents() as $a_component) { + if ($a_component->name == 'VALARM') { + /* var Sabre\VObject\Component\VAlarm $component */ + $alarms[] = $a_component; + } + } - /** @var array|Sabre\VObject\Component\VAlarm[] $alarms */ - $alarms = array(); - foreach ($component->getComponents() as $a_component) if ($a_component->name == "VALARM") { - /** var Sabre\VObject\Component\VAlarm $component */ - $alarms[] = $a_component; - } + $it = new Sabre\VObject\RecurrenceIterator($vObject, (string) $component->__get('UID')); + $last_end = 0; + $max_ts = mktime(0, 0, 0, 1, 1, CALDAV_MAX_YEAR * 1); + $first = true; - $it = new Sabre\VObject\RecurrenceIterator($vObject, (string)$component->__get("UID")); - $last_end = 0; - $max_ts = mktime(0, 0, 0, 1, 1, CALDAV_MAX_YEAR * 1); - $first = true; + while ($it->valid() && $last_end < $max_ts && ($recurring || $first)) { + $first = false; + $last_end = $it->getDtEnd()->getTimestamp(); + $start = $it->getDtStart()->getTimestamp(); - while ($it->valid() && $last_end < $max_ts && ($recurring || $first)) { - $first = false; - $last_end = $it->getDtEnd()->getTimestamp(); - $start = $it->getDtStart()->getTimestamp(); - - q("INSERT INTO %s%sjqcalendar (`calendar_id`, `calendarobject_id`, `Summary`, `StartTime`, `EndTime`, `IsEditable`, `IsAllDayEvent`, `IsRecurring`, `Color`) VALUES + q("INSERT INTO %s%sjqcalendar (`calendar_id`, `calendarobject_id`, `Summary`, `StartTime`, `EndTime`, `IsEditable`, `IsAllDayEvent`, `IsRecurring`, `Color`) VALUES (%d, %d, '%s', CONVERT_TZ('%s', '$timezoneOffset', @@session.time_zone), CONVERT_TZ('%s', '$timezoneOffset', @@session.time_zone), %d, %d, %d, '%s')", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendar["id"]), IntVal($calendarobject["id"]), dbesc($event["summary"]), date("Y-m-d H:i:s", $start), - date("Y-m-d H:i:s", $last_end), 1, $allday, $recurring, dbesc(substr($event["color"], 1)) - ); + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendar['id']), intval($calendarobject['id']), dbesc($event['summary']), date('Y-m-d H:i:s', $start), + date('Y-m-d H:i:s', $last_end), 1, $allday, $recurring, dbesc(substr($event['color'], 1)) + ); - foreach ($alarms as $alarm) { - $alarm = renderCalDavEntry_calcalarm($alarm, $component); - $notified = ($alarm->getTimestamp() < time() ? 1 : 0); - q("INSERT INTO %s%snotifications (`calendar_id`, `calendarobject_id`, `alert_date`, `notified`) VALUES (%d, %d, CONVERT_TZ('%s', '$timezoneOffset', @@session.time_zone), %d)", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendar["id"]), IntVal($calendarobject["id"]), $alarm->format("Y-m-d H:i:s"), $notified - ); - } + foreach ($alarms as $alarm) { + $alarm = renderCalDavEntry_calcalarm($alarm, $component); + $notified = ($alarm->getTimestamp() < time() ? 1 : 0); + q("INSERT INTO %s%snotifications (`calendar_id`, `calendarobject_id`, `alert_date`, `notified`) VALUES (%d, %d, CONVERT_TZ('%s', '$timezoneOffset', @@session.time_zone), %d)", + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendar['id']), intval($calendarobject['id']), $alarm->format('Y-m-d H:i:s'), $notified + ); + } - $it->next(); - } - - return; + $it->next(); + } + return; } - -/** - * - */ function renderAllCalDavEntries() { - q("DELETE FROM %s%sjqcalendar", CALDAV_SQL_DB, CALDAV_SQL_PREFIX); - q("DELETE FROM %s%snotifications", CALDAV_SQL_DB, CALDAV_SQL_PREFIX); - $calendars = q("SELECT * FROM %s%scalendars", CALDAV_SQL_DB, CALDAV_SQL_PREFIX); - $anz = count($calendars); - $i = 0; - foreach ($calendars as $calendar) { - $i++; - if (($i % 100) == 0) echo "$i / $anz\n"; - $calobjs = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendar["id"])); - foreach ($calobjs as $calobj) renderCalDavEntry_data($calendar, $calobj); - } + q('DELETE FROM %s%sjqcalendar', CALDAV_SQL_DB, CALDAV_SQL_PREFIX); + q('DELETE FROM %s%snotifications', CALDAV_SQL_DB, CALDAV_SQL_PREFIX); + $calendars = q('SELECT * FROM %s%scalendars', CALDAV_SQL_DB, CALDAV_SQL_PREFIX); + $anz = count($calendars); + $i = 0; + foreach ($calendars as $calendar) { + ++$i; + if (($i % 100) == 0) { + echo "$i / $anz\n"; + } + $calobjs = q('SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendar['id'])); + foreach ($calobjs as $calobj) { + renderCalDavEntry_data($calendar, $calobj); + } + } } - /** * @param string $uri + * * @return bool */ function renderCalDavEntry_uri($uri) { - $calobj = q("SELECT * FROM %s%scalendarobjects WHERE `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($uri)); - if (count($calobj) == 0) return false; + $calobj = q("SELECT * FROM %s%scalendarobjects WHERE `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($uri)); + if (count($calobj) == 0) { + return false; + } - q("DELETE FROM %s%sjqcalendar WHERE `calendar_id` = %d AND `calendarobject_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calobj[0]["calendar_id"]), IntVal($calobj[0]["id"])); - q("DELETE FROM %s%snotifications WHERE `calendar_id` = %d AND `calendarobject_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calobj[0]["calendar_id"]), IntVal($calobj[0]["id"])); + q('DELETE FROM %s%sjqcalendar WHERE `calendar_id` = %d AND `calendarobject_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calobj[0]['calendar_id']), intval($calobj[0]['id'])); + q('DELETE FROM %s%snotifications WHERE `calendar_id` = %d AND `calendarobject_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calobj[0]['calendar_id']), intval($calobj[0]['id'])); - $calendars = q("SELECT * FROM %s%scalendars WHERE `id`=%d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calobj[0]["calendar_id"])); + $calendars = q('SELECT * FROM %s%scalendars WHERE `id`=%d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calobj[0]['calendar_id'])); - renderCalDavEntry_data($calendars[0], $calobj[0]); - return true; + renderCalDavEntry_data($calendars[0], $calobj[0]); + + return true; } - /** * @param int $calobj_id + * * @return bool */ function renderCalDavEntry_calobj_id($calobj_id) { - $calobj_id = IntVal($calobj_id); - q("DELETE FROM %s%sjqcalendar WHERE `calendarobject_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calobj_id); - q("DELETE FROM %s%snotifications WHERE `calendarobject_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calobj_id); + $calobj_id = intval($calobj_id); + q('DELETE FROM %s%sjqcalendar WHERE `calendarobject_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calobj_id); + q('DELETE FROM %s%snotifications WHERE `calendarobject_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calobj_id); - $calobj = q("SELECT * FROM %s%scalendarobjects WHERE `id` = '%d'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calobj_id); - if (count($calobj) == 0) return false; + $calobj = q("SELECT * FROM %s%scalendarobjects WHERE `id` = '%d'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calobj_id); + if (count($calobj) == 0) { + return false; + } - $calendars = q("SELECT * FROM %s%scalendars WHERE `id`=%d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calobj[0]["calendar_id"])); + $calendars = q('SELECT * FROM %s%scalendars WHERE `id`=%d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calobj[0]['calendar_id'])); - renderCalDavEntry_data($calendars[0], $calobj[0]); - return true; + renderCalDavEntry_data($calendars[0], $calobj[0]); + + return true; } diff --git a/dav/common/dav_caldav_backend_common.inc.php b/dav/common/dav_caldav_backend_common.inc.php index 97d5722a..06a50719 100644 --- a/dav/common/dav_caldav_backend_common.inc.php +++ b/dav/common/dav_caldav_backend_common.inc.php @@ -2,286 +2,295 @@ abstract class Sabre_CalDAV_Backend_Common extends Sabre_CalDAV_Backend_Abstract { - /** - * @var array - */ - protected $propertyMap = array( - '{DAV:}displayname' => 'displayname', - '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description', - '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone', - '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder', - '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor', - ); + /** + * @var array + */ + protected $propertyMap = array( + '{DAV:}displayname' => 'displayname', + '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description', + '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone', + '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder', + '{http://apple.com/ns/ical/}calendar-color' => 'calendarcolor', + ); + /** + * @abstract + * + * @return int + */ + abstract public function getNamespace(); - /** - * @abstract - * @return int - */ - abstract public function getNamespace(); + /** + * @static + * @abstract + * + * @return string + */ + abstract public static function getBackendTypeName(); - /** - * @static - * @abstract - * @return string - */ - abstract public static function getBackendTypeName(); + /** + * @param int $calendarId + * @param string $sd + * @param string $ed + * @param string $base_path + * + * @return array + */ + abstract public function listItemsByRange($calendarId, $sd, $ed, $base_path); + /** + * @var array + */ + private static $calendarCache = array(); - /** - * @param int $calendarId - * @param string $sd - * @param string $ed - * @param string $base_path - * @return array - */ - abstract public function listItemsByRange($calendarId, $sd, $ed, $base_path); + /** + * @var array + */ + private static $calendarObjectCache = array(); + /** + * @static + * + * @param int $calendarId + * + * @return array + */ + public static function loadCalendarById($calendarId) + { + if (!isset(self::$calendarCache[$calendarId])) { + $c = q('SELECT * FROM %s%scalendars WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId)); + self::$calendarCache[$calendarId] = $c[0]; + } - /** - * @var array - */ - static private $calendarCache = array(); + return self::$calendarCache[$calendarId]; + } - /** - * @var array - */ - static private $calendarObjectCache = array(); + /** + * @static + * + * @param int $obj_id + * + * @return array + */ + public static function loadCalendarobjectById($obj_id) + { + if (!isset(self::$calendarObjectCache[$obj_id])) { + $o = q('SELECT * FROM %s%scalendarobjects WHERE `id` = %d', + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($obj_id) + ); + self::$calendarObjectCache[$obj_id] = $o[0]; + } - /** - * @static - * @param int $calendarId - * @return array - */ - static public function loadCalendarById($calendarId) - { - if (!isset(self::$calendarCache[$calendarId])) { - $c = q("SELECT * FROM %s%scalendars WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId)); - self::$calendarCache[$calendarId] = $c[0]; - } - return self::$calendarCache[$calendarId]; - } + return self::$calendarObjectCache[$obj_id]; + } - /** - * @static - * @param int $obj_id - * @return array - */ - static public function loadCalendarobjectById($obj_id) - { - if (!isset(self::$calendarObjectCache[$obj_id])) { - $o = q("SELECT * FROM %s%scalendarobjects WHERE `id` = %d", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($obj_id) - ); - self::$calendarObjectCache[$obj_id] = $o[0]; - } - return self::$calendarObjectCache[$obj_id]; - } + /** + * @static + * + * @param Sabre\VObject\Component\VEvent $component + * + * @return int + */ + public static function getDtEndTimeStamp(&$component) + { + /** @var Sabre\VObject\Property\DateTime $dtstart */ + $dtstart = $component->__get('DTSTART'); + if ($component->__get('DTEND')) { + /** @var Sabre\VObject\Property\DateTime $dtend */ + $dtend = $component->__get('DTEND'); + return $dtend->getDateTime()->getTimeStamp(); + } elseif ($component->__get('DURATION')) { + $endDate = clone $dtstart->getDateTime(); + $endDate->add(Sabre\VObject\DateTimeParser::parse($component->__get('DURATION')->value)); - /** - * @static - * @param Sabre\VObject\Component\VEvent $component - * @return int - */ - public static function getDtEndTimeStamp(&$component) - { - /** @var Sabre\VObject\Property\DateTime $dtstart */ - $dtstart = $component->__get("DTSTART"); - if ($component->__get("DTEND")) { - /** @var Sabre\VObject\Property\DateTime $dtend */ - $dtend = $component->__get("DTEND"); - return $dtend->getDateTime()->getTimeStamp(); - } elseif ($component->__get("DURATION")) { - $endDate = clone $dtstart->getDateTime(); - $endDate->add(Sabre\VObject\DateTimeParser::parse($component->__get("DURATION")->value)); - return $endDate->getTimeStamp(); - } elseif ($dtstart->getDateType() === Sabre\VObject\Property\DateTime::DATE) { - $endDate = clone $dtstart->getDateTime(); - $endDate->modify('+1 day'); - return $endDate->getTimeStamp(); - } else { - return $dtstart->getDateTime()->getTimeStamp() + 3600; - } + return $endDate->getTimeStamp(); + } elseif ($dtstart->getDateType() === Sabre\VObject\Property\DateTime::DATE) { + $endDate = clone $dtstart->getDateTime(); + $endDate->modify('+1 day'); - } + return $endDate->getTimeStamp(); + } else { + return $dtstart->getDateTime()->getTimeStamp() + 3600; + } + } + /** + * Parses some information from calendar objects, used for optimized + * calendar-queries. + * + * Returns an array with the following keys: + * * etag + * * size + * * componentType + * * firstOccurence + * * lastOccurence + * + * @param string $calendarData + * + * @throws Sabre_DAV_Exception_BadRequest + * + * @return array + */ + protected function getDenormalizedData($calendarData) + { + /** @var Sabre\VObject\Component\VEvent $vObject */ + $vObject = Sabre\VObject\Reader::read($calendarData); + $componentType = null; + $component = null; + $firstOccurence = null; + $lastOccurence = null; - /** - * Parses some information from calendar objects, used for optimized - * calendar-queries. - * - * Returns an array with the following keys: - * * etag - * * size - * * componentType - * * firstOccurence - * * lastOccurence - * - * @param string $calendarData - * @throws Sabre_DAV_Exception_BadRequest - * @return array - */ - protected function getDenormalizedData($calendarData) - { - /** @var Sabre\VObject\Component\VEvent $vObject */ - $vObject = Sabre\VObject\Reader::read($calendarData); - $componentType = null; - $component = null; - $firstOccurence = null; - $lastOccurence = null; + foreach ($vObject->getComponents() as $component) { + if ($component->name !== 'VTIMEZONE') { + $componentType = $component->name; + break; + } + } + if (!$componentType) { + throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component'); + } + if ($componentType === 'VEVENT') { + /** @var Sabre\VObject\Component\VEvent $component */ + /** @var Sabre\VObject\Property\DateTime $dtstart */ + $dtstart = $component->__get('DTSTART'); + $firstOccurence = $dtstart->getDateTime()->getTimeStamp(); + // Finding the last occurence is a bit harder + if (!$component->__get('RRULE')) { + $lastOccurence = self::getDtEndTimeStamp($component); + } else { + $it = new Sabre\VObject\RecurrenceIterator($vObject, (string) $component->__get('UID')); + $maxDate = new DateTime(CALDAV_MAX_YEAR.'-01-01'); + if ($it->isInfinite()) { + $lastOccurence = $maxDate->getTimeStamp(); + } else { + $end = $it->getDtEnd(); + while ($it->valid() && $end < $maxDate) { + $end = $it->getDtEnd(); + $it->next(); + } + $lastOccurence = $end->getTimeStamp(); + } + } + } - foreach ($vObject->getComponents() as $component) { - if ($component->name !== 'VTIMEZONE') { - $componentType = $component->name; - break; - } - } - if (!$componentType) { - throw new Sabre_DAV_Exception_BadRequest('Calendar objects must have a VJOURNAL, VEVENT or VTODO component'); - } - if ($componentType === 'VEVENT') { - /** @var Sabre\VObject\Component\VEvent $component */ - /** @var Sabre\VObject\Property\DateTime $dtstart */ - $dtstart = $component->__get("DTSTART"); - $firstOccurence = $dtstart->getDateTime()->getTimeStamp(); - // Finding the last occurence is a bit harder - if (!$component->__get("RRULE")) { - $lastOccurence = self::getDtEndTimeStamp($component); - } else { - $it = new Sabre\VObject\RecurrenceIterator($vObject, (string)$component->__get("UID")); - $maxDate = new DateTime(CALDAV_MAX_YEAR . "-01-01"); - if ($it->isInfinite()) { - $lastOccurence = $maxDate->getTimeStamp(); - } else { - $end = $it->getDtEnd(); - while ($it->valid() && $end < $maxDate) { - $end = $it->getDtEnd(); - $it->next(); + return array( + 'etag' => md5($calendarData), + 'size' => strlen($calendarData), + 'componentType' => $componentType, + 'firstOccurence' => $firstOccurence, + 'lastOccurence' => $lastOccurence, + ); + } - } - $lastOccurence = $end->getTimeStamp(); - } + /** + * Updates properties for a calendar. + * + * The mutations array uses the propertyName in clark-notation as key, + * and the array value for the property value. In the case a property + * should be deleted, the property value will be null. + * + * This method must be atomic. If one property cannot be changed, the + * entire operation must fail. + * + * If the operation was successful, true can be returned. + * If the operation failed, false can be returned. + * + * Deletion of a non-existent property is always successful. + * + * Lastly, it is optional to return detailed information about any + * failures. In this case an array should be returned with the following + * structure: + * + * array( + * 403 => array( + * '{DAV:}displayname' => null, + * ), + * 424 => array( + * '{DAV:}owner' => null, + * ) + * ) + * + * In this example it was forbidden to update {DAV:}displayname. + * (403 Forbidden), which in turn also caused {DAV:}owner to fail + * (424 Failed Dependency) because the request needs to be atomic. + * + * @param mixed $calendarId + * @param array $mutations + * + * @return bool|array + */ + public function updateCalendar($calendarId, array $mutations) + { + $newValues = array(); + $result = array( + 200 => array(), // Ok + 403 => array(), // Forbidden + 424 => array(), // Failed Dependency + ); - } - } + $hasError = false; - return array( - 'etag' => md5($calendarData), - 'size' => strlen($calendarData), - 'componentType' => $componentType, - 'firstOccurence' => $firstOccurence, - 'lastOccurence' => $lastOccurence, - ); + foreach ($mutations as $propertyName => $propertyValue) { - } + // We don't know about this property. + if (!isset($this->propertyMap[$propertyName])) { + $hasError = true; + $result[403][$propertyName] = null; + unset($mutations[$propertyName]); + continue; + } - /** - * Updates properties for a calendar. - * - * The mutations array uses the propertyName in clark-notation as key, - * and the array value for the property value. In the case a property - * should be deleted, the property value will be null. - * - * This method must be atomic. If one property cannot be changed, the - * entire operation must fail. - * - * If the operation was successful, true can be returned. - * If the operation failed, false can be returned. - * - * Deletion of a non-existent property is always successful. - * - * Lastly, it is optional to return detailed information about any - * failures. In this case an array should be returned with the following - * structure: - * - * array( - * 403 => array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param mixed $calendarId - * @param array $mutations - * @return bool|array - */ - public function updateCalendar($calendarId, array $mutations) - { + $fieldName = $this->propertyMap[$propertyName]; + $newValues[$fieldName] = $propertyValue; + } - $newValues = array(); - $result = array( - 200 => array(), // Ok - 403 => array(), // Forbidden - 424 => array(), // Failed Dependency - ); + // If there were any errors we need to fail the request + if ($hasError) { + // Properties has the remaining properties + foreach ($mutations as $propertyName => $propertyValue) { + $result[424][$propertyName] = null; + } - $hasError = false; + // Removing unused statuscodes for cleanliness + foreach ($result as $status => $properties) { + if (is_array($properties) && count($properties) === 0) { + unset($result[$status]); + } + } - foreach ($mutations as $propertyName=> $propertyValue) { + return $result; + } - // We don't know about this property. - if (!isset($this->propertyMap[$propertyName])) { - $hasError = true; - $result[403][$propertyName] = null; - unset($mutations[$propertyName]); - continue; - } + $this->increaseCalendarCtag($calendarId); - $fieldName = $this->propertyMap[$propertyName]; - $newValues[$fieldName] = $propertyValue; + $valuesSql = array(); + foreach ($newValues as $fieldName => $value) { + $valuesSql[] = '`'.$fieldName."` = '".dbesc($value)."'"; + } + if (count($valuesSql) > 0) { + q('UPDATE %s%scalendars SET '.implode(', ', $valuesSql).' WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId)); + } - } + return true; + } - // If there were any errors we need to fail the request - if ($hasError) { - // Properties has the remaining properties - foreach ($mutations as $propertyName=> $propertyValue) { - $result[424][$propertyName] = null; - } + /** + * @param int $calendarId + */ + protected function increaseCalendarCtag($calendarId) + { + q("UPDATE %s%scalendars SET `ctag` = `ctag` + 1 WHERE `id` = '%d'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId)); + self::$calendarObjectCache = array(); + } - // Removing unused statuscodes for cleanliness - foreach ($result as $status=> $properties) { - if (is_array($properties) && count($properties) === 0) unset($result[$status]); - } - - return $result; - - } - - $this->increaseCalendarCtag($calendarId); - - $valuesSql = array(); - foreach ($newValues as $fieldName=> $value) $valuesSql[] = "`" . $fieldName . "` = '" . dbesc($value) . "'"; - if (count($valuesSql) > 0) { - q("UPDATE %s%scalendars SET " . implode(", ", $valuesSql) . " WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId)); - } - - return true; - - } - - /** - * @param int $calendarId - */ - protected function increaseCalendarCtag($calendarId) - { - q("UPDATE %s%scalendars SET `ctag` = `ctag` + 1 WHERE `id` = '%d'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId)); - self::$calendarObjectCache = array(); - } - - /** - * @abstract - * @param int $calendar_id - * @param int $calendarobject_id - * @return string - */ - abstract function getItemDetailRedirect($calendar_id, $calendarobject_id); - -} \ No newline at end of file + /** + * @abstract + * + * @param int $calendar_id + * @param int $calendarobject_id + * + * @return string + */ + abstract public function getItemDetailRedirect($calendar_id, $calendarobject_id); +} diff --git a/dav/common/dav_caldav_backend_private.inc.php b/dav/common/dav_caldav_backend_private.inc.php index 1eb3b365..9565cd9a 100644 --- a/dav/common/dav_caldav_backend_private.inc.php +++ b/dav/common/dav_caldav_backend_private.inc.php @@ -2,509 +2,549 @@ class Sabre_CalDAV_Backend_Private extends Sabre_CalDAV_Backend_Common { + /** + * @var null|Sabre_CalDAV_Backend_Private + */ + private static $instance = null; + /** + * @static + * + * @return Sabre_CalDAV_Backend_Private + */ + public static function getInstance() + { + if (self::$instance == null) { + self::$instance = new self(); + } - /** - * @var null|Sabre_CalDAV_Backend_Private - */ - private static $instance = null; + return self::$instance; + } - /** - * @static - * @return Sabre_CalDAV_Backend_Private - */ - public static function getInstance() - { - if (self::$instance == null) { - self::$instance = new Sabre_CalDAV_Backend_Private(); - } - return self::$instance; - } + /** + * @return int + */ + public function getNamespace() + { + return CALDAV_NAMESPACE_PRIVATE; + } + /** + * @static + * + * @return string + */ + public static function getBackendTypeName() + { + return t('Private Events'); + } - /** - * @return int - */ - public function getNamespace() - { - return CALDAV_NAMESPACE_PRIVATE; - } + /** + * @obsolete + * + * @param array $calendar + * @param int $user + * + * @return array + */ + public function getPermissionsCalendar($calendar, $user) + { + if ($calendar['namespace'] == CALDAV_NAMESPACE_PRIVATE && $user == $calendar['namespace_id']) { + return array('read' => true, 'write' => true); + } - /** - * @static - * @return string - */ - public static function getBackendTypeName() - { - return t("Private Events"); - } + return array('read' => false, 'write' => false); + } - /** - * @obsolete - * @param array $calendar - * @param int $user - * @return array - */ - public function getPermissionsCalendar($calendar, $user) - { - if ($calendar["namespace"] == CALDAV_NAMESPACE_PRIVATE && $user == $calendar["namespace_id"]) return array("read"=> true, "write"=> true); - return array("read"=> false, "write"=> false); - } + /** + * @obsolete + * + * @param array $calendar + * @param int $user + * @param string $calendarobject_id + * @param null|array $item_arr + * + * @return array + */ + public function getPermissionsItem($calendar, $user, $calendarobject_id, $item_arr = null) + { + return $this->getPermissionsCalendar($calendar, $user); + } - /** - * @obsolete - * @param array $calendar - * @param int $user - * @param string $calendarobject_id - * @param null|array $item_arr - * @return array - */ - public function getPermissionsItem($calendar, $user, $calendarobject_id, $item_arr = null) - { - return $this->getPermissionsCalendar($calendar, $user); - } + /** + * @param array $row + * @param array $calendar + * @param string $base_path + * + * @return array + */ + private function jqcal2wdcal($row, $calendar, $base_path) + { + $not = q('SELECT COUNT(*) num FROM %s%snotifications WHERE `calendar_id` = %d AND `calendarobject_id` = %d', + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($row['calendar_id']), intval($row['calendarobject_id']) + ); + $editable = $this->getPermissionsItem($calendar['namespace_id'], $row['calendarobject_id'], $row); + $end = wdcal_mySql2PhpTime($row['EndTime']); + if ($row['IsAllDayEvent']) { + $end -= 1; + } - /** - * @param array $row - * @param array $calendar - * @param string $base_path - * @return array - */ - private function jqcal2wdcal($row, $calendar, $base_path) - { - $not = q("SELECT COUNT(*) num FROM %s%snotifications WHERE `calendar_id` = %d AND `calendarobject_id` = %d", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($row["calendar_id"]), IntVal($row["calendarobject_id"]) - ); - $editable = $this->getPermissionsItem($calendar["namespace_id"], $row["calendarobject_id"], $row); + return array( + 'jq_id' => $row['id'], + 'ev_id' => $row['calendarobject_id'], + 'summary' => escape_tags($row['Summary']), + 'start' => wdcal_mySql2PhpTime($row['StartTime']), + 'end' => $end, + 'is_allday' => $row['IsAllDayEvent'], + 'is_moredays' => 0, + 'is_recurring' => $row['IsRecurring'], + 'color' => (is_null($row['Color']) || $row['Color'] == '' ? $calendar['calendarcolor'] : $row['Color']), + 'is_editable' => ($editable ? 1 : 0), + 'is_editable_quick' => ($editable && !$row['IsRecurring'] ? 1 : 0), + 'location' => 'Loc.', + 'attendees' => '', + 'has_notification' => ($not[0]['num'] > 0 ? 1 : 0), + 'url_detail' => $base_path.$row['calendarobject_id'].'/', + 'url_edit' => $base_path.$row['calendarobject_id'].'/edit/', + 'special_type' => '', + ); + } - $end = wdcal_mySql2PhpTime($row["EndTime"]); - if ($row["IsAllDayEvent"]) $end -= 1; + /** + * @param int $calendarId + * @param string $sd + * @param string $ed + * @param string $base_path + * + * @return array + */ + public function listItemsByRange($calendarId, $sd, $ed, $base_path) + { + $calendar = Sabre_CalDAV_Backend_Common::loadCalendarById($calendarId); + $von = wdcal_php2MySqlTime($sd); + $bis = wdcal_php2MySqlTime($ed); + $timezoneOffset = date('P'); - return array( - "jq_id" => $row["id"], - "ev_id" => $row["calendarobject_id"], - "summary" => escape_tags($row["Summary"]), - "start" => wdcal_mySql2PhpTime($row["StartTime"]), - "end" => $end, - "is_allday" => $row["IsAllDayEvent"], - "is_moredays" => 0, - "is_recurring" => $row["IsRecurring"], - "color" => (is_null($row["Color"]) || $row["Color"] == "" ? $calendar["calendarcolor"] : $row["Color"]), - "is_editable" => ($editable ? 1 : 0), - "is_editable_quick" => ($editable && !$row["IsRecurring"] ? 1 : 0), - "location" => "Loc.", - "attendees" => '', - "has_notification" => ($not[0]["num"] > 0 ? 1 : 0), - "url_detail" => $base_path . $row["calendarobject_id"] . "/", - "url_edit" => $base_path . $row["calendarobject_id"] . "/edit/", - "special_type" => "", - ); - } - - /** - * @param int $calendarId - * @param string $sd - * @param string $ed - * @param string $base_path - * @return array - */ - public function listItemsByRange($calendarId, $sd, $ed, $base_path) - { - $calendar = Sabre_CalDAV_Backend_Common::loadCalendarById($calendarId); - $von = wdcal_php2MySqlTime($sd); - $bis = wdcal_php2MySqlTime($ed); - $timezoneOffset = date("P"); - - // @TODO Events, die früher angefangen haben, aber noch andauern - $evs = q("SELECT *, CONVERT_TZ(`StartTime`, @@session.time_zone, '$timezoneOffset') StartTime, CONVERT_TZ(`EndTime`, @@session.time_zone, '$timezoneOffset') EndTime + // @TODO Events, die früher angefangen haben, aber noch andauern + $evs = q("SELECT *, CONVERT_TZ(`StartTime`, @@session.time_zone, '$timezoneOffset') StartTime, CONVERT_TZ(`EndTime`, @@session.time_zone, '$timezoneOffset') EndTime FROM %s%sjqcalendar WHERE `calendar_id` = %d AND `StartTime` between '%s' and '%s'", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($von), dbesc($bis)); + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId), dbesc($von), dbesc($bis)); - $events = array(); - foreach ($evs as $row) $events[] = $this->jqcal2wdcal($row, $calendar, $base_path . $row["calendar_id"] . "/"); + $events = array(); + foreach ($evs as $row) { + $events[] = $this->jqcal2wdcal($row, $calendar, $base_path.$row['calendar_id'].'/'); + } - return $events; - } + return $events; + } + /** + * @param int $calendar_id + * @param int $calendarobject_id + * + * @return string + */ + public function getItemDetailRedirect($calendar_id, $calendarobject_id) + { + return "/dav/wdcal/$calendar_id/$calendarobject_id/edit/"; + } - /** - * @param int $calendar_id - * @param int $calendarobject_id - * @return string - */ - public function getItemDetailRedirect($calendar_id, $calendarobject_id) - { - return "/dav/wdcal/$calendar_id/$calendarobject_id/edit/"; - } + /** + * Returns a list of calendars for a principal. + * + * Every project is an array with the following keys: + * * id, a unique id that will be used by other functions to modify the + * calendar. This can be the same as the uri or a database key. + * * uri, which the basename of the uri with which the calendar is + * accessed. + * * principaluri. The owner of the calendar. Almost always the same as + * principalUri passed to this method. + * + * Furthermore it can contain webdav properties in clark notation. A very + * common one is '{DAV:}displayname'. + * + * @param string $principalUri + * + * @throws DAVVersionMismatchException + * + * @return array + */ + public function getCalendarsForUser($principalUri) + { + $n = dav_compat_principal2namespace($principalUri); + if ($n['namespace'] != $this->getNamespace()) { + return array(); + } - /** - * Returns a list of calendars for a principal. - * - * Every project is an array with the following keys: - * * id, a unique id that will be used by other functions to modify the - * calendar. This can be the same as the uri or a database key. - * * uri, which the basename of the uri with which the calendar is - * accessed. - * * principaluri. The owner of the calendar. Almost always the same as - * principalUri passed to this method. - * - * Furthermore it can contain webdav properties in clark notation. A very - * common one is '{DAV:}displayname'. - * - * @param string $principalUri - * @throws DAVVersionMismatchException - * @return array - */ - public function getCalendarsForUser($principalUri) - { - $n = dav_compat_principal2namespace($principalUri); - if ($n["namespace"] != $this->getNamespace()) return array(); + $cals = q('SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $this->getNamespace(), intval($n['namespace_id'])); + $ret = array(); + foreach ($cals as $cal) { + if (!isset($cal['uri'])) { + throw new DAVVersionMismatchException(); + } + if (in_array($cal['uri'], $GLOBALS['CALDAV_PRIVATE_SYSTEM_CALENDARS'])) { + continue; + } - $cals = q("SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $this->getNamespace(), IntVal($n["namespace_id"])); - $ret = array(); - foreach ($cals as $cal) { - if (!isset($cal["uri"])) throw new DAVVersionMismatchException(); - if (in_array($cal["uri"], $GLOBALS["CALDAV_PRIVATE_SYSTEM_CALENDARS"])) continue; + $components = array(); + if ($cal['has_vevent']) { + $components[] = 'VEVENT'; + } + if ($cal['has_vtodo']) { + $components[] = 'VTODO'; + } - $components = array(); - if ($cal["has_vevent"]) $components[] = "VEVENT"; - if ($cal["has_vtodo"]) $components[] = "VTODO"; + $dat = array( + 'id' => $cal['id'], + 'uri' => $cal['uri'], + 'principaluri' => $principalUri, + '{'.Sabre_CalDAV_Plugin::NS_CALENDARSERVER.'}getctag' => $cal['ctag'] ? $cal['ctag'] : '0', + '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components), + 'calendar_class' => 'Sabre_CalDAV_Calendar_Private', + ); + foreach ($this->propertyMap as $key => $field) { + $dat[$key] = $cal[$field]; + } - $dat = array( - "id" => $cal["id"], - "uri" => $cal["uri"], - "principaluri" => $principalUri, - '{' . Sabre_CalDAV_Plugin::NS_CALENDARSERVER . '}getctag' => $cal['ctag'] ? $cal['ctag'] : '0', - '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}supported-calendar-component-set' => new Sabre_CalDAV_Property_SupportedCalendarComponentSet($components), - "calendar_class" => "Sabre_CalDAV_Calendar_Private", - ); - foreach ($this->propertyMap as $key=> $field) $dat[$key] = $cal[$field]; + $ret[] = $dat; + } - $ret[] = $dat; - } + return $ret; + } - return $ret; - } + /** + * Creates a new calendar for a principal. + * + * If the creation was a success, an id must be returned that can be used to reference + * this calendar in other methods, such as updateCalendar. + * + * @param string $principalUri + * @param string $calendarUri + * @param array $properties + * + * @throws Sabre_DAV_Exception|Sabre_DAV_Exception_Conflict + * + * @return string|void + */ + public function createCalendar($principalUri, $calendarUri, array $properties) + { + $uid = dav_compat_principal2uid($principalUri); + $r = q("SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, $uid, dbesc($calendarUri)); + if (count($r) > 0) { + throw new Sabre_DAV_Exception_Conflict('A calendar with this URI already exists'); + } - /** - * Creates a new calendar for a principal. - * - * If the creation was a success, an id must be returned that can be used to reference - * this calendar in other methods, such as updateCalendar. - * - * @param string $principalUri - * @param string $calendarUri - * @param array $properties - * @throws Sabre_DAV_Exception|Sabre_DAV_Exception_Conflict - * @return string|void - */ - public function createCalendar($principalUri, $calendarUri, array $properties) - { + $keys = array('`namespace`', '`namespace_id`', '`ctag`', '`uri`'); + $vals = array(CALDAV_NAMESPACE_PRIVATE, intval($uid), 1, "'".dbesc($calendarUri)."'"); - $uid = dav_compat_principal2uid($principalUri); + // Default value + $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'; + $has_vevent = $has_vtodo = 1; + if (isset($properties[$sccs])) { + if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) { + throw new Sabre_DAV_Exception('The '.$sccs.' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet'); + } + $v = $properties[$sccs]->getValue(); + $has_vevent = $has_vtodo = 0; + foreach ($v as $w) { + if (mb_strtolower($w) == 'vevent') { + $has_vevent = 1; + } + if (mb_strtolower($w) == 'vtodo') { + $has_vtodo = 1; + } + } + } + $keys[] = '`has_vevent`'; + $keys[] = '`has_vtodo`'; + $vals[] = $has_vevent; + $vals[] = $has_vtodo; - $r = q("SELECT * FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, $uid, dbesc($calendarUri)); - if (count($r) > 0) throw new Sabre_DAV_Exception_Conflict("A calendar with this URI already exists"); + foreach ($this->propertyMap as $xmlName => $dbName) { + if (isset($properties[$xmlName])) { + $keys[] = "`$dbName`"; + $vals[] = "'".dbesc($properties[$xmlName])."'"; + } + } - $keys = array("`namespace`", "`namespace_id`", "`ctag`", "`uri`"); - $vals = array(CALDAV_NAMESPACE_PRIVATE, IntVal($uid), 1, "'" . dbesc($calendarUri) . "'"); + $sql = sprintf('INSERT INTO %s%scalendars ('.implode(', ', $keys).') VALUES ('.implode(', ', $vals).')', CALDAV_SQL_DB, CALDAV_SQL_PREFIX); - // Default value - $sccs = '{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set'; - $has_vevent = $has_vtodo = 1; - if (isset($properties[$sccs])) { - if (!($properties[$sccs] instanceof Sabre_CalDAV_Property_SupportedCalendarComponentSet)) { - throw new Sabre_DAV_Exception('The ' . $sccs . ' property must be of type: Sabre_CalDAV_Property_SupportedCalendarComponentSet'); - } - $v = $properties[$sccs]->getValue(); - $has_vevent = $has_vtodo = 0; - foreach ($v as $w) { - if (mb_strtolower($w) == "vevent") $has_vevent = 1; - if (mb_strtolower($w) == "vtodo") $has_vtodo = 1; - } - } - $keys[] = "`has_vevent`"; - $keys[] = "`has_vtodo`"; - $vals[] = $has_vevent; - $vals[] = $has_vtodo; + q($sql); - foreach ($this->propertyMap as $xmlName=> $dbName) { - if (isset($properties[$xmlName])) { - $keys[] = "`$dbName`"; - $vals[] = "'" . dbesc($properties[$xmlName]) . "'"; - } - } + $x = q("SELECT id FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'", + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, $uid, $calendarUri + ); - $sql = sprintf("INSERT INTO %s%scalendars (" . implode(', ', $keys) . ") VALUES (" . implode(', ', $vals) . ")", CALDAV_SQL_DB, CALDAV_SQL_PREFIX); + return $x[0]['id']; + } - q($sql); + /** + * Updates properties for a calendar. + * + * The mutations array uses the propertyName in clark-notation as key, + * and the array value for the property value. In the case a property + * should be deleted, the property value will be null. + * + * This method must be atomic. If one property cannot be changed, the + * entire operation must fail. + * + * If the operation was successful, true can be returned. + * If the operation failed, false can be returned. + * + * Deletion of a non-existent property is always successful. + * + * Lastly, it is optional to return detailed information about any + * failures. In this case an array should be returned with the following + * structure: + * + * array( + * 403 => array( + * '{DAV:}displayname' => null, + * ), + * 424 => array( + * '{DAV:}owner' => null, + * ) + * ) + * + * In this example it was forbidden to update {DAV:}displayname. + * (403 Forbidden), which in turn also caused {DAV:}owner to fail + * (424 Failed Dependency) because the request needs to be atomic. + * + * @param string $calendarId + * @param array $mutations + * + * @return bool|array + */ + public function updateCalendar($calendarId, array $mutations) + { + $newValues = array(); + $result = array( + 200 => array(), // Ok + 403 => array(), // Forbidden + 424 => array(), // Failed Dependency + ); - $x = q("SELECT id FROM %s%scalendars WHERE `namespace` = %d AND `namespace_id` = %d AND `uri` = '%s'", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, CALDAV_NAMESPACE_PRIVATE, $uid, $calendarUri - ); - return $x[0]["id"]; + $hasError = false; - } + foreach ($mutations as $propertyName => $propertyValue) { - /** - * Updates properties for a calendar. - * - * The mutations array uses the propertyName in clark-notation as key, - * and the array value for the property value. In the case a property - * should be deleted, the property value will be null. - * - * This method must be atomic. If one property cannot be changed, the - * entire operation must fail. - * - * If the operation was successful, true can be returned. - * If the operation failed, false can be returned. - * - * Deletion of a non-existent property is always successful. - * - * Lastly, it is optional to return detailed information about any - * failures. In this case an array should be returned with the following - * structure: - * - * array( - * 403 => array( - * '{DAV:}displayname' => null, - * ), - * 424 => array( - * '{DAV:}owner' => null, - * ) - * ) - * - * In this example it was forbidden to update {DAV:}displayname. - * (403 Forbidden), which in turn also caused {DAV:}owner to fail - * (424 Failed Dependency) because the request needs to be atomic. - * - * @param string $calendarId - * @param array $mutations - * @return bool|array - */ - public function updateCalendar($calendarId, array $mutations) - { + // We don't know about this property. + if (!isset($this->propertyMap[$propertyName])) { + $hasError = true; + $result[403][$propertyName] = null; + unset($mutations[$propertyName]); + continue; + } - $newValues = array(); - $result = array( - 200 => array(), // Ok - 403 => array(), // Forbidden - 424 => array(), // Failed Dependency - ); + $fieldName = $this->propertyMap[$propertyName]; + $newValues[$fieldName] = $propertyValue; + } - $hasError = false; + // If there were any errors we need to fail the request + if ($hasError) { + // Properties has the remaining properties + foreach ($mutations as $propertyName => $propertyValue) { + $result[424][$propertyName] = null; + } - foreach ($mutations as $propertyName=> $propertyValue) { + // Removing unused statuscodes for cleanliness + foreach ($result as $status => $properties) { + if (is_array($properties) && count($properties) === 0) { + unset($result[$status]); + } + } - // We don't know about this property. - if (!isset($this->propertyMap[$propertyName])) { - $hasError = true; - $result[403][$propertyName] = null; - unset($mutations[$propertyName]); - continue; - } + return $result; + } - $fieldName = $this->propertyMap[$propertyName]; - $newValues[$fieldName] = $propertyValue; + $sql = '`ctag` = `ctag` + 1'; + foreach ($newValues as $key => $val) { + $sql .= ', `'.$key."` = '".dbesc($val)."'"; + } - } + $sql = sprintf("UPDATE %s%scalendars SET $sql WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId)); - // If there were any errors we need to fail the request - if ($hasError) { - // Properties has the remaining properties - foreach ($mutations as $propertyName=> $propertyValue) { - $result[424][$propertyName] = null; - } + q($sql); - // Removing unused statuscodes for cleanliness - foreach ($result as $status=> $properties) { - if (is_array($properties) && count($properties) === 0) unset($result[$status]); - } + return true; + } - return $result; + /** + * Delete a calendar and all it's objects. + * + * @param string $calendarId + */ + public function deleteCalendar($calendarId) + { + q('DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId)); + q('DELETE FROM %s%scalendars WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId)); + } - } + /** + * Returns all calendar objects within a calendar. + * + * Every item contains an array with the following keys: + * * id - unique identifier which will be used for subsequent updates + * * calendardata - The iCalendar-compatible calendar data + * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string. + * * lastmodified - a timestamp of the last modification time + * * etag - An arbitrary string, surrounded by double-quotes. (e.g.: + * ' "abcdef"') + * * calendarid - The calendarid as it was passed to this function. + * * size - The size of the calendar objects, in bytes. + * + * Note that the etag is optional, but it's highly encouraged to return for + * speed reasons. + * + * The calendardata is also optional. If it's not returned + * 'getCalendarObject' will be called later, which *is* expected to return + * calendardata. + * + * If neither etag or size are specified, the calendardata will be + * used/fetched to determine these numbers. If both are specified the + * amount of times this is needed is reduced by a great degree. + * + * @param mixed $calendarId + * + * @return array + */ + public function getCalendarObjects($calendarId) + { + $objs = q('SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId)); + $ret = array(); + foreach ($objs as $obj) { + $ret[] = array( + 'id' => intval($obj['id']), + 'calendardata' => $obj['calendardata'], + 'uri' => $obj['uri'], + 'lastmodified' => $obj['lastmodified'], + 'calendarid' => $calendarId, + 'etag' => $obj['etag'], + 'size' => intval($obj['size']), + ); + } - $sql = "`ctag` = `ctag` + 1"; - foreach ($newValues as $key=> $val) $sql .= ", `" . $key . "` = '" . dbesc($val) . "'"; + return $ret; + } - $sql = sprintf("UPDATE %s%scalendars SET $sql WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId)); + /** + * Returns information from a single calendar object, based on it's object + * uri. + * + * The returned array must have the same keys as getCalendarObjects. The + * 'calendardata' object is required here though, while it's not required + * for getCalendarObjects. + * + * @param string $calendarId + * @param string $objectUri + * + * @throws Sabre_DAV_Exception_NotFound + * + * @return array + */ + public function getCalendarObject($calendarId, $objectUri) + { + $o = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId), dbesc($objectUri)); + if (count($o) > 0) { + $o[0]['calendarid'] = $calendarId; + $o[0]['calendardata'] = str_ireplace('Europe/Belgrade', 'Europe/Berlin', $o[0]['calendardata']); - q($sql); + return $o[0]; + } else { + throw new Sabre_DAV_Exception_NotFound($calendarId.' / '.$objectUri); + } + } - return true; + /** + * Creates a new calendar object. + * + * It is possible return an etag from this function, which will be used in + * the response to this PUT request. Note that the ETag must be surrounded + * by double-quotes. + * + * However, you should only really return this ETag if you don't mangle the + * calendar-data. If the result of a subsequent GET to this object is not + * the exact same as this request body, you should omit the ETag. + * + * @param mixed $calendarId + * @param string $objectUri + * @param string $calendarData + * + * @return string|null + */ + public function createCalendarObject($calendarId, $objectUri, $calendarData) + { + $calendarData = icalendar_sanitize_string($calendarData); - } + $extraData = $this->getDenormalizedData($calendarData); - - /** - * Delete a calendar and all it's objects - * - * @param string $calendarId - * @return void - */ - public function deleteCalendar($calendarId) - { - q("DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId)); - q("DELETE FROM %s%scalendars WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId)); - - } - - - /** - * Returns all calendar objects within a calendar. - * - * Every item contains an array with the following keys: - * * id - unique identifier which will be used for subsequent updates - * * calendardata - The iCalendar-compatible calendar data - * * uri - a unique key which will be used to construct the uri. This can be any arbitrary string. - * * lastmodified - a timestamp of the last modification time - * * etag - An arbitrary string, surrounded by double-quotes. (e.g.: - * ' "abcdef"') - * * calendarid - The calendarid as it was passed to this function. - * * size - The size of the calendar objects, in bytes. - * - * Note that the etag is optional, but it's highly encouraged to return for - * speed reasons. - * - * The calendardata is also optional. If it's not returned - * 'getCalendarObject' will be called later, which *is* expected to return - * calendardata. - * - * If neither etag or size are specified, the calendardata will be - * used/fetched to determine these numbers. If both are specified the - * amount of times this is needed is reduced by a great degree. - * - * @param mixed $calendarId - * @return array - */ - function getCalendarObjects($calendarId) - { - $objs = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId)); - $ret = array(); - foreach ($objs as $obj) { - $ret[] = array( - "id" => IntVal($obj["id"]), - "calendardata" => $obj["calendardata"], - "uri" => $obj["uri"], - "lastmodified" => $obj["lastmodified"], - "calendarid" => $calendarId, - "etag" => $obj["etag"], - "size" => IntVal($obj["size"]), - ); - } - return $ret; - } - - /** - * Returns information from a single calendar object, based on it's object - * uri. - * - * The returned array must have the same keys as getCalendarObjects. The - * 'calendardata' object is required here though, while it's not required - * for getCalendarObjects. - * - * @param string $calendarId - * @param string $objectUri - * @throws Sabre_DAV_Exception_NotFound - * @return array - */ - function getCalendarObject($calendarId, $objectUri) - { - $o = q("SELECT * FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri)); - if (count($o) > 0) { - $o[0]["calendarid"] = $calendarId; - $o[0]["calendardata"] = str_ireplace("Europe/Belgrade", "Europe/Berlin", $o[0]["calendardata"]); - return $o[0]; - } else throw new Sabre_DAV_Exception_NotFound($calendarId . " / " . $objectUri); - } - - /** - * Creates a new calendar object. - * - * It is possible return an etag from this function, which will be used in - * the response to this PUT request. Note that the ETag must be surrounded - * by double-quotes. - * - * However, you should only really return this ETag if you don't mangle the - * calendar-data. If the result of a subsequent GET to this object is not - * the exact same as this request body, you should omit the ETag. - * - * @param mixed $calendarId - * @param string $objectUri - * @param string $calendarData - * @return string|null - */ - function createCalendarObject($calendarId, $objectUri, $calendarData) - { - $calendarData = icalendar_sanitize_string($calendarData); - - $extraData = $this->getDenormalizedData($calendarData); - - q("INSERT INTO %s%scalendarobjects (`calendar_id`, `uri`, `calendardata`, `lastmodified`, `componentType`, `firstOccurence`, `lastOccurence`, `etag`, `size`) + q("INSERT INTO %s%scalendarobjects (`calendar_id`, `uri`, `calendardata`, `lastmodified`, `componentType`, `firstOccurence`, `lastOccurence`, `etag`, `size`) VALUES (%d, '%s', '%s', NOW(), '%s', '%s', '%s', '%s', %d)", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri), addslashes($calendarData), dbesc($extraData['componentType']), - dbesc(wdcal_php2MySqlTime($extraData['firstOccurence'])), dbesc(wdcal_php2MySqlTime($extraData['lastOccurence'])), dbesc($extraData["etag"]), IntVal($extraData["size"]) - ); + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId), dbesc($objectUri), addslashes($calendarData), dbesc($extraData['componentType']), + dbesc(wdcal_php2MySqlTime($extraData['firstOccurence'])), dbesc(wdcal_php2MySqlTime($extraData['lastOccurence'])), dbesc($extraData['etag']), intval($extraData['size']) + ); - $this->increaseCalendarCtag($calendarId); - renderCalDavEntry_uri($objectUri); + $this->increaseCalendarCtag($calendarId); + renderCalDavEntry_uri($objectUri); - return '"' . $extraData['etag'] . '"'; - } + return '"'.$extraData['etag'].'"'; + } - /** - * Updates an existing calendarobject, based on it's uri. - * - * It is possible return an etag from this function, which will be used in - * the response to this PUT request. Note that the ETag must be surrounded - * by double-quotes. - * - * However, you should only really return this ETag if you don't mangle the - * calendar-data. If the result of a subsequent GET to this object is not - * the exact same as this request body, you should omit the ETag. - * - * @param mixed $calendarId - * @param string $objectUri - * @param string $calendarData - * @return string|null - */ - function updateCalendarObject($calendarId, $objectUri, $calendarData) - { - $calendarData = icalendar_sanitize_string($calendarData); + /** + * Updates an existing calendarobject, based on it's uri. + * + * It is possible return an etag from this function, which will be used in + * the response to this PUT request. Note that the ETag must be surrounded + * by double-quotes. + * + * However, you should only really return this ETag if you don't mangle the + * calendar-data. If the result of a subsequent GET to this object is not + * the exact same as this request body, you should omit the ETag. + * + * @param mixed $calendarId + * @param string $objectUri + * @param string $calendarData + * + * @return string|null + */ + public function updateCalendarObject($calendarId, $objectUri, $calendarData) + { + $calendarData = icalendar_sanitize_string($calendarData); - $extraData = $this->getDenormalizedData($calendarData); + $extraData = $this->getDenormalizedData($calendarData); - q("UPDATE %s%scalendarobjects SET `calendardata` = '%s', `lastmodified` = NOW(), `etag` = '%s', `size` = %d, `componentType` = '%s', `firstOccurence` = '%s', `lastOccurence` = '%s' + q("UPDATE %s%scalendarobjects SET `calendardata` = '%s', `lastmodified` = NOW(), `etag` = '%s', `size` = %d, `componentType` = '%s', `firstOccurence` = '%s', `lastOccurence` = '%s' WHERE `calendar_id` = %d AND `uri` = '%s'", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($calendarData), dbesc($extraData["etag"]), IntVal($extraData["size"]), dbesc($extraData["componentType"]), - dbesc(wdcal_php2MySqlTime($extraData["firstOccurence"])), dbesc(wdcal_php2MySqlTime($extraData["lastOccurence"])), IntVal($calendarId), dbesc($objectUri)); + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($calendarData), dbesc($extraData['etag']), intval($extraData['size']), dbesc($extraData['componentType']), + dbesc(wdcal_php2MySqlTime($extraData['firstOccurence'])), dbesc(wdcal_php2MySqlTime($extraData['lastOccurence'])), intval($calendarId), dbesc($objectUri)); - $this->increaseCalendarCtag($calendarId); - renderCalDavEntry_uri($objectUri); + $this->increaseCalendarCtag($calendarId); + renderCalDavEntry_uri($objectUri); - return '"' . $extraData['etag'] . '"'; - } + return '"'.$extraData['etag'].'"'; + } - /** - * Deletes an existing calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @throws Sabre_DAV_Exception_NotFound - * @return void - */ - function deleteCalendarObject($calendarId, $objectUri) - { - $r = q("SELECT `id` FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri)); - if (count($r) == 0) throw new Sabre_DAV_Exception_NotFound(); + /** + * Deletes an existing calendar object. + * + * @param string $calendarId + * @param string $objectUri + * + * @throws Sabre_DAV_Exception_NotFound + */ + public function deleteCalendarObject($calendarId, $objectUri) + { + $r = q("SELECT `id` FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId), dbesc($objectUri)); + if (count($r) == 0) { + throw new Sabre_DAV_Exception_NotFound(); + } - q("DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId), dbesc($objectUri)); + q("DELETE FROM %s%scalendarobjects WHERE `calendar_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId), dbesc($objectUri)); - $this->increaseCalendarCtag($calendarId); - renderCalDavEntry_calobj_id($r[0]["id"]); - } + $this->increaseCalendarCtag($calendarId); + renderCalDavEntry_calobj_id($r[0]['id']); + } } diff --git a/dav/common/dav_caldav_backend_virtual.inc.php b/dav/common/dav_caldav_backend_virtual.inc.php index e2759cf6..c6c0aa8d 100644 --- a/dav/common/dav_caldav_backend_virtual.inc.php +++ b/dav/common/dav_caldav_backend_virtual.inc.php @@ -2,185 +2,198 @@ abstract class Sabre_CalDAV_Backend_Virtual extends Sabre_CalDAV_Backend_Common { - - - - /** - * @static - * @abstract - * @param int $calendarId - * @param string $uri - * @return array - */ - /* - abstract public function getItemsByUri($calendarId, $uri); + /** + * @static + * @abstract + * + * @param int $calendarId + * @param string $uri + * + * @return array + */ + /* + abstract public function getItemsByUri($calendarId, $uri); */ - /** - * @static - * @param int $uid - * @param int $namespace - */ - static public function invalidateCache($uid = 0, $namespace = 0) { - q("DELETE FROM %s%scal_virtual_object_sync WHERE `uid` = %d AND `namespace` = %d", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($uid), IntVal($namespace)); - } + /** + * @static + * + * @param int $uid + * @param int $namespace + */ + public static function invalidateCache($uid = 0, $namespace = 0) + { + q('DELETE FROM %s%scal_virtual_object_sync WHERE `uid` = %d AND `namespace` = %d', + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($uid), intval($namespace)); + } - /** - * @static - * @abstract - * @param int $calendarId - */ - static abstract protected function createCache_internal($calendarId); + /** + * @static + * @abstract + * + * @param int $calendarId + */ + abstract protected static function createCache_internal($calendarId); - /** - * @static - * @param int $calendarId - */ - static protected function createCache($calendarId) { - $calendarId = IntVal($calendarId); - q("DELETE FROM %s%scal_virtual_object_cache WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendarId); - static::createCache_internal($calendarId); - q("REPLACE INTO %s%scal_virtual_object_sync (`calendar_id`, `date`) VALUES (%d, NOW())", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendarId); - } + /** + * @static + * + * @param int $calendarId + */ + protected static function createCache($calendarId) + { + $calendarId = intval($calendarId); + q('DELETE FROM %s%scal_virtual_object_cache WHERE `calendar_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendarId); + static::createCache_internal($calendarId); + q('REPLACE INTO %s%scal_virtual_object_sync (`calendar_id`, `date`) VALUES (%d, NOW())', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendarId); + } - /** - * @param string $calendarId - * @return array - */ - public function getCalendarObjects($calendarId) - { - $calendarId = IntVal($calendarId); - $r = q("SELECT COUNT(*) n FROM %s%scal_virtual_object_sync WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendarId); + /** + * @param string $calendarId + * + * @return array + */ + public function getCalendarObjects($calendarId) + { + $calendarId = intval($calendarId); + $r = q('SELECT COUNT(*) n FROM %s%scal_virtual_object_sync WHERE `calendar_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendarId); - if ($r[0]["n"] == 0) static::createCache($calendarId); + if ($r[0]['n'] == 0) { + static::createCache($calendarId); + } - $r = q("SELECT * FROM %s%scal_virtual_object_cache WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendarId); + $r = q('SELECT * FROM %s%scal_virtual_object_cache WHERE `calendar_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $calendarId); - $ret = array(); - foreach ($r as $obj) { - $ret[] = array( - "id" => IntVal($obj["data_uri"]), - "calendardata" => $obj["calendardata"], - "uri" => $obj["data_uri"], - "lastmodified" => $obj["date"], - "calendarid" => $calendarId, - "etag" => $obj["etag"], - "size" => IntVal($obj["size"]), - ); - } + $ret = array(); + foreach ($r as $obj) { + $ret[] = array( + 'id' => intval($obj['data_uri']), + 'calendardata' => $obj['calendardata'], + 'uri' => $obj['data_uri'], + 'lastmodified' => $obj['date'], + 'calendarid' => $calendarId, + 'etag' => $obj['etag'], + 'size' => intval($obj['size']), + ); + } - return $ret; - } + return $ret; + } - /** - * Returns information from a single calendar object, based on it's object - * uri. - * - * The returned array must have the same keys as getCalendarObjects. The - * 'calendardata' object is required here though, while it's not required - * for getCalendarObjects. - * - * @param string $calendarId - * @param string $objectUri - * @throws Sabre_DAV_Exception_NotFound - * @return array - */ - public function getCalendarObject($calendarId, $objectUri) - { - $calendarId = IntVal($calendarId); - $r = q("SELECT COUNT(*) n FROM %s%scal_virtual_object_sync WHERE `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($calendarId)); + /** + * Returns information from a single calendar object, based on it's object + * uri. + * + * The returned array must have the same keys as getCalendarObjects. The + * 'calendardata' object is required here though, while it's not required + * for getCalendarObjects. + * + * @param string $calendarId + * @param string $objectUri + * + * @throws Sabre_DAV_Exception_NotFound + * + * @return array + */ + public function getCalendarObject($calendarId, $objectUri) + { + $calendarId = intval($calendarId); + $r = q('SELECT COUNT(*) n FROM %s%scal_virtual_object_sync WHERE `calendar_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($calendarId)); - if ($r[0]["n"] == 0) static::createCache($calendarId); + if ($r[0]['n'] == 0) { + static::createCache($calendarId); + } - $r = q("SELECT * FROM %s%scal_virtual_object_cache WHERE `data_uri` = '%s' AND `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($objectUri), IntVal($calendarId)); - if (count($r) == 0) throw new Sabre_DAV_Exception_NotFound(); + $r = q("SELECT * FROM %s%scal_virtual_object_cache WHERE `data_uri` = '%s' AND `calendar_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($objectUri), intval($calendarId)); + if (count($r) == 0) { + throw new Sabre_DAV_Exception_NotFound(); + } - $obj = $r[0]; - $ret = array( - "id" => IntVal($obj["data_uri"]), - "calendardata" => $obj["calendardata"], - "uri" => $obj["data_uri"], - "lastmodified" => $obj["date"], - "calendarid" => $calendarId, - "etag" => $obj["etag"], - "size" => IntVal($obj["size"]), - ); - return $ret; - } + $obj = $r[0]; + $ret = array( + 'id' => intval($obj['data_uri']), + 'calendardata' => $obj['calendardata'], + 'uri' => $obj['data_uri'], + 'lastmodified' => $obj['date'], + 'calendarid' => $calendarId, + 'etag' => $obj['etag'], + 'size' => intval($obj['size']), + ); + return $ret; + } + /** + * Creates a new calendar for a principal. + * + * If the creation was a success, an id must be returned that can be used to reference + * this calendar in other methods, such as updateCalendar. + * + * @param string $principalUri + * @param string $calendarUri + * @param array $properties + * + * @throws Sabre_DAV_Exception_Forbidden + */ + public function createCalendar($principalUri, $calendarUri, array $properties) + { + throw new Sabre_DAV_Exception_Forbidden(); + } - /** - * Creates a new calendar for a principal. - * - * If the creation was a success, an id must be returned that can be used to reference - * this calendar in other methods, such as updateCalendar. - * - * @param string $principalUri - * @param string $calendarUri - * @param array $properties - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function createCalendar($principalUri, $calendarUri, array $properties) - { - throw new Sabre_DAV_Exception_Forbidden(); - } + /** + * Delete a calendar and all it's objects. + * + * @param string $calendarId + * + * @throws Sabre_DAV_Exception_Forbidden + */ + public function deleteCalendar($calendarId) + { + throw new Sabre_DAV_Exception_Forbidden(); + } - /** - * Delete a calendar and all it's objects - * - * @param string $calendarId - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function deleteCalendar($calendarId) - { - throw new Sabre_DAV_Exception_Forbidden(); - } - - - /** - * Creates a new calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @throws Sabre_DAV_Exception_Forbidden - * @return null|string|void - */ - function createCalendarObject($calendarId, $objectUri, $calendarData) - { - throw new Sabre_DAV_Exception_Forbidden(); - } - - /** - * Updates an existing calendarobject, based on it's uri. - * - * @param string $calendarId - * @param string $objectUri - * @param string $calendarData - * @throws Sabre_DAV_Exception_Forbidden - * @return null|string|void - */ - function updateCalendarObject($calendarId, $objectUri, $calendarData) - { - throw new Sabre_DAV_Exception_Forbidden(); - } - - /** - * Deletes an existing calendar object. - * - * @param string $calendarId - * @param string $objectUri - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - function deleteCalendarObject($calendarId, $objectUri) - { - throw new Sabre_DAV_Exception_Forbidden(); - } + /** + * Creates a new calendar object. + * + * @param string $calendarId + * @param string $objectUri + * @param string $calendarData + * + * @throws Sabre_DAV_Exception_Forbidden + * + * @return null|string|void + */ + public function createCalendarObject($calendarId, $objectUri, $calendarData) + { + throw new Sabre_DAV_Exception_Forbidden(); + } + /** + * Updates an existing calendarobject, based on it's uri. + * + * @param string $calendarId + * @param string $objectUri + * @param string $calendarData + * + * @throws Sabre_DAV_Exception_Forbidden + * + * @return null|string|void + */ + public function updateCalendarObject($calendarId, $objectUri, $calendarData) + { + throw new Sabre_DAV_Exception_Forbidden(); + } + /** + * Deletes an existing calendar object. + * + * @param string $calendarId + * @param string $objectUri + * + * @throws Sabre_DAV_Exception_Forbidden + */ + public function deleteCalendarObject($calendarId, $objectUri) + { + throw new Sabre_DAV_Exception_Forbidden(); + } } diff --git a/dav/common/dav_caldav_calendar_private.inc.php b/dav/common/dav_caldav_calendar_private.inc.php index 65f7c2b0..0eded890 100644 --- a/dav/common/dav_caldav_calendar_private.inc.php +++ b/dav/common/dav_caldav_calendar_private.inc.php @@ -3,48 +3,42 @@ class Sabre_CalDAV_Calendar_Private extends Sabre_CalDAV_Calendar { + public function getACL() + { + return array( + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'], + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->calendarInfo['principaluri'], + 'protected' => true, + ), + /* + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', + 'protected' => true, + ), + array( + 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy', + 'principal' => '{DAV:}authenticated', + 'protected' => true, + ), + */ - public function getACL() - { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - /* - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', - 'protected' => true, - ), - array( - 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy', - 'principal' => '{DAV:}authenticated', - 'protected' => true, - ), - */ - - ); - - } - - - -} \ No newline at end of file + ); + } +} diff --git a/dav/common/dav_caldav_calendar_virtual.inc.php b/dav/common/dav_caldav_calendar_virtual.inc.php index ee140712..6f0bdc6b 100644 --- a/dav/common/dav_caldav_calendar_virtual.inc.php +++ b/dav/common/dav_caldav_calendar_virtual.inc.php @@ -1,44 +1,43 @@ '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'], + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'].'/calendar-proxy-write', + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->calendarInfo['principaluri'].'/calendar-proxy-read', + 'protected' => true, + ), + array( + 'privilege' => '{'.Sabre_CalDAV_Plugin::NS_CALDAV.'}read-free-busy', + 'principal' => '{DAV:}authenticated', + 'protected' => true, + ), - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'], - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-write', - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->calendarInfo['principaluri'] . '/calendar-proxy-read', - 'protected' => true, - ), - array( - 'privilege' => '{' . Sabre_CalDAV_Plugin::NS_CALDAV . '}read-free-busy', - 'principal' => '{DAV:}authenticated', - 'protected' => true, - ), - - ); - - } + ); + } } diff --git a/dav/common/dav_caldav_root.inc.php b/dav/common/dav_caldav_root.inc.php index fe87900d..e7281884 100644 --- a/dav/common/dav_caldav_root.inc.php +++ b/dav/common/dav_caldav_root.inc.php @@ -1,69 +1,64 @@ caldavBackends = $caldavBackends; - } /** - * Returns the nodename + * Returns the nodename. * * We're overriding this, because the default will be the 'principalPrefix', - * and we want it to be Sabre_CalDAV_Plugin::CALENDAR_ROOT + * and we want it to be Sabre_CalDAV_Plugin::CALENDAR_ROOT * - * @return string + * @return string */ - public function getName() { - + public function getName() + { return Sabre_CalDAV_Plugin::CALENDAR_ROOT; - } - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principal - * @return \Sabre_CalDAV_AnimexxUserCalendars|\Sabre_DAVACL_IPrincipal - */ - public function getChildForPrincipal(array $principal) { - + /** + * This method returns a node for a principal. + * + * The passed array contains principal information, and is guaranteed to + * at least contain a uri item. Other properties may or may not be + * supplied by the authentication backend. + * + * @param array $principal + * + * @return \Sabre_CalDAV_AnimexxUserCalendars|\Sabre_DAVACL_IPrincipal + */ + public function getChildForPrincipal(array $principal) + { return new Sabre_CalDAV_AnimexxUserCalendars($this->principalBackend, $this->caldavBackends, $principal['uri']); - } - } diff --git a/dav/common/dav_carddav_backend_common.inc.php b/dav/common/dav_carddav_backend_common.inc.php index 4279f8a1..97a95db7 100644 --- a/dav/common/dav_carddav_backend_common.inc.php +++ b/dav/common/dav_carddav_backend_common.inc.php @@ -2,115 +2,122 @@ abstract class Sabre_CardDAV_Backend_Common extends Sabre_CardDAV_Backend_Abstract { - /** - * @abstract - * @return int - */ - abstract public function getNamespace(); + /** + * @abstract + * + * @return int + */ + abstract public function getNamespace(); - /** - * @static - * @abstract - * @return string - */ - abstract public static function getBackendTypeName(); + /** + * @static + * @abstract + * + * @return string + */ + abstract public static function getBackendTypeName(); - /** - * @var array - */ - static private $addressbookCache = array(); + /** + * @var array + */ + private static $addressbookCache = array(); - /** - * @var array - */ - static private $addressbookObjectCache = array(); + /** + * @var array + */ + private static $addressbookObjectCache = array(); - /** - * @static - * @param int $addressbookId - * @return array - */ - static public function loadCalendarById($addressbookId) - { - if (!isset(self::$addressbookCache[$addressbookId])) { - $c = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId)); - self::$addressbookCache[$addressbookId] = $c[0]; - } - return self::$addressbookCache[$addressbookId]; - } + /** + * @static + * + * @param int $addressbookId + * + * @return array + */ + public static function loadCalendarById($addressbookId) + { + if (!isset(self::$addressbookCache[$addressbookId])) { + $c = q('SELECT * FROM %s%saddressbooks WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressbookId)); + self::$addressbookCache[$addressbookId] = $c[0]; + } - /** - * @static - * @param int $obj_id - * @return array - */ - static public function loadAddressbookobjectById($obj_id) - { - if (!isset(self::$addressbookObjectCache[$obj_id])) { - $o = q("SELECT * FROM %s%saddressbookobjects WHERE `id` = %d", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($obj_id) - ); - self::$addressbookObjectCache[$obj_id] = $o[0]; - } - return self::$addressbookObjectCache[$obj_id]; - } + return self::$addressbookCache[$addressbookId]; + } + /** + * @static + * + * @param int $obj_id + * + * @return array + */ + public static function loadAddressbookobjectById($obj_id) + { + if (!isset(self::$addressbookObjectCache[$obj_id])) { + $o = q('SELECT * FROM %s%saddressbookobjects WHERE `id` = %d', + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($obj_id) + ); + self::$addressbookObjectCache[$obj_id] = $o[0]; + } - /** - * Updates an addressbook's properties - * - * See Sabre_DAV_IProperties for a description of the mutations array, as - * well as the return value. - * - * @param mixed $addressBookId - * @param array $mutations - * @throws Sabre_DAV_Exception_Forbidden - * @see Sabre_DAV_IProperties::updateProperties - * @return bool|array - */ - public function updateAddressBook($addressBookId, array $mutations) - { - $updates = array(); + return self::$addressbookObjectCache[$obj_id]; + } - foreach ($mutations as $property=> $newValue) { + /** + * Updates an addressbook's properties. + * + * See Sabre_DAV_IProperties for a description of the mutations array, as + * well as the return value. + * + * @param mixed $addressBookId + * @param array $mutations + * + * @throws Sabre_DAV_Exception_Forbidden + * + * @see Sabre_DAV_IProperties::updateProperties + * + * @return bool|array + */ + public function updateAddressBook($addressBookId, array $mutations) + { + $updates = array(); - switch ($property) { - case '{DAV:}displayname' : - $updates['displayname'] = $newValue; - break; - case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : - $updates['description'] = $newValue; - break; - default : - // If any unsupported values were being updated, we must - // let the entire request fail. - return false; - } + foreach ($mutations as $property => $newValue) { + switch ($property) { + case '{DAV:}displayname': + $updates['displayname'] = $newValue; + break; + case '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description': + $updates['description'] = $newValue; + break; + default: + // If any unsupported values were being updated, we must + // let the entire request fail. + return false; + } + } - } + // No values are being updated? + if (!$updates) { + return false; + } - // No values are being updated? - if (!$updates) { - return false; - } + $query = 'UPDATE '.CALDAV_SQL_DB.CALDAV_SQL_PREFIX.'addressbooks SET ctag = ctag + 1 '; + foreach ($updates as $key => $value) { + $query .= ', `'.dbesc($key).'` = '.dbesc($key).' '; + } + $query .= ' WHERE id = '.intval($addressBookId); + q($query); - $query = 'UPDATE ' . CALDAV_SQL_DB . CALDAV_SQL_PREFIX . 'addressbooks SET ctag = ctag + 1 '; - foreach ($updates as $key=> $value) { - $query .= ', `' . dbesc($key) . '` = ' . dbesc($key) . ' '; - } - $query .= ' WHERE id = ' . IntVal($addressBookId); - q($query); + return true; + } - return true; - - } - - /** - * @param int $addressbookId - */ - protected function increaseAddressbookCtag($addressbookId) - { - q("UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = '%d'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId)); - self::$addressbookCache = array(); - } -} \ No newline at end of file + /** + * @param int $addressbookId + */ + protected function increaseAddressbookCtag($addressbookId) + { + q("UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = '%d'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressbookId)); + self::$addressbookCache = array(); + } +} diff --git a/dav/common/dav_carddav_backend_private.inc.php b/dav/common/dav_carddav_backend_private.inc.php index 71923b99..0ab97797 100644 --- a/dav/common/dav_carddav_backend_private.inc.php +++ b/dav/common/dav_carddav_backend_private.inc.php @@ -2,274 +2,288 @@ class Sabre_CardDAV_Backend_Std extends Sabre_CardDAV_Backend_Common { + /** + * @var null|Sabre_CardDAV_Backend_Std + */ + private static $instance = null; - /** - * @var null|Sabre_CardDAV_Backend_Std - */ - private static $instance = null; + /** + * @static + * + * @return Sabre_CardDAV_Backend_Std + */ + public static function getInstance() + { + if (self::$instance == null) { + self::$instance = new self(); + } - /** - * @static - * @return Sabre_CardDAV_Backend_Std - */ - public static function getInstance() { - if (self::$instance == null) { - self::$instance = new Sabre_CardDAV_Backend_Std(); - } - return self::$instance; - } + return self::$instance; + } + /** + * Sets up the object. + */ + public function __construct() + { + } - /** - * Sets up the object - */ - public function __construct() - { + /** + * @return int + */ + public function getNamespace() + { + return CARDDAV_NAMESPACE_PRIVATE; + } - } + /** + * @static + * + * @return string + */ + public static function getBackendTypeName() + { + return t('Private Addressbooks'); + } + /** + * Returns the list of addressbooks for a specific user. + * + * @param string $principalUri + * + * @return array + */ + public function getAddressBooksForUser($principalUri) + { + $n = dav_compat_principal2namespace($principalUri); + if ($n['namespace'] != $this->getNamespace()) { + return array(); + } - /** - * @return int - */ - public function getNamespace() - { - return CARDDAV_NAMESPACE_PRIVATE; - } + $addressBooks = array(); - /** - * @static - * @return string - */ - public static function getBackendTypeName() - { - return t("Private Addressbooks"); - } + $books = q('SELECT * FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($n['namespace']), intval($n['namespace_id'])); + foreach ($books as $row) { + if (in_array($row['uri'], $GLOBALS['CARDDAV_PRIVATE_SYSTEM_ADDRESSBOOKS'])) { + continue; + } - /** - * Returns the list of addressbooks for a specific user. - * - * @param string $principalUri - * @return array - */ - public function getAddressBooksForUser($principalUri) - { - $n = dav_compat_principal2namespace($principalUri); - if ($n["namespace"] != $this->getNamespace()) return array(); + $addressBooks[] = array( + 'id' => $row['id'], + 'uri' => $row['uri'], + 'principaluri' => $principalUri, + '{DAV:}displayname' => $row['displayname'], + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description' => $row['description'], + '{http://calendarserver.org/ns/}getctag' => $row['ctag'], + '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}supported-address-data' => new Sabre_CardDAV_Property_SupportedAddressData(), + ); + } - $addressBooks = array(); + return $addressBooks; + } - $books = q("SELECT * FROM %s%saddressbooks WHERE `namespace` = %d AND `namespace_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($n["namespace"]), IntVal($n["namespace_id"])); - foreach ($books as $row) { - if (in_array($row["uri"], $GLOBALS["CARDDAV_PRIVATE_SYSTEM_ADDRESSBOOKS"])) continue; + /** + * Creates a new address book. + * + * @param string $principalUri + * @param string $url Just the 'basename' of the url + * @param array $properties + * + * @throws Sabre_DAV_Exception_BadRequest + */ + public function createAddressBook($principalUri, $url, array $properties) + { + $uid = dav_compat_principal2uid($principalUri); - $addressBooks[] = array( - 'id' => $row['id'], - 'uri' => $row['uri'], - 'principaluri' => $principalUri, - '{DAV:}displayname' => $row['displayname'], - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'], - '{http://calendarserver.org/ns/}getctag' => $row['ctag'], - '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}supported-address-data' => - new Sabre_CardDAV_Property_SupportedAddressData(), - ); - } + $values = array( + 'displayname' => null, + 'description' => null, + 'principaluri' => $principalUri, + 'uri' => $url, + ); - return $addressBooks; + foreach ($properties as $property => $newValue) { + switch ($property) { + case '{DAV:}displayname': + $values['displayname'] = $newValue; + break; + case '{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook-description': + $values['description'] = $newValue; + break; + default: + throw new Sabre_DAV_Exception_BadRequest('Unknown property: '.$property); + } + } - } + q("INSERT INTO %s%saddressbooks (`uri`, `displayname`, `description`, `namespace`, `namespace_id`, `ctag`) VALUES ('%s', '%s', '%s', %d, %d, 1)", + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($values['uri']), dbesc($values['displayname']), dbesc($values['description']), CARDDAV_NAMESPACE_PRIVATE, intval($uid) + ); + } + /** + * Deletes an entire addressbook and all its contents. + * + * @param int $addressBookId + * + * @throws Sabre_DAV_Exception_Forbidden + */ + public function deleteAddressBook($addressBookId) + { + q('DELETE FROM %s%saddressbookobjects WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressBookId)); + q('DELETE FROM %s%saddressbooks WHERE `addressbook_id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressBookId)); + } - /** - * Creates a new address book - * - * @param string $principalUri - * @param string $url Just the 'basename' of the url. - * @param array $properties - * @throws Sabre_DAV_Exception_BadRequest - * @return void - */ - public function createAddressBook($principalUri, $url, array $properties) - { - $uid = dav_compat_principal2uid($principalUri); + /** + * Returns all cards for a specific addressbook id. + * + * This method should return the following properties for each card: + * * carddata - raw vcard data + * * uri - Some unique url + * * lastmodified - A unix timestamp + * + * It's recommended to also return the following properties: + * * etag - A unique etag. This must change every time the card changes. + * * size - The size of the card in bytes. + * + * If these last two properties are provided, less time will be spent + * calculating them. If they are specified, you can also ommit carddata. + * This may speed up certain requests, especially with large cards. + * + * @param string $addressbookId + * + * @return array + */ + public function getCards($addressbookId) + { + $r = q('SELECT `id`, `carddata`, `uri`, `lastmodified`, `etag`, `size`, `contact` FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `manually_deleted` = 0', + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressbookId) + ); + if ($r) { + return $r; + } - $values = array( - 'displayname' => null, - 'description' => null, - 'principaluri' => $principalUri, - 'uri' => $url, - ); + return array(); + } - foreach ($properties as $property=> $newValue) { + /** + * Returns a specfic card. + * + * The same set of properties must be returned as with getCards. The only + * exception is that 'carddata' is absolutely required. + * + * @param mixed $addressBookId + * @param string $cardUri + * + * @throws Sabre_DAV_Exception_NotFound + * + * @return array + */ + public function getCard($addressBookId, $cardUri) + { + $x = q("SELECT `id`, `carddata`, `uri`, `lastmodified`, `etag`, `size` FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `uri` = '%s'", + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressBookId), dbesc($cardUri)); + if (count($x) == 0) { + throw new Sabre_DAV_Exception_NotFound(); + } - switch ($property) { - case '{DAV:}displayname' : - $values['displayname'] = $newValue; - break; - case '{' . Sabre_CardDAV_Plugin::NS_CARDDAV . '}addressbook-description' : - $values['description'] = $newValue; - break; - default : - throw new Sabre_DAV_Exception_BadRequest('Unknown property: ' . $property); - } + return $x[0]; + } - } + /** + * Creates a new card. + * + * The addressbook id will be passed as the first argument. This is the + * same id as it is returned from the getAddressbooksForUser method. + * + * The cardUri is a base uri, and doesn't include the full path. The + * cardData argument is the vcard body, and is passed as a string. + * + * It is possible to return an ETag from this method. This ETag is for the + * newly created resource, and must be enclosed with double quotes (that + * is, the string itself must contain the double quotes). + * + * You should only return the ETag if you store the carddata as-is. If a + * subsequent GET request on the same card does not have the same body, + * byte-by-byte and you did return an ETag here, clients tend to get + * confused. + * + * If you don't return an ETag, you can just return null. + * + * @param string $addressBookId + * @param string $cardUri + * @param string $cardData + * + * @throws Sabre_DAV_Exception_Forbidden + * + * @return string + */ + public function createCard($addressBookId, $cardUri, $cardData) + { + $etag = md5($cardData); + q("INSERT INTO %s%saddressbookobjects (`carddata`, `uri`, `lastmodified`, `addressbook_id`, `etag`, `size`) VALUES ('%s', '%s', NOW(), %d, '%s', %d)", + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), dbesc($cardUri), intval($addressBookId), dbesc($etag), strlen($cardData) + ); - q("INSERT INTO %s%saddressbooks (`uri`, `displayname`, `description`, `namespace`, `namespace_id`, `ctag`) VALUES ('%s', '%s', '%s', %d, %d, 1)", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($values["uri"]), dbesc($values["displayname"]), dbesc($values["description"]), CARDDAV_NAMESPACE_PRIVATE, IntVal($uid) - ); - } + q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressBookId)); - /** - * Deletes an entire addressbook and all its contents - * - * @param int $addressBookId - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function deleteAddressBook($addressBookId) - { - q("DELETE FROM %s%saddressbookobjects WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId)); - q("DELETE FROM %s%saddressbooks WHERE `addressbook_id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId)); - } + return '"'.$etag.'"'; + } - /** - * Returns all cards for a specific addressbook id. - * - * This method should return the following properties for each card: - * * carddata - raw vcard data - * * uri - Some unique url - * * lastmodified - A unix timestamp - * - * It's recommended to also return the following properties: - * * etag - A unique etag. This must change every time the card changes. - * * size - The size of the card in bytes. - * - * If these last two properties are provided, less time will be spent - * calculating them. If they are specified, you can also ommit carddata. - * This may speed up certain requests, especially with large cards. - * - * @param string $addressbookId - * @return array - */ - public function getCards($addressbookId) - { - $r = q('SELECT `id`, `carddata`, `uri`, `lastmodified`, `etag`, `size`, `contact` FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `manually_deleted` = 0', - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId) - ); - if ($r) return $r; - return array(); - } + /** + * Updates a card. + * + * The addressbook id will be passed as the first argument. This is the + * same id as it is returned from the getAddressbooksForUser method. + * + * The cardUri is a base uri, and doesn't include the full path. The + * cardData argument is the vcard body, and is passed as a string. + * + * It is possible to return an ETag from this method. This ETag should + * match that of the updated resource, and must be enclosed with double + * quotes (that is: the string itself must contain the actual quotes). + * + * You should only return the ETag if you store the carddata as-is. If a + * subsequent GET request on the same card does not have the same body, + * byte-by-byte and you did return an ETag here, clients tend to get + * confused. + * + * If you don't return an ETag, you can just return null. + * + * @param string $addressBookId + * @param string $cardUri + * @param string $cardData + * + * @throws Sabre_DAV_Exception_Forbidden + * + * @return string|null + */ + public function updateCard($addressBookId, $cardUri, $cardData) + { + $etag = md5($cardData); + q("UPDATE %s%saddressbookobjects SET `carddata` = '%s', `lastmodified` = NOW(), `etag` = '%s', `size` = %d, `manually_edited` = 1 WHERE `uri` = '%s' AND `addressbook_id` = %d", + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), dbesc($etag), strlen($cardData), dbesc($cardUri), intval($addressBookId) + ); - /** - * Returns a specfic card. - * - * The same set of properties must be returned as with getCards. The only - * exception is that 'carddata' is absolutely required. - * - * @param mixed $addressBookId - * @param string $cardUri - * @throws Sabre_DAV_Exception_NotFound - * @return array - */ - public function getCard($addressBookId, $cardUri) - { - $x = q("SELECT `id`, `carddata`, `uri`, `lastmodified`, `etag`, `size` FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `uri` = '%s'", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId), dbesc($cardUri)); - if (count($x) == 0) throw new Sabre_DAV_Exception_NotFound(); - return $x[0]; - } + q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressBookId)); - /** - * Creates a new card. - * - * The addressbook id will be passed as the first argument. This is the - * same id as it is returned from the getAddressbooksForUser method. - * - * The cardUri is a base uri, and doesn't include the full path. The - * cardData argument is the vcard body, and is passed as a string. - * - * It is possible to return an ETag from this method. This ETag is for the - * newly created resource, and must be enclosed with double quotes (that - * is, the string itself must contain the double quotes). - * - * You should only return the ETag if you store the carddata as-is. If a - * subsequent GET request on the same card does not have the same body, - * byte-by-byte and you did return an ETag here, clients tend to get - * confused. - * - * If you don't return an ETag, you can just return null. - * - * @param string $addressBookId - * @param string $cardUri - * @param string $cardData - * @throws Sabre_DAV_Exception_Forbidden - * @return string - */ - public function createCard($addressBookId, $cardUri, $cardData) - { - $etag = md5($cardData); - q("INSERT INTO %s%saddressbookobjects (`carddata`, `uri`, `lastmodified`, `addressbook_id`, `etag`, `size`) VALUES ('%s', '%s', NOW(), %d, '%s', %d)", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), dbesc($cardUri), IntVal($addressBookId), dbesc($etag), strlen($cardData) - ); + return '"'.$etag.'"'; + } - q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId)); + /** + * Deletes a card. + * + * @param string $addressBookId + * @param string $cardUri + * + * @throws Sabre_DAV_Exception_Forbidden + * + * @return bool + */ + public function deleteCard($addressBookId, $cardUri) + { + q("DELETE FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressBookId), dbesc($cardUri)); + q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressBookId)); - return '"' . $etag . '"'; - - } - - /** - * Updates a card. - * - * The addressbook id will be passed as the first argument. This is the - * same id as it is returned from the getAddressbooksForUser method. - * - * The cardUri is a base uri, and doesn't include the full path. The - * cardData argument is the vcard body, and is passed as a string. - * - * It is possible to return an ETag from this method. This ETag should - * match that of the updated resource, and must be enclosed with double - * quotes (that is: the string itself must contain the actual quotes). - * - * You should only return the ETag if you store the carddata as-is. If a - * subsequent GET request on the same card does not have the same body, - * byte-by-byte and you did return an ETag here, clients tend to get - * confused. - * - * If you don't return an ETag, you can just return null. - * - * @param string $addressBookId - * @param string $cardUri - * @param string $cardData - * @throws Sabre_DAV_Exception_Forbidden - * @return string|null - */ - public function updateCard($addressBookId, $cardUri, $cardData) - { - $etag = md5($cardData); - q("UPDATE %s%saddressbookobjects SET `carddata` = '%s', `lastmodified` = NOW(), `etag` = '%s', `size` = %d, `manually_edited` = 1 WHERE `uri` = '%s' AND `addressbook_id` = %d", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), dbesc($etag), strlen($cardData), dbesc($cardUri), IntVal($addressBookId) - ); - - q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId)); - - return '"' . $etag . '"'; - } - - /** - * Deletes a card - * - * @param string $addressBookId - * @param string $cardUri - * @throws Sabre_DAV_Exception_Forbidden - * @return bool - */ - public function deleteCard($addressBookId, $cardUri) - { - q("DELETE FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId), dbesc($cardUri)); - q('UPDATE %s%saddressbooks SET `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId)); - - return true; - } + return true; + } } diff --git a/dav/common/dav_carddav_backend_virtual.inc.php b/dav/common/dav_carddav_backend_virtual.inc.php index f81a0a48..9daa00d2 100644 --- a/dav/common/dav_carddav_backend_virtual.inc.php +++ b/dav/common/dav_carddav_backend_virtual.inc.php @@ -2,268 +2,288 @@ abstract class Sabre_CardDAV_Backend_Virtual extends Sabre_CardDAV_Backend_Common { - - /** - * @static - * @abstract - * @param int $addressbookId - * @param string $uri - * @return array - */ - /* - abstract public function getItemsByUri($addressbookId, $uri); + /** + * @static + * @abstract + * + * @param int $addressbookId + * @param string $uri + * + * @return array + */ + /* + abstract public function getItemsByUri($addressbookId, $uri); */ - /** - * @static - * @param int $addressbookId - */ - static public function invalidateCache($addressbookId) { - q("UPDATE %s%saddressbooks SET `needs_rebuild` = 1 WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressbookId)); - } + /** + * @static + * + * @param int $addressbookId + */ + public static function invalidateCache($addressbookId) + { + q('UPDATE %s%saddressbooks SET `needs_rebuild` = 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressbookId)); + } - /** - * @static - * @abstract - * @param int $addressbookId - * @param bool $force - */ - static abstract protected function createCache_internal($addressbookId, $force = false); + /** + * @static + * @abstract + * + * @param int $addressbookId + * @param bool $force + */ + abstract protected static function createCache_internal($addressbookId, $force = false); - /** - * @param int $addressbookId - * @param null|array $addressbook - * @param bool $force - */ - public function createCache($addressbookId, $addressbook = null, $force = false) { - $addressbookId = IntVal($addressbookId); + /** + * @param int $addressbookId + * @param null|array $addressbook + * @param bool $force + */ + public function createCache($addressbookId, $addressbook = null, $force = false) + { + $addressbookId = intval($addressbookId); - if (!$addressbook) { - $add = q("SELECT `needs_rebuild`, `uri` FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); - $addressbook = $add[0]; - } - if ($addressbook["needs_rebuild"] == 1 || $force) { - static::createCache_internal($addressbookId, $force); - q("UPDATE %s%saddressbooks SET `needs_rebuild` = 0, `ctag` = `ctag` + 1 WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); - } - } + if (!$addressbook) { + $add = q('SELECT `needs_rebuild`, `uri` FROM %s%saddressbooks WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); + $addressbook = $add[0]; + } + if ($addressbook['needs_rebuild'] == 1 || $force) { + static::createCache_internal($addressbookId, $force); + q('UPDATE %s%saddressbooks SET `needs_rebuild` = 0, `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); + } + } - /** - * @static - * @abstract - * @param int $addressbookId - * @param int $contactId - * @param bool $force - */ - static abstract protected function createCardCache($addressbookId, $contactId, $force = false); + /** + * @static + * @abstract + * + * @param int $addressbookId + * @param int $contactId + * @param bool $force + */ + abstract protected static function createCardCache($addressbookId, $contactId, $force = false); - /** - * @param int $addressbookId - * @return array - */ - public function getCards($addressbookId) - { - $addressbookId = IntVal($addressbookId); - $add = q("SELECT * FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); - if ($add[0]["needs_rebuild"]) { - static::createCache_internal($addressbookId); - q("UPDATE %s%saddressbooks SET `needs_rebuild` = 0, `ctag` = `ctag` + 1 WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); - $add[0]["needs_rebuild"] = 0; - $add[0]["ctag"]++; - } + /** + * @param int $addressbookId + * + * @return array + */ + public function getCards($addressbookId) + { + $addressbookId = intval($addressbookId); + $add = q('SELECT * FROM %s%saddressbooks WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); + if ($add[0]['needs_rebuild']) { + static::createCache_internal($addressbookId); + q('UPDATE %s%saddressbooks SET `needs_rebuild` = 0, `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); + $add[0]['needs_rebuild'] = 0; + ++$add[0]['ctag']; + } - $ret = array(); - $x = q("SELECT * FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `manually_deleted` = 0", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); - foreach ($x as $y) $ret[] = self::getCard($addressbookId, $add[0]["uri"], $add[0], $y); + $ret = array(); + $x = q('SELECT * FROM %s%saddressbookobjects WHERE `addressbook_id` = %d AND `manually_deleted` = 0', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); + foreach ($x as $y) { + $ret[] = self::getCard($addressbookId, $add[0]['uri'], $add[0], $y); + } - return $ret; - } + return $ret; + } + /** + * Replaces the x-prop_name value. Replaces the prop_name value IF the old value is the same as the old value of x-prop_name (meaning: the user has not manually changed it). + * + * @param Sabre\VObject\Component $component + * @param string $prop_name + * @param string $prop_value + * @param array $parameters + */ + public static function card_set_automatic_value(&$component, $prop_name, $prop_value, $parameters = array()) + { + $automatic = $component->select('X-'.$prop_name); + $curr = $component->select($prop_name); - /** - * Replaces the x-prop_name value. Replaces the prop_name value IF the old value is the same as the old value of x-prop_name (meaning: the user has not manually changed it) - * - * @param Sabre\VObject\Component $component - * @param string $prop_name - * @param string $prop_value - * @param array $parameters - * @return void - */ - static public function card_set_automatic_value(&$component, $prop_name, $prop_value, $parameters = array()) { - $automatic = $component->select("X-" . $prop_name); - $curr = $component->select($prop_name); + if (count($automatic) == 0) { + $prop = new Sabre\VObject\Property('X-'.$prop_name, $prop_value); + foreach ($parameters as $key => $val) { + $prop->add($key, $val); + } + $component->children[] = $prop; - if (count($automatic) == 0) { - $prop = new Sabre\VObject\Property('X-' . $prop_name, $prop_value); - foreach ($parameters as $key=>$val) $prop->add($key, $val); - $component->children[] = $prop; + if (count($curr) == 0) { + $prop = new Sabre\VObject\Property($prop_name, $prop_value); + foreach ($parameters as $key => $val) { + $prop->add($key, $val); + } + $component->children[] = $prop; + } + } else { + foreach ($automatic as $auto_prop) { + /* @var Sabre\VObject\Property $auto_prop */ + /** @var Sabre\VObject\Property $actual_prop */ + foreach ($curr as $actual_prop) { + if ($auto_prop->value == $actual_prop->value) { + $actual_prop->setValue($prop_value); + } + } + $auto_prop->setValue($prop_value); + } + } + } - if (count($curr) == 0) { - $prop = new Sabre\VObject\Property($prop_name, $prop_value); - foreach ($parameters as $key=>$val) $prop->add($key, $val); - $component->children[] = $prop; - } + /** + * Deletes the x-prop_name value. Deletes the prop_name value IF the old value is the same as the old value of x-prop_name (meaning: the user has not manually changed it). + * + * @param Sabre\VObject\Component $component + * @param string $prop_name + * @param array $parameters + */ + public static function card_del_automatic_value(&$component, $prop_name, $parameters = array()) + { + // @TODO + } - } else foreach ($automatic as $auto_prop) { - /** @var Sabre\VObject\Property $auto_prop */ - /** @var Sabre\VObject\Property $actual_prop */ - foreach ($curr as $actual_prop) { - if ($auto_prop->value == $actual_prop->value) $actual_prop->setValue($prop_value); - } - $auto_prop->setValue($prop_value); - } - } + /** + * @param int $addressbookId + * @param string $objectUri + * @param array $book + * @param array $obj + * + * @throws Sabre_DAV_Exception_NotFound + * + * @return array + */ + public function getCard($addressbookId, $objectUri, $book = null, $obj = null) + { + $addressbookId = intval($addressbookId); + if ($book == null) { + $add = q('SELECT `needs_rebuild`, `uri` FROM %s%saddressbooks WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); + $book = $add[0]; + } + if ($book['needs_rebuild'] == 1) { + static::createCache_internal($addressbookId); + q('UPDATE %s%saddressbooks SET `needs_rebuild` = 0, `ctag` = `ctag` + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); + $add[0]['needs_rebuild'] = 0; + } + if ($obj == null) { + $r = q("SELECT * FROM %s%saddressbookobjects WHERE `uri` = '%s' AND `addressbook_id` = %d AND `manually_deleted` = 0", + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($objectUri), intval($addressbookId)); + if (count($r) == 0) { + throw new Sabre_DAV_Exception_NotFound(); + } + $obj = $r[0]; + if ($obj['needs_rebuild'] == 1) { + $obj = static::createCardCache($addressbookId, $obj['contact']); + } + } - /** - * Deletes the x-prop_name value. Deletes the prop_name value IF the old value is the same as the old value of x-prop_name (meaning: the user has not manually changed it) - * - * @param Sabre\VObject\Component $component - * @param string $prop_name - * @param array $parameters - */ - static public function card_del_automatic_value(&$component, $prop_name, $parameters = array()) { - // @TODO - } + $ret = array( + 'id' => intval($obj['uri']), + 'carddata' => $obj['carddata'], + 'uri' => $obj['uri'], + 'lastmodified' => $obj['lastmodified'], + 'addressbookid' => $addressbookId, + 'etag' => $obj['etag'], + 'size' => intval($obj['size']), + ); - /** - * @param int $addressbookId - * @param string $objectUri - * @param array $book - * @param array $obj - * @throws Sabre_DAV_Exception_NotFound - * @return array - */ - public function getCard($addressbookId, $objectUri, $book = null, $obj = null) - { - $addressbookId = IntVal($addressbookId); + return $ret; + } - if ($book == null) { - $add = q("SELECT `needs_rebuild`, `uri` FROM %s%saddressbooks WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); - $book = $add[0]; - } - if ($book["needs_rebuild"] == 1) { - static::createCache_internal($addressbookId); - q("UPDATE %s%saddressbooks SET `needs_rebuild` = 0, `ctag` = `ctag` + 1 WHERE `id` = %d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, $addressbookId); - $add[0]["needs_rebuild"] = 0; - } + /** + * @param string $principalUri + * @param string $addressbookUri + * @param array $properties + * + * @throws Sabre_DAV_Exception_Forbidden + */ + public function createAddressBook($principalUri, $addressbookUri, array $properties) + { + throw new Sabre_DAV_Exception_Forbidden(); + } - if ($obj == null) { - $r = q("SELECT * FROM %s%saddressbookobjects WHERE `uri` = '%s' AND `addressbook_id` = %d AND `manually_deleted` = 0", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($objectUri), IntVal($addressbookId)); - if (count($r) == 0) throw new Sabre_DAV_Exception_NotFound(); - $obj = $r[0]; - if ($obj["needs_rebuild"] == 1) $obj = static::createCardCache($addressbookId, $obj["contact"]); - } + /** + * @param string $addressbookId + * + * @throws Sabre_DAV_Exception_Forbidden + */ + public function deleteAddressBook($addressbookId) + { + throw new Sabre_DAV_Exception_Forbidden(); + } - $ret = array( - "id" => IntVal($obj["uri"]), - "carddata" => $obj["carddata"], - "uri" => $obj["uri"], - "lastmodified" => $obj["lastmodified"], - "addressbookid" => $addressbookId, - "etag" => $obj["etag"], - "size" => IntVal($obj["size"]), - ); - return $ret; - } + /** + * @param string $addressbookId + * @param string $objectUri + * @param string $cardData + * + * @throws Sabre_DAV_Exception_Forbidden + * + * @return null|string|void + */ + public function createCard($addressbookId, $objectUri, $cardData) + { + throw new Sabre_DAV_Exception_Forbidden(); + } + /** + * Updates a card. + * + * The addressbook id will be passed as the first argument. This is the + * same id as it is returned from the getAddressbooksForUser method. + * + * The cardUri is a base uri, and doesn't include the full path. The + * cardData argument is the vcard body, and is passed as a string. + * + * It is possible to return an ETag from this method. This ETag should + * match that of the updated resource, and must be enclosed with double + * quotes (that is: the string itself must contain the actual quotes). + * + * You should only return the ETag if you store the carddata as-is. If a + * subsequent GET request on the same card does not have the same body, + * byte-by-byte and you did return an ETag here, clients tend to get + * confused. + * + * If you don't return an ETag, you can just return null. + * + * @param string $addressBookId + * @param string $cardUri + * @param string $cardData + * + * @throws Sabre_DAV_Exception_Forbidden + * + * @return string|null + */ + public function updateCard($addressBookId, $cardUri, $cardData) + { + echo 'Die!'; + die(); // @TODO + $x = explode('-', $addressBookId); + $etag = md5($cardData); + q("UPDATE %s%scards SET carddata = '%s', lastmodified = %d, etag = '%s', size = %d, manually_edited = 1 WHERE uri = '%s' AND namespace = %d AND namespace_id =%d", + CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), time(), $etag, strlen($cardData), dbesc($cardUri), intval($x[10]), intval($x[1]) + ); + q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($x[1])); - /** - * @param string $principalUri - * @param string $addressbookUri - * @param array $properties - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function createAddressBook($principalUri, $addressbookUri, array $properties) - { - throw new Sabre_DAV_Exception_Forbidden(); - } + return '"'.$etag.'"'; + } - /** - * @param string $addressbookId - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function deleteAddressBook($addressbookId) - { - throw new Sabre_DAV_Exception_Forbidden(); - } + /** + * Deletes a card. + * + * @param string $addressBookId + * @param string $cardUri + * + * @throws Sabre_DAV_Exception_Forbidden + * + * @return bool + */ + public function deleteCard($addressBookId, $cardUri) + { + q("UPDATE %s%scards SET `manually_deleted` = 1 WHERE `addressbook_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressBookId), dbesc($cardUri)); + q('UPDATE %s%saddressbooks SET ctag = ctag + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($addressBookId)); - - /** - * @param string $addressbookId - * @param string $objectUri - * @param string $cardData - * @throws Sabre_DAV_Exception_Forbidden - * @return null|string|void - */ - function createCard($addressbookId, $objectUri, $cardData) - { - throw new Sabre_DAV_Exception_Forbidden(); - } - - /** - * Updates a card. - * - * The addressbook id will be passed as the first argument. This is the - * same id as it is returned from the getAddressbooksForUser method. - * - * The cardUri is a base uri, and doesn't include the full path. The - * cardData argument is the vcard body, and is passed as a string. - * - * It is possible to return an ETag from this method. This ETag should - * match that of the updated resource, and must be enclosed with double - * quotes (that is: the string itself must contain the actual quotes). - * - * You should only return the ETag if you store the carddata as-is. If a - * subsequent GET request on the same card does not have the same body, - * byte-by-byte and you did return an ETag here, clients tend to get - * confused. - * - * If you don't return an ETag, you can just return null. - * - * @param string $addressBookId - * @param string $cardUri - * @param string $cardData - * @throws Sabre_DAV_Exception_Forbidden - * @return string|null - */ - public function updateCard($addressBookId, $cardUri, $cardData) - { - echo "Die!"; die(); // @TODO - $x = explode("-", $addressBookId); - - $etag = md5($cardData); - q("UPDATE %s%scards SET carddata = '%s', lastmodified = %d, etag = '%s', size = %d, manually_edited = 1 WHERE uri = '%s' AND namespace = %d AND namespace_id =%d", - CALDAV_SQL_DB, CALDAV_SQL_PREFIX, dbesc($cardData), time(), $etag, strlen($cardData), dbesc($cardUri), IntVal($x[10]), IntVal($x[1]) - ); - q('UPDATE %s%saddressbooks_community SET ctag = ctag + 1 WHERE uid = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($x[1])); - - return '"' . $etag . '"'; - } - - - - - /** - * Deletes a card - * - * @param string $addressBookId - * @param string $cardUri - * @throws Sabre_DAV_Exception_Forbidden - * @return bool - */ - public function deleteCard($addressBookId, $cardUri) - { - q("UPDATE %s%scards SET `manually_deleted` = 1 WHERE `addressbook_id` = %d AND `uri` = '%s'", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId), dbesc($cardUri)); - q('UPDATE %s%saddressbooks SET ctag = ctag + 1 WHERE `id` = %d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($addressBookId)); - - return true; - } - - -} \ No newline at end of file + return true; + } +} diff --git a/dav/common/dav_carddav_root.inc.php b/dav/common/dav_carddav_root.inc.php index b896afd3..f9156a12 100644 --- a/dav/common/dav_carddav_root.inc.php +++ b/dav/common/dav_carddav_root.inc.php @@ -1,64 +1,64 @@ carddavBackends = $carddavBackends; + parent::__construct($principalBackend, $principalPrefix); + } - /** - * Constructor - * - * This constructor needs both a principal and a carddav backend. - * - * By default this class will show a list of addressbook collections for - * principals in the 'principals' collection. If your main principals are - * actually located in a different path, use the $principalPrefix argument - * to override this. - * - * @param Sabre_DAVACL_IPrincipalBackend $principalBackend - * @param array|Sabre_CardDAV_Backend_Abstract[] $carddavBackends - * @param string $principalPrefix - */ - public function __construct(Sabre_DAVACL_IPrincipalBackend $principalBackend, $carddavBackends, $principalPrefix = 'principals/users') { - - $this->carddavBackends = $carddavBackends; - parent::__construct($principalBackend, $principalPrefix); - - } - - /** - * Returns the name of the node - * - * @return string - */ - public function getName() { - return Sabre_CardDAV_Plugin::ADDRESSBOOK_ROOT; - } - - /** - * This method returns a node for a principal. - * - * The passed array contains principal information, and is guaranteed to - * at least contain a uri item. Other properties may or may not be - * supplied by the authentication backend. - * - * @param array $principal - * @return Sabre_DAVACL_IPrincipal - */ - public function getChildForPrincipal(array $principal) { - return new Sabre_CardDAV_UserAddressBooksMultiBackend($this->carddavBackends, $principal['uri']); - - } + /** + * Returns the name of the node. + * + * @return string + */ + public function getName() + { + return Sabre_CardDAV_Plugin::ADDRESSBOOK_ROOT; + } + /** + * This method returns a node for a principal. + * + * The passed array contains principal information, and is guaranteed to + * at least contain a uri item. Other properties may or may not be + * supplied by the authentication backend. + * + * @param array $principal + * + * @return Sabre_DAVACL_IPrincipal + */ + public function getChildForPrincipal(array $principal) + { + return new Sabre_CardDAV_UserAddressBooksMultiBackend($this->carddavBackends, $principal['uri']); + } } diff --git a/dav/common/dav_user_addressbooks.inc.php b/dav/common/dav_user_addressbooks.inc.php index d430274c..bfcbb590 100644 --- a/dav/common/dav_user_addressbooks.inc.php +++ b/dav/common/dav_user_addressbooks.inc.php @@ -1,264 +1,252 @@ carddavBackends = $carddavBackends; + $this->principalUri = $principalUri; + } - /** - * Constructor - * - * @param array|Sabre_CardDAV_Backend_Abstract[] $carddavBackends - * @param string $principalUri - */ - public function __construct($carddavBackends, $principalUri) { + /** + * Returns the name of this object. + * + * @return string + */ + public function getName() + { + list(, $name) = Sabre_DAV_URLUtil::splitPath($this->principalUri); - $this->carddavBackends = $carddavBackends; - $this->principalUri = $principalUri; + return $name; + } - } + /** + * Updates the name of this object. + * + * @param string $name + * + * @throws Sabre_DAV_Exception_MethodNotAllowed + */ + public function setName($name) + { + throw new Sabre_DAV_Exception_MethodNotAllowed(); + } - /** - * Returns the name of this object - * - * @return string - */ - public function getName() { + /** + * Deletes this object. + * + * @throws Sabre_DAV_Exception_MethodNotAllowed + */ + public function delete() + { + throw new Sabre_DAV_Exception_MethodNotAllowed(); + } - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalUri); - return $name; + /** + * Returns the last modification date. + * + * @return int + */ + public function getLastModified() + { + return null; + } - } + /** + * Creates a new file under this object. + * + * This is currently not allowed + * + * @param string $filename + * @param resource $data + * + * @throws Sabre_DAV_Exception_MethodNotAllowed + * + * @return null|string|void + */ + public function createFile($filename, $data = null) + { + throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); + } - /** - * Updates the name of this object - * - * @param string $name - * @throws Sabre_DAV_Exception_MethodNotAllowed - * @return void - */ - public function setName($name) { + /** + * Creates a new directory under this object. + * + * This is currently not allowed. + * + * @param string $filename + * + * @throws Sabre_DAV_Exception_MethodNotAllowed + */ + public function createDirectory($filename) + { + throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); + } - throw new Sabre_DAV_Exception_MethodNotAllowed(); + /** + * Returns a single calendar, by name. + * + * @param string $name + * + * @throws Sabre_DAV_Exception_NotFound + * + * @todo needs optimizing + * + * @return \Sabre_CardDAV_AddressBook|\Sabre_DAV_INode + */ + public function getChild($name) + { + foreach ($this->getChildren() as $child) { + if ($name == $child->getName()) { + return $child; + } + } + throw new Sabre_DAV_Exception_NotFound('Addressbook with name \''.$name.'\' could not be found'); + } - } + /** + * Returns a list of addressbooks. + * + * @return array|Sabre_DAV_INode[] + */ + public function getChildren() + { + $objs = array(); + foreach ($this->carddavBackends as $backend) { + $addressbooks = $backend->getAddressbooksForUser($this->principalUri); + foreach ($addressbooks as $addressbook) { + $objs[] = new Sabre_CardDAV_AddressBook($backend, $addressbook); + } + } - /** - * Deletes this object - * - * @throws Sabre_DAV_Exception_MethodNotAllowed - * @return void - */ - public function delete() { + return $objs; + } - throw new Sabre_DAV_Exception_MethodNotAllowed(); + /** + * Creates a new addressbook. + * + * @param string $name + * @param array $resourceType + * @param array $properties + * + * @throws Sabre_DAV_Exception_InvalidResourceType + */ + public function createExtendedCollection($name, array $resourceType, array $properties) + { + if (!in_array('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook', $resourceType) || count($resourceType) !== 2) { + throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); + } + $this->carddavBackends[0]->createAddressBook($this->principalUri, $name, $properties); + } - } + /** + * Returns the owner principal. + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getOwner() + { + return $this->principalUri; + } - /** - * Returns the last modification date - * - * @return int - */ - public function getLastModified() { + /** + * Returns a group principal. + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getGroup() + { + return null; + } - return null; + /** + * Returns a list of ACE's for this node. + * + * Each ACE has the following properties: + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * currently the only supported privileges + * * 'principal', a url to the principal who owns the node + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array + */ + public function getACL() + { + return array( + array( + 'privilege' => '{DAV:}read', + 'principal' => $this->principalUri, + 'protected' => true, + ), + array( + 'privilege' => '{DAV:}write', + 'principal' => $this->principalUri, + 'protected' => true, + ), - } + ); + } - /** - * Creates a new file under this object. - * - * This is currently not allowed - * - * @param string $filename - * @param resource $data - * @throws Sabre_DAV_Exception_MethodNotAllowed - * @return null|string|void - */ - public function createFile($filename, $data=null) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); - - } - - /** - * Creates a new directory under this object. - * - * This is currently not allowed. - * - * @param string $filename - * @throws Sabre_DAV_Exception_MethodNotAllowed - * @return void - */ - public function createDirectory($filename) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); - - } - - /** - * Returns a single calendar, by name - * - * @param string $name - * @throws Sabre_DAV_Exception_NotFound - * @todo needs optimizing - * @return \Sabre_CardDAV_AddressBook|\Sabre_DAV_INode - */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return $child; - - } - throw new Sabre_DAV_Exception_NotFound('Addressbook with name \'' . $name . '\' could not be found'); - - } - - /** - * Returns a list of addressbooks - * - * @return array|Sabre_DAV_INode[] - */ - public function getChildren() { - - $objs = array(); - foreach ($this->carddavBackends as $backend) { - $addressbooks = $backend->getAddressbooksForUser($this->principalUri); - foreach($addressbooks as $addressbook) { - $objs[] = new Sabre_CardDAV_AddressBook($backend, $addressbook); - } - } - return $objs; - - } - - /** - * Creates a new addressbook - * - * @param string $name - * @param array $resourceType - * @param array $properties - * @throws Sabre_DAV_Exception_InvalidResourceType - * @return void - */ - public function createExtendedCollection($name, array $resourceType, array $properties) { - - if (!in_array('{'.Sabre_CardDAV_Plugin::NS_CARDDAV.'}addressbook',$resourceType) || count($resourceType)!==2) { - throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); - } - $this->carddavBackends[0]->createAddressBook($this->principalUri, $name, $properties); - - } - - /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalUri; - - } - - /** - * Returns a group principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getGroup() { - - return null; - - } - - /** - * Returns a list of ACE's for this node. - * - * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are - * currently the only supported privileges - * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array - */ - public function getACL() { - - return array( - array( - 'privilege' => '{DAV:}read', - 'principal' => $this->principalUri, - 'protected' => true, - ), - array( - 'privilege' => '{DAV:}write', - 'principal' => $this->principalUri, - 'protected' => true, - ), - - ); - - } - - /** - * Updates the ACL - * - * This method will receive a list of new ACE's. - * - * @param array $acl - * @throws Sabre_DAV_Exception_MethodNotAllowed - * @return void - */ - public function setACL(array $acl) { - - throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - - } - - /** - * Returns the list of supported privileges for this node. - * - * The returned data structure is a list of nested privileges. - * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple - * standard structure. - * - * If null is returned from this method, the default privilege set is used, - * which is fine for most common usecases. - * - * @return array|null - */ - public function getSupportedPrivilegeSet() { - - return null; - - } + /** + * Updates the ACL. + * + * This method will receive a list of new ACE's. + * + * @param array $acl + * + * @throws Sabre_DAV_Exception_MethodNotAllowed + */ + public function setACL(array $acl) + { + throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); + } + /** + * Returns the list of supported privileges for this node. + * + * The returned data structure is a list of nested privileges. + * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple + * standard structure. + * + * If null is returned from this method, the default privilege set is used, + * which is fine for most common usecases. + * + * @return array|null + */ + public function getSupportedPrivilegeSet() + { + return null; + } } diff --git a/dav/common/dav_user_calendars.inc.php b/dav/common/dav_user_calendars.inc.php index b292074d..a5324038 100644 --- a/dav/common/dav_user_calendars.inc.php +++ b/dav/common/dav_user_calendars.inc.php @@ -1,235 +1,232 @@ principalBackend = $principalBackend; $this->caldavBackends = $caldavBackends; $this->principalInfo = $principalBackend->getPrincipalByPath($userUri); - } /** - * Returns the name of this object - * + * Returns the name of this object. + * * @return string */ - public function getName() { - - list(,$name) = Sabre_DAV_URLUtil::splitPath($this->principalInfo['uri']); - return $name; - - } - - /** - * Updates the name of this object - * - * @param string $name - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function setName($name) { - - throw new Sabre_DAV_Exception_Forbidden(); - - } - - /** - * Deletes this object - * - * @throws Sabre_DAV_Exception_Forbidden - * @return void - */ - public function delete() { - - throw new Sabre_DAV_Exception_Forbidden(); + public function getName() + { + list(, $name) = Sabre_DAV_URLUtil::splitPath($this->principalInfo['uri']); + return $name; } /** - * Returns the last modification date - * - * @return int + * Updates the name of this object. + * + * @param string $name + * + * @throws Sabre_DAV_Exception_Forbidden */ - public function getLastModified() { - - return null; - + public function setName($name) + { + throw new Sabre_DAV_Exception_Forbidden(); } - /** - * Creates a new file under this object. - * - * This is currently not allowed - * - * @param string $filename - * @param resource $data - * @throws Sabre_DAV_Exception_MethodNotAllowed - * @return null|string|void - */ - public function createFile($filename, $data=null) { + /** + * Deletes this object. + * + * @throws Sabre_DAV_Exception_Forbidden + */ + public function delete() + { + throw new Sabre_DAV_Exception_Forbidden(); + } + /** + * Returns the last modification date. + * + * @return int + */ + public function getLastModified() + { + return null; + } + + /** + * Creates a new file under this object. + * + * This is currently not allowed + * + * @param string $filename + * @param resource $data + * + * @throws Sabre_DAV_Exception_MethodNotAllowed + * + * @return null|string|void + */ + public function createFile($filename, $data = null) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new files in this collection is not supported'); - } - /** - * Creates a new directory under this object. - * - * This is currently not allowed. - * - * @param string $filename - * @throws Sabre_DAV_Exception_MethodNotAllowed - * @return void - */ - public function createDirectory($filename) { - + /** + * Creates a new directory under this object. + * + * This is currently not allowed. + * + * @param string $filename + * + * @throws Sabre_DAV_Exception_MethodNotAllowed + */ + public function createDirectory($filename) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Creating new collections in this collection is not supported'); - } - /** - * Returns a single calendar, by name - * - * @param string $name - * @throws Sabre_DAV_Exception_NotFound - * @todo needs optimizing - * @return \Sabre_CalDAV_Calendar|\Sabre_DAV_INode - */ - public function getChild($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) + /** + * Returns a single calendar, by name. + * + * @param string $name + * + * @throws Sabre_DAV_Exception_NotFound + * + * @todo needs optimizing + * + * @return \Sabre_CalDAV_Calendar|\Sabre_DAV_INode + */ + public function getChild($name) + { + foreach ($this->getChildren() as $child) { + if ($name == $child->getName()) { return $child; - + } } - throw new Sabre_DAV_Exception_NotFound('Calendar with name \'' . $name . '\' could not be found'); - + throw new Sabre_DAV_Exception_NotFound('Calendar with name \''.$name.'\' could not be found'); } /** * Checks if a calendar exists. - * + * * @param string $name + * * @todo needs optimizing - * @return bool + * + * @return bool */ - public function childExists($name) { - - foreach($this->getChildren() as $child) { - if ($name==$child->getName()) - return true; - + public function childExists($name) + { + foreach ($this->getChildren() as $child) { + if ($name == $child->getName()) { + return true; + } } + return false; - } - /** - * Returns a list of calendars - * - * @return array|\Sabre_DAV_INode[] - */ - - public function getChildren() { - $objs = array(); - foreach ($this->caldavBackends as $backend) { - $calendars = $backend->getCalendarsForUser($this->principalInfo["uri"]); - foreach($calendars as $calendar) { - $objs[] = new $calendar["calendar_class"]($this->principalBackend, $backend, $calendar); - } - } + /** + * Returns a list of calendars. + * + * @return array|\Sabre_DAV_INode[] + */ + public function getChildren() + { + $objs = array(); + foreach ($this->caldavBackends as $backend) { + $calendars = $backend->getCalendarsForUser($this->principalInfo['uri']); + foreach ($calendars as $calendar) { + $objs[] = new $calendar['calendar_class']($this->principalBackend, $backend, $calendar); + } + } + return $objs; - } - /** - * Creates a new calendar - * - * @param string $name - * @param array $resourceType - * @param array $properties - * @throws Sabre_DAV_Exception_InvalidResourceType - * @return void - */ - public function createExtendedCollection($name, array $resourceType, array $properties) { - - if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar',$resourceType) || count($resourceType)!==2) { + /** + * Creates a new calendar. + * + * @param string $name + * @param array $resourceType + * @param array $properties + * + * @throws Sabre_DAV_Exception_InvalidResourceType + */ + public function createExtendedCollection($name, array $resourceType, array $properties) + { + if (!in_array('{urn:ietf:params:xml:ns:caldav}calendar', $resourceType) || count($resourceType) !== 2) { throw new Sabre_DAV_Exception_InvalidResourceType('Unknown resourceType for this collection'); } $this->caldavBackends[0]->createCalendar($this->principalInfo['uri'], $name, $properties); - } /** - * Returns the owner principal - * - * This must be a url to a principal, or null if there's no owner - * - * @return string|null - */ - public function getOwner() { - - return $this->principalInfo['uri']; - - } - - /** - * Returns a group principal + * Returns the owner principal. * * This must be a url to a principal, or null if there's no owner - * - * @return string|null + * + * @return string|null */ - public function getGroup() { + public function getOwner() + { + return $this->principalInfo['uri']; + } + /** + * Returns a group principal. + * + * This must be a url to a principal, or null if there's no owner + * + * @return string|null + */ + public function getGroup() + { return null; - } /** * Returns a list of ACE's for this node. * * Each ACE has the following properties: - * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are + * * 'privilege', a string such as {DAV:}read or {DAV:}write. These are * currently the only supported privileges * * 'principal', a url to the principal who owns the node - * * 'protected' (optional), indicating that this ACE is not allowed to - * be updated. - * - * @return array + * * 'protected' (optional), indicating that this ACE is not allowed to + * be updated. + * + * @return array */ - public function getACL() { + public function getACL() + { return array( array( 'privilege' => '{DAV:}read', @@ -243,54 +240,51 @@ class Sabre_CalDAV_AnimexxUserCalendars implements Sabre_DAV_IExtendedCollection ), array( 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', + 'principal' => $this->principalInfo['uri'].'/calendar-proxy-write', 'protected' => true, ), array( 'privilege' => '{DAV:}write', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-write', + 'principal' => $this->principalInfo['uri'].'/calendar-proxy-write', 'protected' => true, ), array( 'privilege' => '{DAV:}read', - 'principal' => $this->principalInfo['uri'] . '/calendar-proxy-read', + 'principal' => $this->principalInfo['uri'].'/calendar-proxy-read', 'protected' => true, ), ); - } /** - * Updates the ACL + * Updates the ACL. + * + * This method will receive a list of new ACE's. * - * This method will receive a list of new ACE's. - * * @param array $acl - * @throws Sabre_DAV_Exception_MethodNotAllowed - * @return void + * + * @throws Sabre_DAV_Exception_MethodNotAllowed */ - public function setACL(array $acl) { - + public function setACL(array $acl) + { throw new Sabre_DAV_Exception_MethodNotAllowed('Changing ACL is not yet supported'); - } - - /** - * Returns the list of supported privileges for this node. - * - * The returned data structure is a list of nested privileges. - * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple - * standard structure. - * - * If null is returned from this method, the default privilege set is used, - * which is fine for most common usecases. - * - * @return array|null - */ - function getSupportedPrivilegeSet() - { - return null; - } + /** + * Returns the list of supported privileges for this node. + * + * The returned data structure is a list of nested privileges. + * See Sabre_DAVACL_Plugin::getDefaultSupportedPrivilegeSet for a simple + * standard structure. + * + * If null is returned from this method, the default privilege set is used, + * which is fine for most common usecases. + * + * @return array|null + */ + public function getSupportedPrivilegeSet() + { + return null; + } } diff --git a/dav/common/wdcal_backend.inc.php b/dav/common/wdcal_backend.inc.php index 330f2988..074a6ac9 100644 --- a/dav/common/wdcal_backend.inc.php +++ b/dav/common/wdcal_backend.inc.php @@ -1,238 +1,248 @@ getProperties(array("id")); - if (isset($prop["id"]) && (!isset($_REQUEST["cal"]) || in_array($prop["id"], $_REQUEST["cal"]))) $calfound = $cals[$i]; - } - return $calfound; + $cals = dav_get_current_user_calendars($server, $right); + $calfound = null; + for ($i = 0; $i < count($cals) && $calfound === null; ++$i) { + $prop = $cals[$i]->getProperties(array('id')); + if (isset($prop['id']) && (!isset($_REQUEST['cal']) || in_array($prop['id'], $_REQUEST['cal']))) { + $calfound = $cals[$i]; + } + } + + return $calfound; } - -/** - * - */ -function wdcal_print_feed($base_path = "") +function wdcal_print_feed($base_path = '') { - $server = dav_create_server(true, true, false); + $server = dav_create_server(true, true, false); - $ret = null; + $ret = null; - $method = $_GET["method"]; - switch ($method) { - case "add": - $cs = wdcal_print_feed_getCal($server, DAV_ACL_WRITE); - if ($cs == null) { - echo wdcal_jsonp_encode(array('IsSuccess' => false, - 'Msg' => t('No access'))); - killme(); - } - try { - $item = dav_create_empty_vevent(); - $component = dav_get_eventComponent($item); - $component->add("SUMMARY", icalendar_sanitize_string(dav_compat_parse_text_serverside("CalendarTitle"))); + $method = $_GET['method']; + switch ($method) { + case 'add': + $cs = wdcal_print_feed_getCal($server, DAV_ACL_WRITE); + if ($cs == null) { + echo wdcal_jsonp_encode(array('IsSuccess' => false, + 'Msg' => t('No access'), )); + killme(); + } + try { + $item = dav_create_empty_vevent(); + $component = dav_get_eventComponent($item); + $component->add('SUMMARY', icalendar_sanitize_string(dav_compat_parse_text_serverside('CalendarTitle'))); - if (isset($_REQUEST["allday"])) $type = Sabre\VObject\Property\DateTime::DATE; - else $type = Sabre\VObject\Property\DateTime::LOCALTZ; + if (isset($_REQUEST['allday'])) { + $type = Sabre\VObject\Property\DateTime::DATE; + } else { + $type = Sabre\VObject\Property\DateTime::LOCALTZ; + } - $datetime_start = new Sabre\VObject\Property\DateTime("DTSTART"); - $datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarStartTime"]))), $type); - $datetime_end = new Sabre\VObject\Property\DateTime("DTEND"); - $datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarEndTime"]))), $type); + $datetime_start = new Sabre\VObject\Property\DateTime('DTSTART'); + $datetime_start->setDateTime(new DateTime(date('Y-m-d H:i:s', intval($_REQUEST['CalendarStartTime']))), $type); + $datetime_end = new Sabre\VObject\Property\DateTime('DTEND'); + $datetime_end->setDateTime(new DateTime(date('Y-m-d H:i:s', intval($_REQUEST['CalendarEndTime']))), $type); - $component->add($datetime_start); - $component->add($datetime_end); + $component->add($datetime_start); + $component->add($datetime_end); - $uid = $component->__get("UID"); - $data = $item->serialize(); + $uid = $component->__get('UID'); + $data = $item->serialize(); - $cs->createFile($uid . ".ics", $data); + $cs->createFile($uid.'.ics', $data); - $ret = array( - 'IsSuccess' => true, - 'Msg' => 'add success', - 'Data' => $uid . ".ics", - ); + $ret = array( + 'IsSuccess' => true, + 'Msg' => 'add success', + 'Data' => $uid.'.ics', + ); + } catch (Exception $e) { + $ret = array( + 'IsSuccess' => false, + 'Msg' => $e->__toString(), + ); + } + break; + case 'list': + $weekstartday = (isset($_REQUEST['weekstartday']) ? intval($_REQUEST['weekstartday']) : 1); // 1 = Monday + $num_days = (isset($_REQUEST['num_days']) ? intval($_REQUEST['num_days']) : 7); + $ret = null; - } catch (Exception $e) { - $ret = array( - 'IsSuccess' => false, - 'Msg' => $e->__toString(), - ); - } - break; - case "list": - $weekstartday = (isset($_REQUEST["weekstartday"]) ? IntVal($_REQUEST["weekstartday"]) : 1); // 1 = Monday - $num_days = (isset($_REQUEST["num_days"]) ? IntVal($_REQUEST["num_days"]) : 7); - $ret = null; + $date = wdcal_get_list_range_params($_REQUEST['showdate'], $weekstartday, $num_days, $_REQUEST['viewtype']); + $ret = array(); + $ret['events'] = array(); + $ret['issort'] = true; + $ret['start'] = $date[0]; + $ret['end'] = $date[1]; + $ret['error'] = null; - $date = wdcal_get_list_range_params($_REQUEST["showdate"], $weekstartday, $num_days, $_REQUEST["viewtype"]); - $ret = array(); - $ret['events'] = array(); - $ret["issort"] = true; - $ret["start"] = $date[0]; - $ret["end"] = $date[1]; - $ret['error'] = null; + $cals = dav_get_current_user_calendars($server, DAV_ACL_READ); + foreach ($cals as $cal) { + $prop = $cal->getProperties(array('id')); + if (isset($prop['id']) && (!isset($_REQUEST['cal']) || in_array($prop['id'], $_REQUEST['cal']))) { + $backend = wdcal_calendar_factory_by_id($prop['id']); + $events = $backend->listItemsByRange($prop['id'], $date[0], $date[1], $base_path); + $ret['events'] = array_merge($ret['events'], $events); + } + } - $cals = dav_get_current_user_calendars($server, DAV_ACL_READ); - foreach ($cals as $cal) { - $prop = $cal->getProperties(array("id")); - if (isset($prop["id"]) && (!isset($_REQUEST["cal"]) || in_array($prop["id"], $_REQUEST["cal"]))) { - $backend = wdcal_calendar_factory_by_id($prop["id"]); - $events = $backend->listItemsByRange($prop["id"], $date[0], $date[1], $base_path); - $ret["events"] = array_merge($ret["events"], $events); - } - } + $tmpev = array(); + foreach ($ret['events'] as $e) { + if (!isset($tmpev[$e['start']])) { + $tmpev[$e['start']] = array(); + } + $tmpev[$e['start']][] = $e; + } + ksort($tmpev); + $ret['events'] = array(); + foreach ($tmpev as $e) { + foreach ($e as $f) { + $ret['events'][] = $f; + } + } - $tmpev = array(); - foreach ($ret["events"] as $e) { - if (!isset($tmpev[$e["start"]])) $tmpev[$e["start"]] = array(); - $tmpev[$e["start"]][] = $e; - } - ksort($tmpev); - $ret["events"] = array(); - foreach ($tmpev as $e) foreach ($e as $f) $ret["events"][] = $f; + break; + case 'update': + $r = q('SELECT `calendarobject_id`, `calendar_id` FROM %s%sjqcalendar WHERE `id`=%d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($_REQUEST['jq_id'])); + if (count($r) != 1) { + echo wdcal_jsonp_encode(array('IsSuccess' => false, + 'Msg' => t('No access'), )); + killme(); + } + try { + $cs = dav_get_current_user_calendar_by_id($server, $r[0]['calendar_id'], DAV_ACL_READ); + $obj_uri = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($r[0]['calendarobject_id']); - break; - case "update": - $r = q("SELECT `calendarobject_id`, `calendar_id` FROM %s%sjqcalendar WHERE `id`=%d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($_REQUEST["jq_id"])); - if (count($r) != 1) { - echo wdcal_jsonp_encode(array('IsSuccess' => false, - 'Msg' => t('No access'))); - killme(); - } - try { - $cs = dav_get_current_user_calendar_by_id($server, $r[0]["calendar_id"], DAV_ACL_READ); - $obj_uri = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($r[0]["calendarobject_id"]); + $vObject = dav_get_current_user_calendarobject($server, $cs, $obj_uri['uri'], DAV_ACL_WRITE); + $component = dav_get_eventComponent($vObject); - $vObject = dav_get_current_user_calendarobject($server, $cs, $obj_uri["uri"], DAV_ACL_WRITE); - $component = dav_get_eventComponent($vObject); + if (!$component) { + echo wdcal_jsonp_encode(array('IsSuccess' => false, + 'Msg' => t('No access'), )); + killme(); + } - if (!$component) { - echo wdcal_jsonp_encode(array('IsSuccess' => false, - 'Msg' => t('No access'))); - killme(); - } + if (isset($_REQUEST['allday'])) { + $type = Sabre\VObject\Property\DateTime::DATE; + } else { + $type = Sabre\VObject\Property\DateTime::LOCALTZ; + } - if (isset($_REQUEST["allday"])) $type = Sabre\VObject\Property\DateTime::DATE; - else $type = Sabre\VObject\Property\DateTime::LOCALTZ; + $datetime_start = new Sabre\VObject\Property\DateTime('DTSTART'); + $datetime_start->setDateTime(new DateTime(date('Y-m-d H:i:s', intval($_REQUEST['CalendarStartTime']))), $type); + $datetime_end = new Sabre\VObject\Property\DateTime('DTEND'); + $datetime_end->setDateTime(new DateTime(date('Y-m-d H:i:s', intval($_REQUEST['CalendarEndTime']))), $type); - $datetime_start = new Sabre\VObject\Property\DateTime("DTSTART"); - $datetime_start->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarStartTime"]))), $type); - $datetime_end = new Sabre\VObject\Property\DateTime("DTEND"); - $datetime_end->setDateTime(new DateTime(date("Y-m-d H:i:s", IntVal($_REQUEST["CalendarEndTime"]))), $type); + $component->__unset('DTSTART'); + $component->__unset('DTEND'); + $component->add($datetime_start); + $component->add($datetime_end); - $component->__unset("DTSTART"); - $component->__unset("DTEND"); - $component->add($datetime_start); - $component->add($datetime_end); + $data = $vObject->serialize(); + /** @var Sabre_CalDAV_CalendarObject $child */ + $child = $cs->getChild($obj_uri['uri']); + $child->put($data); - $data = $vObject->serialize(); - /** @var Sabre_CalDAV_CalendarObject $child */ - $child = $cs->getChild($obj_uri["uri"]); - $child->put($data); + $ret = array( + 'IsSuccess' => true, + 'Msg' => 'Succefully', + ); + } catch (Exception $e) { + echo wdcal_jsonp_encode(array('IsSuccess' => false, + 'Msg' => t('No access'), )); + killme(); + } + break; + case 'remove': + $r = q('SELECT `calendarobject_id`, `calendar_id` FROM %s%sjqcalendar WHERE `id`=%d', CALDAV_SQL_DB, CALDAV_SQL_PREFIX, intval($_REQUEST['jq_id'])); + if (count($r) != 1) { + echo wdcal_jsonp_encode(array('IsSuccess' => false, + 'Msg' => t('No access'), )); + killme(); + } + try { + $cs = dav_get_current_user_calendar_by_id($server, $r[0]['calendar_id'], DAV_ACL_WRITE); + $obj_uri = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($r[0]['calendarobject_id']); + $child = $cs->getChild($obj_uri['uri']); + $child->delete(); - $ret = array( - 'IsSuccess' => true, - 'Msg' => 'Succefully', - ); - } catch (Exception $e) { - echo wdcal_jsonp_encode(array('IsSuccess' => false, - 'Msg' => t('No access'))); - killme(); - } - break; - case "remove": - $r = q("SELECT `calendarobject_id`, `calendar_id` FROM %s%sjqcalendar WHERE `id`=%d", CALDAV_SQL_DB, CALDAV_SQL_PREFIX, IntVal($_REQUEST["jq_id"])); - if (count($r) != 1) { - echo wdcal_jsonp_encode(array('IsSuccess' => false, - 'Msg' => t('No access'))); - killme(); - } - try { - $cs = dav_get_current_user_calendar_by_id($server, $r[0]["calendar_id"], DAV_ACL_WRITE); - $obj_uri = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($r[0]["calendarobject_id"]); - $child = $cs->getChild($obj_uri["uri"]); - $child->delete(); + $ret = array( + 'IsSuccess' => true, + 'Msg' => 'Succefully', + ); + } catch (Exception $e) { + echo wdcal_jsonp_encode(array('IsSuccess' => false, + 'Msg' => t('No access'), )); + killme(); + } - $ret = array( - 'IsSuccess' => true, - 'Msg' => 'Succefully', - ); - } catch (Exception $e) { - echo wdcal_jsonp_encode(array('IsSuccess' => false, - 'Msg' => t('No access'))); - killme(); - } - - break; - } - echo wdcal_jsonp_encode($ret); - killme(); + break; + } + echo wdcal_jsonp_encode($ret); + killme(); } - diff --git a/dav/common/wdcal_configuration.php b/dav/common/wdcal_configuration.php index c7b66fb1..7f55858a 100644 --- a/dav/common/wdcal_configuration.php +++ b/dav/common/wdcal_configuration.php @@ -2,322 +2,382 @@ abstract class wdcal_local { + const LOCAL_US = 0; + const LOCAL_DE = 1; - const LOCAL_US = 0; - const LOCAL_DE = 1; + /** + * @static + * + * @return array|wdcal_local[] + */ + public static function getInstanceClasses() + { + return array( + self::LOCAL_US => 'wdcal_local_us', + self::LOCAL_DE => 'wdcal_local_de', + ); + } - /** - * @static - * @return array|wdcal_local[] - */ - static function getInstanceClasses() { - return array( - self::LOCAL_US => "wdcal_local_us", - self::LOCAL_DE => "wdcal_local_de", - ); - } + /** + * @static + * + * @param int $config + * + * @return null|wdcal_local + */ + public static function getInstance($config = 0) + { + $classes = self::getInstanceClasses(); + if (isset($classes[$config])) { + return new $classes[$config](); + } - /** - * @static - * @param int $config - * @return null|wdcal_local - */ - static function getInstance($config = 0) { - $classes = self::getInstanceClasses(); - if (isset($classes[$config])) return new $classes[$config]; - return null; - } + return null; + } - /** - * @static - * @param int $uid - * @return wdcal_local - */ - static function getInstanceByUser($uid = 0) { - $dateformat = get_pconfig($uid, "dav", "dateformat"); - $format = self::getInstance($dateformat); - if ($format == null) $format = self::getInstance(self::LOCAL_US); - return $format; - } + /** + * @static + * + * @param int $uid + * + * @return wdcal_local + */ + public static function getInstanceByUser($uid = 0) + { + $dateformat = get_pconfig($uid, 'dav', 'dateformat'); + $format = self::getInstance($dateformat); + if ($format == null) { + $format = self::getInstance(self::LOCAL_US); + } - /** - * @static - * @abstract - * @return string - */ - abstract static function getLanguageCode(); + return $format; + } - /** - * @abstract - * @static - * @return string - */ - abstract static function getName(); + /** + * @static + * @abstract + * + * @return string + */ + abstract public static function getLanguageCode(); - /** - * @static - * @abstract - * @return int - */ - abstract static function getID(); + /** + * @abstract + * @static + * + * @return string + */ + abstract public static function getName(); - /** - * @param string $str - * @return int - */ - function date_local2timestamp($str) { - $x = $this->date_parseLocal($str); - return mktime($x["hour"], $x["minute"], $x["second"], $x["month"], $x["day"], $x["year"]); - } + /** + * @static + * @abstract + * + * @return int + */ + abstract public static function getID(); - /** - * @abstract - * @param string $str - * @return array - */ - abstract function date_parseLocal($str); + /** + * @param string $str + * + * @return int + */ + public function date_local2timestamp($str) + { + $x = $this->date_parseLocal($str); - /** - * @abstract - * @param int $ts - * @return string - */ - abstract function date_timestamp2local($ts); + return mktime($x['hour'], $x['minute'], $x['second'], $x['month'], $x['day'], $x['year']); + } - /** - * @abstract - * @param int $ts - * @return string - */ - abstract function date_timestamp2localDate($ts); + /** + * @abstract + * + * @param string $str + * + * @return array + */ + abstract public function date_parseLocal($str); - /** - * @abstract - * @return int - */ - abstract function getFirstDayOfWeek(); + /** + * @abstract + * + * @param int $ts + * + * @return string + */ + abstract public function date_timestamp2local($ts); - /** - * @abstract - * @return string - */ - abstract function dateformat_js_dm1(); - /** - * @abstract - * @return string - */ - abstract function dateformat_js_dm2(); + /** + * @abstract + * + * @param int $ts + * + * @return string + */ + abstract public function date_timestamp2localDate($ts); - /** - * @abstract - * @return string - */ - abstract function dateformat_js_dm3(); + /** + * @abstract + * + * @return int + */ + abstract public function getFirstDayOfWeek(); - /** - * @abstract - * @return string - */ - abstract function dateformat_datepicker_js(); + /** + * @abstract + * + * @return string + */ + abstract public function dateformat_js_dm1(); + /** + * @abstract + * + * @return string + */ + abstract public function dateformat_js_dm2(); - /** - * @abstract - * @param int $ts - * @return string - */ - abstract function dateformat_datepicker_php($ts = 0); + /** + * @abstract + * + * @return string + */ + abstract public function dateformat_js_dm3(); + /** + * @abstract + * + * @return string + */ + abstract public function dateformat_datepicker_js(); + + /** + * @abstract + * + * @param int $ts + * + * @return string + */ + abstract public function dateformat_datepicker_php($ts = 0); } +class wdcal_local_us extends wdcal_local +{ + /** + * @static + * + * @return string + */ + public static function getLanguageCode() + { + return 'en'; + } + /** + * @return string + */ + public static function getName() + { + return t('U.S. Time Format (mm/dd/YYYY)'); + } -class wdcal_local_us extends wdcal_local { + /** + * @static + * + * @return int + */ + public static function getID() + { + return wdcal_local::LOCAL_US; + } - /** - * @static - * @return string - */ - static function getLanguageCode() { - return "en"; - } + /** + * @param string $str + * + * @return array + */ + public function date_parseLocal($str) + { + return date_parse_from_format('m/d/Y H:i', $str); + } - /** - * @return string - */ - static function getName() { - return t("U.S. Time Format (mm/dd/YYYY)"); - } + /** + * @param int $ts + * + * @return string + */ + public function date_timestamp2local($ts) + { + return date('m/d/Y H:i', $ts); + } - /** - * @static - * @return int - */ - static function getID() { - return wdcal_local::LOCAL_US; - } + /** + * @param int $ts + * + * @return string + */ + public function date_timestamp2localDate($ts) + { + return date('l, F jS Y', $ts); + } - /** - * @param string $str - * @return array - */ - function date_parseLocal($str) { - return date_parse_from_format("m/d/Y H:i", $str); - } + /** + * @return int + */ + public function getFirstDayOfWeek() + { + return 0; + } + /** + * @return string + */ + public function dateformat_js_dm1() + { + return 'W, M/d'; + } - /** - * @param int $ts - * @return string - */ - function date_timestamp2local($ts) - { - return date("m/d/Y H:i", $ts); - } + /** + * @return string + */ + public function dateformat_js_dm2() + { + return 'd. L'; + } - /** - * @param int $ts - * @return string - */ - function date_timestamp2localDate($ts) { - return date("l, F jS Y", $ts); - } + /** + * @return string + */ + public function dateformat_js_dm3() + { + return 'd L yyyy'; + } - /** - * @return int - */ - function getFirstDayOfWeek() { - return 0; - } + /** + * @return string + */ + public function dateformat_datepicker_js() + { + return 'mm/dd/yy'; + } - /** - * @return string - */ - function dateformat_js_dm1() { - return "W, M/d"; - } - - /** - * @return string - */ - function dateformat_js_dm2() { - return "d. L"; - } - - /** - * @return string - */ - function dateformat_js_dm3() { - return "d L yyyy"; - } - - /** - * @return string - */ - function dateformat_datepicker_js() { - return "mm/dd/yy"; - } - - /** - * @param int $ts - * @return string - */ - function dateformat_datepicker_php($ts = 0) { - return date("m/d/Y", $ts); - } + /** + * @param int $ts + * + * @return string + */ + public function dateformat_datepicker_php($ts = 0) + { + return date('m/d/Y', $ts); + } } -class wdcal_local_de extends wdcal_local { +class wdcal_local_de extends wdcal_local +{ + /** + * @static + * + * @return string + */ + public static function getLanguageCode() + { + return 'de'; + } - /** - * @static - * @return string - */ - static function getLanguageCode() { - return "de"; - } + /** + * @return string + */ + public static function getName() + { + return t('German Time Format (dd.mm.YYYY)'); + } - /** - * @return string - */ - static function getName() { - return t("German Time Format (dd.mm.YYYY)"); - } + /** + * @static + * + * @return int + */ + public static function getID() + { + return wdcal_local::LOCAL_DE; + } - /** - * @static - * @return int - */ - static function getID() { - return wdcal_local::LOCAL_DE; - } + /** + * @param string $str + * + * @return array + */ + public function date_parseLocal($str) + { + return date_parse_from_format('d.m.Y H:i', $str); + } - /** - * @param string $str - * @return array - */ - function date_parseLocal($str) - { - return date_parse_from_format("d.m.Y H:i", $str); - } + /** + * @param int $ts + * + * @return string + */ + public function date_timestamp2local($ts) + { + return date('d.m.Y H:i', $ts); + } - /** - * @param int $ts - * @return string - */ - function date_timestamp2local($ts) - { - return date("d.m.Y H:i", $ts); - } + /** + * @param int $ts + * + * @return string + */ + public function date_timestamp2localDate($ts) + { + return date('l, j. F Y', $ts); + } - /** - * @param int $ts - * @return string - */ - function date_timestamp2localDate($ts) { - return date("l, j. F Y", $ts); - } + /** + * @return int + */ + public function getFirstDayOfWeek() + { + return 1; + } - /** - * @return int - */ - function getFirstDayOfWeek() { - return 1; - } + /** + * @return string + */ + public function dateformat_js_dm1() + { + return 'W, d.M'; + } - /** - * @return string - */ - function dateformat_js_dm1() { - return "W, d.M"; - } + /** + * @return string + */ + public function dateformat_js_dm2() + { + return 'd. L'; + } - /** - * @return string - */ - function dateformat_js_dm2() { - return "d. L"; - } + /** + * @return string + */ + public function dateformat_js_dm3() + { + return 'd L yyyy'; + } - /** - * @return string - */ - function dateformat_js_dm3() { - return "d L yyyy"; - } + /** + * @return string + */ + public function dateformat_datepicker_js() + { + return 'dd.mm.yy'; + } - /** - * @return string - */ - function dateformat_datepicker_js() { - return "dd.mm.yy"; - } - - /** - * @param int $ts - * @return string - */ - function dateformat_datepicker_php($ts = 0) { - return date("d.m.Y", $ts); - } + /** + * @param int $ts + * + * @return string + */ + public function dateformat_datepicker_php($ts = 0) + { + return date('d.m.Y', $ts); + } } - diff --git a/dav/common/wdcal_edit.inc.php b/dav/common/wdcal_edit.inc.php index d507a900..3b52de4d 100644 --- a/dav/common/wdcal_edit.inc.php +++ b/dav/common/wdcal_edit.inc.php @@ -2,807 +2,973 @@ /** * @param wdcal_local $localization - * @param string $baseurl - * @param int $calendar_id - * @param int $uri + * @param string $baseurl + * @param int $calendar_id + * @param int $uri + * * @return string */ function wdcal_getEditPage_str(&$localization, $baseurl, $calendar_id, $uri) { - $server = dav_create_server(true, true, false); + $server = dav_create_server(true, true, false); - if ($uri > 0) { - $calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE); - if (!$calendar) { - $calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_READ); - $calendars = array(); - } else { - $calendars = dav_get_current_user_calendars($server, DAV_ACL_WRITE); - } + if ($uri > 0) { + $calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE); + if (!$calendar) { + $calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_READ); + $calendars = array(); + } else { + $calendars = dav_get_current_user_calendars($server, DAV_ACL_WRITE); + } - if ($calendar == null) return "Calendar not found"; + if ($calendar == null) { + return 'Calendar not found'; + } - $obj_uri = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($uri); + $obj_uri = Sabre_CalDAV_Backend_Common::loadCalendarobjectById($uri); - $vObject = dav_get_current_user_calendarobject($server, $calendar, $obj_uri["uri"], DAV_ACL_WRITE); - $component = dav_get_eventComponent($vObject); + $vObject = dav_get_current_user_calendarobject($server, $calendar, $obj_uri['uri'], DAV_ACL_WRITE); + $component = dav_get_eventComponent($vObject); - if ($component == null) return t('Could not open component for editing'); + if ($component == null) { + return t('Could not open component for editing'); + } - /** @var Sabre\VObject\Property\DateTime $dtstart */ - $dtstart = $component->__get("DTSTART"); - $event = array( - "id" => IntVal($uri), - "Summary" => ($component->__get("SUMMARY") ? $component->__get("SUMMARY")->value : null), - "StartTime" => $dtstart->getDateTime()->getTimeStamp(), - "EndTime" => Sabre_CalDAV_Backend_Common::getDtEndTimeStamp($component), - "IsAllDayEvent" => (strlen($dtstart->value) == 8), - "Description" => ($component->__get("DESCRIPTION") ? $component->__get("DESCRIPTION")->value : null), - "Location" => ($component->__get("LOCATION") ? $component->__get("LOCATION")->value : null), - "Color" => ($component->__get("X-ANIMEXX-COLOR") ? $component->__get("X-ANIMEXX-COLOR")->value : null), - ); + /** @var Sabre\VObject\Property\DateTime $dtstart */ + $dtstart = $component->__get('DTSTART'); + $event = array( + 'id' => intval($uri), + 'Summary' => ($component->__get('SUMMARY') ? $component->__get('SUMMARY')->value : null), + 'StartTime' => $dtstart->getDateTime()->getTimeStamp(), + 'EndTime' => Sabre_CalDAV_Backend_Common::getDtEndTimeStamp($component), + 'IsAllDayEvent' => (strlen($dtstart->value) == 8), + 'Description' => ($component->__get('DESCRIPTION') ? $component->__get('DESCRIPTION')->value : null), + 'Location' => ($component->__get('LOCATION') ? $component->__get('LOCATION')->value : null), + 'Color' => ($component->__get('X-ANIMEXX-COLOR') ? $component->__get('X-ANIMEXX-COLOR')->value : null), + ); - $exdates = $component->select("EXDATE"); - $recurrentce_exdates = array(); - /** @var Sabre\VObject\Property\MultiDateTime $x */ - foreach ($exdates as $x) { - /** @var DateTime $y */ - $z = $x->getDateTimes(); - foreach ($z as $y) $recurrentce_exdates[] = $y->getTimeStamp(); - } + $exdates = $component->select('EXDATE'); + $recurrentce_exdates = array(); + /** @var Sabre\VObject\Property\MultiDateTime $x */ + foreach ($exdates as $x) { + /** @var DateTime $y */ + $z = $x->getDateTimes(); + foreach ($z as $y) { + $recurrentce_exdates[] = $y->getTimeStamp(); + } + } - $notifications = array(); - $alarms = $component->select("VALARM"); - foreach ($alarms as $alarm) { - /** @var Sabre_VObject_Component_VAlarm $alarm */ - $action = $alarm->__get("ACTION")->value; - $trigger = $alarm->__get("TRIGGER"); + $notifications = array(); + $alarms = $component->select('VALARM'); + foreach ($alarms as $alarm) { + /** @var Sabre_VObject_Component_VAlarm $alarm */ + $action = $alarm->__get('ACTION')->value; + $trigger = $alarm->__get('TRIGGER'); - if(isset($trigger['VALUE']) && strtoupper($trigger['VALUE']) !== 'DURATION') { - notice("The notification of this event cannot be parsed"); - continue; - } + if (isset($trigger['VALUE']) && strtoupper($trigger['VALUE']) !== 'DURATION') { + notice('The notification of this event cannot be parsed'); + continue; + } - /** @var DateInterval $triggerDuration */ - $triggerDuration = Sabre_VObject_DateTimeParser::parseDuration($trigger); - $unit = "hour"; - $value = 1; - if ($triggerDuration->s > 0) { - $unit = "second"; - $value = $triggerDuration->s + $triggerDuration->i * 60 + $triggerDuration->h * 3600 + $triggerDuration->d * 3600 * 24; // @TODO support more than days? - } elseif ($triggerDuration->i) { - $unit = "minute"; - $value = $triggerDuration->i + $triggerDuration->h * 60 + $triggerDuration->d * 60 * 24; - } elseif ($triggerDuration->h) { - $unit = "hour"; - $value = $triggerDuration->h + $triggerDuration->d * 24; - } elseif ($triggerDuration->d > 0) { - $unit = "day"; - $value = $triggerDuration->d; - } + /** @var DateInterval $triggerDuration */ + $triggerDuration = Sabre_VObject_DateTimeParser::parseDuration($trigger); + $unit = 'hour'; + $value = 1; + if ($triggerDuration->s > 0) { + $unit = 'second'; + $value = $triggerDuration->s + $triggerDuration->i * 60 + $triggerDuration->h * 3600 + $triggerDuration->d * 3600 * 24; // @TODO support more than days? + } elseif ($triggerDuration->i) { + $unit = 'minute'; + $value = $triggerDuration->i + $triggerDuration->h * 60 + $triggerDuration->d * 60 * 24; + } elseif ($triggerDuration->h) { + $unit = 'hour'; + $value = $triggerDuration->h + $triggerDuration->d * 24; + } elseif ($triggerDuration->d > 0) { + $unit = 'day'; + $value = $triggerDuration->d; + } - $rel = (isset($trigger['RELATED']) && strtoupper($trigger['RELATED']) == 'END') ? 'end' : 'start'; + $rel = (isset($trigger['RELATED']) && strtoupper($trigger['RELATED']) == 'END') ? 'end' : 'start'; + $notifications[] = array( + 'action' => strtolower($action), + 'rel' => $rel, + 'trigger_unit' => $unit, + 'trigger_value' => $value, + ); + } - $notifications[] = array( - "action" => strtolower($action), - "rel" => $rel, - "trigger_unit" => $unit, - "trigger_value" => $value, - ); - } + if ($component->select('RRULE')) { + $recurrence = new Sabre_VObject_RecurrenceIterator($vObject, (string) $component->__get('UID')); + } else { + $recurrence = null; + } + } elseif (isset($_REQUEST['start']) && $_REQUEST['start'] > 0) { + $calendars = dav_get_current_user_calendars($server, DAV_ACL_WRITE); + //$calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE); - if ($component->select("RRULE")) $recurrence = new Sabre_VObject_RecurrenceIterator($vObject, (string)$component->__get("UID")); - else $recurrence = null; + $event = array( + 'id' => 0, + 'Summary' => $_REQUEST['title'], + 'StartTime' => intval($_REQUEST['start']), + 'EndTime' => intval($_REQUEST['end']), + 'IsAllDayEvent' => $_REQUEST['isallday'], + 'Description' => '', + 'Location' => '', + 'Color' => null, + ); + if ($_REQUEST['isallday']) { + $notifications = array(); + } else { + $notifications = array(array('action' => 'email', 'rel' => 'start', 'trigger_unit' => 'hour', 'trigger_value' => 1)); + } + $recurrence = null; + $recurrentce_exdates = array(); + } else { + $calendars = dav_get_current_user_calendars($server, DAV_ACL_WRITE); + //$calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE); - } elseif (isset($_REQUEST["start"]) && $_REQUEST["start"] > 0) { - $calendars = dav_get_current_user_calendars($server, DAV_ACL_WRITE); - //$calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE); + $event = array( + 'id' => 0, + 'Summary' => '', + 'StartTime' => time(), + 'EndTime' => time() + 3600, + 'IsAllDayEvent' => '0', + 'Description' => '', + 'Location' => '', + 'Color' => null, + ); + $notifications = array(array('action' => 'email', 'rel' => 'start', 'trigger_unit' => 'hour', 'trigger_value' => 1)); + $recurrence = null; + $recurrentce_exdates = array(); + } - $event = array( - "id" => 0, - "Summary" => $_REQUEST["title"], - "StartTime" => InTVal($_REQUEST["start"]), - "EndTime" => IntVal($_REQUEST["end"]), - "IsAllDayEvent" => $_REQUEST["isallday"], - "Description" => "", - "Location" => "", - "Color" => null, - ); - if ($_REQUEST["isallday"]) { - $notifications = array(); - } else { - $notifications = array(array("action" => "email", "rel" => "start", "trigger_unit" => "hour", "trigger_value" => 1)); - } - $recurrence = null; - $recurrentce_exdates = array(); - } else { - $calendars = dav_get_current_user_calendars($server, DAV_ACL_WRITE); - //$calendar = dav_get_current_user_calendar_by_id($server, $calendar_id, DAV_ACL_WRITE); + $postto = $baseurl.'/dav/wdcal/'.($uri == 0 ? 'new/' : $calendar_id.'/'.$uri.'/edit/'); - $event = array( - "id" => 0, - "Summary" => "", - "StartTime" => time(), - "EndTime" => time() + 3600, - "IsAllDayEvent" => "0", - "Description" => "", - "Location" => "", - "Color" => null, - ); - $notifications = array(array("action" => "email", "rel" => "start", "trigger_unit" => "hour", "trigger_value" => 1)); - $recurrence = null; - $recurrentce_exdates = array(); - } + $out = "".t('Go back to the calendar').'

'; + $out .= "
+ \n"; - $postto = $baseurl . "/dav/wdcal/" . ($uri == 0 ? "new/" : $calendar_id . "/" . $uri . "/edit/"); + $out .= '

'.t('Event data').'

'; - $out = "" . t("Go back to the calendar") . "

"; - $out .= " - \n"; + $out .= "'; + $out .= "