/**
  * Executes $query against database and returns the result set as an array of POG objects
  *
  * @param string $query. SQL query to execute against database
  * @param string $objectClass. POG Object type to return
  * @param bool $lazy. If true, will also load all children/sibling
  */
 function FetchObjects($query, $objectClass, $lazy = true)
 {
     $databaseConnection = Database::Connect();
     $result = Database::Query($query, $databaseConnection);
     $objectList = $this->CreateObjects($result, $objectClass, $lazy);
     return $objectList;
 }
 /**
  * Physically saves the mapping to the database
  * @return 
  */
 function Save()
 {
     $connection = Database::Connect();
     $this->pog_query = "select `objectid` from `objectsiblingmap` where `objectid`='" . $this->objectId . "' AND `siblingid`='" . $this->siblingId . "' LIMIT 1";
     $rows = Database::Query($this->pog_query, $connection);
     if ($rows == 0) {
         $this->pog_query = "insert into `objectsiblingmap` (`objectid`, `siblingid`) values ('" . $this->objectId . "', '" . $this->siblingId . "')";
     }
     return Database::InsertOrUpdate($this->pog_query, $connection);
 }
 function __construct()
 {
     if (isset($_SESSION)) {
         $this->_uniqueID = !isset($_SESSION[parent::_SITENAME]) ? time() . "_" . uniqid('', true) : $_SESSION[parent::_SITENAME];
         $_SESSION[parent::_SITENAME] = !isset($_SESSION[parent::_SITENAME]) ? $this->_uniqueID : $_SESSION[parent::_SITENAME];
         if (parent::_ENABLE_IP_ROTATION) {
             Database::Connect(parent::_SERVER, parent::_DB_USER, parent::_DB_PASSWORD, parent::_DATABASE);
         }
     } else {
         die('Error!: Session must be started in the calling file to use this class.');
     }
 }
 function Execute()
 {
     $objectName = get_class($this->sourceObject);
     $fcv_array = $this->argv[0];
     $sql = 'select count(*) as mycount from `' . strtolower($objectName) . '`';
     if (sizeof($fcv_array) > 0) {
         $sql .= " where ";
         for ($i = 0, $c = sizeof($fcv_array); $i < $c; $i++) {
             if (sizeof($fcv_array[$i]) == 1) {
                 $sql .= " " . $fcv_array[$i][0] . " ";
                 continue;
             } else {
                 if ($i > 0 && sizeof($fcv_array[$i - 1]) != 1) {
                     $sql .= " AND ";
                 }
                 $fieldAttributes = $this->sourceObject->GetFieldAttribute($fcv_array[$i][0], 'db_attributes');
                 if ($fieldAttributes != null && $fieldAttributes[0] != 'NUMERIC' && $fieldAttributes[0] != 'SET') {
                     if ($GLOBALS['configuration']['db_encoding'] == 1) {
                         $value = POG_Base::IsColumn($fcv_array[$i][2]) ? "BASE64_DECODE(" . $fcv_array[$i][2] . ")" : "'" . $fcv_array[$i][2] . "'";
                         $sql .= "BASE64_DECODE(`" . $fcv_array[$i][0] . "`) " . $fcv_array[$i][1] . " " . $value;
                     } else {
                         $value = POG_Base::IsColumn($fcv_array[$i][2]) ? $fcv_array[$i][2] : "'" . $this->Escape($fcv_array[$i][2]) . "'";
                         $sql .= "`" . $fcv_array[$i][0] . "` " . $fcv_array[$i][1] . " " . $value;
                     }
                 } else {
                     $value = POG_Base::IsColumn($fcv_array[$i][2]) ? $fcv_array[$i][2] : "'" . $fcv_array[$i][2] . "'";
                     $sql .= "`" . $fcv_array[$i][0] . "` " . $fcv_array[$i][1] . " " . $value;
                 }
             }
         }
     }
     $connection = Database::Connect();
     $cursor = Database::Reader($sql, $connection);
     while ($row = Database::Read($cursor)) {
         $count = $row['mycount'];
     }
     return $count;
 }
