Example #1
0
 /**
  * Forces an URL rewrite to the specified path
  *
  * @param string $fix_uri  URL to forcibly redirect to
  * @param int    $http HTPP status code for the redirect
  */
 static function fixPath(string $fix_uri, int $http = self::FIXPATH_TEMP)
 {
     $_split = explode('?', $_SERVER['REQUEST_URI'], 2);
     $path = $_split[0];
     $query = empty($_split[1]) ? '' : "?{$_split[1]}";
     $_split = explode('?', $fix_uri, 2);
     $fix_path = $_split[0];
     $fix_query = empty($_split[1]) ? '' : "?{$_split[1]}";
     if (empty($fix_query)) {
         $fix_query = $query;
     } else {
         $query_assoc = self::queryStringAssoc($query);
         $fix_query_assoc = self::queryStringAssoc($fix_query);
         $merged = $query_assoc;
         foreach ($fix_query_assoc as $key => $item) {
             $merged[$key] = $item;
         }
         $fix_query_arr = array();
         foreach ($merged as $key => $item) {
             if (!isset($item) || $item !== self::FIXPATH_EMPTY) {
                 $fix_query_arr[] = $key . (!empty($item) ? '=' . urlencode($item) : '');
             }
         }
         $fix_query = empty($fix_query_arr) ? '' : '?' . implode('&', $fix_query_arr);
     }
     if ($path !== $fix_path || $query !== $fix_query) {
         HTTP::redirect("{$fix_path}{$fix_query}", $http);
     }
 }
