get_db() public static method

Returns the PDO instance used by the the ORM to communicate with the database. This can be called if any low-level DB access is required outside the class. If multiple connections are used, accepts an optional key name for the connection.
public static get_db ( string $connection_name = self::DEFAULT_CONNECTION ) : PDO
$connection_name string Which connection to use
return PDO
Example #1
0
 public function create($table, $ignore_keys = null)
 {
     if ($_POST) {
         $params = $_POST;
         $insert = \ORM::for_table($table)->create();
         \ORM::get_db()->beginTransaction();
         try {
             foreach ($params as $key => $value) {
                 $insert->{$key} = $value;
             }
             $insert->save();
             \ORM::get_db()->commit();
         } catch (Exception $e) {
             \ORM::get_db()->rollBack();
             throw $e;
         }
         $this->view = new Create('done');
     } else {
         $fields = \ORM::for_table($table)->raw_query('DESCRIBE ' . $table)->find_array();
         if ($ignore_keys) {
             foreach ($fields as $key => $field) {
                 if (in_array($field['Field'], $ignore_keys)) {
                     unset($fields[$key]);
                 }
             }
         }
         $data['fields'] = $fields;
         $this->view = new Create('create', $data);
     }
 }
Example #2
0
 public function __construct()
 {
     self::$debugbar = new StandardDebugBar();
     $pdo = new DebugBar\DataCollector\PDO\TraceablePDO(ORM::get_db());
     self::$debugbar->addCollector(new DebugBar\DataCollector\PDO\PDOCollector($pdo));
     Oc_Product::$debug = self::$debugbar;
 }
Example #3
0
function escapeLike($searched)
{
    $db = ORM::get_db();
    dd($db);
    //$searched = $db->real_escape_string($searched);
    //	$searched = $db->escape_string();
    return addcslashes($searched, "%_");
}
Example #4
0
 public function run()
 {
     include getcwd() . '/bootstrap.php';
     if (preg_match('#^\\p{Lu}#u', $this->config['name']) === 0) {
         echo "Error: parameter name must be camel-case. At a minimum, it must start with a capital letter.\n";
         \Lucid\Task\Container::run('usage', [static::$trigger]);
         exit;
     }
     $this->config['meta'] = new \Lucid\Library\Metabase\Metabase(\ORM::get_db());
     if (is_null($this->config['table']) === true) {
         $this->config['table'] = $this->config['name'];
     }
     $this->config['columns'] = $this->config['meta']->getColumns($this->config['table']);
     $this->config['keys'] = ['name' => $this->config['name'], 'table' => $this->config['table'], 'id_type' => $this->config['columns'][0]['type'], 'id' => $this->config['columns'][0]['name'], 'first_string_col' => null, 'title' => $this->config['name']];
     foreach ($this->config['columns'] as $column) {
         if ($column['type'] == 'string' && is_null($this->config['keys']['first_string_col']) === true) {
             $this->config['keys']['first_string_col'] = $column['name'];
         }
     }
     # we always run all *BuildKeys methods in case a later *BuildFile function relies on a key built by
     # a component not selected for building
     $this->modelBuildKeys();
     $this->viewBuildKeys();
     $this->controllerBuildKeys();
     $this->helperBuildKeys();
     $this->rulesetBuildKeys();
     $this->testBuildKeys();
     $this->dictionaryBuildKeys();
     if ($this->config['no-model'] === false) {
         echo "Building Model...\n";
         $this->modelBuildFiles();
     }
     if ($this->config['no-view'] === false) {
         echo "Building View...\n";
         $this->viewBuildFiles();
     }
     if ($this->config['no-controller'] === false) {
         echo "Building Controller...\n";
         $this->controllerBuildFiles();
     }
     if ($this->config['no-helper'] === false) {
         echo "Building Helper...\n";
         $this->helperBuildFiles();
     }
     if ($this->config['no-ruleset'] === false) {
         echo "Building Ruleset...\n";
         $this->rulesetBuildFiles();
     }
     if ($this->config['no-test'] === false) {
         echo "Building Test...\n";
         $this->testBuildFiles();
     }
     if ($this->config['no-dictionary'] === false) {
         echo "Building Dictionary...\n";
         $this->dictionaryBuildFiles();
     }
     echo "Complete.\n";
 }
