Esempio n. 1
0
    /**
     * @param integer $id
     * @param null|PdoDatabase $database
     * @return Comment[]
     * @throws Exception
     */
    public static function getForRequest($id, PdoDatabase $database = null)
    {
        if ($database == null) {
            $database = gGetDb();
        }
        if (User::getCurrent()->isAdmin() || User::getCurrent()->isCheckuser()) {
            // current user is an admin or checkuser, so retrieve everything.
            $statement = $database->prepare("SELECT * FROM comment WHERE request = :target;");
        } else {
            // current user isn't an admin, so limit to only those which are visible to users, and private comments
            // the user has posted themselves.
            $statement = $database->prepare(<<<SQL
SELECT * FROM comment
WHERE request = :target AND (visibility = 'user' OR user = :userid);
SQL
);
            $statement->bindValue(":userid", User::getCurrent()->getId());
        }
        $statement->bindValue(":target", $id);
        $statement->execute();
        $result = array();
        /** @var Comment $v */
        foreach ($statement->fetchAll(PDO::FETCH_CLASS, get_called_class()) as $v) {
            $v->isNew = false;
            $v->setDatabase($database);
            $result[] = $v;
        }
        return $result;
    }
Esempio n. 2
0
 public function executeQueryToArray($query)
 {
     $database = gGetDb();
     $statement = $database->prepare($query);
     $statement->execute();
     return $statement->fetchAll($this->rowFetchMode);
 }
Esempio n. 3
0
    private function getUserDetail($userId)
    {
        $database = gGetDb();
        $user = User::getById($userId, $database);
        if ($user == false) {
            return BootstrapSkin::displayAlertBox("User not found", "alert-error", "Error", true, false, true);
        }
        global $smarty;
        $activitySummary = $database->prepare(<<<SQL
            SELECT COALESCE(c.mail_desc, l.log_action) AS action, COUNT(*) AS count 
            FROM acc_log l 
            LEFT JOIN closes c ON l.log_action = c.closes 
            WHERE l.log_user = :username 
            GROUP BY action;
SQL
);
        $activitySummary->execute(array(":username" => $user->getUsername()));
        $activitySummaryData = $activitySummary->fetchAll(PDO::FETCH_ASSOC);
        $smarty->assign("user", $user);
        $smarty->assign("activity", $activitySummaryData);
        $usersCreatedQuery = $database->prepare(<<<SQL
            SELECT l.log_time time, r.name name, r.id id 
            FROM acc_log l
            JOIN request r ON r.id = l.log_pend 
            LEFT JOIN emailtemplate e ON concat('Closed ', e.id) = l.log_action 
            WHERE l.log_user = :username 
                AND l.log_action LIKE 'Closed %' 
                AND (e.oncreated = '1' OR l.log_action = 'Closed custom-y') 
            ORDER BY l.log_time;
SQL
);
        $usersCreatedQuery->execute(array(":username" => $user->getUsername()));
        $usersCreated = $usersCreatedQuery->fetchAll(PDO::FETCH_ASSOC);
        $smarty->assign("created", $usersCreated);
        $usersNotCreatedQuery = $database->prepare(<<<SQL
            SELECT l.log_time time, r.name name, r.id id 
            FROM acc_log l
            JOIN request r ON r.id = l.log_pend 
            LEFT JOIN emailtemplate e ON concat('Closed ', e.id) = l.log_action 
            WHERE l.log_user = :username 
                AND l.log_action LIKE 'Closed %' 
                AND (e.oncreated = '0' OR l.log_action = 'Closed custom-n' OR l.log_action='Closed 0') 
            ORDER BY l.log_time;
SQL
);
        $usersNotCreatedQuery->execute(array(":username" => $user->getUsername()));
        $usersNotCreated = $usersNotCreatedQuery->fetchAll(PDO::FETCH_ASSOC);
        $smarty->assign("notcreated", $usersNotCreated);
        $accountLogQuery = $database->prepare(<<<SQL
            SELECT * 
            FROM acc_log l 
            WHERE l.log_pend = :userid 
\t            AND log_action IN ('Approved','Suspended','Declined','Promoted','Demoted','Renamed','Prefchange');     
SQL
);
        $accountLogQuery->execute(array(":userid" => $user->getId()));
        $accountLog = $accountLogQuery->fetchAll(PDO::FETCH_ASSOC);
        $smarty->assign("accountlog", $accountLog);
        return $smarty->fetch("statistics/userdetail.tpl");
    }
Esempio n. 4
0
 /**
  * Prints the internal interface footer to the screen.
  *
  * @param string|null $tailscript JavaScript to append to the page, usually so it can call jQuery
  * @throws Exception
  */
 public static function displayInternalFooter($tailscript = null)
 {
     global $smarty;
     // close all declared open tags
     while (count(self::$tagstack) != 0) {
         echo array_pop(self::$tagstack);
     }
     $last5min = time() - 300;
     $last5mins = date("Y-m-d H:i:s", $last5min);
     $database = gGetDb();
     $statement = $database->prepare("SELECT * FROM user WHERE lastactive > :lastfive;");
     $statement->execute(array(":lastfive" => $last5mins));
     $resultSet = $statement->fetchAll(PDO::FETCH_CLASS, "User");
     $resultSetCount = count($resultSet);
     $creators = implode(", ", array_map(function ($arg) {
         /** @var User $arg */
         return "<a href=\"statistics.php?page=Users&amp;user="******"\">" . htmlentities($arg->getUsername()) . "</a>";
     }, $resultSet));
     // not equal to one, as zero uses the plural form too.
     if ($resultSetCount != 1) {
         $onlinemessage = $resultSetCount . " Account Creators currently online (past 5 minutes): {$creators}";
     } else {
         $onlinemessage = $resultSetCount . " Account Creator currently online (past 5 minutes): {$creators}";
     }
     $online = '<p class="span6 text-right"><small>' . $onlinemessage . '</small></p>';
     if (isset($_SESSION['user'])) {
         $smarty->assign("onlineusers", $online);
     } else {
         $emptystring = "";
         $smarty->assign("onlineusers", $emptystring);
     }
     $smarty->assign("tailscript", $tailscript);
     $smarty->display("footer.tpl");
 }
