diff options
author | Bart Visscher <bartv@thisnet.nl> | 2012-07-24 18:35:09 +0200 |
---|---|---|
committer | Bart Visscher <bartv@thisnet.nl> | 2012-07-24 18:35:09 +0200 |
commit | 0040b7109f1201805d9e4ac7e586b44261c335a4 (patch) | |
tree | 852fdb4394e8ab3bfb2bdb4300e542e8abbb7d80 /lib | |
parent | 768b44b9b685a07af6030e484ab6322ba44b5b7e (diff) | |
parent | 856d9c0b54cc971940df4ed64429d994faf770f9 (diff) | |
download | nextcloud-server-0040b7109f1201805d9e4ac7e586b44261c335a4.tar.gz nextcloud-server-0040b7109f1201805d9e4ac7e586b44261c335a4.zip |
Merge branch 'master' into routing
Conflicts:
lib/ocs.php
Diffstat (limited to 'lib')
-rwxr-xr-x | lib/app.php | 6 | ||||
-rw-r--r-- | lib/cache.php | 108 | ||||
-rw-r--r-- | lib/cache/apc.php | 5 | ||||
-rw-r--r-- | lib/cache/broker.php | 6 | ||||
-rw-r--r-- | lib/cache/file.php | 5 | ||||
-rw-r--r-- | lib/cache/xcache.php | 5 | ||||
-rw-r--r-- | lib/connector/sabre/node.php | 1 | ||||
-rw-r--r-- | lib/db.php | 6 | ||||
-rw-r--r-- | lib/eventsource.php | 3 | ||||
-rw-r--r-- | lib/exception.php | 93 | ||||
-rw-r--r-- | lib/filecache.php | 32 | ||||
-rw-r--r-- | lib/filesystem.php | 186 | ||||
-rw-r--r-- | lib/filesystemview.php | 436 | ||||
-rw-r--r-- | lib/helper.php | 31 | ||||
-rw-r--r-- | lib/image.php | 13 | ||||
-rw-r--r-- | lib/installer.php | 30 | ||||
-rw-r--r-- | lib/json.php | 14 | ||||
-rw-r--r-- | lib/mimetypes.fixlist.php | 22 | ||||
-rw-r--r-- | lib/mimetypes.list.php | 13 | ||||
-rw-r--r-- | lib/minimizer.php | 10 | ||||
-rw-r--r-- | lib/ocs.php | 964 | ||||
-rw-r--r-- | lib/user.php | 8 | ||||
-rwxr-xr-x | lib/util.php | 59 |
23 files changed, 1221 insertions, 835 deletions
diff --git a/lib/app.php b/lib/app.php index 2b975de9ef0..56132c08671 100755 --- a/lib/app.php +++ b/lib/app.php @@ -195,7 +195,7 @@ class OC_App{ // check if the app is compatible with this version of ownCloud $info=OC_App::getAppInfo($app); $version=OC_Util::getVersion(); - if(!isset($info['require']) or ($version[0]>$info['require'])){ + if(!isset($info['require']) or ($version[0]>$info['require'])){ OC_Log::write('core','App "'.$info['name'].'" can\'t be installed because it is not compatible with this version of ownCloud',OC_Log::ERROR); return false; }else{ @@ -331,8 +331,8 @@ class OC_App{ } /** - * Get the path where to install apps - */ + * Get the path where to install apps + */ public static function getInstallPath() { if(OC_Config::getValue('appstoreenabled', true)==false) { return false; diff --git a/lib/cache.php b/lib/cache.php index 1f269174fad..55f189a5da8 100644 --- a/lib/cache.php +++ b/lib/cache.php @@ -7,48 +7,96 @@ */ class OC_Cache { + /** + * @var OC_Cache $user_cache + */ static protected $user_cache; + /** + * @var OC_Cache $global_cache + */ static protected $global_cache; + /** + * @var OC_Cache $global_cache_fast + */ + static protected $global_cache_fast; + /** + * @var OC_Cache $user_cache_fast + */ + static protected $user_cache_fast; + static protected $isFast=null; - static public function getGlobalCache() { + /** + * get the global cache + * @return OC_Cache + */ + static public function getGlobalCache($fast=false) { if (!self::$global_cache) { - $fast_cache = null; - if (!$fast_cache && function_exists('xcache_set')) { - $fast_cache = new OC_Cache_XCache(true); + self::$global_cache_fast = null; + if (!self::$global_cache_fast && function_exists('xcache_set')) { + self::$global_cache_fast = new OC_Cache_XCache(true); } - if (!$fast_cache && function_exists('apc_store')) { - $fast_cache = new OC_Cache_APC(true); + if (!self::$global_cache_fast && function_exists('apc_store')) { + self::$global_cache_fast = new OC_Cache_APC(true); } + self::$global_cache = new OC_Cache_FileGlobal(); - if ($fast_cache) { - self::$global_cache = new OC_Cache_Broker($fast_cache, self::$global_cache); + if (self::$global_cache_fast) { + self::$global_cache = new OC_Cache_Broker(self::$global_cache_fast, self::$global_cache); + } + } + if($fast){ + if(self::$global_cache_fast){ + return self::$global_cache_fast; + }else{ + return false; } } return self::$global_cache; } - static public function getUserCache() { + /** + * get the user cache + * @return OC_Cache + */ + static public function getUserCache($fast=false) { if (!self::$user_cache) { - $fast_cache = null; - if (!$fast_cache && function_exists('xcache_set')) { - $fast_cache = new OC_Cache_XCache(); + self::$user_cache_fast = null; + if (!self::$user_cache_fast && function_exists('xcache_set')) { + self::$user_cache_fast = new OC_Cache_XCache(); } - if (!$fast_cache && function_exists('apc_store')) { - $fast_cache = new OC_Cache_APC(); + if (!self::$user_cache_fast && function_exists('apc_store')) { + self::$user_cache_fast = new OC_Cache_APC(); } + self::$user_cache = new OC_Cache_File(); - if ($fast_cache) { - self::$user_cache = new OC_Cache_Broker($fast_cache, self::$user_cache); + if (self::$user_cache_fast) { + self::$user_cache = new OC_Cache_Broker(self::$user_cache_fast, self::$user_cache); + } + } + + if($fast){ + if(self::$user_cache_fast){ + return self::$user_cache_fast; + }else{ + return false; } } return self::$user_cache; } + /** + * get a value from the user cache + * @return mixed + */ static public function get($key) { $user_cache = self::getUserCache(); return $user_cache->get($key); } + /** + * set a value in the user cache + * @return bool + */ static public function set($key, $value, $ttl=0) { if (empty($key)) { return false; @@ -57,19 +105,43 @@ class OC_Cache { return $user_cache->set($key, $value, $ttl); } + /** + * check if a value is set in the user cache + * @return bool + */ static public function hasKey($key) { $user_cache = self::getUserCache(); return $user_cache->hasKey($key); } + /** + * remove an item from the user cache + * @return bool + */ static public function remove($key) { $user_cache = self::getUserCache(); return $user_cache->remove($key); } - static public function clear() { + /** + * clear the user cache of all entries starting with a prefix + * @param string prefix (optional) + * @return bool + */ + static public function clear($prefix='') { $user_cache = self::getUserCache(); - return $user_cache->clear(); + return $user_cache->clear($prefix); + } + + /** + * check if a fast memory based cache is available + * @return true + */ + static public function isFast() { + if(is_null(self::$isFast)){ + self::$isFast=function_exists('xcache_set') || function_exists('apc_store'); + } + return self::$isFast; } } diff --git a/lib/cache/apc.php b/lib/cache/apc.php index 6cf47d0c158..c192fe2f196 100644 --- a/lib/cache/apc.php +++ b/lib/cache/apc.php @@ -43,14 +43,15 @@ class OC_Cache_APC { return apc_delete($this->getNamespace().$key); } - public function clear(){ - $ns = $this->getNamespace(); + public function clear($prefix=''){ + $ns = $this->getNamespace().$prefix; $cache = apc_cache_info('user'); foreach($cache['cache_list'] as $entry) { if (strpos($entry['info'], $ns) === 0) { apc_delete($entry['info']); } } + return true; } } if(!function_exists('apc_exists')) { diff --git a/lib/cache/broker.php b/lib/cache/broker.php index 931d0dd407e..c2aceabaf53 100644 --- a/lib/cache/broker.php +++ b/lib/cache/broker.php @@ -46,8 +46,8 @@ class OC_Cache_Broker { return $this->slow_cache->remove($key); } - public function clear(){ - $this->fast_cache->clear(); - $this->slow_cache->clear(); + public function clear($prefix=''){ + $this->fast_cache->clear($prefix); + $this->slow_cache->clear($prefix); } } diff --git a/lib/cache/file.php b/lib/cache/file.php index 0b7d3e30508..562c3d17167 100644 --- a/lib/cache/file.php +++ b/lib/cache/file.php @@ -62,15 +62,16 @@ class OC_Cache_File{ return $storage->unlink($key); } - public function clear(){ + public function clear($prefix=''){ $storage = $this->getStorage(); if($storage and $storage->is_dir('/')){ $dh=$storage->opendir('/'); while($file=readdir($dh)){ - if($file!='.' and $file!='..'){ + if($file!='.' and $file!='..' and ($prefix==='' || strpos($file, $prefix) === 0)){ $storage->unlink('/'.$file); } } } + return true; } } diff --git a/lib/cache/xcache.php b/lib/cache/xcache.php index bd55cee8f6b..951f9b47545 100644 --- a/lib/cache/xcache.php +++ b/lib/cache/xcache.php @@ -43,7 +43,8 @@ class OC_Cache_XCache { return xcache_unset($this->getNamespace().$key); } - public function clear(){ - return xcache_unset_by_prefix($this->getNamespace()); + public function clear($prefix=''){ + xcache_unset_by_prefix($this->getNamespace().$prefix); + return true; } } diff --git a/lib/connector/sabre/node.php b/lib/connector/sabre/node.php index 3cb5412f09f..663970487fb 100644 --- a/lib/connector/sabre/node.php +++ b/lib/connector/sabre/node.php @@ -142,6 +142,7 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr public function updateProperties($properties) { $existing = $this->getProperties(array()); foreach($properties as $propertyName => $propertyValue) { + $propertyName = preg_replace("/^{.*}/", "", $propertyName); // remove leading namespace from property name // If it was null, we need to delete the property if (is_null($propertyValue)) { if(array_key_exists( $propertyName, $existing )){ diff --git a/lib/db.php b/lib/db.php index 6f083d17cfb..6971fe4a583 100644 --- a/lib/db.php +++ b/lib/db.php @@ -368,9 +368,6 @@ class OC_DB { if( $definition instanceof MDB2_Schema_Error ){ die( $definition->getMessage().': '.$definition->getUserInfo()); } -// if(OC_Config::getValue('dbtype','sqlite')=='sqlite'){ -// $definition['overwrite']=true;//always overwrite for sqlite -// } $ret=self::$schema->createDatabase( $definition ); // Die in case something went wrong @@ -527,8 +524,7 @@ class OC_DB { * @brief replaces the owncloud tables with a new set * @param $file string path to the MDB2 xml db export file */ - public static function replaceDB( $file ){ - + public static function replaceDB( $file ){ $apps = OC_App::getAllApps(); self::beginTransaction(); // Delete the old tables diff --git a/lib/eventsource.php b/lib/eventsource.php index 2a8c6b92902..95af2e471bc 100644 --- a/lib/eventsource.php +++ b/lib/eventsource.php @@ -42,6 +42,9 @@ class OC_EventSource{ }else{ header("Content-Type: text/event-stream"); } + if( !OC_Util::isCallRegistered()){ + exit(); + } flush(); } diff --git a/lib/exception.php b/lib/exception.php new file mode 100644 index 00000000000..db516fc12d2 --- /dev/null +++ b/lib/exception.php @@ -0,0 +1,93 @@ +<?php +/** + * ownCloud + * + * @author Georg Ehrke + * @copyright 2012 georg@owncloud.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU AFFERO GENERAL PUBLIC LICENSE for more details. + * + * You should have received a copy of the GNU Affero General Public + * License along with this library. If not, see <http://www.gnu.org/licenses/>. + * + */ +class OC_Exception extends Exception{ + + function __construct($message = null, $code = 0, $file = null, $line = null){ + parent::__construct($message, $code); + if(!is_null($file)){ + $this->file = $file; + } + if(!is_null($line)){ + $this->line = $line; + } + $this->writelog(); + } + + private function writelog(){ + @OC_Log::write(OC_App::getCurrentApp(), $this->getMessage() . '-' . $this->getFile() . '-' . $this->getLine(), OC_Log::FATAL); + } + + private function generatesysinfo(){ + return array('phpversion' => PHP_VERSION, + 'os' => php_uname('s'), + 'osrelease' => php_uname('r'), + 'osarchitecture' => php_uname('m'), + 'phpserverinterface' => php_sapi_name(), + 'serverprotocol' => $_SERVER['SERVER_PROTOCOL'], + 'requestmethod' => $_SERVER['REQUEST_METHOD'], + 'https' => ($_SERVER['HTTPS']==''?'false':'true'), + 'database'=>(@OC_Config::getValue('dbtype')!=''?@OC_Config::getValue('dbtype'):'') + ); + } + + function __toString(){ + $tmpl = new OC_Template('core', 'exception', 'guest'); + $tmpl->assign('showsysinfo', true); + $tmpl->assign('message', $this->getMessage()); + $tmpl->assign('code', $this->getCode()); + $tmpl->assign('file', $this->getFile()); + $tmpl->assign('line', $this->getLine()); + $tmpl->assign('sysinfo', $this->generatesysinfo()); + $tmpl->printPage(); + } +} + +function oc_exceptionhandler($exception){ + switch($exception->getCode()){ + case E_NOTICE: + case E_DEPRECATED: + case E_USER_NOTICE: + case E_USER_DEPRECATED: + break; + default: + throw new OC_Exception($exception->getMessage(), $exception->getCode(), $exception->getFile(), $exception->getLine()); + break; + } + return true; +} + +function oc_errorhandler($errno , $errstr , $errfile , $errline){ + switch($errno){ + case E_NOTICE: + case E_DEPRECATED: + case E_USER_NOTICE: + case E_USER_DEPRECATED: + break; + default: + throw new OC_Exception($errstr, $errno, $errfile, $errline); + break; + } + return true; +} +set_exception_handler('oc_exceptionhandler'); +set_error_handler('oc_errorhandler'); +error_reporting(E_ERROR | E_WARNING | E_PARSE);
\ No newline at end of file diff --git a/lib/filecache.php b/lib/filecache.php index 4b1774925c3..22f7427ae42 100644 --- a/lib/filecache.php +++ b/lib/filecache.php @@ -98,6 +98,10 @@ class OC_FileCache{ if(OC_DB::isError($result)){ OC_Log::write('files','error while writing file('.$path.') to cache',OC_Log::ERROR); } + + if($cache=OC_Cache::getUserCache(true)){ + $cache->remove('fileid/'.$path);//ensure we don't have -1 cached + } } /** @@ -146,6 +150,11 @@ class OC_FileCache{ $query=OC_DB::prepare('UPDATE *PREFIX*fscache SET parent=? ,name=?, path=?, path_hash=? WHERE path_hash=?'); $query->execute(array($newParent,basename($newPath),$newPath,md5($newPath),md5($oldPath))); + if(($cache=OC_Cache::getUserCache(true)) && $cache->hasKey('fileid/'.$oldPath)){ + $cache->set('fileid/'.$newPath,$cache->get('fileid/'.$oldPath)); + $cache->remove('fileid/'.$oldPath); + } + $query=OC_DB::prepare('SELECT path FROM *PREFIX*fscache WHERE path LIKE ?'); $oldLength=strlen($oldPath); $updateQuery=OC_DB::prepare('UPDATE *PREFIX*fscache SET path=?, path_hash=? WHERE path_hash=?'); @@ -153,6 +162,11 @@ class OC_FileCache{ $old=$row['path']; $new=$newPath.substr($old,$oldLength); $updateQuery->execute(array($new,md5($new),md5($old))); + + if(($cache=OC_Cache::getUserCache(true)) && $cache->hasKey('fileid/'.$old)){ + $cache->set('fileid/'.$new,$cache->get('fileid/'.$old)); + $cache->remove('fileid/'.$old); + } } } @@ -171,6 +185,8 @@ class OC_FileCache{ //delete everything inside the folder $query=OC_DB::prepare('DELETE FROM *PREFIX*fscache WHERE path LIKE ?'); $query->execute(array($root.$path.'/%')); + + OC_Cache::remove('fileid/'.$root.$path); } /** @@ -245,9 +261,14 @@ class OC_FileCache{ if($root===false){ $root=OC_Filesystem::getRoot(); } + + $fullPath=$root.$path; + if(($cache=OC_Cache::getUserCache(true)) && $cache->hasKey('fileid/'.$fullPath)){ + return $cache->get('fileid/'.$fullPath); + } $query=OC_DB::prepare('SELECT id FROM *PREFIX*fscache WHERE path_hash=?'); - $result=$query->execute(array(md5($root.$path))); + $result=$query->execute(array(md5($fullPath))); if(OC_DB::isError($result)){ OC_Log::write('files','error while getting file id of '.$path,OC_Log::ERROR); return -1; @@ -255,10 +276,15 @@ class OC_FileCache{ $result=$result->fetchRow(); if(is_array($result)){ - return $result['id']; + $id=$result['id']; }else{ - return -1; + $id=-1; + } + if($cache=OC_Cache::getUserCache(true)){ + $cache->set('fileid/'.$fullPath,$id); } + + return $id; } /** diff --git a/lib/filesystem.php b/lib/filesystem.php index ec30ffb8f4c..a5edcf5bab3 100644 --- a/lib/filesystem.php +++ b/lib/filesystem.php @@ -53,99 +53,99 @@ class OC_Filesystem{ static private $defaultInstance; - /** - * classname which used for hooks handling - * used as signalclass in OC_Hooks::emit() - */ - const CLASSNAME = 'OC_Filesystem'; - - /** - * signalname emited before file renaming - * @param oldpath - * @param newpath - */ - const signal_rename = 'rename'; - - /** - * signal emited after file renaming - * @param oldpath - * @param newpath - */ - const signal_post_rename = 'post_rename'; - - /** - * signal emited before file/dir creation - * @param path - * @param run changing this flag to false in hook handler will cancel event - */ - const signal_create = 'create'; - - /** - * signal emited after file/dir creation - * @param path - * @param run changing this flag to false in hook handler will cancel event - */ - const signal_post_create = 'post_create'; - - /** - * signal emits before file/dir copy - * @param oldpath - * @param newpath - * @param run changing this flag to false in hook handler will cancel event - */ - const signal_copy = 'copy'; - - /** - * signal emits after file/dir copy - * @param oldpath - * @param newpath - */ - const signal_post_copy = 'post_copy'; - - /** - * signal emits before file/dir save - * @param path - * @param run changing this flag to false in hook handler will cancel event - */ - const signal_write = 'write'; - - /** - * signal emits after file/dir save - * @param path - */ - const signal_post_write = 'post_write'; - - /** - * signal emits when reading file/dir - * @param path - */ - const signal_read = 'read'; - - /** - * signal emits when removing file/dir - * @param path - */ - const signal_delete = 'delete'; - - /** - * parameters definitions for signals - */ - const signal_param_path = 'path'; - const signal_param_oldpath = 'oldpath'; - const signal_param_newpath = 'newpath'; - - /** - * run - changing this flag to false in hook handler will cancel event - */ - const signal_param_run = 'run'; - - /** - * get the mountpoint of the storage object for a path - ( note: because a storage is not always mounted inside the fakeroot, the returned mountpoint is relative to the absolute root of the filesystem and doesn't take the chroot into account - * - * @param string path - * @return string - */ + /** + * classname which used for hooks handling + * used as signalclass in OC_Hooks::emit() + */ + const CLASSNAME = 'OC_Filesystem'; + + /** + * signalname emited before file renaming + * @param oldpath + * @param newpath + */ + const signal_rename = 'rename'; + + /** + * signal emited after file renaming + * @param oldpath + * @param newpath + */ + const signal_post_rename = 'post_rename'; + + /** + * signal emited before file/dir creation + * @param path + * @param run changing this flag to false in hook handler will cancel event + */ + const signal_create = 'create'; + + /** + * signal emited after file/dir creation + * @param path + * @param run changing this flag to false in hook handler will cancel event + */ + const signal_post_create = 'post_create'; + + /** + * signal emits before file/dir copy + * @param oldpath + * @param newpath + * @param run changing this flag to false in hook handler will cancel event + */ + const signal_copy = 'copy'; + + /** + * signal emits after file/dir copy + * @param oldpath + * @param newpath + */ + const signal_post_copy = 'post_copy'; + + /** + * signal emits before file/dir save + * @param path + * @param run changing this flag to false in hook handler will cancel event + */ + const signal_write = 'write'; + + /** + * signal emits after file/dir save + * @param path + */ + const signal_post_write = 'post_write'; + + /** + * signal emits when reading file/dir + * @param path + */ + const signal_read = 'read'; + + /** + * signal emits when removing file/dir + * @param path + */ + const signal_delete = 'delete'; + + /** + * parameters definitions for signals + */ + const signal_param_path = 'path'; + const signal_param_oldpath = 'oldpath'; + const signal_param_newpath = 'newpath'; + + /** + * run - changing this flag to false in hook handler will cancel event + */ + const signal_param_run = 'run'; + + /** + * get the mountpoint of the storage object for a path + ( note: because a storage is not always mounted inside the fakeroot, the returned mountpoint is relative to the absolute root of the filesystem and doesn't take the chroot into account + * + * @param string path + * @return string + */ static public function getMountPoint($path){ OC_Hook::emit(self::CLASSNAME,'get_mountpoint',array('path'=>$path)); if(!$path){ diff --git a/lib/filesystemview.php b/lib/filesystemview.php index a23d7bbe7fd..9beda01e5a1 100644 --- a/lib/filesystemview.php +++ b/lib/filesystemview.php @@ -22,19 +22,19 @@ /** - * Class to provide access to ownCloud filesystem via a "view", and methods for - * working with files within that view (e.g. read, write, delete, etc.). Each - * view is restricted to a set of directories via a virtual root. The default view - * uses the currently logged in user's data directory as root (parts of + * Class to provide access to ownCloud filesystem via a "view", and methods for + * working with files within that view (e.g. read, write, delete, etc.). Each + * view is restricted to a set of directories via a virtual root. The default view + * uses the currently logged in user's data directory as root (parts of * OC_Filesystem are merely a wrapper for OC_FilesystemView). - * + * * Apps that need to access files outside of the user data folders (to modify files * belonging to a user other than the one currently logged in, for example) should * use this class directly rather than using OC_Filesystem, or making use of PHP's - * built-in file manipulation functions. This will ensure all hooks and proxies + * built-in file manipulation functions. This will ensure all hooks and proxies * are triggered correctly. * - * Filesystem functions are not called directly; they are passed to the correct + * Filesystem functions are not called directly; they are passed to the correct * OC_Filestorage object */ @@ -43,11 +43,11 @@ class OC_FilesystemView { private $internal_path_cache=array(); private $storage_cache=array(); - public function __construct($root){ + public function __construct($root) { $this->fakeRoot=$root; } - public function getAbsolutePath($path){ + public function getAbsolutePath($path) { if(!$path){ $path='/'; } @@ -63,9 +63,9 @@ class OC_FilesystemView { * @param string fakeRoot * @return bool */ - public function chroot($fakeRoot){ + public function chroot($fakeRoot) { if(!$fakeRoot==''){ - if($fakeRoot[0]!=='/'){ + if($fakeRoot[0]!=='/') { $fakeRoot='/'.$fakeRoot; } } @@ -76,7 +76,7 @@ class OC_FilesystemView { * get the fake root * @return string */ - public function getRoot(){ + public function getRoot() { return $this->fakeRoot; } @@ -85,7 +85,7 @@ class OC_FilesystemView { * @param string path * @return bool */ - public function getInternalPath($path){ + public function getInternalPath($path) { if (!isset($this->internal_path_cache[$path])) { $this->internal_path_cache[$path] = OC_Filesystem::getInternalPath($this->getAbsolutePath($path)); } @@ -97,23 +97,23 @@ class OC_FilesystemView { * @param string path * @return string */ - public function getRelativePath($path){ - if($this->fakeRoot==''){ + public function getRelativePath($path) { + if($this->fakeRoot=='') { return $path; } - if(strpos($path,$this->fakeRoot)!==0){ + if(strpos($path, $this->fakeRoot)!==0) { return null; }else{ - return substr($path,strlen($this->fakeRoot)); + return substr($path, strlen($this->fakeRoot)); } } - + /** * get the storage object for a path * @param string path * @return OC_Filestorage */ - public function getStorage($path){ + public function getStorage($path) { if (!isset($this->storage_cache[$path])) { $this->storage_cache[$path] = OC_Filesystem::getStorage($this->getAbsolutePath($path)); } @@ -127,7 +127,7 @@ class OC_FilesystemView { * @param string path * @return string */ - public function getMountPoint($path){ + public function getMountPoint($path) { return OC_Filesystem::getMountPoint($this->getAbsolutePath($path)); } @@ -137,55 +137,55 @@ class OC_FilesystemView { * @param string path * @return string */ - public function getLocalFile($path){ - $parent=substr($path,0,strrpos($path,'/')); - if(OC_Filesystem::isValidPath($parent) and $storage=$this->getStorage($path)){ + public function getLocalFile($path) { + $parent=substr($path, 0, strrpos($path,'/')); + if(OC_Filesystem::isValidPath($parent) and $storage=$this->getStorage($path)) { return $storage->getLocalFile($this->getInternalPath($path)); } } /** - * the following functions operate with arguments and return values identical - * to those of their PHP built-in equivalents. Mostly they are merely wrappers + * the following functions operate with arguments and return values identical + * to those of their PHP built-in equivalents. Mostly they are merely wrappers * for OC_Filestorage via basicOperation(). */ - public function mkdir($path){ - return $this->basicOperation('mkdir',$path,array('create','write')); + public function mkdir($path) { + return $this->basicOperation('mkdir', $path, array('create', 'write')); } - public function rmdir($path){ - return $this->basicOperation('rmdir',$path,array('delete')); + public function rmdir($path) { + return $this->basicOperation('rmdir', $path, array('delete')); } - public function opendir($path){ - return $this->basicOperation('opendir',$path,array('read')); + public function opendir($path) { + return $this->basicOperation('opendir', $path, array('read')); } - public function readdir($handle){ + public function readdir($handle) { $fsLocal= new OC_Filestorage_Local( array( 'datadir' => '/' ) ); return $fsLocal->readdir( $handle ); } - public function is_dir($path){ + public function is_dir($path) { if($path=='/'){ return true; } - return $this->basicOperation('is_dir',$path); + return $this->basicOperation('is_dir', $path); } - public function is_file($path){ + public function is_file($path) { if($path=='/'){ return false; } - return $this->basicOperation('is_file',$path); + return $this->basicOperation('is_file', $path); } - public function stat($path){ - return $this->basicOperation('stat',$path); + public function stat($path) { + return $this->basicOperation('stat', $path); } - public function filetype($path){ - return $this->basicOperation('filetype',$path); + public function filetype($path) { + return $this->basicOperation('filetype', $path); } - public function filesize($path){ - return $this->basicOperation('filesize',$path); + public function filesize($path) { + return $this->basicOperation('filesize', $path); } - public function readfile($path){ + public function readfile($path) { @ob_end_clean(); - $handle=$this->fopen($path,'rb'); + $handle=$this->fopen($path, 'rb'); if ($handle) { $chunkSize = 8192;// 8 MB chunks while (!feof($handle)) { @@ -197,137 +197,210 @@ class OC_FilesystemView { } return false; } - public function is_readable($path){ - return $this->basicOperation('is_readable',$path); + public function is_readable($path) { + return $this->basicOperation('is_readable', $path); } - public function is_writable($path){ - return $this->basicOperation('is_writable',$path); + public function is_writable($path) { + return $this->basicOperation('is_writable', $path); } - public function file_exists($path){ + public function file_exists($path) { if($path=='/'){ return true; } - return $this->basicOperation('file_exists',$path); + return $this->basicOperation('file_exists', $path); } - public function filectime($path){ - return $this->basicOperation('filectime',$path); + public function filectime($path) { + return $this->basicOperation('filectime', $path); } - public function filemtime($path){ - return $this->basicOperation('filemtime',$path); + public function filemtime($path) { + return $this->basicOperation('filemtime', $path); } - public function touch($path, $mtime=null){ + public function touch($path, $mtime=null) { return $this->basicOperation('touch', $path, array('write'), $mtime); } - public function file_get_contents($path){ - return $this->basicOperation('file_get_contents',$path,array('read')); - } - public function file_put_contents($path,$data){ - if(is_resource($data)){//not having to deal with streams in file_put_contents makes life easier - $exists=$this->file_exists($path); - $run=true; - if(!$exists){ - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_create, array( OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run)); + public function file_get_contents($path) { + return $this->basicOperation('file_get_contents', $path, array('read')); + } + public function file_put_contents($path, $data) { + if(is_resource($data)) {//not having to deal with streams in file_put_contents makes life easier + $exists = $this->file_exists($path); + $run = true; + if(!$exists) { + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_create, + array( + OC_Filesystem::signal_param_path => $path, + OC_Filesystem::signal_param_run => &$run + ) + ); } - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_write, array( OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run)); - if(!$run){ + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_write, + array( + OC_Filesystem::signal_param_path => $path, + OC_Filesystem::signal_param_run => &$run + ) + ); + if(!$run) { return false; } - $target=$this->fopen($path,'w'); - if($target){ - $count=OC_Helper::streamCopy($data,$target); + $target=$this->fopen($path, 'w'); + if($target) { + $count=OC_Helper::streamCopy($data, $target); fclose($target); fclose($data); - if(!$exists){ - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_create, array( OC_Filesystem::signal_param_path => $path)); + if(!$exists) { + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_post_create, + array( OC_Filesystem::signal_param_path => $path) + ); } - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_write, array( OC_Filesystem::signal_param_path => $path)); - return $count>0; + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_post_write, + array( OC_Filesystem::signal_param_path => $path) + ); + return $count > 0; }else{ return false; } }else{ - return $this->basicOperation('file_put_contents',$path,array('create','write'),$data); + return $this->basicOperation('file_put_contents', $path, array('create', 'write'), $data); } } - public function unlink($path){ - return $this->basicOperation('unlink',$path,array('delete')); + public function unlink($path) { + return $this->basicOperation('unlink', $path, array('delete')); } public function deleteAll( $directory, $empty = false ) { return $this->basicOperation( 'deleteAll', $directory, array('delete'), $empty ); } - public function rename($path1,$path2){ - $absolutePath1=$this->getAbsolutePath($path1); - $absolutePath2=$this->getAbsolutePath($path2); - if(OC_FileProxy::runPreProxies('rename',$absolutePath1,$absolutePath2) and OC_Filesystem::isValidPath($path2)){ - $path1=$this->getRelativePath($absolutePath1); - $path2=$this->getRelativePath($absolutePath2); - if($path1==null or $path2==null){ + public function rename($path1, $path2) { + $absolutePath1 = $this->getAbsolutePath($path1); + $absolutePath2 = $this->getAbsolutePath($path2); + if(OC_FileProxy::runPreProxies('rename', $absolutePath1, $absolutePath2) and OC_Filesystem::isValidPath($path2)) { + $path1 = $this->getRelativePath($absolutePath1); + $path2 = $this->getRelativePath($absolutePath2); + if($path1 == null or $path2 == null) { return false; } $run=true; - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_rename, array( OC_Filesystem::signal_param_oldpath => $path1 , OC_Filesystem::signal_param_newpath=>$path2, OC_Filesystem::signal_param_run => &$run)); - if($run){ - $mp1=$this->getMountPoint($path1); - $mp2=$this->getMountPoint($path2); - if($mp1==$mp2){ - if($storage=$this->getStorage($path1)){ - $result=$storage->rename($this->getInternalPath($path1),$this->getInternalPath($path2)); + OC_Hook::emit( + OC_Filesystem::CLASSNAME, OC_Filesystem::signal_rename, + array( + OC_Filesystem::signal_param_oldpath => $path1, + OC_Filesystem::signal_param_newpath => $path2, + OC_Filesystem::signal_param_run => &$run + ) + ); + if($run) { + $mp1 = $this->getMountPoint($path1); + $mp2 = $this->getMountPoint($path2); + if($mp1 == $mp2) { + if($storage = $this->getStorage($path1)) { + $result = $storage->rename($this->getInternalPath($path1), $this->getInternalPath($path2)); } - }else{ - $source=$this->fopen($path1,'r'); - $target=$this->fopen($path2,'w'); - $count=OC_Helper::streamCopy($source,$target); - $storage1=$this->getStorage($path1); + } else { + $source = $this->fopen($path1, 'r'); + $target = $this->fopen($path2, 'w'); + $count = OC_Helper::streamCopy($source, $target); + $storage1 = $this->getStorage($path1); $storage1->unlink($this->getInternalPath($path1)); - $result=$count>0; + $result = $count>0; } - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_rename, array( OC_Filesystem::signal_param_oldpath => $path1, OC_Filesystem::signal_param_newpath=>$path2)); + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_post_rename, + array( + OC_Filesystem::signal_param_oldpath => $path1, + OC_Filesystem::signal_param_newpath => $path2 + ) + ); return $result; } } } - public function copy($path1,$path2){ - $absolutePath1=$this->getAbsolutePath($path1); - $absolutePath2=$this->getAbsolutePath($path2); - if(OC_FileProxy::runPreProxies('copy',$absolutePath1,$absolutePath2) and OC_Filesystem::isValidPath($path2)){ - $path1=$this->getRelativePath($absolutePath1); - $path2=$this->getRelativePath($absolutePath2); - if($path1==null or $path2==null){ + public function copy($path1, $path2) { + $absolutePath1 = $this->getAbsolutePath($path1); + $absolutePath2 = $this->getAbsolutePath($path2); + if(OC_FileProxy::runPreProxies('copy', $absolutePath1, $absolutePath2) and OC_Filesystem::isValidPath($path2)) { + $path1 = $this->getRelativePath($absolutePath1); + $path2 = $this->getRelativePath($absolutePath2); + if($path1 == null or $path2 == null) { return false; } $run=true; - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_copy, array( OC_Filesystem::signal_param_oldpath => $path1 , OC_Filesystem::signal_param_newpath=>$path2, OC_Filesystem::signal_param_run => &$run)); + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_copy, + array( + OC_Filesystem::signal_param_oldpath => $path1, + OC_Filesystem::signal_param_newpath=>$path2, + OC_Filesystem::signal_param_run => &$run + ) + ); $exists=$this->file_exists($path2); - if($run and !$exists){ - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_create, array( OC_Filesystem::signal_param_path => $path2, OC_Filesystem::signal_param_run => &$run)); + if($run and !$exists) { + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_create, + array( + OC_Filesystem::signal_param_path => $path2, + OC_Filesystem::signal_param_run => &$run + ) + ); } - if($run){ - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_write, array( OC_Filesystem::signal_param_path => $path2, OC_Filesystem::signal_param_run => &$run)); + if($run) { + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_write, + array( + OC_Filesystem::signal_param_path => $path2, + OC_Filesystem::signal_param_run => &$run + ) + ); } - if($run){ + if($run) { $mp1=$this->getMountPoint($path1); $mp2=$this->getMountPoint($path2); - if($mp1==$mp2){ - if($storage=$this->getStorage($path1)){ - $result=$storage->copy($this->getInternalPath($path1),$this->getInternalPath($path2)); + if($mp1 == $mp2){ + if($storage = $this->getStorage($path1)) { + $result=$storage->copy($this->getInternalPath($path1), $this->getInternalPath($path2)); } - }else{ - $source=$this->fopen($path1,'r'); - $target=$this->fopen($path2,'w'); - $result=OC_Helper::streamCopy($source,$target); + } else { + $source = $this->fopen($path1, 'r'); + $target = $this->fopen($path2, 'w'); + $result = OC_Helper::streamCopy($source, $target); } - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_copy, array( OC_Filesystem::signal_param_oldpath => $path1 , OC_Filesystem::signal_param_newpath=>$path2)); - if(!$exists){ - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_create, array( OC_Filesystem::signal_param_path => $path2)); + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_post_copy, + array( + OC_Filesystem::signal_param_oldpath => $path1, + OC_Filesystem::signal_param_newpath=>$path2 + ) + ); + if(!$exists) { + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_post_create, + array(OC_Filesystem::signal_param_path => $path2) + ); } - OC_Hook::emit( OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_write, array( OC_Filesystem::signal_param_path => $path2)); + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + OC_Filesystem::signal_post_write, + array( OC_Filesystem::signal_param_path => $path2) + ); return $result; } } } - public function fopen($path,$mode){ + public function fopen($path, $mode) { $hooks=array(); - switch($mode){ + switch($mode) { case 'r': case 'rb': $hooks[]='read'; @@ -355,49 +428,49 @@ class OC_FilesystemView { OC_Log::write('core','invalid mode ('.$mode.') for '.$path,OC_Log::ERROR); } - return $this->basicOperation('fopen',$path,$hooks,$mode); + return $this->basicOperation('fopen', $path, $hooks, $mode); } - public function toTmpFile($path){ - if(OC_Filesystem::isValidPath($path)){ - $source=$this->fopen($path,'r'); - if($source){ + public function toTmpFile($path) { + if(OC_Filesystem::isValidPath($path)) { + $source = $this->fopen($path, 'r'); + if($source) { $extension=''; - $extOffset=strpos($path,'.'); + $extOffset=strpos($path, '.'); if($extOffset !== false) { - $extension=substr($path,strrpos($path,'.')); + $extension=substr($path, strrpos($path,'.')); } - $tmpFile=OC_Helper::tmpFile($extension); - file_put_contents($tmpFile,$source); + $tmpFile = OC_Helper::tmpFile($extension); + file_put_contents($tmpFile, $source); return $tmpFile; } } } - public function fromTmpFile($tmpFile,$path){ - if(OC_Filesystem::isValidPath($path)){ - if(!$tmpFile){ + public function fromTmpFile($tmpFile, $path) { + if(OC_Filesystem::isValidPath($path)) { + if(!$tmpFile) { debug_print_backtrace(); } - $source=fopen($tmpFile,'r'); - if($source){ - $this->file_put_contents($path,$source); + $source=fopen($tmpFile, 'r'); + if($source) { + $this->file_put_contents($path, $source); unlink($tmpFile); return true; - }else{ + } else { } - }else{ + } else { return false; } } - public function getMimeType($path){ - return $this->basicOperation('getMimeType',$path); + public function getMimeType($path) { + return $this->basicOperation('getMimeType', $path); } - public function hash($type,$path){ - return $this->basicOperation('hash',$path,array('read'),$type); + public function hash($type, $path) { + return $this->basicOperation('hash', $path, array('read'), $type); } - public function free_space($path='/'){ - return $this->basicOperation('free_space',$path); + public function free_space($path='/') { + return $this->basicOperation('free_space', $path); } /** @@ -407,41 +480,56 @@ class OC_FilesystemView { * @param array (optional) hooks * @param mixed (optional) $extraParam * @return mixed - * - * This method takes requests for basic filesystem functions (e.g. reading & writing - * files), processes hooks and proxies, sanitises paths, and finally passes them on to + * + * This method takes requests for basic filesystem functions (e.g. reading & writing + * files), processes hooks and proxies, sanitises paths, and finally passes them on to * OC_Filestorage for delegation to a storage backend for execution */ - private function basicOperation($operation,$path,$hooks=array(),$extraParam=null){ - $absolutePath=$this->getAbsolutePath($path); - if(OC_FileProxy::runPreProxies($operation,$absolutePath, $extraParam) and OC_Filesystem::isValidPath($path)){ - $path=$this->getRelativePath($absolutePath); - if($path==null){ + private function basicOperation($operation, $path, $hooks=array(), $extraParam=null) { + $absolutePath = $this->getAbsolutePath($path); + if(OC_FileProxy::runPreProxies($operation, $absolutePath, $extraParam) and OC_Filesystem::isValidPath($path)) { + $path = $this->getRelativePath($absolutePath); + if($path == null) { return false; } - $internalPath=$this->getInternalPath($path); - $run=true; - if(OC_Filesystem::$loaded and $this->fakeRoot==OC_Filesystem::getRoot()){ - foreach($hooks as $hook){ - if($hook!='read'){ - OC_Hook::emit( OC_Filesystem::CLASSNAME, $hook, array( OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run)); - }else{ - OC_Hook::emit( OC_Filesystem::CLASSNAME, $hook, array( OC_Filesystem::signal_param_path => $path)); + $internalPath = $this->getInternalPath($path); + $run = true; + if(OC_Filesystem::$loaded and $this->fakeRoot==OC_Filesystem::getRoot()) { + foreach($hooks as $hook) { + if($hook!='read') { + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + $hook, + array( + OC_Filesystem::signal_param_path => $path, + OC_Filesystem::signal_param_run => &$run + ) + ); + } else { + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + $hook, + array( OC_Filesystem::signal_param_path => $path) + ); } } } - if($run and $storage=$this->getStorage($path)){ - if(!is_null($extraParam)){ - $result=$storage->$operation($internalPath,$extraParam); - }else{ - $result=$storage->$operation($internalPath); + if($run and $storage = $this->getStorage($path)) { + if(!is_null($extraParam)) { + $result = $storage->$operation($internalPath, $extraParam); + } else { + $result = $storage->$operation($internalPath); } - $result=OC_FileProxy::runPostProxies($operation,$this->getAbsolutePath($path),$result); - if(OC_Filesystem::$loaded and $this->fakeRoot==OC_Filesystem::getRoot()){ - if($operation!='fopen'){//no post hooks for fopen, the file stream is still open - foreach($hooks as $hook){ + $result = OC_FileProxy::runPostProxies($operation, $this->getAbsolutePath($path), $result); + if(OC_Filesystem::$loaded and $this->fakeRoot==OC_Filesystem::getRoot()) { + if($operation!='fopen') {//no post hooks for fopen, the file stream is still open + foreach($hooks as $hook) { if($hook!='read'){ - OC_Hook::emit( OC_Filesystem::CLASSNAME, 'post_'.$hook, array( OC_Filesystem::signal_param_path => $path)); + OC_Hook::emit( + OC_Filesystem::CLASSNAME, + 'post_'.$hook, + array( OC_Filesystem::signal_param_path => $path) + ); } } } @@ -457,7 +545,7 @@ class OC_FilesystemView { * @param int $time * @return bool */ - public function hasUpdated($path,$time){ - return $this->basicOperation('hasUpdated',$path,array(),$time); + public function hasUpdated($path, $time) { + return $this->basicOperation('hasUpdated', $path, array(), $time); } } diff --git a/lib/helper.php b/lib/helper.php index c4f7e8b2e19..f328c14ac77 100644 --- a/lib/helper.php +++ b/lib/helper.php @@ -175,10 +175,8 @@ class OC_Helper { */ public static function mimetypeIcon( $mimetype ){ $alias=array('application/xml'=>'code/xml'); -// echo $mimetype; if(isset($alias[$mimetype])){ $mimetype=$alias[$mimetype]; -// echo $mimetype; } // Replace slash with a minus $mimetype = str_replace( "/", "-", $mimetype ); @@ -345,18 +343,24 @@ class OC_Helper { */ static function getMimeType($path){ $isWrapped=(strpos($path,'://')!==false) and (substr($path,0,7)=='file://'); - $mimeType='application/octet-stream'; - if ($mimeType=='application/octet-stream') { - self::$mimetypes = include('mimetypes.fixlist.php'); - $extension=strtolower(strrchr(basename($path), ".")); - $extension=substr($extension,1);//remove leading . - $mimeType=(isset(self::$mimetypes[$extension]))?self::$mimetypes[$extension]:'application/octet-stream'; - } if (@is_dir($path)) { // directories are easy return "httpd/unix-directory"; } + + if(strpos($path,'.')){ + //try to guess the type by the file extension + if(!self::$mimetypes || self::$mimetypes != include('mimetypes.list.php')){ + self::$mimetypes=include('mimetypes.list.php'); + } + $extension=strtolower(strrchr(basename($path), ".")); + $extension=substr($extension,1);//remove leading . + $mimeType=(isset(self::$mimetypes[$extension]))?self::$mimetypes[$extension]:'application/octet-stream'; + }else{ + $mimeType='application/octet-stream'; + } + if($mimeType=='application/octet-stream' and function_exists('finfo_open') and function_exists('finfo_file') and $finfo=finfo_open(FILEINFO_MIME)){ $info = @strtolower(finfo_file($finfo,$path)); if($info){ @@ -385,15 +389,6 @@ class OC_Helper { } } - if ($mimeType=='application/octet-stream') { - // Fallback solution: (try to guess the type by the file extension - if(!self::$mimetypes || self::$mimetypes != include('mimetypes.list.php')){ - self::$mimetypes=include('mimetypes.list.php'); - } - $extension=strtolower(strrchr(basename($path), ".")); - $extension=substr($extension,1);//remove leading . - $mimeType=(isset(self::$mimetypes[$extension]))?self::$mimetypes[$extension]:'application/octet-stream'; - } return $mimeType; } diff --git a/lib/image.php b/lib/image.php index c438b3d67f6..90c64320a7c 100644 --- a/lib/image.php +++ b/lib/image.php @@ -23,12 +23,12 @@ //From user comments at http://dk2.php.net/manual/en/function.exif-imagetype.php if ( ! function_exists( 'exif_imagetype' ) ) { - function exif_imagetype ( $filename ) { - if ( ( $info = getimagesize( $filename ) ) !== false ) { - return $info[2]; - } - return false; - } + function exif_imagetype ( $filename ) { + if ( ( $info = getimagesize( $filename ) ) !== false ) { + return $info[2]; + } + return false; + } } function ellipsis($str, $maxlen) { @@ -66,7 +66,6 @@ class OC_Image { public function __construct($imageref = null) { //OC_Log::write('core',__METHOD__.'(): start', OC_Log::DEBUG); if(!extension_loaded('gd') || !function_exists('gd_info')) { - //if(!function_exists('imagecreatefromjpeg')) { OC_Log::write('core',__METHOD__.'(): GD module not installed', OC_Log::ERROR); return false; } diff --git a/lib/installer.php b/lib/installer.php index 00feb6d4709..a8b56cb34f2 100644 --- a/lib/installer.php +++ b/lib/installer.php @@ -126,19 +126,19 @@ class OC_Installer{ return false; } $info=OC_App::getAppInfo($extractDir.'/appinfo/info.xml',true); - // check the code for not allowed calls - if(!OC_Installer::checkCode($info['id'],$extractDir)){ + // check the code for not allowed calls + if(!OC_Installer::checkCode($info['id'],$extractDir)){ OC_Log::write('core','App can\'t be installed because of not allowed code in the App',OC_Log::ERROR); OC_Helper::rmdirr($extractDir); - return false; + return false; } - // check if the app is compatible with this version of ownCloud + // check if the app is compatible with this version of ownCloud $version=OC_Util::getVersion(); - if(!isset($info['require']) or ($version[0]>$info['require'])){ + if(!isset($info['require']) or ($version[0]>$info['require'])){ OC_Log::write('core','App can\'t be installed because it is not compatible with this version of ownCloud',OC_Log::ERROR); OC_Helper::rmdirr($extractDir); - return false; + return false; } //check if an app with the same id is already installed @@ -339,12 +339,12 @@ class OC_Installer{ } - /** - * check the code of an app with some static code checks - * @param string $folder the folder of the app to check - * @returns true for app is o.k. and false for app is not o.k. - */ - public static function checkCode($appname,$folder){ + /** + * check the code of an app with some static code checks + * @param string $folder the folder of the app to check + * @returns true for app is o.k. and false for app is not o.k. + */ + public static function checkCode($appname,$folder){ $blacklist=array( 'exec(', @@ -377,9 +377,7 @@ class OC_Installer{ return true; }else{ - return true; + return true; } - } - - + } } diff --git a/lib/json.php b/lib/json.php index c49b831c12b..b46878375d5 100644 --- a/lib/json.php +++ b/lib/json.php @@ -94,12 +94,12 @@ class OC_JSON{ * Encode and print $data in json format */ public static function encodedPrint($data,$setContentType=true){ - // Disable mimesniffing, don't move this to setContentTypeHeader! - header( 'X-Content-Type-Options: nosniff' ); - if($setContentType){ - self::setContentTypeHeader(); - } - array_walk_recursive($data, array('OC_JSON', 'to_string')); - echo json_encode($data); + // Disable mimesniffing, don't move this to setContentTypeHeader! + header( 'X-Content-Type-Options: nosniff' ); + if($setContentType){ + self::setContentTypeHeader(); + } + array_walk_recursive($data, array('OC_JSON', 'to_string')); + echo json_encode($data); } } diff --git a/lib/mimetypes.fixlist.php b/lib/mimetypes.fixlist.php deleted file mode 100644 index 13e3f16b369..00000000000 --- a/lib/mimetypes.fixlist.php +++ /dev/null @@ -1,22 +0,0 @@ -<?php -return array( - 'ics'=>'text/calendar', - 'ical'=>'text/calendar', - 'js'=>'application/javascript', - 'odt'=>'application/vnd.oasis.opendocument.text', - 'ods'=>'application/vnd.oasis.opendocument.spreadsheet', - 'odg'=>'application/vnd.oasis.opendocument.graphics', - 'odp'=>'application/vnd.oasis.opendocument.presentation', - 'pl'=>'text/x-script.perl', - 'py'=>'text/x-script.phyton', - 'vcf' => 'text/vcard', - 'vcard' => 'text/vcard', - 'doc'=>'application/msword', - 'docx'=>'application/msword', - 'xls'=>'application/msexcel', - 'xlsx'=>'application/msexcel', - 'ppt'=>'application/mspowerpoint', - 'pptx'=>'application/mspowerpoint', - 'sgf' => 'application/sgf', - 'cdr' => 'application/coreldraw' -); diff --git a/lib/mimetypes.list.php b/lib/mimetypes.list.php index ccf47999b1c..f7207493f7f 100644 --- a/lib/mimetypes.list.php +++ b/lib/mimetypes.list.php @@ -78,5 +78,16 @@ return array( 'mpeg'=>'video/mpeg', 'mov'=>'video/quicktime', 'webm'=>'video/webm', - 'wmv'=>'video/x-ms-asf' + 'wmv'=>'video/x-ms-asf', + 'py'=>'text/x-script.phyton', + 'vcf' => 'text/vcard', + 'vcard' => 'text/vcard', + 'doc'=>'application/msword', + 'docx'=>'application/msword', + 'xls'=>'application/msexcel', + 'xlsx'=>'application/msexcel', + 'ppt'=>'application/mspowerpoint', + 'pptx'=>'application/mspowerpoint', + 'sgf' => 'application/sgf', + 'cdr' => 'application/coreldraw', ); diff --git a/lib/minimizer.php b/lib/minimizer.php index 3bf5ff9980b..3dc89e331a6 100644 --- a/lib/minimizer.php +++ b/lib/minimizer.php @@ -46,3 +46,13 @@ abstract class OC_Minimizer { echo $out; } } + +if (!function_exists('gzdecode')) { + function gzdecode($data,$maxlength=null,&$filename='',&$error='') + { + if (strcmp(substr($data,0,9),"\x1f\x8b\x8\0\0\0\0\0\0")) { + return null; // Not the GZIP format we expect (See RFC 1952) + } + return gzinflate(substr($data,10,-8)); + } +} diff --git a/lib/ocs.php b/lib/ocs.php index 27007076661..18f01518bdb 100644 --- a/lib/ocs.php +++ b/lib/ocs.php @@ -4,7 +4,9 @@ * ownCloud * * @author Frank Karlitschek +* @author Michael Gapczynski * @copyright 2012 Frank Karlitschek frank@owncloud.org +* @copyright 2012 Michael Gapczynski mtgap@owncloud.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE @@ -27,431 +29,476 @@ */ class OC_OCS { - /** - * reads input date from get/post/cookies and converts the date to a special data-type - * - * @param variable $key - * @param variable-type $type - * @param priority $getpriority - * @param default $default - * @return data - */ - public static function readData($key,$type='raw',$getpriority=false,$default='') { - if($getpriority) { - if(isset($_GET[$key])) { - $data=$_GET[$key]; - } elseif(isset($_POST[$key])) { - $data=$_POST[$key]; - } else { - if($default=='') { - if(($type=='int') or ($type=='float')) $data=0; else $data=''; - } else { - $data=$default; - } - } - } else { - if(isset($_POST[$key])) { - $data=$_POST[$key]; - } elseif(isset($_GET[$key])) { - $data=$_GET[$key]; - } elseif(isset($_COOKIE[$key])) { - $data=$_COOKIE[$key]; - } else { - if($default=='') { - if(($type=='int') or ($type=='float')) $data=0; else $data=''; - } else { - $data=$default; - } - } - } - - if($type=='raw') return($data); - elseif($type=='text') return(addslashes(strip_tags($data))); - elseif($type=='int') { $data = (int) $data; return($data); } - elseif($type=='float') { $data = (float) $data; return($data); } - elseif($type=='array') { $data = $data; return($data); } - } - - - /** - main function to handle the REST request - **/ - public static function handle() { - - // overwrite the 404 error page returncode - header("HTTP/1.0 200 OK"); - - $router = new OC_Router(); - $router->useCollection('ocs'); - // CONFIG - $router->create('config', '/config.{format}') - ->defaults(array('format'=>'')) - ->action('OC_OCS', 'apiConfig') - ->requirements(array('format'=>'xml|json')); - - // PERSON - $router->create('person_check', '/person/check.{format}') - ->post() - ->defaults(array('format'=>'')) - ->action(function ($parameters) { - $format = $parameters['format'] ? $parameters['format'] : OC_OCS::readdata('format','text'); - $login=OC_OCS::readdata('login','text'); - $passwd=OC_OCS::readdata('password','text'); - OC_OCS::personcheck($format,$login,$passwd); - }) - ->requirements(array('format'=>'xml|json')); - - // ACTIVITY - // activityget - GET ACTIVITY page,pagesize als urlparameter - $router->create('activity_get', '/activity.{format}') - ->defaults(array('format'=>'')) - ->action(function ($parameters) { - $format = $parameters['format'] ? $parameters['format'] : OC_OCS::readdata('format','text'); - $page=OC_OCS::readdata('page','int'); - $pagesize=OC_OCS::readdata('pagesize','int'); - if($pagesize<1 or $pagesize>100) $pagesize=10; - OC_OCS::activityget($format,$page,$pagesize); - }) - ->requirements(array('format'=>'xml|json')); - // activityput - POST ACTIVITY - $router->create('activity_put', '/activity.{format}') - ->post() - ->defaults(array('format'=>'')) - ->action(function ($parameters) { - $format = $parameters['format'] ? $parameters['format'] : OC_OCS::readdata('format','text'); - $message=OC_OCS::readdata('message','text'); - OC_OCS::activityput($format,$message); - }) - ->requirements(array('format'=>'xml|json')); - - // PRIVATEDATA - // get - GET DATA - $router->create('privatedata_get', - '/privatedata/getattribute/{app}/{key}.{format}') - ->defaults(array('app' => '', 'key' => '', 'format' => '')) - ->action(function ($parameters) { - $format = $parameters['format'] ? $parameters['format'] : OC_OCS::readdata('format','text'); - $app = addslashes(strip_tags($parameters['app'])); - $key = addslashes(strip_tags($parameters['key'])); - OC_OCS::privateDataGet($format, $app, $key); - }) - ->requirements(array('format'=>'xml|json')); - // set - POST DATA - $router->create('privatedata_set', - '/privatedata/setattribute/{app}/{key}.{format}') - ->post() - ->defaults(array('format'=>'')) - ->action(function ($parameters) { - $format = $parameters['format'] ? $parameters['format'] : OC_OCS::readdata('format','text'); - $app = addslashes(strip_tags($parameters['app'])); - $key = addslashes(strip_tags($parameters['key'])); - $value=OC_OCS::readdata('value','text'); - OC_OCS::privateDataSet($format, $app, $key, $value); - }) - ->requirements(array('format'=>'xml|json')); - // delete - POST DATA - $router->create('privatedata_delete', - '/privatedata/deleteattribute/{app}/{key}.{format}') - ->post() - ->defaults(array('format'=>'')) - ->action(function ($parameters) { - $format = $parameters['format'] ? $parameters['format'] : OC_OCS::readdata('format','text'); - $app = addslashes(strip_tags($parameters['app'])); - $key = addslashes(strip_tags($parameters['key'])); - OC_OCS::privateDataDelete($format, $app, $key); - }) - ->requirements(array('format'=>'xml|json')); - - try { - $router->match($_SERVER['PATH_INFO']); - } catch (ResourceNotFoundException $e) { - $format=OC_OCS::readdata('format','text'); - $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n"; - $txt.=OC_OCS::getdebugoutput(); - echo(OC_OCS::generatexml($format,'failed',999,$txt)); - } - exit(); - } - - /** - * generated some debug information to make it easier to find faild API calls - * @return debug data string - */ - private static function getDebugOutput() { - $txt=''; - $txt.="debug output:\n"; - if(isset($_SERVER['REQUEST_METHOD'])) $txt.='http request method: '.$_SERVER['REQUEST_METHOD']."\n"; - if(isset($_SERVER['REQUEST_URI'])) $txt.='http request uri: '.$_SERVER['REQUEST_URI']."\n"; - if(isset($_GET)) foreach($_GET as $key=>$value) $txt.='get parameter: '.$key.'->'.$value."\n"; - if(isset($_POST)) foreach($_POST as $key=>$value) $txt.='post parameter: '.$key.'->'.$value."\n"; - return($txt); - } - - /** - * checks if the user is authenticated - * checks the IP whitlist, apikeys and login/password combination - * if $forceuser is true and the authentication failed it returns an 401 http response. - * if $forceuser is false and authentification fails it returns an empty username string - * @param bool $forceuser - * @return username string - */ - private static function checkPassword($forceuser=true) { - //valid user account ? - if(isset($_SERVER['PHP_AUTH_USER'])) $authuser=$_SERVER['PHP_AUTH_USER']; else $authuser=''; - if(isset($_SERVER['PHP_AUTH_PW'])) $authpw=$_SERVER['PHP_AUTH_PW']; else $authpw=''; - - if(empty($authuser)) { - if($forceuser){ - header('WWW-Authenticate: Basic realm="your valid user account or api key"'); - header('HTTP/1.0 401 Unauthorized'); - exit; - }else{ - $identifieduser=''; - } - }else{ - if(!OC_User::login($authuser,$authpw)){ - if($forceuser){ - header('WWW-Authenticate: Basic realm="your valid user account or api key"'); - header('HTTP/1.0 401 Unauthorized'); - exit; - }else{ - $identifieduser=''; - } - }else{ - $identifieduser=$authuser; - } - } - - return($identifieduser); - } - - - /** - * generates the xml or json response for the API call from an multidimenional data array. - * @param string $format - * @param string $status - * @param string $statuscode - * @param string $message - * @param array $data - * @param string $tag - * @param string $tagattribute - * @param int $dimension - * @param int $itemscount - * @param int $itemsperpage - * @return string xml/json - */ - private static function generateXml($format,$status,$statuscode,$message,$data=array(),$tag='',$tagattribute='',$dimension=-1,$itemscount='',$itemsperpage='') { - if($format=='json') { - - $json=array(); - $json['status']=$status; - $json['statuscode']=$statuscode; - $json['message']=$message; - $json['totalitems']=$itemscount; - $json['itemsperpage']=$itemsperpage; - $json['data']=$data; - return(json_encode($json)); - - - }else{ - $txt=''; - $writer = xmlwriter_open_memory(); - xmlwriter_set_indent( $writer, 2 ); - xmlwriter_start_document($writer ); - xmlwriter_start_element($writer,'ocs'); - xmlwriter_start_element($writer,'meta'); - xmlwriter_write_element($writer,'status',$status); - xmlwriter_write_element($writer,'statuscode',$statuscode); - xmlwriter_write_element($writer,'message',$message); - if($itemscount<>'') xmlwriter_write_element($writer,'totalitems',$itemscount); - if(!empty($itemsperpage)) xmlwriter_write_element($writer,'itemsperpage',$itemsperpage); - xmlwriter_end_element($writer); - if($dimension=='0') { - // 0 dimensions - xmlwriter_write_element($writer,'data',$data); - - }elseif($dimension=='1') { - xmlwriter_start_element($writer,'data'); - foreach($data as $key=>$entry) { - xmlwriter_write_element($writer,$key,$entry); - } - xmlwriter_end_element($writer); - - }elseif($dimension=='2') { - xmlwriter_start_element($writer,'data'); - foreach($data as $entry) { - xmlwriter_start_element($writer,$tag); - if(!empty($tagattribute)) { - xmlwriter_write_attribute($writer,'details',$tagattribute); - } - foreach($entry as $key=>$value) { - if(is_array($value)){ - foreach($value as $k=>$v) { - xmlwriter_write_element($writer,$k,$v); - } - } else { - xmlwriter_write_element($writer,$key,$value); - } - } - xmlwriter_end_element($writer); - } - xmlwriter_end_element($writer); - - }elseif($dimension=='3') { - xmlwriter_start_element($writer,'data'); - foreach($data as $entrykey=>$entry) { - xmlwriter_start_element($writer,$tag); - if(!empty($tagattribute)) { - xmlwriter_write_attribute($writer,'details',$tagattribute); - } - foreach($entry as $key=>$value) { - if(is_array($value)){ - xmlwriter_start_element($writer,$entrykey); - foreach($value as $k=>$v) { - xmlwriter_write_element($writer,$k,$v); - } - xmlwriter_end_element($writer); - } else { - xmlwriter_write_element($writer,$key,$value); - } - } - xmlwriter_end_element($writer); - } - xmlwriter_end_element($writer); - }elseif($dimension=='dynamic') { - xmlwriter_start_element($writer,'data'); - OC_OCS::toxml($writer,$data,'comment'); - xmlwriter_end_element($writer); - } - - xmlwriter_end_element($writer); - - xmlwriter_end_document( $writer ); - $txt.=xmlwriter_output_memory( $writer ); - unset($writer); - return($txt); - } - } - - public static function toXml($writer,$data,$node) { - foreach($data as $key => $value) { - if (is_numeric($key)) { - $key = $node; - } - if (is_array($value)){ - xmlwriter_start_element($writer,$key); - OC_OCS::toxml($writer,$value,$node); - xmlwriter_end_element($writer); - }else{ - xmlwriter_write_element($writer,$key,$value); - } - - } - } - - - - - /** - * return the config data of this server - * @param string $format - * @return string xml/json - */ - public static function apiConfig($parameters) { - $format = $parameters['format'] ? $parameters['format'] : OC_OCS::readdata('format','text'); - $xml['version']='1.5'; - $xml['website']='ownCloud'; - $xml['host']=OCP\Util::getServerHost(); - $xml['contact']=''; - $xml['ssl']='false'; - echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'config','',1)); - } - - - /** - * check if the provided login/apikey/password is valid - * @param string $format - * @param string $login - * @param string $passwd - * @return string xml/json - */ - private static function personCheck($format,$login,$passwd) { - if($login<>''){ - if(OC_User::login($login,$passwd)){ - $xml['person']['personid']=$login; - echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'person','check',2)); - }else{ - echo(OC_OCS::generatexml($format,'failed',102,'login not valid')); - } - }else{ - echo(OC_OCS::generatexml($format,'failed',101,'please specify all mandatory fields')); - } - } - - - - // ACTIVITY API ############################################# - - /** - * get my activities - * @param string $format - * @param string $page - * @param string $pagesize - * @return string xml/json - */ - private static function activityGet($format,$page,$pagesize) { - $user=OC_OCS::checkpassword(); - - //TODO - - $txt=OC_OCS::generatexml($format,'ok',100,'',$xml,'activity','full',2,$totalcount,$pagesize); - echo($txt); - } - - /** - * submit a activity - * @param string $format - * @param string $message - * @return string xml/json - */ - private static function activityPut($format,$message) { - // not implemented in ownCloud - OC_OCS::checkpassword(); - echo(OC_OCS::generatexml($format,'ok',100,'')); - } - - // PRIVATEDATA API ############################################# - - /** - * get private data and create the xml for ocs - * @param string $format - * @param string $app - * @param string $key - * @return string xml/json - */ - private static function privateDataGet($format,$app="",$key="") { - $user=OC_OCS::checkpassword(); - $result=OC_OCS::getData($user,$app,$key); - $xml=array(); - foreach($result as $i=>$log) { - $xml[$i]['key']=$log['key']; - $xml[$i]['app']=$log['app']; - $xml[$i]['value']=$log['value']; - } - - - $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'privatedata', 'full', 2, count($xml), 0);//TODO: replace 'privatedata' with 'attribute' once a new libattice has been released that works with it - echo($txt); - } - - /** - * set private data referenced by $key to $value and generate the xml for ocs - * @param string $format - * @param string $app - * @param string $key - * @param string $value - * @return string xml/json - */ + /** + * reads input date from get/post/cookies and converts the date to a special data-type + * + * @param string HTTP method to read the key from + * @param string Parameter to read + * @param string Variable type to format data + * @param mixed Default value to return if the key is not found + * @return mixed Data or if the key is not found and no default is set it will exit with a 400 Bad request + */ + public static function readData($method, $key, $type = 'raw', $default = null) { + if ($method == 'get') { + if (isset($_GET[$key])) { + $data = $_GET[$key]; + } else if (isset($default)) { + return $default; + } else { + $data = false; + } + } else if ($method == 'post') { + if (isset($_POST[$key])) { + $data = $_POST[$key]; + } else if (isset($default)) { + return $default; + } else { + $data = false; + } + } + if ($data === false) { + echo self::generateXml('', 'fail', 400, 'Bad request. Please provide a valid '.$key); + exit(); + } else { + // NOTE: Is the raw type necessary? It might be a little risky without sanitization + if ($type == 'raw') return $data; + elseif ($type == 'text') return OC_Util::sanitizeHTML($data); + elseif ($type == 'int') return (int) $data; + elseif ($type == 'float') return (float) $data; + elseif ($type == 'array') return OC_Util::sanitizeHTML($data); + else return OC_Util::sanitizeHTML($data); + } + } + + /** + main function to handle the REST request + **/ + public static function handle() { + // overwrite the 404 error page returncode + header("HTTP/1.0 200 OK"); + + + if($_SERVER['REQUEST_METHOD'] == 'GET') { + $method='get'; + }elseif($_SERVER['REQUEST_METHOD'] == 'PUT') { + $method='put'; + parse_str(file_get_contents("php://input"),$put_vars); + }elseif($_SERVER['REQUEST_METHOD'] == 'POST') { + $method='post'; + }else{ + echo('internal server error: method not supported'); + exit(); + } + + // preprocess url + $url = strtolower($_SERVER['REQUEST_URI']); + $format = self::readData($method, 'format', 'text', ''); + + $router = new OC_Router(); + $router->useCollection('ocs'); + // CONFIG + $router->create('config', '/config.{format}') + ->defaults(array('format' => $format)) + ->action('OC_OCS', 'apiConfig') + ->requirements(array('format'=>'xml|json')); + + // PERSON + $router->create('person_check', '/person/check.{format}') + ->post() + ->defaults(array('format' => $format)) + ->action(function ($parameters) { + $format = $parameters['format']; + $login = OC_OCS::readData('post', 'login', 'text'); + $passwd = OC_OCS::readData('post', 'password', 'text'); + OC_OCS::personCheck($format,$login,$passwd); + }) + ->requirements(array('format'=>'xml|json')); + + // ACTIVITY + // activityget - GET ACTIVITY page,pagesize als urlparameter + $router->create('activity_get', '/activity.{format}') + ->defaults(array('format' => $format)) + ->action(function ($parameters) { + $format = $parameters['format']; + $page = OC_OCS::readData('get', 'page', 'int', 0); + $pagesize = OC_OCS::readData('get', 'pagesize', 'int', 10); + if($pagesize<1 or $pagesize>100) $pagesize=10; + OC_OCS::activityGet($format, $page, $pagesize); + }) + ->requirements(array('format'=>'xml|json')); + // activityput - POST ACTIVITY + $router->create('activity_put', '/activity.{format}') + ->post() + ->defaults(array('format' => $format)) + ->action(function ($parameters) { + $format = $parameters['format']; + $message = OC_OCS::readData('post', 'message', 'text'); + OC_OCS::activityPut($format,$message); + }) + ->requirements(array('format'=>'xml|json')); + + // PRIVATEDATA + // get - GET DATA + $router->create('privatedata_get', + '/privatedata/getattribute/{app}/{key}.{format}') + ->defaults(array('app' => '', 'key' => '', 'format' => $format)) + ->action(function ($parameters) { + $format = $parameters['format']; + $app = addslashes(strip_tags($parameters['app'])); + $key = addslashes(strip_tags($parameters['key'])); + OC_OCS::privateDataGet($format, $app, $key); + }) + ->requirements(array('format'=>'xml|json')); + // set - POST DATA + $router->create('privatedata_set', + '/privatedata/setattribute/{app}/{key}.{format}') + ->post() + ->defaults(array('format' => $format)) + ->action(function ($parameters) { + $format = $parameters['format']; + $app = addslashes(strip_tags($parameters['app'])); + $key = addslashes(strip_tags($parameters['key'])); + $value=OC_OCS::readData('post', 'value', 'text'); + OC_OCS::privateDataSet($format, $app, $key, $value); + }) + ->requirements(array('format'=>'xml|json')); + // delete - POST DATA + $router->create('privatedata_delete', + '/privatedata/deleteattribute/{app}/{key}.{format}') + ->post() + ->defaults(array('format' => $format)) + ->action(function ($parameters) { + $format = $parameters['format']; + $app = addslashes(strip_tags($parameters['app'])); + $key = addslashes(strip_tags($parameters['key'])); + OC_OCS::privateDataDelete($format, $app, $key); + }) + ->requirements(array('format'=>'xml|json')); + + // CLOUD + // quotaget + $router->create('quota_get', + '/cloud/user/{user}.{format}') + ->defaults(array('format' => $format)) + ->action(function ($parameters) { + $format = $parameters['format']; + $user = $parameters['user']; + OC_OCS::quotaGet($format, $user); + }) + ->requirements(array('format'=>'xml|json')); + // quotaset + $router->create('quota_set', + '/cloud/user/{user}.{format}') + ->post() + ->defaults(array('format' => $format)) + ->action(function ($parameters) { + $format = $parameters['format']; + $user = $parameters['user']; + $quota = self::readData('post', 'quota', 'int'); + OC_OCS::quotaSet($format, $user, $quota); + }) + ->requirements(array('format'=>'xml|json')); + + +// add more calls here +// please document all the call in the draft spec +// http://www.freedesktop.org/wiki/Specifications/open-collaboration-services-1.7#CLOUD + +// TODO: +// users +// groups +// bookmarks +// sharing +// versioning +// news (rss) + try { + $router->match($_SERVER['PATH_INFO']); + } catch (ResourceNotFoundException $e) { + $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n"; + $txt.=OC_OCS::getdebugoutput(); + echo(OC_OCS::generatexml($format,'failed',999,$txt)); + } + exit(); + } + + /** + * generated some debug information to make it easier to find faild API calls + * @return debug data string + */ + private static function getDebugOutput() { + $txt=''; + $txt.="debug output:\n"; + if(isset($_SERVER['REQUEST_METHOD'])) $txt.='http request method: '.$_SERVER['REQUEST_METHOD']."\n"; + if(isset($_SERVER['REQUEST_URI'])) $txt.='http request uri: '.$_SERVER['REQUEST_URI']."\n"; + if(isset($_GET)) foreach($_GET as $key=>$value) $txt.='get parameter: '.$key.'->'.$value."\n"; + if(isset($_POST)) foreach($_POST as $key=>$value) $txt.='post parameter: '.$key.'->'.$value."\n"; + return($txt); + } + + /** + * checks if the user is authenticated + * checks the IP whitlist, apikeys and login/password combination + * if $forceuser is true and the authentication failed it returns an 401 http response. + * if $forceuser is false and authentification fails it returns an empty username string + * @param bool $forceuser + * @return username string + */ + private static function checkPassword($forceuser=true) { + //valid user account ? + if(isset($_SERVER['PHP_AUTH_USER'])) $authuser=$_SERVER['PHP_AUTH_USER']; else $authuser=''; + if(isset($_SERVER['PHP_AUTH_PW'])) $authpw=$_SERVER['PHP_AUTH_PW']; else $authpw=''; + + if(empty($authuser)) { + if($forceuser){ + header('WWW-Authenticate: Basic realm="your valid user account or api key"'); + header('HTTP/1.0 401 Unauthorized'); + exit; + }else{ + $identifieduser=''; + } + }else{ + if(!OC_User::login($authuser,$authpw)){ + if($forceuser){ + header('WWW-Authenticate: Basic realm="your valid user account or api key"'); + header('HTTP/1.0 401 Unauthorized'); + exit; + }else{ + $identifieduser=''; + } + }else{ + $identifieduser=$authuser; + } + } + + return($identifieduser); + } + + + /** + * generates the xml or json response for the API call from an multidimenional data array. + * @param string $format + * @param string $status + * @param string $statuscode + * @param string $message + * @param array $data + * @param string $tag + * @param string $tagattribute + * @param int $dimension + * @param int $itemscount + * @param int $itemsperpage + * @return string xml/json + */ + private static function generateXml($format,$status,$statuscode,$message,$data=array(),$tag='',$tagattribute='',$dimension=-1,$itemscount='',$itemsperpage='') { + if($format=='json') { + $json=array(); + $json['status']=$status; + $json['statuscode']=$statuscode; + $json['message']=$message; + $json['totalitems']=$itemscount; + $json['itemsperpage']=$itemsperpage; + $json['data']=$data; + return(json_encode($json)); + }else{ + $txt=''; + $writer = xmlwriter_open_memory(); + xmlwriter_set_indent( $writer, 2 ); + xmlwriter_start_document($writer ); + xmlwriter_start_element($writer,'ocs'); + xmlwriter_start_element($writer,'meta'); + xmlwriter_write_element($writer,'status',$status); + xmlwriter_write_element($writer,'statuscode',$statuscode); + xmlwriter_write_element($writer,'message',$message); + if($itemscount<>'') xmlwriter_write_element($writer,'totalitems',$itemscount); + if(!empty($itemsperpage)) xmlwriter_write_element($writer,'itemsperpage',$itemsperpage); + xmlwriter_end_element($writer); + if($dimension=='0') { + // 0 dimensions + xmlwriter_write_element($writer,'data',$data); + + }elseif($dimension=='1') { + xmlwriter_start_element($writer,'data'); + foreach($data as $key=>$entry) { + xmlwriter_write_element($writer,$key,$entry); + } + xmlwriter_end_element($writer); + + }elseif($dimension=='2') { + xmlwriter_start_element($writer,'data'); + foreach($data as $entry) { + xmlwriter_start_element($writer,$tag); + if(!empty($tagattribute)) { + xmlwriter_write_attribute($writer,'details',$tagattribute); + } + foreach($entry as $key=>$value) { + if(is_array($value)){ + foreach($value as $k=>$v) { + xmlwriter_write_element($writer,$k,$v); + } + } else { + xmlwriter_write_element($writer,$key,$value); + } + } + xmlwriter_end_element($writer); + } + xmlwriter_end_element($writer); + + }elseif($dimension=='3') { + xmlwriter_start_element($writer,'data'); + foreach($data as $entrykey=>$entry) { + xmlwriter_start_element($writer,$tag); + if(!empty($tagattribute)) { + xmlwriter_write_attribute($writer,'details',$tagattribute); + } + foreach($entry as $key=>$value) { + if(is_array($value)){ + xmlwriter_start_element($writer,$entrykey); + foreach($value as $k=>$v) { + xmlwriter_write_element($writer,$k,$v); + } + xmlwriter_end_element($writer); + } else { + xmlwriter_write_element($writer,$key,$value); + } + } + xmlwriter_end_element($writer); + } + xmlwriter_end_element($writer); + }elseif($dimension=='dynamic') { + xmlwriter_start_element($writer,'data'); + OC_OCS::toxml($writer,$data,'comment'); + xmlwriter_end_element($writer); + } + + xmlwriter_end_element($writer); + + xmlwriter_end_document( $writer ); + $txt.=xmlwriter_output_memory( $writer ); + unset($writer); + return($txt); + } + } + + public static function toXml($writer,$data,$node) { + foreach($data as $key => $value) { + if (is_numeric($key)) { + $key = $node; + } + if (is_array($value)){ + xmlwriter_start_element($writer,$key); + OC_OCS::toxml($writer,$value,$node); + xmlwriter_end_element($writer); + }else{ + xmlwriter_write_element($writer,$key,$value); + } + } + } + + + + + /** + * return the config data of this server + * @param string $format + * @return string xml/json + */ + public static function apiConfig($parameters) { + $format = $parameters['format']; + $user=OC_OCS::checkpassword(false); + $url=substr(OCP\Util::getServerHost().$_SERVER['SCRIPT_NAME'],0,-11).''; + + $xml['version']='1.7'; + $xml['website']='ownCloud'; + $xml['host']=OCP\Util::getServerHost(); + $xml['contact']=''; + $xml['ssl']='false'; + echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'config','',1)); + } + + + /** + * check if the provided login/apikey/password is valid + * @param string $format + * @param string $login + * @param string $passwd + * @return string xml/json + */ + private static function personCheck($format,$login,$passwd) { + if($login<>''){ + if(OC_User::login($login,$passwd)){ + $xml['person']['personid']=$login; + echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'person','check',2)); + }else{ + echo(OC_OCS::generatexml($format,'failed',102,'login not valid')); + } + }else{ + echo(OC_OCS::generatexml($format,'failed',101,'please specify all mandatory fields')); + } + } + + + + // ACTIVITY API ############################################# + + /** + * get my activities + * @param string $format + * @param string $page + * @param string $pagesize + * @return string xml/json + */ + private static function activityGet($format,$page,$pagesize) { + $user=OC_OCS::checkpassword(); + + //TODO + + $txt=OC_OCS::generatexml($format,'ok',100,'',$xml,'activity','full',2,$totalcount,$pagesize); + echo($txt); + } + + /** + * submit a activity + * @param string $format + * @param string $message + * @return string xml/json + */ + private static function activityPut($format,$message) { + // not implemented in ownCloud + $user=OC_OCS::checkpassword(); + echo(OC_OCS::generatexml($format,'ok',100,'')); + } + + // PRIVATEDATA API ############################################# + + /** + * get private data and create the xml for ocs + * @param string $format + * @param string $app + * @param string $key + * @return string xml/json + */ + private static function privateDataGet($format,$app="",$key="") { + $user=OC_OCS::checkpassword(); + $result=OC_OCS::getData($user,$app,$key); + $xml=array(); + foreach($result as $i=>$log) { + $xml[$i]['key']=$log['key']; + $xml[$i]['app']=$log['app']; + $xml[$i]['value']=$log['value']; + } + + + $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'privatedata', 'full', 2, count($xml), 0);//TODO: replace 'privatedata' with 'attribute' once a new libattice has been released that works with it + echo($txt); + } + + /** + * set private data referenced by $key to $value and generate the xml for ocs + * @param string $format + * @param string $app + * @param string $key + * @param string $value + * @return string xml/json + */ private static function privateDataSet($format, $app, $key, $value) { $user=OC_OCS::checkpassword(); if(OC_OCS::setData($user,$app,$key,$value)){ @@ -529,4 +576,71 @@ class OC_OCS { public static function deleteData($user, $app, $key) { return OC_Preferences::deleteKey($user,$app,$key); } + + + // CLOUD API ############################################# + + /** + * get the quota of a user + * @param string $format + * @param string $user + * @return string xml/json + */ + private static function quotaGet($format,$user) { + $login=OC_OCS::checkpassword(); + if(OC_Group::inGroup($login, 'admin') or ($login==$user)) { + + if(OC_User::userExists($user)){ + // calculate the disc space + $user_dir = '/'.$user.'/files'; + OC_Filesystem::init($user_dir); + $rootInfo=OC_FileCache::get(''); + $sharedInfo=OC_FileCache::get('/Shared'); + $used=$rootInfo['size']-$sharedInfo['size']; + $free=OC_Filesystem::free_space(); + $total=$free+$used; + if($total==0) $total=1; // prevent division by zero + $relative=round(($used/$total)*10000)/100; + + $xml=array(); + $xml['quota']=$total; + $xml['free']=$free; + $xml['used']=$used; + $xml['relative']=$relative; + + $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'cloud', 'full', 1, count($xml), 0); + echo($txt); + }else{ + echo self::generateXml('', 'fail', 300, 'User does not exist'); + } + }else{ + echo self::generateXml('', 'fail', 300, 'You don´t have permission to access this ressource.'); + } + } + + /** + * set the quota of a user + * @param string $format + * @param string $user + * @param string $quota + * @return string xml/json + */ + private static function quotaSet($format,$user,$quota) { + $login=OC_OCS::checkpassword(); + if(OC_Group::inGroup($login, 'admin')) { + + // todo + // not yet implemented + // edit logic here + error_log('OCS call: user:'.$user.' quota:'.$quota); + + $xml=array(); + $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'cloud', 'full', 1, count($xml), 0); + echo($txt); + }else{ + echo self::generateXml('', 'fail', 300, 'You don´t have permission to access this ressource.'); + } + } + + } diff --git a/lib/user.php b/lib/user.php index 356be4decf9..549319b3a77 100644 --- a/lib/user.php +++ b/lib/user.php @@ -104,11 +104,17 @@ class OC_User { break; } } - true; } /** + * remove all used backends + */ + public static function clearBackends(){ + self::$_usedBackends=array(); + } + + /** * @brief Create a new user * @param $uid The username of the user to create * @param $password The password of the new user diff --git a/lib/util.php b/lib/util.php index f35e5a18e42..0c563278cc5 100755 --- a/lib/util.php +++ b/lib/util.php @@ -77,13 +77,13 @@ class OC_Util { return '5 pre alpha'; } - /** - * get the current installed edition of ownCloud. There is the community edition that just returns an empty string and the enterprise edition that returns "Enterprise". - * @return string - */ - public static function getEditionString(){ - return ''; - } + /** + * get the current installed edition of ownCloud. There is the community edition that just returns an empty string and the enterprise edition that returns "Enterprise". + * @return string + */ + public static function getEditionString(){ + return ''; + } /** * add a javascript file @@ -131,12 +131,12 @@ class OC_Util { self::$headers[]=array('tag'=>$tag,'attributes'=>$attributes,'text'=>$text); } - /** - * formats a timestamp in the "right" way - * - * @param int timestamp $timestamp - * @param bool dateOnly option to ommit time from the result - */ + /** + * formats a timestamp in the "right" way + * + * @param int timestamp $timestamp + * @param bool dateOnly option to ommit time from the result + */ public static function formatDate( $timestamp,$dateOnly=false){ if(isset($_SESSION['timezone'])){//adjust to clients timezone if we know it $systemTimeZone = intval(date('O')); @@ -438,26 +438,25 @@ class OC_Util { } - /** - * Check if the htaccess file is working by creating a test file in the data directory and trying to access via http - */ - public static function ishtaccessworking() { - + /** + * Check if the htaccess file is working by creating a test file in the data directory and trying to access via http + */ + public static function ishtaccessworking() { // testdata $filename='/htaccesstest.txt'; $testcontent='testcontent'; // creating a test file - $testfile = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ).'/'.$filename; - $fp = @fopen($testfile, 'w'); - @fwrite($fp, $testcontent); - @fclose($fp); + $testfile = OC_Config::getValue( "datadirectory", OC::$SERVERROOT."/data" ).'/'.$filename; + $fp = @fopen($testfile, 'w'); + @fwrite($fp, $testcontent); + @fclose($fp); // accessing the file via http - $url = OC_Helper::serverProtocol(). '://' . OC_Helper::serverHost() . OC::$WEBROOT.'/data'.$filename; - $fp = @fopen($url, 'r'); - $content=@fread($fp, 2048); - @fclose($fp); + $url = OC_Helper::serverProtocol(). '://' . OC_Helper::serverHost() . OC::$WEBROOT.'/data'.$filename; + $fp = @fopen($url, 'r'); + $content=@fread($fp, 2048); + @fclose($fp); // cleanup @unlink($testfile); @@ -467,13 +466,7 @@ class OC_Util { return(false); }else{ return(true); - } - - } - - - - + } } |