Example #5
0
 public function readSqlFile($sql_file)
 {
     $sql_content = trim(file_get_contents($sql_file));
     if (!empty($sql_content)) {
         \ORM::get_db()->exec($sql_content);
     } else {
         throw new \Exception("No content for sql file");
     }
 }
Example #6
0
function db_getArrayOfRows($query)
{
    $dbResult = ORM::get_db()->query($query);
    $results = array();
    foreach ($dbResult as $row) {
        $results[] = $row;
    }
    return $results;
}
Example #7
0
 public function setUp()
 {
     // The tests for eager loading requires a real database.
     // Set up SQLite in memory
     ORM::set_db(new PDO('sqlite::memory:'));
     // Create schemas and populate with data
     ORM::get_db()->exec(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'models.sql'));
     // Enable logging
     ORM::configure('logging', true);
 }
Example #8
0
    public function create_database()
    {
        ORM::get_db()->query('CREATE TABLE `book` (
		  `id` integer NOT NULL CONSTRAINT pid PRIMARY KEY AUTOINCREMENT,
		  `title` varchar NOT NULL,
		  `url` varchar NOT NULL,
		  `date` varchar NOT NULL,
		  `pages` integer NOT NULL,
		  `thumb` varchar NOT NULL,
		  `tags` text NOT NULL
		)');
    }
 public function __construct(&$core)
 {
     $core->registerMessageHandler('PRIVMSG', "seen", "seenator");
     $core->registerCommand("seen", "seen", "Muestra cuando fue la ultima vez que se vio a un usuario. Sintaxis: seen <nick>");
     try {
         $k = ORM::for_table('seen')->find_one();
     } catch (PDOException $e) {
         $query = "CREATE TABLE 'seen' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'nick' TEXT NOT NULL, 'ts' INTEGER NOT NULL, 'txt' TEXT NOT NULL);";
         $db = ORM::get_db();
         $db->exec($query);
     }
 }
 public function __construct(&$core)
 {
     $core->registerCommand("autodeop", "autodeop", "Activa o desactiva el auto-deop en un canal. Sintaxis: autodeop <on/off> <canal>", 8, CUSTOMPRIV);
     $core->registerMessageHandler('MODE', "autodeop", "deop");
     try {
         $k = ORM::for_table('deopchans')->find_one();
     } catch (PDOException $e) {
         $query = "CREATE TABLE 'deopchans' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'channel' TEXT NOT NULL);";
         $db = ORM::get_db();
         $db->exec($query);
     }
 }
 public function __construct(&$core)
 {
     $core->registerCommand("quote", "quote", "Permite gestionar Quotes en el bot. Sintaxis: " . $core->conf['irc']['prefix'] . "quote [add|last|find|del|random] [mensaje de quote|número de quote]");
     $core->registerMessageHandler("307", "quote", "isregistered");
     try {
         $k = ORM::for_table('quotes')->find_one();
     } catch (PDOException $e) {
         $query = "CREATE TABLE 'quotes' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'nick' TEXT NOT NULL,  'quote' TEXT NOT NULL, 'date' datetime default current_timestamp);";
         $db = ORM::get_db();
         $db->exec($query);
     }
 }
    public function create_database()
    {
        ORM::get_db()->query('CREATE TABLE `hmanga` (
		  `id` integer NOT NULL CONSTRAINT pid PRIMARY KEY AUTOINCREMENT,
		  `url` varchar NOT NULL,
		  `real_id` int NOT NULL,
		  `title` varchar NOT NULL,
		  `date` varchar NOT NULL,
		  `description` text NOT NULL,
		  `pages` integer NOT NULL,
		  `gallery_url` varchar NOT NULL,
		  `tags` text NOT NULL
		)');
    }
 public function __construct(&$core)
 {
     $core->registerMessageHandler('PRIVMSG', "regexakick", "msgs");
     $core->registerMessageHandler('NOTICE', "regexakick", "msgs");
     $core->registerMessageHandler('JOIN', "regexakick", "joinlookup");
     $core->registerCommand("msgakick", "regexakick", "Maneja los akicks por expresiones regulares (por mensajes). Sintaxis: regexakick <add|del|list> <canal> <Expresión regular> (Nota: las expresiones regulares deben incluir el separador.)", 5);
     $core->registerCommand("joinakick", "regexakick", "Maneja los akicks por expresiones regulares (Al entrar al canal, por máscara). Sintaxis: regexakick <add|del|list> <canal> <Expresión regular> (Nota: las expresiones regulares deben incluir el separador. Nota 2: la regex se analiza teniendo en cuenta la máscara del usuario (nick!user@host). )", 5);
     try {
         $k = ORM::for_table('akicks')->find_one();
     } catch (PDOException $e) {
         $query = "CREATE TABLE 'akicks' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'regex' TEXT NOT NULL, 'type' INTEGER NOT NULL, 'channel' TEXT NOT NULL);";
         $db = ORM::get_db();
         $db->exec($query);
     }
 }
 public function __construct(&$core)
 {
     $core->registerCommand("chwadd", "wikichan", "Activa funciones wiki en un canal. Sintaxis: chwadd <#canal> <ruta a la API mediawiki>", 5);
     $core->registerCommand("chwrem", "wikichan", "Desctiva funciones wiki en un canal. Sintaxis: chwrem <#canal>", 5);
     $core->registerCommand("info", "wikichan", "Miestra información de un usuario wiki. Sintaxis: info <usuario>");
     $core->registerCommand("preview", "wikichan", "Muestra los primeros 440 caracteres de un articulo. Sintaxis: preview <Nombre del articulo>");
     $core->registerCommand("wikisearch", "wikichan", "Busca un articulo wiki. Sintaxis: wikisearch <Termino de busqueda/>");
     try {
         $k = ORM::for_table('wikichan')->find_one();
     } catch (PDOException $e) {
         $query = "CREATE TABLE 'wikichan' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'chan' TEXT NOT NULL, 'api' TEXT NOT NULL);";
         $db = ORM::get_db();
         $db->exec($query);
     }
 }
 public function __construct(&$core)
 {
     try {
         $k = ORM::for_table('chignore2')->find_one();
     } catch (PDOException $e) {
         $query = "CREATE TABLE 'chignore2' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'user' TEXT NOT NULL);";
         $db = ORM::get_db();
         $db->exec($query);
     }
     //$this->timehandlerid = $core->irc->registerTimehandler(20000, $this, "th");
     $core->registerTimeHandler(20000, "whitebotvoy", "th");
     //$core->registerCommand("admin", "whitebotsh", "Avisa a los administradores disponibles.");
     $core->registerCommand("talk", "whitebotvoy", "Habilita o deshabilita el habla del bot. Sintaxis: hablar <si/no>", 5, "whitesh");
     $core->registerCommand("chignore", "whitebotsh", "Ignora un usuario en los cambios recientes. Sintaxis: chignore <usuario>", 5, "whitesh");
     $core->registerCommand("dechignore", "whitebotsh", "Designora un usuario en los cambios recientes. Sintaxis: chignore <usuario>", 5, "whitesh");
 }
