Example #1
0
 /**
  * Do security precheck for not logged in users
  * @param bool callcheck - whether security token check is needed
  */
 public static function preDispatchGuest($callcheck = true)
 {
     if ($callcheck) {
         \OCP\JSON::callCheck();
     }
     \OCP\JSON::checkAppEnabled('documents');
 }
Example #2
0
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  */
 public function Add()
 {
     \OCP\JSON::setContentTypeHeader('application/json');
     if (isset($_POST['FILE']) && strlen($_POST['FILE']) > 0 && Tools::CheckURL($_POST['FILE']) && isset($_POST['OPTIONS'])) {
         try {
             $Target = Tools::CleanString(substr($_POST['FILE'], strrpos($_POST['FILE'], '/') + 1));
             // If target file exists, create a new one
             if (\OC\Files\Filesystem::file_exists($this->DownloadsFolder . '/' . $Target)) {
                 $Target = time() . '_' . $Target;
             }
             // Create the target file if the downloader is Aria2
             if ($this->WhichDownloader == 0) {
                 \OC\Files\Filesystem::touch($this->DownloadsFolder . '/' . $Target);
             } else {
                 if (!\OC\Files\Filesystem::is_dir($this->DownloadsFolder)) {
                     \OC\Files\Filesystem::mkdir($this->DownloadsFolder);
                 }
             }
             // Build OPTIONS array
             $OPTIONS = array('dir' => $this->AbsoluteDownloadsFolder, 'out' => $Target, 'follow-torrent' => false);
             if (isset($_POST['OPTIONS']['FTPUser']) && strlen(trim($_POST['OPTIONS']['FTPUser'])) > 0 && isset($_POST['OPTIONS']['FTPPasswd']) && strlen(trim($_POST['OPTIONS']['FTPPasswd'])) > 0) {
                 $OPTIONS['ftp-user'] = $_POST['OPTIONS']['FTPUser'];
                 $OPTIONS['ftp-passwd'] = $_POST['OPTIONS']['FTPPasswd'];
             }
             if (isset($_POST['OPTIONS']['FTPPasv']) && strlen(trim($_POST['OPTIONS']['FTPPasv'])) > 0) {
                 $OPTIONS['ftp-pasv'] = strcmp($_POST['OPTIONS']['FTPPasv'], "true") == 0 ? true : false;
             }
             if (!$this->ProxyOnlyWithYTDL && !is_null($this->ProxyAddress) && $this->ProxyPort > 0 && $this->ProxyPort <= 65536) {
                 $OPTIONS['all-proxy'] = rtrim($this->ProxyAddress, '/') . ':' . $this->ProxyPort;
                 if (!is_null($this->ProxyUser) && !is_null($this->ProxyPasswd)) {
                     $OPTIONS['all-proxy-user'] = $this->ProxyUser;
                     $OPTIONS['all-proxy-passwd'] = $this->ProxyPasswd;
                 }
             }
             $AddURI = $this->WhichDownloader == 0 ? Aria2::AddUri(array($_POST['FILE']), array('Params' => $OPTIONS)) : CURL::AddUri($_POST['FILE'], $OPTIONS);
             if (isset($AddURI['result']) && !is_null($AddURI['result'])) {
                 $SQL = 'INSERT INTO `*PREFIX*ocdownloader_queue` (`UID`, `GID`, `FILENAME`, `PROTOCOL`, `STATUS`, `TIMESTAMP`) VALUES (?, ?, ?, ?, ?, ?)';
                 if ($this->DbType == 1) {
                     $SQL = 'INSERT INTO *PREFIX*ocdownloader_queue ("UID", "GID", "FILENAME", "PROTOCOL", "STATUS", "TIMESTAMP") VALUES (?, ?, ?, ?, ?, ?)';
                 }
                 $Query = \OCP\DB::prepare($SQL);
                 $Result = $Query->execute(array($this->CurrentUID, $AddURI['result'], $Target, strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), 1, time()));
                 sleep(1);
                 $Status = $this->WhichDownloader == 0 ? Aria2::TellStatus($AddURI['result']) : CURL::TellStatus($AddURI['result']);
                 $Progress = 0;
                 if ($Status['result']['totalLength'] > 0) {
                     $Progress = $Status['result']['completedLength'] / $Status['result']['totalLength'];
                 }
                 $ProgressString = Tools::GetProgressString($Status['result']['completedLength'], $Status['result']['totalLength'], $Progress);
                 return new JSONResponse(array('ERROR' => false, 'MESSAGE' => (string) $this->L10N->t('Download started'), 'GID' => $AddURI['result'], 'PROGRESSVAL' => round($Progress * 100, 2) . '%', 'PROGRESS' => is_null($ProgressString) ? (string) $this->L10N->t('N/A') : $ProgressString, 'STATUS' => isset($Status['result']['status']) ? (string) $this->L10N->t(ucfirst($Status['result']['status'])) : (string) $this->L10N->t('N/A'), 'STATUSID' => Tools::GetDownloadStatusID($Status['result']['status']), 'SPEED' => isset($Status['result']['downloadSpeed']) ? Tools::FormatSizeUnits($Status['result']['downloadSpeed']) . '/s' : (string) $this->L10N->t('N/A'), 'FILENAME' => strlen($Target) > 40 ? substr($Target, 0, 40) . '...' : $Target, 'PROTO' => strtoupper(substr($_POST['FILE'], 0, strpos($_POST['FILE'], ':'))), 'ISTORRENT' => false));
             } else {
                 return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t($this->WhichDownloader == 0 ? 'Returned GID is null ! Is Aria2c running as a daemon ?' : 'An error occurred while running the CURL download')));
             }
         } catch (Exception $E) {
             return new JSONResponse(array('ERROR' => true, 'MESSAGE' => $E->getMessage()));
         }
     } else {
         return new JSONResponse(array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('Please check the URL you\'ve just provided')));
     }
 }
 /**
  *@PublicPage
  * @NoCSRFRequired
  * 
  */
 public function exportEvents()
 {
     $token = $this->params('t');
     $calid = null;
     $eventid = null;
     if (isset($token)) {
         $linkItem = \OCP\Share::getShareByToken($token, false);
         if (is_array($linkItem) && isset($linkItem['uid_owner'])) {
             $rootLinkItem = \OCP\Share::resolveReShare($linkItem);
             if (isset($rootLinkItem['uid_owner'])) {
                 \OCP\JSON::checkUserExists($rootLinkItem['uid_owner']);
                 if ($linkItem['item_type'] === CalendarApp::SHARECALENDAR) {
                     $sPrefix = CalendarApp::SHARECALENDARPREFIX;
                 }
                 if ($linkItem['item_type'] === CalendarApp::SHAREEVENT) {
                     $sPrefix = CalendarApp::SHAREEVENTPREFIX;
                 }
                 if ($linkItem['item_type'] === CalendarApp::SHARETODO) {
                     $sPrefix = CalendarApp::SHARETODOPREFIX;
                 }
                 $itemSource = CalendarApp::validateItemSource($linkItem['item_source'], $sPrefix);
                 if ($linkItem['item_type'] === CalendarApp::SHARECALENDAR) {
                     $calid = $itemSource;
                 }
                 if ($linkItem['item_type'] === CalendarApp::SHAREEVENT || $linkItem['item_type'] === CalendarApp::SHARETODO) {
                     $eventid = $itemSource;
                 }
             }
         }
     } else {
         if (\OCP\User::isLoggedIn()) {
             $calid = $this->params('calid');
             $eventid = $this->params('eventid');
         }
     }
     if (!is_null($calid)) {
         $calendar = CalendarApp::getCalendar($calid, true);
         if (!$calendar) {
             $params = ['status' => 'error'];
             $response = new JSONResponse($params);
             return $response;
         }
         $name = str_replace(' ', '_', $calendar['displayname']) . '.ics';
         $calendarEvents = Export::export($calid, Export::CALENDAR);
         $response = new DataDownloadResponse($calendarEvents, $name, 'text/calendar');
         return $response;
     }
     if (!is_null($eventid)) {
         $data = CalendarApp::getEventObject($eventid, false);
         if (!$data) {
             $params = ['status' => 'error'];
             $response = new JSONResponse($params);
             return $response;
         }
         $name = str_replace(' ', '_', $data['summary']) . '.ics';
         $singleEvent = Export::export($eventid, Export::EVENT);
         $response = new DataDownloadResponse($singleEvent, $name, 'text/calendar');
         return $response;
     }
 }