Example #5
0
         * Returns the current database connection ($GLOBALS['DATABASE'])
         */
        public static function GetLink()
        {
            return $GLOBALS['DATABASE'];
        }
        /**
         * Tries to connect to the database
         */
        public static function Connect()
        {
            $GLOBALS['DATABASE'] = new PDO(DBVENDOR . ':host=' . DBSERVER . ';dbname=' . DBDATABASE . ';charset=' . DBENCODING, DBUSERNAME, DBPASSWORD);
            Database::Check();
        }
        /**
         * Checks if a connection to the database has been established
         */
        public static function Check()
        {
            // TODO: Find out how to check the connection with PDO
        }
        /**
         * Disconnects from the database
         */
        public static function Disconnect()
        {
            $GLOBALS['DATABASE'] = null;
        }
    }
    Database::Connect();
}
 /**
  * Returns a sorted array of objects that match given conditions
  * @param multidimensional array {("field", "comparator", "value"), ("field", "comparator", "value"), ..} 
  * @param string $sortBy 
  * @param boolean $ascending 
  * @param int limit 
  * @return array $siblingList
  */
 function GetObjectList($fcv_array = array(), $sortBy = '', $ascending = true, $limit = '')
 {
     $sqlLimit = $limit != '' ? "LIMIT {$limit}" : '';
     $connection = Database::Connect();
     $object = new object();
     $objectList = array();
     $this->pog_query = "select distinct * from `object` a INNER JOIN `objectsiblingmap` m ON m.objectid = a.objectid where m.siblingid = '{$this->siblingId}' ";
     if (sizeof($fcv_array) > 0) {
         $this->pog_query = $this->pog_query . " AND ";
         for ($i = 0, $c = sizeof($fcv_array); $i < $c; $i++) {
             if (sizeof($fcv_array[$i]) == 1) {
                 $this->pog_query = $this->pog_query . " " . $fcv_array[$i][0] . " ";
                 continue;
             } else {
                 if ($i > 0 && sizeof($fcv_array[$i - 1]) != 1) {
                     $this->pog_query = $this->pog_query . " AND ";
                 }
                 if (isset($object->pog_attribute_type[$fcv_array[$i][0]]['db_attributes']) && $object->pog_attribute_type[$fcv_array[$i][0]]['db_attributes'][0] != 'NUMERIC' && $object->pog_attribute_type[$fcv_array[$i][0]]['db_attributes'][0] != 'SET') {
                     if ($GLOBALS['configuration']['db_encoding'] == 1) {
                         $value = POG_Base::IsColumn($fcv_array[$i][2]) ? "BASE64_DECODE(" . $fcv_array[$i][2] . ")" : "'" . $fcv_array[$i][2] . "'";
                         $this->pog_query = $this->pog_query . "BASE64_DECODE(`" . $fcv_array[$i][0] . "`) " . $fcv_array[$i][1] . " " . $value;
                     } else {
                         $value = POG_Base::IsColumn($fcv_array[$i][2]) ? $fcv_array[$i][2] : "'" . $this->Escape($fcv_array[$i][2]) . "'";
                         $this->pog_query = $this->pog_query . "a.`" . $fcv_array[$i][0] . "` " . $fcv_array[$i][1] . " " . $value;
                     }
                 } else {
                     $value = POG_Base::IsColumn($fcv_array[$i][2]) ? $fcv_array[$i][2] : "'" . $fcv_array[$i][2] . "'";
                     $this->pog_query = $this->pog_query . "a.`" . $fcv_array[$i][0] . "` " . $fcv_array[$i][1] . " " . $value;
                 }
             }
         }
     }
     if ($sortBy != '') {
         if (isset($object->pog_attribute_type[$sortBy]['db_attributes']) && $object->pog_attribute_type[$sortBy]['db_attributes'][0] != 'NUMERIC' && $object->pog_attribute_type[$sortBy]['db_attributes'][0] != 'SET') {
             if ($GLOBALS['configuration']['db_encoding'] == 1) {
                 $sortBy = "BASE64_DECODE(a.{$sortBy}) ";
             } else {
                 $sortBy = "a.{$sortBy} ";
             }
         } else {
             $sortBy = "a.{$sortBy} ";
         }
     } else {
         $sortBy = "a.objectid";
     }
     $this->pog_query = $this->pog_query . " order by " . $sortBy . " " . ($ascending ? "asc" : "desc") . " {$sqlLimit}";
     $cursor = Database::Reader($this->pog_query, $connection);
     while ($row = Database::Read($cursor)) {
         $object = new object();
         foreach ($object->pog_attribute_type as $attribute_name => $attrubute_type) {
             if ($attrubute_type['db_attributes'][1] != "HASMANY" && $attrubute_type['db_attributes'][1] != "JOIN") {
                 if ($attrubute_type['db_attributes'][1] == "BELONGSTO") {
                     $object->{strtolower($attribute_name) . 'Id'} = $row[strtolower($attribute_name) . 'id'];
                     continue;
                 }
                 $object->{$attribute_name} = $this->Unescape($row[strtolower($attribute_name)]);
             }
         }
         $objectList[] = $object;
     }
     return $objectList;
 }
