/** * @param string[] $groups */ private static function handleKnownGroups($groups) { \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG); $query = \OCP\DB::prepare(' UPDATE `*PREFIX*ldap_group_members` SET `owncloudusers` = ? WHERE `owncloudname` = ? '); foreach ($groups as $group) { //we assume, that self::$groupsFromDB has been retrieved already $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']); $actualUsers = self::getGroupBE()->usersInGroup($group); $hasChanged = false; foreach (array_diff($knownUsers, $actualUsers) as $removedUser) { \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group)); \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – "' . $removedUser . '" removed from "' . $group . '".', \OCP\Util::INFO); $hasChanged = true; } foreach (array_diff($actualUsers, $knownUsers) as $addedUser) { \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group)); \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – "' . $addedUser . '" added to "' . $group . '".', \OCP\Util::INFO); $hasChanged = true; } if ($hasChanged) { $query->execute(array(serialize($actualUsers), $group)); } } \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – FINISHED dealing with known Groups.', \OCP\Util::DEBUG); }
/** * create a new share * * @param array $params * @return \OC_OCS_Result */ public function createShare($params) { if (!$this->isS2SEnabled(true)) { return new \OC_OCS_Result(null, 503, 'Server does not support federated cloud sharing'); } $remote = isset($_POST['remote']) ? $_POST['remote'] : null; $token = isset($_POST['token']) ? $_POST['token'] : null; $name = isset($_POST['name']) ? $_POST['name'] : null; $owner = isset($_POST['owner']) ? $_POST['owner'] : null; $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null; $remoteId = isset($_POST['remoteId']) ? (int) $_POST['remoteId'] : null; if ($remote && $token && $name && $owner && $remoteId && $shareWith) { if (!\OCP\Util::isValidFileName($name)) { return new \OC_OCS_Result(null, 400, 'The mountpoint name contains invalid characters.'); } // FIXME this should be a method in the user management instead \OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG); \OCP\Util::emitHook('\\OCA\\Files_Sharing\\API\\Server2Server', 'preLoginNameUsedAsUserName', array('uid' => &$shareWith)); \OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG); if (!\OCP\User::userExists($shareWith)) { return new \OC_OCS_Result(null, 400, 'User does not exists'); } \OC_Util::setupFS($shareWith); $externalManager = new \OCA\Files_Sharing\External\Manager(\OC::$server->getDatabaseConnection(), \OC\Files\Filesystem::getMountManager(), \OC\Files\Filesystem::getLoader(), \OC::$server->getHTTPHelper(), \OC::$server->getNotificationManager(), $shareWith); try { $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId); $user = $owner . '@' . $this->cleanupRemote($remote); \OC::$server->getActivityManager()->publishActivity(Activity::FILES_SHARING_APP, Activity::SUBJECT_REMOTE_SHARE_RECEIVED, array($user, trim($name, '/')), '', array(), '', '', $shareWith, Activity::TYPE_REMOTE_SHARE, Activity::PRIORITY_LOW); /** * FIXME $urlGenerator = \OC::$server->getURLGenerator(); $notificationManager = \OC::$server->getNotificationManager(); $notification = $notificationManager->createNotification(); $notification->setApp('files_sharing') ->setUser($shareWith) ->setTimestamp(time()) ->setObject('remote_share', $remoteId) ->setSubject('remote_share', [$user, trim($name, '/')]); $declineAction = $notification->createAction(); $declineAction->setLabel('decline') ->setLink($urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/remote_shares/' . $remoteId), 'DELETE'); $notification->addAction($declineAction); $acceptAction = $notification->createAction(); $acceptAction->setLabel('accept') ->setLink($urlGenerator->getAbsoluteURL('/ocs/v1.php/apps/files_sharing/api/v1/remote_shares/' . $remoteId), 'POST'); $notification->addAction($acceptAction); $notificationManager->notify($notification); */ return new \OC_OCS_Result(); } catch (\Exception $e) { \OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR); return new \OC_OCS_Result(null, 500, 'internal server error, was not able to add share from ' . $remote); } } return new \OC_OCS_Result(null, 400, 'server can not add remote share, missing parameter'); }
/** * Creates new objects from import * * @param \OCA\Calendar\IObjectCollection $collection * @throws \OCA\Calendar\BusinessLayer\Exception * @return \OCA\Calendar\IObjectCollection */ public function createCollection(IObjectCollection $collection) { $className = get_class($collection); /** @var IObjectCollection $createdObjects */ $createdObjects = new $className(); $this->checkCalendarSupports(Permissions::CREATE); if (!$this->api instanceof BackendUtils\IObjectAPICreate) { throw new Exception('Backend does not support creating objects'); } foreach ($collection as $object) { try { if ($object->getUri() === null) { $randomURI = ObjectUtility::randomURI(); $object->setUri($randomURI); } $object->setCalendar($this->calendar); $object->getEtag(true); $this->checkObjectIsValid($object); Util::emitHook('\\OCA\\Calendar', 'preCreateObject', array($object)); $object = $this->api->create($object); Util::emitHook('\\OCA\\Calendar', 'postCreateObject', array($object)); $createdObjects[] = $object; } catch (BackendUtils\Exception $ex) { $this->logger->debug($ex->getMessage()); } catch (Exception $ex) { $this->logger->debug($ex->getMessage()); } catch (CorruptDataException $ex) { $this->logger->debug($ex->getMessage()); } } if ($this->isCachingEnabled) { $this->calendar->checkUpdate(); } return $createdObjects; }
/** * create a new share * * @param array $params * @return \OC_OCS_Result */ public function createShare($params) { if (!$this->isS2SEnabled(true)) { return new \OC_OCS_Result(null, 503, 'Server does not support federated cloud sharing'); } $remote = isset($_POST['remote']) ? $_POST['remote'] : null; $token = isset($_POST['token']) ? $_POST['token'] : null; $name = isset($_POST['name']) ? $_POST['name'] : null; $owner = isset($_POST['owner']) ? $_POST['owner'] : null; $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null; $remoteId = isset($_POST['remoteId']) ? (int) $_POST['remoteId'] : null; if ($remote && $token && $name && $owner && $remoteId && $shareWith) { if (!\OCP\Util::isValidFileName($name)) { return new \OC_OCS_Result(null, 400, 'The mountpoint name contains invalid characters.'); } \OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG); \OCP\Util::emitHook('\\OCA\\Files_Sharing\\API\\Server2Server', 'preLoginNameUsedAsUserName', array('uid' => &$shareWith)); \OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG); if (!\OCP\User::userExists($shareWith)) { return new \OC_OCS_Result(null, 400, 'User does not exists'); } \OC_Util::setupFS($shareWith); $externalManager = new \OCA\Files_Sharing\External\Manager(\OC::$server->getDatabaseConnection(), \OC\Files\Filesystem::getMountManager(), \OC\Files\Filesystem::getLoader(), \OC::$server->getHTTPHelper(), $shareWith); try { $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId); $user = $owner . '@' . $this->cleanupRemote($remote); \OC::$server->getActivityManager()->publishActivity(Activity::FILES_SHARING_APP, Activity::SUBJECT_REMOTE_SHARE_RECEIVED, array($user, trim($name, '/')), '', array(), '', '', $shareWith, Activity::TYPE_REMOTE_SHARE, Activity::PRIORITY_LOW); return new \OC_OCS_Result(); } catch (\Exception $e) { \OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR); return new \OC_OCS_Result(null, 500, 'internal server error, was not able to add share from ' . $remote); } } return new \OC_OCS_Result(null, 400, 'server can not add remote share, missing parameter'); }
/** * @brief Send an event into the activity stream * @param string $app The app where this event is associated with * @param string $subject A short description of the event * @param string $message A longer description of the event * @param string $file The file including path where this event is associated with. (optional) * @param string $link A link where this event is associated with (optional) * @return boolean */ public static function send($app, $subject, $subjectparams = array(), $message = '', $messageparams = array(), $file = '', $link = '', $affecteduser = '', $type = 0, $prio = Data::PRIORITY_MEDIUM) { $timestamp = time(); $user = \OCP\User::getUser(); if ($affecteduser === '') { $auser = \OCP\User::getUser(); } else { $auser = $affecteduser; } // store in DB $query = \OCP\DB::prepare('INSERT INTO `*PREFIX*activity`(`app`, `subject`, `subjectparams`, `message`, `messageparams`, `file`, `link`, `user`, `affecteduser`, `timestamp`, `priority`, `type`)' . ' VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )'); $query->execute(array($app, $subject, serialize($subjectparams), $message, serialize($messageparams), $file, $link, $user, $auser, $timestamp, $prio, $type)); // call the expire function only every 1000x time to preserve performance. if (rand(0, 1000) == 0) { Data::expire(); } // fire a hook so that other apps like notification systems can connect // todo translations \OCP\Util::emitHook('OC_Activity', 'post_event', array('app' => $app, 'subject' => $subject, 'user' => $user, 'affecteduser' => $affecteduser, 'message' => $message, 'file' => $file, 'link' => $link, 'prio' => $prio, 'type' => $type)); return true; }
/** * check if two federated cloud IDs refer to the same user * * @param string $user1 * @param string $server1 * @param string $user2 * @param string $server2 * @return bool true if both users and servers are the same */ public function compareAddresses($user1, $server1, $user2, $server2) { $normalizedServer1 = strtolower($this->removeProtocolFromUrl($server1)); $normalizedServer2 = strtolower($this->removeProtocolFromUrl($server2)); if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) { // FIXME this should be a method in the user management instead \OCP\Util::emitHook('\\OCA\\Files_Sharing\\API\\Server2Server', 'preLoginNameUsedAsUserName', array('uid' => &$user1)); \OCP\Util::emitHook('\\OCA\\Files_Sharing\\API\\Server2Server', 'preLoginNameUsedAsUserName', array('uid' => &$user2)); if ($user1 === $user2) { return true; } } return false; }
/** * @deprecated implement the emitter interface instead * Emits a signal. To get data from the slot use references! * @param string $signalClass class name of emitter * @param string $signalName name of signal * @param array $params default: array() array with additional data * @return bool true if slots exists or false if not */ public function emitHook($signalClass, $signalName, $params = array()) { return \OCP\Util::emitHook($signalClass, $signalName, $params); }
/** * @brief analyses the parameter for calendar parameter and returns the objects * @param (string) $calendarid - calendarid * @param (int) $start - unixtimestamp of start * @param (int) $end - unixtimestamp of end * @return (array) $events */ public static function getrequestedEvents($calendarid, $start, $end) { $events = array(); if ($calendarid === 'shared_events') { $checkStart = $start->format('U'); $singleevents = \OCP\Share::getItemsSharedWith(self::SHAREEVENT, ShareEvent::FORMAT_EVENT); foreach ($singleevents as $singleevent) { $startCheck_dt = new \DateTime($singleevent['startdate'], new \DateTimeZone('UTC')); $checkStartSE = $startCheck_dt->format('U'); // \OCP\Util::writeLog('calendar','STARTDATE'.$checkStart.' -> '.$checkStartSE, \OCP\Util::DEBUG); if ($checkStartSE > $checkStart) { $singleevent['summary'] .= ' (' . (string) self::$l10n->t('by') . ' ' . Object::getowner($singleevent['id']) . ')'; $events[] = $singleevent; } } } else { if (is_numeric($calendarid)) { $calendar = self::getCalendar($calendarid); \OCP\Response::enableCaching(0); \OCP\Response::setETagHeader($calendar['ctag']); $events = Object::allInPeriod($calendarid, $start, $end, $calendar['userid'] !== \OCP\User::getUser()); } else { \OCP\Util::emitHook('OCA\\CalendarPlus', 'getEvents', array('calendar_id' => $calendarid, 'events' => &$events)); } } return $events; }
\OC::$session->close(); $dispatcher = new Dispatcher($params); $dispatcher->dispatch('GroupController', 'deleteGroup'); }); $this->create('contacts_categories_rename', 'groups/rename')->post()->action(function ($params) { \OC::$session->close(); $dispatcher = new Dispatcher($params); $dispatcher->dispatch('GroupController', 'renameGroup'); }); $this->create('contacts_categories_addto', 'groups/addto/{categoryId}')->post()->action(function ($params) { \OC::$session->close(); $dispatcher = new Dispatcher($params); $dispatcher->dispatch('GroupController', 'addToGroup'); }); $this->create('contacts_categories_removefrom', 'groups/removefrom/{categoryId}')->post()->action(function ($params) { \OC::$session->close(); $dispatcher = new Dispatcher($params); $dispatcher->dispatch('GroupController', 'removeFromGroup'); })->requirements(array('categoryId')); $this->create('contacts_setpreference', 'preference/set')->post()->action(function ($params) { \OC::$session->close(); $dispatcher = new Dispatcher($params); $dispatcher->dispatch('SettingsController', 'set'); }); $this->create('contacts_index_properties', 'indexproperties/{user}/')->post()->action(function ($params) { \OC::$session->close(); // TODO: Add BackgroundJob for this. \OCP\Util::emitHook('OCA\\Contacts', 'indexProperties', array()); \OCP\Config::setUserValue($params['user'], 'contacts', 'contacts_properties_indexed', 'yes'); \OCP\JSON::success(array('isIndexed' => true)); })->requirements(array('user'))->defaults(array('user' => \OCP\User::getUser()));
public function fopen($path, $mode) { if ($source = $this->getSourcePath($path)) { switch ($mode) { case 'r+': case 'rb+': case 'w+': case 'wb+': case 'x+': case 'xb+': case 'a+': case 'ab+': case 'w': case 'wb': case 'x': case 'xb': case 'a': case 'ab': $exists = $this->file_exists($path); if ($exists && !$this->isUpdatable($path)) { return false; } if (!$exists && !$this->isCreatable(dirname($path))) { return false; } } $info = array('target' => $this->getMountPoint() . $path, 'source' => $source, 'mode' => $mode); \OCP\Util::emitHook('\\OC\\Files\\Storage\\Shared', 'fopen', $info); list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath($source); return $storage->fopen($internalPath, $mode); } return false; }
/** * @param string $password * @throws \Exception */ private static function verifyPassword($password) { $accepted = true; $message = ''; \OCP\Util::emitHook('\\OC\\Share', 'verifyPassword', ['password' => $password, 'accepted' => &$accepted, 'message' => &$message]); if (!$accepted) { throw new \Exception($message); } }
/** * Deletes a contact * * @param string $addressBookId * @param string|array $id * @param array $options - Optional (backend specific options) * @see getContact * @return bool */ public function deleteContact($addressBookId, $id, array $options = array()) { // TODO: pass the uri in $options instead. $noCollection = isset($options['noCollection']) ? $options['noCollection'] : false; $isBatch = isset($options['isBatch']) ? $options['isBatch'] : false; if (is_array($id)) { if (isset($id['id'])) { $id = $id['id']; } elseif (isset($id['uri'])) { $id = $this->getIdFromUri($id['uri']); if (is_null($id)) { \OCP\Util::writeLog('contacts', __METHOD__ . ' Couldn\'t find contact', \OCP\Util::ERROR); return false; } } else { throw new \Exception(__METHOD__ . ' If second argument is an array, either \'id\' or \'uri\' has to be set.'); } } if (!$isBatch) { \OCP\Util::emitHook('OCA\\Contacts', 'pre_deleteContact', array('id' => $id)); } if ($noCollection) { $me = $this->getContact(null, $id, $options); $addressBookId = $me['parent']; } try { $result = $this->getPreparedQuery('deletecontact')->execute(array($id, $addressBookId)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('contacts', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return false; } } catch (\Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); \OCP\Util::writeLog('contacts', __METHOD__ . ', id: ' . $id, \OCP\Util::DEBUG); return false; } $this->setModifiedAddressBook($addressBookId); return true; }
/** * restore files from trash bin * * @param string $file path to the deleted file * @param string $filename name of the file * @param int $timestamp time when the file was deleted * * @return bool */ public static function restore($file, $filename, $timestamp) { $user = \OCP\User::getUser(); $view = new \OC\Files\View('/' . $user); $location = ''; if ($timestamp) { $query = \OC_DB::prepare('SELECT `location` FROM `*PREFIX*files_trash`' . ' WHERE `user`=? AND `id`=? AND `timestamp`=?'); $result = $query->execute(array($user, $filename, $timestamp))->fetchAll(); if (count($result) !== 1) { \OC_Log::write('files_trashbin', 'trash bin database inconsistent!', \OC_Log::ERROR); } else { $location = $result[0]['location']; // if location no longer exists, restore file in the root directory if ($location !== '/' && (!$view->is_dir('files' . $location) || !$view->isUpdatable('files' . $location))) { $location = ''; } } } // we need a extension in case a file/dir with the same name already exists $uniqueFilename = self::getUniqueFilename($location, $filename, $view); $source = \OC\Files\Filesystem::normalizePath('files_trashbin/files/' . $file); $target = \OC\Files\Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename); $mtime = $view->filemtime($source); // disable proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; // restore file $restoreResult = $view->rename($source, $target); // handle the restore result if ($restoreResult) { $fakeRoot = $view->getRoot(); $view->chroot('/' . $user . '/files'); $view->touch('/' . $location . '/' . $uniqueFilename, $mtime); $view->chroot($fakeRoot); \OCP\Util::emitHook('\\OCA\\Files_Trashbin\\Trashbin', 'post_restore', array('filePath' => \OC\Files\Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename), 'trashPath' => \OC\Files\Filesystem::normalizePath($file))); self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp); self::restoreEncryptionKeys($view, $file, $filename, $uniqueFilename, $location, $timestamp); if ($timestamp) { $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); $query->execute(array($user, $filename, $timestamp)); } // enable proxy \OC_FileProxy::$enabled = $proxyStatus; return true; } // enable proxy \OC_FileProxy::$enabled = $proxyStatus; return false; }
/** * @brief Send an event into the activity stream * * @param string $app The app where this event is associated with * @param string $subject A short description of the event * @param array $subjectParams Array of parameters that are filled in the placeholders * @param string $affectedUser Name of the user we are sending the activity to * @param string $type Type of notification * @param int $latestSendTime Activity time() + batch setting of $affectedUser * @return bool */ public static function storeMail($app, $subject, array $subjectParams, $affectedUser, $type, $latestSendTime) { $timestamp = time(); // store in DB $query = DB::prepare('INSERT INTO `*PREFIX*activity_mq` ' . ' (`amq_appid`, `amq_subject`, `amq_subjectparams`, `amq_affecteduser`, `amq_timestamp`, `amq_type`, `amq_latest_send`) ' . ' VALUES(?, ?, ?, ?, ?, ?, ?)'); $query->execute(array($app, $subject, json_encode($subjectParams), $affectedUser, $timestamp, $type, $latestSendTime)); // fire a hook so that other apps like notification systems can connect Util::emitHook('OC_Activity', 'post_email', array('app' => $app, 'subject' => $subject, 'subjectparams' => $subjectParams, 'affecteduser' => $affectedUser, 'timestamp' => $timestamp, 'type' => $type, 'latest_send' => $latestSendTime)); return true; }
/** * @brief Returns the list of calendars for a specific user. * @param string $uid User ID * @param boolean $active Only return calendars with this $active state, default(=false) is don't care * @param boolean $bSubscribe return calendars with this $issubscribe state, default(=true) is don't care * @return array */ public function all($active = false, $bSubscribe = true) { $calendarDB = new CalendarDAO($this->db, $this->userId); $calendars = $calendarDB->all($active, $bSubscribe); $calendars = array_merge($calendars, $this->shareConnector->getItemsSharedWithCalendar()); \OCP\Util::emitHook('OCA\\CalendarPlus', 'getCalendars', array('calendar' => &$calendars)); return $calendars; }
public function file_put_contents($path, $data) { $info = ['target' => $this->getMountPoint() . '/' . $path, 'source' => $this->getSourcePath($path)]; \OCP\Util::emitHook('\\OC\\Files\\Storage\\Shared', 'file_put_contents', $info); return parent::file_put_contents($path, $data); }
/** * @brief removes a calendar * @param integer $id * @return boolean */ public static function deleteCalendar($id) { $calendar = self::find($id); //\OCP\Util::writeLog('DAV', 'DEL ID-> '.$id, \OCP\Util::DEBUG); $group = \OC::$server->getGroupManager()->get('admin'); $user = \OCP\User::getUser(); if ($calendar['userid'] != $user && !$group->inGroup($user)) { $sharedCalendar = \OCP\Share::getItemSharedWithBySource(App::SHARECALENDAR, App::SHARECALENDARPREFIX . $id); if (!$sharedCalendar || !($sharedCalendar['permissions'] & \OCP\PERMISSION_DELETE)) { throw new \Exception(App::$l10n->t('You do not have the permissions to delete this calendar.')); } } $stmt = \OCP\DB::prepare('DELETE FROM `' . App::CldCalendarTable . '` WHERE `id` = ?'); $stmt->execute(array($id)); $stmt = \OCP\DB::prepare('DELETE FROM `' . App::CldObjectTable . '` WHERE `calendarid` = ?'); $stmt->execute(array($id)); \OCP\Share::unshareAll(App::SHARECALENDAR, App::SHARECALENDARPREFIX . $id); \OCP\Util::emitHook('\\OCA\\CalendarPlus', 'deleteCalendar', $id); $calendars = self::allCalendars(\OCP\USER::getUser(), false, false); if (\OCP\USER::isLoggedIn() && count($calendars) === 0 || count($calendars) == 1 && $calendars[0]['id'] == 'birthday_' . \OCP\USER::getUser()) { self::addDefaultCalendars(\OCP\USER::getUser()); } $link = \OC::$server->getURLGenerator()->linkToRoute(App::$appname . '.page.index'); $params = array('mode' => 'deleted', 'link' => $link, 'trans_type' => '', 'summary' => $calendar['displayname'], 'cal_user' => $user, 'cal_displayname' => $calendar['displayname']); ActivityData::logEventActivity($params, false, true); return true; }
/** * @brief Edits a calendar * @param integer $id * @param string $name Default: null * @param string $components Default: null * @param string $timezone Default: null * @param integer $order Default: null * @param string $color Default: null, format: '#RRGGBB(AA)' * @return boolean * * Values not null will be set */ public static function editCalendar($id, $name = null, $components = null, $timezone = null, $order = null, $color = null, $transparent = null) { // Need these ones for checking uri $calendar = self::find($id); $userid = \OCP\User::getUser(); if ($calendar['userid'] !== $userid) { $sharedCalendar = \OCP\Share::getItemSharedWithBySource(App::SHARECALENDAR, App::SHARECALENDARPREFIX . $id); if (!$sharedCalendar || !($sharedCalendar['permissions'] & \OCP\PERMISSION_UPDATE)) { throw new \Exception(App::$l10n->t('You do not have the permissions to update this calendar.')); } } // Keep old stuff if (is_null($name)) { $name = $calendar['displayname']; } if (is_null($components)) { $components = $calendar['components']; } if (is_null($timezone)) { $timezone = $calendar['timezone']; } if (is_null($order)) { $order = $calendar['calendarorder']; } if (is_null($color)) { $color = $calendar['calendarcolor']; } if (is_null($transparent)) { $transparent = $calendar['transparent']; } $dbObject = \OC::$server->getDb(); $calendarDB = new CalendarDAO($dbObject, $userid); $bUpdateCalendar = $calendarDB->update($name, $order, $color, $timezone, $components, $transparent, $id); if ($bUpdateCalendar === true) { \OCP\Util::emitHook('\\OCA\\CalendarPlus', 'editCalendar', $id); $link = \OC::$server->getURLGenerator()->linkToRoute(App::$appname . '.page.index'); $params = array('mode' => 'edited', 'link' => $link, 'trans_type' => '', 'summary' => $calendar['displayname'], 'cal_user' => $calendar['userid'], 'cal_displayname' => $calendar['displayname']); ActivityData::logEventActivity($params, false, true); return true; } else { return null; } }
/** * Validate if the expiration date fits the system settings * * @param \OCP\Share\IShare $share The share to validate the expiration date of * @return \OCP\Share\IShare The expiration date or null if $expireDate was null and it is not required * @throws GenericShareException * @throws \InvalidArgumentException * @throws \Exception */ protected function validateExpirationDate(\OCP\Share\IShare $share) { $expirationDate = $share->getExpirationDate(); if ($expirationDate !== null) { //Make sure the expiration date is a date $expirationDate->setTime(0, 0, 0); $date = new \DateTime(); $date->setTime(0, 0, 0); if ($date >= $expirationDate) { $message = $this->l->t('Expiration date is in the past'); throw new GenericShareException($message, $message, 404); } } // If we enforce the expiration date check that is does not exceed if ($this->shareApiLinkDefaultExpireDateEnforced()) { if ($expirationDate === null) { throw new \InvalidArgumentException('Expiration date is enforced'); } $date = new \DateTime(); $date->setTime(0, 0, 0); $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D')); if ($date < $expirationDate) { $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]); throw new GenericShareException($message, $message, 404); } } // If expiredate is empty set a default one if there is a default if ($expirationDate === null && $this->shareApiLinkDefaultExpireDate()) { $expirationDate = new \DateTime(); $expirationDate->setTime(0, 0, 0); $expirationDate->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D')); } $accepted = true; $message = ''; \OCP\Util::emitHook('\\OC\\Share', 'verifyExpirationDate', ['expirationDate' => &$expirationDate, 'accepted' => &$accepted, 'message' => &$message, 'passwordSet' => $share->getPassword() === null]); if (!$accepted) { throw new \Exception($message); } $share->setExpirationDate($expirationDate); return $expirationDate; }
public static function moveToCalendar($id, $calendarid) { $calendar = Calendar::find($calendarid); if ($calendar['userid'] != \OCP\User::getUser()) { $sharedCalendar = \OCP\Share::getItemSharedWithBySource(App::SHARECALENDAR, App::SHARECALENDARPREFIX . $calendarid); if (!$sharedCalendar || !($sharedCalendar['permissions'] & \OCP\PERMISSION_DELETE)) { throw new \Exception(App::$l10n->t('You do not have the permissions to add events to this calendar.')); } } $stmt = \OCP\DB::prepare('UPDATE `' . App::CldObjectTable . '` SET `calendarid`=? WHERE `id`=?'); $stmt->execute(array($calendarid, $id)); Calendar::touchCalendar($calendarid); \OCP\Util::emitHook('\\OCA\\CalendarPlus', 'moveEvent', $id); return true; }
/** * Restore a file or folder from trash bin * * @param string $file path to the deleted file/folder relative to "files_trashbin/files/", * including the timestamp suffix ".d12345678" * @param string $filename name of the file/folder * @param int $timestamp time when the file/folder was deleted * * @return bool true on success, false otherwise */ public static function restore($file, $filename, $timestamp) { $user = \OCP\User::getUser(); $view = new \OC\Files\View('/' . $user); $location = ''; if ($timestamp) { $location = self::getLocation($user, $filename, $timestamp); if ($location === false) { \OCP\Util::writeLog('files_trashbin', 'trash bin database inconsistent!', \OCP\Util::ERROR); } else { // if location no longer exists, restore file in the root directory if ($location !== '/' && (!$view->is_dir('files/' . $location) || !$view->isCreatable('files/' . $location))) { $location = ''; } } } // we need a extension in case a file/dir with the same name already exists $uniqueFilename = self::getUniqueFilename($location, $filename, $view); $source = \OC\Files\Filesystem::normalizePath('files_trashbin/files/' . $file); $target = \OC\Files\Filesystem::normalizePath('files/' . $location . '/' . $uniqueFilename); if (!$view->file_exists($source)) { return false; } $mtime = $view->filemtime($source); // restore file $restoreResult = $view->rename($source, $target); // handle the restore result if ($restoreResult) { $fakeRoot = $view->getRoot(); $view->chroot('/' . $user . '/files'); $view->touch('/' . $location . '/' . $uniqueFilename, $mtime); $view->chroot($fakeRoot); \OCP\Util::emitHook('\\OCA\\Files_Trashbin\\Trashbin', 'post_restore', array('filePath' => \OC\Files\Filesystem::normalizePath('/' . $location . '/' . $uniqueFilename), 'trashPath' => \OC\Files\Filesystem::normalizePath($file))); self::restoreVersions($view, $file, $filename, $uniqueFilename, $location, $timestamp); if ($timestamp) { $query = \OC_DB::prepare('DELETE FROM `*PREFIX*files_trash` WHERE `user`=? AND `id`=? AND `timestamp`=?'); $query->execute(array($user, $filename, $timestamp)); } return true; } return false; }
/** * Triggers the given hook signal for all the applicables given * * @param string $signal signal * @param string $mountPoint hook mount pount param * @param string $mountType hook mount type param * @param array $applicableArray array of applicable users/groups for which to trigger the hook */ protected function triggerApplicableHooks($signal, $mountPoint, $mountType, $applicableArray) { foreach ($applicableArray as $applicable) { \OCP\Util::emitHook(Filesystem::CLASSNAME, $signal, [Filesystem::signal_param_path => $mountPoint, Filesystem::signal_param_mount_type => $mountType, Filesystem::signal_param_users => $applicable]); } }
/** * Creates a new calendar * @param string $userid * @param string $name * @param string $components Default: "VEVENT,VTODO,VJOURNAL" * @param string $timezone Default: null * @param integer $order Default: 1 * @param string $color * @return insertid || null */ public function add($userid, $name, $components = 'VEVENT,VTODO,VJOURNAL', $timezone = null, $order = 0, $color = "#C2F9FC", $issubscribe = 0, $externuri = '', $lastmodified = 0) { $all = $this->allCalendars(); $uris = array(); foreach ($all as $i) { $uris[] = $i['uri']; } if ($lastmodified === 0) { $lastmodified = time(); } $uri = $this->createURI($name, $uris); $insertid = $this->calendarDB->add($name, $uri, $order, $color, $timezone, $components, $issubscribe, $externuri, $lastmodified); if ($insertid !== null) { \OCP\Util::emitHook('\\OCA\\CalendarPlus', 'addCalendar', $insertid); $link = \OC::$server->getURLGenerator()->linkToRoute($this->appName . '.page.index'); $params = array('mode' => 'created', 'link' => $link, 'trans_type' => '', 'summary' => $name, 'cal_user' => $userid, 'cal_displayname' => $name); ActivityData::logEventActivity($params, false, true); return $insertid; } else { return null; } }
/** * @brief removes an address book * @param integer $id * @return boolean true on success, otherwise an exception will be thrown */ public static function delete($id) { $addressbook = self::find($id); if ($addressbook['userid'] !== \OCP\User::getUser() && !\OC_Group::inGroup(\OCP\User::getUser(), 'admin')) { $sharedAddressbook = \OCP\Share::getItemSharedWithBySource(App::SHAREADDRESSBOOK, App::SHAREADDRESSBOOKPREFIX . $id); if (!$sharedAddressbook || !($sharedAddressbook['permissions'] & \OCP\PERMISSION_DELETE)) { throw new \Exception(App::$l10n->t('You do not have the permissions to delete this addressbook.')); } } // First delete cards belonging to this addressbook. $cards = VCard::all($id); foreach ($cards as $card) { try { VCard::delete($card['id']); } catch (\Exception $e) { \OCP\Util::writeLog(App::$appname, __METHOD__ . ', exception deleting vCard ' . $card['id'] . ': ' . $e->getMessage(), \OCP\Util::ERROR); } } try { $stmt = \OCP\DB::prepare('DELETE FROM `' . App::AddrBookTable . '` WHERE `id` = ?'); $stmt->execute(array($id)); } catch (\Exception $e) { \OCP\Util::writeLog(App::$appname, __METHOD__ . ', exception for ' . $id . ': ' . $e->getMessage(), \OCP\Util::ERROR); throw new \Exception(App::$l10n->t('There was an error deleting this addressbook.')); } \OCP\Share::unshareAll(App::SHAREADDRESSBOOK, App::SHAREADDRESSBOOKPREFIX . $id); \OCP\Util::emitHook('\\OCA\\ContactsPlus', 'deleteAddressbook', $id); return true; }
/** * Verify if a password meets all requirements * * @param string $password * @throws \Exception */ protected function verifyPassword($password) { if ($password === null) { // No password is set, check if this is allowed. if ($this->shareApiLinkEnforcePassword()) { throw new \InvalidArgumentException('Passwords are enforced for link shares'); } return; } // Let others verify the password $accepted = true; $message = ''; \OCP\Util::emitHook('\\OC\\Share', 'verifyPassword', ['password' => $password, 'accepted' => &$accepted, 'message' => &$message]); if (!$accepted) { throw new \Exception($message); } }
/** * Deletes a contact * * @param string $addressbookid * @param string $id * @param array $options - Optional (backend specific options) * @see getContact * @return bool */ public function deleteContact($addressbookid, $id, array $options = array()) { // TODO: pass the uri in $options instead. $qname = 'deletecontact'; $noCollection = isset($options['noCollection']) ? $options['noCollection'] : false; $isBatch = isset($options['isBatch']) ? $options['isBatch'] : false; if (is_array($id)) { if (isset($id['id'])) { $id = $id['id']; } elseif (isset($id['uri'])) { $id = $this->getIdFromUri($id['uri']); if (is_null($id)) { \OCP\Util::writeLog('contacts', __METHOD__ . ' Couldn\'t find contact', \OCP\Util::ERROR); return false; } } else { throw new Exception(__METHOD__ . ' If second argument is an array, either \'id\' or \'uri\' has to be set.'); } } if (!$isBatch) { \OCP\Util::emitHook('OCA\\Contacts', 'pre_deleteContact', array('id' => $id)); } if ($noCollection) { $me = $this->getContact(null, $id, $options); $addressbookid = $me['parent']; } if (!isset(self::$preparedQueries[$qname])) { self::$preparedQueries[$qname] = \OCP\DB::prepare('DELETE FROM `' . $this->cardsTableName . '` WHERE `id` = ? AND `addressbookid` = ?'); } \OCP\Util::writeLog('contacts', __METHOD__ . ' updates: ' . $id . '/' . $addressbookid, \OCP\Util::DEBUG); try { $result = self::$preparedQueries[$qname]->execute(array($id, $addressbookid)); if (\OCP\DB::isError($result)) { \OCP\Util::writeLog('contacts', __METHOD__ . 'DB error: ' . \OC_DB::getErrorMessage($result), \OCP\Util::ERROR); return false; } } catch (\Exception $e) { \OCP\Util::writeLog('contacts', __METHOD__ . ', exception: ' . $e->getMessage(), \OCP\Util::ERROR); \OCP\Util::writeLog('contacts', __METHOD__ . ', id: ' . $id, \OCP\Util::DEBUG); return false; } $this->touchAddressBook($addressbookid); return true; }
public function fopen($path, $mode) { if ($source = $this->getSourcePath($path)) { switch ($mode) { case 'r+': case 'rb+': case 'w+': case 'wb+': case 'x+': case 'xb+': case 'a+': case 'ab+': case 'w': case 'wb': case 'x': case 'xb': case 'a': case 'ab': $creatable = $this->isCreatable($path); $updatable = $this->isUpdatable($path); // if neither permissions given, no need to continue if (!$creatable && !$updatable) { return false; } $exists = $this->file_exists($path); // if a file exists, updatable permissions are required if ($exists && !$updatable) { return false; } // part file is allowed if !$creatable but the final file is $updatable if (pathinfo($path, PATHINFO_EXTENSION) !== 'part') { if (!$exists && !$creatable) { return false; } } } $info = array('target' => $this->getMountPoint() . $path, 'source' => $source, 'mode' => $mode); \OCP\Util::emitHook('\\OC\\Files\\Storage\\Shared', 'fopen', $info); list($storage, $internalPath) = \OC\Files\Filesystem::resolvePath($source); return $storage->fopen($internalPath, $mode); } return false; }
protected function isTwoFactorEnforced($username) { Util::emitHook('\\OCA\\Files_Sharing\\API\\Server2Server', 'preLoginNameUsedAsUserName', array('uid' => &$username)); $user = $this->manager->get($username); if (is_null($user)) { $users = $this->manager->getByEmail($username); if (count($users) !== 1) { return true; } $user = $users[0]; } // DI not possible due to cyclic dependencies :'-/ return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user); }
/** * Delete a list of contacts from the address book * * @param array $ids * @return array containing the status * @throws \Exception on missing permissions */ public function deleteChildren($ids) { if (!$this->hasPermission(\OCP\PERMISSION_DELETE)) { throw new \Exception(self::$l10n->t('You do not have permissions to delete this contact'), Http::STATUS_FORBIDDEN); } if (!$this->getBackend()->hasContactMethodFor(\OCP\PERMISSION_DELETE)) { throw new \Exception(self::$l10n->t('The backend for this address book does not support deleting contacts'), Http::STATUS_NOT_IMPLEMENTED); } $response = array(); \OCP\Util::emitHook('OCA\\Contacts', 'pre_deleteContact', array('id' => $ids)); foreach ($ids as $id) { try { if (!$this->deleteChild($id, array('isBatch' => true))) { \OCP\Util::writeLog('contacts', __METHOD__ . ' Error deleting contact: ' . $this->getBackend()->name . '::' . $this->getId() . '::' . $id, \OCP\Util::ERROR); $response[] = array('id' => (string) $id, 'status' => 'error', 'message' => self::$l10n->t('Unknown error')); } else { $response[] = array('id' => (string) $id, 'status' => 'success'); } } catch (\Exception $e) { $response[] = array('id' => (string) $id, 'status' => 'error', 'message' => $e->getMessage()); } } return $response; }
/** * @NoAdminRequired */ public function setActiveCalendar() { $calendarid = $this->params('calendarid'); $pActive = intval($this->params('active')); $calendar = false; if ($calendarid !== 'birthday_' . $this->userId) { $calendar = CalendarApp::getCalendar((int) $calendarid, true, true); } if (!$calendar && $calendarid !== 'birthday_' . $this->userId) { $params = ['status' => 'error', 'message' => 'permission denied']; $response = new JSONResponse($params); return $response; } CalendarCalendar::setCalendarActive($calendarid, (int) $pActive); $isAktiv = $pActive; if ($this->configInfo->getUserValue($this->userId, $this->appName, 'calendar_' . $calendarid) !== '') { $isAktiv = $this->configInfo->getUserValue($this->userId, $this->appName, 'calendar_' . $calendarid); } $eventSource = ''; if ($calendarid !== 'birthday_' . $this->userId) { $eventSource = CalendarCalendar::getEventSourceInfo($calendar); } else { \OCP\Util::emitHook('OC_Calendar', 'getSources', array('all' => false, 'sources' => &$eventSource)); } $params = ['status' => 'success', 'active' => $isAktiv, 'eventSource' => $eventSource]; $response = new JSONResponse($params); return $response; }