public function register() { $loginRecord = function ($user) { $UserRole = \OC::$server->getConfig()->getUserValue(\OC_User::getUser(), "settings", "role", "undefined"); Util::writeLog('core', "user:"******" role:" . $UserRole . " action:login success", Util::INFO); }; $logoutRecord = function () { $UserRole = \OC::$server->getConfig()->getUserValue(\OC_User::getUser(), "settings", "role", "undefined"); Util::writeLog('core', "user:"******" role:" . $this->UserRole . " action:logout success", Util::INFO); }; $createRecord = function ($node) { $UserRole = \OC::$server->getConfig()->getUserValue(\OC_User::getUser(), "settings", "role", "undefined"); Util::writeLog('activity', "user:"******" role:" . $UserRole . " action:creates " . $node->getName() . " success", Util::INFO); }; $deleteRecord = function ($node) { $UserRole = \OC::$server->getConfig()->getUserValue(\OC_User::getUser(), "settings", "role", "undefined"); Util::writeLog('activity', "user:"******" role:" . $UserRole . " action:deletes " . $node->getName() . " success", Util::INFO); }; $renameRecord = function ($node) { $UserRole = \OC::$server->getConfig()->getUserValue(\OC_User::getUser(), "settings", "role", "undefined"); Util::writeLog('activity', "user:"******" role:" . $UserRole . " action:renames " . $node->getName() . " success", Util::INFO); }; $touchRecord = function ($node) { $UserRole = \OC::$server->getConfig()->getUserValue(\OC_User::getUser(), "settings", "role", "undefined"); Util::writeLog('activity', "user:"******" role:" . $UserRole . " action:touches " . $node->getName() . " success", Util::INFO); }; Util::connectHook('OCP\\Share', 'post_shared', 'OCA\\Activity_Logging\\UserHooks', 'share'); $this->userManager->listen('\\OC\\User', 'postLogin', $loginRecord); $this->userManager->listen('\\OC\\User', 'logout', $logoutRecord); $this->UserFolder->listen('\\OC\\Files', 'postCreate', $createRecord); $this->UserFolder->listen('\\OC\\Files', 'postDelete', $deleteRecord); $this->UserFolder->listen('\\OC\\Files', 'postRename', $renameRecord); }
public function register() { $loginRecord = function ($user) { \OCP\Util::writeLog('core', "user:"******" action:login success", \OCP\Util::INFO); }; $logoutRecord = function () { \OCP\Util::writeLog('core', "user:"******" action:logout success", \OCP\Util::INFO); }; $createRecord = function ($node) { \OCP\Util::writeLog('activity', "user:"******" action:cretes " . $node->getName() . " sucess", \OCP\Util::INFO); }; $deleteRecord = function ($node) { \OCP\Util::writeLog('activity', "user:"******" action:deletes " . $node->getName() . " sucess", \OCP\Util::INFO); }; $renameRecord = function ($node) { \OCP\Util::writeLog('activity', "user:"******" action:renames " . $node->getName() . " sucess", \OCP\Util::INFO); }; $touchRecord = function ($node) { \OCP\Util::writeLog('activity', "user:"******" action:touches " . $node->getName() . " sucess", \OCP\Util::INFO); }; $this->userManager->listen('\\OC\\User', 'postLogin', $loginRecord); $this->userManager->listen('\\OC\\User', 'logout', $logoutRecord); $this->UserFolder->listen('\\OC\\Files', 'postCreate', $createRecord); $this->UserFolder->listen('\\OC\\Files', 'postDelete', $deleteRecord); $this->UserFolder->listen('\\OC\\Files', 'postRename', $renameRecord); }
/** * Start a editing session or return an existing one * @param string $uid of the user starting a session * @param \OCA\Documents\File $file - file object * @return array * @throws \Exception */ public static function start($uid, $file) { // Create a directory to store genesis $genesis = new Genesis($file); list($ownerView, $path) = $file->getOwnerViewAndPath(); $oldSession = new Db_Session(); $oldSession->loadBy('file_id', $file->getFileId()); //If there is no existing session we need to start a new one if (!$oldSession->hasData()) { $newSession = new Db_Session(array($genesis->getPath(), $genesis->getHash(), $file->getOwner(), $file->getFileId())); if (!$newSession->insert()) { throw new \Exception('Failed to add session into database'); } } $sessionData = $oldSession->loadBy('file_id', $file->getFileId())->getData(); $memberColor = Helper::getMemberColor($uid); $member = new Db_Member(array($sessionData['es_id'], $uid, $memberColor, time(), intval($file->isPublicShare()), $file->getToken())); if ($member->insert()) { // Do we have OC_Avatar in out disposal? if (!class_exists('\\OC_Avatar') || \OC_Config::getValue('enable_avatars', true) !== true) { $imageUrl = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw=='; } else { $imageUrl = $uid; } $displayName = $file->isPublicShare() ? $uid . ' ' . Db_Member::getGuestPostfix() : \OCP\User::getDisplayName($uid); $sessionData['member_id'] = (string) $member->getLastInsertId(); $op = new Db_Op(); $op->addMember($sessionData['es_id'], $sessionData['member_id'], $displayName, $memberColor, $imageUrl); } else { throw new \Exception('Failed to add member into database'); } $sessionData['title'] = basename($path); $sessionData['permissions'] = $ownerView->getFilePermissions($path); return $sessionData; }
/** * Get the template for a specific activity-event in the activities * * @param array $activity An array with all the activity data in it * @return string */ public static function show($activity) { $tmpl = new Template('activity', 'activity.box'); $tmpl->assign('formattedDate', Util::formatDate($activity['timestamp'])); $tmpl->assign('formattedTimestamp', \OCP\relative_modified_date($activity['timestamp'])); $tmpl->assign('user', $activity['user']); $tmpl->assign('displayName', User::getDisplayName($activity['user'])); if (strpos($activity['subjectformatted']['markup']['trimmed'], '<a ') !== false) { // We do not link the subject as we create links for the parameters instead $activity['link'] = ''; } $tmpl->assign('event', $activity); if ($activity['file']) { $rootView = new View('/' . $activity['affecteduser'] . '/files'); $exist = $rootView->file_exists($activity['file']); $is_dir = $rootView->is_dir($activity['file']); unset($rootView); // show a preview image if the file still exists $mimetype = \OC_Helper::getFileNameMimeType($activity['file']); if (!$is_dir && \OC::$server->getPreviewManager()->isMimeSupported($mimetype) && $exist) { $tmpl->assign('previewLink', Util::linkTo('files', 'index.php', array('dir' => dirname($activity['file'])))); $tmpl->assign('previewImageLink', Util::linkToRoute('core_ajax_preview', array('file' => $activity['file'], 'x' => 150, 'y' => 150))); } else { $tmpl->assign('previewLink', Util::linkTo('files', 'index.php', array('dir' => $activity['file']))); $tmpl->assign('previewImageLink', \OC_Helper::mimetypeIcon($is_dir ? 'dir' : $mimetype)); $tmpl->assign('previewLinkIsDir', true); } } return $tmpl->fetchPage(); }
/** * Get the template for a specific activity-event in the activities * * @param array $activity An array with all the activity data in it * @return string */ public function show($activity) { $tmpl = new Template('activity', 'stream.item'); $tmpl->assign('formattedDate', $this->dateTimeFormatter->formatDateTime($activity['timestamp'])); $tmpl->assign('formattedTimestamp', Template::relative_modified_date($activity['timestamp'])); $tmpl->assign('user', $activity['user']); $tmpl->assign('displayName', User::getDisplayName($activity['user'])); if (strpos($activity['subjectformatted']['markup']['trimmed'], '<a ') !== false) { // We do not link the subject as we create links for the parameters instead $activity['link'] = ''; } $tmpl->assign('event', $activity); if ($activity['file']) { $this->view->chroot('/' . $activity['affecteduser'] . '/files'); $exist = $this->view->file_exists($activity['file']); $is_dir = $this->view->is_dir($activity['file']); $tmpl->assign('previewLink', $this->getPreviewLink($activity['file'], $is_dir)); // show a preview image if the file still exists $mimeType = \OC_Helper::getFileNameMimeType($activity['file']); if ($mimeType && !$is_dir && $this->preview->isMimeSupported($mimeType) && $exist) { $tmpl->assign('previewImageLink', $this->urlGenerator->linkToRoute('core_ajax_preview', array('file' => $activity['file'], 'x' => 150, 'y' => 150))); } else { $mimeTypeIcon = Template::mimetype_icon($is_dir ? 'dir' : $mimeType); $mimeTypeIcon = substr($mimeTypeIcon, -4) === '.png' ? substr($mimeTypeIcon, 0, -4) . '.svg' : $mimeTypeIcon; $tmpl->assign('previewImageLink', $mimeTypeIcon); $tmpl->assign('previewLinkIsDir', true); } } return $tmpl->fetchPage(); }
/** * Get the template for a specific activity-event in the activities * * @param array $activity An array with all the activity data in it * @param return string */ public static function show($activity) { $tmpl = new \OCP\Template('activity', 'activity.box'); $tmpl->assign('formattedDate', \OCP\Util::formatDate($activity['timestamp'])); $tmpl->assign('formattedTimestamp', \OCP\relative_modified_date($activity['timestamp'])); $tmpl->assign('user', $activity['user']); $tmpl->assign('displayName', \OCP\User::getDisplayName($activity['user'])); if ($activity['app'] === 'files') { // We do not link the subject as we create links for the parameters instead $activity['link'] = ''; } $tmpl->assign('event', $activity); if ($activity['file']) { $rootView = new \OC\Files\View(''); $exist = $rootView->file_exists('/' . $activity['user'] . '/files' . $activity['file']); $is_dir = $rootView->is_dir('/' . $activity['user'] . '/files' . $activity['file']); unset($rootView); // show a preview image if the file still exists if (!$is_dir && $exist) { $tmpl->assign('previewLink', \OCP\Util::linkTo('files', 'index.php', array('dir' => dirname($activity['file'])))); $tmpl->assign('previewImageLink', \OCP\Util::linkToRoute('core_ajax_preview', array('file' => $activity['file'], 'x' => 150, 'y' => 150))); } else { if ($exist) { $tmpl->assign('previewLink', \OCP\Util::linkTo('files', 'index.php', array('dir' => $activity['file']))); $tmpl->assign('previewImageLink', \OC_Helper::mimetypeIcon('dir')); $tmpl->assign('previewLinkIsDir', true); } } } return $tmpl->fetchPage(); }
public static function readdir($path) { $result = parent::readdir($path); if ($result === false) { \OCP\Util::writeLog('activity', "user:"******" action:read fail", \OCP\Util::WARN); } return $result; }
public static function getUsername() { $username = self::getValue(self::CONFIG_USERNAME, \OCP\User::getDisplayName()); if (!$username) { $username = \OCP\User::getUser(); } return $username; }
public function __construct($returnstring) { $user_name = trim(\OCP\User::getDisplayName()) != '' ? \OCP\User::getDisplayName() : \OCP\User::getUser(); $export_name = '"ownCloud Bookmarks (' . $user_name . ') (' . date('Y-m-d') . ').html"'; $this->addHeader("Cache-Control", "private"); $this->addHeader("Content-Type", " application/stream"); $this->addHeader("Content-Length", strlen($returnstring)); $this->addHeader("Content-Disposition", "attachment; filename=" . $export_name); $this->returnstring = $returnstring; }
/** * inform users if a file was shared with them * * @param array $recipientList list of recipients * @param string $itemSource shared item source * @param string $itemType shared item type * @return array list of user to whom the mail send operation failed */ public function sendInternalShareMail($recipientList, $itemSource, $itemType) { $noMail = array(); foreach ($recipientList as $recipient) { $recipientDisplayName = \OCP\User::getDisplayName($recipient); $to = \OC_Preferences::getValue($recipient, 'settings', 'email', ''); if ($to === '') { $noMail[] = $recipientDisplayName; continue; } $items = \OCP\Share::getItemSharedWithUser($itemType, $itemSource, $recipient); $filename = trim($items[0]['file_target'], '/'); $subject = (string) $this->l->t('%s shared »%s« with you', array($this->senderDisplayName, $filename)); $expiration = null; if (isset($items[0]['expiration'])) { try { $date = new DateTime($items[0]['expiration']); $expiration = $date->getTimestamp(); } catch (\Exception $e) { \OCP\Util::writeLog('sharing', "Couldn't read date: " . $e->getMessage(), \OCP\Util::ERROR); } } // Link to folder, or root folder if a file if ($itemType === 'folder') { $args = array( 'dir' => $filename, ); } else { $args = array( 'dir' => '/', 'scrollto' => $filename, ); } $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args); list($htmlMail, $alttextMail) = $this->createMailBody($filename, $link, $expiration); // send it out now try { \OCP\Util::sendMail($to, $recipientDisplayName, $subject, $htmlMail, $this->from, $this->senderDisplayName, 1, $alttextMail); } catch (\Exception $e) { \OCP\Util::writeLog('sharing', "Can't send mail to inform the user about an internal share: " . $e->getMessage() , \OCP\Util::ERROR); $noMail[] = $recipientDisplayName; } } return $noMail; }
/** * inform users if a file was shared with them * * @param array $recipientList list of recipients * @param string $itemSource shared item source * @param string $itemType shared item type * @return array list of user to whom the mail send operation failed */ public function sendInternalShareMail($recipientList, $itemSource, $itemType) { $noMail = []; foreach ($recipientList as $recipient) { $recipientDisplayName = \OCP\User::getDisplayName($recipient); $to = $this->config->getUserValue($recipient, 'settings', 'email', ''); if ($to === '') { $noMail[] = $recipientDisplayName; continue; } $items = \OCP\Share::getItemSharedWithUser($itemType, $itemSource, $recipient); $filename = trim($items[0]['file_target'], '/'); $subject = (string) $this->l->t('%s shared »%s« with you', array($this->senderDisplayName, $filename)); $expiration = null; if (isset($items[0]['expiration'])) { try { $date = new DateTime($items[0]['expiration']); $expiration = $date->getTimestamp(); } catch (\Exception $e) { $this->logger->error("Couldn't read date: " . $e->getMessage(), ['app' => 'sharing']); } } // Link to folder, or root folder if a file if ($itemType === 'folder') { $args = array('dir' => $filename); } else { if (strpos($filename, '/')) { $args = array('dir' => '/' . dirname($filename), 'scrollto' => basename($filename)); } else { $args = array('dir' => '/', 'scrollto' => $filename); } } $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args); list($htmlBody, $textBody) = $this->createMailBody($filename, $link, $expiration); // send it out now try { $message = $this->mailer->createMessage(); $message->setSubject($subject); $message->setTo([$to => $recipientDisplayName]); $message->setHtmlBody($htmlBody); $message->setPlainBody($textBody); $message->setFrom([\OCP\Util::getDefaultEmailAddress('sharing-noreply') => (string) $this->l->t('%s via %s', [$this->senderDisplayName, $this->defaults->getName()])]); if (!is_null($this->replyTo)) { $message->setReplyTo([$this->replyTo]); } $this->mailer->send($message); } catch (\Exception $e) { $this->logger->error("Can't send mail to inform the user about an internal share: " . $e->getMessage(), ['app' => 'sharing']); $noMail[] = $recipientDisplayName; } } return $noMail; }
/** * Start a editing session or return an existing one * @param string $uid of the user starting a session * @param \OCA\Documents\File $file - file object * @return array * @throws \Exception */ public static function start($uid, File $file) { list($ownerView, $path) = $file->getOwnerViewAndPath(); // Create a directory to store genesis $genesis = new Genesis($ownerView, $path, $file->getOwner()); $oldSession = new Db_Session(); $oldSession->loadBy('file_id', $file->getFileId()); //If there is no existing session we need to start a new one if (!$oldSession->hasData()) { $newSession = new Db_Session(array($genesis->getPath(), $genesis->getHash(), $file->getOwner(), $file->getFileId())); if (!$newSession->insert()) { throw new \Exception('Failed to add session into database'); } } $session = $oldSession->loadBy('file_id', $file->getFileId())->getData(); $memberColor = Helper::getRandomColor(); $member = new Db_Member(array($session['es_id'], $uid, $memberColor, time())); if ($member->insert()) { // Do we have OC_Avatar in out disposal? if (!class_exists('\\OC_Avatar') || \OC_Config::getValue('enable_avatars', true) !== true) { //$x['avatar_url'] = \OCP\Util::linkToRoute('documents_user_avatar'); $imageUrl = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw=='; } else { // https://github.com/owncloud/documents/issues/51 // Temporary stub $imageUrl = $uid; /* $avatar = new \OC_Avatar($uid); $image = $avatar->get(64); // User has an avatar if ($image instanceof \OC_Image) { $imageUrl = \OC_Helper::linkToRoute( 'core_avatar_get', array( 'user' => $uid, 'size' => 64) ) . '?requesttoken=' . \OC::$session->get('requesttoken'); } else { //shortcircuit if it's not an image $imageUrl = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAAAAACH5BAAAAAAALAAAAAABAAEAAAICTAEAOw=='; } */ } $session['member_id'] = (string) $member->getLastInsertId(); $op = new Db_Op(); $op->addMember($session['es_id'], $session['member_id'], \OCP\User::getDisplayName($uid), $memberColor, $imageUrl); } else { throw new \Exception('Failed to add member into database'); } $session['permissions'] = $ownerView->getFilePermissions($path); return $session; }
public static function sendMail($path) { if (!\OCP\User::isLoggedIn()) { return; } $email = \OCP\Config::getUserValue(\OCP\User::getUser(), 'settings', 'email', ''); \OCP\Util::writeLog('files_antivirus', 'Email: ' . $email, \OCP\Util::DEBUG); if (!empty($email)) { $defaults = new \OCP\Defaults(); $tmpl = new \OCP\Template('files_antivirus', 'notification'); $tmpl->assign('file', $path); $tmpl->assign('host', \OCP\Util::getServerHost()); $tmpl->assign('user', \OCP\User::getDisplayName()); $msg = $tmpl->fetchPage(); $from = \OCP\Util::getDefaultEmailAddress('security-noreply'); \OCP\Util::sendMail($email, \OCP\User::getUser(), \OCP\Util::getL10N('files_antivirus')->t('Malware detected'), $msg, $from, $defaults->getName(), true); } }
/** * @brief serve opds feed for given directory * * @param string $dir full path to directory * @param int $id requested id */ public static function serveFeed($dir, $id) { if (isset($_SERVER['HTTP_ACCEPT']) && stristr($_SERVER['HTTP_ACCEPT'], 'application/atom+xml')) { header('Content-Type: application/atom+xml'); } else { header('Content-Type: text/xml; charset=UTF-8'); } $sortAttribute = 'name'; $sortDirection = false; $defaults = new \OC_Defaults(); $tmpl = new \OCP\Template('files_opds', 'feed'); $tmpl->assign('files', Files::formatFileInfos(Files::getFiles($dir, $sortAttribute, $sortDirection))); $tmpl->assign('bookshelf', Files::formatFileInfos(Bookshelf::get())); $tmpl->assign('bookshelf-count', Bookshelf::count()); $tmpl->assign('feed_id', self::getFeedId()); $tmpl->assign('id', $id); $tmpl->assign('dir', $dir); $tmpl->assign('user', \OCP\User::getDisplayName()); $tmpl->assign('feed_title', Config::get('feed_title', \OCP\User::getDisplayName() . "'s Library")); $tmpl->assign('feed_subtitle', Config::getApp('feed_subtitle', $defaults->getName() . " OPDS catalog")); $tmpl->assign('feed_updated', time()); $tmpl->printPage(); }
/** * get shared parents * * @param int $itemSource item source ID * @param string $shareWith with whom should the item be shared * @param string $owner owner of the item * @return array with shares */ public function getParents($itemSource, $shareWith = null, $owner = null) { $result = array(); $parent = $this->getParentId($itemSource); while ($parent) { $shares = \OCP\Share::getItemSharedWithUser('folder', $parent, $shareWith, $owner); if ($shares) { foreach ($shares as $share) { $name = substr($share['path'], strrpos($share['path'], '/') + 1); $share['collection']['path'] = $name; $share['collection']['item_type'] = 'folder'; $share['file_path'] = $name; $displayNameOwner = \OCP\User::getDisplayName($share['uid_owner']); $displayNameShareWith = \OCP\User::getDisplayName($share['share_with']); $share['displayname_owner'] = $displayNameOwner ? $displayNameOwner : $share['uid_owner']; $share['share_with_displayname'] = $displayNameShareWith ? $displayNameShareWith : $share['uid_owner']; $result[] = $share; } } $parent = $this->getParentId($parent); } return $result; }
} OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('gallery'); $images = \OCP\Files::searchByMime('image'); $user = \OCP\User::getUser(); $users = array(); $result = array(); foreach ($images as &$image) { // we show shared images another way if ($image->getStorage() instanceof \OC\Files\Storage\Shared) { $owner = $image['uid_owner']; $users[$owner] = $owner; } else { $owner = $user; } $path = $image['path']; if (strpos($path, DIRECTORY_SEPARATOR . ".")) { continue; } $result[] = $owner . $path; } $displayNames = array(); foreach ($users as $user) { $displayNames[$user] = \OCP\User::getDisplayName($user); } function startsWith($haystack, $needle) { return !strncmp($haystack, $needle, strlen($needle)); } OCP\JSON::setContentTypeHeader(); echo json_encode(array('images' => $result, 'users' => array_values($users), 'displayNames' => $displayNames));
public static function post_login($parameters) { // Do nothing if we're sharding and not on the master if (OCP\App::isEnabled('files_sharding') && !OCA\FilesSharding\Lib::isMaster()) { return true; } $uid = ''; $userid = $parameters['uid']; $samlBackend = new OC_USER_SAML(); $ocUserDatabase = new OC_User_Database(); // Redirect regardless of whether the user has authenticated with SAML or not. // Since this is a post_login hook, he will have authenticated in some way and have a valid session. if ($ocUserDatabase->userExists($userid)) { // Set user attributes for sharding $display_name = \OCP\User::getDisplayName($userid); $email = \OCP\Config::getUserValue($userid, 'settings', 'email'); $groups = \OC_Group::getUserGroups($userid); $quota = \OC_Preferences::getValue($userid, 'files', 'quota'); OC_Util::teardownFS($userid); OC_Util::setupFS($userid); OC_Log::write('saml', 'Setting user attributes: ' . $userid . ":" . $display_name . ":" . $email . ":" . join($groups) . ":" . $quota, OC_Log::INFO); self::setAttributes($userid, $display_name, $email, $groups, $quota); self::user_redirect($userid); } if (!$samlBackend->auth->isAuthenticated()) { return false; } $attributes = $samlBackend->auth->getAttributes(); //$email = "<pre>" . print_r($attributes, 1) . "</pre>"; //$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; //error_log($email, 1, '*****@*****.**', $headers); $usernameFound = false; foreach ($samlBackend->usernameMapping as $usernameMapping) { if (array_key_exists($usernameMapping, $attributes) && !empty($attributes[$usernameMapping][0])) { $usernameFound = true; $uid = $attributes[$usernameMapping][0]; OC_Log::write('saml', 'Authenticated user ' . $uid, OC_Log::INFO); break; } } if (!$usernameFound || $uid !== $userid) { return false; } $attrs = self::get_user_attributes($uid, $samlBackend); if (!$ocUserDatabase->userExists($uid)) { // If autocreate is not enabled - back off if (!$samlBackend->autocreate) { return false; } // Apparently it is necessary to clear the uid first, to be able to create the user in the DB $userManager = \OC_User::getManager(); $userManager->delete($uid); // Reject invalid user names if (preg_match('/[^a-zA-Z0-9 _\\.@\\-]/', $uid)) { OC_Log::write('saml', 'Invalid username "' . $uid . '", allowed chars "a-zA-Z0-9" and "_.@-" ', OC_Log::DEBUG); return false; } $cookiedomain = OCP\App::isEnabled('files_sharding') ? OCA\FilesSharding\Lib::getCookieDomain() : null; // Reject users we don't allow to autocreate an account if (isset($uid) && trim($uid) != '' && !OC_User::userExists($uid) && !self::check_user_attributes($attributes)) { $failCookieName = 'saml_auth_fail'; $userCookieName = 'saml_auth_fail_user'; $expire = 0; //time()+60*60*24*30; $expired = time() - 3600; $path = '/'; setcookie($failCookieName, "notallowed:" . $uid, $expire, $path, $cookiedomain, false, false); setcookie($userCookieName, $uid, $expire, $path, $cookiedomain, false, false); $spSource = 'default-sp'; $auth = new SimpleSAML_Auth_Simple($spSource); OC_Log::write('saml', 'Rejected user "' . $uid, OC_Log::ERROR); if (OCP\App::isEnabled('files_sharding') && !OCA\FilesSharding\Lib::isMaster()) { $auth->logout(!OCA\FilesSharding\Lib::getMasterURL()); } else { $auth->logout(); } return false; } // Create new user $random_password = OC_Util::generateRandomBytes(20); OC_Log::write('saml', 'Creating new user: '******'/' . $uid . '/files'; \OC\Files\Filesystem::init($uid, $userDir); if ($samlBackend->updateUserData) { self::update_user_data($uid, $samlBackend, $attrs, true); if (OCP\App::isEnabled('files_sharding') && OCA\FilesSharding\Lib::isMaster()) { $master_site = OCA\FilesSharding\Lib::dbGetSite(null); $server_id = OCA\FilesSharding\Lib::dbChooseServerForUser($uid, $master_site, 0, null); OC_Log::write('saml', 'Setting server for new user: '******'display_name'], $attrs['email'], $attrs['groups'], $attrs['quota']); } } else { if ($samlBackend->updateUserData) { self::update_user_data($uid, $samlBackend, $attrs, false); } } self::user_redirect($userid); return true; }
/** * Get shared items from the database * @param string $itemType * @param string $item Item source or target (optional) * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique * @param string $shareWith User or group the item is being shared with * @param string $uidOwner User that is the owner of shared items (optional) * @param int $format Format to convert items to with formatItems() (optional) * @param mixed $parameters to pass to formatItems() (optional) * @param int $limit Number of items to return, -1 to return all matches (optional) * @param boolean $includeCollections Include collection item types (optional) * @param boolean $itemShareWithBySource (optional) * @param boolean $checkExpireDate * @return array * * See public functions getItem(s)... for parameter usage * */ public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null, $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1, $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) { if (!self::isEnabled()) { return array(); } $backend = self::getBackend($itemType); $collectionTypes = false; // 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') { if (!is_null($uidOwner)) { $root = \OC\Files\Filesystem::getRoot(); } else { $root = ''; } $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` '; if (!isset($item)) { $where .= ' AND `file_target` IS NOT NULL '; } $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` '; $fileDependent = true; $queryArgs = array(); } else { $fileDependent = false; $root = ''; $collectionTypes = self::getCollectionItemTypes($itemType); if ($includeCollections && !isset($item) && $collectionTypes) { // If includeCollections is true, find collections of this item type, e.g. a music album contains songs if (!in_array($itemType, $collectionTypes)) { $itemTypes = array_merge(array($itemType), $collectionTypes); } else { $itemTypes = $collectionTypes; } $placeholders = join(',', array_fill(0, count($itemTypes), '?')); $where = ' WHERE `item_type` IN (' . $placeholders . '))'; $queryArgs = $itemTypes; } else { $where = ' WHERE `item_type` = ?'; $queryArgs = array($itemType); } } if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') { $where .= ' AND `share_type` != ?'; $queryArgs[] = self::SHARE_TYPE_LINK; } if (isset($shareType)) { // Include all user and group items if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) { $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) '; $queryArgs[] = self::SHARE_TYPE_USER; $queryArgs[] = self::$shareTypeGroupUserUnique; $queryArgs[] = $shareWith; $groups = \OC_Group::getUserGroups($shareWith); if (!empty($groups)) { $placeholders = join(',', array_fill(0, count($groups), '?')); $where .= ' OR (`share_type` = ? AND `share_with` IN (' . $placeholders . ')) '; $queryArgs[] = self::SHARE_TYPE_GROUP; $queryArgs = array_merge($queryArgs, $groups); } $where .= ')'; // Don't include own group shares $where .= ' AND `uid_owner` != ?'; $queryArgs[] = $shareWith; } else { $where .= ' AND `share_type` = ?'; $queryArgs[] = $shareType; if (isset($shareWith)) { $where .= ' AND `share_with` = ?'; $queryArgs[] = $shareWith; } } } if (isset($uidOwner)) { $where .= ' AND `uid_owner` = ?'; $queryArgs[] = $uidOwner; if (!isset($shareType)) { // Prevent unique user targets for group shares from being selected $where .= ' AND `share_type` != ?'; $queryArgs[] = self::$shareTypeGroupUserUnique; } if ($fileDependent) { $column = 'file_source'; } else { $column = 'item_source'; } } else { if ($fileDependent) { $column = 'file_target'; } else { $column = 'item_target'; } } if (isset($item)) { $collectionTypes = self::getCollectionItemTypes($itemType); if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) { $where .= ' AND ('; } else { $where .= ' AND'; } // If looking for own shared items, check item_source else check item_target if (isset($uidOwner) || $itemShareWithBySource) { // If item type is a file, file source needs to be checked in case the item was converted if ($fileDependent) { $where .= ' `file_source` = ?'; $column = 'file_source'; } else { $where .= ' `item_source` = ?'; $column = 'item_source'; } } else { if ($fileDependent) { $where .= ' `file_target` = ?'; $item = \OC\Files\Filesystem::normalizePath($item); } else { $where .= ' `item_target` = ?'; } } $queryArgs[] = $item; if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) { $placeholders = join(',', array_fill(0, count($collectionTypes), '?')); $where .= ' OR `item_type` IN (' . $placeholders . '))'; $queryArgs = array_merge($queryArgs, $collectionTypes); } } if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) { // 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'; } else { $where .= ' ORDER BY `*PREFIX*share`.`id` ASC'; } if ($limit != -1 && !$includeCollections) { // The limit must be at least 3, because filtering needs to be done if ($limit < 3) { $queryLimit = 3; } else { $queryLimit = $limit; } } else { $queryLimit = null; } $select = self::createSelectStatement($format, $fileDependent, $uidOwner); $root = strlen($root); $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where, $queryLimit); $result = $query->execute($queryArgs); if (\OC_DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', \OC_DB::getErrorMessage() . ', select=' . $select . ' where=', \OCP\Util::ERROR); } $items = array(); $targets = array(); $switchedItems = array(); $mounts = array(); while ($row = $result->fetchRow()) { self::transformDBResults($row); // Filter out duplicate group shares for users with unique targets if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) { continue; } if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) { $row['share_type'] = self::SHARE_TYPE_GROUP; $row['unique_name'] = true; // remember that we use a unique name for this user $row['share_with'] = $items[$row['parent']]['share_with']; // if the group share was unshared from the user we keep the permission, otherwise // we take the permission from the parent because this is always the up-to-date // permission for the group share if ($row['permissions'] > 0) { $row['permissions'] = $items[$row['parent']]['permissions']; } // Remove the parent group share unset($items[$row['parent']]); if ($row['permissions'] == 0) { continue; } } else { if (!isset($uidOwner)) { // Check if the same target already exists if (isset($targets[$row['id']])) { // Check if the same owner shared with the user twice // through a group and user share - this is allowed $id = $targets[$row['id']]; if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) { // Switch to group share type to ensure resharing conditions aren't bypassed if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) { $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'] & \OCP\Constants::PERMISSION_SHARE && (int) $row['permissions'] & \OCP\Constants::PERMISSION_SHARE) { $items[$row['id']] = $items[$id]; $switchedItems[$id] = $row['id']; unset($items[$id]); $id = $row['id']; } $items[$id]['permissions'] |= (int) $row['permissions']; } continue; } elseif (!empty($row['parent'])) { $targets[$row['parent']] = $row['id']; } } } // Remove root from file source paths if retrieving own shared items if (isset($uidOwner) && isset($row['path'])) { if (isset($row['parent'])) { $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?'); $parentResult = $query->execute(array($row['parent'])); if (\OC_DB::isError($result)) { \OCP\Util::writeLog('OCP\\Share', 'Can\'t select parent: ' . \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where, \OCP\Util::ERROR); } else { $parentRow = $parentResult->fetchRow(); $tmpPath = $parentRow['file_target']; // find the right position where the row path continues from the target path $pos = strrpos($row['path'], $parentRow['file_target']); $subPath = substr($row['path'], $pos); $splitPath = explode('/', $subPath); foreach (array_slice($splitPath, 2) as $pathPart) { $tmpPath = $tmpPath . '/' . $pathPart; } $row['path'] = $tmpPath; } } else { if (!isset($mounts[$row['storage']])) { $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']); if (is_array($mountPoints) && !empty($mountPoints)) { $mounts[$row['storage']] = current($mountPoints); } } if (!empty($mounts[$row['storage']])) { $path = $mounts[$row['storage']]->getMountPoint() . $row['path']; $relPath = substr($path, $root); // path relative to data/user $row['path'] = rtrim($relPath, '/'); } } } if ($checkExpireDate) { if (self::expireItem($row)) { continue; } } // Check if resharing is allowed, if not remove share permission if (isset($row['permissions']) && !self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser()) { $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE; } // Add display names to result $row['share_with_displayname'] = $row['share_with']; if (isset($row['share_with']) && $row['share_with'] != '' && $row['share_type'] === self::SHARE_TYPE_USER) { $row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']); } else { if (isset($row['share_with']) && $row['share_with'] != '' && $row['share_type'] === self::SHARE_TYPE_REMOTE) { $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']); foreach ($addressBookEntries as $entry) { foreach ($entry['CLOUD'] as $cloudID) { if ($cloudID === $row['share_with']) { $row['share_with_displayname'] = $entry['FN']; } } } } } if (isset($row['uid_owner']) && $row['uid_owner'] != '') { $row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']); } if ($row['permissions'] > 0) { $items[$row['id']] = $row; } } // group items if we are looking for items shared with the current user if (isset($shareWith) && $shareWith === \OCP\User::getUser()) { $items = self::groupItems($items, $itemType); } if (!empty($items)) { $collectionItems = array(); foreach ($items as &$row) { // Return only the item instead of a 2-dimensional array if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) { if ($format == self::FORMAT_NONE) { return $row; } else { break; } } // Check if this is a collection of the requested item type if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) { if (($collectionBackend = self::getBackend($row['item_type'])) && $collectionBackend instanceof \OCP\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; } else { $collection = array(); $collection['item_type'] = $row['item_type']; if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') { $collection['path'] = basename($row['path']); } $row['collection'] = $collection; // Fetch all of the children sources $children = $collectionBackend->getChildren($row[$column]); foreach ($children as $child) { $childItem = $row; $childItem['item_type'] = $itemType; if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') { $childItem['item_source'] = $child['source']; $childItem['item_target'] = $child['target']; } if ($backend instanceof \OCP\Share_Backend_File_Dependent) { if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') { $childItem['file_source'] = $child['source']; } else { // TODO is this really needed if we already know that we use the file backend? $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']); $childItem['file_source'] = $meta['fileid']; } $childItem['file_target'] = \OC\Files\Filesystem::normalizePath($child['file_path']); } if (isset($item)) { if ($childItem[$column] == $item) { // Return only the item instead of a 2-dimensional array if ($limit == 1) { if ($format == self::FORMAT_NONE) { return $childItem; } else { // Unset the items array and break out of both loops $items = array(); $items[] = $childItem; break 2; } } else { $collectionItems[] = $childItem; } } } else { $collectionItems[] = $childItem; } } } } // Remove collection item $toRemove = $row['id']; if (array_key_exists($toRemove, $switchedItems)) { $toRemove = $switchedItems[$toRemove]; } unset($items[$toRemove]); } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) { // FIXME: Thats a dirty hack to improve file sharing performance, // see github issue #10588 for more details // Need to find a solution which works for all back-ends $collectionBackend = self::getBackend($row['item_type']); $sharedParents = $collectionBackend->getParents($row['item_source']); foreach ($sharedParents as $parent) { $collectionItems[] = $parent; } } } if (!empty($collectionItems)) { $collectionItems = array_unique($collectionItems, SORT_REGULAR); $items = array_merge($items, $collectionItems); } // filter out invalid items, these can appear when subshare entries exist // for a group in which the requested user isn't a member any more $items = array_filter($items, function ($item) { return $item['share_type'] !== self::$shareTypeGroupUserUnique; }); return self::formatResult($items, $column, $backend, $format, $parameters); } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) { // FIXME: Thats a dirty hack to improve file sharing performance, // see github issue #10588 for more details // Need to find a solution which works for all back-ends $collectionItems = array(); $collectionBackend = self::getBackend('folder'); $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner); foreach ($sharedParents as $parent) { $collectionItems[] = $parent; } if ($limit === 1) { return reset($collectionItems); } return self::formatResult($collectionItems, $column, $backend, $format, $parameters); } return array(); }
OC_Files::get($path, $files_list, $_SERVER['REQUEST_METHOD'] == 'HEAD'); } else { OC_Files::get($dir, $file, $_SERVER['REQUEST_METHOD'] == 'HEAD'); } exit; } else { OCP\Util::addScript('files', 'file-upload'); OCP\Util::addStyle('files_sharing', 'public'); OCP\Util::addStyle('files_sharing', 'mobile'); OCP\Util::addScript('files_sharing', 'public'); OCP\Util::addScript('files', 'fileactions'); OCP\Util::addScript('files', 'jquery.iframe-transport'); OCP\Util::addScript('files', 'jquery.fileupload'); $maxUploadFilesize = OCP\Util::maxUploadFilesize($path); $tmpl = new OCP\Template('files_sharing', 'public', 'base'); $tmpl->assign('displayName', \OCP\User::getDisplayName($shareOwner)); $tmpl->assign('filename', $file); $tmpl->assign('directory_path', $linkItem['file_target']); $tmpl->assign('mimetype', \OC\Files\Filesystem::getMimeType($path)); $tmpl->assign('dirToken', $linkItem['token']); $tmpl->assign('sharingToken', $token); $tmpl->assign('protected', isset($linkItem['share_with']) ? 'true' : 'false'); $urlLinkIdentifiers = (isset($token) ? '&t=' . $token : '') . (isset($_GET['dir']) ? '&dir=' . $_GET['dir'] : '') . (isset($_GET['file']) ? '&file=' . $_GET['file'] : ''); // Show file list if (\OC\Files\Filesystem::is_dir($path)) { $tmpl->assign('dir', $getPath); OCP\Util::addStyle('files', 'files'); OCP\Util::addStyle('files', 'upload'); OCP\Util::addScript('files', 'filesummary'); OCP\Util::addScript('files', 'breadcrumb'); OCP\Util::addScript('files', 'files');
/** * @PublicPage * @NoCSRFRequired * * @param string $token * @param string $path * @return TemplateResponse|RedirectResponse */ public function showShare($token, $path = '') { \OC_User::setIncognitoMode(true); // Check whether share exists $linkItem = Share::getShareByToken($token, false); if ($linkItem === false) { return new NotFoundResponse(); } $shareOwner = $linkItem['uid_owner']; $originalSharePath = $this->getPath($token); // Share is password protected - check whether the user is permitted to access the share if (isset($linkItem['share_with']) && !Helper::authenticate($linkItem)) { return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', array('token' => $token))); } if (Filesystem::isReadable($originalSharePath . $path)) { $getPath = Filesystem::normalizePath($path); $originalSharePath .= $path; } else { throw new OCP\Files\NotFoundException(); } $file = basename($originalSharePath); $shareTmpl = []; $shareTmpl['displayName'] = User::getDisplayName($shareOwner); $shareTmpl['filename'] = $file; $shareTmpl['directory_path'] = $linkItem['file_target']; $shareTmpl['mimetype'] = Filesystem::getMimeType($originalSharePath); $shareTmpl['previewSupported'] = \OC::$server->getPreviewManager()->isMimeSupported($shareTmpl['mimetype']); $shareTmpl['dirToken'] = $linkItem['token']; $shareTmpl['sharingToken'] = $token; $shareTmpl['server2serversharing'] = Helper::isOutgoingServer2serverShareEnabled(); $shareTmpl['protected'] = isset($linkItem['share_with']) ? 'true' : 'false'; $shareTmpl['dir'] = ''; $nonHumanFileSize = \OC\Files\Filesystem::filesize($originalSharePath); $shareTmpl['nonHumanFileSize'] = $nonHumanFileSize; $shareTmpl['fileSize'] = \OCP\Util::humanFileSize($nonHumanFileSize); // Show file list if (Filesystem::is_dir($originalSharePath)) { $shareTmpl['dir'] = $getPath; $maxUploadFilesize = Util::maxUploadFilesize($originalSharePath); $freeSpace = Util::freeSpace($originalSharePath); $uploadLimit = Util::uploadLimit(); $folder = new Template('files', 'list', ''); $folder->assign('dir', $getPath); $folder->assign('dirToken', $linkItem['token']); $folder->assign('permissions', \OCP\Constants::PERMISSION_READ); $folder->assign('isPublic', true); $folder->assign('publicUploadEnabled', 'no'); $folder->assign('uploadMaxFilesize', $maxUploadFilesize); $folder->assign('uploadMaxHumanFilesize', OCP\Util::humanFileSize($maxUploadFilesize)); $folder->assign('freeSpace', $freeSpace); $folder->assign('uploadLimit', $uploadLimit); // PHP upload limit $folder->assign('usedSpacePercent', 0); $folder->assign('trash', false); $shareTmpl['folder'] = $folder->fetchPage(); } $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', array('token' => $token)); $shareTmpl['maxSizeAnimateGif'] = $this->config->getSystemValue('max_filesize_animated_gifs_public_sharing', 10); $csp = new OCP\AppFramework\Http\ContentSecurityPolicy(); $csp->addAllowedFrameDomain('\'self\''); $response = new TemplateResponse($this->appName, 'public', $shareTmpl, 'base'); $response->setContentSecurityPolicy($csp); return $response; }
/** * @brief generate v3 UUID based on display name and site url * * @return string uuid */ public static function genUuid() { $defaults = new \OC_Defaults(); $hash = md5(\OCP\User::getDisplayName() . $defaults->getBaseUrl()); $hash = substr($hash, 0, 8) . '-' . substr($hash, 8, 4) . '-3' . substr($hash, 13, 3) . '-9' . substr($hash, 17, 3) . '-' . substr($hash, 20); return $hash; }
/** * @PublicPage * @NoCSRFRequired * * @param string $token * @param string $path * @return TemplateResponse */ public function showShare($token, $path = '') { \OC_User::setIncognitoMode(true); // Check whether share exists $linkItem = Share::getShareByToken($token, false); if ($linkItem === false) { return new TemplateResponse('core', '404', array(), 'guest'); } $linkItem = OCP\Share::getShareByToken($token, false); $shareOwner = $linkItem['uid_owner']; $originalSharePath = null; $rootLinkItem = OCP\Share::resolveReShare($linkItem); if (isset($rootLinkItem['uid_owner'])) { OCP\JSON::checkUserExists($rootLinkItem['uid_owner']); OC_Util::tearDownFS(); OC_Util::setupFS($rootLinkItem['uid_owner']); $originalSharePath = Filesystem::getPath($linkItem['file_source']); } // Share is password protected - check whether the user is permitted to access the share if (isset($linkItem['share_with']) && !Helper::authenticate($linkItem)) { return new RedirectResponse($this->urlGenerator->linkToRoute('files_sharing.sharecontroller.authenticate', array('token' => $token))); } if (Filesystem::isReadable($originalSharePath . $path)) { $getPath = Filesystem::normalizePath($path); $originalSharePath .= $path; } $file = basename($originalSharePath); $shareTmpl = array(); $shareTmpl['displayName'] = User::getDisplayName($shareOwner); $shareTmpl['filename'] = $file; $shareTmpl['directory_path'] = $linkItem['file_target']; $shareTmpl['mimetype'] = Filesystem::getMimeType($originalSharePath); $shareTmpl['dirToken'] = $linkItem['token']; $shareTmpl['sharingToken'] = $token; $shareTmpl['server2serversharing'] = Helper::isOutgoingServer2serverShareEnabled(); $shareTmpl['protected'] = isset($linkItem['share_with']) ? 'true' : 'false'; $shareTmpl['dir'] = ''; $shareTmpl['fileSize'] = \OCP\Util::humanFileSize(\OC\Files\Filesystem::filesize($originalSharePath)); // Show file list if (Filesystem::is_dir($originalSharePath)) { $shareTmpl['dir'] = $getPath; $files = array(); $maxUploadFilesize = Util::maxUploadFilesize($originalSharePath); $freeSpace = Util::freeSpace($originalSharePath); $uploadLimit = Util::uploadLimit(); $folder = new Template('files', 'list', ''); $folder->assign('dir', $getPath); $folder->assign('dirToken', $linkItem['token']); $folder->assign('permissions', \OCP\Constants::PERMISSION_READ); $folder->assign('isPublic', true); $folder->assign('publicUploadEnabled', 'no'); $folder->assign('files', $files); $folder->assign('uploadMaxFilesize', $maxUploadFilesize); $folder->assign('uploadMaxHumanFilesize', OCP\Util::humanFileSize($maxUploadFilesize)); $folder->assign('freeSpace', $freeSpace); $folder->assign('uploadLimit', $uploadLimit); // PHP upload limit $folder->assign('usedSpacePercent', 0); $folder->assign('trash', false); $shareTmpl['folder'] = $folder->fetchPage(); } $shareTmpl['downloadURL'] = $this->urlGenerator->linkToRouteAbsolute('files_sharing.sharecontroller.downloadShare', array('token' => $token)); return new TemplateResponse($this->appName, 'public', $shareTmpl, 'base'); }
/** * @brief use to create HTML emails and send them * @param $eventid The event id * @param $location The location * @param $description The description * @param $dtstart The start date * @param $dtend The end date * */ public static function sendEmails($eventid, $summary, $location, $description, $dtstart, $dtend) { $user = \OCP\User::getUser(); $eventsharees = array(); $eventShareesNames = array(); $emails = array(); $sharedwithByEvent = \OCP\Share::getItemShared('event', $eventid); if (is_array($sharedwithByEvent)) { foreach ($sharedwithByEvent as $share) { if ($share['share_type'] === \OCP\Share::SHARE_TYPE_USER || $share['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) { $eventsharees[] = $share; } } foreach ($eventsharees as $sharee) { $shwth = $sharee['share_with']; if ($sharee['share_type'] == \OCP\Share::SHARE_TYPE_GROUP) { foreach (OC_Group::usersInGroup($shwth) as $u) { if (!in_array($u, $eventShareesNames)) { $eventShareesNames[] = $u; } } } else { if (!in_array($shwth, $eventShareesNames)) { $eventShareesNames[] = $shwth; } } } } foreach ($eventShareesNames as $name) { $result = OC_Calendar_Calendar::getUsersEmails($name); $emails[] = $result; } $adminmail = \OCP\Util::getDefaultEmailAddress('no-reply'); foreach ($emails as $email) { if ($email === null) { continue; } $subject = 'Calendar Event Shared'; $message = '<html><body>'; $message .= '<table style="border:1px solid black;" cellpadding="10">'; $message .= "<tr style='background: #eee;'><td colspan='2'><strong>" . $user . '</strong><strong> has shared with you an event</strong></td></tr>'; $message .= '<tr><td><strong>Summary:</strong> </td><td>' . \OCP\Util::sanitizeHTML($summary) . '</td></tr>'; $message .= '<tr><td><strong>Location:</strong> </td><td>' . \OCP\Util::sanitizeHTML($location) . '</td></tr>'; $message .= '<tr><td><strong>Description:</strong> </td><td>' . \OCP\Util::sanitizeHTML($description) . '</td></tr>'; $message .= '</table>'; $message .= '</body></html>'; OCP\Util::sendMail($email, \OCP\User::getDisplayName(), $subject, $message, $adminmail, $user, $html = 1); } }
private function getPublicEvent($itemSource, $shareOwner, $token) { $itemSource = CalendarApp::validateItemSource($itemSource, CalendarApp::SHAREEVENTPREFIX); $data = CalendarApp::getEventObject($itemSource, false, false); $object = VObject::parse($data['calendardata']); $vevent = $object->VEVENT; $object = Object::cleanByAccessClass($itemSource, $object); $accessclass = $vevent->getAsString('CLASS'); if ($accessclass == 'PRIVATE') { header('HTTP/1.0 404 Not Found'); $response = new TemplateResponse('core', '404', '', 'guest'); return $response; } $permissions = CalendarApp::getPermissions($itemSource, CalendarApp::EVENT, $accessclass); $dtstart = $vevent->DTSTART; $dtend = Object::getDTEndFromVEvent($vevent); $dtstartType = $vevent->DTSTART->getValueType(); if ($dtstartType == 'DATE') { $startdate = $dtstart->getDateTime()->format('d-m-Y'); $starttime = ''; $enddate = $dtend->getDateTime()->modify('-1 day')->format('d-m-Y'); $endtime = ''; $choosenDate = $choosenDate + 3600 * 24; $allday = true; } if ($dtstartType == 'DATE-TIME') { $startdate = $dtstart->getDateTime()->format('d-m-Y'); $starttime = $dtstart->getDateTime()->format('H:i'); $enddate = $dtend->getDateTime()->format('d-m-Y'); $endtime = $dtend->getDateTime()->format('H:i'); $allday = false; } $summary = strtr($vevent->getAsString('SUMMARY'), array('\\,' => ',', '\\;' => ';')); $location = strtr($vevent->getAsString('LOCATION'), array('\\,' => ',', '\\;' => ';')); $categories = $vevent->getAsArray('CATEGORIES'); $description = strtr($vevent->getAsString('DESCRIPTION'), array('\\,' => ',', '\\;' => ';')); $link = strtr($vevent->getAsString('URL'), array('\\,' => ',', '\\;' => ';')); $last_modified = $vevent->__get('LAST-MODIFIED'); if ($last_modified) { $lastmodified = $last_modified->getDateTime()->format('U'); } else { $lastmodified = 0; } $repeatInfo = array(); $repeat['repeat'] = ''; if ($data['repeating'] == 1) { $rrule = explode(';', $vevent->getAsString('RRULE')); $rrulearr = array(); $repeat['repeat_rules'] = ''; foreach ($rrule as $rule) { list($attr, $val) = explode('=', $rule); if ($attr != 'COUNT' && $attr !== 'UNTIL') { if ($repeat['repeat_rules'] === '') { $repeat['repeat_rules'] = $attr . '=' . $val; } else { $repeat['repeat_rules'] .= ';' . $attr . '=' . $val; } } if ($attr === 'COUNT' || $attr !== 'UNTIL') { $rrulearr[$attr] = $val; } } if (array_key_exists('COUNT', $rrulearr)) { $repeat['end'] = 'count'; $repeat['count'] = $rrulearr['COUNT']; } elseif (array_key_exists('UNTIL', $rrulearr)) { $repeat['end'] = 'date'; $endbydate_day = substr($rrulearr['UNTIL'], 6, 2); $endbydate_month = substr($rrulearr['UNTIL'], 4, 2); $endbydate_year = substr($rrulearr['UNTIL'], 0, 4); $repeat['date'] = $endbydate_day . '-' . $endbydate_month . '-' . $endbydate_year; } else { $repeat['end'] = 'never'; } $repeat_end_options = CalendarApp::getEndOptions(); if ($repeat['end'] === 'count') { $repeatInfo['end'] = $this->l10n->t('after') . ' ' . $repeat['count'] . ' ' . $this->l10n->t('Events'); } if ($repeat['end'] === 'date') { $repeatInfo['end'] = $repeat['date']; } if ($repeat['end'] === 'never') { $repeatInfo['end'] = $repeat_end_options[$repeat['end']]; } } else { $repeat['repeat'] = 'doesnotrepeat'; } $calendar_options[0]['id'] = $data['calendarid']; $access_class_options = CalendarApp::getAccessClassOptions(); $aOExdate = ''; if ($vevent->EXDATE) { $timezone = CalendarApp::getTimezone(); foreach ($vevent->EXDATE as $param) { $param = new \DateTime($param); $aOExdate[$param->format('U')] = $param->format('d-m-Y'); } } $timezone = \OC::$server->getSession()->get('public_link_timezone'); $sCat = ''; if (is_array($categories) && count($categories) > 0) { $sCat = $categories; } $params = ['eventid' => $itemSource, 'appname' => $this->appName, 'permissions' => $permissions, 'lastmodified' => $lastmodified, 'exDate' => $aOExdate, 'sharingToken' => $token, 'token' => $token, 'calendar_options' => $calendar_options, 'access_class_options' => $access_class_options, 'title' => $summary, 'accessclass' => $accessclass, 'location' => $location, 'calendar' => $data['calendarid'], 'timezone' => $timezone, 'uidOwner' => $shareOwner, 'displayName' => \OCP\User::getDisplayName($shareOwner), 'allday' => $allday, 'startdate' => $startdate, 'starttime' => $starttime, 'enddate' => $enddate, 'endtime' => $endtime, 'description' => $description, 'link' => $link, 'repeat_rules' => isset($repeat['repeat_rules']) ? $repeat['repeat_rules'] : '', 'repeat' => $repeat['repeat'], 'repeatInfo' => $repeat['repeat'] != 'doesnotrepeat' ? $repeatInfo : '', 'categories' => $sCat]; $response = new TemplateResponse($this->appName, 'publicevent', $params, 'base'); return $response; }
/** * get share from all files in a given folder (non-recursive) * @param array $params contains 'path' to the folder * @return \OC_OCS_Result */ private static function getSharesFromFolder($params) { $path = $params['path']; $view = new \OC\Files\View('/' . \OCP\User::getUser() . '/files'); if (!$view->is_dir($path)) { return new \OC_OCS_Result(null, 400, "not a directory"); } $content = $view->getDirectoryContent($path); $result = array(); foreach ($content as $file) { // workaround because folders are named 'dir' in this context $itemType = $file['type'] === 'file' ? 'file' : 'folder'; $share = \OCP\Share::getItemShared($itemType, $file['fileid']); if ($share) { $receivedFrom = \OCP\Share::getItemSharedWithBySource($itemType, $file['fileid']); reset($share); $key = key($share); if ($receivedFrom) { $share[$key]['received_from'] = $receivedFrom['uid_owner']; $share[$key]['received_from_displayname'] = \OCP\User::getDisplayName($receivedFrom['uid_owner']); } $result = array_merge($result, $share); } } return new \OC_OCS_Result($result); }
/** * collect all share information, either of a specific share or all * shares for a given path * @param array $params * @return \OC_OCS_Result */ private static function collectShares($params) { $itemSource = $params['itemSource']; $itemType = $params['itemType']; $getSpecificShare = isset($params['specificShare']) ? $params['specificShare'] : false; if ($itemSource !== null) { $shares = \OCP\Share::getItemShared($itemType, $itemSource); $receivedFrom = \OCP\Share::getItemSharedWithBySource($itemType, $itemSource); // if a specific share was specified only return this one if ($getSpecificShare === true) { $shareEE = array(); foreach ($shares as $share) { if ($share['id'] === (int) $params['id']) { $shareEE[] = $share; break; } } if ($params['reshare'] === true) { self::checkReShare($itemSource, $itemType); if (count(self::$sItems) > 0) { $shares = array_merge($shareEE, self::$sItems); } } } if ($receivedFrom) { foreach ($shares as $key => $share) { $shares[$key]['received_from'] = $receivedFrom['uid_owner']; $shares[$key]['received_from_displayname'] = \OCP\User::getDisplayName($receivedFrom['uid_owner']); } } } else { $shares = null; } if ($shares === null || empty($shares)) { return new \OC_OCS_Result(null, 404, 'share doesn\'t exist'); } else { return new \OC_OCS_Result($shares); } }
public function testGetDisplayNamePublicAPI() { $access = $this->getAccessMock(); $access->expects($this->any())->method('username2dn')->will($this->returnCallback(function ($uid) { switch ($uid) { case 'gunslinger': return 'dnOfRoland,dc=test'; break; case 'formerUser': return 'dnOfFormerUser,dc=test'; break; case 'newyorker': return 'dnOfNewYorker,dc=test'; break; case 'ladyofshadows': return 'dnOfLadyOfShadows,dc=test'; break; default: return false; } })); $this->prepareAccessForGetDisplayName($access); $backend = new UserLDAP($access, $this->getMock('\\OCP\\IConfig')); $this->prepareMockForUserExists($access); $access->connection->expects($this->any())->method('getConnectionResource')->will($this->returnCallback(function () { return true; })); \OC_User::useBackend($backend); //with displayName $result = \OCP\User::getDisplayName('gunslinger'); $this->assertEquals('Roland Deschain', $result); //empty displayname retrieved $result = \OCP\User::getDisplayName('newyorker'); $this->assertEquals('newyorker', $result); }
public function testGetDisplayNamePublicAPI() { $access = $this->getAccessMock(); $this->prepareAccessForGetDisplayName($access); $backend = new UserLDAP($access); $this->prepareMockForUserExists($access); \OC_User::useBackend($backend); //with displayName $result = \OCP\User::getDisplayName('gunslinger'); $this->assertEquals('Roland Deschain', $result); //empty displayname retrieved $result = \OCP\User::getDisplayName('newyorker'); $this->assertEquals('newyorker', $result); }
/** * Prepares a user name parameter for usage * * Add an avatar to usernames * * @param string $param * @param bool $highlightParams * @return string */ protected function prepareUserParam($param, $highlightParams) { $displayName = User::getDisplayName($param); $param = Util::sanitizeHTML($param); $displayName = Util::sanitizeHTML($displayName); if ($highlightParams) { return '<div class="avatar" data-user="******"></div>' . '<strong>' . $displayName . '</strong>'; } else { return $displayName; } }
/** * @brief Show a specific event in the activities * @param array $event An array with all the event data in it */ public static function show($event) { $l = \OC_L10N::get('lib'); $user = $event['user']; if (!isset($event['isGrouped'])) { $event['isGrouped'] = false; } $formattedDate = \OCP\Util::formatDate($event['timestamp']); $formattedTimestamp = \OCP\relative_modified_date($event['timestamp']); $displayName = \OCP\User::getDisplayName($user); // TODO: move into template? echo '<div class="box">'; echo '<div class="header">'; echo '<span class="avatar" data-user="******"></span>'; echo '<span>'; echo '<span class="user">' . \OC_Util::sanitizeHTML($displayName) . '</span>'; echo '<span class="activitytime tooltip" title="' . \OC_Util::sanitizeHTML($formattedDate) . '">' . \OC_Util::sanitizeHTML($formattedTimestamp) . '</span>'; echo '<span class="appname">' . \OC_Util::sanitizeHTML($event['app']) . '</span>'; echo '</span>'; echo '</div>'; echo '<div class="messagecontainer">'; if ($event['isGrouped']) { $count = 0; echo '<ul class="activitysubject grouped">'; foreach ($event['events'] as $subEvent) { echo '<li>'; if ($subEvent['link'] != '') { echo '<a href="' . $subEvent['link'] . '">'; } echo \OC_Util::sanitizeHTML($subEvent['subject']); if ($subEvent['link'] != '') { echo '</a>'; } echo '</li>'; $count++; if ($count > 5) { echo '<li class="more">' . $l->n('%n more...', '%n more...', count($event['events']) - $count) . '</li>'; break; } } echo '</ul>'; } else { if ($event['link'] != '') { echo '<a href="' . $event['link'] . '">'; } echo '<div class="activitysubject">' . \OC_Util::sanitizeHTML($event['subject']) . '</div>'; echo '<div class="activitymessage">' . \OC_Util::sanitizeHTML($event['message']) . '</div>'; } $rootView = new \OC\Files\View(''); if ($event['file'] !== null) { $exist = $rootView->file_exists('/' . $user . '/files' . $event['file']); unset($rootView); // show a preview image if the file still exists if ($exist) { echo '<img class="preview" src="' . \OCP\Util::linkToRoute('core_ajax_preview', array('file' => $event['file'], 'x' => 150, 'y' => 150)) . '" />'; } } if (!$event['isGrouped'] && $event['link'] != '') { echo '</a>'; } echo '</div>'; // end messagecontainer echo '</div>'; // end box }