/** * @param IEvent $event * @param string $parameter The parameter to be formatted * @param bool $allowHtml Should HTML be used to format the parameter? * @param bool $verbose Should paths, names, etc be shortened or full length * @return string The formatted parameter */ public function format(IEvent $event, $parameter, $allowHtml, $verbose = false) { // If the username is empty, the action has been performed by a remote // user, or via a public share. We don't know the username in that case if ($parameter === '') { if ($allowHtml === null) { return '<user display-name="' . Util::sanitizeHTML($this->l->t('"remote user"')) . '">' . Util::sanitizeHTML('') . '</user>'; } if ($allowHtml) { return '<strong>' . $this->l->t('"remote user"') . '</strong>'; } else { return $this->l->t('"remote user"'); } } $user = $this->manager->get($parameter); $displayName = $user ? $user->getDisplayName() : $parameter; $parameter = Util::sanitizeHTML($parameter); if ($allowHtml === null) { return '<user display-name="' . Util::sanitizeHTML($displayName) . '">' . Util::sanitizeHTML($parameter) . '</user>'; } if ($allowHtml) { $avatarPlaceholder = ''; if ($this->config->getSystemValue('enable_avatars', true)) { $avatarPlaceholder = '<div class="avatar" data-user="******"></div>'; } return $avatarPlaceholder . '<strong>' . Util::sanitizeHTML($displayName) . '</strong>'; } else { return $displayName; } }
/** * Asynchronously scan data that are written to the file * @param string $path * @param string $mode * @return resource | bool */ public function fopen($path, $mode) { $stream = $this->storage->fopen($path, $mode); if (is_resource($stream) && $this->isWritingMode($mode)) { try { $scanner = $this->scannerFactory->getScanner(); $scanner->initAsyncScan(); return CallBackWrapper::wrap($stream, null, function ($data) use($scanner) { $scanner->onAsyncData($data); }, function () use($scanner, $path) { $status = $scanner->completeAsyncScan(); if (intval($status->getNumericStatus()) === \OCA\Files_Antivirus\Status::SCANRESULT_INFECTED) { //prevent from going to trashbin if (App::isEnabled('files_trashbin')) { \OCA\Files_Trashbin\Storage::preRenameHook([]); } $owner = $this->getOwner($path); $this->unlink($path); if (App::isEnabled('files_trashbin')) { \OCA\Files_Trashbin\Storage::postRenameHook([]); } \OC::$server->getActivityManager()->publishActivity('files_antivirus', Activity::SUBJECT_VIRUS_DETECTED, [$path, $status->getDetails()], Activity::MESSAGE_FILE_DELETED, [], $path, '', $owner, Activity::TYPE_VIRUS_DETECTED, Activity::PRIORITY_HIGH); throw new InvalidContentException($this->l10n->t('Virus %s is detected in the file. Upload cannot be completed.', $status->getDetails())); } }); } catch (\Exception $e) { $message = implode(' ', [__CLASS__, __METHOD__, $e->getMessage()]); $this->logger->warning($message); } } return $stream; }
/** * @NoAdminRequired * @UseSession * * @param string $oldPassword * @param string $newPassword * @return DataResponse */ public function updatePrivateKeyPassword($oldPassword, $newPassword) { $result = false; $uid = $this->userSession->getUser()->getUID(); $errorMessage = $this->l->t('Could not update the private key password.'); //check if password is correct $passwordCorrect = $this->userManager->checkPassword($uid, $newPassword); if ($passwordCorrect !== false) { $encryptedKey = $this->keyManager->getPrivateKey($uid); $decryptedKey = $this->crypt->decryptPrivateKey($encryptedKey, $oldPassword); if ($decryptedKey) { $encryptedKey = $this->crypt->symmetricEncryptFileContent($decryptedKey, $newPassword); $header = $this->crypt->generateHeader(); if ($encryptedKey) { $this->keyManager->setPrivateKey($uid, $header . $encryptedKey); $this->session->setPrivateKey($decryptedKey); $result = true; } } else { $errorMessage = $this->l->t('The old password was not correct, please try again.'); } } else { $errorMessage = $this->l->t('The current log-in password was not correct, please try again.'); } if ($result === true) { $this->session->setStatus(Session::INIT_SUCCESSFUL); return new DataResponse(['message' => (string) $this->l->t('Private key password successfully updated.')]); } else { return new DataResponse(['message' => (string) $errorMessage], Http::STATUS_BAD_REQUEST); } }
/** * set log level for logger * * @param int $level * @return JSONResponse */ public function setLogLevel($level) { if ($level < 0 || $level > 4) { return new JSONResponse(['message' => (string) $this->l10n->t('log-level out of allowed range')], Http::STATUS_BAD_REQUEST); } $this->config->setSystemValue('loglevel', $level); return new JSONResponse(['level' => $level]); }
private function validatePrice() { $price = $this->request->getParam("price"); $name = $this->l10n->t("Price"); if (!$this->validator->validateRequired($name, $price)) { return; } $this->validator->validateFloat($name, $price); }
public function __construct(IL10N $l, OpenStack $openstackAuth, Rackspace $rackspaceAuth) { $this->setIdentifier('swift')->addIdentifierAlias('\\OC\\Files\\Storage\\Swift')->setStorageClass('\\OCA\\Files_External\\Lib\\Storage\\Swift')->setText($l->t('OpenStack Object Storage'))->addParameters([(new DefinitionParameter('service_name', $l->t('Service name')))->setFlag(DefinitionParameter::FLAG_OPTIONAL), (new DefinitionParameter('region', $l->t('Region')))->setFlag(DefinitionParameter::FLAG_OPTIONAL), new DefinitionParameter('bucket', $l->t('Bucket')), (new DefinitionParameter('timeout', $l->t('Request timeout (seconds)')))->setFlag(DefinitionParameter::FLAG_OPTIONAL)])->addAuthScheme(AuthMechanism::SCHEME_OPENSTACK)->setLegacyAuthMechanismCallback(function (array $params) use($openstackAuth, $rackspaceAuth) { if (isset($params['options']['key']) && $params['options']['key']) { return $rackspaceAuth; } return $openstackAuth; }); }
/** * @param string $id * @return DataResponse */ public function destroy($id) { $group = $this->groupManager->get($id); if ($group) { if ($group->delete()) { return new DataResponse(array('status' => 'success', 'data' => array('groupname' => $id)), Http::STATUS_NO_CONTENT); } } return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Unable to delete group.'))), Http::STATUS_FORBIDDEN); }
/** * Log error message and return a response which can be displayed to the user * * @param \OCP\AppFramework\Controller $controller * @param string $methodName * @param \Exception $exception * @return JSONResponse */ public function afterException($controller, $methodName, \Exception $exception) { $this->logger->error($exception->getMessage(), ['app' => $this->appName]); if ($exception instanceof HintException) { $message = $exception->getHint(); } else { $message = $this->l->t('Unknown error'); } return new JSONResponse(['message' => $message], Http::STATUS_BAD_REQUEST); }
/** * Save Parameters * @param string $avMode - antivirus mode * @param string $avSocket - path to socket (Socket mode) * @param string $avHost - antivirus url * @param int $avPort - port * @param string $avCmdOptions - extra command line options * @param int $avChunkSize - Size of one portion * @param string $avPath - path to antivirus executable (Executable mode) * @param string $avInfectedAction - action performed on infected files * @return JSONResponse */ public function save($avMode, $avSocket, $avHost, $avPort, $avCmdOptions, $avChunkSize, $avPath, $avInfectedAction) { $this->settings->setAvMode($avMode); $this->settings->setAvSocket($avSocket); $this->settings->setAvHost($avHost); $this->settings->setAvPort($avPort); $this->settings->setAvCmdOptions($avCmdOptions); $this->settings->setAvChunkSize($avChunkSize); $this->settings->setAvPath($avPath); $this->settings->setAvInfectedAction($avInfectedAction); return new JSONResponse(array('data' => array('message' => (string) $this->l10n->t('Saved')), 'status' => 'success', 'settings' => $this->settings->getAllValues())); }
/** * @param \OCP\IL10N $l * @return array Array "stringID of the type" => "translated string description for the setting" */ public function getNotificationTypes(\OCP\IL10N $l) { if (isset($this->notificationTypes[$l->getLanguageCode()])) { return $this->notificationTypes[$l->getLanguageCode()]; } $notificationTypes = array(self::TYPE_SHARED => $l->t('A file or folder has been <strong>shared</strong>'), self::TYPE_SHARE_CREATED => $l->t('A new file or folder has been <strong>created</strong>'), self::TYPE_SHARE_CHANGED => $l->t('A file or folder has been <strong>changed</strong>'), self::TYPE_SHARE_DELETED => $l->t('A file or folder has been <strong>deleted</strong>'), self::TYPE_SHARE_RESTORED => $l->t('A file or folder has been <strong>restored</strong>')); // Allow other apps to add new notification types $additionalNotificationTypes = $this->activityManager->getNotificationTypes($l->getLanguageCode()); $notificationTypes = array_merge($notificationTypes, $additionalNotificationTypes); $this->notificationTypes[$l->getLanguageCode()] = $notificationTypes; return $notificationTypes; }
/** * @param IEvent $event * @param string $parameter The parameter to be formatted * @return string The formatted parameter */ public function format(IEvent $event, $parameter) { // If the username is empty, the action has been performed by a remote // user, or via a public share. We don't know the username in that case if ($parameter === '') { return '<user display-name="' . Util::sanitizeHTML($this->l->t('"remote user"')) . '">' . Util::sanitizeHTML('') . '</user>'; } $user = $this->manager->get($parameter); $displayName = $user ? $user->getDisplayName() : $parameter; $parameter = Util::sanitizeHTML($parameter); return '<user display-name="' . Util::sanitizeHTML($displayName) . '">' . Util::sanitizeHTML($parameter) . '</user>'; }
/** * @ControllerManaged * * @param boolean $scheduled */ protected function setBackupScheduled($scheduled) { $statusContainer = $this->backupService->createStatusInformation(); if ($statusContainer->getOverallStatus() == StatusContainer::ERROR) { throw new EasyBackupException($this->trans->t('Not all preconditions are met, backup cannot be scheduled')); } $this->configService->setBackupScheduled($scheduled); if ($scheduled) { $this->backupService->scheduleBackupJob(); } else { $this->backupService->unScheduleBackupJob(); } }
/** * add server to the list of trusted ownCloud servers * * @param string $url * @return int * @throws HintException */ public function addServer($url) { $hash = $this->hash($url); $query = $this->connection->getQueryBuilder(); $query->insert($this->dbTable)->values(['url' => $query->createParameter('url'), 'url_hash' => $query->createParameter('url_hash')])->setParameter('url', $url)->setParameter('url_hash', $hash); $result = $query->execute(); if ($result) { return (int) $this->connection->lastInsertId('*PREFIX*' . $this->dbTable); } else { $message = 'Internal failure, Could not add ownCloud as trusted server: ' . $url; $message_t = $this->l->t('Could not add server'); throw new HintException($message, $message_t); } }
/** * Get all available categories * @return array */ public function listCategories() { $categories = array(array('id' => 0, 'displayName' => (string) $this->l10n->t('Enabled')), array('id' => 1, 'displayName' => (string) $this->l10n->t('Not enabled'))); if ($this->config->getSystemValue('appstoreenabled', true)) { $categories[] = array('id' => 2, 'displayName' => (string) $this->l10n->t('Recommended')); // apps from external repo via OCS $ocs = \OC_OCSClient::getCategories(); foreach ($ocs as $k => $v) { $categories[] = array('id' => $k, 'displayName' => str_replace('ownCloud ', '', $v)); } } $categories['status'] = 'success'; return $categories; }
public function __construct(IL10N $l, ISession $session, ICrypto $crypto) { $this->session = $session; $this->crypto = $crypto; $this->setIdentifier('password::sessioncredentials')->setScheme(self::SCHEME_PASSWORD)->setText($l->t('Session credentials'))->addParameters([]); \OCP\Util::connectHook('OC_User', 'post_login', $this, 'authenticate'); }
/** * Set the mail address of a user * * @NoAdminRequired * @NoSubadminRequired * * @param string $id * @param string $mailAddress * @return DataResponse */ public function setMailAddress($id, $mailAddress) { $userId = $this->userSession->getUser()->getUID(); if ($userId !== $id && !$this->isAdmin && !$this->subAdminFactory->isUserAccessible($userId, $id)) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Forbidden'))), Http::STATUS_FORBIDDEN); } if ($mailAddress !== '' && !$this->mailer->validateMailAddress($mailAddress)) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Invalid mail address'))), Http::STATUS_UNPROCESSABLE_ENTITY); } $user = $this->userManager->get($id); if (!$user) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Invalid user'))), Http::STATUS_UNPROCESSABLE_ENTITY); } // this is the only permission a backend provides and is also used // for the permission of setting a email address if (!$user->canChangeDisplayName()) { return new DataResponse(array('status' => 'error', 'data' => array('message' => (string) $this->l10n->t('Unable to change mail address'))), Http::STATUS_FORBIDDEN); } // delete user value if email address is empty if ($mailAddress === '') { $this->config->deleteUserValue($id, 'settings', 'email'); } else { $this->config->setUserValue($id, 'settings', 'email', $mailAddress); } return new DataResponse(array('status' => 'success', 'data' => array('username' => $id, 'mailAddress' => $mailAddress, 'message' => (string) $this->l10n->t('Email saved'))), Http::STATUS_OK); }
/** * * @param string $restoreConfig * JSON-Encoded */ public function scheduleRestoreJob($restoreConfig) { $c = json_decode($restoreConfig, true); $dataDir = $this->configService->getDataDir(); // Get the parent of data directory $dataDir = substr($dataDir, 0, strrpos($dataDir, DIRECTORY_SEPARATOR)); $logfileName = $this->configService->getLogfileName(); $restoreHostName = $c['backupuser'] . '@' . $c['backupserver']; $keyFileName = $this->configService->getPrivateKeyFilename(); $knownHostsFileName = $this->configService->getKnownHostsFileName(); $restoreTargetFolder = $this->configService->getDataDir(); $sshCommand = "ssh -q -i \"{$keyFileName}\" -o StrictHostKeyChecking=no -o UserKnownHostsFile={$knownHostsFileName}"; $rsyncOptions = "-rtgov -e '{$sshCommand}' --numeric-ids --omit-dir-times"; foreach ($c['include'] as $include) { $rsyncOptions .= " --include='{$include}'"; } foreach ($c['exclude'] as $exclude) { $rsyncOptions .= " --exclude='{$exclude}'"; } $rsyncCommand = "rsync {$rsyncOptions} {$restoreHostName}:" . $c['restorebase'] . " {$dataDir} "; $command = "{$rsyncCommand} >> {$logfileName} 2>&1"; $this->configService->setRestoreCommand($command); $this->configService->register($this->runOnceJob, '\\OCA\\EasyBackup\\RestoreCommandHandler'); $date = date('Y-m-d H:i:s e'); file_put_contents($logfileName, "[{$date}] " . $this->trans->t('Restore job will be executed with next CRON') . "\n", FILE_APPEND); }
/** * Gathers system information like database type and does * a few system checks. * * @return array of system info, including an "errors" value * in case of errors/warnings */ public function getSystemInfo($allowAllDatabases = false) { $databases = $this->getSupportedDatabases($allowAllDatabases); $dataDir = $this->config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data'); $errors = array(); // Create data directory to test whether the .htaccess works // Notice that this is not necessarily the same data directory as the one // that will effectively be used. @mkdir($dataDir); $htAccessWorking = true; if (is_dir($dataDir) && is_writable($dataDir)) { // Protect data directory here, so we can test if the protection is working \OC\Setup::protectDataDirectory(); try { $util = new \OC_Util(); $htAccessWorking = $util->isHtaccessWorking(\OC::$server->getConfig()); } catch (\OC\HintException $e) { $errors[] = array('error' => $e->getMessage(), 'hint' => $e->getHint()); $htAccessWorking = false; } } if (\OC_Util::runningOnMac()) { $errors[] = array('error' => $this->l10n->t('Mac OS X is not supported and %s will not work properly on this platform. ' . 'Use it at your own risk! ', $this->defaults->getName()), 'hint' => $this->l10n->t('For the best results, please consider using a GNU/Linux server instead.')); } if ($this->iniWrapper->getString('open_basedir') !== '' && PHP_INT_SIZE === 4) { $errors[] = array('error' => $this->l10n->t('It seems that this %s instance is running on a 32-bit PHP environment and the open_basedir has been configured in php.ini. ' . 'This will lead to problems with files over 4 GB and is highly discouraged.', $this->defaults->getName()), 'hint' => $this->l10n->t('Please remove the open_basedir setting within your php.ini or switch to 64-bit PHP.')); } return array('hasSQLite' => isset($databases['sqlite']), 'hasMySQL' => isset($databases['mysql']), 'hasPostgreSQL' => isset($databases['pgsql']), 'hasOracle' => isset($databases['oci']), 'databases' => $databases, 'directory' => $dataDir, 'htaccessWorking' => $htAccessWorking, 'errors' => $errors); }
/** * Returns a list of grouped parameters * * 2 parameters are joined by "and": * => A and B * Up to 5 parameters are joined by "," and "and": * => A, B, C, D and E * More than 5 parameters are joined by "," and trimmed: * => A, B, C and #n more * * @param array $parameterList * @param array $plainParameterList * @param bool $highlightParams * @return string */ protected function joinParameterList($parameterList, $plainParameterList, $highlightParams) { if (empty($parameterList)) { return ''; } $count = sizeof($parameterList); $lastItem = array_pop($parameterList); if ($count === 1) { return $lastItem; } else { if ($count === 2) { $firstItem = array_pop($parameterList); return $this->l->t('%s and %s', array($firstItem, $lastItem)); } else { if ($count <= 5) { $list = implode($this->l->t(', '), $parameterList); return $this->l->t('%s and %s', array($list, $lastItem)); } } } $firstParams = array_slice($parameterList, 0, 3); $firstList = implode($this->l->t(', '), $firstParams); $trimmedParams = array_slice($plainParameterList, 3); $trimmedList = implode($this->l->t(', '), $trimmedParams); if ($highlightParams) { return $this->l->n('%s and <strong %s>%n more</strong>', '%s and <strong %s>%n more</strong>', $count - 3, array($firstList, 'class="has-tooltip" title="' . Util::sanitizeHTML($trimmedList) . '"')); } return $this->l->n('%s and %n more', '%s and %n more', $count - 3, array($firstList)); }
/** * @param string $user * @throws \Exception */ protected function sendEmail($user) { if (!$this->userManager->userExists($user)) { throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.')); } $email = $this->config->getUserValue($user, 'settings', 'email'); if (empty($email)) { throw new \Exception($this->l10n->t('Couldn\'t send reset email because there is no ' . 'email address for this username. Please ' . 'contact your administrator.')); } $token = $this->secureRandom->getMediumStrengthGenerator()->generate(21, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER); $this->config->setUserValue($user, 'owncloud', 'lostpassword', $token); $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token)); $tmpl = new \OC_Template('core/lostpassword', 'email'); $tmpl->assign('link', $link, false); $msg = $tmpl->fetchPage(); try { $message = $this->mailer->createMessage(); $message->setTo([$email => $user]); $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()])); $message->setPlainBody($msg); $message->setFrom([$this->from => $this->defaults->getName()]); $this->mailer->send($message); } catch (\Exception $e) { throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please contact your administrator.')); } }
/** * Check if the used SSL lib is outdated. Older OpenSSL and NSS versions do * have multiple bugs which likely lead to problems in combination with * functionality required by ownCloud such as SNI. * * @link https://github.com/owncloud/core/issues/17446#issuecomment-122877546 * @link https://bugzilla.redhat.com/show_bug.cgi?id=1241172 * @return string */ private function isUsedTlsLibOutdated() { $versionString = $this->getCurlVersion(); if (isset($versionString['ssl_version'])) { $versionString = $versionString['ssl_version']; } else { return ''; } $features = (string) $this->l10n->t('installing and updating apps via the app store or Federated Cloud Sharing'); if (OC_Util::getEditionString() !== '') { $features = (string) $this->l10n->t('Federated Cloud Sharing'); } // Check if at least OpenSSL after 1.01d or 1.0.2b if (strpos($versionString, 'OpenSSL/') === 0) { $majorVersion = substr($versionString, 8, 5); $patchRelease = substr($versionString, 13, 6); if ($majorVersion === '1.0.1' && ord($patchRelease) < ord('d') || $majorVersion === '1.0.2' && ord($patchRelease) < ord('b')) { return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['OpenSSL', $versionString, $features]); } } // Check if NSS and perform heuristic check if (strpos($versionString, 'NSS/') === 0) { try { $firstClient = $this->clientService->newClient(); $firstClient->get('https://www.owncloud.org/'); $secondClient = $this->clientService->newClient(); $secondClient->get('https://owncloud.org/'); } catch (ClientException $e) { if ($e->getResponse()->getStatusCode() === 400) { return (string) $this->l10n->t('cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably.', ['NSS', $versionString, $features]); } } } return ''; }
/** * start migration * * @return array */ public function startMigration() { // allow as long execution on the web server as possible set_time_limit(0); try { $migration = $this->getMigration($this->config, $this->view, $this->connection, $this->logger); $migration->reorganizeSystemFolderStructure(); $migration->updateDB(); foreach ($this->userManager->getBackends() as $backend) { $limit = 500; $offset = 0; do { $users = $backend->getUsers('', $limit, $offset); foreach ($users as $user) { $migration->reorganizeFolderStructureForUser($user); } $offset += $limit; } while (count($users) >= $limit); } $migration->finalCleanUp(); } catch (\Exception $e) { return ['data' => ['message' => (string) $this->l10n->t('A problem occurred, please check your log files (Error: %s)', [$e->getMessage()])], 'status' => 'error']; } return ['data' => ['message' => (string) $this->l10n->t('Migration Completed')], 'status' => 'success']; }
/** * Validate if the expiration date fits the system settings * * @param \DateTime $expireDate The current expiration date (can be null) * @return \DateTime|null The expiration date or null if $expireDate was null and it is not required * @throws \OC\HintException */ protected function validateExpiredate($expireDate) { if ($expireDate !== null) { //Make sure the expiration date is a date $expireDate->setTime(0, 0, 0); $date = new \DateTime(); $date->setTime(0, 0, 0); if ($date >= $expireDate) { $message = $this->l->t('Expiration date is in the past'); throw new \OC\HintException($message, $message, 404); } } // If we enforce the expiration date check that is does not exceed if ($this->shareApiLinkDefaultExpireDateEnforced()) { if ($expireDate === 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 < $expireDate) { $message = $this->l->t('Cannot set expiration date more than %s days in the future', [$this->shareApiLinkDefaultExpireDays()]); throw new \OC\HintException($message, $message, 404); } return $expireDate; } // If expiredate is empty set a default one if there is a default if ($expireDate === null && $this->shareApiLinkDefaultExpireDate()) { $date = new \DateTime(); $date->setTime(0, 0, 0); $date->add(new \DateInterval('P' . $this->shareApiLinkDefaultExpireDays() . 'D')); return $date; } return $expireDate; }
/** * sets the users avatar * @param IImage|resource|string $data An image object, imagedata or path to set a new avatar * @throws \Exception if the provided file is not a jpg or png image * @throws \Exception if the provided image is not valid * @throws NotSquareException if the image is not square * @return void */ public function set($data) { if ($data instanceof IImage) { $img = $data; $data = $img->data(); } else { $img = new OC_Image($data); } $type = substr($img->mimeType(), -3); if ($type === 'peg') { $type = 'jpg'; } if ($type !== 'jpg' && $type !== 'png') { throw new \Exception($this->l->t("Unknown filetype")); } if (!$img->valid()) { throw new \Exception($this->l->t("Invalid image")); } if (!($img->height() === $img->width())) { throw new NotSquareException(); } $this->remove(); $this->folder->newFile('avatar.' . $type)->putContent($data); $this->user->triggerChange(); }
/** * @NoAdminRequired * @NoCSRFRequired * * @param int $accountId * @param string $folderId * @param int $from * @param int $to * @param string $filter * @param array $ids * @return JSONResponse */ public function index($accountId, $folderId, $from = 0, $to = 20, $filter = null, $ids = null) { if (!is_null($ids)) { $ids = explode(',', $ids); return $this->loadMultiple($accountId, $folderId, $ids); } $mailBox = $this->getFolder($accountId, $folderId); $this->logger->debug("loading messages {$from} to {$to} of folder <{$folderId}>"); $json = $mailBox->getMessages($from, $to - $from + 1, $filter); $ci = $this->contactsIntegration; $json = array_map(function ($j) use($ci, $mailBox) { if ($mailBox->getSpecialRole() === 'trash') { $j['delete'] = (string) $this->l10n->t('Delete permanently'); } if ($mailBox->getSpecialRole() === 'sent') { $j['fromEmail'] = $j['toEmail']; $j['from'] = $j['to']; if (count($j['toList']) > 1 || count($j['ccList']) > 0) { $j['from'] .= ' ' . $this->l10n->t('& others'); } } $j['senderImage'] = $ci->getPhoto($j['fromEmail']); return $j; }, $json); return new JSONResponse($json); }
private function analyzeOC($dependencies, $appInfo) { $missing = []; $minVersion = null; if (isset($dependencies['owncloud']['@attributes']['min-version'])) { $minVersion = $dependencies['owncloud']['@attributes']['min-version']; } elseif (isset($appInfo['requiremin'])) { $minVersion = $appInfo['requiremin']; } elseif (isset($appInfo['require'])) { $minVersion = $appInfo['require']; } $maxVersion = null; if (isset($dependencies['owncloud']['@attributes']['max-version'])) { $maxVersion = $dependencies['owncloud']['@attributes']['max-version']; } elseif (isset($appInfo['requiremax'])) { $maxVersion = $appInfo['requiremax']; } if (!is_null($minVersion)) { if ($this->compareSmaller($this->platform->getOcVersion(), $minVersion)) { $missing[] = (string) $this->l->t('ownCloud %s or higher is required.', $minVersion); } } if (!is_null($maxVersion)) { if ($this->compareBigger($this->platform->getOcVersion(), $maxVersion)) { $missing[] = (string) $this->l->t('ownCloud with a version lower than %s is required.', $maxVersion); } } return $missing; }
public function __construct(IL10N $l, ISession $session, ICredentialsManager $credentialsManager) { $this->session = $session; $this->credentialsManager = $credentialsManager; $this->setIdentifier('password::logincredentials')->setScheme(self::SCHEME_PASSWORD)->setText($l->t('Log-in credentials, save in database'))->addParameters([]); \OCP\Util::connectHook('OC_User', 'post_login', $this, 'authenticate'); }
public function __construct(BackendInterface $caldavBackend, $calendarInfo, IL10N $l10n) { parent::__construct($caldavBackend, $calendarInfo); if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) { $this->calendarInfo['{DAV:}displayname'] = $l10n->t('Contact birthdays'); } }
/** * @NoAdminRequired * * @param array $crop * @return DataResponse */ public function postCroppedAvatar($crop) { $userId = $this->userSession->getUser()->getUID(); if (is_null($crop)) { return new DataResponse(['data' => ['message' => $this->l->t("No crop data provided")]], Http::STATUS_BAD_REQUEST); } if (!isset($crop['x'], $crop['y'], $crop['w'], $crop['h'])) { return new DataResponse(['data' => ['message' => $this->l->t("No valid crop data provided")]], Http::STATUS_BAD_REQUEST); } $tmpAvatar = $this->cache->get('tmpAvatar'); if (is_null($tmpAvatar)) { return new DataResponse(['data' => ['message' => $this->l->t("No temporary profile picture available, try again")]], Http::STATUS_BAD_REQUEST); } $image = new \OC_Image($tmpAvatar); $image->crop($crop['x'], $crop['y'], round($crop['w']), round($crop['h'])); try { $avatar = $this->avatarManager->getAvatar($userId); $avatar->set($image); // Clean up $this->cache->remove('tmpAvatar'); return new DataResponse(['status' => 'success']); } catch (\OC\NotSquareException $e) { return new DataResponse(['data' => ['message' => $this->l->t('Crop is not square')]], Http::STATUS_BAD_REQUEST); } catch (\Exception $e) { return new DataResponse(['data' => ['message' => $e->getMessage()]], Http::STATUS_BAD_REQUEST); } }
/** * @PublicPage * @NoCSRFRequired * * @return TemplateResponse */ public function show() { try { $user = $this->activityManager->getCurrentUserId(); $userLang = $this->config->getUserValue($user, 'core', 'lang'); // Overwrite user and language in the helper $this->l = $this->l10nFactory->get('activity', $userLang); $parser = new PlainTextParser($this->l); $this->helper->setL10n($this->l); $this->helper->setUser($user); $description = (string) $this->l->t('Personal activity feed for %s', $user); $response = $this->data->get($this->helper, $this->settings, $user, 0, self::DEFAULT_PAGE_SIZE, 'desc', 'all'); $data = $response['data']; $activities = []; foreach ($data as $activity) { $activity['subject_prepared'] = $parser->parseMessage($activity['subject_prepared']); $activity['message_prepared'] = $parser->parseMessage($activity['message_prepared']); $activities[] = $activity; } } catch (\UnexpectedValueException $e) { $this->l = $this->l10nFactory->get('activity'); $description = (string) $this->l->t('Your feed URL is invalid'); $activities = [['activity_id' => -1, 'timestamp' => time(), 'subject' => true, 'subject_prepared' => $description]]; } $response = new TemplateResponse('activity', 'rss', ['rssLang' => $this->l->getLanguageCode(), 'rssLink' => $this->urlGenerator->linkToRouteAbsolute('activity.Feed.show'), 'rssPubDate' => date('r'), 'description' => $description, 'activities' => $activities], ''); if ($this->request->getHeader('accept') !== null && stristr($this->request->getHeader('accept'), 'application/rss+xml')) { $response->addHeader('Content-Type', 'application/rss+xml'); } else { $response->addHeader('Content-Type', 'text/xml; charset=UTF-8'); } return $response; }