Example #4
0
 public static function initAjaxController()
 {
     \OCP\JSON::checkLoggedIn();
     \OCP\JSON::callCheck();
     \OCP\JSON::checkAppEnabled('contacts');
     \OCP\JSON::checkAppEnabled(self::APP_ID);
 }
Example #5
0
 /**
  * Returns the rendered json
  * @return the rendered json
  */
 public function render()
 {
     parent::render();
     ob_start();
     if ($this->error) {
         \OCP\JSON::error($this->data);
     } else {
         \OCP\JSON::success($this->data);
     }
     $result = ob_get_contents();
     ob_end_clean();
     return $result;
 }
Example #6
0
 /**
  * Runs all security checks
  */
 public function runChecks()
 {
     if ($this->csrfCheck) {
         \OCP\JSON::callCheck();
     }
     if ($this->loggedInCheck) {
         \OCP\JSON::checkLoggedIn();
     }
     if ($this->appEnabledCheck) {
         \OCP\JSON::checkAppEnabled($this->appName);
     }
     if ($this->isAdminCheck) {
         \OCP\User::checkAdminUser();
     }
 }
 /**
  * Send JSON response on successful login
  * @param String $uid
  */
 public static function postlogin_hook($uid)
 {
     if (!self::$_isPersona) {
         return;
     }
     \OCP\Util::writeLog(App::APP_ID, 'Check ambigous ', \OCP\Util::DEBUG);
     if (self::$_isAmbigous) {
         //Reply with error and logout
         \OCP\User::logout();
         \OCP\JSON::error(array('msg' => 'More than one user found'));
         exit;
     } else {
         \OCP\JSON::success(array('msg' => 'Access granted'));
         exit;
     }
 }