Example #16
0
 public function save()
 {
     \ORM::get_db()->beginTransaction();
     if ($this->is_new()) {
         Tweet::reset_in_reply_to_status_id();
     }
     TweetDate::register($this->date());
     parent::save();
     if (is_array($this->_medias)) {
         foreach ($this->_medias as $media) {
             $media->tweet_id = $this->id;
             $media->save();
         }
     }
     \ORM::get_db()->commit();
 }
Example #17
0
 public function process(string $email, string $password)
 {
     lucid::$app->logger()->debug('Attempting to authenticate user: '******'vw_users_details')->where_raw('LOWER(email) = ?', strtolower($email))->find_one();
     /*
     if ($user === false) {
         Ruleset::sendError(_('error:authentication:failed1'));
     }
     */
     if (password_verify($password, $user->password) === false) {
         //Ruleset::sendError(_('error:authentication:failed2'));
     }
     lucid::$app->session()->setValues($user->as_array());
     \ORM::get_db()->query('update users set last_login=CURRENT_TIMESTAMP where user_id=' . $user->user_id);
     lucid::$app->logger()->debug('Successful authentication for ' . lucid::$app->session()->string('email'));
     lucid::$app->response()->redirect('dashboard', lucid::$app->session()->string('role_name'));
 }
 public function __construct(&$core)
 {
     $this->core = $core;
     $core->registerMessageHandler('PRIVMSG', "games", "gamecommandhandler");
     $core->registerCommand("changemoney", "games", "Cambia el dinero almacenado en la cuenta de un usuario. Sintaxis: changemoney <nick> <dinero>", 6, "games", null, SMARTIRC_TYPE_QUERY | SMARTIRC_TYPE_CHANNEL);
     $core->registerCommand("impuesto", "games", "Cobra impuestos.", 6, "games", null, SMARTIRC_TYPE_QUERY | SMARTIRC_TYPE_CHANNEL);
     $core->registerCommand("enablegame", "games", "Activa los juegos en un cana. Sintaxis: enablegame <canal>", 4, "games", null, SMARTIRC_TYPE_QUERY | SMARTIRC_TYPE_CHANNEL);
     $core->registerCommand("disablegame", "games", "Desactiva los juegos en un canal. Sintaxis: disablegame <canal>", 4, "games", null, SMARTIRC_TYPE_QUERY | SMARTIRC_TYPE_CHANNEL);
     $core->registerCommand("delgameuser", "games", "Elimina a un usurio de los juegos. Sintaxis: delgameuser <usuario>", 6, "games", null, SMARTIRC_TYPE_QUERY | SMARTIRC_TYPE_CHANNEL);
     $core->registerCommand("congelar", "games", "Congela a un usuario de los juegos. Sintaxis congelar <usuario> [hiper|light]", 6, "games", null, SMARTIRC_TYPE_QUERY | SMARTIRC_TYPE_CHANNEL);
     $core->registerCommand("descongelar", "games", "Descongela a un usuario de los juegos. Sintaxis: descongelar <usuario>", 6, "games", null, SMARTIRC_TYPE_QUERY | SMARTIRC_TYPE_CHANNEL);
     $core->registerCommand("top100", "games", "Muestra los 100 usuarios con mas dinero", 4, "games", null, SMARTIRC_TYPE_QUERY | SMARTIRC_TYPE_CHANNEL);
     $core->irc->setSenddelay(500);
     // Nosotros hacemos mucho flood, pero queremos que el bot siga vivo!
     $core->registerTimeHandler(86400000, "games", "autoimp");
     $core->registerTimeHandler(1800000, "games", "sourprise");
     try {
         $k = ORM::for_table('games_users')->find_one();
         $k = ORM::for_table('games_banco')->find_one();
         $k = ORM::for_table('games_cgames')->find_one();
         $k = ORM::for_table('games_channels')->find_one();
     } catch (PDOException $e) {
         try {
             $db = ORM::get_db();
             $db->exec("CREATE TABLE 'games_channels' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'channel' TEXT NOT NULL, 'extrainf' TEXT NOT NULL);");
             $db->exec("CREATE TABLE 'games_users' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'nick' TEXT NOT NULL, 'dinero' INTEGER NOT NULL, 'nivel' INTEGER NOT NULL, 'congelado' INTEGER NOT NULL, 'extrainf' TEXT NOT NULL);");
             $db->exec("CREATE TABLE 'games_banco' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'dinero' INTEGER NOT NULL, 'extrainf' TEXT NOT NULL);");
             $db->exec("CREATE TABLE 'games_cgames' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'extrainf' TEXT NOT NULL);");
             $k = ORM::for_table('games_banco')->where('id', 1)->find_one();
             if (!$k) {
                 $banco = ORM::for_table('games_banco')->create();
                 $banco->dinero = 1000000;
                 $banco->extrainf = json_encode(array('pozo' => '0'));
                 $banco->save();
             }
         } catch (PDOException $e) {
             /* meh */
         }
     }
 }
 public function __construct(&$core)
 {
     if (!$core->isLoaded("country")) {
         $core->loadModule("m_countries.php");
     }
     // Usaremos a m_countries!
     $this->paises = array_flip($core->getModule("country")->paises);
     $this->paises2 = $core->getModule("country")->paises;
     $core->registerMessageHandler('JOIN', "skynet", "hostspy");
     //$core->registerTimeHandler(1800000, "skynet", "spyall"); // Cada 30 minutos los espiamos a todos!
     $core->irc->setChannelSyncing(true);
     $core->registerCommand("espiar", "skynet", false, 1);
     $core->registerCommand("skystats", "skynet", false, 1);
     $core->registerCommand("skytop", "skynet", "Muestra un ranking de los usuarios por país. Sintaxis: skytop [cantidad] [pais]", 1);
     $core->registerCommand("skyuser", "skynet", "Muestra la información de un usuario o borra la entrada de ese usuario. Sintaxis: skyuser <nick> [del]", 3);
     try {
         $k = ORM::for_table('spy')->find_one();
     } catch (PDOException $e) {
         $query = "CREATE TABLE 'spy' ('id' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, 'nick' TEXT NOT NULL, 'ip' TEXT NOT NULL, 'pais' TEXT NOT NULL, 'region' TEXT NOT NULL, 'ciudad' TEXT NOT NULL, 'timezone' TEXT NOT NULL);";
         $db = ORM::get_db();
         $db->exec($query);
     }
 }
 public function register(Application $app)
 {
     $app['paris.initializer'] = $app->protect(function () use($app) {
         static $initialized = false;
         if ($initialized) {
             return;
         }
         $initialized = true;
         $config = isset($app['idiorm.config']) ? $app['idiorm.config'] : null;
         \ORM::configure($config);
         if (isset($app['paris.model.prefix'])) {
             \Model::$auto_prefix_models = $app['paris.model.prefix'];
         }
     });
     $app['paris'] = $app->share(function ($app) {
         $app['paris.initializer']();
         return new ParisService();
     });
     $app['paris.db'] = $app->share(function ($app) {
         $app['paris.initializer']();
         return \ORM::get_db();
     });
 }
