function forgotPassword() { global $SETTINGS, $TABLE_PREFIX, $PROGRAM_DIR; $GLOBALS['sentEmail'] = false; // Lookup username or email if (@$_REQUEST['usernameOrEmail']) { security_dieUnlessPostForm(); security_dieUnlessInternalReferer(); security_dieOnInvalidCsrfToken(); disableInDemoMode('', 'forgotPassword.php', false); // send emails $escapedNameOrEmail = mysql_escape($_REQUEST['usernameOrEmail']); $matchingUsers = mysql_select('accounts', "'{$escapedNameOrEmail}' IN(`username`,`email`)"); foreach ($matchingUsers as $user) { // get reset url $resetBaseUrl = array_value(explode('?', thisPageUrl()), 0); $resetCode = _generatePasswordResetCode($user['num']); $resetUrl = "{$resetBaseUrl}?menu=resetPassword&userNum=" . $user['num'] . "&resetCode={$resetCode}"; // send message - v2.50 switched to emailTemplate_loadFromDB() $emailHeaders = emailTemplate_loadFromDB(array('template_id' => 'CMS-PASSWORD-RESET', 'placeholders' => array('user.num' => $user['num'], 'user.email' => $user['email'], 'resetUrl' => $resetUrl))); $errors = sendMessage($emailHeaders); if ($errors) { alert("Mail Error: " . nl2br($errors)); } // $GLOBALS['sentEmail'] = true; } } // display errors if (array_key_exists('usernameOrEmail', $_REQUEST) && @$_REQUEST['usernameOrEmail'] == '') { alert(t("No username or email specified!")); } if (@$_REQUEST['usernameOrEmail'] && !$GLOBALS['sentEmail']) { alert(t("No matching username or email was found!")); } // showInterface('forgotPassword.php', false); exit; }
function _init_loadSettings() { // get settings filenames and paths (either) list($hostnameWithoutPort) = explode(':', strtolower(@$_SERVER['HTTP_HOST'])); $hostnameWithoutPort = preg_replace('/[^\\w\\-\\.]/', '', $hostnameWithoutPort); // security: HTTP_HOST is user defined - remove non-filename chars to prevent ../ attacks $hostnameWithoutPort = preg_replace('/^www\\./i', '', $hostnameWithoutPort); // v2.50 - usability: don't require www. prefix so www.example.com and example.com both check for settings.example.com.php $settings_fileName = 'settings.' . preg_replace('/[^\\w\\-\\.]/', '', $hostnameWithoutPort) . '.php'; $settings_filePath = DATA_DIR . '/' . $settings_fileName; // supports host based settings files such as: /data/settings.localhost.php define('SETTINGS_DEV_FILENAME', $settings_fileName); define('SETTINGS_DEV_FILEPATH', DATA_DIR . '/' . SETTINGS_DEV_FILENAME); // set settings name and path for this server $useDev = is_file(SETTINGS_DEV_FILEPATH); define('SETTINGS_FILENAME', $useDev ? SETTINGS_DEV_FILENAME : 'settings.dat.php'); define('SETTINGS_FILEPATH', $useDev ? SETTINGS_DEV_FILEPATH : DATA_DIR . '/settings.dat.php'); // Require hostname-based settings files on development server domains (this section to be expanded) if (isInstalled() && isDevServer() && !is_file(SETTINGS_DEV_FILEPATH)) { header("Content-type: text/plain"); die("Development server requires custom settings files. Delete /data/isInstalled.php and re-install to create one."); } // load settings global $SETTINGS; if (!is_file(SETTINGS_FILEPATH)) { renameOrRemoveDefaultFiles(); } // rename settings.dat.php.default to settings.dat.php $SETTINGS = loadStructOrINI(SETTINGS_FILEPATH); // legacy support $SETTINGS['advanced']['encryptPasswords'] = 1; // added in 2.08, removed in 2.62 (force on for legacy support since encryption is always required now) ### set defaults (if not already defined in settings file - this happens when a user upgrades) // NOTE: Do this here for future instead of _upgradeSettings() $defaults = array('language' => '', 'adminEmail' => '', 'adminUrl' => '', 'cookiePrefix' => substr(md5(mt_rand()), 0, 5) . '_', 'activePlugins' => '', 'headerImageUrl' => '', 'footerHTML' => '', 'dateFormat' => '', 'cssTheme' => 'blue.css', 'webRootDir' => @$_SERVER['DOCUMENT_ROOT'], 'wysiwyg' => array(), 'advanced' => array(), 'bgtasks_lastRun' => '0', 'bgtasks_lastEmail' => '0', 'webPrefixUrl' => ''); $wysiwygDefaults = array('wysiwygLang' => 'en', 'includeDomainInLinks' => '0'); $advancedDefaults = array('imageResizeQuality' => 80, 'showExpandedMenu' => 0, 'disableFlashUploader' => 0, 'codeGeneratorExpertMode' => 0, 'hideLanguageSettings' => 0, 'session_cookie_domain' => '', 'session_save_path' => '', 'useDatepicker' => 0, 'requireHTTPS' => 0, 'httpProxyServer' => '', 'allowRelatedRecordsDragSorting' => 0, 'outgoingMail' => 'sendOnly', 'languageDeveloperMode' => 0, 'login_expiry_limit' => '30', 'login_expiry_unit' => 'minutes', 'restrictByIP' => 0, 'restrictByIP_allowed' => '', 'smtp_method' => 'php', 'smtp_hostname' => '', 'smtp_port' => '', 'smtp_username' => '', 'smtp_password' => '', 'phpHideErrors' => '0', 'phpEmailErrors' => '0', 'checkReferer' => '1', 'disableAutocomplete' => '0'); foreach ($defaults as $key => $value) { if (!array_key_exists($key, $SETTINGS)) { $SETTINGS[$key] = $value; } } foreach ($wysiwygDefaults as $key => $value) { if (!array_key_exists($key, $SETTINGS['wysiwyg'])) { $SETTINGS['wysiwyg'][$key] = $value; } } foreach ($advancedDefaults as $key => $value) { if (!array_key_exists($key, $SETTINGS['advanced'])) { $SETTINGS['advanced'][$key] = $value; } } ### custom defaults // adminUrl - update if url path has changed if (defined('IS_CMS_ADMIN')) { $hasAdminPathChanged = parse_url(thisPageUrl(), PHP_URL_PATH) != parse_url(@$SETTINGS['adminUrl'], PHP_URL_PATH); if ($hasAdminPathChanged) { // only update adminUrl when in the CMS admin $SETTINGS['adminUrl'] = @array_shift(explode('?', thisPageUrl())); // added in 2.12 - this must be set when admin.php is being access directly so we get the right URL saveSettings(); alert(sprintf(t("Updating Program Url to: %s") . "<br/>\n", $SETTINGS['adminUrl'])); } } // set default uploadDir and uploadUrl (do this here as above defaults code only runs when keys are undefined, not when they are blank) if (!$SETTINGS['uploadDir']) { $SETTINGS['uploadDir'] = 'uploads/'; // previously: /../uploads/ } if (!$SETTINGS['uploadUrl'] && !inCLI()) { // SCRIPT_NAME is set to filepath not web path when running in CLI, giving us incorrect values $SETTINGS['uploadUrl'] = dirname($_SERVER['SCRIPT_NAME']) . "/uploads/"; // previously: /../uploads/ $SETTINGS['uploadUrl'] = realUrl($SETTINGS['uploadUrl']); // remove ../ parent reference $SETTINGS['uploadUrl'] = parse_url($SETTINGS['uploadUrl'], PHP_URL_PATH); // remove scheme://hostname and leave /url/path } // remove old settings $removeKeys = array('vendorPoweredBy', 'timezoneOffsetAddMinus', 'timezoneOffsetHours', 'timezoneOffsetMinutes'); $removeCount = 0; foreach ($removeKeys as $key) { if (array_key_exists($key, $SETTINGS)) { unset($SETTINGS[$key]); $removeCount++; } } if ($removeCount) { saveSettings(); } // remove/convert old 'isInstalled' setting (from v2.09) if (array_key_exists('isInstalled', $SETTINGS)) { isInstalled(true); // set new installed status (semaphore file) unset($SETTINGS['isInstalled']); saveSettings(); } // Update PHP config with SMTP values from settings (only effects users who call mail() explicitly) if ($GLOBALS['SETTINGS']['advanced']['smtp_hostname']) { ini_set('SMTP', $GLOBALS['SETTINGS']['advanced']['smtp_hostname']); } if ($GLOBALS['SETTINGS']['advanced']['smtp_port']) { ini_set('smtp_port', $GLOBALS['SETTINGS']['advanced']['smtp_port']); } // Note: We don't need to return $SETTINGS because we're modifying the global. }
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 relatedRecordsButton($label, $url, $addReturnUrl = true) { // get menu type $isViewMenu = @$GLOBALS['action'] == 'view'; // view menus - we always have record number so just redirect // get target url $recordNumOrPlaceholder = $isViewMenu ? intval($_REQUEST['num']) : '###'; // ### gets replaced by saveRedirectAndReturn() in edit_functions.js if ($isViewMenu) { $url = str_replace('###', intval($_REQUEST['num']), $url); } // replace any occurances of ### in $url (in case it's used in multiple places) if ($addReturnUrl) { $url .= "&returnUrl=" . urlencode(thisPageUrl(array('num' => $recordNumOrPlaceholder), true)); } // get onclick if ($isViewMenu) { $onclick = htmlencode('window.location="' . jsEncode($url) . '"; return false;'); } else { $onclick = htmlencode('saveRedirectAndReturn("' . jsEncode($url) . '"); return false;'); } // call saveRedirectAndReturn() to save record, get record num, and replace ### with real record num in links // create button $button = "<a href='#' onclick='{$onclick}'><input class='button' type='button' name='_null_' value='" . htmlencode($label) . "' /></a>\n"; return $button; }
include "header.php"; ?> <?php // Security: Form action is set to the program url here so admin.php/path-info/ name/value pairs can't be passed through malicious urls ?> <form method="post" action="<?php echo parse_url(thisPageUrl(), PHP_URL_PATH); ?> " <?php disableAutocomplete(); ?> > <input type="hidden" name="action" value="loginSubmit" /> <input type="hidden" name="redirectUrl" value="<?php echo htmlencode(@$_REQUEST['redirectUrl'] ? $_REQUEST['redirectUrl'] : thisPageUrl(null, true)); ?> " /> <?php echo security_getHiddenCsrfTokenField(); disableAutocomplete('form-headers'); ?> <div class="content-box"> <div class="content-box-header"><h3><?php et('Login'); ?> </h3></div> <div class="content-box-content login-content"> <div class="tab-content default-tab" align="center">
die(t("You must be logged in as Admin to run this script from the web!")); } // security check for web access - don't show cron filepaths unless logged in ob_disable(); // Turn off browser buffering ignore_user_abort(true); // continue running even if user clicks stop on their browser session_write_close(); // v2.51 - End the current session and store session data so locked session data doesn't prevent concurrent access to CMS by user while backup in progress } // ignore PHP's max_execution_time directive set_time_limit(0); // Show cronjob instructions and web warning if (!inCLI()) { $thisScriptPath = __FILE__; $thisScriptUrl = preg_replace("/\\?.*/", '', thisPageUrl()) . '?run=1'; print "CRON WEB INTERFACE WARNING!\n"; print "-------------------------------------------------------------------------------\n"; print "You are currently running cron.php through the web interface. This can be useful\n"; print "for testing but please be aware that many web servers will terminate tasks that run\n"; print "for more than a few seconds causing some of your scheduled tasks to not complete.\n"; print "\n"; print "For best results ask you website administrator to setup a cronjob or 'scheduled task'\n"; print "to run this command every 1 minute (or as frequently as they otherwise allow):\n"; print "php -q {$thisScriptPath}\n\n"; print "CHECKING TASKS\n"; print "-------------------------------------------------------------------------------\n"; print "Please don't close this browser until the page is finished loading.\n"; print "Task output and updates can be found under the Admin Menu.\n\n"; } // error checking
function setupDemoIfNeeded() { global $SETTINGS, $TABLE_PREFIX; // skip if not in demo mode if (!inDemoMode()) { return; } // error checking if (!isInstalled()) { die("You must install the software before you can use demoMode!"); } // reset demo if needed if (@$_REQUEST['resetDemo']) { unset($_SESSION['demoCreatedTimeAsFloat']); } // change tableprefix for active demos $isActiveDemo = @$_SESSION['demoCreatedTimeAsFloat'] && $_SESSION['demoCreatedTimeAsFloat'] >= time() - MAX_DEMO_TIME; if ($isActiveDemo) { if (preg_match("/[^\\d\\.]/", $_SESSION['demoCreatedTimeAsFloat'])) { die("Invalid demo value in session!"); } $TABLE_PREFIX = $SETTINGS['mysql']['tablePrefix']; $TABLE_PREFIX .= '(demo' . $_SESSION['demoCreatedTimeAsFloat'] . ')_'; $TABLE_PREFIX = str_replace('.', '-', $TABLE_PREFIX); // . isn't allowed in tablenames } else { echo t("Creating demo (please wait a moment)...") . "<br/>\n"; _removeOldDemos(); $demoNum = _createNewDemo(); $_SESSION['demoCreatedTimeAsFloat'] = $demoNum; $refreshUrl = @$_REQUEST['resetDemo'] ? '?' : thisPageUrl(); printf(t("Done, <a href='%s'>click here to continue</a> or wait a moment while we redirect you."), $refreshUrl); print "<br/>\n<meta http-equiv='refresh' content='1;{$refreshUrl}' />"; // showBuildInfo(); exit; } }
<?php // for compatibility with older plugins, include functions that have been factored out of admin_functions.php $libDir = pathinfo(__FILE__, PATHINFO_DIRNAME); require_once "{$libDir}/login_functions.php"; // require HTTPS if (@$SETTINGS['advanced']['requireHTTPS'] && !isHTTPS()) { $httpsUrl = preg_replace('/^http:/i', 'https:', thisPageUrl()); die(sprintf(t("Secure HTTP login required: %s"), "<a href='{$httpsUrl}'>{$httpsUrl}</a>")); } // restrict IP access if (@$SETTINGS['advanced']['restrictByIP'] && !isIpAllowed()) { die(sprintf(t("Access is not permitted from your IP address (%s)"), $_SERVER['REMOTE_ADDR'])); } // install or upgrade if needed installIfNeeded(); upgradeIfNeeded(); // register if needed # NOTE: Disabling or modifying licensing or registration code violates your license agreement and is willful copyright infringement. # NOTE: Copyright infringement can be very expensive: http://en.wikipedia.org/wiki/Statutory_damages_for_copyright_infringement # NOTE: Please do not steal our software. registerIfNeeded(); // set current user or show login menu function adminLoginMenu() { global $CURRENT_USER; // login menu actions $action = @$_REQUEST['action']; if ($action == 'logoff') { user_logoff(); exit;
function cg2_showCode($function, $name, $instructions, $suffix, $code) { $tableName = @$_REQUEST['tableName']; $viewerUrlsLink = "?menu=database&action=editTable&tableName={$tableName}#viewer"; // Replace <#php and #>, makes writing PHP tags MUCH easier $code = str_replace('<#', '<?', $code); $code = str_replace('#>', '?>', $code); // default instructions if (!$instructions) { $instructions[] = sprintf('%s <b>%s-%s.php</b> (%s)', t('Save this code as'), htmlencode($tableName), $suffix, t('or choose your own name')); $instructions[] = sprintf('%s<a href="%s">%s</a> ', t('Update the '), $viewerUrlsLink, t('Viewer Urls'), t('for this section with the new url')); } // debug: allow evaling code if (@$_REQUEST['_eval'] && !alert()) { if (!@$GLOBALS['CG2_DEBUG']) { die("Debug mode not enabled!"); } $_REQUEST = array(); // clear _REQUEST() so searches don't get triggered eval("?>{$code}"); exit; } // header echo cg2_header($function, $name); // body ?> <div style="padding: 10px; font-size; 14px"> <b><?php et('Instructions'); ?> :</b> <ul> <?php foreach ($instructions as $line) { print "<li>{$line}</li>\n"; } ?> </ul> </div> <textarea name="phpCode" class="setAttr-spellcheck-false setAttr-wrap-off" style="width: 100%; height: 400px; border: 2px groove; font-family: monospace;" rows="10" cols="50"><?php $code = htmlencode($code, true); echo $code; ?> </textarea> <div align="center" style="padding-right: 5px" class="fieldOption"> <?php $backLink = htmlencode(thisPageUrl(array('_showCode' => '', 'phpCode' => ''))); // php code can be too long for get urls so remove it $backLink = preg_replace("/^.*\\?/", '?', $backLink); print "<input class='button' type='button' name='_null_' value='<< " . t('Go Back') . "' onclick=\"location.href='{$backLink}'\" />\n"; if (@$GLOBALS['CG2_DEBUG']) { $evalLink = thisPageUrl(array('_eval' => '1')); $evalLink = preg_replace("/^.*\\?/", '?', $evalLink); print "<input class='button' type='button' name='_eval' value='Debug: Run Viewer>>' onclick=\"location.href='{$evalLink}'\" />\n"; } ?> </div> <?php // footer echo cg2_footer(); }
function emailTemplate_showPreviewHeader() { if (@$_REQUEST['noheader']) { return; } $hideHeaderLink = thisPageUrl(array('noheader' => 1)); global $FROM, $TO, $SUBJECT; ?> <div style="border: 3px solid #000; background-color: #EEE; padding: 10px; text-align: left; margin: 25px"> <b>Header Preview:</b> (Users won't see this - <a href="<?php echo $hideHeaderLink; ?> ">hide header</a>) <xmp> From: <?php echo htmlencode($FROM) . "\n"; ?> To: <?php echo htmlencode($TO) . "\n"; ?> Subject: <?php echo htmlencode($SUBJECT); ?> </xmp> </div> <?php }