/** * Connect to database server using data from config file. */ function database_connect() { global $db_type, $db, $db_config; $result = false; // create database object switch ($db_type) { case DatabaseType::MYSQL: $db = new Database_MySQL(); $connected = $db->connect($db_config); $selected = $db->select($db_config['name']); $result = $connected && $selected; // connection was successful but database doesn't exist if ($connected && (!$selected || $selected && !ModuleManager::getInstance()->tableExists())) { $result = database_initialize(!$selected); } break; case DatabaseType::PGSQL: break; case DatabaseType::SQLITE: $db = new Database_SQLite(); $result = $db->connect($db_config); // try to initialize database if (!$result && !$db->exists($db_config['name'])) { $result = $db->create($db_config['name']); if ($result) { $result = database_initialize(); } } break; } return $result; }
function DatabaseTest() { global $DB; try { $DB = new Database_MySQL(Request::Get('db_username'), Request::Get('db_password'), Request::Get('db_database'), Request::Get('db_hostname')); $version = $DB->Version(); if (!($version['major'] > 4 || $version['major'] == 4 && $version['minor'] > 0)) { throw new BaseException('This software requires MySQL Server version 4.1.0 or newer', 'Your MySQL Server is version ' . $version['full']); } } catch (Exception $e) { include_once 'install-main.php'; return false; } return true; }
public function connect() { if ($this->_connection) { return; } if (Database_MySQL::$_set_names === NULL) { // Determine if we can use mysql_set_charset(), which is only // available on PHP 5.2.3+ when compiled against MySQL 5.0+ Database_MySQL::$_set_names = !function_exists('mysql_set_charset'); } // Extract the connection parameters, adding required variabels extract($this->_config['connection'] + array('database' => '', 'hostname' => '', 'username' => '', 'password' => '', 'persistent' => FALSE)); // Prevent this information from showing up in traces unset($this->_config['connection']['username'], $this->_config['connection']['password']); try { if ($persistent) { // Create a persistent connection $this->_connection = @mysql_pconnect($hostname, $username, $password); } else { // Create a connection and force it to be a new link $this->_connection = @mysql_connect($hostname, $username, $password, TRUE); } } catch (ErrorException $e) { // No connection exists $this->_connection = NULL; throw new Database_Exception(mysql_errno(), '[:code] :error', array(':code' => mysql_errno(), ':error' => mysql_error())); } // \xFF is a better delimiter, but the PHP driver uses underscore $this->_connection_id = sha1($hostname . '_' . $username . '_' . $password); $this->_select_db($database); if (!empty($this->_config['charset'])) { // Set the character set $this->set_charset($this->_config['charset']); } }
public function connect() { if ($this->_connection) { return; } if (Database_MySQL::$_set_names === NULL) { Database_MySQL::$_set_names = !function_exists('mysql_set_charset'); } $cfg = $this->_config['connection'] + array('database' => '', 'hostname' => '', 'username' => '', 'password' => '', 'persistent' => FALSE); extract($cfg); unset($this->_config['connection']['username'], $this->_config['connection']['password']); try { if ($persistent) { $this->_connection = mysql_pconnect($hostname, $username, $password); } else { $this->_connection = mysql_connect($hostname, $username, $password, TRUE); } } catch (Exception $e) { $this->_connection = NULL; throw new Database_Exception(':error', array(':error' => $e->getMessage()), $e->getCode()); } $this->_connection_id = sha1($hostname . '_' . $username . '_' . $password); $this->_select_db($database); if (!empty($this->_config['charset'])) { $this->set_charset($this->_config['charset']); } if (!empty($this->_config['connection']['variables'])) { $variables = array(); foreach ($this->_config['connection']['variables'] as $var => $val) { $variables[] = 'SESSION ' . $var . ' = ' . $this->quote($val); } mysql_query('SET ' . implode(', ', $variables), $this->_connection); } }
public static function Login() { $DB = GetDB(); self::$authenticated = false; self::$superuser = false; self::$username = null; $cookie_settings = self::GetCookieSettings(); if (isset($_REQUEST[self::FIELD_USERNAME])) { if (String::IsEmpty($_REQUEST[self::FIELD_USERNAME])) { self::$error = 'The username field was left blank'; return; } if (String::IsEmpty($_REQUEST[self::FIELD_PASSWORD])) { self::$error = 'The password field was left blank'; return; } $account = $DB->Row('SELECT * FROM `tbx_administrator` WHERE `username`=? AND `password`=?', array($_REQUEST[self::FIELD_USERNAME], sha1($_REQUEST[self::FIELD_PASSWORD]))); if (!$account) { self::$error = 'The supplied username/password combination is not valid'; return; } else { $session = sha1(uniqid(rand(), true)); $DB->Update('INSERT INTO `tbx_administrator_session` VALUES (?,?,?,?,?)', array($account['username'], $session, sha1($_SERVER['HTTP_USER_AGENT']), $_SERVER['REMOTE_ADDR'], time())); $DB->Update('INSERT INTO `tbx_administrator_login_history` VALUES (?,?,?)', array($account['username'], Database_MySQL::Now(), $_SERVER['REMOTE_ADDR'])); setcookie(self::COOKIE_NAME, self::FIELD_USERNAME . '=' . urlencode($account['username']) . '&' . self::FIELD_SESSION . '=' . urlencode($session), $_REQUEST[self::FIELD_REMEMBER] ? time() + self::SESSION_LENGTH : null, $cookie_settings['path'], $cookie_settings['domain']); self::$username = $account['username']; self::$superuser = $account['type'] == self::TYPE_SUPERUSER; self::$privileges = $account['privileges']; self::$authenticated = true; } } else { if (isset($_COOKIE[self::COOKIE_NAME])) { $cookie = array(); parse_str($_COOKIE[self::COOKIE_NAME], $cookie); $DB->Update('DELETE FROM `tbx_administrator_session` WHERE `timestamp` < ?', array(time() - self::SESSION_LENGTH)); $session = $DB->Row('SELECT * FROM `tbx_administrator_session` WHERE `username`=? AND `session`=? AND `browser`=? AND `ip_address`=?', array($cookie[self::FIELD_USERNAME], $cookie[self::FIELD_SESSION], sha1($_SERVER['HTTP_USER_AGENT']), $_SERVER['REMOTE_ADDR'])); if (!$session) { setcookie(self::COOKIE_NAME, false, time() - self::SESSION_LENGTH, $cookie_settings['path'], $cookie_settings['domain']); self::$error = 'Your control panel session has expired'; return; } else { $account = $DB->Row('SELECT * FROM `tbx_administrator` WHERE `username`=?', array($session['username'])); if (!$account) { setcookie(self::COOKIE_NAME, false, time() - self::SESSION_LENGTH, $cookie_settings['path'], $cookie_settings['domain']); self::$error = 'Invalid control panel account'; return; } else { self::$username = $account['username']; self::$superuser = $account['type'] == self::TYPE_SUPERUSER; self::$privileges = $account['privileges']; self::$authenticated = true; } } } } return self::$authenticated; }
public function init() { $this->_boardurl = 'http://127.0.0.1'; $this->_db_server = 'localhost'; $this->_db_type = 'mysql'; $this->_db_name = 'hello_world_test'; $this->_db_user = '******'; $this->_db_passwd = ''; $this->_db_prefix = 'elkarte_'; $connection = Database_MySQL::initiate($this->_db_server, $this->_db_name, $this->_db_user, $this->_db_passwd, $this->_db_prefix); $this->_db = Database_MySQL::db(); $this->load_queries(BOARDDIR . '/install/install_1-0_mysql.sql'); $this->prepare(); }
public function connect() { if ($this->_connection) { return; } if (Database_MySQL::$_set_names === null) { // Determine if we can use mysql_set_charset(), which is only // available on PHP 5.2.3+ when compiled against MySQL 5.0+ Database_MySQL::$_set_names = !function_exists('mysql_set_charset'); } // Extract the connection parameters, adding required variabels /** * @var string $database * @var string $hostname * @var string $username * @var string $password * @var bool $persistent */ extract($this->_config['connection'] + ['database' => '', 'hostname' => '', 'username' => '', 'password' => '', 'persistent' => false]); // Prevent this information from showing up in traces unset($this->_config['connection']['username'], $this->_config['connection']['password']); try { if ($persistent) { // Create a persistent connection $this->_connection = mysql_pconnect($hostname, $username, $password); } else { // Create a connection and force it to be a new link $this->_connection = mysql_connect($hostname, $username, $password, true); } } catch (Exception $e) { // No connection exists $this->_connection = null; throw new Database_Exception(':error', [':error' => $e->getMessage()], $e->getCode()); } // \xFF is a better delimiter, but the PHP driver uses underscore $this->_connection_id = sha1($hostname . '_' . $username . '_' . $password); $this->_select_db($database); if (!empty($this->_config['charset'])) { // Set the character set $this->set_charset($this->_config['charset']); } if (!empty($this->_config['connection']['variables'])) { // Set session variables $variables = []; foreach ($this->_config['connection']['variables'] as $var => $val) { $variables[] = 'SESSION ' . $var . ' = ' . $this->quote($val); } mysql_query('SET ' . implode(', ', $variables), $this->_connection); } }
/** * Initializes a database connection. * It returns the connection, if successful. * * @param string $db_server * @param string $db_name * @param string $db_user * @param string $db_passwd * @param string $db_prefix * @param mixed[] $db_options * * @return resource */ public static function initiate($db_server, $db_name, $db_user, $db_passwd, $db_prefix, $db_options = array()) { global $mysql_set_mode; // Initialize the instance... if not done already! if (self::$_db === null) { self::$_db = new self(); } // Non-standard port if (!empty($db_options['port'])) { $db_port = (int) $db_options['port']; } else { $db_port = 0; } // Select the database. Maybe. if (empty($db_options['dont_select_db'])) { $connection = @mysqli_connect((!empty($db_options['persist']) ? 'p:' : '') . $db_server, $db_user, $db_passwd, $db_name, $db_port); } else { $connection = @mysqli_connect((!empty($db_options['persist']) ? 'p:' : '') . $db_server, $db_user, $db_passwd, '', $db_port); } // Something's wrong, show an error if its fatal (which we assume it is) if (!$connection) { if (!empty($db_options['non_fatal'])) { return null; } else { display_db_error(); } } // This makes it possible to automatically change the sql_mode and autocommit if needed. if (isset($mysql_set_mode) && $mysql_set_mode === true) { self::$_db->query('', 'SET sql_mode = \'\', AUTOCOMMIT = 1', array(), false); } self::$_db->_connection = $connection; // Few databases still have not set UTF-8 as their default input charset self::$_db->query('', ' SET NAMES UTF8', array()); return $connection; }
public function connect() { if ($this->_connection) { return; } if (Database_MySQL::$_set_names === NULL) { // Determine if we can use mysql_set_charset(), which is only // available on PHP 5.2.3+ when compiled against MySQL 5.0+ Database_MySQL::$_set_names = !function_exists('mysql_set_charset'); } // Extract the connection parameters, adding required variabels extract($this->_config['connection'] + array('database' => '', 'hostname' => '', 'port' => NULL, 'socket' => NULL, 'username' => '', 'password' => '', 'persistent' => FALSE)); // Clear the connection parameters for security unset($this->_config['connection']); try { if (empty($persistent)) { // Create a connection and force it to be a new link $this->_connection = mysql_connect($hostname, $username, $password, true); } else { // Create a persistent connection $this->_connection = mysql_pconnect($hostname, $username, $password); } } catch (ErrorException $e) { // No connection exists $this->_connection = NULL; // Unable to connect to the database throw new Database_Exception(':error', array(':error' => mysql_error()), mysql_errno()); } if (!mysql_select_db($database, $this->_connection)) { // Unable to select database throw new Database_Exception(':error', array(':error' => mysql_error($this->_connection)), mysql_errno($this->_connection)); } if (!empty($this->_config['charset'])) { // Set the character set $this->set_charset($this->_config['charset']); } }
public function Import() { $imported = 0; $DB = GetDB(); $yt = new Zend_Gdata_YouTube(); $video_feed = $yt->getVideoFeed($this->feed['feed_url']); $entry; foreach ($video_feed as $entry) { // Check for duplicates, and skip if ($DB->QueryCount('SELECT COUNT(*) FROM `tbx_video_feed_history` WHERE `feed_id`=? AND `unique_id`=?', array($this->feed['feed_id'], $entry->getVideoId()))) { continue; } // Video is not embeddable, skip if (!$entry->isVideoEmbeddable()) { continue; } // Setup defaults $video = $this->defaults; $video['title'] = $entry->getVideoTitle(); $video['description'] = $entry->getVideoDescription(); $video['tags'] = Tags::Format(implode(' ', $entry->getVideoTags())); $video['duration'] = $entry->getVideoDuration(); // Get preview images $times = array(); $thumbs = array(); foreach ($entry->getVideoThumbnails() as $thumb) { if (!isset($times[$thumb['time']])) { $times[$thumb['time']] = true; $thumbs[] = array('thumbnail' => $thumb['url']); } } $clip = array('type' => 'Embed', 'clip' => '<object width="640" height="385">' . '<param name="movie" value="http://www.youtube.com/v/' . $entry->getVideoId() . '&fs=1"></param>' . '<param name="allowFullScreen" value="true"></param>' . '<param name="allowscriptaccess" value="always"></param>' . '<embed src="http://www.youtube.com/v/' . $entry->getVideoId() . '&fs=1" type="application/x-shockwave-flash" allowfullscreen="true" width="640" height="385"></embed>' . '</object>'); $best_category = GetBestCategory(join(' ', array($video['title'], $video['description'], $video['tags']))); if (!empty($best_category)) { $video['category_id'] = $best_category; } $video['video_id'] = DatabaseAdd('tbx_video', $video); DatabaseAdd('tbx_video_custom', $video); DatabaseAdd('tbx_video_stat', $video); if (!$video['is_private']) { Tags::AddToFrequency($video['tags']); } UpdateCategoryStats($video['category_id']); $video_dir = new Video_Dir(Video_Dir::DirNameFromId($video['video_id'])); $clip['video_id'] = $video['video_id']; DatabaseAdd('tbx_video_clip', $clip); $display_thumbnail = null; foreach ($thumbs as $thumb) { $thttp = new HTTP(); if ($thttp->Get($thumb['thumbnail'], $thumb['thumbnail'])) { $temp_file = $video_dir->AddTempFromVar($thttp->body, JPG_EXTENSION); $imgsize = @getimagesize($temp_file); if ($imgsize !== false) { if (Video_Thumbnail::CanResize()) { $local_filename = Video_Thumbnail::Resize($temp_file, Config::Get('thumb_size'), Config::Get('thumb_quality'), $video_dir->GetThumbsDir()); } else { $local_filename = $video_dir->AddThumbFromFile($temp_file, JPG_EXTENSION); } $local_filename = str_replace(Config::Get('document_root'), '', $local_filename); $thumb_id = DatabaseAdd('tbx_video_thumbnail', array('video_id' => $video['video_id'], 'thumbnail' => $local_filename)); if (empty($display_thumbnail)) { $display_thumbnail = $thumb_id; } } else { unlink($temp_file); } } } if (!empty($display_thumbnail)) { $DB->Update('UPDATE `tbx_video` SET `display_thumbnail`=? WHERE `video_id`=?', array($display_thumbnail, $video['video_id'])); } $DB->Update('INSERT INTO `tbx_video_feed_history` VALUES (?,?)', array($this->feed['feed_id'], $entry->getVideoId())); $imported++; } $DB->Update('UPDATE `tbx_video_feed` SET `date_last_read`=? WHERE `feed_id`=?', array(Database_MySQL::Now(), $this->feed['feed_id'])); UpdateSponsorStats($this->feed['sponsor_id']); return $imported; }
public static function Run() { chdir(realpath(dirname(__FILE__) . '/../')); require_once 'includes/global.php'; $doc_root = Config::Get('document_root'); $DB = GetDB(); self::Log('Starting...'); self::MarkRunning(); while (true) { // See if we were requested to stop if (self::ShouldStop()) { self::Log('User requested stop...'); break; } self::Ping(); $DB->Connect(); $queue_item = $DB->Row('SELECT *,`tbx_conversion_queue`.`video_id` AS `video_id`,`tbx_conversion_queue`.`queued` AS `queued` FROM `tbx_conversion_queue` LEFT JOIN ' . '`tbx_thumb_queue` USING (`video_id`) WHERE `tbx_thumb_queue`.`video_id` IS NULL ORDER BY `tbx_conversion_queue`.`queued` LIMIT 1'); if (!empty($queue_item)) { $video = $DB->Row('SELECT * FROM `tbx_video` WHERE `video_id`=?', array($queue_item['video_id'])); if (!empty($video)) { $DB->Update('UPDATE `tbx_video` SET `conversion_failed`=0 WHERE `video_id`=?', array($video['video_id'])); $DB->Update('UPDATE `tbx_conversion_queue` SET `date_started`=? WHERE `video_id`=?', array(Database_MySQL::Now(), $video['video_id'])); $clips = $DB->FetchAll('SELECT * FROM `tbx_video_clip` WHERE `video_id`=? ORDER BY `clip_id`', array($queue_item['video_id'])); $dir = new Video_Dir(Video_Dir::DirNameFromId($video['video_id'])); Video_Converter::SetLogFile($dir->GetBaseDir() . '/convert.log'); $convert_start = time(); $conversion_failed = false; foreach ($clips as $clip) { $clip_path = null; $old_path = null; try { // Stored locally, move to originals directory if ($clip['clip'][0] == '/') { $old_path = $doc_root . $clip['clip']; $clip_path = $dir->AddOriginalFromFile($old_path); } else { $http = new HTTP(); if ($http->Get($clip['clip'], $clip['clip'])) { $clip_path = $dir->AddOriginalFromVar($http->body, File::Extension($clip['clip'])); } else { throw new BaseException('Could not download clip for conversion: ' . $http->error); } } $output_file = Video_Converter::Convert($clip_path, $dir->GetProcessingDir(), Config::Get('video_format'), Config::Get('video_bitrate'), Config::Get('audio_bitrate'), Config::Get('video_size'), array('ConversionQueue', 'Ping')); $converted_video = $dir->AddClipFromFile($output_file); $DB->Disconnect(); $DB->Connect(); $DB->Update('UPDATE `tbx_video_clip` SET `clip`=?,`filesize`=? WHERE `clip_id`=?', array(str_replace($doc_root, '', $converted_video), filesize($converted_video), $clip['clip_id'])); } catch (Exception $e) { if (!empty($old_path) && !empty($clip_path)) { rename($clip_path, $old_path); } Video_Converter::Log($e->getMessage() . (strtolower(get_class($e)) == 'baseexception' ? $e->getExtras() : '') . "\n" . $e->getTraceAsString()); $conversion_failed = true; } } $convert_end = time(); $dir->ClearProcessing(); $dir->ClearTemp(); $DB->Connect(); $DB->Update('DELETE FROM `tbx_conversion_queue` WHERE `video_id`=?', array($queue_item['video_id'])); if ($conversion_failed) { self::UpdateStatsProcessed($convert_start, $convert_end, $queue_item['queued'], true); $DB->Update('UPDATE `tbx_video` SET `conversion_failed`=1 WHERE `video_id`=?', array($video['video_id'])); } else { // Update stats self::UpdateStatsProcessed($convert_start, $convert_end, $queue_item['queued']); $status = empty($video['next_status']) ? STATUS_ACTIVE : $video['next_status']; // Set video status $DB->Update('UPDATE `tbx_video` SET `status`=? WHERE `video_id`=?', array($status, $video['video_id'])); if ($video['status'] != $status && $status == STATUS_ACTIVE && !$video['is_private']) { Tags::AddToFrequency($video['tags']); } UpdateCategoryStats($video['category_id']); } } } else { break; } } self::MarkStopped(); self::Log('Exiting...'); }
$db2->runSQL($sqlTime); while ($row2 = $db2->retrieveRow()) { $scheduleBlock = $row2['schedule_block']; // echo $scheduleBlock . " | "; // create an entry in cim_sch_timeblocks for all the timeblock $sqlBlock = "INSERT INTO cim_sch_scheduleblocks (schedule_id, scheduleBlocks_timeblock) VALUES ( " . $scheduleID . "," . $scheduleBlock . " )"; $db1->runSQL($sqlBlock); } echo "Inserted schedule block for personID[" . $personID . "]<br/>"; } // while // echo "<pre>".print_r($_POST, true)."</pre>"; if (isset($_POST['Process'])) { echo '<p>Your name will be entered in the draw.</p>'; echo 'Name: <b>' . $_POST['name'] . '</b><br/>'; echo 'Email: <b>' . $_POST['email'] . '</b><br/>'; $db = new Database_MySQL(); $db->connectToDB(SPT_DB_NAME, SPT_DB_HOST, SPT_DB_USER, SPT_DB_PWD); $sql = 'INSERT INTO 08_staff_survey (survey_name, survey_email) VALUES ("' . $_POST['name'] . '", "' . $_POST['email'] . '")'; $db->runSQL($sql); } else { echo "<p>Thanks for filling out the C4C Staff Survey. Please enter your name and email to enter the draw for 25,000 Aeroplan miles. Your name and email are in no way connected to your survey response.</p>"; echo '<form name="draw" method="post">'; echo 'Name: <input name="name" type="text" /><br/>'; echo 'Email: <input name="email" type="text" /><br/>'; echo '<br/>'; echo '<input type="submit"/ value="Submit">'; echo '<input name="Process" type="hidden" id="Process" value="T" />'; echo '</form>'; } echo "<p>If you experience technical difficulties, please contact russ.martin@c4c.ca.</p>";
// Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. require_once 'includes/global.php'; Request::Setup(); if (AuthenticateUser::Login()) { $username = AuthenticateUser::GetUsername(); $video_id = $_REQUEST['video_id']; $add = $_REQUEST['add']; $DB = GetDB(); if ($add) { if ($DB->QueryCount('SELECT COUNT(*) FROM `tbx_user_favorite` WHERE `username`=? AND `video_id`=?', array($username, $video_id)) == 0) { $DB->Update('INSERT INTO `tbx_user_favorite` VALUES (?,?)', array($username, $video_id)); if ($DB->QueryCount('SELECT COUNT(*) FROM `tbx_video_favorited` WHERE `video_id`=? AND `username`=?', array($video_id, $username)) == 0) { StatsRollover(); $DB->Update('INSERT INTO `tbx_video_favorited` VALUES (?,?,?)', array($video_id, $username, Database_MySQL::Now())); $DB->Update('UPDATE `tbx_video_stat` SET ' . '`today_num_favorited`=`today_num_favorited`+1,' . '`week_num_favorited`=`week_num_favorited`+1,' . '`month_num_favorited`=`month_num_favorited`+1,' . '`total_num_favorited`=`total_num_favorited`+1 ' . 'WHERE `video_id`=?', array($video_id)); } echo _T('Text:Favorite added'); } else { echo _T('Text:Favorite exists'); } } else { $DB->Update('DELETE FROM `tbx_user_favorite` WHERE `username`=? AND `video_id`=?', array($username, $video_id)); echo _T('Text:Favorite removed'); } } else { echo _T('Validation:Must be logged in'); }
function tbxVideoFeature($video) { if (!$video['is_featured']) { $DB = GetDB(); $DB->Update('UPDATE `tbx_video` SET `is_featured`=1,`date_last_featured`=? WHERE `video_id`=?', array(Database_MySQL::Now(), $video['video_id'])); return true; } return false; }
function PrintData($Indx, $Condition) { // Get Data from DB $SQL = 'SELECT ' . $this->FieldList . ' FROM ' . $this->TableList . ' WHERE ' . $Condition; if (isset($this->OrderByList) == true) { $SQL .= ' ORDER BY ' . $this->OrderByList; } else { $SQL .= ' ORDER BY ' . $this->FieldList; } $DataDB = new Database_MySQL(); $DataDB->ConnectToDB($this->DatabaseName, DB_PATH, DB_USER, DB_PWORD); $DataDB->RunSQL($SQL); // if this is an HTML report ... if ($this->isExcelSheet == false) { // Set Color to RowColorOn... $BGColor = $this->RowColorOn; } else { // Set Format to EXCEL_FORMAT_TEXT_COLOR_ON $BGColor = EXCEL_FORMAT_TEXT_COLOR_ON; } // Add Leading Spacers for ($SpacerIndx = 0; $SpacerIndx < $Indx; $SpacerIndx++) { $this->AddSpacer(); } // For each Field in List for ($FieldIndx = 0; $FieldIndx < count($this->aFields); $FieldIndx++) { // Add Heading for Field $Heading = $this->ReturnFieldHeading($this->aFields[$FieldIndx]); $this->WriteHeading($Heading, $BGColor); // if this is an HTML report ... /* if ( $this->isExcelSheet == false ) { // Add Header to output table... $this->OutputTable->AddTableCell( '<strong>'.$Heading.'</strong>', $BGColor.' class="modify" valign="bottom" '); } else { // Add Header to Excel Workbook $this->ExcelWorkBook->AddCell( $Heading, EXCEL_FORMAT_HEADING ); } */ } // Next Field // For each value returned while ($this->Row = $DataDB->RetrieveRow()) { $BGColor = $this->ToggleColor($BGColor); // Add Leading Spacers for ($SpacerIndx = 0; $SpacerIndx < $Indx; $SpacerIndx++) { $this->AddSpacer(); } // For each Field in List for ($FieldIndx = 0; $FieldIndx < count($this->aFields); $FieldIndx++) { // Output Value $TempValue = $this->ReturnFieldValue($this->aFields[$FieldIndx]); // if this is an HTML report ... if ($this->isExcelSheet == false) { // Add Data to output table... $this->OutputTable->AddTableCell($TempValue, $BGColor . ' class="modify" valign="top" '); } else { // Add Data to Excel Workbook $this->ExcelWorkBook->AddCell($TempValue, $BGColor); } } // Next Field } // next // if this is an HTML report ... if ($this->isExcelSheet == false) { for ($SpacerIndx = 0; $SpacerIndx < $Indx; $SpacerIndx++) { $this->AddSpacer(); } // Add a Row of Spacers ... $this->OutputTable->AddTableCell('<hr width="100%" size="1" noshade color="#223450">', $this->SpacerCell, DISPLAYOBJECT_TYPE_HTML, $this->NumColumns - $SpacerIndx); } else { // Add 2 Rows of Spaces for ($SpacerIndx = 0; $SpacerIndx < $this->NumColumns * 2; $SpacerIndx++) { $this->AddSpacer(); } // // Add Data to Excel Workbook // $this->ExcelWorkBook->AddCell( '-----------------------', '' ,$this->NumColumns - $SpacerIndx ); } }
<?php require_once '../../../php5/objects/SiteObject.php'; require_once '../../../php5/objects/Database.php'; $db = new Database_MySQL(); $db->connectToDB('ciministry_development', 'localhost', 'spt', 'cIm777'); $WEEK = 3; // = freq_id $commaList = ''; $firstDate = '2007-12-30'; $date = $firstDate; $weekDesc = 'Week 1 of 2008'; $j = 2; for ($i = 0; $i < 200; $i++) { // $sql = 'insert into p2c_stats_freqvalue set freqvalue_value ="'.$date.'" and freq_id ='.$WEEK.' and freqvalue_desc="'.$weekDesc.'";'; $sql = 'insert into p2c_stats_freqvalue values ("", ' . $WEEK . ',"' . $date . '","' . $weekDesc . '");'; $time = strtotime($date); $new_time = mktime(0, 0, 0, date('m', $time), date('d', $time) + 7, date('Y', $time)); $date = date("Y-m-d", $new_time); if ($j == 53) { $j = 1; $new_year = mktime(0, 0, 0, date('m', $time), date('d', $time), date('Y', $time) + 1); $weekDesc = 'Week ' . $j . ' of ' . date('Y', $new_year); } else { $weekDesc = 'Week ' . $j . ' of ' . date('Y', $new_time); } echo $sql . '<br/>'; $db->runSQL($sql); $j++; }
function tbxUploadStepTwo() { global $t; $upload = $_FILES['video_file']; $v = Validator::Create(); $DB = GetDB(); $v->Register(sha1($_REQUEST['step_one_data'] . Config::Get('random_value')) == $_REQUEST['step_one_sig'], Validator_Type::IS_TRUE, _T('Validation:Video Data Altered')); $v->Register($upload['error'] == UPLOAD_ERR_OK, Validator_Type::IS_TRUE, Uploads::CodeToMessage($upload['error'])); if (is_uploaded_file($upload['tmp_name'])) { $max_filesize = Format::StringToBytes(Config::Get('max_upload_size')); $max_duration = Format::DurationToSeconds(Config::Get('max_upload_duration')); $extensions = str_replace(',', '|', Config::Get('upload_extensions')); $v->Register($upload['size'], Validator_Type::IS_BETWEEN, _T('Validation:Video size too large'), '1,' . $max_filesize); $v->Register(File::Extension($upload['name']), Validator_Type::REGEX_MATCH, _T('Validation:Video file extension not allowed'), '~^(' . $extensions . ')$~'); try { $vi = new Video_Info($upload['tmp_name']); $vi->Extract(); $v->Register($vi->length, Validator_Type::LESS_EQ, _T('Validation:Video duration too long'), $max_duration); } catch (Exception $e) { $v->Register(false, Validator_Type::IS_TRUE, $e->getMessage()); } $md5 = md5_file($upload['tmp_name']); if (Config::Get('flag_upload_reject_duplicates')) { $v->Register($DB->QueryCount('SELECT COUNT(*) FROM `tbx_video_md5sum` WHERE `md5`=?', array($md5)), Validator_Type::IS_ZERO, _T('Validation:Duplicate video')); } } // Validate input if (!$v->Validate()) { $t->Assign('g_errors', $v->GetErrors()); $t->AssignByRef('g_form', $_REQUEST); if (isset($_REQUEST['flash'])) { $t->Display('upload-flash-errors.tpl'); } else { $t->Assign('g_file_types', '*.' . str_replace(',', ';*.', Config::Get('upload_extensions'))); $t->Assign('g_cookie', $_COOKIE[LOGIN_COOKIE]); $t->Display('upload-step-two.tpl'); } return; } $_REQUEST = array_merge($_REQUEST, unserialize(base64_decode($_REQUEST['step_one_data']))); Form_Prepare::Standard('tbx_video'); Form_Prepare::Standard('tbx_video_stat'); Form_Prepare::Custom('tbx_video_custom_schema', 'on_submit'); $_REQUEST['duration'] = $vi->length; $_REQUEST['date_added'] = Database_MySQL::Now(); $_REQUEST['username'] = AuthenticateUser::GetUsername(); $_REQUEST['is_private'] = Config::Get('flag_upload_allow_private') ? intval($_REQUEST['is_private']) : 0; $_REQUEST['allow_ratings'] = intval($_REQUEST['allow_ratings']); $_REQUEST['allow_embedding'] = intval($_REQUEST['allow_embedding']); $_REQUEST['allow_comments'] = intval($_REQUEST['allow_comments']) ? 'Yes - Add Immediately' : 'No'; $_REQUEST['is_user_submitted'] = 1; if ($_REQUEST['recorded_day'] && $_REQUEST['recorded_month'] && $_REQUEST['recorded_year']) { $_REQUEST['date_recorded'] = $_REQUEST['recorded_year'] . '-' . $_REQUEST['recorded_month'] . '-' . $_REQUEST['recorded_day']; } // Strip HTML tags if (Config::Get('flag_video_strip_tags')) { $_REQUEST = String::StripTags($_REQUEST); } // Configure status $_REQUEST['status'] = STATUS_ACTIVE; if (Config::Get('flag_upload_convert')) { $_REQUEST['status'] = STATUS_QUEUED; $_REQUEST['next_status'] = Config::Get('flag_upload_review') ? STATUS_PENDING : STATUS_ACTIVE; } else { if (Config::Get('flag_upload_review')) { $_REQUEST['status'] = STATUS_PENDING; } } // Add to database $_REQUEST['video_id'] = DatabaseAdd('tbx_video', $_REQUEST); DatabaseAdd('tbx_video_custom', $_REQUEST); DatabaseAdd('tbx_video_stat', $_REQUEST); if ($_REQUEST['status'] == STATUS_ACTIVE && !$_REQUEST['is_private']) { Tags::AddToFrequency($_REQUEST['tags']); } else { if ($_REQUEST['status'] == STATUS_QUEUED) { DatabaseAdd('tbx_conversion_queue', array('video_id' => $_REQUEST['video_id'], 'queued' => time())); } } // Mark as private if ($_REQUEST['is_private']) { $_REQUEST['private_id'] = sha1(uniqid(rand(), true)); DatabaseAdd('tbx_video_private', $_REQUEST); } // Setup video files and generate thumbnails $directory = Video_Dir::DirNameFromId($_REQUEST['video_id']); $vd = new Video_Dir($directory); $clip = $vd->AddClipFromFile($upload['tmp_name'], File::Extension($upload['name'])); if (Video_FrameGrabber::CanGrab()) { Video_FrameGrabber::Grab($clip, $vd->GetThumbsDir(), Config::Get('thumb_amount'), Config::Get('thumb_quality'), Config::Get('thumb_size'), $vi); } foreach ($vd->GetClipURIs() as $clip) { $_REQUEST['clip'] = $clip; $_REQUEST['filesize'] = filesize(Config::Get('document_root') . $clip); DatabaseAdd('tbx_video_clip', $_REQUEST); } $thumb_ids = array(); foreach ($vd->GetThumbURIs() as $thumb) { $_REQUEST['thumbnail'] = $thumb; $thumb_ids[] = DatabaseAdd('tbx_video_thumbnail', $_REQUEST); } // Select the display thumbnail $num_thumbnails = count($thumb_ids); $display_thumbnail = null; if ($num_thumbnails > 0) { $display_thumbnail = $thumb_ids[rand(0, floor(0.4 * $num_thumbnails))]; } DatabaseUpdate('tbx_video', array('video_id' => $_REQUEST['video_id'], 'num_thumbnails' => $num_thumbnails, 'display_thumbnail' => $display_thumbnail)); // Add MD5 sum for prevention of duplicates $DB->Update('REPLACE INTO `tbx_video_md5sum` VALUES (?)', array($md5)); // Update user stats StatsRollover(); $DB->Update('UPDATE `tbx_user_stat` SET ' . '`today_videos_uploaded`=`today_videos_uploaded`+1,' . '`week_videos_uploaded`=`week_videos_uploaded`+1,' . '`month_videos_uploaded`=`month_videos_uploaded`+1,' . '`total_videos_uploaded`=`total_videos_uploaded`+1 ' . 'WHERE `username`=?', array($_REQUEST['username'])); $t->AssignByRef('g_form', $_REQUEST); $t->AssignByRef('g_video', $_REQUEST); $t->Display(isset($_REQUEST['flash']) ? 'upload-flash-complete.tpl' : 'upload-complete.tpl'); UpdateCategoryStats($_REQUEST['category_id']); if (!Config::Get('flag_using_cron') && $_REQUEST['status'] == STATUS_QUEUED) { ConversionQueue::Start(); } }
public static function Login($fail_function = null) { $DB = GetDB(); self::$authenticated = false; self::$username = null; try { if (isset($_REQUEST[self::FIELD_USERNAME])) { if (String::IsEmpty($_REQUEST[self::FIELD_USERNAME])) { throw new Exception(_T('Validation:Required', _T('Label:Username'))); } if (String::IsEmpty($_REQUEST[self::FIELD_PASSWORD])) { throw new Exception(_T('Validation:Required', _T('Label:Password'))); } $user = $DB->Row('SELECT * FROM `tbx_user` WHERE `username`=? AND `password`=?', array($_REQUEST[self::FIELD_USERNAME], sha1($_REQUEST[self::FIELD_PASSWORD]))); if (!$user) { throw new Exception(_T('Validation:Invalid Login')); } else { if ($user['status'] != STATUS_ACTIVE) { throw new Exception(_T('Validation:Inactive Account')); } $session = sha1(uniqid(rand(), true)); $DB->Update('UPDATE `tbx_user_stat` SET `date_last_login`=? WHERE `username`=?', array(Database_MySQL::Now(), $user['username'])); $DB->Update('INSERT INTO `tbx_user_session` VALUES (?,?,?,?,?)', array($user['username'], $session, sha1($_SERVER['HTTP_USER_AGENT']), $_SERVER['REMOTE_ADDR'], time())); setcookie(LOGIN_COOKIE, self::FIELD_USERNAME . '=' . urlencode($user['username']) . '&' . self::FIELD_SESSION . '=' . urlencode($session), $_REQUEST[self::FIELD_REMEMBER] ? time() + self::REMEMBER_PERIOD : null, Config::Get('cookie_path'), Config::Get('cookie_domain')); self::$username = $user['username']; self::$authenticated = true; } } else { if (isset($_COOKIE[LOGIN_COOKIE])) { $cookie = array(); parse_str(html_entity_decode($_COOKIE[LOGIN_COOKIE]), $cookie); $DB->Update('DELETE FROM `tbx_user_session` WHERE `timestamp` < ?', array(time() - self::REMEMBER_PERIOD)); $session = $DB->Row('SELECT * FROM `tbx_user_session` WHERE `username`=? AND `session`=?', array($cookie[self::FIELD_USERNAME], $cookie[self::FIELD_SESSION])); if (!$session) { setcookie(LOGIN_COOKIE, false, time() - 604800, Config::Get('cookie_path'), Config::Get('cookie_domain')); throw new Exception(_T('Validation:Session Expired')); } else { $user = $DB->Row('SELECT * FROM `tbx_user` WHERE `username`=?', array($session['username'])); if (!$user) { setcookie(LOGIN_COOKIE, false, time() - 604800, Config::Get('cookie_path'), Config::Get('cookie_domain')); throw new Exception(_T('Validation:Invalid Account')); } else { if ($user['status'] != STATUS_ACTIVE) { throw new Exception(_T('Validation:Inactive Account')); } self::$username = $user['username']; self::$authenticated = true; } } } } } catch (Exception $e) { self::$error = $e->getMessage(); self::$authenticated = false; } if (!self::$authenticated && function_exists($fail_function)) { call_user_func($fail_function); exit; } return self::$authenticated; }
// Copyright 2011 JMB Software, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. require_once 'includes/global.php'; Request::Setup(); if (AuthenticateUser::Login()) { $username = AuthenticateUser::GetUsername(); $video_id = $_REQUEST['video_id']; $reason_id = $_REQUEST['reason_id']; $DB = GetDB(); if ($DB->QueryCount('SELECT COUNT(*) FROM `tbx_video_featured` WHERE `username`=? AND `video_id`=?', array($username, $video_id)) == 0) { StatsRollover(); $DB->Update('INSERT INTO `tbx_video_featured` VALUES (?,?,?,?)', array($video_id, $username, $reason_id, Database_MySQL::Now())); $DB->Update('UPDATE `tbx_video_stat` SET ' . '`today_num_featured`=`today_num_featured`+1,' . '`week_num_featured`=`week_num_featured`+1,' . '`month_num_featured`=`month_num_featured`+1,' . '`total_num_featured`=`total_num_featured`+1 ' . 'WHERE `video_id`=?', array($video_id)); echo _T('Text:Feature request recorded'); } else { echo _T('Validation:You have already featured this video'); } } else { echo _T('Validation:Must be logged in'); }
// limitations under the License. require_once 'includes/global.php'; Request::Setup(); $flag_guest_ratings = Config::Get('flag_guest_ratings'); if (AuthenticateUser::Login() || $flag_guest_ratings) { $username = AuthenticateUser::GetUsername(); if ($flag_guest_ratings && empty($username)) { $username = $_SERVER['REMOTE_ADDR']; } $rating = $_REQUEST['rating']; $video_id = $_REQUEST['video_id']; if ($rating >= 1 && $rating <= 5) { $DB = GetDB(); if ($DB->QuerySingleColumn('SELECT `allow_ratings` FROM `tbx_video` WHERE `video_id`=?', array($video_id)) == 1) { if ($DB->QueryCount('SELECT COUNT(*) FROM `tbx_video_rating` WHERE `username`=? AND `video_id`=?', array($username, $video_id)) == 0) { StatsRollover(); $DB->Update('INSERT INTO `tbx_video_rating` VALUES (?,?,?,?)', array($username, $video_id, $rating, Database_MySQL::Now())); $DB->Update('UPDATE `tbx_video_stat` SET ' . '`today_num_ratings`=`today_num_ratings`+1,' . '`today_sum_of_ratings`=`today_sum_of_ratings`+?,' . '`today_avg_rating`=`today_sum_of_ratings`/`today_num_ratings`,' . '`week_num_ratings`=`week_num_ratings`+1,' . '`week_sum_of_ratings`=`week_sum_of_ratings`+?,' . '`week_avg_rating`=`week_sum_of_ratings`/`week_num_ratings`,' . '`month_num_ratings`=`month_num_ratings`+1,' . '`month_sum_of_ratings`=`month_sum_of_ratings`+?,' . '`month_avg_rating`=`month_sum_of_ratings`/`month_num_ratings`,' . '`total_num_ratings`=`total_num_ratings`+1,' . '`total_sum_of_ratings`=`total_sum_of_ratings`+?,' . '`total_avg_rating`=`total_sum_of_ratings`/`total_num_ratings` ' . 'WHERE `video_id`=?', array($rating, $rating, $rating, $rating, $video_id)); echo _T('Text:Rating recorded'); } else { echo _T('Validation:You have already rated this video'); } } else { echo _T('Validation:Rating disabled'); } } else { echo _T('Validation:Invalid rating'); } } else { echo _T('Validation:Must be logged in'); }
Jeremy's Blog Website <br /> <br /> <?php //include 'sql.php'; $id = 10001; //$db = new Database; //$default = Database::instance(); $query = Database_MySQL::query(Database::SELECT, 'SELECT * FROM posts');
public static function Import($settings) { $DB = GetDB(); ProgressBarShow('pb-import'); $file = TEMP_DIR . '/' . File::Sanitize($settings['import_file']); $fp = fopen($file, 'r'); $filesize = filesize($file); $line = $read = $imported = 0; $expected = count($settings['fields']); while (!feof($fp)) { $line++; $string = fgets($fp); $read += strlen($string); $data = explode($settings['delimiter'], trim($string)); ProgressBarUpdate('pb-import', $read / $filesize * 100); // Line does not have the expected number of fields if (count($data) != $expected) { continue; } $video = array(); $defaults = array('category_id' => $settings['category_id'], 'sponsor_id' => $settings['sponsor_id'], 'username' => $settings['username'], 'duration' => Format::DurationToSeconds($settings['duration']), 'status' => $settings['status'], 'next_status' => $settings['status'], 'allow_comments' => $settings['allow_comments'], 'allow_ratings' => $settings['allow_ratings'], 'allow_embedding' => $settings['allow_embedding'], 'is_private' => $settings['is_private'], 'date_added' => Database_MySQL::Now(), 'is_featured' => 0, 'is_user_submitted' => 0, 'conversion_failed' => 0, 'tags' => null, 'title' => null, 'description' => null); foreach ($settings['fields'] as $index => $field) { if (!empty($field)) { $video[$field] = trim($data[$index]); } } // Setup clips $clips = array(); $thumbs = array(); $clip_type = 'URL'; if (isset($video['embed_code'])) { // Cannot convert or thumbnail from embed code $settings['flag_convert'] = $settings['flag_thumb'] = false; $clips[] = $video['embed_code']; $clip_type = 'Embed'; } else { if (isset($video['gallery_url'])) { $http = new HTTP(); if (!$http->Get($video['gallery_url'])) { // Broken gallery URL, continue continue; } list($thumbs, $clips) = Video_Source_Gallery::ExtractUrls($http->url, $http->body); } else { if (!isset($video['video_url']) && isset($video['base_video_url'])) { if (!preg_match('~/$~', $video['base_video_url'])) { $video['base_video_url'] .= '/'; } foreach (explode(',', $video['video_filename']) as $filename) { $clips[] = $video['base_video_url'] . $filename; } } else { $clips[] = $video['video_url']; } } } // Check for duplicate clips $duplicate = false; foreach ($clips as $clip) { if (!Request::Get('flag_skip_imported_check') && $DB->QueryCount('SELECT COUNT(*) FROM `tbx_imported` WHERE `video_url`=?', array($clip)) > 0) { $duplicate = true; } $DB->Update('REPLACE INTO `tbx_imported` VALUES (?)', array($clip)); } // Dupe found if ($duplicate) { continue; } // Setup thumbs if (!isset($video['gallery_url']) && !isset($video['thumbnail_url']) && isset($video['base_thumbnail_url'])) { if (!preg_match('~/$~', $video['base_thumbnail_url'])) { $video['base_thumbnail_url'] .= '/'; } foreach (explode(',', String::FormatCommaSeparated($video['thumbnail_filename'])) as $filename) { $thumbs[] = $video['base_thumbnail_url'] . $filename; } } else { if (!isset($video['gallery_url']) && isset($video['thumbnail_url'])) { $thumbs[] = $video['thumbnail_url']; } } // Setup duration if (isset($video['duration_seconds'])) { $video['duration'] = $video['duration_seconds']; } else { if (isset($video['duration_formatted'])) { $video['duration'] = Format::DurationToSeconds($video['duration_formatted']); } } // Use description for title if (empty($video['title'])) { $video['title'] = isset($video['description']) ? $video['description'] : ''; } // Use title for description if (empty($video['description'])) { $video['description'] = isset($video['title']) ? $video['title'] : ''; } // Use title for tags if (empty($video['tags'])) { $video['tags'] = isset($video['title']) ? $video['title'] : ''; } // Setup category if (isset($video['category']) && ($category_id = $DB->QuerySingleColumn('SELECT `category_id` FROM `tbx_category` WHERE `name` LIKE ?', array($video['category']))) !== false) { $video['category_id'] = $category_id; } else { if (($category_id = GetBestCategory($video['title'] . ' ' . $video['description'])) !== null) { $video['category_id'] = $category_id; } } // Merge in the defaults $video = array_merge($defaults, $video); // Format tags and convert to UTF-8 $video['tags'] = Tags::Format($video['tags']); $video = String::ToUTF8($video); if (Request::Get('flag_convert')) { $video['status'] = STATUS_QUEUED; } // Add to database $video['video_id'] = DatabaseAdd('tbx_video', $video); DatabaseAdd('tbx_video_custom', $video); DatabaseAdd('tbx_video_stat', $video); if ($video['is_private']) { $video['private_id'] = sha1(uniqid(mt_rand(), true)); DatabaseAdd('tbx_video_private', $video); } if ($video['status'] == STATUS_QUEUED) { $video['queued'] = time(); DatabaseAdd('tbx_conversion_queue', $video); } if (Request::Get('flag_thumb')) { $video['queued'] = time(); DatabaseAdd('tbx_thumb_queue', $video); } if ($video['status'] == STATUS_ACTIVE && !$video['is_private']) { Tags::AddToFrequency($video['tags']); } // Add clips foreach ($clips as $clip) { DatabaseAdd('tbx_video_clip', array('video_id' => $video['video_id'], 'type' => $clip_type, 'clip' => $clip)); } $dir = new Video_Dir(Video_Dir::DirNameFromId($video['video_id'])); // Process thumbs $thumb_ids = array(); foreach ($thumbs as $thumb) { $http = new HTTP(); if ($http->Get($thumb, $thumb)) { if (Video_Thumbnail::CanResize()) { $thumb_temp = $dir->AddTempFromVar($http->body, 'jpg'); $thumb_file = Video_Thumbnail::Resize($thumb_temp, Config::Get('thumb_size'), Config::Get('thumb_quality'), $dir->GetThumbsDir()); } else { $thumb_file = $dir->AddThumbFromVar($http->body); } if (!empty($thumb_file)) { $thumb_ids[] = DatabaseAdd('tbx_video_thumbnail', array('video_id' => $video['video_id'], 'thumbnail' => str_replace(Config::Get('document_root'), '', $thumb_file))); } } } // Determine number of thumbnails and select random display thumbnail $num_thumbnails = count($thumb_ids); $display_thumbnail = null; if ($num_thumbnails > 0) { // Select display thumbnail randomly from the first 40% $display_thumbnail = $thumb_ids[rand(0, floor(0.4 * $num_thumbnails))]; } DatabaseUpdate('tbx_video', array('video_id' => $video['video_id'], 'num_thumbnails' => $num_thumbnails, 'display_thumbnail' => $display_thumbnail)); $imported++; } fclose($fp); UpdateCategoryStats(); UpdateSponsorStats($settings['sponsor_id']); $t = new Template(); $t->ClearCache('categories.tpl'); ProgressBarHide('pb-import', NumberFormatInteger($imported) . ' videos have been imported!'); // Start up the thumbnail and converson queues if needed if (!Config::Get('flag_using_cron')) { if (Request::Get('flag_convert')) { ConversionQueue::Start(); } if (Request::Get('flag_thumb')) { ThumbQueue::Start(); } } File::Delete($file); }
/** * This is the class constructor for Database_Site */ function __construct($dbName = null, $host = 'localhost', $userName = '', $passWord = '') { // Call the parent Class Constructor parent::__construct($dbName, $host, $userName, $passWord); }
function tbxRegister() { global $t; $DB = GetDB(); $v = Validator::Create(); $v->Register($_REQUEST['username'], Validator_Type::NOT_EMPTY, _T('Validation:Required', _T('Label:Username'))); $v->Register($_REQUEST['username'], Validator_Type::IS_ALPHANUM, _T('Validation:Alphanumeric', _T('Label:Username'))); $v->Register($DB->QueryCount('SELECT COUNT(*) FROM `tbx_user` WHERE `username`=?', array($_REQUEST['username'])), Validator_Type::IS_ZERO, _T('Validation:Username Taken')); $v->Register($_REQUEST['password'], Validator_Type::NOT_EMPTY, _T('Validation:Required', _T('Label:Password'))); $v->Register($_REQUEST['password'], Validator_Type::LENGTH_GREATER_EQ, _T('Validation:Length Greater Equal', _T('Label:Password'), 8), 8); $v->Register($_REQUEST['password'], Validator_Type::EQUALS, _T('Validation:Passwords do not match'), $_REQUEST['confirm_password']); $v->Register($_REQUEST['email'], Validator_Type::NOT_EMPTY, _T('Validation:Required', _T('Label:E-mail'))); $v->Register($_REQUEST['email'], Validator_Type::VALID_EMAIL, _T('Validation:E-mail', _T('Label:E-mail'))); $v->Register($DB->QueryCount('SELECT COUNT(*) FROM `tbx_user` WHERE `email`=?', array($_REQUEST['email'])), Validator_Type::IS_ZERO, _T('Validation:E-mail Taken')); $v->Register($_REQUEST['name'], Validator_Type::NOT_EMPTY, _T('Validation:Required', _T('Label:Name'))); $v->Register(empty($_REQUEST['birth_month']) || empty($_REQUEST['birth_day']) || empty($_REQUEST['birth_year']), Validator_Type::IS_FALSE, _T('Validation:Birthday Required')); $v->Register($_REQUEST['gender'], Validator_Type::NOT_EMPTY, _T('Validation:Required', _T('Label:Gender'))); $v->Register($_REQUEST['terms'], Validator_Type::NOT_EMPTY, _T('Validation:Accept Terms')); // Register user-defined field validators $schema = GetDBSchema(); $v->RegisterFromXml($schema->el('//table[name="tbx_user_custom"]'), 'user', 'create'); // Check blacklist $_REQUEST['ip_address'] = $_SERVER['REMOTE_ADDR']; if (($match = Blacklist::Match($_REQUEST, Blacklist::ITEM_USER)) !== false) { $v->SetError(_T('Validation:Blacklisted', $match['match'])); } // Check CAPTCHA if (Config::Get('flag_captcha_on_signup')) { Captcha::Verify(); } if (!$v->Validate()) { $t->Assign('g_errors', $v->GetErrors()); $t->Assign('g_form', $_REQUEST); return tbxDisplayRegister(); } // Format data $_REQUEST['date_birth'] = $_REQUEST['birth_year'] . '-' . $_REQUEST['birth_month'] . '-' . $_REQUEST['birth_day']; $_REQUEST['date_created'] = Database_MySQL::Now(); $_REQUEST['user_level_id'] = $DB->QuerySingleColumn('SELECT `user_level_id` FROM `tbx_user_level` WHERE `is_default`=1'); $_REQUEST['password'] = sha1($_REQUEST['password']); // Strip HTML tags if (Config::Get('flag_user_strip_tags')) { $_REQUEST = String::StripTags($_REQUEST); } // Prepare fields for database Form_Prepare::Standard('tbx_user'); Form_Prepare::Standard('tbx_user_stat'); Form_Prepare::Custom('tbx_user_custom_schema', 'on_submit'); // Setup account status $_REQUEST['status'] = STATUS_ACTIVE; $email_template = 'email-user-added.tpl'; if (Config::Get('flag_user_confirm_email')) { $_REQUEST['status'] = STATUS_SUBMITTED; $email_template = 'email-user-confirm.tpl'; } else { if (Config::Get('flag_user_approve')) { $_REQUEST['status'] = STATUS_PENDING; $email_template = 'email-user-pending.tpl'; } } // Add data to the database DatabaseAdd('tbx_user', $_REQUEST); DatabaseAdd('tbx_user_custom', $_REQUEST); DatabaseAdd('tbx_user_stat', $_REQUEST); if ($_REQUEST['status'] == STATUS_SUBMITTED) { $_REQUEST['register_code'] = sha1(uniqid(mt_rand(), true)); $_REQUEST['timestamp'] = time(); DatabaseAdd('tbx_user_register_code', $_REQUEST); $t->Assign('g_code', $_REQUEST['register_code']); } $t->AssignByRef('g_user', $_REQUEST); $t->AssignByRef('g_form', $_REQUEST); // Send e-mail message $m = new Mailer(); $m->Mail($email_template, $t, $_REQUEST['email'], $_REQUEST['name']); // Display confirmation $t->Display('user-register-complete.tpl'); }
<?php $si = ServerInfo::GetCached(); $defaults = array('date_added' => Database_MySQL::Now(), 'status' => STATUS_ACTIVE, 'allow_comments' => 'Yes - Add Immediately', 'allow_ratings' => 1, 'allow_embedding' => 1, 'is_private' => 0); $_REQUEST = array_merge($defaults, $_REQUEST); $DB = GetDB(); $categories = $DB->FetchAll('SELECT `category_id`,`name` FROM `tbx_category` ORDER BY `name`'); $clips = $DB->FetchAll('SELECT * FROM `tbx_video_clip` WHERE `video_id`=?', array(Request::Get('video_id'))); ?> <div id="dialog-header" class="ui-widget-header ui-corner-all"> <div id="dialog-close"></div> <?php echo isset($editing) ? 'Update a Video' : 'Add a Video'; ?> </div> <form method="post" action="ajax.php" enctype="multipart/form-data"> <div id="dialog-panel"> <div style="padding: 8px;"> <?php if (empty($categories)) { ?> <div class="message-error"> You will need to create at least one category before you can begin adding videos </div> <?php } else { ?> <?php if (!isset($editing)) {
function tbxUpdateStats($video_id) { global $cookie, $t; $count_as_view = true; $stats = array('vv' => ''); if (isset($_COOKIE[STATS_COOKIE])) { $stats = unserialize($_COOKIE[STATS_COOKIE]); if (strstr(",{$stats['vv']},", ",{$video_id},")) { $count_as_view = false; } } if ($count_as_view) { StatsRollover(); $DB = GetDB(); $DB->Update('UPDATE `tbx_video_stat` SET ' . '`date_last_view`=?,' . '`today_num_views`=`today_num_views`+1,' . '`week_num_views`=`week_num_views`+1,' . '`month_num_views`=`month_num_views`+1,' . '`total_num_views`=`total_num_views`+1 ' . 'WHERE `video_id`=?', array(Database_MySQL::Now(), $video_id)); $DB->Update('UPDATE `tbx_user_stat` JOIN `tbx_video` USING (`username`) SET ' . '`today_video_views`=`today_video_views`+1,' . '`week_video_views`=`week_video_views`+1,' . '`month_video_views`=`month_video_views`+1,' . '`total_video_views`=`total_video_views`+1 ' . 'WHERE `video_id`=?', array($video_id)); if (!empty($cookie) && isset($cookie['username'])) { $DB->Update('UPDATE `tbx_user_stat` SET ' . '`today_videos_watched`=`today_videos_watched`+1,' . '`week_videos_watched`=`week_videos_watched`+1,' . '`month_videos_watched`=`month_videos_watched`+1,' . '`total_videos_watched`=`total_videos_watched`+1 ' . 'WHERE `username`=?', array($cookie['username'])); } else { $ip = sprintf('%u', ip2long($_SERVER['REMOTE_ADDR'])); if ($DB->Update('UPDATE `tbx_guest_usage` SET `watched`=`watched`+1 WHERE `ip`=?', array($ip)) == 0) { $DB->Update('INSERT INTO `tbx_guest_usage` VALUES (?,0,1)', array($ip)); } } $stats['vv'] .= ",{$_GET['id']}"; setcookie(STATS_COOKIE, serialize($stats), time() + 90 * 86400, Config::Get('cookie_path'), Config::Get('cookie_domain')); } }
public function __construct($feed) { $this->feed = $feed; $this->defaults = array('username' => $this->feed['username'], 'date_added' => Database_MySQL::Now(), 'date_recorded' => null, 'location_recorded' => null, 'source_url' => null, 'status' => $this->feed['status'], 'category_id' => $this->feed['category_id'], 'sponsor_id' => $this->feed['sponsor_id'], 'duration' => 0, 'is_private' => $this->feed['is_private'], 'allow_comments' => $this->feed['allow_comments'], 'allow_ratings' => $this->feed['allow_ratings'], 'allow_embedding' => $this->feed['allow_embedding']); $this->defaults['username'] = String::Nullify($this->defaults['username']); }
/** * function getBasePriceForRegistrant * <pre> * Returns registration cost for a particular registration, not including scholarship discounts * </pre> * Pre-condition: all variables must be initialized with proper values * * @param $regID [INTEGER] registration ID * @param $eventID [INTEGER] event ID * @param $campusID [INTEGER] campus ID (precondition: must be associated directly with registration ID) * @param $eventBasePrice [INTEGER] the cost of the event per registration, before any discounts * @param $priceRulesArray [ARRAY] an array of the price rules applying to event denoted by $eventID * @param &$rulesApplied [ARRAY REFERENCE] reference to an array to be filled with applied rules * @return [INTEGER] $basePriceForThisGuy the new base price for registration $regID (before scholarships) */ function getBasePriceForRegistrant($regID, $eventID, $campusID, $eventBasePrice, $priceRulesArray, &$rulesApplied = array()) { // Need to manually calculate discounts for these exceptions: $BC_SUMMIT_2007 = 19; $MB_SUMMIT_2007 = 22; $LAKESHORE_SUMMIT_2007 = 25; $EASTERN_WC_2007 = 28; $AIA_NATIONAL_TRAINING = 33; $MARITIMES_SUMMIT_2008 = 34; $basePriceForThisGuy = $eventBasePrice; // echo "<pre>".print_r($priceRulesArray,true)."</pre>"; // PUT SPECIAL EVENT EXCEPTIONS HERE AS CONDITIONAL STATEMENTS: /* if ($eventID == $MARITIMES_SUMMIT_2008) { $FROSH_DISCOUNT_FIELD = 119; // first check for Frosh Discount $fieldValue = new RowManager_FieldValueManager(); // $fieldValue->loadByFieldIDandRegID($rule['fields_id'],$regID); $fieldValue->setFieldID($FROSH_DISCOUNT_FIELD); $fieldValue->setRegID($regID); $valueListManager = $fieldValue->getListIterator(); $fieldValueList = $valueListManager->getDataList(); // echo "<pre>".print_r($fieldValueList,true)."</pre>"; reset($fieldValueList); $record = current($fieldValueList); // CHECK TO SEE IF SOME FIELD VALUE HAS BEEN SET FOR GIVEN PARAMETERS // $userValue = ''; $userValue = $record['fieldvalues_value']; // $fieldValue->getFieldValue(); if ((isset($userValue))&&($userValue != '')) { // DETERMINE WHETHER PRICE RULE VALUE IS EQUIVALENT TO CURRENT FIELD VALUE if ( $userValue == '1') { // form criteria is met, apply the discount/penalty // $basePriceForThisGuy -= 15; // subtract $15 from $65 event base cost $basePriceForThisGuy = 50; // frosh cost $rulesApplied[] = $priceRulesArray['45']; return $basePriceForThisGuy; } } // if no frosh discount, THEN apply early bird discount (if conditions met) // echo "DATE RULE<BR>"; // get the user's registration date $registration = new RowManager_RegistrationManager(); $registration->setRegID($regID); $regListManager = $registration->getListIterator(); $regArray = $regListManager->getDataList(); // echo "<pre>".print_r($registration,true)."</pre>"; // set default date-time $regTime = ''; // retrieve registration date reset($regArray); $record = current($regArray); // should be only 1 record for regID $regTime = $record['registration_date']; // $regTime = $registration->getRegistrationDate(); if ($regTime != '') { // if the registrant signed up before a deadline, apply the rule if ( strtotime($regTime) < strtotime( '2008-04-01' ) ) //$rule['pricerules_value'] { // date criteria is met, apply the discount/penalty // $basePriceForThisGuy -= 15; // apply early bird discount to $65 event base cost to get $50 $basePriceForThisGuy = 50; $rulesApplied[] = $priceRulesArray['47']; return $basePriceForThisGuy; } } return $basePriceForThisGuy; // otherwise return unaltered base event cost ($125) } */ if ($eventID == $AIA_NATIONAL_TRAINING) { $FOOD_PASS_REQ_FIELD = 102; $HOUSING_REQ_FIELD = 103; // first check for Food Pass Fee $fieldValue = new RowManager_FieldValueManager(); // $fieldValue->loadByFieldIDandRegID($rule['fields_id'],$regID); $fieldValue->setFieldID($FOOD_PASS_REQ_FIELD); $fieldValue->setRegID($regID); $valueListManager = $fieldValue->getListIterator(); $fieldValueList = $valueListManager->getDataList(); // echo "<pre>".print_r($fieldValueList,true)."</pre>"; reset($fieldValueList); $record = current($fieldValueList); // CHECK TO SEE IF SOME FIELD VALUE HAS BEEN SET FOR $FOOD_PASS_REQ_FIELD // $userValue = ''; $userValue = $record['fieldvalues_value']; // $fieldValue->getFieldValue(); if (isset($userValue) && $userValue != '') { /** Get the user's registration date **/ $registration = new RowManager_RegistrationManager(); $registration->setRegID($regID); $regListManager = $registration->getListIterator(); $regArray = $regListManager->getDataList(); // echo "<pre>".print_r($registration,true)."</pre>"; // set default date-time $regTime = ''; // retrieve registration date-time reset($regArray); $record = current($regArray); // should be only 1 record for regID $regTime = $record['registration_date']; // DETERMINE WHETHER PRICE RULE VALUE IS EQUIVALENT TO CURRENT FIELD VALUE if ($userValue == '1') { // form criteria is met, apply the discount/penalty // $basePriceForThisGuy += 100; // add 150 to base 260 event price $basePriceForThisGuy += 150; $rulesApplied[] = $priceRulesArray['39']; // Apply early-bird discount on this if applicable if ($regTime != '') { // if the registrant signed up before a deadline, apply the rule if (strtotime($regTime) < strtotime('2008-04-16')) { $basePriceForThisGuy -= 50; // subtract 50 $rulesApplied[] = $priceRulesArray['42']; } } } } // second check for Housing Fee $fieldValue = new RowManager_FieldValueManager(); // $fieldValue->loadByFieldIDandRegID($rule['fields_id'],$regID); $fieldValue->setFieldID($HOUSING_REQ_FIELD); $fieldValue->setRegID($regID); $valueListManager = $fieldValue->getListIterator(); $fieldValueList = $valueListManager->getDataList(); // echo "<pre>".print_r($fieldValueList,true)."</pre>"; reset($fieldValueList); $record = current($fieldValueList); // CHECK TO SEE IF SOME FIELD VALUE HAS BEEN SET FOR $HOUSING_REQ_FIELD // $userValue = ''; $userValue = $record['fieldvalues_value']; // $fieldValue->getFieldValue(); if (isset($userValue) && $userValue != '') { /** Get the user's registration date **/ $registration = new RowManager_RegistrationManager(); $registration->setRegID($regID); $regListManager = $registration->getListIterator(); $regArray = $regListManager->getDataList(); // echo "<pre>".print_r($registration,true)."</pre>"; // set default date-time $regTime = ''; // retrieve registration date-time reset($regArray); $record = current($regArray); // should be only 1 record for regID $regTime = $record['registration_date']; // DETERMINE WHETHER PRICE RULE VALUE IS EQUIVALENT TO CURRENT FIELD VALUE if ($userValue == '1') { // form criteria is met, apply the discount/penalty // $basePriceForThisGuy += 180; // add 230 to base 260 event price $basePriceForThisGuy += 230; $rulesApplied[] = $priceRulesArray['41']; // Apply early-bird discount on this if applicable if ($regTime != '') { // if the registrant signed up before a deadline, apply the rule if (strtotime($regTime) < strtotime('2008-04-16')) { $basePriceForThisGuy -= 50; // subtract 50 $rulesApplied[] = $priceRulesArray['42']; } } return $basePriceForThisGuy; } } return $basePriceForThisGuy; // otherwise return unaltered base event cost ($125) } if ($eventID == $EASTERN_WC_2007) { $COMMUTER_DISCOUNT_FIELD = 86; // first check for Frosh Discount $fieldValue = new RowManager_FieldValueManager(); // $fieldValue->loadByFieldIDandRegID($rule['fields_id'],$regID); $fieldValue->setFieldID($COMMUTER_DISCOUNT_FIELD); $fieldValue->setRegID($regID); $valueListManager = $fieldValue->getListIterator(); $fieldValueList = $valueListManager->getDataList(); // echo "<pre>".print_r($fieldValueList,true)."</pre>"; reset($fieldValueList); $record = current($fieldValueList); // CHECK TO SEE IF SOME FIELD VALUE HAS BEEN SET FOR GIVEN PARAMETERS // $userValue = ''; $userValue = $record['fieldvalues_value']; // $fieldValue->getFieldValue(); if (isset($userValue) && $userValue != '') { // DETERMINE WHETHER PRICE RULE VALUE IS EQUIVALENT TO CURRENT FIELD VALUE if ($userValue == '1') { // form criteria is met, apply the discount/penalty // $basePriceForThisGuy -= 80; // subtract $80 from $279 event base cost $basePriceForThisGuy = 199; // commuter cost $rulesApplied[] = $priceRulesArray['38']; return $basePriceForThisGuy; } } // if no commuter discount, THEN apply early bird discount (if conditions met) // echo "DATE RULE<BR>"; // get the user's registration date $registration = new RowManager_RegistrationManager(); $registration->setRegID($regID); $regListManager = $registration->getListIterator(); $regArray = $regListManager->getDataList(); // echo "<pre>".print_r($registration,true)."</pre>"; // set default date-time $regTime = ''; // retrieve registration date reset($regArray); $record = current($regArray); // should be only 1 record for regID $regTime = $record['registration_date']; // $regTime = $registration->getRegistrationDate(); if ($regTime != '') { // if the registrant signed up before a deadline, apply the rule if (strtotime($regTime) < strtotime('2007-12-01')) { if (strtotime($regTime) < strtotime('2007-10-09')) { // date criteria is met, apply the discount/penalty // $basePriceForThisGuy -= 50; // apply early bird discounts to $279 event base cost to get $229 $basePriceForThisGuy = 229; $rulesApplied[] = $priceRulesArray['37']; $rulesApplied[] = $priceRulesArray['36']; return $basePriceForThisGuy; } else { // date criteria is met, apply the discount/penalty // $basePriceForThisGuy -= 50; // apply regular discount to $279 event base cost to get $259 $basePriceForThisGuy = 259; $rulesApplied[] = $priceRulesArray['36']; return $basePriceForThisGuy; } } } return $basePriceForThisGuy; // otherwise return unaltered base event cost ($125) } // PUT SPECIAL EVENT EXCEPTIONS HERE AS CONDITIONAL STATEMENTS: if ($eventID == $BC_SUMMIT_2007) { $FROSH_DISCOUNT_FIELD = 54; // first check for Frosh Discount $fieldValue = new RowManager_FieldValueManager(); // $fieldValue->loadByFieldIDandRegID($rule['fields_id'],$regID); $fieldValue->setFieldID($FROSH_DISCOUNT_FIELD); $fieldValue->setRegID($regID); $valueListManager = $fieldValue->getListIterator(); $fieldValueList = $valueListManager->getDataList(); // echo "<pre>".print_r($fieldValueList,true)."</pre>"; reset($fieldValueList); $record = current($fieldValueList); // CHECK TO SEE IF SOME FIELD VALUE HAS BEEN SET FOR GIVEN PARAMETERS // $userValue = ''; $userValue = $record['fieldvalues_value']; // $fieldValue->getFieldValue(); if (isset($userValue) && $userValue != '') { // DETERMINE WHETHER PRICE RULE VALUE IS EQUIVALENT TO CURRENT FIELD VALUE if ($userValue == '1') { // form criteria is met, apply the discount/penalty // $basePriceForThisGuy -= 46; // subtract $46 from $125 event base cost $basePriceForThisGuy = 79; // frosh cost $rulesApplied[] = $priceRulesArray['14']; return $basePriceForThisGuy; } } // if no frosh discount, THEN apply early bird discount (if conditions met) // echo "DATE RULE<BR>"; // get the user's registration date $registration = new RowManager_RegistrationManager(); $registration->setRegID($regID); $regListManager = $registration->getListIterator(); $regArray = $regListManager->getDataList(); // echo "<pre>".print_r($registration,true)."</pre>"; // set default date-time $regTime = ''; // retrieve registration date reset($regArray); $record = current($regArray); // should be only 1 record for regID $regTime = $record['registration_date']; // $regTime = $registration->getRegistrationDate(); if ($regTime != '') { // if the registrant signed up before a deadline, apply the rule if (strtotime($regTime) < strtotime('2007-09-21')) { // date criteria is met, apply the discount/penalty // $basePriceForThisGuy -= 26; // apply early bird discount to $125 event base cost to get $99 $basePriceForThisGuy = 99; $rulesApplied[] = $priceRulesArray['15']; return $basePriceForThisGuy; } } return $basePriceForThisGuy; // otherwise return unaltered base event cost ($125) } if ($eventID == $MB_SUMMIT_2007) { $FROSH_DISCOUNT_FIELD = 60; $FROSH_VOLUME_THRESHOLD = 20; $MB_EARLY_FROSH_TABLE = 'temp_mb_early_frosh'; // first check for Frosh Discount $fieldValue = new RowManager_FieldValueManager(); // $fieldValue->loadByFieldIDandRegID($rule['fields_id'],$regID); $fieldValue->setFieldID($FROSH_DISCOUNT_FIELD); $fieldValue->setRegID($regID); $valueListManager = $fieldValue->getListIterator(); $fieldValueList = $valueListManager->getDataList(); // echo "<pre>".print_r($fieldValueList,true)."</pre>"; reset($fieldValueList); $record = current($fieldValueList); // CHECK TO SEE IF SOME FIELD VALUE HAS BEEN SET FOR GIVEN PARAMETERS // $userValue = ''; $userValue = $record['fieldvalues_value']; // $fieldValue->getFieldValue(); if (isset($userValue) && $userValue != '') { // DETERMINE WHETHER PRICE RULE VALUE IS EQUIVALENT TO CURRENT FIELD VALUE if ($userValue == '1') { // check if there are 20 or more frosh already stored $froshValues = new RowManager_FieldValueManager(); $froshValues->setFieldID($FROSH_DISCOUNT_FIELD); $froshValues->setFieldValue('1'); // 1 = checked checkbox $fieldsManager = new MultiTableManager(); $fieldsManager->addRowManager($froshValues); // TODO: sub-query like 'SELECT <ALL FIELD VALUES FOR SPECIFIC FROSH DISCOUNT> WHERE REG_ID IN (SELECT ALL REGISTRATIONS FOR EVENT)' $regs = new RowManager_RegistrationManager(); $regs->setEventID($eventID); $regData = new MultiTableManager(); $regData->addRowManager($regs); $regData->setFieldList('registration_id'); $registered_SQL = $regData->createSQL(); // actually creates the sub-query in order to get an accurate count of discount field values stored $negateSubQuery = false; $addSubQuery = true; $fieldsManager->constructSubQuery('registration_id', $registered_SQL, $negateSubQuery, $addSubQuery); // $froshValues->setSortOrder('registration_id'); $froshList = $fieldsManager->getListIterator(); $froshArray = array(); $froshArray = $froshList->getDataList(); // echo "COUNT = ".count($froshArray); if (count($froshArray) <= $FROSH_VOLUME_THRESHOLD) { // form criteria is met, apply the discount/penalty // $basePriceForThisGuy -= 25; // subtract $46 from $125 event base cost $basePriceForThisGuy = 40; // frosh cost $rulesApplied[] = $priceRulesArray['25']; $db = new Database_MySQL(); $db->connectToDB(SITE_DB_NAME, SITE_DB_PATH, SITE_DB_USER, SITE_DB_PWORD); // precaution that avoids duplicates $sql = "DELETE FROM " . $MB_EARLY_FROSH_TABLE . " WHERE registration_id = " . $regID; $db->runSQL($sql); $sql = "INSERT INTO " . $MB_EARLY_FROSH_TABLE . " (registration_id) VALUES (" . $regID . ")"; $db->runSQL($sql); } else { $db = new Database_MySQL(); $db->connectToDB(SITE_DB_NAME, SITE_DB_PATH, SITE_DB_USER, SITE_DB_PWORD); $sql = "SELECT * FROM " . $MB_EARLY_FROSH_TABLE . " WHERE registration_id = " . $regID; $db->runSQL($sql); $temp_regID = ''; if ($row = $db->retrieveRow()) { $temp_regID = $row['registration_id']; } // apply rule despite there being >20 frosh because this registration existed before cut-off if ($regID == $temp_regID) { // $basePriceForThisGuy -= 25; // subtract $25 from $85 event base cost $basePriceForThisGuy = 40; // frosh cost $rulesApplied[] = $priceRulesArray['25']; } else { $basePriceForThisGuy = 60; // basic frosh cost $rulesApplied[] = $priceRulesArray['28']; } } return $basePriceForThisGuy; } } return $basePriceForThisGuy; // otherwise return unaltered base event cost ($85) } if ($eventID == $LAKESHORE_SUMMIT_2007) { $FROSH_DISCOUNT_FIELD = 64; // first check for Frosh Discount $fieldValue = new RowManager_FieldValueManager(); // $fieldValue->loadByFieldIDandRegID($rule['fields_id'],$regID); $fieldValue->setFieldID($FROSH_DISCOUNT_FIELD); $fieldValue->setRegID($regID); $valueListManager = $fieldValue->getListIterator(); $fieldValueList = $valueListManager->getDataList(); // echo "<pre>".print_r($fieldValueList,true)."</pre>"; reset($fieldValueList); $record = current($fieldValueList); // CHECK TO SEE IF SOME FIELD VALUE HAS BEEN SET FOR GIVEN PARAMETERS // $userValue = ''; $userValue = $record['fieldvalues_value']; // $fieldValue->getFieldValue(); if (isset($userValue) && $userValue != '') { // DETERMINE WHETHER PRICE RULE VALUE IS EQUIVALENT TO CURRENT FIELD VALUE if ($userValue == '1') { // form criteria is met, apply the discount/penalty // $basePriceForThisGuy -= <varies>; // subtract <varying amount> from $120/$115/$110/$105 to get $75 $basePriceForThisGuy = 75; // frosh cost $rulesApplied[] = $priceRulesArray['19']; return $basePriceForThisGuy; } } // if no frosh discount, THEN apply early bird discount (if conditions met) // echo "DATE RULE<BR>"; // get the user's registration date $registration = new RowManager_RegistrationManager(); $registration->setRegID($regID); $regListManager = $registration->getListIterator(); $regArray = $regListManager->getDataList(); // echo "<pre>".print_r($registration,true)."</pre>"; // set default date-time $regTime = ''; // retrieve registration date reset($regArray); $record = current($regArray); // should be only 1 record for regID $regTime = $record['registration_date']; // $regTime = $registration->getRegistrationDate(); if ($regTime != '') { // if the registrant signed up before a deadline, apply the rule if (strtotime($regTime) < strtotime('2007-09-26')) { // date criteria is met, apply the discount/penalty // $basePriceForThisGuy -= 15; // apply early bird discount to $115 event base cost to get $105 $basePriceForThisGuy = 105; $rulesApplied[] = $priceRulesArray['20']; return $basePriceForThisGuy; } } return $basePriceForThisGuy; // otherwise return unaltered base event cost ($120) } /**** END OF RULE EXCEPTIONS ****/ // apply any price rules foreach ($priceRulesArray as $key => $rule) { $ruleType = $rule['priceruletypes_id']; // form attribute rule: apply price rule based on whether some form field value exists (i.e. frosh discount) if ($ruleType == RowManager_PriceRuleTypeManager::FORM_ATTRIBUTE_RULE) { // echo "FORM RULE<BR>"; // get the user's input for this form attribute $fieldValue = new RowManager_FieldValueManager(); // $fieldValue->loadByFieldIDandRegID($rule['fields_id'],$regID); $fieldValue->setFieldID($rule['fields_id']); $fieldValue->setRegID($regID); $valueListManager = $fieldValue->getListIterator(); $fieldValueList = $valueListManager->getDataList(); // echo "<pre>".print_r($fieldValueList,true)."</pre>"; reset($fieldValueList); $record = current($fieldValueList); // CHECK TO SEE IF SOME FIELD VALUE HAS BEEN SET FOR GIVEN PARAMETERS // $userValue = ''; $userValue = $record['fieldvalues_value']; // $fieldValue->getFieldValue(); if (isset($userValue) && $userValue != '') { // DETERMINE WHETHER PRICE RULE VALUE IS EQUIVALENT TO CURRENT FIELD VALUE if ($rule['pricerules_value'] == $userValue) { // form criteria is met, apply the discount/penalty $basePriceForThisGuy += $rule['pricerules_discount']; $rulesApplied[] = $rule; } } } else { if ($ruleType == RowManager_PriceRuleTypeManager::DATE_RULE) { // echo "DATE RULE<BR>"; // get the user's registration date $registration = new RowManager_RegistrationManager(); $registration->setRegID($regID); $regListManager = $registration->getListIterator(); $regArray = $regListManager->getDataList(); // echo "<pre>".print_r($registration,true)."</pre>"; // set default date-time $regTime = ''; // retrieve registration date reset($regArray); $record = current($regArray); // should be only 1 record for regID $regTime = $record['registration_date']; // $regTime = $registration->getRegistrationDate(); if ($regTime != '') { // if the registrant signed up before a deadline, apply the rule if (strtotime($regTime) < strtotime($rule['pricerules_value'])) { // date criteria is met, apply the discount/penalty $basePriceForThisGuy += $rule['pricerules_discount']; $rulesApplied[] = $rule; } } } else { if ($ruleType == RowManager_PriceRuleTypeManager::VOLUME_RULE) { $volumeNeeded = $rule['pricerules_value']; // $correctCampus = false; // $pattern = RowManager_PriceRuleTypeManager::CAMPUS_VOLUME_REGEX; // $numMatches = preg_match($pattern, $rule['pricerules_value']); // if ($numMatches > 0) // { // // $pricingValues = explode('|',$rule['pricerules_value']); // // echo '<pre>'.print_r($pricingValues,true).'</pre>'; // // echo 'campus = '.$pricingValues[0].' cut-off = '.$pricingValues[1]; // if ((int)$pricingValues[0] == $campusID) // { // $correctCampus = true; // $volumeNeeded = $pricingValues[1]; // // /* if ($numRegistrantsMyCampus != '') // { // // if the # of registrants >= the bulk discount value... // if ( $numRegistrantsMyCampus >= $pricingValues[1] ) // { // // bulk discount criteria is met, apply the discount/penalty // $basePriceForThisGuy += $rule['pricerules_discount']; // // $rulesApplied[] = $rule; // } // } // else // try to calculate the # of registrants on our own // { // */ // // /** } // **/ // } // } // // // check volume rule if no specific campus associated or current campus is associated with rule // if (($numMatches == 0)||($correctCampus == true)) // { if (isset($campusID) && $campusID != '') { // get total registrations for specific campus and particular event $total = array(); $summary = new RegSummaryTools(); $total = $summary->getCampusRegistrations($eventID, '', false, $campusID, '', RowManager_RegistrationManager::STATUS_REGISTERED); if (isset($total[$campusID])) { $numRegistrantsMyCampus = $total[$campusID]; } else { $numRegistrantsMyCampus = 0; } if (count($total) > 0) { // if the # of registrants >= the bulk discount value... if ($numRegistrantsMyCampus >= $volumeNeeded) { // bulk discount criteria is met, apply the discount/penalty $basePriceForThisGuy += $rule['pricerules_discount']; $rulesApplied[] = $rule; } } } else { // should not occur, this function meant to be used with campusID set } } else { if ($ruleType == RowManager_PriceRuleTypeManager::CAMPUS_RULE) { // echo "CAMPUS RULE<BR>"; // check the campus ID against the one stored in the price rules table if ($campusID == $rule['pricerules_value']) { $basePriceForThisGuy += $rule['pricerules_discount']; $rulesApplied[] = $rule; } } else { die('unknown ruletype[' . $ruleType . ']'); } } } } } // foreach rule // special hack for Eastern Ontario/Montreal summit 2006 /* if ( $eventID == 4 ) { $basePriceForThisGuy = getBasePriceEasternSummit2006( $regID, $numRegistrantsMyCampus, $rulesApplied ); } else if ( $eventID == 11 ) { $basePriceForThisGuy = getBasePricePrairieSummit2006( $regID, $campusID, $numRegistrantsMyCampus, $rulesApplied ); } */ return $basePriceForThisGuy; }
public static function Run() { chdir(realpath(dirname(__FILE__) . '/../')); require_once 'includes/global.php'; $doc_root = Config::Get('document_root'); $DB = GetDB(); self::Log('Starting...'); self::MarkRunning(); while (true) { // See if we were requested to stop if (self::ShouldStop()) { self::Log('User requested stop...'); break; } self::Ping(); $DB->Connect(); $queue_item = $DB->Row('SELECT * FROM `tbx_thumb_queue` ORDER BY `queued` LIMIT 1'); if (!empty($queue_item)) { $video = $DB->Row('SELECT * FROM `tbx_video` WHERE `video_id`=?', array($queue_item['video_id'])); if (!empty($video)) { $DB->Update('UPDATE `tbx_thumb_queue` SET `date_started`=? WHERE `video_id`=?', array(Database_MySQL::Now(), $video['video_id'])); $clips = $DB->FetchAll('SELECT * FROM `tbx_video_clip` WHERE `video_id`=? AND `type`!=? ORDER BY `clip_id`', array($queue_item['video_id'], 'Embed')); $dir = new Video_Dir(Video_Dir::DirNameFromId($video['video_id'])); Video_FrameGrabber::SetLogFile($dir->GetBaseDir() . '/thumbnailer.log'); $thumb_start = time(); try { if (!empty($clips)) { $thumbs = array(); $duration = 0; // Number of thumbs to create per clip $amount = round(Config::Get('thumb_amount') / count($clips)); // Move existing thumbnails $dir->MoveFiles($dir->GetThumbsDir(), $dir->GetTempDir(), JPG_EXTENSION); // Process each clip foreach ($clips as $clip) { self::Ping(); // Remote video if (preg_match('~https?://~i', $clip['clip'])) { $http = new HTTP(); if ($http->Get($clip['clip'], $clip['clip'])) { $video_file = $dir->AddOriginalFromVar($http->body, File::Extension($clip['clip'])); $vi = new Video_Info($video_file); $vi->Extract(); $duration += $vi->length; $temp_thumbs = Video_FrameGrabber::Grab($video_file, $dir->GetProcessingDir(), $amount, Config::Get('thumb_quality'), Config::Get('thumb_size'), $vi); // Move generated thumbs from the processing directory foreach ($temp_thumbs as $temp_thumb) { $thumbs[] = $dir->AddThumbFromFile($temp_thumb); } @unlink($video_file); } } else { $temp_thumbs = Video_FrameGrabber::Grab($doc_root . '/' . $clip['clip'], $dir->GetProcessingDir(), $amount, Config::Get('thumb_quality'), Config::Get('thumb_size')); // Move generated thumbs from the processing directory foreach ($temp_thumbs as $temp_thumb) { $thumbs[] = $dir->AddThumbFromFile($temp_thumb); } } } // Get the relative URL for each thumb and add to database $thumb_ids = array(); foreach ($thumbs as $thumb) { $thumb = str_replace($doc_root, '', $thumb); $thumb_ids[] = DatabaseAdd('tbx_video_thumbnail', array('video_id' => $video['video_id'], 'thumbnail' => $thumb)); } // Determine number of thumbnails and select random display thumbnail $num_thumbnails = count($thumbs); $display_thumbnail = null; if ($num_thumbnails > 0) { // Select display thumbnail randomly from the first 40% $display_thumbnail = $thumb_ids[rand(0, floor(0.4 * $num_thumbnails))]; } $update = array('video_id' => $video['video_id'], 'num_thumbnails' => $num_thumbnails, 'display_thumbnail' => $display_thumbnail); if (empty($video['duration']) && !empty($duration)) { $update['duration'] = $duration; } DatabaseUpdate('tbx_video', $update); // Remove old thumbnails $DB->Update('DELETE FROM `tbx_video_thumbnail` WHERE `video_id`=?' . (!empty($thumb_ids) ? ' AND`thumbnail_id` NOT IN (' . join(',', $thumb_ids) . ')' : ''), array($video['video_id'])); $dir->ClearTemp(); } } catch (Exception $e) { // Restore old thumbnails $dir->MoveFiles($dir->GetTempDir(), $dir->GetThumbsDir(), JPG_EXTENSION); Video_FrameGrabber::Log($e->getMessage() . (strtolower(get_class($e)) == 'baseexception' ? $e->getExtras() : '') . "\n" . $e->getTraceAsString()); self::UpdateStatsProcessed($thumb_start, $thumb_end, $queue_item['queued'], true); } $thumb_end = time(); $DB->Update('DELETE FROM `tbx_thumb_queue` WHERE `video_id`=?', array($queue_item['video_id'])); self::UpdateStatsProcessed($thumb_start, $thumb_end, $queue_item['queued']); } } else { break; } } self::MarkStopped(); self::Log('Exiting...'); }
function CreateBar() { $this->Labels = new MultiLingual_Labels('AI', 'NavBar', 'NavBar', $this->LanguageID); // Get List of User's Groups as a Group Clause $SQL = 'SELECT * FROM login.logingroups WHERE login_ViewerID=' . $this->ViewerID; if ($this->DB->RunSQL($SQL) == true) { $GroupClause = ''; while ($Row = $this->DB->RetrieveRow()) { if ($GroupClause != '') { $GroupClause .= ' OR grouplist_id=' . $Row['grouplist_id']; } else { $GroupClause = 'grouplist_id=' . $Row['grouplist_id']; } } // make sure "All" Group (Group ID = 0) is included ... if ($GroupClause != '') { $GroupClause = '(' . $GroupClause . ' OR grouplist_id=0)'; } else { $GroupClause = 'grouplist_id=0'; } // Now Get List of Menu's $SQL = 'SELECT * FROM login.navbarmenu WHERE ' . $GroupClause . ' OR viewer_id=' . $this->ViewerID; $SQL .= ' ORDER BY navbarmenu_order'; if ($this->DB->RunSQL($SQL) == true) { // Begin Main Menu $MenuList = "with(milonic=new menuname(\"Main Menu\")){\n"; $MenuList .= " style=barStyle;\n"; $MenuList .= " alwaysvisible=1;\n"; $MenuList .= " orientation=\"horizontal\";\n"; $MenuList .= " overfilter=\"\";\n"; $MenuList .= " position=\"relative\";\n"; $MenuListCounter = 1; // Prep a DB Object for working with MenuEntries $MenuEntryDB = new Database_MySQL(); $MenuEntryDB->ConnectToDB('login', DB_PATH, DB_USER, DB_PWORD); $MenuEntryList = ''; // For Each Menu Item while ($Row = $this->DB->RetrieveRow()) { $CurrentMenuEntries = array(); // Get MenuEntries Related To this MenuItem $SQL = 'SELECT * FROM login.navbarentries WHERE navbarmenu_id=' . $Row['navbarmenu_id']; $SQL .= ' AND (' . $GroupClause . ' OR viewer_id=' . $this->ViewerID . ') '; $SQL .= ' ORDER BY navbarentries_order '; if ($MenuEntryDB->RunSQL($SQL) == true) { $TempMenuEntry = "with(milonic=new menuname(\"menu" . $MenuListCounter . "\")){\n"; $TempMenuEntry .= " style=menuStyle;\n"; $TempMenuEntry .= " overflow=\"scroll\";\n"; $MenuEntryCounter = 1; while ($EntryRow = $MenuEntryDB->RetrieveRow()) { if (array_key_exists($EntryRow['navbarentries_cmd'], $CurrentMenuEntries) == false) { $Temp = $this->Labels->Label($EntryRow['navbarentries_label']); // if link is local to this site then if ($EntryRow['navbarentries_islocal'] == 1) { // add an entry with the site root path appended... $TempMenuEntry .= "aI(\"text=" . $Temp . ";url=" . NAVBAR_PATH . $EntryRow['navbarentries_cmd'] . ";title=" . $EntryRow['navbarentries_title'] . ";\");\n"; } else { // else add an entry with http:// appended... $TempMenuEntry .= "aI(\"text=" . $Temp . ";url=http://" . $EntryRow['navbarentries_cmd'] . ";title=" . $EntryRow['navbarentries_title'] . ";\");\n"; } $MenuEntryCounter++; $CurrentMenuEntries[$EntryRow['navbarentries_cmd']] = 0; } } $TempMenuEntry .= "}\n\n"; } else { echo 'NavBar::CreateBar:Unable to get Sub List of Main MenuList [' . $Row['navbarmenu_id'] . '] [' . $SQL . ']<br>'; } // Add Current Main Menu Entry $Temp = $this->Labels->Label($Row['navbarmenu_label']); $MenuList .= " aI(\"text=" . $Temp . ";showmenu=menu" . $MenuListCounter . "\");\n"; // Save Current Menu Entry List $MenuEntryList .= $TempMenuEntry; $MenuListCounter++; } $MenuList .= "}\n\ndrawMenus();\n"; // Now Save all this data in NavBarData ... $this->NavBarData['MainMenu'] = $MenuList; $this->NavBarData['SubMenus'] = $MenuEntryList; } else { echo 'NavBar::CreateBar:Unable to get Main MenuList [' . $SQL . ']<br>'; } } else { echo 'NavBar::CreateBar: Unable to get Viewer\'s List Of Groups.<br>'; } }