aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
Diffstat (limited to 'lib')
-rw-r--r--lib/MDB2/Driver/sqlite3.php2
-rw-r--r--lib/api.php204
-rw-r--r--[-rwxr-xr-x]lib/app.php122
-rw-r--r--lib/backgroundjob.php2
-rw-r--r--lib/base.php1467
-rw-r--r--lib/cache/apc.php2
-rw-r--r--lib/connector/sabre/ServiceUnavailable.php22
-rw-r--r--lib/connector/sabre/client.php173
-rw-r--r--lib/connector/sabre/maintenanceplugin.php56
-rw-r--r--lib/connector/sabre/node.php6
-rw-r--r--lib/db.php46
-rw-r--r--lib/filecache.php15
-rw-r--r--lib/fileproxy/quota.php2
-rw-r--r--lib/files.php2
-rw-r--r--lib/filestorage.php2
-rw-r--r--lib/filestorage/local.php45
-rw-r--r--lib/filesystem.php14
-rw-r--r--lib/filesystemview.php44
-rw-r--r--lib/helper.php138
-rw-r--r--lib/image.php2
-rw-r--r--lib/json.php21
-rw-r--r--lib/l10n.php18
-rw-r--r--lib/l10n/bg_BG.php34
-rw-r--r--lib/l10n/bn_BD.php29
-rw-r--r--lib/l10n/ca.php1
-rw-r--r--lib/l10n/cs_CZ.php1
-rw-r--r--lib/l10n/de.php1
-rw-r--r--lib/l10n/de_DE.php1
-rw-r--r--lib/l10n/el.php1
-rw-r--r--lib/l10n/es.php1
-rw-r--r--lib/l10n/es_AR.php1
-rw-r--r--lib/l10n/eu.php1
-rw-r--r--lib/l10n/fi_FI.php1
-rw-r--r--lib/l10n/fr.php1
-rw-r--r--lib/l10n/gl.php1
-rw-r--r--lib/l10n/hu_HU.php29
-rw-r--r--lib/l10n/id.php8
-rw-r--r--lib/l10n/is.php34
-rw-r--r--lib/l10n/it.php1
-rw-r--r--lib/l10n/ja_JP.php1
-rw-r--r--lib/l10n/lb.php2
-rw-r--r--lib/l10n/ms_MY.php1
-rw-r--r--lib/l10n/nb_NO.php8
-rw-r--r--lib/l10n/nl.php1
-rw-r--r--lib/l10n/pt_PT.php1
-rw-r--r--lib/l10n/ro.php8
-rw-r--r--lib/l10n/sr.php1
-rw-r--r--lib/l10n/sv.php1
-rw-r--r--lib/l10n/th_TH.php1
-rw-r--r--lib/l10n/tr.php28
-rw-r--r--lib/l10n/uk.php1
-rw-r--r--lib/l10n/zh_TW.php13
-rw-r--r--lib/log.php4
-rw-r--r--lib/mail.php24
-rw-r--r--lib/migrate.php4
-rw-r--r--lib/migration/content.php2
-rw-r--r--lib/mimetypes.list.php2
-rw-r--r--lib/ocs.php488
-rw-r--r--lib/ocs/activity.php28
-rw-r--r--lib/ocs/cloud.php98
-rw-r--r--lib/ocs/config.php36
-rw-r--r--lib/ocs/person.php42
-rw-r--r--lib/ocs/privatedata.php66
-rw-r--r--lib/ocs/result.php75
-rw-r--r--lib/ocsclient.php14
-rw-r--r--lib/public/api.php44
-rw-r--r--lib/public/app.php7
-rw-r--r--lib/public/constants.php1
-rw-r--r--lib/public/db.php14
-rw-r--r--lib/public/files.php3
-rw-r--r--lib/public/response.php32
-rw-r--r--lib/public/share.php586
-rw-r--r--lib/public/user.php6
-rw-r--r--lib/public/util.php130
-rwxr-xr-xlib/request.php4
-rw-r--r--lib/router.php6
-rw-r--r--lib/setup.php46
-rw-r--r--lib/subadmin.php7
-rw-r--r--lib/template.php34
-rw-r--r--lib/templatelayout.php17
-rw-r--r--lib/user.php18
-rwxr-xr-xlib/util.php211
-rw-r--r--lib/vcategories.php1
83 files changed, 2759 insertions, 1909 deletions
diff --git a/lib/MDB2/Driver/sqlite3.php b/lib/MDB2/Driver/sqlite3.php
index 9839dafbce1..8f057cfb6e8 100644
--- a/lib/MDB2/Driver/sqlite3.php
+++ b/lib/MDB2/Driver/sqlite3.php
@@ -98,7 +98,7 @@ class MDB2_Driver_sqlite3 extends MDB2_Driver_Common
if ($this->connection) {
$native_code = $this->connection->lastErrorCode();
}
- $native_msg = html_entity_decode($this->_lasterror);
+ $native_msg = html_entity_decode($this->_lasterror);
// PHP 5.2+ prepends the function name to $php_errormsg, so we need
// this hack to work around it, per bug #9599.
diff --git a/lib/api.php b/lib/api.php
new file mode 100644
index 00000000000..545b55757ff
--- /dev/null
+++ b/lib/api.php
@@ -0,0 +1,204 @@
+<?php
+/**
+* ownCloud
+*
+* @author Tom Needham
+* @author Michael Gapczynski
+* @author Bart Visscher
+* @copyright 2012 Tom Needham tom@owncloud.com
+* @copyright 2012 Michael Gapczynski mtgap@owncloud.com
+* @copyright 2012 Bart Visscher bartv@thisnet.nl
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* License as published by the Free Software Foundation; either
+* version 3 of the License, or any later version.
+*
+* This library is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
+*
+* You should have received a copy of the GNU Affero General Public
+* License along with this library. If not, see <http://www.gnu.org/licenses/>.
+*
+*/
+
+class OC_API {
+
+ /**
+ * API authentication levels
+ */
+ const GUEST_AUTH = 0;
+ const USER_AUTH = 1;
+ const SUBADMIN_AUTH = 2;
+ const ADMIN_AUTH = 3;
+
+ private static $server;
+
+ /**
+ * initialises the OAuth store and server
+ */
+ private static function init() {
+ self::$server = new OC_OAuth_Server(new OC_OAuth_Store());
+ }
+
+ /**
+ * api actions
+ */
+ protected static $actions = array();
+
+ /**
+ * registers an api call
+ * @param string $method the http method
+ * @param string $url the url to match
+ * @param callable $action the function to run
+ * @param string $app the id of the app registering the call
+ * @param int $authLevel the level of authentication required for the call
+ * @param array $defaults
+ * @param array $requirements
+ */
+ public static function register($method, $url, $action, $app,
+ $authLevel = OC_API::USER_AUTH,
+ $defaults = array(),
+ $requirements = array()) {
+ $name = strtolower($method).$url;
+ $name = str_replace(array('/', '{', '}'), '_', $name);
+ if(!isset(self::$actions[$name])) {
+ OC::getRouter()->useCollection('ocs');
+ OC::getRouter()->create($name, $url)
+ ->method($method)
+ ->action('OC_API', 'call');
+ self::$actions[$name] = array();
+ }
+ self::$actions[$name] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
+ }
+
+ /**
+ * handles an api call
+ * @param array $parameters
+ */
+ public static function call($parameters) {
+ // Prepare the request variables
+ if($_SERVER['REQUEST_METHOD'] == 'PUT') {
+ parse_str(file_get_contents("php://input"), $parameters['_put']);
+ } else if($_SERVER['REQUEST_METHOD'] == 'DELETE'){
+ parse_str(file_get_contents("php://input"), $parameters['_delete']);
+ }
+ $name = $parameters['_route'];
+ // Check authentication and availability
+ if(self::isAuthorised(self::$actions[$name])) {
+ if(is_callable(self::$actions[$name]['action'])) {
+ $response = call_user_func(self::$actions[$name]['action'], $parameters);
+ if(!($response instanceof OC_OCS_Result)) {
+ $response = new OC_OCS_Result(null, 996, 'Internal Server Error');
+ }
+ } else {
+ $response = new OC_OCS_Result(null, 998, 'Api method not found');
+ }
+ } else {
+ header('WWW-Authenticate: Basic realm="Authorization Required"');
+ header('HTTP/1.0 401 Unauthorized');
+ $response = new OC_OCS_Result(null, 997, 'Unauthorised');
+ }
+ // Send the response
+ $formats = array('json', 'xml');
+ $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
+ self::respond($response, $format);
+ // logout the user to be stateless
+ OC_User::logout();
+ }
+
+ /**
+ * authenticate the api call
+ * @param array $action the action details as supplied to OC_API::register()
+ * @return bool
+ */
+ private static function isAuthorised($action) {
+ $level = $action['authlevel'];
+ switch($level) {
+ case OC_API::GUEST_AUTH:
+ // Anyone can access
+ return true;
+ break;
+ case OC_API::USER_AUTH:
+ // User required
+ return self::loginUser();
+ break;
+ case OC_API::SUBADMIN_AUTH:
+ // Check for subadmin
+ $user = self::loginUser();
+ if(!$user) {
+ return false;
+ } else {
+ $subAdmin = OC_SubAdmin::isSubAdmin($user);
+ if($subAdmin) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+ break;
+ case OC_API::ADMIN_AUTH:
+ // Check for admin
+ $user = self::loginUser();
+ if(!$user) {
+ return false;
+ } else {
+ return OC_User::isAdminUser($user);
+ }
+ break;
+ default:
+ // oops looks like invalid level supplied
+ return false;
+ break;
+ }
+ }
+
+ /**
+ * http basic auth
+ * @return string|false (username, or false on failure)
+ */
+ private static function loginUser(){
+ $authUser = isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '';
+ $authPw = isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '';
+ return OC_User::login($authUser, $authPw) ? $authUser : false;
+ }
+
+ /**
+ * respond to a call
+ * @param int|array $result the result from the api method
+ * @param string $format the format xml|json
+ */
+ private static function respond($result, $format='xml') {
+ $response = array('ocs' => $result->getResult());
+ if ($format == 'json') {
+ OC_JSON::encodedPrint($response);
+ } else if ($format == 'xml') {
+ header('Content-type: text/xml; charset=UTF-8');
+ $writer = new XMLWriter();
+ $writer->openMemory();
+ $writer->setIndent( true );
+ $writer->startDocument();
+ self::toXML($response, $writer);
+ $writer->endDocument();
+ echo $writer->outputMemory(true);
+ }
+ }
+
+ private static function toXML($array, $writer) {
+ foreach($array as $k => $v) {
+ if (is_numeric($k)) {
+ $k = 'element';
+ }
+ if (is_array($v)) {
+ $writer->startElement($k);
+ self::toXML($v, $writer);
+ $writer->endElement();
+ } else {
+ $writer->writeElement($k, $v);
+ }
+ }
+ }
+
+}
diff --git a/lib/app.php b/lib/app.php
index be6d5ab3dd3..108226fc1a1 100755..100644
--- a/lib/app.php
+++ b/lib/app.php
@@ -63,17 +63,17 @@ class OC_App{
if (!defined('DEBUG') || !DEBUG) {
if (is_null($types)
- && empty(OC_Util::$core_scripts)
- && empty(OC_Util::$core_styles)) {
+ && empty(OC_Util::$core_scripts)
+ && empty(OC_Util::$core_styles)) {
OC_Util::$core_scripts = OC_Util::$scripts;
- OC_Util::$scripts = array();
- OC_Util::$core_styles = OC_Util::$styles;
- OC_Util::$styles = array();
- }
+ OC_Util::$scripts = array();
+ OC_Util::$core_styles = OC_Util::$styles;
+ OC_Util::$styles = array();
}
- // return
- return true;
}
+ // return
+ return true;
+}
/**
* load a single app
@@ -139,6 +139,20 @@ class OC_App{
}
/**
+ * check if app is shipped
+ * @param string $appid the id of the app to check
+ * @return bool
+ */
+ public static function isShipped($appid){
+ $info = self::getAppInfo($appid);
+ if(isset($info['shipped']) && $info['shipped']=='true'){
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /**
* get all enabled apps
*/
public static function getEnabledApps() {
@@ -285,7 +299,7 @@ class OC_App{
if(OC_Config::getValue('knowledgebaseenabled', true)==true) {
$settings = array(
array( "id" => "help", "order" => 1000, "href" => OC_Helper::linkToRoute( "settings_help" ), "name" => $l->t("Help"), "icon" => OC_Helper::imagePath( "settings", "help.svg" ))
- );
+ );
}
// if the user is logged-in
@@ -299,14 +313,14 @@ class OC_App{
$settings[]=array( "id" => "settings", "order" => 1000, "href" => OC_Helper::linkToRoute( "settings_settings" ), "name" => $l->t("Settings"), "icon" => OC_Helper::imagePath( "settings", "settings.svg" ));
//SubAdmins are also allowed to access user management
- if(OC_SubAdmin::isSubAdmin($_SESSION["user_id"]) || OC_Group::inGroup( $_SESSION["user_id"], "admin" )) {
+ if(OC_SubAdmin::isSubAdmin(OC_User::getUser())) {
// admin users menu
$settings[] = array( "id" => "core_users", "order" => 2, "href" => OC_Helper::linkToRoute( "settings_users" ), "name" => $l->t("Users"), "icon" => OC_Helper::imagePath( "settings", "users.svg" ));
}
// if the user is an admin
- if(OC_Group::inGroup( $_SESSION["user_id"], "admin" )) {
+ if(OC_User::isAdminUser(OC_User::getUser())) {
// admin apps menu
$settings[] = array( "id" => "core_apps", "order" => 3, "href" => OC_Helper::linkToRoute( "settings_apps" ).'?installed', "name" => $l->t("Apps"), "icon" => OC_Helper::imagePath( "settings", "apps.svg" ));
@@ -505,16 +519,16 @@ class OC_App{
$forms=array();
switch($type) {
case 'settings':
- $source=self::$settingsForms;
- break;
+ $source=self::$settingsForms;
+ break;
case 'admin':
- $source=self::$adminForms;
- break;
+ $source=self::$adminForms;
+ break;
case 'personal':
- $source=self::$personalForms;
- break;
+ $source=self::$personalForms;
+ break;
default:
- return array();
+ return array();
}
foreach($source as $form) {
$forms[]=include $form;
@@ -575,6 +589,72 @@ class OC_App{
}
/**
+ * @brief: Lists all apps, this is used in apps.php
+ * @return array
+ */
+ public static function listAllApps() {
+ $installedApps = OC_App::getAllApps();
+
+ //TODO which apps do we want to blacklist and how do we integrate blacklisting with the multi apps folder feature?
+
+ $blacklist = array('files');//we dont want to show configuration for these
+ $appList = array();
+
+ foreach ( $installedApps as $app ) {
+ if ( array_search( $app, $blacklist ) === false ) {
+
+ $info=OC_App::getAppInfo($app);
+
+ if (!isset($info['name'])) {
+ OC_Log::write('core', 'App id "'.$app.'" has no name in appinfo', OC_Log::ERROR);
+ continue;
+ }
+
+ if ( OC_Appconfig::getValue( $app, 'enabled', 'no') == 'yes' ) {
+ $active = true;
+ } else {
+ $active = false;
+ }
+
+ $info['active'] = $active;
+
+ if(isset($info['shipped']) and ($info['shipped']=='true')) {
+ $info['internal']=true;
+ $info['internallabel']='Internal App';
+ } else {
+ $info['internal']=false;
+ $info['internallabel']='3rd Party App';
+ }
+
+ $info['preview'] = OC_Helper::imagePath('settings', 'trans.png');
+ $info['version'] = OC_App::getAppVersion($app);
+ $appList[] = $info;
+ }
+ }
+ $remoteApps = OC_App::getAppstoreApps();
+ if ( $remoteApps ) {
+ // Remove duplicates
+ foreach ( $appList as $app ) {
+ foreach ( $remoteApps AS $key => $remote ) {
+ if (
+ $app['name'] == $remote['name']
+ // To set duplicate detection to use OCS ID instead of string name,
+ // enable this code, remove the line of code above,
+ // and add <ocs_id>[ID]</ocs_id> to info.xml of each 3rd party app:
+ // OR $app['ocs_id'] == $remote['ocs_id']
+ ) {
+ unset( $remoteApps[$key]);
+ }
+ }
+ }
+ $combinedApps = array_merge( $appList, $remoteApps );
+ } else {
+ $combinedApps = $appList;
+ }
+ return $combinedApps;
+}
+
+ /**
* @brief: get a list of all apps on apps.owncloud.com
* @return array, multi-dimensional array of apps. Keys: id, name, type, typename, personid, license, detailpage, preview, changed, description
*/
@@ -634,12 +714,15 @@ class OC_App{
if ($currentVersion) {
$installedVersion = $versions[$app];
if (version_compare($currentVersion, $installedVersion, '>')) {
+ $info = self::getAppInfo($app);
OC_Log::write($app, 'starting app upgrade from '.$installedVersion.' to '.$currentVersion, OC_Log::DEBUG);
try {
OC_App::updateApp($app);
+ OC_Hook::emit('update', 'success', 'Updated '.$info['name'].' app');
}
catch (Exception $e) {
echo 'Failed to upgrade "'.$app.'". Exception="'.$e->getMessage().'"';
+ OC_Hook::emit('update', 'failure', 'Failed to update '.$info['name'].' app: '.$e->getMessage());
die;
}
OC_Appconfig::setValue($app, 'installed_version', OC_App::getAppVersion($app));
@@ -664,6 +747,7 @@ class OC_App{
if(!isset($info['require']) or (($version[0].'.'.$version[1])>$info['require'])) {
OC_Log::write('core', 'App "'.$info['name'].'" ('.$app.') can\'t be used because it is not compatible with this version of ownCloud', OC_Log::ERROR);
OC_App::disable( $app );
+ OC_Hook::emit('update', 'success', 'Disabled '.$info['name'].' app because it is not compatible');
}
}
}
@@ -730,7 +814,7 @@ class OC_App{
}
return new OC_FilesystemView('/'.OC_User::getUser().'/'.$appid);
}else{
- OC_Log::write('core', 'Can\'t get app storage, app, user not logged in', OC_Log::ERROR);
+ OC_Log::write('core', 'Can\'t get app storage, app '.$appid.', user not logged in', OC_Log::ERROR);
return false;
}
}else{
diff --git a/lib/backgroundjob.php b/lib/backgroundjob.php
index 28b5ce3af20..9619dcb732c 100644
--- a/lib/backgroundjob.php
+++ b/lib/backgroundjob.php
@@ -34,7 +34,7 @@ class OC_BackgroundJob{
public static function getExecutionType() {
return OC_Appconfig::getValue( 'core', 'backgroundjobs_mode', 'ajax' );
}
-
+
/**
* @brief sets the background jobs execution type
* @param $type execution type
diff --git a/lib/base.php b/lib/base.php
index 94fb7979620..aff3e1d5a11 100644
--- a/lib/base.php
+++ b/lib/base.php
@@ -29,729 +29,766 @@ require_once 'public/constants.php';
*/
class OC
{
- /**
- * Assoziative array for autoloading. classname => filename
- */
- public static $CLASSPATH = array();
- /**
- * The installation path for owncloud on the server (e.g. /srv/http/owncloud)
- */
- public static $SERVERROOT = '';
- /**
- * the current request path relative to the owncloud root (e.g. files/index.php)
- */
- private static $SUBURI = '';
- /**
- * the owncloud root path for http requests (e.g. owncloud/)
- */
- public static $WEBROOT = '';
- /**
- * The installation path of the 3rdparty folder on the server (e.g. /srv/http/owncloud/3rdparty)
- */
- public static $THIRDPARTYROOT = '';
- /**
- * the root path of the 3rdparty folder for http requests (e.g. owncloud/3rdparty)
- */
- public static $THIRDPARTYWEBROOT = '';
- /**
- * The installation path array of the apps folder on the server (e.g. /srv/http/owncloud) 'path' and
- * web path in 'url'
- */
- public static $APPSROOTS = array();
- /*
- * requested app
- */
- public static $REQUESTEDAPP = '';
- /*
- * requested file of app
- */
- public static $REQUESTEDFILE = '';
- /**
- * check if owncloud runs in cli mode
- */
- public static $CLI = false;
- /*
- * OC router
- */
- protected static $router = null;
-
- /**
- * SPL autoload
- */
- public static function autoload($className)
- {
- if (array_key_exists($className, OC::$CLASSPATH)) {
- $path = OC::$CLASSPATH[$className];
- /** @TODO: Remove this when necessary
- Remove "apps/" from inclusion path for smooth migration to mutli app dir
- */
- if (strpos($path, 'apps/') === 0) {
- OC_Log::write('core', 'include path for class "' . $className . '" starts with "apps/"', OC_Log::DEBUG);
- $path = str_replace('apps/', '', $path);
- }
- } elseif (strpos($className, 'OC_') === 0) {
- $path = strtolower(str_replace('_', '/', substr($className, 3)) . '.php');
- } elseif (strpos($className, 'OC\\') === 0) {
- $path = strtolower(str_replace('\\', '/', substr($className, 3)) . '.php');
- } elseif (strpos($className, 'OCP\\') === 0) {
- $path = 'public/' . strtolower(str_replace('\\', '/', substr($className, 3)) . '.php');
- } elseif (strpos($className, 'OCA\\') === 0) {
- $path = 'apps/' . strtolower(str_replace('\\', '/', substr($className, 3)) . '.php');
- } elseif (strpos($className, 'Sabre_') === 0) {
- $path = str_replace('_', '/', $className) . '.php';
- } elseif (strpos($className, 'Symfony\\Component\\Routing\\') === 0) {
- $path = 'symfony/routing/' . str_replace('\\', '/', $className) . '.php';
- } elseif (strpos($className, 'Sabre\\VObject') === 0) {
- $path = str_replace('\\', '/', $className) . '.php';
- } elseif (strpos($className, 'Test_') === 0) {
- $path = 'tests/lib/' . strtolower(str_replace('_', '/', substr($className, 5)) . '.php');
- } else {
- return false;
- }
-
- if ($fullPath = stream_resolve_include_path($path)) {
- require_once $fullPath;
- }
- return false;
- }
-
- public static function initPaths()
- {
- // calculate the root directories
- OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
- OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
- $scriptName = $_SERVER["SCRIPT_NAME"];
- if (substr($scriptName, -1) == '/') {
- $scriptName .= 'index.php';
- //make sure suburi follows the same rules as scriptName
- if (substr(OC::$SUBURI, -9) != 'index.php') {
- if (substr(OC::$SUBURI, -1) != '/') {
- OC::$SUBURI = OC::$SUBURI . '/';
- }
- OC::$SUBURI = OC::$SUBURI . 'index.php';
- }
- }
-
- OC::$WEBROOT = substr($scriptName, 0, strlen($scriptName) - strlen(OC::$SUBURI));
-
- if (OC::$WEBROOT != '' and OC::$WEBROOT[0] !== '/') {
- OC::$WEBROOT = '/' . OC::$WEBROOT;
- }
-
- // ensure we can find OC_Config
- set_include_path(
- OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
- get_include_path()
- );
-
- // search the 3rdparty folder
- if (OC_Config::getValue('3rdpartyroot', '') <> '' and OC_Config::getValue('3rdpartyurl', '') <> '') {
- OC::$THIRDPARTYROOT = OC_Config::getValue('3rdpartyroot', '');
- OC::$THIRDPARTYWEBROOT = OC_Config::getValue('3rdpartyurl', '');
- } elseif (file_exists(OC::$SERVERROOT . '/3rdparty')) {
- OC::$THIRDPARTYROOT = OC::$SERVERROOT;
- OC::$THIRDPARTYWEBROOT = OC::$WEBROOT;
- } elseif (file_exists(OC::$SERVERROOT . '/../3rdparty')) {
- OC::$THIRDPARTYWEBROOT = rtrim(dirname(OC::$WEBROOT), '/');
- OC::$THIRDPARTYROOT = rtrim(dirname(OC::$SERVERROOT), '/');
- } else {
- echo("3rdparty directory not found! Please put the ownCloud 3rdparty folder in the ownCloud folder or the folder above. You can also configure the location in the config.php file.");
- exit;
- }
- // search the apps folder
- $config_paths = OC_Config::getValue('apps_paths', array());
- if (!empty($config_paths)) {
- foreach ($config_paths as $paths) {
- if (isset($paths['url']) && isset($paths['path'])) {
- $paths['url'] = rtrim($paths['url'], '/');
- $paths['path'] = rtrim($paths['path'], '/');
- OC::$APPSROOTS[] = $paths;
- }
- }
- } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
- OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
- } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
- OC::$APPSROOTS[] = array('path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps', 'url' => '/apps', 'writable' => true);
- }
-
- if (empty(OC::$APPSROOTS)) {
- echo("apps directory not found! Please put the ownCloud apps folder in the ownCloud folder or the folder above. You can also configure the location in the config.php file.");
- exit;
- }
- $paths = array();
- foreach (OC::$APPSROOTS as $path)
- $paths[] = $path['path'];
-
- // set the right include path
- set_include_path(
- OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
- OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
- OC::$THIRDPARTYROOT . '/3rdparty' . PATH_SEPARATOR .
- implode($paths, PATH_SEPARATOR) . PATH_SEPARATOR .
- get_include_path() . PATH_SEPARATOR .
- OC::$SERVERROOT
- );
- }
-
- public static function checkInstalled()
- {
- // Redirect to installer if not installed
- if (!OC_Config::getValue('installed', false) && OC::$SUBURI != '/index.php') {
- if (!OC::$CLI) {
- $url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
- header("Location: $url");
- }
- exit();
- }
- }
-
- public static function checkSSL()
- {
- // redirect to https site if configured
- if (OC_Config::getValue("forcessl", false)) {
- header('Strict-Transport-Security: max-age=31536000');
- ini_set("session.cookie_secure", "on");
- if (OC_Request::serverProtocol() <> 'https' and !OC::$CLI) {
- $url = "https://" . OC_Request::serverHost() . $_SERVER['REQUEST_URI'];
- header("Location: $url");
- exit();
- }
- }
- }
-
- public static function checkUpgrade()
- {
- if (OC_Config::getValue('installed', false)) {
- $installedVersion = OC_Config::getValue('version', '0.0.0');
- $currentVersion = implode('.', OC_Util::getVersion());
- if (version_compare($currentVersion, $installedVersion, '>')) {
- // Check if the .htaccess is existing - this is needed for upgrades from really old ownCloud versions
- if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) {
- if (!OC_Util::ishtaccessworking()) {
- if (!file_exists(OC::$SERVERROOT . '/data/.htaccess')) {
- OC_Setup::protectDataDirectory();
- }
- }
- }
- OC_Log::write('core', 'starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, OC_Log::DEBUG);
- $result = OC_DB::updateDbFromStructure(OC::$SERVERROOT . '/db_structure.xml');
- if (!$result) {
- echo 'Error while upgrading the database';
- die();
- }
- if (file_exists(OC::$SERVERROOT . "/config/config.php") and !is_writable(OC::$SERVERROOT . "/config/config.php")) {
- $tmpl = new OC_Template('', 'error', 'guest');
- $tmpl->assign('errors', array(1 => array('error' => "Can't write into config directory 'config'", 'hint' => "You can usually fix this by giving the webserver user write access to the config directory in owncloud")));
- $tmpl->printPage();
- exit;
- }
- $minimizerCSS = new OC_Minimizer_CSS();
- $minimizerCSS->clearCache();
- $minimizerJS = new OC_Minimizer_JS();
- $minimizerJS->clearCache();
- OC_Config::setValue('version', implode('.', OC_Util::getVersion()));
- OC_App::checkAppsRequirements();
- // load all apps to also upgrade enabled apps
- OC_App::loadApps();
- }
- }
- }
-
- public static function initTemplateEngine()
- {
- // Add the stuff we need always
- OC_Util::addScript("jquery-1.7.2.min");
- OC_Util::addScript("jquery-ui-1.8.16.custom.min");
- OC_Util::addScript("jquery-showpassword");
- OC_Util::addScript("jquery.infieldlabel");
- OC_Util::addScript("jquery-tipsy");
- OC_Util::addScript("oc-dialogs");
- OC_Util::addScript("js");
- OC_Util::addScript("eventsource");
- OC_Util::addScript("config");
- //OC_Util::addScript( "multiselect" );
- OC_Util::addScript('search', 'result');
- OC_Util::addScript('router');
-
- if (OC_Config::getValue('installed', false)) {
- if (OC_Appconfig::getValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
- OC_Util::addScript('backgroundjobs');
- }
- }
-
- OC_Util::addStyle("styles");
- OC_Util::addStyle("multiselect");
- OC_Util::addStyle("jquery-ui-1.8.16.custom");
- OC_Util::addStyle("jquery-tipsy");
- }
-
- public static function initSession()
- {
- // prevents javascript from accessing php session cookies
- ini_set('session.cookie_httponly', '1;');
-
- // set the session name to the instance id - which is unique
- session_name(OC_Util::getInstanceId());
-
- // (re)-initialize session
- session_start();
-
- // regenerate session id periodically to avoid session fixation
- if (!isset($_SESSION['SID_CREATED'])) {
- $_SESSION['SID_CREATED'] = time();
- } else if (time() - $_SESSION['SID_CREATED'] > 900) {
- session_regenerate_id(true);
- $_SESSION['SID_CREATED'] = time();
- }
-
- // session timeout
- if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
- if (isset($_COOKIE[session_name()])) {
- setcookie(session_name(), '', time() - 42000, '/');
- }
- session_unset();
- session_destroy();
- session_start();
- }
- $_SESSION['LAST_ACTIVITY'] = time();
- }
-
- public static function getRouter()
- {
- if (!isset(OC::$router)) {
- OC::$router = new OC_Router();
- OC::$router->loadRoutes();
- }
-
- return OC::$router;
- }
-
- public static function init()
- {
- // register autoloader
- spl_autoload_register(array('OC', 'autoload'));
- setlocale(LC_ALL, 'en_US.UTF-8');
-
- // set some stuff
- //ob_start();
- error_reporting(E_ALL | E_STRICT);
- if (defined('DEBUG') && DEBUG) {
- ini_set('display_errors', 1);
- }
- self::$CLI = (php_sapi_name() == 'cli');
-
- date_default_timezone_set('UTC');
- ini_set('arg_separator.output', '&amp;');
-
- // try to switch magic quotes off.
- if (get_magic_quotes_gpc()) {
- @set_magic_quotes_runtime(false);
- }
-
- //try to configure php to enable big file uploads.
- //this doesn´t work always depending on the webserver and php configuration.
- //Let´s try to overwrite some defaults anyways
-
- //try to set the maximum execution time to 60min
- @set_time_limit(3600);
- @ini_set('max_execution_time', 3600);
- @ini_set('max_input_time', 3600);
-
- //try to set the maximum filesize to 10G
- @ini_set('upload_max_filesize', '10G');
- @ini_set('post_max_size', '10G');
- @ini_set('file_uploads', '50');
-
- //try to set the session lifetime to 60min
- @ini_set('gc_maxlifetime', '3600');
-
- //copy http auth headers for apache+php-fcgid work around
- if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
- $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
- }
-
- //set http auth headers for apache+php-cgi work around
- if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
- list($name, $password) = explode(':', base64_decode($matches[1]), 2);
- $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
- $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
- }
-
- //set http auth headers for apache+php-cgi work around if variable gets renamed by apache
- if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) {
- list($name, $password) = explode(':', base64_decode($matches[1]), 2);
- $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
- $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
- }
-
- self::initPaths();
-
- register_shutdown_function(array('OC_Log', 'onShutdown'));
- set_error_handler(array('OC_Log', 'onError'));
- set_exception_handler(array('OC_Log', 'onException'));
-
- // set debug mode if an xdebug session is active
- if (!defined('DEBUG') || !DEBUG) {
- if (isset($_COOKIE['XDEBUG_SESSION'])) {
- define('DEBUG', true);
- }
- }
-
- // register the stream wrappers
- require_once 'streamwrappers.php';
- stream_wrapper_register("fakedir", "OC_FakeDirStream");
- stream_wrapper_register('static', 'OC_StaticStreamWrapper');
- stream_wrapper_register('close', 'OC_CloseStreamWrapper');
-
- self::checkInstalled();
- self::checkSSL();
- self::initSession();
- self::initTemplateEngine();
- self::checkUpgrade();
-
- $errors = OC_Util::checkServer();
- if (count($errors) > 0) {
- OC_Template::printGuestPage('', 'error', array('errors' => $errors));
- exit;
- }
-
- // User and Groups
- if (!OC_Config::getValue("installed", false)) {
- $_SESSION['user_id'] = '';
- }
-
- OC_User::useBackend(new OC_User_Database());
- OC_Group::useBackend(new OC_Group_Database());
-
- if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SESSION['user_id']) && $_SERVER['PHP_AUTH_USER'] != $_SESSION['user_id']) {
- OC_User::logout();
- }
-
- // Load Apps
- // This includes plugins for users and filesystems as well
- global $RUNTIME_NOAPPS;
- global $RUNTIME_APPTYPES;
- if (!$RUNTIME_NOAPPS) {
- if ($RUNTIME_APPTYPES) {
- OC_App::loadApps($RUNTIME_APPTYPES);
- } else {
- OC_App::loadApps();
- }
- }
-
- //setup extra user backends
- OC_User::setupBackends();
-
- self::registerCacheHooks();
- self::registerFilesystemHooks();
- self::registerShareHooks();
-
- //make sure temporary files are cleaned up
- register_shutdown_function(array('OC_Helper', 'cleanTmp'));
-
- //parse the given parameters
- self::$REQUESTEDAPP = (isset($_GET['app']) && trim($_GET['app']) != '' && !is_null($_GET['app']) ? str_replace(array('\0', '/', '\\', '..'), '', strip_tags($_GET['app'])) : OC_Config::getValue('defaultapp', 'files'));
- if (substr_count(self::$REQUESTEDAPP, '?') != 0) {
- $app = substr(self::$REQUESTEDAPP, 0, strpos(self::$REQUESTEDAPP, '?'));
- $param = substr($_GET['app'], strpos($_GET['app'], '?') + 1);
- parse_str($param, $get);
- $_GET = array_merge($_GET, $get);
- self::$REQUESTEDAPP = $app;
- $_GET['app'] = $app;
- }
- self::$REQUESTEDFILE = (isset($_GET['getfile']) ? $_GET['getfile'] : null);
- if (substr_count(self::$REQUESTEDFILE, '?') != 0) {
- $file = substr(self::$REQUESTEDFILE, 0, strpos(self::$REQUESTEDFILE, '?'));
- $param = substr(self::$REQUESTEDFILE, strpos(self::$REQUESTEDFILE, '?') + 1);
- parse_str($param, $get);
- $_GET = array_merge($_GET, $get);
- self::$REQUESTEDFILE = $file;
- $_GET['getfile'] = $file;
- }
- if (!is_null(self::$REQUESTEDFILE)) {
- $subdir = OC_App::getAppPath(OC::$REQUESTEDAPP) . '/' . self::$REQUESTEDFILE;
- $parent = OC_App::getAppPath(OC::$REQUESTEDAPP);
- if (!OC_Helper::issubdirectory($subdir, $parent)) {
- self::$REQUESTEDFILE = null;
- header('HTTP/1.0 404 Not Found');
- exit;
- }
- }
-
- // write error into log if locale can't be set
- if (OC_Util::issetlocaleworking() == false) {
- OC_Log::write('core', 'setting locate to en_US.UTF-8 failed. Support is probably not installed on your system', OC_Log::ERROR);
- }
- }
-
- /**
- * register hooks for the cache
- */
- public static function registerCacheHooks()
- {
- // register cache cleanup jobs
- OC_BackgroundJob_RegularTask::register('OC_Cache_FileGlobal', 'gc');
- OC_Hook::connect('OC_User', 'post_login', 'OC_Cache_File', 'loginListener');
- }
-
- /**
- * register hooks for the filesystem
- */
- public static function registerFilesystemHooks()
- {
- // Check for blacklisted files
- OC_Hook::connect('OC_Filesystem', 'write', 'OC_Filesystem', 'isBlacklisted');
- OC_Hook::connect('OC_Filesystem', 'rename', 'OC_Filesystem', 'isBlacklisted');
- }
-
- /**
- * register hooks for sharing
- */
- public static function registerShareHooks()
- {
- OC_Hook::connect('OC_User', 'post_deleteUser', 'OCP\Share', 'post_deleteUser');
- OC_Hook::connect('OC_User', 'post_addToGroup', 'OCP\Share', 'post_addToGroup');
- OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OCP\Share', 'post_removeFromGroup');
- OC_Hook::connect('OC_User', 'post_deleteGroup', 'OCP\Share', 'post_deleteGroup');
- }
-
- /**
- * @brief Handle the request
- */
- public static function handleRequest()
- {
- if (!OC_Config::getValue('installed', false)) {
- require_once 'core/setup.php';
- exit();
- }
- // Handle redirect URL for logged in users
- if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
- $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
- header('Location: ' . $location);
- return;
- }
- // Handle WebDAV
- if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
- header('location: ' . OC_Helper::linkToRemote('webdav'));
- return;
- }
- try {
- OC::getRouter()->match(OC_Request::getPathInfo());
- return;
- } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
- //header('HTTP/1.0 404 Not Found');
- } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
- OC_Response::setStatus(405);
- return;
- }
- $app = OC::$REQUESTEDAPP;
- $file = OC::$REQUESTEDFILE;
- $param = array('app' => $app, 'file' => $file);
- // Handle app css files
- if (substr($file, -3) == 'css') {
- self::loadCSSFile($param);
- return;
- }
- // Someone is logged in :
- if (OC_User::isLoggedIn()) {
- OC_App::loadApps();
- OC_User::setupBackends();
- if (isset($_GET["logout"]) and ($_GET["logout"])) {
- OC_Preferences::deleteKey(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
- OC_User::logout();
- header("Location: " . OC::$WEBROOT . '/');
- } else {
- if (is_null($file)) {
- $param['file'] = 'index.php';
- }
- $file_ext = substr($param['file'], -3);
- if ($file_ext != 'php'
- || !self::loadAppScriptFile($param)
- ) {
- header('HTTP/1.0 404 Not Found');
- }
- }
- return;
- }
- // Not handled and not logged in
- self::handleLogin();
- }
-
- public static function loadAppScriptFile($param)
- {
- OC_App::loadApps();
- $app = $param['app'];
- $file = $param['file'];
- $app_path = OC_App::getAppPath($app);
- $file = $app_path . '/' . $file;
- unset($app, $app_path);
- if (file_exists($file)) {
- require_once $file;
- return true;
- }
- return false;
- }
-
- public static function loadCSSFile($param)
- {
- $app = $param['app'];
- $file = $param['file'];
- $app_path = OC_App::getAppPath($app);
- if (file_exists($app_path . '/' . $file)) {
- $app_web_path = OC_App::getAppWebPath($app);
- $filepath = $app_web_path . '/' . $file;
- $minimizer = new OC_Minimizer_CSS();
- $info = array($app_path, $app_web_path, $file);
- $minimizer->output(array($info), $filepath);
- }
- }
-
- protected static function handleLogin()
- {
- OC_App::loadApps(array('prelogin'));
- $error = array();
- // remember was checked after last login
- if (OC::tryRememberLogin()) {
- $error[] = 'invalidcookie';
-
- // Someone wants to log in :
- } elseif (OC::tryFormLogin()) {
- $error[] = 'invalidpassword';
-
- // The user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP
- } elseif (OC::tryBasicAuthLogin()) {
- $error[] = 'invalidpassword';
- }
- OC_Util::displayLoginPage(array_unique($error));
- }
-
- protected static function cleanupLoginTokens($user)
- {
- $cutoff = time() - OC_Config::getValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
- $tokens = OC_Preferences::getKeys($user, 'login_token');
- foreach ($tokens as $token) {
- $time = OC_Preferences::getValue($user, 'login_token', $token);
- if ($time < $cutoff) {
- OC_Preferences::deleteKey($user, 'login_token', $token);
- }
- }
- }
-
- protected static function tryRememberLogin()
- {
- if (!isset($_COOKIE["oc_remember_login"])
- || !isset($_COOKIE["oc_token"])
- || !isset($_COOKIE["oc_username"])
- || !$_COOKIE["oc_remember_login"]
- ) {
- return false;
- }
- OC_App::loadApps(array('authentication'));
- if (defined("DEBUG") && DEBUG) {
- OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG);
- }
- // confirm credentials in cookie
- if (isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username'])) {
- // delete outdated cookies
- self::cleanupLoginTokens($_COOKIE['oc_username']);
- // get stored tokens
- $tokens = OC_Preferences::getKeys($_COOKIE['oc_username'], 'login_token');
- // test cookies token against stored tokens
- if (in_array($_COOKIE['oc_token'], $tokens, true)) {
- // replace successfully used token with a new one
- OC_Preferences::deleteKey($_COOKIE['oc_username'], 'login_token', $_COOKIE['oc_token']);
- $token = OC_Util::generate_random_bytes(32);
- OC_Preferences::setValue($_COOKIE['oc_username'], 'login_token', $token, time());
- OC_User::setMagicInCookie($_COOKIE['oc_username'], $token);
- // login
- OC_User::setUserId($_COOKIE['oc_username']);
- OC_Util::redirectToDefaultPage();
- // doesn't return
- }
- // if you reach this point you have changed your password
- // or you are an attacker
- // we can not delete tokens here because users may reach
- // this point multiple times after a password change
- OC_Log::write('core', 'Authentication cookie rejected for user ' . $_COOKIE['oc_username'], OC_Log::WARN);
- }
- OC_User::unsetMagicInCookie();
- return true;
- }
-
- protected static function tryFormLogin()
- {
- if (!isset($_POST["user"]) || !isset($_POST['password'])) {
- return false;
- }
-
- OC_App::loadApps();
-
- //setup extra user backends
- OC_User::setupBackends();
-
- if (OC_User::login($_POST["user"], $_POST["password"])) {
- // setting up the time zone
- if (isset($_POST['timezone-offset'])) {
- $_SESSION['timezone'] = $_POST['timezone-offset'];
- }
-
- self::cleanupLoginTokens($_POST['user']);
- if (!empty($_POST["remember_login"])) {
- if (defined("DEBUG") && DEBUG) {
- OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG);
- }
- $token = OC_Util::generate_random_bytes(32);
- OC_Preferences::setValue($_POST['user'], 'login_token', $token, time());
- OC_User::setMagicInCookie($_POST["user"], $token);
- } else {
- OC_User::unsetMagicInCookie();
- }
- OC_Util::redirectToDefaultPage();
- exit();
- }
- return true;
- }
-
- protected static function tryBasicAuthLogin()
- {
- if (!isset($_SERVER["PHP_AUTH_USER"])
- || !isset($_SERVER["PHP_AUTH_PW"])
- ) {
- return false;
- }
- OC_App::loadApps(array('authentication'));
- if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
- //OC_Log::write('core',"Logged in with HTTP Authentication", OC_Log::DEBUG);
- OC_User::unsetMagicInCookie();
- $_REQUEST['redirect_url'] = (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '');
- OC_Util::redirectToDefaultPage();
- }
- return true;
- }
+ /**
+ * Associative array for autoloading. classname => filename
+ */
+ public static $CLASSPATH = array();
+ /**
+ * The installation path for owncloud on the server (e.g. /srv/http/owncloud)
+ */
+ public static $SERVERROOT = '';
+ /**
+ * the current request path relative to the owncloud root (e.g. files/index.php)
+ */
+ private static $SUBURI = '';
+ /**
+ * the owncloud root path for http requests (e.g. owncloud/)
+ */
+ public static $WEBROOT = '';
+ /**
+ * The installation path of the 3rdparty folder on the server (e.g. /srv/http/owncloud/3rdparty)
+ */
+ public static $THIRDPARTYROOT = '';
+ /**
+ * the root path of the 3rdparty folder for http requests (e.g. owncloud/3rdparty)
+ */
+ public static $THIRDPARTYWEBROOT = '';
+ /**
+ * The installation path array of the apps folder on the server (e.g. /srv/http/owncloud) 'path' and
+ * web path in 'url'
+ */
+ public static $APPSROOTS = array();
+ /*
+ * requested app
+ */
+ public static $REQUESTEDAPP = '';
+ /*
+ * requested file of app
+ */
+ public static $REQUESTEDFILE = '';
+ /**
+ * check if owncloud runs in cli mode
+ */
+ public static $CLI = false;
+ /*
+ * OC router
+ */
+ protected static $router = null;
+
+ /**
+ * SPL autoload
+ */
+ public static function autoload($className)
+ {
+ if (array_key_exists($className, OC::$CLASSPATH)) {
+ $path = OC::$CLASSPATH[$className];
+ /** @TODO: Remove this when necessary
+ Remove "apps/" from inclusion path for smooth migration to mutli app dir
+ */
+ if (strpos($path, 'apps/') === 0) {
+ OC_Log::write('core', 'include path for class "' . $className . '" starts with "apps/"', OC_Log::DEBUG);
+ $path = str_replace('apps/', '', $path);
+ }
+ } elseif (strpos($className, 'OC_') === 0) {
+ $path = strtolower(str_replace('_', '/', substr($className, 3)) . '.php');
+ } elseif (strpos($className, 'OC\\') === 0) {
+ $path = strtolower(str_replace('\\', '/', substr($className, 3)) . '.php');
+ } elseif (strpos($className, 'OCP\\') === 0) {
+ $path = 'public/' . strtolower(str_replace('\\', '/', substr($className, 3)) . '.php');
+ } elseif (strpos($className, 'OCA\\') === 0) {
+ foreach(self::$APPSROOTS as $appDir) {
+ $path = $appDir['path'] . '/' . strtolower(str_replace('\\', '/', substr($className, 3)) . '.php');
+ $fullPath = stream_resolve_include_path($path);
+ if (file_exists($fullPath)) {
+ require_once $fullPath;
+ return false;
+ }
+ }
+ } elseif (strpos($className, 'Sabre_') === 0) {
+ $path = str_replace('_', '/', $className) . '.php';
+ } elseif (strpos($className, 'Symfony\\Component\\Routing\\') === 0) {
+ $path = 'symfony/routing/' . str_replace('\\', '/', $className) . '.php';
+ } elseif (strpos($className, 'Sabre\\VObject') === 0) {
+ $path = str_replace('\\', '/', $className) . '.php';
+ } elseif (strpos($className, 'Test_') === 0) {
+ $path = 'tests/lib/' . strtolower(str_replace('_', '/', substr($className, 5)) . '.php');
+ } else {
+ return false;
+ }
+
+ if ($fullPath = stream_resolve_include_path($path)) {
+ require_once $fullPath;
+ }
+ return false;
+ }
+
+ public static function initPaths()
+ {
+ // calculate the root directories
+ OC::$SERVERROOT = str_replace("\\", '/', substr(__DIR__, 0, -4));
+ OC::$SUBURI = str_replace("\\", "/", substr(realpath($_SERVER["SCRIPT_FILENAME"]), strlen(OC::$SERVERROOT)));
+ $scriptName = $_SERVER["SCRIPT_NAME"];
+ if (substr($scriptName, -1) == '/') {
+ $scriptName .= 'index.php';
+ //make sure suburi follows the same rules as scriptName
+ if (substr(OC::$SUBURI, -9) != 'index.php') {
+ if (substr(OC::$SUBURI, -1) != '/') {
+ OC::$SUBURI = OC::$SUBURI . '/';
+ }
+ OC::$SUBURI = OC::$SUBURI . 'index.php';
+ }
+ }
+
+ OC::$WEBROOT = substr($scriptName, 0, strlen($scriptName) - strlen(OC::$SUBURI));
+
+ if (OC::$WEBROOT != '' and OC::$WEBROOT[0] !== '/') {
+ OC::$WEBROOT = '/' . OC::$WEBROOT;
+ }
+
+ // ensure we can find OC_Config
+ set_include_path(
+ OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
+ get_include_path()
+ );
+
+ // search the 3rdparty folder
+ if (OC_Config::getValue('3rdpartyroot', '') <> '' and OC_Config::getValue('3rdpartyurl', '') <> '') {
+ OC::$THIRDPARTYROOT = OC_Config::getValue('3rdpartyroot', '');
+ OC::$THIRDPARTYWEBROOT = OC_Config::getValue('3rdpartyurl', '');
+ } elseif (file_exists(OC::$SERVERROOT . '/3rdparty')) {
+ OC::$THIRDPARTYROOT = OC::$SERVERROOT;
+ OC::$THIRDPARTYWEBROOT = OC::$WEBROOT;
+ } elseif (file_exists(OC::$SERVERROOT . '/../3rdparty')) {
+ OC::$THIRDPARTYWEBROOT = rtrim(dirname(OC::$WEBROOT), '/');
+ OC::$THIRDPARTYROOT = rtrim(dirname(OC::$SERVERROOT), '/');
+ } else {
+ echo("3rdparty directory not found! Please put the ownCloud 3rdparty folder in the ownCloud folder or the folder above. You can also configure the location in the config.php file.");
+ exit;
+ }
+ // search the apps folder
+ $config_paths = OC_Config::getValue('apps_paths', array());
+ if (!empty($config_paths)) {
+ foreach ($config_paths as $paths) {
+ if (isset($paths['url']) && isset($paths['path'])) {
+ $paths['url'] = rtrim($paths['url'], '/');
+ $paths['path'] = rtrim($paths['path'], '/');
+ OC::$APPSROOTS[] = $paths;
+ }
+ }
+ } elseif (file_exists(OC::$SERVERROOT . '/apps')) {
+ OC::$APPSROOTS[] = array('path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true);
+ } elseif (file_exists(OC::$SERVERROOT . '/../apps')) {
+ OC::$APPSROOTS[] = array('path' => rtrim(dirname(OC::$SERVERROOT), '/') . '/apps', 'url' => '/apps', 'writable' => true);
+ }
+
+ if (empty(OC::$APPSROOTS)) {
+ echo("apps directory not found! Please put the ownCloud apps folder in the ownCloud folder or the folder above. You can also configure the location in the config.php file.");
+ exit;
+ }
+ $paths = array();
+ foreach (OC::$APPSROOTS as $path)
+ $paths[] = $path['path'];
+
+ // set the right include path
+ set_include_path(
+ OC::$SERVERROOT . '/lib' . PATH_SEPARATOR .
+ OC::$SERVERROOT . '/config' . PATH_SEPARATOR .
+ OC::$THIRDPARTYROOT . '/3rdparty' . PATH_SEPARATOR .
+ implode($paths, PATH_SEPARATOR) . PATH_SEPARATOR .
+ get_include_path() . PATH_SEPARATOR .
+ OC::$SERVERROOT
+ );
+ }
+
+ public static function checkConfig() {
+ if (file_exists(OC::$SERVERROOT . "/config/config.php") and !is_writable(OC::$SERVERROOT . "/config/config.php")) {
+ $tmpl = new OC_Template('', 'error', 'guest');
+ $tmpl->assign('errors', array(1 => array('error' => "Can't write into config directory 'config'", 'hint' => "You can usually fix this by giving the webserver user write access to the config directory in owncloud")));
+ $tmpl->printPage();
+ exit();
+ }
+ }
+
+ public static function checkInstalled()
+ {
+ // Redirect to installer if not installed
+ if (!OC_Config::getValue('installed', false) && OC::$SUBURI != '/index.php') {
+ if (!OC::$CLI) {
+ $url = 'http://' . $_SERVER['SERVER_NAME'] . OC::$WEBROOT . '/index.php';
+ header("Location: $url");
+ }
+ exit();
+ }
+ }
+
+ public static function checkSSL()
+ {
+ // redirect to https site if configured
+ if (OC_Config::getValue("forcessl", false)) {
+ header('Strict-Transport-Security: max-age=31536000');
+ ini_set("session.cookie_secure", "on");
+ if (OC_Request::serverProtocol() <> 'https' and !OC::$CLI) {
+ $url = "https://" . OC_Request::serverHost() . $_SERVER['REQUEST_URI'];
+ header("Location: $url");
+ exit();
+ }
+ }
+ }
+
+ public static function checkMaintenanceMode() {
+ // Allow ajax update script to execute without being stopped
+ if (OC_Config::getValue('maintenance', false) && OC::$SUBURI != '/core/ajax/update.php') {
+ // send http status 503
+ header('HTTP/1.1 503 Service Temporarily Unavailable');
+ header('Status: 503 Service Temporarily Unavailable');
+ header('Retry-After: 120');
+
+ // render error page
+ $tmpl = new OC_Template('', 'error', 'guest');
+ $tmpl->assign('errors', array(1 => array('error' => 'ownCloud is in maintenance mode')));
+ $tmpl->printPage();
+ exit();
+ }
+ }
+
+ public static function checkUpgrade($showTemplate = true) {
+ if (OC_Config::getValue('installed', false)) {
+ $installedVersion = OC_Config::getValue('version', '0.0.0');
+ $currentVersion = implode('.', OC_Util::getVersion());
+ if (version_compare($currentVersion, $installedVersion, '>')) {
+ if ($showTemplate && !OC_Config::getValue('maintenance', false)) {
+ OC_Config::setValue('maintenance', true);
+ OC_Log::write('core', 'starting upgrade from ' . $installedVersion . ' to ' . $currentVersion, OC_Log::DEBUG);
+ $tmpl = new OC_Template('', 'update', 'guest');
+ $tmpl->assign('version', OC_Util::getVersionString());
+ $tmpl->printPage();
+ exit();
+ } else {
+ return true;
+ }
+ }
+ return false;
+ }
+ }
+
+ public static function initTemplateEngine()
+ {
+ // Add the stuff we need always
+ OC_Util::addScript("jquery-1.7.2.min");
+ OC_Util::addScript("jquery-ui-1.10.0.custom");
+ OC_Util::addScript("jquery-showpassword");
+ OC_Util::addScript("jquery.infieldlabel");
+ OC_Util::addScript("jquery-tipsy");
+ OC_Util::addScript("oc-dialogs");
+ OC_Util::addScript("js");
+ OC_Util::addScript("eventsource");
+ OC_Util::addScript("config");
+ //OC_Util::addScript( "multiselect" );
+ OC_Util::addScript('search', 'result');
+ OC_Util::addScript('router');
+
+ OC_Util::addStyle("styles");
+ OC_Util::addStyle("multiselect");
+ OC_Util::addStyle("jquery-ui-1.10.0.custom");
+ OC_Util::addStyle("jquery-tipsy");
+ OC_Util::addScript("oc-requesttoken");
+ }
+
+ public static function initSession()
+ {
+ // prevents javascript from accessing php session cookies
+ ini_set('session.cookie_httponly', '1;');
+
+ // set the session name to the instance id - which is unique
+ session_name(OC_Util::getInstanceId());
+
+ // (re)-initialize session
+ session_start();
+
+ // regenerate session id periodically to avoid session fixation
+ if (!isset($_SESSION['SID_CREATED'])) {
+ $_SESSION['SID_CREATED'] = time();
+ } else if (time() - $_SESSION['SID_CREATED'] > 900) {
+ session_regenerate_id(true);
+ $_SESSION['SID_CREATED'] = time();
+ }
+
+ // session timeout
+ if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
+ if (isset($_COOKIE[session_name()])) {
+ setcookie(session_name(), '', time() - 42000, '/');
+ }
+ session_unset();
+ session_destroy();
+ session_start();
+ }
+ $_SESSION['LAST_ACTIVITY'] = time();
+ }
+
+ public static function getRouter()
+ {
+ if (!isset(OC::$router)) {
+ OC::$router = new OC_Router();
+ OC::$router->loadRoutes();
+ }
+
+ return OC::$router;
+ }
+
+
+ public static function loadAppClassPaths()
+ {
+ foreach(OC_APP::getEnabledApps() as $app) {
+ $file = OC_App::getAppPath($app).'/appinfo/classpath.php';
+ if(file_exists($file)) {
+ require_once $file;
+ }
+ }
+ }
+
+
+ public static function init()
+ {
+ // register autoloader
+ spl_autoload_register(array('OC', 'autoload'));
+ setlocale(LC_ALL, 'en_US.UTF-8');
+
+ // set some stuff
+ //ob_start();
+ error_reporting(E_ALL | E_STRICT);
+ if (defined('DEBUG') && DEBUG) {
+ ini_set('display_errors', 1);
+ }
+ self::$CLI = (php_sapi_name() == 'cli');
+
+ date_default_timezone_set('UTC');
+ ini_set('arg_separator.output', '&amp;');
+
+ // try to switch magic quotes off.
+ if (get_magic_quotes_gpc()) {
+ @set_magic_quotes_runtime(false);
+ }
+
+ //try to configure php to enable big file uploads.
+ //this doesn´t work always depending on the webserver and php configuration.
+ //Let´s try to overwrite some defaults anyways
+
+ //try to set the maximum execution time to 60min
+ @set_time_limit(3600);
+ @ini_set('max_execution_time', 3600);
+ @ini_set('max_input_time', 3600);
+
+ //try to set the maximum filesize to 10G
+ @ini_set('upload_max_filesize', '10G');
+ @ini_set('post_max_size', '10G');
+ @ini_set('file_uploads', '50');
+
+ //try to set the session lifetime to 60min
+ @ini_set('gc_maxlifetime', '3600');
+
+ //copy http auth headers for apache+php-fcgid work around
+ if (isset($_SERVER['HTTP_XAUTHORIZATION']) && !isset($_SERVER['HTTP_AUTHORIZATION'])) {
+ $_SERVER['HTTP_AUTHORIZATION'] = $_SERVER['HTTP_XAUTHORIZATION'];
+ }
+
+ //set http auth headers for apache+php-cgi work around
+ if (isset($_SERVER['HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['HTTP_AUTHORIZATION'], $matches)) {
+ list($name, $password) = explode(':', base64_decode($matches[1]), 2);
+ $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
+ $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
+ }
+
+ //set http auth headers for apache+php-cgi work around if variable gets renamed by apache
+ if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']) && preg_match('/Basic\s+(.*)$/i', $_SERVER['REDIRECT_HTTP_AUTHORIZATION'], $matches)) {
+ list($name, $password) = explode(':', base64_decode($matches[1]), 2);
+ $_SERVER['PHP_AUTH_USER'] = strip_tags($name);
+ $_SERVER['PHP_AUTH_PW'] = strip_tags($password);
+ }
+
+ self::initPaths();
+
+ register_shutdown_function(array('OC_Log', 'onShutdown'));
+ set_error_handler(array('OC_Log', 'onError'));
+ set_exception_handler(array('OC_Log', 'onException'));
+
+ // set debug mode if an xdebug session is active
+ if (!defined('DEBUG') || !DEBUG) {
+ if (isset($_COOKIE['XDEBUG_SESSION'])) {
+ define('DEBUG', true);
+ }
+ }
+
+ // register the stream wrappers
+ require_once 'streamwrappers.php';
+ stream_wrapper_register("fakedir", "OC_FakeDirStream");
+ stream_wrapper_register('static', 'OC_StaticStreamWrapper');
+ stream_wrapper_register('close', 'OC_CloseStreamWrapper');
+
+ self::checkConfig();
+ self::checkInstalled();
+ self::checkSSL();
+ self::initSession();
+ self::initTemplateEngine();
+ self::checkMaintenanceMode();
+ self::checkUpgrade();
+
+ $errors = OC_Util::checkServer();
+ if (count($errors) > 0) {
+ OC_Template::printGuestPage('', 'error', array('errors' => $errors));
+ exit;
+ }
+
+ // User and Groups
+ if (!OC_Config::getValue("installed", false)) {
+ $_SESSION['user_id'] = '';
+ }
+
+ OC_User::useBackend(new OC_User_Database());
+ OC_Group::useBackend(new OC_Group_Database());
+
+ if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SESSION['user_id']) && $_SERVER['PHP_AUTH_USER'] != $_SESSION['user_id']) {
+ OC_User::logout();
+ }
+
+ // Load Apps
+ // This includes plugins for users and filesystems as well
+ global $RUNTIME_NOAPPS;
+ global $RUNTIME_APPTYPES;
+ if (!$RUNTIME_NOAPPS) {
+ if ($RUNTIME_APPTYPES) {
+ OC_App::loadApps($RUNTIME_APPTYPES);
+ } else {
+ OC_App::loadApps();
+ }
+ }
+
+ //setup extra user backends
+ OC_User::setupBackends();
+
+ self::registerCacheHooks();
+ self::registerFilesystemHooks();
+ self::registerShareHooks();
+
+ //make sure temporary files are cleaned up
+ register_shutdown_function(array('OC_Helper', 'cleanTmp'));
+
+ //parse the given parameters
+ self::$REQUESTEDAPP = (isset($_GET['app']) && trim($_GET['app']) != '' && !is_null($_GET['app']) ? str_replace(array('\0', '/', '\\', '..'), '', strip_tags($_GET['app'])) : OC_Config::getValue('defaultapp', 'files'));
+ if (substr_count(self::$REQUESTEDAPP, '?') != 0) {
+ $app = substr(self::$REQUESTEDAPP, 0, strpos(self::$REQUESTEDAPP, '?'));
+ $param = substr($_GET['app'], strpos($_GET['app'], '?') + 1);
+ parse_str($param, $get);
+ $_GET = array_merge($_GET, $get);
+ self::$REQUESTEDAPP = $app;
+ $_GET['app'] = $app;
+ }
+ self::$REQUESTEDFILE = (isset($_GET['getfile']) ? $_GET['getfile'] : null);
+ if (substr_count(self::$REQUESTEDFILE, '?') != 0) {
+ $file = substr(self::$REQUESTEDFILE, 0, strpos(self::$REQUESTEDFILE, '?'));
+ $param = substr(self::$REQUESTEDFILE, strpos(self::$REQUESTEDFILE, '?') + 1);
+ parse_str($param, $get);
+ $_GET = array_merge($_GET, $get);
+ self::$REQUESTEDFILE = $file;
+ $_GET['getfile'] = $file;
+ }
+ if (!is_null(self::$REQUESTEDFILE)) {
+ $subdir = OC_App::getAppPath(OC::$REQUESTEDAPP) . '/' . self::$REQUESTEDFILE;
+ $parent = OC_App::getAppPath(OC::$REQUESTEDAPP);
+ if (!OC_Helper::issubdirectory($subdir, $parent)) {
+ self::$REQUESTEDFILE = null;
+ header('HTTP/1.0 404 Not Found');
+ exit;
+ }
+ }
+
+ // write error into log if locale can't be set
+ if (OC_Util::issetlocaleworking() == false) {
+ OC_Log::write('core', 'setting locate to en_US.UTF-8 failed. Support is probably not installed on your system', OC_Log::ERROR);
+ }
+ if (OC_Config::getValue('installed', false)) {
+ if (OC_Appconfig::getValue('core', 'backgroundjobs_mode', 'ajax') == 'ajax') {
+ OC_Util::addScript('backgroundjobs');
+ }
+ }
+ }
+
+ /**
+ * register hooks for the cache
+ */
+ public static function registerCacheHooks()
+ {
+ // register cache cleanup jobs
+ OC_BackgroundJob_RegularTask::register('OC_Cache_FileGlobal', 'gc');
+ OC_Hook::connect('OC_User', 'post_login', 'OC_Cache_File', 'loginListener');
+ }
+
+ /**
+ * register hooks for the filesystem
+ */
+ public static function registerFilesystemHooks()
+ {
+ // Check for blacklisted files
+ OC_Hook::connect('OC_Filesystem', 'write', 'OC_Filesystem', 'isBlacklisted');
+ OC_Hook::connect('OC_Filesystem', 'rename', 'OC_Filesystem', 'isBlacklisted');
+ }
+
+ /**
+ * register hooks for sharing
+ */
+ public static function registerShareHooks()
+ {
+ OC_Hook::connect('OC_User', 'post_deleteUser', 'OCP\Share', 'post_deleteUser');
+ OC_Hook::connect('OC_User', 'post_addToGroup', 'OCP\Share', 'post_addToGroup');
+ OC_Hook::connect('OC_User', 'post_removeFromGroup', 'OCP\Share', 'post_removeFromGroup');
+ OC_Hook::connect('OC_User', 'post_deleteGroup', 'OCP\Share', 'post_deleteGroup');
+ }
+
+ /**
+ * @brief Handle the request
+ */
+ public static function handleRequest()
+ {
+ // load all the classpaths from the enabled apps so they are available
+ // in the routing files of each app
+ OC::loadAppClassPaths();
+
+ try {
+ OC::getRouter()->match(OC_Request::getPathInfo());
+ return;
+ } catch (Symfony\Component\Routing\Exception\ResourceNotFoundException $e) {
+ //header('HTTP/1.0 404 Not Found');
+ } catch (Symfony\Component\Routing\Exception\MethodNotAllowedException $e) {
+ OC_Response::setStatus(405);
+ return;
+ }
+ $app = OC::$REQUESTEDAPP;
+ $file = OC::$REQUESTEDFILE;
+ $param = array('app' => $app, 'file' => $file);
+ // Handle app css files
+ if (substr($file, -3) == 'css') {
+ self::loadCSSFile($param);
+ return;
+ }
+
+ if (!OC_Config::getValue('installed', false)) {
+ require_once 'core/setup.php';
+ exit();
+ }
+
+ // Handle redirect URL for logged in users
+ if (isset($_REQUEST['redirect_url']) && OC_User::isLoggedIn()) {
+ $location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
+ header('Location: ' . $location);
+ return;
+ }
+ // Handle WebDAV
+ if ($_SERVER['REQUEST_METHOD'] == 'PROPFIND') {
+ header('location: ' . OC_Helper::linkToRemote('webdav'));
+ return;
+ }
+
+ // Someone is logged in :
+ if (OC_User::isLoggedIn()) {
+ OC_App::loadApps();
+ OC_User::setupBackends();
+ if (isset($_GET["logout"]) and ($_GET["logout"])) {
+ if (isset($_COOKIE['oc_token'])) {
+ OC_Preferences::deleteKey(OC_User::getUser(), 'login_token', $_COOKIE['oc_token']);
+ }
+ OC_User::logout();
+ header("Location: " . OC::$WEBROOT . '/');
+ } else {
+ if (is_null($file)) {
+ $param['file'] = 'index.php';
+ }
+ $file_ext = substr($param['file'], -3);
+ if ($file_ext != 'php'
+ || !self::loadAppScriptFile($param)
+ ) {
+ header('HTTP/1.0 404 Not Found');
+ }
+ }
+ return;
+ }
+ // Not handled and not logged in
+ self::handleLogin();
+ }
+
+ public static function loadAppScriptFile($param)
+ {
+ OC_App::loadApps();
+ $app = $param['app'];
+ $file = $param['file'];
+ $app_path = OC_App::getAppPath($app);
+ $file = $app_path . '/' . $file;
+ unset($app, $app_path);
+ if (file_exists($file)) {
+ require_once $file;
+ return true;
+ }
+ return false;
+ }
+
+ public static function loadCSSFile($param)
+ {
+ $app = $param['app'];
+ $file = $param['file'];
+ $app_path = OC_App::getAppPath($app);
+ if (file_exists($app_path . '/' . $file)) {
+ $app_web_path = OC_App::getAppWebPath($app);
+ $filepath = $app_web_path . '/' . $file;
+ $minimizer = new OC_Minimizer_CSS();
+ $info = array($app_path, $app_web_path, $file);
+ $minimizer->output(array($info), $filepath);
+ }
+ }
+
+ protected static function handleLogin()
+ {
+ OC_App::loadApps(array('prelogin'));
+ $error = array();
+ // remember was checked after last login
+ if (OC::tryRememberLogin()) {
+ $error[] = 'invalidcookie';
+
+ // Someone wants to log in :
+ } elseif (OC::tryFormLogin()) {
+ $error[] = 'invalidpassword';
+
+ // The user is already authenticated using Apaches AuthType Basic... very usable in combination with LDAP
+ } elseif (OC::tryBasicAuthLogin()) {
+ $error[] = 'invalidpassword';
+ }
+ OC_Util::displayLoginPage(array_unique($error));
+ }
+
+ protected static function cleanupLoginTokens($user)
+ {
+ $cutoff = time() - OC_Config::getValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
+ $tokens = OC_Preferences::getKeys($user, 'login_token');
+ foreach ($tokens as $token) {
+ $time = OC_Preferences::getValue($user, 'login_token', $token);
+ if ($time < $cutoff) {
+ OC_Preferences::deleteKey($user, 'login_token', $token);
+ }
+ }
+ }
+
+ protected static function tryRememberLogin()
+ {
+ if (!isset($_COOKIE["oc_remember_login"])
+ || !isset($_COOKIE["oc_token"])
+ || !isset($_COOKIE["oc_username"])
+ || !$_COOKIE["oc_remember_login"]
+ ) {
+ return false;
+ }
+ OC_App::loadApps(array('authentication'));
+ if (defined("DEBUG") && DEBUG) {
+ OC_Log::write('core', 'Trying to login from cookie', OC_Log::DEBUG);
+ }
+ // confirm credentials in cookie
+ if (isset($_COOKIE['oc_token']) && OC_User::userExists($_COOKIE['oc_username'])) {
+ // delete outdated cookies
+ self::cleanupLoginTokens($_COOKIE['oc_username']);
+ // get stored tokens
+ $tokens = OC_Preferences::getKeys($_COOKIE['oc_username'], 'login_token');
+ // test cookies token against stored tokens
+ if (in_array($_COOKIE['oc_token'], $tokens, true)) {
+ // replace successfully used token with a new one
+ OC_Preferences::deleteKey($_COOKIE['oc_username'], 'login_token', $_COOKIE['oc_token']);
+ $token = OC_Util::generate_random_bytes(32);
+ OC_Preferences::setValue($_COOKIE['oc_username'], 'login_token', $token, time());
+ OC_User::setMagicInCookie($_COOKIE['oc_username'], $token);
+ // login
+ OC_User::setUserId($_COOKIE['oc_username']);
+ OC_Util::redirectToDefaultPage();
+ // doesn't return
+ }
+ // if you reach this point you have changed your password
+ // or you are an attacker
+ // we can not delete tokens here because users may reach
+ // this point multiple times after a password change
+ OC_Log::write('core', 'Authentication cookie rejected for user ' . $_COOKIE['oc_username'], OC_Log::WARN);
+ }
+ OC_User::unsetMagicInCookie();
+ return true;
+ }
+
+ protected static function tryFormLogin()
+ {
+ if (!isset($_POST["user"]) || !isset($_POST['password'])) {
+ return false;
+ }
+
+ OC_App::loadApps();
+
+ //setup extra user backends
+ OC_User::setupBackends();
+
+ if (OC_User::login($_POST["user"], $_POST["password"])) {
+ // setting up the time zone
+ if (isset($_POST['timezone-offset'])) {
+ $_SESSION['timezone'] = $_POST['timezone-offset'];
+ }
+
+ self::cleanupLoginTokens($_POST['user']);
+ if (!empty($_POST["remember_login"])) {
+ if (defined("DEBUG") && DEBUG) {
+ OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG);
+ }
+ $token = OC_Util::generate_random_bytes(32);
+ OC_Preferences::setValue($_POST['user'], 'login_token', $token, time());
+ OC_User::setMagicInCookie($_POST["user"], $token);
+ } else {
+ OC_User::unsetMagicInCookie();
+ }
+ OC_Util::redirectToDefaultPage();
+ exit();
+ }
+ return true;
+ }
+
+ protected static function tryBasicAuthLogin()
+ {
+ if (!isset($_SERVER["PHP_AUTH_USER"])
+ || !isset($_SERVER["PHP_AUTH_PW"])
+ ) {
+ return false;
+ }
+ OC_App::loadApps(array('authentication'));
+ if (OC_User::login($_SERVER["PHP_AUTH_USER"], $_SERVER["PHP_AUTH_PW"])) {
+ //OC_Log::write('core',"Logged in with HTTP Authentication", OC_Log::DEBUG);
+ OC_User::unsetMagicInCookie();
+ $_REQUEST['redirect_url'] = (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '');
+ OC_Util::redirectToDefaultPage();
+ }
+ return true;
+ }
}
// define runtime variables - unless this already has been done
if (!isset($RUNTIME_NOAPPS)) {
- $RUNTIME_NOAPPS = false;
+ $RUNTIME_NOAPPS = false;
}
if (!function_exists('get_temp_dir')) {
- function get_temp_dir()
- {
- if ($temp = ini_get('upload_tmp_dir')) return $temp;
- if ($temp = getenv('TMP')) return $temp;
- if ($temp = getenv('TEMP')) return $temp;
- if ($temp = getenv('TMPDIR')) return $temp;
- $temp = tempnam(__FILE__, '');
- if (file_exists($temp)) {
- unlink($temp);
- return dirname($temp);
- }
- if ($temp = sys_get_temp_dir()) return $temp;
-
- return null;
- }
+ function get_temp_dir()
+ {
+ if ($temp = ini_get('upload_tmp_dir')) return $temp;
+ if ($temp = getenv('TMP')) return $temp;
+ if ($temp = getenv('TEMP')) return $temp;
+ if ($temp = getenv('TMPDIR')) return $temp;
+ $temp = tempnam(__FILE__, '');
+ if (file_exists($temp)) {
+ unlink($temp);
+ return dirname($temp);
+ }
+ if ($temp = sys_get_temp_dir()) return $temp;
+
+ return null;
+ }
}
OC::init();
diff --git a/lib/cache/apc.php b/lib/cache/apc.php
index 6dda0a0ff8c..895d307ea26 100644
--- a/lib/cache/apc.php
+++ b/lib/cache/apc.php
@@ -57,7 +57,7 @@ class OC_Cache_APC {
if(!function_exists('apc_exists')) {
function apc_exists($keys)
{
- $result;
+ $result=false;
apc_fetch($keys, $result);
return $result;
}
diff --git a/lib/connector/sabre/ServiceUnavailable.php b/lib/connector/sabre/ServiceUnavailable.php
new file mode 100644
index 00000000000..c1cc815c989
--- /dev/null
+++ b/lib/connector/sabre/ServiceUnavailable.php
@@ -0,0 +1,22 @@
+<?php
+/**
+ * ownCloud
+ *
+ * @author Thomas Müller
+ * @copyright 2013 Thomas Müller <thomas.mueller@tmit.eu>
+ *
+ * @license AGPL3
+ */
+
+class Sabre_DAV_Exception_ServiceUnavailable extends Sabre_DAV_Exception {
+
+ /**
+ * Returns the HTTP statuscode for this exception
+ *
+ * @return int
+ */
+ public function getHTTPCode() {
+
+ return 503;
+ }
+}
diff --git a/lib/connector/sabre/client.php b/lib/connector/sabre/client.php
deleted file mode 100644
index 8df5fb9a9ad..00000000000
--- a/lib/connector/sabre/client.php
+++ /dev/null
@@ -1,173 +0,0 @@
-<?php
-
-/**
- * ownCloud
- *
- * @author Bjoern Schiessle
- * @copyright 2012 Bjoern Schiessle <schiessle@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_Connector_Sabre_Client extends Sabre_DAV_Client {
-
- protected $trustedCertificates;
-
- /**
- * Add trusted root certificates to the webdav client.
- *
- * The parameter certificates should be a absulute path to a file which contains
- * all trusted certificates
- *
- * @param string $certificates
- */
- public function addTrustedCertificates($certificates) {
- $this->trustedCertificates = $certificates;
- }
-
- /**
- * Copied from SabreDAV with some modification to use user defined curlSettings
- * Performs an actual HTTP request, and returns the result.
- *
- * If the specified url is relative, it will be expanded based on the base
- * url.
- *
- * The returned array contains 3 keys:
- * * body - the response body
- * * httpCode - a HTTP code (200, 404, etc)
- * * headers - a list of response http headers. The header names have
- * been lowercased.
- *
- * @param string $method
- * @param string $url
- * @param string $body
- * @param array $headers
- * @return array
- */
- public function request($method, $url = '', $body = null, $headers = array()) {
-
- $url = $this->getAbsoluteUrl($url);
-
- $curlSettings = array(
- CURLOPT_RETURNTRANSFER => true,
- // Return headers as part of the response
- CURLOPT_HEADER => true,
- CURLOPT_POSTFIELDS => $body,
- // Automatically follow redirects
- CURLOPT_FOLLOWLOCATION => true,
- CURLOPT_MAXREDIRS => 5,
- );
-
- if($this->trustedCertificates) {
- $curlSettings[CURLOPT_CAINFO] = $this->trustedCertificates;
- }
-
- switch ($method) {
- 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
- // specs...) cURL does unfortunately return an error in this case ("transfer closed transfer closed with
- // ... bytes remaining to read") this can be circumvented by explicitly telling cURL to ignore the
- // response body
- $curlSettings[CURLOPT_NOBODY] = true;
- $curlSettings[CURLOPT_CUSTOMREQUEST] = 'HEAD';
- break;
-
- default:
- $curlSettings[CURLOPT_CUSTOMREQUEST] = $method;
- break;
-
- }
-
- // Adding HTTP headers
- $nHeaders = array();
- foreach($headers as $key=>$value) {
-
- $nHeaders[] = $key . ': ' . $value;
-
- }
- $curlSettings[CURLOPT_HTTPHEADER] = $nHeaders;
-
- if ($this->proxy) {
- $curlSettings[CURLOPT_PROXY] = $this->proxy;
- }
-
- if ($this->userName && $this->authType) {
- $curlType = 0;
- if ($this->authType & self::AUTH_BASIC) {
- $curlType |= CURLAUTH_BASIC;
- }
- if ($this->authType & self::AUTH_DIGEST) {
- $curlType |= CURLAUTH_DIGEST;
- }
- $curlSettings[CURLOPT_HTTPAUTH] = $curlType;
- $curlSettings[CURLOPT_USERPWD] = $this->userName . ':' . $this->password;
- }
-
- list(
- $response,
- $curlInfo,
- $curlErrNo,
- $curlError
- ) = $this->curlRequest($url, $curlSettings);
-
- $headerBlob = substr($response, 0, $curlInfo['header_size']);
- $response = substr($response, $curlInfo['header_size']);
-
- // In the case of 100 Continue, or redirects we'll have multiple lists
- // of headers for each separate HTTP response. We can easily split this
- // because they are separated by \r\n\r\n
- $headerBlob = explode("\r\n\r\n", trim($headerBlob, "\r\n"));
-
- // We only care about the last set of headers
- $headerBlob = $headerBlob[count($headerBlob)-1];
-
- // Splitting headers
- $headerBlob = explode("\r\n", $headerBlob);
-
- $headers = array();
- foreach($headerBlob as $header) {
- $parts = explode(':', $header, 2);
- if (count($parts)==2) {
- $headers[strtolower(trim($parts[0]))] = trim($parts[1]);
- }
- }
-
- $response = array(
- 'body' => $response,
- 'statusCode' => $curlInfo['http_code'],
- 'headers' => $headers
- );
-
- if ($curlErrNo) {
- throw new Sabre_DAV_Exception('[CURL] Error while making request: ' . $curlError . ' (error code: ' . $curlErrNo . ')');
- }
-
- if ($response['statusCode']>=400) {
- switch ($response['statusCode']) {
- case 404:
- throw new Sabre_DAV_Exception_NotFound('Resource ' . $url . ' not found.');
- break;
-
- default:
- throw new Sabre_DAV_Exception('HTTP error response. (errorcode ' . $response['statusCode'] . ')');
- }
- }
-
- return $response;
-
- }
-} \ No newline at end of file
diff --git a/lib/connector/sabre/maintenanceplugin.php b/lib/connector/sabre/maintenanceplugin.php
new file mode 100644
index 00000000000..329fa4443ad
--- /dev/null
+++ b/lib/connector/sabre/maintenanceplugin.php
@@ -0,0 +1,56 @@
+<?php
+
+/**
+ * ownCloud
+ *
+ * @author Thomas Müller
+ * @copyright 2013 Thomas Müller <thomas.mueller@tmit.eu>
+ *
+ * @license AGPL3
+ */
+
+require 'ServiceUnavailable.php';
+
+class OC_Connector_Sabre_MaintenancePlugin extends Sabre_DAV_ServerPlugin
+{
+
+ /**
+ * Reference to main server object
+ *
+ * @var Sabre_DAV_Server
+ */
+ private $server;
+
+ /**
+ * This initializes the plugin.
+ *
+ * This function is called by Sabre_DAV_Server, after
+ * addPlugin is called.
+ *
+ * This method should set up the required event subscriptions.
+ *
+ * @param Sabre_DAV_Server $server
+ * @return void
+ */
+ public function initialize(Sabre_DAV_Server $server) {
+
+ $this->server = $server;
+ $this->server->subscribeEvent('beforeMethod', array($this, 'checkMaintenanceMode'), 10);
+ }
+
+ /**
+ * This method is called before any HTTP method and returns http status code 503
+ * in case the system is in maintenance mode.
+ *
+ * @throws Sabre_DAV_Exception_ServiceUnavailable
+ * @internal param string $method
+ * @return bool
+ */
+ public function checkMaintenanceMode() {
+ if (OC_Config::getValue('maintenance', false)) {
+ throw new Sabre_DAV_Exception_ServiceUnavailable();
+ }
+
+ return true;
+ }
+}
diff --git a/lib/connector/sabre/node.php b/lib/connector/sabre/node.php
index 52350072fb2..026ec9f7ec5 100644
--- a/lib/connector/sabre/node.php
+++ b/lib/connector/sabre/node.php
@@ -176,9 +176,9 @@ abstract class OC_Connector_Sabre_Node implements Sabre_DAV_INode, Sabre_DAV_IPr
* @brief Returns a list of properties for this nodes.;
* @param array $properties
* @return array
- * @note 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
+ * @note 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
*/
public function getProperties($properties) {
diff --git a/lib/db.php b/lib/db.php
index 7e60b41d230..51f7c7679d4 100644
--- a/lib/db.php
+++ b/lib/db.php
@@ -41,6 +41,8 @@ class OC_DB {
const BACKEND_PDO=0;
const BACKEND_MDB2=1;
+ static private $preparedQueries = array();
+
/**
* @var MDB2_Driver_Common
*/
@@ -121,6 +123,7 @@ class OC_DB {
return true;
}
}
+ self::$preparedQueries = array();
// The global data we need
$name = OC_Config::getValue( "dbname", "owncloud" );
$host = OC_Config::getValue( "dbhost", "" );
@@ -181,7 +184,14 @@ class OC_DB {
try{
self::$PDO=new PDO($dsn, $user, $pass, $opts);
}catch(PDOException $e) {
- OC_Template::printErrorPage( 'can not connect to database, using '.$type.'. ('.$e->getMessage().')' );
+ OC_Log::write('core', $e->getMessage(), OC_Log::FATAL);
+ OC_User::setUserId(null);
+
+ // send http status 503
+ header('HTTP/1.1 503 Service Temporarily Unavailable');
+ header('Status: 503 Service Temporarily Unavailable');
+ OC_Template::printErrorPage('Failed to connect to database');
+ die();
}
// We always, really always want associative arrays
self::$PDO->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
@@ -201,6 +211,7 @@ class OC_DB {
return true;
}
}
+ self::$preparedQueries = array();
// The global data we need
$name = OC_Config::getValue( "dbname", "owncloud" );
$host = OC_Config::getValue( "dbhost", "" );
@@ -277,7 +288,13 @@ class OC_DB {
if( PEAR::isError( self::$MDB2 )) {
OC_Log::write('core', self::$MDB2->getUserInfo(), OC_Log::FATAL);
OC_Log::write('core', self::$MDB2->getMessage(), OC_Log::FATAL);
- OC_Template::printErrorPage( 'can not connect to database, using '.$type.'. ('.self::$MDB2->getUserInfo().')' );
+ OC_User::setUserId(null);
+
+ // send http status 503
+ header('HTTP/1.1 503 Service Temporarily Unavailable');
+ header('Status: 503 Service Temporarily Unavailable');
+ OC_Template::printErrorPage('Failed to connect to database');
+ die();
}
// We always, really always want associative arrays
@@ -321,7 +338,12 @@ class OC_DB {
$query.=$limitsql;
}
}
+ } else {
+ if (isset(self::$preparedQueries[$query])) {
+ return self::$preparedQueries[$query];
+ }
}
+ $rawQuery = $query;
// Optimize the query
$query = self::processQuery( $query );
@@ -343,6 +365,9 @@ class OC_DB {
}
$result=new PDOStatementWrapper($result);
}
+ if (is_null($limit) || $limit == -1) {
+ self::$preparedQueries[$rawQuery] = $result;
+ }
return $result;
}
@@ -428,6 +453,9 @@ class OC_DB {
$CONFIG_DBTABLEPREFIX = OC_Config::getValue( "dbtableprefix", "oc_" );
$CONFIG_DBTYPE = OC_Config::getValue( "dbtype", "sqlite" );
+ // cleanup the cached queries
+ self::$preparedQueries = array();
+
self::connectScheme();
// read file
@@ -495,8 +523,9 @@ class OC_DB {
if (PEAR::isError($previousSchema)) {
$error = $previousSchema->getMessage();
$detail = $previousSchema->getDebugInfo();
- OC_Log::write('core', 'Failed to get existing database structure for upgrading ('.$error.', '.$detail.')', OC_Log::FATAL);
- return false;
+ $message = 'Failed to get existing database structure for updating ('.$error.', '.$detail.')';
+ OC_Log::write('core', $message, OC_Log::FATAL);
+ throw new Exception($message);
}
// Make changes and save them to an in-memory file
@@ -523,8 +552,9 @@ class OC_DB {
if (PEAR::isError($op)) {
$error = $op->getMessage();
$detail = $op->getDebugInfo();
- OC_Log::write('core', 'Failed to update database structure ('.$error.', '.$detail.')', OC_Log::FATAL);
- return false;
+ $message = 'Failed to update database structure ('.$error.', '.$detail.')';
+ OC_Log::write('core', $message, OC_Log::FATAL);
+ throw new Exception($message);
}
return true;
}
@@ -586,7 +616,7 @@ class OC_DB {
error_log('DB error: '.$entry);
OC_Template::printErrorPage( $entry );
}
-
+
if($result->numRows() == 0) {
$query = 'INSERT INTO "' . $table . '" ("'
. implode('","', array_keys($input)) . '") VALUES("'
@@ -621,7 +651,7 @@ class OC_DB {
return $result->execute();
}
-
+
/**
* @brief does minor changes to query
* @param string $query Query string
diff --git a/lib/filecache.php b/lib/filecache.php
index c3256c783e6..7764890ef1a 100644
--- a/lib/filecache.php
+++ b/lib/filecache.php
@@ -23,9 +23,14 @@
* provide caching for filesystem info in the database
*
* not used by OC_Filesystem for reading filesystem info,
- * instread apps should use OC_FileCache::get where possible
+ * instead apps should use OC_FileCache::get where possible
+ *
+ * It will try to keep the data up to date but changes from outside
+ * ownCloud can invalidate the cache
+ *
+ * Methods that take $path and $root params expect $path to be relative, like
+ * /admin/files/file.txt, if $root is false
*
- * It will try to keep the data up to date but changes from outside ownCloud can invalidate the cache
*/
class OC_FileCache{
@@ -59,7 +64,7 @@ class OC_FileCache{
* @param string $path
* @param array data
* @param string root (optional)
- * @note $data is an associative array in the same format as returned
+ * @note $data is an associative array in the same format as returned
* by get
*/
public static function put($path, $data, $root=false) {
@@ -206,7 +211,7 @@ class OC_FileCache{
OC_Cache::remove('fileid/'.$root.$path);
}
-
+
/**
* return array of filenames matching the querty
* @param string $query
@@ -354,7 +359,7 @@ class OC_FileCache{
public static function increaseSize($path, $sizeDiff, $root=false) {
if($sizeDiff==0) return;
$item = OC_FileCache_Cached::get($path);
- //stop walking up the filetree if we hit a non-folder or reached to root folder
+ //stop walking up the filetree if we hit a non-folder or reached the root folder
if($path == '/' || $path=='' || $item['mimetype'] !== 'httpd/unix-directory') {
return;
}
diff --git a/lib/fileproxy/quota.php b/lib/fileproxy/quota.php
index 742e02d471b..503288142aa 100644
--- a/lib/fileproxy/quota.php
+++ b/lib/fileproxy/quota.php
@@ -76,7 +76,7 @@ class OC_FileProxy_Quota extends OC_FileProxy{
$usedSpace=isset($sharedInfo['size'])?$usedSpace-$sharedInfo['size']:$usedSpace;
return $totalSpace-$usedSpace;
}
-
+
public function postFree_space($path, $space) {
$free=$this->getFreeSpace($path);
if($free==-1) {
diff --git a/lib/files.php b/lib/files.php
index 69097e41074..f4e0f140a44 100644
--- a/lib/files.php
+++ b/lib/files.php
@@ -141,7 +141,7 @@ class OC_Files {
*/
public static function get($dir, $files, $only_header = false) {
$xsendfile = false;
- if (isset($_SERVER['MOD_X_SENDFILE_ENABLED']) ||
+ if (isset($_SERVER['MOD_X_SENDFILE_ENABLED']) ||
isset($_SERVER['MOD_X_ACCEL_REDIRECT_ENABLED'])) {
$xsendfile = true;
}
diff --git a/lib/filestorage.php b/lib/filestorage.php
index dd65f4421b7..2e03c4cb6da 100644
--- a/lib/filestorage.php
+++ b/lib/filestorage.php
@@ -21,7 +21,7 @@
*/
/**
- * Provde a common interface to all different storage options
+ * Provide a common interface to all different storage options
*/
abstract class OC_Filestorage{
abstract public function __construct($parameters);
diff --git a/lib/filestorage/local.php b/lib/filestorage/local.php
index 6fe45acf8c5..4a4019a3224 100644
--- a/lib/filestorage/local.php
+++ b/lib/filestorage/local.php
@@ -29,7 +29,15 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
return is_file($this->datadir.$path);
}
public function stat($path) {
- return stat($this->datadir.$path);
+ $fullPath = $this->datadir . $path;
+ $statResult = stat($fullPath);
+
+ if ($statResult['size'] < 0) {
+ $size = self::getFileSizeFromOS($fullPath);
+ $statResult['size'] = $size;
+ $statResult[7] = $size;
+ }
+ return $statResult;
}
public function filetype($path) {
$filetype=filetype($this->datadir.$path);
@@ -42,7 +50,13 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
if($this->is_dir($path)) {
return 0;
}else{
- return filesize($this->datadir.$path);
+ $fullPath = $this->datadir . $path;
+ $fileSize = filesize($fullPath);
+ if ($fileSize < 0) {
+ return self::getFileSizeFromOS($fullPath);
+ }
+
+ return $fileSize;
}
}
public function isReadable($path) {
@@ -78,7 +92,7 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
public function file_get_contents($path) {
return file_get_contents($this->datadir.$path);
}
- public function file_put_contents($path, $data) {
+ public function file_put_contents($path, $data) {//trigger_error("$path = ".var_export($path, 1));
return file_put_contents($this->datadir.$path, $data);
}
public function unlink($path) {
@@ -156,6 +170,30 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
return $return;
}
+ private static function getFileSizeFromOS($fullPath) {
+ $name = strtolower(php_uname('s'));
+ // Windows OS: we use COM to access the filesystem
+ if (strpos($name, 'win') !== false) {
+ if (class_exists('COM')) {
+ $fsobj = new COM("Scripting.FileSystemObject");
+ $f = $fsobj->GetFile($fullPath);
+ return $f->Size;
+ }
+ } else if (strpos($name, 'bsd') !== false) {
+ if (\OC_Helper::is_function_enabled('exec')) {
+ return (float)exec('stat -f %z ' . escapeshellarg($fullPath));
+ }
+ } else if (strpos($name, 'linux') !== false) {
+ if (\OC_Helper::is_function_enabled('exec')) {
+ return (float)exec('stat -c %s ' . escapeshellarg($fullPath));
+ }
+ } else {
+ OC_Log::write('core', 'Unable to determine file size of "'.$fullPath.'". Unknown OS: '.$name, OC_Log::ERROR);
+ }
+
+ return 0;
+ }
+
public function hash($path, $type, $raw=false) {
return hash_file($type, $this->datadir.$path, $raw);
}
@@ -190,6 +228,7 @@ class OC_Filestorage_Local extends OC_Filestorage_Common{
/**
* check if a file or folder has been updated since $time
+ * @param string $path
* @param int $time
* @return bool
*/
diff --git a/lib/filesystem.php b/lib/filesystem.php
index aa03593908d..f185d777def 100644
--- a/lib/filesystem.php
+++ b/lib/filesystem.php
@@ -179,11 +179,11 @@ class OC_Filesystem{
$internalPath=substr($path, strlen($mountPoint));
return $internalPath;
}
-
+
static private function mountPointsLoaded($user) {
return in_array($user, self::$loadedUsers);
}
-
+
/**
* get the storage object for a path
* @param string path
@@ -216,7 +216,7 @@ class OC_Filesystem{
self::mount($options['class'], $options['options'], $mountPoint);
}
}
-
+
if(isset($mountConfig['group'])) {
foreach($mountConfig['group'] as $group=>$mounts) {
if(OC_Group::inGroup($user, $group)) {
@@ -230,7 +230,7 @@ class OC_Filesystem{
}
}
}
-
+
if(isset($mountConfig['user'])) {
foreach($mountConfig['user'] as $mountUser=>$mounts) {
if($user==='all' or strtolower($mountUser)===strtolower($user)) {
@@ -244,16 +244,16 @@ class OC_Filesystem{
}
}
}
-
+
$mtime=filemtime(OC::$SERVERROOT.'/config/mount.php');
$previousMTime=OC_Appconfig::getValue('files', 'mountconfigmtime', 0);
if($mtime>$previousMTime) {//mount config has changed, filecache needs to be updated
OC_FileCache::triggerUpdate();
OC_Appconfig::setValue('files', 'mountconfigmtime', $mtime);
}
- }
+ }
}
-
+
static public function init($root, $user = '') {
if(self::$defaultInstance) {
return false;
diff --git a/lib/filesystemview.php b/lib/filesystemview.php
index e944ae5045d..1fc8e83d68f 100644
--- a/lib/filesystemview.php
+++ b/lib/filesystemview.php
@@ -36,8 +36,12 @@
*
* Filesystem functions are not called directly; they are passed to the correct
* OC_Filestorage object
+ *
+ * @note default root (if $root is empty or '/') is /data/[user]/
+ * @note If you don't include a leading slash, you may encounter problems.
+ * e.g. use $v = new \OC_FilesystemView( '/' . $params['uid'] ); not
+ * $v = new \OC_FilesystemView( $params['uid'] );
*/
-
class OC_FilesystemView {
private $fakeRoot='';
private $internal_path_cache=array();
@@ -430,10 +434,10 @@ class OC_FilesystemView {
$target = $this->fopen($path2.$postFix2, 'w');
$result = OC_Helper::streamCopy($source, $target);
}
- if( $this->fakeRoot==OC_Filesystem::getRoot() ) {
- // If the file to be copied originates within
+ if( $this->fakeRoot==OC_Filesystem::getRoot() ) {
+ // If the file to be copied originates within
// the user's data directory
-
+
OC_Hook::emit(
OC_Filesystem::CLASSNAME,
OC_Filesystem::signal_post_copy,
@@ -454,33 +458,33 @@ class OC_FilesystemView {
OC_Filesystem::signal_post_write,
array( OC_Filesystem::signal_param_path => $path2)
);
-
- } else {
- // If this is not a normal file copy operation
- // and the file originates somewhere else
- // (e.g. a version rollback operation), do not
+
+ } else {
+ // If this is not a normal file copy operation
+ // and the file originates somewhere else
+ // (e.g. a version rollback operation), do not
// perform all the other post_write actions
-
+
// Update webdav properties
OC_Filesystem::removeETagHook(array("path" => $path2), $this->fakeRoot);
-
+
$splitPath2 = explode( '/', $path2 );
-
- // Only cache information about files
- // that are being copied from within
- // the user files directory. Caching
+
+ // Only cache information about files
+ // that are being copied from within
+ // the user files directory. Caching
// other files, like VCS backup files,
// serves no purpose
if ( $splitPath2[1] == 'files' ) {
-
+
OC_FileCache_Update::update($path2, $this->fakeRoot);
-
+
}
-
+
}
-
+
return $result;
-
+
}
}
}
diff --git a/lib/helper.php b/lib/helper.php
index be4e4e52677..d2c6b1695bd 100644
--- a/lib/helper.php
+++ b/lib/helper.php
@@ -31,8 +31,9 @@ class OC_Helper {
/**
* @brief Creates an url using a defined route
* @param $route
- * @param $parameters
- * @param $args array with param=>value, will be appended to the returned url
+ * @param array $parameters
+ * @return
+ * @internal param array $args with param=>value, will be appended to the returned url
* @returns the url
*
* Returns a url to the given app and file.
@@ -128,6 +129,7 @@ class OC_Helper {
/**
* @brief Creates an absolute url for remote use
* @param string $service id
+ * @param bool $add_slash
* @return string the url
*
* Returns a absolute url to the given service.
@@ -139,6 +141,7 @@ class OC_Helper {
/**
* @brief Creates an absolute url for public use
* @param string $service id
+ * @param bool $add_slash
* @return string the url
*
* Returns a absolute url to the given service.
@@ -190,8 +193,9 @@ class OC_Helper {
if(isset($alias[$mimetype])) {
$mimetype=$alias[$mimetype];
}
- // Replace slash with a minus
+ // Replace slash and backslash with a minus
$mimetype = str_replace( "/", "-", $mimetype );
+ $mimetype = str_replace( "\\", "-", $mimetype );
// Is it a dir?
if( $mimetype == "dir" ) {
@@ -220,6 +224,10 @@ class OC_Helper {
* Makes 2048 to 2 kB.
*/
public static function humanFileSize( $bytes ) {
+ if( $bytes < 0 ) {
+ $l = OC_L10N::get('lib');
+ return $l->t("couldn't be determined");
+ }
if( $bytes < 1024 ) {
return "$bytes B";
}
@@ -450,12 +458,14 @@ class OC_Helper {
}
/**
- * detect if a given program is found in the search PATH
- *
- * @param string $program name
- * @param string $optional search path, defaults to $PATH
- * @return bool true if executable program found in path
- */
+ * detect if a given program is found in the search PATH
+ *
+ * @param $name
+ * @param bool $path
+ * @internal param string $program name
+ * @internal param string $optional search path, defaults to $PATH
+ * @return bool true if executable program found in path
+ */
public static function canExecute($name, $path = false) {
// path defaults to PATH from environment if not set
if ($path === false) {
@@ -544,7 +554,7 @@ class OC_Helper {
fclose($fh);
return $file;
}
-
+
/**
* create a temporary folder with an unique filename
* @return string
@@ -620,37 +630,17 @@ class OC_Helper {
return $newpath;
}
- /*
- * checks if $sub is a subdirectory of $parent
+ /**
+ * @brief Checks if $sub is a subdirectory of $parent
*
* @param string $sub
* @param string $parent
* @return bool
*/
public static function issubdirectory($sub, $parent) {
- if($sub == null || $sub == '' || $parent == null || $parent == '') {
- return false;
- }
- $realpath_sub = realpath($sub);
- $realpath_parent = realpath($parent);
- if(($realpath_sub == false && substr_count($realpath_sub, './') != 0) || ($realpath_parent == false && substr_count($realpath_parent, './') != 0)) { //it checks for both ./ and ../
- return false;
- }
- if($realpath_sub && $realpath_sub != '' && $realpath_parent && $realpath_parent != '') {
- if(substr($realpath_sub, 0, strlen($realpath_parent)) == $realpath_parent) {
- return true;
- }
- }else{
- if(substr($sub, 0, strlen($parent)) == $parent) {
- return true;
- }
+ if (strpos(realpath($sub), realpath($parent)) === 0) {
+ return true;
}
- /*echo 'SUB: ' . $sub . "\n";
- echo 'PAR: ' . $parent . "\n";
- echo 'REALSUB: ' . $realpath_sub . "\n";
- echo 'REALPAR: ' . $realpath_parent . "\n";
- echo substr($realpath_sub, 0, strlen($realpath_parent));
- exit;*/
return false;
}
@@ -676,22 +666,22 @@ class OC_Helper {
}
/**
- * @brief replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
- *
- * @param string $input The input string. .Opposite to the PHP build-in function does not accept an array.
- * @param string $replacement The replacement string.
- * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
- * @param int $length Length of the part to be replaced
- * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
- * @return string
- *
- */
+ * @brief replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
+ *
+ * @param $string
+ * @param string $replacement The replacement string.
+ * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
+ * @param int $length Length of the part to be replaced
+ * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
+ * @internal param string $input The input string. .Opposite to the PHP build-in function does not accept an array.
+ * @return string
+ */
public static function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = 'UTF-8') {
$start = intval($start);
$length = intval($length);
$string = mb_substr($string, 0, $start, $encoding) .
- $replacement .
- mb_substr($string, $start+$length, mb_strlen($string, 'UTF-8')-$start, $encoding);
+ $replacement .
+ mb_substr($string, $start+$length, mb_strlen($string, 'UTF-8')-$start, $encoding);
return $string;
}
@@ -758,4 +748,60 @@ class OC_Helper {
}
return $str;
}
+
+ /**
+ * @brief calculates the maximum upload size respecting system settings, free space and user quota
+ *
+ * @param $dir the current folder where the user currently operates
+ * @return number of bytes representing
+ */
+ public static function maxUploadFilesize($dir) {
+ $upload_max_filesize = OCP\Util::computerFileSize(ini_get('upload_max_filesize'));
+ $post_max_size = OCP\Util::computerFileSize(ini_get('post_max_size'));
+ $maxUploadFilesize = min($upload_max_filesize, $post_max_size);
+
+ $freeSpace = OC_Filesystem::free_space($dir);
+ $freeSpace = max($freeSpace, 0);
+
+ return min($maxUploadFilesize, $freeSpace);
+ }
+
+ /**
+ * Checks if a function is available
+ * @param string $function_name
+ * @return bool
+ */
+ public static function is_function_enabled($function_name) {
+ if (!function_exists($function_name)) {
+ return false;
+ }
+ $disabled = explode(', ', ini_get('disable_functions'));
+ if (in_array($function_name, $disabled)) {
+ return false;
+ }
+ $disabled = explode(', ', ini_get('suhosin.executor.func.blacklist'));
+ if (in_array($function_name, $disabled)) {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Calculate the disc space
+ */
+ public static function getStorageInfo() {
+ $rootInfo = OC_FileCache::get('');
+ $used = $rootInfo['size'];
+ if ($used < 0) {
+ $used = 0;
+ }
+ $free = OC_Filesystem::free_space();
+ $total = $free + $used;
+ if ($total == 0) {
+ $total = 1; // prevent division by zero
+ }
+ $relative = round(($used / $total) * 10000) / 100;
+
+ return array('free' => $free, 'used' => $used, 'total' => $total, 'relative' => $relative);
+ }
}
diff --git a/lib/image.php b/lib/image.php
index 2043a452541..cfc6d477395 100644
--- a/lib/image.php
+++ b/lib/image.php
@@ -646,7 +646,7 @@ class OC_Image {
fclose($fh);
return $im;
}
-
+
/**
* @brief Resizes the image preserving ratio.
* @param $maxsize The maximum size of either the width or height.
diff --git a/lib/json.php b/lib/json.php
index 204430411c0..f929e958957 100644
--- a/lib/json.php
+++ b/lib/json.php
@@ -57,9 +57,7 @@ class OC_JSON{
* Check if the user is a admin, send json error msg if not
*/
public static function checkAdminUser() {
- self::checkLoggedIn();
- self::verifyUser();
- if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )) {
+ if( !OC_User::isAdminUser(OC_User::getUser())) {
$l = OC_L10N::get('lib');
self::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
exit();
@@ -70,9 +68,7 @@ class OC_JSON{
* Check if the user is a subadmin, send json error msg if not
*/
public static function checkSubAdminUser() {
- self::checkLoggedIn();
- self::verifyUser();
- if(!OC_Group::inGroup(OC_User::getUser(), 'admin') && !OC_SubAdmin::isSubAdmin(OC_User::getUser())) {
+ if(!OC_SubAdmin::isSubAdmin(OC_User::getUser())) {
$l = OC_L10N::get('lib');
self::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
exit();
@@ -80,19 +76,6 @@ class OC_JSON{
}
/**
- * Check if the user verified the login with his password
- */
- public static function verifyUser() {
- if(OC_Config::getValue('enhancedauth', false) === true) {
- if(!isset($_SESSION['verifiedLogin']) OR $_SESSION['verifiedLogin'] < time()) {
- $l = OC_L10N::get('lib');
- self::error(array( 'data' => array( 'message' => $l->t('Authentication error') )));
- exit();
- }
- }
- }
-
- /**
* Send json error msg
*/
public static function error($data = array()) {
diff --git a/lib/l10n.php b/lib/l10n.php
index f70dfa5e34e..ca53b3cf65c 100644
--- a/lib/l10n.php
+++ b/lib/l10n.php
@@ -141,15 +141,15 @@ class OC_L10N{
}
}
- /**
- * @brief Translating
- * @param $text String The text we need a translation for
- * @param array $parameters default:array() Parameters for sprintf
- * @return \OC_L10N_String Translation or the same text
- *
- * Returns the translation. If no translation is found, $text will be
- * returned.
- */
+ /**
+ * @brief Translating
+ * @param $text String The text we need a translation for
+ * @param array $parameters default:array() Parameters for sprintf
+ * @return \OC_L10N_String Translation or the same text
+ *
+ * Returns the translation. If no translation is found, $text will be
+ * returned.
+ */
public function t($text, $parameters = array()) {
return new OC_L10N_String($this, $text, $parameters);
}
diff --git a/lib/l10n/bg_BG.php b/lib/l10n/bg_BG.php
index 3eb0660d944..31f37458b81 100644
--- a/lib/l10n/bg_BG.php
+++ b/lib/l10n/bg_BG.php
@@ -1,4 +1,34 @@
<?php $TRANSLATIONS = array(
-"Personal" => "Лично",
-"Authentication error" => "Проблем с идентификацията"
+"Help" => "Помощ",
+"Personal" => "Лични",
+"Settings" => "Настройки",
+"Users" => "Потребители",
+"Apps" => "Приложения",
+"Admin" => "Админ",
+"ZIP download is turned off." => "Изтеглянето като ZIP е изключено.",
+"Files need to be downloaded one by one." => "Файловете трябва да се изтеглят един по един.",
+"Back to Files" => "Назад към файловете",
+"Selected files too large to generate zip file." => "Избраните файлове са прекалено големи за генерирането на ZIP архив.",
+"Application is not enabled" => "Приложението не е включено.",
+"Authentication error" => "Възникна проблем с идентификацията",
+"Token expired. Please reload page." => "Ключът е изтекъл, моля презаредете страницата",
+"Files" => "Файлове",
+"Text" => "Текст",
+"Images" => "Снимки",
+"seconds ago" => "преди секунди",
+"1 minute ago" => "преди 1 минута",
+"%d minutes ago" => "преди %d минути",
+"1 hour ago" => "преди 1 час",
+"%d hours ago" => "преди %d часа",
+"today" => "днес",
+"yesterday" => "вчера",
+"%d days ago" => "преди %d дни",
+"last month" => "последният месец",
+"%d months ago" => "преди %d месеца",
+"last year" => "последната година",
+"years ago" => "последните години",
+"%s is available. Get <a href=\"%s\">more information</a>" => "%s е налична. Получете <a href=\"%s\">повече информация</a>",
+"up to date" => "е актуална",
+"updates check is disabled" => "проверката за обновления е изключена",
+"Could not find category \"%s\"" => "Невъзможно откриване на категорията \"%s\""
);
diff --git a/lib/l10n/bn_BD.php b/lib/l10n/bn_BD.php
new file mode 100644
index 00000000000..cb6ff4455a9
--- /dev/null
+++ b/lib/l10n/bn_BD.php
@@ -0,0 +1,29 @@
+<?php $TRANSLATIONS = array(
+"Help" => "সহায়িকা",
+"Personal" => "ব্যক্তিগত",
+"Settings" => "নিয়ামকসমূহ",
+"Users" => "ব্যভহারকারী",
+"Apps" => "অ্যাপ",
+"Admin" => "প্রশাসক",
+"ZIP download is turned off." => "ZIP ডাউনলোড বন্ধ করা আছে।",
+"Files need to be downloaded one by one." => "ফাইলগুলো একে একে ডাউনলোড করা আবশ্যক।",
+"Back to Files" => "ফাইলে ফিরে চল",
+"Selected files too large to generate zip file." => "নির্বাচিত ফাইলগুলো এতই বৃহৎ যে জিপ ফাইল তৈরী করা সম্ভব নয়।",
+"Application is not enabled" => "অ্যাপ্লিকেসনটি সক্রিয় নয়",
+"Authentication error" => "অনুমোদন ঘটিত সমস্যা",
+"Token expired. Please reload page." => "টোকেন মেয়াদোত্তীর্ণ। দয়া করে পৃষ্ঠাটি পূনরায় লোড করুন।",
+"Files" => "ফাইল",
+"seconds ago" => "সেকেন্ড পূর্বে",
+"1 minute ago" => "১ মিনিট পূর্বে",
+"%d minutes ago" => "%d মিনিট পূর্বে",
+"1 hour ago" => "1 ঘন্টা পূর্বে",
+"today" => "আজ",
+"yesterday" => "গতকাল",
+"%d days ago" => "%d দিন পূর্বে",
+"last month" => "গত মাস",
+"last year" => "গত বছর",
+"years ago" => "বছর পূর্বে",
+"%s is available. Get <a href=\"%s\">more information</a>" => "%s এখন সুলভ। <a href=\"%s\">আরও জানুন</a>",
+"up to date" => "সর্বশেষ",
+"updates check is disabled" => "পরিবর্ধন পরীক্ষণ করা বন্ধ রাখা হয়েছে"
+);
diff --git a/lib/l10n/ca.php b/lib/l10n/ca.php
index b3321ef82e1..f6401fa39b6 100644
--- a/lib/l10n/ca.php
+++ b/lib/l10n/ca.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Els fitxers s'han de baixar d'un en un.",
"Back to Files" => "Torna a Fitxers",
"Selected files too large to generate zip file." => "Els fitxers seleccionats son massa grans per generar un fitxer zip.",
+"couldn't be determined" => "no s'ha pogut determinar",
"Application is not enabled" => "L'aplicació no està habilitada",
"Authentication error" => "Error d'autenticació",
"Token expired. Please reload page." => "El testimoni ha expirat. Torneu a carregar la pàgina.",
diff --git a/lib/l10n/cs_CZ.php b/lib/l10n/cs_CZ.php
index fa11e886774..2c823194b96 100644
--- a/lib/l10n/cs_CZ.php
+++ b/lib/l10n/cs_CZ.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Soubory musí být stahovány jednotlivě.",
"Back to Files" => "Zpět k souborům",
"Selected files too large to generate zip file." => "Vybrané soubory jsou příliš velké pro vytvoření zip souboru.",
+"couldn't be determined" => "nelze zjistit",
"Application is not enabled" => "Aplikace není povolena",
"Authentication error" => "Chyba ověření",
"Token expired. Please reload page." => "Token vypršel. Obnovte prosím stránku.",
diff --git a/lib/l10n/de.php b/lib/l10n/de.php
index 4b77bf7210d..c285a07f63a 100644
--- a/lib/l10n/de.php
+++ b/lib/l10n/de.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Die Dateien müssen einzeln heruntergeladen werden.",
"Back to Files" => "Zurück zu \"Dateien\"",
"Selected files too large to generate zip file." => "Die gewählten Dateien sind zu groß, um eine ZIP-Datei zu erstellen.",
+"couldn't be determined" => "Konnte nicht festgestellt werden",
"Application is not enabled" => "Die Anwendung ist nicht aktiviert",
"Authentication error" => "Authentifizierungs-Fehler",
"Token expired. Please reload page." => "Token abgelaufen. Bitte lade die Seite neu.",
diff --git a/lib/l10n/de_DE.php b/lib/l10n/de_DE.php
index e9f0f34a0e1..625ba2ecf20 100644
--- a/lib/l10n/de_DE.php
+++ b/lib/l10n/de_DE.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Die Dateien müssen einzeln heruntergeladen werden.",
"Back to Files" => "Zurück zu \"Dateien\"",
"Selected files too large to generate zip file." => "Die gewählten Dateien sind zu groß, um eine ZIP-Datei zu erstellen.",
+"couldn't be determined" => "konnte nicht ermittelt werden",
"Application is not enabled" => "Die Anwendung ist nicht aktiviert",
"Authentication error" => "Authentifizierungs-Fehler",
"Token expired. Please reload page." => "Token abgelaufen. Bitte laden Sie die Seite neu.",
diff --git a/lib/l10n/el.php b/lib/l10n/el.php
index 315b995ecc9..cf0be24b432 100644
--- a/lib/l10n/el.php
+++ b/lib/l10n/el.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Τα αρχεία πρέπει να ληφθούν ένα-ένα.",
"Back to Files" => "Πίσω στα Αρχεία",
"Selected files too large to generate zip file." => "Τα επιλεγμένα αρχεία είναι μεγάλα ώστε να δημιουργηθεί αρχείο zip.",
+"couldn't be determined" => "δεν μπορούσε να προσδιορισθεί",
"Application is not enabled" => "Δεν ενεργοποιήθηκε η εφαρμογή",
"Authentication error" => "Σφάλμα πιστοποίησης",
"Token expired. Please reload page." => "Το αναγνωριστικό έληξε. Παρακαλώ φορτώστε ξανά την σελίδα.",
diff --git a/lib/l10n/es.php b/lib/l10n/es.php
index f843c42dfd3..8bbc8a8f7b4 100644
--- a/lib/l10n/es.php
+++ b/lib/l10n/es.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Los archivos deben ser descargados uno por uno.",
"Back to Files" => "Volver a Archivos",
"Selected files too large to generate zip file." => "Los archivos seleccionados son demasiado grandes para generar el archivo zip.",
+"couldn't be determined" => "no pudo ser determinado",
"Application is not enabled" => "La aplicación no está habilitada",
"Authentication error" => "Error de autenticación",
"Token expired. Please reload page." => "Token expirado. Por favor, recarga la página.",
diff --git a/lib/l10n/es_AR.php b/lib/l10n/es_AR.php
index 2bbffd39e9e..c32017a10f8 100644
--- a/lib/l10n/es_AR.php
+++ b/lib/l10n/es_AR.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Los archivos deben ser descargados de a uno.",
"Back to Files" => "Volver a archivos",
"Selected files too large to generate zip file." => "Los archivos seleccionados son demasiado grandes para generar el archivo zip.",
+"couldn't be determined" => "no pudo ser determinado",
"Application is not enabled" => "La aplicación no está habilitada",
"Authentication error" => "Error de autenticación",
"Token expired. Please reload page." => "Token expirado. Por favor, recargá la página.",
diff --git a/lib/l10n/eu.php b/lib/l10n/eu.php
index 5d47ecbda23..1941551b176 100644
--- a/lib/l10n/eu.php
+++ b/lib/l10n/eu.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Fitxategiak banan-banan deskargatu behar dira.",
"Back to Files" => "Itzuli fitxategietara",
"Selected files too large to generate zip file." => "Hautatuko fitxategiak oso handiak dira zip fitxategia sortzeko.",
+"couldn't be determined" => "ezin izan da zehaztu",
"Application is not enabled" => "Aplikazioa ez dago gaituta",
"Authentication error" => "Autentikazio errorea",
"Token expired. Please reload page." => "Tokena iraungitu da. Mesedez birkargatu orria.",
diff --git a/lib/l10n/fi_FI.php b/lib/l10n/fi_FI.php
index 6a5734e978d..b8d4b137431 100644
--- a/lib/l10n/fi_FI.php
+++ b/lib/l10n/fi_FI.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Tiedostot on ladattava yksittäin.",
"Back to Files" => "Takaisin tiedostoihin",
"Selected files too large to generate zip file." => "Valitut tiedostot ovat liian suurikokoisia mahtuakseen zip-tiedostoon.",
+"couldn't be determined" => "ei voitu määrittää",
"Application is not enabled" => "Sovellusta ei ole otettu käyttöön",
"Authentication error" => "Todennusvirhe",
"Token expired. Please reload page." => "Valtuutus vanheni. Lataa sivu uudelleen.",
diff --git a/lib/l10n/fr.php b/lib/l10n/fr.php
index 218c22c1d53..c6bf8f7f9c3 100644
--- a/lib/l10n/fr.php
+++ b/lib/l10n/fr.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Les fichiers nécessitent d'être téléchargés un par un.",
"Back to Files" => "Retour aux Fichiers",
"Selected files too large to generate zip file." => "Les fichiers sélectionnés sont trop volumineux pour être compressés.",
+"couldn't be determined" => "impossible à déterminer",
"Application is not enabled" => "L'application n'est pas activée",
"Authentication error" => "Erreur d'authentification",
"Token expired. Please reload page." => "La session a expiré. Veuillez recharger la page.",
diff --git a/lib/l10n/gl.php b/lib/l10n/gl.php
index 1e897959e41..532b3443b44 100644
--- a/lib/l10n/gl.php
+++ b/lib/l10n/gl.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Os ficheiros necesitan seren descargados de un en un.",
"Back to Files" => "Volver aos ficheiros",
"Selected files too large to generate zip file." => "Os ficheiros seleccionados son demasiado grandes como para xerar un ficheiro zip.",
+"couldn't be determined" => "non puido ser determinado",
"Application is not enabled" => "O aplicativo non está activado",
"Authentication error" => "Produciuse un erro na autenticación",
"Token expired. Please reload page." => "Testemuña caducada. Recargue a páxina.",
diff --git a/lib/l10n/hu_HU.php b/lib/l10n/hu_HU.php
index 63704a978c5..e25de3e1ed6 100644
--- a/lib/l10n/hu_HU.php
+++ b/lib/l10n/hu_HU.php
@@ -5,22 +5,31 @@
"Users" => "Felhasználók",
"Apps" => "Alkalmazások",
"Admin" => "Admin",
-"ZIP download is turned off." => "ZIP-letöltés letiltva",
-"Files need to be downloaded one by one." => "A file-okat egyenként kell letölteni",
-"Back to Files" => "Vissza a File-okhoz",
-"Selected files too large to generate zip file." => "Túl nagy file-ok a zip-generáláshoz",
+"ZIP download is turned off." => "A ZIP-letöltés nincs engedélyezve.",
+"Files need to be downloaded one by one." => "A fájlokat egyenként kell letölteni",
+"Back to Files" => "Vissza a Fájlokhoz",
+"Selected files too large to generate zip file." => "A kiválasztott fájlok túl nagyok a zip tömörítéshez.",
+"couldn't be determined" => "nem határozható meg",
"Application is not enabled" => "Az alkalmazás nincs engedélyezve",
"Authentication error" => "Hitelesítési hiba",
-"Token expired. Please reload page." => "A token lejárt. Frissítsd az oldalt.",
+"Token expired. Please reload page." => "A token lejárt. Frissítse az oldalt.",
"Files" => "Fájlok",
"Text" => "Szöveg",
-"seconds ago" => "másodperccel ezelőtt",
-"1 minute ago" => "1 perccel ezelőtt",
-"%d minutes ago" => "%d perccel ezelőtt",
+"Images" => "Képek",
+"seconds ago" => "másodperce",
+"1 minute ago" => "1 perce",
+"%d minutes ago" => "%d perce",
+"1 hour ago" => "1 órája",
+"%d hours ago" => "%d órája",
"today" => "ma",
"yesterday" => "tegnap",
-"%d days ago" => "%d évvel ezelőtt",
+"%d days ago" => "%d napja",
"last month" => "múlt hónapban",
+"%d months ago" => "%d hónapja",
"last year" => "tavaly",
-"years ago" => "évvel ezelőtt"
+"years ago" => "éve",
+"%s is available. Get <a href=\"%s\">more information</a>" => "%s elérhető. <a href=\"%s\">További információ</a>.",
+"up to date" => "a legfrissebb változat",
+"updates check is disabled" => "A frissitések ellenőrzése nincs engedélyezve.",
+"Could not find category \"%s\"" => "Ez a kategória nem található: \"%s\""
);
diff --git a/lib/l10n/id.php b/lib/l10n/id.php
index e31b4caf4f5..8f0e38123b6 100644
--- a/lib/l10n/id.php
+++ b/lib/l10n/id.php
@@ -12,17 +12,23 @@
"Application is not enabled" => "aplikasi tidak diaktifkan",
"Authentication error" => "autentikasi bermasalah",
"Token expired. Please reload page." => "token kadaluarsa.mohon perbaharui laman.",
+"Files" => "Berkas",
"Text" => "teks",
+"Images" => "Gambar",
"seconds ago" => "beberapa detik yang lalu",
"1 minute ago" => "1 menit lalu",
"%d minutes ago" => "%d menit lalu",
+"1 hour ago" => "1 jam yang lalu",
+"%d hours ago" => "%d jam yang lalu",
"today" => "hari ini",
"yesterday" => "kemarin",
"%d days ago" => "%d hari lalu",
"last month" => "bulan kemarin",
+"%d months ago" => "%d bulan yang lalu",
"last year" => "tahun kemarin",
"years ago" => "beberapa tahun lalu",
"%s is available. Get <a href=\"%s\">more information</a>" => "%s tersedia. dapatkan <a href=\"%s\"> info lebih lanjut</a>",
"up to date" => "terbaru",
-"updates check is disabled" => "pengecekan pembaharuan sedang non-aktifkan"
+"updates check is disabled" => "pengecekan pembaharuan sedang non-aktifkan",
+"Could not find category \"%s\"" => "Tidak dapat menemukan kategori \"%s\""
);
diff --git a/lib/l10n/is.php b/lib/l10n/is.php
new file mode 100644
index 00000000000..8fdb45a05cd
--- /dev/null
+++ b/lib/l10n/is.php
@@ -0,0 +1,34 @@
+<?php $TRANSLATIONS = array(
+"Help" => "Hjálp",
+"Personal" => "Um mig",
+"Settings" => "Stillingar",
+"Users" => "Notendur",
+"Apps" => "Forrit",
+"Admin" => "Stjórnun",
+"ZIP download is turned off." => "Slökkt á ZIP niðurhali.",
+"Files need to be downloaded one by one." => "Skrárnar verður að sækja eina og eina",
+"Back to Files" => "Aftur í skrár",
+"Selected files too large to generate zip file." => "Valdar skrár eru of stórar til að búa til ZIP skrá.",
+"Application is not enabled" => "Forrit ekki virkt",
+"Authentication error" => "Villa við auðkenningu",
+"Token expired. Please reload page." => "Auðkenning útrunnin. Vinsamlegast skráðu þig aftur inn.",
+"Files" => "Skrár",
+"Text" => "Texti",
+"Images" => "Myndir",
+"seconds ago" => "sek.",
+"1 minute ago" => "Fyrir 1 mínútu",
+"%d minutes ago" => "fyrir %d mínútum",
+"1 hour ago" => "Fyrir 1 klst.",
+"%d hours ago" => "fyrir %d klst.",
+"today" => "í dag",
+"yesterday" => "í gær",
+"%d days ago" => "fyrir %d dögum",
+"last month" => "síðasta mánuði",
+"%d months ago" => "fyrir %d mánuðum",
+"last year" => "síðasta ári",
+"years ago" => "einhverjum árum",
+"%s is available. Get <a href=\"%s\">more information</a>" => "%s er í boði. Sækja <a href=\"%s\">meiri upplýsingar</a>",
+"up to date" => "nýjasta útgáfa",
+"updates check is disabled" => "uppfærslupróf er ekki virkjað",
+"Could not find category \"%s\"" => "Fann ekki flokkinn \"%s\""
+);
diff --git a/lib/l10n/it.php b/lib/l10n/it.php
index c0fb0babfb3..eb404db7fb5 100644
--- a/lib/l10n/it.php
+++ b/lib/l10n/it.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "I file devono essere scaricati uno alla volta.",
"Back to Files" => "Torna ai file",
"Selected files too large to generate zip file." => "I file selezionati sono troppo grandi per generare un file zip.",
+"couldn't be determined" => "non può essere determinato",
"Application is not enabled" => "L'applicazione non è abilitata",
"Authentication error" => "Errore di autenticazione",
"Token expired. Please reload page." => "Token scaduto. Ricarica la pagina.",
diff --git a/lib/l10n/ja_JP.php b/lib/l10n/ja_JP.php
index 854734c9764..11cefe900c2 100644
--- a/lib/l10n/ja_JP.php
+++ b/lib/l10n/ja_JP.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "ファイルは1つずつダウンロードする必要があります。",
"Back to Files" => "ファイルに戻る",
"Selected files too large to generate zip file." => "選択したファイルはZIPファイルの生成には大きすぎます。",
+"couldn't be determined" => "測定できませんでした",
"Application is not enabled" => "アプリケーションは無効です",
"Authentication error" => "認証エラー",
"Token expired. Please reload page." => "トークンが無効になりました。ページを再読込してください。",
diff --git a/lib/l10n/lb.php b/lib/l10n/lb.php
index baee630e897..a5a9adca187 100644
--- a/lib/l10n/lb.php
+++ b/lib/l10n/lb.php
@@ -1,6 +1,8 @@
<?php $TRANSLATIONS = array(
+"Help" => "Hëllef",
"Personal" => "Perséinlech",
"Settings" => "Astellungen",
"Authentication error" => "Authentifikatioun's Fehler",
+"Files" => "Dateien",
"Text" => "SMS"
);
diff --git a/lib/l10n/ms_MY.php b/lib/l10n/ms_MY.php
index 86c7e51b486..5afee1cb5a8 100644
--- a/lib/l10n/ms_MY.php
+++ b/lib/l10n/ms_MY.php
@@ -1,4 +1,5 @@
<?php $TRANSLATIONS = array(
+"Help" => "Bantuan",
"Personal" => "Peribadi",
"Settings" => "Tetapan",
"Users" => "Pengguna",
diff --git a/lib/l10n/nb_NO.php b/lib/l10n/nb_NO.php
index b01e0979889..01144672caa 100644
--- a/lib/l10n/nb_NO.php
+++ b/lib/l10n/nb_NO.php
@@ -16,15 +16,19 @@
"Text" => "Tekst",
"Images" => "Bilder",
"seconds ago" => "sekunder siden",
-"1 minute ago" => "1 minuitt siden",
+"1 minute ago" => "1 minutt siden",
"%d minutes ago" => "%d minutter siden",
+"1 hour ago" => "1 time siden",
+"%d hours ago" => "%d timer siden",
"today" => "i dag",
"yesterday" => "i går",
"%d days ago" => "%d dager siden",
"last month" => "forrige måned",
+"%d months ago" => "%d måneder siden",
"last year" => "i fjor",
"years ago" => "år siden",
"%s is available. Get <a href=\"%s\">more information</a>" => "%s er tilgjengelig. Få <a href=\"%s\">mer informasjon</a>",
"up to date" => "oppdatert",
-"updates check is disabled" => "versjonssjekk er avslått"
+"updates check is disabled" => "versjonssjekk er avslått",
+"Could not find category \"%s\"" => "Kunne ikke finne kategori \"%s\""
);
diff --git a/lib/l10n/nl.php b/lib/l10n/nl.php
index 087cf23a627..7ce134e3621 100644
--- a/lib/l10n/nl.php
+++ b/lib/l10n/nl.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Bestanden moeten één voor één worden gedownload.",
"Back to Files" => "Terug naar bestanden",
"Selected files too large to generate zip file." => "De geselecteerde bestanden zijn te groot om een zip bestand te maken.",
+"couldn't be determined" => "kon niet worden vastgesteld",
"Application is not enabled" => "De applicatie is niet actief",
"Authentication error" => "Authenticatie fout",
"Token expired. Please reload page." => "Token verlopen. Herlaad de pagina.",
diff --git a/lib/l10n/pt_PT.php b/lib/l10n/pt_PT.php
index 84867c4c37c..e35bb489c49 100644
--- a/lib/l10n/pt_PT.php
+++ b/lib/l10n/pt_PT.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Os ficheiros precisam de ser descarregados um por um.",
"Back to Files" => "Voltar a Ficheiros",
"Selected files too large to generate zip file." => "Os ficheiros seleccionados são grandes demais para gerar um ficheiro zip.",
+"couldn't be determined" => "Não foi possível determinar",
"Application is not enabled" => "A aplicação não está activada",
"Authentication error" => "Erro na autenticação",
"Token expired. Please reload page." => "O token expirou. Por favor recarregue a página.",
diff --git a/lib/l10n/ro.php b/lib/l10n/ro.php
index 27912550e17..3f8e59cdac2 100644
--- a/lib/l10n/ro.php
+++ b/lib/l10n/ro.php
@@ -9,21 +9,27 @@
"Files need to be downloaded one by one." => "Fișierele trebuie descărcate unul câte unul.",
"Back to Files" => "Înapoi la fișiere",
"Selected files too large to generate zip file." => "Fișierele selectate sunt prea mari pentru a genera un fișier zip.",
+"couldn't be determined" => "nu poate fi determinat",
"Application is not enabled" => "Aplicația nu este activată",
"Authentication error" => "Eroare la autentificare",
"Token expired. Please reload page." => "Token expirat. Te rugăm să reîncarci pagina.",
"Files" => "Fișiere",
"Text" => "Text",
+"Images" => "Imagini",
"seconds ago" => "secunde în urmă",
"1 minute ago" => "1 minut în urmă",
"%d minutes ago" => "%d minute în urmă",
+"1 hour ago" => "Acum o ora",
+"%d hours ago" => "%d ore in urma",
"today" => "astăzi",
"yesterday" => "ieri",
"%d days ago" => "%d zile în urmă",
"last month" => "ultima lună",
+"%d months ago" => "%d luni in urma",
"last year" => "ultimul an",
"years ago" => "ani în urmă",
"%s is available. Get <a href=\"%s\">more information</a>" => "%s este disponibil. Vezi <a href=\"%s\">mai multe informații</a>",
"up to date" => "la zi",
-"updates check is disabled" => "verificarea după actualizări este dezactivată"
+"updates check is disabled" => "verificarea după actualizări este dezactivată",
+"Could not find category \"%s\"" => "Cloud nu a gasit categoria \"%s\""
);
diff --git a/lib/l10n/sr.php b/lib/l10n/sr.php
index 2ae7400ba79..34ae89a6219 100644
--- a/lib/l10n/sr.php
+++ b/lib/l10n/sr.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Датотеке морате преузимати једну по једну.",
"Back to Files" => "Назад на датотеке",
"Selected files too large to generate zip file." => "Изабране датотеке су превелике да бисте направили ZIP датотеку.",
+"couldn't be determined" => "није одређено",
"Application is not enabled" => "Апликација није омогућена",
"Authentication error" => "Грешка при провери идентитета",
"Token expired. Please reload page." => "Жетон је истекао. Поново учитајте страницу.",
diff --git a/lib/l10n/sv.php b/lib/l10n/sv.php
index 5799e2dd1a8..36f00636b2b 100644
--- a/lib/l10n/sv.php
+++ b/lib/l10n/sv.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Filer laddas ner en åt gången.",
"Back to Files" => "Tillbaka till Filer",
"Selected files too large to generate zip file." => "Valda filer är för stora för att skapa zip-fil.",
+"couldn't be determined" => "kunde inte bestämmas",
"Application is not enabled" => "Applikationen är inte aktiverad",
"Authentication error" => "Fel vid autentisering",
"Token expired. Please reload page." => "Ogiltig token. Ladda om sidan.",
diff --git a/lib/l10n/th_TH.php b/lib/l10n/th_TH.php
index 75fa02f84b0..0da607a0589 100644
--- a/lib/l10n/th_TH.php
+++ b/lib/l10n/th_TH.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "ไฟล์สามารถดาวน์โหลดได้ทีละครั้งเท่านั้น",
"Back to Files" => "กลับไปที่ไฟล์",
"Selected files too large to generate zip file." => "ไฟล์ที่เลือกมีขนาดใหญ่เกินกว่าที่จะสร้างเป็นไฟล์ zip",
+"couldn't be determined" => "ไม่สามารถกำหนดได้",
"Application is not enabled" => "แอพพลิเคชั่นดังกล่าวยังไม่ได้เปิดใช้งาน",
"Authentication error" => "เกิดข้อผิดพลาดในสิทธิ์การเข้าใช้งาน",
"Token expired. Please reload page." => "รหัสยืนยันความถูกต้องหมดอายุแล้ว กรุณาโหลดหน้าเว็บใหม่อีกครั้ง",
diff --git a/lib/l10n/tr.php b/lib/l10n/tr.php
index 69067d7ec57..e55caa15972 100644
--- a/lib/l10n/tr.php
+++ b/lib/l10n/tr.php
@@ -3,7 +3,33 @@
"Personal" => "Kişisel",
"Settings" => "Ayarlar",
"Users" => "Kullanıcılar",
+"Apps" => "Uygulamalar",
+"Admin" => "Yönetici",
+"ZIP download is turned off." => "ZIP indirmeleri kapatılmıştır.",
+"Files need to be downloaded one by one." => "Dosyaların birer birer indirilmesi gerekmektedir.",
+"Back to Files" => "Dosyalara dön",
+"Selected files too large to generate zip file." => "Seçilen dosyalar bir zip dosyası oluşturmak için fazla büyüktür.",
+"couldn't be determined" => "tespit edilemedi",
+"Application is not enabled" => "Uygulama etkinleştirilmedi",
"Authentication error" => "Kimlik doğrulama hatası",
+"Token expired. Please reload page." => "Jetonun süresi geçti. Lütfen sayfayı yenileyin.",
"Files" => "Dosyalar",
-"Text" => "Metin"
+"Text" => "Metin",
+"Images" => "Resimler",
+"seconds ago" => "saniye önce",
+"1 minute ago" => "1 dakika önce",
+"%d minutes ago" => "%d dakika önce",
+"1 hour ago" => "1 saat önce",
+"%d hours ago" => "%d saat önce",
+"today" => "bugün",
+"yesterday" => "dün",
+"%d days ago" => "%d gün önce",
+"last month" => "geçen ay",
+"%d months ago" => "%d ay önce",
+"last year" => "geçen yıl",
+"years ago" => "yıl önce",
+"%s is available. Get <a href=\"%s\">more information</a>" => "%s kullanılabilir durumda. <a href=\"%s\">Daha fazla bilgi</a> alın",
+"up to date" => "güncel",
+"updates check is disabled" => "güncelleme kontrolü kapalı",
+"Could not find category \"%s\"" => "\"%s\" kategorisi bulunamadı"
);
diff --git a/lib/l10n/uk.php b/lib/l10n/uk.php
index f5d52f8682d..053644ddede 100644
--- a/lib/l10n/uk.php
+++ b/lib/l10n/uk.php
@@ -9,6 +9,7 @@
"Files need to be downloaded one by one." => "Файли повинні бути завантаженні послідовно.",
"Back to Files" => "Повернутися до файлів",
"Selected files too large to generate zip file." => "Вибрані фали завеликі для генерування zip файлу.",
+"couldn't be determined" => "не може бути визначено",
"Application is not enabled" => "Додаток не увімкнений",
"Authentication error" => "Помилка автентифікації",
"Token expired. Please reload page." => "Строк дії токена скінчився. Будь ласка, перезавантажте сторінку.",
diff --git a/lib/l10n/zh_TW.php b/lib/l10n/zh_TW.php
index 4dbf89c2e0e..62ab8fedd52 100644
--- a/lib/l10n/zh_TW.php
+++ b/lib/l10n/zh_TW.php
@@ -9,26 +9,27 @@
"Files need to be downloaded one by one." => "檔案需要逐一下載",
"Back to Files" => "回到檔案列表",
"Selected files too large to generate zip file." => "選擇的檔案太大以致於無法產生壓縮檔",
+"couldn't be determined" => "無法判斷",
"Application is not enabled" => "應用程式未啟用",
"Authentication error" => "認證錯誤",
-"Token expired. Please reload page." => "Token 過期. 請重新整理頁面",
+"Token expired. Please reload page." => "Token 過期,請重新整理頁面。",
"Files" => "檔案",
"Text" => "文字",
"Images" => "圖片",
"seconds ago" => "幾秒前",
"1 minute ago" => "1 分鐘前",
"%d minutes ago" => "%d 分鐘前",
-"1 hour ago" => "1小時之前",
-"%d hours ago" => "%d小時之前",
+"1 hour ago" => "1 小時之前",
+"%d hours ago" => "%d 小時之前",
"today" => "今天",
"yesterday" => "昨天",
"%d days ago" => "%d 天前",
"last month" => "上個月",
-"%d months ago" => "%d個月之前",
+"%d months ago" => "%d 個月之前",
"last year" => "去年",
"years ago" => "幾年前",
-"%s is available. Get <a href=\"%s\">more information</a>" => "%s 已經可用. 取得 <a href=\"%s\">更多資訊</a>",
+"%s is available. Get <a href=\"%s\">more information</a>" => "%s 已經可用。取得 <a href=\"%s\">更多資訊</a>",
"up to date" => "最新的",
"updates check is disabled" => "檢查更新已停用",
-"Could not find category \"%s\"" => "找不到分類-\"%s\""
+"Could not find category \"%s\"" => "找不到分類:\"%s\""
);
diff --git a/lib/log.php b/lib/log.php
index e9cededa5c0..e869282e88c 100644
--- a/lib/log.php
+++ b/lib/log.php
@@ -39,7 +39,7 @@ class OC_Log {
$log_class::write($app, $message, $level);
}
}
-
+
//Fatal errors handler
public static function onShutdown() {
$error = error_get_last();
@@ -50,7 +50,7 @@ class OC_Log {
return true;
}
}
-
+
// Uncaught exception handler
public static function onException($exception) {
self::write('PHP', $exception->getMessage() . ' at ' . $exception->getFile() . '#' . $exception->getLine(), self::FATAL);
diff --git a/lib/mail.php b/lib/mail.php
index c78fcce88d4..ffc4d01b79f 100644
--- a/lib/mail.php
+++ b/lib/mail.php
@@ -25,15 +25,24 @@ class OC_Mail {
* @param string $mailtext
* @param string $fromaddress
* @param string $fromname
- * @param bool $html
+ * @param bool|int $html
+ * @param string $altbody
+ * @param string $ccaddress
+ * @param string $ccname
+ * @param string $bcc
+ * @throws Exception
*/
public static function send($toaddress,$toname,$subject,$mailtext,$fromaddress,$fromname,$html=0,$altbody='',$ccaddress='',$ccname='', $bcc='') {
$SMTPMODE = OC_Config::getValue( 'mail_smtpmode', 'sendmail' );
$SMTPHOST = OC_Config::getValue( 'mail_smtphost', '127.0.0.1' );
+ $SMTPPORT = OC_Config::getValue( 'mail_smtpport', 25 );
$SMTPAUTH = OC_Config::getValue( 'mail_smtpauth', false );
$SMTPUSERNAME = OC_Config::getValue( 'mail_smtpname', '' );
$SMTPPASSWORD = OC_Config::getValue( 'mail_smtppassword', '' );
+ $SMTPDEBUG = OC_Config::getValue( 'mail_smtpdebug', false );
+ $SMTPTIMEOUT = OC_Config::getValue( 'mail_smtptimeout', 10 );
+ $SMTPSECURE = OC_Config::getValue( 'mail_smtpsecure', '' );
$mailo = new PHPMailer(true);
@@ -49,13 +58,17 @@ class OC_Mail {
$mailo->Host = $SMTPHOST;
+ $mailo->Port = $SMTPPORT;
$mailo->SMTPAuth = $SMTPAUTH;
+ $mailo->SMTPDebug = $SMTPDEBUG;
+ $mailo->SMTPSecure = $SMTPSECURE;
$mailo->Username = $SMTPUSERNAME;
$mailo->Password = $SMTPPASSWORD;
+ $mailo->Timeout = $SMTPTIMEOUT;
- $mailo->From =$fromaddress;
+ $mailo->From = $fromaddress;
$mailo->FromName = $fromname;;
- $mailo->Sender =$fromaddress;
+ $mailo->Sender = $fromaddress;
$a=explode(' ', $toaddress);
try {
foreach($a as $ad) {
@@ -89,8 +102,6 @@ class OC_Mail {
}
}
-
-
/**
* return the footer for a mail
*
@@ -103,7 +114,4 @@ class OC_Mail {
return($txt);
}
-
-
-
}
diff --git a/lib/migrate.php b/lib/migrate.php
index 5ff8e338a44..87bdd016fe4 100644
--- a/lib/migrate.php
+++ b/lib/migrate.php
@@ -219,7 +219,7 @@ class OC_Migrate{
// We need to be an admin if we are not importing our own data
if(($type == 'user' && self::$uid != $currentuser) || $type != 'user' ) {
- if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )) {
+ if( !OC_User::isAdminUser($currentuser)) {
// Naughty.
OC_Log::write( 'migration', 'Import not permitted.', OC_Log::ERROR );
return json_encode( array( 'success' => false ) );
@@ -655,7 +655,7 @@ class OC_Migrate{
$query = OC_DB::prepare( "INSERT INTO `*PREFIX*users` ( `uid`, `password` ) VALUES( ?, ? )" );
$result = $query->execute( array( $uid, $hash));
if( !$result ) {
- OC_Log::write('migration', 'Failed to create the new user "'.$uid."");
+ OC_Log::write('migration', 'Failed to create the new user "'.$uid."", OC_Log::ERROR);
}
return $result ? true : false;
diff --git a/lib/migration/content.php b/lib/migration/content.php
index 00df62f0c7f..e81c8f217ff 100644
--- a/lib/migration/content.php
+++ b/lib/migration/content.php
@@ -66,7 +66,7 @@ class OC_Migration_Content{
// Die if we have an error (error means: bad query, not 0 results!)
if( PEAR::isError( $query ) ) {
- $entry = 'DB Error: "'.$result->getMessage().'"<br />';
+ $entry = 'DB Error: "'.$query->getMessage().'"<br />';
$entry .= 'Offending command was: '.$query.'<br />';
OC_Log::write( 'migration', $entry, OC_Log::FATAL );
return false;
diff --git a/lib/mimetypes.list.php b/lib/mimetypes.list.php
index 77b97917583..fc87d011ecd 100644
--- a/lib/mimetypes.list.php
+++ b/lib/mimetypes.list.php
@@ -95,4 +95,6 @@ return array(
'cdr' => 'application/coreldraw',
'impress' => 'text/impress',
'ai' => 'application/illustrator',
+ 'epub' => 'application/epub+zip',
+ 'mobi' => 'application/x-mobipocket-ebook',
);
diff --git a/lib/ocs.php b/lib/ocs.php
index 1a0abf0e367..879aaa76687 100644
--- a/lib/ocs.php
+++ b/lib/ocs.php
@@ -73,14 +73,7 @@ class OC_OCS {
}
}
- /**
- main function to handle the REST request
- **/
- public static function handle() {
- // overwrite the 404 error page returncode
- header("HTTP/1.0 200 OK");
-
-
+ public static function notFound() {
if($_SERVER['REQUEST_METHOD'] == 'GET') {
$method='get';
}elseif($_SERVER['REQUEST_METHOD'] == 'PUT') {
@@ -94,169 +87,10 @@ class OC_OCS {
}
$format = self::readData($method, 'format', 'text', '');
+ $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n";
+ $txt.=OC_OCS::getDebugOutput();
+ echo(OC_OCS::generateXml($format,'failed',999,$txt));
- $router = new OC_Router();
- $router->useCollection('root');
- // CONFIG
- $router->create('config', '/config.{format}')
- ->defaults(array('format' => $format))
- ->action('OC_OCS', 'apiConfig')
- ->requirements(array('format'=>'xml|json'));
-
- // PERSON
- $router->create('person_check', '/person/check.{format}')
- ->post()
- ->defaults(array('format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- $login = OC_OCS::readData('post', 'login', 'text');
- $passwd = OC_OCS::readData('post', 'password', 'text');
- OC_OCS::personCheck($format, $login, $passwd);
- })
- ->requirements(array('format'=>'xml|json'));
-
- // ACTIVITY
- // activityget - GET ACTIVITY page,pagesize als urlparameter
- $router->create('activity_get', '/activity.{format}')
- ->defaults(array('format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- $page = OC_OCS::readData('get', 'page', 'int', 0);
- $pagesize = OC_OCS::readData('get', 'pagesize', 'int', 10);
- if($pagesize<1 or $pagesize>100) $pagesize=10;
- OC_OCS::activityGet($format, $page, $pagesize);
- })
- ->requirements(array('format'=>'xml|json'));
- // activityput - POST ACTIVITY
- $router->create('activity_put', '/activity.{format}')
- ->post()
- ->defaults(array('format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- $message = OC_OCS::readData('post', 'message', 'text');
- OC_OCS::activityPut($format, $message);
- })
- ->requirements(array('format'=>'xml|json'));
-
- // PRIVATEDATA
- // get - GET DATA
- $router->create('privatedata_get',
- '/privatedata/getattribute/{app}/{key}.{format}')
- ->defaults(array('app' => '', 'key' => '', 'format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- $app = addslashes(strip_tags($parameters['app']));
- $key = addslashes(strip_tags($parameters['key']));
- OC_OCS::privateDataGet($format, $app, $key);
- })
- ->requirements(array('format'=>'xml|json'));
- // set - POST DATA
- $router->create('privatedata_set',
- '/privatedata/setattribute/{app}/{key}.{format}')
- ->post()
- ->defaults(array('format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- $app = addslashes(strip_tags($parameters['app']));
- $key = addslashes(strip_tags($parameters['key']));
- $value=OC_OCS::readData('post', 'value', 'text');
- OC_OCS::privateDataSet($format, $app, $key, $value);
- })
- ->requirements(array('format'=>'xml|json'));
- // delete - POST DATA
- $router->create('privatedata_delete',
- '/privatedata/deleteattribute/{app}/{key}.{format}')
- ->post()
- ->defaults(array('format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- $app = addslashes(strip_tags($parameters['app']));
- $key = addslashes(strip_tags($parameters['key']));
- OC_OCS::privateDataDelete($format, $app, $key);
- })
- ->requirements(array('format'=>'xml|json'));
-
- // CLOUD
- // systemWebApps
- $router->create('system_webapps',
- '/cloud/system/webapps.{format}')
- ->defaults(array('format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- OC_OCS::systemwebapps($format);
- })
- ->requirements(array('format'=>'xml|json'));
-
- // quotaget
- $router->create('quota_get',
- '/cloud/user/{user}.{format}')
- ->defaults(array('format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- $user = $parameters['user'];
- OC_OCS::quotaGet($format, $user);
- })
- ->requirements(array('format'=>'xml|json'));
- // quotaset
- $router->create('quota_set',
- '/cloud/user/{user}.{format}')
- ->post()
- ->defaults(array('format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- $user = $parameters['user'];
- $quota = self::readData('post', 'quota', 'int');
- OC_OCS::quotaSet($format, $user, $quota);
- })
- ->requirements(array('format'=>'xml|json'));
-
- // keygetpublic
- $router->create('keygetpublic',
- '/cloud/user/{user}/publickey.{format}')
- ->defaults(array('format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- $user = $parameters['user'];
- OC_OCS::publicKeyGet($format, $user);
- })
- ->requirements(array('format'=>'xml|json'));
-
- // keygetprivate
- $router->create('keygetpublic',
- '/cloud/user/{user}/privatekey.{format}')
- ->defaults(array('format' => $format))
- ->action(function ($parameters) {
- $format = $parameters['format'];
- $user = $parameters['user'];
- OC_OCS::privateKeyGet($format, $user);
- })
- ->requirements(array('format'=>'xml|json'));
-
-
-// add more calls here
-// please document all the call in the draft spec
-// http://www.freedesktop.org/wiki/Specifications/open-collaboration-services-1.7#CLOUD
-
-// TODO:
-// users
-// groups
-// bookmarks
-// sharing
-// versioning
-// news (rss)
- try {
- $router->match($_SERVER['PATH_INFO']);
- } catch (ResourceNotFoundException $e) {
- $txt='Invalid query, please check the syntax. '
- .'API specifications are here: '
- .'http://www.freedesktop.org/wiki/Specifications/open-collaboration-services.'
- .'DEBUG OUTPUT:'."\n";
- $txt.=OC_OCS::getdebugoutput();
- echo(OC_OCS::generatexml($format, 'failed', 999, $txt));
- } catch (MethodNotAllowedException $e) {
- OC_Response::setStatus(405);
- }
- exit();
}
/**
@@ -273,44 +107,6 @@ class OC_OCS {
return($txt);
}
- /**
- * checks if the user is authenticated
- * checks the IP whitlist, apikeys and login/password combination
- * if $forceuser is true and the authentication failed it returns an 401 http response.
- * if $forceuser is false and authentification fails it returns an empty username string
- * @param bool $forceuser
- * @return username string
- */
- private static function checkPassword($forceuser=true) {
- //valid user account ?
- if(isset($_SERVER['PHP_AUTH_USER'])) $authuser=$_SERVER['PHP_AUTH_USER']; else $authuser='';
- if(isset($_SERVER['PHP_AUTH_PW'])) $authpw=$_SERVER['PHP_AUTH_PW']; else $authpw='';
-
- if(empty($authuser)) {
- if($forceuser) {
- header('WWW-Authenticate: Basic realm="your valid user account or api key"');
- header('HTTP/1.0 401 Unauthorized');
- exit;
- }else{
- $identifieduser='';
- }
- }else{
- if(!OC_User::login($authuser, $authpw)) {
- if($forceuser) {
- header('WWW-Authenticate: Basic realm="your valid user account or api key"');
- header('HTTP/1.0 401 Unauthorized');
- exit;
- }else{
- $identifieduser='';
- }
- }else{
- $identifieduser=$authuser;
- }
- }
-
- return($identifieduser);
- }
-
/**
* generates the xml or json response for the API call from an multidimenional data array.
@@ -432,130 +228,6 @@ class OC_OCS {
}
/**
- * return the config data of this server
- * @param string $format
- * @return string xml/json
- */
- public static function apiConfig($parameters) {
- $format = $parameters['format'];
- $user=OC_OCS::checkpassword(false);
- $url=substr(OCP\Util::getServerHost().$_SERVER['SCRIPT_NAME'], 0, -11).'';
-
- $xml['version']='1.7';
- $xml['website']='ownCloud';
- $xml['host']=OCP\Util::getServerHost();
- $xml['contact']='';
- $xml['ssl']='false';
- echo(OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'config', '', 1));
- }
-
- /**
- * check if the provided login/apikey/password is valid
- * @param string $format
- * @param string $login
- * @param string $passwd
- * @return string xml/json
- */
- private static function personCheck($format, $login, $passwd) {
- if($login<>'') {
- if(OC_User::login($login, $passwd)) {
- $xml['person']['personid']=$login;
- echo(OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'person', 'check', 2));
- }else{
- echo(OC_OCS::generatexml($format, 'failed', 102, 'login not valid'));
- }
- }else{
- echo(OC_OCS::generatexml($format, 'failed', 101, 'please specify all mandatory fields'));
- }
- }
-
- // ACTIVITY API #############################################
-
- /**
- * get my activities
- * @param string $format
- * @param string $page
- * @param string $pagesize
- * @return string xml/json
- */
- private static function activityGet($format, $page, $pagesize) {
- $user=OC_OCS::checkpassword();
-
- //TODO
-
- $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'activity', 'full', 2, $totalcount, $pagesize);
- echo($txt);
- }
-
- /**
- * submit a activity
- * @param string $format
- * @param string $message
- * @return string xml/json
- */
- private static function activityPut($format, $message) {
- // not implemented in ownCloud
- $user=OC_OCS::checkpassword();
- echo(OC_OCS::generatexml($format, 'ok', 100, ''));
- }
-
- // PRIVATEDATA API #############################################
-
- /**
- * get private data and create the xml for ocs
- * @param string $format
- * @param string $app
- * @param string $key
- * @return string xml/json
- */
- private static function privateDataGet($format, $app="", $key="") {
- $user=OC_OCS::checkpassword();
- $result=OC_OCS::getData($user, $app, $key);
- $xml=array();
- foreach($result as $i=>$log) {
- $xml[$i]['key']=$log['key'];
- $xml[$i]['app']=$log['app'];
- $xml[$i]['value']=$log['value'];
- }
-
-
- $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'privatedata', 'full', 2, count($xml), 0);//TODO: replace 'privatedata' with 'attribute' once a new libattice has been released that works with it
- echo($txt);
- }
-
- /**
- * set private data referenced by $key to $value and generate the xml for ocs
- * @param string $format
- * @param string $app
- * @param string $key
- * @param string $value
- * @return string xml/json
- */
- private static function privateDataSet($format, $app, $key, $value) {
- $user=OC_OCS::checkpassword();
- if(OC_OCS::setData($user, $app, $key, $value)) {
- echo(OC_OCS::generatexml($format, 'ok', 100, ''));
- }
- }
-
- /**
- * delete private data referenced by $key and generate the xml for ocs
- * @param string $format
- * @param string $app
- * @param string $key
- * @return string xml/json
- */
- private static function privateDataDelete($format, $app, $key) {
- if($key=="" or $app=="") {
- return; //key and app are NOT optional here
- }
- $user=OC_OCS::checkpassword();
- if(OC_OCS::deleteData($user, $app, $key)) {
- echo(OC_OCS::generatexml($format, 'ok', 100, ''));
- }
- }
-
- /**
* get private data
* @param string $user
* @param string $app
@@ -586,156 +258,4 @@ class OC_OCS {
return $result;
}
- /**
- * set private data referenced by $key to $value
- * @param string $user
- * @param string $app
- * @param string $key
- * @param string $value
- * @return bool
- */
- public static function setData($user, $app, $key, $value) {
- return OC_Preferences::setValue($user, $app, $key, $value);
- }
-
- /**
- * delete private data referenced by $key
- * @param string $user
- * @param string $app
- * @param string $key
- * @return string xml/json
- */
- public static function deleteData($user, $app, $key) {
- return OC_Preferences::deleteKey($user, $app, $key);
- }
-
-
- // CLOUD API #############################################
-
- /**
- * get a list of installed web apps
- * @param string $format
- * @return string xml/json
- */
- private static function systemWebApps($format) {
- $login=OC_OCS::checkpassword();
- $apps=OC_App::getEnabledApps();
- $values=array();
- foreach($apps as $app) {
- $info=OC_App::getAppInfo($app);
- if(isset($info['standalone'])) {
- $newvalue=array('name'=>$info['name'], 'url'=>OC_Helper::linkToAbsolute($app, ''), 'icon'=>'');
- $values[]=$newvalue;
- }
-
- }
- $txt=OC_OCS::generatexml($format, 'ok', 100, '', $values, 'cloud', '', 2, 0, 0);
- echo($txt);
-
- }
-
-
- /**
- * get the quota of a user
- * @param string $format
- * @param string $user
- * @return string xml/json
- */
- private static function quotaGet($format, $user) {
- $login=OC_OCS::checkpassword();
- if(OC_Group::inGroup($login, 'admin') or ($login==$user)) {
-
- if(OC_User::userExists($user)) {
- // calculate the disc space
- $user_dir = '/'.$user.'/files';
- OC_Filesystem::init($user_dir);
- $rootInfo=OC_FileCache::get('');
- $sharedInfo=OC_FileCache::get('/Shared');
- $used=$rootInfo['size']-$sharedInfo['size'];
- $free=OC_Filesystem::free_space();
- $total=$free+$used;
- if($total==0) $total=1; // prevent division by zero
- $relative=round(($used/$total)*10000)/100;
-
- $xml=array();
- $xml['quota']=$total;
- $xml['free']=$free;
- $xml['used']=$used;
- $xml['relative']=$relative;
-
- $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'cloud', '', 1, 0, 0);
- echo($txt);
- }else{
- echo self::generateXml('', 'fail', 300, 'User does not exist');
- }
- }else{
- echo self::generateXml('', 'fail', 300, 'You don´t have permission to access this ressource.');
- }
- }
-
- /**
- * set the quota of a user
- * @param string $format
- * @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
- // add logic here
- error_log('OCS call: user:'.$user.' quota:'.$quota);
-
- $xml=array();
- $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'cloud', '', 1, 0, 0);
- echo($txt);
- }else{
- echo self::generateXml('', 'fail', 300, 'You don´t have permission to access this ressource.');
- }
- }
-
- /**
- * get the public key of a user
- * @param string $format
- * @param string $user
- * @return string xml/json
- */
- private static function publicKeyGet($format, $user) {
- $login=OC_OCS::checkpassword();
-
- if(OC_User::userExists($user)) {
- // calculate the disc space
- $txt='this is the public key of '.$user;
- echo($txt);
- }else{
- echo self::generateXml('', 'fail', 300, 'User does not exist');
- }
- }
-
- /**
- * get the private key of a user
- * @param string $format
- * @param string $user
- * @return string xml/json
- */
- private static function privateKeyGet($format, $user) {
- $login=OC_OCS::checkpassword();
- if(OC_Group::inGroup($login, 'admin') or ($login==$user)) {
-
- if(OC_User::userExists($user)) {
- // calculate the disc space
- $txt='this is the private key of '.$user;
- echo($txt);
- }else{
- echo self::generateXml('', 'fail', 300, 'User does not exist');
- }
- }else{
- echo self::generateXml('', 'fail', 300, 'You don´t have permission to access this ressource.');
- }
- }
-
-
}
diff --git a/lib/ocs/activity.php b/lib/ocs/activity.php
new file mode 100644
index 00000000000..c30e21018d3
--- /dev/null
+++ b/lib/ocs/activity.php
@@ -0,0 +1,28 @@
+<?php
+/**
+* ownCloud
+*
+* @author Frank Karlitschek
+* @copyright 2012 Frank Karlitschek frank@owncloud.org
+*
+* 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_OCS_Activity {
+
+ public static function activityGet($parameters){
+ // TODO
+ }
+}
diff --git a/lib/ocs/cloud.php b/lib/ocs/cloud.php
new file mode 100644
index 00000000000..2d18b1db3f2
--- /dev/null
+++ b/lib/ocs/cloud.php
@@ -0,0 +1,98 @@
+<?php
+/**
+* ownCloud
+*
+* @author Frank Karlitschek
+* @author Tom Needham
+* @copyright 2012 Frank Karlitschek frank@owncloud.org
+* @copyright 2012 Tom Needham tom@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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_OCS_Cloud {
+
+ public static function getSystemWebApps() {
+ OC_Util::checkLoggedIn();
+ $apps = OC_App::getEnabledApps();
+ $values = array();
+ foreach($apps as $app) {
+ $info = OC_App::getAppInfo($app);
+ if(isset($info['standalone'])) {
+ $newValue = array('name'=>$info['name'],'url'=>OC_Helper::linkToAbsolute($app,''),'icon'=>'');
+ $values[] = $newValue;
+ }
+ }
+ return new OC_OCS_Result($values);
+ }
+
+ public static function getUserQuota($parameters) {
+ $user = OC_User::getUser();
+ if(OC_User::isAdminUser($user) or ($user==$parameters['user'])) {
+
+ if(OC_User::userExists($parameters['user'])) {
+ // calculate the disc space
+ $userDir = '/'.$parameters['user'].'/files';
+ OC_Filesystem::init($userDir);
+ $rootInfo = OC_FileCache::get('');
+ $sharedInfo = OC_FileCache::get('/Shared');
+ $used = $rootInfo['size'] - $sharedInfo['size'];
+ $free = OC_Filesystem::free_space();
+ $total = $free + $used;
+ if($total===0) $total = 1; // prevent division by zero
+ $relative = round(($used/$total)*10000)/100;
+
+ $xml = array();
+ $xml['quota'] = $total;
+ $xml['free'] = $free;
+ $xml['used'] = $used;
+ $xml['relative'] = $relative;
+
+ return new OC_OCS_Result($xml);
+ } else {
+ return new OC_OCS_Result(null, 300);
+ }
+ } else {
+ return new OC_OCS_Result(null, 300);
+ }
+ }
+
+ public static function getUserPublickey($parameters) {
+
+ if(OC_User::userExists($parameters['user'])) {
+ // calculate the disc space
+ // TODO
+ return new OC_OCS_Result(array());
+ } else {
+ return new OC_OCS_Result(null, 300);
+ }
+ }
+
+ public static function getUserPrivatekey($parameters) {
+ $user = OC_User::getUser();
+ if(OC_User::isAdminUser($user) or ($user==$parameters['user'])) {
+
+ if(OC_User::userExists($user)) {
+ // calculate the disc space
+ $txt = 'this is the private key of '.$parameters['user'];
+ echo($txt);
+ } else {
+ return new OC_OCS_Result(null, 300, 'User does not exist');
+ }
+ } else {
+ return new OC_OCS_Result('null', 300, 'You don´t have permission to access this ressource.');
+ }
+ }
+}
diff --git a/lib/ocs/config.php b/lib/ocs/config.php
new file mode 100644
index 00000000000..f19121f4b2b
--- /dev/null
+++ b/lib/ocs/config.php
@@ -0,0 +1,36 @@
+<?php
+/**
+* ownCloud
+*
+* @author Frank Karlitschek
+* @author Tom Needham
+* @copyright 2012 Frank Karlitschek frank@owncloud.org
+* @copyright 2012 Tom Needham tom@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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_OCS_Config {
+
+ public static function apiConfig($parameters) {
+ $xml['version'] = '1.7';
+ $xml['website'] = 'ownCloud';
+ $xml['host'] = OCP\Util::getServerHost();
+ $xml['contact'] = '';
+ $xml['ssl'] = 'false';
+ return new OC_OCS_Result($xml);
+ }
+
+}
diff --git a/lib/ocs/person.php b/lib/ocs/person.php
new file mode 100644
index 00000000000..1c8210d0825
--- /dev/null
+++ b/lib/ocs/person.php
@@ -0,0 +1,42 @@
+<?php
+/**
+* ownCloud
+*
+* @author Frank Karlitschek
+* @author Tom Needham
+* @copyright 2012 Frank Karlitschek frank@owncloud.org
+* @copyright 2012 Tom Needham tom@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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_OCS_Person {
+
+ public static function check($parameters) {
+ $login = isset($_POST['login']) ? $_POST['login'] : false;
+ $password = isset($_POST['password']) ? $_POST['password'] : false;
+ if($login && $password) {
+ if(OC_User::checkPassword($login, $password)) {
+ $xml['person']['personid'] = $login;
+ return new OC_OCS_Result($xml);
+ } else {
+ return new OC_OCS_Result(null, 102);
+ }
+ } else {
+ return new OC_OCS_Result(null, 101);
+ }
+ }
+
+}
diff --git a/lib/ocs/privatedata.php b/lib/ocs/privatedata.php
new file mode 100644
index 00000000000..311b24269dd
--- /dev/null
+++ b/lib/ocs/privatedata.php
@@ -0,0 +1,66 @@
+<?php
+/**
+* ownCloud
+*
+* @author Frank Karlitschek
+* @author Tom Needham
+* @copyright 2012 Frank Karlitschek frank@owncloud.org
+* @copyright 2012 Tom Needham tom@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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_OCS_Privatedata {
+
+ public static function get($parameters) {
+ OC_Util::checkLoggedIn();
+ $user = OC_User::getUser();
+ $app = addslashes(strip_tags($parameters['app']));
+ $key = addslashes(strip_tags($parameters['key']));
+ $result = OC_OCS::getData($user,$app,$key);
+ $xml = array();
+ foreach($result as $i=>$log) {
+ $xml[$i]['key']=$log['key'];
+ $xml[$i]['app']=$log['app'];
+ $xml[$i]['value']=$log['value'];
+ }
+ return new OC_OCS_Result($xml);
+ //TODO: replace 'privatedata' with 'attribute' once a new libattice has been released that works with it
+ }
+
+ public static function set($parameters) {
+ OC_Util::checkLoggedIn();
+ $user = OC_User::getUser();
+ $app = addslashes(strip_tags($parameters['app']));
+ $key = addslashes(strip_tags($parameters['key']));
+ $value = OC_OCS::readData('post', 'value', 'text');
+ if(OC_Preferences::setValue($user, $app, $key, $value)){
+ return new OC_OCS_Result(null, 100);
+ }
+ }
+
+ public static function delete($parameters) {
+ OC_Util::checkLoggedIn();
+ $user = OC_User::getUser();
+ $app = addslashes(strip_tags($parameters['app']));
+ $key = addslashes(strip_tags($parameters['key']));
+ if($key==="" or $app==="") {
+ return new OC_OCS_Result(null, 101); //key and app are NOT optional here
+ }
+ if(OC_Preferences::deleteKey($user, $app, $key)) {
+ return new OC_OCS_Result(null, 100);
+ }
+ }
+}
diff --git a/lib/ocs/result.php b/lib/ocs/result.php
new file mode 100644
index 00000000000..65b2067fc3f
--- /dev/null
+++ b/lib/ocs/result.php
@@ -0,0 +1,75 @@
+<?php
+/**
+* ownCloud
+*
+* @author Tom Needham
+* @copyright 2012 Tom Needham tom@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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_OCS_Result{
+
+ private $data, $message, $statusCode, $items, $perPage;
+
+ /**
+ * create the OCS_Result object
+ * @param $data mixed the data to return
+ */
+ public function __construct($data=null, $code=100, $message=null) {
+ $this->data = $data;
+ $this->statusCode = $code;
+ $this->message = $message;
+ }
+
+ /**
+ * optionally set the total number of items available
+ * @param $items int
+ */
+ public function setTotalItems(int $items) {
+ $this->items = $items;
+ }
+
+ /**
+ * optionally set the the number of items per page
+ * @param $items int
+ */
+ public function setItemsPerPage(int $items) {
+ $this->perPage = $items;
+ }
+
+ /**
+ * returns the data associated with the api result
+ * @return array
+ */
+ public function getResult() {
+ $return = array();
+ $return['meta'] = array();
+ $return['meta']['status'] = ($this->statusCode === 100) ? 'ok' : 'failure';
+ $return['meta']['statuscode'] = $this->statusCode;
+ $return['meta']['message'] = $this->message;
+ if(isset($this->items)) {
+ $return['meta']['totalitems'] = $this->items;
+ }
+ if(isset($this->perPage)) {
+ $return['meta']['itemsperpage'] = $this->perPage;
+ }
+ $return['data'] = $this->data;
+ // Return the result data.
+ return $return;
+ }
+
+
+} \ No newline at end of file
diff --git a/lib/ocsclient.php b/lib/ocsclient.php
index 24081425f1e..ca0665da436 100644
--- a/lib/ocsclient.php
+++ b/lib/ocsclient.php
@@ -39,11 +39,11 @@ class OC_OCSClient{
return($url);
}
- /**
- * @brief Get the url of the OCS KB server.
- * @returns string of the KB server
- * This function returns the url of the OCS knowledge base server. It´s possible to set it in the config file or it will fallback to the default
- */
+ /**
+ * @brief Get the url of the OCS KB server.
+ * @returns string of the KB server
+ * This function returns the url of the OCS knowledge base server. It´s possible to set it in the config file or it will fallback to the default
+ */
private static function getKBURL() {
$url = OC_Config::getValue('knowledgebaseurl', 'http://api.apps.owncloud.com/v1');
return($url);
@@ -59,7 +59,7 @@ class OC_OCSClient{
return($data);
}
- /**
+ /**
* @brief Get all the categories from the OCS server
* @returns array with category ids
* @note returns NULL if config value appstoreenabled is set to false
@@ -242,7 +242,7 @@ class OC_OCSClient{
}
$kbe['totalitems'] = $data->meta->totalitems;
}
- return $kbe;
+ return $kbe;
}
diff --git a/lib/public/api.php b/lib/public/api.php
new file mode 100644
index 00000000000..95d333f2165
--- /dev/null
+++ b/lib/public/api.php
@@ -0,0 +1,44 @@
+<?php
+/**
+* ownCloud
+*
+* @author Tom Needham
+* @copyright 2012 Tom Needham tom@owncloud.com
+*
+* This library is free software; you can redistribute it and/or
+* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+* 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/>.
+*
+*/
+
+namespace OCP;
+
+/**
+ * This class provides functions to manage apps in ownCloud
+ */
+class API {
+
+ /**
+ * registers an api call
+ * @param string $method the http method
+ * @param string $url the url to match
+ * @param callable $action the function to run
+ * @param string $app the id of the app registering the call
+ * @param int $authLevel the level of authentication required for the call (See OC_API constants)
+ * @param array $defaults
+ * @param array $requirements
+ */
+ public static function register($method, $url, $action, $app, $authLevel = OC_API::USER_AUTH, $defaults = array(), $requirements = array()){
+ \OC_API::register($method, $url, $action, $app, $authLevel, $defaults, $requirements);
+ }
+
+}
diff --git a/lib/public/app.php b/lib/public/app.php
index 809a656f17f..a1ecf524cc8 100644
--- a/lib/public/app.php
+++ b/lib/public/app.php
@@ -89,7 +89,7 @@ class App {
* @param $page string page to be included
*/
public static function registerPersonal( $app, $page ) {
- return \OC_App::registerPersonal( $app, $page );
+ \OC_App::registerPersonal( $app, $page );
}
/**
@@ -98,7 +98,7 @@ class App {
* @param $page string page to be included
*/
public static function registerAdmin( $app, $page ) {
- return \OC_App::registerAdmin( $app, $page );
+ \OC_App::registerAdmin( $app, $page );
}
/**
@@ -125,10 +125,9 @@ class App {
/**
* @brief Check if the app is enabled, redirects to home if not
* @param $app app
- * @returns true/false
*/
public static function checkAppEnabled( $app ) {
- return \OC_Util::checkAppEnabled( $app );
+ \OC_Util::checkAppEnabled( $app );
}
/**
diff --git a/lib/public/constants.php b/lib/public/constants.php
index bc979c9031f..1495c620dc9 100644
--- a/lib/public/constants.php
+++ b/lib/public/constants.php
@@ -35,4 +35,3 @@ const PERMISSION_UPDATE = 2;
const PERMISSION_DELETE = 8;
const PERMISSION_SHARE = 16;
const PERMISSION_ALL = 31;
-
diff --git a/lib/public/db.php b/lib/public/db.php
index 92ff8f93a22..932e79d9ef1 100644
--- a/lib/public/db.php
+++ b/lib/public/db.php
@@ -36,8 +36,8 @@ namespace OCP;
class DB {
/**
* @brief Prepare a SQL query
- * @param $query Query string
- * @returns prepared SQL query
+ * @param string $query Query string
+ * @return \MDB2_Statement_Common prepared SQL query
*
* SQL query via MDB2 prepare(), needs to be execute()'d!
*/
@@ -49,9 +49,9 @@ class DB {
* @brief Insert a row if a matching row doesn't exists.
* @param $table string The table name (will replace *PREFIX*) to perform the replace on.
* @param $input array
- *
+ *
* The input array if in the form:
- *
+ *
* array ( 'id' => array ( 'value' => 6,
* 'key' => true
* ),
@@ -59,17 +59,17 @@ class DB {
* 'family' => array ('value' => 'Stefanov'),
* 'birth_date' => array ('value' => '1975-06-20')
* );
- * @returns true/false
+ * @return bool
*
*/
public static function insertIfNotExist($table, $input) {
return(\OC_DB::insertIfNotExist($table, $input));
}
-
+
/**
* @brief gets last value of autoincrement
* @param $table string The optional table name (will replace *PREFIX*) and add sequence suffix
- * @returns id
+ * @return int
*
* MDB2 lastInsertID()
*
diff --git a/lib/public/files.php b/lib/public/files.php
index 90889c59ad8..75e1d2fbbc1 100644
--- a/lib/public/files.php
+++ b/lib/public/files.php
@@ -38,9 +38,10 @@ class Files {
* @brief Recusive deletion of folders
* @param string $dir path to the folder
*
+ * @return bool
*/
static function rmdirr( $dir ) {
- \OC_Helper::rmdirr( $dir );
+ return \OC_Helper::rmdirr( $dir );
}
/**
diff --git a/lib/public/response.php b/lib/public/response.php
index 95e67a85720..de0c3f25347 100644
--- a/lib/public/response.php
+++ b/lib/public/response.php
@@ -31,27 +31,27 @@
namespace OCP;
/**
- * This class provides convinient functions to send the correct http response headers
+ * This class provides convenient functions to send the correct http response headers
*/
class Response {
/**
* @brief Enable response caching by sending correct HTTP headers
- * @param $cache_time time to cache the response
+ * @param int $cache_time time to cache the response
* >0 cache time in seconds
* 0 and <0 enable default browser caching
* null cache indefinitly
*/
static public function enableCaching( $cache_time = null ) {
- return(\OC_Response::enableCaching( $cache_time ));
+ \OC_Response::enableCaching( $cache_time );
}
/**
* Checks and set Last-Modified header, when the request matches sends a
* 'not modified' response
- * @param $lastModified time when the reponse was last modified
+ * @param string $lastModified time when the reponse was last modified
*/
static public function setLastModifiedHeader( $lastModified ) {
- return(\OC_Response::setLastModifiedHeader( $lastModified ));
+ \OC_Response::setLastModifiedHeader( $lastModified );
}
/**
@@ -59,41 +59,41 @@ class Response {
* @see enableCaching with cache_time = 0
*/
static public function disableCaching() {
- return(\OC_Response::disableCaching());
+ \OC_Response::disableCaching();
}
/**
* Checks and set ETag header, when the request matches sends a
* 'not modified' response
- * @param $etag token to use for modification check
+ * @param string $etag token to use for modification check
*/
static public function setETagHeader( $etag ) {
- return(\OC_Response::setETagHeader( $etag ));
+ \OC_Response::setETagHeader( $etag );
}
/**
* @brief Send file as response, checking and setting caching headers
- * @param $filepath of file to send
+ * @param string $filepath of file to send
*/
static public function sendFile( $filepath ) {
- return(\OC_Response::sendFile( $filepath ));
+ \OC_Response::sendFile( $filepath );
}
/**
- * @brief Set reponse expire time
- * @param $expires date-time when the response expires
+ * @brief Set response expire time
+ * @param string|\DateTime $expires date-time when the response expires
* string for DateInterval from now
* DateTime object when to expire response
*/
static public function setExpiresHeader( $expires ) {
- return(\OC_Response::setExpiresHeader( $expires ));
+ \OC_Response::setExpiresHeader( $expires );
}
/**
* @brief Send redirect response
- * @param $location to redirect to
+ * @param string $location to redirect to
*/
static public function redirect( $location ) {
- return(\OC_Response::redirect( $location ));
+ \OC_Response::redirect( $location );
}
-} \ No newline at end of file
+}
diff --git a/lib/public/share.php b/lib/public/share.php
index d736871d244..cda583aa073 100644
--- a/lib/public/share.php
+++ b/lib/public/share.php
@@ -37,7 +37,8 @@ class Share {
const SHARE_TYPE_REMOTE = 6;
/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
- * Construct permissions for share() and setPermissions with Or (|) e.g. Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
+ * Construct permissions for share() and setPermissions with Or (|)
+ * e.g. Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
* Check if permission is granted with And (&) e.g. Check if delete is granted: if ($permissions & PERMISSION_DELETE)
* Remove permissions with And (&) and Not (~) e.g. Remove the update permission: $permissions &= ~PERMISSION_UPDATE
* Apps are required to handle permissions on their own, this class only stores and manages the permissions of shares
@@ -66,14 +67,17 @@ class Share {
public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
if (self::isEnabled()) {
if (!isset(self::$backendTypes[$itemType])) {
- self::$backendTypes[$itemType] = array('class' => $class, 'collectionOf' => $collectionOf, 'supportedFileExtensions' => $supportedFileExtensions);
+ self::$backendTypes[$itemType] = array('class' => $class,
+ 'collectionOf' => $collectionOf,
+ 'supportedFileExtensions' => $supportedFileExtensions);
if(count(self::$backendTypes) === 1) {
\OC_Util::addScript('core', 'share');
\OC_Util::addStyle('core', 'share');
}
return true;
}
- \OC_Log::write('OCP\Share', 'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class'].' is already registered for '.$itemType, \OC_Log::WARN);
+ \OC_Log::write('OCP\Share', 'Sharing backend '.$class.' not registered, '
+ .self::$backendTypes[$itemType]['class'].' is already registered for '.$itemType, \OC_Log::WARN);
}
return false;
}
@@ -99,8 +103,20 @@ class Share {
* @param int Number of items to return (optional) Returns all by default
* @return Return depends on format
*/
- public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false) {
- return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format, $parameters, $limit, $includeCollections);
+ public static function getItemsSharedWith($itemType,
+ $format = self::FORMAT_NONE,
+ $parameters = null,
+ $limit = -1,
+ $includeCollections = false) {
+ return self::getItems($itemType,
+ null,
+ self::$shareTypeUserAndGroups,
+ \OC_User::getUser(),
+ null,
+ $format,
+ $parameters,
+ $limit,
+ $includeCollections);
}
/**
@@ -110,8 +126,20 @@ class Share {
* @param int Format (optional) Format type must be defined by the backend
* @return Return depends on format
*/
- public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE, $parameters = null, $includeCollections = false) {
- return self::getItems($itemType, $itemTarget, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format, $parameters, 1, $includeCollections);
+ public static function getItemSharedWith($itemType,
+ $itemTarget,
+ $format = self::FORMAT_NONE,
+ $parameters = null,
+ $includeCollections = false) {
+ return self::getItems($itemType,
+ $itemTarget,
+ self::$shareTypeUserAndGroups,
+ \OC_User::getUser(),
+ null,
+ $format,
+ $parameters,
+ 1,
+ $includeCollections);
}
/**
@@ -121,8 +149,20 @@ class Share {
* @param int Format (optional) Format type must be defined by the backend
* @return Return depends on format
*/
- public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE, $parameters = null, $includeCollections = false) {
- return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format, $parameters, 1, $includeCollections, true);
+ public static function getItemSharedWithBySource($itemType,
+ $itemSource,
+ $format = self::FORMAT_NONE,
+ $parameters = null,
+ $includeCollections = false) {
+ return self::getItems($itemType,
+ $itemSource,
+ self::$shareTypeUserAndGroups,
+ \OC_User::getUser(),
+ null,
+ $format,
+ $parameters,
+ 1,
+ $includeCollections, true);
}
/**
@@ -133,7 +173,14 @@ class Share {
* @return Item
*/
public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) {
- return self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1);
+ return self::getItems($itemType,
+ $itemSource,
+ self::SHARE_TYPE_LINK,
+ null,
+ $uidOwner,
+ self::FORMAT_NONE,
+ null,
+ 1);
}
/**
@@ -142,7 +189,7 @@ class Share {
* @return Item
*/
public static function getShareByToken($token) {
- $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?',1);
+ $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
$result = $query->execute(array($token));
if (\OC_DB::isError($result)) {
\OC_Log::write('OCP\Share', \OC_DB::getErrorMessage($result) . ', token=' . $token, \OC_Log::ERROR);
@@ -157,8 +204,20 @@ class Share {
* @param int Number of items to return (optional) Returns all by default
* @return Return depends on format
*/
- public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false) {
- return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format, $parameters, $limit, $includeCollections);
+ public static function getItemsShared($itemType,
+ $format = self::FORMAT_NONE,
+ $parameters = null,
+ $limit = -1,
+ $includeCollections = false) {
+ return self::getItems($itemType,
+ null,
+ null,
+ null,
+ \OC_User::getUser(),
+ $format,
+ $parameters,
+ $limit,
+ $includeCollections);
}
/**
@@ -168,8 +227,20 @@ class Share {
* @param int Format (optional) Format type must be defined by the backend
* @return Return depends on format
*/
- public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE, $parameters = null, $includeCollections = false) {
- return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format, $parameters, -1, $includeCollections);
+ public static function getItemShared($itemType,
+ $itemSource,
+ $format = self::FORMAT_NONE,
+ $parameters = null,
+ $includeCollections = false) {
+ return self::getItems($itemType,
+ $itemSource,
+ null,
+ null,
+ \OC_User::getUser(),
+ $format,
+ $parameters,
+ -1,
+ $includeCollections);
}
/**
@@ -199,14 +270,26 @@ class Share {
if ($sharingPolicy == 'groups_only') {
$inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
if (empty($inGroup)) {
- $message = 'Sharing '.$itemSource.' failed, because the user '.$shareWith.' is not a member of any groups that '.$uidOwner.' is a member of';
+ $message = 'Sharing '.$itemSource.' failed, because the user '.$shareWith.' is not a member'
+ .' of any groups that '.$uidOwner.' is a member of';
\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
throw new \Exception($message);
}
}
// Check if the item source is already shared with the user, either from the same owner or a different user
- if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
- // Only allow the same share to occur again if it is the same owner and is not a user share, this use case is for increasing permissions for a specific user
+ $checkExists = self::getItems($itemType,
+ $itemSource,
+ self::$shareTypeUserAndGroups,
+ $shareWith,
+ null,
+ self::FORMAT_NONE,
+ null,
+ 1,
+ true,
+ true);
+ if ($checkExists) {
+ // Only allow the same share to occur again if it is the same owner and is not a user share,
+ // this use case is for increasing permissions for a specific user
if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
$message = 'Sharing '.$itemSource.' failed, because this item is already shared with '.$shareWith;
\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
@@ -220,14 +303,26 @@ class Share {
throw new \Exception($message);
}
if ($sharingPolicy == 'groups_only' && !\OC_Group::inGroup($uidOwner, $shareWith)) {
- $message = 'Sharing '.$itemSource.' failed, because '.$uidOwner.' is not a member of the group '.$shareWith;
+ $message = 'Sharing '.$itemSource.' failed, because '.$uidOwner
+ .' is not a member of the group '.$shareWith;
\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
throw new \Exception($message);
}
// Check if the item source is already shared with the group, either from the same owner or a different user
// The check for each user in the group is done inside the put() function
- if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
- // Only allow the same share to occur again if it is the same owner and is not a group share, this use case is for increasing permissions for a specific user
+ $checkExists = self::getItems($itemType,
+ $itemSource,
+ self::SHARE_TYPE_GROUP,
+ $shareWith,
+ null,
+ self::FORMAT_NONE,
+ null,
+ 1,
+ true,
+ true);
+ if ($checkExists) {
+ // Only allow the same share to occur again if it is the same owner and is not a group share,
+ // this use case is for increasing permissions for a specific user
if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
$message = 'Sharing '.$itemSource.' failed, because this item is already shared with '.$shareWith;
\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
@@ -242,27 +337,42 @@ class Share {
} else if ($shareType === self::SHARE_TYPE_LINK) {
if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
// when updating a link share
- if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) {
+ $checkExists = self::getItems($itemType,
+ $itemSource,
+ self::SHARE_TYPE_LINK,
+ null,
+ $uidOwner,
+ self::FORMAT_NONE,
+ null,
+ 1);
+ if ($checkExists) {
// remember old token
$oldToken = $checkExists['token'];
//delete the old share
self::delete($checkExists['id']);
}
-
+
// Generate hash of password - same method as user passwords
if (isset($shareWith)) {
$forcePortable = (CRYPT_BLOWFISH != 1);
$hasher = new \PasswordHash(8, $forcePortable);
$shareWith = $hasher->HashPassword($shareWith.\OC_Config::getValue('passwordsalt', ''));
}
-
+
// Generate token
if (isset($oldToken)) {
$token = $oldToken;
} else {
$token = \OC_Util::generate_random_bytes(self::TOKEN_LENGTH);
}
- $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token);
+ $result = self::put($itemType,
+ $itemSource,
+ $shareType,
+ $shareWith,
+ $uidOwner,
+ $permissions,
+ null,
+ $token);
if ($result) {
return $token;
} else {
@@ -305,19 +415,26 @@ class Share {
if ($parentFolder && $files = \OC_Files::getDirectoryContent($itemSource)) {
for ($i = 0; $i < count($files); $i++) {
$name = substr($files[$i]['name'], strpos($files[$i]['name'], $itemSource) - strlen($itemSource));
- if ($files[$i]['mimetype'] == 'httpd/unix-directory' && $children = \OC_Files::getDirectoryContent($name, '/')) {
+ if ($files[$i]['mimetype'] == 'httpd/unix-directory'
+ && $children = \OC_Files::getDirectoryContent($name, '/')
+ ) {
// Continue scanning into child folders
array_push($files, $children);
} else {
// Check file extension for an equivalent item type to convert to
$extension = strtolower(substr($itemSource, strrpos($itemSource, '.') + 1));
foreach (self::$backends as $type => $backend) {
- if (isset($backend->dependsOn) && $backend->dependsOn == 'file' && isset($backend->supportedFileExtensions) && in_array($extension, $backend->supportedFileExtensions)) {
+ if (isset($backend->dependsOn)
+ && $backend->dependsOn == 'file'
+ && isset($backend->supportedFileExtensions)
+ && in_array($extension, $backend->supportedFileExtensions)
+ ) {
$itemType = $type;
break;
}
}
- // Pass on to put() to check if this item should be converted, the item won't be inserted into the database unless it can be converted
+ // Pass on to put() to check if this item should be converted,
+ // the item won't be inserted into the database unless it can be converted
self::put($itemType, $name, $shareType, $shareWith, $uidOwner, $permissions, $parentFolder);
}
}
@@ -339,7 +456,15 @@ class Share {
* @return Returns true on success or false on failure
*/
public static function unshare($itemType, $itemSource, $shareType, $shareWith) {
- if ($item = self::getItems($itemType, $itemSource, $shareType, $shareWith, \OC_User::getUser(), self::FORMAT_NONE, null, 1)) {
+ $item = self::getItems($itemType,
+ $itemSource,
+ $shareType,
+ $shareWith,
+ \OC_User::getUser(),
+ self::FORMAT_NONE,
+ null,
+ 1);
+ if ($item) {
self::delete($item['id']);
return true;
}
@@ -353,7 +478,8 @@ class Share {
* @return Returns true on success or false on failure
*/
public static function unshareAll($itemType, $itemSource) {
- if ($shares = self::getItemShared($itemType, $itemSource)) {
+ $shares = self::getItemShared($itemType, $itemSource);
+ if ($shares) {
foreach ($shares as $share) {
self::delete($share['id']);
}
@@ -372,11 +498,27 @@ class Share {
*
*/
public static function unshareFromSelf($itemType, $itemTarget) {
- if ($item = self::getItemSharedWith($itemType, $itemTarget)) {
+ $item = self::getItemSharedWith($itemType, $itemTarget);
+ if ($item) {
if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
- // Insert an extra row for the group share and set permission to 0 to prevent it from showing up for the user
- $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (`item_type`, `item_source`, `item_target`, `parent`, `share_type`, `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`) VALUES (?,?,?,?,?,?,?,?,?,?,?)');
- $query->execute(array($item['item_type'], $item['item_source'], $item['item_target'], $item['id'], self::$shareTypeGroupUserUnique, \OC_User::getUser(), $item['uid_owner'], 0, $item['stime'], $item['file_source'], $item['file_target']));
+ // Insert an extra row for the group share and set permission to 0
+ // to prevent it from showing up for the user
+ $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
+ .'`item_type`, `item_source`, `item_target`, `parent`, `share_type`, `share_with`, '
+ .'`uid_owner`, `permissions`, `stime`, `file_source`, `file_target`'
+ .') VALUES (?,?,?,?,?,?,?,?,?,?,?)');
+ $query->execute(array(
+ $item['item_type'],
+ $item['item_source'],
+ $item['item_target'],
+ $item['id'],
+ self::$shareTypeGroupUserUnique,
+ \OC_User::getUser(),
+ $item['uid_owner'],
+ 0,
+ $item['stime'],
+ $item['file_source'],
+ $item['file_target']));
\OC_DB::insertid('*PREFIX*share');
// Delete all reshares by this user of the group share
self::delete($item['id'], true, \OC_User::getUser());
@@ -403,13 +545,24 @@ class Share {
* @return Returns true on success or false on failure
*/
public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) {
- if ($item = self::getItems($itemType, $itemSource, $shareType, $shareWith, \OC_User::getUser(), self::FORMAT_NONE, null, 1, false)) {
- // Check if this item is a reshare and verify that the permissions granted don't exceed the parent shared item
+ $item = self::getItems($itemType,
+ $itemSource,
+ $shareType,
+ $shareWith,
+ \OC_User::getUser(),
+ self::FORMAT_NONE,
+ null,
+ 1,
+ false);
+ if ($item) {
+ // Check if this item is a reshare and
+ // verify that the permissions granted don't exceed the parent shared item
if (isset($item['parent'])) {
$query = \OC_DB::prepare('SELECT `permissions` FROM `*PREFIX*share` WHERE `id` = ?', 1);
$result = $query->execute(array($item['parent']))->fetchRow();
if (~(int)$result['permissions'] & $permissions) {
- $message = 'Setting permissions for '.$itemSource.' failed, because the permissions exceed permissions granted to '.\OC_User::getUser();
+ $message = 'Setting permissions for '.$itemSource.' failed, '
+ .'because the permissions exceed permissions granted to '.\OC_User::getUser();
\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
throw new \Exception($message);
}
@@ -426,9 +579,12 @@ class Share {
$parents = array($item['id']);
while (!empty($parents)) {
$parents = "'".implode("','", $parents)."'";
- $query = \OC_DB::prepare('SELECT `id`, `permissions` FROM `*PREFIX*share` WHERE `parent` IN ('.$parents.')');
+ $query = \OC_DB::prepare('SELECT `id`, `permissions`'
+ .' FROM `*PREFIX*share`'
+ .' WHERE `parent` IN ('.$parents.')');
$result = $query->execute();
- // Reset parents array, only go through loop again if items are found that need permissions removed
+ // Reset parents array,
+ // only go through loop again if items are found that need permissions removed
$parents = array();
while ($item = $result->fetchRow()) {
// Check if permissions need to be removed
@@ -442,7 +598,9 @@ class Share {
// Remove the permissions for all reshares of this item
if (!empty($ids)) {
$ids = "'".implode("','", $ids)."'";
- $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = `permissions` & ? WHERE `id` IN ('.$ids.')');
+ $query = \OC_DB::prepare('UPDATE `*PREFIX*share`'
+ .' SET `permissions` = `permissions` & ?'
+ .' WHERE `id` IN ('.$ids.')');
$query->execute(array($permissions));
}
}
@@ -455,7 +613,16 @@ class Share {
}
public static function setExpirationDate($itemType, $itemSource, $date) {
- if ($items = self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), self::FORMAT_NONE, null, -1, false)) {
+ $items = self::getItems($itemType,
+ $itemSource,
+ null,
+ null,
+ \OC_User::getUser(),
+ self::FORMAT_NONE,
+ null,
+ -1,
+ false);
+ if ($items) {
if (!empty($items)) {
if ($date == '') {
$date = null;
@@ -517,7 +684,8 @@ class Share {
if (!self::getBackend($itemType) instanceof Share_Backend_Collection) {
unset($collectionTypes[0]);
}
- // Return array if collections were found or the item type is a collection itself - collections can be inside collections
+ // Return array if collections were found or the item type is a collection itself
+ // - collections can be inside collections
if (count($collectionTypes) > 0) {
return $collectionTypes;
}
@@ -528,7 +696,8 @@ class Share {
* @brief Get shared items from the database
* @param string Item type
* @param string Item source or target (optional)
- * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
+ * @param int SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK,
+ * $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
* @param string User or group the item is being shared with
* @param string User that is the owner of shared items (optional)
* @param int Format to convert items to with formatItems()
@@ -540,7 +709,16 @@ class Share {
* See public functions getItem(s)... for parameter usage
*
*/
- private static function getItems($itemType, $item = null, $shareType = null, $shareWith = null, $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false, $itemShareWithBySource = false) {
+ private static function getItems($itemType,
+ $item = null,
+ $shareType = null,
+ $shareWith = null,
+ $uidOwner = null,
+ $format = self::FORMAT_NONE,
+ $parameters = null,
+ $limit = -1,
+ $includeCollections = false,
+ $itemShareWithBySource = false) {
if (!self::isEnabled()) {
if ($limit == 1 || (isset($uidOwner) && isset($item))) {
return false;
@@ -549,7 +727,8 @@ class Share {
}
}
$backend = self::getBackend($itemType);
- // Get filesystem root to add it to the file target and remove from the file source, match file_source with the file cache
+ // Get filesystem root to add it to the file target and remove from the file source,
+ // match file_source with the file cache
if ($itemType == 'file' || $itemType == 'folder') {
$root = \OC_Filesystem::getRoot();
$where = 'INNER JOIN `*PREFIX*fscache` ON `file_source` = `*PREFIX*fscache`.`id`';
@@ -569,7 +748,7 @@ class Share {
$itemTypes = $collectionTypes;
}
$placeholders = join(',', array_fill(0, count($itemTypes), '?'));
- $where .= ' WHERE `item_type` IN ('.$placeholders.'))';
+ $where = ' WHERE `item_type` IN ('.$placeholders.'))';
$queryArgs = $itemTypes;
} else {
$where = ' WHERE `item_type` = ?';
@@ -652,7 +831,8 @@ class Share {
}
if ($limit != -1 && !$includeCollections) {
if ($shareType == self::$shareTypeUserAndGroups) {
- // Make sure the unique user target is returned if it exists, unique targets should follow the group share in the database
+ // Make sure the unique user target is returned if it exists,
+ // unique targets should follow the group share in the database
// If the limit is not 1, the filtering can be done later
$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
}
@@ -668,23 +848,34 @@ class Share {
// TODO Optimize selects
if ($format == self::FORMAT_STATUSES) {
if ($itemType == 'file' || $itemType == 'folder') {
- $select = '`*PREFIX*share`.`id`, `item_type`, `*PREFIX*share`.`parent`, `share_type`, `file_source`, `path`, `expiration`';
+ $select = '`*PREFIX*share`.`id`, `item_type`, `*PREFIX*share`.`parent`, '
+ .'`share_type`, `file_source`, `path`, `expiration`';
} else {
$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `expiration`';
}
} else {
if (isset($uidOwner)) {
if ($itemType == 'file' || $itemType == 'folder') {
- $select = '`*PREFIX*share`.`id`, `item_type`, `*PREFIX*share`.`parent`, `share_type`, `share_with`, `file_source`, `path`, `permissions`, `stime`, `expiration`, `token`';
+ $select = '`*PREFIX*share`.`id`, `item_type`, `*PREFIX*share`.`parent`, `share_type`, '
+ .'`share_with`, `file_source`, `path`, `permissions`, `stime`, `expiration`, `token`';
} else {
- $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `permissions`, `stime`, `file_source`, `expiration`, `token`';
+ $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, '
+ .'`permissions`, `stime`, `file_source`, `expiration`, `token`';
}
} else {
if ($fileDependent) {
- if (($itemType == 'file' || $itemType == 'folder') && $format == \OC_Share_Backend_File::FORMAT_FILE_APP || $format == \OC_Share_Backend_File::FORMAT_FILE_APP_ROOT) {
- $select = '`*PREFIX*share`.`id`, `item_type`, `*PREFIX*share`.`parent`, `uid_owner`, `share_type`, `share_with`, `file_source`, `path`, `file_target`, `permissions`, `expiration`, `name`, `ctime`, `mtime`, `mimetype`, `size`, `encrypted`, `versioned`, `writable`';
+ if (($itemType == 'file' || $itemType == 'folder')
+ && $format == \OC_Share_Backend_File::FORMAT_FILE_APP
+ || $format == \OC_Share_Backend_File::FORMAT_FILE_APP_ROOT
+ ) {
+ $select = '`*PREFIX*share`.`id`, `item_type`, `*PREFIX*share`.`parent`, `uid_owner`, '
+ .'`share_type`, `share_with`, `file_source`, `path`, `file_target`, `permissions`, '
+ .'`expiration`, `name`, `ctime`, `mtime`, `mimetype`, `size`, `encrypted`, '
+ .'`versioned`, `writable`';
} else {
- $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`, `*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`, `file_source`, `path`, `file_target`, `permissions`, `stime`, `expiration`, `token`';
+ $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`, '
+ .'`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`, `file_source`, '
+ .'`path`, `file_target`, `permissions`, `stime`, `expiration`, `token`';
}
} else {
$select = '*';
@@ -695,7 +886,9 @@ class Share {
$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
$result = $query->execute($queryArgs);
if (\OC_DB::isError($result)) {
- \OC_Log::write('OCP\Share', \OC_DB::getErrorMessage($result) . ', select=' . $select . ' where=' . $where, \OC_Log::ERROR);
+ \OC_Log::write('OCP\Share', \OC_DB::getErrorMessage($result)
+ . ', select=' . $select
+ . ' where=' . $where, \OC_Log::ERROR);
}
$items = array();
$targets = array();
@@ -712,7 +905,8 @@ class Share {
} else if (!isset($uidOwner)) {
// Check if the same target already exists
if (isset($targets[$row[$column]])) {
- // Check if the same owner shared with the user twice through a group and user share - this is allowed
+ // Check if the same owner shared with the user twice through a group and user share
+ // - this is allowed
$id = $targets[$row[$column]];
if ($items[$id]['uid_owner'] == $row['uid_owner']) {
// Switch to group share type to ensure resharing conditions aren't bypassed
@@ -720,8 +914,11 @@ class Share {
$items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
$items[$id]['share_with'] = $row['share_with'];
}
- // Switch ids if sharing permission is granted on only one share to ensure correct parent is used if resharing
- if (~(int)$items[$id]['permissions'] & PERMISSION_SHARE && (int)$row['permissions'] & PERMISSION_SHARE) {
+ // Switch ids if sharing permission is granted on only one share
+ // to ensure correct parent is used if resharing
+ if (~(int)$items[$id]['permissions'] & PERMISSION_SHARE
+ && (int)$row['permissions'] & PERMISSION_SHARE
+ ) {
$items[$row['id']] = $items[$id];
unset($items[$id]);
$id = $row['id'];
@@ -764,7 +961,9 @@ class Share {
}
// Check if this is a collection of the requested item type
if ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
- if (($collectionBackend = self::getBackend($row['item_type'])) && $collectionBackend instanceof Share_Backend_Collection) {
+ if (($collectionBackend = self::getBackend($row['item_type']))
+ && $collectionBackend instanceof Share_Backend_Collection
+ ) {
// Collections can be inside collections, check if the item is a collection
if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
$collectionItems[] = $row;
@@ -856,10 +1055,18 @@ class Share {
* @param bool|array Parent folder target (optional)
* @return bool Returns true on success or false on failure
*/
- private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $parentFolder = null, $token = null) {
+ private static function put($itemType,
+ $itemSource,
+ $shareType,
+ $shareWith,
+ $uidOwner,
+ $permissions,
+ $parentFolder = null,
+ $token = null) {
$backend = self::getBackend($itemType);
// Check if this is a reshare
- if ($checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true)) {
+ $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
+ if ($checkReshare) {
// Check if attempting to share back to owner
if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
$message = 'Sharing '.$itemSource.' failed, because the user '.$shareWith.' is the original sharer';
@@ -869,7 +1076,8 @@ class Share {
// Check if share permissions is granted
if ((int)$checkReshare['permissions'] & PERMISSION_SHARE) {
if (~(int)$checkReshare['permissions'] & $permissions) {
- $message = 'Sharing '.$itemSource.' failed, because the permissions exceed permissions granted to '.$uidOwner;
+ $message = 'Sharing '.$itemSource.' failed, '
+ .'because the permissions exceed permissions granted to '.$uidOwner;
\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
throw new \Exception($message);
} else {
@@ -891,7 +1099,8 @@ class Share {
$suggestedItemTarget = null;
$suggestedFileTarget = null;
if (!$backend->isValidSource($itemSource, $uidOwner)) {
- $message = 'Sharing '.$itemSource.' failed, because the sharing backend for '.$itemType.' could not find its source';
+ $message = 'Sharing '.$itemSource.' failed, '
+ .'because the sharing backend for '.$itemType.' could not find its source';
\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
throw new \Exception($message);
}
@@ -913,14 +1122,27 @@ class Share {
$fileSource = null;
}
}
- $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (`item_type`, `item_source`, `item_target`, `parent`, `share_type`, `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`, `token`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
+ $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (`item_type`, `item_source`, `item_target`, `parent`,'
+ .' `share_type`, `share_with`, `uid_owner`, `permissions`,'
+ .' `stime`, `file_source`, `file_target`, `token`'
+ .') VALUES (?,?,?,?,?,?,?,?,?,?,?,?)');
// Share with a group
if ($shareType == self::SHARE_TYPE_GROUP) {
- $groupItemTarget = self::generateTarget($itemType, $itemSource, $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
+ $groupItemTarget = self::generateTarget($itemType,
+ $itemSource,
+ $shareType,
+ $shareWith['group'],
+ $uidOwner,
+ $suggestedItemTarget);
if (isset($fileSource)) {
if ($parentFolder) {
if ($parentFolder === true) {
- $groupFileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith['group'], $uidOwner, $suggestedFileTarget);
+ $groupFileTarget = self::generateTarget('file',
+ $filePath,
+ $shareType,
+ $shareWith['group'],
+ $uidOwner,
+ $suggestedFileTarget);
// Set group default file target for future use
$parentFolders[0]['folder'] = $groupFileTarget;
} else {
@@ -929,21 +1151,50 @@ class Share {
$parent = $parentFolder[0]['id'];
}
} else {
- $groupFileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith['group'], $uidOwner, $suggestedFileTarget);
+ $groupFileTarget = self::generateTarget('file',
+ $filePath,
+ $shareType,
+ $shareWith['group'],
+ $uidOwner,
+ $suggestedFileTarget);
}
} else {
$groupFileTarget = null;
}
- $query->execute(array($itemType, $itemSource, $groupItemTarget, $parent, $shareType, $shareWith['group'], $uidOwner, $permissions, time(), $fileSource, $groupFileTarget, $token));
+ $query->execute(array(
+ $itemType,
+ $itemSource,
+ $groupItemTarget,
+ $parent,
+ $shareType,
+ $shareWith['group'],
+ $uidOwner,
+ $permissions,
+ time(),
+ $fileSource,
+ $groupFileTarget,
+ $token));
// Save this id, any extra rows for this group share will need to reference it
$parent = \OC_DB::insertid('*PREFIX*share');
// Loop through all users of this group in case we need to add an extra row
foreach ($shareWith['users'] as $uid) {
- $itemTarget = self::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $uid, $uidOwner, $suggestedItemTarget, $parent);
+ $itemTarget = self::generateTarget($itemType,
+ $itemSource,
+ self::SHARE_TYPE_USER,
+ $uid,
+ $uidOwner,
+ $suggestedItemTarget,
+ $parent);
if (isset($fileSource)) {
if ($parentFolder) {
if ($parentFolder === true) {
- $fileTarget = self::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $uid, $uidOwner, $suggestedFileTarget, $parent);
+ $fileTarget = self::generateTarget('file',
+ $filePath,
+ self::SHARE_TYPE_USER,
+ $uid,
+ $uidOwner,
+ $suggestedFileTarget,
+ $parent);
if ($fileTarget != $groupFileTarget) {
$parentFolders[$uid]['folder'] = $fileTarget;
}
@@ -952,7 +1203,13 @@ class Share {
$parent = $parentFolder[$uid]['id'];
}
} else {
- $fileTarget = self::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $uid, $uidOwner, $suggestedFileTarget, $parent);
+ $fileTarget = self::generateTarget('file',
+ $filePath,
+ self::SHARE_TYPE_USER,
+ $uid,
+ $uidOwner,
+ $suggestedFileTarget,
+ $parent);
}
} else {
$fileTarget = null;
@@ -973,7 +1230,19 @@ class Share {
));
// Insert an extra row for the group share if the item or file target is unique for this user
if ($itemTarget != $groupItemTarget || (isset($fileSource) && $fileTarget != $groupFileTarget)) {
- $query->execute(array($itemType, $itemSource, $itemTarget, $parent, self::$shareTypeGroupUserUnique, $uid, $uidOwner, $permissions, time(), $fileSource, $fileTarget, $token));
+ $query->execute(array(
+ $itemType,
+ $itemSource,
+ $itemTarget,
+ $parent,
+ self::$shareTypeGroupUserUnique,
+ $uid,
+ $uidOwner,
+ $permissions,
+ time(),
+ $fileSource,
+ $fileTarget,
+ $token));
$id = \OC_DB::insertid('*PREFIX*share');
}
}
@@ -982,23 +1251,50 @@ class Share {
return $parentFolders;
}
} else {
- $itemTarget = self::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedItemTarget);
+ $itemTarget = self::generateTarget($itemType,
+ $itemSource,
+ $shareType,
+ $shareWith,
+ $uidOwner,
+ $suggestedItemTarget);
if (isset($fileSource)) {
if ($parentFolder) {
if ($parentFolder === true) {
- $fileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith, $uidOwner, $suggestedFileTarget);
+ $fileTarget = self::generateTarget('file',
+ $filePath,
+ $shareType,
+ $shareWith,
+ $uidOwner,
+ $suggestedFileTarget);
$parentFolders['folder'] = $fileTarget;
} else {
$fileTarget = $parentFolder['folder'].$itemSource;
$parent = $parentFolder['id'];
}
} else {
- $fileTarget = self::generateTarget('file', $filePath, $shareType, $shareWith, $uidOwner, $suggestedFileTarget);
+ $fileTarget = self::generateTarget('file',
+ $filePath,
+ $shareType,
+ $shareWith,
+ $uidOwner,
+ $suggestedFileTarget);
}
} else {
$fileTarget = null;
}
- $query->execute(array($itemType, $itemSource, $itemTarget, $parent, $shareType, $shareWith, $uidOwner, $permissions, time(), $fileSource, $fileTarget, $token));
+ $query->execute(array(
+ $itemType,
+ $itemSource,
+ $itemTarget,
+ $parent,
+ $shareType,
+ $shareWith,
+ $uidOwner,
+ $permissions,
+ time(),
+ $fileSource,
+ $fileTarget,
+ $token));
$id = \OC_DB::insertid('*PREFIX*share');
\OC_Hook::emit('OCP\Share', 'post_shared', array(
'itemType' => $itemType,
@@ -1033,7 +1329,13 @@ class Share {
* @param int The id of the parent group share (optional)
* @return string Item target
*/
- private static function generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedTarget = null, $groupParent = null) {
+ private static function generateTarget($itemType,
+ $itemSource,
+ $shareType,
+ $shareWith,
+ $uidOwner,
+ $suggestedTarget = null,
+ $groupParent = null) {
$backend = self::getBackend($itemType);
if ($shareType == self::SHARE_TYPE_LINK) {
if (isset($suggestedTarget)) {
@@ -1099,18 +1401,43 @@ class Share {
// Find similar targets to improve backend's chances to generate a unqiue target
if ($userAndGroups) {
if ($column == 'file_target') {
- $checkTargets = \OC_DB::prepare('SELECT `'.$column.'` FROM `*PREFIX*share` WHERE `item_type` IN (\'file\', \'folder\') AND `share_type` IN (?,?,?) AND `share_with` IN (\''.implode('\',\'', $userAndGroups).'\')');
- $result = $checkTargets->execute(array(self::SHARE_TYPE_USER, self::SHARE_TYPE_GROUP, self::$shareTypeGroupUserUnique));
+ $checkTargets = \OC_DB::prepare('SELECT `'.$column.'`'
+ .' FROM `*PREFIX*share`'
+ .' WHERE `item_type` IN (\'file\', \'folder\')'
+ .' AND `share_type` IN (?,?,?)'
+ .' AND `share_with`'
+ .' IN (\''.implode('\',\'', $userAndGroups).'\')');
+ $result = $checkTargets->execute(array(
+ self::SHARE_TYPE_USER,
+ self::SHARE_TYPE_GROUP,
+ self::$shareTypeGroupUserUnique));
} else {
- $checkTargets = \OC_DB::prepare('SELECT `'.$column.'` FROM `*PREFIX*share` WHERE `item_type` = ? AND `share_type` IN (?,?,?) AND `share_with` IN (\''.implode('\',\'', $userAndGroups).'\')');
- $result = $checkTargets->execute(array($itemType, self::SHARE_TYPE_USER, self::SHARE_TYPE_GROUP, self::$shareTypeGroupUserUnique));
+ $checkTargets = \OC_DB::prepare('SELECT `'.$column.'`'
+ .' FROM `*PREFIX*share`'
+ .' WHERE `item_type` = ?'
+ .' AND `share_type` IN (?,?,?)'
+ .' AND `share_with`'
+ .' IN (\''.implode('\',\'', $userAndGroups).'\')');
+ $result = $checkTargets->execute(array(
+ $itemType,
+ self::SHARE_TYPE_USER,
+ self::SHARE_TYPE_GROUP,
+ self::$shareTypeGroupUserUnique));
}
} else {
if ($column == 'file_target') {
- $checkTargets = \OC_DB::prepare('SELECT `'.$column.'` FROM `*PREFIX*share` WHERE `item_type` IN (\'file\', \'folder\') AND `share_type` = ? AND `share_with` = ?');
+ $checkTargets = \OC_DB::prepare('SELECT `'.$column.'`'
+ .' FROM `*PREFIX*share`'
+ .' WHERE `item_type` IN (\'file\', \'folder\')'
+ .' AND `share_type` = ?'
+ .' AND `share_with` = ?');
$result = $checkTargets->execute(array(self::SHARE_TYPE_GROUP, $shareWith));
} else {
- $checkTargets = \OC_DB::prepare('SELECT `'.$column.'` FROM `*PREFIX*share` WHERE `item_type` = ? AND `share_type` = ? AND `share_with` = ?');
+ $checkTargets = \OC_DB::prepare('SELECT `'.$column.'`'
+ .' FROM `*PREFIX*share`'
+ .' WHERE `item_type` = ?'
+ .' AND `share_type` = ?'
+ .' AND `share_with` = ?');
$result = $checkTargets->execute(array($itemType, self::SHARE_TYPE_GROUP, $shareWith));
}
}
@@ -1138,21 +1465,43 @@ class Share {
$parents = array($parent);
while (!empty($parents)) {
$parents = "'".implode("','", $parents)."'";
- // Check the owner on the first search of reshares, useful for finding and deleting the reshares by a single user of a group share
+ // Check the owner on the first search of reshares,
+ // useful for finding and deleting the reshares by a single user of a group share
if (count($ids) == 1 && isset($uidOwner)) {
- $query = \OC_DB::prepare('SELECT `id`, `uid_owner`, `item_type`, `item_target`, `parent` FROM `*PREFIX*share` WHERE `parent` IN ('.$parents.') AND `uid_owner` = ?');
+ $query = \OC_DB::prepare('SELECT `id`, `uid_owner`, `item_type`, `item_target`, `parent`'
+ .' FROM `*PREFIX*share`'
+ .' WHERE `parent` IN ('.$parents.')'
+ .' AND `uid_owner` = ?');
$result = $query->execute(array($uidOwner));
} else {
- $query = \OC_DB::prepare('SELECT `id`, `item_type`, `item_target`, `parent`, `uid_owner` FROM `*PREFIX*share` WHERE `parent` IN ('.$parents.')');
+ $query = \OC_DB::prepare('SELECT `id`, `item_type`, `item_target`, `parent`, `uid_owner`'
+ .' FROM `*PREFIX*share`'
+ .' WHERE `parent` IN ('.$parents.')');
$result = $query->execute();
}
// Reset parents array, only go through loop again if items are found
$parents = array();
while ($item = $result->fetchRow()) {
- // Search for a duplicate parent share, this occurs when an item is shared to the same user through a group and user or the same item is shared by different users
+ // Search for a duplicate parent share,
+ // this occurs when an item is shared to the same user through a group and user
+ // or the same item is shared by different users
$userAndGroups = array_merge(array($item['uid_owner']), \OC_Group::getUserGroups($item['uid_owner']));
- $query = \OC_DB::prepare('SELECT `id`, `permissions` FROM `*PREFIX*share` WHERE `item_type` = ? AND `item_target` = ? AND `share_type` IN (?,?,?) AND `share_with` IN (\''.implode('\',\'', $userAndGroups).'\') AND `uid_owner` != ? AND `id` != ?');
- $duplicateParent = $query->execute(array($item['item_type'], $item['item_target'], self::SHARE_TYPE_USER, self::SHARE_TYPE_GROUP, self::$shareTypeGroupUserUnique, $item['uid_owner'], $item['parent']))->fetchRow();
+ $query = \OC_DB::prepare('SELECT `id`, `permissions`'
+ .' FROM `*PREFIX*share`'
+ .' WHERE `item_type` = ?'
+ .' AND `item_target` = ?'
+ .' AND `share_type` IN (?,?,?)'
+ .' AND `share_with` IN (\''.implode('\',\'', $userAndGroups).'\')'
+ .' AND `uid_owner` != ?'
+ .' AND `id` != ?');
+ $duplicateParent = $query->execute(array(
+ $item['item_type'],
+ $item['item_target'],
+ self::SHARE_TYPE_USER,
+ self::SHARE_TYPE_GROUP,
+ self::$shareTypeGroupUserUnique,
+ $item['uid_owner'],
+ $item['parent']))->fetchRow();
if ($duplicateParent) {
// Change the parent to the other item id if share permission is granted
if ($duplicateParent['permissions'] & PERMISSION_SHARE) {
@@ -1181,7 +1530,10 @@ class Share {
public static function post_deleteUser($arguments) {
// Delete any items shared with the deleted user
- $query = \OC_DB::prepare('DELETE FROM `*PREFIX*share` WHERE `share_with` = ? AND `share_type` = ? OR `share_type` = ?');
+ $query = \OC_DB::prepare('DELETE FROM `*PREFIX*share`'
+ .' WHERE `share_with` = ?'
+ .' AND `share_type` = ?'
+ .' OR `share_type` = ?');
$result = $query->execute(array($arguments['uid'], self::SHARE_TYPE_USER, self::$shareTypeGroupUserUnique));
// Delete any items the deleted user shared
$query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*share` WHERE `uid_owner` = ?');
@@ -1195,21 +1547,46 @@ class Share {
// Find the group shares and check if the user needs a unique target
$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `share_type` = ? AND `share_with` = ?');
$result = $query->execute(array(self::SHARE_TYPE_GROUP, $arguments['gid']));
- $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (`item_type`, `item_source`, `item_target`, `parent`, `share_type`, `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`) VALUES (?,?,?,?,?,?,?,?,?,?,?)');
+ $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` (`item_type`, `item_source`, `item_target`, `parent`,'
+ .' `share_type`, `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
+ .' `file_target`)'
+ .' VALUES (?,?,?,?,?,?,?,?,?,?,?)');
while ($item = $result->fetchRow()) {
if ($item['item_type'] == 'file' || $item['item_type'] == 'file') {
$itemTarget = null;
} else {
- $itemTarget = self::generateTarget($item['item_type'], $item['item_source'], self::SHARE_TYPE_USER, $arguments['uid'], $item['uid_owner'], $item['item_target'], $item['id']);
+ $itemTarget = self::generateTarget($item['item_type'],
+ $item['item_source'],
+ self::SHARE_TYPE_USER,
+ $arguments['uid'],
+ $item['uid_owner'],
+ $item['item_target'],
+ $item['id']);
}
if (isset($item['file_source'])) {
- $fileTarget = self::generateTarget($item['item_type'], $item['item_source'], self::SHARE_TYPE_USER, $arguments['uid'], $item['uid_owner'], $item['file_target'], $item['id']);
+ $fileTarget = self::generateTarget($item['item_type'],
+ $item['item_source'],
+ self::SHARE_TYPE_USER,
+ $arguments['uid'],
+ $item['uid_owner'],
+ $item['file_target'],
+ $item['id']);
} else {
$fileTarget = null;
}
// Insert an extra row for the group share if the item or file target is unique for this user
if ($itemTarget != $item['item_target'] || $fileTarget != $item['file_target']) {
- $query->execute(array($item['item_type'], $item['item_source'], $itemTarget, $item['id'], self::$shareTypeGroupUserUnique, $arguments['uid'], $item['uid_owner'], $item['permissions'], $item['stime'], $item['file_source'], $fileTarget));
+ $query->execute(array($item['item_type'],
+ $item['item_source'],
+ $itemTarget,
+ $item['id'],
+ self::$shareTypeGroupUserUnique,
+ $arguments['uid'],
+ $item['uid_owner'],
+ $item['permissions'],
+ $item['stime'],
+ $item['file_source'],
+ $fileTarget));
\OC_DB::insertid('*PREFIX*share');
}
}
@@ -1217,8 +1594,15 @@ class Share {
public static function post_removeFromGroup($arguments) {
// TODO Don't call if user deleted?
- $query = \OC_DB::prepare('SELECT `id`, `share_type` FROM `*PREFIX*share` WHERE (`share_type` = ? AND `share_with` = ?) OR (`share_type` = ? AND `share_with` = ?)');
- $result = $query->execute(array(self::SHARE_TYPE_GROUP, $arguments['gid'], self::$shareTypeGroupUserUnique, $arguments['uid']));
+ $query = \OC_DB::prepare('SELECT `id`, `share_type`'
+ .' FROM `*PREFIX*share`'
+ .' WHERE (`share_type` = ? AND `share_with` = ?)'
+ .' OR (`share_type` = ? AND `share_with` = ?)');
+ $result = $query->execute(array(
+ self::SHARE_TYPE_GROUP,
+ $arguments['gid'],
+ self::$shareTypeGroupUserUnique,
+ $arguments['uid']));
while ($item = $result->fetchRow()) {
if ($item['share_type'] == self::SHARE_TYPE_GROUP) {
// Delete all reshares by this user of the group share
@@ -1275,10 +1659,13 @@ interface Share_Backend {
* @param int Format
* @return ?
*
- * The items array is a 3-dimensional array with the item_source as the first key and the share id as the second key to an array with the share info.
+ * The items array is a 3-dimensional array with the item_source as the first key
+ * and the share id as the second key to an array with the share info.
* The key/value pairs included in the share info depend on the function originally called:
- * If called by getItem(s)Shared: id, item_type, item, item_source, share_type, share_with, permissions, stime, file_source
- * If called by getItem(s)SharedWith: id, item_type, item, item_source, item_target, share_type, share_with, permissions, stime, file_source, file_target
+ * If called by getItem(s)Shared: id, item_type, item, item_source,
+ * share_type, share_with, permissions, stime, file_source
+ * If called by getItem(s)SharedWith: id, item_type, item, item_source,
+ * item_target, share_type, share_with, permissions, stime, file_source, file_target
* This function allows the backend to control the output of shared items with custom formats.
* It is only called through calls to the public getItem(s)Shared(With) functions.
*/
@@ -1311,7 +1698,8 @@ interface Share_Backend_Collection extends Share_Backend {
/**
* @brief Get the sources of the children of the item
* @param string Item source
- * @return array Returns an array of children each inside an array with the keys: source, target, and file_path if applicable
+ * @return array Returns an array of children each inside an array with the keys:
+ * source, target, and file_path if applicable
*/
public function getChildren($itemSource);
diff --git a/lib/public/user.php b/lib/public/user.php
index 9e50115ab70..204d8e4c0f1 100644
--- a/lib/public/user.php
+++ b/lib/public/user.php
@@ -65,7 +65,7 @@ class User {
/**
* @brief check if a user exists
* @param string $uid the username
- * @param string $excludingBackend (default none)
+ * @param string $excludingBackend (default none)
* @return boolean
*/
public static function userExists( $uid, $excludingBackend = null ) {
@@ -73,12 +73,10 @@ class User {
}
/**
* @brief Loggs the user out including all the session data
- * @returns true
- *
* Logout, destroys session
*/
public static function logout() {
- return \OC_USER::logout();
+ \OC_USER::logout();
}
/**
diff --git a/lib/public/util.php b/lib/public/util.php
index af782b01483..413dbcccd28 100644
--- a/lib/public/util.php
+++ b/lib/public/util.php
@@ -68,7 +68,7 @@ class Util {
* @brief write a message in the log
* @param string $app
* @param string $message
- * @param int level
+ * @param int $level
*/
public static function writeLog( $app, $message, $level ) {
// call the internal log class
@@ -77,7 +77,7 @@ class Util {
/**
* @brief add a css file
- * @param url $url
+ * @param string $url
*/
public static function addStyle( $application, $file = null ) {
\OC_Util::addStyle( $application, $file );
@@ -85,8 +85,8 @@ class Util {
/**
* @brief add a javascript file
- * @param appid $application
- * @param filename $file
+ * @param string $application
+ * @param string $file
*/
public static function addScript( $application, $file = null ) {
\OC_Util::addScript( $application, $file );
@@ -94,7 +94,7 @@ class Util {
/**
* @brief Add a custom element to the header
- * @param string tag tag name of the element
+ * @param string $tag tag name of the element
* @param array $attributes array of attributes for the element
* @param string $text the text content for the element
*/
@@ -104,8 +104,8 @@ class Util {
/**
* @brief formats a timestamp in the "right" way
- * @param int timestamp $timestamp
- * @param bool dateOnly option to ommit time from the result
+ * @param int $timestamp $timestamp
+ * @param bool $dateOnly option to omit time from the result
*/
public static function formatDate( $timestamp, $dateOnly=false) {
return(\OC_Util::formatDate( $timestamp, $dateOnly ));
@@ -113,11 +113,11 @@ class Util {
/**
* @brief Creates an absolute url
- * @param $app app
- * @param $file file
- * @param $args array with param=>value, will be appended to the returned url
+ * @param string $app app
+ * @param string $file file
+ * @param array $args array with param=>value, will be appended to the returned url
* The value of $args will be urlencoded
- * @returns the url
+ * @returns string the url
*
* Returns a absolute url to the given app and file.
*/
@@ -127,8 +127,8 @@ class Util {
/**
* @brief Creates an absolute url for remote use
- * @param $service id
- * @returns the url
+ * @param string $service id
+ * @returns string the url
*
* Returns a absolute url to the given app and file.
*/
@@ -138,8 +138,8 @@ class Util {
/**
* @brief Creates an absolute url for public use
- * @param $service id
- * @returns the url
+ * @param string $service id
+ * @returns string the url
*
* Returns a absolute url to the given app and file.
*/
@@ -149,11 +149,11 @@ class Util {
/**
* @brief Creates an url
- * @param $app app
- * @param $file file
- * @param $args array with param=>value, will be appended to the returned url
+ * @param string $app app
+ * @param string $file file
+ * @param array $args array with param=>value, will be appended to the returned url
* The value of $args will be urlencoded
- * @returns the url
+ * @returns string the url
*
* Returns a url to the given app and file.
*/
@@ -163,7 +163,7 @@ class Util {
/**
* @brief Returns the server host
- * @returns the server host
+ * @returns string the server host
*
* Returns the server host, even if the website uses one or more
* reverse proxies
@@ -174,7 +174,7 @@ class Util {
/**
* @brief returns the server hostname
- * @returns the server hostname
+ * @returns string the server hostname
*
* Returns the server host name without an eventual port number
*/
@@ -190,8 +190,8 @@ class Util {
/**
* @brief Returns the default email address
- * @param $user_part the user part of the address
- * @returns the default email address
+ * @param string $user_part the user part of the address
+ * @returns string the default email address
*
* Assembles a default email address (using the server hostname
* and the given user part, and returns it
@@ -203,14 +203,14 @@ class Util {
$host_name = self::getServerHostName();
// handle localhost installations
if ($host_name === 'localhost') {
- $host_name = "example.com";
+ $host_name = "example.com";
}
return $user_part.'@'.$host_name;
}
/**
* @brief Returns the server protocol
- * @returns the server protocol
+ * @returns string the server protocol
*
* Returns the server protocol. It respects reverse proxy servers and load balancers
*/
@@ -220,9 +220,9 @@ class Util {
/**
* @brief Creates path to an image
- * @param $app app
- * @param $image image name
- * @returns the url
+ * @param string $app app
+ * @param string $image image name
+ * @returns string the url
*
* Returns the path to the image.
*/
@@ -232,8 +232,8 @@ class Util {
/**
* @brief Make a human file size
- * @param $bytes file size in bytes
- * @returns a human readable file size
+ * @param int $bytes file size in bytes
+ * @returns string a human readable file size
*
* Makes 2048 to 2 kB.
*/
@@ -243,8 +243,8 @@ class Util {
/**
* @brief Make a computer file size
- * @param $str file size in a fancy format
- * @returns a file size in bytes
+ * @param string $str file size in a fancy format
+ * @returns int a file size in bytes
*
* Makes 2kB to 2048.
*
@@ -256,11 +256,11 @@ class Util {
/**
* @brief connects a function to a hook
- * @param $signalclass class name of emitter
- * @param $signalname name of signal
- * @param $slotclass class name of slot
- * @param $slotname name of slot
- * @returns true/false
+ * @param string $signalclass class name of emitter
+ * @param string $signalname name of signal
+ * @param string $slotclass class name of slot
+ * @param string $slotname name of slot
+ * @returns bool
*
* This function makes it very easy to connect to use hooks.
*
@@ -272,10 +272,10 @@ class Util {
/**
* @brief emitts a signal
- * @param $signalclass class name of emitter
- * @param $signalname name of signal
- * @param $params defautl: array() array with additional data
- * @returns true if slots exists or false if not
+ * @param string $signalclass class name of emitter
+ * @param string $signalname name of signal
+ * @param string $params defautl: array() array with additional data
+ * @returns bool true if slots exists or false if not
*
* Emits a signal. To get data from the slot use references!
*
@@ -298,7 +298,7 @@ class Util {
* Todo: Write howto
*/
public static function callCheck() {
- return(\OC_Util::callCheck());
+ \OC_Util::callCheck();
}
/**
@@ -306,7 +306,7 @@ class Util {
*
* This function is used to sanitize HTML and should be applied on any string or array of strings before displaying it on a web page.
*
- * @param string or array of strings
+ * @param string|array of strings
* @return array with sanitized strings or a single sinitized string, depends on the input parameter.
*/
public static function sanitizeHTML( $value ) {
@@ -316,9 +316,9 @@ class Util {
/**
* @brief Returns an array with all keys from input lowercased or uppercased. Numbered indices are left as is.
*
- * @param $input The array to work on
- * @param $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
- * @param $encoding The encoding parameter is the character encoding. Defaults to UTF-8
+ * @param array $input The array to work on
+ * @param int $case Either MB_CASE_UPPER or MB_CASE_LOWER (default)
+ * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
* @return array
*
*
@@ -330,11 +330,11 @@ class Util {
/**
* @brief replaces a copy of string delimited by the start and (optionally) length parameters with the string given in replacement.
*
- * @param $input The input string. .Opposite to the PHP build-in function does not accept an array.
- * @param $replacement The replacement string.
- * @param $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
- * @param $length Length of the part to be replaced
- * @param $encoding The encoding parameter is the character encoding. Defaults to UTF-8
+ * @param string $input The input string. .Opposite to the PHP build-in function does not accept an array.
+ * @param string $replacement The replacement string.
+ * @param int $start If start is positive, the replacing will begin at the start'th offset into string. If start is negative, the replacing will begin at the start'th character from the end of string.
+ * @param int $length Length of the part to be replaced
+ * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
* @return string
*
*/
@@ -345,11 +345,11 @@ class Util {
/**
* @brief Replace all occurrences of the search string with the replacement string
*
- * @param $search The value being searched for, otherwise known as the needle. String.
- * @param $replace The replacement string.
- * @param $subject The string or array being searched and replaced on, otherwise known as the haystack.
- * @param $encoding The encoding parameter is the character encoding. Defaults to UTF-8
- * @param $count If passed, this will be set to the number of replacements performed.
+ * @param string $search The value being searched for, otherwise known as the needle. String.
+ * @param string $replace The replacement string.
+ * @param string $subject The string or array being searched and replaced on, otherwise known as the haystack.
+ * @param string $encoding The encoding parameter is the character encoding. Defaults to UTF-8
+ * @param int $count If passed, this will be set to the number of replacements performed.
* @return string
*
*/
@@ -359,12 +359,22 @@ class Util {
/**
* @brief performs a search in a nested array
- * @param haystack the array to be searched
- * @param needle the search string
- * @param $index optional, only search this key name
- * @return the key of the matching field, otherwise false
+ * @param array $haystack the array to be searched
+ * @param string $needle the search string
+ * @param int $index optional, only search this key name
+ * @return mixed the key of the matching field, otherwise false
*/
public static function recursiveArraySearch($haystack, $needle, $index = null) {
return(\OC_Helper::recursiveArraySearch($haystack, $needle, $index));
}
+
+ /**
+ * @brief calculates the maximum upload size respecting system settings, free space and user quota
+ *
+ * @param $dir the current folder where the user currently operates
+ * @return number of bytes representing
+ */
+ public static function maxUploadFilesize($dir) {
+ return \OC_Helper::maxUploadFilesize($dir);
+ }
}
diff --git a/lib/request.php b/lib/request.php
index 99a77e1b59e..f2f15c21103 100755
--- a/lib/request.php
+++ b/lib/request.php
@@ -19,7 +19,7 @@ class OC_Request {
return 'localhost';
}
if(OC_Config::getValue('overwritehost', '')<>'') {
- return OC_Config::getValue('overwritehost');
+ return OC_Config::getValue('overwritehost');
}
if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
if (strpos($_SERVER['HTTP_X_FORWARDED_HOST'], ",") !== false) {
@@ -44,7 +44,7 @@ class OC_Request {
*/
public static function serverProtocol() {
if(OC_Config::getValue('overwriteprotocol', '')<>'') {
- return OC_Config::getValue('overwriteprotocol');
+ return OC_Config::getValue('overwriteprotocol');
}
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$proto = strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']);
diff --git a/lib/router.php b/lib/router.php
index 8cb8fd4f33b..746b68c2c0c 100644
--- a/lib/router.php
+++ b/lib/router.php
@@ -49,6 +49,7 @@ class OC_Router {
$files = $this->getRoutingFiles();
$files[] = 'settings/routes.php';
$files[] = 'core/routes.php';
+ $files[] = 'ocs/routes.php';
$this->cache_key = OC_Cache::generateCacheKeyFromFiles($files);
}
return $this->cache_key;
@@ -67,6 +68,11 @@ class OC_Router {
$this->useCollection('root');
require_once 'settings/routes.php';
require_once 'core/routes.php';
+
+ // include ocs routes
+ require_once 'ocs/routes.php';
+ $collection = $this->getCollection('ocs');
+ $this->root->addCollection($collection, '/ocs');
}
protected function getCollection($name) {
diff --git a/lib/setup.php b/lib/setup.php
index fdd10be6824..4dd190b99fb 100644
--- a/lib/setup.php
+++ b/lib/setup.php
@@ -1,5 +1,23 @@
<?php
+class DatabaseSetupException extends Exception
+{
+ private $hint;
+
+ public function __construct($message, $hint, $code = 0, Exception $previous = null) {
+ $this->hint = $hint;
+ parent::__construct($message, $code, $previous);
+ }
+
+ public function __toString() {
+ return __CLASS__ . ": [{$this->code}]: {$this->message} ({$this->hint})\n";
+ }
+
+ public function getHint() {
+ return $this->hint;
+ }
+}
+
class OC_Setup {
public static function install($options) {
$error = array();
@@ -19,9 +37,9 @@ class OC_Setup {
if($dbtype=='mysql')
$dbprettyname = 'MySQL';
else if($dbtype=='pgsql')
- $dbprettyname = 'PostgreSQL';
+ $dbprettyname = 'PostgreSQL';
else
- $dbprettyname = 'Oracle';
+ $dbprettyname = 'Oracle';
if(empty($options['dbuser'])) {
@@ -69,10 +87,16 @@ class OC_Setup {
try {
self::setupMySQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $username);
+ } catch (DatabaseSetupException $e) {
+ $error[] = array(
+ 'error' => $e->getMessage(),
+ 'hint' => $e->getHint()
+ );
+ return($error);
} catch (Exception $e) {
$error[] = array(
- 'error' => 'MySQL username and/or password not valid',
- 'hint' => 'You need to enter either an existing account or the administrator.'
+ 'error' => $e->getMessage(),
+ 'hint' => ''
);
return($error);
}
@@ -141,7 +165,9 @@ class OC_Setup {
if(count($error) == 0) {
OC_Appconfig::setValue('core', 'installedat', microtime(true));
OC_Appconfig::setValue('core', 'lastupdatedat', microtime(true));
-
+ OC_AppConfig::setValue('core', 'remote_core.css', '/core/minimizer.php');
+ OC_AppConfig::setValue('core', 'remote_core.js', '/core/minimizer.php');
+
OC_Group::createGroup('admin');
OC_Group::addToGroup($username, 'admin');
OC_User::login($username, $password);
@@ -153,7 +179,7 @@ class OC_Setup {
if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) {
self::createHtaccess();
}
-
+
//and we are done
OC_Config::setValue('installed', true);
}
@@ -166,7 +192,7 @@ class OC_Setup {
//check if the database user has admin right
$connection = @mysql_connect($dbhost, $dbuser, $dbpass);
if(!$connection) {
- throw new Exception('MySQL username and/or password not valid');
+ throw new DatabaseSetupException('MySQL username and/or password not valid','You need to enter either an existing account or the administrator.');
}
$oldUser=OC_Config::getValue('dbuser', false);
@@ -229,8 +255,14 @@ class OC_Setup {
// the anonymous user would take precedence when there is one.
$query = "CREATE USER '$name'@'localhost' IDENTIFIED BY '$password'";
$result = mysql_query($query, $connection);
+ if (!$result) {
+ throw new DatabaseSetupException("MySQL user '" . "$name" . "'@'localhost' already exists","Delete this user from MySQL.");
+ }
$query = "CREATE USER '$name'@'%' IDENTIFIED BY '$password'";
$result = mysql_query($query, $connection);
+ if (!$result) {
+ throw new DatabaseSetupException("MySQL user '" . "$name" . "'@'%' already exists","Delete this user from MySQL.");
+ }
}
private static function setupPostgreSQLDatabase($dbhost, $dbuser, $dbpass, $dbname, $dbtableprefix, $username) {
diff --git a/lib/subadmin.php b/lib/subadmin.php
index 9e83e6da430..8cda7240ac9 100644
--- a/lib/subadmin.php
+++ b/lib/subadmin.php
@@ -122,6 +122,11 @@ class OC_SubAdmin{
* @return bool
*/
public static function isSubAdmin($uid) {
+ // Check if the user is already an admin
+ if(OC_Group::inGroup($uid, 'admin' )) {
+ return true;
+ }
+
$stmt = OC_DB::prepare('SELECT COUNT(*) AS `count` FROM `*PREFIX*group_admin` WHERE `uid` = ?');
$result = $stmt->execute(array($uid));
$result = $result->fetchRow();
@@ -141,7 +146,7 @@ class OC_SubAdmin{
if(!self::isSubAdmin($subadmin)) {
return false;
}
- if(OC_Group::inGroup($user, 'admin')) {
+ if(OC_User::isAdminUser($user)) {
return false;
}
$accessiblegroups = self::getSubAdminsGroups($subadmin);
diff --git a/lib/template.php b/lib/template.php
index 04667d73a2c..238d8a8ad0f 100644
--- a/lib/template.php
+++ b/lib/template.php
@@ -85,15 +85,25 @@ function human_file_size( $bytes ) {
}
function simple_file_size($bytes) {
- $mbytes = round($bytes/(1024*1024), 1);
- if($bytes == 0) { return '0'; }
- else if($mbytes < 0.1) { return '&lt; 0.1'; }
- else if($mbytes > 1000) { return '&gt; 1000'; }
- else { return number_format($mbytes, 1); }
+ if ($bytes < 0) {
+ return '?';
+ }
+ $mbytes = round($bytes / (1024 * 1024), 1);
+ if ($bytes == 0) {
+ return '0';
+ }
+ if ($mbytes < 0.1) {
+ return '&lt; 0.1';
+ }
+ if ($mbytes > 1000) {
+ return '&gt; 1000';
+ } else {
+ return number_format($mbytes, 1);
+ }
}
function relative_modified_date($timestamp) {
- $l=OC_L10N::get('lib');
+ $l=OC_L10N::get('lib');
$timediff = time() - $timestamp;
$diffminutes = round($timediff/60);
$diffhours = round($diffminutes/60);
@@ -176,9 +186,15 @@ class OC_Template{
$this->l10n = OC_L10N::get($parts[0]);
// Some headers to enhance security
- header('X-Frame-Options: Sameorigin');
- header('X-XSS-Protection: 1; mode=block');
- header('X-Content-Type-Options: nosniff');
+ header('X-Frame-Options: Sameorigin'); // Disallow iFraming from other domains
+ header('X-XSS-Protection: 1; mode=block'); // Enforce browser based XSS filters
+ header('X-Content-Type-Options: nosniff'); // Disable sniffing the content type for IE
+
+ // Content Security Policy
+ // If you change the standard policy, please also change it in config.sample.php
+ $policy = OC_Config::getValue('custom_csp_policy', 'default-src \'self\'; script-src \'self\' \'unsafe-eval\'; style-src \'self\' \'unsafe-inline\'; frame-src *; img-src *');
+ header('Content-Security-Policy:'.$policy); // Standard
+ header('X-WebKit-CSP:'.$policy); // Older webkit browsers
$this->findTemplate($name);
}
diff --git a/lib/templatelayout.php b/lib/templatelayout.php
index 4173e008ba7..83d36199986 100644
--- a/lib/templatelayout.php
+++ b/lib/templatelayout.php
@@ -28,23 +28,16 @@ class OC_TemplateLayout extends OC_Template {
break;
}
}
+ $apps_paths = array();
+ foreach(OC_App::getEnabledApps() as $app) {
+ $apps_paths[$app] = OC_App::getAppWebPath($app);
+ }
+ $this->assign( 'apps_paths', str_replace('\\/', '/', json_encode($apps_paths)), false ); // Ugly unescape slashes waiting for better solution
} else if ($renderas == 'guest') {
parent::__construct('core', 'layout.guest');
} else {
parent::__construct('core', 'layout.base');
}
-
- $apps_paths = array();
- foreach(OC_App::getEnabledApps() as $app) {
- $apps_paths[$app] = OC_App::getAppWebPath($app);
- }
- $this->assign( 'apps_paths', str_replace('\\/', '/', json_encode($apps_paths)), false ); // Ugly unescape slashes waiting for better solution
-
- if (OC_Config::getValue('installed', false) && !OC_AppConfig::getValue('core', 'remote_core.css', false)) {
- OC_AppConfig::setValue('core', 'remote_core.css', '/core/minimizer.php');
- OC_AppConfig::setValue('core', 'remote_core.js', '/core/minimizer.php');
- }
-
// Add the js files
$jsfiles = self::findJavascriptFiles(OC_Util::$scripts);
$this->assign('jsfiles', array(), false);
diff --git a/lib/user.php b/lib/user.php
index 80f88ca7052..fd0ed6ecd3a 100644
--- a/lib/user.php
+++ b/lib/user.php
@@ -260,17 +260,13 @@ class OC_User {
/**
* @brief Sets user id for session and triggers emit
- * @returns true
- *
*/
public static function setUserId($uid) {
$_SESSION['user_id'] = $uid;
- return true;
}
/**
* @brief Logs the current user out and kills all the session data
- * @returns true
*
* Logout, destroys session
*/
@@ -279,7 +275,6 @@ class OC_User {
session_unset();
session_destroy();
OC_User::unsetMagicInCookie();
- return true;
}
/**
@@ -300,6 +295,19 @@ class OC_User {
}
/**
+ * @brief Check if the user is an admin user
+ * @param $uid uid of the admin
+ * @returns bool
+ */
+ public static function isAdminUser($uid) {
+ if(OC_Group::inGroup($uid, 'admin' )) {
+ return true;
+ }
+ return false;
+ }
+
+
+ /**
* @brief get the user id of the user currently logged in.
* @return string uid or false
*/
diff --git a/lib/util.php b/lib/util.php
index 4170de2125a..374baa43dbe 100755
--- a/lib/util.php
+++ b/lib/util.php
@@ -111,7 +111,7 @@ class OC_Util {
* @return string
*/
public static function getEditionString() {
- return '';
+ return '';
}
/**
@@ -311,14 +311,14 @@ class OC_Util {
if (isset($_REQUEST['redirect_url'])) {
$redirect_url = OC_Util::sanitizeHTML($_REQUEST['redirect_url']);
$parameters['redirect_url'] = urlencode($redirect_url);
- }
+ }
OC_Template::printGuestPage("", "login", $parameters);
}
/**
- * Check if the app is enabled, redirects to home if not
- */
+ * Check if the app is enabled, redirects to home if not
+ */
public static function checkAppEnabled($app) {
if( !OC_App::isEnabled($app)) {
header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
@@ -327,9 +327,9 @@ class OC_Util {
}
/**
- * Check if the user is logged in, redirects to home if not. With
- * redirect URL parameter to the request URI.
- */
+ * Check if the user is logged in, redirects to home if not. With
+ * redirect URL parameter to the request URI.
+ */
public static function checkLoggedIn() {
// Check if we are a user
if( !OC_User::isLoggedIn()) {
@@ -339,29 +339,20 @@ class OC_Util {
}
/**
- * Check if the user is a admin, redirects to home if not
- */
+ * Check if the user is a admin, redirects to home if not
+ */
public static function checkAdminUser() {
- // Check if we are a user
- self::checkLoggedIn();
- self::verifyUser();
- if( !OC_Group::inGroup( OC_User::getUser(), 'admin' )) {
+ if( !OC_User::isAdminUser(OC_User::getUser())) {
header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
exit();
}
}
/**
- * Check if the user is a subadmin, redirects to home if not
- * @return array $groups where the current user is subadmin
- */
+ * Check if the user is a subadmin, redirects to home if not
+ * @return array $groups where the current user is subadmin
+ */
public static function checkSubAdminUser() {
- // Check if we are a user
- self::checkLoggedIn();
- self::verifyUser();
- if(OC_Group::inGroup(OC_User::getUser(), 'admin')) {
- return true;
- }
if(!OC_SubAdmin::isSubAdmin(OC_User::getUser())) {
header( 'Location: '.OC_Helper::linkToAbsolute( '', 'index.php' ));
exit();
@@ -370,42 +361,8 @@ class OC_Util {
}
/**
- * Check if the user verified the login with his password in the last 15 minutes
- * If not, the user will be shown a password verification page
- */
- public static function verifyUser() {
- if(OC_Config::getValue('enhancedauth', false) === true) {
- // Check password to set session
- if(isset($_POST['password'])) {
- if (OC_User::login(OC_User::getUser(), $_POST["password"] ) === true) {
- $_SESSION['verifiedLogin']=time() + OC_Config::getValue('enhancedauthtime', 15 * 60);
- }
- }
-
- // Check if the user verified his password
- if(!isset($_SESSION['verifiedLogin']) OR $_SESSION['verifiedLogin'] < time()) {
- OC_Template::printGuestPage("", "verify", array('username' => OC_User::getUser()));
- exit();
- }
- }
- }
-
- /**
- * Check if the user verified the login with his password
- * @return bool
- */
- public static function isUserVerified() {
- if(OC_Config::getValue('enhancedauth', false) === true) {
- if(!isset($_SESSION['verifiedLogin']) OR $_SESSION['verifiedLogin'] < time()) {
- return false;
- }
- }
- return true;
- }
-
- /**
- * Redirect to the user default page
- */
+ * Redirect to the user default page
+ */
public static function redirectToDefaultPage() {
if(isset($_REQUEST['redirect_url'])) {
$location = OC_Helper::makeURLAbsolute(urldecode($_REQUEST['redirect_url']));
@@ -510,8 +467,11 @@ class OC_Util {
* @return array with sanitized strings or a single sanitized string, depends on the input parameter.
*/
public static function sanitizeHTML( &$value ) {
- if (is_array($value) || is_object($value)) array_walk_recursive($value, 'OC_Util::sanitizeHTML');
- else $value = htmlentities($value, ENT_QUOTES, 'UTF-8'); //Specify encoding for PHP<5.4
+ if (is_array($value) || is_object($value)) {
+ array_walk_recursive($value, 'OC_Util::sanitizeHTML');
+ } else {
+ $value = htmlentities($value, ENT_QUOTES, 'UTF-8'); //Specify encoding for PHP<5.4
+ }
return $value;
}
@@ -553,9 +513,9 @@ class OC_Util {
}
- /**
- * Check if the setlocal call doesn't work. This can happen if the right local packages are not available on the server.
- */
+ /**
+ * Check if the setlocal call doesn't work. This can happen if the right local packages are not available on the server.
+ */
public static function issetlocaleworking() {
$result=setlocale(LC_ALL, 'en_US.UTF-8');
if($result==false) {
@@ -565,20 +525,20 @@ class OC_Util {
}
}
- /**
- * Check if the ownCloud server can connect to the internet
- */
+ /**
+ * Check if the ownCloud server can connect to the internet
+ */
public static function isinternetconnectionworking() {
// try to connect to owncloud.org to see if http connections to the internet are possible.
- $connected = @fsockopen("www.owncloud.org", 80);
+ $connected = @fsockopen("www.owncloud.org", 80);
if ($connected) {
fclose($connected);
return true;
}else{
// second try in case one server is down
- $connected = @fsockopen("apps.owncloud.com", 80);
+ $connected = @fsockopen("apps.owncloud.com", 80);
if ($connected) {
fclose($connected);
return true;
@@ -601,11 +561,11 @@ class OC_Util {
/**
- * @brief Generates a cryptographical secure pseudorandom string
- * @param Int with the length of the random string
- * @return String
- * Please also update secureRNG_available if you change something here
- */
+ * @brief Generates a cryptographical secure pseudorandom string
+ * @param Int with the length of the random string
+ * @return String
+ * Please also update secureRNG_available if you change something here
+ */
public static function generate_random_bytes($length = 30) {
// Try to use openssl_random_pseudo_bytes
@@ -637,9 +597,9 @@ class OC_Util {
}
/**
- * @brief Checks if a secure random number generator is available
- * @return bool
- */
+ * @brief Checks if a secure random number generator is available
+ * @return bool
+ */
public static function secureRNG_available() {
// Check openssl_random_pseudo_bytes
@@ -658,48 +618,61 @@ class OC_Util {
return false;
}
-
- /**
- * @Brief Get file content via curl.
- * @param string $url Url to get content
- * @return string of the response or false on error
- * This function get the content of a page via curl, if curl is enabled.
- * If not, file_get_element is used.
- */
-
- public static function getUrlContent($url){
-
- if (function_exists('curl_init')) {
-
- $curl = curl_init();
-
- curl_setopt($curl, CURLOPT_HEADER, 0);
- curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
- curl_setopt($curl, CURLOPT_URL, $url);
- curl_setopt($curl, CURLOPT_USERAGENT, "ownCloud Server Crawler");
- if(OC_Config::getValue('proxy','')<>'') {
- curl_setopt($curl, CURLOPT_PROXY, OC_Config::getValue('proxy'));
- }
- if(OC_Config::getValue('proxyuserpwd','')<>'') {
- curl_setopt($curl, CURLOPT_PROXYUSERPWD, OC_Config::getValue('proxyuserpwd'));
- }
- $data = curl_exec($curl);
- curl_close($curl);
-
- } else {
-
- $ctx = stream_context_create(
- array(
- 'http' => array(
- 'timeout' => 10
- )
- )
- );
- $data=@file_get_contents($url, 0, $ctx);
-
- }
- return $data;
+
+ /**
+ * @Brief Get file content via curl.
+ * @param string $url Url to get content
+ * @return string of the response or false on error
+ * This function get the content of a page via curl, if curl is enabled.
+ * If not, file_get_element is used.
+ */
+
+ public static function getUrlContent($url){
+
+ if (function_exists('curl_init')) {
+
+ $curl = curl_init();
+
+ curl_setopt($curl, CURLOPT_HEADER, 0);
+ curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
+ curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
+ curl_setopt($curl, CURLOPT_URL, $url);
+ curl_setopt($curl, CURLOPT_USERAGENT, "ownCloud Server Crawler");
+ if(OC_Config::getValue('proxy','')<>'') {
+ curl_setopt($curl, CURLOPT_PROXY, OC_Config::getValue('proxy'));
+ }
+ if(OC_Config::getValue('proxyuserpwd','')<>'') {
+ curl_setopt($curl, CURLOPT_PROXYUSERPWD, OC_Config::getValue('proxyuserpwd'));
+ }
+ $data = curl_exec($curl);
+ curl_close($curl);
+
+ } else {
+ $contextArray = null;
+
+ if(OC_Config::getValue('proxy','')<>'') {
+ $contextArray = array(
+ 'http' => array(
+ 'timeout' => 10,
+ 'proxy' => OC_Config::getValue('proxy')
+ )
+ );
+ } else {
+ $contextArray = array(
+ 'http' => array(
+ 'timeout' => 10
+ )
+ );
+ }
+
+
+ $ctx = stream_context_create(
+ $contextArray
+ );
+ $data=@file_get_contents($url, 0, $ctx);
+
+ }
+ return $data;
}
-
+
}
diff --git a/lib/vcategories.php b/lib/vcategories.php
index 406a4eb1074..1700870f91f 100644
--- a/lib/vcategories.php
+++ b/lib/vcategories.php
@@ -763,4 +763,3 @@ class OC_VCategories {
return array_search(strtolower($needle), array_map('strtolower', $haystack));
}
}
-