Example #8
0
 /**
  * @AdminRequired
  * @NoCSRFRequired
  */
 public function Check()
 {
     \OCP\JSON::setContentTypeHeader('application/json');
     if ($this->Allow) {
         try {
             $LastVersionNumber = Tools::GetLastVersionNumber();
             $AppVersion = \OCP\App::getAppVersion('ocdownloader');
             $Response = array('ERROR' => false, 'RESULT' => version_compare($AppVersion, $LastVersionNumber, '<'));
         } catch (Exception $E) {
             $Response = array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('Error while checking application version on GitHub'));
         }
     } else {
         $Response = array('ERROR' => true, 'MESSAGE' => (string) $this->L10N->t('You are not allowed to check for application updates'));
     }
     return new JSONResponse($Response);
 }
 /**
  * Invite users to the editing session
  */
 public static function invite()
 {
     self::preDispatch();
     $invitees = @$_POST['users'];
     if (is_array($invitees)) {
         $invitees = array_unique($invitees);
         $esId = @$_POST['esId'];
         foreach ($invitees as $userId) {
             try {
                 Invite::add($esId, $userId);
             } catch (\Exception $e) {
             }
         }
     }
     \OCP\JSON::success();
 }
Example #10
0
 /**
  * Sets up the filesystem and user for public sharing
  * @param string $token string share token
  * @param string $relativePath optional path relative to the share
  * @param string $password optional password
  */
 public static function setupFromToken($token, $relativePath = null, $password = null)
 {
     \OC_User::setIncognitoMode(true);
     $linkItem = \OCP\Share::getShareByToken($token, !$password);
     if ($linkItem === false || $linkItem['item_type'] !== 'file' && $linkItem['item_type'] !== 'folder') {
         \OC_Response::setStatus(404);
         \OC_Log::write('core-preview', 'Passed token parameter is not valid', \OC_Log::DEBUG);
         exit;
     }
     if (!isset($linkItem['uid_owner']) || !isset($linkItem['file_source'])) {
         \OC_Response::setStatus(500);
         \OC_Log::write('core-preview', 'Passed token seems to be valid, but it does not contain all necessary information . ("' . $token . '")', \OC_Log::WARN);
         exit;
     }
     $rootLinkItem = \OCP\Share::resolveReShare($linkItem);
     $path = null;
     if (isset($rootLinkItem['uid_owner'])) {
         \OCP\JSON::checkUserExists($rootLinkItem['uid_owner']);
         \OC_Util::tearDownFS();
         \OC_Util::setupFS($rootLinkItem['uid_owner']);
         $path = \OC\Files\Filesystem::getPath($linkItem['file_source']);
     }
     if ($path === null) {
         \OCP\Util::writeLog('share', 'could not resolve linkItem', \OCP\Util::DEBUG);
         \OC_Response::setStatus(404);
         \OCP\JSON::error(array('success' => false));
         exit;
     }
     if (!isset($linkItem['item_type'])) {
         \OCP\Util::writeLog('share', 'No item type set for share id: ' . $linkItem['id'], \OCP\Util::ERROR);
         \OC_Response::setStatus(404);
         \OCP\JSON::error(array('success' => false));
         exit;
     }
     if (isset($linkItem['share_with'])) {
         if (!self::authenticate($linkItem, $password)) {
             \OC_Response::setStatus(403);
             \OCP\JSON::error(array('success' => false));
             exit;
         }
     }
     $basePath = $path;
     if ($relativePath !== null && \OC\Files\Filesystem::isReadable($basePath . $relativePath)) {
         $path .= \OC\Files\Filesystem::normalizePath($relativePath);
     }
     return array('linkItem' => $linkItem, 'basePath' => $basePath, 'realPath' => $path);
 }
Example #11
0
 public static function rename($args)
 {
     self::preDispatchGuest();
     $memberId = Helper::getArrayValueByKey($args, 'member_id');
     $name = Helper::getArrayValueByKey($_POST, 'name');
     $member = new Db\Member();
     $member->load($memberId);
     if ($member->getEsId() && $member->getStatus() == Db\Member::MEMBER_STATUS_ACTIVE && $member->getIsGuest()) {
         $guestMark = Db\Member::getGuestPostfix();
         if (substr($name, -strlen($guestMark)) !== $guestMark) {
             $name = $name . ' ' . $guestMark;
         }
         $op = new Db\Op();
         $op->changeNick($member->getEsId(), $memberId, $name);
     }
     \OCP\JSON::success();
 }
