本文整理汇总了PHP中Gdn::database方法的典型用法代码示例。如果您正苦于以下问题:PHP Gdn::database方法的具体用法?PHP Gdn::database怎么用?PHP Gdn::database使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Gdn
的用法示例。
在下文中一共展示了Gdn::database方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: _GetData
protected function _GetData()
{
$Px = Gdn::database()->DatabasePrefix;
$Sql = "show table status where Name in ('{$Px}User', '{$Px}Discussion', '{$Px}Comment')";
$Result = array('User' => 0, 'Discussion' => 0, 'Comment' => 0);
foreach ($Result as $Name => $Value) {
$Result[$Name] = $this->getCount($Name);
}
$this->setData('Totals', $Result);
}
示例2: __construct
/**
* The constructor for this class. Automatically fills $this->ClassName.
*
* @param string $Database
* @todo $Database needs a description.
*/
public function __construct($Database = null)
{
parent::__construct();
if (is_null($Database)) {
$this->Database = Gdn::database();
} else {
$this->Database = $Database;
}
$this->databasePrefix($this->Database->DatabasePrefix);
$this->reset();
}
示例3: discussionController_afterDiscussionTitle_handler
/**
* Write information about addons to the discussion if it is related to an addon.
*
* @param DiscussionController $Sender
*/
public function discussionController_afterDiscussionTitle_handler($Sender)
{
$Discussion = $Sender->data('Discussion');
$AddonID = val('AddonID', $Discussion);
if (is_numeric($AddonID) && $AddonID > 0) {
$Data = Gdn::database()->sql()->select('Name')->from('Addon')->where('AddonID', $AddonID)->get()->firstRow();
if ($Data) {
echo renderDiscussionAddonWarning($AddonID, $Data->Name, val('DiscussionID', $Discussion));
}
}
}
示例4: __construct
/**
* Class constructor. Defines the related database table name.
*
* @param string $Name An optional parameter that allows you to explicitly define the name of
* the table that this model represents. You can also explicitly set this value with $this->Name.
*/
public function __construct($Name = '')
{
if ($Name == '') {
$Name = get_class($this);
}
$this->Database = Gdn::database();
$this->SQL = $this->Database->SQL();
$this->Validation = new Gdn_Validation();
$this->Name = $Name;
$this->PrimaryKey = $Name . 'ID';
parent::__construct();
}
示例5: __construct
/**
* The constructor for this class. Automatically fills $this->ClassName.
*
* @param string $Database
* @todo $Database needs a description.
*/
public function __construct($Database = null)
{
parent::__construct();
if (is_null($Database)) {
$this->Database = Gdn::database();
} else {
$this->Database = $Database;
}
$this->databasePrefix($this->Database->DatabasePrefix);
$this->setAlterTableThreshold(c('Database.AlterTableThreshold', 0));
$this->reset();
}
示例6: __construct
/**
* Class constructor. Defines the related database table name.
*
* @param string $Name An optional parameter that allows you to explicitly define the name of
* the table that this model represents. You can also explicitly set this value with $this->Name.
*/
public function __construct($Name = '')
{
if ($Name == '') {
$Name = get_class($this);
}
$this->Database = Gdn::database();
$this->SQL = $this->Database->SQL();
$this->Validation = new Gdn_Validation();
$this->Name = $Name;
$this->PrimaryKey = $Name . 'ID';
$this->filterFields = array('Attributes' => 0, 'DateInserted' => 0, 'InsertUserID' => 0, 'InsertIPAddress' => 0, 'CheckBoxes' => 0, 'DateUpdated' => 0, 'UpdateUserID' => 0, 'UpdateIPAddress' => 0, 'DeliveryMethod' => 0, 'DeliveryType' => 0, 'OK' => 0, 'TransientKey' => 0, 'hpt' => 0);
parent::__construct();
}
示例7: export
/**
* Export core Vanilla and Conversations tables.
*
* @since 2.0.0
* @access public
*/
public function export()
{
$this->permission('Garden.Export');
// This permission doesn't exist, so only users with Admin == '1' will succeed.
set_time_limit(60 * 2);
$Ex = new ExportModel();
$Ex->pdo(Gdn::database()->connection());
$Ex->Prefix = Gdn::database()->DatabasePrefix;
/// 2. Do the export. ///
$Ex->UseCompression = true;
$Ex->beginExport(PATH_ROOT . DS . 'uploads' . DS . 'export ' . date('Y-m-d His') . '.txt.gz', 'Vanilla 2.0');
$Ex->exportTable('User', 'select * from :_User');
// ":_" will be replace by database prefix
$Ex->exportTable('Role', 'select * from :_Role');
$Ex->exportTable('UserRole', 'select * from :_UserRole');
$Ex->exportTable('Category', 'select * from :_Category');
$Ex->exportTable('Discussion', 'select * from :_Discussion');
$Ex->exportTable('Comment', 'select * from :_Comment');
$Ex->exportTable('Conversation', 'select * from :_Conversation');
$Ex->exportTable('UserConversation', 'select * from :_UserConversation');
$Ex->exportTable('ConversationMessage', 'select * from :_ConversationMessage');
$Ex->endExport();
}
示例8: registerApproval
/**
* Registration that requires approval.
*
* Events: RegistrationPending
*
* @access private
* @since 2.0.0
*/
private function registerApproval()
{
Gdn::userModel()->addPasswordStrength($this);
// If the form has been posted back...
if ($this->Form->isPostBack()) {
// Add validation rules that are not enforced by the model
$this->UserModel->defineSchema();
$this->UserModel->Validation->applyRule('Name', 'Username', $this->UsernameError);
$this->UserModel->Validation->applyRule('TermsOfService', 'Required', t('You must agree to the terms of service.'));
$this->UserModel->Validation->applyRule('Password', 'Required');
$this->UserModel->Validation->applyRule('Password', 'Strength');
$this->UserModel->Validation->applyRule('Password', 'Match');
$this->UserModel->Validation->applyRule('DiscoveryText', 'Required', 'Tell us why you want to join!');
// $this->UserModel->Validation->applyRule('DateOfBirth', 'MinimumAge');
$this->fireEvent('RegisterValidation');
try {
$Values = $this->Form->formValues();
$Values = $this->UserModel->filterForm($Values, true);
unset($Values['Roles']);
$AuthUserID = $this->UserModel->register($Values);
$this->setData('UserID', $AuthUserID);
if (!$AuthUserID) {
$this->Form->setValidationResults($this->UserModel->validationResults());
} else {
// The user has been created successfully, so sign in now.
Gdn::session()->start($AuthUserID);
if ($this->Form->getFormValue('RememberMe')) {
Gdn::authenticator()->SetIdentity($AuthUserID, true);
}
// Notification text
$Label = t('NewApplicantEmail', 'New applicant:');
$Story = anchor(Gdn_Format::text($Label . ' ' . $Values['Name']), ExternalUrl('dashboard/user/applicants'));
$this->EventArguments['AuthUserID'] = $AuthUserID;
$this->EventArguments['Story'] =& $Story;
$this->fireEvent('RegistrationPending');
$this->View = "RegisterThanks";
// Tell the user their application will be reviewed by an administrator.
// Grab all of the users that need to be notified.
$Data = Gdn::database()->sql()->getWhere('UserMeta', array('Name' => 'Preferences.Email.Applicant'))->resultArray();
$ActivityModel = new ActivityModel();
foreach ($Data as $Row) {
$ActivityModel->add($AuthUserID, 'Applicant', $Story, $Row['UserID'], '', '/dashboard/user/applicants', 'Only');
}
}
} catch (Exception $Ex) {
$this->Form->addError($Ex);
}
$this->render();
} else {
$this->render();
}
}
示例9: configure
/**
* Allows the configuration of basic setup information in Garden. This
* should not be functional after the application has been set up.
*
* @since 2.0.0
* @access public
* @param string $RedirectUrl Where to send user afterward.
*/
private function configure($RedirectUrl = '')
{
// Create a model to save configuration settings
$Validation = new Gdn_Validation();
$ConfigurationModel = new Gdn_ConfigurationModel($Validation);
$ConfigurationModel->setField(array('Garden.Locale', 'Garden.Title', 'Garden.WebRoot', 'Garden.Cookie.Salt', 'Garden.Cookie.Domain', 'Database.Name', 'Database.Host', 'Database.User', 'Database.Password', 'Garden.Registration.ConfirmEmail', 'Garden.Email.SupportName'));
// Set the models on the forms.
$this->Form->setModel($ConfigurationModel);
// If seeing the form for the first time...
if (!$this->Form->isPostback()) {
// Force the webroot using our best guesstimates
$ConfigurationModel->Data['Database.Host'] = 'localhost';
$this->Form->setData($ConfigurationModel->Data);
} else {
// Define some validation rules for the fields being saved
$ConfigurationModel->Validation->applyRule('Database.Name', 'Required', 'You must specify the name of the database in which you want to set up Vanilla.');
// Let's make some user-friendly custom errors for database problems
$DatabaseHost = $this->Form->getFormValue('Database.Host', '~~Invalid~~');
$DatabaseName = $this->Form->getFormValue('Database.Name', '~~Invalid~~');
$DatabaseUser = $this->Form->getFormValue('Database.User', '~~Invalid~~');
$DatabasePassword = $this->Form->getFormValue('Database.Password', '~~Invalid~~');
$ConnectionString = GetConnectionString($DatabaseName, $DatabaseHost);
try {
$Connection = new PDO($ConnectionString, $DatabaseUser, $DatabasePassword);
} catch (PDOException $Exception) {
switch ($Exception->getCode()) {
case 1044:
$this->Form->addError(t('The database user you specified does not have permission to access the database. Have you created the database yet? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage()));
break;
case 1045:
$this->Form->addError(t('Failed to connect to the database with the username and password you entered. Did you mistype them? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage()));
break;
case 1049:
$this->Form->addError(t('It appears as though the database you specified does not exist yet. Have you created it yet? Did you mistype the name? The database reported: <code>%s</code>'), strip_tags($Exception->getMessage()));
break;
case 2005:
$this->Form->addError(t("Are you sure you've entered the correct database host name? Maybe you mistyped it? The database reported: <code>%s</code>"), strip_tags($Exception->getMessage()));
break;
default:
$this->Form->addError(sprintf(t('ValidateConnection'), strip_tags($Exception->getMessage())));
break;
}
}
$ConfigurationModel->Validation->applyRule('Garden.Title', 'Required');
$ConfigurationFormValues = $this->Form->formValues();
if ($ConfigurationModel->validate($ConfigurationFormValues) !== true || $this->Form->errorCount() > 0) {
// Apply the validation results to the form(s)
$this->Form->setValidationResults($ConfigurationModel->validationResults());
} else {
$Host = array_shift(explode(':', Gdn::request()->requestHost()));
$Domain = Gdn::request()->domain();
// Set up cookies now so that the user can be signed in.
$ExistingSalt = c('Garden.Cookie.Salt', false);
$ConfigurationFormValues['Garden.Cookie.Salt'] = $ExistingSalt ? $ExistingSalt : betterRandomString(16, 'Aa0');
$ConfigurationFormValues['Garden.Cookie.Domain'] = '';
// Don't set this to anything by default. # Tim - 2010-06-23
// Additional default setup values.
$ConfigurationFormValues['Garden.Registration.ConfirmEmail'] = true;
$ConfigurationFormValues['Garden.Email.SupportName'] = $ConfigurationFormValues['Garden.Title'];
$ConfigurationModel->save($ConfigurationFormValues, true);
// If changing locale, redefine locale sources:
$NewLocale = 'en-CA';
// $this->Form->getFormValue('Garden.Locale', false);
if ($NewLocale !== false && Gdn::config('Garden.Locale') != $NewLocale) {
$Locale = Gdn::locale();
$Locale->set($NewLocale);
}
// Install db structure & basic data.
$Database = Gdn::database();
$Database->init();
$Drop = false;
$Explicit = false;
try {
include PATH_APPLICATIONS . DS . 'dashboard' . DS . 'settings' . DS . 'structure.php';
} catch (Exception $ex) {
$this->Form->addError($ex);
}
if ($this->Form->errorCount() > 0) {
return false;
}
// Create the administrative user
$UserModel = Gdn::userModel();
$UserModel->defineSchema();
$UsernameError = t('UsernameError', 'Username can only contain letters, numbers, underscores, and must be between 3 and 20 characters long.');
$UserModel->Validation->applyRule('Name', 'Username', $UsernameError);
$UserModel->Validation->applyRule('Name', 'Required', t('You must specify an admin username.'));
$UserModel->Validation->applyRule('Password', 'Required', t('You must specify an admin password.'));
$UserModel->Validation->applyRule('Password', 'Match');
$UserModel->Validation->applyRule('Email', 'Email');
if (!($AdminUserID = $UserModel->SaveAdminUser($ConfigurationFormValues))) {
$this->Form->setValidationResults($UserModel->validationResults());
} else {
//.........这里部分代码省略.........
示例10: query
/**
* Run a query, replacing database prefixes.
*
* @param string $Sql The sql to execute.
* - :_z will be replaced by the import prefix.
* - :_ will be replaced by the database prefix.
* @param array $Parameters PDO parameters to pass to the query.
* @return Gdn_DataSet
*/
public function query($Sql, $Parameters = null)
{
$Db = Gdn::database();
// Replace db prefixes.
$Sql = str_replace(array(':_z', ':_'), array($Db->DatabasePrefix . self::TABLE_PREFIX, $Db->DatabasePrefix), $Sql);
// Figure out the type of the type of the query.
if (stringBeginsWith($Sql, 'select')) {
$Type = 'select';
} elseif (stringBeginsWith($Sql, 'truncate')) {
$Type = 'truncate';
} elseif (stringBeginsWith($Sql, 'insert')) {
$Type = 'insert';
} elseif (stringBeginsWith($Sql, 'update')) {
$Type = 'update';
} elseif (stringBeginsWith($Sql, 'delete')) {
$Type = 'delete';
} else {
$Type = 'select';
}
// Execute the query.
if (is_array($Parameters)) {
$this->SQL->namedParameters($Parameters);
}
$Result = $this->SQL->query($Sql, $Type);
//$this->Timer->Split('Sql: '. str_replace("\n", "\n ", $Sql));
return $Result;
}
示例11: DiscussionModel
<?php
if (!defined('APPLICATION')) {
exit;
}
/**
* Vanilla stub content for a new forum.
*
* Called by VanillaHooks::Setup() to insert stub content upon enabling app.
*
* @copyright 2009-2016 Vanilla Forums Inc.
* @license http://www.opensource.org/licenses/gpl-2.0.php GNU GPL v2
* @since 2.0
* @package Vanilla
*/
$SQL = Gdn::database()->sql();
// Only do this once, ever.
$Row = $SQL->get('Discussion', '', 'asc', 1)->firstRow(DATASET_TYPE_ARRAY);
if ($Row) {
return;
}
$DiscussionModel = new DiscussionModel();
// Prep default content
$DiscussionTitle = "BAM! You’ve got a sweet forum";
$DiscussionBody = "There’s nothing sweeter than a fresh new forum, ready to welcome your community. A Vanilla Forum has all the bits and pieces you need to build an awesome discussion platform customized to your needs. Here’s a few tips:\n<ul>\n <li>Use the <a href=\"/dashboard/settings/gettingstarted\">Getting Started</a> list in the Dashboard to configure your site.</li>\n <li>Don’t use too many categories. We recommend 3-8. Keep it simple!</li>\n <li>“Announce” a discussion (click the gear) to stick to the top of the list, and “Close” it to stop further comments.</li>\n <li>Use “Sink” to take attention away from a discussion. New comments will no longer bring it back to the top of the list.</li>\n <li>Bookmark a discussion (click the star) to get notifications for new comments. You can edit notification settings from your profile.</li>\n</ul>\nGo ahead and edit or delete this discussion, then spread the word to get this place cooking. Cheers!";
$CommentBody = "This is the first comment on your site and it’s an important one.\n\nDon’t see your must-have feature? We keep Vanilla nice and simple by default. Use <b>addons</b> to get the special sauce your community needs.\n\nNot sure which addons to enable? Our favorites are Button Bar and Tagging. They’re almost always a great start.";
$WallBody = "Ping! An activity post is a public way to talk at someone. When you update your status here, it posts it on your activity feed.";
// Prep content meta data
$SystemUserID = Gdn::userModel()->GetSystemUserID();
$TargetUserID = Gdn::session()->UserID;
$Now = Gdn_Format::toDateTime();
示例12: count
echo '<h3><strong>Backtrace:</strong></h3>
<div class="PreContainer">';
$BacktraceCount = count($Backtrace);
$Odd = FALSE;
for ($i = 0; $i < $BacktraceCount; ++$i) {
echo '<pre' . ($Odd === FALSE ? '' : ' class="Odd"') . '>';
if (array_key_exists('file', $Backtrace[$i])) {
$File = '[' . $Backtrace[$i]['file'] . ':' . $Backtrace[$i]['line'] . '] ';
}
echo $File, '<strong>', array_key_exists('class', $Backtrace[$i]) ? $Backtrace[$i]['class'] : 'PHP', array_key_exists('type', $Backtrace[$i]) ? $Backtrace[$i]['type'] : '::', $Backtrace[$i]['function'], '();</strong>', "</pre>\n";
$Odd = $Odd == TRUE ? FALSE : TRUE;
}
echo "</div>\n";
}
// Dump queries if present.
$Database = Gdn::database();
if (!is_null($Database) && method_exists($Database, 'Queries')) {
$Queries = $Database->Queries();
$QueryTimes = $Database->QueryTimes();
if (count($Queries) > 0) {
echo '<h3><strong>Queries:</strong></h3>
<div class="PreContainer">';
$Odd = FALSE;
foreach ($Queries as $Key => $QueryInfo) {
$Query = $QueryInfo['Sql'];
// this is a bit of a kludge. I found that the regex below would mess up when there were incremented named parameters. Ie. it would replace :Param before :Param0, which ended up with some values like "'4'0".
$tmp = (array) $QueryInfo['Parameters'];
arsort($tmp);
foreach ($tmp as $Name => $Parameter) {
$Pattern = '/(.+)(' . $Name . ')([\\W\\s]*)(.*)/';
$Replacement = "\$1'" . htmlentities($Parameter, ENT_COMPAT, 'UTF-8') . "'\$3\$4";
示例13: lookupNonce
/**
*
*
* @param $TokenKey
* @param null $Nonce
* @return bool
*/
public function lookupNonce($TokenKey, $Nonce = null)
{
$NonceData = Gdn::database()->sql()->select('uan.*')->from('UserAuthenticationNonce uan')->where('uan.Token', $TokenKey)->get()->firstRow(DATASET_TYPE_ARRAY);
if ($NonceData && (is_null($Nonce) || $NonceData['Nonce'] == $Nonce)) {
return $NonceData['Nonce'];
}
return false;
}
示例14: setup
/**
* Database & config changes to be done upon enable.
*
* @since 2.0.0
* @access public
*/
public function setup()
{
$Database = Gdn::database();
$Config = Gdn::factory(Gdn::AliasConfig);
$Drop = false;
//c('Conversations.Version') === FALSE ? TRUE : FALSE;
$Validation = new Gdn_Validation();
// This is going to be needed by structure.php to validate permission names
include PATH_APPLICATIONS . DS . 'conversations' . DS . 'settings' . DS . 'structure.php';
include PATH_APPLICATIONS . DS . 'conversations' . DS . 'settings' . DS . 'stub.php';
$ApplicationInfo = array();
include combinePaths(array(PATH_APPLICATIONS . DS . 'conversations' . DS . 'settings' . DS . 'about.php'));
$Version = val('Version', val('Conversations', $ApplicationInfo, array()), 'Undefined');
saveToConfig('Conversations.Version', $Version);
}
示例15: runStructure
/**
*
*
* @param null $AddonCode
* @param bool $Explicit
* @param bool $Drop
* @throws Exception
*/
public function runStructure($AddonCode = null, $Explicit = false, $Drop = false)
{
// Get the structure files for all of the enabled applications.
$ApplicationManager = new Gdn_ApplicationManager();
$Apps = $ApplicationManager->EnabledApplications();
$AppNames = consolidateArrayValuesByKey($Apps, 'Folder');
$Paths = array();
foreach ($Apps as $Key => $AppInfo) {
$Path = PATH_APPLICATIONS . "/{$AppInfo['Folder']}/settings/structure.php";
if (file_exists($Path)) {
$Paths[] = $Path;
}
Gdn::ApplicationManager()->RegisterPermissions($Key, $this->Validation);
}
// Execute the structures.
$Database = Gdn::database();
$SQL = Gdn::sql();
$Structure = Gdn::structure();
foreach ($Paths as $Path) {
include $Path;
}
// Execute the structures for all of the plugins.
$PluginManager = Gdn::pluginManager();
$Registered = $PluginManager->RegisteredPlugins();
foreach ($Registered as $ClassName => $Enabled) {
if (!$Enabled) {
continue;
}
try {
$Plugin = $PluginManager->GetPluginInstance($ClassName, Gdn_PluginManager::ACCESS_CLASSNAME);
if (method_exists($Plugin, 'Structure')) {
trace("{$ClassName}->Structure()");
$Plugin->Structure();
}
} catch (Exception $Ex) {
// Do nothing, plugin wouldn't load/structure.
if (Debug()) {
throw $Ex;
}
}
}
$this->fireEvent('AfterStructure');
}