/**
 * Função que valida um usuário e senha
 *
 * @param string $usuario - O usuário a ser validado
 * @param string $senha - A senha a ser validada
 *
 * @return bool - Se o usuário foi validado ou não (true/false)
 */
function validaUsuario($user, $password)
{
    //Instância do banco de dados.
    $database = new Config();
    $db = $database->getConnection();
    global $_SG;
    //$cS = ($_SG['caseSensitive']) ? 'BINARY' : '';
    // Usa a função addslashes para escapar as aspas
    //    $nusuario = addslashes($user);
    //    $nsenha = addslashes($password);
    $usuario = new Usuario($db);
    $usuario->readName($user);
    if (empty($usuario->cd_usuario)) {
        // Nenhum registro foi encontrado => o usuário é inválido
        return false;
    } else {
        if (password_verify($password, $usuario->nm_senha_usuario)) {
            $_SESSION['usuarioID'] = $usuario->cd_usuario;
            // Pega o valor da coluna 'id do registro encontrado no MySQL
            $_SESSION['usuarioNome'] = $usuario->nm_usuario;
            // Pega o valor da coluna 'nome' do registro encontrado no MySQL
            // Verifica a opção se sempre validar o login
            if ($_SG['validaSempre'] == true) {
                // Definimos dois valores na sessão com os dados do login
                $_SESSION['usuarioLogin'] = $user;
                $_SESSION['usuarioSenha'] = $password;
            }
            return true;
        } else {
            return false;
        }
    }
}
Example #2
0
 public function save()
 {
     $config = new Config();
     $conn = $config->getConnection();
     $query = "INSERT INTO admin (username,password,pathname)\n\t\t\t\tVALUES ('{$this->username}','{$this->password}', '{$this->pathname}')";
     if ($conn->query($query) !== TRUE) {
         echo 'user cannot add to databse';
     }
 }
Example #3
0
 /**
  * @param Spider\Component\Config
  */
 public function __construct(Config $Config)
 {
     $Storage = $Config->getStorage();
     $Connection = $Config->getConnection();
     $this->script = escapeshellarg(__DIR__ . "/../bin/weeve.php");
     $this->conn = base64_encode($Connection->sleep());
     $this->storage = base64_encode($Storage->sleep());
     $this->memory = $Config->getMemory();
     $this->table = $Config->getTable();
     $this->trace = $Config->getTrace();
 }
Example #4
0
function get_pathname()
{
    $config = new Config();
    $conn = $config->getConnection();
    $query = "SELECT pathname from admin";
    $result = $conn->query($query);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            return $row["pathname"];
        }
    }
}
Example #5
0
 public function save()
 {
     $config = new Config();
     $conn = $config->getConnection();
     $exist_q = "SELECT docname FROM books WHERE docname = '{$this->docName}'";
     if (mysqli_num_rows($conn->query($exist_q)) != 0) {
         return;
     }
     $query = "INSERT INTO books (docname, title, pagenum)\n\t\t\t\tVALUES ('{$this->docName}', '{$this->title}', '{$this->pageNum}')";
     if ($conn->query($query) !== TRUE) {
         echo 'something bad happened while saving';
     }
 }
Example #6
0
 public static function titleToDocName($title)
 {
     $query = "SELECT docname,title from books";
     $conn = new Config();
     $result = $conn->getConnection()->query($query);
     if ($result->num_rows > 0) {
         while ($row = $result->fetch_assoc()) {
             if ($row["title"] == $title) {
                 return $row["docname"];
             }
         }
     }
 }
Example #7
0
 public static function searchUser($passwd)
 {
     $config = new Config();
     $conn = $config->getConnection();
     $sql = "SELECT id, password FROM users";
     $result = $conn->query($sql);
     if ($result->num_rows > 0) {
         // output data of each row
         while ($row = $result->fetch_assoc()) {
             // echo "id: " . $row["id"]. " - Name: " . $row["password"]. "<br>";
             if ($passwd == $row["password"]) {
                 return true;
             }
         }
     }
     return false;
 }