Example #12
0
 public function __construct($AppName, IRequest $request, $UserId)
 {
     parent::__construct($AppName, $request);
     $this->userId = $UserId;
     $path = self::PROJECTKIT_PREFIX . DIRECTORY_SEPARATOR;
     if (isset($_GET['containerId'])) {
         $path .= self::PROJECT_PREFIX . (string) $_GET['containerId'] . DIRECTORY_SEPARATOR;
         if (isset($_GET['targetType']) && isset($_GET['targetId'])) {
             switch ($_GET['targetType']) {
                 case TargetType::TASK:
                     $path .= self::TASK_PREFIX;
                     break;
                 case TargetType::ISSUE:
                     $path .= self::ISSUE_PREFIX;
                     break;
                 default:
                     break;
             }
             $path .= (string) $_GET['targetId'] . DIRECTORY_SEPARATOR;
             $_SESSION['targetType'] = $_GET['targetType'];
         } elseif (!isset($_GET['targetType']) && !isset($_GET['targetId'])) {
             $_SESSION['targetType'] = TargetType::PROJECT;
         }
         //use session to save targetType
         $path = Filesystem::normalizePath($path);
         //Create folder for path
         if (!Filesystem::file_exists($path)) {
             try {
                 Filesystem::mkdir($path);
             } catch (\Exception $e) {
                 $result = ['success' => false, 'data' => ['message' => $e->getMessage()]];
                 \OCP\JSON::error($result);
                 exit;
             }
         }
         if (!isset($_GET['dir'])) {
             $params = array_merge($_GET, ["dir" => $path]);
             $url = $_SERVER['PHP_SELF'] . '?' . http_build_query($params);
             header('Location: ' . $url, true, 302);
             exit;
         }
     }
 }
Example #13
0
 public static function av_scan($path)
 {
     $path = $path[\OC\Files\Filesystem::signal_param_path];
     if ($path != '') {
         if (isset($_POST['dirToken'])) {
             //Public upload case
             $filesView = \OC\Files\Filesystem::getView();
         } else {
             $filesView = \OCP\Files::getStorage("files");
         }
         if (!is_object($filesView)) {
             \OCP\Util::writeLog('files_antivirus', 'Can\'t init filesystem view', \OCP\Util::WARN);
             return;
         }
         // check if path is a directory
         if ($filesView->is_dir($path)) {
             return;
         }
         // we should have a file to work with, and the file shouldn't
         // be empty
         $fileExists = $filesView->file_exists($path);
         if ($fileExists && $filesView->filesize($path) > 0) {
             $fileStatus = self::scanFile($filesView, $path);
             $result = $fileStatus->getNumericStatus();
             switch ($result) {
                 case Status::SCANRESULT_UNCHECKED:
                     //TODO: Show warning to the user: The file can not be checked
                     break;
                 case Status::SCANRESULT_INFECTED:
                     //remove file
                     $filesView->unlink($path);
                     Notification::sendMail($path);
                     $message = \OCP\Util::getL10N('files_antivirus')->t("Virus detected! Can't upload the file %s", array(basename($path)));
                     \OCP\JSON::error(array("data" => array("message" => $message)));
                     exit;
                     break;
                 case Status::SCANRESULT_CLEAN:
                     //do nothing
                     break;
             }
         }
     }
 }
Example #14
0
 /**
  * Check if we have a user to login
  * @param String $email 
  * @param String $uid 
  * @return String 
  */
 public static function apply($email, $uid = '')
 {
     //Get list of matching users
     $list = array();
     $query = \OCP\DB::prepare('SELECT userid FROM *PREFIX*preferences WHERE appid = ? AND configkey = ? AND configvalue  = ?');
     $result = $query->execute(array('settings', 'email', $email));
     while ($userid = $result->fetchOne()) {
         $list[] = $userid;
     }
     $qtyUser = count($list);
     //No users found
     if (!$qtyUser) {
         \OCP\Util::writeLog(App::APP_ID, 'No users found. Deny login.', \OCP\Util::DEBUG);
         return false;
     }
     //One user found
     if ($qtyUser == 1) {
         \OCP\Util::writeLog(App::APP_ID, 'Single user found. Entering the open space.', \OCP\Util::DEBUG);
         return $list[0];
     }
     //Multiple users found
     $currentPolicy = self::getSystemPolicy();
     $isValidUid = in_array($uid, $list);
     if ($currentPolicy == self::MULTIPLE_USERS_LIST) {
         //Do we have correct uid?
         if ($isValidUid) {
             \OCP\Util::writeLog(App::APP_ID, 'Multiple users found. Entering the open space.', \OCP\Util::DEBUG);
             return $uid;
         } else {
             \OCP\Util::writeLog(App::APP_ID, 'Multiple users found. List them all.', \OCP\Util::DEBUG);
             \OCP\JSON::success(array('list' => $list));
             exit;
         }
     } elseif ($currentPolicy == self::MULTIPLE_USERS_FIRST) {
         \OCP\Util::writeLog(App::APP_ID, 'Multiple users found. Use first.', \OCP\Util::DEBUG);
         //not first but the best matching ;)
         $userid = $isValidUid ? $uid : $list[0];
         return $userid;
     }
     \OCP\Util::writeLog(App::APP_ID, 'Multiple users found. Deny login.', \OCP\Util::DEBUG);
     return Validator::setAmbigous();
 }
