function getDisplayValue($record) { // format createdBy/updatedBy dates require_once SCRIPT_DIR . '/lib/fieldtypes/date.php'; $dateFields = array('createdDate', 'updatedDate'); if (in_array($this->name, $dateFields)) { return @DateField::getDisplayValue($record); // XXX: supress warning about calling a non-static method statically } // format createByUserNum/updatedByUserNum $value = parent::getDatabaseValue($record); $userNumFields = array('createdByUserNum', 'updatedByUserNum'); if (in_array($this->name, $userNumFields)) { $accountsTable = "{$GLOBALS['TABLE_PREFIX']}accounts"; $query = mysql_escapef("SELECT username FROM `{$accountsTable}` WHERE num = ?", $value); list($username) = mysql_get_query($query, true); $value = $username; return $value; } return parent::getDisplayValue($record); }
function redirectSingleRecordAuthorsToEditPage() { global $CURRENT_USER, $hasEditorAccess, $hasAuthorAccess, $hasAuthorViewerAccess, $schema, $tableName, $escapedTableName; $isAuthorOnly = !$CURRENT_USER['isAdmin'] && !$hasEditorAccess && !$hasAuthorViewerAccess && $hasAuthorAccess; $onlyAllowedOneRecord = @$schema['_maxRecordsPerUser'] == 1 || @$CURRENT_USER['accessList'][$tableName]['maxRecords'] == 1; if ($isAuthorOnly && $onlyAllowedOneRecord) { $query = "SELECT * FROM `{$escapedTableName}` WHERE createdByUserNum = '{$CURRENT_USER['num']}' LIMIT 1"; $record = mysql_get_query($query); $_REQUEST['num'] = $record['num']; // fake the record num being requested showInterface('default/edit.php', false); } }
function mysql_get($tableName, $recordNum, $customWhere = null) { if ($recordNum && preg_match("/[^0-9]/", strval($recordNum))) { die(__FUNCTION__ . ": second argument must be numeric or null, not '" . htmlencode(strval($recordNum)) . "'!"); } $fullTableName = getTableNameWithPrefix($tableName); $where = _mysql_getWhereFromNumAndCustomWhere($recordNum, $customWhere); $query = "SELECT * FROM `{$fullTableName}` WHERE {$where} LIMIT 1"; $record = mysql_get_query($query); // add _tableName key to record if ($record) { $record['_tableName'] = $tableName; } return $record; }
function _updateMySQL() { global $TABLE_PREFIX, $schema; $escapedTableName = mysql_escape($_REQUEST['tableName']); // get current column name and type $oldColumnName = $_REQUEST['fieldname']; $newColumnName = $_REQUEST['newFieldname']; $oldColumnType = getMysqlColumnType($_REQUEST['tableName'], $oldColumnName); $newColumnType = getColumnTypeFor($newColumnName, $_REQUEST['type'], @$_REQUEST['customColumnType']); // create/alter/remove MySQL columns $isOldColumn = $oldColumnType; $isNewColumn = $newColumnType != 'none' && $newColumnType != ''; $doEraseColumn = $isOldColumn && !$isNewColumn; $doCreateColumn = !$oldColumnType && $isNewColumn; $doAlterColumn = $isOldColumn && $isNewColumn; // remove existing index (if any) - always dropping/recreating indexes ensure they match renamed fields, etc list($oldIndexName, $oldIndexColList) = getIndexNameAndColumnListForField($oldColumnName, $oldColumnType); $indexExists = (bool) mysql_get_query("SHOW INDEX FROM `{$escapedTableName}` WHERE Key_name = '{$oldIndexName}'"); if ($indexExists) { mysql_query("DROP INDEX `{$oldIndexName}` ON `{$escapedTableName}`") or die("Error dropping index `{$newIndexName}`:" . htmlencode(mysql_error())); } // update table: create, alter, or erase field if ($doCreateColumn) { // create field $query = "ALTER TABLE `" . mysql_escape($_REQUEST['tableName']) . "`\n ADD COLUMN `" . mysql_escape($newColumnName) . "` {$newColumnType}"; $result = mysql_query($query) or die("There was an error creating the MySQL Column, the error was:\n\n" . mysql_error()); } else { if ($doAlterColumn) { // change field type $result = mysql_query("ALTER TABLE `" . mysql_escape($_REQUEST['tableName']) . "`\n CHANGE COLUMN `" . mysql_escape($oldColumnName) . "`\n `" . mysql_escape($newColumnName) . "` {$newColumnType}") or die("There was an error changing the MySQL Column, the error was:\n\n" . mysql_error() . "\n"); } else { if ($doEraseColumn) { // erase mysql field $query = "ALTER TABLE `" . mysql_escape($_REQUEST['tableName']) . "`\n DROP COLUMN `" . mysql_escape($oldColumnName) . "`"; $result = mysql_query($query) or die("There was an error removing the MySQL Column, the error was:\n\n" . mysql_error() . "\n"); } } } // add/re-create index if required if (@$_REQUEST['indexed']) { list($newIndexName, $newIndexColList) = getIndexNameAndColumnListForField($newColumnName, $newColumnType); $result = mysql_query("CREATE INDEX `{$newIndexName}` ON `{$escapedTableName}` {$newIndexColList}") or die("Error creating index `{$newIndexName}`:" . htmlencode(mysql_error())); } // update uploads table (rename upload field if it was changed) $uploadFieldRenamed = $_REQUEST['type'] == 'upload' && $oldColumnName && $oldColumnName != $newColumnName; if ($uploadFieldRenamed) { $tableNameWithoutPrefix = getTableNameWithoutPrefix($_REQUEST['tableName']); $query = "UPDATE `{$TABLE_PREFIX}uploads`"; $query .= " SET fieldName='" . mysql_escape($newColumnName) . "'"; $query .= " WHERE fieldName='" . mysql_escape($oldColumnName) . "' AND"; $query .= " tableName='" . mysql_escape($tableNameWithoutPrefix) . "'"; mysql_query($query) or die("There was an error updating the uploads database:\n\n" . htmlencode(mysql_error()) . "\n"); } }
function _errorlog_logErrorRecord($logType, $logData) { // limit errors logged per session (to prevent infinite loops from logging infinite errors) $maxErrorsPerPage = 25; $maxErrorsReached = false; static $totalErrorsLogged = 0; $totalErrorsLogged++; if ($totalErrorsLogged > $maxErrorsPerPage + 1) { return; } // ignore any errors after max error limit if ($totalErrorsLogged > $maxErrorsPerPage) { $maxErrorsReached = true; } // get summary of CMS user data $CMS_USER = getCurrentUserFromCMS(); $subsetFields = array(); foreach (array('num', 'username') as $field) { if (isset($CMS_USER[$field])) { $subsetFields[$field] = $CMS_USER[$field]; } } $subsetFields['_tableName'] = 'accounts'; $cms_user_summary = print_r($subsetFields, true); // get summary of WEB user data $WEB_USER = getCurrentUser(); $subsetFields = array(); foreach (array('num', 'username') as $field) { if (isset($WEB_USER[$field])) { $subsetFields[$field] = $WEB_USER[$field]; } } $subsetFields['_tableName'] = accountsTable(); $web_user_summary = print_r($subsetFields, true); // create error message if ($maxErrorsReached) { $errorMessage = t(sprintf("Max error limit reached! Only the first %s errors per page will be logged.", $maxErrorsPerPage)); } else { if (isset($logData['errno'])) { $errorName = _errorLog_erronoToConstantName($logData['errno']); } else { $errorName = 'UNKNOWN_ERROR'; } $errorMessage = "{$errorName}: " . (isset($logData['errstr']) ? $logData['errstr'] : ''); } // create $logDataSummary without $logDataSummary = $logData; if (array_key_exists('errcontext', $logData)) { $logDataSummary['errcontext'] = "*** in symbol table field above ***"; } // create log record data $colsToValues = array('dateLogged=' => 'NOW()', 'updatedDate=' => 'NOW()', 'updatedByuserNum' => '0', 'error' => $errorMessage, 'url' => thisPageUrl(), 'filepath' => isset($logData['errfile']) ? $logData['errfile'] : '', 'line_num' => isset($logData['errline']) ? $logData['errline'] : '', 'user_cms' => isset($CMS_USER['num']) ? $cms_user_summary : '', 'user_web' => isset($WEB_USER['num']) ? $web_user_summary : '', 'http_user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '', 'remote_addr' => isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '', 'request_vars' => print_r($_REQUEST, true), 'get_vars' => print_r($_GET, true), 'post_vars' => print_r($_POST, true), 'cookie_vars' => print_r($_COOKIE, true), 'session_vars' => isset($_SESSION) ? print_r($_SESSION, true) : '', 'server_vars' => print_r($_SERVER, true), 'symbol_table' => isset($logData['errcontext']) ? print_r($logData['errcontext'], true) : '', 'raw_log_data' => print_r($logDataSummary, true), 'email_sent' => 0); // insert record $newRecordNum = mysql_insert('_error_log', utf8_force($colsToValues, true)); // remove old log records $maxRecords = 900; $buffer = 100; // only erase records when we're this many over (to avoid erasing records every time) if (mysql_count('_error_log') > $maxRecords + $buffer) { $oldestRecordToSave_query = "SELECT * FROM `{$GLOBALS['TABLE_PREFIX']}_error_log` ORDER BY `num` DESC LIMIT 1 OFFSET " . ($maxRecords - 1); $oldestRecordToSave = mysql_get_query($oldestRecordToSave_query); if (!empty($oldestRecordToSave['num'])) { mysql_delete('_error_log', null, "num < {$oldestRecordToSave['num']}"); } } // send email update if ($GLOBALS['SETTINGS']['advanced']['phpEmailErrors']) { register_shutdown_function('_errorlog_sendEmailAlert'); } }
function getPrevAndNextRecords($options) { global $TABLE_PREFIX; // error checking $errors = ''; if (!@$options['tableName']) { $errors .= "No 'tableName' value specified in options!<br/>\n"; } if ($errors) { die(__FUNCTION__ . ": {$errors}"); } $tableSchema = loadSchema($options['tableName']); $mysqlTableName = mysql_escape($TABLE_PREFIX . $options['tableName']); $targetNum = @$options['recordNum'] ? mysql_escape($options['recordNum']) : 0; $orderBy = @$options['orderBy'] ? $options['orderBy'] : $tableSchema['listPageOrder']; // set inital mysql variables $query = "SELECT @lastSeenNum:=0, @prevNum:=0, @nextNum:=0, @firstNum:=0, @lastNum:=0, @prevNumSet:=0, @foundTarget:=0"; if (@$options['debugSql']) { print "<xmp>{$query}</xmp>"; } mysql_query($query) or die("MySQL Error: " . htmlencode(mysql_error()) . "\n"); // get mysql to figure out which nums are prev, next, first, and last // NOTE: "The order of evaluation for expressions involving user variables is undefined..." See: http://dev.mysql.com/doc/refman/5.0/en/user-variables.html $query = "SELECT \n"; $query .= " IF(@firstNum, NULL, @firstNum:=num),\n"; // get firstRecordNum $query .= " @lastNum := num,\n"; // get lastRecordNum $query .= " IF(num='{$targetNum}', (@foundTarget:=1) & (@prevNum:=@lastSeenNum), @lastSeenNum:=num),\n"; // get prevRecordNum (Note that using AND here instead of & caused an issue with unexpected evalutation of the assignment operators on a Windows/MySQL 5.5.33 server) $query .= " IF(@foundTarget=1 AND num !='{$targetNum}' AND @nextNum = 0, @nextNum := num, null)\n"; // get nextRecordNum $query .= "FROM `{$mysqlTableName}` \n"; if (@$options['where']) { $query .= "WHERE {$options['where']} \n"; } $query .= "ORDER BY {$orderBy} \n"; if (@$options['debugSql']) { print "<xmp>{$query}</xmp>"; } mysql_query($query) or die("MySQL Error: " . htmlencode(mysql_error()) . "\n"); // load our calculated nums $query = "SELECT @prevNum as 'prevRecordNum', @nextNum as 'nextRecordNum', @firstNum as 'firstRecordNum', @lastNum as 'lastRecordNum'"; if (@$options['debugSql']) { print "<xmp>{$query}</xmp>"; } $row = mysql_get_query($query); // load records matching returned nums $numsToGet = array_values(array_filter($row)); array_push($numsToGet, 0); list($records, $metaData) = getRecords(array('tableName' => $options['tableName'], 'where' => "num IN (" . implode(',', $numsToGet) . ")", 'allowSearch' => false, 'debugSql' => @$options['debugSql'])); $recordsByNum = array_combine(array_pluck($records, 'num'), $records); // package up output $firstRecord = $row['firstRecordNum'] ? @$recordsByNum[$row['firstRecordNum']] : array(); $prevRecord = $row['prevRecordNum'] ? @$recordsByNum[$row['prevRecordNum']] : array(); $nextRecord = $row['nextRecordNum'] ? @$recordsByNum[$row['nextRecordNum']] : array(); $lastRecord = $row['lastRecordNum'] ? @$recordsByNum[$row['lastRecordNum']] : array(); return array($prevRecord, $nextRecord, $firstRecord, $lastRecord); }
<?php global $tableName, $schema, $escapedTableName, $isMyAccountMenu; // Check if old record exists and load it $query = mysql_escapef("SELECT * FROM `{$escapedTableName}` WHERE num = ? LIMIT 1", @$_REQUEST['num']); $oldRecord = mysql_get_query($query); $recordExists = $oldRecord; $isNewRecord = !$oldRecord; // doAction('record_presave', $tableName, $isNewRecord, $oldRecord); // $mySqlColsAndTypes = getMySqlColsAndType($escapedTableName); $newRecordValues = _getRecordValuesFromFormInput(); ### Security Checks security_dieUnlessPostForm(); security_dieUnlessInternalReferer(); security_dieOnInvalidCsrfToken(); ### error checking $inputErrors = ''; $maxRecordError = $recordExists ? '' : showMaxRecordsError('returnText'); if ($maxRecordError) { $inputErrors = $maxRecordError; } elseif (@$schema['_disableAdd'] && !$recordExists) { $inputErrors = t('Adding records has been disabled for this section!') . "\n"; } elseif (@$schema['_disableModify'] && $recordExists) { $inputErrors = t('Modifying records has been disabled for this section!') . "\n"; } else { $inputErrors = _getInputValidationErrors($mySqlColsAndTypes, $newRecordValues); } if ($inputErrors) { die($inputErrors);
</tr> <tr> <tr><td colspan="2"> </td></tr> <tr> <td width="192"><?php et('Database Server'); ?> </td> <td> <?php print sprintf(t('MySQL v%s'), preg_replace("/[^0-9\\.]/", '', mysql_get_server_info())); ?> <?php list($maxConnections, $maxUserConnections) = mysql_get_query("SELECT @@max_connections, @@max_user_connections", true); // returns the session value if it exists and the global value otherwise if ($maxUserConnections && $maxUserConnections < $maxConnections) { $maxConnections = $maxUserConnections; } echo " (" . t('Max Connections') . ": {$maxConnections})"; ?> </td> </tr> <tr> <td width="192"> </td> <td style="padding: 5px 20px 0px; line-height: 1.5em"> <li><?php echo t('Hostname'); ?> : <?php
function _saveUpload_getHighestUploadOrder($tablename, $fieldname, $recordNum, $preSaveTempId) { global $TABLE_PREFIX; // creating query $query = "SELECT MAX(`order`) FROM `{$TABLE_PREFIX}uploads` "; $query .= " WHERE tableName = '" . mysql_escape($tablename) . "' AND "; $query .= " fieldName = '" . mysql_escape($fieldname) . "' AND "; if ($recordNum) { $query .= "recordNum = '" . mysql_escape($recordNum) . "' "; } else { if ($preSaveTempId) { $query .= "preSaveTempId = '" . mysql_escape($preSaveTempId) . "' "; } else { die("You must specify either a record 'num' or 'preSaveTempId'!"); } } // get result list($highestOrder) = mysql_get_query($query, true); // return $highestOrder; }
function &mysql_fetch($query, $firstRowOnly = false, $indexedArray = false) { if ($firstRowOnly) { return mysql_get_query($query, $indexedArray); } else { return mysql_select_query($query, $indexedArray); } }