Esempio n. 5
0
 /**
  * Returns a value if the IP address is a trusted proxy
  * @param string $ip
  * @param PdoDatabase $database
  * @return bool
  */
 public function isTrusted($ip, PdoDatabase $database = null)
 {
     if (in_array($ip, $this->trustedCache)) {
         return true;
     }
     if (in_array($ip, $this->untrustedCache)) {
         return false;
     }
     if ($database == null) {
         $database = gGetDb();
     }
     $query = "SELECT COUNT(*) FROM xfftrustcache WHERE ip = :ip;";
     $statement = $database->prepare($query);
     $statement->execute(array(":ip" => $ip));
     $result = $statement->fetchColumn();
     $statement->closeCursor();
     if ($result == 0) {
         $this->untrustedCache[] = $ip;
         return false;
     }
     if ($result >= 1) {
         $this->trustedCache[] = $ip;
         return true;
     }
     // something weird has happened if we've got here.
     // default to untrusted.
     return false;
 }
Esempio n. 6
0
 /**
  * Summary of execute
  * @param \DOMElement $apiDocument
  * @return \DOMElement
  * @throws ApiException
  * @throws \Exception
  */
 public function execute(\DOMElement $apiDocument)
 {
     $username = isset($_GET['user']) ? trim($_GET['user']) : '';
     $wikiusername = isset($_GET['wikiuser']) ? trim($_GET['wikiuser']) : '';
     if ($username === '' && $wikiusername === '') {
         throw new ApiException("Please specify a username using either user or wikiuser parameters.");
     }
     $userElement = $this->document->createElement("user");
     $apiDocument->appendChild($userElement);
     $this->database = gGetDb();
     if ($username !== '') {
         $this->user = \User::getByUsername($username, $this->database);
     } else {
         $this->user = \User::getByOnWikiUsername($wikiusername, $this->database);
     }
     if ($this->user === false) {
         $userElement->setAttribute("missing", "true");
         return $apiDocument;
     }
     $userElement->setAttribute("username", $this->user->getUsername());
     $userElement->setAttribute("status", $this->user->getStatus());
     $userElement->setAttribute("lastactive", $this->user->getLastActive());
     $userElement->setAttribute("welcome_template", $this->user->getWelcomeTemplate());
     $userElement->setAttribute("onwikiname", $this->user->getOnWikiName());
     $userElement->setAttribute("oauth", $this->user->isOAuthLinked() ? "true" : "false");
     return $apiDocument;
 }
Esempio n. 7
0
 /**
  * Gets the relevant statistics from the database for the small statistics table
  */
 private function smallStats()
 {
     global $smarty;
     $database = gGetDb();
     $requestsQuery = "SELECT COUNT(*) FROM request WHERE status = :status AND emailconfirm = 'Confirmed';";
     $requestsStatement = $database->prepare($requestsQuery);
     // TODO: use the request states thing here.
     // Open Requests
     $requestsStatement->execute(array(":status" => "Open"));
     $open = $requestsStatement->fetchColumn();
     $requestsStatement->closeCursor();
     $smarty->assign("statsOpen", $open);
     // Admin Requests
     $requestsStatement->execute(array(":status" => "Admin"));
     $admin = $requestsStatement->fetchColumn();
     $requestsStatement->closeCursor();
     $smarty->assign("statsAdmin", $admin);
     // Checkuser Requests
     $requestsStatement->execute(array(":status" => "Checkuser"));
     $checkuser = $requestsStatement->fetchColumn();
     $requestsStatement->closeCursor();
     $smarty->assign("statsCheckuser", $checkuser);
     // Unconfirmed requests
     $unconfirmedStatement = $database->query("SELECT COUNT(*) FROM request WHERE emailconfirm != 'Confirmed' AND emailconfirm != '';");
     $unconfirmed = $unconfirmedStatement->fetchColumn();
     $unconfirmedStatement->closeCursor();
     $smarty->assign("statsUnconfirmed", $unconfirmed);
     $userStatusStatement = $database->prepare("SELECT COUNT(*) FROM user WHERE status = :status;");
     // Admin users
     $userStatusStatement->execute(array(":status" => "Admin"));
     $adminusers = $userStatusStatement->fetchColumn();
     $userStatusStatement->closeCursor();
     $smarty->assign("statsAdminUsers", $adminusers);
     // Users
     $userStatusStatement->execute(array(":status" => "User"));
     $users = $userStatusStatement->fetchColumn();
     $userStatusStatement->closeCursor();
     $smarty->assign("statsUsers", $users);
     // Suspended users
     $userStatusStatement->execute(array(":status" => "Suspended"));
     $suspendedUsers = $userStatusStatement->fetchColumn();
     $userStatusStatement->closeCursor();
     $smarty->assign("statsSuspendedUsers", $suspendedUsers);
     // New users
     $userStatusStatement->execute(array(":status" => "New"));
     $newUsers = $userStatusStatement->fetchColumn();
     $userStatusStatement->closeCursor();
     $smarty->assign("statsNewUsers", $newUsers);
     // Most comments on a request
     $mostCommentsStatement = $database->query("SELECT request FROM comment GROUP BY request ORDER BY COUNT(*) DESC LIMIT 1;");
     $mostComments = $mostCommentsStatement->fetchColumn();
     $mostCommentsStatement->closeCursor();
     $smarty->assign("mostComments", $mostComments);
 }
Esempio n. 8
0
 protected function execute()
 {
     global $smarty;
     $showImmune = false;
     if (isset($_GET['showimmune'])) {
         $showImmune = true;
     }
     $smarty->assign("showImmune", $showImmune);
     $inactiveUsers = User::getAllInactive(gGetDb());
     $smarty->assign("inactiveUsers", $inactiveUsers);
     return $smarty->fetch("statistics/inactiveusers.tpl");
 }