Example #15
0
 /**
  * Send a mail to test the settings
  */
 public static function sendTestMail()
 {
     \OC_Util::checkAdminUser();
     \OCP\JSON::callCheck();
     $l = \OC::$server->getL10N('settings');
     $email = \OC_Preferences::getValue(\OC_User::getUser(), 'settings', 'email', '');
     if (!empty($email)) {
         $defaults = new \OC_Defaults();
         try {
             \OC_Mail::send($email, \OC_User::getDisplayName(), $l->t('test email settings'), $l->t('If you received this email, the settings seem to be correct.'), \OCP\Util::getDefaultEmailAddress('no-reply'), $defaults->getName());
         } catch (\Exception $e) {
             $message = $l->t('A problem occurred while sending the e-mail. Please revisit your settings.');
             \OC_JSON::error(array("data" => array("message" => $message)));
             exit;
         }
         \OC_JSON::success(array("data" => array("message" => $l->t("Email sent"))));
     } else {
         $message = $l->t('You need to set your user email before being able to send test emails.');
         \OC_JSON::error(array("data" => array("message" => $message)));
     }
 }
Example #16
0
 /**
  * @NoAdminRequired
  * @NoCSRFRequired
  */
 public function Get()
 {
     \OCP\JSON::setContentTypeHeader('application/json');
     $PersonalSettings = array();
     foreach ($this->OCDSettingKeys as $SettingKey) {
         $this->Settings->SetKey($SettingKey);
         $PersonalSettings[$SettingKey] = $this->Settings->GetValue();
         // Set default if not set in the database
         if (is_null($PersonalSettings[$SettingKey])) {
             switch ($SettingKey) {
                 case 'DownloadsFolder':
                     $PersonalSettings[$SettingKey] = 'Downloads';
                     break;
                 case 'TorrentsFolder':
                     $PersonalSettings[$SettingKey] = 'Downloads/Files/Torrents';
                     break;
             }
         }
     }
     return new JSONResponse(array('ERROR' => false, 'VALS' => $PersonalSettings));
 }
 /**
  * lists the documents the user has access to (including shared files, once the code in core has been fixed)
  * also adds session and member info for these files
  */
 public static function listAll()
 {
     self::preDispatch();
     $documents = Storage::getDocuments();
     $fileIds = array();
     //$previewAvailable = \OCP\Preview::show($file);
     foreach ($documents as $key => $document) {
         //\OCP\Preview::show($document['path']);
         $documents[$key]['icon'] = preg_replace('/\\.png$/', '.svg', \OC_Helper::mimetypeIcon($document['mimetype']));
         $fileIds[] = $document['fileid'];
     }
     usort($documents, function ($a, $b) {
         return @$b['mtime'] - @$a['mtime'];
     });
     $session = new Db_Session();
     $sessions = $session->getCollectionBy('file_id', $fileIds);
     $members = array();
     $member = new Db_Member();
     foreach ($sessions as $session) {
         $members[$session['es_id']] = $member->getActiveCollection($session['es_id']);
     }
     \OCP\JSON::success(array('documents' => $documents, 'sessions' => $sessions, 'members' => $members));
 }