Example #8
0
function verify_admin()
{
    $config = new Config();
    $conn = $config->getConnection();
    $query = "SELECT username,password from admin";
    $result = $conn->query($query);
    if ($result->num_rows > 0) {
        while ($row = $result->fetch_assoc()) {
            if ($_POST['username'] == $row['username'] && $_POST['password'] == $row['password']) {
                session_start();
                $_SESSION['username'] = $_POST['username'];
                $_SESSION['password'] = $_POST['password'];
                return TRUE;
            }
        }
    }
    return FALSE;
}
Example #9
0
 private function removeOlds()
 {
     $conf = new Config();
     $conn = $conf->getConnection();
     $sql = "SELECT docname from books";
     $result = $conn->query($sql);
     if ($result->num_rows > 0) {
         # code...
         while ($row = $result->fetch_assoc()) {
             if (!in_array($row["docname"], $this->fileArray)) {
                 $delSql = "DELETE FROM books WHERE docname='" . $row['docname'] . "'";
                 if ($conn->query($delSql) === TRUE) {
                     echo "Deleted : " . $row["docname"] . "<br>";
                 } else {
                     echo "Error : " . $row["docname"] . "<br>";
                 }
             }
         }
     }
 }
Example #10
0
/**
  Returns the UserId for the current session or dies.
  It is strongly advised to check if the session is valid first.
*/
function session_getUid()
{
    if (!isset($_SESSION['UserId'])) {
        Config::error('UserId is not set in validate.php:session_getUid()');
    }
    return Config::getConnection()->escape_string($_SESSION['UserId']);
}
 /**
   @param $studyId String CONCAT(StudyIx, FamilyIx)
   @return $defaults [ language => LanguageIx
                     , word => CONCAT(IxElicitation,IxMorpholigcalInstance)
                     , languages => [LanguageIx]
                     , words => [CONCAT(IxElicitation,IxMorpholigcalInstance)]
                     , excludeMap => [LanguageIx]]
   Given a studyId, this method fetches the default words and languages.
 */
 public static function getDefaults($studyId)
 {
     $db = Config::getConnection();
     $sId = $db->escape_string($studyId);
     $ret = array();
     //Single queries:
     foreach (array('language' => "SELECT LanguageIx FROM Default_Languages " . "WHERE CONCAT(StudyIx, FamilyIx) = {$sId} LIMIT 1", 'word' => "SELECT IxElicitation, IxMorphologicalInstance FROM Default_Words " . "WHERE CONCAT(StudyIx, FamilyIx) = {$sId} LIMIT 1") as $k => $q) {
         $ret[$k] = $db->query($q)->fetch_assoc();
     }
     //Multiple queries:
     foreach (array('languages' => "SELECT LanguageIx FROM Default_Multiple_Languages " . "WHERE CONCAT(StudyIx, FamilyIx) = {$sId}", 'words' => "SELECT IxElicitation, IxMorphologicalInstance FROM Default_Multiple_Words " . "WHERE CONCAT(StudyIx, FamilyIx) = {$sId}", 'excludeMap' => "SELECT LanguageIx FROM Default_Languages_Exclude_Map " . "WHERE CONCAT(StudyIx, FamilyIx) = {$sId}") as $k => $q) {
         $ret[$k] = static::fetchAll($q);
     }
     return $ret;
 }
<?php