Example #21
0
 /**
  * スキーマ作成
  */
 public function schemaAction()
 {
     $schema_dir = GENERATOR_ROOT . '/workspace/db/';
     //twig
     $view = $this->getView();
     //ディレクトリ生成
     $this->mkDir($schema_dir);
     $db = \ORM::get_db();
     $result = $db->query('SHOW TABLES');
     $tables = array();
     foreach ($result as $row) {
         $tables[] = array_shift($row);
     }
     #region 設定ファイル生成
     foreach ($tables as $table) {
         $php_name = $this->snakeToCamel($table);
         $result = $db->query("SHOW FULL COLUMNS FROM {$table}");
         $columns = array();
         foreach ($result as $row) {
             $_row = $row;
             preg_match("/(.*)\\((.*)\\)(.*)/is", $_row['Type'], $retArr);
             if ((bool) $retArr) {
                 $_row['Type'] = $retArr[1];
                 $_row['Size'] = $retArr[2];
             } else {
                 $_row['Size'] = '';
             }
             $columns[] = $_row;
         }
         $xml_name = $table . ".xml";
         $template = $this->getTemplate('schema.twig');
         $this->output($schema_dir . $xml_name, $view->render($template, compact('table', 'php_name', 'columns')), true);
     }
     # endregion
     echo " Build Schema complete!\n";
 }