Example #18
0
    $password = $_POST['password'];
}
$relativePath = null;
if (isset($_GET['dir'])) {
    $relativePath = $_GET['dir'];
}
$sortAttribute = isset($_GET['sort']) ? $_GET['sort'] : 'name';
$sortDirection = isset($_GET['sortdirection']) ? $_GET['sortdirection'] === 'desc' : false;
$data = \OCA\Files_Sharing\Helper::setupFromToken($token, $relativePath, $password);
$linkItem = $data['linkItem'];
// Load the files
$dir = $data['realPath'];
$dir = \OC\Files\Filesystem::normalizePath($dir);
if (!\OC\Files\Filesystem::is_dir($dir . '/')) {
    \OC_Response::setStatus(\OC_Response::STATUS_NOT_FOUND);
    \OCP\JSON::error(array('success' => false));
    exit;
}
$data = array();
// make filelist
$files = \OCA\Files\Helper::getFiles($dir, $sortAttribute, $sortDirection);
$formattedFiles = array();
foreach ($files as $file) {
    $entry = \OCA\Files\Helper::formatFileInfo($file);
    unset($entry['directory']);
    // for now
    $entry['permissions'] = \OCP\PERMISSION_READ;
    $formattedFiles[] = $entry;
}
$data['directory'] = $relativePath;
$data['files'] = $formattedFiles;
Example #19
0
        } catch (\Exception $e) {
            \OCP\JSON::error(array('message' => $e->getMessage()));
            exit;
        }
        \OCP\JSON::error();
        exit;
        break;
    case 'save':
        $key = isset($_POST['cfgkey']) ? $_POST['cfgkey'] : false;
        $val = isset($_POST['cfgval']) ? $_POST['cfgval'] : null;
        if ($key === false || is_null($val)) {
            \OCP\JSON::error(array('message' => $l->t('No data specified')));
            exit;
        }
        $cfg = array($key => $val);
        $setParameters = array();
        $configuration->setConfiguration($cfg, $setParameters);
        if (!in_array($key, $setParameters)) {
            \OCP\JSON::error(array('message' => $l->t($key . ' Could not set configuration %s', $setParameters[0])));
            exit;
        }
        $configuration->saveConfiguration();
        //clear the cache on save
        $connection = new \OCA\user_ldap\lib\Connection($ldapWrapper, $prefix);
        $connection->clearCache();
        OCP\JSON::success();
        break;
    default:
        \OCP\JSON::error(array('message' => $l->t('Action does not exist')));
        break;
}
Example #20
0
 /**
  * @param $token
  * @return null|string
  */
 private function getPath($token)
 {
     $linkItem = Share::getShareByToken($token, false);
     $path = null;
     if (is_array($linkItem) && isset($linkItem['uid_owner'])) {
         // seems to be a valid share
         $rootLinkItem = Share::resolveReShare($linkItem);
         if (isset($rootLinkItem['uid_owner'])) {
             JSON::checkUserExists($rootLinkItem['uid_owner']);
             OC_Util::tearDownFS();
             OC_Util::setupFS($rootLinkItem['uid_owner']);
             $path = Filesystem::getPath($linkItem['file_source']);
         }
     }
     return $path;
 }
 * This code is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