Example #7
0
    header('Content-Disposition: attachment; filename="config.ini"');
    die($_SESSION['config']);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $form_values = $_POST;
    // Validation
    $required = array('mysql_host', 'mysql_database', 'mysql_user', 'mysql_password', 'config_username', 'config_password');
    foreach ($required as $field) {
        if (empty($_POST[$field])) {
            $form_errors[$field] = 'Field is required.';
        }
    }
    // Installation
    try {
        if (0 == count($form_errors)) {
            $res = Database::Connect($_POST['mysql_host'], $_POST['mysql_database'], $_POST['mysql_user'], $_POST['mysql_password']);
            if (true !== $res) {
                $form_errors['mysql_host'] = 'Please check this field.';
                $form_errors['mysql_database'] = 'Please check this field.';
                $form_errors['mysql_user'] = '******';
                $form_errors['mysql_password'] = '******';
                throw new Exception($res);
            }
            Check::good('[' . date('H:i:s') . '] Connected to database.');
            $res = Database::RunFolder($root . '/protected/install/database/schema/');
            if (true !== $res) {
                throw new Exception('Error loading database schema:<br/><div class="nested-error">' . $res . '</div>');
            }
            // Save the new version
            @file_put_contents($root . '/protected/install/database/version', DATABASE_VERSION);
            Check::good('[' . date('H:i:s') . '] Loaded database schema.');
 /**
  * Deletes a list of objects that match given conditions
  * @param multidimensional array {("field", "comparator", "value"), ("field", "comparator", "value"), ..}
  * @param bool $deep
  * @return
  */
 function DeleteList($fcv_array)
 {
     if (sizeof($fcv_array) > 0) {
         $connection = Database::Connect();
         $pog_query = "delete from `plugin` where ";
         for ($i = 0, $c = sizeof($fcv_array); $i < $c; $i++) {
             if (sizeof($fcv_array[$i]) == 1) {
                 $pog_query = $pog_query . " " . $fcv_array[$i][0] . " ";
                 continue;
             } else {
                 if ($i > 0 && sizeof($fcv_array[$i - 1]) !== 1) {
                     $pog_query = $pog_query . " AND ";
                 }
                 if (isset($this->pog_attribute_type[$fcv_array[$i][0]]['db_attributes']) && $this->pog_attribute_type[$fcv_array[$i][0]]['db_attributes'][0] != 'NUMERIC' && $this->pog_attribute_type[$fcv_array[$i][0]]['db_attributes'][0] != 'SET') {
                     $pog_query = $pog_query . "`" . $fcv_array[$i][0] . "` " . $fcv_array[$i][1] . " '" . $this->Escape($fcv_array[$i][2]) . "'";
                 } else {
                     $pog_query = $pog_query . "`" . $fcv_array[$i][0] . "` " . $fcv_array[$i][1] . " '" . $fcv_array[$i][2] . "'";
                 }
             }
         }
         return Database::NonQuery($pog_query, $connection);
     }
 }
Example #9
0
 /**
  * Construct a Wikimedia instance.
  * @param Database $db The database with which to connect to the database.
  * @param Cacher $cache The cache with which to read and write cached data.
  */
 public function __construct($db, $cache)
 {
     $this->wikis = $cache->Get('wikimedia-wikis');
     if (!$this->wikis) {
         // build wiki list
         $this->wikis = array();
         $db->Connect('metawiki.labsdb', 'metawiki_p');
         foreach ($db->Query('SELECT dbname, lang, family, url, size, is_closed, slice FROM meta_p.wiki WHERE url IS NOT NULL')->fetchAllAssoc() as $row) {
             if ($row['dbname'] == 'votewiki') {
                 continue;
             }
             // DB schema is broken
             $this->wikis[$row['dbname']] = new Wiki($row['dbname'], $row['lang'], $row['family'], $row['url'], $row['size'], $row['is_closed'], $row['slice']);
         }
         // cache result
         if (count($this->wikis)) {
             // if the fetch failed, we *don't* want to cache the result for a full day
             $cache->Save('wikimedia-wikis', $this->wikis);
         }
         $db->ConnectPrevious();
     }
 }
 function IsBase64FunctionInstalled()
 {
     $sql1 = "show function status where Db='" . $GLOBALS['configuration']['db'] . "' and (Name='BASE64_DECODE' or Name='BASE64_ENCODE')";
     $sql2 = "show tables like 'base64_data'";
     $connection = Database::Connect();
     $result = Database::Query($sql1, $connection);
     $result2 = Database::Query($sql2, $connection);
     if ($result == 2 && $result2 == 1) {
         return true;
     }
     return false;
 }
Example #11
0
    http_response_code(503);
}
// Set proper response code if site is in offline mode
$credentials = json_decode(file_get_contents(CONFIG_DIR . 'credentials.conf'), true);
// Load database credentials
foreach ($credentials as $name => $credential) {
    if (isset($credential['driver'])) {
        if (in_array($credential['driver'], Database::Drivers())) {
            if ($credential['driver'] == 'internal') {
                Database::ConnectFile(INTERNAL_DIR . 'lightwork.db');
            } else {
                if (isset($credential['file'])) {
                    Database::ConnectFile($credential['file'], $credential['driver']);
                } else {
                    if (isset($credential['host'])) {
                        Database::Connect($credential['user'], $credential['password'], $credential['database'], $credential['host'], $credential['port'], $credential['driver'], $credential['charset']);
                    } else {
                        if (isset($credential['socket'])) {
                            Database::ConnectSocket($credential['user'], $credential['password'], $credential['database'], $credential['socket'], $credential['driver'], $credential['charset']);
                        } else {
                            Lightwork::Log('Could not find fitting driver using current database configuration.', Lightwork::LOG_FATAL_ERROR);
                        }
                    }
                }
            }
        } else {
            Lightwork::Log('Tried to use unsupported database driver!', Lightwork::LOG_FATAL_ERROR);
        }
    } else {
        Lightwork::Log('Invalid database configuration!', Lightwork::LOG_FATAL_ERROR);
    }
Example #12
0
<?php

/**
 * Created by PhpStorm.
 * User: Rimas
 * Date: 1/27/2016
 * Time: 12:03 AM
 */
require 'config.php';
require 'autoload.php';
if (!empty($_POST)) {
    $validator = new Validator();
    if ($validator->validateName($_POST['name']) && $validator->validateName($_POST['password'])) {
        $database = new Database();
        if ($database->Connect($servername, $dbname, $username, $password)) {
            $database->setTable('users');
            $data = $database->GetDataWhere('name', $_POST['name']);
            $database->Close();
        }
        if ($data) {
            foreach ($data as $row) {
                if ($row['password'] === hash('sha256', $_POST['password'])) {
                    session_start();
                    $_SESSION['username'] = $_POST['name'];
                    header("Location: admin.php");
                } else {
                    echo "Incorrect password";
                }
            }
        } else {
            echo "Incorrect name";
Example #13
0
<?php

session_start();
define("PLSPATH", __DIR__ . "/../");
require PLSPATH . 'classes/Config.php';
require PLSPATH . 'classes/Database.php';
require PLSPATH . 'classes/Validate.php';
require PLSPATH . 'classes/Authentication.php';
require PLSPATH . 'classes/User.php';
require PLSPATH . 'classes/Session.php';
require PLSPATH . 'classes/Error.php';
require PLSPATH . 'classes/Email.php';
require PLSPATH . 'classes/Cookie.php';
require PLSPATH . 'classes/Avatar.php';
Config::LoadFile("config/config.php");
Config::LoadFile("config/lang.php");
$db = new Database();
$db->Connect();
if (Config::Get("validation.use_captcha")) {
    require PLSPATH . 'classes/vendor/captcha/recaptchalib.php';
}
if (isset($_COOKIE["rememberme"])) {
    if (!Authentication::Login(Cookie::Get(), true)) {
        Cookie::Clear();
    }
}
Example #14
0
 public static function GetAllUsers()
 {
     $database = new Database();
     $error = $database->Connect();
     if ($error->code != Error::NoError) {
         return new StatementResult(array(), $error);
     }
     $query = "SELECT id AS id, name AS name FROM Users ORDER BY name ASC";
     $queryParameters = array();
     $result = $database->ExecuteStatement($query, $queryParameters);
     return $result;
 }
Example #15
0
 private static function IsChampionOwnedByUser($championId, $userId)
 {
     $database = new Database();
     $error = $database->Connect();
     if ($error->code != Error::NoError) {
         return $error;
     }
     $query = "SELECT 1 AS isOwned FROM UserChampions WHERE userId = ? AND championId = ?";
     $queryParameters = array();
     $queryParameters[] = $userId;
     $queryParameters[] = $championId;
     $result = $database->ExecuteStatement($query, $queryParameters);
     if ($result->error->code != Error::NoError) {
         return false;
     }
     if (count($result->result) == 0) {
         return false;
     }
     return true;
 }
 public function __construct()
 {
     parent::Connect();
 }
Example #17
0
File: Jam.php Project: etienne/jam
 function Initialize()
 {
     // Set PHP configuration options
     $options = array('mbstring.language' => 'Neutral', 'mbstring.internal_encoding' => 'UTF-8', 'mbstring.encoding_translation' => 'On', 'mbstring.http_input' => 'auto', 'mbstring.detect_order' => 'ASCII,UTF-8,JIS,SJIS,EUC-JP', 'upload_max_filesize' => '21M', 'post_max_size' => '24M', 'display_errors' => true);
     foreach ($options as $key => $value) {
         ini_set($key, $value);
     }
     // Required for UTF-8 support
     mb_language('uni');
     // Error display
     error_reporting(E_ALL ^ E_NOTICE);
     // Add app/ and engine/ to include path
     set_include_path(get_include_path() . PATH_SEPARATOR . './app' . PATH_SEPARATOR . './engine');
     // Load classes
     $classesDir = 'engine/classes';
     $dirHandle = opendir($classesDir);
     while ($filename = readdir($dirHandle)) {
         // Make sure files end in .php
         if ($filename != basename($filename, '.php')) {
             $classPath = $classesDir . '/' . $filename;
             if (!is_dir($classPath)) {
                 require_once $classPath;
             }
         }
     }
     // Start caching engine; this also initializes output buffering
     $this->cache = new Cache();
     // Start output buffering
     ob_start('mb_output_handler');
     // Define files directory
     $this->filesDirectory = 'files/';
     // Load configuration files
     $this->projectConfig = IniFile::Parse('app/config/project.ini', true);
     $this->serverConfig = IniFile::Parse('app/config/server.ini', true);
     // Define constants
     define('ROOT', $this->serverConfig['root']);
     define('ERROR_FOREIGN_KEY_CONSTRAINT', 2);
     // Used in engine/classes/Module.php
     // Load database field types
     $this->fieldTypes = IniFile::Parse('engine/database/types.ini');
     // Load module fields
     $this->moduleFields = IniFile::Parse('engine/database/moduleFields.ini', true);
     $this->versionsSupportFields = IniFile::Parse('engine/database/versionsSupportFields.ini', true);
     // Load GetID3
     require_once 'engine/libraries/getid3/getid3.php';
     // Determine default language
     $this->defaultLanguage = $this->projectConfig['languages'][0];
     // Determine requested language
     $requestedLanguage = $_GET['language'];
     if ($requestedLanguage && in_array($requestedLanguage, $this->projectConfig['languages'])) {
         // User has manually switched language
         Cookie::Create('language', $requestedLanguage);
         $this->language = $requestedLanguage;
     } elseif ($_COOKIE['language']) {
         // User has previously selected a language
         $this->language = $_COOKIE['language'];
     } else {
         // User has never selected a language; use default
         $this->language = $this->defaultLanguage;
     }
     // Load strings in the requested language
     $this->strings = IniFile::Parse('engine/strings/' . $this->language . '.ini', true);
     // Load shorthands (useful function aliases; must load after strings)
     require 'engine/helpers/shorthands.php';
     // Connect to database
     $db = $this->serverConfig['database'];
     if (!($this->databaseLink = Database::Connect($db['server'], $db['username'], $db['password'], $db['database']))) {
         trigger_error("Couldn't connect to database " . $db['database'], E_USER_ERROR);
     }
     // Get available modules list
     $engineModules = Filesystem::GetDirNames('engine/modules');
     $this->appModules = Filesystem::GetDirNames('app/modules');
     $this->availableModules = $engineModules + $this->appModules;
     // Strip root directory and trailing slashes from full path request
     $pathString = $_SERVER['REQUEST_URI'];
     $barePath = substr($pathString, 0, strrpos($pathString, '?'));
     $pathString = $barePath ? $barePath : $pathString;
     $fullRequest = rtrim($pathString, '/');
     preg_match('|^' . ROOT . '(.*)$|', $fullRequest, $requestArray);
     // Use requested URL, or use root path if none was requested
     $this->request = $requestArray[1] ? $requestArray[1] : $this->projectConfig['rootPath'];
     // We sync using database time (might differ from PHP time)
     $databaseTimeQuery = new Query(array('fields' => 'NOW()'));
     $databaseTime = $databaseTimeQuery->GetSingleValue();
     $this->databaseTime = $databaseTime;
     // Make sure everything is properly initialized
     $tables = Database::GetTables();
     if (!$tables['users'] || !$tables['_paths']) {
         $this->FirstRun();
     }
     // Get installed modules list
     $this->installedModules = Query::SimpleResults('_modules');
     // Create User object
     $this->user = new User();
     // Create layout object
     $this->template = new Template();
     // Determine mode
     $requestedMode = $_GET['mode'];
     $availableModes = IniFile::Parse('engine/config/modes.ini');
     if ($availableModes[$requestedMode]) {
         // If requested mode exists, use it
         $this->mode = $requestedMode;
     } else {
         // HTML is the default mode
         $this->mode = 'html';
     }
     // Load paths
     $paths = Query::FullResults('_paths');
     foreach ($paths as $path) {
         // Use path as key in $_JAM->paths array
         $this->paths[$path['path']] = $path;
     }
     // Look for request in paths
     if ($path = $this->paths[$this->request]) {
         // Path does exist
         if ($path['current']) {
             // This is a valid path; proceed to module
             if ($this->rootModule = Module::GetNewModule($this->installedModules[$path['module']], $path['item'])) {
                 // Check whether we have sufficient privileges to display the module
                 if ($this->rootModule->CanView()) {
                     // Display module
                     $this->rootModule->Display();
                     // Determine path to admin pane for this item
                     $adminPath = 'admin/' . $moduleName;
                     if ($this->paths[$adminPath]) {
                         if ($path['item']) {
                             $adminPath .= '?a=edit&id=' . $path['item'];
                         }
                         $this->adminPath = ROOT . $adminPath;
                     } else {
                         $this->adminPath = ROOT . 'admin';
                     }
                 } else {
                     // Display login if we can't display
                     $this->user->Connect();
                 }
             } else {
                 trigger_error("Couldn't load root module", E_USER_ERROR);
             }
         } else {
             // This is an obsolete URL; find its current (up to date) equivalent
             $whereArray = array('module = ' . $path['module'], 'item = ' . $path['item'], "language = '" . $path['language'] . "'", 'current = TRUE');
             $currentPath = Query::SingleValue('_paths', 'path', $whereArray);
             HTTP::NewLocation($currentPath);
         }
     } else {
         // Path does not exist; throw 404
         header("HTTP/1.0 404 Not Found");
         $this->rootModule = Module::GetNewModule('errors');
         $this->rootModule->Display();
     }
     // Store and flush the contents of the output buffer
     $buffer = ob_get_clean();
     // Load and display template
     if ($this->mode == 'html' && $this->rootModuleName == 'admin') {
         // Special case for admin pages requested in HTML
         $templateName = 'html_admin';
     } else {
         $templateName = $this->mode;
     }
     $this->template->SetTemplate($templateName);
     $this->template->Display($buffer);
     // Set MIME type
     $contentType = $this->contentType ? $this->contentType : $availableModes[$this->mode];
     if ($contentType) {
         header('Content-Type: ' . $contentType);
     }
     // Write to cache; this also cleans output buffering
     $this->cache->Write();
 }
 function PerformUnitTest()
 {
     //test w/o arguments
     //any object
     $objectNames = unserialize($_SESSION['objectNameList']);
     //try getting a count
     if (sizeof($objectNames) > 0) {
         $anyObject = $objectNames[0];
         include_once "../objects/class." . strtolower($anyObject) . ".php";
         $anyObjectInstance = new $anyObject();
         $count = $anyObjectInstance->GetCount();
         $count2 = 0;
         $sql = 'select count(*) from `' . strtolower($anyObject) . '`;';
         $connection = Database::Connect();
         $cursor = Database::Reader($sql, $connection);
         if ($cursor !== false) {
             while ($row = Database::Read($cursor)) {
                 $count2 = $row['count(*)'];
             }
         }
         if ($count == $count2) {
             return true;
         }
         return false;
     }
     //test w/ arguments
 }
Example #19
0
 public function Connect($host, $database = NULL, $username = NULL, $password = NULL)
 {
     /* alias host */
     if (isset($this->dbn_hosts[$host]) && $this->dbn_hosts[$host]) {
         $database = $host;
         $host = $this->dbn_hosts[$host];
     }
     parent::Connect($host, $database, $username, $password);
 }
Example #20
0
    } else {
        if (file_exists('/etc/storytlr/config.ini')) {
            $config_path = '/etc/storytlr/config.ini';
        }
    }
}
$config = new Zend_Config_Ini($config_path, 'general');
// Check the version number
if (!file_exists($root . '/protected/install/database/version')) {
    $current_version = 0;
} else {
    $current_version = (int) @file_get_contents($root . '/protected/install/database/version');
}
try {
    // Connect to the database
    $res = Database::Connect($config->db->host, $config->db->dbname, $config->db->username, $config->db->password);
    if (true !== $res) {
        throw new Exception('Error connecting to the database:<br/><div class="nested-error">' . $res . '</div>');
    }
    // If version = 0, run the initial schema
    if ($current_version == 0) {
        $res = Database::RunFolder($root . '/protected/install/database/schema/');
        if (true !== $res) {
            throw new Exception('Error loading database schema:<br/><div class="nested-error">' . $res . '</div>');
        }
    }
    // Run the update scripts
    while ($current_version < DATABASE_VERSION) {
        $next_version = $current_version + 1;
        $folder = sprintf($root . '/protected/install/database/update/%03d/', $next_version);
        $res = Database::RunFolder($folder);
<?php

// UPUO 1.0B https://github.com/jake-cryptic/ultrapowa-user-overviews
if (empty($_GET["id"])) {
    header("Location: index.php");
    die("<a href='index.php'>If not redirected click here</a>");
} else {
    if (is_numeric($_GET["id"])) {
        $setId = strip_tags($_GET["id"]);
        require_once "config.inc.php";
        require_once "database.class.php";
        $Database = new Database();
        $Database->config = $conf;
        $Database->Connect();
        $sql = "SELECT * FROM player WHERE PlayerId = '" . $setId . "'";
    } else {
        header("Location: index.php");
        die("<a href='index.php'>If not redirected click here</a>");
    }
}
?>
<!DOCTYPE HTML>
<html lang="<?php 
echo $conf->meta->default_lang;
?>
">
	<head>
	
		<title><?php 
echo $conf->meta->site_name;
?>
/**
 * Gets total no. of records;
 */
function GetNumberOfRecords($objectName)
{
    $sql = 'select count(*) from `' . strtolower($objectName) . "`";
    $connection = Database::Connect();
    $cursor = Database::Reader($sql, $connection);
    if ($cursor !== false) {
        while ($row = Database::Read($cursor)) {
            return $row['count(*)'];
        }
    }
    return 0;
}
Example #23
0
	<div id="header">
  	<ul>
  	<li id='inactive'>My Objects:</li>
	<?php 
        if (!isset($_SESSION['objectName'])) {
            $_SESSION['objectName'] = $objectNameList[0];
        }
        for ($i = 0; $i < count($objectNameList); $i++) {
            $name = $objectNameList[$i];
            eval('$instance = new ' . $name . '();');
            if (!TestIsMapping($instance)) {
                echo "<li " . ($_SESSION['objectName'] == $objectNameList[$i] ? "id='current'" : '') . "><a href='./index.php?objectName=" . $objectNameList[$i] . "'>" . $objectNameList[$i] . "</a></li>";
                //echo "<a href='./index.php?objectName=".$objectNameList[$i]."'".(isset($_SESSION['objectName']) && $_SESSION['objectName']==$objectNameList[$i]?"class='activetab'":(!isset($_SESSION['objectName'])&&$i==0?"class='activetab'":"inactivetab")).">".$objectNameList[$i]."</a> ";
            }
        }
        $connection = Database::Connect();
        $count = 0;
        $sql = 'show index from `' . strtolower($_SESSION['objectName']) . '` where Key_name = "searching"';
        $cursor = Database::Reader($sql, $connection);
        while ($row = Database::Read($cursor)) {
            $count++;
        }
        ?>
	</ul>
	</div><!--header-->
	</div><!--subtabs-->
	<div class="toolbar"><div style="float:left;"><a href="<?php 
        echo $_SESSION['links'][$_SESSION['objectName']];
        ?>
" target="_blank" title="modify and regenerate object"><img src="./setup_images/setup_regenerate.jpg" border="0"/></a><a href="#" title="Delete all objects" onclick="if (confirm('Are you sure you want to delete all objects in this table? TPress OK to Delete.')){window.location='./?thrashall=true';}else{alert('Phew, nothing was deleted ;)');}"><img src='./setup_images/setup_deleteall.jpg' alt='delete all' border="0"/></a><a href="#" onclick="javascript:expandAll();return false;" title="expand all nodes"><img src='./setup_images/setup_expandall.jpg' alt='expand all' border="0"/></a><a href="#" onclick="javascript:collapseAll();return false;" title="collapse all nodes"><img src='./setup_images/setup_collapseall.jpg' alt='collapse all' border="0"/></a><a href="#" title="update all objects to newest POG version" onclick="if (confirm('Setup will now attempt to upgrade your objects by contacting the POG SOAP server. Would you like to continue?')){window.location='./setup_library/upgrade.php';}else{alert('Upgrade aborted');}"><img src='./setup_images/setup_updateall.jpg' alt='update all objects' border='0'/></a></div><?php 
        if ($count > 0) {
Example #24
0
<?php

spl_autoload_register('MyLoader');
function MyLoader($sClass)
{
    if (strstr($sClass, 'Sql')) {
        require_once '../classes/databases/' . $sClass . '.php';
    } else {
        require_once '../classes/' . $sClass . '.php';
    }
}
$oDatabase_connection = new Database();
$oDatabase = $oDatabase_connection->Connect();
$oSupporter = new Supporter();
$bError = false;
// Wenn false dann Fehlerfrei
$sMessage = "";
$aFilterAssoc = array('name' => FILTER_SANITIZE_ENCODED, 'action' => FILTER_SANITIZE_ENCODED, 'password' => FILTER_SANITIZE_ENCODED);
$aUserInputsAssoc = filter_input_array(INPUT_POST, $aFilterAssoc);
if ($aUserInputsAssoc['action'] === 'register') {
    $aResultAssoc = $oSupporter->Login($aUserInputsAssoc, $oDatabase);
    echo json_encode($aResultAssoc);
}
 /**
  * Deletes a list of objects that match given conditions
  * @param multidimensional array {("field", "comparator", "value"), ("field", "comparator", "value"), ...} 
  * @param bool $deep 
  * @return 
  */
 function DeleteList($fcv_array, $deep = false, $across = false)
 {
     if (sizeof($fcv_array) > 0) {
         if ($deep || $across) {
             $objectList = $this->GetList($fcv_array);
             foreach ($objectList as $object) {
                 $object->Delete($deep, $across);
             }
         } else {
             $connection = Database::Connect();
             $pog_query = "delete from `parent_` where ";
             for ($i = 0, $c = sizeof($fcv_array); $i < $c; $i++) {
                 if (sizeof($fcv_array[$i]) == 1) {
                     $pog_query .= " " . $fcv_array[$i][0] . " ";
                     continue;
                 } else {
                     if ($i > 0 && sizeof($fcv_array[$i - 1]) !== 1) {
                         $pog_query .= " AND ";
                     }
                     if (isset($this->pog_attribute_type[$fcv_array[$i][0]]['db_attributes']) && $this->pog_attribute_type[$fcv_array[$i][0]]['db_attributes'][0] != 'NUMERIC' && $this->pog_attribute_type[$fcv_array[$i][0]]['db_attributes'][0] != 'SET') {
                         $pog_query .= "`" . $fcv_array[$i][0] . "` " . $fcv_array[$i][1] . " '" . $this->Escape($fcv_array[$i][2]) . "'";
                     } else {
                         $pog_query .= "`" . $fcv_array[$i][0] . "` " . $fcv_array[$i][1] . " '" . $fcv_array[$i][2] . "'";
                     }
                 }
             }
             return Database::NonQuery($pog_query, $connection);
         }
     }
 }
Example #26
0
 public function Process($id, $new_file, $process_id)
 {
     global $CONFIG;
     $outputfile = $CONFIG["PRICE_WORKER_LOG"];
     $dateExt = new DateTime();
     $cur_date = $dateExt->format("Y-m-d H:i:s");
     $prov_data = "";
     $to_search = new ArrayObject();
     $this->WriteLog($outputfile, "\n\n------------------------------------------------------------------------------\n");
     $this->WriteLog($outputfile, "Start process: " . $cur_date . "\n");
     $this->WriteLog($outputfile, "Input params: \n");
     $this->WriteLog($outputfile, "* id: " . $id . "\n* file: " . $new_file . "\n* processId: " . $process_id . " \n-- \n");
     $db = new Database($CONFIG["DB_HOST"], $CONFIG["DB_NAME"], $CONFIG["DB_USER"], $CONFIG["DB_PASS"]);
     $db->Connect();
     $filesize = filesize($new_file);
     $handle = @fopen($new_file, "r");
     if (!$handle) {
         $db->Exec("update `Uploads` set Status='Ошибка' where id='" . $process_id . "' ;");
         $this->WriteLog($outputfile, "Error open file! \n");
         die("Error open file!");
     }
     $this->WriteLog($outputfile, "\nInput file size:" . $filesize . "\n");
     if (($buffer = fgets($handle, 4096)) !== false) {
         $columnsCount = substr_count($buffer, ';');
         if ($columnsCount != 7) {
             fclose($handle);
             $db->Exec("update `Uploads` set Status='Ошибка' where id='" . $process_id . "' ;");
             $this->WriteLog($outputfile, "Incorrect file format. Columns count must be: 7. Actual: " . $columnsCount . " \n");
             die("Incorrect file format");
         }
     } else {
         $db->Exec("update `Uploads` set Status='Ошибка' where id='" . $process_id . "' ;");
         $this->WriteLog($outputfile, "Can't open file or file is empty ! \n");
         die("Can't open file");
     }
     try {
         $this->WriteLog($outputfile, "Structure of file: OK\n");
         $db->Exec("update `Uploads` set Status='Подготовка 10%' where id='" . $process_id . "' ;");
         $db->Exec("delete from `ProductsSearch` where ProductId in (select id from `Products` where ProviderId='" . $id . "');");
         $db->Exec("update `Uploads` set Status='Подготовка 40%' where id='" . $process_id . "' ;");
         $db->Exec("delete from `Products` where ProviderId='" . $id . "' ;");
         $db->Exec("update `Uploads` set Status='Подготовка 70%' where id='" . $process_id . "' ;");
         //$db->Exec("delete from `ProductsSearch` where ProductId not in (select id from `Products`);");
         $this->WriteLog($outputfile, "Clean before process\n");
         $dbh = new PDO("mysql:host=" . $CONFIG["DB_HOST"] . ";dbname=" . $CONFIG["DB_NAME"], $CONFIG["DB_USER"], $CONFIG["DB_PASS"]);
         $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         $sql = "SELECT Name,FullName,City,Address,Phone FROM Provider where id='{$id}' ";
         foreach ($dbh->query($sql) as $row) {
             $prov_data = $row['Name'] . $row['FullName'] . $row['City'] . $row['Address'] . $row['Phone'];
         }
         $this->WriteLog($outputfile, "\nPrepare to process\n");
         $dbh->beginTransaction();
         $sql = "INSERT INTO `Products`(`id`,`Number`,`NumberProvider`,`Name`,`FullName`,`BasicCharacteristics`,`ProviderId`," . "`Unit`,`Price`,`Rest`,`Updated`) VALUE (?,?,?,?,?,?,?,?,?,?,?);";
         $sth = $dbh->prepare($sql);
         if (!$sth) {
             $this->WriteLog($outputfile, "PDO::errorInfo():\n" . print_r($dbh->errorInfo(), true));
         }
         $readed = 0;
         $progress = 0;
         while (($buffer = fgets($handle, 4096)) !== false) {
             $readed += strlen($buffer);
             if ($progress != intval($readed * 100 / $filesize)) {
                 $progress = intval($readed * 100 / $filesize);
                 $this->WriteLog($outputfile, "Updating product " . $progress . "\n");
                 $db->Exec("update `Uploads` set Status='Обработка " . $progress . "%' where id='" . $process_id . "' ;");
             }
             $buffer = iconv("windows-1251", "UTF-8//IGNORE", $buffer);
             $elem = explode(";", $buffer);
             $guid = UUID::v4();
             if (!(empty($elem[0]) || empty($elem[1]) || empty($elem[2]))) {
                 $ss = $elem[0] . $elem[1] . $elem[2] . $elem[3] . $elem[4] . $id . $elem[5] . $elem[6] . $elem[7] . $prov_data;
                 $to_search[count($to_search)] = array("id" => $guid, "data" => mb_strtolower($ss, 'UTF-8'));
                 $sth->execute(array($guid, $elem[0], $elem[1], $elem[2], $elem[3], $elem[4], $id, $elem[5], str_replace(",", ".", $elem[6]), $elem[7], $cur_date));
             }
         }
         $this->WriteLog($outputfile, "Finished processing\n\n");
         $sql = "insert into `ProductsSearch` (ProductId,SearchString) values (?,?);";
         $this->WriteLog($outputfile, "Count of item:" . count($to_search) . "\n\n");
         $progress = 0;
         $col = 0;
         $sth = $dbh->prepare($sql);
         foreach ($to_search as $i) {
             $col++;
             if ($progress != intval($col * 100 / count($to_search))) {
                 $progress = intval($col * 100 / count($to_search));
                 $this->WriteLog($outputfile, "Optimization search " . $progress . "\n");
                 $db->Exec("update `Uploads` set Status='Постобработка " . $progress . "%' where id='" . $process_id . "' ;");
             }
             $sth->execute(array($i["id"], $i["data"]));
         }
         $this->WriteLog($outputfile, "Optimization finished\n");
         $dbh->commit();
     } catch (PDOException $e) {
         $dbh->rollBack();
         $db->Exec("update `Uploads` set Status='Ошибка' where id='" . $process_id . "' ;");
         $this->WriteLog($outputfile, "Exception while update product: " . $e->getMessage() . "\n");
         die("Error!: " . $e->getMessage() . "<br/>");
     } catch (Exception $e) {
         $this->WriteLog($outputfile, "Exception while update product: " . $e->getMessage() . "\n");
     }
     if (!feof($handle)) {
         $db->Exec("update `Uploads` set Status='Ошибка' where id='" . $process_id . "' ;");
         $this->WriteLog($outputfile, "Error: unexpected fgets() fail\n");
     }
     $db->Exec("update `Uploads` set Status='Готово' where id='" . $process_id . "' ;");
     fclose($handle);
     sleep(1);
     if ($CONFIG["DEBUG"] != 1) {
         unlink($new_file);
         $this->WriteLog($outputfile, "Remove uploaded file\n");
     } else {
         $this->WriteLog($outputfile, "Uploaded file will not be deleted, because debug flag is turned on.\n");
     }
 }