require_once __DIR__ . '/bootstrap.php';
$header = "  _____    _                                      _           _        ____  _   _ ____  \n |_   _|__| | ___  __ _ _ __ __ _ _ __ ___       | |__   ___ | |_     |  _ \\| | | |  _ \\ \n   | |/ _ \\ |/ _ \\/ _` | '__/ _` | '_ ` _ \\ _____| '_ \\ / _ \\| __|____| |_) | |_| | |_) |\n   | |  __/ |  __/ (_| | | | (_| | | | | | |_____| |_) | (_) | ||_____|  __/|  _  |  __/ \n   |_|\\___|_|\\___|\\__, |_|  \\__,_|_| |_| |_|     |_.__/ \\___/ \\__|    |_|   |_| |_|_|    \n                  |___/                                                                  \n-----------------------------------------------------------------------------------------";
echo $header . PHP_EOL;
writeColor('green', 'This command installs the required migration file for reponses');
echo "Are you sure you want to run the migration and create the table? Type 'yes' to continue: ";
//Let's read the user input
//$handle = fopen ("php://stdin","r");
//$userInput = fgets($handle);
$userInput = fgets(STDIN);
if (trim($userInput) !== 'yes') {
    echo PHP_EOL . "Bye!" . PHP_EOL;
    exit;
}
//Now let's try to create the table
try {
    $db = ORM::get_db();
    $db->exec($config['connection'][$config['source']]['migration']);
    writeColor('green', 'Database table created successfully!');
} catch (PDOException $e) {
    writeColor('red', 'An error has been occurred:');
    writeColor('red', 'Error ' . $e->getCode() . ': ' . $e->getMessage());
}
//This helper will only be needed here,
//So until more of these are needed elsewhere, I've decided to keep this here for now
/**
 * Writes given message in specified color
 * Taken From Scabbla2 PHP Framework
 * https://github.com/scabbiafw/scabbia2-fw/
 *
 * @param string $uColor color
 * @param string $uMessage message
Example #23
0
 public function rollbackTransaction()
 {
     // Откатываем транзакцию
     return ORM::get_db()->rollBack();
 }
Example #24
0
 public function __construct()
 {
     $this->db = \ORM::get_db();
 }
Example #25
0
<?php

/*
 * Transaction testing for Dakota.
 */