Example #2
0
                echo "pong";
                break;
            default:
                CoreUtils::notFound();
        }
        exit;
    }
    CoreUtils::notFound();
}
// Static redirects
switch ($do) {
    // PAGES
    case "logs":
        $do = 'admin';
        $data = rtrim("logs/{$data}", '/');
        HTTP::redirect(rtrim("/{$do}/{$data}", '/'));
        break;
    case "u":
        $do = 'user';
        break;
    case "cg":
    case "colourguides":
    case "colourguide":
    case "colorguides":
        $do = 'colorguide';
        break;
}
// Load controller
$controller = INCPATH . "controllers/{$do}.php";
if (!($do === 'colorguide' && preg_match(new RegExp('\\.(svg|png)$'), $data))) {
    Users::authenticate();
Example #3
0
 /**
  * Requests or refreshes an Access Token
  * $type defaults to 'authorization_code'
  *
  * @param string $code
  * @param null|string $type
  *
  * @return User|void
  */
 static function getToken(string $code, string $type = null)
 {
     global $Database, $http_response_header;
     if (empty($type) || !in_array($type, array('authorization_code', 'refresh_token'))) {
         $type = 'authorization_code';
     }
     $URL_Start = 'https://www.deviantart.com/oauth2/token?client_id=' . DA_CLIENT . '&client_secret=' . DA_SECRET . "&grant_type={$type}";
     switch ($type) {
         case "authorization_code":
             $json = DeviantArt::request("{$URL_Start}&code={$code}" . OAUTH_REDIRECT_URI, false);
             break;
         case "refresh_token":
             $json = DeviantArt::request("{$URL_Start}&refresh_token={$code}", false);
             break;
     }
     if (empty($json)) {
         if (Cookie::exists('access')) {
             $Database->where('access', Cookie::get('access'))->delete('sessions');
             Cookie::delete('access', Cookie::HTTPONLY);
         }
         HTTP::redirect("/da-auth?error=server_error&error_description={$http_response_header[0]}");
     }
     if (empty($json['status'])) {
         HTTP::redirect("/da-auth?error={$json['error']}&error_description={$json['error_description']}");
     }
     $userdata = DeviantArt::request('user/whoami', $json['access_token']);
     /** @var $User Models\User */
     $User = $Database->where('id', $userdata['userid'])->getOne('users');
     if (isset($User->role) && $User->role === 'ban') {
         $_GET['error'] = 'user_banned';
         $BanReason = $Database->where('target', $User->id)->orderBy('entryid', 'ASC')->getOne('log__banish');
         if (!empty($BanReason)) {
             $_GET['error_description'] = $BanReason['reason'];
         }
         return;
     }
     $UserID = strtolower($userdata['userid']);
     $UserData = array('name' => $userdata['username'], 'avatar_url' => URL::makeHttps($userdata['usericon']));
     $AuthData = array('access' => $json['access_token'], 'refresh' => $json['refresh_token'], 'expires' => date('c', time() + intval($json['expires_in'])), 'scope' => $json['scope']);
     $cookie = bin2hex(random_bytes(64));
     $AuthData['token'] = sha1($cookie);
     $browser = CoreUtils::detectBrowser();
     foreach ($browser as $k => $v) {
         if (!empty($v)) {
             $AuthData[$k] = $v;
         }
     }
     if (empty($User)) {
         $MoreInfo = array('id' => $UserID, 'role' => 'user');
         $makeDev = !$Database->has('users');
         if ($makeDev) {
             $MoreInfo['id'] = strtoupper($MoreInfo['id']);
         }
         $Insert = array_merge($UserData, $MoreInfo);
         $Database->insert('users', $Insert);
         $User = new User($Insert);
         if ($makeDev) {
             $User->updateRole('developer');
         }
     } else {
         $Database->where('id', $UserID)->update('users', $UserData);
     }
     if (empty($makeDev) && !empty($User) && Permission::insufficient('member', $User->role) && $User->isClubMember()) {
         $User->updateRole('member');
     }
     if ($type === 'refresh_token') {
         $Database->where('refresh', $code)->update('sessions', $AuthData);
     } else {
         $Database->where('user', $User->id)->where('scope', $AuthData['scope'], '!=')->delete('sessions');
         $Database->insert('sessions', array_merge($AuthData, array('user' => $UserID)));
     }
     $Database->rawQuery("DELETE FROM sessions WHERE \"user\" = ? && lastvisit <= NOW() - INTERVAL '1 MONTH'", array($UserID));
     Cookie::set('access', $cookie, time() + Time::$IN_SECONDS['year'], Cookie::HTTPONLY);
     return $User ?? null;
 }
Example #4
0
 /**
  * Loads the episode page
  *
  * @param null|int|Episode $force              If null: Parses $data and loads approperiate epaisode
  *                                             If array: Uses specified arra as Episode data
  * @param bool             $serverSideRedirect Handle redirection to the correct page on the server/client side
  */
 static function loadPage($force = null, $serverSideRedirect = true)
 {
     global $data, $CurrentEpisode, $Database, $PrevEpisode, $NextEpisode, $LinkedPost;
     if ($force instanceof Episode) {
         $CurrentEpisode = $force;
     } else {
         $EpData = self::parseID($data);
         if ($EpData['season'] === 0) {
             error_log("Attempted visit to {$data} from " . (!empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '[unknown referrer]') . ', redirecting to /movie page');
             HTTP::redirect('/movie/' . $EpData['episode']);
         }
         $CurrentEpisode = empty($EpData) ? self::getLatest() : self::getActual($EpData['season'], $EpData['episode']);
     }
     if (empty($CurrentEpisode)) {
         CoreUtils::notFound();
     }
     $url = $CurrentEpisode->formatURL();
     if (!empty($LinkedPost)) {
         $url .= '#' . $LinkedPost->getID();
     }
     if ($serverSideRedirect) {
         CoreUtils::fixPath($url);
     }
     $js = array('imagesloaded.pkgd', 'jquery.ba-throttle-debounce', 'jquery.fluidbox', 'Chart', 'episode');
     if (Permission::sufficient('member')) {
         $js[] = 'episode-manage';
     }
     if (Permission::sufficient('staff')) {
         $js[] = 'moment-timezone';
         $js[] = 'episodes-manage';
     }
     if (!$CurrentEpisode->isMovie) {
         $PrevEpisode = $Database->where('no', $CurrentEpisode->no, '<')->where('season', 0, '!=')->orderBy('no', 'DESC')->getOne('episodes', 'season,episode,title,twoparter');
         $NextEpisode = $Database->where('no', $CurrentEpisode->no, '>')->where('season', 0, '!=')->orderBy('no', 'ASC')->getOne('episodes', 'season,episode,title,twoparter');
     } else {
         $PrevEpisode = $Database->where('season', 0)->where('episode', $CurrentEpisode->episode, '<')->orderBy('episode', 'DESC')->getOne('episodes', 'season,episode,title');
         $NextEpisode = $Database->where('season', 0)->where('episode', $CurrentEpisode->episode, '>')->orderBy('episode', 'ASC')->getOne('episodes', 'season,episode,title');
     }
     $heading = $CurrentEpisode->formatTitle();
     CoreUtils::loadPage(array('title' => "{$heading} - Vector Requests & Reservations", 'heading' => $heading, 'view' => 'episode', 'css' => 'episode', 'js' => $js, 'url' => $serverSideRedirect ? null : $url));
 }
Example #5
0
 /**
  * Check authentication cookie and set global
  */
 static function authenticate()
 {
     global $Database, $signedIn, $currentUser, $Color, $color;
     CSRFProtection::detect();
     if (!POST_REQUEST && isset($_GET['CSRF_TOKEN'])) {
         HTTP::redirect(CSRFProtection::removeParamFromURL($_SERVER['REQUEST_URI']));
     }
     if (!Cookie::exists('access')) {
         return;
     }
     $authKey = Cookie::get('access');
     if (!empty($authKey)) {
         if (!preg_match(new RegExp('^[a-f\\d]+$', 'iu'), $authKey)) {
             $oldAuthKey = $authKey;
             $authKey = bin2hex($authKey);
             $Database->where('token', sha1($oldAuthKey))->update('sessions', array('token' => sha1($authKey)));
             Cookie::set('access', $authKey, time() + Time::$IN_SECONDS['year'], Cookie::HTTPONLY);
         }
         $currentUser = Users::get(sha1($authKey), 'token');
     }
     if (!empty($currentUser)) {
         if ($currentUser->role === 'ban') {
             $Database->where('id', $currentUser->id)->delete('sessions');
         } else {
             if (strtotime($currentUser->Session['expires']) < time()) {
                 $tokenvalid = false;
                 try {
                     DeviantArt::getToken($currentUser->Session['refresh'], 'refresh_token');
                     $tokenvalid = true;
                 } catch (CURLRequestException $e) {
                     $Database->where('id', $currentUser->Session['id'])->delete('sessions');
                     trigger_error("Session refresh failed for {$currentUser->name} ({$currentUser->id}) | {$e->getMessage()} (HTTP {$e->getCode()})", E_USER_WARNING);
                 }
             } else {
                 $tokenvalid = true;
             }
             if ($tokenvalid) {
                 $signedIn = true;
                 if (time() - strtotime($currentUser->Session['lastvisit']) > Time::$IN_SECONDS['minute']) {
                     $lastVisitTS = date('c');
                     if ($Database->where('id', $currentUser->Session['id'])->update('sessions', array('lastvisit' => $lastVisitTS))) {
                         $currentUser->Session['lastvisit'] = $lastVisitTS;
                     }
                 }
                 $_PrefersColour = array('Pirill-Poveniy' => true, 'itv-canterlot' => true);
                 if (isset($_PrefersColour[$currentUser->name])) {
                     $Color = 'Colour';
                     $color = 'colour';
                 }
             }
         }
     } else {
         Cookie::delete('access', Cookie::HTTPONLY);
     }
 }
Example #6
0
<?php

use App\HTTP;
/** @var $data string */
if (is_numeric($data)) {
    HTTP::redirect("/movie/{$data}");
} else {
    HTTP::redirect("/movie/equestria-girls-{$data}");
}
Example #7
0
        $errdesc = $_GET['error_description'];
    }
    global $signedIn;
    if ($signedIn) {
        HTTP::redirect($_GET['state']);
    }
    Episodes::loadPage();
}
$currentUser = DeviantArt::getToken($_GET['code']);
$signedIn = !empty($currentUser);
if (isset($_GET['error'])) {
    $err = $_GET['error'];
    if (isset($_GET['error_description'])) {
        $errdesc = $_GET['error_description'];
    }
    if ($err === 'user_banned') {
        $errdesc .= "\n\nIf you'd like to appeal your ban, please <a href='http://mlp-vectorclub.deviantart.com/notes/'>send the group a note</a>.";
    }
    Episodes::loadPage();
}
if (preg_match(new RegExp('^[a-z\\d]+$', 'i'), $_GET['state'], $_match)) {
    $confirm = str_replace('{{CODE}}', $_match[0], file_get_contents(INCPATH . 'views/loginConfrim.html'));
    $confirm = str_replace('{{USERID}}', Permission::sufficient('developer') || UserPrefs::get('p_disable_ga') ? '' : $currentUser->id, $confirm);
    die($confirm);
} else {
    if (preg_match($REWRITE_REGEX, $_GET['state'])) {
        HTTP::redirect($_GET['state']);
    }
}
HTTP::redirect('/');