Esempio n. 9
0
    public function execute(\DOMElement $apiDocument)
    {
        $this->database = gGetDb();
        $statusElement = $this->document->createElement("status");
        $apiDocument->appendChild($statusElement);
        $query = $this->database->prepare(<<<SQL
            SELECT /* Api/StatusAction */ COUNT(*) AS count
            FROM request
            WHERE
                status = :pstatus
                AND emailconfirm = 'Confirmed';
SQL
);
        global $availableRequestStates;
        foreach ($availableRequestStates as $key => $value) {
            $query->bindValue(":pstatus", $key);
            $query->execute();
            $sus = $query->fetchColumn();
            $statusElement->setAttribute($value['api'], $sus);
            $query->closeCursor();
        }
        $query = $this->database->prepare(<<<SQL
            SELECT /* Api/StatusAction */ COUNT(*) AS count
            FROM ban
            WHERE
                (duration > UNIX_TIMESTAMP() OR duration = -1)
                AND active = 1;
SQL
);
        $query->execute();
        $sus = $query->fetchColumn();
        $statusElement->setAttribute("bans", $sus);
        $query->closeCursor();
        $query = $this->database->prepare("SELECT /* Api/StatusAction */ COUNT(*) AS count FROM user WHERE status = :ulevel;");
        $query->bindValue(":ulevel", "Admin");
        $query->execute();
        $sus = $query->fetchColumn();
        $statusElement->setAttribute("useradmin", $sus);
        $query->closeCursor();
        $query->bindValue(":ulevel", "User");
        $query->execute();
        $sus = $query->fetchColumn();
        $statusElement->setAttribute("user", $sus);
        $query->closeCursor();
        $query->bindValue(":ulevel", "New");
        $query->execute();
        $sus = $query->fetchColumn();
        $statusElement->setAttribute("usernew", $sus);
        $query->closeCursor();
        return $apiDocument;
    }
Esempio n. 10
0
    /**
     * This function removes all old requests which are not yet email-confirmed
     * from the database.
     */
    public static function cleanExpiredUnconfirmedRequests()
    {
        global $emailConfirmationExpiryDays;
        $database = gGetDb();
        $statement = $database->prepare(<<<SQL
            DELETE FROM request
            WHERE
                date < DATE_SUB(CURRENT_TIMESTAMP(), INTERVAL {$emailConfirmationExpiryDays} DAY)
                AND emailconfirm != 'Confirmed'
                AND emailconfirm != '';
SQL
);
        $statement->execute();
    }
Esempio n. 11
0
 public function execute(\DOMElement $apiDocument)
 {
     $this->database = gGetDb();
     $now = new \DateTime();
     $old = $this->getOldest();
     $oldest = new \DateTime($old);
     $new = $this->getNewest();
     $newest = new \DateTime($new);
     $monitoringElement = $this->document->createElement("data");
     $monitoringElement->setAttribute("date", $now->format('c'));
     $monitoringElement->setAttribute("oldest", $old == null ? null : $oldest->format('c'));
     $monitoringElement->setAttribute("newest", $new == null ? null : $newest->format('c'));
     $apiDocument->appendChild($monitoringElement);
     return $apiDocument;
 }
Esempio n. 12
0
 /**
  * Summary of getAll
  * @param PdoDatabase $database
  * @return WelcomeTemplate[]
  */
 public static function getAll(PdoDatabase $database = null)
 {
     if ($database == null) {
         $database = gGetDb();
     }
     $statement = $database->prepare("SELECT * FROM welcometemplate;");
     $statement->execute();
     $result = array();
     foreach ($statement->fetchAll(PDO::FETCH_CLASS, get_called_class()) as $v) {
         $v->isNew = false;
         $v->setDatabase($database);
         $result[] = $v;
     }
     return $result;
 }
Esempio n. 13
0
 /**
  * Summary of getCurrent
  * @param PdoDatabase $database
  * @return User The currently logged in user, or an anonymous coward with userid -1.
  */
 public static function getCurrent(PdoDatabase $database = null)
 {
     if ($database === null) {
         $database = gGetDb();
     }
     if (self::$currentUser === null) {
         if (isset($_SESSION['userID'])) {
             self::$currentUser = self::getById($_SESSION['userID'], $database);
         } else {
             $anonymousCoward = new CommunityUser();
             self::$currentUser = $anonymousCoward;
         }
     }
     return self::$currentUser;
 }
Esempio n. 14
0
 /**
  * Gets active non-preload and preload templates
  * @param string $defaultAction Default action to take (EmailTemplate::CREATED or EmailTemplate::NOT_CREATED)
  * @param PdoDatabase $database 
  * @return array|false
  */
 public static function getAllActiveTemplates($defaultAction, PdoDatabase $database = null)
 {
     if ($database == null) {
         $database = gGetDb();
     }
     $statement = $database->prepare("SELECT * FROM `emailtemplate` WHERE defaultaction = :forcreated AND active = 1;");
     if ($defaultAction === false) {
         $statement = $database->prepare("SELECT * FROM `emailtemplate` WHERE defaultaction not in ('created', 'not created') AND active = 1;");
     }
     $statement->bindValue(":forcreated", $defaultAction);
     $statement->execute();
     $resultObject = $statement->fetchAll(PDO::FETCH_CLASS, get_called_class());
     foreach ($resultObject as $t) {
         $t->setDatabase($database);
         $t->isNew = false;
     }
     return $resultObject;
 }
 public function getSpoofs($username)
 {
     global $mediawikiWebServiceEndpoint;
     $cacheResult = AntiSpoofCache::getByUsername($username, gGetDb());
     if ($cacheResult == false) {
         // get the data from the API
         $data = file_get_contents($mediawikiWebServiceEndpoint . "?action=antispoof&format=php&username="******"Unrecognised API response to query: " . $result['error']['info']);
         }
         throw new Exception("Unrecognised API response to query.");
     }
     if ($result['antispoof']['result'] == "pass") {
         // All good here!
         return array();
     }
     if ($result['antispoof']['result'] == "conflict") {
         // we've got conflicts, let's do something with them.
         return $result['antispoof']['users'];
     }
     if ($result['antispoof']['result'] == "error") {
         // we've got conflicts, let's do something with them.
         throw new Exception("Encountered error while getting result: " . $result['antispoof']['error']);
     }
     throw new Exception("Unrecognised API response to query.");
 }
Esempio n. 16
0
 public function execute(\DOMElement $apiDocument)
 {
     $username = isset($_GET['user']) ? trim($_GET['user']) : '';
     if ($username == '') {
         throw new ApiException("Please specify a username");
     }
     $userElement = $this->document->createElement("user");
     $userElement->setAttribute("name", $username);
     $apiDocument->appendChild($userElement);
     $this->database = gGetDb();
     $this->user = \User::getByUsername($username, $this->database);
     if ($this->user === false) {
         $userElement->setAttribute("missing", "true");
         return $apiDocument;
     }
     $userElement->setAttribute("level", $this->user->getStatus());
     $userElement->setAttribute("created", $this->getAccountsCreated());
     $userElement->setAttribute("today", $this->getToday());
     if ($this->user->isAdmin()) {
         $this->fetchAdminData($userElement);
     }
     return $apiDocument;
 }