require_once dirname(__FILE__) . "/idiorm.php";
require_once dirname(__FILE__) . "/../dakota.php";
require_once dirname(__FILE__) . "/test_classes.php";
// Enable logging
ORM::configure('logging', true);
// Use SQLite in-memory database
ORM::configure('sqlite::memory:');
ORM::get_db()->exec('CREATE TABLE user(id INTEGER PRIMARY KEY ASC, name TEXT, age INT)');
class User extends Model
{
}
$user = new User();
$user->name = "Ted";
$user->age = 22;
$user->save();
// Quick sanity check for inserting rows without a transaction
Tester::check_equal('Insert ID for first insert', (int) $user->id, 1);
$count = Model::factory('User')->count();
Tester::check_equal('Row count after first insert', $count, 1);
// Test rolling back a transaction
Model::start_transaction();
$user = new User();
$user->name = "Frank";
$user->age = 15;
$user->save();
Tester::check_equal('Insert ID for insert to rollback', (int) $user->id, 2);
Example #26
0
 private function changeCredits($userId, $amount)
 {
     $user = $this->bcms->users->get($userId);
     if (!$user) {
         $this->bcms->flashNow('error', 'User not found');
         return false;
     }
     $profile = $this->bcms->users->getProfile($user->id);
     try {
         // Start a transaction
         \ORM::get_db()->beginTransaction();
         $profile->balance = $profile->balance + $amount;
         $profile->save();
         //print_r($profile->as_array());
         // Commit a transaction
         \ORM::get_db()->commit();
         if ($amount > 0) {
             $operationName = 'Пополнение ';
         } else {
             $operationName = 'Списание со';
         }
         $this->bcms->history->add(array('title' => $operationName . ' счета пользователя ' . $user->email . ' ' . $amount . ' кредитов', 'link' => '/admin/users/edit/' . $user->id, 'where' => '', 'css_class' => ''));
         return true;
     } catch (Exception $e) {
         // An exception has been thrown
         // We must rollback the transaction
         \ORM::get_db()->rollBack();
         return false;
     }
 }