/*
  This script harvests wikipediaLinks and stores them in the database.
  Links are searched for every ISO code and every Translation in the db.
*/
require_once '../config.php';
$dbConnection = Config::getConnection();
/*
  We need the ISOCodes from all studies,
  so we first need all studies:
*/
$studies = array();
$set = $dbConnection->query('SELECT Name FROM Studies');
while ($r = $set->fetch_row()) {
    array_push($studies, $r[0]);
}
//Looking for ISOCodes and LinkParts:
$targets = array();
foreach ($studies as $study) {
    $q = "SELECT ISOCode, WikipediaLinkPart FROM Languages_{$study} WHERE ISOCODE != ''";
    $set = $dbConnection->query($q);
    while ($r = $set->fetch_row()) {
        $targets[implode(',', $r)] = $r;
    }
}
echo "Targets loaded:\t" . count($targets) . "\n";
/*
  They are originally used to determine the browser language,
  but for now I'll use them also to figure out the wikipedia language
  necessary for that translation.
Example #13
0
 /**
  * Generate a prepare statement
  *
  * @param $sql
  *
  * @return \PDOStatement
  */
 protected static function getStatement($sql)
 {
     return Config::getConnection()->prepare($sql);
 }
 /**
   @param $tId TranslationId the Translation to search
   @param $searchText String the Text to search
   @param $searchStrategy {'both','translation','original'}
   @return $ret [obj] || Exception
   obj will be arrays resembling JSON objects following this syntax:
   {
     Description: {Req: '', Description: ''}
   , Original: ''
   , Translation: {TranslationId: 5, Translation: '', Payload: '', TranslationProvider: ''}
   }
   Searches for the given $searchText and returns array to allow translation for found entries.
   $searchStrategy specifies if the originals, the translations or both should be searched.
 */
 public function search($tId, $searchText, $searchStrategy = 'both')
 {
     //Sanitizing $tId:
     $tId = is_numeric($tId) ? $tId : 1;
     //Sanitizing $searchText:
     $searchText = Config::getConnection()->escape_string($searchText);
     //Sanitizing $searchStrategy:
     if (preg_match('/^(both|translation|original)$/', $searchStrategy) === 0) {
         return new Exception("Invalid \$searchStrategy: '{$searchStrategy}'");
     }
     //Table to use:
     $tableName = $this->getTable();
     //Study to use:
     $study = $this->getStudy();
     // String || null
     //Column specific code:
     return $this->withColumn(function ($column) use($tId, $searchText, $searchStrategy, $tableName, $study) {
         $category = $column['category'];
         //Description to use for entries:
         $description = TranslationTableProjection::fetchDescription($column);
         //Payload -> $entry to prevent duplicates
         $payloadMap = array();
         //Searching in originals:
         if ($searchStrategy === 'both' || $searchStrategy === 'original') {
             $columnName = $column['columnName'];
             $fieldSelect = $column['fieldSelect'];
             $q = "SELECT {$columnName} AS columnName, {$fieldSelect} AS fieldSelect " . "FROM {$tableName} " . "WHERE {$columnName} LIKE '%{$searchText}%'";
             $originals = DataProvider::fetchAll($q);
             foreach ($originals as $original) {
                 $fieldSelect = $original['fieldSelect'];
                 if ($study !== null) {
                     $fieldSelect = "{$study}-{$fieldSelect}";
                 }
                 //Stub for $entry:
                 $entry = array('Description' => $description, 'Original' => $original['columnName'], 'Translation' => array('TranslationId' => $tId, 'Translation' => '', 'Payload' => $fieldSelect, 'TranslationProvider' => $category));
                 if ($study !== null) {
                     $entry['Study'] = $study;
                 }
                 //Trying to add existing translation:
                 $entry = $this->addTranslation($entry);
                 //Putting $entry into map:
                 $payloadMap[$fieldSelect] = $entry;
             }
         }
         //Searching in translations:
         if ($searchStrategy === 'both' || $searchStrategy === 'translation') {
             //Setting $columnName and $fieldSelect:
             $columnName = $column['columnName'];
             $fieldSelect = $column['fieldSelect'];
             //Need to fetch all originals to find matching translations:
             $q = "SELECT {$columnName} AS columnName, {$fieldSelect} AS fieldSelect " . "FROM {$tableName} ";
             $originals = DataProvider::fetchAll($q);
             foreach ($originals as $original) {
                 $fieldSelect = $original['fieldSelect'];
                 if ($study !== null) {
                     $fieldSelect = "{$study}-{$fieldSelect}";
                 }
                 //Preventing possible duplicates:
                 if (array_key_exists($fieldSelect, $payloadMap)) {
                     continue;
                 }
                 //Checking for translation:
                 $q = "SELECT Trans FROM Page_DynamicTranslation " . "WHERE TranslationId = {$tId} " . "AND Category = '{$category}' " . "AND Field = '{$fieldSelect}' " . "AND Trans LIKE '%{$searchText}%' " . "LIMIT 1";
                 foreach (DataProvider::fetchAll($q) as $r) {
                     //foreach works as if
                     $entry = array('Description' => $description, 'Original' => $original['columnName'], 'Translation' => array('TranslationId' => $tId, 'Translation' => $r['Trans'], 'Payload' => $fieldSelect, 'TranslationProvider' => $category));
                     if ($study !== null) {
                         $entry['Study'] = $study;
                     }
                     $payloadMap[$fieldSelect] = $entry;
                 }
             }
         }
         //Done:
         return array_values($payloadMap);
     });
 }
 /**
   Since we don't have a RfcLanguages nor a Languages view anymore,
   this is going to be a little more complicated:
   We need to iterate all Languages_<study> tables,
   and select all RfcLanguages from them.
   @return array LanguageIx => ShortName
 */
 public static function getRfcLanguages()
 {
     $dbConnection = Config::getConnection();
     $set = $dbConnection->query('SELECT Name FROM Studies');
     $studies = array();
     while ($r = $set->fetch_row()) {
         array_push($studies, $r[0]);
     }
     $ret = array();
     foreach ($studies as $study) {
         $q = "SELECT ShortName, LanguageIx FROM Languages_{$study} " . "WHERE LanguageIx = ANY (" . "SELECT DISTINCT RfcLanguage FROM Languages_{$study} " . "WHERE RfcLanguage IS NOT NULL)";
         $set = $dbConnection->query($q);
         if ($set === false) {
             //May fail if a studies entry exists but no Lanugage_$study table…
             Config::error("Problem with query: {$q}", false, false);
         } else {
             while ($r = $set->fetch_row()) {
                 $ret[$r[1]] = $r[0];
             }
         }
     }
     return $ret;
 }
 /**
   @param lng String as BrowserMatch from v4.Page_Translations table.
   @return $i18n :: [[Req => Trans],[Category.Field => Trans]]
 */
 public static function getI18n($lng)
 {
     $db = Config::getConnection();
     $q = 'SELECT TranslationId FROM Page_Translations WHERE BrowserMatch = ?';
     $stmt = $db->prepare($q);
     $stmt->bind_param('s', $lng);
     $stmt->execute();
     $stmt->bind_result($tId);
     if (!$stmt->fetch()) {
         //BrowserMatch not found -> empty array
         error_log('TranslationProvider::getI18n(' . $lng . ') returns empty.');
         return array();
     }
     $stmt->close();
     $i18n = self::getStatic($tId);
     foreach (self::getDynamic($tId) as $dynamic) {
         $i18n[$dynamic['Category'] . $dynamic['Field']] = $dynamic['Trans'];
     }
     return $i18n;
 }