Esempio n. 17
0
 protected function execute()
 {
     $qb = new QueryBrowser();
     $query = "SELECT COUNT(DISTINCT log_id) AS 'Requests Closed', YEAR(log_time) AS 'Year', MONTHNAME(log_time) AS 'Month' FROM acc_log WHERE log_action LIKE 'Closed%' GROUP BY EXTRACT(YEAR_MONTH FROM log_time) ORDER BY YEAR(log_time), MONTH(log_time) ASC;";
     $out = $qb->executeQueryToTable($query);
     global $showGraphs;
     if ($showGraphs == 1) {
         global $filepath;
         require_once $filepath . 'graph/pChart/pChart.class';
         require_once $filepath . 'graph/pChart/pData.class';
         $queries = array();
         $queries[] = array('query' => "SELECT COUNT(DISTINCT log_id) AS 'y', CONCAT( YEAR(log_time), '/' , MONTHNAME(log_time)) AS 'x' FROM acc_log WHERE log_action LIKE 'Closed%' AND YEAR(log_time) != 0 GROUP BY EXTRACT(YEAR_MONTH FROM log_time) ORDER BY YEAR(log_time), MONTH(log_time) ASC;", 'series' => "All closed requests by month");
         $queries[] = array('query' => "SELECT COUNT(DISTINCT log_id) AS 'y', CONCAT( YEAR(log_time), '/' , MONTHNAME(log_time)) AS 'x' FROM acc_log WHERE log_action LIKE 'Closed 0' AND YEAR(log_time) != 0 GROUP BY EXTRACT(YEAR_MONTH FROM log_time) ORDER BY YEAR(log_time), MONTH(log_time) ASC;", 'series' => "Dropped requests by month");
         $query = gGetDb()->query("SELECT id, name FROM emailtemplate WHERE active = '1';");
         if (!$query) {
             die("Query error.");
         }
         foreach ($query->fetchAll(PDO::FETCH_ASSOC) as $row) {
             $id = $row['id'];
             $name = $row['name'];
             $queries[] = array('query' => "SELECT COUNT(DISTINCT log_id) AS 'y', CONCAT( YEAR(log_time), '/' , MONTHNAME(log_time)) AS 'x' FROM acc_log WHERE log_action LIKE 'Closed {$id}' AND YEAR(log_time) != 0 GROUP BY EXTRACT(YEAR_MONTH FROM log_time) ORDER BY YEAR(log_time), MONTH(log_time) ASC;", 'series' => "{$name} requests by month");
         }
         $queries[] = array('query' => "SELECT COUNT(DISTINCT log_id) AS 'y', CONCAT( YEAR(log_time), '/' , MONTHNAME(log_time)) AS 'x' FROM acc_log WHERE log_action LIKE 'Closed custom-y' AND YEAR(log_time) != 0 GROUP BY EXTRACT(YEAR_MONTH FROM log_time) ORDER BY YEAR(log_time), MONTH(log_time) ASC;", 'series' => "Custom created requests by month");
         $queries[] = array('query' => "SELECT COUNT(DISTINCT log_id) AS 'y', CONCAT( YEAR(log_time), '/' , MONTHNAME(log_time)) AS 'x' FROM acc_log WHERE log_action LIKE 'Closed custom-n' AND YEAR(log_time) != 0 GROUP BY EXTRACT(YEAR_MONTH FROM log_time) ORDER BY YEAR(log_time), MONTH(log_time) ASC;", 'series' => "Custom not created requests by month");
         global $availableRequestStates;
         foreach ($availableRequestStates as $state) {
             $queries[] = array('query' => "SELECT COUNT(DISTINCT log_id) AS 'y', CONCAT( YEAR(log_time), '/' , MONTHNAME(log_time)) AS 'x' FROM acc_log WHERE log_action LIKE 'Deferred to " . $state['defertolog'] . "' AND YEAR(log_time) != 0 GROUP BY EXTRACT(YEAR_MONTH FROM log_time) ORDER BY YEAR(log_time), MONTH(log_time) ASC;", 'series' => "Requests deferred to " . $state['deferto'] . " by month");
         }
         global $baseurl;
         foreach ($this->createClosuresGraph($queries) as $i) {
             $out .= '<img src="' . $baseurl . '/render/' . $i[0] . '" alt="' . $i[1] . '"/>';
         }
     } else {
         $out .= BootstrapSkin::displayAlertBox("Graph drawing is currently disabled.", "alert-info", "", false, false, true);
     }
     return $out;
 }
Esempio n. 18
0
 /**
  * Get a message.
  *
  * This is going to be used as a new way of dealing with saved messages for #28
  *
  * The basic idea is there's a key stored in a new column, and we do lookups on that
  * instead of a possibly variable auto-incrementing ID.
  *
  * We can use class constants so the keys are defined in one place only for now, and for
  * now we are using the auto-incrementing ID as the value of the key, so this function
  * just uses getById() at the moment.
  *
  * @param mixed $key
  * @return mixed
  */
 public static function get($key)
 {
     return self::getById($key, gGetDb())->getContentForDisplay();
 }