\OCP\JSON::checkAppEnabled('files_external_listing');
\OCP\JSON::checkLoggedIn();
\OCP\JSON::callCheck();
\OC_JSON::checkAdminUser();
$defaultDir = '/home';
if (\OC_Util::runningOnWindows()) {
    $defaultDir = 'C:\\';
}
$localroot = OCP\Config::getAppValue('files_external_listing', 'starting_dir', $defaultDir);
if (isset($_POST['path'])) {
    $path = realpath($_POST['path']);
    if (strpos($path, $localroot) === 0 or empty($_POST['path'])) {
        if (empty($_POST['path'])) {
            $path = $localroot;
        }
        if (!is_dir($path)) {
            //path is incorrect or is a file. Nothing to do, we work only with dirs
            OCP\JSON::error(array('data' => array('message' => 'Incorrect path: ' . $_POST['path'])));
Example #22
0
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License, version 3,
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
 *
 */
set_time_limit(0);
//scanning can take ages
\OCP\JSON::checkLoggedIn();
\OCP\JSON::callCheck();
\OC::$server->getSession()->close();
$force = (isset($_GET['force']) and $_GET['force'] === 'true');
$dir = isset($_GET['dir']) ? (string) $_GET['dir'] : '';
if (isset($_GET['users'])) {
    \OCP\JSON::checkAdminUser();
    if ($_GET['users'] === 'all') {
        $users = OC_User::getUsers();
    } else {
        $users = json_decode($_GET['users']);
    }
} else {
    $users = array(OC_User::getUser());
}
$eventSource = \OC::$server->createEventSource();
$listener = new ScanListener($eventSource);
foreach ($users as $user) {
    $eventSource->send('user', $user);
    $scanner = new \OC\Files\Utils\Scanner($user, \OC::$server->getDatabaseConnection());
    $scanner->listen('\\OC\\Files\\Utils\\Scanner', 'scanFile', array($listener, 'file'));
    $scanner->listen('\\OC\\Files\\Utils\\Scanner', 'scanFolder', array($listener, 'folder'));
Example #23
0
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 *
 * Script to handle admin settings for encrypted key recovery
 */
use OCA\Encryption;
\OCP\JSON::checkAdminUser();
\OCP\JSON::checkAppEnabled('files_encryption');
\OCP\JSON::callCheck();
$l = OC_L10N::get('files_encryption');
$return = false;
// Enable recoveryAdmin
$recoveryKeyId = \OC::$server->getAppConfig()->getValue('files_encryption', 'recoveryKeyId');
if (isset($_POST['adminEnableRecovery']) && $_POST['adminEnableRecovery'] === '1') {
    $return = \OCA\Encryption\Helper::adminEnableRecovery($recoveryKeyId, $_POST['recoveryPassword']);
    // Return success or failure
    if ($return) {
        \OCP\JSON::success(array('data' => array('message' => $l->t('Recovery key successfully enabled'))));
    } else {
        \OCP\JSON::error(array('data' => array('message' => $l->t('Could not enable recovery key. Please check your recovery key password!'))));
    }
    // Disable recoveryAdmin
} elseif (isset($_POST['adminEnableRecovery']) && '0' === $_POST['adminEnableRecovery']) {
    $return = \OCA\Encryption\Helper::adminDisableRecovery($_POST['recoveryPassword']);
    // Return success or failure
    if ($return) {
        \OCP\JSON::success(array('data' => array('message' => $l->t('Recovery key successfully disabled'))));
    } else {
        \OCP\JSON::error(array('data' => array('message' => $l->t('Could not disable recovery key. Please check your recovery key password!'))));
    }
}
    $errorMessage = $l->t('Please repeat the new recovery password');
    \OCP\JSON::error(array('data' => array('message' => $errorMessage)));
    exit;
}
if ($_POST['newPassword'] !== $_POST['confirmPassword']) {
    $errorMessage = $l->t('Repeated recovery key password does not match the provided recovery key password');
    \OCP\JSON::error(array('data' => array('message' => $errorMessage)));
    exit;
}
$view = new \OC\Files\View('/');
$util = new \OCA\Files_Encryption\Util(new \OC\Files\View('/'), \OCP\User::getUser());
$proxyStatus = \OC_FileProxy::$enabled;
\OC_FileProxy::$enabled = false;
$keyId = $util->getRecoveryKeyId();
$encryptedRecoveryKey = \OCA\Files_Encryption\Keymanager::getPrivateSystemKey($keyId);
$decryptedRecoveryKey = $encryptedRecoveryKey ? \OCA\Files_Encryption\Crypt::decryptPrivateKey($encryptedRecoveryKey, $oldPassword) : false;
if ($decryptedRecoveryKey) {
    $cipher = \OCA\Files_Encryption\Helper::getCipher();
    $encryptedKey = \OCA\Files_Encryption\Crypt::symmetricEncryptFileContent($decryptedRecoveryKey, $newPassword, $cipher);
    if ($encryptedKey) {
        \OCA\Files_Encryption\Keymanager::setPrivateSystemKey($encryptedKey, $keyId);
        $return = true;
    }
}
\OC_FileProxy::$enabled = $proxyStatus;
// success or failure
if ($return) {
    \OCP\JSON::success(array('data' => array('message' => $l->t('Password successfully changed.'))));
} else {
    \OCP\JSON::error(array('data' => array('message' => $l->t('Could not change the password. Maybe the old password was not correct.'))));
}
Example #25
0
            $link = (string) $_POST['link'];
            $file = (string) $_POST['file'];
            $to_address = (string) $_POST['toaddress'];
            $mailNotification = new \OC\Share\MailNotifications();
            $expiration = null;
            if (isset($_POST['expiration']) && $_POST['expiration'] !== '') {
                try {
                    $date = new DateTime((string) $_POST['expiration']);
                    $expiration = $date->getTimestamp();
                } catch (Exception $e) {
                    \OCP\Util::writeLog('sharing', "Couldn't read date: " . $e->getMessage(), \OCP\Util::ERROR);
                }
            }
            $result = $mailNotification->sendLinkShareMail($to_address, $file, $link, $expiration);
            if (empty($result)) {
                \OCP\JSON::success();
            } else {
                $l = \OC::$server->getL10N('core');
                OCP\JSON::error(array('data' => array('message' => $l->t("Couldn't send mail to following users: %s ", implode(', ', $result)))));
            }
            break;
    }
} else {
    if (isset($_GET['fetch'])) {
        switch ($_GET['fetch']) {
            case 'getItemsSharedStatuses':
                if (isset($_GET['itemType'])) {
                    $return = OCP\Share::getItemsShared((string) $_GET['itemType'], OCP\Share::FORMAT_STATUSES);
                    is_array($return) ? OC_JSON::success(array('data' => $return)) : OC_JSON::error();
                }
                break;
Example #26
0
 */
namespace OCA_Updater;

\OCP\JSON::checkAdminUser();
// Url to download package e.g. http://download.owncloud.org/releases/owncloud-4.0.5.tar.bz2
$packageUrl = 'http://owncloud.org/releases/owncloud-latest.zip';
//Package version e.g. 4.0.4
$packageVersion = '';
$updateData = \OC_Updater::check();
if (isset($updateData['version'])) {
    $packageVersion = $updateData['version'];
}
if (isset($updateData['url']) && extension_loaded('bz2')) {
    $packageUrl = $updateData['url'];
}
if (!$packageVersion) {
    \OCP\JSON::error(array('msg' => 'Version not found'));
    exit;
}
$sourcePath = Downloader::getPackage($packageUrl, $packageVersion);
if (!$sourcePath) {
    \OCP\JSON::error(array('msg' => 'Unable to fetch package'));
    exit;
}
$backupPath = Backup::createBackup();
if ($backupPath) {
    Updater::update($sourcePath, $backupPath);
    \OCP\JSON::success(array());
} else {
    \OCP\JSON::error(array('msg' => 'Failed to create backup'));
}
Example #27
0
<?php

/**
 * ownCloud - ownpad_lite plugin
 *
 * @author Victor Dubiniuk
 * @copyright 2012 Victor Dubiniuk victor.dubiniuk@gmail.com
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later.
 */
namespace OCA\ownpad_lite;

$serviceUrl = isset($_POST[App::CONFIG_ETHERPAD_URL]) ? $_POST[App::CONFIG_ETHERPAD_URL] : false;
$username = isset($_POST[App::CONFIG_USERNAME]) ? $_POST[App::CONFIG_USERNAME] : false;
$errors = array();
$username = preg_replace('/[^0-9a-zA-Z\\.\\-_]*/i', '', $username);
if ($username) {
    App::setUsername($username);
} else {
    $errors[] = App::ERROR_USERNAME_INVALID;
}
if ($serviceUrl) {
    if (preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $serviceUrl)) {
        App::setServiceUrl($serviceUrl);
    } else {
        $errors[] = App::ERROR_URL_INVALID;
    }
}
\OCP\JSON::success(array('data' => $errors));
Example #28
0
        } catch (\Exception $e) {
            \OCP\JSON::error(array('message' => $e->getMessage()));
            exit;
        }
        \OCP\JSON::error();
        exit;
        break;
    case 'save':
        $key = isset($_POST['cfgkey']) ? $_POST['cfgkey'] : false;
        $val = isset($_POST['cfgval']) ? $_POST['cfgval'] : null;
        if ($key === false || is_null($val)) {
            \OCP\JSON::error(array('message' => $l->t('No data specified')));
            exit;
        }
        $cfg = array($key => $val);
        $setParameters = array();
        $configuration->setConfiguration($cfg, $setParameters);
        if (!in_array($key, $setParameters)) {
            \OCP\JSON::error(array('message' => $l->t($key . ' Could not set configuration %s', $setParameters[0])));
            exit;
        }
        $configuration->saveConfiguration();
        //clear the cache on save
        $connection = new \OCA\user_ldap\lib\Connection($ldapWrapper, $prefix);
        $connection->clearCache();
        OCP\JSON::success();
        break;
    default:
        //TODO: return 4xx error
        break;
}
<?php

/**
 * Copyright (c) 2013, Bjoern Schiessle <*****@*****.**>
 * This file is licensed under the Affero General Public License version 3 or later.
 * See the COPYING-README file.
 *
 * check migration status
 */
use OCA\Encryption\Util;
\OCP\JSON::checkAppEnabled('files_encryption');
$loginname = isset($_POST['user']) ? $_POST['user'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';
$migrationStatus = Util::MIGRATION_COMPLETED;
if ($loginname !== '' && $password !== '') {
    $username = \OCP\User::checkPassword($loginname, $password);
    if ($username) {
        $util = new Util(new \OC\Files\View('/'), $username);
        $migrationStatus = $util->getMigrationStatus();
    }
}
\OCP\JSON::success(array('data' => array('migrationStatus' => $migrationStatus)));
Example #30
0
 * License as published by the Free Software Foundation; either 
 * version 3 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *  
 * You should have received a copy of the GNU Affero General Public
 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */
namespace OCA\Documents;

\OCP\User::checkLoggedIn();
\OCP\JSON::checkAppEnabled('documents');
\OCP\App::setActiveNavigationEntry('documents_index');
\OCP\Util::addStyle('documents', 'style');
\OCP\Util::addStyle('documents', '3rdparty/webodf/dojo-app');
\OCP\Util::addScript('documents', 'documents');
\OCP\Util::addScript('files', 'file-upload');
\OCP\Util::addScript('files', 'jquery.iframe-transport');
\OCP\Util::addScript('files', 'jquery.fileupload');
$tmpl = new \OCP\Template('documents', 'documents', 'user');
$previewsEnabled = \OC::$server->getConfig()->getSystemValue('enable_previews', true);
$unstable = \OCP\Config::getAppValue('documents', 'unstable', 'false');
$maxUploadFilesize = \OCP\Util::maxUploadFilesize("/");
$savePath = \OCP\Config::getUserValue(\OCP\User::getUser(), 'documents', 'save_path', '/');
$tmpl->assign('enable_previews', $previewsEnabled);
$tmpl->assign('useUnstable', $unstable);
$tmpl->assign('uploadMaxFilesize', $maxUploadFilesize);