Example #27
0
    public function create_database()
    {
        ORM::get_db()->query('CREATE TABLE `hmanga` (
			`id` integer NOT NULL CONSTRAINT pid PRIMARY KEY AUTOINCREMENT,
			`title` varchar NOT NULL,
			`series` varchar NOT NULL,
			`artist` varchar NOT NULL,
			`date` varchar NOT NULL,
			`desc` varchar NULL,
			`tags` varchar NULL,
			`url` varchar NOT NULL,
			`thumbs` text NULL,
			`pattern` varchar NULL
		)');
    }
Example #28
0
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see http://www.gnu.org/licenses/.
*/
$klein->respond('GET', function ($request, $response, $service, $app) {
});
$klein->respond('POST', function ($request, $response, $service) {
    $params = $request->paramsPost();
    $mysql = ORM::get_db();
    try {
        $mysql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $mysql->beginTransaction();
        $query = $mysql->prepare("INSERT INTO `acp_settings` (`setting_ref`, `setting_val`) VALUES\n\t\t\t\t\t('company_name', :cname),\n\t\t\t\t\t('master_url', :murl),\n\t\t\t\t\t('assets_url', :aurl),\n\t\t\t\t\t('main_website', :mwebsite),\n\t\t\t\t\t('postmark_api_key', NULL),\n\t\t\t\t\t('mandrill_api_key', NULL),\n\t\t\t\t\t('mailgun_api_key', NULL),\n\t\t\t\t\t('sendgrid_api_key', NULL),\n\t\t\t\t\t('sendmail_email', NULL),\n\t\t\t\t\t('sendmail_method','php'),\n\t\t\t\t\t('captcha_pub',NULL),\n\t\t\t\t\t('captcha_priv',NULL),\n\t\t\t\t\t('default_language', 'en'),\n\t\t\t\t\t('force_online', 0),\n\t\t\t\t\t('https', 0),\n\t\t\t\t\t('use_api', 0),\n\t\t\t\t\t('allow_subusers', 0)");
        $query->execute(array(':cname' => $params['companyName'], ':murl' => 'http://' . $params['siteUrl'] . '/', ':mwebsite' => 'http://' . $params['siteUrl'] . '/', ':aurl' => '//' . $params['siteUrl'] . '/assets/'));
        $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xfff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
        $mysql->prepare("INSERT INTO `users` VALUES(NULL, :uuid, :username, :email, :password, :language, :time, NULL, NULL, 1, 0, 1, 0, NULL)")->execute(array(':uuid' => $uuid, ':username' => $params['adminName'], ':email' => $params['adminEmail'], ':password' => password_hash($params['adminPass'], PASSWORD_BCRYPT), ':language' => 'en', ':time' => time()));
        $response->redirect('/index');
    } catch (\Exception $ex) {
        echo $ex->getMessage() . "\n";
        if (isset($mysql) && $mysql->inTransaction()) {
            $mysql->rollBack();
        }
        exit(1);
        $service->flash("Error occurred while committing changes: ");
Example #29
0
 protected function _resequenceEntityOrder($entityName, $parentId, $order)
 {
     ORM::get_db()->beginTransaction();
     $entities = $parentId === null ? Model::factory($entityName)->filter('orderAfter', $order)->findMany() : Model::factory($entityName)->filter('orderAfter', $parentId, $order)->findMany();
     foreach ($entities as $e) {
         $e->Order = $order;
         $e->save();
         $order += 1;
     }
     return ORM::get_db()->commit();
 }
Example #30
0
function db_getArrayOfRows($query, $fetchStyle = PDO::FETCH_BOTH)
{
    $dbResult = ORM::get_db()->query($query, $fetchStyle);
    $results = array();
    foreach ($dbResult as $row) {
        $results[] = $row;
    }
    return $results;
}