Esempio n. 19
0
function zoomPage($id, $urlhash)
{
    global $session, $availableRequestStates, $createdid;
    global $smarty, $locationProvider, $rdnsProvider, $antispoofProvider;
    global $xffTrustProvider, $enableEmailConfirm;
    $database = gGetDb();
    $request = Request::getById($id, $database);
    if ($request == false) {
        // Notifies the user and stops the script.
        BootstrapSkin::displayAlertBox("Could not load the requested request!", "alert-error", "Error", true, false);
        BootstrapSkin::displayInternalFooter();
        die;
    }
    $smarty->assign('ecenable', $enableEmailConfirm);
    if (isset($_GET['ecoverride']) && User::getCurrent()->isAdmin()) {
        $smarty->assign('ecoverride', true);
    } else {
        $smarty->assign('ecoverride', false);
    }
    $smarty->assign('request', $request);
    $smarty->assign("usernamerawunicode", html_entity_decode($request->getName()));
    $smarty->assign("iplocation", $locationProvider->getIpLocation($request->getTrustedIp()));
    $createdreason = EmailTemplate::getById($createdid, gGetDb());
    $smarty->assign("createdEmailTemplate", $createdreason);
    #region setup whether data is viewable or not
    $viewableDataStatement = $database->prepare(<<<SQL
        SELECT COUNT(*) 
        FROM request 
        WHERE 
            (
                email = :email 
                OR ip = :trustedIp 
                OR forwardedip LIKE :trustedProxy
            ) 
            AND reserved = :reserved 
            AND emailconfirm = 'Confirmed' 
            AND status != 'Closed';
SQL
);
    $viewableDataStatement->bindValue(":email", $request->getEmail());
    $viewableDataStatement->bindValue(":reserved", User::getCurrent()->getId());
    $viewableDataStatement->bindValue(":trustedIp", $request->getTrustedIp());
    $viewableDataStatement->bindValue(":trustedProxy", '%' . $request->getTrustedIp() . '%');
    $viewableDataStatement->execute();
    $viewableData = $viewableDataStatement->fetchColumn();
    $viewableDataStatement->closeCursor();
    $hideinfo = $viewableData == 0;
    #endregion
    if ($request->getStatus() == "Closed") {
        $hash = md5($request->getId() . $request->getEmail() . $request->getTrustedIp() . microtime());
        //If the request is closed, change the hash based on microseconds similar to the checksums.
        $smarty->assign("isclosed", true);
    } else {
        $hash = md5($request->getId() . $request->getEmail() . $request->getTrustedIp());
        $smarty->assign("isclosed", false);
    }
    $smarty->assign("hash", $hash);
    if ($hash == $urlhash) {
        $correcthash = true;
    } else {
        $correcthash = false;
    }
    $smarty->assign("showinfo", false);
    if ($hideinfo == false || $correcthash == true || User::getCurrent()->isAdmin() || User::getCurrent()->isCheckuser()) {
        $smarty->assign("showinfo", true);
    }
    // force to not show, overriden later
    $smarty->assign("proxyip", "");
    if ($hideinfo == false || $correcthash == true || User::getCurrent()->isAdmin() || User::getCurrent()->isCheckuser()) {
        $smarty->assign("proxyip", $request->getForwardedIp());
        if ($request->getForwardedIp()) {
            $smartyproxies = array();
            // Initialize array to store data to be output in Smarty template.
            $smartyproxiesindex = 0;
            $proxies = explode(",", $request->getForwardedIp());
            $proxies[] = $request->getIp();
            $origin = $proxies[0];
            $smarty->assign("origin", $origin);
            $proxies = array_reverse($proxies);
            $trust = true;
            global $rfc1918ips;
            foreach ($proxies as $proxynum => $p) {
                $p2 = trim($p);
                $smartyproxies[$smartyproxiesindex]['ip'] = $p2;
                // get data on this IP.
                $trusted = $xffTrustProvider->isTrusted($p2);
                $ipisprivate = ipInRange($rfc1918ips, $p2);
                if (!$ipisprivate) {
                    $iprdns = $rdnsProvider->getRdns($p2);
                    $iplocation = $locationProvider->getIpLocation($p2);
                } else {
                    // this is going to fail, so why bother trying?
                    $iprdns = false;
                    $iplocation = false;
                }
                // current trust chain status BEFORE this link
                $pretrust = $trust;
                // is *this* link trusted?
                $smartyproxies[$smartyproxiesindex]['trustedlink'] = $trusted;
                // current trust chain status AFTER this link
                $trust = $trust & $trusted;
                if ($pretrust && $p2 == $origin) {
                    $trust = true;
                }
                $smartyproxies[$smartyproxiesindex]['trust'] = $trust;
                $smartyproxies[$smartyproxiesindex]['rdnsfailed'] = $iprdns === false;
                $smartyproxies[$smartyproxiesindex]['rdns'] = $iprdns;
                $smartyproxies[$smartyproxiesindex]['routable'] = !$ipisprivate;
                $smartyproxies[$smartyproxiesindex]['location'] = $iplocation;
                if ($iprdns == $p2 && $ipisprivate == false) {
                    $smartyproxies[$smartyproxiesindex]['rdns'] = null;
                }
                $smartyproxies[$smartyproxiesindex]['showlinks'] = (!$trust || $p2 == $origin) && !$ipisprivate;
                $smartyproxiesindex++;
            }
            $smarty->assign("proxies", $smartyproxies);
        }
    }
    global $defaultRequestStateKey;
    // TODO: remove me and replace with call in the template directly
    $smarty->assign("isprotected", $request->isProtected());
    $smarty->assign("defaultstate", $defaultRequestStateKey);
    $smarty->assign("requeststates", $availableRequestStates);
    try {
        $spoofs = $antispoofProvider->getSpoofs($request->getName());
    } catch (Exception $ex) {
        $spoofs = $ex->getMessage();
    }
    $smarty->assign("spoofs", $spoofs);
    // START LOG DISPLAY
    $logs = Logger::getRequestLogsWithComments($request->getId(), $request->getDatabase());
    $requestLogs = array();
    if (trim($request->getComment()) !== "") {
        $requestLogs[] = array('type' => 'comment', 'security' => 'user', 'userid' => null, 'user' => $request->getName(), 'entry' => null, 'time' => $request->getDate(), 'canedit' => false, 'id' => $request->getId(), 'comment' => $request->getComment());
    }
    $namecache = array();
    $editableComments = false;
    if (User::getCurrent()->isAdmin() || User::getCurrent()->isCheckuser()) {
        $editableComments = true;
    }
    foreach ($logs as $entry) {
        // both log and comment have a 'user' field
        if (!array_key_exists($entry->getUser(), $namecache)) {
            $namecache[$entry->getUser()] = $entry->getUserObject();
        }
        if ($entry instanceof Comment) {
            $requestLogs[] = array('type' => 'comment', 'security' => $entry->getVisibility(), 'user' => $namecache[$entry->getUser()]->getUsername(), 'userid' => $entry->getUser() == -1 ? null : $entry->getUser(), 'entry' => null, 'time' => $entry->getTime(), 'canedit' => $editableComments || $entry->getUser() == User::getCurrent()->getId(), 'id' => $entry->getId(), 'comment' => $entry->getComment());
        }
        if ($entry instanceof Log) {
            $requestLogs[] = array('type' => 'log', 'security' => 'user', 'userid' => $entry->getUser() == -1 ? null : $entry->getUser(), 'user' => $namecache[$entry->getUser()]->getUsername(), 'entry' => Logger::getLogDescription($entry), 'time' => $entry->getTimestamp(), 'canedit' => false, 'id' => $entry->getId(), 'comment' => $entry->getComment());
        }
    }
    $smarty->assign("requestLogs", $requestLogs);
    // START OTHER REQUESTS BY IP AND EMAIL STUFF
    // Displays other requests from this ip.
    // assign to user
    $userListQuery = "SELECT username FROM user WHERE status = 'User' or status = 'Admin';";
    $userListResult = gGetDb()->query($userListQuery);
    $userListData = $userListResult->fetchAll(PDO::FETCH_COLUMN);
    $userListProcessedData = array();
    foreach ($userListData as $userListItem) {
        $userListProcessedData[] = "\"" . htmlentities($userListItem) . "\"";
    }
    $userList = '[' . implode(",", $userListProcessedData) . ']';
    $smarty->assign("jsuserlist", $userList);
    // end: assign to user
    // TODO: refactor this!
    $createreasons = EmailTemplate::getActiveTemplates(EmailTemplate::CREATED);
    $smarty->assign("createreasons", $createreasons);
    $declinereasons = EmailTemplate::getActiveTemplates(EmailTemplate::NOT_CREATED);
    $smarty->assign("declinereasons", $declinereasons);
    $allcreatereasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::CREATED);
    $smarty->assign("allcreatereasons", $allcreatereasons);
    $alldeclinereasons = EmailTemplate::getAllActiveTemplates(EmailTemplate::NOT_CREATED);
    $smarty->assign("alldeclinereasons", $alldeclinereasons);
    $allotherreasons = EmailTemplate::getAllActiveTemplates(false);
    $smarty->assign("allotherreasons", $allotherreasons);
    return $smarty->fetch("request-zoom.tpl");
}
Esempio n. 20
0
require_once 'functions.php';
require_once 'includes/PdoDatabase.php';
require_once 'includes/SmartyInit.php';
// Check to see if the database is unavailable.
// Uses the true variable as the public uses this page.
if (Offline::isOffline()) {
    echo Offline::getOfflineMessage(true);
    die;
}
// TODO: move me to a maintenance job
if ($enableEmailConfirm == 1) {
    Request::cleanExpiredUnconfirmedRequests();
}
$antispoofProvider = new $antispoofProviderClass();
$xffTrustProvider = new $xffTrustProviderClass($squidIpList);
$database = gGetDb();
// Display the header of the interface.
BootstrapSkin::displayPublicHeader();
if (isset($_GET['action']) && $_GET['action'] == "confirm") {
    try {
        if (!isset($_GET['id']) || !isset($_GET['si'])) {
            BootstrapSkin::displayAlertBox("Please check the link you received", "alert-error", "Missing parameters", true, false);
            BootstrapSkin::displayPublicFooter();
            die;
        }
        $request = Request::getById($_GET['id'], $database);
        if ($request === false) {
            BootstrapSkin::displayAlertBox($smarty->fetch('request/request-not-found.tpl'), "alert-error", "Request not found", true, false);
            BootstrapSkin::displayPublicFooter();
            die;
        }
Esempio n. 21
0
function defaultpage()
{
    global $availableRequestStates, $defaultRequestStateKey, $requestLimitShowOnly, $enableEmailConfirm;
    $database = gGetDb();
    $requestSectionData = array();
    if ($enableEmailConfirm == 1) {
        $query = "SELECT * FROM request WHERE status = :type AND emailconfirm = 'Confirmed' LIMIT :lim;";
        $totalquery = "SELECT COUNT(*) FROM request WHERE status = :type AND emailconfirm = 'Confirmed';";
    } else {
        $query = "SELECT * FROM request WHERE status = :type LIMIT :lim;";
        $totalquery = "SELECT COUNT(*) FROM request WHERE status = :type;";
    }
    $statement = $database->prepare($query);
    $statement->bindValue(":lim", $requestLimitShowOnly, PDO::PARAM_INT);
    $totalRequestsStatement = $database->prepare($totalquery);
    // list requests in each section
    foreach ($availableRequestStates as $type => $v) {
        $statement->bindValue(":type", $type);
        $statement->execute();
        $requests = $statement->fetchAll(PDO::FETCH_CLASS, "Request");
        foreach ($requests as $req) {
            $req->setDatabase($database);
        }
        $totalRequestsStatement->bindValue(":type", $type);
        $totalRequestsStatement->execute();
        $totalRequests = $totalRequestsStatement->fetchColumn();
        $totalRequestsStatement->closeCursor();
        $requestSectionData[$v['header']] = array("requests" => $requests, "total" => $totalRequests, "api" => $v['api']);
    }
    global $smarty;
    $smarty->assign("requestLimitShowOnly", $requestLimitShowOnly);
    $query = <<<SQL
\t\tSELECT request.id, request.name, request.checksum
\t\tFROM request 
\t\tJOIN log ON log.objectid = request.id and log.objecttype = 'Request'
\t\tWHERE log.action LIKE 'Closed%' 
\t\tORDER BY log.timestamp DESC 
\t\tLIMIT 5;
SQL;
    $statement = $database->prepare($query);
    $statement->execute();
    $last5result = $statement->fetchAll(PDO::FETCH_ASSOC);
    $smarty->assign("lastFive", $last5result);
    $smarty->assign("requestSectionData", $requestSectionData);
    $html = $smarty->fetch("mainpage/mainpage.tpl");
    return $html;
}
Esempio n. 22
0
// OAuth callback script
// THIS IS AN ENTRY POINT
chdir("..");
// stop all output until we want it
ob_start();
// load the configuration
require_once 'config.inc.php';
// Initialize the session data.
session_start();
// Get all the classes.
require_once 'functions.php';
require_once 'includes/PdoDatabase.php';
require_once 'includes/SmartyInit.php';
// this needs to be high up, but below config, functions, and database
$user = User::getByRequestToken($_GET['oauth_token'], gGetDb());
if ($user == false) {
    BootstrapSkin::displayInternalHeader();
    BootstrapSkin::displayAlertBox("Could not find request token in local store.", "alert-error", "Error", true, false);
    BootstrapSkin::displayInternalFooter();
    die;
}
global $oauthConsumerToken, $oauthSecretToken, $oauthBaseUrl, $oauthBaseUrlInternal;
$util = new OAuthUtility($oauthConsumerToken, $oauthSecretToken, $oauthBaseUrl, $oauthBaseUrlInternal);
try {
    $result = $util->callbackCompleted($user->getOAuthRequestToken(), $user->getOAuthRequestSecret(), $_GET['oauth_verifier']);
} catch (Exception $exception) {
    BootstrapSkin::displayInternalHeader();
    BootstrapSkin::displayAlertBox("OAuth Error: {$exception->getMessage()}", "alert-error", "OAuth Error", true, false);
    BootstrapSkin::displayInternalFooter();
    die;
Esempio n. 23
0
    /**
     * Check the user's security level on page load, and bounce accordingly
     * 
     * @deprecated
     */
    public function checksecurity()
    {
        global $secure, $smarty;
        // CommunityUser has no database row, and we really don't want CommunityUser to have oauth credentials...
        if (!User::getCurrent()->isCommunityUser()) {
            if (User::getCurrent()->getStoredOnWikiName() == "##OAUTH##" && User::getCurrent()->getOAuthAccessToken() == null) {
                reattachOAuthAccount(User::getCurrent());
            }
            if (User::getCurrent()->isOAuthLinked()) {
                try {
                    // test retrieval of the identity
                    User::getCurrent()->getOAuthIdentity();
                } catch (TransactionException $ex) {
                    User::getCurrent()->setOAuthAccessToken(null);
                    User::getCurrent()->setOAuthAccessSecret(null);
                    User::getCurrent()->save();
                    reattachOAuthAccount(User::getCurrent());
                }
            } else {
                global $enforceOAuth;
                if ($enforceOAuth) {
                    reattachOAuthAccount(User::getCurrent());
                }
            }
        }
        if (User::getCurrent()->isNew()) {
            BootstrapSkin::displayAlertBox("I'm sorry, but, your account has not been approved by a site administrator yet. Please stand by.", "alert-error", "New account", true, false);
            BootstrapSkin::displayInternalFooter();
            die;
        } elseif (User::getCurrent()->isSuspended()) {
            $database = gGetDb();
            $suspendstatement = $database->prepare(<<<SQL
SELECT comment 
FROM log 
WHERE action = 'Suspended' AND objectid = :userid and objecttype = 'User' 
ORDER BY timestamp DESC
LIMIT 1;
SQL
);
            $suspendstatement->bindValue(":userid", User::getCurrent()->getId());
            $suspendstatement->execute();
            $suspendreason = $suspendstatement->fetchColumn();
            $suspendstatement->closeCursor();
            $smarty->assign("suspendreason", $suspendreason);
            $smarty->display("login/suspended.tpl");
            BootstrapSkin::displayInternalFooter();
            die;
        } elseif (User::getCurrent()->isDeclined()) {
            $database = gGetDb();
            $suspendstatement = $database->prepare(<<<SQL
SELECT comment
FROM log
WHERE action = 'Declined' AND objectid = :userid and objecttype = 'User'
ORDER BY timestamp DESC
LIMIT 1;
SQL
);
            $suspendstatement->bindValue(":userid", User::getCurrent()->getId());
            $suspendstatement->execute();
            $suspendreason = $suspendstatement->fetchColumn();
            $suspendstatement->closeCursor();
            $smarty->assign("suspendreason", $suspendreason);
            $smarty->display("login/declined.tpl");
            BootstrapSkin::displayInternalFooter();
            die;
        } elseif (!User::getCurrent()->isCommunityUser() && (User::getCurrent()->isUser() || User::getCurrent()->isAdmin())) {
            $secure = 1;
        } else {
            //die("Not logged in!");
        }
    }
Esempio n. 24
0
 /**
  * Send a notification
  * @param string $message The text to send
  */
 protected static function send($message)
 {
     global $ircBotNotificationType, $whichami, $ircBotNotificationsEnabled;
     if (!$ircBotNotificationsEnabled) {
         return;
     }
     $blacklist = array("DCC", "CCTP", "PRIVMSG");
     $message = str_replace($blacklist, "(IRC Blacklist)", $message);
     //Lets stop DCC etc
     $msg = IrcColourCode::RESET . IrcColourCode::BOLD . "[{$whichami}]" . IrcColourCode::RESET . ": {$message}";
     try {
         $database = gGetDb('notifications');
         $notification = new Notification();
         $notification->setDatabase($database);
         $notification->setType($ircBotNotificationType);
         $notification->setText($msg);
         $notification->save();
     } catch (Exception $ex) {
         // OK, so we failed to send the notification - that db might be down?
         // This is non-critical, so silently fail.
         // Disable notifications for remainder of request.
         $ircBotNotificationsEnabled = false;
     }
 }
Esempio n. 25
0
 /**
  * Get a message.
  *
  * This is going to be used as a new way of dealing with saved messages for #28
  *
  * The basic idea is there's a key stored in a new column, and we do lookups on that
  * instead of a possibly variable auto-incrementing ID.
  *
  * We can use class constants so the keys are defined in one place only for now, and for
  * now we are using the auto-incrementing ID as the value of the key, so this function
  * just uses getById() at the moment.
  *
  * @param mixed $key
  * @return mixed
  */
 public static function get($key)
 {
     /** @var InterfaceMessage $message */
     $message = self::getById($key, gGetDb());
     return $message->getContentForDisplay();
 }
Esempio n. 26
0
 /**
  * Summary of getLogActions
  */
 public static function getLogActions()
 {
     $database = gGetDb();
     $lookup = array('Reserved' => 'reserved', 'Email Confirmed' => 'email-confirmed', 'Unreserved' => 'unreserved', 'Approved' => 'approved', 'Suspended' => 'suspended', 'Banned' => 'banned', 'Edited' => 'edited interface message', 'Declined' => 'declined', 'EditComment-c' => 'edited a comment', 'EditComment-r' => 'edited a comment', 'Unbanned' => 'unbanned', 'Promoted' => 'promoted to tool admin', 'BreakReserve' => 'forcibly broke the reservation', 'Prefchange' => 'changed user preferences', 'Renamed' => 'renamed', 'Demoted' => 'demoted from tool admin', 'ReceiveReserved' => 'received the reservation', 'SendReserved' => 'sent the reservation', 'EditedEmail' => 'edited email', 'DeletedTemplate' => 'deleted template', 'EditedTemplate' => 'edited template', 'CreatedEmail' => 'created email', 'CreatedTemplate' => 'created template', 'SentMail' => 'sent an email to the requestor');
     $statement = $database->query("SELECT CONCAT('Closed ', id) as k, CONCAT('closed (',name,')') as v FROM emailtemplate;");
     foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
         $lookup[$row['k']] = $row['v'];
     }
     return $lookup;
 }
Esempio n. 27
0
 public function setUser($user)
 {
     if (User::getById($user, gGetDb()) == false) {
         $u = User::getByUsername($user, gGetDb());
         if ($u == false) {
             throw new Exception("Unknown user trying to create ban!");
         }
         $this->user = $u->getId();
     } else {
         $this->user = $user;
     }
 }
Esempio n. 28
0
    private function getUserDetail($userId)
    {
        $database = gGetDb();
        $user = User::getById($userId, $database);
        if ($user == false) {
            return BootstrapSkin::displayAlertBox("User not found", "alert-error", "Error", true, false, true);
        }
        global $smarty;
        $activitySummary = $database->prepare(<<<SQL
SELECT COALESCE(closes.mail_desc, log.action) AS action, COUNT(*) AS count
FROM log
INNER JOIN user ON log.user = user.id
LEFT JOIN closes ON log.action = closes.closes
WHERE user.username = :username
GROUP BY action;
SQL
);
        $activitySummary->execute(array(":username" => $user->getUsername()));
        $activitySummaryData = $activitySummary->fetchAll(PDO::FETCH_ASSOC);
        $smarty->assign("user", $user);
        $smarty->assign("activity", $activitySummaryData);
        $usersCreatedQuery = $database->prepare(<<<SQL
SELECT log.timestamp time, request.name name, request.id id
FROM log
INNER JOIN request ON (request.id = log.objectid and log.objecttype = 'Request')
INNER JOIN user ON log.user = user.id
LEFT JOIN emailtemplate ON concat('Closed ', emailtemplate.id) = log.action
WHERE user.username = :username
    AND log.action LIKE 'Closed %'
    AND (emailtemplate.oncreated = '1' OR log.action = 'Closed custom-y')
ORDER BY log.timestamp;
SQL
);
        $usersCreatedQuery->execute(array(":username" => $user->getUsername()));
        $usersCreated = $usersCreatedQuery->fetchAll(PDO::FETCH_ASSOC);
        $smarty->assign("created", $usersCreated);
        $usersNotCreatedQuery = $database->prepare(<<<SQL
SELECT log.timestamp time, request.name name, request.id id
FROM log
JOIN request ON request.id = log.objectid and log.objecttype = 'Request'
JOIN user ON log.user = user.id
LEFT JOIN emailtemplate ON concat('Closed ', emailtemplate.id) = log.action
WHERE user.username = :username
    AND log.action LIKE 'Closed %'
    AND (emailtemplate.oncreated = '0' OR log.action = 'Closed custom-n' OR log.action = 'Closed 0')
ORDER BY log.timestamp;
SQL
);
        $usersNotCreatedQuery->execute(array(":username" => $user->getUsername()));
        $usersNotCreated = $usersNotCreatedQuery->fetchAll(PDO::FETCH_ASSOC);
        $smarty->assign("notcreated", $usersNotCreated);
        $accountLogQuery = $database->prepare(<<<SQL
SELECT
\tuser.username as log_user,
    log.action as log_action,
    log.timestamp as log_time,
    log.comment as log_cmt
FROM log
INNER JOIN user ON user.id = log.user
WHERE log.objectid = :userid
AND log.objecttype = 'User'
AND log.action IN ('Approved','Suspended','Declined','Promoted','Demoted','Renamed','Prefchange');
SQL
);
        $accountLogQuery->execute(array(":userid" => $user->getId()));
        $accountLog = $accountLogQuery->fetchAll(PDO::FETCH_ASSOC);
        $smarty->assign("accountlog", $accountLog);
        return $smarty->fetch("statistics/userdetail.tpl");
    }
Esempio n. 29
0
        foreach ($requests as $r) {
            $r->setDatabase(gGetDb());
        }
        $smarty->assign("term", $term);
        $smarty->assign("requests", $requests);
        $target = "IP address";
        $smarty->assign("target", $target);
        $smarty->display("search/searchresult.tpl");
    } elseif ($_GET['type'] == 'Request') {
        $qterm = '%' . $term . '%';
        $statement = gGetDb()->prepare("SELECT * FROM request WHERE name LIKE :term;");
        $statement->bindValue(":term", $qterm);
        $statement->execute();
        $requests = $statement->fetchAll(PDO::FETCH_CLASS, "Request");
        foreach ($requests as $r) {
            $r->setDatabase(gGetDb());
        }
        $smarty->assign("term", $term);
        $smarty->assign("requests", $requests);
        $target = "requested name";
        $smarty->assign("target", $target);
        $smarty->display("search/searchresult.tpl");
    } else {
        BootstrapSkin::displayAlertBox("Unknown search type", "alert-error", "Error");
        $smarty->display("search/searchform.tpl");
        BootstrapSkin::displayInternalFooter();
        die;
    }
} else {
    $smarty->display("search/searchform.tpl");
}
Esempio n. 30
0
<?php

if (isset($_SERVER['REQUEST_METHOD'])) {
    die;
}
// Web clients die.
ini_set('display_errors', 1);
require_once 'config.inc.php';
require_once 'includes/PdoDatabase.php';
$db = gGetDb();
$db->transactionally(function () use($db) {
    global $cDataClearIp, $cDataClearEmail, $dataclear_interval;
    $query = $db->prepare("UPDATE request SET ip = :ip, forwardedip = null, email = :mail, useragent = '' WHERE date < DATE_SUB(curdate(), INTERVAL {$dataclear_interval});");
    $success = $query->execute(array(":ip" => $cDataClearIp, ":mail" => $cDataClearEmail));
    if (!$success) {
        throw new TransactionException("Error in transaction: Could not clear data.");
    }
});
echo "Deletion complete.";