Example #17
0
<?php

require_once '../config.php';
/**
  Under http://<domain>/projects/<familyname>
  we want to serve an iframe page that seamlessly integrates
  the project URL for the given family, if possible.
  This script expects a $_GET['name'] parameter,
  and will catch the correct routes due to .htaccess magic.
*/
$family = $_GET['name'];
if ($family) {
    $stmt = Config::getConnection()->prepare('SELECT ProjectAboutUrl FROM Families WHERE FamilyNm = ?');
    $stmt->bind_param('s', $family);
    $stmt->execute();
    $stmt->bind_result($url);
    if ($stmt->fetch()) {
        echo Config::getMustache()->render('Projects', array('title' => "Project page for {$family}", 'backlink' => 'soundcomparisons.com', 'url' => $url));
    } else {
        die("Sorry, we cannot find a family named '{$family}' in our database.");
    }
} else {
    die('Sorry, we cannot find that project in our database.');
}
Example #18
0
        $action = $argv[1];
        switch ($action) {
            case 'import':
                if (count($argv) <= 2) {
                    die('Usage: php -f ' . $argv[0] . " import <file>\n");
                }
                $file = file_get_contents($argv[2]);
                break;
        }
    }
} else {
    $allowed = session_validate() && session_mayEdit();
    if (!$allowed) {
        //Special case for action=export:
        if (array_key_exists('ch1', $_GET) && array_key_exists('ch2', $_GET)) {
            $db = Config::getConnection();
            $login = $dbConnection->escape_string($_GET['ch1']);
            $hash = $dbConnection->escape_string($_GET['ch2']);
            $q = "SELECT AccessEdit FROM Edit_Users" . " WHERE Login = '******' AND Hash = '{$hash}'";
            if ($r = $db->query($q)->fetch_row()) {
                $allowed = $r[0] == 1;
            }
            unset($db, $login, $hash, $q, $r);
        }
        if (!$allowed) {
            Config::error('403 Forbidden');
            die('403 Forbidden');
        }
    }
    if (array_key_exists('action', $_GET)) {
        $action = $_GET['action'];
 /**
   Translation field come with descriptions to aid work in the translation interface.
   This method fetches such descriptions.
 */
 public static function getDescription($req)
 {
     $q = "SELECT Description " . "FROM Page_StaticDescription " . "WHERE Req = '{$req}'";
     $rst = Config::getConnection()->query($q);
     if ($r = $rst->fetch_row()) {
         return array('Req' => $req, 'Description' => $r[0]);
     }
     return array('Req' => $req, 'Description' => 'Description not found in database.');
 }
Example #20
0
 /**
   @param $table String
   @return $tDesc [Field String => IsString Bool]
   Generates a simple description of a table mapping Fields to Bools.
 */
 public static function descTable($table)
 {
     $tDesc = array();
     $set = Config::getConnection()->query("DESCRIBE {$table}");
     while ($r = $set->fetch_assoc()) {
         $type = $r['Type'];
         $isString = $type === 'text' || strpos($type, 'varchar') !== false;
         $tDesc[$r['Field']] = $isString;
     }
     if (count($tDesc) === 0) {
         array_push(self::$log, "Importer::descTable could not find description for table {$table}.");
     }
     return $tDesc;
 }
<?php

include "security.php";
// Inclui o arquivo com o sistema de segurança
protegePagina();
// Chama a função que protege a página
//Indica a página ativa para ativar o marcador do menu lateral
$pg_ativa = 'eventos';
//Inclui o arquivo de configuração do banco.
include_once 'include/config.php';
//Instância do banco de dados.
$database = new Config();
$db = $database->getConnection();
//Inclui as classes com as principais funções dos módulos.
include_once 'include/ambiente.php';
include_once 'include/evento.php';
include_once 'include/categoria.php';
//Instância dos módulos.
$ambiente = new Ambiente($db);
$categoria = new TipoCategoria($db, 'evento');
$evento = new Evento($db);
//Define valores para o objeto instanciado para utilizar uma função.
$evento->cd_evento = $_GET['id'];
$evento->readOne();
//Variável que recebe o resultado da consulta de outra instância.
$stmt = $categoria->readAllSmall();
$stmt_ambiente = $ambiente->readAllSmall();
//Variável com o endereço raíz do módulo.
$url = 'eventos.php?ordem=1';
?>
<!DOCTYPE html>
 /**
   @param $hash String
   @return $arr [url => String, hex => String, str => String] || Exception
   Fetches an entry from the database by it's hash.
 */
 public static function getByHash($hash)
 {
     if (!is_string($hash)) {
         return new Exception('Given $hash is not a string!');
     }
     //Fallback in case fetching fails:
     $arr = new Exception('Could not fetch data.');
     //Fetching data:
     $q = 'SELECT Hash, Name, Target FROM Page_ShortLinks WHERE Hash = ?';
     $stmt = Config::getConnection()->prepare($q);
     $stmt->bind_param('s', $hash);
     $stmt->execute();
     $stmt->bind_result($hash, $name, $target);
     if ($stmt->fetch()) {
         $arr = array('url' => $target, 'hex' => $hash, 'str' => $name);
     }
     $stmt->close();
     return $arr;
 }
Example #23
0
<?php

include_once '../../include/config.php';
$config = new Config();
$db = $config->getConnection();
include_once '../../include/login.php';
if ($_POST) {
    $login = new Login($db);
    $login->userid = $_POST['username'];
    $login->passid = md5($_POST['password']);
    if ($login->login()) {
        echo "<script>location.href='../'</script>";
    } else {
        echo "<script>alert('Maaf kombinasi Username dan Password yang anda masukkan salah, silahkan coba lagi!')</script>";
    }
}
?>

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">
    <title>Calm breeze login screen</title>
    
    
    
    
        <link rel="stylesheet" href="css/style.css">

  </head>
  <body>
Example #24
0
    die('');
    //die to make sure no content after redirect.
}
?>
<!DOCTYPE HTML>
<html>
  <?php 
$title = "Edit and review the meanings list.";
require_once 'head.php';
?>
  <body>
    <?php 
require_once 'topmenu.php';
if (array_key_exists('IxElicitation', $_GET)) {
    $q = 'SELECT IxElicitation, name, description, example, justification FROM Meanings WHERE IxElicitation = ?';
    $stmt = Config::getConnection()->prepare($q);
    $stmt->bind_param('i', $_GET['IxElicitation']);
    $stmt->execute();
    $stmt->bind_result($IxElicitation, $name, $description, $example, $justification);
    if ($stmt->fetch()) {
        ?>
          <form action="index.php?action=meanings" method="post">
            <fieldset>
              <legend>Editing Meaning</legend>
              <input name="IxElicitation" value="<?php 
        echo $IxElicitation;
        ?>
" type="hidden">
              <label>Name:</label>
              <input name="name" value="<?php 
        echo $name;